Skip to content

Index

Per-node, backend-agnostic data generation process (DGP).

Public surface:

  • DGP — the backend-agnostic protocol: per-node mechanisms (fit_node/response/draw_noise), joint sample, and the value-level intervene (Pearl surgery on given rows). The DGP is an immutable, fitted model — it has NO structure-edit methods;
  • DGPMixin — the generic reference implementations of everything above except fit_node (backends may override any method natively, preserving the protocol semantics);
  • edits — the structure-modification vocabulary as free functions (scale_edge/remove_edge/add_edge_contribution/ exogenize/set_form), returning NEW DGPs;
  • backends — the concrete backend modules (badgers.core.dgp.backends);
  • ordered_descendants — topological descendant walk (in badgers.core.causal_graph).

Heavy estimation libraries (PyMC, DoWhy) live in their own backend modules under badgers.core.dgp.backends and are imported lazily inside those modules; they are never imported by this package.

DGP

Bases: Protocol

Protocol for a per-node data generation process.

Source code in badgers/core/dgp/protocol.py
 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
class DGP(Protocol):
    """Protocol for a per-node data generation process."""

    #: The structural DAG (latent variables).
    graph: nx.DiGraph
    #: Node -> integer column index of its measurement.
    column_mapping: dict

    def fit(self, X: np.ndarray) -> DGP:
        """Fit every node's mechanism in topological order; return ``self``.

        ``DGPMixin`` provides the default topological walk over
        ``fit_node``; backends that do not inherit it must implement
        ``fit`` themselves. Generators call ``fit`` on any backend passed
        via ``fit(dgp=...)``.
        """
        ...

    def is_fitted(self) -> bool:
        """True iff every structural node has a fitted mechanism.

        Generator-side convenience: lets a generator fit an UNFITTED DGP
        lazily on the generate-time data while leaving a fitted one
        untouched. Backend-specific storage means backends implement
        this; read-only views delegate to the DGP they wrap.
        """
        ...

    def fit_node(self, node: Hashable, parents: Iterable[Hashable],
                 data: np.ndarray) -> None:
        """Fit ONE node's mechanism from (data, parents).

        This is the only backend-specific operation. For a root node (no
        parents) the mechanism is a distribution (fitted mean + spread).
        """
        ...

    def response(self, node: Hashable,
                 parent_values: np.ndarray) -> np.ndarray:
        """Evaluate the fitted response of ``node`` for given parent values.

        ``parent_values`` has shape ``(n_rows, len(parents))``; for a root
        node it must have shape ``(n_rows, 0)``. Returns shape ``(n_rows,)``.
        """
        ...

    def draw_noise(self, node: Hashable, rng: np.random.Generator,
                   n: int) -> np.ndarray:
        """Draw ``n`` shocks from the node's own (fitted) noise.

        Representation-free by design: parametric backends draw from their
        fitted scale, empirical backends resample their residuals.
        """
        ...

    def structural(self, node: Hashable, parent_values: np.ndarray,
                   rng: np.random.Generator, n: int) -> np.ndarray:
        """Compose ONE node's values for a cascade: deterministic part +
        noise.

        Default (``DGPMixin``): the additive composition
        ``response(parent_values) + draw_noise(node, rng, n)``. Backends
        whose mechanisms are not additive override it — e.g. the gcm
        backend delegates the composition to the mechanism's own
        ``evaluate(parents, noise)`` (rounded discrete predictions, class
        CDFs) while still drawing the noise with ``rng``.
        """
        ...

    def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
        """Tier 2: sample ``n`` joint rows from the fitted graph."""
        ...

    def pick_parameters(self, rng=None) -> "DGP":
        """Hook called ONCE at the top of ``sample``/``intervene``: return
        the DGP instance whose mechanisms drive this cascade.

        Generic default (``DGPMixin``): ``self`` — deterministic backends
        fit exactly one parameter set. Uncertainty-carrying backends
        override it: they select ONE coherent parameter draw from ``rng``
        and return a read-only view of themselves evaluating it. The DGP
        keeps every draw from ``fit``; the choice is made at the top of
        each cascade from the caller's rng — never inside ``response``
        and never by mutating the fitted DGP.
        """
        ...

    # -- Value-level intervention -------------------------------------------

    def intervene(self, rows: np.ndarray, nodes: Hashable | Iterable,
                  values=None, *, rng=None) -> np.ndarray:
        """Pearl surgery applied to GIVEN rows: fix the nodes at ``values``,
        recompute all their descendants (topological order, fresh noise).

        ``DGPMixin`` provides the generic implementation; backends may
        override it natively, preserving the same semantics (upstream and
        non-descendant columns and rows untouched; intervened nodes keep
        their fixed values even if they are descendants of other
        intervened nodes).

        NOTE: structure edits are intentionally NOT part of this protocol.
        The DGP is an immutable, fitted world; structural modifications
        live in ``badgers.core.dgp.edits`` (free functions returning a new
        world: ``scale_edge``/``remove_edge``/``add_edge_contribution``/
        ``exogenize``/``set_form``).
        """
        ...

