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/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """dfor: build CP-SAT models with polars pipe verbs."""
2
+ from . import model_view, quickxplain, report
3
+ from .problem import Problem
4
+ from .snapshot import Snapshot
5
+
6
+ __all__ = ["Problem", "Snapshot", "model_view", "quickxplain", "report"]
dfor/ids.py ADDED
@@ -0,0 +1,18 @@
1
+ from itertools import count
2
+
3
+
4
+ class Ids:
5
+ """One independent monotonic counter per namespace.
6
+
7
+ ids.next("var") -> 'var_0', 'var_1', ...
8
+ ids.next("con") -> 'con_0', ...
9
+ Strings are intentional: the prefix tells you the *kind* at a glance,
10
+ and (per design) string ids are load-bearing for satvar detection.
11
+ """
12
+
13
+ def __init__(self):
14
+ self._counters = {}
15
+
16
+ def next(self, namespace):
17
+ c = self._counters.setdefault(namespace, count())
18
+ return f"{namespace}_{next(c)}"
dfor/matrix_view.py ADDED
@@ -0,0 +1,196 @@
1
+ """Bus-matrix model view: grains as rows, entities as columns, a mark where
2
+ a grain includes that entity. Landing page links to one static drilldown page
3
+ per grain, generated in the same pass. Pure static HTML, no JS.
4
+ """
5
+ import os
6
+
7
+ import polars as pl
8
+
9
+ from .model_analysis import constraint_grains as _constraint_grains
10
+ from .model_analysis import _VAR_RE
11
+
12
+ _PALETTE = ["#e3b341", "#bc8cff", "#39c5cf", "#f778ba", "#ffa657"]
13
+
14
+ _CSS = """
15
+ body { font-family: ui-monospace, monospace; background:#0d1117; color:#e6edf3; padding:20px; }
16
+ h2 { color:#58a6ff; }
17
+ h3 { color:#79c0ff; margin-top:28px; }
18
+ a { color:#58a6ff; text-decoration:none; }
19
+ a:hover { text-decoration:underline; }
20
+ table.matrix { border-collapse: collapse; }
21
+ table.matrix th, table.matrix td { padding: 6px 10px; border: 1px solid #21262d; }
22
+ table.matrix th { color:#8b949e; font-weight:400; }
23
+ table.matrix th.entity { writing-mode: vertical-rl; transform: rotate(180deg);
24
+ vertical-align: bottom; color:#56d364; font-weight:700; }
25
+ table.matrix td.grain-name { color:#79c0ff; font-weight:700; white-space:nowrap; }
26
+ table.matrix td.dot { text-align:center; }
27
+ table.matrix td.dot.on { background:#122642; color:#79c0ff; font-weight:700; }
28
+ table.matrix td.count { color:#8b949e; text-align:right; }
29
+ table.matrix td.vars { color:#b8c4d1; font-size:12px; max-width:340px; }
30
+ table.matrix td.cons { font-size:12px; max-width:420px; }
31
+ table.matrix tr:hover td { background:#161b22; }
32
+ table.matrix tr:hover td.dot.on { background:#1a3a63; }
33
+ .chip { display:inline-block; border:1px solid; border-radius:10px;
34
+ padding:1px 8px; margin:2px 2px; font-size:12px; }
35
+ .cross { color:#8b949e; font-size:11px; }
36
+ .cons-card { border:1px solid; border-radius:6px; padding:8px 12px;
37
+ margin:6px 0; background:#161b22; }
38
+ .cons-title { font-weight:700; font-size:13px; margin-bottom:3px; }
39
+ .expr { color:#c9d1d9; font-size:12px; white-space:pre-wrap; }
40
+ .expr.fields { color:#f7f0dd; }
41
+ .meta { color:#8b949e; font-size:13px; margin:4px 0; }
42
+ """
43
+
44
+
45
+ def _esc(text):
46
+ return (str(text).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))
47
+
48
+
49
+ def _page(title, body):
50
+ return (f"<!doctype html><html><head><meta charset=\"utf-8\">"
51
+ f"<style>{_CSS}</style></head><body>{body}</body></html>")
52
+
53
+
54
+ def _matrix_data(frames):
55
+ """Everything both pages need, computed once."""
56
+ members = frames["grain_members"]
57
+ variables = frames["variables"]
58
+ cons = frames["constraints"]
59
+ labels = dict(zip(frames["grain_labels"]["grain_id"],
60
+ frames["grain_labels"]["label"])) if "grain_labels" in frames else {}
61
+
62
+ # grains in declared order; entities in first-appearance order
63
+ grain_order, grain_ents, entity_order = [], {}, []
64
+ for gid, ent in members.iter_rows():
65
+ if gid not in grain_ents:
66
+ grain_ents[gid] = []
67
+ grain_order.append(gid)
68
+ grain_ents[gid].append(ent)
69
+ if ent not in entity_order:
70
+ entity_order.append(ent)
71
+
72
+ vars_by_grain = {
73
+ r["birth_grain_id"]: (r["var_entities"], r["n_vars"])
74
+ for r in (variables.group_by("birth_grain_id")
75
+ .agg(pl.col("entity").unique(maintain_order=True).alias("var_entities"),
76
+ pl.len().alias("n_vars"))
77
+ .iter_rows(named=True))
78
+ }
79
+
80
+ # constraint families: one per pipe-call site, with user names when given
81
+ var_to_entity = dict(zip(variables["var_id"], variables["entity"]))
82
+ con_grains = _constraint_grains(cons, variables)
83
+ has_name = "name" in cons.columns
84
+ fam_meta = (
85
+ cons.group_by(["type", "grain_id", "call_id"])
86
+ .agg(pl.len().alias("count"),
87
+ pl.col("expr").first().alias("example_ids"),
88
+ *([pl.col("name").first().alias("user_name")] if has_name else []))
89
+ .rename({"grain_id": "app_grain"}))
90
+ fam_grains = (
91
+ con_grains.join(cons.select(["con_id", "type", "grain_id", "call_id"])
92
+ .rename({"grain_id": "app_grain"}), on="con_id", how="left")
93
+ .group_by(["type", "app_grain", "call_id"])
94
+ .agg(pl.col("grain_id").unique().alias("connects")))
95
+ families = (fam_meta.join(fam_grains, on=["type", "app_grain", "call_id"], how="left")
96
+ .sort(["type", "app_grain", "call_id"]))
97
+
98
+ fams = []
99
+ for i, f in enumerate(families.iter_rows(named=True)):
100
+ example_ids = f["example_ids"] or ""
101
+ fams.append({
102
+ "cf_id": f"cf{i}",
103
+ "color": _PALETTE[i % len(_PALETTE)],
104
+ "app_grain": f["app_grain"],
105
+ "title": (f.get("user_name") or f["type"]),
106
+ "verb": f["type"],
107
+ "count": f["count"],
108
+ "example_ids": example_ids,
109
+ "example_fields": _VAR_RE.sub(
110
+ lambda m: var_to_entity.get(m.group(0), m.group(0)), example_ids),
111
+ "connects": [g for g in (f["connects"] or []) if g != f["app_grain"]],
112
+ })
113
+
114
+ def display(gid):
115
+ return labels.get(gid, gid)
116
+
117
+ return {
118
+ "grain_order": grain_order, "grain_ents": grain_ents,
119
+ "entity_order": entity_order, "vars_by_grain": vars_by_grain,
120
+ "families": fams, "display": display,
121
+ }
122
+
123
+
124
+ def to_matrix_html(frames, path):
125
+ """Landing page: the bus matrix. Also writes one drilldown page per grain
126
+ (grain_<id>.html) into the same directory."""
127
+ d = _matrix_data(frames)
128
+ out_dir = os.path.dirname(os.path.abspath(path))
129
+
130
+ header = ("<tr><th></th>"
131
+ + "".join(f'<th class="entity">{_esc(e)}</th>' for e in d["entity_order"])
132
+ + "<th>vars</th><th>constraints</th></tr>")
133
+
134
+ rows = []
135
+ for gid in d["grain_order"]:
136
+ ents = set(d["grain_ents"][gid])
137
+ var_entities, n_vars = d["vars_by_grain"].get(gid, ([], 0))
138
+ dots = "".join(
139
+ f'<td class="dot on">&#9679;</td>' if e in ents else '<td class="dot"></td>'
140
+ for e in d["entity_order"])
141
+ vars_cell = f'{_esc(", ".join(var_entities))} ({n_vars})' if n_vars else ""
142
+ chips = ""
143
+ for f in d["families"]:
144
+ if f["app_grain"] != gid:
145
+ continue
146
+ cross = "".join(f' <span class="cross">&#8599;{_esc(d["display"](g))}</span>'
147
+ for g in f["connects"])
148
+ chips += (f'<span class="chip" style="border-color:{f["color"]};'
149
+ f'color:{f["color"]};">{_esc(f["title"])} &times;{f["count"]}</span>{cross}')
150
+ rows.append(
151
+ f'<tr><td class="grain-name"><a href="grain_{gid}.html">{_esc(d["display"](gid))}</a></td>'
152
+ f'{dots}<td class="vars">{vars_cell}</td><td class="cons">{chips}</td></tr>')
153
+
154
+ body = (f"<h2>model matrix</h2>"
155
+ f'<table class="matrix">{header}{"".join(rows)}</table>')
156
+ with open(path, "w", encoding="utf-8") as fh:
157
+ fh.write(_page("model matrix", body))
158
+
159
+ for gid in d["grain_order"]:
160
+ _write_grain_page(d, gid, os.path.join(out_dir, f"grain_{gid}.html"),
161
+ os.path.basename(path))
162
+ return path
163
+
164
+
165
+ def _write_grain_page(d, gid, path, index_name):
166
+ var_entities, n_vars = d["vars_by_grain"].get(gid, ([], 0))
167
+ ents = d["grain_ents"][gid]
168
+
169
+ cards = []
170
+ for f in d["families"]:
171
+ if f["app_grain"] != gid and gid not in f["connects"]:
172
+ continue
173
+ home = ("" if f["app_grain"] == gid else
174
+ f' <span class="cross">(home: <a href="grain_{f["app_grain"]}.html">'
175
+ f'{_esc(d["display"](f["app_grain"]))}</a>)</span>')
176
+ cross = "".join(
177
+ f' <span class="cross">&#8599;<a href="grain_{g}.html">{_esc(d["display"](g))}</a></span>'
178
+ for g in f["connects"] if g != gid)
179
+ title = _esc(f["title"])
180
+ if f["title"] != f["verb"]:
181
+ title += f' <span class="cross">[{_esc(f["verb"])}]</span>'
182
+ cards.append(f"""
183
+ <div class="cons-card" style="border-color:{f['color']};">
184
+ <div class="cons-title" style="color:{f['color']};">{title} &times;{f['count']}{home}{cross}</div>
185
+ <div class="expr fields">{_esc(f['example_fields'])}</div>
186
+ <div class="expr">{_esc(f['example_ids'])}</div>
187
+ </div>""")
188
+
189
+ body = (f'<div class="meta"><a href="{index_name}">&larr; matrix</a></div>'
190
+ f"<h2>{_esc(d['display'](gid))}</h2>"
191
+ f'<div class="meta">{_esc(gid)} &mdash; {_esc(" x ".join(ents))}</div>'
192
+ f'<div class="meta">vars: {_esc(", ".join(var_entities))} ({n_vars})</div>'
193
+ f"<h3>constraints</h3>{''.join(cards) or '<div class=\"meta\">none</div>'}")
194
+ with open(path, "w", encoding="utf-8") as fh:
195
+ fh.write(_page(gid, body))
196
+ return path
dfor/model_analysis.py ADDED
@@ -0,0 +1,410 @@
1
+ """Structural analysis over captured diagnostic frames: cardinality + FD
2
+ analysis of grains, building an IR of how the model's entities relate.
3
+ """
4
+ import re
5
+ from collections import defaultdict
6
+
7
+ import polars as pl
8
+
9
+ _VAR_RE = re.compile(r"var_\d+")
10
+
11
+
12
+ def constraint_variables(cons):
13
+ """Parse var ids out of each constraint's expr string -> long edge table
14
+ (con_id, var_id). This is the missing relation; recovered from the
15
+ formatted expr rather than threading a var list through capture."""
16
+ recs = []
17
+ for con_id, expr in zip(cons["con_id"], cons["expr"]):
18
+ for vid in dict.fromkeys(_VAR_RE.findall(expr or "")): # dedupe, keep order
19
+ recs.append({"con_id": con_id, "var_id": vid})
20
+ if not recs:
21
+ return pl.DataFrame(schema={"con_id": pl.String, "var_id": pl.String})
22
+ return pl.DataFrame(recs)
23
+
24
+
25
+ def constraint_grains(cons, variables):
26
+ """Every (con_id, grain_id) link a constraint participates in: its OWN
27
+ application grain, UNION the birth-grain of every var it touches."""
28
+ con_vars = constraint_variables(cons)
29
+ via_vars = (
30
+ con_vars
31
+ .join(variables.select(["var_id", "birth_grain_id"]), on="var_id", how="left")
32
+ .select(["con_id", pl.col("birth_grain_id").alias("grain_id")])
33
+ .drop_nulls("grain_id")
34
+ )
35
+ own = cons.select(["con_id", "grain_id"])
36
+ return pl.concat([own, via_vars]).unique()
37
+
38
+
39
+ def entity_pair_cardinality(frames):
40
+ """One row per ordered pair of entities that co-occur in some grain,
41
+ classified by functional dependency: 1:1, n:1, 1:n, or n:n.
42
+
43
+ Candidate pairs come from grain_members (schema-level: which entities
44
+ share a grain). The actual values used to test FD come from
45
+ constraint_rows, since that's the only frame holding real co-occurring
46
+ id/scalar values (captured as the full grain of each add* call — see
47
+ problem.py:_make_constraint_verb). Pairs whose entities never appear
48
+ together in a constraint (vars born but never constrained) come back
49
+ with relationship=None: no evidence either way, not a guess.
50
+ """
51
+ grain_members = frames["grain_members"]
52
+ constraint_rows = frames["constraint_rows"]
53
+
54
+ # candidate pairs: any two distinct entities that share a grain
55
+ pairs = (
56
+ grain_members.join(grain_members, on="grain_id", suffix="_rhs")
57
+ .filter(pl.col("entity") != pl.col("entity_rhs"))
58
+ .select(pl.col("entity").alias("lhs"), pl.col("entity_rhs").alias("rhs"))
59
+ .unique()
60
+ )
61
+
62
+ recs = []
63
+ for lhs, rhs in pairs.iter_rows():
64
+ left = constraint_rows.filter(pl.col("key") == lhs).select(
65
+ "con_id", pl.col("value").alias("lhs_value"))
66
+ right = constraint_rows.filter(pl.col("key") == rhs).select(
67
+ "con_id", pl.col("value").alias("rhs_value"))
68
+ joined = left.join(right, on="con_id", how="inner").unique(
69
+ ["lhs_value", "rhs_value"])
70
+
71
+ if joined.is_empty():
72
+ recs.append({
73
+ "lhs": lhs, "rhs": rhs, "n_pairs": 0,
74
+ "lhs_determines_rhs": None, "rhs_determines_lhs": None,
75
+ "relationship": None,
76
+ })
77
+ continue
78
+
79
+ max_rhs_per_lhs = (
80
+ joined.group_by("lhs_value").agg(pl.col("rhs_value").n_unique())
81
+ ["rhs_value"].max())
82
+ max_lhs_per_rhs = (
83
+ joined.group_by("rhs_value").agg(pl.col("lhs_value").n_unique())
84
+ ["lhs_value"].max())
85
+ lhs_determines_rhs = max_rhs_per_lhs == 1
86
+ rhs_determines_lhs = max_lhs_per_rhs == 1
87
+
88
+ if lhs_determines_rhs and rhs_determines_lhs:
89
+ relationship = "1:1"
90
+ elif lhs_determines_rhs:
91
+ relationship = "n:1"
92
+ elif rhs_determines_lhs:
93
+ relationship = "1:n"
94
+ else:
95
+ relationship = "n:n"
96
+
97
+ recs.append({
98
+ "lhs": lhs, "rhs": rhs, "n_pairs": joined.height,
99
+ "lhs_determines_rhs": lhs_determines_rhs,
100
+ "rhs_determines_lhs": rhs_determines_lhs,
101
+ "relationship": relationship,
102
+ })
103
+
104
+ if not recs:
105
+ # zero candidate pairs -- e.g. a reduced core with only one
106
+ # surviving entity. Same shape as the populated case, just empty,
107
+ # so downstream .filter()/.join() calls don't blow up on a
108
+ # columnless frame.
109
+ return pl.DataFrame(schema={
110
+ "lhs": pl.String, "rhs": pl.String, "n_pairs": pl.Int64,
111
+ "lhs_determines_rhs": pl.Boolean, "rhs_determines_lhs": pl.Boolean,
112
+ "relationship": pl.String})
113
+ return pl.DataFrame(recs)
114
+
115
+
116
+ def cardinality_hierarchy(frames):
117
+ """Derive a grain hierarchy from the captured frames.
118
+
119
+ Input: the bundle from Problem.to_frames() — "variables", "constraints",
120
+ "constraint_rows", "grain_members", "entities".
121
+
122
+ Output shape:
123
+ column, row, row_type ("entity"|"entity_ref"|"grain"), node_id,
124
+ parent_entity(nullable, a node_id), entity (display label),
125
+ relationship_type(nullable), grain_id(nullable)
126
+
127
+ An entity is top-level iff it's never the LHS of an n:1 (never
128
+ functionally dependent on something else). n:n partners don't drag an
129
+ entity down — cross-joining with a child doesn't make you one — but 1:1
130
+ partners do (a 1:1 partner is the same identity, so whatever's true of
131
+ it is true of you). Root entities that share an n:n/1:1 edge cluster
132
+ into one column; unrelated root clusters get separate columns.
133
+
134
+ Below each entity, grains are surfaced the moment every entity they
135
+ span has been placed in that column (not just the entity that "closed"
136
+ a strict parent chain) — a grain's span is often a proper subset of a
137
+ node's full lineage, formed earlier in the pipeline before a later join
138
+ happened, so this is a subset check against everything placed so far in
139
+ the column, not an exact-match on the current path alone.
140
+
141
+ A grain's entities aren't always literal ancestors on the branch it's
142
+ surfaced on (e.g. it's placed under entity X, but also needs entity Y
143
+ which actually lives elsewhere in the tree). Rather than hide that, a
144
+ short "entity_ref" chain is inserted right above the grain for every
145
+ such missing entity, in visit order -- a repeat of an entity that's
146
+ placed for real elsewhere, existing only to make the grain's actual
147
+ composition legible at the point it's shown. node_id disambiguates
148
+ these from the real placement (f"{entity}__{grain_id}"); "entity" stays
149
+ the plain display name in both places.
150
+ """
151
+ grain_members = frames["grain_members"]
152
+ pairs = entity_pair_cardinality(frames)
153
+
154
+ grain_entity_sets = sorted(
155
+ (
156
+ (row["grain_id"], set(row["entity"]))
157
+ for row in grain_members.group_by("grain_id")
158
+ .agg(pl.col("entity")).to_dicts()
159
+ ),
160
+ key=lambda g: len(g[1]), # coarsest (fewest entities) first
161
+ )
162
+
163
+ entities = sorted(set(grain_members["entity"]))
164
+
165
+ # child -> its n:1 parent. More than one n:1 target is a real ambiguity
166
+ # (which one is "the" parent?) -- often a sign the data's too small or
167
+ # degenerate for FD detection to mean anything (an entity with only one
168
+ # distinct value is trivially "n:1" to everything). Break the tie toward
169
+ # whichever candidate has more distinct values -- a single-value entity
170
+ # carries no real partitioning information -- and say so out loud,
171
+ # rather than silently picking or hard-failing the whole pipeline.
172
+ n1 = pairs.filter(pl.col("relationship") == "n:1")
173
+ parent_candidates = defaultdict(list)
174
+ for lhs, rhs in zip(n1["lhs"], n1["rhs"]):
175
+ parent_candidates[lhs].append(rhs)
176
+
177
+ distinct_counts = dict(
178
+ frames["constraint_rows"].group_by("key")
179
+ .agg(pl.col("value").n_unique().alias("n")).iter_rows())
180
+ parent_of = {}
181
+ for e, candidates in parent_candidates.items():
182
+ if len(candidates) > 1:
183
+ chosen = max(candidates, key=lambda p: (distinct_counts.get(p, 0), p))
184
+ print(f"[cardinality_hierarchy] ambiguous n:1 parent for {e!r}: "
185
+ f"{candidates} -> picked {chosen!r} (most distinct values)")
186
+ parent_of[e] = chosen
187
+ else:
188
+ parent_of[e] = candidates[0]
189
+
190
+ same_level = pairs.filter(pl.col("relationship").is_in(["1:1", "n:n"]))
191
+ adjacency = defaultdict(set)
192
+ for a, b in zip(same_level["lhs"], same_level["rhs"]):
193
+ adjacency[a].add(b)
194
+ adjacency[b].add(a)
195
+
196
+ one_to_one = pairs.filter(pl.col("relationship") == "1:1")
197
+ alias_adjacency = defaultdict(set)
198
+ for a, b in zip(one_to_one["lhs"], one_to_one["rhs"]):
199
+ alias_adjacency[a].add(b)
200
+ alias_adjacency[b].add(a)
201
+
202
+ def is_root(entity, seen):
203
+ if entity in seen:
204
+ return True
205
+ seen.add(entity)
206
+ if entity in parent_of:
207
+ return False
208
+ return all(is_root(alias, seen) for alias in alias_adjacency[entity])
209
+
210
+ roots = [e for e in entities if is_root(e, set())]
211
+
212
+ # cluster roots tied together by an n:n/1:1 edge into one column
213
+ unclustered = set(roots)
214
+ columns = []
215
+ while unclustered:
216
+ start = min(unclustered)
217
+ stack, comp = [start], set()
218
+ while stack:
219
+ cur = stack.pop()
220
+ if cur in comp:
221
+ continue
222
+ comp.add(cur)
223
+ stack.extend(p for p in adjacency[cur] if p in roots)
224
+ unclustered -= comp
225
+ columns.append(sorted(comp))
226
+ columns.sort(key=lambda c: c[0])
227
+
228
+ children_of = defaultdict(list)
229
+ for child, parent in parent_of.items():
230
+ children_of[parent].append(child)
231
+
232
+ relationship_of = {(l, r): rel for l, r, rel in
233
+ zip(pairs["lhs"], pairs["rhs"], pairs["relationship"])}
234
+
235
+ rows = []
236
+ # placed/placed_order/emitted_grains are shared ACROSS columns, not reset
237
+ # per column. Why: an entity with no evidenced relationship to anything
238
+ # (constraint_rows never saw it alongside a partner -- e.g. a column
239
+ # dropped by a group_by before reaching an add* call) becomes an
240
+ # isolated root in its own column. A grain spanning that entity plus
241
+ # others placed in a DIFFERENT column would never satisfy "all my
242
+ # members are placed" under a per-column check, so it -- and every
243
+ # constraint whose home is that grain -- would silently vanish from the
244
+ # tree. Sharing state globally lets the existing entity_ref/chain
245
+ # machinery (already built for the single-column case) reach across
246
+ # columns too: whichever entity's placement completes the grain's
247
+ # membership becomes its home, with entity_ref breadcrumbs for members
248
+ # placed elsewhere, column boundary or not.
249
+ placed = set()
250
+ placed_order = [] # same entities as `placed`, in visit order
251
+ emitted_grains = set()
252
+
253
+ for col_idx, root_cluster in enumerate(columns):
254
+ row_idx = 0
255
+
256
+ def place(entity, parent_id, relation, ancestors):
257
+ nonlocal row_idx
258
+ rows.append({
259
+ "column": col_idx, "row": row_idx, "row_type": "entity",
260
+ "parent_entity": parent_id, "entity": entity,
261
+ "relationship_type": relation, "grain_id": None,
262
+ "node_id": entity,
263
+ })
264
+ row_idx += 1
265
+ placed.add(entity)
266
+ placed_order.append(entity)
267
+ here = ancestors + (entity,)
268
+
269
+ for gid, gset in grain_entity_sets:
270
+ if gid in emitted_grains:
271
+ continue
272
+ if entity in gset and gset <= placed:
273
+ # label entities in the order the hierarchy visited them,
274
+ # not alphabetically -- reads as the flow down the tree
275
+ members = [e for e in placed_order if e in gset]
276
+
277
+ # a grain often needs entities that aren't literal
278
+ # ancestors on THIS branch (they're really placed
279
+ # elsewhere in the tree) -- show them as a short
280
+ # reference chain right above the grain rather than
281
+ # silently nesting the grain under an unrelated entity,
282
+ # so a reader doesn't have to hunt for what composes it
283
+ chain_parent = entity
284
+ for ref_entity in members:
285
+ if ref_entity in here:
286
+ continue
287
+ ref_id = f"{ref_entity}__{gid}"
288
+ rows.append({
289
+ "column": col_idx, "row": row_idx, "row_type": "entity_ref",
290
+ "parent_entity": chain_parent, "entity": ref_entity,
291
+ "relationship_type": "ref", "grain_id": None,
292
+ "node_id": ref_id,
293
+ })
294
+ row_idx += 1
295
+ chain_parent = ref_id
296
+
297
+ rows.append({
298
+ "column": col_idx, "row": row_idx, "row_type": "grain",
299
+ "parent_entity": chain_parent,
300
+ "entity": " x ".join(members),
301
+ "relationship_type": "grain", "grain_id": gid,
302
+ "node_id": gid,
303
+ })
304
+ row_idx += 1
305
+ emitted_grains.add(gid)
306
+
307
+ for child in sorted(children_of.get(entity, [])):
308
+ place(child, entity, relationship_of[(child, entity)], here)
309
+
310
+ for e in root_cluster:
311
+ place(e, None, "root", ())
312
+
313
+ return pl.DataFrame(rows)
314
+
315
+
316
+ def model_graph(frames):
317
+ """Render-agnostic IR: every entity/grain/constraint-family is a node,
318
+ hierarchy placement and constraint reach are edges. No Mermaid, HTML, or
319
+ any other rendering syntax lives here -- that's entirely the render
320
+ layer's job, consuming {"nodes": DataFrame, "edges": DataFrame}. Swap
321
+ the renderer (flowchart, erDiagram, plain text) without touching this.
322
+
323
+ nodes: node_id, node_type ("entity"|"entity_ref"|"grain"|"constraint"), label,
324
+ column (hierarchy column), row (hierarchy row, nullable on constraint
325
+ nodes -- sort by (column, row) to recover the flat top-to-bottom
326
+ traversal order, whether or not a renderer chooses to box columns
327
+ apart), depth (nesting level, root=0, nullable on constraint nodes),
328
+ parent_id (nullable), grain_id (nullable, the real grain_id -- only
329
+ set on grain nodes), count (constraint instance count), example_ids
330
+ (one raw var-id expr), example_fields (same expr with var ids
331
+ swapped for entity names, so the *shape* of the constraint is
332
+ legible without the row numbers).
333
+
334
+ edges: source, target, edge_type ("hierarchy"|"touches"), label.
335
+ Hierarchy edges carry the n:1/n:n/... relationship as their label.
336
+ Touches edges are a constraint reaching a grain beyond its own
337
+ application grain -- the cross-grain bridges. A constraint is always
338
+ a node with 1..n touches edges out, never squeezed into a single
339
+ binary line, so 3+ grain constraints need no special-casing.
340
+ """
341
+ hierarchy = cardinality_hierarchy(frames)
342
+ cons = frames["constraints"]
343
+ variables = frames["variables"]
344
+
345
+ node_recs, edge_recs = [], []
346
+ grain_column = {}
347
+ depth_of = {} # node_id -> nesting level, root = 0
348
+
349
+ for row in hierarchy.iter_rows(named=True):
350
+ node_id = row["node_id"]
351
+ parent = row["parent_entity"]
352
+ depth_of[node_id] = 0 if parent is None else depth_of[parent] + 1
353
+ node_recs.append({
354
+ "node_id": node_id, "node_type": row["row_type"], "label": row["entity"],
355
+ "column": row["column"], "row": row["row"], "depth": depth_of[node_id],
356
+ "parent_id": parent, "grain_id": row["grain_id"], "count": None,
357
+ "example_ids": None, "example_fields": None,
358
+ })
359
+ if parent is not None:
360
+ edge_recs.append({
361
+ "source": parent, "target": node_id,
362
+ "edge_type": "hierarchy", "label": row["relationship_type"],
363
+ })
364
+ if row["row_type"] == "grain":
365
+ grain_column[row["grain_id"]] = row["column"]
366
+
367
+ # ---- constraint families: one node per pipe-call site (type, grain,
368
+ # call_id) -- NOT just (type, grain). Two different `.pipe(problem.add,
369
+ # ...)` calls can share both a verb name and a home grain while doing
370
+ # completely different things (a bound vs. a defining equality, say);
371
+ # call_id is the only signal that actually tells them apart. ----
372
+ var_to_entity = dict(zip(variables["var_id"], variables["entity"]))
373
+ con_grains = constraint_grains(cons, variables)
374
+ con_family = cons.select(["con_id", "type", "grain_id", "call_id"]).rename(
375
+ {"grain_id": "app_grain"})
376
+ family_grains = (
377
+ con_grains.join(con_family, on="con_id", how="left")
378
+ .group_by(["type", "app_grain", "call_id"])
379
+ .agg(pl.col("grain_id").unique().alias("connects_grains")))
380
+ family_meta = (
381
+ cons.group_by(["type", "grain_id", "call_id"])
382
+ .agg(pl.len().alias("count"), pl.col("expr").first().alias("example_ids"))
383
+ .rename({"grain_id": "app_grain"}))
384
+ # sort before assigning ids -- group_by order isn't guaranteed stable
385
+ # across calls, and stable cf-ids matter for reproducible output/diffs
386
+ families = (family_meta.join(family_grains, on=["type", "app_grain", "call_id"], how="left")
387
+ .sort(["type", "app_grain", "call_id"]))
388
+
389
+ for i, fam in enumerate(families.iter_rows(named=True)):
390
+ cf_id = f"cf{i}"
391
+ example_ids = fam["example_ids"] or ""
392
+ example_fields = _VAR_RE.sub(
393
+ lambda m: var_to_entity.get(m.group(0), m.group(0)), example_ids)
394
+ node_recs.append({
395
+ "node_id": cf_id, "node_type": "constraint",
396
+ "label": f"{fam['type']} ×{fam['count']}",
397
+ "column": grain_column.get(fam["app_grain"]), "row": None,
398
+ "depth": depth_of.get(fam["app_grain"]),
399
+ "parent_id": fam["app_grain"], "grain_id": None,
400
+ "count": fam["count"], "example_ids": example_ids,
401
+ "example_fields": example_fields,
402
+ })
403
+ for g in (fam["connects_grains"] or []):
404
+ if g != fam["app_grain"]:
405
+ edge_recs.append({
406
+ "source": cf_id, "target": g,
407
+ "edge_type": "touches", "label": None,
408
+ })
409
+
410
+ return {"nodes": pl.DataFrame(node_recs), "edges": pl.DataFrame(edge_recs)}