dfor 0.1.0__tar.gz

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-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Andrew Cantu-Donaldson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
dfor-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,131 @@
1
+ Metadata-Version: 2.4
2
+ Name: dfor
3
+ Version: 0.1.0
4
+ Summary: Build, diagram, and diagnose OR-Tools CP-SAT models as Polars pipelines
5
+ License-Expression: MIT
6
+ Project-URL: Repository, https://github.com/neon-tetra/dfor
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ License-File: LICENSE
10
+ Requires-Dist: ortools
11
+ Requires-Dist: polars>=1.24
12
+ Provides-Extra: test
13
+ Requires-Dist: pytest; extra == "test"
14
+ Dynamic: license-file
15
+
16
+ # dfor
17
+
18
+ Build OR-Tools CP-SAT models as Polars method chains. Variables and constraints added to the model via the polars pipe operator - methods / arguments pass through the dfor Problem object naturally, methods via __getattr__ fallback, expressions as lambda functions to be iterated over per-row.
19
+
20
+ ---
21
+
22
+ ## Example
23
+
24
+ Each frame row is one decision, and constraints are written as ordinary CP-SAT expressions:
25
+
26
+ ```python
27
+ import polars as pl
28
+ from ortools.sat.python import cp_model
29
+ from dfor import Problem
30
+
31
+ model = cp_model.CpModel()
32
+ problem = Problem(model)
33
+ # nurse_wings, slots, windows: ordinary Polars frames
34
+
35
+ # one bool per nurse x wing x shift the nurse is qualified for
36
+ works = (nurse_wings.join(slots, how="cross")
37
+ .pipe(problem.new_bool_var, "works"))
38
+
39
+ # at most one shift a day
40
+ (works.group_by("nurse", "day").agg(pl.col("works").alias("list_works"))
41
+ .pipe(problem.add,
42
+ lambda r: (sum(r["list_works"]) <= 1,),
43
+ con_name="one_shift_a_day"))
44
+
45
+ # at most 5 shifts in any 7 days
46
+ (works.join(windows, how="cross")
47
+ .filter(pl.col("day").is_between(pl.col("window_start"), pl.col("window_start") + 6))
48
+ .group_by("nurse", "window_start").agg(pl.col("works").alias("list_works"))
49
+ .pipe(problem.add,
50
+ lambda r: (sum(r["list_works"]) <= 5,),
51
+ con_name="rolling_window_cap"))
52
+ ```
53
+
54
+ The full example, [`examples/nurse_shifts.py`](https://github.com/neon-tetra/dfor/blob/main/examples/nurse_shifts.py), schedules 55 nurses across three wings for two weeks: coverage, rest after nights, rolling caps, patient load and severity limits, plus soft goals for walking distance, continuity of care, and requested days off.
55
+
56
+ To run it, from a clone of the repository:
57
+
58
+ ```bash
59
+ pip install -e .
60
+ python examples/nurse_shifts.py
61
+ ```
62
+
63
+ It writes the model views to `examples/nurse_views/`, then solves with a 60-second limit (`TIME_LIMIT` in the script). The model is large (about 72,000 variables and 230,000 constraints), so on a slow or few-core machine the solver may not find a first solution within 60 seconds; raise `TIME_LIMIT` if the status comes back `UNKNOWN`.
64
+
65
+ ---
66
+
67
+ ## Design
68
+
69
+ **Method chaining, in the style of dplyr or pandas.** dfor adds verbs on a `Problem` object, used inside `.pipe()`. Polars and CP-SAT are imported and used as normal; dfor never wraps a frame, so any Polars operation works mid-chain.
70
+
71
+ **Every CP-SAT method passes straight through.** `Problem` defines no constraint methods of its own. `__getattr__` forwards any name to the underlying `CpModel`: `new_*` methods create one variable per row, and `add_*` methods apply one constraint per row. Anything CP-SAT supports works immediately, with no per-method code in dfor.
72
+
73
+ **No expression DSL.** A constraint is a lambda that returns the same arguments you would pass to `CpModel`, written the same way. dfor resolves each row's columns to the real CP-SAT variables and applies the lambda across every row.
74
+
75
+ **Variables are held by reference.** Frames hold string ids, not variable objects; dfor keeps the objects in its own store. Early versions stored CP-SAT variables directly in the frames, but when I reported a [panic crash on certain operations](https://github.com/pola-rs/polars/issues/28182), polars maintainers let me know list/object functionality itself was supposed to be blocked, and fixed the bug by locking it down further. Now dfor handles variable registration/resolution behind the scenes, so from the users perspective it should still feel as if cpsat variables are still stored directly in-frame.
76
+
77
+ **dfor documents as it builds, enabling automated model diagnostic and diagramming;** Since every variable and constraint passes through a `.pipe()` call, `Problem` records each one with its grain (the key columns of the frame it was built on), its source call, and its name. This makes enables functionality like one-line automatic minimum-infeasibility-core diagnosis via QuickXplain (already implemented) and automatic rendering of expressive html model diagrams (already implemented). More tools for diagnosing for speed, infeasibility etc still planned.
78
+
79
+ ---
80
+
81
+ ## Model views and diagnostics
82
+
83
+ **Model views.** `to_frames()` exports the recorded model as Polars frames, and the view functions render it: an interactive tree (`to_tree_html`) and a per-grain matrix (`to_matrix_html`). They can be written before solving, so the structure is available even if a solve stalls.
84
+
85
+ **Infeasibility diagnosis.** Set `problem.diagnostic_mode = True` before building constraints, and every constraint is gated behind an assumption literal. On an infeasible solve, `problem.explain(solver)` gives a quick summary, and `problem.quickxplain()` narrows it to a minimal conflicting set. Conflicts are reported by constraint and grain, with example rows, rather than as raw variable indices.
86
+
87
+ **Solved values.** `report.solved(df, problem, solver)` takes any frame that still holds variable ids and returns it with each one replaced by its solved value.
88
+
89
+ ---
90
+
91
+ ## Warm starts
92
+
93
+ Save a solved model's values as a snapshot, then use them to hint (or fix) a later run. Rows are matched by the `keys` declared on `label_grain`, so a snapshot still applies after rows are added or removed. Label a grain before building its variables:
94
+
95
+ ```python
96
+ problem.label_grain(["nurse", "day", "shift"], "assignments", keys=["nurse", "day"])
97
+ # ... build the model, solve ...
98
+ problem.snapshot(solver).save("run.dfsnap")
99
+
100
+ snap = Snapshot.load("run.dfsnap")
101
+ problem.hint_grain("assignments", snap) # CpModel.add_hint; unmatched rows stay unhinted
102
+ problem.fix_grain("assignments", snap) # or pin the matched rows as constraints
103
+ ```
104
+
105
+ Unmatched rows are left alone, and the matched, new, and dropped counts are printed. Keys must identify a row (duplicates raise at snapshot time), and a snapshot whose keys differ from the model's raises. Solver settings stay plain CP-SAT: a hint usually wants `repair_hint = True` and a raised `hint_conflict_limit`, and it should cover derived variables too, so snapshot those grains as well.
106
+
107
+ ---
108
+
109
+ ## Status
110
+
111
+ Working and in use. Next to explore:
112
+ - More automated debugging and model-testing tools
113
+ - Possibly a MathOpt backend, for MIP solvers
114
+
115
+ More detail on the internals is in [`design.md`](https://github.com/neon-tetra/dfor/blob/main/design.md).
116
+
117
+ ---
118
+
119
+ ## Install
120
+
121
+ ```bash
122
+ pip install dfor
123
+ ```
124
+
125
+ Requires Python 3.10+, `ortools`, and `polars` 1.24+.
126
+
127
+ ---
128
+
129
+ ## License
130
+
131
+ MIT. See [LICENSE](https://github.com/neon-tetra/dfor/blob/main/LICENSE).
dfor-0.1.0/README.md ADDED
@@ -0,0 +1,116 @@
1
+ # dfor
2
+
3
+ Build OR-Tools CP-SAT models as Polars method chains. Variables and constraints added to the model via the polars pipe operator - methods / arguments pass through the dfor Problem object naturally, methods via __getattr__ fallback, expressions as lambda functions to be iterated over per-row.
4
+
5
+ ---
6
+
7
+ ## Example
8
+
9
+ Each frame row is one decision, and constraints are written as ordinary CP-SAT expressions:
10
+
11
+ ```python
12
+ import polars as pl
13
+ from ortools.sat.python import cp_model
14
+ from dfor import Problem
15
+
16
+ model = cp_model.CpModel()
17
+ problem = Problem(model)
18
+ # nurse_wings, slots, windows: ordinary Polars frames
19
+
20
+ # one bool per nurse x wing x shift the nurse is qualified for
21
+ works = (nurse_wings.join(slots, how="cross")
22
+ .pipe(problem.new_bool_var, "works"))
23
+
24
+ # at most one shift a day
25
+ (works.group_by("nurse", "day").agg(pl.col("works").alias("list_works"))
26
+ .pipe(problem.add,
27
+ lambda r: (sum(r["list_works"]) <= 1,),
28
+ con_name="one_shift_a_day"))
29
+
30
+ # at most 5 shifts in any 7 days
31
+ (works.join(windows, how="cross")
32
+ .filter(pl.col("day").is_between(pl.col("window_start"), pl.col("window_start") + 6))
33
+ .group_by("nurse", "window_start").agg(pl.col("works").alias("list_works"))
34
+ .pipe(problem.add,
35
+ lambda r: (sum(r["list_works"]) <= 5,),
36
+ con_name="rolling_window_cap"))
37
+ ```
38
+
39
+ The full example, [`examples/nurse_shifts.py`](https://github.com/neon-tetra/dfor/blob/main/examples/nurse_shifts.py), schedules 55 nurses across three wings for two weeks: coverage, rest after nights, rolling caps, patient load and severity limits, plus soft goals for walking distance, continuity of care, and requested days off.
40
+
41
+ To run it, from a clone of the repository:
42
+
43
+ ```bash
44
+ pip install -e .
45
+ python examples/nurse_shifts.py
46
+ ```
47
+
48
+ It writes the model views to `examples/nurse_views/`, then solves with a 60-second limit (`TIME_LIMIT` in the script). The model is large (about 72,000 variables and 230,000 constraints), so on a slow or few-core machine the solver may not find a first solution within 60 seconds; raise `TIME_LIMIT` if the status comes back `UNKNOWN`.
49
+
50
+ ---
51
+
52
+ ## Design
53
+
54
+ **Method chaining, in the style of dplyr or pandas.** dfor adds verbs on a `Problem` object, used inside `.pipe()`. Polars and CP-SAT are imported and used as normal; dfor never wraps a frame, so any Polars operation works mid-chain.
55
+
56
+ **Every CP-SAT method passes straight through.** `Problem` defines no constraint methods of its own. `__getattr__` forwards any name to the underlying `CpModel`: `new_*` methods create one variable per row, and `add_*` methods apply one constraint per row. Anything CP-SAT supports works immediately, with no per-method code in dfor.
57
+
58
+ **No expression DSL.** A constraint is a lambda that returns the same arguments you would pass to `CpModel`, written the same way. dfor resolves each row's columns to the real CP-SAT variables and applies the lambda across every row.
59
+
60
+ **Variables are held by reference.** Frames hold string ids, not variable objects; dfor keeps the objects in its own store. Early versions stored CP-SAT variables directly in the frames, but when I reported a [panic crash on certain operations](https://github.com/pola-rs/polars/issues/28182), polars maintainers let me know list/object functionality itself was supposed to be blocked, and fixed the bug by locking it down further. Now dfor handles variable registration/resolution behind the scenes, so from the users perspective it should still feel as if cpsat variables are still stored directly in-frame.
61
+
62
+ **dfor documents as it builds, enabling automated model diagnostic and diagramming;** Since every variable and constraint passes through a `.pipe()` call, `Problem` records each one with its grain (the key columns of the frame it was built on), its source call, and its name. This makes enables functionality like one-line automatic minimum-infeasibility-core diagnosis via QuickXplain (already implemented) and automatic rendering of expressive html model diagrams (already implemented). More tools for diagnosing for speed, infeasibility etc still planned.
63
+
64
+ ---
65
+
66
+ ## Model views and diagnostics
67
+
68
+ **Model views.** `to_frames()` exports the recorded model as Polars frames, and the view functions render it: an interactive tree (`to_tree_html`) and a per-grain matrix (`to_matrix_html`). They can be written before solving, so the structure is available even if a solve stalls.
69
+
70
+ **Infeasibility diagnosis.** Set `problem.diagnostic_mode = True` before building constraints, and every constraint is gated behind an assumption literal. On an infeasible solve, `problem.explain(solver)` gives a quick summary, and `problem.quickxplain()` narrows it to a minimal conflicting set. Conflicts are reported by constraint and grain, with example rows, rather than as raw variable indices.
71
+
72
+ **Solved values.** `report.solved(df, problem, solver)` takes any frame that still holds variable ids and returns it with each one replaced by its solved value.
73
+
74
+ ---
75
+
76
+ ## Warm starts
77
+
78
+ Save a solved model's values as a snapshot, then use them to hint (or fix) a later run. Rows are matched by the `keys` declared on `label_grain`, so a snapshot still applies after rows are added or removed. Label a grain before building its variables:
79
+
80
+ ```python
81
+ problem.label_grain(["nurse", "day", "shift"], "assignments", keys=["nurse", "day"])
82
+ # ... build the model, solve ...
83
+ problem.snapshot(solver).save("run.dfsnap")
84
+
85
+ snap = Snapshot.load("run.dfsnap")
86
+ problem.hint_grain("assignments", snap) # CpModel.add_hint; unmatched rows stay unhinted
87
+ problem.fix_grain("assignments", snap) # or pin the matched rows as constraints
88
+ ```
89
+
90
+ Unmatched rows are left alone, and the matched, new, and dropped counts are printed. Keys must identify a row (duplicates raise at snapshot time), and a snapshot whose keys differ from the model's raises. Solver settings stay plain CP-SAT: a hint usually wants `repair_hint = True` and a raised `hint_conflict_limit`, and it should cover derived variables too, so snapshot those grains as well.
91
+
92
+ ---
93
+
94
+ ## Status
95
+
96
+ Working and in use. Next to explore:
97
+ - More automated debugging and model-testing tools
98
+ - Possibly a MathOpt backend, for MIP solvers
99
+
100
+ More detail on the internals is in [`design.md`](https://github.com/neon-tetra/dfor/blob/main/design.md).
101
+
102
+ ---
103
+
104
+ ## Install
105
+
106
+ ```bash
107
+ pip install dfor
108
+ ```
109
+
110
+ Requires Python 3.10+, `ortools`, and `polars` 1.24+.
111
+
112
+ ---
113
+
114
+ ## License
115
+
116
+ MIT. See [LICENSE](https://github.com/neon-tetra/dfor/blob/main/LICENSE).
@@ -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-0.1.0/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)}"
@@ -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