draw_noise(node, rng, n)

Draw n shocks from the node's own (fitted) noise.

Representation-free by design: parametric backends draw from their fitted scale, empirical backends resample their residuals.

Source code in badgers/core/dgp/protocol.py
66
67
68
69
70
71
72
73
def draw_noise(self, node: Hashable, rng: np.random.Generator,
               n: int) -> np.ndarray:
    """Draw ``n`` shocks from the node's own (fitted) noise.

    Representation-free by design: parametric backends draw from their
    fitted scale, empirical backends resample their residuals.
    """
    ...

fit(X)

Fit every node's mechanism in topological order; return self.

DGPMixin provides the default topological walk over fit_node; backends that do not inherit it must implement fit themselves. Generators call fit on any backend passed via fit(dgp=...).

Source code in badgers/core/dgp/protocol.py
28
29
30
31
32
33
34
35
36
def fit(self, X: np.ndarray) -> DGP:
    """Fit every node's mechanism in topological order; return ``self``.

    ``DGPMixin`` provides the default topological walk over
    ``fit_node``; backends that do not inherit it must implement
    ``fit`` themselves. Generators call ``fit`` on any backend passed
    via ``fit(dgp=...)``.
    """
    ...

fit_node(node, parents, data)

Fit ONE node's mechanism from (data, parents).

This is the only backend-specific operation. For a root node (no parents) the mechanism is a distribution (fitted mean + spread).

Source code in badgers/core/dgp/protocol.py
48
49
50
51
52
53
54
55
def fit_node(self, node: Hashable, parents: Iterable[Hashable],
             data: np.ndarray) -> None:
    """Fit ONE node's mechanism from (data, parents).

    This is the only backend-specific operation. For a root node (no
    parents) the mechanism is a distribution (fitted mean + spread).
    """
    ...

intervene(rows, nodes, values=None, *, rng=None)

Pearl surgery applied to GIVEN rows: fix the nodes at values, recompute all their descendants (topological order, fresh noise).

DGPMixin provides the generic implementation; backends may override it natively, preserving the same semantics (upstream and non-descendant columns and rows untouched; intervened nodes keep their fixed values even if they are descendants of other intervened nodes).

NOTE: structure edits are intentionally NOT part of this protocol. The DGP is an immutable, fitted world; structural modifications live in badgers.core.dgp.edits (free functions returning a new world: scale_edge/remove_edge/add_edge_contribution/ exogenize/set_form).

Source code in badgers/core/dgp/protocol.py
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def intervene(self, rows: np.ndarray, nodes: Hashable | Iterable,
              values=None, *, rng=None) -> np.ndarray:
    """Pearl surgery applied to GIVEN rows: fix the nodes at ``values``,
    recompute all their descendants (topological order, fresh noise).

    ``DGPMixin`` provides the generic implementation; backends may
    override it natively, preserving the same semantics (upstream and
    non-descendant columns and rows untouched; intervened nodes keep
    their fixed values even if they are descendants of other
    intervened nodes).

    NOTE: structure edits are intentionally NOT part of this protocol.
    The DGP is an immutable, fitted world; structural modifications
    live in ``badgers.core.dgp.edits`` (free functions returning a new
    world: ``scale_edge``/``remove_edge``/``add_edge_contribution``/
    ``exogenize``/``set_form``).
    """
    ...

is_fitted()

True iff every structural node has a fitted mechanism.

Generator-side convenience: lets a generator fit an UNFITTED DGP lazily on the generate-time data while leaving a fitted one untouched. Backend-specific storage means backends implement this; read-only views delegate to the DGP they wrap.

