Skip to content

cogant.markov

The cogant.markov package partitions a program graph into internal (mu), sensory (s), active (a), and external (eta) nodes — the four disjoint sets of an Active Inference Markov blanket.

Package

cogant.markov

COGANT Markov blanket extraction.

This submodule partitions a program graph into an Active-Inference-style Markov blanket: a triple of (internal, blanket={sensory, active}, external) states that together determine the conditional independence structure of a system of interest.

The canonical Active Inference decomposition is::

μ  — internal states  (only interact with sensory/active/other μ)
s  — sensory states    (internal  ← external, blanket)
a  — active states     (internal  → external, blanket)
η  — external states   (only interact with sensory/active/other η)

A Markov blanket is the minimal set B = s ∪ a such that μ ⊥ η | B.

Public API
  • :class:MarkovBlanket — dataclass holding the partition and metadata.
  • :class:MarkovBlanketExtractor — builds a blanket from a :class:ProgramGraph given a user-supplied "system of interest" seed set or an automatic seed chosen by cohesion/coupling scoring.
  • :func:partition_by_seeds — low-level partitioning primitive.
  • :func:serialize_blanket — JSON-ready dictionary form for the GNN bundle.

See :mod:cogant.markov.blanket, :mod:cogant.markov.extractor, and :mod:cogant.markov.network for implementation details.

BlanketNetwork dataclass

Collapsed four-node Active Inference network view of a blanket.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) net = build_blanket_network(graph, blanket) isinstance(net, BlanketNetwork) True "graph LR" in net.to_mermaid() True

Source code in py/cogant/markov/network.py
 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
@dataclass
class BlanketNetwork:
    """Collapsed four-node Active Inference network view of a blanket.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> net = build_blanket_network(graph, blanket)
        >>> isinstance(net, BlanketNetwork)
        True
        >>> "graph LR" in net.to_mermaid()
        True
    """

    role_counts: dict[str, int]
    """Number of concrete nodes per role (``internal``, ``sensory``, …)."""

    role_members: dict[str, list[str]]
    """Node ids per role, sorted."""

    aggregate_edges: dict[tuple[str, str], int]
    """Dict of ``(from_role, to_role) → edge count``."""

    edge_kind_breakdown: dict[tuple[str, str], dict[str, int]]
    """Same shape as ``aggregate_edges`` but bucketed by ``EdgeKind``."""

    metadata: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        """Serialize the network as a JSON-friendly dictionary."""
        return {
            "role_counts": dict(self.role_counts),
            "role_members": {k: list(v) for k, v in self.role_members.items()},
            "aggregate_edges": [
                {"from": a, "to": b, "count": c}
                for (a, b), c in sorted(self.aggregate_edges.items())
            ],
            "edge_kind_breakdown": [
                {"from": a, "to": b, "kinds": dict(sorted(d.items()))}
                for (a, b), d in sorted(self.edge_kind_breakdown.items())
            ],
            "metadata": dict(self.metadata),
        }

    def to_mermaid(self) -> str:
        """Render the collapsed view as a Mermaid ``graph LR`` block.

        The four roles are drawn with bracketed labels summarising the
        node count in that role. Aggregate edges are labelled with the
        number of underlying concrete edges.
        """
        lines = ["graph LR"]
        label = {
            "internal": f"μ internal [{self.role_counts.get('internal', 0)}]",
            "sensory": f"s sensory [{self.role_counts.get('sensory', 0)}]",
            "active": f"a active [{self.role_counts.get('active', 0)}]",
            "external": f"η external [{self.role_counts.get('external', 0)}]",
        }
        for key, text in label.items():
            lines.append(f'    {key}["{text}"]')
        for (src, dst), count in sorted(self.aggregate_edges.items()):
            if count > 0:
                lines.append(f"    {src} -->|{count}| {dst}")
        return "\n".join(lines)

aggregate_edges instance-attribute

Dict of (from_role, to_role) → edge count.

edge_kind_breakdown instance-attribute

Same shape as aggregate_edges but bucketed by EdgeKind.

role_counts instance-attribute

Number of concrete nodes per role (internal, sensory, …).

role_members instance-attribute

Node ids per role, sorted.

to_dict()

Serialize the network as a JSON-friendly dictionary.

Source code in py/cogant/markov/network.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def to_dict(self) -> dict[str, Any]:
    """Serialize the network as a JSON-friendly dictionary."""
    return {
        "role_counts": dict(self.role_counts),
        "role_members": {k: list(v) for k, v in self.role_members.items()},
        "aggregate_edges": [
            {"from": a, "to": b, "count": c}
            for (a, b), c in sorted(self.aggregate_edges.items())
        ],
        "edge_kind_breakdown": [
            {"from": a, "to": b, "kinds": dict(sorted(d.items()))}
            for (a, b), d in sorted(self.edge_kind_breakdown.items())
        ],
        "metadata": dict(self.metadata),
    }

to_mermaid()

Render the collapsed view as a Mermaid graph LR block.

The four roles are drawn with bracketed labels summarising the node count in that role. Aggregate edges are labelled with the number of underlying concrete edges.

Source code in py/cogant/markov/network.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def to_mermaid(self) -> str:
    """Render the collapsed view as a Mermaid ``graph LR`` block.

    The four roles are drawn with bracketed labels summarising the
    node count in that role. Aggregate edges are labelled with the
    number of underlying concrete edges.
    """
    lines = ["graph LR"]
    label = {
        "internal": f"μ internal [{self.role_counts.get('internal', 0)}]",
        "sensory": f"s sensory [{self.role_counts.get('sensory', 0)}]",
        "active": f"a active [{self.role_counts.get('active', 0)}]",
        "external": f"η external [{self.role_counts.get('external', 0)}]",
    }
    for key, text in label.items():
        lines.append(f'    {key}["{text}"]')
    for (src, dst), count in sorted(self.aggregate_edges.items()):
        if count > 0:
            lines.append(f"    {src} -->|{count}| {dst}")
    return "\n".join(lines)

BlanketRole

Bases: StrEnum

Active Inference role of a node within a Markov blanket.

Source code in py/cogant/markov/blanket.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class BlanketRole(StrEnum):
    """Active Inference role of a node within a Markov blanket."""

    INTERNAL = "internal"
    """μ — inside the system of interest with no external adjacency."""

    SENSORY = "sensory"
    """s — boundary node with incoming edges from external states."""

    ACTIVE = "active"
    """a — boundary node with outgoing edges to external states."""

    EXTERNAL = "external"
    """η — outside the system of interest."""

ACTIVE = 'active' class-attribute instance-attribute

a — boundary node with outgoing edges to external states.

EXTERNAL = 'external' class-attribute instance-attribute

η — outside the system of interest.

INTERNAL = 'internal' class-attribute instance-attribute

μ — inside the system of interest with no external adjacency.

SENSORY = 'sensory' class-attribute instance-attribute

s — boundary node with incoming edges from external states.

MarkovBlanket dataclass

Active-Inference Markov blanket partition of a program graph.

Instances are usually produced by :meth:MarkovBlanketExtractor.extract or by the low-level :func:partition_by_seeds helper. The dataclass is intentionally serialization-friendly: serialize_blanket returns a dictionary suitable for JSON, parquet, or YAML output.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=set()) isinstance(blanket, MarkovBlanket) True blanket.boundary_ids set()

Attributes:

Name Type Description
roles dict[str, BlanketRole]

Mapping of node id → :class:BlanketRole.

seeds set[str]

The seed set supplied to the partitioner.

internal_ids set[str]

Convenience accessor for μ nodes.

sensory_ids set[str]

Convenience accessor for s nodes.

active_ids set[str]

Convenience accessor for a nodes.

external_ids set[str]

Convenience accessor for η nodes.

boundary_ids set[str]

Union of sensory and active (the blanket B).

rationale dict[str, str]

Per-node short string explaining why the role was assigned (e.g. "internal; neighbours all in seed set"). Populated by :func:partition_by_seeds.

stats dict[str, Any]

Counts and coverage ratios, convenient for reports.

metadata dict[str, Any]

Free-form extra information (strategy used, seed heuristic, graph hash, etc.).

Source code in py/cogant/markov/blanket.py
 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@dataclass
