dfor 0.1.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.
dfor/model_view.py ADDED
@@ -0,0 +1,490 @@
1
+ """Standalone family-level model view. Grain-AGNOSTIC: a constraint touches
2
+ 1..n grains (its application grain + the birth-grains of every variable it
3
+ references), and inter-grain links fall out of joins with no special-casing.
4
+
5
+ Tacked onto to_frames(); not integrated into report.py (that refactor is later).
6
+ """
7
+ import json
8
+ from collections import defaultdict
9
+
10
+ import polars as pl
11
+
12
+ from .model_analysis import constraint_grains as _constraint_grains
13
+ from .model_analysis import model_graph
14
+
15
+
16
+ def family_view(frames):
17
+ cons = frames["constraints"]
18
+ members = frames["grain_members"]
19
+ variables = frames["variables"]
20
+
21
+ # nodes: one per grain, with the entities it spans + its vars
22
+ grain_entities = members.group_by("grain_id").agg(pl.col("entity").alias("spans"))
23
+ grain_vars = (
24
+ variables.group_by("birth_grain_id")
25
+ .agg(pl.col("entity").unique().alias("var_entities"), pl.len().alias("n_vars"))
26
+ .rename({"birth_grain_id": "grain_id"})
27
+ )
28
+ nodes = (grain_entities.join(grain_vars, on="grain_id", how="left")
29
+ .sort("grain_id"))
30
+
31
+ # per-constraint grain participation (1..n grains each)
32
+ con_grains = _constraint_grains(cons, variables)
33
+
34
+ # roll grains up to the family, so a family lists ALL grains it connects
35
+ con_family = cons.select(["con_id", "type", "grain_id"]).rename(
36
+ {"grain_id": "app_grain"})
37
+ family_grains = (
38
+ con_grains
39
+ .join(con_family, on="con_id", how="left")
40
+ .group_by(["type", "app_grain"])
41
+ .agg(pl.col("grain_id").unique().alias("connects_grains"))
42
+ )
43
+
44
+ # family metadata (count / examples), joined to the grain wiring
45
+ family_meta = (
46
+ cons.group_by(["type", "grain_id"])
47
+ .agg(
48
+ pl.len().alias("count"),
49
+ pl.col("entities").first().alias("entities"),
50
+ pl.col("expr").head(2).alias("examples"),
51
+ )
52
+ .rename({"grain_id": "app_grain"})
53
+ )
54
+ edges = (
55
+ family_meta.join(family_grains, on=["type", "app_grain"], how="left")
56
+ .sort("count", descending=True)
57
+ )
58
+
59
+ return {"nodes": nodes.to_dicts(), "edges": edges.to_dicts()}
60
+
61
+
62
+ def to_json(frames, path=None):
63
+ blob = json.dumps(family_view(frames), indent=2, default=str)
64
+ if path:
65
+ with open(path, "w", encoding="utf-8") as f:
66
+ f.write(blob)
67
+ return blob
68
+
69
+ # ---- rough HTML card renderer (throwaway; the JSON is the real artifact) ----
70
+ def to_html(frames, path):
71
+ view = family_view(frames)
72
+
73
+ def node_card(n):
74
+ spans = ", ".join(n.get("spans") or [])
75
+ vents = ", ".join(n.get("var_entities") or [])
76
+ return f"""
77
+ <div class="node">
78
+ <div class="title">{n['grain_id']}</div>
79
+ <div class="row"><b>spans:</b> {spans}</div>
80
+ <div class="row"><b>vars:</b> {vents} ({n.get('n_vars', 0)})</div>
81
+ </div>"""
82
+
83
+ def edge_card(e):
84
+ ents = ", ".join(e.get("entities") or [])
85
+ connects = " → ".join(e.get("connects_grains") or []) # the multi-grain span
86
+ exs = "<br>".join(e.get("examples") or [])
87
+ bridge = "bridge" if len(e.get("connects_grains") or []) > 1 else "same-grain"
88
+ return f"""
89
+ <div class="edge {bridge}">
90
+ <div class="title">{e['type']} @ {e['app_grain']} &times;{e['count']}</div>
91
+ <div class="row"><b>connects:</b> {connects}</div>
92
+ <div class="row"><b>touches:</b> {ents}</div>
93
+ <div class="row example">{exs}</div>
94
+ </div>"""
95
+
96
+ nodes_html = "".join(node_card(n) for n in view["nodes"])
97
+ edges_html = "".join(edge_card(e) for e in view["edges"])
98
+
99
+ html = f"""<!doctype html><html><head><meta charset="utf-8"><style>
100
+ body {{ font-family: ui-monospace, monospace; background:#0d1117; color:#c9d1d9; padding:20px; }}
101
+ h2 {{ color:#58a6ff; }}
102
+ .node, .edge {{ border:1px solid #30363d; border-radius:8px; padding:10px 14px;
103
+ margin:8px 0; background:#161b22; }}
104
+ .edge {{ border-left:3px solid #58a6ff; }}
105
+ .edge.same-grain {{ border-left:3px solid #d29922; }} /* flag the exception case */
106
+ .node {{ border-left:3px solid #3fb950; }}
107
+ .title {{ font-weight:700; color:#e6edf3; margin-bottom:6px; }}
108
+ .row {{ font-size:13px; margin:2px 0; }}
109
+ .example {{ color:#8b949e; white-space:pre-wrap; }}
110
+ .cols {{ display:grid; grid-template-columns:1fr 2fr; gap:20px; }}
111
+ </style></head><body>
112
+ <div class="cols">
113
+ <div><h2>grains (nodes)</h2>{nodes_html}</div>
114
+ <div><h2>families (edges)</h2>{edges_html}</div>
115
+ </div>
116
+ </body></html>"""
117
+
118
+ with open(path, "w", encoding="utf-8") as f:
119
+ f.write(html)
120
+ return path
121
+
122
+
123
+ # ---- Mermaid flowchart renderer: pure render layer over model_graph's IR.
124
+ # No structural logic here -- swap this for erDiagram (or anything else)
125
+ # by writing a new function that consumes the same {"nodes","edges"} shape.
126
+ _NODE_SHAPES = {
127
+ "entity": ('["', '"]'),
128
+ "entity_ref": ('["', '"]'),
129
+ "grain": ('(["', '"])'),
130
+ "constraint": ('{{"', '"}}'),
131
+ }
132
+
133
+
134
+ def _mmd_escape(label):
135
+ return str(label).replace('"', "'")
136
+
137
+
138
+ def to_mermaid(frames, path=None):
139
+ """Entities/grains nested in per-column subgraphs mirroring
140
+ cardinality_hierarchy; constraint families are their own nodes with
141
+ solid edges to their home grain's neighborhood and dashed 'touches'
142
+ edges fanning out to every other grain they reach -- so a constraint
143
+ spanning 3+ grains never gets squeezed into a single binary line."""
144
+ graph = model_graph(frames)
145
+ nodes, edges = graph["nodes"], graph["edges"]
146
+
147
+ lines = ["flowchart TD"]
148
+
149
+ columns = sorted(c for c in nodes["column"].unique().to_list() if c is not None)
150
+ for col in columns:
151
+ col_nodes = nodes.filter(pl.col("column") == col)
152
+ roots = col_nodes.filter(
153
+ (pl.col("node_type") == "entity") & (pl.col("parent_id").is_null()))
154
+ title = _mmd_escape(" / ".join(roots["label"].to_list()) or f"column {col}")
155
+ lines.append(f' subgraph col{col} ["{title}"]')
156
+ for n in col_nodes.iter_rows(named=True):
157
+ open_, close_ = _NODE_SHAPES[n["node_type"]]
158
+ lines.append(f' {n["node_id"]}{open_}{_mmd_escape(n["label"])}{close_}')
159
+ lines.append(" end")
160
+
161
+ for n in nodes.filter(pl.col("column").is_null()).iter_rows(named=True):
162
+ open_, close_ = _NODE_SHAPES[n["node_type"]]
163
+ lines.append(f' {n["node_id"]}{open_}{_mmd_escape(n["label"])}{close_}')
164
+
165
+ for e in edges.iter_rows(named=True):
166
+ arrow = "-->" if e["edge_type"] == "hierarchy" else "-.->"
167
+ label = f'|{_mmd_escape(e["label"])}|' if e["label"] else ""
168
+ lines.append(f' {e["source"]} {arrow}{label} {e["target"]}')
169
+
170
+ lines += [
171
+ " classDef entity fill:#161b22,stroke:#3fb950,color:#e6edf3;",
172
+ " classDef entity_ref fill:#161b22,stroke:#3fb950,color:#e6edf3,stroke-dasharray: 3 2;",
173
+ " classDef grain fill:#161b22,stroke:#58a6ff,color:#e6edf3;",
174
+ " classDef constraint fill:#161b22,stroke:#d29922,color:#e6edf3;",
175
+ ]
176
+ for node_type in ("entity", "entity_ref", "grain", "constraint"):
177
+ ids = nodes.filter(pl.col("node_type") == node_type)["node_id"].to_list()
178
+ if ids:
179
+ lines.append(f" class {','.join(ids)} {node_type};")
180
+
181
+ text = "\n".join(lines)
182
+ if path:
183
+ with open(path, "w", encoding="utf-8") as f:
184
+ f.write(text)
185
+ return text
186
+
187
+
188
+ def to_mermaid_html(frames, path):
189
+ """Standalone page wrapping to_mermaid()'s output: loads Mermaid from a
190
+ public CDN (a static JS file, not a signup-required service -- no
191
+ account, no Mermaid Chart cloud) and renders on load. Otherwise fully
192
+ self-contained; just open the file in a browser, no server needed."""
193
+ diagram = to_mermaid(frames)
194
+ html = f"""<!doctype html><html><head><meta charset="utf-8"><style>
195
+ body {{ background:#0d1117; color:#e6edf3; font-family: ui-monospace, monospace; padding:20px; }}
196
+ </style></head><body>
197
+ <pre class="mermaid">
198
+ {diagram}
199
+ </pre>
200
+ <script type="module">
201
+ import mermaid from "https://cdn.jsdelivr.net/npm/mermaid@11/dist/mermaid.esm.min.mjs";
202
+ mermaid.initialize({{ startOnLoad: true, theme: "dark" }});
203
+ </script>
204
+ </body></html>"""
205
+ with open(path, "w", encoding="utf-8") as f:
206
+ f.write(html)
207
+ return path
208
+
209
+
210
+ # ---- indented-outline renderer: another pure render layer over model_graph's
211
+ # IR, nothing structural here either. One continuous tree (model_graph's
212
+ # "column" still orders rows, it just isn't boxed apart visually), grains
213
+ # and their constraints inline, and constraint bridges to OTHER grains drawn
214
+ # as curved connector lines computed client-side from actual rendered row
215
+ # positions (robust to text wrapping / variable row heights, unlike
216
+ # precomputing pixel offsets in Python).
217
+ def _tree_escape(text):
218
+ return (str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
219
+
220
+
221
+ def _truncate(text, limit=300):
222
+ text = str(text)
223
+ return text if len(text) <= limit else text[:limit] + "…"
224
+
225
+
226
+ _GUIDE_CONT = "│ " # │
227
+ _GUIDE_BLANK = " "
228
+ _GUIDE_TEE = "├── " # ├──
229
+ _GUIDE_ELBOW = "└── " # └──
230
+
231
+ # cycled across constraint families so adjacent cards/lines are visually
232
+ # distinguishable; kept clear of the green/blue already used for entity/grain
233
+ _CONSTRAINT_PALETTE = ["#e3b341", "#bc8cff", "#39c5cf", "#f778ba", "#ffa657"]
234
+
235
+
236
+ def _color_for(cf_id):
237
+ idx = int(cf_id[2:]) % len(_CONSTRAINT_PALETTE)
238
+ return idx, _CONSTRAINT_PALETTE[idx]
239
+
240
+
241
+ def to_tree_json(frames, path=None):
242
+ """Same tree structure as to_tree_html (grains/entities nested by
243
+ parent_id, constraints attached to their home grain, cross-grain
244
+ 'touches' recorded), as plain JSON instead of HTML+SVG -- meant for
245
+ grepping/scanning (by a human or an LLM) rather than viewing, and for
246
+ dumping *before* a solve so the structure survives a lockup or crash."""
247
+ graph = model_graph(frames)
248
+ nodes, edges = graph["nodes"], graph["edges"]
249
+ variables = frames["variables"]
250
+
251
+ vars_by_grain = {
252
+ r["birth_grain_id"]: (r["var_entities"], r["n_vars"])
253
+ for r in (
254
+ variables.group_by("birth_grain_id")
255
+ .agg(pl.col("entity").unique().alias("var_entities"), pl.len().alias("n_vars"))
256
+ .iter_rows(named=True)
257
+ )
258
+ }
259
+
260
+ constraints_by_home = defaultdict(list)
261
+ for n in nodes.filter(pl.col("node_type") == "constraint").iter_rows(named=True):
262
+ constraints_by_home[n["parent_id"]].append(n)
263
+
264
+ touches = defaultdict(list)
265
+ for e in edges.filter(pl.col("edge_type") == "touches").iter_rows(named=True):
266
+ touches[e["source"]].append(e["target"])
267
+
268
+ tree_nodes = (
269
+ nodes.filter(pl.col("node_type").is_in(["entity", "entity_ref", "grain"]))
270
+ .sort(["column", "row"])
271
+ .to_dicts()
272
+ )
273
+
274
+ node_records = []
275
+ for n in tree_nodes:
276
+ record = {
277
+ "node_id": n["node_id"],
278
+ "node_type": n["node_type"],
279
+ "parent_id": n["parent_id"],
280
+ "label": n["label"],
281
+ }
282
+ if n["node_type"] == "grain":
283
+ var_entities, n_vars = vars_by_grain.get(n["grain_id"], ([], 0))
284
+ record["grain_id"] = n["grain_id"]
285
+ record["vars"] = list(var_entities)
286
+ record["n_vars"] = n_vars
287
+
288
+ cons = []
289
+ for c in constraints_by_home.get(n["node_id"], []):
290
+ cons.append({
291
+ "constraint_id": c["node_id"],
292
+ "label": c["label"], # e.g. "add_element ×1008"
293
+ "example_fields": c["example_fields"],
294
+ "example_ids": c["example_ids"],
295
+ "touches": touches.get(c["node_id"], []),
296
+ })
297
+ record["constraints"] = cons
298
+ node_records.append(record)
299
+
300
+ blob = json.dumps(node_records, indent=2, default=str)
301
+ if path:
302
+ with open(path, "w", encoding="utf-8") as f:
303
+ f.write(blob)
304
+ return blob
305
+
306
+
307
+ def to_tree_html(frames, path):
308
+ graph = model_graph(frames)
309
+ nodes, edges = graph["nodes"], graph["edges"]
310
+ variables = frames["variables"]
311
+
312
+ vars_by_grain = {
313
+ r["birth_grain_id"]: (r["var_entities"], r["n_vars"])
314
+ for r in (
315
+ variables.group_by("birth_grain_id")
316
+ .agg(pl.col("entity").unique().alias("var_entities"), pl.len().alias("n_vars"))
317
+ .iter_rows(named=True)
318
+ )
319
+ }
320
+
321
+ constraints_by_home = defaultdict(list)
322
+ for n in nodes.filter(pl.col("node_type") == "constraint").iter_rows(named=True):
323
+ constraints_by_home[n["parent_id"]].append(n)
324
+
325
+ touches = defaultdict(list)
326
+ for e in edges.filter(pl.col("edge_type") == "touches").iter_rows(named=True):
327
+ touches[e["source"]].append(e["target"])
328
+
329
+ tree_nodes = (
330
+ nodes.filter(pl.col("node_type").is_in(["entity", "entity_ref", "grain"]))
331
+ .sort(["column", "row"])
332
+ .to_dicts()
333
+ )
334
+ node_by_id = {n["node_id"]: n for n in tree_nodes}
335
+
336
+ # immediate children in display order, keyed by parent_id (None = the
337
+ # top-level peers -- treating "no separate columns" literally, multiple
338
+ # root clusters are just siblings at the top of one tree, not walled off)
339
+ children_of = defaultdict(list)
340
+ for n in tree_nodes:
341
+ children_of[n["parent_id"]].append(n["node_id"])
342
+
343
+ def is_last(node_id):
344
+ parent = node_by_id[node_id]["parent_id"]
345
+ return children_of[parent][-1] == node_id
346
+
347
+ def guide_for(n):
348
+ # walk the parent chain root-first: a "|" continues under any
349
+ # ancestor that still has siblings coming after it, blank otherwise
350
+ chain = []
351
+ cur_parent = n["parent_id"]
352
+ while cur_parent is not None:
353
+ chain.append(cur_parent)
354
+ cur_parent = node_by_id[cur_parent]["parent_id"]
355
+ chain.reverse()
356
+ prefix = "".join(_GUIDE_BLANK if is_last(a) else _GUIDE_CONT for a in chain)
357
+ return prefix + (_GUIDE_ELBOW if is_last(n["node_id"]) else _GUIDE_TEE)
358
+
359
+ connectors = []
360
+ row_html = []
361
+ for n in tree_nodes:
362
+ is_grain = n["node_type"] == "grain"
363
+ guide = _tree_escape(guide_for(n))
364
+ label = (f'{n["grain_id"]} ({_tree_escape(n["label"])})' if is_grain
365
+ else _tree_escape(n["label"]))
366
+
367
+ vars_cell = ""
368
+ if is_grain:
369
+ var_entities, n_vars = vars_by_grain.get(n["grain_id"], ([], 0))
370
+ if n_vars:
371
+ vars_cell = f'{_tree_escape(", ".join(var_entities))} ({n_vars})'
372
+
373
+ cons_parts = []
374
+ for c in constraints_by_home.get(n["node_id"], []):
375
+ idx, color = _color_for(c["node_id"])
376
+ cons_parts.append(f"""
377
+ <div class="cons" id="{c['node_id']}" style="border-color:{color};">
378
+ <div class="cons-title" style="color:{color};">{_tree_escape(c['label'])}</div>
379
+ <div class="expr fields">{_tree_escape(_truncate(c['example_fields']))}</div>
380
+ <div class="expr">{_tree_escape(_truncate(c['example_ids']))}</div>
381
+ </div>""")
382
+ # a line to its OWN home grain too (always horizontal, same row)
383
+ # -- redundant with position alone, but makes "this constraint
384
+ # lives here" explicit and consistent with every other line
385
+ connectors.append({
386
+ "from": c["node_id"], "to": f"gutter-{n['node_id']}",
387
+ "color": color, "marker": f"arrow-{idx}",
388
+ })
389
+ for target in touches.get(c["node_id"], []):
390
+ # anchor to the gutter's own edges, not the row's full-width
391
+ # edge, so the line only ever crosses the gutter -- never
392
+ # the tree/vars content itself
393
+ connectors.append({
394
+ "from": c["node_id"], "to": f"gutter-{target}",
395
+ "color": color, "marker": f"arrow-{idx}",
396
+ })
397
+
398
+ row_html.append(f"""
399
+ <tr id="row-{n['node_id']}" class="{n['node_type']}">
400
+ <td class="tree"><span class="guide">{guide}</span><span class="label">{label}</span></td>
401
+ <td class="vars">{vars_cell}</td>
402
+ <td class="gutter" id="gutter-{n['node_id']}"></td>
403
+ <td class="cons-col">{"".join(cons_parts)}</td>
404
+ </tr>""")
405
+
406
+ connectors_json = json.dumps(connectors)
407
+ markers_svg = "".join(
408
+ f'<marker id="arrow-{i}" markerWidth="8" markerHeight="8" refX="6" refY="3" orient="auto">'
409
+ f'<path d="M0,0 L6,3 L0,6 Z" fill="{color}"></path></marker>'
410
+ for i, color in enumerate(_CONSTRAINT_PALETTE)
411
+ )
412
+
413
+ html = f"""<!doctype html><html><head><meta charset="utf-8"><style>
414
+ body {{ font-family: ui-monospace, monospace; background:#0d1117; color:#e6edf3; padding:20px; }}
415
+ h2 {{ color:#58a6ff; }}
416
+ table {{ border-collapse: separate; border-spacing: 0 5px; width: 100%; table-layout: fixed; }}
417
+ td {{ vertical-align: top; padding: 8px 12px; }}
418
+ tr.entity {{ background: #142b1a; }}
419
+ tr.grain {{ background: #122642; }}
420
+ tr.entity_ref {{ background: #10151c; }}
421
+ tr.entity > td.tree {{ border-left: 5px solid #3fb950; }}
422
+ tr.grain > td.tree {{ border-left: 5px solid #58a6ff; }}
423
+ tr.entity_ref > td.tree {{ border-left: 5px dashed #3a4552; }}
424
+ tr.entity > td.tree .label {{ color:#56d364; font-weight: 700; }}
425
+ tr.grain > td.tree .label {{ color:#79c0ff; font-weight: 700; }}
426
+ tr.entity_ref > td.tree .label {{ color:#7d8798; font-style: italic; }}
427
+ .guide {{ color:#6e7b8c; white-space: pre; }}
428
+ td.vars {{ color:#b8c4d1; font-size: 13px; word-break: break-word; }}
429
+ td.gutter {{ padding: 0; border-left: 1px dashed #30363d;
430
+ border-right: 1px dashed #30363d; }}
431
+ .cons {{ display:block; border:1px solid #e3b341; border-radius:6px;
432
+ padding:8px 12px; margin:4px 0; background:#2b2008; }}
433
+ .cons-title {{ color:#f0c674; font-weight:700; font-size:13px; margin-bottom:3px; }}
434
+ .expr {{ color:#c9d1d9; font-size:12px; white-space:pre-wrap; }}
435
+ .expr.fields {{ color:#f7f0dd; }}
436
+ #tree-container {{ position: relative; }}
437
+ #connector-svg {{ position: absolute; top:0; left:0; pointer-events:none; }}
438
+ </style></head><body>
439
+ <h2>model tree</h2>
440
+ <div id="tree-container">
441
+ <svg id="connector-svg"><defs>{markers_svg}</defs></svg>
442
+ <table>
443
+ <colgroup>
444
+ <col style="width:30%"><col style="width:30%">
445
+ <col style="width:10%"><col style="width:30%">
446
+ </colgroup>
447
+ <tbody>{"".join(row_html)}</tbody>
448
+ </table>
449
+ </div>
450
+ <script>
451
+ const connectors = {connectors_json};
452
+ function draw() {{
453
+ const container = document.getElementById("tree-container");
454
+ const svg = document.getElementById("connector-svg");
455
+ const cRect = container.getBoundingClientRect();
456
+ svg.setAttribute("width", cRect.width);
457
+ svg.setAttribute("height", cRect.height);
458
+ svg.innerHTML = svg.innerHTML.split("</defs>")[0] + "</defs>";
459
+ for (const c of connectors) {{
460
+ const a = document.getElementById(c.from);
461
+ const b = document.getElementById(c.to);
462
+ if (!a || !b) continue;
463
+ const ar = a.getBoundingClientRect(), br = b.getBoundingClientRect();
464
+ // source: LEFT edge of the constraint card (the gutter's right
465
+ // boundary); target: LEFT edge of the target row's gutter cell
466
+ // (the gutter's left boundary) -- opposite sides, so the line
467
+ // actually spans the gutter's width instead of both endpoints
468
+ // landing on the same edge. Same row (own home grain) means
469
+ // y1 == y2, which collapses the curve to a straight horizontal
470
+ // line automatically.
471
+ const x1 = ar.left - cRect.left, y1 = ar.top + ar.height / 2 - cRect.top;
472
+ const x2 = br.left - cRect.left, y2 = br.top + br.height / 2 - cRect.top;
473
+ const mx = (x1 + x2) / 2;
474
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
475
+ path.setAttribute("d", `M ${{x1}} ${{y1}} C ${{mx}} ${{y1}}, ${{mx}} ${{y2}}, ${{x2}} ${{y2}}`);
476
+ path.setAttribute("stroke", c.color);
477
+ path.setAttribute("fill", "none");
478
+ path.setAttribute("stroke-width", "2.5");
479
+ path.setAttribute("marker-end", `url(#${{c.marker}})`);
480
+ svg.appendChild(path);
481
+ }}
482
+ }}
483
+ window.addEventListener("load", draw);
484
+ window.addEventListener("resize", draw);
485
+ </script>
486
+ </body></html>"""
487
+
488
+ with open(path, "w", encoding="utf-8") as f:
489
+ f.write(html)
490
+ return path