Source code in badgers/core/dgp/protocol.py
38
39
40
41
42
43
44
45
46
def is_fitted(self) -> bool:
    """True iff every structural node has a fitted mechanism.

    Generator-side convenience: lets a generator fit an UNFITTED DGP
    lazily on the generate-time data while leaving a fitted one
    untouched. Backend-specific storage means backends implement
    this; read-only views delegate to the DGP they wrap.
    """
    ...

pick_parameters(rng=None)

Hook called ONCE at the top of sample/intervene: return the DGP instance whose mechanisms drive this cascade.

Generic default (DGPMixin): self — deterministic backends fit exactly one parameter set. Uncertainty-carrying backends override it: they select ONE coherent parameter draw from rng and return a read-only view of themselves evaluating it. The DGP keeps every draw from fit; the choice is made at the top of each cascade from the caller's rng — never inside response and never by mutating the fitted DGP.

Source code in badgers/core/dgp/protocol.py
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
def pick_parameters(self, rng=None) -> "DGP":
    """Hook called ONCE at the top of ``sample``/``intervene``: return
    the DGP instance whose mechanisms drive this cascade.

    Generic default (``DGPMixin``): ``self`` — deterministic backends
    fit exactly one parameter set. Uncertainty-carrying backends
    override it: they select ONE coherent parameter draw from ``rng``
    and return a read-only view of themselves evaluating it. The DGP
    keeps every draw from ``fit``; the choice is made at the top of
    each cascade from the caller's rng — never inside ``response``
    and never by mutating the fitted DGP.
    """
    ...

response(node, parent_values)

Evaluate the fitted response of node for given parent values.

parent_values has shape (n_rows, len(parents)); for a root node it must have shape (n_rows, 0). Returns shape (n_rows,).

Source code in badgers/core/dgp/protocol.py
57
58
59
60
61
62
63
64
def response(self, node: Hashable,
             parent_values: np.ndarray) -> np.ndarray:
    """Evaluate the fitted response of ``node`` for given parent values.

    ``parent_values`` has shape ``(n_rows, len(parents))``; for a root
    node it must have shape ``(n_rows, 0)``. Returns shape ``(n_rows,)``.
    """
    ...

sample(rng, n)

Tier 2: sample n joint rows from the fitted graph.

Source code in badgers/core/dgp/protocol.py
89
90
91
def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
    """Tier 2: sample ``n`` joint rows from the fitted graph."""
    ...

structural(node, parent_values, rng, n)

Compose ONE node's values for a cascade: deterministic part + noise.

Default (DGPMixin): the additive composition response(parent_values) + draw_noise(node, rng, n). Backends whose mechanisms are not additive override it — e.g. the gcm backend delegates the composition to the mechanism's own evaluate(parents, noise) (rounded discrete predictions, class CDFs) while still drawing the noise with rng.

Source code in badgers/core/dgp/protocol.py
75
76
77
78
79
80
81
82
83
84
85
86
87
def structural(self, node: Hashable, parent_values: np.ndarray,
               rng: np.random.Generator, n: int) -> np.ndarray:
    """Compose ONE node's values for a cascade: deterministic part +
    noise.

    Default (``DGPMixin``): the additive composition
    ``response(parent_values) + draw_noise(node, rng, n)``. Backends
    whose mechanisms are not additive override it — e.g. the gcm
    backend delegates the composition to the mechanism's own
    ``evaluate(parents, noise)`` (rounded discrete predictions, class
    CDFs) while still drawing the noise with ``rng``.
    """
    ...

DGPMixin

Mixin providing default fit, sample, intervene and the structure edits.

Source code in badgers/core/dgp/base.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
 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