class MarkovBlanket:
    """Active-Inference Markov blanket partition of a program graph.

    Instances are usually produced by
    :meth:`MarkovBlanketExtractor.extract` or by the low-level
    :func:`partition_by_seeds` helper. The dataclass is intentionally
    serialization-friendly: ``serialize_blanket`` returns a dictionary
    suitable for JSON, parquet, or YAML output.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=set())
        >>> isinstance(blanket, MarkovBlanket)
        True
        >>> blanket.boundary_ids
        set()

    Attributes:
        roles: Mapping of node id → :class:`BlanketRole`.
        seeds: The seed set supplied to the partitioner.
        internal_ids: Convenience accessor for μ nodes.
        sensory_ids: Convenience accessor for s nodes.
        active_ids: Convenience accessor for a nodes.
        external_ids: Convenience accessor for η nodes.
        boundary_ids: Union of sensory and active (the blanket B).
        rationale: Per-node short string explaining *why* the role was
            assigned (e.g. ``"internal; neighbours all in seed set"``).
            Populated by :func:`partition_by_seeds`.
        stats: Counts and coverage ratios, convenient for reports.
        metadata: Free-form extra information (strategy used, seed
            heuristic, graph hash, etc.).
    """

    roles: dict[str, BlanketRole]
    seeds: set[str]
    internal_ids: set[str] = field(default_factory=set)
    sensory_ids: set[str] = field(default_factory=set)
    active_ids: set[str] = field(default_factory=set)
    external_ids: set[str] = field(default_factory=set)
    rationale: dict[str, str] = field(default_factory=dict)
    stats: dict[str, Any] = field(default_factory=dict)
    metadata: dict[str, Any] = field(default_factory=dict)

    @property
    def boundary_ids(self) -> set[str]:
        """Union of sensory and active nodes — the Markov blanket B."""
        return self.sensory_ids | self.active_ids

    def role_of(self, node_id: str) -> BlanketRole:
        """Return the role of ``node_id``, defaulting to EXTERNAL."""
        return self.roles.get(node_id, BlanketRole.EXTERNAL)

    def ids_by_role(self, role: BlanketRole) -> set[str]:
        """Return the set of node ids that carry a given role."""
        if role is BlanketRole.INTERNAL:
            return self.internal_ids
        if role is BlanketRole.SENSORY:
            return self.sensory_ids
        if role is BlanketRole.ACTIVE:
            return self.active_ids
        return self.external_ids

    def get_sensory_states(self) -> list[str]:
        """Return all sensory boundary states (information flowing IN).

        Returns:
            Sorted list of sensory node ids.

        Example:
            >>> sensory = blanket.get_sensory_states()
            >>> print(f"{len(sensory)} sensory nodes")
        """
        return sorted(self.sensory_ids)

    def get_active_states(self) -> list[str]:
        """Return all active boundary states (information flowing OUT).

        Returns:
            Sorted list of active node ids.

        Example:
            >>> active = blanket.get_active_states()
            >>> print(f"{len(active)} active nodes")
        """
        return sorted(self.active_ids)

    def visualize(self) -> dict[str, Any]:
        """Export a visualization-friendly dictionary of the partition.

        Returns:
            Dictionary with keys:

            * ``internal``: List of internal node ids.
            * ``sensory``: List of sensory boundary node ids.
            * ``active``: List of active boundary node ids.
            * ``external``: List of external node ids.
            * ``edges``: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.

        Example:
            >>> vis = blanket.visualize()
            >>> print(f"{len(vis['internal'])} internal nodes")
        """
        return {
            "internal": sorted(self.internal_ids),
            "sensory": sorted(self.sensory_ids),
            "active": sorted(self.active_ids),
            "external": sorted(self.external_ids),
            "edges": [],  # Reserved field; full edge list would require graph
        }

    def validate(self) -> list[str]:
        """Validate partition consistency.

        Checks:
        * All nodes appear exactly once across all role sets.
        * No overlap between role sets.
        * Seeds are a subset of internal + boundary nodes.

        Returns:
            List of validation issue strings (empty if all checks pass).

        Example:
            >>> issues = blanket.validate()
            >>> if issues:
            ...     for issue in issues:
            ...         print(f"Error: {issue}")
        """
        issues: list[str] = []

        all_ids = self.internal_ids | self.sensory_ids | self.active_ids | self.external_ids

        # Check roles are in dict
        role_nodes = set(self.roles.keys())
        if role_nodes != all_ids:
            issues.append(f"Role dict size {len(role_nodes)} doesn't match union {len(all_ids)}")

        # Check for overlaps
        pairs = [
            (self.internal_ids, self.sensory_ids, "internal/sensory"),
            (self.internal_ids, self.active_ids, "internal/active"),
            (self.internal_ids, self.external_ids, "internal/external"),
            (self.sensory_ids, self.active_ids, "sensory/active"),
            (self.sensory_ids, self.external_ids, "sensory/external"),
            (self.active_ids, self.external_ids, "active/external"),
        ]
        for s1, s2, name in pairs:
            if s1 & s2:
                issues.append(f"Overlap between {name}: {len(s1 & s2)} nodes")

        # Check seeds are within system
        system_ids = self.internal_ids | self.sensory_ids | self.active_ids
        if not self.seeds.issubset(system_ids):
            external_seeds = self.seeds - system_ids
            issues.append(f"{len(external_seeds)} seed(s) are external: {external_seeds}")

        return issues

    def to_mermaid(self) -> str:
        """Export the Markov blanket partition as a Mermaid diagram.

        Returns:
            String containing valid Mermaid graph syntax.

        Example:
            >>> blanket = partition_by_seeds(graph, seeds=[...])
            >>> diagram = blanket.to_mermaid()
            >>> print(diagram)
            graph LR
                subgraph Internal
                    ...
        """
        lines = ["graph LR"]

        # Define subgraphs for each role
        if self.internal_ids:
            lines.append("    subgraph internal [Internal (μ)]")
            for node_id in sorted(self.internal_ids)[:5]:  # Limit for readability
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.sensory_ids:
            lines.append("    subgraph sensory [Sensory (s)]")
            for node_id in sorted(self.sensory_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.active_ids:
            lines.append("    subgraph active [Active (a)]")
            for node_id in sorted(self.active_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.external_ids:
            lines.append("    subgraph external [External (η)]")
            for node_id in sorted(self.external_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        return "\n".join(lines)

    def merge(self, other: MarkovBlanket) -> MarkovBlanket:
        """Merge two Markov blanket partitions.

        Combines the seed sets (union) and recomputes partition boundaries
        by taking the union of internal/sensory/active/external nodes.

        Args:
            other: Another MarkovBlanket to merge with this one.

        Returns:
            A new MarkovBlanket with merged partitions.

        Example:
            >>> b1 = partition_by_seeds(graph, seeds=[n1])
            >>> b2 = partition_by_seeds(graph, seeds=[n2])
            >>> merged = b1.merge(b2)
        """
        merged_seeds = self.seeds | other.seeds

        return MarkovBlanket(
            roles={**self.roles, **other.roles},
            seeds=merged_seeds,
            internal_ids=self.internal_ids | other.internal_ids,
            sensory_ids=self.sensory_ids | other.sensory_ids,
            active_ids=self.active_ids | other.active_ids,
            external_ids=self.external_ids | other.external_ids,
            rationale={**self.rationale, **other.rationale},
            stats={**self.stats, **other.stats},
            metadata={**self.metadata, **other.metadata},
        )

    def blanket_summary(self) -> dict[str, Any]:
        """Return a summary of blanket node counts and key statistics.

        Returns:
            Dictionary with keys:
            * ``n_internal``, ``n_sensory``, ``n_active``, ``n_external``: Counts.
            * ``blanket_size``: Size of boundary (sensory + active).
            * ``system_size``: Total system size (internal + boundary).
            * ``key_nodes``: List of prominent node ids (up to 5).

        Example:
            >>> summary = blanket.blanket_summary()
            >>> print(f"System size: {summary['system_size']}")
        """
        internal_list = sorted(self.internal_ids)
        boundary_list = sorted(self.sensory_ids | self.active_ids)
        key_nodes = (internal_list[:2] + boundary_list[:3])[:5]

        return {
            "n_internal": len(self.internal_ids),
            "n_sensory": len(self.sensory_ids),
            "n_active": len(self.active_ids),
            "n_external": len(self.external_ids),
            "blanket_size": len(self.sensory_ids) + len(self.active_ids),
            "system_size": len(self.internal_ids) + len(self.sensory_ids) + len(self.active_ids),
            "key_nodes": key_nodes,
        }

boundary_ids property

Union of sensory and active nodes — the Markov blanket B.

blanket_summary()

Return a summary of blanket node counts and key statistics.

Returns:

Type Description
dict[str, Any]

Dictionary with keys:

dict[str, Any]
  • n_internal, n_sensory, n_active, n_external: Counts.
dict[str, Any]
  • blanket_size: Size of boundary (sensory + active).
dict[str, Any]
  • system_size: Total system size (internal + boundary).
dict[str, Any]
  • key_nodes: List of prominent node ids (up to 5).
Example

summary = blanket.blanket_summary() print(f"System size: {summary['system_size']}")

Source code in py/cogant/markov/blanket.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def blanket_summary(self) -> dict[str, Any]:
    """Return a summary of blanket node counts and key statistics.

    Returns:
        Dictionary with keys:
        * ``n_internal``, ``n_sensory``, ``n_active``, ``n_external``: Counts.
        * ``blanket_size``: Size of boundary (sensory + active).
        * ``system_size``: Total system size (internal + boundary).
        * ``key_nodes``: List of prominent node ids (up to 5).

    Example:
        >>> summary = blanket.blanket_summary()
        >>> print(f"System size: {summary['system_size']}")
    """
    internal_list = sorted(self.internal_ids)
    boundary_list = sorted(self.sensory_ids | self.active_ids)
    key_nodes = (internal_list[:2] + boundary_list[:3])[:5]

    return {
        "n_internal": len(self.internal_ids),
        "n_sensory": len(self.sensory_ids),
        "n_active": len(self.active_ids),
        "n_external": len(self.external_ids),
        "blanket_size": len(self.sensory_ids) + len(self.active_ids),
        "system_size": len(self.internal_ids) + len(self.sensory_ids) + len(self.active_ids),
        "key_nodes": key_nodes,
    }

get_active_states()

Return all active boundary states (information flowing OUT).

Returns:

Type Description
list[str]

Sorted list of active node ids.

Example

active = blanket.get_active_states() print(f"{len(active)} active nodes")

Source code in py/cogant/markov/blanket.py
143
144
145
146
147
148
149
150
151
152
153
def get_active_states(self) -> list[str]:
    """Return all active boundary states (information flowing OUT).

    Returns:
        Sorted list of active node ids.

    Example:
        >>> active = blanket.get_active_states()
        >>> print(f"{len(active)} active nodes")
    """
    return sorted(self.active_ids)

get_sensory_states()

Return all sensory boundary states (information flowing IN).

Returns:

Type Description
list[str]

Sorted list of sensory node ids.

Example

sensory = blanket.get_sensory_states() print(f"{len(sensory)} sensory nodes")

Source code in py/cogant/markov/blanket.py
131
132
133
134
135
136
137
138
139
140
141
def get_sensory_states(self) -> list[str]:
    """Return all sensory boundary states (information flowing IN).

    Returns:
        Sorted list of sensory node ids.

    Example:
        >>> sensory = blanket.get_sensory_states()
        >>> print(f"{len(sensory)} sensory nodes")
    """
    return sorted(self.sensory_ids)

ids_by_role(role)

Return the set of node ids that carry a given role.

Source code in py/cogant/markov/blanket.py
121
122
123
124
125
126
127
128
129
def ids_by_role(self, role: BlanketRole) -> set[str]:
    """Return the set of node ids that carry a given role."""
    if role is BlanketRole.INTERNAL:
        return self.internal_ids
    if role is BlanketRole.SENSORY:
        return self.sensory_ids
    if role is BlanketRole.ACTIVE:
        return self.active_ids
    return self.external_ids

merge(other)

Merge two Markov blanket partitions.

Combines the seed sets (union) and recomputes partition boundaries by taking the union of internal/sensory/active/external nodes.

Parameters:

Name Type Description Default
other MarkovBlanket

Another MarkovBlanket to merge with this one.

required

Returns:

Type Description
MarkovBlanket

A new MarkovBlanket with merged partitions.

Example

b1 = partition_by_seeds(graph, seeds=[n1]) b2 = partition_by_seeds(graph, seeds=[n2]) merged = b1.merge(b2)

Source code in py/cogant/markov/blanket.py
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
def merge(self, other: MarkovBlanket) -> MarkovBlanket:
    """Merge two Markov blanket partitions.

    Combines the seed sets (union) and recomputes partition boundaries
    by taking the union of internal/sensory/active/external nodes.

    Args:
        other: Another MarkovBlanket to merge with this one.

    Returns:
        A new MarkovBlanket with merged partitions.

    Example:
        >>> b1 = partition_by_seeds(graph, seeds=[n1])
        >>> b2 = partition_by_seeds(graph, seeds=[n2])
        >>> merged = b1.merge(b2)
    """
    merged_seeds = self.seeds | other.seeds

    return MarkovBlanket(
        roles={**self.roles, **other.roles},
        seeds=merged_seeds,
        internal_ids=self.internal_ids | other.internal_ids,
        sensory_ids=self.sensory_ids | other.sensory_ids,
        active_ids=self.active_ids | other.active_ids,
        external_ids=self.external_ids | other.external_ids,
        rationale={**self.rationale, **other.rationale},
        stats={**self.stats, **other.stats},
        metadata={**self.metadata, **other.metadata},
    )

role_of(node_id)

Return the role of node_id, defaulting to EXTERNAL.

Source code in py/cogant/markov/blanket.py
117
118
119
def role_of(self, node_id: str) -> BlanketRole:
    """Return the role of ``node_id``, defaulting to EXTERNAL."""
    return self.roles.get(node_id, BlanketRole.EXTERNAL)

to_mermaid()

Export the Markov blanket partition as a Mermaid diagram.

Returns:

Type Description
str

String containing valid Mermaid graph syntax.

Example

blanket = partition_by_seeds(graph, seeds=[...]) diagram = blanket.to_mermaid() print(diagram) graph LR subgraph Internal ...

Source code in py/cogant/markov/blanket.py
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
def to_mermaid(self) -> str:
    """Export the Markov blanket partition as a Mermaid diagram.

    Returns:
        String containing valid Mermaid graph syntax.

    Example:
        >>> blanket = partition_by_seeds(graph, seeds=[...])
        >>> diagram = blanket.to_mermaid()
        >>> print(diagram)
        graph LR
            subgraph Internal
                ...
    """
    lines = ["graph LR"]

    # Define subgraphs for each role
    if self.internal_ids:
        lines.append("    subgraph internal [Internal (μ)]")
        for node_id in sorted(self.internal_ids)[:5]:  # Limit for readability
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.sensory_ids:
        lines.append("    subgraph sensory [Sensory (s)]")
        for node_id in sorted(self.sensory_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.active_ids:
        lines.append("    subgraph active [Active (a)]")
        for node_id in sorted(self.active_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.external_ids:
        lines.append("    subgraph external [External (η)]")
        for node_id in sorted(self.external_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    return "\n".join(lines)

validate()

Validate partition consistency.

Checks: * All nodes appear exactly once across all role sets. * No overlap between role sets. * Seeds are a subset of internal + boundary nodes.

Returns:

Type Description
list[str]

List of validation issue strings (empty if all checks pass).

Example

issues = blanket.validate() if issues: ... for issue in issues: ... print(f"Error: {issue}")

Source code in py/cogant/markov/blanket.py
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
def validate(self) -> list[str]:
    """Validate partition consistency.

    Checks:
    * All nodes appear exactly once across all role sets.
    * No overlap between role sets.
    * Seeds are a subset of internal + boundary nodes.

    Returns:
        List of validation issue strings (empty if all checks pass).

    Example:
        >>> issues = blanket.validate()
        >>> if issues:
        ...     for issue in issues:
        ...         print(f"Error: {issue}")
    """
    issues: list[str] = []

    all_ids = self.internal_ids | self.sensory_ids | self.active_ids | self.external_ids

    # Check roles are in dict
    role_nodes = set(self.roles.keys())
    if role_nodes != all_ids:
        issues.append(f"Role dict size {len(role_nodes)} doesn't match union {len(all_ids)}")

    # Check for overlaps
    pairs = [
        (self.internal_ids, self.sensory_ids, "internal/sensory"),
        (self.internal_ids, self.active_ids, "internal/active"),
        (self.internal_ids, self.external_ids, "internal/external"),
        (self.sensory_ids, self.active_ids, "sensory/active"),
        (self.sensory_ids, self.external_ids, "sensory/external"),
        (self.active_ids, self.external_ids, "active/external"),
    ]
    for s1, s2, name in pairs:
        if s1 & s2:
            issues.append(f"Overlap between {name}: {len(s1 & s2)} nodes")

    # Check seeds are within system
    system_ids = self.internal_ids | self.sensory_ids | self.active_ids
    if not self.seeds.issubset(system_ids):
        external_seeds = self.seeds - system_ids
        issues.append(f"{len(external_seeds)} seed(s) are external: {external_seeds}")

    return issues

visualize()

Export a visualization-friendly dictionary of the partition.

Returns:

Type Description
dict[str, Any]

Dictionary with keys:

dict[str, Any]
  • internal: List of internal node ids.
dict[str, Any]
  • sensory: List of sensory boundary node ids.
dict[str, Any]
  • active: List of active boundary node ids.
dict[str, Any]
  • external: List of external node ids.
dict[str, Any]
  • edges: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.
Example

vis = blanket.visualize() print(f"{len(vis['internal'])} internal nodes")

Source code in py/cogant/markov/blanket.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def visualize(self) -> dict[str, Any]:
    """Export a visualization-friendly dictionary of the partition.

    Returns:
        Dictionary with keys:

        * ``internal``: List of internal node ids.
        * ``sensory``: List of sensory boundary node ids.
        * ``active``: List of active boundary node ids.
        * ``external``: List of external node ids.
        * ``edges``: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.

    Example:
        >>> vis = blanket.visualize()
        >>> print(f"{len(vis['internal'])} internal nodes")
    """
    return {
        "internal": sorted(self.internal_ids),
        "sensory": sorted(self.sensory_ids),
        "active": sorted(self.active_ids),
        "external": sorted(self.external_ids),
        "edges": [],  # Reserved field; full edge list would require graph
    }

MarkovBlanketExtractor

Build Markov blankets from program graphs.

The extractor is stateless beyond a reference to the source graph and a handful of default knobs. Invoke :meth:extract with the desired strategy and parameters and it returns a :class:MarkovBlanket ready to feed into the GNN bundle.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph to partition.

required
prefer_boundary int

When set, a node marked as boundary AND present in at least prefer_boundary mapping kinds will be recorded in the resulting blanket's metadata.

1
Source code in py/cogant/markov/extractor.py
 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
308
309
310
311
312
313
314
315
316
317
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
class MarkovBlanketExtractor:
    """Build Markov blankets from program graphs.

    The extractor is stateless beyond a reference to the source graph
    and a handful of default knobs. Invoke :meth:`extract` with the
    desired strategy and parameters and it returns a
    :class:`MarkovBlanket` ready to feed into the GNN bundle.

    Args:
        graph: The program graph to partition.
        prefer_boundary: When set, a node marked as boundary AND
            present in at least ``prefer_boundary`` mapping kinds will
            be recorded in the resulting blanket's ``metadata``.
    """

    def __init__(self, graph: ProgramGraph, *, prefer_boundary: int = 1):
        self.graph = graph
        self.prefer_boundary = prefer_boundary
        self._adjacency = _bidirectional_adjacency(graph)

    def extract(
        self,
        *,
        strategy: SeedStrategy = "auto",
        seeds: Iterable[str] | None = None,
        module_names: Sequence[str] | None = None,
        kinds: Sequence[NodeKind] | None = None,
        mapping_kinds: Sequence[str] | None = None,
        semantic_mappings: dict[str, Any] | None = None,
    ) -> MarkovBlanket:
        """Compute a Markov blanket.

        Args:
            strategy: Seed selection strategy. See module docstring.
            seeds: Explicit node ids (required when ``strategy="explicit"``).
            module_names: Module/package names to anchor on
                (``strategy="module"``).
            kinds: Node kinds to aggregate (``strategy="kind"``).
            mapping_kinds: Mapping-kind strings such as ``"hidden_state"``
                (``strategy="mapping_kind"``).
            semantic_mappings: Optional mapping dict from
                ``orchestration.run_translate`` (required when
                ``strategy="mapping_kind"``).

        Returns:
            A :class:`MarkovBlanket` with metadata recording the
            strategy and inputs that produced it.

        Example:
            >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
            >>> from cogant.markov.extractor import MarkovBlanketExtractor
            >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
            >>> extractor = MarkovBlanketExtractor(graph)
            >>> blanket = extractor.extract(strategy="auto")
            >>> blanket.metadata["strategy"]
            'auto'
        """
        if strategy == "explicit":
            if not seeds:
                raise ValueError("strategy='explicit' requires a non-empty seeds list")
            seed_set = set(seeds)

        elif strategy == "module":
            if not module_names:
                raise ValueError("strategy='module' requires module_names")
            seed_set = self._seeds_from_modules(module_names)

        elif strategy == "kind":
            if not kinds:
                raise ValueError("strategy='kind' requires kinds")
            seed_set = self._seeds_from_kinds(kinds)

        elif strategy == "mapping_kind":
            seed_set = self._seeds_from_mapping_kinds(
                semantic_mappings or {}, mapping_kinds or ["hidden_state"]
            )

        elif strategy == "auto":
            seed_set, auto_meta = self._seeds_auto()
        else:
            raise ValueError(f"Unknown strategy: {strategy!r}")

        logger.info(
            "Markov blanket extraction: strategy=%s, %d seeds from %d graph nodes",
            strategy,
            len(seed_set),
            len(self.graph.nodes),
        )

        blanket = partition_by_seeds(self.graph, seed_set, adjacency=self._adjacency)
        blanket.metadata["strategy"] = strategy
        blanket.metadata["requested_seed_count"] = len(list(seed_set))
        if strategy == "module":
            blanket.metadata["module_names"] = list(module_names or [])
        if strategy == "kind":
            blanket.metadata["kinds"] = [
                k.value if hasattr(k, "value") else str(k) for k in (kinds or [])
            ]
        if strategy == "mapping_kind":
            blanket.metadata["mapping_kinds"] = list(mapping_kinds or [])
        if strategy == "auto":
            blanket.metadata.update(auto_meta)

        logger.info(
            "Markov blanket partitioned: internal=%d, sensory=%d, active=%d, external=%d",
            blanket.stats.get("internal_count", 0),
            blanket.stats.get("sensory_count", 0),
            blanket.stats.get("active_count", 0),
            blanket.stats.get("external_count", 0),
        )
        return blanket

    # ---------------------- Seed strategy helpers ---------------------- #

    def _seeds_from_modules(self, module_names: Sequence[str]) -> set[str]:
        """Collect module nodes + everything they ``CONTAINS``-reach."""
        targets = {m.lower() for m in module_names}
        seeds: set[str] = set()
        module_nodes = self.graph.get_nodes_by_kind(NodeKind.MODULE)
        for node in module_nodes:
            name_match = (node.name or "").lower()
            qn_match = (node.qualified_name or "").lower()
            if any(t in name_match or t in qn_match for t in targets):
                seeds.add(node.id)
                seeds.update(self._descend_contains(node.id))
        return seeds

    def _descend_contains(self, root_id: str) -> set[str]:
        """Return the transitive CONTAINS-closure of ``root_id``."""
        collected: set[str] = set()
        frontier = [root_id]
        while frontier:
            cur = frontier.pop()
            for edge in self.graph.get_edges_from(cur):
                if edge.kind is EdgeKind.CONTAINS and edge.target_id not in collected:
                    collected.add(edge.target_id)
                    frontier.append(edge.target_id)
        return collected

    def _seeds_from_kinds(self, kinds: Sequence[NodeKind]) -> set[str]:
        seeds: set[str] = set()
        for kind in kinds:
            for node in self.graph.get_nodes_by_kind(kind):
                seeds.add(node.id)
        return seeds

    def _seeds_from_mapping_kinds(
        self,
        semantic_mappings: dict[str, Any],
        mapping_kinds: Sequence[str],
    ) -> set[str]:
        wanted = {mk.lower() for mk in mapping_kinds}
        seeds: set[str] = set()
        for mapping in semantic_mappings.values():
            kind_value = getattr(mapping, "kind", None)
            if kind_value is None:
                continue
            kv = kind_value.value if hasattr(kind_value, "value") else str(kind_value)
            if kv.lower() not in wanted:
                continue
            node_ids = getattr(mapping, "graph_fragment_node_ids", None) or []
            for nid in node_ids:
                if nid in self.graph.nodes:
                    seeds.add(nid)
        return seeds

    def _seeds_auto(self) -> tuple[set[str], dict[str, Any]]:
        """Pick the best cohesion/coupling seed set automatically.

        The heuristic has two tiers:

        1. **Module tier.** For every ``MODULE`` node we compute::

               cohesion  = edges inside the module's contains-closure
               coupling  = edges crossing the closure boundary
               score     = cohesion / (cohesion + coupling + 1)

           and take the argmax. Ties are broken by higher total node
           count so tiny helper modules do not win by accident.

        2. **Class tier fallback.** When there are no modules, or when
           the best module contains the entire graph (making the
           partition degenerate — every node is internal, the blanket
           is empty), we fall back to the largest ``CLASS`` node. Its
           :meth:`~cogant.markov.extractor.MarkovBlanketExtractor._descend_contains`
           closure becomes the seed set. If there are no classes
           either, we fall back to every ``CLASS`` node taken together.

        The returned metadata always records which tier was used, which
        candidate won, and the scoreboard for every module considered,
        so downstream reports can explain *why* this partition was
        selected.
        """
        total_nodes = len(self.graph.nodes)
        modules = self.graph.get_nodes_by_kind(NodeKind.MODULE)

        # Tier 2: no modules at all.
        if not modules:
            return self._auto_class_fallback(reason="no modules present")

        best_score = -1.0
        best_id: str | None = None
        best_size = 0
        scoreboard: list[dict[str, Any]] = []

        for module in modules:
            closure = {module.id} | self._descend_contains(module.id)
            cohesion = 0
            coupling = 0
            for nid in closure:
                for edge in self.graph.get_edges_from(nid):
                    if edge.target_id in closure:
                        cohesion += 1
                    else:
                        coupling += 1
                for edge in self.graph.get_edges_to(nid):
                    if edge.source_id not in closure:
                        coupling += 1
            score = cohesion / (cohesion + coupling + 1)
            scoreboard.append(
                {
                    "module_id": module.id,
                    "module_name": module.name or module.qualified_name,
                    "closure_size": len(closure),
                    "cohesion": cohesion,
                    "coupling": coupling,
                    "score": round(score, 4),
                }
            )
            if score > best_score or (score == best_score and len(closure) > best_size):
                best_score = score
                best_id = module.id
                best_size = len(closure)

        if best_id is None:
            return set(), {"auto_reason": "no candidate modules scored above 0"}

        # Tier 2: best module swallows the whole graph → degenerate
        # partition with no boundary. Fall back to a class-level seed.
        if best_size >= total_nodes:
            fallback = self._auto_class_fallback(
                reason="only module spans whole graph; fell back to class tier"
            )
            fallback_seeds, fallback_meta = fallback
            fallback_meta["module_scoreboard"] = scoreboard
            fallback_meta["fallback_from_module_id"] = best_id
            return fallback_seeds, fallback_meta

        seeds = {best_id} | self._descend_contains(best_id)
        meta = {
            "auto_reason": "argmax of cohesion/(cohesion+coupling+1) over modules",
            "auto_tier": "module",
            "chosen_module_id": best_id,
            "chosen_score": best_score,
            "chosen_closure_size": best_size,
            "candidate_modules": len(modules),
            "scoreboard": scoreboard,
        }
        logger.info(
            "Markov blanket auto-seed chose module %s (score=%.3f, nodes=%d)",
            best_id,
            best_score,
            best_size,
        )
        return seeds, meta

    def _auto_class_fallback(self, *, reason: str) -> tuple[set[str], dict[str, Any]]:
        """Pick the largest ``CLASS`` closure as the auto seed set.

        Chooses the class whose ``CONTAINS``-closure size is largest
        (ties broken by node id for determinism). If there are no
        classes, returns every class node — which, when the graph has
        none, yields an empty seed set and a degenerate (all-external)
        blanket; this is the correct honest answer for such a graph.
        """
        classes = self.graph.get_nodes_by_kind(NodeKind.CLASS)
        if not classes:
            return set(), {
                "auto_reason": f"{reason}; no classes to fall back to",
                "auto_tier": "empty",
                "candidate_classes": 0,
            }

        best_cls_id: str | None = None
        best_closure: set[str] = set()
        for cls in sorted(classes, key=lambda c: c.id):
            closure = {cls.id} | self._descend_contains(cls.id)
            if len(closure) > len(best_closure):
                best_cls_id = cls.id
                best_closure = closure

        if best_cls_id is None or len(best_closure) <= 1:
            # Classes exist but none have methods/members → aggregate all classes.
            seeds = {c.id for c in classes}
            return seeds, {
                "auto_reason": f"{reason}; no class has non-trivial closure, used all CLASS nodes",
                "auto_tier": "class_aggregate",
                "candidate_classes": len(classes),
            }

        return best_closure, {
            "auto_reason": reason,
            "auto_tier": "class",
            "chosen_class_id": best_cls_id,
            "chosen_closure_size": len(best_closure),
            "candidate_classes": len(classes),
        }

extract(*, strategy='auto', seeds=None, module_names=None, kinds=None, mapping_kinds=None, semantic_mappings=None)

Compute a Markov blanket.

Parameters:

Name Type Description Default
strategy SeedStrategy

Seed selection strategy. See module docstring.

'auto'
seeds Iterable[str] | None

Explicit node ids (required when strategy="explicit").

None
module_names Sequence[str] | None

Module/package names to anchor on (strategy="module").

None
kinds Sequence[NodeKind] | None

Node kinds to aggregate (strategy="kind").

None
mapping_kinds Sequence[str] | None

Mapping-kind strings such as "hidden_state" (strategy="mapping_kind").

None
semantic_mappings dict[str, Any] | None

Optional mapping dict from orchestration.run_translate (required when strategy="mapping_kind").

None

Returns:

Name Type Description
A MarkovBlanket

class:MarkovBlanket with metadata recording the

MarkovBlanket

strategy and inputs that produced it.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.extractor import MarkovBlanketExtractor graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) extractor = MarkovBlanketExtractor(graph) blanket = extractor.extract(strategy="auto") blanket.metadata["strategy"] 'auto'

Source code in py/cogant/markov/extractor.py
 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
def extract(
    self,
    *,
    strategy: SeedStrategy = "auto",
    seeds: Iterable[str] | None = None,
    module_names: Sequence[str] | None = None,
    kinds: Sequence[NodeKind] | None = None,
    mapping_kinds: Sequence[str] | None = None,
    semantic_mappings: dict[str, Any] | None = None,
) -> MarkovBlanket:
    """Compute a Markov blanket.

    Args:
        strategy: Seed selection strategy. See module docstring.
        seeds: Explicit node ids (required when ``strategy="explicit"``).
        module_names: Module/package names to anchor on
            (``strategy="module"``).
        kinds: Node kinds to aggregate (``strategy="kind"``).
        mapping_kinds: Mapping-kind strings such as ``"hidden_state"``
            (``strategy="mapping_kind"``).
        semantic_mappings: Optional mapping dict from
            ``orchestration.run_translate`` (required when
            ``strategy="mapping_kind"``).

    Returns:
        A :class:`MarkovBlanket` with metadata recording the
        strategy and inputs that produced it.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.extractor import MarkovBlanketExtractor
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> extractor = MarkovBlanketExtractor(graph)
        >>> blanket = extractor.extract(strategy="auto")
        >>> blanket.metadata["strategy"]
        'auto'
    """
    if strategy == "explicit":
        if not seeds:
            raise ValueError("strategy='explicit' requires a non-empty seeds list")
        seed_set = set(seeds)

    elif strategy == "module":
        if not module_names:
            raise ValueError("strategy='module' requires module_names")
        seed_set = self._seeds_from_modules(module_names)

    elif strategy == "kind":
        if not kinds:
            raise ValueError("strategy='kind' requires kinds")
        seed_set = self._seeds_from_kinds(kinds)

    elif strategy == "mapping_kind":
        seed_set = self._seeds_from_mapping_kinds(
            semantic_mappings or {}, mapping_kinds or ["hidden_state"]
        )

    elif strategy == "auto":
        seed_set, auto_meta = self._seeds_auto()
    else:
        raise ValueError(f"Unknown strategy: {strategy!r}")

    logger.info(
        "Markov blanket extraction: strategy=%s, %d seeds from %d graph nodes",
        strategy,
        len(seed_set),
        len(self.graph.nodes),
    )

    blanket = partition_by_seeds(self.graph, seed_set, adjacency=self._adjacency)
    blanket.metadata["strategy"] = strategy
    blanket.metadata["requested_seed_count"] = len(list(seed_set))
    if strategy == "module":
        blanket.metadata["module_names"] = list(module_names or [])
    if strategy == "kind":
        blanket.metadata["kinds"] = [
            k.value if hasattr(k, "value") else str(k) for k in (kinds or [])
        ]
    if strategy == "mapping_kind":
        blanket.metadata["mapping_kinds"] = list(mapping_kinds or [])
    if strategy == "auto":
        blanket.metadata.update(auto_meta)

    logger.info(
        "Markov blanket partitioned: internal=%d, sensory=%d, active=%d, external=%d",
        blanket.stats.get("internal_count", 0),
        blanket.stats.get("sensory_count", 0),
        blanket.stats.get("active_count", 0),
        blanket.stats.get("external_count", 0),
    )
    return blanket

build_blanket_network(graph, blanket)

Collapse graph into a four-role aggregate network.

Every concrete edge in graph is mapped to a pair (role_of_source, role_of_target) and counted. Edges are also bucketed by :class:EdgeKind so that downstream tooling can see, e.g., how many of the s→μ edges are READS vs CALLS.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph used to build blanket.

required
blanket MarkovBlanket

The Markov blanket partition.

required

Returns:

Name Type Description
A BlanketNetwork

class:BlanketNetwork summarising the collapsed view.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) network = build_blanket_network(graph, blanket) sorted(network.role_counts.keys()) ['active', 'external', 'internal', 'sensory']

Source code in py/cogant/markov/network.py
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
def build_blanket_network(graph: ProgramGraph, blanket: MarkovBlanket) -> BlanketNetwork:
    """Collapse ``graph`` into a four-role aggregate network.

    Every concrete edge in ``graph`` is mapped to a pair
    ``(role_of_source, role_of_target)`` and counted. Edges are also
    bucketed by :class:`EdgeKind` so that downstream tooling can see,
    e.g., how many of the s→μ edges are ``READS`` vs ``CALLS``.

    Args:
        graph: The program graph used to build ``blanket``.
        blanket: The Markov blanket partition.

    Returns:
        A :class:`BlanketNetwork` summarising the collapsed view.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> network = build_blanket_network(graph, blanket)
        >>> sorted(network.role_counts.keys())
        ['active', 'external', 'internal', 'sensory']
    """
    aggregate: dict[tuple[str, str], int] = defaultdict(int)
    kind_break: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: defaultdict(int))

    def _role_name(node_id: str) -> str:
        return blanket.role_of(node_id).value

    for edge in graph.edges.values():
        src_role = _role_name(edge.source_id)
        dst_role = _role_name(edge.target_id)
        key = (src_role, dst_role)
        aggregate[key] += 1
        kind_value = edge.kind.value if isinstance(edge.kind, EdgeKind) else str(edge.kind)
        kind_break[key][kind_value] += 1

    # Freeze inner defaultdicts so json.dumps doesn't serialize a factory.
    edge_kind_breakdown = {k: dict(v) for k, v in kind_break.items()}

    role_members = {
        BlanketRole.INTERNAL.value: sorted(blanket.internal_ids),
        BlanketRole.SENSORY.value: sorted(blanket.sensory_ids),
        BlanketRole.ACTIVE.value: sorted(blanket.active_ids),
        BlanketRole.EXTERNAL.value: sorted(blanket.external_ids),
    }
    role_counts = {k: len(v) for k, v in role_members.items()}

    network = BlanketNetwork(
        role_counts=role_counts,
        role_members=role_members,
        aggregate_edges=dict(aggregate),
        edge_kind_breakdown=edge_kind_breakdown,
        metadata={
            "edge_count": len(graph.edges),
            "node_count": len(graph.nodes),
            "seed_count": len(blanket.seeds),
        },
    )
    return network

partition_by_seeds(graph, seeds, *, adjacency=None)

Assign every node in graph a Markov blanket role.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph to partition.

required
seeds Iterable[str]

Iterable of node ids that define the "system of interest". Nodes NOT in this set are considered environmental.

required
adjacency Mapping[str, tuple[set[str], set[str]]] | None

Optional precomputed {id: (in_set, out_set)} map to avoid rebuilding if the caller already has one.

None

Returns:

Type Description
MarkovBlanket

A fully populated :class:MarkovBlanket. Every node id in the

MarkovBlanket

graph will appear exactly once across internal_ids,

MarkovBlanket

sensory_ids, active_ids, and external_ids.

The partitioning rule is purely topological:

.. code-block:: text

node ∈ seeds  and  all neighbours ∈ seeds         → INTERNAL
node ∈ seeds  and  ∃ external neighbour           → SENSORY/ACTIVE
node ∉ seeds                                       → EXTERNAL
Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) blanket.stats["total_nodes"] 0

Source code in py/cogant/markov/blanket.py
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def partition_by_seeds(
    graph: ProgramGraph,
    seeds: Iterable[str],
    *,
    adjacency: Mapping[str, tuple[set[str], set[str]]] | None = None,
) -> MarkovBlanket:
    """Assign every node in ``graph`` a Markov blanket role.

    Args:
        graph: The program graph to partition.
        seeds: Iterable of node ids that define the "system of interest".
            Nodes NOT in this set are considered environmental.
        adjacency: Optional precomputed ``{id: (in_set, out_set)}`` map
            to avoid rebuilding if the caller already has one.

    Returns:
        A fully populated :class:`MarkovBlanket`. Every node id in the
        graph will appear exactly once across ``internal_ids``,
        ``sensory_ids``, ``active_ids``, and ``external_ids``.

    The partitioning rule is purely topological:

    .. code-block:: text

        node ∈ seeds  and  all neighbours ∈ seeds         → INTERNAL
        node ∈ seeds  and  ∃ external neighbour           → SENSORY/ACTIVE
        node ∉ seeds                                       → EXTERNAL

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> blanket.stats["total_nodes"]
        0
    """
    seed_set: set[str] = {s for s in seeds if s in graph.nodes}

    if adjacency is None:
        adjacency = _bidirectional_adjacency(graph)

    roles: dict[str, BlanketRole] = {}
    rationale: dict[str, str] = {}
    internal: set[str] = set()
    sensory: set[str] = set()
    active: set[str] = set()
    external: set[str] = set()
    bidirectional: set[str] = set()
    external_neighbours: set[str] = set()

    for node_id in graph.nodes:
        in_neigh, out_neigh = adjacency[node_id]
        neigh = in_neigh | out_neigh

        if node_id in seed_set:
            ext_in = {n for n in in_neigh if n not in seed_set}
            ext_out = {n for n in out_neigh if n not in seed_set}

            if not (ext_in or ext_out):
                roles[node_id] = BlanketRole.INTERNAL
                rationale[node_id] = "internal: all neighbours inside seed set"
                internal.add(node_id)
                continue

            if ext_out and ext_in:
                roles[node_id] = BlanketRole.ACTIVE
                rationale[node_id] = "active (bidirectional): edges flow in and out of the system"
                active.add(node_id)
                bidirectional.add(node_id)
            elif ext_out:
                roles[node_id] = BlanketRole.ACTIVE
                rationale[node_id] = "active: writes/calls reach external states"
                active.add(node_id)
            else:
                roles[node_id] = BlanketRole.SENSORY
                rationale[node_id] = "sensory: reads/observes external states"
                sensory.add(node_id)
        else:
            roles[node_id] = BlanketRole.EXTERNAL
            if neigh & seed_set:
                rationale[node_id] = "external: immediate neighbour of the system"
                external_neighbours.add(node_id)
            else:
                rationale[node_id] = "external: no adjacency with the system"
            external.add(node_id)

    total = len(graph.nodes) or 1
    stats = {
        "total_nodes": len(graph.nodes),
        "seed_count": len(seed_set),
        "internal_count": len(internal),
        "sensory_count": len(sensory),
        "active_count": len(active),
        "external_count": len(external),
        "external_neighbour_count": len(external_neighbours),
        "bidirectional_count": len(bidirectional),
        "internal_ratio": round(len(internal) / total, 4),
        "boundary_ratio": round((len(sensory) + len(active)) / total, 4),
        "external_ratio": round(len(external) / total, 4),
    }

    blanket = MarkovBlanket(
        roles=roles,
        seeds=seed_set,
        internal_ids=internal,
        sensory_ids=sensory,
        active_ids=active,
        external_ids=external,
        rationale=rationale,
        stats=stats,
        metadata={
            "bidirectional_ids": sorted(bidirectional),
            "external_neighbour_ids": sorted(external_neighbours),
        },
    )
    return blanket

serialize_blanket(blanket, graph, *, include_rationale=True, max_nodes_per_role=None)

Convert a :class:MarkovBlanket into a JSON-friendly dictionary.

Parameters:

Name Type Description Default
blanket MarkovBlanket

The partition to serialize.

required
graph ProgramGraph

The graph used to produce the partition. Needed so that each node id can be enriched with its human-readable kind, name, and path for downstream reports.

required
include_rationale bool

Whether to include the per-node rationale string. Defaults to True; set False if the caller wants a more compact file.

True
max_nodes_per_role int | None

Optional cap on how many nodes to emit per role (useful for very large graphs). Capping is applied deterministically by sorting node ids first.

None

Returns:

Type Description
dict[str, Any]

A dict with the schema::

{ "schema_version": "1.0.0", "seeds": [...], "stats": {...}, "roles": { "internal": [{id, kind, name, path, rationale?}, ...], "sensory": [...], "active": [...], "external": [...], }, "metadata": {...} }

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) doc = serialize_blanket(blanket, graph) doc["schema_version"] '1.0.0' sorted(doc["roles"].keys()) ['active', 'external', 'internal', 'sensory']

Source code in py/cogant/markov/blanket.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def serialize_blanket(
    blanket: MarkovBlanket,
    graph: ProgramGraph,
    *,
    include_rationale: bool = True,
    max_nodes_per_role: int | None = None,
) -> dict[str, Any]:
    """Convert a :class:`MarkovBlanket` into a JSON-friendly dictionary.

    Args:
        blanket: The partition to serialize.
        graph: The graph used to produce the partition. Needed so that
            each node id can be enriched with its human-readable
            ``kind``, ``name``, and ``path`` for downstream reports.
        include_rationale: Whether to include the per-node rationale
            string. Defaults to ``True``; set ``False`` if the caller
            wants a more compact file.
        max_nodes_per_role: Optional cap on how many nodes to emit per
            role (useful for very large graphs). Capping is applied
            deterministically by sorting node ids first.

    Returns:
        A dict with the schema::

            {
              "schema_version": "1.0.0",
              "seeds": [...],
              "stats": {...},
              "roles": {
                  "internal": [{id, kind, name, path, rationale?}, ...],
                  "sensory":  [...],
                  "active":   [...],
                  "external": [...],
              },
              "metadata": {...}
            }

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> doc = serialize_blanket(blanket, graph)
        >>> doc["schema_version"]
        '1.0.0'
        >>> sorted(doc["roles"].keys())
        ['active', 'external', 'internal', 'sensory']
    """

    def _format(node_ids: Iterable[str]) -> list[dict[str, Any]]:
        ids = sorted(node_ids)
        if max_nodes_per_role is not None:
            ids = ids[:max_nodes_per_role]
        out: list[dict[str, Any]] = []
        for nid in ids:
            node = graph.get_node(nid)
            record: dict[str, Any] = {
                "id": nid,
                "kind": _node_kind_value(node) if node else None,
                "name": node.name if node else None,
                "path": node.path if node else None,
            }
            if include_rationale and nid in blanket.rationale:
                record["rationale"] = blanket.rationale[nid]
            out.append(record)
        return out

    return {
        "schema_version": "1.0.0",
        "seeds": sorted(blanket.seeds),
        "stats": dict(blanket.stats),
        "roles": {
            BlanketRole.INTERNAL.value: _format(blanket.internal_ids),
            BlanketRole.SENSORY.value: _format(blanket.sensory_ids),
            BlanketRole.ACTIVE.value: _format(blanket.active_ids),
            BlanketRole.EXTERNAL.value: _format(blanket.external_ids),
        },
        "metadata": dict(blanket.metadata),
    }

Blanket

The pure-function partitioner. partition_by_seeds is deterministic for a given graph and seed set.

cogant.markov.blanket

Markov blanket data model and partitioning primitive.

This module defines the :class:MarkovBlanket dataclass and a pure-function partitioning primitive, :func:partition_by_seeds, that assigns every node of a :class:~cogant.schemas.graph.ProgramGraph to exactly one Active Inference role: INTERNAL, SENSORY, ACTIVE, or EXTERNAL.

The implementation is deliberately graph-theoretic rather than heuristic: given a seed set S (the "system of interest"), every non-seed node is labelled by looking at its bidirectional adjacency with S. No language- or domain-specific knowledge is required, so the primitive can be re-used for any repo translated by COGANT.

Partitioning rules (applied to the undirected projection of the graph):

  • A node n ∈ S with no edge leaving S is internal (μ). Its only neighbours are other internal or boundary nodes in S.
  • A node n ∈ S with at least one neighbour outside S is a boundary node. We further split boundary nodes into sensory and active based on directed edge flow:
    • sensory — there exists a directed edge from an external node into n (information flowing IN).
    • active — there exists a directed edge from n to an external node (information flowing OUT).
    • A node that both reads and writes across the boundary is tagged as active by default (because it has causal influence outward) and reported as bidirectional in metadata.
  • A node n ∉ S with at least one neighbour in S is part of the immediate external neighbourhood (external with neighbour metadata flag).
  • All other nodes are external with no special flag.

The result is a complete, mutually-exclusive partition of the graph, which is exactly what is required to populate the Markov blanket section of the GNN export bundle. The function is deterministic: given the same graph and seed set, it always produces the same partition.

BlanketRole

Bases: StrEnum

Active Inference role of a node within a Markov blanket.

Source code in py/cogant/markov/blanket.py
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class BlanketRole(StrEnum):
    """Active Inference role of a node within a Markov blanket."""

    INTERNAL = "internal"
    """μ — inside the system of interest with no external adjacency."""

    SENSORY = "sensory"
    """s — boundary node with incoming edges from external states."""

    ACTIVE = "active"
    """a — boundary node with outgoing edges to external states."""

    EXTERNAL = "external"
    """η — outside the system of interest."""

ACTIVE = 'active' class-attribute instance-attribute

a — boundary node with outgoing edges to external states.

EXTERNAL = 'external' class-attribute instance-attribute

η — outside the system of interest.

INTERNAL = 'internal' class-attribute instance-attribute

μ — inside the system of interest with no external adjacency.

SENSORY = 'sensory' class-attribute instance-attribute

s — boundary node with incoming edges from external states.

MarkovBlanket dataclass

Active-Inference Markov blanket partition of a program graph.

Instances are usually produced by :meth:MarkovBlanketExtractor.extract or by the low-level :func:partition_by_seeds helper. The dataclass is intentionally serialization-friendly: serialize_blanket returns a dictionary suitable for JSON, parquet, or YAML output.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=set()) isinstance(blanket, MarkovBlanket) True blanket.boundary_ids set()

