cogant.reverse
The cogant.reverse package is the inverse of the forward translate
pipeline: it parses GNN markdown, plans a synthesis target, and either
emits a runnable Python package (synthesize_package) or binds
runtime-callable closures (MatrixFunctions) directly.
Package
cogant.reverse
COGANT reverse synthesis engine — GNN markdown → Python package.
The :mod:cogant.reverse package implements the reverse direction of the
COGANT pipeline. Where the forward direction consumes a source tree and
emits a Generalized Notation for Networks (GNN) Active Inference model,
the reverse direction consumes a GNN markdown file and synthesizes a
runnable Python package whose structure mirrors the GNN topology.
Roundtrip contract
The round-trip cannot reproduce the original source code verbatim — GNN is a lossy semantic projection that discards implementation details, argument names, control-flow, docstrings, and anything that is not a hidden-state, observation, action, policy, or constraint role.
The public verifier reports a roundtrip_status enum plus an invariant
ledger. ROLE_PRESERVED means the semantic role multiset survived above
the configured role_preservation_score threshold. The stricter
STRUCTURALLY_ISOMORPHIC status is reserved for runs that also preserve
graph counts, edge kinds, state-space shapes, matrix shapes/values, GNN
sections, generated-code compile status, and the second forward pass.
Concrete node IDs and edge weights are not expected to survive unless the strict invariant tier says they did.
Public API
- :class:
ReverseGNNModel— parsed representation of a GNN markdown file. - :func:
parse_gnn— parse a GNN markdown file into a ReverseGNNModel. - :class:
PackagePlan— mapping plan from GNN roles to Python package files. - :func:
plan_package— construct a PackagePlan from a ReverseGNNModel. - :func:
synthesize_package— emit Python source files from a PackagePlan. - :func:
verify_roundtrip— round-trip idempotency verifier.
ROLE_PRESERVATION_THRESHOLD = 0.5
module-attribute
Default minimum role-preservation score for the weaker success tier.
DEFAULT_ISOMORPHISM_THRESHOLD = 0.7
module-attribute
Default cutoff for :attr:IsomorphismReport.structurally_isomorphic.
MatrixFunctions
Copied source matrices with categorical filtering and policy operations.
Source code in py/cogant/reverse/callable.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
prior()
Return D vector (initial state prior).
Source code in py/cogant/reverse/callable.py
49 50 51 | |
expected_free_energy(state_dist, action)
Evaluate one-step outcome risk plus expected likelihood ambiguity.
Source code in py/cogant/reverse/callable.py
53 54 55 | |
score_preference_gradient(state_dist, policy)
Return fixed-policy score sensitivity along the C observation axis.
Source code in py/cogant/reverse/callable.py
57 58 59 | |
best_action(state_dist)
Return argmin EFE over the declared action axis.
Source code in py/cogant/reverse/callable.py
61 62 63 64 65 66 67 68 69 70 71 72 | |
RoundtripResult
dataclass
Outcome of a single round-trip verification run.
Attributes:
| Name | Type | Description |
|---|---|---|
roundtrip_status |
str
|
One of |
role_preservation_score |
float
|
Per-role mean of
|
role_preserved |
bool
|
True when |
structurally_isomorphic |
bool
|
True only when the full strict invariant ledger passes. |
matrix_preserved |
bool
|
True when observed A/B/C/D shapes and values are preserved within tolerance. |
gnn_sections_preserved |
bool
|
True when Markdown section membership survives the round-trip exactly. |
generated_code_ok |
bool
|
True when synthesized Python files import
through |
vacuous_roundtrip |
bool
|
True when both role multisets are empty and the role-preservation score's 1.0 value is vacuous. |
matrix_score |
float
|
Frobenius-based similarity of the A/B/C/D
matrix stacks produced by the two sides of the round-trip.
Range |
structural_score |
float
|
Graph-structure similarity (node/edge role
multiset symmetric difference, normalized and inverted).
Range |
original_roles |
dict[str, int]
|
Role multiset derived from the source GNN
( |
synthesized_roles |
dict[str, int]
|
Role multiset from the forward pipeline's semantic mappings after reverse-synthesis, restricted to the role-bearing definitions named in the package's semantic-target manifest (generated runtime support code is not scored). |
shape_match |
dict[str, bool]
|
Dict describing whether n_states, n_obs, and n_actions dimensions survived the round-trip. |
package_path: Absolute path to the synthesized package (kept
on disk if the caller passed a persistent tmp_dir).
original_graph_summary: Node/edge/kind summary for the first
graph view in the comparison.
synthesized_graph_summary: Node/edge/kind summary for the
graph produced by the forward re-run.
graph_delta: Count and kind deltas between the graph summaries.
gnn_diff: Section-level diff between original and regenerated
GNN Markdown when both sides are available.
matrix_delta: Shape/value deltas for A/B/C/D matrices when
parseable GNN matrix blocks are available.
invariants: Explicit pass/fail invariants for the
code → graph → GNN → code → graph cycle.
rule_evidence_trace: Rule/mapping evidence artifact from the
synthesized forward pass, suitable for dashboard review.
warnings: Non-fatal diagnostic warnings collected during the
round-trip that do not affect status.
errors: Non-fatal errors collected during the round-trip.
Source code in py/cogant/reverse/idempotency.py
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 | |
summary()
Return a human-readable single-line summary of the result.
Source code in py/cogant/reverse/idempotency.py
273 274 275 276 277 278 279 280 281 | |
IsomorphismReport
dataclass
Aggregate GNN-to-GNN distance report.
All *_score fields are in [0.0, 1.0] where 1.0 means
"identical" and 0.0 means "maximally different under this
metric". The total_score is the weighted mean of the three
component scores and is itself in [0.0, 1.0]. structurally_isomorphic
is simply total_score >= threshold.
Attributes:
| Name | Type | Description |
|---|---|---|
structural_score |
float
|
Graph-structure similarity in |
role_score |
float
|
Role distribution similarity (inverted JS
divergence) in |
matrix_score |
float
|
Frobenius-based matrix similarity in |
total_score |
float
|
Weighted mean
|
structurally_isomorphic |
bool
|
True when |
breakdown |
dict[str, Any]
|
Per-metric diagnostic detail. Keys include the three component scores, the threshold, the weighting, and (when available) per-matrix Frobenius distances. |
Source code in py/cogant/reverse/metrics.py
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 | |
summary()
Return a compact, human-readable one-line summary.
The format is::
[ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60
with ISO swapped for DRIFT when
structurally_isomorphic is False.
Source code in py/cogant/reverse/metrics.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
ReverseGNNModel
dataclass
Parsed GNN model ready for planning and synthesis.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
The |
raw_model_name |
str
|
The unsanitized |
hidden_states |
list[str]
|
Names of hidden-state factors ( |
observations |
list[str]
|
Names of observation modalities
( |
actions |
list[str]
|
Names of action/control factors ( |
policies |
list[str]
|
Names of policy variables (rare; usually empty). |
constraints |
list[str]
|
Names of constraint/preference variables. |
annotations |
dict[str, str]
|
Map from variable name → ontology concept
( |
cardinalities |
dict[str, int]
|
Map from variable name → categorical dimension
(from |
types |
dict[str, str]
|
Map from variable name → upstream type string
( |
A |
list[list[float]]
|
Likelihood matrix |
B |
list[list[list[float]]]
|
Transition tensor |
C |
list[float]
|
Log-preference vector over observations of shape |
D |
list[float]
|
Prior distribution over hidden states of shape |
connections |
list[str]
|
Raw list of arrow-syntax connection strings from
|
human_names |
dict[str, str]
|
Map from |
Source code in py/cogant/reverse/parser.py
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 | |
n_hidden_factors
property
Number of named hidden-state factors in the source ontology.
n_states
property
Number of hidden dimensions represented by this model.
Matrix dimensions are authoritative when present. Before matrices are parsed, retain the declared factor count so callers can inspect a syntactically valid but not-yet-executable model.
n_obs
property
Number of observation dimensions represented by this model.
n_actions
property
Number of action dimensions represented by this model.
validate()
Return evidence and dimension errors without inventing values.
Source code in py/cogant/reverse/parser.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
NodePlan
dataclass
Plan for a single GNN node → Python construct.
Attributes:
| Name | Type | Description |
|---|---|---|
slot |
str
|
The GNN slot identifier ( |
name |
str
|
The Python identifier to emit (derived from the human name when available, else the slot name). |
role |
str
|
The MappingKind label (e.g. |
python_type |
str
|
The Python type annotation string ( |
module |
str
|
The module file this node is emitted into
( |
cardinality |
int
|
Categorical cardinality from the GNN declaration, or 0 if unknown. Used for default values and type hints. |
initial_value |
str
|
Source-level literal for the initial value
( |
Source code in py/cogant/reverse/planner.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 | |
PackagePlan
dataclass
Full synthesis plan for a GNN → Python package.
Attributes:
| Name | Type | Description |
|---|---|---|
package_name |
str
|
Sanitized Python package name (derived from the
GNN |
raw_model_name |
str
|
Original unsanitized model name for docstrings. |
nodes |
list[NodePlan]
|
All node plans in declaration order. |
state_vars |
list[NodePlan]
|
Subset of |
obs_functions |
list[NodePlan]
|
Subset with role |
action_methods |
list[NodePlan]
|
Subset with role |
policy_functions |
list[NodePlan]
|
Subset with role |
constraint_checks |
list[NodePlan]
|
Subset with role |
context_functions |
list[NodePlan]
|
Subset with role |
target_role_counts |
dict[str, int]
|
Expected semantic role multiset for the synthesized package. Round-trip verification passes the source roles here so generated scaffolds are deficit-based rather than fixed boilerplate. |
scaffold_constraint_checks |
list[NodePlan]
|
Additional |
scaffold_policy_functions |
list[NodePlan]
|
Additional top-level POLICY scaffolds emitted only when target POLICY roles remain after authoritative policy functions and the optional policy selector helper. |
scaffold_context_classes |
list[NodePlan]
|
Additional top-level CONTEXT classes emitted only when source roles include CONTEXT deficits. |
has_A_matrix |
bool
|
True if the parsed A matrix has non-zero rows. |
has_B_tensor |
bool
|
True if the parsed B tensor is non-trivial. |
has_C_vector |
bool
|
True if the parsed C vector is non-empty. |
has_D_vector |
bool
|
True if the parsed D vector is non-empty. |
Source code in py/cogant/reverse/planner.py
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 | |
validate()
Validate the package plan for structural consistency.
Checks that the plan is internally coherent and can be synthesized. Does not validate the plan against external sources (e.g., the original GNN).
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of validation issues. Empty list means the plan is valid. |
list[str]
|
Issues describe problems but do not necessarily prevent synthesis |
list[str]
|
from succeeding. |
Source code in py/cogant/reverse/planner.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 | |
diff(other)
Return a human-readable diff between this plan and another.
Compares the role distributions, node counts, and key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
PackagePlan
|
Another PackagePlan to compare against. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A human-readable diff string. Empty string if the plans are |
str
|
identical. |
Source code in py/cogant/reverse/planner.py
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 | |
to_json()
Serialize the PackagePlan to JSON.
Returns:
| Type | Description |
|---|---|
str
|
A JSON string representation of the plan suitable for |
str
|
serialization and round-trip recovery. |
Source code in py/cogant/reverse/planner.py
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 | |
from_json(data)
classmethod
Deserialize a PackagePlan from JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str
|
A JSON string representation of a PackagePlan. |
required |
Returns:
| Type | Description |
|---|---|
PackagePlan
|
A reconstructed PackagePlan instance. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If the JSON is malformed. |
KeyError
|
If required fields are missing. |
Source code in py/cogant/reverse/planner.py
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 | |
verify_repo_roundtrip(repo_path, output_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD)
Run forward → reverse → forward on an existing repository.
This is the entry point used by the cogant roundtrip CLI
subcommand. It:
- Runs the forward pipeline on
repo_pathand emits a GNN plus a first semantic-mappings multisetR1. - Parses the emitted GNN back into a ReverseGNNModel.
- Synthesizes a Python package from the plan.
- Runs the forward pipeline again on the synthesized package and
collects a second semantic-mappings multiset
R2. - Compares
R1andR2directly; the role-preservation score is the mean per-rolemin(count1, count2) / max(count1, count2)multiset similarity.
This comparison style (forward-vs-forward) is the strictest role preservation measurement for an existing repository: it asks whether the same pipeline sees the same roles in the synthesized package that it saw in the original. The alternative (parse the GNN, compare to forward-on-synth) is weaker because it mixes two different rule systems — the parser's role derivation and the forward pipeline's semantic rules — on the two sides of the comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path
|
str | Path
|
Repository to round-trip. |
required |
output_dir
|
str | Path | None
|
Directory to write intermediate artifacts into. If None, a temporary directory is used and cleaned up. |
None
|
role_threshold
|
float
|
Minimum role match score to accept. |
ROLE_PRESERVATION_THRESHOLD
|
Returns:
| Type | Description |
|---|---|
RoundtripResult
|
class: |
RoundtripResult
|
first forward pass and |
RoundtripResult
|
second. When the reverse parser, planning, or synthesis rejects the |
RoundtripResult
|
emitted model, the result has |
RoundtripResult
|
reason in |
Source code in py/cogant/reverse/idempotency.py
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 | |
verify_roundtrip(gnn_path, tmp_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD, keep_tmp=False)
Run a full round-trip on a GNN markdown file and score the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn_path
|
str | Path
|
Path to a GNN markdown file produced by COGANT (or any conforming emitter). |
required |
tmp_dir
|
str | Path | None
|
Optional directory where the synthesized package
should be written. If None, a temporary directory is
created and removed after the run (unless |
None
|
role_threshold
|
float
|
Minimum |
ROLE_PRESERVATION_THRESHOLD
|
keep_tmp
|
bool
|
When True, do not delete the temporary directory after the run. Useful for debugging. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RoundtripResult
|
class: |
RoundtripResult
|
has been parsed, the result is always returned — a model that |
|
RoundtripResult
|
planning or synthesis rejects yields |
|
RoundtripResult
|
and exceptions inside the forward pipeline are captured as |
|
RoundtripResult
|
|
|
RoundtripResult
|
is removed even when the run fails. |
Source code in py/cogant/reverse/idempotency.py
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | |
compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)
Return a graph-structure similarity score in [0, 1].
We build two multisets for each graph:
role(nodes)— one bucket per node role label.(source_role, target_role)— one bucket per edge.
We then compute the normalized symmetric difference of each
multiset separately and return 1 - mean(d_nodes, d_edges).
Nodes-only graphs (no edges on either side) skip the edge term.
Edge cases:
- Both graphs empty → return
1.0(vacuously identical). - One graph empty, other non-empty → return
0.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes_a
|
Sequence[Any]
|
Iterable of node-like objects for graph A. |
required |
edges_a
|
Sequence[Any]
|
Iterable of edge-like objects for graph A. |
required |
nodes_b
|
Sequence[Any]
|
Iterable of node-like objects for graph B. |
required |
edges_b
|
Sequence[Any]
|
Iterable of edge-like objects for graph B. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score in |
Source code in py/cogant/reverse/metrics.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | |
compare_matrices(matrices_a, matrices_b)
Return an averaged Frobenius-similarity score in [0, 1].
For each canonical Active Inference matrix slot
(A, B, C, D) present in both input dicts and
non-empty on both sides, we compute::
1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)
after zero-padding the two matrices to their common bounding shape. The returned score is the unweighted mean of these per-matrix similarities.
Edge cases:
- If neither side has any recognisable numeric matrix entry,
return
0.5(neutral — the metric is undefined, not zero). - If a key is present on only one side it is ignored (the structural-graph score is the axis that penalises missing slots).
- Extra keys beyond
{A, B, C, D}are tolerated and included.
The metric is symmetric: compare_matrices(a, b) ==
compare_matrices(b, a) up to floating point round-off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrices_a
|
Mapping[str, Any]
|
Dict mapping matrix name to a 2D array-like. |
required |
matrices_b
|
Mapping[str, Any]
|
Dict mapping matrix name to a 2D array-like. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean similarity score in |
float
|
comparable matrices exist. |
Source code in py/cogant/reverse/metrics.py
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 | |
compare_role_distributions(roles_a, roles_b)
Return a similarity score in [0, 1] for two role multisets.
The underlying distance is the Jensen-Shannon divergence in base 2,
which for two probability vectors p and q is::
JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M), M = 0.5*(p+q)
and is bounded in [0, 1]. We return 1 - JS so that higher
is better.
Edge cases:
- If both distributions are empty, we return
0.0(there is no distribution to compare, and the spec asks for a neutral-low value here so that the overall isomorphism score does not spuriously inflate on degenerate inputs). - If exactly one distribution is empty, we also return
0.0(maximally different — one side has no roles at all).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roles_a
|
Mapping[str, float]
|
Mapping from role name to count (or weight). |
required |
roles_b
|
Mapping[str, float]
|
Mapping from role name to count (or weight). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score in |
float
|
distributions are identical; |
float
|
disjoint or one side is empty. |
Source code in py/cogant/reverse/metrics.py
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 | |
compute_isomorphism_report(gnn_a, gnn_b, threshold=DEFAULT_ISOMORPHISM_THRESHOLD)
Compute a full :class:IsomorphismReport for two GNN packages.
gnn_a and gnn_b are expected to be dict-like bundles with
the following optional keys:
roles—{role_name: count}multiset.matrices—{"A"|"B"|"C"|"D": array_like}dict.nodes— iterable of node objects or dicts.edges— iterable of edge objects or dicts.
Missing keys are tolerated: the corresponding component score
falls back to its documented neutral value (0.0 for roles,
0.5 for matrices, 1.0 for an empty graph).
The three component scores are combined with fixed weights::
total = 0.4 * role + 0.4 * matrix + 0.2 * structural
and structurally_isomorphic is total >= threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn_a
|
Mapping[str, Any]
|
First GNN package dict. |
required |
gnn_b
|
Mapping[str, Any]
|
Second GNN package dict. |
required |
threshold
|
float
|
Cutoff for :attr: |
DEFAULT_ISOMORPHISM_THRESHOLD
|
Returns:
| Type | Description |
|---|---|
IsomorphismReport
|
A fully populated :class: |
Source code in py/cogant/reverse/metrics.py
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | |
parse_gnn(gnn)
Parse a GNN markdown file or string into a :class:ReverseGNNModel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn
|
str | Path
|
Either a path to a |
required |
Returns:
| Type | Description |
|---|---|
ReverseGNNModel
|
A populated :class: |
ReverseGNNModel
|
from the source remain empty. Consumers must treat an incomplete |
ReverseGNNModel
|
model as invalid evidence rather than filling missing semantics. |
Example
from cogant.reverse.parser import parse_gnn gnn = '''## ModelName ... Demo ... ... ## StateSpaceBlock ... s_f0[2,1,type=int] ... o_m0[2,1,type=int] ... ''' model = parse_gnn(gnn) model.raw_model_name 'Demo'
Source code in py/cogant/reverse/parser.py
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | |
plan_package(model, *, expected_roles=None)
Build a :class:PackagePlan from a :class:ReverseGNNModel.
Each hidden-state slot becomes a State dataclass attribute; each
observation slot becomes an observe_* function; each action
slot becomes an act_* function; etc. Naming prefers the
human-readable labels from the extended state-variable table when
available, else falls back to the slot name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ReverseGNNModel
|
Parsed GNN model. |
required |
expected_roles
|
Mapping[str, int] | None
|
Optional source semantic role multiset. When provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added only for deficits relative to that target. When omitted, the target is derived from the parsed GNN itself. |
None
|
Source code in py/cogant/reverse/planner.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 | |
synthesize_package(plan, model, output_dir)
Emit a full Python package to output_dir from plan.
The function creates a package directory named plan.package_name
inside output_dir so that the parent directory can contain
multiple synthesized models side by side. Inside the package it
writes state.py, observe.py, act.py, policy.py,
constraints.py, matrices.py, main.py, and a smoke
test under tests/.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
PackagePlan
|
Package plan produced by :func: |
required |
model
|
ReverseGNNModel
|
Parsed GNN model (provides matrix values). |
required |
output_dir
|
str | Path
|
Directory where the package is created. The directory is created if it does not exist. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path to the created package directory (``output_dir / |
Path
|
package_name``). |
Source code in py/cogant/reverse/synthesizer.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 | |
Parser
GNN markdown → ReverseGNNModel. Tolerates both the upstream canonical
syntax and the COGANT extended sections.
cogant.reverse.parser
GNN markdown → :class:ReverseGNNModel parser.
This module is the inverse of :mod:cogant.gnn.formatter. It reads a
GNN markdown file (COGANT schema GNN v2.0.0, including the bundle emitted by
current COGANT) and extracts the structured content required to synthesize a
Python package: the state space, observation modalities, actions,
policies, constraints, ontology annotations, and A/B/C/D matrices.
Connection and section parsing accepts bare upstream connection
syntax (D_f0>s_f0), grouped multi-source edges ((A_m0, s_f0)>o_m0),
bare comma sources (A_m0,s_f0>o_m0), and
parenthesised examples ((D_f0) > (s_f0)), both bracketed matrix blocks
(A[[rows=3][cols=2]]) and InitialParameterization tuple blocks
(D_f0={ (0.3, 0.3, 0.4) }), and any mix of COGANT's extended
sections alongside the upstream header. Upstream files keep their own
variable names (s, o, u, s_beliefs), trailing # comments,
multi-line A={ ... } parameter literals, and action-major B
slices. Sections the parser does not recognise are ignored rather than
causing an error, so the parser tolerates future COGANT extensions.
Matrices the source does not provide are projected from its factorized
declarations and the model is marked degraded with diagnostics;
every allocation sized by source integers is bounded by
:data:MAX_REVERSE_MATRIX_ELEMENTS.
The parser does not consult the ProgramGraph; it relies entirely on the markdown text. This keeps the reverse pipeline standalone — a GNN file alone is sufficient to produce a ReverseGNNModel.
MAX_REVERSE_MATRIX_ELEMENTS = 2000000
module-attribute
Largest number of cells a single A/B/C/D tensor may allocate while parsing.
Every dimension the parser allocates from — identity(r,c,d) shorthands,
fenced B[[rows=..][cols=..][depth=..]] headers, and the Cartesian product
of declared factor cardinalities — is an integer taken from the GNN text,
which the /reverse endpoint accepts from untrusted clients. A ~100-byte
document could otherwise request billions of cells. The budget is checked
before the nested lists are built; exceeding it raises
:class:ReverseModelError. Callers that knowingly reverse larger models may
raise this module attribute.
ReverseGNNModel
dataclass
Parsed GNN model ready for planning and synthesis.
Attributes:
| Name | Type | Description |
|---|---|---|
model_name |
str
|
The |
raw_model_name |
str
|
The unsanitized |
hidden_states |
list[str]
|
Names of hidden-state factors ( |
observations |
list[str]
|
Names of observation modalities
( |
actions |
list[str]
|
Names of action/control factors ( |
policies |
list[str]
|
Names of policy variables (rare; usually empty). |
constraints |
list[str]
|
Names of constraint/preference variables. |
annotations |
dict[str, str]
|
Map from variable name → ontology concept
( |
cardinalities |
dict[str, int]
|
Map from variable name → categorical dimension
(from |
types |
dict[str, str]
|
Map from variable name → upstream type string
( |
A |
list[list[float]]
|
Likelihood matrix |
B |
list[list[list[float]]]
|
Transition tensor |
C |
list[float]
|
Log-preference vector over observations of shape |
D |
list[float]
|
Prior distribution over hidden states of shape |
connections |
list[str]
|
Raw list of arrow-syntax connection strings from
|
human_names |
dict[str, str]
|
Map from |
Source code in py/cogant/reverse/parser.py
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 | |
n_actions
property
Number of action dimensions represented by this model.
n_hidden_factors
property
Number of named hidden-state factors in the source ontology.
n_obs
property
Number of observation dimensions represented by this model.
n_states
property
Number of hidden dimensions represented by this model.
Matrix dimensions are authoritative when present. Before matrices are parsed, retain the declared factor count so callers can inspect a syntactically valid but not-yet-executable model.
validate()
Return evidence and dimension errors without inventing values.
Source code in py/cogant/reverse/parser.py
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 | |
ReverseModelError
Bases: ValueError
Raised when a parsed model cannot provide executable semantics.
Source code in py/cogant/reverse/parser.py
46 47 48 49 | |
parse_gnn(gnn)
Parse a GNN markdown file or string into a :class:ReverseGNNModel.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn
|
str | Path
|
Either a path to a |
required |
Returns:
| Type | Description |
|---|---|
ReverseGNNModel
|
A populated :class: |
ReverseGNNModel
|
from the source remain empty. Consumers must treat an incomplete |
ReverseGNNModel
|
model as invalid evidence rather than filling missing semantics. |
Example
from cogant.reverse.parser import parse_gnn gnn = '''## ModelName ... Demo ... ... ## StateSpaceBlock ... s_f0[2,1,type=int] ... o_m0[2,1,type=int] ... ''' model = parse_gnn(gnn) model.raw_model_name 'Demo'
Source code in py/cogant/reverse/parser.py
1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 | |
Callable
Runtime-callable closures built directly from a ReverseGNNModel.
No code generation, no exec() — plain Python function calls.
cogant.reverse.callable
Parsed GNN matrix operations using the shared categorical numerical kernel.
MatrixFunctions
Copied source matrices with categorical filtering and policy operations.
Source code in py/cogant/reverse/callable.py
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 | |
best_action(state_dist)
Return argmin EFE over the declared action axis.
Source code in py/cogant/reverse/callable.py
61 62 63 64 65 66 67 68 69 70 71 72 | |
expected_free_energy(state_dist, action)
Evaluate one-step outcome risk plus expected likelihood ambiguity.
Source code in py/cogant/reverse/callable.py
53 54 55 | |
prior()
Return D vector (initial state prior).
Source code in py/cogant/reverse/callable.py
49 50 51 | |
score_preference_gradient(state_dist, policy)
Return fixed-policy score sensitivity along the C observation axis.
Source code in py/cogant/reverse/callable.py
57 58 59 | |
Planner
Planning step that turns a parsed model into a synthesis plan (names, dimensions, helper signatures).
cogant.reverse.planner
Package planner: :class:ReverseGNNModel → :class:PackagePlan.
This module decides how each semantic role in a GNN model becomes a Python construct. The mapping is intentionally simple and mechanical so the forward COGANT pipeline can recognise the resulting code:
=============== ========================================================
GNN role Python target
=============== ========================================================
HIDDEN_STATE @dataclass field on State in state.py
OBSERVATION def observe_<name>(state) in observe.py
ACTION def act_<name>(state) in act.py
POLICY def policy_<name>(state, obs) in policy.py
CONSTRAINT def check_<name>(state) in constraints.py
PREFERENCE def prefer_<name>(obs) in constraints.py
=============== ========================================================
This mapping is designed so that when COGANT's forward pipeline parses
the synthesized package, it naturally classifies the dataclass fields
as hidden-state variables (mutated inside class methods), the observe_*
functions as observation modalities (pure reads over state), the
act_* functions as actions (WRITES edges to state), and the
policy_* / check_* functions as POLICY/CONSTRAINT mappings.
This gives the round-trip the best chance of role multiset equality.
Human naming
Wherever possible the planner prefers human-readable identifiers
extracted from the GNN's COGANT-extended state-variable table rather
than the opaque upstream slot names (s_f0, o_m1). When no
human name is available, the slot name is used verbatim. All final
identifiers are sanitized to valid Python identifiers.
NodePlan
dataclass
Plan for a single GNN node → Python construct.
Attributes:
| Name | Type | Description |
|---|---|---|
slot |
str
|
The GNN slot identifier ( |
name |
str
|
The Python identifier to emit (derived from the human name when available, else the slot name). |
role |
str
|
The MappingKind label (e.g. |
python_type |
str
|
The Python type annotation string ( |
module |
str
|
The module file this node is emitted into
( |
cardinality |
int
|
Categorical cardinality from the GNN declaration, or 0 if unknown. Used for default values and type hints. |
initial_value |
str
|
Source-level literal for the initial value
( |
Source code in py/cogant/reverse/planner.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 | |
PackagePlan
dataclass
Full synthesis plan for a GNN → Python package.
Attributes:
| Name | Type | Description |
|---|---|---|
package_name |
str
|
Sanitized Python package name (derived from the
GNN |
raw_model_name |
str
|
Original unsanitized model name for docstrings. |
nodes |
list[NodePlan]
|
All node plans in declaration order. |
state_vars |
list[NodePlan]
|
Subset of |
obs_functions |
list[NodePlan]
|
Subset with role |
action_methods |
list[NodePlan]
|
Subset with role |
policy_functions |
list[NodePlan]
|
Subset with role |
constraint_checks |
list[NodePlan]
|
Subset with role |
context_functions |
list[NodePlan]
|
Subset with role |
target_role_counts |
dict[str, int]
|
Expected semantic role multiset for the synthesized package. Round-trip verification passes the source roles here so generated scaffolds are deficit-based rather than fixed boilerplate. |
scaffold_constraint_checks |
list[NodePlan]
|
Additional |
scaffold_policy_functions |
list[NodePlan]
|
Additional top-level POLICY scaffolds emitted only when target POLICY roles remain after authoritative policy functions and the optional policy selector helper. |
scaffold_context_classes |
list[NodePlan]
|
Additional top-level CONTEXT classes emitted only when source roles include CONTEXT deficits. |
has_A_matrix |
bool
|
True if the parsed A matrix has non-zero rows. |
has_B_tensor |
bool
|
True if the parsed B tensor is non-trivial. |
has_C_vector |
bool
|
True if the parsed C vector is non-empty. |
has_D_vector |
bool
|
True if the parsed D vector is non-empty. |
Source code in py/cogant/reverse/planner.py
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 | |
diff(other)
Return a human-readable diff between this plan and another.
Compares the role distributions, node counts, and key attributes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
PackagePlan
|
Another PackagePlan to compare against. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A human-readable diff string. Empty string if the plans are |
str
|
identical. |
Source code in py/cogant/reverse/planner.py
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 | |
from_json(data)
classmethod
Deserialize a PackagePlan from JSON.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
str
|
A JSON string representation of a PackagePlan. |
required |
Returns:
| Type | Description |
|---|---|
PackagePlan
|
A reconstructed PackagePlan instance. |
Raises:
| Type | Description |
|---|---|
JSONDecodeError
|
If the JSON is malformed. |
KeyError
|
If required fields are missing. |
Source code in py/cogant/reverse/planner.py
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 | |
to_json()
Serialize the PackagePlan to JSON.
Returns:
| Type | Description |
|---|---|
str
|
A JSON string representation of the plan suitable for |
str
|
serialization and round-trip recovery. |
Source code in py/cogant/reverse/planner.py
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 | |
validate()
Validate the package plan for structural consistency.
Checks that the plan is internally coherent and can be synthesized. Does not validate the plan against external sources (e.g., the original GNN).
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of validation issues. Empty list means the plan is valid. |
list[str]
|
Issues describe problems but do not necessarily prevent synthesis |
list[str]
|
from succeeding. |
Source code in py/cogant/reverse/planner.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 | |
plan_package(model, *, expected_roles=None)
Build a :class:PackagePlan from a :class:ReverseGNNModel.
Each hidden-state slot becomes a State dataclass attribute; each
observation slot becomes an observe_* function; each action
slot becomes an act_* function; etc. Naming prefers the
human-readable labels from the extended state-variable table when
available, else falls back to the slot name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
|
ReverseGNNModel
|
Parsed GNN model. |
required |
expected_roles
|
Mapping[str, int] | None
|
Optional source semantic role multiset. When provided, POLICY / CONSTRAINT / CONTEXT scaffolds are added only for deficits relative to that target. When omitted, the target is derived from the parsed GNN itself. |
None
|
Source code in py/cogant/reverse/planner.py
566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 | |
Synthesizer
End-to-end package synthesis. synthesize_package writes a runnable
Python package to disk from a parsed model.
cogant.reverse.synthesizer
Package synthesizer: :class:PackagePlan → Python source files.
This is the core of the reverse pipeline. Given a planned mapping of GNN roles to Python constructs, it emits a runnable Python package with the following layout::
<output_dir>/
+-- __init__.py
+-- state.py # State dataclass (HIDDEN_STATE fields)
+-- observe.py # get_<name> functions (OBSERVATION)
+-- act.py # update_<name> functions (ACTION)
+-- policy.py # selector + policy/scaffold functions
+-- constraints.py # check_<name> functions (CONSTRAINT)
+-- matrices.py # A/B/C/D runtime matrices
+-- main.py # Driver that runs a few inference steps
+-- tests/
| +-- __init__.py
| +-- test_smoke.py
The synthesizer uses string templates rather than an AST builder.
Building ASTs via ast.unparse would work for Python 3.9+ but string
templates are simpler, debuggable by eye, produce cleaner formatting,
and avoid the libCST/ast-unparse dependency question entirely.
Determinism
The emitter is deterministic: given the same PackagePlan it produces identical source files on every run. This is essential for the round-trip verifier, which caches synthesized packages by GNN hash.
SynthesisResult
dataclass
Result of synthesizing code from a PackagePlan.
Attributes:
| Name | Type | Description |
|---|---|---|
code |
str
|
The synthesized Python code as a string. |
parse_ok |
bool
|
True if the code parses successfully with ast.parse(). |
issues |
list[str]
|
List of validation issues encountered (empty = valid). |
role_counts |
dict[str, int]
|
Dict mapping role names to counts of synthesized functions/classes for that role (e.g., {"HIDDEN_STATE": 5, "ACTION": 3}). Useful for debugging role distribution. |
filename |
str
|
Optional filename for error reporting. |
Source code in py/cogant/reverse/synthesizer.py
110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 | |
supports_stable_minimal_profile(plan, model)
Return whether a model belongs to the strict reversible subset.
The profile is intentionally narrow. It is not a shortcut around the strict verifier; it only avoids emitting the full demo/runtime scaffold when the source model is already the one-class/one-observer/one-mutator shape that COGANT can re-ingest without graph or matrix growth.
Source code in py/cogant/reverse/synthesizer.py
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 | |
synthesize_package(plan, model, output_dir)
Emit a full Python package to output_dir from plan.
The function creates a package directory named plan.package_name
inside output_dir so that the parent directory can contain
multiple synthesized models side by side. Inside the package it
writes state.py, observe.py, act.py, policy.py,
constraints.py, matrices.py, main.py, and a smoke
test under tests/.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
PackagePlan
|
Package plan produced by :func: |
required |
model
|
ReverseGNNModel
|
Parsed GNN model (provides matrix values). |
required |
output_dir
|
str | Path
|
Directory where the package is created. The directory is created if it does not exist. |
required |
Returns:
| Type | Description |
|---|---|
Path
|
The path to the created package directory (``output_dir / |
Path
|
package_name``). |
Source code in py/cogant/reverse/synthesizer.py
903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 | |
synthesize_stable_minimal_package(plan, model, output_dir)
Emit the strict reversible subset package.
The emitted source is deliberately small: one module, one hidden-state
class, one read-only observation function, and one top-level action
mutator. The class __init__ provides the second ACTION role that the
forward parser records for this subset. No helper modules, tests, imports,
or runtime scaffolds are emitted, because each of those is observable to
the graph verifier and would correctly fail strict isomorphism.
Source code in py/cogant/reverse/synthesizer.py
84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 | |
synthesize_with_validation(plan, model, output_dir)
Synthesize code and validate that it parses as valid Python.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
plan
|
PackagePlan
|
Package plan produced by :func: |
required |
model
|
ReverseGNNModel
|
Parsed GNN model (provides matrix values). |
required |
output_dir
|
str | Path
|
Directory where the package is created. |
required |
Returns:
| Type | Description |
|---|---|
str
|
A tuple of (package_path_str, issues_list). The path is the string |
list[str]
|
representation of the synthesized package directory. issues_list |
tuple[str, list[str]]
|
contains zero or more validation warnings/errors. An empty list |
tuple[str, list[str]]
|
means all files synthesized and parsed successfully. |
Source code in py/cogant/reverse/synthesizer.py
976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 | |
Matrices
Code-generation helpers used by the synthesizer to render the A/B/C/D matrices module.
cogant.reverse.matrices
Standalone matrix modules embedding the shared categorical numerical kernel.
render_matrices_module(model)
Embed the shared stdlib categorical kernel with the exact source matrices.
Source code in py/cogant/reverse/matrices.py
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 | |
Metrics
Roundtrip error (ε) and isomorphism metrics — the empirical bar the forward-reverse cycle is held against.
cogant.reverse.metrics
GNN-to-GNN distance and isomorphism metrics.
This module supplies the real, principled distance functions used by
:mod:cogant.reverse.idempotency when it asks the question "is the
round-tripped GNN isomorphic to the source GNN?".
Three orthogonal views of "close" are measured and then fused into a
single :class:IsomorphismReport:
- Role distribution — a Jensen-Shannon divergence between the two
role multisets (
HIDDEN_STATE,OBSERVATION,ACTION, ...). JS-divergence is bounded in[0, log 2]for base-eand in[0, 1]for base-2. We use base-2 and invert so that identical distributions score 1.0 and disjoint supports score 0.0. - Matrix Frobenius distance — for each Active Inference matrix
A(likelihood),B(transition),C(preferences),D(prior) present in both packages, we compute the normalized Frobenius distance||M1 - M2|| / (||M1|| + ||M2|| + eps)and convert it to a score1 - d. Matrices of mismatched shape are zero-padded to a common envelope before subtraction so the metric is defined for round-trips that change factor cardinality. We average over matrix types present in both dicts; if no shared matrix types exist the score is the neutral value0.5. - Graph structure — a normalized symmetric-difference distance
between the multisets of node roles and between the multisets of
edge-role-pairs. This is intentionally weaker than exact graph edit
distance (which is NP-hard and overkill here) but captures the
right intuition: "did the synthesized package grow or drop nodes
and edges relative to the source?". The returned score is
1 - normalized_symdiff.
The three scores are combined with the weights 0.4 * role +
0.4 * matrix + 0.2 * structural — role and matrix carry equal top
billing because they are the scientifically meaningful axes for an
Active Inference model, while structural drift is treated as a
tie-breaker. The cutoff for structurally_isomorphic defaults to 0.7 and
can be tightened by the caller.
All functions in this module are pure and free of side effects. The
only external dependency is NumPy, which the cogant test environment
provides (numpy>=2.0). Inputs may be NumPy arrays or plain
Python lists; they are coerced to float64 on entry.
DEFAULT_ISOMORPHISM_THRESHOLD = 0.7
module-attribute
Default cutoff for :attr:IsomorphismReport.structurally_isomorphic.
MATRIX_KEYS = ('A', 'B', 'C', 'D')
module-attribute
Canonical Active Inference matrix slot names used by COGANT.
IsomorphismReport
dataclass
Aggregate GNN-to-GNN distance report.
All *_score fields are in [0.0, 1.0] where 1.0 means
"identical" and 0.0 means "maximally different under this
metric". The total_score is the weighted mean of the three
component scores and is itself in [0.0, 1.0]. structurally_isomorphic
is simply total_score >= threshold.
Attributes:
| Name | Type | Description |
|---|---|---|
structural_score |
float
|
Graph-structure similarity in |
role_score |
float
|
Role distribution similarity (inverted JS
divergence) in |
matrix_score |
float
|
Frobenius-based matrix similarity in |
total_score |
float
|
Weighted mean
|
structurally_isomorphic |
bool
|
True when |
breakdown |
dict[str, Any]
|
Per-metric diagnostic detail. Keys include the three component scores, the threshold, the weighting, and (when available) per-matrix Frobenius distances. |
Source code in py/cogant/reverse/metrics.py
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 | |
summary()
Return a compact, human-readable one-line summary.
The format is::
[ISO] total=0.82 role=0.90 matrix=0.85 struct=0.60
with ISO swapped for DRIFT when
structurally_isomorphic is False.
Source code in py/cogant/reverse/metrics.py
113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 | |
compare_graph_structure(nodes_a, edges_a, nodes_b, edges_b)
Return a graph-structure similarity score in [0, 1].
We build two multisets for each graph:
role(nodes)— one bucket per node role label.(source_role, target_role)— one bucket per edge.
We then compute the normalized symmetric difference of each
multiset separately and return 1 - mean(d_nodes, d_edges).
Nodes-only graphs (no edges on either side) skip the edge term.
Edge cases:
- Both graphs empty → return
1.0(vacuously identical). - One graph empty, other non-empty → return
0.0.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nodes_a
|
Sequence[Any]
|
Iterable of node-like objects for graph A. |
required |
edges_a
|
Sequence[Any]
|
Iterable of edge-like objects for graph A. |
required |
nodes_b
|
Sequence[Any]
|
Iterable of node-like objects for graph B. |
required |
edges_b
|
Sequence[Any]
|
Iterable of edge-like objects for graph B. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score in |
Source code in py/cogant/reverse/metrics.py
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | |
compare_matrices(matrices_a, matrices_b)
Return an averaged Frobenius-similarity score in [0, 1].
For each canonical Active Inference matrix slot
(A, B, C, D) present in both input dicts and
non-empty on both sides, we compute::
1 - ||m1 - m2||_F / (||m1||_F + ||m2||_F + eps)
after zero-padding the two matrices to their common bounding shape. The returned score is the unweighted mean of these per-matrix similarities.
Edge cases:
- If neither side has any recognisable numeric matrix entry,
return
0.5(neutral — the metric is undefined, not zero). - If a key is present on only one side it is ignored (the structural-graph score is the axis that penalises missing slots).
- Extra keys beyond
{A, B, C, D}are tolerated and included.
The metric is symmetric: compare_matrices(a, b) ==
compare_matrices(b, a) up to floating point round-off.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
matrices_a
|
Mapping[str, Any]
|
Dict mapping matrix name to a 2D array-like. |
required |
matrices_b
|
Mapping[str, Any]
|
Dict mapping matrix name to a 2D array-like. |
required |
Returns:
| Type | Description |
|---|---|
float
|
Mean similarity score in |
float
|
comparable matrices exist. |
Source code in py/cogant/reverse/metrics.py
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 | |
compare_role_distributions(roles_a, roles_b)
Return a similarity score in [0, 1] for two role multisets.
The underlying distance is the Jensen-Shannon divergence in base 2,
which for two probability vectors p and q is::
JS(p, q) = 0.5 * KL(p || M) + 0.5 * KL(q || M), M = 0.5*(p+q)
and is bounded in [0, 1]. We return 1 - JS so that higher
is better.
Edge cases:
- If both distributions are empty, we return
0.0(there is no distribution to compare, and the spec asks for a neutral-low value here so that the overall isomorphism score does not spuriously inflate on degenerate inputs). - If exactly one distribution is empty, we also return
0.0(maximally different — one side has no roles at all).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
roles_a
|
Mapping[str, float]
|
Mapping from role name to count (or weight). |
required |
roles_b
|
Mapping[str, float]
|
Mapping from role name to count (or weight). |
required |
Returns:
| Type | Description |
|---|---|
float
|
Similarity score in |
float
|
distributions are identical; |
float
|
disjoint or one side is empty. |
Source code in py/cogant/reverse/metrics.py
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 | |
compute_isomorphism_report(gnn_a, gnn_b, threshold=DEFAULT_ISOMORPHISM_THRESHOLD)
Compute a full :class:IsomorphismReport for two GNN packages.
gnn_a and gnn_b are expected to be dict-like bundles with
the following optional keys:
roles—{role_name: count}multiset.matrices—{"A"|"B"|"C"|"D": array_like}dict.nodes— iterable of node objects or dicts.edges— iterable of edge objects or dicts.
Missing keys are tolerated: the corresponding component score
falls back to its documented neutral value (0.0 for roles,
0.5 for matrices, 1.0 for an empty graph).
The three component scores are combined with fixed weights::
total = 0.4 * role + 0.4 * matrix + 0.2 * structural
and structurally_isomorphic is total >= threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn_a
|
Mapping[str, Any]
|
First GNN package dict. |
required |
gnn_b
|
Mapping[str, Any]
|
Second GNN package dict. |
required |
threshold
|
float
|
Cutoff for :attr: |
DEFAULT_ISOMORPHISM_THRESHOLD
|
Returns:
| Type | Description |
|---|---|
IsomorphismReport
|
A fully populated :class: |
Source code in py/cogant/reverse/metrics.py
483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 | |
Idempotency
Helpers for the idempotency checks that drive the roundtrip ε metric.
cogant.reverse.idempotency
Round-trip idempotency verifier.
This module answers the question: "If we synthesize a Python package from a GNN markdown file and then re-run COGANT forward on the resulting package, what survived the round-trip?"
Earlier versions used one role-overlap score and called the result
"isomorphic". That was too strong: COGANT can preserve the semantic
roles that matter for active-inference interpretation while still
changing graph counts, section text, matrix values, or generated-code
behavior. The public contract is now an invariant ledger plus a
roundtrip_status taxonomy:
STRUCTURALLY_ISOMORPHIC
The strict tier: role preservation passes, graph node/edge counts
and edge kinds match, state-space and matrix invariants hold, GNN
sections are preserved, generated code imports/compiles, and the
second forward pass succeeded.
ROLE_PRESERVED
The useful weaker tier: the source and regenerated artifacts
preserve the semantic role multiset above the configured threshold,
but at least one strict structural invariant drifted or was not
observable.
DRIFT
The round-trip completed but role preservation did not meet the
configured threshold.
FAILED
Synthesis or the second forward pass failed.
The role metric is intentionally soft. The forward pipeline emits semantic mappings for any pattern it recognises, including patterns the synthesizer did not explicitly model. The verifier rewards overlap but reports extra/missing roles, graph deltas, matrix deltas, and GNN section deltas instead of collapsing distinct evidence into one label.
MATRIX_VALUE_TOLERANCE = 1e-09
module-attribute
Maximum absolute A/B/C/D value delta allowed for strict preservation.
ROLE_PRESERVATION_THRESHOLD = 0.5
module-attribute
Default minimum role-preservation score for the weaker success tier.
IdempotencyReport
dataclass
Detailed structural and semantic idempotency analysis.
Attributes:
| Name | Type | Description |
|---|---|---|
is_idempotent |
bool
|
True if the round-trip preserved structural and semantic properties above their respective thresholds. |
forward_roles |
dict[str, int]
|
Role multiset from the original forward pipeline run on the source code (before synthesis). |
reverse_roles |
dict[str, int]
|
Role multiset from the re-run of forward on the synthesized code. |
differences |
list[str]
|
List of human-readable differences found between forward_roles and reverse_roles. |
score |
float
|
A composite score in [0.0, 1.0] combining role match, structural match, and semantic match. Higher is better. |
Source code in py/cogant/reverse/idempotency.py
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 | |
RoundtripResult
dataclass
Outcome of a single round-trip verification run.
Attributes:
| Name | Type | Description |
|---|---|---|
roundtrip_status |
str
|
One of |
role_preservation_score |
float
|
Per-role mean of
|
role_preserved |
bool
|
True when |
structurally_isomorphic |
bool
|
True only when the full strict invariant ledger passes. |
matrix_preserved |
bool
|
True when observed A/B/C/D shapes and values are preserved within tolerance. |
gnn_sections_preserved |
bool
|
True when Markdown section membership survives the round-trip exactly. |
generated_code_ok |
bool
|
True when synthesized Python files import
through |
vacuous_roundtrip |
bool
|
True when both role multisets are empty and the role-preservation score's 1.0 value is vacuous. |
matrix_score |
float
|
Frobenius-based similarity of the A/B/C/D
matrix stacks produced by the two sides of the round-trip.
Range |
structural_score |
float
|
Graph-structure similarity (node/edge role
multiset symmetric difference, normalized and inverted).
Range |
original_roles |
dict[str, int]
|
Role multiset derived from the source GNN
( |
synthesized_roles |
dict[str, int]
|
Role multiset from the forward pipeline's semantic mappings after reverse-synthesis, restricted to the role-bearing definitions named in the package's semantic-target manifest (generated runtime support code is not scored). |
shape_match |
dict[str, bool]
|
Dict describing whether n_states, n_obs, and n_actions dimensions survived the round-trip. |
package_path: Absolute path to the synthesized package (kept
on disk if the caller passed a persistent tmp_dir).
original_graph_summary: Node/edge/kind summary for the first
graph view in the comparison.
synthesized_graph_summary: Node/edge/kind summary for the
graph produced by the forward re-run.
graph_delta: Count and kind deltas between the graph summaries.
gnn_diff: Section-level diff between original and regenerated
GNN Markdown when both sides are available.
matrix_delta: Shape/value deltas for A/B/C/D matrices when
parseable GNN matrix blocks are available.
invariants: Explicit pass/fail invariants for the
code → graph → GNN → code → graph cycle.
rule_evidence_trace: Rule/mapping evidence artifact from the
synthesized forward pass, suitable for dashboard review.
warnings: Non-fatal diagnostic warnings collected during the
round-trip that do not affect status.
errors: Non-fatal errors collected during the round-trip.
Source code in py/cogant/reverse/idempotency.py
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 | |
summary()
Return a human-readable single-line summary of the result.
Source code in py/cogant/reverse/idempotency.py
273 274 275 276 277 278 279 280 281 | |
check_semantic_idempotency(original_mappings, roundtrip_mappings)
Check semantic idempotency of two semantic-mapping dicts.
Compares the role populations and distributions of two sets of semantic mappings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_mappings
|
dict[str, Any]
|
Semantic mappings from the original forward run. |
required |
roundtrip_mappings
|
dict[str, Any]
|
Semantic mappings from the re-run. |
required |
Returns:
| Type | Description |
|---|---|
IdempotencyReport
|
An IdempotencyReport describing semantic similarities and |
IdempotencyReport
|
differences. |
Source code in py/cogant/reverse/idempotency.py
989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 | |
check_structural_idempotency(original_graph, roundtrip_graph)
Check structural idempotency of two program graphs.
Compares the node and edge populations of two graphs to determine if they have the same structural shape.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
original_graph
|
Any
|
The original ProgramGraph or compatible structure. |
required |
roundtrip_graph
|
Any
|
The ProgramGraph from the re-run. |
required |
Returns:
| Type | Description |
|---|---|
IdempotencyReport
|
An IdempotencyReport describing structural similarities and |
IdempotencyReport
|
differences. |
Source code in py/cogant/reverse/idempotency.py
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 | |
verify_repo_roundtrip(repo_path, output_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD)
Run forward → reverse → forward on an existing repository.
This is the entry point used by the cogant roundtrip CLI
subcommand. It:
- Runs the forward pipeline on
repo_pathand emits a GNN plus a first semantic-mappings multisetR1. - Parses the emitted GNN back into a ReverseGNNModel.
- Synthesizes a Python package from the plan.
- Runs the forward pipeline again on the synthesized package and
collects a second semantic-mappings multiset
R2. - Compares
R1andR2directly; the role-preservation score is the mean per-rolemin(count1, count2) / max(count1, count2)multiset similarity.
This comparison style (forward-vs-forward) is the strictest role preservation measurement for an existing repository: it asks whether the same pipeline sees the same roles in the synthesized package that it saw in the original. The alternative (parse the GNN, compare to forward-on-synth) is weaker because it mixes two different rule systems — the parser's role derivation and the forward pipeline's semantic rules — on the two sides of the comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
repo_path
|
str | Path
|
Repository to round-trip. |
required |
output_dir
|
str | Path | None
|
Directory to write intermediate artifacts into. If None, a temporary directory is used and cleaned up. |
None
|
role_threshold
|
float
|
Minimum role match score to accept. |
ROLE_PRESERVATION_THRESHOLD
|
Returns:
| Type | Description |
|---|---|
RoundtripResult
|
class: |
RoundtripResult
|
first forward pass and |
RoundtripResult
|
second. When the reverse parser, planning, or synthesis rejects the |
RoundtripResult
|
emitted model, the result has |
RoundtripResult
|
reason in |
Source code in py/cogant/reverse/idempotency.py
1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 | |
verify_roundtrip(gnn_path, tmp_dir=None, *, role_threshold=ROLE_PRESERVATION_THRESHOLD, keep_tmp=False)
Run a full round-trip on a GNN markdown file and score the result.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gnn_path
|
str | Path
|
Path to a GNN markdown file produced by COGANT (or any conforming emitter). |
required |
tmp_dir
|
str | Path | None
|
Optional directory where the synthesized package
should be written. If None, a temporary directory is
created and removed after the run (unless |
None
|
role_threshold
|
float
|
Minimum |
ROLE_PRESERVATION_THRESHOLD
|
keep_tmp
|
bool
|
When True, do not delete the temporary directory after the run. Useful for debugging. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
RoundtripResult
|
class: |
RoundtripResult
|
has been parsed, the result is always returned — a model that |
|
RoundtripResult
|
planning or synthesis rejects yields |
|
RoundtripResult
|
and exceptions inside the forward pipeline are captured as |
|
RoundtripResult
|
|
|
RoundtripResult
|
is removed even when the run fails. |
Source code in py/cogant/reverse/idempotency.py
1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 | |
Examples
The full reverse surface (parser, callable, planner, synthesizer, matrices, metrics, idempotency) is exercised by:
- Zoo:
examples/zoo/01_simple_state/— round-trip target with the smallest non-trivialMatrixFunctionsclosure. - Zoo:
examples/zoo/04_pomdp_minimal/— A/B/C/D round-trip used byverify_repo_roundtrip. - Zoo:
examples/zoo/13_js_observer/— cross-language reverse target (JS → GNN → Python package). - Cookbook: Recipe 6: Generating code from a GNN —
synthesize_packagewalkthrough. - Cookbook: Recipe 7: Reverse with custom output layout — planner / synthesizer customization.
- Tutorial: Tutorial 6: Reverse mode — GNN to code — full CLI + programmatic walkthrough including ε metric.