class DGPMixin:
    """Mixin providing default ``fit``, ``sample``, ``intervene`` and the
    structure edits."""

    graph: nx.DiGraph
    column_mapping: dict

    def fit(self, X: np.ndarray) -> DGPMixin:
        """Fit every structural node's mechanism, in topological order."""
        for node in topological_order(self.graph):
            self.fit_node(node, get_parents(self.graph, node), X)
        return self


    def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
        """Sample ``n`` joint rows.

        Topological walk: every node contributes its :meth:`structural`
        values (default: the additive composition ``response(parents) +
        draw_noise``); for roots, ``parent_values`` has shape ``(n, 0)``.

        ONE parameter set drives the whole cascade (one call = one
        coherent model); see :meth:`pick_parameters`.
        """
        carrier = self.pick_parameters(rng)
        order = topological_order(carrier.graph)
        X_sampled = np.zeros((n, len(carrier.graph.nodes)))
        for node in order:
            col = carrier.column_mapping[node]
            pcols = [
                carrier.column_mapping[p]
                for p in get_parents(carrier.graph, node)
            ]
            X_sampled[:, col] = carrier.structural(
                node, X_sampled[:, pcols], rng, n
            )
        return X_sampled

    def structural(self, node, parent_values, rng, n):
        """One node's values for a cascade: compose the deterministic
        part and the noise.

        Default: the additive composition ``response(parents) +
        draw_noise``. Backends whose mechanisms are not additive (e.g.
        dowhy functional causal models, where ``evaluate`` owns the
        composition — rounded predictions, class CDFs, post-nonlinear
        links) override this and delegate the composition to the
        library's own ``evaluate`` while still drawing the noise with
        the caller's ``rng``.
        """
        return self.response(node, parent_values) + self.draw_noise(node, rng, n)

    # -- Value-level intervention --------------------------------------------

    def intervene(self, rows, nodes, values=None, *, rng=None):
        """Pearl surgery applied to given rows: fix the nodes at ``values``,
        recompute ALL their descendants with fresh noise.

        Semantics:

        1. If ``values`` is given, overwrite each node's column (the
           intervention itself; ``None`` keeps the current column values —
           callers that pre-write their perturbation use this).
        2. Walk the descendants of ``nodes`` in topological order (the
           intervened nodes themselves are excluded — pinned values stay
           pinned even if one intervened node is a descendant of another)
           and recompute each via :meth:`structural` (default
           ``response(parents_new) + fresh noise``).

        Upstream and non-descendant columns and rows are untouched.
        Pre-existing NaNs in a recomputed descendant column are
        re-evaluated (a NaN parent propagates to the child; a NaN child
        with finite parents is recomputed to a finite value).

        Args:
            rows: array of shape (n_rows, n_features); modified in place.
            nodes: one node or a list of nodes to intervene on.
            values: optional list of per-node column values (one array of
                shape (n_rows,) per node, same order as ``nodes``).
            rng: NumPy generator (fresh descendant noise); required.

        Returns:
            The same ``rows`` array, with the intervention applied.
        """
        nodes = _as_node_list(nodes)
        if rng is None:
            raise ValueError(
                "intervene requires rng (descendants are recomputed with "
                "fresh noise)"
            )
        # ONE parameter set drives the whole cascade (one intervention =
        # one coherent model); see pick_parameters.
        carrier = self.pick_parameters(rng)
        if values is not None:
            for node, vals in zip(nodes, values, strict=True):
                rows[:, carrier.column_mapping[node]] = vals
        pinned = set(nodes)
        n = rows.shape[0]
        for child in ordered_descendants(carrier.graph, nodes):
            if child in pinned:
                continue
            ccol = carrier.column_mapping[child]
            pcols = [
                carrier.column_mapping[p]
                for p in get_parents(carrier.graph, child)
            ]
            rows[:, ccol] = carrier.structural(child, rows[:, pcols], rng, n)
        return rows

    def pick_parameters(self, rng=None):
        """Hook called ONCE at the top of ``sample``/``intervene``: return
        the DGP instance whose mechanisms should drive this cascade.

        Generic default: ``self`` — a deterministic backend fits exactly
        ONE parameter set, so there is nothing to choose and no rng is
        consumed. Backends carrying parameter uncertainty override it:
        they use ``rng`` to select ONE coherent parameter draw and return
        a read-only view of themselves evaluating it. Separation of
        concerns: the DGP keeps every draw from ``fit``; the choice of
        which one drives a batch is made at the top of each cascade, from
        the caller's rng — never inside ``response`` (which takes no rng)
        and never by mutating the fitted DGP.
        """
        return self

fit(X)

Fit every structural node's mechanism, in topological order.

Source code in badgers/core/dgp/base.py
58
59
60
61
62
def fit(self, X: np.ndarray) -> DGPMixin:
    """Fit every structural node's mechanism, in topological order."""
    for node in topological_order(self.graph):
        self.fit_node(node, get_parents(self.graph, node), X)
    return self

intervene(rows, nodes, values=None, *, rng=None)

Pearl surgery applied to given rows: fix the nodes at values, recompute ALL their descendants with fresh noise.