Attributes:

Name Type Description
roles dict[str, BlanketRole]

Mapping of node id → :class:BlanketRole.

seeds set[str]

The seed set supplied to the partitioner.

internal_ids set[str]

Convenience accessor for μ nodes.

sensory_ids set[str]

Convenience accessor for s nodes.

active_ids set[str]

Convenience accessor for a nodes.

external_ids set[str]

Convenience accessor for η nodes.

boundary_ids set[str]

Union of sensory and active (the blanket B).

rationale dict[str, str]

Per-node short string explaining why the role was assigned (e.g. "internal; neighbours all in seed set"). Populated by :func:partition_by_seeds.

stats dict[str, Any]

Counts and coverage ratios, convenient for reports.

metadata dict[str, Any]

Free-form extra information (strategy used, seed heuristic, graph hash, etc.).

Source code in py/cogant/markov/blanket.py
 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
@dataclass
class MarkovBlanket:
    """Active-Inference Markov blanket partition of a program graph.

    Instances are usually produced by
    :meth:`MarkovBlanketExtractor.extract` or by the low-level
    :func:`partition_by_seeds` helper. The dataclass is intentionally
    serialization-friendly: ``serialize_blanket`` returns a dictionary
    suitable for JSON, parquet, or YAML output.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=set())
        >>> isinstance(blanket, MarkovBlanket)
        True
        >>> blanket.boundary_ids
        set()

    Attributes:
        roles: Mapping of node id → :class:`BlanketRole`.
        seeds: The seed set supplied to the partitioner.
        internal_ids: Convenience accessor for μ nodes.
        sensory_ids: Convenience accessor for s nodes.
        active_ids: Convenience accessor for a nodes.
        external_ids: Convenience accessor for η nodes.
        boundary_ids: Union of sensory and active (the blanket B).
        rationale: Per-node short string explaining *why* the role was
            assigned (e.g. ``"internal; neighbours all in seed set"``).
            Populated by :func:`partition_by_seeds`.
        stats: Counts and coverage ratios, convenient for reports.
        metadata: Free-form extra information (strategy used, seed
            heuristic, graph hash, etc.).
    """

    roles: dict[str, BlanketRole]
    seeds: set[str]
    internal_ids: set[str] = field(default_factory=set)
    sensory_ids: set[str] = field(default_factory=set)
    active_ids: set[str] = field(default_factory=set)
    external_ids: set[str] = field(default_factory=set)
    rationale: dict[str, str] = field(default_factory=dict)
    stats: dict[str, Any] = field(default_factory=dict)
    metadata: dict[str, Any] = field(default_factory=dict)

    @property
    def boundary_ids(self) -> set[str]:
        """Union of sensory and active nodes — the Markov blanket B."""
        return self.sensory_ids | self.active_ids

    def role_of(self, node_id: str) -> BlanketRole:
        """Return the role of ``node_id``, defaulting to EXTERNAL."""
        return self.roles.get(node_id, BlanketRole.EXTERNAL)

    def ids_by_role(self, role: BlanketRole) -> set[str]:
        """Return the set of node ids that carry a given role."""
        if role is BlanketRole.INTERNAL:
            return self.internal_ids
        if role is BlanketRole.SENSORY:
            return self.sensory_ids
        if role is BlanketRole.ACTIVE:
            return self.active_ids
        return self.external_ids

    def get_sensory_states(self) -> list[str]:
        """Return all sensory boundary states (information flowing IN).

        Returns:
            Sorted list of sensory node ids.

        Example:
            >>> sensory = blanket.get_sensory_states()
            >>> print(f"{len(sensory)} sensory nodes")
        """
        return sorted(self.sensory_ids)

    def get_active_states(self) -> list[str]:
        """Return all active boundary states (information flowing OUT).

        Returns:
            Sorted list of active node ids.

        Example:
            >>> active = blanket.get_active_states()
            >>> print(f"{len(active)} active nodes")
        """
        return sorted(self.active_ids)

    def visualize(self) -> dict[str, Any]:
        """Export a visualization-friendly dictionary of the partition.

        Returns:
            Dictionary with keys:

            * ``internal``: List of internal node ids.
            * ``sensory``: List of sensory boundary node ids.
            * ``active``: List of active boundary node ids.
            * ``external``: List of external node ids.
            * ``edges``: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.

        Example:
            >>> vis = blanket.visualize()
            >>> print(f"{len(vis['internal'])} internal nodes")
        """
        return {
            "internal": sorted(self.internal_ids),
            "sensory": sorted(self.sensory_ids),
            "active": sorted(self.active_ids),
            "external": sorted(self.external_ids),
            "edges": [],  # Reserved field; full edge list would require graph
        }

    def validate(self) -> list[str]:
        """Validate partition consistency.

        Checks:
        * All nodes appear exactly once across all role sets.
        * No overlap between role sets.
        * Seeds are a subset of internal + boundary nodes.

        Returns:
            List of validation issue strings (empty if all checks pass).

        Example:
            >>> issues = blanket.validate()
            >>> if issues:
            ...     for issue in issues:
            ...         print(f"Error: {issue}")
        """
        issues: list[str] = []

        all_ids = self.internal_ids | self.sensory_ids | self.active_ids | self.external_ids

        # Check roles are in dict
        role_nodes = set(self.roles.keys())
        if role_nodes != all_ids:
            issues.append(f"Role dict size {len(role_nodes)} doesn't match union {len(all_ids)}")

        # Check for overlaps
        pairs = [
            (self.internal_ids, self.sensory_ids, "internal/sensory"),
            (self.internal_ids, self.active_ids, "internal/active"),
            (self.internal_ids, self.external_ids, "internal/external"),
            (self.sensory_ids, self.active_ids, "sensory/active"),
            (self.sensory_ids, self.external_ids, "sensory/external"),
            (self.active_ids, self.external_ids, "active/external"),
        ]
        for s1, s2, name in pairs:
            if s1 & s2:
                issues.append(f"Overlap between {name}: {len(s1 & s2)} nodes")

        # Check seeds are within system
        system_ids = self.internal_ids | self.sensory_ids | self.active_ids
        if not self.seeds.issubset(system_ids):
            external_seeds = self.seeds - system_ids
            issues.append(f"{len(external_seeds)} seed(s) are external: {external_seeds}")

        return issues

    def to_mermaid(self) -> str:
        """Export the Markov blanket partition as a Mermaid diagram.

        Returns:
            String containing valid Mermaid graph syntax.

        Example:
            >>> blanket = partition_by_seeds(graph, seeds=[...])
            >>> diagram = blanket.to_mermaid()
            >>> print(diagram)
            graph LR
                subgraph Internal
                    ...
        """
        lines = ["graph LR"]

        # Define subgraphs for each role
        if self.internal_ids:
            lines.append("    subgraph internal [Internal (μ)]")
            for node_id in sorted(self.internal_ids)[:5]:  # Limit for readability
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.sensory_ids:
            lines.append("    subgraph sensory [Sensory (s)]")
            for node_id in sorted(self.sensory_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.active_ids:
            lines.append("    subgraph active [Active (a)]")
            for node_id in sorted(self.active_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        if self.external_ids:
            lines.append("    subgraph external [External (η)]")
            for node_id in sorted(self.external_ids)[:5]:
                lines.append(f"        {node_id}[{node_id}]")
            lines.append("    end")

        return "\n".join(lines)

    def merge(self, other: MarkovBlanket) -> MarkovBlanket:
        """Merge two Markov blanket partitions.

        Combines the seed sets (union) and recomputes partition boundaries
        by taking the union of internal/sensory/active/external nodes.

        Args:
            other: Another MarkovBlanket to merge with this one.

        Returns:
            A new MarkovBlanket with merged partitions.

        Example:
            >>> b1 = partition_by_seeds(graph, seeds=[n1])
            >>> b2 = partition_by_seeds(graph, seeds=[n2])
            >>> merged = b1.merge(b2)
        """
        merged_seeds = self.seeds | other.seeds

        return MarkovBlanket(
            roles={**self.roles, **other.roles},
            seeds=merged_seeds,
            internal_ids=self.internal_ids | other.internal_ids,
            sensory_ids=self.sensory_ids | other.sensory_ids,
            active_ids=self.active_ids | other.active_ids,
            external_ids=self.external_ids | other.external_ids,
            rationale={**self.rationale, **other.rationale},
            stats={**self.stats, **other.stats},
            metadata={**self.metadata, **other.metadata},
        )

    def blanket_summary(self) -> dict[str, Any]:
        """Return a summary of blanket node counts and key statistics.

        Returns:
            Dictionary with keys:
            * ``n_internal``, ``n_sensory``, ``n_active``, ``n_external``: Counts.
            * ``blanket_size``: Size of boundary (sensory + active).
            * ``system_size``: Total system size (internal + boundary).
            * ``key_nodes``: List of prominent node ids (up to 5).

        Example:
            >>> summary = blanket.blanket_summary()
            >>> print(f"System size: {summary['system_size']}")
        """
        internal_list = sorted(self.internal_ids)
        boundary_list = sorted(self.sensory_ids | self.active_ids)
        key_nodes = (internal_list[:2] + boundary_list[:3])[:5]

        return {
            "n_internal": len(self.internal_ids),
            "n_sensory": len(self.sensory_ids),
            "n_active": len(self.active_ids),
            "n_external": len(self.external_ids),
            "blanket_size": len(self.sensory_ids) + len(self.active_ids),
            "system_size": len(self.internal_ids) + len(self.sensory_ids) + len(self.active_ids),
            "key_nodes": key_nodes,
        }

boundary_ids property

Union of sensory and active nodes — the Markov blanket B.

blanket_summary()

Return a summary of blanket node counts and key statistics.

Returns:

Type Description
dict[str, Any]

Dictionary with keys:

dict[str, Any]
  • n_internal, n_sensory, n_active, n_external: Counts.
dict[str, Any]
  • blanket_size: Size of boundary (sensory + active).
dict[str, Any]
  • system_size: Total system size (internal + boundary).
dict[str, Any]
  • key_nodes: List of prominent node ids (up to 5).
Example

summary = blanket.blanket_summary() print(f"System size: {summary['system_size']}")

Source code in py/cogant/markov/blanket.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def blanket_summary(self) -> dict[str, Any]:
    """Return a summary of blanket node counts and key statistics.

    Returns:
        Dictionary with keys:
        * ``n_internal``, ``n_sensory``, ``n_active``, ``n_external``: Counts.
        * ``blanket_size``: Size of boundary (sensory + active).
        * ``system_size``: Total system size (internal + boundary).
        * ``key_nodes``: List of prominent node ids (up to 5).

    Example:
        >>> summary = blanket.blanket_summary()
        >>> print(f"System size: {summary['system_size']}")
    """
    internal_list = sorted(self.internal_ids)
    boundary_list = sorted(self.sensory_ids | self.active_ids)
    key_nodes = (internal_list[:2] + boundary_list[:3])[:5]

    return {
        "n_internal": len(self.internal_ids),
        "n_sensory": len(self.sensory_ids),
        "n_active": len(self.active_ids),
        "n_external": len(self.external_ids),
        "blanket_size": len(self.sensory_ids) + len(self.active_ids),
        "system_size": len(self.internal_ids) + len(self.sensory_ids) + len(self.active_ids),
        "key_nodes": key_nodes,
    }

get_active_states()

Return all active boundary states (information flowing OUT).

Returns:

Type Description
list[str]

Sorted list of active node ids.

Example

active = blanket.get_active_states() print(f"{len(active)} active nodes")

Source code in py/cogant/markov/blanket.py
143
144
145
146
147
148
149
150
151
152
153
def get_active_states(self) -> list[str]:
    """Return all active boundary states (information flowing OUT).

    Returns:
        Sorted list of active node ids.

    Example:
        >>> active = blanket.get_active_states()
        >>> print(f"{len(active)} active nodes")
    """
    return sorted(self.active_ids)

get_sensory_states()

Return all sensory boundary states (information flowing IN).

Returns:

Type Description
list[str]

Sorted list of sensory node ids.

Example

sensory = blanket.get_sensory_states() print(f"{len(sensory)} sensory nodes")

Source code in py/cogant/markov/blanket.py
131
132
133
134
135
136
137
138
139
140
141
def get_sensory_states(self) -> list[str]:
    """Return all sensory boundary states (information flowing IN).

    Returns:
        Sorted list of sensory node ids.

    Example:
        >>> sensory = blanket.get_sensory_states()
        >>> print(f"{len(sensory)} sensory nodes")
    """
    return sorted(self.sensory_ids)

ids_by_role(role)

Return the set of node ids that carry a given role.

Source code in py/cogant/markov/blanket.py
121
122
123
124
125
126
127
128
129
def ids_by_role(self, role: BlanketRole) -> set[str]:
    """Return the set of node ids that carry a given role."""
    if role is BlanketRole.INTERNAL:
        return self.internal_ids
    if role is BlanketRole.SENSORY:
        return self.sensory_ids
    if role is BlanketRole.ACTIVE:
        return self.active_ids
    return self.external_ids

merge(other)

Merge two Markov blanket partitions.

Combines the seed sets (union) and recomputes partition boundaries by taking the union of internal/sensory/active/external nodes.

Parameters:

Name Type Description Default
other MarkovBlanket

Another MarkovBlanket to merge with this one.

required

Returns:

Type Description
MarkovBlanket

A new MarkovBlanket with merged partitions.

Example

b1 = partition_by_seeds(graph, seeds=[n1]) b2 = partition_by_seeds(graph, seeds=[n2]) merged = b1.merge(b2)

Source code in py/cogant/markov/blanket.py
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
def merge(self, other: MarkovBlanket) -> MarkovBlanket:
    """Merge two Markov blanket partitions.

    Combines the seed sets (union) and recomputes partition boundaries
    by taking the union of internal/sensory/active/external nodes.

    Args:
        other: Another MarkovBlanket to merge with this one.

    Returns:
        A new MarkovBlanket with merged partitions.

    Example:
        >>> b1 = partition_by_seeds(graph, seeds=[n1])
        >>> b2 = partition_by_seeds(graph, seeds=[n2])
        >>> merged = b1.merge(b2)
    """
    merged_seeds = self.seeds | other.seeds

    return MarkovBlanket(
        roles={**self.roles, **other.roles},
        seeds=merged_seeds,
        internal_ids=self.internal_ids | other.internal_ids,
        sensory_ids=self.sensory_ids | other.sensory_ids,
        active_ids=self.active_ids | other.active_ids,
        external_ids=self.external_ids | other.external_ids,
        rationale={**self.rationale, **other.rationale},
        stats={**self.stats, **other.stats},
        metadata={**self.metadata, **other.metadata},
    )

role_of(node_id)

Return the role of node_id, defaulting to EXTERNAL.

Source code in py/cogant/markov/blanket.py
117
118
119
def role_of(self, node_id: str) -> BlanketRole:
    """Return the role of ``node_id``, defaulting to EXTERNAL."""
    return self.roles.get(node_id, BlanketRole.EXTERNAL)

to_mermaid()

Export the Markov blanket partition as a Mermaid diagram.

Returns:

Type Description
str

String containing valid Mermaid graph syntax.

Example

blanket = partition_by_seeds(graph, seeds=[...]) diagram = blanket.to_mermaid() print(diagram) graph LR subgraph Internal ...

Source code in py/cogant/markov/blanket.py
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
def to_mermaid(self) -> str:
    """Export the Markov blanket partition as a Mermaid diagram.

    Returns:
        String containing valid Mermaid graph syntax.

    Example:
        >>> blanket = partition_by_seeds(graph, seeds=[...])
        >>> diagram = blanket.to_mermaid()
        >>> print(diagram)
        graph LR
            subgraph Internal
                ...
    """
    lines = ["graph LR"]

    # Define subgraphs for each role
    if self.internal_ids:
        lines.append("    subgraph internal [Internal (μ)]")
        for node_id in sorted(self.internal_ids)[:5]:  # Limit for readability
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.sensory_ids:
        lines.append("    subgraph sensory [Sensory (s)]")
        for node_id in sorted(self.sensory_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.active_ids:
        lines.append("    subgraph active [Active (a)]")
        for node_id in sorted(self.active_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    if self.external_ids:
        lines.append("    subgraph external [External (η)]")
        for node_id in sorted(self.external_ids)[:5]:
            lines.append(f"        {node_id}[{node_id}]")
        lines.append("    end")

    return "\n".join(lines)

validate()

Validate partition consistency.

Checks: * All nodes appear exactly once across all role sets. * No overlap between role sets. * Seeds are a subset of internal + boundary nodes.

Returns:

Type Description
list[str]

List of validation issue strings (empty if all checks pass).

Example

issues = blanket.validate() if issues: ... for issue in issues: ... print(f"Error: {issue}")

Source code in py/cogant/markov/blanket.py
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
def validate(self) -> list[str]:
    """Validate partition consistency.

    Checks:
    * All nodes appear exactly once across all role sets.
    * No overlap between role sets.
    * Seeds are a subset of internal + boundary nodes.

    Returns:
        List of validation issue strings (empty if all checks pass).

    Example:
        >>> issues = blanket.validate()
        >>> if issues:
        ...     for issue in issues:
        ...         print(f"Error: {issue}")
    """
    issues: list[str] = []

    all_ids = self.internal_ids | self.sensory_ids | self.active_ids | self.external_ids

    # Check roles are in dict
    role_nodes = set(self.roles.keys())
    if role_nodes != all_ids:
        issues.append(f"Role dict size {len(role_nodes)} doesn't match union {len(all_ids)}")

    # Check for overlaps
    pairs = [
        (self.internal_ids, self.sensory_ids, "internal/sensory"),
        (self.internal_ids, self.active_ids, "internal/active"),
        (self.internal_ids, self.external_ids, "internal/external"),
        (self.sensory_ids, self.active_ids, "sensory/active"),
        (self.sensory_ids, self.external_ids, "sensory/external"),
        (self.active_ids, self.external_ids, "active/external"),
    ]
    for s1, s2, name in pairs:
        if s1 & s2:
            issues.append(f"Overlap between {name}: {len(s1 & s2)} nodes")

    # Check seeds are within system
    system_ids = self.internal_ids | self.sensory_ids | self.active_ids
    if not self.seeds.issubset(system_ids):
        external_seeds = self.seeds - system_ids
        issues.append(f"{len(external_seeds)} seed(s) are external: {external_seeds}")

    return issues

visualize()

Export a visualization-friendly dictionary of the partition.

Returns:

Type Description
dict[str, Any]

Dictionary with keys:

dict[str, Any]
  • internal: List of internal node ids.
dict[str, Any]
  • sensory: List of sensory boundary node ids.
dict[str, Any]
  • active: List of active boundary node ids.
dict[str, Any]
  • external: List of external node ids.
dict[str, Any]
  • edges: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.
Example

vis = blanket.visualize() print(f"{len(vis['internal'])} internal nodes")

Source code in py/cogant/markov/blanket.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
def visualize(self) -> dict[str, Any]:
    """Export a visualization-friendly dictionary of the partition.

    Returns:
        Dictionary with keys:

        * ``internal``: List of internal node ids.
        * ``sensory``: List of sensory boundary node ids.
        * ``active``: List of active boundary node ids.
        * ``external``: List of external node ids.
        * ``edges``: List of (source, target, kind) tuples for cross-boundary edges; reserved until full edge export.

    Example:
        >>> vis = blanket.visualize()
        >>> print(f"{len(vis['internal'])} internal nodes")
    """
    return {
        "internal": sorted(self.internal_ids),
        "sensory": sorted(self.sensory_ids),
        "active": sorted(self.active_ids),
        "external": sorted(self.external_ids),
        "edges": [],  # Reserved field; full edge list would require graph
    }

partition_by_seeds(graph, seeds, *, adjacency=None)

Assign every node in graph a Markov blanket role.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph to partition.

required
seeds Iterable[str]

Iterable of node ids that define the "system of interest". Nodes NOT in this set are considered environmental.

required
adjacency Mapping[str, tuple[set[str], set[str]]] | None

Optional precomputed {id: (in_set, out_set)} map to avoid rebuilding if the caller already has one.

None

Returns:

Type Description
MarkovBlanket

A fully populated :class:MarkovBlanket. Every node id in the

MarkovBlanket

graph will appear exactly once across internal_ids,

MarkovBlanket

sensory_ids, active_ids, and external_ids.

The partitioning rule is purely topological:

.. code-block:: text

node ∈ seeds  and  all neighbours ∈ seeds         → INTERNAL
node ∈ seeds  and  ∃ external neighbour           → SENSORY/ACTIVE
node ∉ seeds                                       → EXTERNAL
Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) blanket.stats["total_nodes"] 0

Source code in py/cogant/markov/blanket.py
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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
def partition_by_seeds(
    graph: ProgramGraph,
    seeds: Iterable[str],
    *,
    adjacency: Mapping[str, tuple[set[str], set[str]]] | None = None,
) -> MarkovBlanket:
    """Assign every node in ``graph`` a Markov blanket role.

    Args:
        graph: The program graph to partition.
        seeds: Iterable of node ids that define the "system of interest".
            Nodes NOT in this set are considered environmental.
        adjacency: Optional precomputed ``{id: (in_set, out_set)}`` map
            to avoid rebuilding if the caller already has one.

    Returns:
        A fully populated :class:`MarkovBlanket`. Every node id in the
        graph will appear exactly once across ``internal_ids``,
        ``sensory_ids``, ``active_ids``, and ``external_ids``.

    The partitioning rule is purely topological:

    .. code-block:: text

        node ∈ seeds  and  all neighbours ∈ seeds         → INTERNAL
        node ∈ seeds  and  ∃ external neighbour           → SENSORY/ACTIVE
        node ∉ seeds                                       → EXTERNAL

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> blanket.stats["total_nodes"]
        0
    """
    seed_set: set[str] = {s for s in seeds if s in graph.nodes}

    if adjacency is None:
        adjacency = _bidirectional_adjacency(graph)

    roles: dict[str, BlanketRole] = {}
    rationale: dict[str, str] = {}
    internal: set[str] = set()
    sensory: set[str] = set()
    active: set[str] = set()
    external: set[str] = set()
    bidirectional: set[str] = set()
    external_neighbours: set[str] = set()

    for node_id in graph.nodes:
        in_neigh, out_neigh = adjacency[node_id]
        neigh = in_neigh | out_neigh

        if node_id in seed_set:
            ext_in = {n for n in in_neigh if n not in seed_set}
            ext_out = {n for n in out_neigh if n not in seed_set}

            if not (ext_in or ext_out):
                roles[node_id] = BlanketRole.INTERNAL
                rationale[node_id] = "internal: all neighbours inside seed set"
                internal.add(node_id)
                continue

            if ext_out and ext_in:
                roles[node_id] = BlanketRole.ACTIVE
                rationale[node_id] = "active (bidirectional): edges flow in and out of the system"
                active.add(node_id)
                bidirectional.add(node_id)
            elif ext_out:
                roles[node_id] = BlanketRole.ACTIVE
                rationale[node_id] = "active: writes/calls reach external states"
                active.add(node_id)
            else:
                roles[node_id] = BlanketRole.SENSORY
                rationale[node_id] = "sensory: reads/observes external states"
                sensory.add(node_id)
        else:
            roles[node_id] = BlanketRole.EXTERNAL
            if neigh & seed_set:
                rationale[node_id] = "external: immediate neighbour of the system"
                external_neighbours.add(node_id)
            else:
                rationale[node_id] = "external: no adjacency with the system"
            external.add(node_id)

    total = len(graph.nodes) or 1
    stats = {
        "total_nodes": len(graph.nodes),
        "seed_count": len(seed_set),
        "internal_count": len(internal),
        "sensory_count": len(sensory),
        "active_count": len(active),
        "external_count": len(external),
        "external_neighbour_count": len(external_neighbours),
        "bidirectional_count": len(bidirectional),
        "internal_ratio": round(len(internal) / total, 4),
        "boundary_ratio": round((len(sensory) + len(active)) / total, 4),
        "external_ratio": round(len(external) / total, 4),
    }

    blanket = MarkovBlanket(
        roles=roles,
        seeds=seed_set,
        internal_ids=internal,
        sensory_ids=sensory,
        active_ids=active,
        external_ids=external,
        rationale=rationale,
        stats=stats,
        metadata={
            "bidirectional_ids": sorted(bidirectional),
            "external_neighbour_ids": sorted(external_neighbours),
        },
    )
    return blanket

serialize_blanket(blanket, graph, *, include_rationale=True, max_nodes_per_role=None)

Convert a :class:MarkovBlanket into a JSON-friendly dictionary.

Parameters:

Name Type Description Default
blanket MarkovBlanket

The partition to serialize.

required
graph ProgramGraph

The graph used to produce the partition. Needed so that each node id can be enriched with its human-readable kind, name, and path for downstream reports.

required
include_rationale bool

Whether to include the per-node rationale string. Defaults to True; set False if the caller wants a more compact file.

True
max_nodes_per_role int | None

Optional cap on how many nodes to emit per role (useful for very large graphs). Capping is applied deterministically by sorting node ids first.

None

Returns:

Type Description
dict[str, Any]

A dict with the schema::

{ "schema_version": "1.0.0", "seeds": [...], "stats": {...}, "roles": { "internal": [{id, kind, name, path, rationale?}, ...], "sensory": [...], "active": [...], "external": [...], }, "metadata": {...} }

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) doc = serialize_blanket(blanket, graph) doc["schema_version"] '1.0.0' sorted(doc["roles"].keys()) ['active', 'external', 'internal', 'sensory']

Source code in py/cogant/markov/blanket.py
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
def serialize_blanket(
    blanket: MarkovBlanket,
    graph: ProgramGraph,
    *,
    include_rationale: bool = True,
    max_nodes_per_role: int | None = None,
) -> dict[str, Any]:
    """Convert a :class:`MarkovBlanket` into a JSON-friendly dictionary.

    Args:
        blanket: The partition to serialize.
        graph: The graph used to produce the partition. Needed so that
            each node id can be enriched with its human-readable
            ``kind``, ``name``, and ``path`` for downstream reports.
        include_rationale: Whether to include the per-node rationale
            string. Defaults to ``True``; set ``False`` if the caller
            wants a more compact file.
        max_nodes_per_role: Optional cap on how many nodes to emit per
            role (useful for very large graphs). Capping is applied
            deterministically by sorting node ids first.

    Returns:
        A dict with the schema::

            {
              "schema_version": "1.0.0",
              "seeds": [...],
              "stats": {...},
              "roles": {
                  "internal": [{id, kind, name, path, rationale?}, ...],
                  "sensory":  [...],
                  "active":   [...],
                  "external": [...],
              },
              "metadata": {...}
            }

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> doc = serialize_blanket(blanket, graph)
        >>> doc["schema_version"]
        '1.0.0'
        >>> sorted(doc["roles"].keys())
        ['active', 'external', 'internal', 'sensory']
    """

    def _format(node_ids: Iterable[str]) -> list[dict[str, Any]]:
        ids = sorted(node_ids)
        if max_nodes_per_role is not None:
            ids = ids[:max_nodes_per_role]
        out: list[dict[str, Any]] = []
        for nid in ids:
            node = graph.get_node(nid)
            record: dict[str, Any] = {
                "id": nid,
                "kind": _node_kind_value(node) if node else None,
                "name": node.name if node else None,
                "path": node.path if node else None,
            }
            if include_rationale and nid in blanket.rationale:
                record["rationale"] = blanket.rationale[nid]
            out.append(record)
        return out

    return {
        "schema_version": "1.0.0",
        "seeds": sorted(blanket.seeds),
        "stats": dict(blanket.stats),
        "roles": {
            BlanketRole.INTERNAL.value: _format(blanket.internal_ids),
            BlanketRole.SENSORY.value: _format(blanket.sensory_ids),
            BlanketRole.ACTIVE.value: _format(blanket.active_ids),
            BlanketRole.EXTERNAL.value: _format(blanket.external_ids),
        },
        "metadata": dict(blanket.metadata),
    }

Extractor

The seeded extractor with five strategies (auto, module, class, cluster, explicit).

cogant.markov.extractor

High-level Markov blanket extractor for COGANT program graphs.

:class:MarkovBlanketExtractor is the primary user-facing entry point. It wraps :func:cogant.markov.blanket.partition_by_seeds with a set of seed-selection strategies so that callers can either supply their own "system of interest" or ask COGANT to discover one automatically.

Supported strategies:

"explicit" Use an explicit list of node ids provided by the caller.

"module" Treat a named module (or modules) and everything they transitively contain as the system of interest. This is the most common choice when analysing a library or package.

"kind" Treat every node of a given :class:NodeKind (e.g. every CLASS node, every FUNCTION node) as part of the seed set.

"auto" Pick the module with the highest internal cohesion / external coupling ratio, which usually corresponds to the repo's "core" package. This is deterministic and depends only on the graph structure.

"mapping_kind" Seed from semantic mappings: every node that participates in a mapping whose :class:~cogant.schemas.semantic.MappingKind is in a user-specified set (default: HIDDEN_STATE) is included. This links the Markov blanket back to the Active Inference state space produced earlier in the pipeline.

Every strategy returns a fully-populated :class:MarkovBlanket, so callers never need to know which branch was taken to get back a partition ready for serialization into the GNN bundle.

MarkovBlanketExtractor

Build Markov blankets from program graphs.

The extractor is stateless beyond a reference to the source graph and a handful of default knobs. Invoke :meth:extract with the desired strategy and parameters and it returns a :class:MarkovBlanket ready to feed into the GNN bundle.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph to partition.

required
prefer_boundary int

When set, a node marked as boundary AND present in at least prefer_boundary mapping kinds will be recorded in the resulting blanket's metadata.

1
Source code in py/cogant/markov/extractor.py
 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
308
309
310
311
312
313
314
315
316
317
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
class MarkovBlanketExtractor:
    """Build Markov blankets from program graphs.

    The extractor is stateless beyond a reference to the source graph
    and a handful of default knobs. Invoke :meth:`extract` with the
    desired strategy and parameters and it returns a
    :class:`MarkovBlanket` ready to feed into the GNN bundle.

    Args:
        graph: The program graph to partition.
        prefer_boundary: When set, a node marked as boundary AND
            present in at least ``prefer_boundary`` mapping kinds will
            be recorded in the resulting blanket's ``metadata``.
    """

    def __init__(self, graph: ProgramGraph, *, prefer_boundary: int = 1):
        self.graph = graph
        self.prefer_boundary = prefer_boundary
        self._adjacency = _bidirectional_adjacency(graph)

    def extract(
        self,
        *,
        strategy: SeedStrategy = "auto",
        seeds: Iterable[str] | None = None,
        module_names: Sequence[str] | None = None,
        kinds: Sequence[NodeKind] | None = None,
        mapping_kinds: Sequence[str] | None = None,
        semantic_mappings: dict[str, Any] | None = None,
    ) -> MarkovBlanket:
        """Compute a Markov blanket.

        Args:
            strategy: Seed selection strategy. See module docstring.
            seeds: Explicit node ids (required when ``strategy="explicit"``).
            module_names: Module/package names to anchor on
                (``strategy="module"``).
            kinds: Node kinds to aggregate (``strategy="kind"``).
            mapping_kinds: Mapping-kind strings such as ``"hidden_state"``
                (``strategy="mapping_kind"``).
            semantic_mappings: Optional mapping dict from
                ``orchestration.run_translate`` (required when
                ``strategy="mapping_kind"``).

        Returns:
            A :class:`MarkovBlanket` with metadata recording the
            strategy and inputs that produced it.

        Example:
            >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
            >>> from cogant.markov.extractor import MarkovBlanketExtractor
            >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
            >>> extractor = MarkovBlanketExtractor(graph)
            >>> blanket = extractor.extract(strategy="auto")
            >>> blanket.metadata["strategy"]
            'auto'
        """
        if strategy == "explicit":
            if not seeds:
                raise ValueError("strategy='explicit' requires a non-empty seeds list")
            seed_set = set(seeds)

        elif strategy == "module":
            if not module_names:
                raise ValueError("strategy='module' requires module_names")
            seed_set = self._seeds_from_modules(module_names)

        elif strategy == "kind":
            if not kinds:
                raise ValueError("strategy='kind' requires kinds")
            seed_set = self._seeds_from_kinds(kinds)

        elif strategy == "mapping_kind":
            seed_set = self._seeds_from_mapping_kinds(
                semantic_mappings or {}, mapping_kinds or ["hidden_state"]
            )

        elif strategy == "auto":
            seed_set, auto_meta = self._seeds_auto()
        else:
            raise ValueError(f"Unknown strategy: {strategy!r}")

        logger.info(
            "Markov blanket extraction: strategy=%s, %d seeds from %d graph nodes",
            strategy,
            len(seed_set),
            len(self.graph.nodes),
        )

        blanket = partition_by_seeds(self.graph, seed_set, adjacency=self._adjacency)
        blanket.metadata["strategy"] = strategy
        blanket.metadata["requested_seed_count"] = len(list(seed_set))
        if strategy == "module":
            blanket.metadata["module_names"] = list(module_names or [])
        if strategy == "kind":
            blanket.metadata["kinds"] = [
                k.value if hasattr(k, "value") else str(k) for k in (kinds or [])
            ]
        if strategy == "mapping_kind":
            blanket.metadata["mapping_kinds"] = list(mapping_kinds or [])
        if strategy == "auto":
            blanket.metadata.update(auto_meta)

        logger.info(
            "Markov blanket partitioned: internal=%d, sensory=%d, active=%d, external=%d",
            blanket.stats.get("internal_count", 0),
            blanket.stats.get("sensory_count", 0),
            blanket.stats.get("active_count", 0),
            blanket.stats.get("external_count", 0),
        )
        return blanket

    # ---------------------- Seed strategy helpers ---------------------- #

    def _seeds_from_modules(self, module_names: Sequence[str]) -> set[str]:
        """Collect module nodes + everything they ``CONTAINS``-reach."""
        targets = {m.lower() for m in module_names}
        seeds: set[str] = set()
        module_nodes = self.graph.get_nodes_by_kind(NodeKind.MODULE)
        for node in module_nodes:
            name_match = (node.name or "").lower()
            qn_match = (node.qualified_name or "").lower()
            if any(t in name_match or t in qn_match for t in targets):
                seeds.add(node.id)
                seeds.update(self._descend_contains(node.id))
        return seeds

    def _descend_contains(self, root_id: str) -> set[str]:
        """Return the transitive CONTAINS-closure of ``root_id``."""
        collected: set[str] = set()
        frontier = [root_id]
        while frontier:
            cur = frontier.pop()
            for edge in self.graph.get_edges_from(cur):
                if edge.kind is EdgeKind.CONTAINS and edge.target_id not in collected:
                    collected.add(edge.target_id)
                    frontier.append(edge.target_id)
        return collected

    def _seeds_from_kinds(self, kinds: Sequence[NodeKind]) -> set[str]:
        seeds: set[str] = set()
        for kind in kinds:
            for node in self.graph.get_nodes_by_kind(kind):
                seeds.add(node.id)
        return seeds

    def _seeds_from_mapping_kinds(
        self,
        semantic_mappings: dict[str, Any],
        mapping_kinds: Sequence[str],
    ) -> set[str]:
        wanted = {mk.lower() for mk in mapping_kinds}
        seeds: set[str] = set()
        for mapping in semantic_mappings.values():
            kind_value = getattr(mapping, "kind", None)
            if kind_value is None:
                continue
            kv = kind_value.value if hasattr(kind_value, "value") else str(kind_value)
            if kv.lower() not in wanted:
                continue
            node_ids = getattr(mapping, "graph_fragment_node_ids", None) or []
            for nid in node_ids:
                if nid in self.graph.nodes:
                    seeds.add(nid)
        return seeds

    def _seeds_auto(self) -> tuple[set[str], dict[str, Any]]:
        """Pick the best cohesion/coupling seed set automatically.

        The heuristic has two tiers:

        1. **Module tier.** For every ``MODULE`` node we compute::

               cohesion  = edges inside the module's contains-closure
               coupling  = edges crossing the closure boundary
               score     = cohesion / (cohesion + coupling + 1)

           and take the argmax. Ties are broken by higher total node
           count so tiny helper modules do not win by accident.

        2. **Class tier fallback.** When there are no modules, or when
           the best module contains the entire graph (making the
           partition degenerate — every node is internal, the blanket
           is empty), we fall back to the largest ``CLASS`` node. Its
           :meth:`~cogant.markov.extractor.MarkovBlanketExtractor._descend_contains`
           closure becomes the seed set. If there are no classes
           either, we fall back to every ``CLASS`` node taken together.

        The returned metadata always records which tier was used, which
        candidate won, and the scoreboard for every module considered,
        so downstream reports can explain *why* this partition was
        selected.
        """
        total_nodes = len(self.graph.nodes)
        modules = self.graph.get_nodes_by_kind(NodeKind.MODULE)

        # Tier 2: no modules at all.
        if not modules:
            return self._auto_class_fallback(reason="no modules present")

        best_score = -1.0
        best_id: str | None = None
        best_size = 0
        scoreboard: list[dict[str, Any]] = []

        for module in modules:
            closure = {module.id} | self._descend_contains(module.id)
            cohesion = 0
            coupling = 0
            for nid in closure:
                for edge in self.graph.get_edges_from(nid):
                    if edge.target_id in closure:
                        cohesion += 1
                    else:
                        coupling += 1
                for edge in self.graph.get_edges_to(nid):
                    if edge.source_id not in closure:
                        coupling += 1
            score = cohesion / (cohesion + coupling + 1)
            scoreboard.append(
                {
                    "module_id": module.id,
                    "module_name": module.name or module.qualified_name,
                    "closure_size": len(closure),
                    "cohesion": cohesion,
                    "coupling": coupling,
                    "score": round(score, 4),
                }
            )
            if score > best_score or (score == best_score and len(closure) > best_size):
                best_score = score
                best_id = module.id
                best_size = len(closure)

        if best_id is None:
            return set(), {"auto_reason": "no candidate modules scored above 0"}

        # Tier 2: best module swallows the whole graph → degenerate
        # partition with no boundary. Fall back to a class-level seed.
        if best_size >= total_nodes:
            fallback = self._auto_class_fallback(
                reason="only module spans whole graph; fell back to class tier"
            )
            fallback_seeds, fallback_meta = fallback
            fallback_meta["module_scoreboard"] = scoreboard
            fallback_meta["fallback_from_module_id"] = best_id
            return fallback_seeds, fallback_meta

        seeds = {best_id} | self._descend_contains(best_id)
        meta = {
            "auto_reason": "argmax of cohesion/(cohesion+coupling+1) over modules",
            "auto_tier": "module",
            "chosen_module_id": best_id,
            "chosen_score": best_score,
            "chosen_closure_size": best_size,
            "candidate_modules": len(modules),
            "scoreboard": scoreboard,
        }
        logger.info(
            "Markov blanket auto-seed chose module %s (score=%.3f, nodes=%d)",
            best_id,
            best_score,
            best_size,
        )
        return seeds, meta

    def _auto_class_fallback(self, *, reason: str) -> tuple[set[str], dict[str, Any]]:
        """Pick the largest ``CLASS`` closure as the auto seed set.

        Chooses the class whose ``CONTAINS``-closure size is largest
        (ties broken by node id for determinism). If there are no
        classes, returns every class node — which, when the graph has
        none, yields an empty seed set and a degenerate (all-external)
        blanket; this is the correct honest answer for such a graph.
        """
        classes = self.graph.get_nodes_by_kind(NodeKind.CLASS)
        if not classes:
            return set(), {
                "auto_reason": f"{reason}; no classes to fall back to",
                "auto_tier": "empty",
                "candidate_classes": 0,
            }

        best_cls_id: str | None = None
        best_closure: set[str] = set()
        for cls in sorted(classes, key=lambda c: c.id):
            closure = {cls.id} | self._descend_contains(cls.id)
            if len(closure) > len(best_closure):
                best_cls_id = cls.id
                best_closure = closure

        if best_cls_id is None or len(best_closure) <= 1:
            # Classes exist but none have methods/members → aggregate all classes.
            seeds = {c.id for c in classes}
            return seeds, {
                "auto_reason": f"{reason}; no class has non-trivial closure, used all CLASS nodes",
                "auto_tier": "class_aggregate",
                "candidate_classes": len(classes),
            }

        return best_closure, {
            "auto_reason": reason,
            "auto_tier": "class",
            "chosen_class_id": best_cls_id,
            "chosen_closure_size": len(best_closure),
            "candidate_classes": len(classes),
        }

extract(*, strategy='auto', seeds=None, module_names=None, kinds=None, mapping_kinds=None, semantic_mappings=None)

Compute a Markov blanket.

Parameters:

Name Type Description Default
strategy SeedStrategy

Seed selection strategy. See module docstring.

'auto'
seeds Iterable[str] | None

Explicit node ids (required when strategy="explicit").

None
module_names Sequence[str] | None

Module/package names to anchor on (strategy="module").

None
kinds Sequence[NodeKind] | None

Node kinds to aggregate (strategy="kind").

None
mapping_kinds Sequence[str] | None

Mapping-kind strings such as "hidden_state" (strategy="mapping_kind").

None
semantic_mappings dict[str, Any] | None

Optional mapping dict from orchestration.run_translate (required when strategy="mapping_kind").

None

Returns:

Name Type Description
A MarkovBlanket

class:MarkovBlanket with metadata recording the

MarkovBlanket

strategy and inputs that produced it.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.extractor import MarkovBlanketExtractor graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) extractor = MarkovBlanketExtractor(graph) blanket = extractor.extract(strategy="auto") blanket.metadata["strategy"] 'auto'

Source code in py/cogant/markov/extractor.py
 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
def extract(
    self,
    *,
    strategy: SeedStrategy = "auto",
    seeds: Iterable[str] | None = None,
    module_names: Sequence[str] | None = None,
    kinds: Sequence[NodeKind] | None = None,
    mapping_kinds: Sequence[str] | None = None,
    semantic_mappings: dict[str, Any] | None = None,
) -> MarkovBlanket:
    """Compute a Markov blanket.

    Args:
        strategy: Seed selection strategy. See module docstring.
        seeds: Explicit node ids (required when ``strategy="explicit"``).
        module_names: Module/package names to anchor on
            (``strategy="module"``).
        kinds: Node kinds to aggregate (``strategy="kind"``).
        mapping_kinds: Mapping-kind strings such as ``"hidden_state"``
            (``strategy="mapping_kind"``).
        semantic_mappings: Optional mapping dict from
            ``orchestration.run_translate`` (required when
            ``strategy="mapping_kind"``).

    Returns:
        A :class:`MarkovBlanket` with metadata recording the
        strategy and inputs that produced it.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.extractor import MarkovBlanketExtractor
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> extractor = MarkovBlanketExtractor(graph)
        >>> blanket = extractor.extract(strategy="auto")
        >>> blanket.metadata["strategy"]
        'auto'
    """
    if strategy == "explicit":
        if not seeds:
            raise ValueError("strategy='explicit' requires a non-empty seeds list")
        seed_set = set(seeds)

    elif strategy == "module":
        if not module_names:
            raise ValueError("strategy='module' requires module_names")
        seed_set = self._seeds_from_modules(module_names)

    elif strategy == "kind":
        if not kinds:
            raise ValueError("strategy='kind' requires kinds")
        seed_set = self._seeds_from_kinds(kinds)

    elif strategy == "mapping_kind":
        seed_set = self._seeds_from_mapping_kinds(
            semantic_mappings or {}, mapping_kinds or ["hidden_state"]
        )

    elif strategy == "auto":
        seed_set, auto_meta = self._seeds_auto()
    else:
        raise ValueError(f"Unknown strategy: {strategy!r}")

    logger.info(
        "Markov blanket extraction: strategy=%s, %d seeds from %d graph nodes",
        strategy,
        len(seed_set),
        len(self.graph.nodes),
    )

    blanket = partition_by_seeds(self.graph, seed_set, adjacency=self._adjacency)
    blanket.metadata["strategy"] = strategy
    blanket.metadata["requested_seed_count"] = len(list(seed_set))
    if strategy == "module":
        blanket.metadata["module_names"] = list(module_names or [])
    if strategy == "kind":
        blanket.metadata["kinds"] = [
            k.value if hasattr(k, "value") else str(k) for k in (kinds or [])
        ]
    if strategy == "mapping_kind":
        blanket.metadata["mapping_kinds"] = list(mapping_kinds or [])
    if strategy == "auto":
        blanket.metadata.update(auto_meta)

    logger.info(
        "Markov blanket partitioned: internal=%d, sensory=%d, active=%d, external=%d",
        blanket.stats.get("internal_count", 0),
        blanket.stats.get("sensory_count", 0),
        blanket.stats.get("active_count", 0),
        blanket.stats.get("external_count", 0),
    )
    return blanket

Network

Network-level helpers for multi-blanket analysis.

cogant.markov.network

Reduced network representations derived from a Markov blanket.

A :class:~cogant.markov.blanket.MarkovBlanket tells us the role of every node in the graph, but consumers of COGANT (Active Inference modellers, architecture reviewers, diff tools) usually want a reduced network that collapses the full program graph to the canonical four-node Active Inference schematic:

.. code-block:: text

    ┌──────┐        ┌──────┐
    │  η   │◀──────▶│  s   │──────┐
    └──────┘        └──────┘      ▼
                                ┌──────┐
                                │  μ   │
                                └──────┘
    ┌──────┐        ┌──────┐      ▲
    │  η   │◀──────│  a   │──────┘
    └──────┘        └──────┘

:func:build_blanket_network walks the original program graph and produces:

  • Aggregate edges between the four roles (η→s, s→μ, μ→a, a→η) with counts and per-:class:~cogant.schemas.core.EdgeKind breakdowns.
  • Role bags listing which concrete nodes are behind each aggregate vertex, so the reduced view is always traceable to the full graph.

The result is serializable to JSON, Mermaid, and Cytoscape formats so that the bundle can render the Markov blanket as a diagram or load it into a network analysis tool without a second traversal.

BlanketNetwork dataclass

Collapsed four-node Active Inference network view of a blanket.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) net = build_blanket_network(graph, blanket) isinstance(net, BlanketNetwork) True "graph LR" in net.to_mermaid() True

