API reference
causalprog package.
algorithms
Algorithms.
evaluate_down_to(graph, outcome_node_label, values, parameters)
Evaluate all nodes down to a particular node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph that the node is contained in. |
required |
outcome_node_label
|
str
|
The label of the node to evaluate down to. |
required |
values
|
dict[str, float | NDArray[float]]
|
Values taken by nodes whose value is given |
required |
parameters
|
dict[str, ModelParam]
|
Parameters to pass to compute functions |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | NDArray[float]]
|
A dictionary of the values of all the nodes that are ancestors of the input node |
Source code in src/causalprog/algorithms/evaluate.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
expectation(graph, outcome_node_label, samples, *, parameter_values=None, rng_key)
Estimate the expectation of (a random variable attached to) a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the expectation of. |
required |
samples
|
int
|
Number of samples to use to estimate the expectation. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the expectation of |
Source code in src/causalprog/algorithms/moments.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
moment(order, graph, outcome_node_label, samples, *, parameter_values=None, rng_key)
Estimate a moment of (a random variable attached to) a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
int
|
Order of the moment to estimate. |
required |
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the moment of. |
required |
samples
|
int
|
Number of samples to be used to estimate the moment. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the |
Source code in src/causalprog/algorithms/moments.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
standard_deviation(graph, outcome_node_label, samples, *, parameter_values=None, rng_key, rng_key_first_moment=None)
Estimate the standard deviation of (a RV attached to) a node in a graph.
The method computes the standard deviation of node \(X\) via the formula
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the standard deviation of. |
required |
samples
|
int
|
Number of samples to use to estimate the standard deviation. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
rng_key_first_moment
|
Array | None
|
PRNG key that will be used to approximate the expectation, used in the formula to calculate the standard deviation. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the standard deviation of |
Source code in src/causalprog/algorithms/moments.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
do
Algorithms for applying do to a graph.
do(graph, node, value, *, label=None)
Apply do to a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph to apply do to. This will be copied. |
required |
node
|
str
|
The label of the node to apply do to. |
required |
value
|
float
|
The value to set the node to. |
required |
label
|
str | None
|
The label of the new graph. |
None
|
Returns:
| Type | Description |
|---|---|
Graph
|
A copy of the graph with do applied. |
Source code in src/causalprog/algorithms/do.py
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
get_included_excluded_successors(graph, node_list, successors_of)
Split successors of a node into nodes included and not included in a list.
Split the successors of a node into a list of nodes that are included in the input node list and a list of nodes that are not in the list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph. |
required |
node_list
|
dict[str, Node]
|
A dictionary of nodes, indexed by label. |
required |
successors_of
|
str
|
The node to check the successors of. |
required |
Returns:
| Type | Description |
|---|---|
tuple[tuple[str, ...], tuple[str, ...]]
|
Lists of included and excluded nodes. |
Source code in src/causalprog/algorithms/do.py
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | |
removable_nodes(graph, nodes)
Generate list of nodes that can be removed from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph. |
required |
nodes
|
dict[str, Node]
|
A dictionary of nodes, indexed by label. |
required |
Returns:
| Type | Description |
|---|---|
tuple[str, ...]
|
List of labels of removable nodes. |
Source code in src/causalprog/algorithms/do.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 | |
evaluate
Algorithms for evaluating a graph node.
evaluate(graph, outcome_node_label, values, parameters)
Evaluate a node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph that the node is contained in. |
required |
outcome_node_label
|
str
|
The label of the node to evaluate. |
required |
values
|
dict[str, float | NDArray[float]]
|
Values taken by nodes whose value is given |
required |
parameters
|
dict[str, ModelParam]
|
Parameters to pass to compute functions |
required |
Returns:
| Type | Description |
|---|---|
float | NDArray[float]
|
The evaluation of the node |
Source code in src/causalprog/algorithms/evaluate.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 | |
evaluate_down_to(graph, outcome_node_label, values, parameters)
Evaluate all nodes down to a particular node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph that the node is contained in. |
required |
outcome_node_label
|
str
|
The label of the node to evaluate down to. |
required |
values
|
dict[str, float | NDArray[float]]
|
Values taken by nodes whose value is given |
required |
parameters
|
dict[str, ModelParam]
|
Parameters to pass to compute functions |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float | NDArray[float]]
|
A dictionary of the values of all the nodes that are ancestors of the input node |
Source code in src/causalprog/algorithms/evaluate.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
moments
Algorithms for estimating the expectation and standard deviation.
expectation(graph, outcome_node_label, samples, *, parameter_values=None, rng_key)
Estimate the expectation of (a random variable attached to) a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the expectation of. |
required |
samples
|
int
|
Number of samples to use to estimate the expectation. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the expectation of |
Source code in src/causalprog/algorithms/moments.py
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
moment(order, graph, outcome_node_label, samples, *, parameter_values=None, rng_key)
Estimate a moment of (a random variable attached to) a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
order
|
int
|
Order of the moment to estimate. |
required |
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the moment of. |
required |
samples
|
int
|
Number of samples to be used to estimate the moment. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the |
Source code in src/causalprog/algorithms/moments.py
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
sample(graph, outcome_node_label, samples, *, parameter_values=None, rng_key)
Sample data from (a random variable attached to) a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph from which to sample. |
required |
outcome_node_label
|
str
|
The label of the node to sample from. |
required |
samples
|
int
|
Number of desired samples. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
Returns:
| Type | Description |
|---|---|
NDArray[float]
|
Array of |
Source code in src/causalprog/algorithms/moments.py
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | |
standard_deviation(graph, outcome_node_label, samples, *, parameter_values=None, rng_key, rng_key_first_moment=None)
Estimate the standard deviation of (a RV attached to) a node in a graph.
The method computes the standard deviation of node \(X\) via the formula
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph containing the node. |
required |
outcome_node_label
|
str
|
The label of the node to compute the standard deviation of. |
required |
samples
|
int
|
Number of samples to use to estimate the standard deviation. |
required |
parameter_values
|
dict[str, float] | None
|
Values to be taken by node parameters. |
None
|
rng_key
|
Array
|
PRNG key to use to generate samples. |
required |
rng_key_first_moment
|
Array | None
|
PRNG key that will be used to approximate the expectation, used in the formula to calculate the standard deviation. |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Approximation to the standard deviation of |
Source code in src/causalprog/algorithms/moments.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 | |
replace_node
Algorithm for replacing a graph node.
replace_node(graph, node_label_to_replace, replacement_node, *, label=None)
Replace a node in a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
The graph to replace a node in. |
required |
node_label_to_replace
|
str
|
The label of the node to be replaced. |
required |
replacement_node
|
Node
|
The new node to be inserted. |
required |
label
|
str | None
|
The label of the new graph. |
None
|
Returns:
| Type | Description |
|---|---|
Graph
|
A copy of the graph with the replacement made. |
Source code in src/causalprog/algorithms/replace_node.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | |
backend
Helper functionality for incorporating different backends.
causal_problem
Classes for defining causal problems.
CausalEstimand
Bases: _CPComponent
A Causal Estimand.
The causal estimand is the function that we want to minimise (and maximise) as part of a causal problem. It should be a scalar-valued function of the random variables appearing in a graph.
Source code in src/causalprog/causal_problem/components.py
16 17 18 19 20 21 22 23 | |
CausalProblem
Defines a causal problem.
Source code in src/causalprog/causal_problem/causal_problem.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
__init__(graph, *constraints, causal_estimand)
Create a new causal problem.
Source code in src/causalprog/causal_problem/causal_problem.py
51 52 53 54 55 56 57 58 59 60 | |
lagrangian(n_samples=1000, *, maximum_problem=False)
Return a function that evaluates the Lagrangian of this CausalProblem.
Following the KKT theorem, given the causal estimand and the constraints we can assemble a Lagrangian and seek its stationary points, to in turn identify minimisers of the constrained optimisation problem that we started with.
The Lagrangian returned is a mathematical function of its first two arguments.
The first argument is the same dictionary of parameters that is passed to models
like Graph.model, and is the values the parameters (represented by the
ParameterNodes) are taking. The second argument is a 1D vector of Lagrange
multipliers, whose length is equal to the number of constraints.
The remaining argument of the Lagrangian is the PRNG Key that should be used when drawing samples.
Note that our current implementation assumes there are no equality constraints being imposed (in which case, we would need a 3-argument Lagrangian function).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
The number of random samples to be drawn when estimating the value of functions of the RVs. |
1000
|
maximum_problem
|
bool
|
If passed as |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[dict[str, ArrayLike], ArrayLike, Array], ArrayLike]
|
The Lagrangian, as a function of the model parameters, Lagrange multipliers, and PRNG key. |
Source code in src/causalprog/causal_problem/causal_problem.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
Constraint
Bases: _CPComponent
A Constraint that forms part of a causal problem.
Constraints of a causal problem are derived properties of RVs for which we have observed data. The causal estimand is minimised (or maximised) subject to the predicted values of the constraints being close to their observed values in the data.
Adding a constraint \(g(\theta)\) to a causal problem (where \(\theta\) are the parameters of the causal problem) essentially imposes an additional constraint on the minimisation problem;
where \(g_{\text{data}}\) is the observed data value for the quantity \(g\), and \(\epsilon\) is some tolerance.
Source code in src/causalprog/causal_problem/components.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
__call__(samples)
Evaluate the constraint, given RV samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
dict[str, ArrayLike]
|
Mapping of RV (node) labels to drawn samples. |
required |
Returns:
| Type | Description |
|---|---|
ArrayLike
|
Value of the constraint. |
Source code in src/causalprog/causal_problem/components.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
__init__(*effect_handlers, model_quantity, outer_norm=None, data=0.0, tolerance=1e-06)
Create a new constraint.
Constraints have the form
where;
- \(\mathrm{norm}\) is the outer norm of the constraint (outer_norm),
- \(g(\theta)\) is the model quantity involved in the constraint
(model_quantity),
- \(g_{\mathrm{data}}\) is the observed data (data),
- \(\epsilon\) is the tolerance in the data (tolerance).
In a causal problem, each constraint appears as the condition \(c(\theta)\leq 0\) in the minimisation / maximisation (hence the inclusion of the \(-\epsilon\) term within \(c(\theta)\) itself).
\(g\) should be a (possibly vector-valued) function that acts on (a subset of) samples from the random variables of the causal problem. It must accept variable keyword-arguments only, and should access the samples for each random variable by indexing via the RV names (node labels). It should return the model quantity as computed from the samples, that \(g_{\mathrm{data}}\) observed.
\(g_{\mathrm{data}}\) should be a fixed value whose shape is broadcast-able with the return shape of \(g\). It defaults to \(0\) if not explicitly set.
\(\mathrm{norm}\) should be a suitable norm to take on the difference between the model quantity as predicted by the samples (\(g\)) and the observed data (\(g_{\mathrm{data}}\)). It must return a scalar value. The default is the 2-norm.
Source code in src/causalprog/causal_problem/components.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
HandlerToApply
dataclass
Specifies a handler that needs to be applied to a model at runtime.
Source code in src/causalprog/causal_problem/handlers.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
__eq__(other)
Equality operation.
HandlerToApplys are considered equal if they use the same handler function and
provide the same options to this function.
Comparison to other types returns False.
Source code in src/causalprog/causal_problem/handlers.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
__hash__()
Hash.
Source code in src/causalprog/causal_problem/handlers.py
89 90 91 | |
__post_init__()
Validate set attributes.
- The handler is a callable object.
- The options have been passed as a dictionary of keyword-value pairs.
Source code in src/causalprog/causal_problem/handlers.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
from_pair(pair)
classmethod
Create an instance from an effect handler and its options.
The two objects should be passed in as the elements of a container of length
2. They can be passed in any order;
- One element must be a dictionary, which will be interpreted as the options
for the effect handler.
- The other element must be callable, and will be interpreted as the handler
itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
Sequence
|
Container of two elements, one being the effect handler callable and the other being the options to pass to it (as a dictionary). |
required |
Returns:
| Type | Description |
|---|---|
HandlerToApply
|
Class instance corresponding to the effect handler and options passed. |
Source code in src/causalprog/causal_problem/handlers.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
causal_problem
Classes for representing causal problems.
CausalProblem
Defines a causal problem.
Source code in src/causalprog/causal_problem/causal_problem.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
__init__(graph, *constraints, causal_estimand)
Create a new causal problem.
Source code in src/causalprog/causal_problem/causal_problem.py
51 52 53 54 55 56 57 58 59 60 | |
lagrangian(n_samples=1000, *, maximum_problem=False)
Return a function that evaluates the Lagrangian of this CausalProblem.
Following the KKT theorem, given the causal estimand and the constraints we can assemble a Lagrangian and seek its stationary points, to in turn identify minimisers of the constrained optimisation problem that we started with.
The Lagrangian returned is a mathematical function of its first two arguments.
The first argument is the same dictionary of parameters that is passed to models
like Graph.model, and is the values the parameters (represented by the
ParameterNodes) are taking. The second argument is a 1D vector of Lagrange
multipliers, whose length is equal to the number of constraints.
The remaining argument of the Lagrangian is the PRNG Key that should be used when drawing samples.
Note that our current implementation assumes there are no equality constraints being imposed (in which case, we would need a 3-argument Lagrangian function).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_samples
|
int
|
The number of random samples to be drawn when estimating the value of functions of the RVs. |
1000
|
maximum_problem
|
bool
|
If passed as |
False
|
Returns:
| Type | Description |
|---|---|
Callable[[dict[str, ArrayLike], ArrayLike, Array], ArrayLike]
|
The Lagrangian, as a function of the model parameters, Lagrange multipliers, and PRNG key. |
Source code in src/causalprog/causal_problem/causal_problem.py
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 | |
sample_model(model, rng_key, parameter_values)
Draw samples from the predictive model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
Predictive
|
Predictive model to draw samples from. |
required |
rng_key
|
Array
|
PRNG Key to use in pseudorandom number generation. |
required |
parameter_values
|
dict[str, ArrayLike]
|
Model parameter values to substitute. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, ArrayLike]
|
|
Source code in src/causalprog/causal_problem/causal_problem.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 | |
components
Classes for defining causal estimands and constraints of causal problems.
CausalEstimand
Bases: _CPComponent
A Causal Estimand.
The causal estimand is the function that we want to minimise (and maximise) as part of a causal problem. It should be a scalar-valued function of the random variables appearing in a graph.
Source code in src/causalprog/causal_problem/components.py
16 17 18 19 20 21 22 23 | |
Constraint
Bases: _CPComponent
A Constraint that forms part of a causal problem.
Constraints of a causal problem are derived properties of RVs for which we have observed data. The causal estimand is minimised (or maximised) subject to the predicted values of the constraints being close to their observed values in the data.
Adding a constraint \(g(\theta)\) to a causal problem (where \(\theta\) are the parameters of the causal problem) essentially imposes an additional constraint on the minimisation problem;
where \(g_{\text{data}}\) is the observed data value for the quantity \(g\), and \(\epsilon\) is some tolerance.
Source code in src/causalprog/causal_problem/components.py
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
__call__(samples)
Evaluate the constraint, given RV samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
samples
|
dict[str, ArrayLike]
|
Mapping of RV (node) labels to drawn samples. |
required |
Returns:
| Type | Description |
|---|---|
ArrayLike
|
Value of the constraint. |
Source code in src/causalprog/causal_problem/components.py
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | |
__init__(*effect_handlers, model_quantity, outer_norm=None, data=0.0, tolerance=1e-06)
Create a new constraint.
Constraints have the form
where;
- \(\mathrm{norm}\) is the outer norm of the constraint (outer_norm),
- \(g(\theta)\) is the model quantity involved in the constraint
(model_quantity),
- \(g_{\mathrm{data}}\) is the observed data (data),
- \(\epsilon\) is the tolerance in the data (tolerance).
In a causal problem, each constraint appears as the condition \(c(\theta)\leq 0\) in the minimisation / maximisation (hence the inclusion of the \(-\epsilon\) term within \(c(\theta)\) itself).
\(g\) should be a (possibly vector-valued) function that acts on (a subset of) samples from the random variables of the causal problem. It must accept variable keyword-arguments only, and should access the samples for each random variable by indexing via the RV names (node labels). It should return the model quantity as computed from the samples, that \(g_{\mathrm{data}}\) observed.
\(g_{\mathrm{data}}\) should be a fixed value whose shape is broadcast-able with the return shape of \(g\). It defaults to \(0\) if not explicitly set.
\(\mathrm{norm}\) should be a suitable norm to take on the difference between the model quantity as predicted by the samples (\(g\)) and the observed data (\(g_{\mathrm{data}}\)). It must return a scalar value. The default is the 2-norm.
Source code in src/causalprog/causal_problem/components.py
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 | |
handlers
Container class for specifying effect handlers that need to be applied at runtime.
HandlerToApply
dataclass
Specifies a handler that needs to be applied to a model at runtime.
Source code in src/causalprog/causal_problem/handlers.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 | |
__eq__(other)
Equality operation.
HandlerToApplys are considered equal if they use the same handler function and
provide the same options to this function.
Comparison to other types returns False.
Source code in src/causalprog/causal_problem/handlers.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 | |
__hash__()
Hash.
Source code in src/causalprog/causal_problem/handlers.py
89 90 91 | |
__post_init__()
Validate set attributes.
- The handler is a callable object.
- The options have been passed as a dictionary of keyword-value pairs.
Source code in src/causalprog/causal_problem/handlers.py
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | |
from_pair(pair)
classmethod
Create an instance from an effect handler and its options.
The two objects should be passed in as the elements of a container of length
2. They can be passed in any order;
- One element must be a dictionary, which will be interpreted as the options
for the effect handler.
- The other element must be callable, and will be interpreted as the handler
itself.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
pair
|
Sequence
|
Container of two elements, one being the effect handler callable and the other being the options to pass to it (as a dictionary). |
required |
Returns:
| Type | Description |
|---|---|
HandlerToApply
|
Class instance corresponding to the effect handler and options passed. |
Source code in src/causalprog/causal_problem/handlers.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | |
graph
Creation and storage of graphs.
continuous_treatment
Helper functions for continuous treatment models.
Functions in this submodule assist in the creation of models that represent continuous treatments, as described in the documentation.
Function docstrings will refer to the quantities in this document when explaining their purpose, inputs, and outputs.
build_causal_response_function(graph, quadrature)
Build the causal response function for \(Y\) under an intervention on \(X\).
The function constructed is
The returned callable has signature d(xl, model_params), where
xl contains the fixed values of x and l. The latent variable
u_y is supplied internally by the quadrature rule.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
Graph representing a continuous treatment model. |
required |
quadrature
|
QuadratureMethod
|
Quadrature rule used to evaluate the expectation over the standard-normal latent variable \(U_Y\). |
required |
Returns:
| Type | Description |
|---|---|
MLPAlias
|
A callable that evaluates the causal response function \(d(x, l; \theta)\). |
Source code in src/causalprog/graph/continuous_treatment.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 | |
build_loss_function(r, evaluation_points, r_hat_i, *, evaluation_points_axes_mapping=None)
Construct the loss function \(B(\theta)\).
where:
- \(\hat{r}(x, z, l)\) is a learnt estimate of the regression function,
- \(r(x, z, l; \theta)\) is the estimate of the regression function using the graph structure,
- \(\theta\) are the model parameters over which to optimise,
- and the summation is taken over a set of evaluation points \(\mathcal{D} = \left\{ (x^{(i)}, z^{(i)}, l^{(i)}) \right\}_{i=1}^N\). Subscript \(i\)s denote evaluation at the \(i\)-th evaluation point.
To evaluate \(r_i\), learn_initialiser will attempt to vectorise r across r's
first argument. This means that evaluation_points (\(\mathcal{D}\)) should be passed
in a suitable format for jax.vmap to map over. For all-scalar nodes, this would
simply be a dictionary whose values are 1D arrays of the same shape as r_hat_i.
"Slices across the values" of this dictionary correspond to individual evaluation
points \(i\); for example passing evaluation_points = {"x": [0, 1], "z": [10, 20]}
corresponds to \(mathcal{D} = \{ (0, 10), (1, 20) \}\). When mixing scalar- and
vector-valued nodes, use evaluation_points_axes_mapping to specify which axes of
each key-value corresponds to the axes over which to vectorise the inputs (default
is axis 0). For example,
evaluation_points = {
"x": jnp.reshape(jnp.arange(9), (3,3)),
"z": [10, 20, 30]
}
evaluation_points_axes_mapping = {
"x": 0
}
corresponds to \(\mathcal{D} = \{((0, 1, 2), 10), ((3, 4, 5), 20), (6, 7, 8), 30)\}\), whereas
evaluation_points = {
"x": jnp.reshape(jnp.arange(9), (3,3)),
"z": [10, 20, 30]
}
evaluation_points_axes_mapping = {
"x": 1
}
corresponds to \(\mathcal{D} = \{((0, 3, 6), 10), ((1, 4, 7), 20), (2, 5, 8), 30)\}\).
It is only necessary to specify arrays that are not mapping over their 0th axes in
evaluation_points_axes_mapping.
To avoid broadcasting issues, the number of evaluation points is deduced from the
r_hat_i.size. For this reason, r_hat_i must always be passed as a 1D array of as
many elements as there are evaluation points.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
r
|
MLPAlias
|
Regression function, \(r\). Typically the output of
|
required |
evaluation_points
|
dict[str, NDArray]
|
Set of evaluation points, \(\mathcal{D}\). |
required |
r_hat_i
|
NDArray
|
The values of the estimate of r at the evaluation points, \(\hat{r}_i\). Must be a 1D array of as many elements as the number of evaluation points. |
required |
evaluation_points_axes_mapping
|
dict | None
|
Axes to vectorise over when evaluating \(r\)
at the |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[ModelParam], Array]
|
Callable that evaluates \(B(\theta)\). |
Source code in src/causalprog/graph/continuous_treatment.py
318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 | |
build_regression_function(graph, theta_x, quadrature, *, domain_lower_bound=-float('inf'), domain_upper_bound=float('inf'))
Build the regression function for \(Y\) given \(X, Z, L\).
Explicitly, the regression function to be constructed is
however this can be simplified through our understanding of our particular model to be written as
where \(s_q, w_q\) are sample points drawn from a quadrature rule.
Additionally, note that the callable r returned by the method has signature
r(xzl, model_params), rather than the mathematical \(r(x, z, l; \theta)\).
This function assumes the following (in the context of Ricardo's example graph):
- \(f_X\) (or specifically \(\theta_X\)) is known, and thus the inverse map
\(g = f^{-1}_X\) is known too. The graph has been suitably edited so that the edge
connecting \(X\) and \(U_X\) is now directed into \(U_X\).
- The node \(U_Y\) stores the function \(\pi_{ul}(c)\) in it's .compute attribute.
\(U_Y\) also provides access to the functions \(f_r\) and \(f_m\) through two of its
attributes, and has two nodes representing \(\theta_r\) and \(\theta_m\) as parents.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
Graph
|
Graph of the format output by
|
required |
theta_x
|
NDArray
|
Known or learn parameters for \(\theta_X\) (and thus \(f_X^{-1}\) \(g\)). |
required |
quadrature
|
QuadratureMethod
|
Chosen quadrature method to use when evaluating the \(r\). Currently,
only |
required |
domain_lower_bound
|
float
|
Optional value that restricts the domain of integration over which the integral in \(r\) is evaluated. |
-float('inf')
|
domain_upper_bound
|
float
|
See |
float('inf')
|
Source code in src/causalprog/graph/continuous_treatment.py
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 | |
continuous_treatment_model(*, label='continuous_treatment_model', l_len=1, z_len=1, k=10, f_r=None, f_m=None, compute_u_x=None, compute_u_y=None, compute_x=None, compute_y=None)
Create a graph representing the continuous treatment model.
The model created is as described in the documentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label of the graph. |
'continuous_treatment_model'
|
l_len
|
int
|
Number of entries in the vector \(L\), represented by data node |
1
|
z_len
|
int
|
Number of entries in the vector \(Z\), represented by data node |
1
|
k
|
int
|
The maximum value that could be taken by the mixture indicator \(C\). |
10
|
f_r
|
MLPAlias
|
The function \(f_r\). |
None
|
f_m
|
MLPAlias
|
The function \(f_m\). |
None
|
compute_u_x
|
MLPAlias
|
The function \(g = f_X^{-1}\). |
None
|
compute_u_y
|
MLPAlias
|
The function \(f_{\pi}\). |
None
|
compute_x
|
MLPAlias
|
The function \(f_X\). |
None
|
compute_y
|
MLPAlias
|
The function \(f_Y\). |
None
|
Returns:
| Type | Description |
|---|---|
Graph
|
Graph instance representing the continuous treatment model. |
Source code in src/causalprog/graph/continuous_treatment.py
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
graph
Graph storage.
Graph
Bases: Labelled
A directed acyclic graph that represents a causality tree.
Source code in src/causalprog/graph/graph.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 | |
edges
property
leaf_nodes
property
nodes
property
ordered_nodes
property
predecessors
property
root_nodes
property
Returns all root nodes in the graph.
Root nodes are nodes with no parents.
The returned tuple uses the ordered_nodes property to obtain the root
nodes so that a natural "fixed order" is given to the roots. When root
values are given as inputs to the causal estimand and / or constraint functions,
they will ideally be given as a single vector of root values, in which case
a fixed ordering for the leaves is necessary to make an association to the
components of the given input vector.
Returns:
| Type | Description |
|---|---|
tuple[Node, ...]
|
Root nodes. |
successors
property
__init__(*, label, graph=None)
Create a graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
A label to identify the graph. |
required |
graph
|
DiGraph | None
|
A networkx graph to base this graph on. |
None
|
Source code in src/causalprog/graph/graph.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | |
add_edge(start_node, end_node)
Add a directed edge to the graph.
Adding an edge between nodes not currently in the graph, will cause said nodes to be added to the graph along with the edge.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_node
|
Node | str
|
The node that the edge points from. |
required |
end_node
|
Node | str
|
The node that the edge points to. |
required |
Source code in src/causalprog/graph/graph.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 | |
add_node(node)
Add a node to the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
Node
|
The node to add. |
required |
Source code in src/causalprog/graph/graph.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 | |
copy(*, label=None)
Create a copy of a graph.
Source code in src/causalprog/graph/graph.py
39 40 41 42 43 | |
get_node(label)
Get a node from its label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
The label. |
required |
Returns:
| Type | Description |
|---|---|
Node
|
The node. |
Source code in src/causalprog/graph/graph.py
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 | |
is_dag()
Check if this graph is a directed acyclic graph.
Source code in src/causalprog/graph/graph.py
305 306 307 | |
model(**parameter_values)
Model corresponding to the Graph's structure.
The model created takes values of the nodes that are parameter as keyword
arguments. Names of the keyword arguments should match the labels of the
DataNodes, and their values should be the values of those parameters.
The method returns a dictionary recording the mode sites that are created. This means that the model can be 'extended' further by defining additional sites in a wrapper around this method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter_values
|
ArrayLike
|
Names of the keyword arguments should match the labels
of the |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, ArrayLike]
|
Mapping of non- |
Source code in src/causalprog/graph/graph.py
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 | |
remove_edge(start_node, end_node)
Remove a directed edge from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
start_node
|
Node | str
|
The node that the edge points from. |
required |
end_node
|
Node | str
|
The node that the edge points to. |
required |
Source code in src/causalprog/graph/graph.py
125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
remove_node(node)
Remove a node from the graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
node
|
str | Node
|
The node to remove. |
required |
Source code in src/causalprog/graph/graph.py
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
roots_down_to_outcome(outcome_node_label)
Get ordered list of nodes that outcome depends on.
Nodes are ordered so that each node appears after its dependencies.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
outcome_node_label
|
str
|
The label of the outcome node. |
required |
Returns:
| Type | Description |
|---|---|
tuple[Node, ...]
|
A list of the nodes, ordered from root nodes to the outcome |
Source code in src/causalprog/graph/graph.py
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 | |
node
Graph nodes.
base
Base graph node.
Node
Bases: Labelled
An abstract node in a graph.
Source code in src/causalprog/graph/node/base.py
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
parents
abstractmethod
property
shape
property
__getitem__(indices)
Get a component of this node.
Source code in src/causalprog/graph/node/base.py
68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 | |
__init__(*, label, shape=())
Initialise.
Parameters (equivalently ParameterNodes) represent Nodes that do not have
random variables attached. Instead, these nodes represent values that are passed
to nodes that do have distributions attached, and the value of the "parameter"
node is used as a fixed value when constructing the dependent node's
distribution. The set of parameter nodes is the collection of "parameter"s over
which one should want to optimise the causal estimand (subject to any
constraints), and as such the value that a "parameter node" passes to its
dependent nodes will vary as the optimiser runs and explores the solution space.
Distributions (equivalently DistributionNodes) are Nodes that represent
random variables described by probability distributions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
A unique label to identify the node |
required |
shape
|
tuple[int, ...]
|
The shape of the node's value for each sample |
()
|
Source code in src/causalprog/graph/node/base.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
assert_is_valid_value(value)
Check if a value is valid for this node.
Source code in src/causalprog/graph/node/base.py
179 180 181 182 183 184 185 186 187 188 189 | |
copy()
abstractmethod
Make a copy of a node.
Some inner objects stored inside the node may not be copied when this is called. Modifying some inner objects of a copy made using this may affect the original node.
Returns:
| Type | Description |
|---|---|
Node
|
A copy of the node |
Source code in src/causalprog/graph/node/base.py
139 140 141 142 143 144 145 146 147 148 149 150 151 | |
evaluate(given_values, parameters)
abstractmethod
Evaluate the node, given evaluations of its precursor nodes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
given_values
|
dict[str, Array]
|
Values for data nodes and values of parents |
required |
parameters
|
ModelParam
|
Parameters that can be used in the evaluation |
required |
Returns:
| Type | Description |
|---|---|
Array
|
Value of this node given |
Source code in src/causalprog/graph/node/base.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
is_valid_value(_value)
Check if a value is valid for this node.
Source code in src/causalprog/graph/node/base.py
175 176 177 | |
replace_parent(old_parent_label, new_parent_label)
Replace a parent node.
When this method is called directly, it can create inconsistencies in graphs. It is intended to only be used internally by algorithms.
Source code in src/causalprog/graph/node/base.py
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 | |
sample(parameter_values, sampled_dependencies, samples, *, rng_key)
abstractmethod
Sample a value from the node.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parameter_values
|
dict[str, float]
|
Values to be taken by parameters |
required |
sampled_dependencies
|
dict[str, Array]
|
Values taken by dependencies of this node |
required |
samples
|
int
|
Number of samples |
required |
rng_key
|
Array
|
Random key |
required |
Returns:
| Type | Description |
|---|---|
float
|
Sample value of this node |
Source code in src/causalprog/graph/node/base.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |
component
Graph nodes representing distributions.
ComponentNode
Bases: Node
A node representing a component of another node.
Source code in src/causalprog/graph/node/component.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 | |
__init__(parent_node_label, component, *, shape=(), label)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
parent_node_label
|
str
|
The node to take a component of |
required |
component
|
int | tuple[int, ...]
|
The index/indices of the component |
required |
shape
|
tuple[int, ...]
|
The shape of the node's value for each sample |
()
|
label
|
str
|
A unique label to identify the node |
required |
Source code in src/causalprog/graph/node/component.py
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | |
data
Graph nodes representing known of unknown data.
DataNode
Bases: Node
A node containing non-stochastic data.
DataNodes should not be used to encode constant values used by
DistributionNodes. Such constant values should either set when
node is initialised or be given to the necessary
DistributionNodes directly as constant_parameters.
Source code in src/causalprog/graph/node/data.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
__init__(*, shape=None, label, value=None)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label
|
str
|
A unique label to identify the node |
required |
shape
|
tuple[int, ...] | None
|
The shape of the node's value for each sample |
None
|
value
|
ArrayLike | None
|
The value of this constant |
None
|
Source code in src/causalprog/graph/node/data.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 | |
distribution
Graph nodes representing distributions.
DistributionNode
Bases: Node
A node containing a distribution.
Source code in src/causalprog/graph/node/distribution.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
__init__(distribution, *, label, shape=(), parameters=None, constant_parameters=None)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
distribution
|
type
|
The distribution |
required |
label
|
str
|
A unique label to identify the node |
required |
shape
|
tuple[int, ...]
|
The shape of the value for each sample |
()
|
parameters
|
dict[str, str] | None
|
A dictionary of parameters |
None
|
constant_parameters
|
dict[str, float] | None
|
A dictionary of constant parameters |
None
|
Source code in src/causalprog/graph/node/distribution.py
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 | |
create_model_site(**dependent_nodes)
Create a model site for the (conditional) distribution attached to this node.
dependent_nodes should contain keyword arguments mapping dependent node names
to the values that those nodes are taking (ParameterNodes), or the sampling
object for those nodes (DistributionNodes). These are passed to
self._dist as keyword arguments to construct the sample-able object
representing this node.
Source code in src/causalprog/graph/node/distribution.py
109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | |
random_variables
Graph nodes representing random variables.
ContinuousRandomVariableNode
Bases: RandomVariableNode
A node containing a continuous random variable (RV).
Source code in src/causalprog/graph/node/random_variables.py
107 108 109 110 111 112 113 114 115 116 117 118 | |
DiscreteRandomVariableNode
Bases: RandomVariableNode
A node containing a discrete random variable (RV).
Source code in src/causalprog/graph/node/random_variables.py
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 | |
possible_values
property
The values that this RV can take.
__init__(*, values, shape=(), label, compute=None, parents=None)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
list[float] | list[Array]
|
A list of values that this node could take |
required |
shape
|
tuple[int, ...]
|
The shape of the output of the RV |
()
|
label
|
str
|
A unique label to identify the node |
required |
compute
|
MLPAlias | None
|
A function to compute node's value from given values of parents |
None
|
parents
|
list[str] | None
|
Labels of parent nodes |
None
|
Source code in src/causalprog/graph/node/random_variables.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 | |
RandomVariableNode
Bases: Node
A node containing a random variable (RV).
Source code in src/causalprog/graph/node/random_variables.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 | |
__init__(*, shape=(), label, compute=None, parents=None)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
shape
|
tuple[int, ...]
|
The shape of the output of the RV |
()
|
label
|
str
|
A unique label to identify the node |
required |
compute
|
MLPAlias | None
|
A function to compute node's value from given values of parents |
None
|
parents
|
list[str] | None
|
Labels of parent nodes |
None
|
Source code in src/causalprog/graph/node/random_variables.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
compute(*args, **kwargs)
Directly compute the node value given values for all parents.
Source code in src/causalprog/graph/node/random_variables.py
89 90 91 92 93 94 95 96 97 98 | |
mlps
MLPs.
FunctionalMLP
Callable functional version of an MLP.
Source code in src/causalprog/mlps/mlp.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
data_format
property
Input data format this MLP expects, view access only.
Each leaf of data_format represents the shape of the input array expected by
that leaf.
graphdef
property
Model graph definition, for view access only.
__call__(input_values, model_parameters, *, training=False, rngs=None)
Evaluate the MLP with explicit model parameters.
Note that batching is disabled for this method, unless the MLP is explicitly set up to receive 1D arrays as it's input data. In which case, batching is performed along any leading dimensions (if they are present).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_values
|
PyTree
|
Input to pass through the MLP. |
required |
model_parameters
|
State
|
Explicit MLP parameters, as returned by |
required |
training
|
bool
|
If |
False
|
rngs
|
Rngs | None
|
Random number streams used by stochastic layers during training.
Required when |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The MLP output with shape |
Source code in src/causalprog/mlps/mlp.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
__init__(graphdef, data_format)
Construct a functional MLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graphdef
|
GraphDef
|
Model graph definition. |
required |
data_format
|
int | PyTree
|
Size of the input dimension of the input array.
If provided as a PyTree, each leaf should be either an integer or
|
required |
Source code in src/causalprog/mlps/mlp.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
data_as_flat_array(data)
Return the 1D array representing input data.
data should be in a format compatible with self.data_format.
If this is the case, return the 1D array that represents this
input data.
Source code in src/causalprog/mlps/mlp.py
199 200 201 202 203 204 205 206 207 | |
identity(data)
staticmethod
Identity map.
Used as a stand-in for FunctionalMLP.unravel_tree when the input
data format is explicitly a column vector.
Source code in src/causalprog/mlps/mlp.py
120 121 122 123 124 125 126 127 128 | |
unravel_tree(data)
staticmethod
Alias of jax.flatten_util.ravel_pytree.
Used to convert PyTree-formatted input data into column vector
format for passing to flax.nnx layers.
Source code in src/causalprog/mlps/mlp.py
130 131 132 133 134 135 136 137 138 | |
mlp
Multi-Layer Perceptron (MLP) function builder.
FunctionalMLP
Callable functional version of an MLP.
Source code in src/causalprog/mlps/mlp.py
98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 | |
data_format
property
Input data format this MLP expects, view access only.
Each leaf of data_format represents the shape of the input array expected by
that leaf.
graphdef
property
Model graph definition, for view access only.
__call__(input_values, model_parameters, *, training=False, rngs=None)
Evaluate the MLP with explicit model parameters.
Note that batching is disabled for this method, unless the MLP is explicitly set up to receive 1D arrays as it's input data. In which case, batching is performed along any leading dimensions (if they are present).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_values
|
PyTree
|
Input to pass through the MLP. |
required |
model_parameters
|
State
|
Explicit MLP parameters, as returned by |
required |
training
|
bool
|
If |
False
|
rngs
|
Rngs | None
|
Random number streams used by stochastic layers during training.
Required when |
None
|
Returns:
| Type | Description |
|---|---|
Array
|
The MLP output with shape |
Source code in src/causalprog/mlps/mlp.py
140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 | |
__init__(graphdef, data_format)
Construct a functional MLP.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graphdef
|
GraphDef
|
Model graph definition. |
required |
data_format
|
int | PyTree
|
Size of the input dimension of the input array.
If provided as a PyTree, each leaf should be either an integer or
|
required |
Source code in src/causalprog/mlps/mlp.py
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 | |
data_as_flat_array(data)
Return the 1D array representing input data.
data should be in a format compatible with self.data_format.
If this is the case, return the 1D array that represents this
input data.
Source code in src/causalprog/mlps/mlp.py
199 200 201 202 203 204 205 206 207 | |
identity(data)
staticmethod
Identity map.
Used as a stand-in for FunctionalMLP.unravel_tree when the input
data format is explicitly a column vector.
Source code in src/causalprog/mlps/mlp.py
120 121 122 123 124 125 126 127 128 | |
unravel_tree(data)
staticmethod
Alias of jax.flatten_util.ravel_pytree.
Used to convert PyTree-formatted input data into column vector
format for passing to flax.nnx layers.
Source code in src/causalprog/mlps/mlp.py
130 131 132 133 134 135 136 137 138 | |
mlp(input_dim, output_dim, *, hidden_layers=None, hidden_units=None, hidden_dims=None, activation='gelu', norm=None, dropout_rate=0.0, rngs=None, seed=0)
Build an explicit-parameter multilayer perceptron.
The returned FunctionalMLP stores the model structure, while the trainable
parameters are returned separately as an nnx.State.
Hidden layers must be configured either with just hidden_dims or
both hidden_layers and hidden_units.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
input_dim
|
int | PyTree
|
Size of the input dimension of the input array. If provided as a
PyTree, each leaf should be either an integer or |
required |
output_dim
|
int
|
Size of the final dimension of the output array. |
required |
hidden_layers
|
int | None
|
Number of hidden layers to create when using |
None
|
hidden_units
|
int | None
|
Number of units in each hidden layer when using |
None
|
hidden_dims
|
Sequence[int] | None
|
Explicit hidden-layer sizes. For example, |
None
|
activation
|
ActivationName
|
Activation function used after each hidden linear layer. Options are
|
'gelu'
|
norm
|
NormName
|
Optional normalisation layer to apply after each hidden linear layer and
before the activation. Options are |
None
|
dropout_rate
|
float
|
Dropout probability for hidden layers. Must be in the interval \([0, 1)\). |
0.0
|
rngs
|
Rngs | None
|
Random number streams used to initialise the MLP parameters. If not
provided, |
None
|
seed
|
int
|
Seed used for parameter initialisation when |
0
|
Callable functional MLP object as the first return value.
Initial trainable parameter state for the MLP as the second return value.
Source code in src/causalprog/mlps/mlp.py
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | |
quadrature
Quadrature rules.
GaussianQuadrature
Bases: QuadratureMethod
A Gaussian quadrature rule.
The domain of integration for the points \(p_i\) and weights \(w_i\) is \([-1,1]\). This means that to integrate an integrand \(f\) over the interval \([a,b]\), the approximation
is used.
Source code in src/causalprog/quadrature/gaussian.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
integrate(integrand, a=-1, b=1, *integrand_args, **integrand_kwargs)
Integrate the integrand over \([a,b]\) via Gaussian quadrature.
Source code in src/causalprog/quadrature/gaussian.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
points_and_weights(a=-1.0, b=1.0)
Get quadrature points and weights for performing integration on \([a,b]\).
Source code in src/causalprog/quadrature/gaussian.py
59 60 61 62 63 64 65 | |
MonteCarloGaussianQuadrature
Bases: RNGQuadratureMethod
Monte Carlo quadrature, sampled from a Gaussian.
Let \(N\) be the number of sample points to be used by the scheme. The quadrature method approximates the integral
where
- \(T_{[a,b]}\) is the PDF of a truncated normal distribution on \([a,b]\) with mean 0 and variance 1,
- \(x_i\in[a,b]\) are \(N\) samples from the truncated normal distribution defined by \(T_{[a,b]}\),
See also UniformWeightMonteCarloGaussianQuadrature, for computing the expectation
of \(f\) with respect to normally-distributed random variables.
Source code in src/causalprog/quadrature/monte_carlo.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
integrate(integrand, a=-1.0, b=1.0, *integrand_args, **integrand_kwargs)
Perform Monte-Carlo integration of the integrand over \([a,b]\).
Specifically, compute an approximation to
Source code in src/causalprog/quadrature/monte_carlo.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
UniformWeightMonteCarloGaussianQuadrature
Bases: RNGQuadratureMethod
Monte Carlo quadrature, sampled from a Gaussian, but using uniform weights.
Let \(N\) be the number of sample points to be used by the scheme. The quadrature method approximates the integral
where
- \(p_{N}\) is the PDF of a standard normal distribution,
- \(x_i\in[a,b]\) are \(N\) samples from a truncated normal distribution on \([a,b]\),
- \(P = \mathbb{P}[a < X < b \vert X \sim \mathcal{N}(0,1)]\).
When \(a=-\infty\) and \(b=\infty\), this effectively computes \(\mathbb{E}[f(X) \vert X \sim \mathcal{N}(0,1)]\).
See also MonteCarloGaussianQuadrature, for computing the integral of \(f\) alone.
Source code in src/causalprog/quadrature/monte_carlo.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
integrate(integrand, a=-1.0, b=1.0, *integrand_args, **integrand_kwargs)
Compute the expectation of the integrand against a normal RV over \([a,b]\).
Specifically, given a function \(f\), return an approximation to
where \(p_{N}\) is the PDF of the standard normal distribution.
Source code in src/causalprog/quadrature/monte_carlo.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
base
Base quadrature class.
QuadratureMethod
Bases: ABC
An abstract quadrature method.
All QuadratureMethods are required to provide a means of obtaining the
points and weights that they use, accessible through the points_and_weights
method of an instance.
Instances also provide an integrate method, to perform
numerical integration of an integrand.
Source code in src/causalprog/quadrature/base.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 | |
n_points
property
Number of quadrature points.
__init__(n_points)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_points
|
int
|
The number of quadrature points. |
required |
Source code in src/causalprog/quadrature/base.py
26 27 28 29 30 31 32 33 34 | |
integrate(integrand, a=-1.0, b=1.0, *integrand_args, **integrand_kwargs)
abstractmethod
Integrate the integrand over [a,b] using the QuadratureMethod.
Subclasses should implement specific details.
Ideally, we would be able to assume that the integrand is vectorised in it's first argument (Callable[[ArrayLike, ...], ArrayLike]). Then we could do without the for-loop in each of the subclass implementations.
Source code in src/causalprog/quadrature/base.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 | |
points_and_weights(a=-1.0, b=1.0)
abstractmethod
Get quadrature points and weights for performing integration on \([a,b]\).
Source code in src/causalprog/quadrature/base.py
60 61 62 63 64 | |
pts_wts_tuples(a=-1.0, b=1.0)
Get (point, weight) pairs as a list of tuples.
Source code in src/causalprog/quadrature/base.py
66 67 68 69 70 | |
RNGQuadratureMethod
Bases: QuadratureMethod
An abstract quadrature method, that relies on RNG.
The only difference from the base QuadratureMethod class is the requirement
that an rng_key be provided to the instance at creation.
Source code in src/causalprog/quadrature/base.py
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 | |
__init__(n_points, *, rng_key)
Initialise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_points
|
int
|
The number of quadrature points. |
required |
rng_key
|
Array
|
PRNG key used for sample generation. |
required |
Source code in src/causalprog/quadrature/base.py
83 84 85 86 87 88 89 90 91 92 93 94 | |
gaussian
Gaussian quadrature.
GaussianQuadrature
Bases: QuadratureMethod
A Gaussian quadrature rule.
The domain of integration for the points \(p_i\) and weights \(w_i\) is \([-1,1]\). This means that to integrate an integrand \(f\) over the interval \([a,b]\), the approximation
is used.
Source code in src/causalprog/quadrature/gaussian.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 | |
integrate(integrand, a=-1, b=1, *integrand_args, **integrand_kwargs)
Integrate the integrand over \([a,b]\) via Gaussian quadrature.
Source code in src/causalprog/quadrature/gaussian.py
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | |
points_and_weights(a=-1.0, b=1.0)
Get quadrature points and weights for performing integration on \([a,b]\).
Source code in src/causalprog/quadrature/gaussian.py
59 60 61 62 63 64 65 | |
monte_carlo
Monte Carlo quadrature.
MonteCarloGaussianQuadrature
Bases: RNGQuadratureMethod
Monte Carlo quadrature, sampled from a Gaussian.
Let \(N\) be the number of sample points to be used by the scheme. The quadrature method approximates the integral
where
- \(T_{[a,b]}\) is the PDF of a truncated normal distribution on \([a,b]\) with mean 0 and variance 1,
- \(x_i\in[a,b]\) are \(N\) samples from the truncated normal distribution defined by \(T_{[a,b]}\),
See also UniformWeightMonteCarloGaussianQuadrature, for computing the expectation
of \(f\) with respect to normally-distributed random variables.
Source code in src/causalprog/quadrature/monte_carlo.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | |
integrate(integrand, a=-1.0, b=1.0, *integrand_args, **integrand_kwargs)
Perform Monte-Carlo integration of the integrand over \([a,b]\).
Specifically, compute an approximation to
Source code in src/causalprog/quadrature/monte_carlo.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 | |
UniformWeightMonteCarloGaussianQuadrature
Bases: RNGQuadratureMethod
Monte Carlo quadrature, sampled from a Gaussian, but using uniform weights.
Let \(N\) be the number of sample points to be used by the scheme. The quadrature method approximates the integral
where
- \(p_{N}\) is the PDF of a standard normal distribution,
- \(x_i\in[a,b]\) are \(N\) samples from a truncated normal distribution on \([a,b]\),
- \(P = \mathbb{P}[a < X < b \vert X \sim \mathcal{N}(0,1)]\).
When \(a=-\infty\) and \(b=\infty\), this effectively computes \(\mathbb{E}[f(X) \vert X \sim \mathcal{N}(0,1)]\).
See also MonteCarloGaussianQuadrature, for computing the integral of \(f\) alone.
Source code in src/causalprog/quadrature/monte_carlo.py
69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 | |
integrate(integrand, a=-1.0, b=1.0, *integrand_args, **integrand_kwargs)
Compute the expectation of the integrand against a normal RV over \([a,b]\).
Specifically, given a function \(f\), return an approximation to
where \(p_{N}\) is the PDF of the standard normal distribution.
Source code in src/causalprog/quadrature/monte_carlo.py
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
solvers
Solvers for Causal Problems.
augmented_lagrangian(obj_fn, initial_guess, bounds, *, initial_mu=1.0, update_mu=lambda mu: 10 * mu, initial_learning_rate=0.1, update_learning_rate=lambda _, mu, __: 1.0 / mu, bounds_epsilon=0.0, convergence_criterion=None, fn_args=(), fn_kwargs=None, max_or_min='min', maxiter=10, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Optimise a function using the Augmented Lagrangian method.
Implemented the method as described at https://en.wikipedia.org/wiki/Augmented_Lagrangian_method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], Array]
|
Function to minimise. |
required |
initial_guess
|
PyTree
|
An initial guess for the solution. |
required |
bounds
|
Callable[[PyTree], Array]
|
Function that evaluates bounds on the minimisation problem. |
required |
initial_mu
|
float
|
Starting value for |
1.0
|
update_mu
|
Callable[[float], float]
|
Function to update |
lambda mu: 10 * mu
|
initial_learning_rate
|
float
|
Learning rate to use in the first gradient descent solve. |
0.1
|
update_learning_rate
|
Callable[[float, float, float], float]
|
Function to update the learning rate after each gradient
descent solve. Should take 3 positional arguments; the current learning
rate, and the values of |
lambda _, mu, __: 1.0 / mu
|
bounds_epsilon
|
float
|
Value of epsilon to use for the bounds. Any value smaller than this will be treated as equal to 0. |
0.0
|
convergence_criterion
|
Callable[[PyTree, PyTree], Array] | None
|
The quantity that will be tested against |
None
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
max_or_min
|
Literal['max', 'min']
|
Whether to minimise or maximise |
'min'
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
10
|
tolerance
|
float
|
Tolerance used when determining if a minimum has been found. |
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/aug_lagrangian.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
penalty_method(obj_fn, initial_guess, bounds, *, initial_mu=1.0, update_mu=lambda mu: 10 * mu, initial_learning_rate=0.1, update_learning_rate=lambda _, mu: 1.0 / mu, bounds_epsilon=0.0, convergence_criterion=None, fn_args=(), fn_kwargs=None, max_or_min='min', maxiter=10, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Minimise a function using a penalty method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], Array]
|
Function to minimise. |
required |
initial_guess
|
PyTree
|
An initial guess for the solution. |
required |
bounds
|
Callable[[PyTree], Array]
|
Function that evaluates bounds on the minimisation problem. |
required |
initial_mu
|
float
|
Starting value for |
1.0
|
update_mu
|
Callable[[float], float]
|
Function to update |
lambda mu: 10 * mu
|
bounds_epsilon
|
float
|
Value of epsilon to use for the bounds. Any value smaller than this will be treated as equal to 0. |
0.0
|
convergence_criterion
|
Callable[[PyTree, PyTree], Array] | None
|
The quantity that will be tested against |
None
|
initial_learning_rate
|
float
|
Learning rate to use in the first gradient descent solve |
0.1
|
update_learning_rate
|
Callable[[float, float], float]
|
Function to update the learning rate after each gradient
descent solve. Should take 2 positional arguments; the current learning rate
and the value of |
lambda _, mu: 1.0 / mu
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
max_or_min
|
Literal['max', 'min']
|
Whether to minimise or maximise |
'min'
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
10
|
tolerance
|
float
|
Tolerance used when determining if a minimum has been found. |
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/penalty.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
stochastic_gradient_descent(obj_fn, initial_guess, *, convergence_criterion=None, fn_args=(), fn_kwargs=None, learning_rate=0.1, maxiter=1000, optimiser=None, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Minimise a function of one argument using Stochastic Gradient Descent (SGD).
The obj_fn provided will be minimised over its first argument. If you wish to
minimise a function over a different argument, or multiple arguments, wrap it in a
suitable lambda expression that has the correct call signature. For example, to
minimise a function f(x, y, z) over y and z, use
g = lambda yz, x: f(x, yz[0], yz[1]), and pass g in as obj_fn. Note that
you will also need to provide a constant value for x via fn_args or fn_kwargs.
The fn_args and fn_kwargs keys can be used to supply additional parameters that
need to be passed to obj_fn, but which should be held constant.
SGD terminates when the convergence_criterion is found to be smaller than the
tolerance. That is, when
convergence_criterion(objective_value, gradient_value) <= tolerance is found to
be True, the algorithm considers a minimum to have been found. The default
condition under which the algorithm terminates is when the norm of the gradient
at the current argument value is smaller than the provided tolerance.
The optimiser to use can be selected by passing in a suitable optax optimiser
via the optimiser command. By default, optax.adams is used with the supplied
learning_rate. Providing an explicit value for optimiser will result in the
learning_rate argument being ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], ArrayLike]
|
Function to be minimised over its first argument. |
required |
initial_guess
|
PyTree
|
Initial guess for the minimising argument. |
required |
convergence_criterion
|
Callable[[PyTree, PyTree], ArrayLike] | None
|
The quantity that will be tested against |
None
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
learning_rate
|
float
|
Default learning rate (or step size) to use when using the
default |
0.1
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
1000
|
optimiser
|
GradientTransformationExtraArgs | None
|
The |
None
|
tolerance
|
float
|
|
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/sgd.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
aug_lagrangian
Augmented Lagrangian solvers.
augmented_lagrangian(obj_fn, initial_guess, bounds, *, initial_mu=1.0, update_mu=lambda mu: 10 * mu, initial_learning_rate=0.1, update_learning_rate=lambda _, mu, __: 1.0 / mu, bounds_epsilon=0.0, convergence_criterion=None, fn_args=(), fn_kwargs=None, max_or_min='min', maxiter=10, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Optimise a function using the Augmented Lagrangian method.
Implemented the method as described at https://en.wikipedia.org/wiki/Augmented_Lagrangian_method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], Array]
|
Function to minimise. |
required |
initial_guess
|
PyTree
|
An initial guess for the solution. |
required |
bounds
|
Callable[[PyTree], Array]
|
Function that evaluates bounds on the minimisation problem. |
required |
initial_mu
|
float
|
Starting value for |
1.0
|
update_mu
|
Callable[[float], float]
|
Function to update |
lambda mu: 10 * mu
|
initial_learning_rate
|
float
|
Learning rate to use in the first gradient descent solve. |
0.1
|
update_learning_rate
|
Callable[[float, float, float], float]
|
Function to update the learning rate after each gradient
descent solve. Should take 3 positional arguments; the current learning
rate, and the values of |
lambda _, mu, __: 1.0 / mu
|
bounds_epsilon
|
float
|
Value of epsilon to use for the bounds. Any value smaller than this will be treated as equal to 0. |
0.0
|
convergence_criterion
|
Callable[[PyTree, PyTree], Array] | None
|
The quantity that will be tested against |
None
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
max_or_min
|
Literal['max', 'min']
|
Whether to minimise or maximise |
'min'
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
10
|
tolerance
|
float
|
Tolerance used when determining if a minimum has been found. |
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/aug_lagrangian.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
iteration_result
Container classes for outputs from each iteration of solver methods.
IterationResult
dataclass
Result container for iterative solvers with optional history logging.
Stores the latest iterate and if history_logging_interval > 0, update appends
snapshots of the iterate to corresponding history lists each time the iteration
number is a multiple of history_logging_interval.
Instances are mutable but do not allow dynamic attribute creation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fn_args
|
PyTree
|
Argument to the objective function at final iteration (the solution,
if |
required |
grad_val
|
PyTree | None
|
Value of the gradient of the objective function at the |
None
|
iters
|
int
|
Number of iterations performed. |
required |
obj_val
|
ArrayLike
|
Value of the objective function at |
required |
iter_history
|
list[int]
|
List of iteration numbers at which history was logged. |
list()
|
fn_args_history
|
list[PyTree]
|
List of |
list()
|
grad_val_history
|
list[PyTree]
|
List of |
list()
|
obj_val_history
|
list[ArrayLike]
|
List of |
list()
|
history_logging_interval
|
int
|
Interval at which to log history. If
|
0
|
Source code in src/causalprog/solvers/iteration_result.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
update(current_params, iters, objective_value, gradient_value=None)
Update the IterationResult object with current iteration data.
Only updates the history if history_logging_interval is positive and
the current iteration is a multiple of history_logging_interval.
Source code in src/causalprog/solvers/iteration_result.py
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | |
penalty
Penalty method solvers.
penalty_method(obj_fn, initial_guess, bounds, *, initial_mu=1.0, update_mu=lambda mu: 10 * mu, initial_learning_rate=0.1, update_learning_rate=lambda _, mu: 1.0 / mu, bounds_epsilon=0.0, convergence_criterion=None, fn_args=(), fn_kwargs=None, max_or_min='min', maxiter=10, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Minimise a function using a penalty method.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], Array]
|
Function to minimise. |
required |
initial_guess
|
PyTree
|
An initial guess for the solution. |
required |
bounds
|
Callable[[PyTree], Array]
|
Function that evaluates bounds on the minimisation problem. |
required |
initial_mu
|
float
|
Starting value for |
1.0
|
update_mu
|
Callable[[float], float]
|
Function to update |
lambda mu: 10 * mu
|
bounds_epsilon
|
float
|
Value of epsilon to use for the bounds. Any value smaller than this will be treated as equal to 0. |
0.0
|
convergence_criterion
|
Callable[[PyTree, PyTree], Array] | None
|
The quantity that will be tested against |
None
|
initial_learning_rate
|
float
|
Learning rate to use in the first gradient descent solve |
0.1
|
update_learning_rate
|
Callable[[float, float], float]
|
Function to update the learning rate after each gradient
descent solve. Should take 2 positional arguments; the current learning rate
and the value of |
lambda _, mu: 1.0 / mu
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
max_or_min
|
Literal['max', 'min']
|
Whether to minimise or maximise |
'min'
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
10
|
tolerance
|
float
|
Tolerance used when determining if a minimum has been found. |
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/penalty.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
sgd
Minimisation via Stochastic Gradient Descent.
stochastic_gradient_descent(obj_fn, initial_guess, *, convergence_criterion=None, fn_args=(), fn_kwargs=None, learning_rate=0.1, maxiter=1000, optimiser=None, tolerance=1e-08, history_logging_interval=-1, callbacks=None)
Minimise a function of one argument using Stochastic Gradient Descent (SGD).
The obj_fn provided will be minimised over its first argument. If you wish to
minimise a function over a different argument, or multiple arguments, wrap it in a
suitable lambda expression that has the correct call signature. For example, to
minimise a function f(x, y, z) over y and z, use
g = lambda yz, x: f(x, yz[0], yz[1]), and pass g in as obj_fn. Note that
you will also need to provide a constant value for x via fn_args or fn_kwargs.
The fn_args and fn_kwargs keys can be used to supply additional parameters that
need to be passed to obj_fn, but which should be held constant.
SGD terminates when the convergence_criterion is found to be smaller than the
tolerance. That is, when
convergence_criterion(objective_value, gradient_value) <= tolerance is found to
be True, the algorithm considers a minimum to have been found. The default
condition under which the algorithm terminates is when the norm of the gradient
at the current argument value is smaller than the provided tolerance.
The optimiser to use can be selected by passing in a suitable optax optimiser
via the optimiser command. By default, optax.adams is used with the supplied
learning_rate. Providing an explicit value for optimiser will result in the
learning_rate argument being ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj_fn
|
Callable[[PyTree], ArrayLike]
|
Function to be minimised over its first argument. |
required |
initial_guess
|
PyTree
|
Initial guess for the minimising argument. |
required |
convergence_criterion
|
Callable[[PyTree, PyTree], ArrayLike] | None
|
The quantity that will be tested against |
None
|
fn_args
|
tuple
|
Positional arguments to be passed to |
()
|
fn_kwargs
|
dict | None
|
Keyword arguments to be passed to |
None
|
learning_rate
|
float
|
Default learning rate (or step size) to use when using the
default |
0.1
|
maxiter
|
int
|
Maximum number of iterations to perform. An error will be reported if this number of iterations is exceeded. |
1000
|
optimiser
|
GradientTransformationExtraArgs | None
|
The |
None
|
tolerance
|
float
|
|
1e-08
|
history_logging_interval
|
int
|
Interval (in number of iterations) at which to log
the history of optimisation. If |
-1
|
callbacks
|
Callable[[IterationResult], None] | list[Callable[[IterationResult], None]] | None
|
A |
None
|
Returns:
| Type | Description |
|---|---|
SolverResult
|
|
Source code in src/causalprog/solvers/sgd.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 | |
solver_callbacks
Module for callback functions for solvers.
tqdm_callback(total)
Progress bar callback using tqdm.
Creates a callback function that can be passed to solvers to display a progress bar during optimization. The progress bar updates based on the number of iterations and also displays the current objective value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
total
|
int
|
Total number of iterations for the progress bar. |
required |
Returns:
| Type | Description |
|---|---|
Callable[[IterationResult], None]
|
Callback function that updates the progress bar. |
Source code in src/causalprog/solvers/solver_callbacks.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 | |
solver_result
Container class for outputs from solver methods.
SolverResult
dataclass
Container class for outputs from solver methods.
Instances of this class provide a container for useful information that comes out of running one of the solver methods on a causal problem.
Attributes:
| Name | Type | Description |
|---|---|---|
fn_args |
PyTree
|
Argument to the objective function at final iteration (the solution,
if |
grad_val |
PyTree | None
|
Value of the gradient of the objective function at the |
iters |
int
|
Number of iterations performed. |
maxiter |
int
|
Maximum number of iterations the solver was permitted to perform. |
obj_val |
ArrayLike
|
Value of the objective function at |
reason |
str
|
Human-readable string explaining success or reasons for solver failure. |
successful |
bool
|
|
iter_history |
list[int]
|
List of iteration numbers at which history was logged. |
fn_args_history |
list[PyTree]
|
List of |
grad_val_history |
list[PyTree]
|
List of |
obj_val_history |
list[ArrayLike]
|
List of |
Source code in src/causalprog/solvers/solver_result.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | |
utils
Utility classes and methods.
norms
Misc collection of norm-like functions for PyTree structures.
l2_normsq(x)
Square of the l2-norm of a PyTree.
This is effectively "sum(elements**2 in leaf for leaf in x)".
Source code in src/causalprog/utils/norms.py
11 12 13 14 15 16 17 18 | |
translator
Helper class to keep the codebase backend-agnostic.
Our frontend (or user-facing) classes each use a syntax that applies across the package codebase. By contrast, the various backends that we want to support will have different syntaxes and call signatures for the functions that we want to support. As such, we need a helper class that can store this "translation" information, allowing the user to interact with the package in a standard way but also allowing them to choose their own backend if desired.
Translator
Bases: ABC
Maps syntax of a backend function to our frontend syntax.
Different backends have different syntax for drawing samples from the distributions they support. In order to map these different syntaxes to our backend-agnostic framework, we need a container class to map the names we have chosen for our frontend methods to those used by their corresponding backend method.
A Translator allows us to identify whether a user-provided backend object is
compatible with one of our frontend wrapper classes (and thus, call signatures). It
also allows users to write their own translators for any custom backends that we do
not explicitly support.
The use case for a Translator is as follows. Suppose that we have a frontend
class C that needs to provide a method do_something. C stores a
reference to a backend object obj that can provide the functionality of
do_something via one of its methods, obj.backend_method. However, there is
no guarantee that the signature of do_something maps identically to that of
obj.backend_method. A Translator allows us to encode a mapping of
obj.backend_methods arguments to those of do_something.
Source code in src/causalprog/utils/translator.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |
compulsory_backend_args
property
Arguments that are required to be taken by the backend function.
compulsory_frontend_args
abstractmethod
property
Arguments that are required by the frontend function.
__init__(backend_method=None, **front_args_to_back_args)
Create a new Translator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
backend_method
|
str
|
Name of the backend method that the instance translates. |
None
|
**front_args_to_back_args
|
str
|
Mapping of frontend argument names to the corresponding backend argument names. |
{}
|
Source code in src/causalprog/utils/translator.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 | |
translate_args(**kwargs)
Translate frontend arguments (with values) to backend arguments.
Essentially transforms frontend keyword arguments into their backend keyword arguments, preserving the value assigned to each argument.
Source code in src/causalprog/utils/translator.py
85 86 87 88 89 90 91 92 93 94 95 | |
validate_compatible(obj)
Determine if obj provides a compatible backend method.
obj must provide a callable whose name matches self.backend_method,
and the callable referenced must take arguments matching the names specified in
self.compulsory_backend_args.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obj
|
object
|
Object to check possesses a method that can be translated into frontend syntax. |
required |
Source code in src/causalprog/utils/translator.py
97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 | |