Semantics:

  1. If values is given, overwrite each node's column (the intervention itself; None keeps the current column values — callers that pre-write their perturbation use this).
  2. Walk the descendants of nodes in topological order (the intervened nodes themselves are excluded — pinned values stay pinned even if one intervened node is a descendant of another) and recompute each via :meth:structural (default response(parents_new) + fresh noise).

Upstream and non-descendant columns and rows are untouched. Pre-existing NaNs in a recomputed descendant column are re-evaluated (a NaN parent propagates to the child; a NaN child with finite parents is recomputed to a finite value).

Args: rows: array of shape (n_rows, n_features); modified in place. nodes: one node or a list of nodes to intervene on. values: optional list of per-node column values (one array of shape (n_rows,) per node, same order as nodes). rng: NumPy generator (fresh descendant noise); required.

Returns: The same rows array, with the intervention applied.

Source code in badgers/core/dgp/base.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
def intervene(self, rows, nodes, values=None, *, rng=None):
    """Pearl surgery applied to given rows: fix the nodes at ``values``,
    recompute ALL their descendants with fresh noise.

    Semantics:

    1. If ``values`` is given, overwrite each node's column (the
       intervention itself; ``None`` keeps the current column values —
       callers that pre-write their perturbation use this).
    2. Walk the descendants of ``nodes`` in topological order (the
       intervened nodes themselves are excluded — pinned values stay
       pinned even if one intervened node is a descendant of another)
       and recompute each via :meth:`structural` (default
       ``response(parents_new) + fresh noise``).

    Upstream and non-descendant columns and rows are untouched.
    Pre-existing NaNs in a recomputed descendant column are
    re-evaluated (a NaN parent propagates to the child; a NaN child
    with finite parents is recomputed to a finite value).

    Args:
        rows: array of shape (n_rows, n_features); modified in place.
        nodes: one node or a list of nodes to intervene on.
        values: optional list of per-node column values (one array of
            shape (n_rows,) per node, same order as ``nodes``).
        rng: NumPy generator (fresh descendant noise); required.

    Returns:
        The same ``rows`` array, with the intervention applied.
    """
    nodes = _as_node_list(nodes)
    if rng is None:
        raise ValueError(
            "intervene requires rng (descendants are recomputed with "
            "fresh noise)"
        )
    # ONE parameter set drives the whole cascade (one intervention =
    # one coherent model); see pick_parameters.
    carrier = self.pick_parameters(rng)
    if values is not None:
        for node, vals in zip(nodes, values, strict=True):
            rows[:, carrier.column_mapping[node]] = vals
    pinned = set(nodes)
    n = rows.shape[0]
    for child in ordered_descendants(carrier.graph, nodes):
        if child in pinned:
            continue
        ccol = carrier.column_mapping[child]
        pcols = [
            carrier.column_mapping[p]
            for p in get_parents(carrier.graph, child)
        ]
        rows[:, ccol] = carrier.structural(child, rows[:, pcols], rng, n)
    return rows

pick_parameters(rng=None)

Hook called ONCE at the top of sample/intervene: return the DGP instance whose mechanisms should drive this cascade.

Generic default: self — a deterministic backend fits exactly ONE parameter set, so there is nothing to choose and no rng is consumed. Backends carrying parameter uncertainty override it: they use rng to select ONE coherent parameter draw and return a read-only view of themselves evaluating it. Separation of concerns: the DGP keeps every draw from fit; the choice of which one drives a batch is made at the top of each cascade, from the caller's rng — never inside response (which takes no rng) and never by mutating the fitted DGP.

Source code in badgers/core/dgp/base.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def pick_parameters(self, rng=None):
    """Hook called ONCE at the top of ``sample``/``intervene``: return
    the DGP instance whose mechanisms should drive this cascade.

    Generic default: ``self`` — a deterministic backend fits exactly
    ONE parameter set, so there is nothing to choose and no rng is
    consumed. Backends carrying parameter uncertainty override it:
    they use ``rng`` to select ONE coherent parameter draw and return
    a read-only view of themselves evaluating it. Separation of
    concerns: the DGP keeps every draw from ``fit``; the choice of
    which one drives a batch is made at the top of each cascade, from
    the caller's rng — never inside ``response`` (which takes no rng)
    and never by mutating the fitted DGP.
    """
    return self

sample(rng, n)

Sample n joint rows.

Topological walk: every node contributes its :meth:structural values (default: the additive composition response(parents) + draw_noise); for roots, parent_values has shape (n, 0).