Source code in py/cogant/markov/network.py
 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
@dataclass
class BlanketNetwork:
    """Collapsed four-node Active Inference network view of a blanket.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> net = build_blanket_network(graph, blanket)
        >>> isinstance(net, BlanketNetwork)
        True
        >>> "graph LR" in net.to_mermaid()
        True
    """

    role_counts: dict[str, int]
    """Number of concrete nodes per role (``internal``, ``sensory``, …)."""

    role_members: dict[str, list[str]]
    """Node ids per role, sorted."""

    aggregate_edges: dict[tuple[str, str], int]
    """Dict of ``(from_role, to_role) → edge count``."""

    edge_kind_breakdown: dict[tuple[str, str], dict[str, int]]
    """Same shape as ``aggregate_edges`` but bucketed by ``EdgeKind``."""

    metadata: dict[str, Any] = field(default_factory=dict)

    def to_dict(self) -> dict[str, Any]:
        """Serialize the network as a JSON-friendly dictionary."""
        return {
            "role_counts": dict(self.role_counts),
            "role_members": {k: list(v) for k, v in self.role_members.items()},
            "aggregate_edges": [
                {"from": a, "to": b, "count": c}
                for (a, b), c in sorted(self.aggregate_edges.items())
            ],
            "edge_kind_breakdown": [
                {"from": a, "to": b, "kinds": dict(sorted(d.items()))}
                for (a, b), d in sorted(self.edge_kind_breakdown.items())
            ],
            "metadata": dict(self.metadata),
        }

    def to_mermaid(self) -> str:
        """Render the collapsed view as a Mermaid ``graph LR`` block.

        The four roles are drawn with bracketed labels summarising the
        node count in that role. Aggregate edges are labelled with the
        number of underlying concrete edges.
        """
        lines = ["graph LR"]
        label = {
            "internal": f"μ internal [{self.role_counts.get('internal', 0)}]",
            "sensory": f"s sensory [{self.role_counts.get('sensory', 0)}]",
            "active": f"a active [{self.role_counts.get('active', 0)}]",
            "external": f"η external [{self.role_counts.get('external', 0)}]",
        }
        for key, text in label.items():
            lines.append(f'    {key}["{text}"]')
        for (src, dst), count in sorted(self.aggregate_edges.items()):
            if count > 0:
                lines.append(f"    {src} -->|{count}| {dst}")
        return "\n".join(lines)

