Skip to content

cogant.simulate

The cogant.simulate package runs forward simulations of the compiled state-space model: sample trajectories, compute variational free energy, and visualize outcomes.

Package

cogant.simulate

COGANT Simulate: Model validation and state space simulation with Active Inference.

CategoricalDistribution

Categorical probability distribution over discrete states.

Source code in py/cogant/simulate/distributions.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 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
class CategoricalDistribution:
    """Categorical probability distribution over discrete states."""

    def __init__(self, categories: list[str], probabilities: list[float] | None = None):
        """
        Initialize a categorical distribution.

        Args:
            categories: List of category names.
            probabilities: Optional list of probabilities (must sum to 1).
                          If None, uses uniform distribution.
        """
        self.categories = categories
        self.n = len(categories)

        # Handle empty categories case
        if self.n == 0:
            self.probabilities = []
            self.dist = {}
            return

        if probabilities is None:
            # Uniform distribution
            self.probabilities = [1.0 / self.n] * self.n
        else:
            if len(probabilities) != self.n:
                raise ValueError("Number of probabilities must match number of categories")
            total = sum(probabilities)
            if total <= 0:
                raise ValueError(f"Probabilities must be positive, got sum {total}")
            # Normalize to ensure exact sum of 1 (handles incomplete distributions)
            self.probabilities = [p / total for p in probabilities]

        # Build category -> probability mapping
        self.dist = dict(zip(categories, self.probabilities, strict=False))

    def sample(self) -> str:
        """Sample a category from the distribution.

        Returns:
            A sampled category name.
        """
        return random.choices(self.categories, weights=self.probabilities, k=1)[0]

    def log_prob(self, category: str) -> float:
        """Get log probability of a category.

        Args:
            category: Category name.

        Returns:
            log(P(category)). Returns -inf if category has 0 probability.
        """
        if category not in self.dist:
            raise KeyError(f"Unknown category: {category}")
        prob = self.dist[category]
        if prob <= 0:
            return float("-inf")
        return math.log(prob)

    def entropy(self) -> float:
        """Compute Shannon entropy of the distribution.

        Returns:
            Entropy in nats.
        """
        h = 0.0
        for prob in self.probabilities:
            if prob > 0:
                h -= prob * math.log(prob)
        return h

    def kl_divergence(self, other: "CategoricalDistribution") -> float:
        """Compute KL divergence to another distribution.

        Args:
            other: Another CategoricalDistribution with same categories.

        Returns:
            KL(self || other) in nats.
        """
        if set(self.categories) != set(other.categories):
            raise ValueError("Distributions must have same categories for KL divergence")

        kl = 0.0
        for cat in self.categories:
            p = self.dist[cat]
            q = other.dist[cat]
            if p > 0:
                if q <= 0:
                    return float("inf")
                kl += p * (math.log(p) - math.log(q))
        return kl

    def update(
        self, observation: str, likelihood: "CategoricalDistribution"
    ) -> "CategoricalDistribution":
        """Bayesian update: posterior ∝ likelihood × prior.

        Args:
            observation: The observed category.
            likelihood: P(observation | category) for each category.

        Returns:
            Updated posterior distribution.
        """
        if observation not in likelihood.categories:
            raise ValueError(f"Observation {observation} not in likelihood categories")

        # Posterior ∝ likelihood(obs|cat) × prior(cat)
        posterior_unnormalized = []
        for cat in self.categories:
            prior_cat = self.dist[cat]
            # P(obs | cat) from likelihood
            likelihood_obs_given_cat = likelihood.dist.get(cat, 1e-10)
            posterior_unnormalized.append(prior_cat * likelihood_obs_given_cat)

        # Normalize
        total = sum(posterior_unnormalized)
        if total <= 0:
            # If no valid posterior, return prior (avoid division by zero)
            return CategoricalDistribution(self.categories, self.probabilities)

        posterior_probs = [p / total for p in posterior_unnormalized]
        return CategoricalDistribution(self.categories, posterior_probs)

    def __repr__(self) -> str:
        """String representation."""
        items = [f"{cat}: {prob:.3f}" for cat, prob in self.dist.items()]
        return f"CategoricalDistribution({', '.join(items)})"

__init__(categories, probabilities=None)

Initialize a categorical distribution.

Parameters:

Name Type Description Default
categories list[str]

List of category names.

required
probabilities list[float] | None

Optional list of probabilities (must sum to 1). If None, uses uniform distribution.

None
Source code in py/cogant/simulate/distributions.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __init__(self, categories: list[str], probabilities: list[float] | None = None):
    """
    Initialize a categorical distribution.

    Args:
        categories: List of category names.
        probabilities: Optional list of probabilities (must sum to 1).
                      If None, uses uniform distribution.
    """
    self.categories = categories
    self.n = len(categories)

    # Handle empty categories case
    if self.n == 0:
        self.probabilities = []
        self.dist = {}
        return

    if probabilities is None:
        # Uniform distribution
        self.probabilities = [1.0 / self.n] * self.n
    else:
        if len(probabilities) != self.n:
            raise ValueError("Number of probabilities must match number of categories")
        total = sum(probabilities)
        if total <= 0:
            raise ValueError(f"Probabilities must be positive, got sum {total}")
        # Normalize to ensure exact sum of 1 (handles incomplete distributions)
        self.probabilities = [p / total for p in probabilities]

    # Build category -> probability mapping
    self.dist = dict(zip(categories, self.probabilities, strict=False))

__repr__()

String representation.

Source code in py/cogant/simulate/distributions.py
140
141
142
143
def __repr__(self) -> str:
    """String representation."""
    items = [f"{cat}: {prob:.3f}" for cat, prob in self.dist.items()]
    return f"CategoricalDistribution({', '.join(items)})"

entropy()

Compute Shannon entropy of the distribution.

Returns:

Type Description
float

Entropy in nats.

Source code in py/cogant/simulate/distributions.py
74
75
76
77
78
79
80
81
82
83
84
def entropy(self) -> float:
    """Compute Shannon entropy of the distribution.

    Returns:
        Entropy in nats.
    """
    h = 0.0
    for prob in self.probabilities:
        if prob > 0:
            h -= prob * math.log(prob)
    return h

kl_divergence(other)

Compute KL divergence to another distribution.

Parameters:

Name Type Description Default
other CategoricalDistribution

Another CategoricalDistribution with same categories.

required

Returns:

Type Description
float

KL(self || other) in nats.

Source code in py/cogant/simulate/distributions.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def kl_divergence(self, other: "CategoricalDistribution") -> float:
    """Compute KL divergence to another distribution.

    Args:
        other: Another CategoricalDistribution with same categories.

    Returns:
        KL(self || other) in nats.
    """
    if set(self.categories) != set(other.categories):
        raise ValueError("Distributions must have same categories for KL divergence")

    kl = 0.0
    for cat in self.categories:
        p = self.dist[cat]
        q = other.dist[cat]
        if p > 0:
            if q <= 0:
                return float("inf")
            kl += p * (math.log(p) - math.log(q))
    return kl

log_prob(category)

Get log probability of a category.

Parameters:

Name Type Description Default
category str

Category name.

required

Returns:

Type Description
float

log(P(category)). Returns -inf if category has 0 probability.

Source code in py/cogant/simulate/distributions.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def log_prob(self, category: str) -> float:
    """Get log probability of a category.

    Args:
        category: Category name.

    Returns:
        log(P(category)). Returns -inf if category has 0 probability.
    """
    if category not in self.dist:
        raise KeyError(f"Unknown category: {category}")
    prob = self.dist[category]
    if prob <= 0:
        return float("-inf")
    return math.log(prob)

sample()

Sample a category from the distribution.

Returns:

Type Description
str

A sampled category name.

Source code in py/cogant/simulate/distributions.py
50
51
52
53
54
55
56
def sample(self) -> str:
    """Sample a category from the distribution.

    Returns:
        A sampled category name.
    """
    return random.choices(self.categories, weights=self.probabilities, k=1)[0]

update(observation, likelihood)

Bayesian update: posterior ∝ likelihood × prior.

Parameters:

Name Type Description Default
observation str

The observed category.

required
likelihood CategoricalDistribution

P(observation | category) for each category.

required

Returns:

Type Description
CategoricalDistribution

Updated posterior distribution.

Source code in py/cogant/simulate/distributions.py
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
def update(
    self, observation: str, likelihood: "CategoricalDistribution"
) -> "CategoricalDistribution":
    """Bayesian update: posterior ∝ likelihood × prior.

    Args:
        observation: The observed category.
        likelihood: P(observation | category) for each category.

    Returns:
        Updated posterior distribution.
    """
    if observation not in likelihood.categories:
        raise ValueError(f"Observation {observation} not in likelihood categories")

    # Posterior ∝ likelihood(obs|cat) × prior(cat)
    posterior_unnormalized = []
    for cat in self.categories:
        prior_cat = self.dist[cat]
        # P(obs | cat) from likelihood
        likelihood_obs_given_cat = likelihood.dist.get(cat, 1e-10)
        posterior_unnormalized.append(prior_cat * likelihood_obs_given_cat)

    # Normalize
    total = sum(posterior_unnormalized)
    if total <= 0:
        # If no valid posterior, return prior (avoid division by zero)
        return CategoricalDistribution(self.categories, self.probabilities)

    posterior_probs = [p / total for p in posterior_unnormalized]
    return CategoricalDistribution(self.categories, posterior_probs)

FreeEnergyCalculator

Calculate from compiled matrices, preserving the state's declared axis order.