ONE parameter set drives the whole cascade (one call = one coherent model); see :meth:pick_parameters.

Source code in badgers/core/dgp/base.py
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
def sample(self, rng: np.random.Generator, n: int) -> np.ndarray:
    """Sample ``n`` joint rows.

    Topological walk: every node contributes its :meth:`structural`
    values (default: the additive composition ``response(parents) +
    draw_noise``); for roots, ``parent_values`` has shape ``(n, 0)``.

    ONE parameter set drives the whole cascade (one call = one
    coherent model); see :meth:`pick_parameters`.
    """
    carrier = self.pick_parameters(rng)
    order = topological_order(carrier.graph)
    X_sampled = np.zeros((n, len(carrier.graph.nodes)))
    for node in order:
        col = carrier.column_mapping[node]
        pcols = [
            carrier.column_mapping[p]
            for p in get_parents(carrier.graph, node)
        ]
        X_sampled[:, col] = carrier.structural(
            node, X_sampled[:, pcols], rng, n
        )
    return X_sampled

structural(node, parent_values, rng, n)

One node's values for a cascade: compose the deterministic part and the noise.

Default: the additive composition response(parents) + draw_noise. Backends whose mechanisms are not additive (e.g. dowhy functional causal models, where evaluate owns the composition — rounded predictions, class CDFs, post-nonlinear links) override this and delegate the composition to the library's own evaluate while still drawing the noise with the caller's rng.

Source code in badgers/core/dgp/base.py
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
def structural(self, node, parent_values, rng, n):
    """One node's values for a cascade: compose the deterministic
    part and the noise.

    Default: the additive composition ``response(parents) +
    draw_noise``. Backends whose mechanisms are not additive (e.g.
    dowhy functional causal models, where ``evaluate`` owns the
    composition — rounded predictions, class CDFs, post-nonlinear
    links) override this and delegate the composition to the
    library's own ``evaluate`` while still drawing the noise with
    the caller's ``rng``.
    """
    return self.response(node, parent_values) + self.draw_noise(node, rng, n)

add_edge_contribution(dgp, child, parent, contribution=None, coefficient=None, draw_noise=None)

Add a NEW parent's additive term to a child's response (A5 cheap edit; ANM-scoped).

The child's response becomes base_response(child, parents) + contribution(parent_col); the graph gains the edge (parent, child). Exactly one of contribution (a closure of the parent column) or coefficient (sugar for lambda x: coefficient * x) must be given. The child's noise law is inherited from the base mechanism unless a draw_noise(rng, n) closure is supplied (Q2 option (b) pattern).

Raises ValueError if the edge would create a cycle (A6) or if the parent is already a parent of child.

Source code in badgers/core/dgp/edits.py
 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
def add_edge_contribution(dgp, child, parent, contribution=None,
                          coefficient=None, draw_noise=None):
    """Add a NEW parent's additive term to a child's response (A5 cheap
    edit; ANM-scoped).

    The child's response becomes ``base_response(child, parents) +
    contribution(parent_col)``; the graph gains the edge ``(parent,
    child)``. Exactly one of ``contribution`` (a closure of the parent
    column) or ``coefficient`` (sugar for ``lambda x: coefficient * x``)
    must be given. The child's noise law is inherited from the base
    mechanism unless a ``draw_noise(rng, n)`` closure is supplied (Q2
    option (b) pattern).

    Raises ``ValueError`` if the edge would create a cycle (A6) or if the
    parent is already a parent of ``child``.
    """
    if contribution is None and coefficient is None:
        raise ValueError(
            "add_edge_contribution requires a contribution closure or a "
            "coefficient (an ESTIMATED new parent is not supported by "
            "this view edit; for re-estimation after a structural change, "
            "build the modified SCM with the library's own API and wrap "
            "it again with GcmSCMDGP or PyMCSCMDGP)."
        )
    if contribution is not None and coefficient is not None:
        raise ValueError(
            "pass either contribution or coefficient, not both"
        )
    if contribution is not None and not callable(contribution):
        raise ValueError("contribution must be callable")
    if (child, parent) in dgp.graph.edges:
        raise ValueError(
            f"edge ({parent}, {child}) already exists; use set_form or "
            "scale_edge to modify it"
        )
    if nx.has_path(dgp.graph, child, parent):
        raise ValueError(
            f"adding edge ({parent}, {child}) would create a cycle: there "
            "is a directed path from the child back to the parent"
        )
    if coefficient is not None:
        contribution = (lambda x: coefficient * x)
    return _AddedEdgeContributionView(
        dgp, child, parent, contribution, draw_noise
    )