aggregate_edges instance-attribute

Dict of (from_role, to_role) → edge count.

edge_kind_breakdown instance-attribute

Same shape as aggregate_edges but bucketed by EdgeKind.

role_counts instance-attribute

Number of concrete nodes per role (internal, sensory, …).

role_members instance-attribute

Node ids per role, sorted.

to_dict()

Serialize the network as a JSON-friendly dictionary.

Source code in py/cogant/markov/network.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
def to_dict(self) -> dict[str, Any]:
    """Serialize the network as a JSON-friendly dictionary."""
    return {
        "role_counts": dict(self.role_counts),
        "role_members": {k: list(v) for k, v in self.role_members.items()},
        "aggregate_edges": [
            {"from": a, "to": b, "count": c}
            for (a, b), c in sorted(self.aggregate_edges.items())
        ],
        "edge_kind_breakdown": [
            {"from": a, "to": b, "kinds": dict(sorted(d.items()))}
            for (a, b), d in sorted(self.edge_kind_breakdown.items())
        ],
        "metadata": dict(self.metadata),
    }

to_mermaid()

Render the collapsed view as a Mermaid graph LR block.

The four roles are drawn with bracketed labels summarising the node count in that role. Aggregate edges are labelled with the number of underlying concrete edges.

Source code in py/cogant/markov/network.py
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
def to_mermaid(self) -> str:
    """Render the collapsed view as a Mermaid ``graph LR`` block.

    The four roles are drawn with bracketed labels summarising the
    node count in that role. Aggregate edges are labelled with the
    number of underlying concrete edges.
    """
    lines = ["graph LR"]
    label = {
        "internal": f"μ internal [{self.role_counts.get('internal', 0)}]",
        "sensory": f"s sensory [{self.role_counts.get('sensory', 0)}]",
        "active": f"a active [{self.role_counts.get('active', 0)}]",
        "external": f"η external [{self.role_counts.get('external', 0)}]",
    }
    for key, text in label.items():
        lines.append(f'    {key}["{text}"]')
    for (src, dst), count in sorted(self.aggregate_edges.items()):
        if count > 0:
            lines.append(f"    {src} -->|{count}| {dst}")
    return "\n".join(lines)

