courant-dev 0.5.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 (152) hide show
  1. courant/__init__.py +26 -0
  2. courant/case/__init__.py +0 -0
  3. courant/case/_foam_reader.py +269 -0
  4. courant/case/config.py +134 -0
  5. courant/case/mesh.py +135 -0
  6. courant/case/reads.py +90 -0
  7. courant/case/schemes.py +99 -0
  8. courant/case/solvers.py +170 -0
  9. courant/cli/__init__.py +0 -0
  10. courant/cli/commands/__init__.py +6 -0
  11. courant/cli/commands/audit.py +40 -0
  12. courant/cli/commands/convergence.py +68 -0
  13. courant/cli/commands/ctest.py +76 -0
  14. courant/cli/commands/doctor.py +162 -0
  15. courant/cli/commands/gate.py +88 -0
  16. courant/cli/commands/live.py +73 -0
  17. courant/cli/commands/mcp.py +57 -0
  18. courant/cli/commands/preflight.py +36 -0
  19. courant/cli/commands/spec.py +231 -0
  20. courant/cli/commands/tour.py +122 -0
  21. courant/cli/commands/update.py +213 -0
  22. courant/cli/commands/verify.py +222 -0
  23. courant/cli/config.py +244 -0
  24. courant/cli/guard.py +69 -0
  25. courant/cli/main.py +130 -0
  26. courant/cli/tail.py +351 -0
  27. courant/config.py +155 -0
  28. courant/converge/__init__.py +57 -0
  29. courant/converge/assess.py +823 -0
  30. courant/converge/exact.py +112 -0
  31. courant/converge/render.py +182 -0
  32. courant/converge/scale.py +87 -0
  33. courant/converge/sentences.py +82 -0
  34. courant/converge/series.py +413 -0
  35. courant/converge/steady.py +261 -0
  36. courant/converge/tables.py +1019 -0
  37. courant/converge/transient.py +314 -0
  38. courant/ctest/__init__.py +6 -0
  39. courant/ctest/build.py +82 -0
  40. courant/ctest/data/judge-v0.labels.jsonl +31 -0
  41. courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
  42. courant/ctest/judges/__init__.py +27 -0
  43. courant/ctest/judges/constant.py +18 -0
  44. courant/ctest/judges/courant.py +23 -0
  45. courant/ctest/judges/llm.py +166 -0
  46. courant/ctest/run.py +74 -0
  47. courant/ctest/schema.py +46 -0
  48. courant/ctest/score.py +91 -0
  49. courant/ctest/splits.py +20 -0
  50. courant/data/__init__.py +46 -0
  51. courant/data/certification.json +1 -0
  52. courant/data/certified_codes.json +18 -0
  53. courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
  54. courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
  55. courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
  56. courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
  57. courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
  58. courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
  59. courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
  60. courant/data/schemas/audit.1.json +129 -0
  61. courant/data/schemas/cache.1.json +77 -0
  62. courant/data/schemas/convergence.1.json +112 -0
  63. courant/data/schemas/error-rates.1.json +53 -0
  64. courant/data/schemas/preflight.1.json +250 -0
  65. courant/data/schemas/record.1.json +155 -0
  66. courant/data/schemas/release-signature.1.json +39 -0
  67. courant/data/schemas/spec.1.json +258 -0
  68. courant/data/schemas/support.1.json +80 -0
  69. courant/data/schemas/verdict.1.json +716 -0
  70. courant/data/schemas/verdict.2.json +752 -0
  71. courant/diagnosis/__init__.py +0 -0
  72. courant/diagnosis/bundle.py +168 -0
  73. courant/diagnosis/checkers.py +919 -0
  74. courant/diagnosis/deterministic.py +110 -0
  75. courant/diagnosis/findings.py +107 -0
  76. courant/diagnosis/kb.py +188 -0
  77. courant/diagnosis/kb_data.py +253 -0
  78. courant/diagnosis/llm.py +299 -0
  79. courant/diagnosis/redact.py +425 -0
  80. courant/diagnosis/schema.py +83 -0
  81. courant/events/__init__.py +35 -0
  82. courant/events/core.py +194 -0
  83. courant/events/diverged.py +55 -0
  84. courant/gate/__init__.py +1 -0
  85. courant/gate/config.py +150 -0
  86. courant/gate/run.py +295 -0
  87. courant/live/__init__.py +16 -0
  88. courant/live/engine.py +155 -0
  89. courant/live/watch.py +164 -0
  90. courant/llm/__init__.py +59 -0
  91. courant/llm/allowlist.py +60 -0
  92. courant/llm/anthropic.py +137 -0
  93. courant/llm/budget.py +491 -0
  94. courant/llm/door.py +1071 -0
  95. courant/llm/errors.py +105 -0
  96. courant/llm/openrouter.py +118 -0
  97. courant/llm/policy.py +268 -0
  98. courant/llm/transport.py +48 -0
  99. courant/mcp/__init__.py +7 -0
  100. courant/mcp/server.py +113 -0
  101. courant/mcp/tools.py +177 -0
  102. courant/record/__init__.py +22 -0
  103. courant/record/filter.py +99 -0
  104. courant/record/record.py +149 -0
  105. courant/release.py +205 -0
  106. courant/signing.py +99 -0
  107. courant/spec/__init__.py +31 -0
  108. courant/spec/check.py +353 -0
  109. courant/spec/deck.py +455 -0
  110. courant/spec/extract.py +181 -0
  111. courant/spec/impossible.py +197 -0
  112. courant/spec/model.py +194 -0
  113. courant/taxonomy.py +219 -0
  114. courant/verification/__init__.py +30 -0
  115. courant/verification/_fluid_reader.py +228 -0
  116. courant/verification/bounding.py +84 -0
  117. courant/verification/checks.py +369 -0
  118. courant/verification/convergence.py +257 -0
  119. courant/verification/fields.py +38 -0
  120. courant/verification/grade.py +101 -0
  121. courant/verification/suite.py +30 -0
  122. courant/verify/__init__.py +37 -0
  123. courant/verify/about.py +100 -0
  124. courant/verify/audit.py +209 -0
  125. courant/verify/batch.py +141 -0
  126. courant/verify/cache.py +329 -0
  127. courant/verify/checks.py +37 -0
  128. courant/verify/html.py +330 -0
  129. courant/verify/ingest.py +115 -0
  130. courant/verify/junit.py +48 -0
  131. courant/verify/outcome.py +74 -0
  132. courant/verify/pack.py +106 -0
  133. courant/verify/pipeline.py +396 -0
  134. courant/verify/policy.py +167 -0
  135. courant/verify/preflight.py +166 -0
  136. courant/verify/render.py +174 -0
  137. courant/verify/schema.py +398 -0
  138. courant/verify/sentences.py +137 -0
  139. courant/verify/support.py +142 -0
  140. courant/verify/verdict2.py +235 -0
  141. courant/watcher/__init__.py +13 -0
  142. courant/watcher/anomaly.py +244 -0
  143. courant/watcher/exitcode.py +23 -0
  144. courant/watcher/parser.py +435 -0
  145. courant/watcher/watcher.py +49 -0
  146. courant_dev-0.5.0.dist-info/METADATA +146 -0
  147. courant_dev-0.5.0.dist-info/RECORD +152 -0
  148. courant_dev-0.5.0.dist-info/WHEEL +5 -0
  149. courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
  150. courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
  151. courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
  152. courant_dev-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,413 @@
