fuzzybits-server 0.17.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. fuzzybits_server/.dockerignore +64 -0
  2. fuzzybits_server/__init__.py +15 -0
  3. fuzzybits_server/app.py +93 -0
  4. fuzzybits_server/config.py +310 -0
  5. fuzzybits_server/convergence/__init__.py +100 -0
  6. fuzzybits_server/convergence/gbas.py +229 -0
  7. fuzzybits_server/convergence/metrics.py +164 -0
  8. fuzzybits_server/convergence/policies.py +387 -0
  9. fuzzybits_server/convergence/runner.py +398 -0
  10. fuzzybits_server/convergence/sampling.py +409 -0
  11. fuzzybits_server/convergence/special.py +280 -0
  12. fuzzybits_server/convergence/tally.py +179 -0
  13. fuzzybits_server/event_hub.py +58 -0
  14. fuzzybits_server/event_log.py +16 -0
  15. fuzzybits_server/fault_tree_payload.py +899 -0
  16. fuzzybits_server/model_oracle_p.json +44 -0
  17. fuzzybits_server/native.py +536 -0
  18. fuzzybits_server/routes.py +408 -0
  19. fuzzybits_server/state.py +67 -0
  20. fuzzybits_server/supervisor.py +193 -0
  21. fuzzybits_server/ui.py +84 -0
  22. fuzzybits_server/webui/.vite/manifest.json +26 -0
  23. fuzzybits_server/webui/assets/Playground-B6V8NzhX.css +1 -0
  24. fuzzybits_server/webui/assets/Playground-CSpFbzwZ.js +5481 -0
  25. fuzzybits_server/webui/assets/Playground-CSpFbzwZ.js.map +1 -0
  26. fuzzybits_server/webui/assets/index-BnegRRhI.css +1 -0
  27. fuzzybits_server/webui/assets/index-C3oGCBE0.js +13 -0
  28. fuzzybits_server/webui/assets/index-C3oGCBE0.js.map +1 -0
  29. fuzzybits_server/webui/index.html +24 -0
  30. fuzzybits_server/worker.py +64 -0
  31. fuzzybits_server-0.17.0.dist-info/METADATA +281 -0
  32. fuzzybits_server-0.17.0.dist-info/RECORD +34 -0
  33. fuzzybits_server-0.17.0.dist-info/WHEEL +4 -0
  34. fuzzybits_server-0.17.0.dist-info/entry_points.txt +2 -0
