Graphs and CPDs¶
Building a graph and giving it numbers. Weights are in bits throughout, and states are referenced by value, never by position.
Build a graph¶
| Call | What it does |
|---|---|
pf.CausalGraph(name=None) |
A new graph. The name is display only. |
graph.add_variable(name, states=(False, True)) |
Add a variable and return it. |
graph.add_definition(name, states=(False, True)) |
Add a variable its parents constitute rather than cause. |
cause.causes(effect, p_if=None, p_if_not=None) |
Draw a causal edge. With both numbers, writes the CPD too, which only works for a single cause. |
part.constitutes(node) |
Draw a constitutive edge into a definitional node. |
graph.add_edge(cause, effect, kind=Causal) |
The graph-level spelling of the same thing. |
variable.add_evidence(label="evidence", *, p_if=None, p_if_not=None, outcomes=None, table=None, id=None) |
Hang a virtual-evidence node off this variable and return it. |
variable.gates |
The gates on this node's CPD, or (). Each names a source and the parent whose edge it modulates. |
variable.gate_sources |
The parents that gate rather than carry evidence. |
graph.by_id(id) / graph.by_name(name) |
Look a variable back up. The id is the key that survives a rename. |
graph.check() |
Raise if the graph is not ready to answer questions. |
Structure before parameters, with one exception: declaring a gate draws the edge
it implies, because naming the source in a Gate is already a statement that it
bears on the node.
A variable's own parents and children are properties rather than graph methods:
variable.parents, variable.children, variable.evidence.
A gate source is a parent, because the arithmetic needs it to be, so it
appears in parents alongside the causes. gate_sources is which of them are
there to gate, and the difference is the ordinary causal parents:
import probability_flow as pf
g = pf.CausalGraph("camera")
speeding = g.add_variable("The car was speeding")
calibrated = g.add_variable("The camera was calibrated")
reading = g.add_variable("The camera recorded a violation")
speeding.set_prior(0.3)
calibrated.set_prior(0.8)
speeding.causes(reading)
reading.set_cpd(pf.IndependentEvidence(
0.02, {speeding: 5.0},
gates=[pf.Gate(calibrated, modulates=speeding, weight_when_gated=0.6)]))
gating = {id(p) for p in reading.gate_sources}
causal = [p for p in reading.parents if id(p) not in gating]
[p.name for p in causal] # ['The car was speeding']
[(x.source.name, x.modulates.name) for x in reading.gates]
Both are on the variable rather than reached through the CPD, because
cpd.gates exists only on the additive family: on a logical, noisy or tabular
node it raises, and so does a node that has no CPD yet. variable.gates is ()
for all of them.
Give it numbers¶
A prior is the zero-parent CPD, so there is no separate prior concept and a caused variable cannot carry one.
| Call | What it does |
|---|---|
variable.set_prior(value) |
For a parentless variable. One number for a binary, a full distribution otherwise. |
variable.set_cpd(spec) |
Any of the forms below, a dict keyed by state tuples, or a list of (conditions, value) pairs. |
pf.CPT(causes=None, table=None) |
An explicit table. .when({...}, p) names one row, .otherwise(p) fills the rest. |
pf.IndependentEvidence(baseline, weights, gates=()) |
Additive in log-odds. baseline is a probability, weights are in bits and signed, so a negative weight argues against the child. |
pf.Gate(source, modulates, weight_when_gated=0.0) |
Replaces another edge's weight rather than scaling it, so it can weaken, strengthen or reverse. Undercutting is the 0.0 case. |
logical.And(over=(), leak=0.0) |
Every constituent. |
logical.Or(over=(), leak=0.0) |
Any constituent. |
logical.AtLeast(k, over, leak=0.0), Exactly, AtMost |
A predicate on the count. Each k counts against a particular number of inputs. |
noisy.Or(activations, leak=0.0) |
Each input has a chance of doing its job when satisfied. |
noisy.And(activations) |
No leak, because the only leak a conjunction can carry without losing necessity is a downward one. |
And and Or extend when a constituent is added later. A counted predicate is
cleared instead, with a warning, because k would otherwise be re-read against a
new denominator.
Gates are declared on the child's CPD and only IndependentEvidence reads them.
That is a fact about the implementation rather than about gating, and
issue 34
is where a tabular gate would go.
Change one, or take it away¶
A graph can be edited after it is built. Removal asks the CPD to drop the parent rather than rewriting it from outside, because only the family knows its own shape.
| Call | What it does |
|---|---|
graph.remove_edge(cause, effect) |
Drop an edge, and the effect CPD's term for it. |
graph.remove_variable(variable) |
Drop a variable, its virtual evidence, and every edge touching either. |
cpd.set_weight(parent, bits) |
Change what one parent's edge carries. The baseline does not move. |
variable.set_baseline(probability) |
Set P(this) with every parent absent. A probability, like set_prior. |
variable.name = ... |
Rename. The id is what survives a rename, so references keep working. |
A baseline is a probability, and there is no bits= flag. It is the unit
set_prior takes and the unit the file format stores. There is deliberately no
relative shift_baseline either: beside set_baseline(0.2) it would be a
second call that reads the same and means something else, because 0.2 is a
plausible probability and a plausible number of bits. To move a baseline by a
known amount of log-odds, read cpd.baseline, work out where you want it, and
set it.
Ids are never renumbered or reused. Removing n3 leaves n4 as n4, and
the next variable you add takes an id that has never been used rather than the
hole. Ids are the keys every external reference uses, so renumbering would be
schema-breaking rather than merely surprising.
A gate goes when either end does. It names a source and the edge it modulates, so losing either leaves it describing something that is not there. You are warned when that happens, because it is not what a caller expects from removing one edge.
What happens to the CPD depends on the family, and on the same test that governs adding a parent: reduce where the reduction is the only thing you could have meant, clear where it is not.
| Family | Losing a parent |
|---|---|
IndependentEvidence |
loses the term. The baseline does not move. |
noisy.Or, noisy.And |
loses the factor. The leak does not move. |
logical.And, logical.Or |
loses the constituent, which is a different proposition and is meant to be. |
logical.AtLeast, Exactly, AtMost |
cleared, because every k counts against a particular number of inputs. |
pf.CPT |
cleared, because a table is indexed by the whole assignment and nothing in it says which slice should survive. |
A cleared CPD is not a silent reinterpretation: the variable then has no CPD, so
check() and every query fail until you write a new one.
Removing the hypothesis is refused. Set graph.hypothesis to something else
first if that is what you mean.
All three kinds of edge, in one graph¶
Black arrows are causes. The green double lines are constitutive, running into
the ∧ definitional node. The purple dashed line is a gate: it lands on the
edge it modulates, not on the node, because that is what it does.
Things you receive rather than construct¶
These are in the public surface because you get them back, not because you call them. No consumer in this project constructs any of them directly.
| Name | Where it comes from |
|---|---|
pf.Distribution |
What posterior() returns. float() works on a binary one, .p_true, .p(state), and .is_exact travels with it so an approximate answer cannot be mistaken for ground truth. |
pf.Variable, pf.Definition |
What add_variable and add_definition return. |
pf.Evidence |
What add_evidence returns, also reachable as variable.evidence. |
pf.Edge, pf.Causal, pf.Constitutive |
What add_edge returns, and the kind argument it takes. |
pf.CPD, pf.Logical, pf.Table |
Base classes, for an isinstance check on variable.cpd. |
pf.BINARY |
The default states, (False, True). |
A CPD you are handed answers .rows(), .distribution(assignment) and
.as_table(), and an additive one also answers .weight(parent). Every
parameterised form can write itself out in full, which is what keeps the compact
forms inspectable.