1
+ """Reading what a run wrote (TRD CONV-3 to CONV-5). The only module in this package with I/O.
2
+
3
+ Monitors come from function-object output under `postProcessing/`. Residuals and the clock
4
+ come from the solver log's events. Everything here turns files into the plain sequences
5
+ `assess()` takes, and notes every file it read (`courant.case.reads`), so a pack can re-hash
6
+ them (REP-5, VER-14).
7
+
8
+ What it reads:
9
+ - whitespace tables, `*.dat`: forceCoeffs `coefficient.dat`, forces `force.dat` and
10
+ `moment.dat`, surfaceFieldValue, volFieldValue;
11
+ - the probes format, one file per field, `# Probe i (x y z)`;
12
+ - vectors in parentheses, expanded to `_x`, `_y`, `_z`;
13
+ - the legacy forces header `forces(pressure viscous porous)`, expanded to `forces_pressure` …;
14
+ - restarts across start-time directories (M1-S-5).
15
+
16
+ What it does not read: `fieldMinMax`, whose rows interleave fields. Those files are listed as
17
+ ignored, never guessed at.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import math
23
+ import re
24
+ from dataclasses import dataclass
25
+ from pathlib import Path
26
+
27
+ from courant.case.reads import note
28
+ from courant.converge.assess import (
29
+ Clock,
30
+ Convergence,
31
+ Finding,
32
+ MonitorSeries,
33
+ Options,
34
+ RunMeta,
35
+ assess,
36
+ )
37
+
38
+ POST = "postProcessing"
39
+ MAX_FILES = 256
40
+ MAX_BYTES = 256 * 1024 * 1024
41
+ BAD_ROW_FRACTION = 0.01
42
+ RESTART_MAJORITY = 0.5
43
+
44
+ _IGNORED = re.compile(r"minmax", re.I)
45
+ _ENTRY = re.compile(r"\(([^()]*)\)|(\S+)")
46
+ _GROUP = re.compile(r"(\w+)\(([^()]*\s[^()]*)\)")
47
+ _COMPONENT = re.compile(r"^(.+)_([xyz])$")
48
+ _NPROCS = re.compile(r"^nProcs\s*:\s*(\d+)", re.M)
49
+ _EXEC = re.compile(r"^Exec\s*:\s*(\S+)", re.M)
50
+
51
+
52
+ def _is_number(name: str) -> bool:
53
+ try:
54
+ return math.isfinite(float(name))
55
+ except ValueError:
56
+ return False
57
+
58
+
59
+ # ------------------------------------------------------------------ tables
60
+ @dataclass
61
+ class Table:
62
+ columns: list[str]
63
+ vectors: dict[str, str] # expanded column -> its vector's name
64
+ rows: list[tuple[float, list[float]]]
65
+ bad_rows: int
66
+ total_rows: int
67
+
68
+
69
+ def _entries(line: str) -> list[tuple[str, list[str]]]:
70
+ """('s', [tok]) for a scalar, ('v', [x, y, z]) for a parenthesised vector."""
71
+ line = line.replace("((", "(").replace("))", ")")
72
+ out = []
73
+ for m in _ENTRY.finditer(line):
74
+ if m.group(1) is not None:
75
+ out.append(("v", m.group(1).split()))
76
+ else:
77
+ out.append(("s", [m.group(2)]))
78
+ return out
79
+
80
+
81
+ def _header_names(comments: list[str], n_entries: int) -> list[str] | None:
82
+ """Column names for the entries after time, from the comment block, or None."""
83
+ for line in reversed(comments[-2:]):
84
+ text = _GROUP.sub(lambda m: " ".join(f"{m.group(1)}_{s}" for s in m.group(2).split()),
85
+ line.lstrip("#").strip())
86
+ toks = text.split()
87
+ if not toks:
88
+ continue
89
+ if toks[0].lower() == "time" and len(toks) - 1 == n_entries:
90
+ return toks[1:]
91
+ if toks[0].lower() == "probe" and len(toks) - 1 == n_entries:
92
+ return [f"probe{t}" for t in toks[1:]]
93
+ return None
94
+
95
+
96
+ def parse_table(text: str) -> Table | None:
97
+ comments: list[str] = []
98
+ shape: list[tuple[str, int]] | None = None
99
+ names: list[str] = []
100
+ vectors: dict[str, str] = {}
101
+ rows: list[tuple[float, list[float]]] = []
102
+ bad = total = 0
103
+ for raw in text.splitlines():
104
+ line = raw.strip()
105
+ if not line:
106
+ continue
107
+ if line.startswith("#"):
108
+ if shape is None:
109
+ comments.append(line)
110
+ continue
111
+ ents = _entries(line)
112
+ if shape is None:
113
+ if not ents or ents[0][0] != "s":
114
+ return None
115
+ shape = [(k, len(v)) for k, v in ents]
116
+ base = _header_names(comments, len(ents) - 1) or [f"c{i}" for i in range(1, len(ents))]
117
+ for (kind, width), name in zip(shape[1:], base):
118
+ if kind == "v" and width == 3:
119
+ for axis in "xyz":
120
+ names.append(f"{name}_{axis}")
121
+ vectors[f"{name}_{axis}"] = name
122
+ elif kind == "v":
123
+ names.extend(f"{name}_{i}" for i in range(width))
124
+ else:
125
+ names.append(name)
126
+ total = total + 1
127
+ if [(k, len(v)) for k, v in ents] != shape:
128
+ bad = bad + 1
129
+ continue
130
+ try:
131
+ flat = [float(tok) for _, toks in ents for tok in toks]
132
+ except ValueError:
133
+ bad = bad + 1
134
+ continue
135
+ rows.append((flat[0], flat[1:]))
136
+ if shape is None:
137
+ return None
138
+ # v2406 writes force components as separate scalar columns (total_x total_y total_z), not
139
+ # as parenthesised vectors. A full x, y, z triple under one base name is a vector.
140
+ for name in names:
141
+ m = _COMPONENT.match(name)
142
+ if m and name not in vectors and all(f"{m.group(1)}_{a}" in names for a in "xyz"):
143
+ vectors[name] = m.group(1)
144
+ return Table(names, vectors, rows, bad, total)
145
+
146
+
147
+ def _merge_restarts(rows):
148
+ """M1-S-5: the last strictly increasing run wins; earlier runs keep only what precedes it."""
149
+ runs, cur = [], []
150
+ for r in rows:
151
+ if cur and r[0] <= cur[-1][0]:
152
+ runs.append(cur)
153
+ cur = []
154
+ cur.append(r)
155
+ if cur:
156
+ runs.append(cur)
157
+ if not runs:
158
+ return [], 0, None
159
+ merged = list(runs[-1])
160
+ discarded, span = 0, None
161
+ for run in reversed(runs[:-1]):
162
+ t0 = merged[0][0]
163
+ keep = [r for r in run if r[0] < t0]
164
+ lost = [r for r in run if r[0] >= t0]
165
+ if lost:
166
+ discarded = discarded + len(lost)
167
+ lo, hi = lost[0][0], lost[-1][0]
168
+ span = (min(lo, span[0]), max(hi, span[1])) if span else (lo, hi)
169
+ merged = keep + merged
170
+ return merged, discarded, span
171
+
172
+
173
+ # ------------------------------------------------------------------ discovery
174
+ @dataclass
175
+ class Discovery:
176
+ monitors: list[MonitorSeries]
177
+ ignored: list[str]
178
+ searched: list[str]
179
+ files: list[Path]
180
+
181
+
182
+ def _candidate_files(start_dir: Path):
183
+ for f in sorted(start_dir.iterdir()):
184
+ if not f.is_file():
185
+ continue
186
+ if f.suffix == ".dat":
187
+ yield f
188
+ elif f.suffix == "":
189
+ try:
190
+ with f.open("r", errors="replace") as fh:
191
+ head = fh.readline()
192
+ except OSError:
193
+ continue
194
+ note(f) # VER-14: its first line decided whether it is a monitor
195
+ if head.lstrip().startswith("# Probe"):
196
+ yield f
197
+
198
+
199
+ def discover(case_dir: Path) -> Discovery:
200
+ post = case_dir / POST
201
+ searched = [POST]
202
+ if not post.is_dir():
203
+ return Discovery([], [], searched, [])
204
+ groups: dict[tuple[str, str], list[Path]] = {}
205
+ ignored: list[str] = []
206
+ for obj in sorted(p for p in post.iterdir() if p.is_dir()):
207
+ if _IGNORED.search(obj.name):
208
+ ignored.append(f"{POST}/{obj.name}")
209
+ continue
210
+ for start in sorted((d for d in obj.iterdir() if d.is_dir() and _is_number(d.name)),
211
+ key=lambda d: float(d.name)):
212
+ for f in _candidate_files(start):
213
+ if _IGNORED.search(f.name):
214
+ ignored.append(str(f.relative_to(case_dir)))
215
+ continue
216
+ groups.setdefault((obj.name, f.name), []).append(f)
217
+ monitors: list[MonitorSeries] = []
218
+ files: list[Path] = []
219
+ budget = MAX_BYTES
220
+ for (obj, fname), paths in sorted(groups.items()):
221
+ if len(files) + len(paths) > MAX_FILES:
222
+ ignored.extend(str(p.relative_to(case_dir)) for p in paths)
223
+ continue
224
+ try:
225
+ size = sum_ints(p.stat().st_size for p in paths)
226
+ except OSError: # vanished since it was listed: not read, not listed
227
+ ignored.extend(str(p.relative_to(case_dir)) for p in paths)
228
+ continue
229
+ if size > budget:
230
+ ignored.extend(str(p.relative_to(case_dir)) for p in paths)
231
+ continue
232
+ budget = budget - size
233
+ tables = []
234
+ for p in paths:
235
+ try:
236
+ text = p.read_text(errors="replace")
237
+ except OSError: # unreadable: not read, so not listed (VER-14)
238
+ ignored.append(str(p.relative_to(case_dir)))
239
+ continue
240
+ note(p) # VER-14: read, so listed, whether or not it parses
241
+ t = parse_table(text)
242
+ if t is not None:
243
+ tables.append((p, t))
244
+ if not tables:
245
+ ignored.extend(str(p.relative_to(case_dir)) for p in paths)
246
+ continue
247
+ files.extend(p for p, _ in tables)
248
+ columns = tables[-1][1].columns
249
+ usable = [(p, t) for p, t in tables if t.columns == columns]
250
+ rows = [r for _, t in usable for r in t.rows]
251
+ bad = sum_ints(t.bad_rows for _, t in usable)
252
+ total = sum_ints(t.total_rows for _, t in usable)
253
+ merged, discarded, span = _merge_restarts(rows)
254
+ stem = fname[:-4] if fname.endswith(".dat") else fname
255
+ source = ";".join(str(p.relative_to(case_dir)) for p, _ in usable)
256
+ vectors = tables[-1][1].vectors
257
+ for j, col in enumerate(columns):
258
+ mid = f"{obj}/{stem}:{col}"
259
+ findings: list[Finding] = []
260
+ reason = None
261
+ if discarded:
262
+ findings.append(Finding("CONV.RESTART_OVERLAP", "WARN", mid, "M1-S-5",
263
+ {"fraction": RESTART_MAJORITY},
264
+ {"monitor": mid, "discarded_samples": discarded,
265
+ "discarded_time_range": list(span)}))
266
+ if discarded > RESTART_MAJORITY * (len(merged) + discarded):
267
+ reason = "RESTART_OVERLAP_MAJORITY"
268
+ if total and bad > BAD_ROW_FRACTION * total:
269
+ findings.append(Finding("CONV.MONITOR_UNREADABLE", "WARN", mid, "table reader",
270
+ {"fraction": BAD_ROW_FRACTION},
271
+ {"monitor": mid, "bad_rows": bad, "rows": total}))
272
+ reason = "UNREADABLE_ROWS"
273
+ monitors.append(MonitorSeries(
274
+ id=mid, column=col, source=source, times=[r[0] for r in merged],
275
+ values=[r[1][j] for r in merged],
276
+ vector=f"{obj}/{stem}:{vectors[col]}" if col in vectors else None,
277
+ reader_findings=tuple(findings), not_assessable=reason))
278
+ return Discovery(monitors, sorted(set(ignored)), searched, files)
279
+
280
+
281
+ def sum_ints(values) -> int:
282
+ total = 0
283
+ for v in values:
284
+ total = total + int(v)
285
+ return total
286
+
287
+
288
+ # ------------------------------------------------------------------ the log
289
+ def from_events(events) -> tuple[dict[str, list[float]], Clock, int]:
290
+ from courant.events.core import EventKind
291
+
292
+ residuals: dict[str, list[float]] = {}
293
+ times, clock_s, exec_s = [], [], []
294
+ for e in events:
295
+ if e.kind is not EventKind.RESIDUAL:
296
+ continue
297
+ p = e.payload
298
+ for name, value in p.initial_residuals.items():
299
+ residuals.setdefault(name, []).append(value)
300
+ times.append(p.time if p.time is not None else float(len(times) + 1))
301
+ clock_s.append(p.clock_time)
302
+ exec_s.append(p.exec_time)
303
+ return residuals, Clock(times, clock_s, exec_s), len(times)
304
+
305
+
306
+ def ranks_from_log(log_text: str) -> tuple[int, str]:
307
+ m = _NPROCS.search(log_text[:20000])
308
+ if m:
309
+ return int(m.group(1)), "log_nprocs"
310
+ return 1, "serial"
311
+
312
+
313
+ def solver_from_log(log_text: str) -> str | None:
314
+ m = _EXEC.search(log_text[:20000])
315
+ return m.group(1) if m else None
316
+
317
+
318
+ def regime_of(config, solver: str | None, clock: Clock) -> tuple[str | None, str, dict | None]:
319
+ """config first, then the solver table, then the time column (M1-R-1 to R-4)."""
320
+ from courant.case import solvers
321
+
322
+ by_config = None
323
+ if config is not None and getattr(config, "ddt_scheme", None):
324
+ by_config = "steady" if config.is_steady() else "transient"
325
+ by_solver = None
326
+ if solver and solvers.is_known(solver):
327
+ by_solver = "steady" if solvers.is_steady(solver) else "transient"
328
+ conflict = None
329
+ if by_config and by_solver and by_config != by_solver:
330
+ conflict = {"config": by_config, "solver": by_solver}
331
+ if by_config:
332
+ return by_config, "config", conflict
333
+ if by_solver:
334
+ return by_solver, "solver", None
335
+ t = list(clock.times)
336
+ if len(t) >= 2:
337
+ integral = all(float(x).is_integer() for x in t) and all(t[i + 1] - t[i] == 1.0
338
+ for i in range(len(t) - 1))
339
+ return ("steady" if integral else "transient"), "inferred", None
340
+ return None, "unknown", None
341
+
342
+
343
+ def ended_by(events) -> tuple[str | None, int | None]:
344
+ from courant.events.core import EventKind
345
+
346
+ steps = len([e for e in events if e.kind is EventKind.RESIDUAL])
347
+ for e in events:
348
+ if e.kind is EventKind.CRASH:
349
+ return ("signal" if e.payload.signal else "crash"), steps
350
+ return None, steps
351
+
352
+
353
+ # ------------------------------------------------------------------ which monitors are the answer
354
+ #: CONV-4a. By default the answer is the totals a function object writes. A front/rear or
355
+ #: pressure/viscous split is a diagnostic of a total, and judging it as well lets the least
356
+ #: relevant column decide the run. Splits are excluded only where their total is present in
357
+ #: the same file. `--monitor` patterns replace the default entirely.
358
+ _FORCE_SPLIT = re.compile(r"^(pressure|viscous|porous)_[xyz]$")
359
+ _COEFF_SPLIT = re.compile(r"\((f|r)\)$")
360
+
361
+
362
+ def select(monitors, patterns) -> tuple[list, list, str]:
363
+ """(selected, not selected, basis)."""
364
+ import fnmatch
365
+
366
+ if patterns:
367
+ chosen = [m for m in monitors
368
+ if any(fnmatch.fnmatchcase(m.id, p) or fnmatch.fnmatchcase(m.column, p)
369
+ for p in patterns)]
370
+ return chosen, [m.id for m in monitors if m not in chosen], "user_patterns"
371
+ by_file: dict[str, set[str]] = {}
372
+ for m in monitors:
373
+ by_file.setdefault(m.id.rsplit(":", 1)[0], set()).add(m.column)
374
+ chosen, dropped = [], []
375
+ for m in monitors:
376
+ cols = by_file[m.id.rsplit(":", 1)[0]]
377
+ split = ((_FORCE_SPLIT.match(m.column) and "total_x" in cols) or
378
+ (_COEFF_SPLIT.search(m.column) and m.column.split("(")[0] in cols))
379
+ (dropped.append(m.id) if split else chosen.append(m))
380
+ return chosen, dropped, "default_totals"
381
+
382
+
383
+ # ------------------------------------------------------------------ the entry point
384
+ def assess_case(case_dir: str | Path | None, *, log_text: str, events, config=None,
385
+ solver: str | None = None, options: Options = Options(),
386
+ read: tuple = ()) -> Convergence:
387
+ """Read the case's monitors and the log's residuals and clock, then `assess()`.
388
+
389
+ `Convergence.inputs` is the verdict's manifest function applied to this run (VER-14):
390
+ `read`, the manifest of what the caller already read for it (the ingest's log, deck and
391
+ checkMesh log, where the regime and the clock came from), merged with every case file this
392
+ function read, parsed or not, as its readers noted it.
393
+ """
394
+ from courant.case.reads import recording
395
+ from courant.verify.schema import manifest, merge
396
+
397
+ residuals, clock, steps = from_events(events)
398
+ solver = solver or solver_from_log(log_text)
399
+ regime, basis, conflict = regime_of(config, solver, clock)
400
+ ranks, ranks_basis = ranks_from_log(log_text)
401
+ how, last = ended_by(events)
402
+ if case_dir:
403
+ with recording(case_dir) as reads:
404
+ found = discover(Path(case_dir))
405
+ inputs = merge(read, manifest(case_dir, reads.paths()))
406
+ else:
407
+ found, inputs = Discovery([], [], [], []), tuple(read)
408
+ chosen, unselected, basis_sel = select(found.monitors, options.monitors)
409
+ meta = RunMeta(regime=regime, regime_basis=basis, regime_conflict=conflict, ranks=ranks,
410
+ ranks_basis=ranks_basis, ended_by=how, last_complete_step=last,
411
+ paths_searched=tuple(found.searched), monitors_ignored=tuple(found.ignored),
412
+ monitors_unselected=tuple(unselected), selection=basis_sel)
413
+ return assess(chosen, residuals, clock, meta, options, inputs)
@@ -0,0 +1,261 @@
1
+ """The steady branch: fixed point, limit cycle, residual orders (TRD CONV-6, M1 §5.1.5-5.1.7, 5.1.14).
2
+
3
+ A steady solver's answer is a fixed point. This module asks three questions of one monitor:
4
+ 1. Has it stopped moving, and stayed stopped? That is the drift criterion over trailing
5
+ windows.
6
+ 2. From where? That is the stopping-point search.
7
+ 3. Is it in a limit cycle that a trailing-window slope would call settled? That is the
8
+ detrended autocorrelation test.
9
+
10
+ Residuals get their own, weaker questions. They describe the iteration, not the answer.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from array import array
17
+ from collections.abc import Sequence
18
+ from dataclasses import dataclass
19
+
20
+ from courant.converge.exact import ExactSums, mean
21
+
22
+ WINDOW_FLOOR = 200 # M1-F-1: below this, no window rule applies
23
+ DRIFT_FACTOR = 0.2 # M1-F-3: the drift across a window must be < 0.2 * tol
24
+ ACF_THRESHOLD = 0.5 # M1-U-2
25
+ ITERATION_LAG_MAX = 3 # CONV-6c: periods of 2 or 3 iterations are the iteration, not the flow
26
+ ACF_EXACT_MAX = 2048 # CONV-6b: longer windows use the two-level autocorrelation
27
+ COARSE_DIVISOR = 64 # M1-X-2: coarse stride is w // 64
28
+ ORDERS_CAP = 30 # M1-G-1
29
+ PLATEAU_DRIFT = 0.2 # M1-P-2
30
+
31
+
32
+ def window_width(n: int) -> int:
33
+ """w = min(n, max(200, ceil(n / 10)))."""
34
+ return min(n, max(WINDOW_FLOOR, -(-n // 10)))
35
+
36
+
37
+ class Drift:
38
+ """Absolute drift |slope| * (w - 1) of trailing windows of width `w` (M1-F-2, CONV-6a).
39
+
40
+ The values are centred on the final value, `y' = y - c`, so the cancellation in the
41
+ closed-form slope is smallest where the decision is made. A window-local abscissa cannot
42
+ be cached, so `S_xy` uses the global-index sum `S_iy` and the exact identity
43
+ `S_xy = S_iy - a * S_y`. Both sums are exact window sums (`exact.py`).
44
+ """
45
+
46
+ def __init__(self, values: Sequence[float], w: int) -> None:
47
+ n = len(values)
48
+ if w < 2 or w > n:
49
+ raise ValueError(f"window {w} invalid for {n} samples")
50
+ c = values[n - 1]
51
+ centred = array("d", (v - c for v in values))
52
+ self.n = n
53
+ self.w = w
54
+ self._y = ExactSums(centred)
55
+ self._iy = ExactSums(array("d", (i * centred[i] for i in range(n))))
56
+ self._sx = w * (w - 1) // 2
57
+ sxx = (w - 1) * w * (2 * w - 1) // 6
58
+ self._den = w * sxx - self._sx * self._sx
59
+ self.evaluations = 0
60
+
61
+ def slope(self, e: int) -> float:
62
+ """OLS slope per sample over the window ending at index `e` (inclusive)."""
63
+ a = e - self.w + 1
64
+ sy = self._y.window(a, e + 1)
65
+ sxy = self._iy.window(a, e + 1) - a * sy
66
+ return (self.w * sxy - self._sx * sy) / self._den
67
+
68
+ def drift(self, e: int) -> float:
69
+ self.evaluations = self.evaluations + 1
70
+ return abs(self.slope(e)) * (self.w - 1)
71
+
72
+
73
+ def unsettled(drift: float, tau: float) -> bool:
74
+ """A window fails the criterion. An exactly zero drift always passes, so a constant
75
+ tail with no usable scale (tau = 0) is still settled."""
76
+ return drift > 0.0 and drift >= tau
77
+
78
+
79
+ @dataclass(frozen=True, slots=True)
80
+ class Search:
81
+ index: int | None # the stopping point, or None when the last window is unsettled
82
+ evaluations: int
83
+ decimated: bool
84
+ resolution: int # in samples
85
+
86
+
87
+ def stopping_index(drift: Drift, tau: float, budget: int) -> Search:
88
+ """The earliest index from which every trailing window is settled (M1-F-5, M1-X-2).
89
+
90
+ A coarse backward pass at stride w // 64 finds the last failing grid point. The
91
+ exhaustive pass then checks every skipped window after it, from the end backwards,
92
+ so the first failure it meets is the true maximum. If the exhaustive pass would exceed
93
+ `budget`, the coarse answer is reported, rounded up to the next grid point, which
94
+ understates the saving rather than overstating it.
95
+ """
96
+ n, w = drift.n, drift.w
97
+ last, first = n - 1, w - 1
98
+ if unsettled(drift.drift(last), tau):
99
+ return Search(None, drift.evaluations, False, 1)
100
+ sigma = max(1, w // COARSE_DIVISOR)
101
+ fail = None
102
+ e = last - sigma
103
+ while e >= first:
104
+ if unsettled(drift.drift(e), tau):
105
+ fail = e
106
+ break
107
+ e = e - sigma
108
+ lo = fail if fail is not None else first - 1
109
+ gaps = (last - lo) - 1 - (last - lo - 1) // sigma
110
+ if drift.evaluations + gaps > budget:
111
+ if fail is not None:
112
+ index = min(fail + sigma, last)
113
+ else:
114
+ index = last - ((last - first) // sigma) * sigma
115
+ return Search(index, drift.evaluations, True, sigma)
116
+ for e in range(last - 1, lo, -1):
117
+ if (last - e) % sigma == 0:
118
+ continue # a coarse point, already known to pass
119
+ if unsettled(drift.drift(e), tau):
120
+ return Search(e + 1, drift.evaluations, False, 1)
121
+ return Search(lo + 1, drift.evaluations, False, 1)
122
+
123
+
124
+ # ------------------------------------------------------------------ the limit-cycle test
125
+ @dataclass(frozen=True, slots=True)
126
+ class Oscillation:
127
+ tested: bool
128
+ lag: int | None = None
129
+ acf: float | None = None
130
+ amplitude: float | None = None
131
+ n_periods: int | None = None
132
+ fires: bool = False
133
+ cycle_mean: float | None = None
134
+ reason: str | None = None
135
+
136
+
137
+ def detrend(values: Sequence[float], slope: float) -> list[float]:
138
+ """The trailing window minus its fitted line (M1-U-1)."""
139
+ w = len(values)
140
+ m = mean(values)
141
+ intercept = m - slope * ((w - 1) / 2)
142
+ return [values[t] - (intercept + slope * t) for t in range(w)]
143
+
144
+
145
+ def _acf(z: Sequence[float], lmax: int) -> list[float] | None:
146
+ """Biased autocorrelation rho(0..lmax+1), divisor w at every lag (M1-U-1)."""
147
+ w = len(z)
148
+ zbar = mean(z)
149
+ d = [v - zbar for v in z]
150
+ g0 = math.fsum(v * v for v in d) / w
151
+ if g0 <= 0.0:
152
+ return None
153
+ top = min(lmax + 1, w - 1)
154
+ rho = [1.0]
155
+ rho.extend(math.fsum(d[t] * d[t + lag] for t in range(w - lag)) / w / g0
156
+ for lag in range(1, top + 1))
157
+ return rho
158
+
159
+
160
+ def _best_period(rho: list[float], lmax: int) -> tuple[int, float] | None:
161
+ best = None
162
+ for lag in range(2, min(lmax, len(rho) - 2) + 1):
163
+ r = rho[lag]
164
+ if r > ACF_THRESHOLD and r > rho[lag - 1] and r >= rho[lag + 1]:
165
+ if best is None or r > best[1]:
166
+ best = (lag, r)
167
+ return best
168
+
169
+
170
+ def _block_means(z: Sequence[float], size: int) -> list[float]:
171
+ k = len(z) // size
172
+ start = len(z) - k * size
173
+ return [mean(z[start + j * size:start + (j + 1) * size]) for j in range(k)]
174
+
175
+
176
+ def oscillation(z: Sequence[float], limit: float) -> Oscillation:
177
+ """The limit-cycle test on a detrended window `z` (M1-U-2, U-3).
178
+
179
+ `limit` is the amplitude a cycle must exceed to matter: tol for an absolute monitor,
180
+ tol * R for a relative one. When the whole window's peak-to-peak is already below it,
181
+ no cycle in it can fire, and the autocorrelation is not computed (CONV-6b).
182
+ """
183
+ w = len(z)
184
+ if w < 16:
185
+ return Oscillation(False, reason="window too short")
186
+ if max(z) - min(z) <= limit:
187
+ return Oscillation(False, reason="peak-to-peak below tolerance")
188
+ candidates: list[tuple[int, float]] = []
189
+ exact = z[w - ACF_EXACT_MAX:] if w > ACF_EXACT_MAX else z
190
+ lmax = len(exact) // 4
191
+ rho = _acf(exact, lmax)
192
+ if rho is not None:
193
+ found = _best_period(rho, lmax)
194
+ if found:
195
+ candidates.append(found)
196
+ if w > ACF_EXACT_MAX:
197
+ size = -(-w // ACF_EXACT_MAX)
198
+ coarse = _block_means(z, size)
199
+ lmax_c = len(coarse) // 4
200
+ rho_c = _acf(coarse, lmax_c)
201
+ if rho_c is not None:
202
+ found = _best_period(rho_c, lmax_c)
203
+ if found and found[0] * size > ACF_EXACT_MAX // 4:
204
+ candidates.append((found[0] * size, found[1]))
205
+ if not candidates:
206
+ return Oscillation(True, fires=False, reason="no autocorrelation peak above 0.5")
207
+ lag, r = sorted(candidates, key=lambda c: (-c[1], c[0]))[0]
208
+ periods = w // lag
209
+ if periods < 1:
210
+ return Oscillation(True, fires=False, reason="period longer than the window")
211
+ tail = z[w - periods * lag:]
212
+ amplitude = max(tail) - min(tail)
213
+ return Oscillation(True, lag=lag, acf=r, amplitude=amplitude, n_periods=periods,
214
+ fires=amplitude > limit)
215
+
216
+
217
+ # ------------------------------------------------------------------ residuals
218
+ @dataclass(frozen=True, slots=True)
219
+ class ResidualSummary:
220
+ field: str
221
+ n: int
222
+ r_ref: float | None
223
+ r_final: float | None
224
+ r_min: float | None
225
+ r_min_index: int | None
226
+ ratio: float | None
227
+ orders_dropped_floor: int | None
228
+ orders_capped: bool
229
+ plateaued: bool | None # None when the series is too short for a window
230
+ drift_rel: float | None
231
+
232
+
233
+ def orders_dropped(r_ref: float, r_final: float) -> tuple[int, bool]:
234
+ """max{j : r_final * 10**j <= r_ref}, by repeated multiplication, no logarithm."""
235
+ j = 0
236
+ v = r_final
237
+ while j < ORDERS_CAP and v * 10.0 <= r_ref:
238
+ v = v * 10.0
239
+ j = j + 1
240
+ return j, j >= ORDERS_CAP
241
+
242
+
243
+ def residual_summary(field: str, values: Sequence[float]) -> ResidualSummary:
244
+ """Orders dropped (Celik), the minimum, and the plateau test (M1-P-1, P-2, G-1)."""
245
+ finite = [v for v in values if math.isfinite(v) and v > 0.0]
246
+ n = len(finite)
247
+ if n < 2:
248
+ return ResidualSummary(field, n, None, finite[-1] if finite else None, None, None,
249
+ None, None, False, None, None)
250
+ r_ref, r_final = finite[1], finite[-1]
251
+ r_min = min(finite)
252
+ r_min_index = finite.index(r_min)
253
+ orders, capped = orders_dropped(r_ref, r_final)
254
+ plateaued, drift_rel = None, None
255
+ if n >= WINDOW_FLOOR:
256
+ w = window_width(n)
257
+ d = Drift(finite, w)
258
+ drift_rel = d.drift(n - 1) / r_final
259
+ plateaued = drift_rel < PLATEAU_DRIFT
260
+ return ResidualSummary(field, n, r_ref, r_final, r_min, r_min_index, r_ref / r_final,
261
+ orders, capped, plateaued, drift_rel)