Source code in py/cogant/simulate/free_energy.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
class FreeEnergyCalculator:
    """Calculate from compiled matrices, preserving the state's declared axis order."""

    def __init__(self, state_space: StateSpaceModel, matrices: CategoricalModel | None = None):
        self.state_space = state_space
        self.states = list(state_space.variables)
        self.actions = list(state_space.actions)
        self.observations = list(state_space.observations)
        if matrices is None:
            raise ValueError("FreeEnergyCalculator requires explicit A/B/C/D matrices")
        self.model = matrices

    def _beliefs(self, beliefs: CategoricalDistribution) -> list[float]:
        if set(beliefs.categories) != set(self.states):
            raise ValueError("belief categories must match the model state axis")
        return [beliefs.dist[state] for state in self.states]

    def _likelihood(
        self, likelihood_model: dict[str, CategoricalDistribution] | None
    ) -> Sequence[Sequence[float]]:
        if likelihood_model is None:
            return self.model.A
        if set(likelihood_model) != set(self.observations):
            raise ValueError("likelihood keys must match the observation axis")
        return [self._beliefs(likelihood_model[o]) for o in self.observations]

    def variational_free_energy(
        self,
        beliefs: CategoricalDistribution,
        observation: str,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Evaluate posterior free energy against the model's initial prior D."""
        observation_index = self.observations.index(observation)
        observed = [float(i == observation_index) for i in range(len(self.observations))]
        return categorical_vfe(
            self._beliefs(beliefs), self.model.D, self._likelihood(likelihood_model), observed
        )

    def expected_free_energy(
        self,
        beliefs: CategoricalDistribution,
        policy: list[str],
        horizon: int = 3,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Sum the specified candidate policy up to a positive finite horizon."""
        if horizon <= 0:
            raise ValueError("horizon must be positive")
        model = CategoricalModel(
            self._likelihood(likelihood_model), self.model.B, self.model.C, self.model.D
        )
        return model.score(
            self._beliefs(beliefs), [self.actions.index(a) for a in policy[:horizon]]
        )

    def surprisal(
        self,
        observation: str,
        beliefs: CategoricalDistribution,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Return negative log marginal evidence of the observation."""
        import math

        row = self._likelihood(likelihood_model)[self.observations.index(observation)]
        evidence = sum(p * a for p, a in zip(self._beliefs(beliefs), row, strict=True))
        return -math.log(evidence) if evidence > 0 else math.inf

    def complexity(
        self, posterior: CategoricalDistribution, prior: CategoricalDistribution | None = None
    ) -> float:
        """Return KL(q || prior), using the model D when no prior is supplied."""
        from cogant.runtime.categorical import kl_divergence

        reference = self.model.D if prior is None else self._beliefs(prior)
        return kl_divergence(self._beliefs(posterior), reference)

    def accuracy(
        self,
        observation: str,
        beliefs: CategoricalDistribution,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Return expected log likelihood for the observed outcome."""
        return self.complexity(beliefs) - self.variational_free_energy(
            beliefs, observation, likelihood_model
        )

    def policy_ranking(
        self,
        beliefs: CategoricalDistribution,
        available_actions: list[str],
        horizon: int = 3,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> list[tuple[str, float]]:
        """Rank candidate one-action policies by risk plus ambiguity, stably."""
        return sorted(
            [
                (a, self.expected_free_energy(beliefs, [a], horizon, likelihood_model))
                for a in available_actions
            ],
            key=lambda item: item[1],
        )

    def _predict_beliefs(
        self, beliefs: CategoricalDistribution, action: str
    ) -> CategoricalDistribution:
        predicted = self.model.predict(self._beliefs(beliefs), self.actions.index(action))
        return CategoricalDistribution(self.states, predicted)

accuracy(observation, beliefs, likelihood_model=None)

Return expected log likelihood for the observed outcome.

Source code in py/cogant/simulate/free_energy.py
131
132
133
134
135
136
137
138
139
140
def accuracy(
    self,
    observation: str,
    beliefs: CategoricalDistribution,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Return expected log likelihood for the observed outcome."""
    return self.complexity(beliefs) - self.variational_free_energy(
        beliefs, observation, likelihood_model
    )

complexity(posterior, prior=None)

Return KL(q || prior), using the model D when no prior is supplied.

Source code in py/cogant/simulate/free_energy.py
122
123
124
125
126
127
128
129
def complexity(
    self, posterior: CategoricalDistribution, prior: CategoricalDistribution | None = None
) -> float:
    """Return KL(q || prior), using the model D when no prior is supplied."""
    from cogant.runtime.categorical import kl_divergence

    reference = self.model.D if prior is None else self._beliefs(prior)
    return kl_divergence(self._beliefs(posterior), reference)

expected_free_energy(beliefs, policy, horizon=3, likelihood_model=None)

Sum the specified candidate policy up to a positive finite horizon.

Source code in py/cogant/simulate/free_energy.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def expected_free_energy(
    self,
    beliefs: CategoricalDistribution,
    policy: list[str],
    horizon: int = 3,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Sum the specified candidate policy up to a positive finite horizon."""
    if horizon <= 0:
        raise ValueError("horizon must be positive")
    model = CategoricalModel(
        self._likelihood(likelihood_model), self.model.B, self.model.C, self.model.D
    )
    return model.score(
        self._beliefs(beliefs), [self.actions.index(a) for a in policy[:horizon]]
    )

policy_ranking(beliefs, available_actions, horizon=3, likelihood_model=None)

Rank candidate one-action policies by risk plus ambiguity, stably.

Source code in py/cogant/simulate/free_energy.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def policy_ranking(
    self,
    beliefs: CategoricalDistribution,
    available_actions: list[str],
    horizon: int = 3,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> list[tuple[str, float]]:
    """Rank candidate one-action policies by risk plus ambiguity, stably."""
    return sorted(
        [
            (a, self.expected_free_energy(beliefs, [a], horizon, likelihood_model))
            for a in available_actions
        ],
        key=lambda item: item[1],
    )

surprisal(observation, beliefs, likelihood_model=None)

Return negative log marginal evidence of the observation.

Source code in py/cogant/simulate/free_energy.py
109
110
111
112
113
114
115
116
117
118
119
120
def surprisal(
    self,
    observation: str,
    beliefs: CategoricalDistribution,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Return negative log marginal evidence of the observation."""
    import math

    row = self._likelihood(likelihood_model)[self.observations.index(observation)]
    evidence = sum(p * a for p, a in zip(self._beliefs(beliefs), row, strict=True))
    return -math.log(evidence) if evidence > 0 else math.inf

variational_free_energy(beliefs, observation, likelihood_model=None)

Evaluate posterior free energy against the model's initial prior D.

Source code in py/cogant/simulate/free_energy.py
79
80
81
82
83
84
85
86
87
88
89
90
def variational_free_energy(
    self,
    beliefs: CategoricalDistribution,
    observation: str,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Evaluate posterior free energy against the model's initial prior D."""
    observation_index = self.observations.index(observation)
    observed = [float(i == observation_index) for i in range(len(self.observations))]
    return categorical_vfe(
        self._beliefs(beliefs), self.model.D, self._likelihood(likelihood_model), observed
    )

ModelRunner

Bind structural axis names to complete A/B/C/D categorical matrices.

Source code in py/cogant/simulate/runner.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 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
class ModelRunner:
    """Bind structural axis names to complete A/B/C/D categorical matrices."""

    def __init__(
        self,
        seed: int | None = None,
        model: StateSpaceModel | None = None,
        A: list[list[float]] | None = None,
        B: list[list[list[float]]] | None = None,
        C: list[float] | None = None,
        D: list[float] | None = None,
    ):
        self.model = model
        self.A, self.B, self.C, self.D = A, B, C, D
        if any(value is not None for value in (A, B, C, D)):
            self._matrices()

    @property
    def has_generative_model(self) -> bool:
        return all(value is not None for value in (self.A, self.B, self.C, self.D))

    def _matrices(self) -> CategoricalModel:
        if self.A is None or self.B is None or self.C is None or self.D is None:
            raise RuntimeError("inference requires A, B, C, and D matrices on the runner")
        return CategoricalModel(self.A, self.B, self.C, self.D)

    def _axes(self) -> tuple[list[str], list[str], list[str]]:
        if self.model is None:
            raise ValueError("named inference requires a bound StateSpaceModel")
        matrix = self._matrices()
        axes = (list(self.model.variables), list(self.model.observations), list(self.model.actions))
        if tuple(map(len, axes)) != (len(matrix.D), len(matrix.A), matrix.n_actions):
            raise ValueError("structural axes do not match the supplied matrices")
        return axes

    def _vector(self, beliefs: dict[str, float]) -> list[float]:
        states, _, _ = self._axes()
        if set(beliefs) != set(states):
            raise ValueError("belief keys must match the declared state axis")
        return [beliefs[state] for state in states]

    def validate_model(self, state_space: StateSpaceModel) -> dict[str, Any]:
        """
        Check that model is well-formed.

        Validates:
        - All transitions reference valid states and actions
        - All actions reference valid variables
        - State space is connected
        - No dangling references

        Args:
            state_space: StateSpaceModel to validate.

        Returns:
            Dict with "valid" (bool), "errors" (list), "warnings" (list).
        """
        errors: list[str] = []
        warnings: list[str] = []
        valid = True

        # Check variables exist
        if not state_space.variables:
            errors.append("No state variables defined")
            valid = False

        # Check transitions reference valid states
        for trans_id, trans in state_space.transitions.items():
            if trans.action_id and trans.action_id not in state_space.actions:
                errors.append(f"Transition {trans_id} references unknown action {trans.action_id}")
                valid = False

        # Check actions reference valid variables
        for action_id, action in state_space.actions.items():
            for var_id in action.effects:
                if var_id not in state_space.variables:
                    errors.append(f"Action {action_id} references unknown variable {var_id}")
                    valid = False
            for var_id in action.preconditions:
                if var_id not in state_space.variables:
                    errors.append(
                        f"Action {action_id} precondition references unknown variable {var_id}"
                    )
                    valid = False

        # Check observations reference valid nodes
        for obs_id, obs in state_space.observations.items():
            if not obs.source_node_id:
                warnings.append(f"Observation {obs_id} has no source node")

        # Check likelihoods reference valid variables
        for like_id, like in state_space.likelihoods.items():
            if like.variable_id not in state_space.variables:
                errors.append(
                    f"Likelihood {like_id} references unknown variable {like.variable_id}"
                )
                valid = False

        # Check preferences reference valid variables
        for pref_id, pref in state_space.preferences.items():
            for var_id in pref.scope:
                if var_id not in state_space.variables:
                    errors.append(f"Preference {pref_id} references unknown variable {var_id}")
                    valid = False

        return {
            "valid": valid,
            "errors": errors,
            "warnings": warnings,
            "variable_count": len(state_space.variables),
            "action_count": len(state_space.actions),
            "transition_count": len(state_space.transitions),
        }

    def vfe_from_beliefs(
        self,
        beliefs: list[float],
        observation: list[float] | None = None,
        prior: list[float] | None = None,
    ) -> float:
        matrix = self._matrices()
        return variational_free_energy(
            beliefs, matrix.D if prior is None else prior, matrix.A, observation
        )

    def efe_for_policy(
        self, policy_action_sequence: list[int], beliefs: list[float] | None = None
    ) -> float:
        matrix = self._matrices()
        return matrix.score(matrix.D if beliefs is None else beliefs, policy_action_sequence)

    def update_beliefs_from_observation(
        self, prior: list[float], observation_index: int
    ) -> list[float]:
        return posterior(prior, self._matrices().A, observation_index)

    def compute_free_energy(self, state: dict[str, Any], observation: str) -> float:
        _, observations, _ = self._axes()
        return self.vfe_from_beliefs(
            self._vector(state), [float(o == observation) for o in observations]
        )

    def belief_update(self, prior_beliefs: dict[str, float], observation: str) -> dict[str, float]:
        states, observations, _ = self._axes()
        updated = self.update_beliefs_from_observation(
            self._vector(prior_beliefs), observations.index(observation)
        )
        return dict(zip(states, updated, strict=True))

    def policy_evaluation(
        self, beliefs: dict[str, float], available_actions: list[str]
    ) -> list[tuple[str, float]]:
        _, _, actions = self._axes()
        q = self._vector(beliefs)
        return sorted(
            [(a, self.efe_for_policy([actions.index(a)], q)) for a in available_actions],
            key=lambda item: item[1],
        )

    def active_inference_step(
        self, beliefs: dict[str, float], observation: str, state_space: StateSpaceModel
    ) -> dict[str, Any]:
        self.model = state_space
        states, observations, actions = self._axes()
        matrices = self._matrices()
        runtime = AgentRuntime(matrices)
        result = runtime.step(self._vector(beliefs), observations.index(observation))
        return {
            "new_beliefs": dict(zip(states, result.posterior, strict=True)),
            "selected_action": actions[result.action],
            "predicted_next_state": dict(zip(states, result.state_dist, strict=True)),
            "free_energy": result.free_energy,
            "efe_ranking": sorted(
                zip(actions, result.policy_scores, strict=True), key=lambda x: x[1]
            ),
        }

    def simulate_step(
        self, state_space: StateSpaceModel, current_state: dict[str, Any], action_id: str
    ) -> dict[str, Any]:
        self.model = state_space
        states, _, actions = self._axes()
        prediction = self._matrices().predict(self._vector(current_state), actions.index(action_id))
        return {
            "next_state": dict(zip(states, prediction, strict=True)),
            "action_applied": action_id,
            "success": True,
        }

    def run_active_inference(
        self, state_space: StateSpaceModel, steps: int = 20
    ) -> list[dict[str, Any]]:
        self.model = state_space
        states, observations, _ = self._axes()
        matrix = self._matrices()
        belief = dict(zip(states, matrix.D, strict=True))
        trace = [
            {
                "step": 0,
                "phase": "initial",
                "beliefs": belief.copy(),
                "observation": None,
                "action": None,
                "free_energy": None,
                "predicted_state": {},
            }
        ]
        if steps < 0:
            raise ValueError("step count must be non-negative")
        for t in range(1, steps + 1):
            outcomes = matrix.observe(self._vector(belief))
            obs = observations[max(range(len(outcomes)), key=outcomes.__getitem__)]
            result = self.active_inference_step(belief, obs, state_space)
            trace.append(
                {
                    "step": t,
                    "phase": "observation",
                    "beliefs": result["new_beliefs"],
                    "observation": obs,
                    "action": result["selected_action"],
                    "free_energy": result["free_energy"],
                    "predicted_state": result["predicted_next_state"],
                }
            )
            belief = result["predicted_next_state"]
        return trace

    def run_simulation(self, state_space: StateSpaceModel, steps: int = 10) -> list[dict[str, Any]]:
        return self.run_active_inference(state_space, steps)

    def generate_report(self, trace: list[dict[str, Any]]) -> str:
        return generate_report(trace)

    def generate_trace(self, state_space: StateSpaceModel) -> dict[str, Any]:
        return {
            "schema_name": state_space.schema_name,
            "trace": self.run_active_inference(state_space, 5),
            "variables": list(state_space.variables),
            "observations": list(state_space.observations),
            "actions": list(state_space.actions),
            "metadata": state_space.metadata,
        }

validate_model(state_space)

Check that model is well-formed.

Validates: - All transitions reference valid states and actions - All actions reference valid variables - State space is connected - No dangling references

Parameters:

Name Type Description Default
state_space StateSpaceModel

StateSpaceModel to validate.

required

Returns:

Type Description
dict[str, Any]

Dict with "valid" (bool), "errors" (list), "warnings" (list).

Source code in py/cogant/simulate/runner.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def validate_model(self, state_space: StateSpaceModel) -> dict[str, Any]:
    """
    Check that model is well-formed.

    Validates:
    - All transitions reference valid states and actions
    - All actions reference valid variables
    - State space is connected
    - No dangling references

    Args:
        state_space: StateSpaceModel to validate.

    Returns:
        Dict with "valid" (bool), "errors" (list), "warnings" (list).
    """
    errors: list[str] = []
    warnings: list[str] = []
    valid = True

    # Check variables exist
    if not state_space.variables:
        errors.append("No state variables defined")
        valid = False

    # Check transitions reference valid states
    for trans_id, trans in state_space.transitions.items():
        if trans.action_id and trans.action_id not in state_space.actions:
            errors.append(f"Transition {trans_id} references unknown action {trans.action_id}")
            valid = False

    # Check actions reference valid variables
    for action_id, action in state_space.actions.items():
        for var_id in action.effects:
            if var_id not in state_space.variables:
                errors.append(f"Action {action_id} references unknown variable {var_id}")
                valid = False
        for var_id in action.preconditions:
            if var_id not in state_space.variables:
                errors.append(
                    f"Action {action_id} precondition references unknown variable {var_id}"
                )
                valid = False

    # Check observations reference valid nodes
    for obs_id, obs in state_space.observations.items():
        if not obs.source_node_id:
            warnings.append(f"Observation {obs_id} has no source node")

    # Check likelihoods reference valid variables
    for like_id, like in state_space.likelihoods.items():
        if like.variable_id not in state_space.variables:
            errors.append(
                f"Likelihood {like_id} references unknown variable {like.variable_id}"
            )
            valid = False

    # Check preferences reference valid variables
    for pref_id, pref in state_space.preferences.items():
        for var_id in pref.scope:
            if var_id not in state_space.variables:
                errors.append(f"Preference {pref_id} references unknown variable {var_id}")
                valid = False

    return {
        "valid": valid,
        "errors": errors,
        "warnings": warnings,
        "variable_count": len(state_space.variables),
        "action_count": len(state_space.actions),
        "transition_count": len(state_space.transitions),
    }

SimulationVisualizer

Generate visualizations of simulation traces.

Source code in py/cogant/simulate/visualization.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
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
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
class SimulationVisualizer:
    """Generate visualizations of simulation traces."""

    def __init__(self) -> None:
        """Initialize the visualizer."""
        pass

    def plot_free_energy_trajectory(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG plot of free energy over time.

        Args:
            trace: List of simulation steps, each with 'free_energy' key.

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Extract free energy values
        samples = [step for step in trace if step.get("phase") != "initial"]
        fe_values = [observed_free_energy(step.get("free_energy")) for step in samples]

        if not fe_values:
            return self._empty_svg("No free energy data")

        # Compute bounds
        min_fe = min(fe_values)
        max_fe = max(fe_values)
        range_fe = max_fe - min_fe if max_fe != min_fe else 1.0

        # SVG parameters
        width, height = 800, 400
        margin = 60
        plot_width = width - 2 * margin
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .grid { stroke: #ddd; stroke-width: 0.5; }",
            "  .line { stroke: #0066cc; stroke-width: 2; fill: none; }",
            "  .point { fill: #0066cc; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Free Energy Trajectory</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw grid and labels
        n_steps = len(fe_values)
        for i, sample in enumerate(samples):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            svg_lines.append(
                f'<line x1="{x}" y1="{height - margin}" x2="{x}" y2="{height - margin + 3}" class="axis"/>'
            )
            if i % max(1, n_steps // 5) == 0:
                svg_lines.append(
                    f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{sample.get("step", i)}</text>'
                )

        # Draw free energy line
        if len(fe_values) > 1:
            path_parts = []
            for i, fe in enumerate(fe_values):
                x = margin + (i / (n_steps - 1)) * plot_width
                y = height - margin - ((fe - min_fe) / range_fe) * plot_height
                if i == 0:
                    path_parts.append(f"M {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")
            svg_lines.append(f'<path d="{" ".join(path_parts)}" class="line"/>')

        # Draw points
        for i, fe in enumerate(fe_values):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            y = height - margin - ((fe - min_fe) / range_fe) * plot_height
            svg_lines.append(
                f'<circle cx="{x}" cy="{y}" r="3" class="point" opacity="0.6" data-step="{samples[i].get("step", i)}" data-free-energy="{fe}"/>'
            )

        # Draw y-axis labels
        for i in range(5):
            fe_label = min_fe + (i / 4) * range_fe
            y = height - margin - (i / 4) * plot_height
            svg_lines.append(
                f'<text x="{margin - 10}" y="{y + 3}" text-anchor="end" class="text">{fe_label:.2f}</text>'
            )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def plot_belief_evolution(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG showing belief evolution over time.

        Args:
            trace: List of simulation steps, each with 'beliefs' key (dict of state -> prob).

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Extract beliefs
        all_states: set[str] = set()
        belief_history = []

        for step in trace:
            beliefs = step.get("beliefs", {})
            if isinstance(beliefs, dict):
                belief_history.append(beliefs)
                all_states.update(beliefs.keys())
            else:
                belief_history.append({})

        if not belief_history or not all_states:
            return self._empty_svg("No belief data")

        states = sorted(all_states)
        colors = self._generate_colors(len(states))

        # SVG parameters
        width, height = 900, 400
        margin = 60
        plot_width = width - 2 * margin
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "  .legend { font-family: Arial; font-size: 11px; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Belief Evolution</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw stacked area chart
        n_steps = len(belief_history)
        for state_idx, _state in enumerate(states):
            cumulative = [0.0] * n_steps
            for i in range(n_steps):
                beliefs = belief_history[i]
                cumulative[i] = sum(beliefs.get(s, 0.0) for s in states[: state_idx + 1])

            # Generate path for this state
            path_parts = []
            for i in range(n_steps):
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                y = height - margin - (cumulative[i] * plot_height)
                if i == 0:
                    path_parts.append(f"M {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")

            # Close path
            for i in range(n_steps - 1, -1, -1):
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                if state_idx == 0:
                    y = height - margin
                else:
                    prev_cumulative = sum(belief_history[i].get(s, 0.0) for s in states[:state_idx])
                    y = height - margin - (prev_cumulative * plot_height)
                if i == n_steps - 1:
                    path_parts.append(f"L {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")

            path_parts.append("Z")
            color = colors[state_idx]
            svg_lines.append(f'<path d="{" ".join(path_parts)}" fill="{color}" opacity="0.7"/>')

        # Add legend
        legend_x = width - 150
        for state_idx, state in enumerate(states):
            y = margin + 20 + state_idx * 18
            color = colors[state_idx]
            svg_lines.append(
                f'<rect x="{legend_x}" y="{y - 10}" width="12" height="12" fill="{color}"/>'
            )
            svg_lines.append(
                f'<text x="{legend_x + 18}" y="{y}" class="legend">{state[:15]}</text>'
            )

        # X-axis labels
        for i in range(n_steps):
            if i % max(1, n_steps // 5) == 0:
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                svg_lines.append(
                    f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{i}</text>'
                )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def plot_action_distribution(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG bar chart of actions taken.

        Args:
            trace: List of simulation steps, each with 'action' key.

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Count actions
        action_counts: dict[str, int] = defaultdict(int)
        for step in trace:
            action = step.get("action")
            if action:
                action_counts[action] += 1

        if not action_counts:
            return self._empty_svg("No action data")

        actions = sorted(action_counts.keys())
        counts = [action_counts[a] for a in actions]
        max_count = max(counts) if counts else 1

        # SVG parameters
        bar_width = 40
        spacing = 20
        width = len(actions) * (bar_width + spacing) + 100
        height = 400
        margin = 60
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .bar { fill: #0066cc; }",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Action Distribution</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw bars
        for i, action in enumerate(actions):
            count = action_counts[action]
            bar_height = (count / max_count) * plot_height if max_count > 0 else 0
            x = margin + i * (bar_width + spacing) + spacing // 2
            y = height - margin - bar_height

            svg_lines.append(
                f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" class="bar"/>'
            )
            svg_lines.append(
                f'<text x="{x + bar_width / 2}" y="{height - margin + 20}" text-anchor="middle" class="text">{action[:10]}</text>'
            )
            svg_lines.append(
                f'<text x="{x + bar_width / 2}" y="{y - 5}" text-anchor="middle" class="text">{count}</text>'
            )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def generate_mermaid_trajectory(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate Mermaid sequence diagram of state transitions.

        Args:
            trace: List of simulation steps.

        Returns:
            Mermaid diagram string.
        """
        if not trace or len(trace) < 2:
            return "graph LR\n  A[No transitions]"

        lines = ["sequenceDiagram"]
        lines.append("  participant Agent")
        lines.append("  participant Environment")

        for i in range(len(trace) - 1):
            current = trace[i]
            next_step = trace[i + 1]

            state = current.get("state", f"s{i}")
            action = next_step.get("action", "wait")
            next_state = next_step.get("state", f"s{i + 1}")

            # Format state info
            state_str = str(state)[:20]
            action_str = str(action)[:15]
            next_state_str = str(next_state)[:20]

            lines.append(f"  Agent->>Environment: {action_str} @ {state_str}")
            lines.append(f"  Environment->>Agent: → {next_state_str}")

        return "\n".join(lines)

    def generate_html_report(self, trace: list[dict[str, Any]], state_space: Any) -> str:
        """
        Generate full HTML report of simulation.

        Args:
            trace: List of simulation steps.
            state_space: The state space model (for metadata).

        Returns:
            HTML string.
        """
        # Generate individual visualizations
        fe_plot = self.plot_free_energy_trajectory(trace)
        belief_plot = self.plot_belief_evolution(trace)
        action_plot = self.plot_action_distribution(trace)
        mermaid_diagram = self.generate_mermaid_trajectory(trace)

        html_lines = [
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "  <meta charset='utf-8'>",
            "  <title>Active Inference Simulation Report</title>",
            "  <script src='https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js'></script>",
            "  <style>",
            "    body { font-family: Arial; margin: 20px; background: #f5f5f5; }",
            "    .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; }",
            "    h1 { color: #333; }",
            "    .section { margin: 30px 0; }",
            "    .plot { border: 1px solid #ddd; padding: 10px; margin: 10px 0; }",
            "    .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }",
            "    .stat-box { background: #f9f9f9; padding: 15px; border-radius: 5px; }",
            "    .stat-value { font-size: 24px; font-weight: bold; color: #0066cc; }",
            "    .stat-label { color: #666; margin-top: 5px; }",
            "  </style>",
            "</head>",
            "<body>",
            "  <div class='container'>",
            "    <h1>Active Inference Simulation Report</h1>",
            f"    <p>Generated for state space: {state_space.schema_name if hasattr(state_space, 'schema_name') else 'Unknown'}</p>",
        ]

        executed = [step for step in trace if step.get("phase") != "initial"]
        # Statistics
        html_lines.extend(
            [
                "    <div class='section stats'>",
                f"      <div class='stat-box'><div class='stat-value'>{len(executed)}</div><div class='stat-label'>Steps</div></div>",
                f"      <div class='stat-box'><div class='stat-value'>{len({s.get('action') for s in trace if s.get('action')})}</div><div class='stat-label'>Unique Actions</div></div>",
            ]
        )

        # Add mean free energy if available
        fe_values = [observed_free_energy(s.get("free_energy")) for s in executed]
        if fe_values:
            mean_fe = sum(fe_values) / len(fe_values)
            html_lines.append(
                f"      <div class='stat-box'><div class='stat-value'>{mean_fe:.3f}</div><div class='stat-label'>Mean Free Energy</div></div>"
            )

        html_lines.append("    </div>")

        # Plots
        html_lines.extend(
            [
                "    <div class='section'>",
                "      <h2>Free Energy Trajectory</h2>",
                f"      <div class='plot'>{fe_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>Belief Evolution</h2>",
                f"      <div class='plot'>{belief_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>Action Distribution</h2>",
                f"      <div class='plot'>{action_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>State Transition Sequence</h2>",
                f"      <div class='mermaid'>{mermaid_diagram}</div>",
                "    </div>",
                "  </div>",
                "  <script>mermaid.initialize({{ startOnLoad: true }}); mermaid.contentLoaded();</script>",
                "</body>",
                "</html>",
            ]
        )

        return "\n".join(html_lines)

    @staticmethod
    def _empty_svg(message: str) -> str:
        """Generate an empty SVG with a message."""
        return f"""<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
  <text x="200" y="100" text-anchor="middle" font-size="16" fill="#999">{message}</text>
</svg>"""

    @staticmethod
    def _generate_colors(n: int) -> list[str]:
        """Generate n distinct colors."""
        colors = [
            "#FF6B6B",
            "#4ECDC4",
            "#45B7D1",
            "#FFA07A",
            "#98D8C8",
            "#F7DC6F",
            "#BB8FCE",
            "#85C1E2",
        ]
        if n <= len(colors):
            return colors[:n]

        # Generate additional colors
        result = colors.copy()
        for i in range(n - len(colors)):
            hue = (i * 360) / (n - len(colors))
            # Simple HSL to hex conversion
            result.append(f"hsl({hue}, 70%, 50%)")

        return result

__init__()

Initialize the visualizer.

Source code in py/cogant/simulate/visualization.py
16
17
18
def __init__(self) -> None:
    """Initialize the visualizer."""
    pass

generate_html_report(trace, state_space)

Generate full HTML report of simulation.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps.

required
state_space Any

The state space model (for metadata).

required

Returns:

Type Description
str

HTML string.

Source code in py/cogant/simulate/visualization.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def generate_html_report(self, trace: list[dict[str, Any]], state_space: Any) -> str:
    """
    Generate full HTML report of simulation.

    Args:
        trace: List of simulation steps.
        state_space: The state space model (for metadata).

    Returns:
        HTML string.
    """
    # Generate individual visualizations
    fe_plot = self.plot_free_energy_trajectory(trace)
    belief_plot = self.plot_belief_evolution(trace)
    action_plot = self.plot_action_distribution(trace)
    mermaid_diagram = self.generate_mermaid_trajectory(trace)

    html_lines = [
        "<!DOCTYPE html>",
        "<html>",
        "<head>",
        "  <meta charset='utf-8'>",
        "  <title>Active Inference Simulation Report</title>",
        "  <script src='https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js'></script>",
        "  <style>",
        "    body { font-family: Arial; margin: 20px; background: #f5f5f5; }",
        "    .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; }",
        "    h1 { color: #333; }",
        "    .section { margin: 30px 0; }",
        "    .plot { border: 1px solid #ddd; padding: 10px; margin: 10px 0; }",
        "    .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }",
        "    .stat-box { background: #f9f9f9; padding: 15px; border-radius: 5px; }",
        "    .stat-value { font-size: 24px; font-weight: bold; color: #0066cc; }",
        "    .stat-label { color: #666; margin-top: 5px; }",
        "  </style>",
        "</head>",
        "<body>",
        "  <div class='container'>",
        "    <h1>Active Inference Simulation Report</h1>",
        f"    <p>Generated for state space: {state_space.schema_name if hasattr(state_space, 'schema_name') else 'Unknown'}</p>",
    ]

    executed = [step for step in trace if step.get("phase") != "initial"]
    # Statistics
    html_lines.extend(
        [
            "    <div class='section stats'>",
            f"      <div class='stat-box'><div class='stat-value'>{len(executed)}</div><div class='stat-label'>Steps</div></div>",
            f"      <div class='stat-box'><div class='stat-value'>{len({s.get('action') for s in trace if s.get('action')})}</div><div class='stat-label'>Unique Actions</div></div>",
        ]
    )

    # Add mean free energy if available
    fe_values = [observed_free_energy(s.get("free_energy")) for s in executed]
    if fe_values:
        mean_fe = sum(fe_values) / len(fe_values)
        html_lines.append(
            f"      <div class='stat-box'><div class='stat-value'>{mean_fe:.3f}</div><div class='stat-label'>Mean Free Energy</div></div>"
        )

    html_lines.append("    </div>")

    # Plots
    html_lines.extend(
        [
            "    <div class='section'>",
            "      <h2>Free Energy Trajectory</h2>",
            f"      <div class='plot'>{fe_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>Belief Evolution</h2>",
            f"      <div class='plot'>{belief_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>Action Distribution</h2>",
            f"      <div class='plot'>{action_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>State Transition Sequence</h2>",
            f"      <div class='mermaid'>{mermaid_diagram}</div>",
            "    </div>",
            "  </div>",
            "  <script>mermaid.initialize({{ startOnLoad: true }}); mermaid.contentLoaded();</script>",
            "</body>",
            "</html>",
        ]
    )

    return "\n".join(html_lines)

generate_mermaid_trajectory(trace)

Generate Mermaid sequence diagram of state transitions.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps.

required

Returns:

Type Description
str

Mermaid diagram string.

Source code in py/cogant/simulate/visualization.py
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
def generate_mermaid_trajectory(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate Mermaid sequence diagram of state transitions.

    Args:
        trace: List of simulation steps.

    Returns:
        Mermaid diagram string.
    """
    if not trace or len(trace) < 2:
        return "graph LR\n  A[No transitions]"

    lines = ["sequenceDiagram"]
    lines.append("  participant Agent")
    lines.append("  participant Environment")

    for i in range(len(trace) - 1):
        current = trace[i]
        next_step = trace[i + 1]

        state = current.get("state", f"s{i}")
        action = next_step.get("action", "wait")
        next_state = next_step.get("state", f"s{i + 1}")

        # Format state info
        state_str = str(state)[:20]
        action_str = str(action)[:15]
        next_state_str = str(next_state)[:20]

        lines.append(f"  Agent->>Environment: {action_str} @ {state_str}")
        lines.append(f"  Environment->>Agent: → {next_state_str}")

    return "\n".join(lines)

plot_action_distribution(trace)

Generate SVG bar chart of actions taken.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'action' key.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
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
def plot_action_distribution(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG bar chart of actions taken.

    Args:
        trace: List of simulation steps, each with 'action' key.

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Count actions
    action_counts: dict[str, int] = defaultdict(int)
    for step in trace:
        action = step.get("action")
        if action:
            action_counts[action] += 1

    if not action_counts:
        return self._empty_svg("No action data")

    actions = sorted(action_counts.keys())
    counts = [action_counts[a] for a in actions]
    max_count = max(counts) if counts else 1

    # SVG parameters
    bar_width = 40
    spacing = 20
    width = len(actions) * (bar_width + spacing) + 100
    height = 400
    margin = 60
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .bar { fill: #0066cc; }",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Action Distribution</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw bars
    for i, action in enumerate(actions):
        count = action_counts[action]
        bar_height = (count / max_count) * plot_height if max_count > 0 else 0
        x = margin + i * (bar_width + spacing) + spacing // 2
        y = height - margin - bar_height

        svg_lines.append(
            f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" class="bar"/>'
        )
        svg_lines.append(
            f'<text x="{x + bar_width / 2}" y="{height - margin + 20}" text-anchor="middle" class="text">{action[:10]}</text>'
        )
        svg_lines.append(
            f'<text x="{x + bar_width / 2}" y="{y - 5}" text-anchor="middle" class="text">{count}</text>'
        )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)

plot_belief_evolution(trace)

Generate SVG showing belief evolution over time.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'beliefs' key (dict of state -> prob).

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
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
def plot_belief_evolution(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG showing belief evolution over time.

    Args:
        trace: List of simulation steps, each with 'beliefs' key (dict of state -> prob).

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Extract beliefs
    all_states: set[str] = set()
    belief_history = []

    for step in trace:
        beliefs = step.get("beliefs", {})
        if isinstance(beliefs, dict):
            belief_history.append(beliefs)
            all_states.update(beliefs.keys())
        else:
            belief_history.append({})

    if not belief_history or not all_states:
        return self._empty_svg("No belief data")

    states = sorted(all_states)
    colors = self._generate_colors(len(states))

    # SVG parameters
    width, height = 900, 400
    margin = 60
    plot_width = width - 2 * margin
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "  .legend { font-family: Arial; font-size: 11px; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Belief Evolution</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw stacked area chart
    n_steps = len(belief_history)
    for state_idx, _state in enumerate(states):
        cumulative = [0.0] * n_steps
        for i in range(n_steps):
            beliefs = belief_history[i]
            cumulative[i] = sum(beliefs.get(s, 0.0) for s in states[: state_idx + 1])

        # Generate path for this state
        path_parts = []
        for i in range(n_steps):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            y = height - margin - (cumulative[i] * plot_height)
            if i == 0:
                path_parts.append(f"M {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")

        # Close path
        for i in range(n_steps - 1, -1, -1):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            if state_idx == 0:
                y = height - margin
            else:
                prev_cumulative = sum(belief_history[i].get(s, 0.0) for s in states[:state_idx])
                y = height - margin - (prev_cumulative * plot_height)
            if i == n_steps - 1:
                path_parts.append(f"L {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")

        path_parts.append("Z")
        color = colors[state_idx]
        svg_lines.append(f'<path d="{" ".join(path_parts)}" fill="{color}" opacity="0.7"/>')

    # Add legend
    legend_x = width - 150
    for state_idx, state in enumerate(states):
        y = margin + 20 + state_idx * 18
        color = colors[state_idx]
        svg_lines.append(
            f'<rect x="{legend_x}" y="{y - 10}" width="12" height="12" fill="{color}"/>'
        )
        svg_lines.append(
            f'<text x="{legend_x + 18}" y="{y}" class="legend">{state[:15]}</text>'
        )

    # X-axis labels
    for i in range(n_steps):
        if i % max(1, n_steps // 5) == 0:
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            svg_lines.append(
                f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{i}</text>'
            )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)

plot_free_energy_trajectory(trace)

Generate SVG plot of free energy over time.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'free_energy' key.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def plot_free_energy_trajectory(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG plot of free energy over time.

    Args:
        trace: List of simulation steps, each with 'free_energy' key.

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Extract free energy values
    samples = [step for step in trace if step.get("phase") != "initial"]
    fe_values = [observed_free_energy(step.get("free_energy")) for step in samples]

    if not fe_values:
        return self._empty_svg("No free energy data")

    # Compute bounds
    min_fe = min(fe_values)
    max_fe = max(fe_values)
    range_fe = max_fe - min_fe if max_fe != min_fe else 1.0

    # SVG parameters
    width, height = 800, 400
    margin = 60
    plot_width = width - 2 * margin
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .grid { stroke: #ddd; stroke-width: 0.5; }",
        "  .line { stroke: #0066cc; stroke-width: 2; fill: none; }",
        "  .point { fill: #0066cc; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Free Energy Trajectory</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw grid and labels
    n_steps = len(fe_values)
    for i, sample in enumerate(samples):
        x = margin + (i / max(1, n_steps - 1)) * plot_width
        svg_lines.append(
            f'<line x1="{x}" y1="{height - margin}" x2="{x}" y2="{height - margin + 3}" class="axis"/>'
        )
        if i % max(1, n_steps // 5) == 0:
            svg_lines.append(
                f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{sample.get("step", i)}</text>'
            )

    # Draw free energy line
    if len(fe_values) > 1:
        path_parts = []
        for i, fe in enumerate(fe_values):
            x = margin + (i / (n_steps - 1)) * plot_width
            y = height - margin - ((fe - min_fe) / range_fe) * plot_height
            if i == 0:
                path_parts.append(f"M {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")
        svg_lines.append(f'<path d="{" ".join(path_parts)}" class="line"/>')

    # Draw points
    for i, fe in enumerate(fe_values):
        x = margin + (i / max(1, n_steps - 1)) * plot_width
        y = height - margin - ((fe - min_fe) / range_fe) * plot_height
        svg_lines.append(
            f'<circle cx="{x}" cy="{y}" r="3" class="point" opacity="0.6" data-step="{samples[i].get("step", i)}" data-free-energy="{fe}"/>'
        )

    # Draw y-axis labels
    for i in range(5):
        fe_label = min_fe + (i / 4) * range_fe
        y = height - margin - (i / 4) * plot_height
        svg_lines.append(
            f'<text x="{margin - 10}" y="{y + 3}" text-anchor="end" class="text">{fe_label:.2f}</text>'
        )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)

TransitionMatrix

Transition probabilities between states under actions.

Source code in py/cogant/simulate/distributions.py
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
class TransitionMatrix:
    """Transition probabilities between states under actions."""

    def __init__(self, states: list[str], actions: list[str]):
        """
        Initialize a transition matrix.

        Args:
            states: List of state names.
            actions: List of action names.
        """
        self.states = states
        self.actions = actions
        # transitions[action][state] = CategoricalDistribution over next states
        self.transitions: dict[str, dict[str, CategoricalDistribution]] = {
            action: {} for action in actions
        }

    def set_transition(self, state: str, action: str, next_state: str, prob: float) -> None:
        """Set a single transition probability.

        Args:
            state: Current state.
            action: Action taken.
            next_state: Resulting state.
            prob: Probability of transition.
        """
        if state not in self.states:
            raise ValueError(f"Unknown state: {state}")
        if action not in self.actions:
            raise ValueError(f"Unknown action: {action}")
        if next_state not in self.states:
            raise ValueError(f"Unknown next_state: {next_state}")

        if state not in self.transitions[action]:
            # Create new distribution for this state (uniform)
            n = len(self.states)
            self.transitions[action][state] = CategoricalDistribution(self.states, [1.0 / n] * n)

        # Update the distribution
        current_dist = self.transitions[action][state]
        probs = list(current_dist.probabilities)
        idx = self.states.index(next_state)

        # Set the probability for this transition
        # Adjust other probabilities to sum to 1
        probs[idx] = prob
        remaining_prob = 1.0 - prob
        other_indices = [i for i in range(len(self.states)) if i != idx]
        if other_indices:
            other_prob = remaining_prob / len(other_indices)
            for i in other_indices:
                probs[i] = other_prob

        self.transitions[action][state] = CategoricalDistribution(self.states, probs)

    def get_next_state_dist(self, state: str, action: str) -> CategoricalDistribution:
        """Get the distribution over next states.

        Args:
            state: Current state.
            action: Action taken.

        Returns:
            CategoricalDistribution over next states.
        """
        if state not in self.states:
            raise ValueError(f"Unknown state: {state}")
        if action not in self.actions:
            raise ValueError(f"Unknown action: {action}")

        if state not in self.transitions[action]:
            # Default: uniform transition
            return CategoricalDistribution(self.states)

        return self.transitions[action][state]

    @classmethod
    def from_state_space(cls, state_space: StateSpaceModel) -> "TransitionMatrix":
        """Build a transition matrix from a StateSpaceModel.

        Args:
            state_space: The compiled state space model.

        Returns:
            TransitionMatrix with inferred probabilities from transitions.
        """
        states = list(state_space.variables.keys())
        actions = list(state_space.actions.keys())

        matrix = cls(states, actions)

        # Count transitions to estimate probabilities. The compiler emits
        # transitions keyed by ``trans_<action_id>`` with ``source_state`` /
        # ``target_state`` dicts mapping the involved variable ids to
        # symbolic value tags. Derive concrete source/target states from those
        # variable ids (they are the matrix ``states``), not from parsing the
        # transition id (which yields ``trans``/``act`` — never a state).
        transition_counts: dict[tuple[str, str, str], int] = defaultdict(int)

        for trans in state_space.transitions.values():
            if not trans.action_id:
                continue
            action_id = trans.action_id
            if action_id not in actions:
                continue
            sources = [v for v in trans.source_state if v in states]
            targets = [v for v in trans.target_state if v in states]
            # A transition may touch several variables; record each involved
            # (source -> target) pair so no action is silently dropped into a
            # uniform matrix. Pairs with no valid source or target are skipped.
            for source in sources:
                for target in targets:
                    transition_counts[(source, action_id, target)] += 1

        # Convert counts to probabilities. Each observed (action, source) row
        # is built in one go from its normalised count vector: going through
        # ``set_transition`` per target would re-spread the remaining mass
        # uniformly on every call and overwrite earlier targets.
        row_counts: dict[tuple[str, str], list[int]] = {}
        for (source, action, target), count in transition_counts.items():
            row = row_counts.setdefault((action, source), [0] * len(states))
            row[states.index(target)] += count

        for (action, source), counts in row_counts.items():
            if sum(counts) > 0:
                matrix.transitions[action][source] = CategoricalDistribution(
                    states, [float(c) for c in counts]
                )

        return matrix

    def __repr__(self) -> str:
        """String representation."""
        return f"TransitionMatrix({len(self.states)} states, {len(self.actions)} actions)"

__init__(states, actions)

Initialize a transition matrix.

Parameters:

Name Type Description Default
states list[str]

List of state names.

required
actions list[str]

List of action names.

required
Source code in py/cogant/simulate/distributions.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def __init__(self, states: list[str], actions: list[str]):
    """
    Initialize a transition matrix.

    Args:
        states: List of state names.
        actions: List of action names.
    """
    self.states = states
    self.actions = actions
    # transitions[action][state] = CategoricalDistribution over next states
    self.transitions: dict[str, dict[str, CategoricalDistribution]] = {
        action: {} for action in actions
    }

__repr__()

String representation.

Source code in py/cogant/simulate/distributions.py
278
279
280
def __repr__(self) -> str:
    """String representation."""
    return f"TransitionMatrix({len(self.states)} states, {len(self.actions)} actions)"

from_state_space(state_space) classmethod

Build a transition matrix from a StateSpaceModel.

Parameters:

Name Type Description Default
state_space StateSpaceModel

The compiled state space model.

required

Returns:

Type Description
TransitionMatrix

TransitionMatrix with inferred probabilities from transitions.

Source code in py/cogant/simulate/distributions.py
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
@classmethod
def from_state_space(cls, state_space: StateSpaceModel) -> "TransitionMatrix":
    """Build a transition matrix from a StateSpaceModel.

    Args:
        state_space: The compiled state space model.

    Returns:
        TransitionMatrix with inferred probabilities from transitions.
    """
    states = list(state_space.variables.keys())
    actions = list(state_space.actions.keys())

    matrix = cls(states, actions)

    # Count transitions to estimate probabilities. The compiler emits
    # transitions keyed by ``trans_<action_id>`` with ``source_state`` /
    # ``target_state`` dicts mapping the involved variable ids to
    # symbolic value tags. Derive concrete source/target states from those
    # variable ids (they are the matrix ``states``), not from parsing the
    # transition id (which yields ``trans``/``act`` — never a state).
    transition_counts: dict[tuple[str, str, str], int] = defaultdict(int)

    for trans in state_space.transitions.values():
        if not trans.action_id:
            continue
        action_id = trans.action_id
        if action_id not in actions:
            continue
        sources = [v for v in trans.source_state if v in states]
        targets = [v for v in trans.target_state if v in states]
        # A transition may touch several variables; record each involved
        # (source -> target) pair so no action is silently dropped into a
        # uniform matrix. Pairs with no valid source or target are skipped.
        for source in sources:
            for target in targets:
                transition_counts[(source, action_id, target)] += 1

    # Convert counts to probabilities. Each observed (action, source) row
    # is built in one go from its normalised count vector: going through
    # ``set_transition`` per target would re-spread the remaining mass
    # uniformly on every call and overwrite earlier targets.
    row_counts: dict[tuple[str, str], list[int]] = {}
    for (source, action, target), count in transition_counts.items():
        row = row_counts.setdefault((action, source), [0] * len(states))
        row[states.index(target)] += count

    for (action, source), counts in row_counts.items():
        if sum(counts) > 0:
            matrix.transitions[action][source] = CategoricalDistribution(
                states, [float(c) for c in counts]
            )

    return matrix

get_next_state_dist(state, action)

Get the distribution over next states.

Parameters:

Name Type Description Default
state str

Current state.

required
action str

Action taken.

required

Returns:

Type Description
CategoricalDistribution

CategoricalDistribution over next states.

Source code in py/cogant/simulate/distributions.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def get_next_state_dist(self, state: str, action: str) -> CategoricalDistribution:
    """Get the distribution over next states.

    Args:
        state: Current state.
        action: Action taken.

    Returns:
        CategoricalDistribution over next states.
    """
    if state not in self.states:
        raise ValueError(f"Unknown state: {state}")
    if action not in self.actions:
        raise ValueError(f"Unknown action: {action}")

    if state not in self.transitions[action]:
        # Default: uniform transition
        return CategoricalDistribution(self.states)

    return self.transitions[action][state]

set_transition(state, action, next_state, prob)

Set a single transition probability.

Parameters:

Name Type Description Default
state str

Current state.

required
action str

Action taken.

required
next_state str

Resulting state.

required
prob float

Probability of transition.

required
Source code in py/cogant/simulate/distributions.py
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
def set_transition(self, state: str, action: str, next_state: str, prob: float) -> None:
    """Set a single transition probability.

    Args:
        state: Current state.
        action: Action taken.
        next_state: Resulting state.
        prob: Probability of transition.
    """
    if state not in self.states:
        raise ValueError(f"Unknown state: {state}")
    if action not in self.actions:
        raise ValueError(f"Unknown action: {action}")
    if next_state not in self.states:
        raise ValueError(f"Unknown next_state: {next_state}")

    if state not in self.transitions[action]:
        # Create new distribution for this state (uniform)
        n = len(self.states)
        self.transitions[action][state] = CategoricalDistribution(self.states, [1.0 / n] * n)

    # Update the distribution
    current_dist = self.transitions[action][state]
    probs = list(current_dist.probabilities)
    idx = self.states.index(next_state)

    # Set the probability for this transition
    # Adjust other probabilities to sum to 1
    probs[idx] = prob
    remaining_prob = 1.0 - prob
    other_indices = [i for i in range(len(self.states)) if i != idx]
    if other_indices:
        other_prob = remaining_prob / len(other_indices)
        for i in other_indices:
            probs[i] = other_prob

    self.transitions[action][state] = CategoricalDistribution(self.states, probs)

Runner

cogant.simulate.runner

Simulation of explicitly supplied categorical generative matrices.

ModelRunner

Bind structural axis names to complete A/B/C/D categorical matrices.

Source code in py/cogant/simulate/runner.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 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
class ModelRunner:
    """Bind structural axis names to complete A/B/C/D categorical matrices."""

    def __init__(
        self,
        seed: int | None = None,
        model: StateSpaceModel | None = None,
        A: list[list[float]] | None = None,
        B: list[list[list[float]]] | None = None,
        C: list[float] | None = None,
        D: list[float] | None = None,
    ):
        self.model = model
        self.A, self.B, self.C, self.D = A, B, C, D
        if any(value is not None for value in (A, B, C, D)):
            self._matrices()

    @property
    def has_generative_model(self) -> bool:
        return all(value is not None for value in (self.A, self.B, self.C, self.D))

    def _matrices(self) -> CategoricalModel:
        if self.A is None or self.B is None or self.C is None or self.D is None:
            raise RuntimeError("inference requires A, B, C, and D matrices on the runner")
        return CategoricalModel(self.A, self.B, self.C, self.D)

    def _axes(self) -> tuple[list[str], list[str], list[str]]:
        if self.model is None:
            raise ValueError("named inference requires a bound StateSpaceModel")
        matrix = self._matrices()
        axes = (list(self.model.variables), list(self.model.observations), list(self.model.actions))
        if tuple(map(len, axes)) != (len(matrix.D), len(matrix.A), matrix.n_actions):
            raise ValueError("structural axes do not match the supplied matrices")
        return axes

    def _vector(self, beliefs: dict[str, float]) -> list[float]:
        states, _, _ = self._axes()
        if set(beliefs) != set(states):
            raise ValueError("belief keys must match the declared state axis")
        return [beliefs[state] for state in states]

    def validate_model(self, state_space: StateSpaceModel) -> dict[str, Any]:
        """
        Check that model is well-formed.

        Validates:
        - All transitions reference valid states and actions
        - All actions reference valid variables
        - State space is connected
        - No dangling references

        Args:
            state_space: StateSpaceModel to validate.

        Returns:
            Dict with "valid" (bool), "errors" (list), "warnings" (list).
        """
        errors: list[str] = []
        warnings: list[str] = []
        valid = True

        # Check variables exist
        if not state_space.variables:
            errors.append("No state variables defined")
            valid = False

        # Check transitions reference valid states
        for trans_id, trans in state_space.transitions.items():
            if trans.action_id and trans.action_id not in state_space.actions:
                errors.append(f"Transition {trans_id} references unknown action {trans.action_id}")
                valid = False

        # Check actions reference valid variables
        for action_id, action in state_space.actions.items():
            for var_id in action.effects:
                if var_id not in state_space.variables:
                    errors.append(f"Action {action_id} references unknown variable {var_id}")
                    valid = False
            for var_id in action.preconditions:
                if var_id not in state_space.variables:
                    errors.append(
                        f"Action {action_id} precondition references unknown variable {var_id}"
                    )
                    valid = False

        # Check observations reference valid nodes
        for obs_id, obs in state_space.observations.items():
            if not obs.source_node_id:
                warnings.append(f"Observation {obs_id} has no source node")

        # Check likelihoods reference valid variables
        for like_id, like in state_space.likelihoods.items():
            if like.variable_id not in state_space.variables:
                errors.append(
                    f"Likelihood {like_id} references unknown variable {like.variable_id}"
                )
                valid = False

        # Check preferences reference valid variables
        for pref_id, pref in state_space.preferences.items():
            for var_id in pref.scope:
                if var_id not in state_space.variables:
                    errors.append(f"Preference {pref_id} references unknown variable {var_id}")
                    valid = False

        return {
            "valid": valid,
            "errors": errors,
            "warnings": warnings,
            "variable_count": len(state_space.variables),
            "action_count": len(state_space.actions),
            "transition_count": len(state_space.transitions),
        }

    def vfe_from_beliefs(
        self,
        beliefs: list[float],
        observation: list[float] | None = None,
        prior: list[float] | None = None,
    ) -> float:
        matrix = self._matrices()
        return variational_free_energy(
            beliefs, matrix.D if prior is None else prior, matrix.A, observation
        )

    def efe_for_policy(
        self, policy_action_sequence: list[int], beliefs: list[float] | None = None
    ) -> float:
        matrix = self._matrices()
        return matrix.score(matrix.D if beliefs is None else beliefs, policy_action_sequence)

    def update_beliefs_from_observation(
        self, prior: list[float], observation_index: int
    ) -> list[float]:
        return posterior(prior, self._matrices().A, observation_index)

    def compute_free_energy(self, state: dict[str, Any], observation: str) -> float:
        _, observations, _ = self._axes()
        return self.vfe_from_beliefs(
            self._vector(state), [float(o == observation) for o in observations]
        )

    def belief_update(self, prior_beliefs: dict[str, float], observation: str) -> dict[str, float]:
        states, observations, _ = self._axes()
        updated = self.update_beliefs_from_observation(
            self._vector(prior_beliefs), observations.index(observation)
        )
        return dict(zip(states, updated, strict=True))

    def policy_evaluation(
        self, beliefs: dict[str, float], available_actions: list[str]
    ) -> list[tuple[str, float]]:
        _, _, actions = self._axes()
        q = self._vector(beliefs)
        return sorted(
            [(a, self.efe_for_policy([actions.index(a)], q)) for a in available_actions],
            key=lambda item: item[1],
        )

    def active_inference_step(
        self, beliefs: dict[str, float], observation: str, state_space: StateSpaceModel
    ) -> dict[str, Any]:
        self.model = state_space
        states, observations, actions = self._axes()
        matrices = self._matrices()
        runtime = AgentRuntime(matrices)
        result = runtime.step(self._vector(beliefs), observations.index(observation))
        return {
            "new_beliefs": dict(zip(states, result.posterior, strict=True)),
            "selected_action": actions[result.action],
            "predicted_next_state": dict(zip(states, result.state_dist, strict=True)),
            "free_energy": result.free_energy,
            "efe_ranking": sorted(
                zip(actions, result.policy_scores, strict=True), key=lambda x: x[1]
            ),
        }

    def simulate_step(
        self, state_space: StateSpaceModel, current_state: dict[str, Any], action_id: str
    ) -> dict[str, Any]:
        self.model = state_space
        states, _, actions = self._axes()
        prediction = self._matrices().predict(self._vector(current_state), actions.index(action_id))
        return {
            "next_state": dict(zip(states, prediction, strict=True)),
            "action_applied": action_id,
            "success": True,
        }

    def run_active_inference(
        self, state_space: StateSpaceModel, steps: int = 20
    ) -> list[dict[str, Any]]:
        self.model = state_space
        states, observations, _ = self._axes()
        matrix = self._matrices()
        belief = dict(zip(states, matrix.D, strict=True))
        trace = [
            {
                "step": 0,
                "phase": "initial",
                "beliefs": belief.copy(),
                "observation": None,
                "action": None,
                "free_energy": None,
                "predicted_state": {},
            }
        ]
        if steps < 0:
            raise ValueError("step count must be non-negative")
        for t in range(1, steps + 1):
            outcomes = matrix.observe(self._vector(belief))
            obs = observations[max(range(len(outcomes)), key=outcomes.__getitem__)]
            result = self.active_inference_step(belief, obs, state_space)
            trace.append(
                {
                    "step": t,
                    "phase": "observation",
                    "beliefs": result["new_beliefs"],
                    "observation": obs,
                    "action": result["selected_action"],
                    "free_energy": result["free_energy"],
                    "predicted_state": result["predicted_next_state"],
                }
            )
            belief = result["predicted_next_state"]
        return trace

    def run_simulation(self, state_space: StateSpaceModel, steps: int = 10) -> list[dict[str, Any]]:
        return self.run_active_inference(state_space, steps)

    def generate_report(self, trace: list[dict[str, Any]]) -> str:
        return generate_report(trace)

    def generate_trace(self, state_space: StateSpaceModel) -> dict[str, Any]:
        return {
            "schema_name": state_space.schema_name,
            "trace": self.run_active_inference(state_space, 5),
            "variables": list(state_space.variables),
            "observations": list(state_space.observations),
            "actions": list(state_space.actions),
            "metadata": state_space.metadata,
        }

validate_model(state_space)

Check that model is well-formed.

Validates: - All transitions reference valid states and actions - All actions reference valid variables - State space is connected - No dangling references

Parameters:

Name Type Description Default
state_space StateSpaceModel

StateSpaceModel to validate.

required

Returns:

Type Description
dict[str, Any]

Dict with "valid" (bool), "errors" (list), "warnings" (list).

Source code in py/cogant/simulate/runner.py
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def validate_model(self, state_space: StateSpaceModel) -> dict[str, Any]:
    """
    Check that model is well-formed.

    Validates:
    - All transitions reference valid states and actions
    - All actions reference valid variables
    - State space is connected
    - No dangling references

    Args:
        state_space: StateSpaceModel to validate.

    Returns:
        Dict with "valid" (bool), "errors" (list), "warnings" (list).
    """
    errors: list[str] = []
    warnings: list[str] = []
    valid = True

    # Check variables exist
    if not state_space.variables:
        errors.append("No state variables defined")
        valid = False

    # Check transitions reference valid states
    for trans_id, trans in state_space.transitions.items():
        if trans.action_id and trans.action_id not in state_space.actions:
            errors.append(f"Transition {trans_id} references unknown action {trans.action_id}")
            valid = False

    # Check actions reference valid variables
    for action_id, action in state_space.actions.items():
        for var_id in action.effects:
            if var_id not in state_space.variables:
                errors.append(f"Action {action_id} references unknown variable {var_id}")
                valid = False
        for var_id in action.preconditions:
            if var_id not in state_space.variables:
                errors.append(
                    f"Action {action_id} precondition references unknown variable {var_id}"
                )
                valid = False

    # Check observations reference valid nodes
    for obs_id, obs in state_space.observations.items():
        if not obs.source_node_id:
            warnings.append(f"Observation {obs_id} has no source node")

    # Check likelihoods reference valid variables
    for like_id, like in state_space.likelihoods.items():
        if like.variable_id not in state_space.variables:
            errors.append(
                f"Likelihood {like_id} references unknown variable {like.variable_id}"
            )
            valid = False

    # Check preferences reference valid variables
    for pref_id, pref in state_space.preferences.items():
        for var_id in pref.scope:
            if var_id not in state_space.variables:
                errors.append(f"Preference {pref_id} references unknown variable {var_id}")
                valid = False

    return {
        "valid": valid,
        "errors": errors,
        "warnings": warnings,
        "variable_count": len(state_space.variables),
        "action_count": len(state_space.actions),
        "transition_count": len(state_space.transitions),
    }

Distributions

cogant.simulate.distributions

Probability distributions for Active Inference simulations.

Provides categorical distributions, transition matrices, and belief updates.

CategoricalDistribution

Categorical probability distribution over discrete states.

Source code in py/cogant/simulate/distributions.py
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 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
class CategoricalDistribution:
    """Categorical probability distribution over discrete states."""

    def __init__(self, categories: list[str], probabilities: list[float] | None = None):
        """
        Initialize a categorical distribution.

        Args:
            categories: List of category names.
            probabilities: Optional list of probabilities (must sum to 1).
                          If None, uses uniform distribution.
        """
        self.categories = categories
        self.n = len(categories)

        # Handle empty categories case
        if self.n == 0:
            self.probabilities = []
            self.dist = {}
            return

        if probabilities is None:
            # Uniform distribution
            self.probabilities = [1.0 / self.n] * self.n
        else:
            if len(probabilities) != self.n:
                raise ValueError("Number of probabilities must match number of categories")
            total = sum(probabilities)
            if total <= 0:
                raise ValueError(f"Probabilities must be positive, got sum {total}")
            # Normalize to ensure exact sum of 1 (handles incomplete distributions)
            self.probabilities = [p / total for p in probabilities]

        # Build category -> probability mapping
        self.dist = dict(zip(categories, self.probabilities, strict=False))

    def sample(self) -> str:
        """Sample a category from the distribution.

        Returns:
            A sampled category name.
        """
        return random.choices(self.categories, weights=self.probabilities, k=1)[0]

    def log_prob(self, category: str) -> float:
        """Get log probability of a category.

        Args:
            category: Category name.

        Returns:
            log(P(category)). Returns -inf if category has 0 probability.
        """
        if category not in self.dist:
            raise KeyError(f"Unknown category: {category}")
        prob = self.dist[category]
        if prob <= 0:
            return float("-inf")
        return math.log(prob)

    def entropy(self) -> float:
        """Compute Shannon entropy of the distribution.

        Returns:
            Entropy in nats.
        """
        h = 0.0
        for prob in self.probabilities:
            if prob > 0:
                h -= prob * math.log(prob)
        return h

    def kl_divergence(self, other: "CategoricalDistribution") -> float:
        """Compute KL divergence to another distribution.

        Args:
            other: Another CategoricalDistribution with same categories.

        Returns:
            KL(self || other) in nats.
        """
        if set(self.categories) != set(other.categories):
            raise ValueError("Distributions must have same categories for KL divergence")

        kl = 0.0
        for cat in self.categories:
            p = self.dist[cat]
            q = other.dist[cat]
            if p > 0:
                if q <= 0:
                    return float("inf")
                kl += p * (math.log(p) - math.log(q))
        return kl

    def update(
        self, observation: str, likelihood: "CategoricalDistribution"
    ) -> "CategoricalDistribution":
        """Bayesian update: posterior ∝ likelihood × prior.

        Args:
            observation: The observed category.
            likelihood: P(observation | category) for each category.

        Returns:
            Updated posterior distribution.
        """
        if observation not in likelihood.categories:
            raise ValueError(f"Observation {observation} not in likelihood categories")

        # Posterior ∝ likelihood(obs|cat) × prior(cat)
        posterior_unnormalized = []
        for cat in self.categories:
            prior_cat = self.dist[cat]
            # P(obs | cat) from likelihood
            likelihood_obs_given_cat = likelihood.dist.get(cat, 1e-10)
            posterior_unnormalized.append(prior_cat * likelihood_obs_given_cat)

        # Normalize
        total = sum(posterior_unnormalized)
        if total <= 0:
            # If no valid posterior, return prior (avoid division by zero)
            return CategoricalDistribution(self.categories, self.probabilities)

        posterior_probs = [p / total for p in posterior_unnormalized]
        return CategoricalDistribution(self.categories, posterior_probs)

    def __repr__(self) -> str:
        """String representation."""
        items = [f"{cat}: {prob:.3f}" for cat, prob in self.dist.items()]
        return f"CategoricalDistribution({', '.join(items)})"

__init__(categories, probabilities=None)

Initialize a categorical distribution.

Parameters:

Name Type Description Default
categories list[str]

List of category names.

required
probabilities list[float] | None

Optional list of probabilities (must sum to 1). If None, uses uniform distribution.

None
Source code in py/cogant/simulate/distributions.py
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
def __init__(self, categories: list[str], probabilities: list[float] | None = None):
    """
    Initialize a categorical distribution.

    Args:
        categories: List of category names.
        probabilities: Optional list of probabilities (must sum to 1).
                      If None, uses uniform distribution.
    """
    self.categories = categories
    self.n = len(categories)

    # Handle empty categories case
    if self.n == 0:
        self.probabilities = []
        self.dist = {}
        return

    if probabilities is None:
        # Uniform distribution
        self.probabilities = [1.0 / self.n] * self.n
    else:
        if len(probabilities) != self.n:
            raise ValueError("Number of probabilities must match number of categories")
        total = sum(probabilities)
        if total <= 0:
            raise ValueError(f"Probabilities must be positive, got sum {total}")
        # Normalize to ensure exact sum of 1 (handles incomplete distributions)
        self.probabilities = [p / total for p in probabilities]

    # Build category -> probability mapping
    self.dist = dict(zip(categories, self.probabilities, strict=False))

__repr__()

String representation.

Source code in py/cogant/simulate/distributions.py
140
141
142
143
def __repr__(self) -> str:
    """String representation."""
    items = [f"{cat}: {prob:.3f}" for cat, prob in self.dist.items()]
    return f"CategoricalDistribution({', '.join(items)})"

entropy()

Compute Shannon entropy of the distribution.

Returns:

Type Description
float

Entropy in nats.

Source code in py/cogant/simulate/distributions.py
74
75
76
77
78
79
80
81
82
83
84
def entropy(self) -> float:
    """Compute Shannon entropy of the distribution.

    Returns:
        Entropy in nats.
    """
    h = 0.0
    for prob in self.probabilities:
        if prob > 0:
            h -= prob * math.log(prob)
    return h

kl_divergence(other)

Compute KL divergence to another distribution.

Parameters:

Name Type Description Default
other CategoricalDistribution

Another CategoricalDistribution with same categories.

required

Returns:

Type Description
float

KL(self || other) in nats.

Source code in py/cogant/simulate/distributions.py
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
def kl_divergence(self, other: "CategoricalDistribution") -> float:
    """Compute KL divergence to another distribution.

    Args:
        other: Another CategoricalDistribution with same categories.

    Returns:
        KL(self || other) in nats.
    """
    if set(self.categories) != set(other.categories):
        raise ValueError("Distributions must have same categories for KL divergence")

    kl = 0.0
    for cat in self.categories:
        p = self.dist[cat]
        q = other.dist[cat]
        if p > 0:
            if q <= 0:
                return float("inf")
            kl += p * (math.log(p) - math.log(q))
    return kl

log_prob(category)

Get log probability of a category.

Parameters:

Name Type Description Default
category str

Category name.

required

Returns:

Type Description
float

log(P(category)). Returns -inf if category has 0 probability.

Source code in py/cogant/simulate/distributions.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
def log_prob(self, category: str) -> float:
    """Get log probability of a category.

    Args:
        category: Category name.

    Returns:
        log(P(category)). Returns -inf if category has 0 probability.
    """
    if category not in self.dist:
        raise KeyError(f"Unknown category: {category}")
    prob = self.dist[category]
    if prob <= 0:
        return float("-inf")
    return math.log(prob)

sample()

Sample a category from the distribution.

Returns:

Type Description
str

A sampled category name.

Source code in py/cogant/simulate/distributions.py
50
51
52
53
54
55
56
def sample(self) -> str:
    """Sample a category from the distribution.

    Returns:
        A sampled category name.
    """
    return random.choices(self.categories, weights=self.probabilities, k=1)[0]

update(observation, likelihood)

Bayesian update: posterior ∝ likelihood × prior.

Parameters:

Name Type Description Default
observation str

The observed category.

required
likelihood CategoricalDistribution

P(observation | category) for each category.

required

Returns:

Type Description
CategoricalDistribution

Updated posterior distribution.

Source code in py/cogant/simulate/distributions.py
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
def update(
    self, observation: str, likelihood: "CategoricalDistribution"
) -> "CategoricalDistribution":
    """Bayesian update: posterior ∝ likelihood × prior.

    Args:
        observation: The observed category.
        likelihood: P(observation | category) for each category.

    Returns:
        Updated posterior distribution.
    """
    if observation not in likelihood.categories:
        raise ValueError(f"Observation {observation} not in likelihood categories")

    # Posterior ∝ likelihood(obs|cat) × prior(cat)
    posterior_unnormalized = []
    for cat in self.categories:
        prior_cat = self.dist[cat]
        # P(obs | cat) from likelihood
        likelihood_obs_given_cat = likelihood.dist.get(cat, 1e-10)
        posterior_unnormalized.append(prior_cat * likelihood_obs_given_cat)

    # Normalize
    total = sum(posterior_unnormalized)
    if total <= 0:
        # If no valid posterior, return prior (avoid division by zero)
        return CategoricalDistribution(self.categories, self.probabilities)

    posterior_probs = [p / total for p in posterior_unnormalized]
    return CategoricalDistribution(self.categories, posterior_probs)

TransitionMatrix

Transition probabilities between states under actions.

Source code in py/cogant/simulate/distributions.py
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
class TransitionMatrix:
    """Transition probabilities between states under actions."""

    def __init__(self, states: list[str], actions: list[str]):
        """
        Initialize a transition matrix.

        Args:
            states: List of state names.
            actions: List of action names.
        """
        self.states = states
        self.actions = actions
        # transitions[action][state] = CategoricalDistribution over next states
        self.transitions: dict[str, dict[str, CategoricalDistribution]] = {
            action: {} for action in actions
        }

    def set_transition(self, state: str, action: str, next_state: str, prob: float) -> None:
        """Set a single transition probability.

        Args:
            state: Current state.
            action: Action taken.
            next_state: Resulting state.
            prob: Probability of transition.
        """
        if state not in self.states:
            raise ValueError(f"Unknown state: {state}")
        if action not in self.actions:
            raise ValueError(f"Unknown action: {action}")
        if next_state not in self.states:
            raise ValueError(f"Unknown next_state: {next_state}")

        if state not in self.transitions[action]:
            # Create new distribution for this state (uniform)
            n = len(self.states)
            self.transitions[action][state] = CategoricalDistribution(self.states, [1.0 / n] * n)

        # Update the distribution
        current_dist = self.transitions[action][state]
        probs = list(current_dist.probabilities)
        idx = self.states.index(next_state)

        # Set the probability for this transition
        # Adjust other probabilities to sum to 1
        probs[idx] = prob
        remaining_prob = 1.0 - prob
        other_indices = [i for i in range(len(self.states)) if i != idx]
        if other_indices:
            other_prob = remaining_prob / len(other_indices)
            for i in other_indices:
                probs[i] = other_prob

        self.transitions[action][state] = CategoricalDistribution(self.states, probs)

    def get_next_state_dist(self, state: str, action: str) -> CategoricalDistribution:
        """Get the distribution over next states.

        Args:
            state: Current state.
            action: Action taken.

        Returns:
            CategoricalDistribution over next states.
        """
        if state not in self.states:
            raise ValueError(f"Unknown state: {state}")
        if action not in self.actions:
            raise ValueError(f"Unknown action: {action}")

        if state not in self.transitions[action]:
            # Default: uniform transition
            return CategoricalDistribution(self.states)

        return self.transitions[action][state]

    @classmethod
    def from_state_space(cls, state_space: StateSpaceModel) -> "TransitionMatrix":
        """Build a transition matrix from a StateSpaceModel.

        Args:
            state_space: The compiled state space model.

        Returns:
            TransitionMatrix with inferred probabilities from transitions.
        """
        states = list(state_space.variables.keys())
        actions = list(state_space.actions.keys())

        matrix = cls(states, actions)

        # Count transitions to estimate probabilities. The compiler emits
        # transitions keyed by ``trans_<action_id>`` with ``source_state`` /
        # ``target_state`` dicts mapping the involved variable ids to
        # symbolic value tags. Derive concrete source/target states from those
        # variable ids (they are the matrix ``states``), not from parsing the
        # transition id (which yields ``trans``/``act`` — never a state).
        transition_counts: dict[tuple[str, str, str], int] = defaultdict(int)

        for trans in state_space.transitions.values():
            if not trans.action_id:
                continue
            action_id = trans.action_id
            if action_id not in actions:
                continue
            sources = [v for v in trans.source_state if v in states]
            targets = [v for v in trans.target_state if v in states]
            # A transition may touch several variables; record each involved
            # (source -> target) pair so no action is silently dropped into a
            # uniform matrix. Pairs with no valid source or target are skipped.
            for source in sources:
                for target in targets:
                    transition_counts[(source, action_id, target)] += 1

        # Convert counts to probabilities. Each observed (action, source) row
        # is built in one go from its normalised count vector: going through
        # ``set_transition`` per target would re-spread the remaining mass
        # uniformly on every call and overwrite earlier targets.
        row_counts: dict[tuple[str, str], list[int]] = {}
        for (source, action, target), count in transition_counts.items():
            row = row_counts.setdefault((action, source), [0] * len(states))
            row[states.index(target)] += count

        for (action, source), counts in row_counts.items():
            if sum(counts) > 0:
                matrix.transitions[action][source] = CategoricalDistribution(
                    states, [float(c) for c in counts]
                )

        return matrix

    def __repr__(self) -> str:
        """String representation."""
        return f"TransitionMatrix({len(self.states)} states, {len(self.actions)} actions)"

__init__(states, actions)

Initialize a transition matrix.

Parameters:

Name Type Description Default
states list[str]

List of state names.

required
actions list[str]

List of action names.

required
Source code in py/cogant/simulate/distributions.py
149
150
151
152
153
154
155
156
157
158
159
160
161
162
def __init__(self, states: list[str], actions: list[str]):
    """
    Initialize a transition matrix.

    Args:
        states: List of state names.
        actions: List of action names.
    """
    self.states = states
    self.actions = actions
    # transitions[action][state] = CategoricalDistribution over next states
    self.transitions: dict[str, dict[str, CategoricalDistribution]] = {
        action: {} for action in actions
    }

__repr__()

String representation.

Source code in py/cogant/simulate/distributions.py
278
279
280
def __repr__(self) -> str:
    """String representation."""
    return f"TransitionMatrix({len(self.states)} states, {len(self.actions)} actions)"

from_state_space(state_space) classmethod

Build a transition matrix from a StateSpaceModel.

Parameters:

Name Type Description Default
state_space StateSpaceModel

The compiled state space model.

required

Returns:

Type Description
TransitionMatrix

TransitionMatrix with inferred probabilities from transitions.

Source code in py/cogant/simulate/distributions.py
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
@classmethod
def from_state_space(cls, state_space: StateSpaceModel) -> "TransitionMatrix":
    """Build a transition matrix from a StateSpaceModel.

    Args:
        state_space: The compiled state space model.

    Returns:
        TransitionMatrix with inferred probabilities from transitions.
    """
    states = list(state_space.variables.keys())
    actions = list(state_space.actions.keys())

    matrix = cls(states, actions)

    # Count transitions to estimate probabilities. The compiler emits
    # transitions keyed by ``trans_<action_id>`` with ``source_state`` /
    # ``target_state`` dicts mapping the involved variable ids to
    # symbolic value tags. Derive concrete source/target states from those
    # variable ids (they are the matrix ``states``), not from parsing the
    # transition id (which yields ``trans``/``act`` — never a state).
    transition_counts: dict[tuple[str, str, str], int] = defaultdict(int)

    for trans in state_space.transitions.values():
        if not trans.action_id:
            continue
        action_id = trans.action_id
        if action_id not in actions:
            continue
        sources = [v for v in trans.source_state if v in states]
        targets = [v for v in trans.target_state if v in states]
        # A transition may touch several variables; record each involved
        # (source -> target) pair so no action is silently dropped into a
        # uniform matrix. Pairs with no valid source or target are skipped.
        for source in sources:
            for target in targets:
                transition_counts[(source, action_id, target)] += 1

    # Convert counts to probabilities. Each observed (action, source) row
    # is built in one go from its normalised count vector: going through
    # ``set_transition`` per target would re-spread the remaining mass
    # uniformly on every call and overwrite earlier targets.
    row_counts: dict[tuple[str, str], list[int]] = {}
    for (source, action, target), count in transition_counts.items():
        row = row_counts.setdefault((action, source), [0] * len(states))
        row[states.index(target)] += count

    for (action, source), counts in row_counts.items():
        if sum(counts) > 0:
            matrix.transitions[action][source] = CategoricalDistribution(
                states, [float(c) for c in counts]
            )

    return matrix

get_next_state_dist(state, action)

Get the distribution over next states.

Parameters:

Name Type Description Default
state str

Current state.

required
action str

Action taken.

required

Returns:

Type Description
CategoricalDistribution

CategoricalDistribution over next states.

Source code in py/cogant/simulate/distributions.py
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
def get_next_state_dist(self, state: str, action: str) -> CategoricalDistribution:
    """Get the distribution over next states.

    Args:
        state: Current state.
        action: Action taken.

    Returns:
        CategoricalDistribution over next states.
    """
    if state not in self.states:
        raise ValueError(f"Unknown state: {state}")
    if action not in self.actions:
        raise ValueError(f"Unknown action: {action}")

    if state not in self.transitions[action]:
        # Default: uniform transition
        return CategoricalDistribution(self.states)

    return self.transitions[action][state]

set_transition(state, action, next_state, prob)

Set a single transition probability.

Parameters:

Name Type Description Default
state str

Current state.

required
action str

Action taken.

required
next_state str

Resulting state.

required
prob float

Probability of transition.

required
Source code in py/cogant/simulate/distributions.py
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
def set_transition(self, state: str, action: str, next_state: str, prob: float) -> None:
    """Set a single transition probability.

    Args:
        state: Current state.
        action: Action taken.
        next_state: Resulting state.
        prob: Probability of transition.
    """
    if state not in self.states:
        raise ValueError(f"Unknown state: {state}")
    if action not in self.actions:
        raise ValueError(f"Unknown action: {action}")
    if next_state not in self.states:
        raise ValueError(f"Unknown next_state: {next_state}")

    if state not in self.transitions[action]:
        # Create new distribution for this state (uniform)
        n = len(self.states)
        self.transitions[action][state] = CategoricalDistribution(self.states, [1.0 / n] * n)

    # Update the distribution
    current_dist = self.transitions[action][state]
    probs = list(current_dist.probabilities)
    idx = self.states.index(next_state)

    # Set the probability for this transition
    # Adjust other probabilities to sum to 1
    probs[idx] = prob
    remaining_prob = 1.0 - prob
    other_indices = [i for i in range(len(self.states)) if i != idx]
    if other_indices:
        other_prob = remaining_prob / len(other_indices)
        for i in other_indices:
            probs[i] = other_prob

    self.transitions[action][state] = CategoricalDistribution(self.states, probs)

Free energy

cogant.simulate.free_energy

Categorical free-energy API backed by the shared dependency-free kernel.

FreeEnergyCalculator

Calculate from compiled matrices, preserving the state's declared axis order.

Source code in py/cogant/simulate/free_energy.py
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
class FreeEnergyCalculator:
    """Calculate from compiled matrices, preserving the state's declared axis order."""

    def __init__(self, state_space: StateSpaceModel, matrices: CategoricalModel | None = None):
        self.state_space = state_space
        self.states = list(state_space.variables)
        self.actions = list(state_space.actions)
        self.observations = list(state_space.observations)
        if matrices is None:
            raise ValueError("FreeEnergyCalculator requires explicit A/B/C/D matrices")
        self.model = matrices

    def _beliefs(self, beliefs: CategoricalDistribution) -> list[float]:
        if set(beliefs.categories) != set(self.states):
            raise ValueError("belief categories must match the model state axis")
        return [beliefs.dist[state] for state in self.states]

    def _likelihood(
        self, likelihood_model: dict[str, CategoricalDistribution] | None
    ) -> Sequence[Sequence[float]]:
        if likelihood_model is None:
            return self.model.A
        if set(likelihood_model) != set(self.observations):
            raise ValueError("likelihood keys must match the observation axis")
        return [self._beliefs(likelihood_model[o]) for o in self.observations]

    def variational_free_energy(
        self,
        beliefs: CategoricalDistribution,
        observation: str,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Evaluate posterior free energy against the model's initial prior D."""
        observation_index = self.observations.index(observation)
        observed = [float(i == observation_index) for i in range(len(self.observations))]
        return categorical_vfe(
            self._beliefs(beliefs), self.model.D, self._likelihood(likelihood_model), observed
        )

    def expected_free_energy(
        self,
        beliefs: CategoricalDistribution,
        policy: list[str],
        horizon: int = 3,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Sum the specified candidate policy up to a positive finite horizon."""
        if horizon <= 0:
            raise ValueError("horizon must be positive")
        model = CategoricalModel(
            self._likelihood(likelihood_model), self.model.B, self.model.C, self.model.D
        )
        return model.score(
            self._beliefs(beliefs), [self.actions.index(a) for a in policy[:horizon]]
        )

    def surprisal(
        self,
        observation: str,
        beliefs: CategoricalDistribution,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Return negative log marginal evidence of the observation."""
        import math

        row = self._likelihood(likelihood_model)[self.observations.index(observation)]
        evidence = sum(p * a for p, a in zip(self._beliefs(beliefs), row, strict=True))
        return -math.log(evidence) if evidence > 0 else math.inf

    def complexity(
        self, posterior: CategoricalDistribution, prior: CategoricalDistribution | None = None
    ) -> float:
        """Return KL(q || prior), using the model D when no prior is supplied."""
        from cogant.runtime.categorical import kl_divergence

        reference = self.model.D if prior is None else self._beliefs(prior)
        return kl_divergence(self._beliefs(posterior), reference)

    def accuracy(
        self,
        observation: str,
        beliefs: CategoricalDistribution,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> float:
        """Return expected log likelihood for the observed outcome."""
        return self.complexity(beliefs) - self.variational_free_energy(
            beliefs, observation, likelihood_model
        )

    def policy_ranking(
        self,
        beliefs: CategoricalDistribution,
        available_actions: list[str],
        horizon: int = 3,
        likelihood_model: dict[str, CategoricalDistribution] | None = None,
    ) -> list[tuple[str, float]]:
        """Rank candidate one-action policies by risk plus ambiguity, stably."""
        return sorted(
            [
                (a, self.expected_free_energy(beliefs, [a], horizon, likelihood_model))
                for a in available_actions
            ],
            key=lambda item: item[1],
        )

    def _predict_beliefs(
        self, beliefs: CategoricalDistribution, action: str
    ) -> CategoricalDistribution:
        predicted = self.model.predict(self._beliefs(beliefs), self.actions.index(action))
        return CategoricalDistribution(self.states, predicted)

accuracy(observation, beliefs, likelihood_model=None)

Return expected log likelihood for the observed outcome.

Source code in py/cogant/simulate/free_energy.py
131
132
133
134
135
136
137
138
139
140
def accuracy(
    self,
    observation: str,
    beliefs: CategoricalDistribution,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Return expected log likelihood for the observed outcome."""
    return self.complexity(beliefs) - self.variational_free_energy(
        beliefs, observation, likelihood_model
    )

complexity(posterior, prior=None)

Return KL(q || prior), using the model D when no prior is supplied.

Source code in py/cogant/simulate/free_energy.py
122
123
124
125
126
127
128
129
def complexity(
    self, posterior: CategoricalDistribution, prior: CategoricalDistribution | None = None
) -> float:
    """Return KL(q || prior), using the model D when no prior is supplied."""
    from cogant.runtime.categorical import kl_divergence

    reference = self.model.D if prior is None else self._beliefs(prior)
    return kl_divergence(self._beliefs(posterior), reference)

expected_free_energy(beliefs, policy, horizon=3, likelihood_model=None)

Sum the specified candidate policy up to a positive finite horizon.

Source code in py/cogant/simulate/free_energy.py
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
def expected_free_energy(
    self,
    beliefs: CategoricalDistribution,
    policy: list[str],
    horizon: int = 3,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Sum the specified candidate policy up to a positive finite horizon."""
    if horizon <= 0:
        raise ValueError("horizon must be positive")
    model = CategoricalModel(
        self._likelihood(likelihood_model), self.model.B, self.model.C, self.model.D
    )
    return model.score(
        self._beliefs(beliefs), [self.actions.index(a) for a in policy[:horizon]]
    )

policy_ranking(beliefs, available_actions, horizon=3, likelihood_model=None)

Rank candidate one-action policies by risk plus ambiguity, stably.

Source code in py/cogant/simulate/free_energy.py
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
def policy_ranking(
    self,
    beliefs: CategoricalDistribution,
    available_actions: list[str],
    horizon: int = 3,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> list[tuple[str, float]]:
    """Rank candidate one-action policies by risk plus ambiguity, stably."""
    return sorted(
        [
            (a, self.expected_free_energy(beliefs, [a], horizon, likelihood_model))
            for a in available_actions
        ],
        key=lambda item: item[1],
    )

surprisal(observation, beliefs, likelihood_model=None)

Return negative log marginal evidence of the observation.

Source code in py/cogant/simulate/free_energy.py
109
110
111
112
113
114
115
116
117
118
119
120
def surprisal(
    self,
    observation: str,
    beliefs: CategoricalDistribution,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Return negative log marginal evidence of the observation."""
    import math

    row = self._likelihood(likelihood_model)[self.observations.index(observation)]
    evidence = sum(p * a for p, a in zip(self._beliefs(beliefs), row, strict=True))
    return -math.log(evidence) if evidence > 0 else math.inf

variational_free_energy(beliefs, observation, likelihood_model=None)

Evaluate posterior free energy against the model's initial prior D.

Source code in py/cogant/simulate/free_energy.py
79
80
81
82
83
84
85
86
87
88
89
90
def variational_free_energy(
    self,
    beliefs: CategoricalDistribution,
    observation: str,
    likelihood_model: dict[str, CategoricalDistribution] | None = None,
) -> float:
    """Evaluate posterior free energy against the model's initial prior D."""
    observation_index = self.observations.index(observation)
    observed = [float(i == observation_index) for i in range(len(self.observations))]
    return categorical_vfe(
        self._beliefs(beliefs), self.model.D, self._likelihood(likelihood_model), observed
    )

bayesian_belief_update(prior, likelihood_matrix, observation_index)

Condition on an observed index; reject observations with zero evidence.

Source code in py/cogant/simulate/free_energy.py
25
26
27
28
29
30
31
def bayesian_belief_update(
    prior: Sequence[float],
    likelihood_matrix: Sequence[Sequence[float]],
    observation_index: int,
) -> list[float]:
    """Condition on an observed index; reject observations with zero evidence."""
    return posterior(prior, likelihood_matrix, observation_index)

expected_free_energy(policy_action_sequence, beliefs, likelihood_matrix, transition_tensor, log_preferences)

Sum risk KL(predicted outcomes || softmax(C)) and expected ambiguity.

Source code in py/cogant/simulate/free_energy.py
34
35
36
37
38
39
40
41
42
43
def expected_free_energy(
    policy_action_sequence: Sequence[int],
    beliefs: Sequence[float],
    likelihood_matrix: Sequence[Sequence[float]],
    transition_tensor: Sequence[Sequence[Sequence[float]]],
    log_preferences: Sequence[float],
) -> float:
    """Sum risk KL(predicted outcomes || softmax(C)) and expected ambiguity."""
    model = CategoricalModel(likelihood_matrix, transition_tensor, log_preferences, beliefs)
    return model.score(beliefs, policy_action_sequence)

uniform_distribution(n)

Construct an explicitly requested uniform categorical distribution.

Source code in py/cogant/simulate/free_energy.py
46
47
48
49
50
def uniform_distribution(n: int) -> list[float]:
    """Construct an explicitly requested uniform categorical distribution."""
    if n <= 0:
        raise ValueError("distribution dimension must be positive")
    return [1.0 / n] * n

variational_free_energy(beliefs, prior, likelihood_matrix, observation=None)

Evaluate F against an explicit predicted prior and observation distribution.

Source code in py/cogant/simulate/free_energy.py
13
14
15
16
17
18
19
20
21
22
def variational_free_energy(
    beliefs: Sequence[float],
    prior: Sequence[float],
    likelihood_matrix: Sequence[Sequence[float]],
    observation: Sequence[float] | None = None,
) -> float:
    """Evaluate F against an explicit predicted prior and observation distribution."""
    if observation is None:
        raise ValueError("variational free energy requires an explicit observation distribution")
    return categorical_vfe(beliefs, prior, likelihood_matrix, observation)

Visualization

cogant.simulate.visualization

Visualization for Active Inference simulations.

Generates SVG plots and HTML reports of simulation traces.

SimulationVisualizer

Generate visualizations of simulation traces.

Source code in py/cogant/simulate/visualization.py
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
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
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
class SimulationVisualizer:
    """Generate visualizations of simulation traces."""

    def __init__(self) -> None:
        """Initialize the visualizer."""
        pass

    def plot_free_energy_trajectory(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG plot of free energy over time.

        Args:
            trace: List of simulation steps, each with 'free_energy' key.

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Extract free energy values
        samples = [step for step in trace if step.get("phase") != "initial"]
        fe_values = [observed_free_energy(step.get("free_energy")) for step in samples]

        if not fe_values:
            return self._empty_svg("No free energy data")

        # Compute bounds
        min_fe = min(fe_values)
        max_fe = max(fe_values)
        range_fe = max_fe - min_fe if max_fe != min_fe else 1.0

        # SVG parameters
        width, height = 800, 400
        margin = 60
        plot_width = width - 2 * margin
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .grid { stroke: #ddd; stroke-width: 0.5; }",
            "  .line { stroke: #0066cc; stroke-width: 2; fill: none; }",
            "  .point { fill: #0066cc; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Free Energy Trajectory</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw grid and labels
        n_steps = len(fe_values)
        for i, sample in enumerate(samples):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            svg_lines.append(
                f'<line x1="{x}" y1="{height - margin}" x2="{x}" y2="{height - margin + 3}" class="axis"/>'
            )
            if i % max(1, n_steps // 5) == 0:
                svg_lines.append(
                    f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{sample.get("step", i)}</text>'
                )

        # Draw free energy line
        if len(fe_values) > 1:
            path_parts = []
            for i, fe in enumerate(fe_values):
                x = margin + (i / (n_steps - 1)) * plot_width
                y = height - margin - ((fe - min_fe) / range_fe) * plot_height
                if i == 0:
                    path_parts.append(f"M {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")
            svg_lines.append(f'<path d="{" ".join(path_parts)}" class="line"/>')

        # Draw points
        for i, fe in enumerate(fe_values):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            y = height - margin - ((fe - min_fe) / range_fe) * plot_height
            svg_lines.append(
                f'<circle cx="{x}" cy="{y}" r="3" class="point" opacity="0.6" data-step="{samples[i].get("step", i)}" data-free-energy="{fe}"/>'
            )

        # Draw y-axis labels
        for i in range(5):
            fe_label = min_fe + (i / 4) * range_fe
            y = height - margin - (i / 4) * plot_height
            svg_lines.append(
                f'<text x="{margin - 10}" y="{y + 3}" text-anchor="end" class="text">{fe_label:.2f}</text>'
            )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def plot_belief_evolution(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG showing belief evolution over time.

        Args:
            trace: List of simulation steps, each with 'beliefs' key (dict of state -> prob).

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Extract beliefs
        all_states: set[str] = set()
        belief_history = []

        for step in trace:
            beliefs = step.get("beliefs", {})
            if isinstance(beliefs, dict):
                belief_history.append(beliefs)
                all_states.update(beliefs.keys())
            else:
                belief_history.append({})

        if not belief_history or not all_states:
            return self._empty_svg("No belief data")

        states = sorted(all_states)
        colors = self._generate_colors(len(states))

        # SVG parameters
        width, height = 900, 400
        margin = 60
        plot_width = width - 2 * margin
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "  .legend { font-family: Arial; font-size: 11px; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Belief Evolution</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw stacked area chart
        n_steps = len(belief_history)
        for state_idx, _state in enumerate(states):
            cumulative = [0.0] * n_steps
            for i in range(n_steps):
                beliefs = belief_history[i]
                cumulative[i] = sum(beliefs.get(s, 0.0) for s in states[: state_idx + 1])

            # Generate path for this state
            path_parts = []
            for i in range(n_steps):
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                y = height - margin - (cumulative[i] * plot_height)
                if i == 0:
                    path_parts.append(f"M {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")

            # Close path
            for i in range(n_steps - 1, -1, -1):
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                if state_idx == 0:
                    y = height - margin
                else:
                    prev_cumulative = sum(belief_history[i].get(s, 0.0) for s in states[:state_idx])
                    y = height - margin - (prev_cumulative * plot_height)
                if i == n_steps - 1:
                    path_parts.append(f"L {x} {y}")
                else:
                    path_parts.append(f"L {x} {y}")

            path_parts.append("Z")
            color = colors[state_idx]
            svg_lines.append(f'<path d="{" ".join(path_parts)}" fill="{color}" opacity="0.7"/>')

        # Add legend
        legend_x = width - 150
        for state_idx, state in enumerate(states):
            y = margin + 20 + state_idx * 18
            color = colors[state_idx]
            svg_lines.append(
                f'<rect x="{legend_x}" y="{y - 10}" width="12" height="12" fill="{color}"/>'
            )
            svg_lines.append(
                f'<text x="{legend_x + 18}" y="{y}" class="legend">{state[:15]}</text>'
            )

        # X-axis labels
        for i in range(n_steps):
            if i % max(1, n_steps // 5) == 0:
                x = margin + (i / max(1, n_steps - 1)) * plot_width
                svg_lines.append(
                    f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{i}</text>'
                )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def plot_action_distribution(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate SVG bar chart of actions taken.

        Args:
            trace: List of simulation steps, each with 'action' key.

        Returns:
            SVG string.
        """
        if not trace:
            return self._empty_svg("No trace data")

        # Count actions
        action_counts: dict[str, int] = defaultdict(int)
        for step in trace:
            action = step.get("action")
            if action:
                action_counts[action] += 1

        if not action_counts:
            return self._empty_svg("No action data")

        actions = sorted(action_counts.keys())
        counts = [action_counts[a] for a in actions]
        max_count = max(counts) if counts else 1

        # SVG parameters
        bar_width = 40
        spacing = 20
        width = len(actions) * (bar_width + spacing) + 100
        height = 400
        margin = 60
        plot_height = height - 2 * margin

        # Build SVG
        svg_lines = [
            f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
            "<style>",
            "  .bar { fill: #0066cc; }",
            "  .axis { stroke: #333; stroke-width: 1; }",
            "  .text { font-family: Arial; font-size: 12px; }",
            "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
            "</style>",
            f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Action Distribution</text>',
        ]

        # Draw axes
        svg_lines.append(
            f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
        )
        svg_lines.append(
            f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
        )

        # Draw bars
        for i, action in enumerate(actions):
            count = action_counts[action]
            bar_height = (count / max_count) * plot_height if max_count > 0 else 0
            x = margin + i * (bar_width + spacing) + spacing // 2
            y = height - margin - bar_height

            svg_lines.append(
                f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" class="bar"/>'
            )
            svg_lines.append(
                f'<text x="{x + bar_width / 2}" y="{height - margin + 20}" text-anchor="middle" class="text">{action[:10]}</text>'
            )
            svg_lines.append(
                f'<text x="{x + bar_width / 2}" y="{y - 5}" text-anchor="middle" class="text">{count}</text>'
            )

        svg_lines.append("</svg>")
        return "\n".join(svg_lines)

    def generate_mermaid_trajectory(self, trace: list[dict[str, Any]]) -> str:
        """
        Generate Mermaid sequence diagram of state transitions.

        Args:
            trace: List of simulation steps.

        Returns:
            Mermaid diagram string.
        """
        if not trace or len(trace) < 2:
            return "graph LR\n  A[No transitions]"

        lines = ["sequenceDiagram"]
        lines.append("  participant Agent")
        lines.append("  participant Environment")

        for i in range(len(trace) - 1):
            current = trace[i]
            next_step = trace[i + 1]

            state = current.get("state", f"s{i}")
            action = next_step.get("action", "wait")
            next_state = next_step.get("state", f"s{i + 1}")

            # Format state info
            state_str = str(state)[:20]
            action_str = str(action)[:15]
            next_state_str = str(next_state)[:20]

            lines.append(f"  Agent->>Environment: {action_str} @ {state_str}")
            lines.append(f"  Environment->>Agent: → {next_state_str}")

        return "\n".join(lines)

    def generate_html_report(self, trace: list[dict[str, Any]], state_space: Any) -> str:
        """
        Generate full HTML report of simulation.

        Args:
            trace: List of simulation steps.
            state_space: The state space model (for metadata).

        Returns:
            HTML string.
        """
        # Generate individual visualizations
        fe_plot = self.plot_free_energy_trajectory(trace)
        belief_plot = self.plot_belief_evolution(trace)
        action_plot = self.plot_action_distribution(trace)
        mermaid_diagram = self.generate_mermaid_trajectory(trace)

        html_lines = [
            "<!DOCTYPE html>",
            "<html>",
            "<head>",
            "  <meta charset='utf-8'>",
            "  <title>Active Inference Simulation Report</title>",
            "  <script src='https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js'></script>",
            "  <style>",
            "    body { font-family: Arial; margin: 20px; background: #f5f5f5; }",
            "    .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; }",
            "    h1 { color: #333; }",
            "    .section { margin: 30px 0; }",
            "    .plot { border: 1px solid #ddd; padding: 10px; margin: 10px 0; }",
            "    .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }",
            "    .stat-box { background: #f9f9f9; padding: 15px; border-radius: 5px; }",
            "    .stat-value { font-size: 24px; font-weight: bold; color: #0066cc; }",
            "    .stat-label { color: #666; margin-top: 5px; }",
            "  </style>",
            "</head>",
            "<body>",
            "  <div class='container'>",
            "    <h1>Active Inference Simulation Report</h1>",
            f"    <p>Generated for state space: {state_space.schema_name if hasattr(state_space, 'schema_name') else 'Unknown'}</p>",
        ]

        executed = [step for step in trace if step.get("phase") != "initial"]
        # Statistics
        html_lines.extend(
            [
                "    <div class='section stats'>",
                f"      <div class='stat-box'><div class='stat-value'>{len(executed)}</div><div class='stat-label'>Steps</div></div>",
                f"      <div class='stat-box'><div class='stat-value'>{len({s.get('action') for s in trace if s.get('action')})}</div><div class='stat-label'>Unique Actions</div></div>",
            ]
        )

        # Add mean free energy if available
        fe_values = [observed_free_energy(s.get("free_energy")) for s in executed]
        if fe_values:
            mean_fe = sum(fe_values) / len(fe_values)
            html_lines.append(
                f"      <div class='stat-box'><div class='stat-value'>{mean_fe:.3f}</div><div class='stat-label'>Mean Free Energy</div></div>"
            )

        html_lines.append("    </div>")

        # Plots
        html_lines.extend(
            [
                "    <div class='section'>",
                "      <h2>Free Energy Trajectory</h2>",
                f"      <div class='plot'>{fe_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>Belief Evolution</h2>",
                f"      <div class='plot'>{belief_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>Action Distribution</h2>",
                f"      <div class='plot'>{action_plot}</div>",
                "    </div>",
                "    <div class='section'>",
                "      <h2>State Transition Sequence</h2>",
                f"      <div class='mermaid'>{mermaid_diagram}</div>",
                "    </div>",
                "  </div>",
                "  <script>mermaid.initialize({{ startOnLoad: true }}); mermaid.contentLoaded();</script>",
                "</body>",
                "</html>",
            ]
        )

        return "\n".join(html_lines)

    @staticmethod
    def _empty_svg(message: str) -> str:
        """Generate an empty SVG with a message."""
        return f"""<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
  <text x="200" y="100" text-anchor="middle" font-size="16" fill="#999">{message}</text>
</svg>"""

    @staticmethod
    def _generate_colors(n: int) -> list[str]:
        """Generate n distinct colors."""
        colors = [
            "#FF6B6B",
            "#4ECDC4",
            "#45B7D1",
            "#FFA07A",
            "#98D8C8",
            "#F7DC6F",
            "#BB8FCE",
            "#85C1E2",
        ]
        if n <= len(colors):
            return colors[:n]

        # Generate additional colors
        result = colors.copy()
        for i in range(n - len(colors)):
            hue = (i * 360) / (n - len(colors))
            # Simple HSL to hex conversion
            result.append(f"hsl({hue}, 70%, 50%)")

        return result

__init__()

Initialize the visualizer.

Source code in py/cogant/simulate/visualization.py
16
17
18
def __init__(self) -> None:
    """Initialize the visualizer."""
    pass

generate_html_report(trace, state_space)

Generate full HTML report of simulation.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps.

required
state_space Any

The state space model (for metadata).

required

Returns:

Type Description
str

HTML string.

Source code in py/cogant/simulate/visualization.py
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
def generate_html_report(self, trace: list[dict[str, Any]], state_space: Any) -> str:
    """
    Generate full HTML report of simulation.

    Args:
        trace: List of simulation steps.
        state_space: The state space model (for metadata).

    Returns:
        HTML string.
    """
    # Generate individual visualizations
    fe_plot = self.plot_free_energy_trajectory(trace)
    belief_plot = self.plot_belief_evolution(trace)
    action_plot = self.plot_action_distribution(trace)
    mermaid_diagram = self.generate_mermaid_trajectory(trace)

    html_lines = [
        "<!DOCTYPE html>",
        "<html>",
        "<head>",
        "  <meta charset='utf-8'>",
        "  <title>Active Inference Simulation Report</title>",
        "  <script src='https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js'></script>",
        "  <style>",
        "    body { font-family: Arial; margin: 20px; background: #f5f5f5; }",
        "    .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 5px; }",
        "    h1 { color: #333; }",
        "    .section { margin: 30px 0; }",
        "    .plot { border: 1px solid #ddd; padding: 10px; margin: 10px 0; }",
        "    .stats { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; }",
        "    .stat-box { background: #f9f9f9; padding: 15px; border-radius: 5px; }",
        "    .stat-value { font-size: 24px; font-weight: bold; color: #0066cc; }",
        "    .stat-label { color: #666; margin-top: 5px; }",
        "  </style>",
        "</head>",
        "<body>",
        "  <div class='container'>",
        "    <h1>Active Inference Simulation Report</h1>",
        f"    <p>Generated for state space: {state_space.schema_name if hasattr(state_space, 'schema_name') else 'Unknown'}</p>",
    ]

    executed = [step for step in trace if step.get("phase") != "initial"]
    # Statistics
    html_lines.extend(
        [
            "    <div class='section stats'>",
            f"      <div class='stat-box'><div class='stat-value'>{len(executed)}</div><div class='stat-label'>Steps</div></div>",
            f"      <div class='stat-box'><div class='stat-value'>{len({s.get('action') for s in trace if s.get('action')})}</div><div class='stat-label'>Unique Actions</div></div>",
        ]
    )

    # Add mean free energy if available
    fe_values = [observed_free_energy(s.get("free_energy")) for s in executed]
    if fe_values:
        mean_fe = sum(fe_values) / len(fe_values)
        html_lines.append(
            f"      <div class='stat-box'><div class='stat-value'>{mean_fe:.3f}</div><div class='stat-label'>Mean Free Energy</div></div>"
        )

    html_lines.append("    </div>")

    # Plots
    html_lines.extend(
        [
            "    <div class='section'>",
            "      <h2>Free Energy Trajectory</h2>",
            f"      <div class='plot'>{fe_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>Belief Evolution</h2>",
            f"      <div class='plot'>{belief_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>Action Distribution</h2>",
            f"      <div class='plot'>{action_plot}</div>",
            "    </div>",
            "    <div class='section'>",
            "      <h2>State Transition Sequence</h2>",
            f"      <div class='mermaid'>{mermaid_diagram}</div>",
            "    </div>",
            "  </div>",
            "  <script>mermaid.initialize({{ startOnLoad: true }}); mermaid.contentLoaded();</script>",
            "</body>",
            "</html>",
        ]
    )

    return "\n".join(html_lines)

generate_mermaid_trajectory(trace)

Generate Mermaid sequence diagram of state transitions.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps.

required

Returns:

Type Description
str

Mermaid diagram string.

Source code in py/cogant/simulate/visualization.py
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
def generate_mermaid_trajectory(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate Mermaid sequence diagram of state transitions.

    Args:
        trace: List of simulation steps.

    Returns:
        Mermaid diagram string.
    """
    if not trace or len(trace) < 2:
        return "graph LR\n  A[No transitions]"

    lines = ["sequenceDiagram"]
    lines.append("  participant Agent")
    lines.append("  participant Environment")

    for i in range(len(trace) - 1):
        current = trace[i]
        next_step = trace[i + 1]

        state = current.get("state", f"s{i}")
        action = next_step.get("action", "wait")
        next_state = next_step.get("state", f"s{i + 1}")

        # Format state info
        state_str = str(state)[:20]
        action_str = str(action)[:15]
        next_state_str = str(next_state)[:20]

        lines.append(f"  Agent->>Environment: {action_str} @ {state_str}")
        lines.append(f"  Environment->>Agent: → {next_state_str}")

    return "\n".join(lines)

plot_action_distribution(trace)

Generate SVG bar chart of actions taken.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'action' key.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
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
def plot_action_distribution(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG bar chart of actions taken.

    Args:
        trace: List of simulation steps, each with 'action' key.

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Count actions
    action_counts: dict[str, int] = defaultdict(int)
    for step in trace:
        action = step.get("action")
        if action:
            action_counts[action] += 1

    if not action_counts:
        return self._empty_svg("No action data")

    actions = sorted(action_counts.keys())
    counts = [action_counts[a] for a in actions]
    max_count = max(counts) if counts else 1

    # SVG parameters
    bar_width = 40
    spacing = 20
    width = len(actions) * (bar_width + spacing) + 100
    height = 400
    margin = 60
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .bar { fill: #0066cc; }",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Action Distribution</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw bars
    for i, action in enumerate(actions):
        count = action_counts[action]
        bar_height = (count / max_count) * plot_height if max_count > 0 else 0
        x = margin + i * (bar_width + spacing) + spacing // 2
        y = height - margin - bar_height

        svg_lines.append(
            f'<rect x="{x}" y="{y}" width="{bar_width}" height="{bar_height}" class="bar"/>'
        )
        svg_lines.append(
            f'<text x="{x + bar_width / 2}" y="{height - margin + 20}" text-anchor="middle" class="text">{action[:10]}</text>'
        )
        svg_lines.append(
            f'<text x="{x + bar_width / 2}" y="{y - 5}" text-anchor="middle" class="text">{count}</text>'
        )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)

plot_belief_evolution(trace)

Generate SVG showing belief evolution over time.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'beliefs' key (dict of state -> prob).

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
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
def plot_belief_evolution(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG showing belief evolution over time.

    Args:
        trace: List of simulation steps, each with 'beliefs' key (dict of state -> prob).

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Extract beliefs
    all_states: set[str] = set()
    belief_history = []

    for step in trace:
        beliefs = step.get("beliefs", {})
        if isinstance(beliefs, dict):
            belief_history.append(beliefs)
            all_states.update(beliefs.keys())
        else:
            belief_history.append({})

    if not belief_history or not all_states:
        return self._empty_svg("No belief data")

    states = sorted(all_states)
    colors = self._generate_colors(len(states))

    # SVG parameters
    width, height = 900, 400
    margin = 60
    plot_width = width - 2 * margin
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "  .legend { font-family: Arial; font-size: 11px; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Belief Evolution</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw stacked area chart
    n_steps = len(belief_history)
    for state_idx, _state in enumerate(states):
        cumulative = [0.0] * n_steps
        for i in range(n_steps):
            beliefs = belief_history[i]
            cumulative[i] = sum(beliefs.get(s, 0.0) for s in states[: state_idx + 1])

        # Generate path for this state
        path_parts = []
        for i in range(n_steps):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            y = height - margin - (cumulative[i] * plot_height)
            if i == 0:
                path_parts.append(f"M {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")

        # Close path
        for i in range(n_steps - 1, -1, -1):
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            if state_idx == 0:
                y = height - margin
            else:
                prev_cumulative = sum(belief_history[i].get(s, 0.0) for s in states[:state_idx])
                y = height - margin - (prev_cumulative * plot_height)
            if i == n_steps - 1:
                path_parts.append(f"L {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")

        path_parts.append("Z")
        color = colors[state_idx]
        svg_lines.append(f'<path d="{" ".join(path_parts)}" fill="{color}" opacity="0.7"/>')

    # Add legend
    legend_x = width - 150
    for state_idx, state in enumerate(states):
        y = margin + 20 + state_idx * 18
        color = colors[state_idx]
        svg_lines.append(
            f'<rect x="{legend_x}" y="{y - 10}" width="12" height="12" fill="{color}"/>'
        )
        svg_lines.append(
            f'<text x="{legend_x + 18}" y="{y}" class="legend">{state[:15]}</text>'
        )

    # X-axis labels
    for i in range(n_steps):
        if i % max(1, n_steps // 5) == 0:
            x = margin + (i / max(1, n_steps - 1)) * plot_width
            svg_lines.append(
                f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{i}</text>'
            )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)

plot_free_energy_trajectory(trace)

Generate SVG plot of free energy over time.

Parameters:

Name Type Description Default
trace list[dict[str, Any]]

List of simulation steps, each with 'free_energy' key.

required

Returns:

Type Description
str

SVG string.

Source code in py/cogant/simulate/visualization.py
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
def plot_free_energy_trajectory(self, trace: list[dict[str, Any]]) -> str:
    """
    Generate SVG plot of free energy over time.

    Args:
        trace: List of simulation steps, each with 'free_energy' key.

    Returns:
        SVG string.
    """
    if not trace:
        return self._empty_svg("No trace data")

    # Extract free energy values
    samples = [step for step in trace if step.get("phase") != "initial"]
    fe_values = [observed_free_energy(step.get("free_energy")) for step in samples]

    if not fe_values:
        return self._empty_svg("No free energy data")

    # Compute bounds
    min_fe = min(fe_values)
    max_fe = max(fe_values)
    range_fe = max_fe - min_fe if max_fe != min_fe else 1.0

    # SVG parameters
    width, height = 800, 400
    margin = 60
    plot_width = width - 2 * margin
    plot_height = height - 2 * margin

    # Build SVG
    svg_lines = [
        f'<svg width="{width}" height="{height}" xmlns="http://www.w3.org/2000/svg">',
        "<style>",
        "  .axis { stroke: #333; stroke-width: 1; }",
        "  .grid { stroke: #ddd; stroke-width: 0.5; }",
        "  .line { stroke: #0066cc; stroke-width: 2; fill: none; }",
        "  .point { fill: #0066cc; }",
        "  .text { font-family: Arial; font-size: 12px; }",
        "  .title { font-family: Arial; font-size: 16px; font-weight: bold; }",
        "</style>",
        f'<text x="{width / 2}" y="25" text-anchor="middle" class="title">Free Energy Trajectory</text>',
    ]

    # Draw axes
    svg_lines.append(
        f'<line x1="{margin}" y1="{height - margin}" x2="{width - margin}" y2="{height - margin}" class="axis"/>'
    )
    svg_lines.append(
        f'<line x1="{margin}" y1="{margin}" x2="{margin}" y2="{height - margin}" class="axis"/>'
    )

    # Draw grid and labels
    n_steps = len(fe_values)
    for i, sample in enumerate(samples):
        x = margin + (i / max(1, n_steps - 1)) * plot_width
        svg_lines.append(
            f'<line x1="{x}" y1="{height - margin}" x2="{x}" y2="{height - margin + 3}" class="axis"/>'
        )
        if i % max(1, n_steps // 5) == 0:
            svg_lines.append(
                f'<text x="{x}" y="{height - margin + 20}" text-anchor="middle" class="text">{sample.get("step", i)}</text>'
            )

    # Draw free energy line
    if len(fe_values) > 1:
        path_parts = []
        for i, fe in enumerate(fe_values):
            x = margin + (i / (n_steps - 1)) * plot_width
            y = height - margin - ((fe - min_fe) / range_fe) * plot_height
            if i == 0:
                path_parts.append(f"M {x} {y}")
            else:
                path_parts.append(f"L {x} {y}")
        svg_lines.append(f'<path d="{" ".join(path_parts)}" class="line"/>')

    # Draw points
    for i, fe in enumerate(fe_values):
        x = margin + (i / max(1, n_steps - 1)) * plot_width
        y = height - margin - ((fe - min_fe) / range_fe) * plot_height
        svg_lines.append(
            f'<circle cx="{x}" cy="{y}" r="3" class="point" opacity="0.6" data-step="{samples[i].get("step", i)}" data-free-energy="{fe}"/>'
        )

    # Draw y-axis labels
    for i in range(5):
        fe_label = min_fe + (i / 4) * range_fe
        y = height - margin - (i / 4) * plot_height
        svg_lines.append(
            f'<text x="{margin - 10}" y="{y + 3}" text-anchor="end" class="text">{fe_label:.2f}</text>'
        )

    svg_lines.append("</svg>")
    return "\n".join(svg_lines)