@@ -0,0 +1,899 @@
1
+ """Parse MEF fault-tree XML into the JSON graph consumed by the site canvas."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ import xml.etree.ElementTree as ET
8
+ from functools import lru_cache
9
+ from pathlib import Path
10
+ from typing import Any
11
+
12
+ from fuzzybits_server.config import server_data_dir
13
+ from fuzzybits_server.native import CompileProduct, native_import_error, run_compile_isolated
14
+
15
+
16
+ DAG_NODE_TYPES: tuple[str, ...] = (
17
+ "basic_event",
18
+ "unknown_event",
19
+ "and_gate",
20
+ "nand_gate",
21
+ "or_gate",
22
+ "nor_gate",
23
+ "xor_gate",
24
+ "xnor_gate",
25
+ "atleast_gate",
26
+ "not_gate",
27
+ "null_gate",
28
+ "constant_event",
29
+ )
30
+ NODE_TYPE_BY_NAME = {name: index for index, name in enumerate(DAG_NODE_TYPES)}
31
+
32
+ NODE_TYPE_BY_CONNECTIVE = {
33
+ "and": 2,
34
+ "nand": 3,
35
+ "or": 4,
36
+ "nor": 5,
37
+ "xor": 6,
38
+ "xnor": 7,
39
+ "atleast": 8,
40
+ "not": 9,
41
+ "null": 10,
42
+ }
43
+
44
+ REFERENCE_TAGS = {"basic-event", "gate", "house-event", "event"}
45
+ NON_OPERATIONAL_GATE_CHILDREN = {"label", "description"}
46
+
47
+
48
+ @lru_cache(maxsize=1)
49
+ def _model_oracle_p() -> dict[str, float]:
50
+ """Known oracle probabilities keyed by canonical model id.
51
+
52
+ This resource is generated from the published build-data corpus and is
53
+ intentionally optional: missing or malformed data should not block model
54
+ discovery in local/dev containers.
55
+ """
56
+ path = Path(__file__).with_name("model_oracle_p.json")
57
+ try:
58
+ payload = json.loads(path.read_text())
59
+ except (OSError, json.JSONDecodeError):
60
+ return {}
61
+ if not isinstance(payload, dict):
62
+ return {}
63
+ out: dict[str, float] = {}
64
+ for key, value in payload.items():
65
+ if isinstance(key, str) and isinstance(value, (int, float)) and value >= 0:
66
+ out[key.lower()] = float(value)
67
+ return out
68
+
69
+
70
+ def _oracle_p_for_model_id(model_id: str, oracle_p_by_model: dict[str, float]) -> float | None:
71
+ """Return oracle probability for flat or root-relative catalog ids."""
72
+ if model_id in oracle_p_by_model:
73
+ return oracle_p_by_model[model_id]
74
+ basename = model_id.rsplit("/", 1)[-1]
75
+ return oracle_p_by_model.get(basename)
76
+
77
+
78
+ def _tag(element: ET.Element) -> str:
79
+ return element.tag.rsplit("}", 1)[-1]
80
+
81
+
82
+ def _node_id(kind: str, name: str) -> str:
83
+ return f"{kind}:{name}"
84
+
85
+
86
+ def _qualified_gate_name(scope: str | None, name: str) -> str:
87
+ if not scope or "." in name:
88
+ return name
89
+ return f"{scope}.{name}"
90
+
91
+
92
+ def _reference_node_id(element: ET.Element, scope: str | None = None) -> str | None:
93
+ """Map a connective child element to a stable canvas node id."""
94
+ tag = _tag(element)
95
+ name = element.attrib.get("name")
96
+ if not name:
97
+ return None
98
+ if tag == "basic-event":
99
+ return _node_id("basic_event", name)
100
+ if tag == "house-event":
101
+ return _node_id("house_event", name)
102
+ if tag == "gate":
103
+ return _node_id("gate", _qualified_gate_name(scope, name))
104
+ if tag == "event":
105
+ ref_type = (element.attrib.get("type") or "").strip().lower()
106
+ if ref_type == "gate":
107
+ return _node_id("gate", _qualified_gate_name(scope, name))
108
+ if ref_type in {"basic-event", "basic_event", "basic"}:
109
+ return _node_id("basic_event", name)
110
+ if ref_type in {"house-event", "house_event", "house"}:
111
+ return _node_id("house_event", name)
112
+ return None
113
+
114
+
115
+ def _gate_connective(gate: ET.Element) -> tuple[ET.Element | None, str]:
116
+ child = next((child for child in gate if _tag(child) not in NON_OPERATIONAL_GATE_CHILDREN), None)
117
+ if child is None:
118
+ return None, "unknown"
119
+ if _tag(child) in REFERENCE_TAGS:
120
+ return child, "null"
121
+ return child, _tag(child)
122
+
123
+
124
+ def _connective_children(connective: ET.Element | None, connective_name: str) -> list[ET.Element]:
125
+ if connective is None:
126
+ return []
127
+ if connective_name == "null":
128
+ return [connective]
129
+ return [child for child in connective if _tag(child) not in NON_OPERATIONAL_GATE_CHILDREN]
130
+
131
+
132
+ def _ensure_reference_node(nodes: dict[str, dict[str, Any]], node_id: str) -> None:
133
+ if node_id in nodes:
134
+ return
135
+ kind, _, name = node_id.partition(":")
136
+ if kind == "gate":
137
+ nodes[node_id] = {
138
+ "id": node_id,
139
+ "kind": "gate",
140
+ "label": name,
141
+ "connective": "unknown",
142
+ }
143
+ elif kind == "basic_event":
144
+ nodes[node_id] = {
145
+ "id": node_id,
146
+ "kind": "basic_event",
147
+ "label": name,
148
+ }
149
+ elif kind == "house_event":
150
+ nodes[node_id] = {
151
+ "id": node_id,
152
+ "kind": "house_event",
153
+ "label": name,
154
+ }
155
+
156
+
157
+ def _iter_scoped_gate_defs(
158
+ element: ET.Element,
159
+ scope: str | None = None,
160
+ ) -> list[tuple[str, ET.Element, str | None]]:
161
+ gate_defs: list[tuple[str, ET.Element, str | None]] = []
162
+ for child in element:
163
+ tag = _tag(child)
164
+ if tag == "define-gate":
165
+ name = child.attrib.get("name")
166
+ if name:
167
+ gate_defs.append((_qualified_gate_name(scope, name), child, scope))
168
+ elif tag == "define-component":
169
+ name = child.attrib.get("name")
170
+ component_scope = _qualified_gate_name(scope, name) if name else scope
171
+ gate_defs.extend(_iter_scoped_gate_defs(child, component_scope))
172
+ return gate_defs
173
+
174
+
175
+ def _child_text(element: ET.Element, tag_name: str) -> str | None:
176
+ child = next((child for child in element if _tag(child) == tag_name), None)
177
+ if child is None or child.text is None:
178
+ return None
179
+ text = " ".join(child.text.split())
180
+ return text or None
181
+
182
+
183
+ def _attribute_value(element: ET.Element, name: str) -> str | None:
184
+ for attribute in element.iter():
185
+ if _tag(attribute) == "attribute" and attribute.attrib.get("name") == name:
186
+ return attribute.attrib.get("value")
187
+ return None
188
+
189
+
190
+ def _constant_value(element: ET.Element) -> str | None:
191
+ constant = next((child for child in element if _tag(child) == "constant"), None)
192
+ return constant.attrib.get("value") if constant is not None else None
193
+
194
+
195
+ def _infer_fault_tree_top(
196
+ gate_defs: list[tuple[str, ET.Element, str | None]],
197
+ edges: list[dict[str, str]],
198
+ ) -> str | None:
199
+ """Use a single top gate only when the graph has one gate root."""
200
+ gate_ids = [_node_id("gate", name) for name, _, _ in gate_defs]
201
+ targets = {edge["target"] for edge in edges}
202
+ roots = [gate_id for gate_id in gate_ids if gate_id not in targets]
203
+ if len(roots) == 1:
204
+ return roots[0]
205
+ return None
206
+
207
+
208
+ def aralia_model_search_roots() -> list[Path]:
209
+ """Search roots for OpenPSA/Aralia ``*.xml`` models.
210
+
211
+ Missing directories are skipped by callers. With no data mount the catalog
212
+ is empty; the server still serves ``/healthz`` and the pytest suite.
213
+ """
214
+ roots: list[Path] = []
215
+ seen: set[str] = set()
216
+
217
+ def _add(path: Path) -> None:
218
+ key = str(path)
219
+ if key in seen:
220
+ return
221
+ seen.add(key)
222
+ roots.append(path)
223
+
224
+ env_root = os.getenv("MCSCRAM_ARALIA_INPUT_DIR")
225
+ if env_root:
226
+ _add(Path(env_root))
227
+
228
+ data = server_data_dir()
229
+ if data is not None:
230
+ _add(data)
231
+ _add(data / "Aralia")
232
+ _add(data / "input")
233
+ _add(data / "input" / "Aralia")
234
+
235
+ # Legacy bench image copies `input/*` into `/app/input/` (flattened).
236
+ _add(Path("/app/input"))
237
+ _add(Path("/app/input/Aralia"))
238
+
239
+ # Walk up from this file to the fuzzybits repo root (the directory that
240
+ # contains tools/server/pyproject.toml). Installed copies may live at a
241
+ # shorter path than the source tree; skip rather than IndexError.
242
+ for parent in Path(__file__).resolve().parents:
243
+ if (parent / "tools" / "server" / "pyproject.toml").is_file():
244
+ _add(parent / "input" / "Aralia")
245
+ break
246
+ return roots
247
+
248
+
249
+ def _normalise_model_id_token(model_id: str) -> str:
250
+ token = model_id.strip().lower().removesuffix(".xml")
251
+ if not token:
252
+ raise ValueError("model_id is required")
253
+ if any(part in {"", ".", ".."} for part in token.split("/")):
254
+ raise ValueError(f"invalid model_id: {model_id}")
255
+ return token
256
+
257
+
258
+ def _model_id_for_path(root: Path, path: Path) -> str:
259
+ return path.relative_to(root).with_suffix("").as_posix().lower()
260
+
261
+
262
+ def resolve_model_xml_path(model_id: str) -> Path:
263
+ token = _normalise_model_id_token(model_id)
264
+ rel_parts = token.split("/")
265
+ for root in aralia_model_search_roots():
266
+ if not root.is_dir():
267
+ continue
268
+ candidate = root.joinpath(*rel_parts).with_suffix(".xml")
269
+ if candidate.is_file():
270
+ return candidate
271
+ for path in root.rglob("*.xml"):
272
+ if path.is_file() and _model_id_for_path(root, path) == token:
273
+ return path
274
+ raise FileNotFoundError(f"Unknown model_id: {model_id}")
275
+
276
+
277
+ def list_aralia_xml_inputs() -> dict[str, Any]:
278
+ """Discover ``*.xml`` under :func:`aralia_model_search_roots` (recursive).
279
+
280
+ Each entry's ``modelId`` is the path relative to its search root, without
281
+ the ``.xml`` suffix, lowercased and POSIX-normalised. The first root in
282
+ search order wins when the same ``modelId`` appears in multiple roots.
283
+ """
284
+ models: list[dict[str, Any]] = []
285
+ seen: set[str] = set()
286
+ roots_out: list[str] = []
287
+ oracle_p_by_model = _model_oracle_p()
288
+
289
+ for root in aralia_model_search_roots():
290
+ if not root.is_dir():
291
+ continue
292
+ roots_out.append(str(root.resolve()))
293
+ for path in sorted(root.rglob("*.xml")):
294
+ if not path.is_file():
295
+ continue
296
+ rel = path.relative_to(root)
297
+ model_id = _model_id_for_path(root, path)
298
+ if model_id in seen:
299
+ continue
300
+ seen.add(model_id)
301
+ entry: dict[str, Any] = {
302
+ "modelId": model_id,
303
+ "relativePath": rel.as_posix(),
304
+ "root": str(root.resolve()),
305
+ }
306
+ oracle_p = _oracle_p_for_model_id(model_id, oracle_p_by_model)
307
+ if oracle_p is not None:
308
+ entry["oracle_p"] = oracle_p
309
+ models.append(entry)
310
+
311
+ models.sort(key=lambda row: row["modelId"])
312
+ return {
313
+ "roots": roots_out,
314
+ "models": models,
315
+ "modelIds": [row["modelId"] for row in models],
316
+ }
317
+
318
+
319
+ def build_fault_tree_payload(input_files: list[str]) -> dict[str, Any]:
320
+ if not input_files:
321
+ return {"model": None, "top": None, "nodes": [], "edges": []}
322
+
323
+ path = Path(input_files[0])
324
+ tree = ET.parse(path)
325
+ root = tree.getroot()
326
+ fault_tree = next((child for child in root.iter() if _tag(child) == "define-fault-tree"), None)
327
+ if fault_tree is None:
328
+ return {"model": path.name, "top": None, "nodes": [], "edges": []}
329
+
330
+ model_name = fault_tree.attrib.get("name") or path.stem
331
+ gate_defs = _iter_scoped_gate_defs(fault_tree)
332
+ basic_defs = [child for child in root.iter() if _tag(child) == "define-basic-event"]
333
+ house_defs = [child for child in root.iter() if _tag(child) == "define-house-event"]
334
+
335
+ nodes: dict[str, dict[str, Any]] = {}
336
+ edges: list[dict[str, str]] = []
337
+
338
+ for basic in basic_defs:
339
+ name = basic.attrib.get("name")
340
+ if not name:
341
+ continue
342
+ nodes[_node_id("basic_event", name)] = {
343
+ "id": _node_id("basic_event", name),
344
+ "kind": "basic_event",
345
+ "label": name,
346
+ "description": _child_text(basic, "label"),
347
+ "flavor": _attribute_value(basic, "flavor"),
348
+ }
349
+
350
+ for house in house_defs:
351
+ name = house.attrib.get("name")
352
+ if not name:
353
+ continue
354
+ nodes[_node_id("house_event", name)] = {
355
+ "id": _node_id("house_event", name),
356
+ "kind": "house_event",
357
+ "label": name,
358
+ "description": _child_text(house, "label"),
359
+ "value": _constant_value(house),
360
+ }
361
+
362
+ for name, gate, scope in gate_defs:
363
+ gate_id = _node_id("gate", name)
364
+ connective, connective_name = _gate_connective(gate)
365
+ nodes[gate_id] = {
366
+ "id": gate_id,
367
+ "kind": "gate",
368
+ "label": name,
369
+ "description": _child_text(gate, "label"),
370
+ "connective": connective_name,
371
+ "min": connective.attrib.get("min") if connective is not None else None,
372
+ "max": connective.attrib.get("max") if connective is not None else None,
373
+ }
374
+ if connective is None:
375
+ continue
376
+ for child in _connective_children(connective, connective_name):
377
+ child_id = _reference_node_id(child, scope)
378
+ if child_id is None:
379
+ continue
380
+ _ensure_reference_node(nodes, child_id)
381
+ edges.append({"source": gate_id, "target": child_id})
382
+
383
+ top = _infer_fault_tree_top(gate_defs, edges)
384
+
385
+ return {
386
+ "model": model_name,
387
+ "source": str(path),
388
+ "top": top,
389
+ "nodes": list(nodes.values()),
390
+ "edges": edges,
391
+ }
392
+
393
+
394
+ def build_source_dag_payload(input_files: list[str]) -> dict[str, Any]:
395
+ return _build_source_dag_payload(input_files)
396
+
397
+
398
+ def build_compiled_dag_payload(
399
+ input_files: list[str],
400
+ options: dict[str, Any] | None = None,
401
+ *,
402
+ pcfb_path: str | None = None,
403
+ ) -> dict[str, Any]:
404
+ """Build the WebGL DAG payload from the native compiled PDAG."""
405
+ return _build_native_dag_payload(input_files, options, graph_kind="compiled", pcfb_path=pcfb_path)
406
+
407
+
408
+ def build_kernel_dag_payload(
409
+ input_files: list[str],
410
+ options: dict[str, Any] | None = None,
411
+ *,
412
+ pcfb_path: str | None = None,
413
+ ) -> dict[str, Any]:
414
+ """Build the WebGL DAG payload from the DirectEval kernel execution DAG."""
415
+ return _build_native_dag_payload(input_files, options, graph_kind="kernel", pcfb_path=pcfb_path)
416
+
417
+
418
+ def build_dag_payload(
419
+ input_files: list[str],
420
+ options: dict[str, Any] | None = None,
421
+ *,
422
+ pcfb_path: str | None = None,
423
+ ) -> dict[str, Any]:
424
+ return build_compiled_dag_payload(input_files, options, pcfb_path=pcfb_path)
425
+
426
+
427
+ def build_execution_plan_payload(
428
+ input_files: list[str],
429
+ options: dict[str, Any] | None = None,
430
+ *,
431
+ pcfb_path: str | None = None,
432
+ ) -> dict[str, Any]:
433
+ """Build the native DirectEval execution-plan payload."""
434
+ if not input_files and not pcfb_path:
435
+ return {"schema": "mcscram.execution_plan.v1", "partitions": [], "dependency_edges": [], "nodes": []}
436
+
437
+ if import_error := native_import_error():
438
+ return {
439
+ "schema": "mcscram.execution_plan.v1",
440
+ "error": import_error,
441
+ "partitions": [],
442
+ "dependency_edges": [],
443
+ "nodes": [],
444
+ }
445
+
446
+ result = run_compile_isolated(
447
+ input_files, options, CompileProduct.EXECUTION_PLAN, pcfb_path=pcfb_path
448
+ )
449
+ if not result.ok:
450
+ return {
451
+ "schema": "mcscram.execution_plan.v1",
452
+ "error": result.error,
453
+ "partitions": [],
454
+ "dependency_edges": [],
455
+ "nodes": [],
456
+ }
457
+ return result.payload
458
+
459
+
460
+ def build_sample_shape_payload(
461
+ input_files: list[str],
462
+ options: dict[str, Any] | None = None,
463
+ *,
464
+ pcfb_path: str | None = None,
465
+ ) -> dict[str, Any]:
466
+ """Build the DirectEval layer-manager sample-shape payload for sampler controls."""
467
+ if not input_files and not pcfb_path:
468
+ return {"sample_shape": None}
469
+
470
+ if import_error := native_import_error():
471
+ return {"sample_shape": None, "error": import_error}
472
+
473
+ result = run_compile_isolated(
474
+ input_files, options, CompileProduct.SAMPLE_SHAPE, pcfb_path=pcfb_path
475
+ )
476
+ if not result.ok:
477
+ return {"sample_shape": None, "error": result.error}
478
+ return result.payload
479
+
480
+
481
+ def build_dag_bundle_payload(
482
+ input_files: list[str],
483
+ options: dict[str, Any] | None = None,
484
+ *,
485
+ pcfb_path: str | None = None,
486
+ ) -> dict[str, Any]:
487
+ """Build source, compiled, and kernel DAG payloads with one native compilation."""
488
+ source_payload = _build_source_dag_payload(input_files)
489
+ if not input_files and not pcfb_path:
490
+ empty = _empty_dag_payload(None)
491
+ return {"source": source_payload, "compiled": empty, "kernel": empty}
492
+
493
+ if import_error := native_import_error():
494
+ compiled_payload = dict(source_payload)
495
+ compiled_payload["compiled"] = False
496
+ compiled_payload["compileError"] = import_error
497
+ kernel_payload = dict(compiled_payload)
498
+ kernel_payload["graphKind"] = "kernel_dag"
499
+ return {"source": source_payload, "compiled": compiled_payload, "kernel": kernel_payload}
500
+
501
+ result = run_compile_isolated(
502
+ input_files, options, CompileProduct.BUNDLE, pcfb_path=pcfb_path
503
+ )
504
+ if not result.ok:
505
+ compiled_payload = dict(source_payload)
506
+ compiled_payload["compiled"] = False
507
+ compiled_payload["compileError"] = result.error
508
+ kernel_payload = dict(compiled_payload)
509
+ kernel_payload["graphKind"] = "kernel_dag"
510
+ return {"source": source_payload, "compiled": compiled_payload, "kernel": kernel_payload}
511
+
512
+ return {
513
+ "source": source_payload,
514
+ "compiled": _native_graph_to_payload(result.payload["compiled"]),
515
+ "kernel": _native_graph_to_payload(result.payload["kernel"]),
516
+ }
517
+
518
+
519
+ def _build_native_dag_payload(
520
+ input_files: list[str],
521
+ options: dict[str, Any] | None,
522
+ *,
523
+ graph_kind: str,
524
+ pcfb_path: str | None = None,
525
+ ) -> dict[str, Any]:
526
+ if not input_files and not pcfb_path:
527
+ return _empty_dag_payload(None)
528
+
529
+ if import_error := native_import_error():
530
+ payload = _build_source_dag_payload(input_files)
531
+ payload["compiled"] = False
532
+ payload["compileError"] = import_error
533
+ return payload
534
+
535
+ product = CompileProduct.KERNEL_GRAPH if graph_kind == "kernel" else CompileProduct.GRAPH
536
+ result = run_compile_isolated(input_files, options, product, pcfb_path=pcfb_path)
537
+ if not result.ok:
538
+ payload = _build_source_dag_payload(input_files)
539
+ payload["compiled"] = False
540
+ payload["compileError"] = result.error
541
+ return payload
542
+ return _native_graph_to_payload(result.payload)
543
+
544
+
545
+ def _native_graph_to_payload(compiled_graph: dict[str, Any]) -> dict[str, Any]:
546
+ render_graph = _compiled_graph_to_render_graph(compiled_graph)
547
+ payload = _columnar_dag_payload(
548
+ model_name=compiled_graph.get("model"),
549
+ source=compiled_graph.get("source"),
550
+ top=render_graph["top"],
551
+ graph=render_graph,
552
+ )
553
+ payload["compiled"] = True
554
+ payload["target"] = compiled_graph.get("target")
555
+ payload["rootComplement"] = compiled_graph.get("root_complement", False)
556
+ payload["compilation"] = compiled_graph.get("compilation", {})
557
+ payload["graphKind"] = compiled_graph.get("graph_kind", "compiled_pdag")
558
+ if kernel := compiled_graph.get("kernel"):
559
+ payload["kernel"] = kernel
560
+ if payload["graphKind"] == "kernel_dag":
561
+ _rotate_payload_counter_clockwise(payload)
562
+ return payload
563
+
564
+
565
+ def _rotate_payload_counter_clockwise(payload: dict[str, Any]) -> None:
566
+ """Rotate world coordinates 90 degrees counter-clockwise in canvas space."""
567
+ nodes = payload["nodes"]
568
+ x_coordinates = nodes["x"]
569
+ y_coordinates = nodes["y"]
570
+ if not x_coordinates or not y_coordinates:
571
+ return
572
+
573
+ # Canvas world-space y increases downward, so visual CCW is (x, y) -> (y, -x).
574
+ rotated_x = [float(y) for y in y_coordinates]
575
+ rotated_y = [-float(x) for x in x_coordinates]
576
+ nodes["x"] = rotated_x
577
+ nodes["y"] = rotated_y
578
+
579
+ min_x = min(rotated_x)
580
+ max_x = max(rotated_x)
581
+ min_y = min(rotated_y)
582
+ max_y = max(rotated_y)
583
+ payload["bounds"] = {
584
+ "minX": min_x,
585
+ "minY": min_y,
586
+ "maxX": max_x,
587
+ "maxY": max_y,
588
+ "width": max(max_x - min_x, 1.0),
589
+ "height": max(max_y - min_y, 1.0),
590
+ }
591
+
592
+
593
+ def _build_source_dag_payload(input_files: list[str]) -> dict[str, Any]:
594
+ """Build a render-ready, columnar DAG payload for the WebGL2 viewer.
595
+
596
+ Shape contract:
597
+ - `nodes.x[i]`, `nodes.y[i]`, and `nodes.type[i]` describe vertex `i`.
598
+ - `edges.source[j]` and `edges.target[j]` are integer node indices.
599
+ - `edges.complemented[j]` is 1 when the native edge target is signed negative.
600
+ - coordinates are scale-agnostic world units; the client only applies a
601
+ uniform affine transform for pan/zoom.
602
+ - `nodeTypes[n]` is a stable semantic type string. Shape, fill, and
603
+ shader styling remain frontend concerns.
604
+ """
605
+ if not input_files:
606
+ return _empty_dag_payload(None)
607
+
608
+ path = Path(input_files[0])
609
+ tree = ET.parse(path)
610
+ root = tree.getroot()
611
+ fault_tree = next((child for child in root.iter() if _tag(child) == "define-fault-tree"), None)
612
+ if fault_tree is None:
613
+ return _empty_dag_payload(path.name, source=str(path))
614
+
615
+ model_name = fault_tree.attrib.get("name") or path.stem
616
+ graph = _parse_fault_tree_graph(fault_tree)
617
+ return _columnar_dag_payload(model_name=model_name, source=str(path), top=graph["top"], graph=graph)
618
+
619
+
620
+ def _columnar_dag_payload(
621
+ model_name: str | None,
622
+ source: str | None,
623
+ top: str | None,
624
+ graph: dict[str, Any],
625
+ ) -> dict[str, Any]:
626
+ node_ids = list(graph["nodes"].keys())
627
+ index_by_id = {node_id: index for index, node_id in enumerate(node_ids)}
628
+ depths = _dag_depths(node_ids, graph["children_by_source"], graph["parents_by_target"])
629
+ has_kernel_layout = all(
630
+ "layer" in graph["nodes"][node_id] and "partition" in graph["nodes"][node_id]
631
+ for node_id in node_ids
632
+ )
633
+
634
+ layers: dict[int, list[str]] = {}
635
+ for node_id in node_ids:
636
+ layer = int(graph["nodes"][node_id]["layer"]) if has_kernel_layout else depths.get(node_id, 0)
637
+ layers.setdefault(layer, []).append(node_id)
638
+
639
+ x_coordinates = [0.0] * len(node_ids)
640
+ y_coordinates = [0.0] * len(node_ids)
641
+ node_types = [0] * len(node_ids)
642
+ node_layers = [0] * len(node_ids)
643
+ node_partitions = [0] * len(node_ids)
644
+ min_x = min_y = 0.0
645
+ max_x = max_y = 0.0
646
+ seen_coordinate = False
647
+
648
+ for layer in sorted(layers):
649
+ ids = layers[layer]
650
+ positioned = _position_layer_nodes(ids, graph["nodes"]) if has_kernel_layout else [
651
+ (node_id, float(offset - (len(ids) - 1) / 2))
652
+ for offset, node_id in enumerate(ids)
653
+ ]
654
+ for node_id, x in positioned:
655
+ index = index_by_id[node_id]
656
+ node = graph["nodes"][node_id]
657
+ partition = int(node.get("partition", 0))
658
+ y = float(layer)
659
+ x_coordinates[index] = x
660
+ y_coordinates[index] = y
661
+ node_types[index] = int(node["type"])
662
+ node_layers[index] = int(layer)
663
+ node_partitions[index] = partition
664
+ if not seen_coordinate:
665
+ min_x = max_x = x
666
+ min_y = max_y = y
667
+ seen_coordinate = True
668
+ else:
669
+ min_x = min(min_x, x)
670
+ max_x = max(max_x, x)
671
+ min_y = min(min_y, y)
672
+ max_y = max(max_y, y)
673
+
674
+ sources: list[int] = []
675
+ targets: list[int] = []
676
+ complemented: list[int] = []
677
+ for edge in graph["edges"]:
678
+ if len(edge) == 3:
679
+ source_id, target_id, edge_complemented = edge
680
+ else:
681
+ source_id, target_id = edge
682
+ edge_complemented = False
683
+ source_index = index_by_id.get(source_id)
684
+ target_index = index_by_id.get(target_id)
685
+ if source_index is None or target_index is None:
686
+ continue
687
+ sources.append(source_index)
688
+ targets.append(target_index)
689
+ complemented.append(1 if edge_complemented else 0)
690
+
691
+ return {
692
+ "version": 1,
693
+ "model": model_name,
694
+ "source": source,
695
+ "top": index_by_id.get(top) if top else None,
696
+ "bounds": {
697
+ "minX": min_x,
698
+ "minY": min_y,
699
+ "maxX": max_x,
700
+ "maxY": max_y,
701
+ "width": max(max_x - min_x, 1.0),
702
+ "height": max(max_y - min_y, 1.0),
703
+ },
704
+ "nodeTypes": list(DAG_NODE_TYPES),
705
+ "nodes": {
706
+ "count": len(node_ids),
707
+ "x": x_coordinates,
708
+ "y": y_coordinates,
709
+ "type": node_types,
710
+ "layer": node_layers,
711
+ "partition": node_partitions,
712
+ },
713
+ "edges": {
714
+ "count": len(sources),
715
+ "source": sources,
716
+ "target": targets,
717
+ "complemented": complemented,
718
+ },
719
+ "counts": graph["counts"],
720
+ }
721
+
722
+
723
+ def _position_layer_nodes(node_ids: list[str], nodes: dict[str, dict[str, Any]]) -> list[tuple[str, float]]:
724
+ groups: dict[int, list[str]] = {}
725
+ for node_id in node_ids:
726
+ groups.setdefault(int(nodes[node_id].get("partition", 0)), []).append(node_id)
727
+
728
+ ordered_groups = [(partition, groups[partition]) for partition in sorted(groups)]
729
+ widths = [max(1.0, 0.35 * (len(ids) - 1) + 1.0) for _, ids in ordered_groups]
730
+ total_width = sum(widths) + max(0, len(widths) - 1) * 0.8
731
+ cursor = -total_width / 2
732
+ positioned: list[tuple[str, float]] = []
733
+
734
+ for (_, ids), width in zip(ordered_groups, widths, strict=True):
735
+ ids.sort(key=lambda node_id: int(node_id))
736
+ center = cursor + width / 2
737
+ midpoint = (len(ids) - 1) / 2
738
+ for offset, node_id in enumerate(ids):
739
+ positioned.append((node_id, center + (offset - midpoint) * 0.35))
740
+ cursor += width + 0.8
741
+
742
+ return positioned
743
+
744
+
745
+ def _compiled_graph_to_render_graph(compiled_graph: dict[str, Any]) -> dict[str, Any]:
746
+ nodes: dict[str, dict[str, Any]] = {}
747
+ edges: list[tuple[str, str, bool]] = []
748
+ children_by_source: dict[str, list[str]] = {}
749
+ parents_by_target: dict[str, list[str]] = {}
750
+ counts = {"gate": 0, "basic_event": 0, "unknown_event": 0, "constant": 0}
751
+
752
+ for node in compiled_graph.get("nodes", []):
753
+ node_id = str(int(node["index"]))
754
+ kind = str(node.get("kind", "unknown_event"))
755
+ node_type = _compiled_node_type(node)
756
+ nodes[node_id] = {
757
+ "kind": kind,
758
+ "type": NODE_TYPE_BY_NAME.get(node_type, NODE_TYPE_BY_NAME["unknown_event"]),
759
+ }
760
+ if "layer" in node:
761
+ nodes[node_id]["layer"] = int(node["layer"])
762
+ if "partition" in node:
763
+ nodes[node_id]["partition"] = int(node["partition"])
764
+ if kind in counts:
765
+ counts[kind] += 1
766
+ else:
767
+ counts["unknown_event"] += 1
768
+
769
+ for edge in compiled_graph.get("edges", []):
770
+ source_id = str(int(edge["source"]))
771
+ raw_target = int(edge["target"])
772
+ target_id = str(abs(raw_target))
773
+ if source_id not in nodes or target_id not in nodes:
774
+ continue
775
+ edges.append((source_id, target_id, raw_target < 0))
776
+ children_by_source.setdefault(source_id, []).append(target_id)
777
+ parents_by_target.setdefault(target_id, []).append(source_id)
778
+
779
+ top = compiled_graph.get("top")
780
+ return {
781
+ "top": str(abs(int(top))) if top is not None else None,
782
+ "nodes": nodes,
783
+ "edges": edges,
784
+ "children_by_source": children_by_source,
785
+ "parents_by_target": parents_by_target,
786
+ "counts": counts,
787
+ }
788
+
789
+
790
+ def _compiled_node_type(node: dict[str, Any]) -> str:
791
+ kind = node.get("kind")
792
+ if kind == "basic_event":
793
+ return "basic_event"
794
+ if kind == "constant":
795
+ return "constant_event"
796
+ if kind != "gate":
797
+ return "unknown_event"
798
+ connective = str(node.get("connective") or "unknown")
799
+ if connective == "atleast":
800
+ return "atleast_gate"
801
+ candidate = f"{connective}_gate"
802
+ return candidate if candidate in NODE_TYPE_BY_NAME else "unknown_event"
803
+
804
+
805
+ def _empty_dag_payload(model: str | None, source: str | None = None) -> dict[str, Any]:
806
+ return {
807
+ "version": 1,
808
+ "model": model,
809
+ "source": source,
810
+ "top": None,
811
+ "bounds": {"minX": 0.0, "minY": 0.0, "maxX": 1.0, "maxY": 1.0, "width": 1.0, "height": 1.0},
812
+ "nodeTypes": list(DAG_NODE_TYPES),
813
+ "nodes": {"count": 0, "x": [], "y": [], "type": []},
814
+ "edges": {"count": 0, "source": [], "target": [], "complemented": []},
815
+ "counts": {"gate": 0, "basic_event": 0, "unknown_event": 0},
816
+ }
817
+
818
+
819
+ def _parse_fault_tree_graph(fault_tree: ET.Element) -> dict[str, Any]:
820
+ gate_defs = _iter_scoped_gate_defs(fault_tree)
821
+ basic_defs = [child for child in fault_tree if _tag(child) == "define-basic-event"]
822
+
823
+ nodes: dict[str, dict[str, Any]] = {}
824
+ edges: list[tuple[str, str]] = []
825
+ children_by_source: dict[str, list[str]] = {}
826
+ parents_by_target: dict[str, list[str]] = {}
827
+
828
+ for basic in basic_defs:
829
+ name = basic.attrib.get("name")
830
+ if name:
831
+ nodes[_node_id("basic_event", name)] = {"kind": "basic_event", "type": 0}
832
+
833
+ for name, gate, scope in gate_defs:
834
+ gate_id = _node_id("gate", name)
835
+ connective, connective_name = _gate_connective(gate)
836
+ nodes[gate_id] = {
837
+ "kind": "gate",
838
+ "type": NODE_TYPE_BY_CONNECTIVE.get(connective_name, 1),
839
+ }
840
+ if connective is None:
841
+ continue
842
+ for child in _connective_children(connective, connective_name):
843
+ child_id = _reference_node_id(child, scope)
844
+ if child_id is None:
845
+ continue
846
+ if child_id.startswith("gate:"):
847
+ nodes.setdefault(child_id, {"kind": "gate", "type": 1})
848
+ elif child_id.startswith("house_event:"):
849
+ nodes.setdefault(child_id, {"kind": "constant_event", "type": NODE_TYPE_BY_NAME["constant_event"]})
850
+ else:
851
+ # A <basic-event> reference is a basic event by its tag, even
852
+ # when its <define-basic-event> lives under <model-data> rather
853
+ # than inside <define-fault-tree>. Type 0 keeps the circle
854
+ # filled; `unknown_event` (type 1) is reserved for truly
855
+ # unidentifiable references.
856
+ nodes.setdefault(child_id, {"kind": "basic_event", "type": 0})
857
+ edges.append((gate_id, child_id))
858
+ children_by_source.setdefault(gate_id, []).append(child_id)
859
+ parents_by_target.setdefault(child_id, []).append(gate_id)
860
+
861
+ edge_dicts = [{"source": source, "target": target} for source, target in edges]
862
+ counts = {
863
+ "gate": sum(1 for node in nodes.values() if node["kind"] == "gate"),
864
+ "basic_event": sum(1 for node in nodes.values() if node["kind"] == "basic_event"),
865
+ "unknown_event": sum(1 for node in nodes.values() if node["kind"] == "unknown_event"),
866
+ }
867
+ return {
868
+ "top": _infer_fault_tree_top(gate_defs, edge_dicts),
869
+ "nodes": nodes,
870
+ "edges": edges,
871
+ "children_by_source": children_by_source,
872
+ "parents_by_target": parents_by_target,
873
+ "counts": counts,
874
+ }
875
+
876
+
877
+ def _dag_depths(
878
+ node_ids: list[str],
879
+ children_by_source: dict[str, list[str]],
880
+ parents_by_target: dict[str, list[str]],
881
+ ) -> dict[str, int]:
882
+ indegree = {node_id: len(parents_by_target.get(node_id, [])) for node_id in node_ids}
883
+ depth = {node_id: 0 for node_id in node_ids}
884
+ queue = [node_id for node_id in node_ids if indegree[node_id] == 0]
885
+
886
+ cursor = 0
887
+ while cursor < len(queue):
888
+ node_id = queue[cursor]
889
+ cursor += 1
890
+ parent_depth = depth[node_id]
891
+ for child_id in children_by_source.get(node_id, []):
892
+ if child_id not in indegree:
893
+ continue
894
+ depth[child_id] = max(depth[child_id], parent_depth + 1)
895
+ indegree[child_id] -= 1
896
+ if indegree[child_id] == 0:
897
+ queue.append(child_id)
898
+
899
+ return depth