build_blanket_network(graph, blanket)

Collapse graph into a four-role aggregate network.

Every concrete edge in graph is mapped to a pair (role_of_source, role_of_target) and counted. Edges are also bucketed by :class:EdgeKind so that downstream tooling can see, e.g., how many of the s→μ edges are READS vs CALLS.

Parameters:

Name Type Description Default
graph ProgramGraph

The program graph used to build blanket.

required
blanket MarkovBlanket

The Markov blanket partition.

required

Returns:

Name Type Description
A BlanketNetwork

class:BlanketNetwork summarising the collapsed view.

Example

from cogant.schemas.graph import ProgramGraph, GraphMetadata from cogant.markov.blanket import partition_by_seeds graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo")) blanket = partition_by_seeds(graph, seeds=[]) network = build_blanket_network(graph, blanket) sorted(network.role_counts.keys()) ['active', 'external', 'internal', 'sensory']

Source code in py/cogant/markov/network.py
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
def build_blanket_network(graph: ProgramGraph, blanket: MarkovBlanket) -> BlanketNetwork:
    """Collapse ``graph`` into a four-role aggregate network.

    Every concrete edge in ``graph`` is mapped to a pair
    ``(role_of_source, role_of_target)`` and counted. Edges are also
    bucketed by :class:`EdgeKind` so that downstream tooling can see,
    e.g., how many of the s→μ edges are ``READS`` vs ``CALLS``.

    Args:
        graph: The program graph used to build ``blanket``.
        blanket: The Markov blanket partition.

    Returns:
        A :class:`BlanketNetwork` summarising the collapsed view.

    Example:
        >>> from cogant.schemas.graph import ProgramGraph, GraphMetadata
        >>> from cogant.markov.blanket import partition_by_seeds
        >>> graph = ProgramGraph(metadata=GraphMetadata(repo_uri="demo"))
        >>> blanket = partition_by_seeds(graph, seeds=[])
        >>> network = build_blanket_network(graph, blanket)
        >>> sorted(network.role_counts.keys())
        ['active', 'external', 'internal', 'sensory']
    """
    aggregate: dict[tuple[str, str], int] = defaultdict(int)
    kind_break: dict[tuple[str, str], dict[str, int]] = defaultdict(lambda: defaultdict(int))

    def _role_name(node_id: str) -> str:
        return blanket.role_of(node_id).value

    for edge in graph.edges.values():
        src_role = _role_name(edge.source_id)
        dst_role = _role_name(edge.target_id)
        key = (src_role, dst_role)
        aggregate[key] += 1
        kind_value = edge.kind.value if isinstance(edge.kind, EdgeKind) else str(edge.kind)
        kind_break[key][kind_value] += 1

    # Freeze inner defaultdicts so json.dumps doesn't serialize a factory.
    edge_kind_breakdown = {k: dict(v) for k, v in kind_break.items()}

    role_members = {
        BlanketRole.INTERNAL.value: sorted(blanket.internal_ids),
        BlanketRole.SENSORY.value: sorted(blanket.sensory_ids),
        BlanketRole.ACTIVE.value: sorted(blanket.active_ids),
        BlanketRole.EXTERNAL.value: sorted(blanket.external_ids),
    }
    role_counts = {k: len(v) for k, v in role_members.items()}

    network = BlanketNetwork(
        role_counts=role_counts,
        role_members=role_members,
        aggregate_edges=dict(aggregate),
        edge_kind_breakdown=edge_kind_breakdown,
        metadata={
            "edge_count": len(graph.edges),
            "node_count": len(graph.nodes),
            "seed_count": len(blanket.seeds),
        },
    )
    return network