exogenize(dgp, node)

Make a node a root: remove its incoming edges (graph surgery as an edit; no refit). Returns an _ExogenizedView.

INTERVENTION-ONLY semantics: designed for the pin-then-intervene flow (the node's column is written by the generator; the cascade never recomputes a root). sample() on the returned view draws the node as 0 + N(0, residual_std) — NOT the node's real marginal; see the _ExogenizedView docstring for the deferred empirical-resampling route.

Source code in badgers/core/dgp/edits.py
122
123
124
125
126
127
128
129
130
131
132
133
def exogenize(dgp, node):
    """Make a node a root: remove its incoming edges (graph surgery as an
    edit; no refit). Returns an ``_ExogenizedView``.

    INTERVENTION-ONLY semantics: designed for the pin-then-intervene flow
    (the node's column is written by the generator; the cascade never
    recomputes a root). ``sample()`` on the returned view draws the node
    as ``0 + N(0, residual_std)`` — NOT the node's real marginal; see the
    ``_ExogenizedView`` docstring for the deferred empirical-resampling
    route.
    """
    return _ExogenizedView(dgp, node)

ordered_descendants(graph, nodes)

Return the descendants of nodes, in topological order.

The nodes themselves are excluded (nx.descendants semantics).

Parameters

graph : nx.DiGraph A directed acyclic graph. nodes : one node or an iterable of nodes

Returns

list Descendants of nodes, in topological order.

Source code in badgers/core/causal_graph.py
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
def ordered_descendants(graph: nx.DiGraph, nodes) -> list:
    """Return the descendants of ``nodes``, in topological order.

    The nodes themselves are excluded (``nx.descendants`` semantics).

    Parameters
    ----------
    graph : nx.DiGraph
        A directed acyclic graph.
    nodes : one node or an iterable of nodes

    Returns
    -------
    list
        Descendants of ``nodes``, in topological order.
    """
    if isinstance(nodes, (str, bytes)):
        nodes = [nodes]
    else:
        try:
            nodes = list(nodes)
        except TypeError:
            nodes = [nodes]
    descendants = set()
    for node in nodes:
        descendants |= nx.descendants(graph, node)
    order = topological_order(graph)
    return [node for node in order if node in descendants]

remove_edge(dgp, child, parent)

Remove an edge s->t: zero the parent's contribution (SCM surgery view — the removed parent's influence is absorbed into the child's exogenous shock; no refit). Q3 option (a).

Source code in badgers/core/dgp/edits.py
68
69
70
71
72
def remove_edge(dgp, child, parent):
    """Remove an edge s->t: zero the parent's contribution (SCM surgery
    view — the removed parent's influence is absorbed into the child's
    exogenous shock; no refit). Q3 option (a)."""
    return _ScaledEdgeView(dgp, child, parent, 0.0)

scale_edge(dgp, child, parent, k)

Scale one edge's contribution by k (variance-preserving view).

Returns the _ScaledEdgeView; call calibrate(data) on it to evaluate the variance budget (raises ValueError if infeasible).

Source code in badgers/core/dgp/edits.py
59
60
61
62
63
64
65
def scale_edge(dgp, child, parent, k):
    """Scale one edge's contribution by ``k`` (variance-preserving view).

    Returns the ``_ScaledEdgeView``; call ``calibrate(data)`` on it to
    evaluate the variance budget (raises ``ValueError`` if infeasible).
    """
    return _ScaledEdgeView(dgp, child, parent, k)

set_form(dgp, node, response_fn, draw_noise=None)

Replace one node's functional form with a user-supplied closure (F ← F′; no refit). Noise law INHERITED from the base mechanism by default; pass a draw_noise(rng, n) closure to supply your own noise law (Q2 option (b)). Returns a _FormView.

Source code in badgers/core/dgp/edits.py
136
137
138
139
140
141
def set_form(dgp, node, response_fn, draw_noise=None):
    """Replace one node's functional form with a user-supplied closure
    (F ← F′; no refit). Noise law INHERITED from the base mechanism by
    default; pass a ``draw_noise(rng, n)`` closure to supply your own
    noise law (Q2 option (b)). Returns a ``_FormView``."""
    return _FormView(dgp, node, response_fn, draw_noise)