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,228 @@
1
+ """Read solution fields from a solved case (live verification path).
2
+
3
+ The fields are parsed with foamlib, the library the case reader already parses `0/`, `constant/`
4
+ and `system/` with, and a dependency of every install (pyproject.toml `dependencies`, the release
5
+ lock, the binary). Until 11 Oct 2026 they were parsed with fluidfoam, which only the `sandbox`
6
+ extra installed and the binary excluded: a development checkout read fields, CI and the shipped
7
+ binary never did, and the verdict said "fields not read" there. fluidfoam also read a binary
8
+ field wrongly (a byte of the data taken for a delimiter), returned nothing for a `.gz` field and
9
+ failed on a one-line header; foamlib reads all three.
10
+
11
+ Best-effort: reads the internal fields the field-based checks use (p, U, k, epsilon,
12
+ omega, T, nut) plus nu, from the latest time directory. Anything missing is simply
13
+ absent — the corresponding checks skip rather than fail.
14
+
15
+ PARALLEL CASES — the reason this file is not three lines shorter.
16
+ ================================================================
17
+ A decomposed run writes its results into `processor0/`, `processor1/`, … and leaves
18
+ the case root holding only `0/`, `constant/` and `system/`. `find_time_dirs` looks
19
+ at the root, so on every parallel case it returned `["0"]` and this function read
20
+ `0/U` — **the initial condition** — and handed it to the verification suite as the
21
+ result.
22
+
23
+ That is worse than failing. Measured on a real 4-rank `icoFoam` run that diverged to
24
+ a Courant number of 1580 with a cumulative continuity error of 2.65e+27, the
25
+ field-based checks reported *"fields within plausible bounds"*, because the initial
26
+ condition is perfectly plausible. The run was graded D only because the log-based
27
+ checks caught it. In the silent-error class — a run that completes and converges but
28
+ is physically wrong, which is half of what this product claims to find — the log is
29
+ clean by definition and these checks are the only thing left. They were reading t=0.
30
+
31
+ So two rules here, in order:
32
+
33
+ 1. **A decomposed case is read from its `processor*/` directories**, concatenated.
34
+ For the checks that use fields — bounds, plausibility, y+, a velocity scale — the
35
+ union of the subdomains is the domain, and concatenation is exactly right.
36
+ 2. **If the real result cannot be read, return no fields at all.** Never fall back to
37
+ `0/`. A check that skips is honest; a check that passes on the initial condition
38
+ is a false "physics-OK", and that is the one invariant this product says is
39
+ structurally zero.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ import glob
45
+ import os
46
+ import sys
47
+
48
+ import numpy as np
49
+
50
+ from courant.case.reads import reading
51
+ from courant.verification.fields import FieldData
52
+
53
+ #: Scalar fields the field-based checks look for.
54
+ _SCALARS = ("p", "k", "epsilon", "omega", "T", "nut")
55
+
56
+
57
+ def _numeric_time_dirs(root: str) -> list[str]:
58
+ """Numeric time directory names directly under `root`, ascending."""
59
+ out: list[str] = []
60
+ if not os.path.isdir(root):
61
+ return out
62
+ for name in os.listdir(root):
63
+ if not os.path.isdir(os.path.join(root, name)):
64
+ continue
65
+ try:
66
+ float(name)
67
+ except ValueError:
68
+ continue
69
+ out.append(name)
70
+ return sorted(out, key=float)
71
+
72
+
73
+ def processor_dirs(case_dir: str) -> list[str]:
74
+ """Where a decomposed run put its results, in rank order.
75
+
76
+ Two layouts, because OpenFOAM has two file handlers:
77
+
78
+ * `uncollated` (the default) — `processor0/`, `processor1/`, … one per rank.
79
+ * `collated` — a single `processors4/` (or `processors4_0-3/` for grouped
80
+ writing) holding one file per field with every rank's data inside it.
81
+ Increasingly the choice on large runs, because it stops a 4096-rank job
82
+ from creating 4096 directories.
83
+
84
+ Both are returned. A collated directory is a *directory of time
85
+ directories* just like a rank directory, so the caller's logic is unchanged;
86
+ whether the field files inside it can be parsed is a separate question, and
87
+ one that fails safely — an unreadable field is simply absent.
88
+ """
89
+ ranked: list[tuple[int, str]] = []
90
+ for path in glob.glob(os.path.join(case_dir, "processor[0-9]*")):
91
+ if not os.path.isdir(path):
92
+ continue
93
+ suffix = os.path.basename(path)[len("processor"):]
94
+ if suffix.isdigit():
95
+ ranked.append((int(suffix), path))
96
+ if ranked:
97
+ return [path for _, path in sorted(ranked)]
98
+
99
+ collated = [p for p in glob.glob(os.path.join(case_dir, "processors[0-9]*"))
100
+ if os.path.isdir(p)]
101
+ return sorted(collated)
102
+
103
+
104
+ def _field_file(case: str, time: str, name: str) -> str:
105
+ """The file a field is read from at `time`: the plain file, else its `.gz`."""
106
+ path = os.path.join(case, time, name)
107
+ if not os.path.exists(path) and os.path.exists(path + ".gz"):
108
+ return path + ".gz"
109
+ return path
110
+
111
+
112
+ def _binary_as_read(arch) -> None:
113
+ """Raise unless a binary field's bytes are what foamlib reads: little-endian 64-bit
114
+ scalars, on a little-endian host. foamlib ignores the header's `arch`, reads the host's byte
115
+ order and guesses the scalar size from the byte count, so a big-endian or single-precision
116
+ field would come back as other numbers. Such a field is left unread, never guessed. No
117
+ `arch` is OpenFOAM's native default (LSB, 64-bit scalars on every platform it ships for).
118
+ The label size does not matter here: a field's counts are written in ASCII."""
119
+ if sys.byteorder != "little":
120
+ raise ValueError(f"binary field on a {sys.byteorder}-endian host")
121
+ if arch is None:
122
+ return
123
+ parts = [p.strip() for p in str(arch).strip().strip('"').split(";") if p.strip()]
124
+ order = [p for p in parts if "=" not in p]
125
+ sizes = dict(p.split("=", 1) for p in parts if "=" in p)
126
+ if order != ["LSB"] or sizes.get("scalar", "64") != "64" or not set(sizes) <= {"label", "scalar"}:
127
+ raise ValueError(f"binary field written as {arch!r}; read only as LSB;scalar=64")
128
+
129
+
130
+ def _internal(path: str, vector: bool) -> np.ndarray | None:
131
+ """The internal field of one field file, as per-cell values: shape (N,) for a scalar,
132
+ (N, 3) for a vector, N = 1 for a `uniform` value. None when the file holds no field of that
133
+ shape (a collated `decomposedBlockData`, a tensor, a region directory's stray file)."""
134
+ from foamlib import FoamFieldFile
135
+
136
+ f = FoamFieldFile(path)
137
+ if str(f.format) == "binary":
138
+ _binary_as_read(f["FoamFile"].get("arch"))
139
+ values = np.asarray(f.internal_field, dtype=float)
140
+ if vector:
141
+ if values.shape == (3,):
142
+ values = values.reshape(1, 3)
143
+ return values if values.ndim == 2 and values.shape[1] == 3 else None
144
+ values = np.atleast_1d(values)
145
+ return values if values.ndim == 1 else None
146
+
147
+
148
+ def _read_one(case: str, time: str) -> dict[str, np.ndarray]:
149
+ """Every readable field in one case-shaped directory at one time."""
150
+ out: dict[str, np.ndarray] = {}
151
+ # VER-14: `reading` notes a field file once it has been read, parsed or not, and leaves out
152
+ # one that could not be opened (absent, unreadable, purged), which is simply a missing field.
153
+ for name, vector in (*((s, False) for s in _SCALARS), ("U", True)):
154
+ path = _field_file(case, time, name)
155
+ try:
156
+ with reading(path):
157
+ values = _internal(path, vector)
158
+ except Exception: # noqa: BLE001 — field not present, or not parseable, in this case
159
+ continue
160
+ if values is not None:
161
+ out[name] = values
162
+ return out
163
+
164
+
165
+ def _concat(parts: list[dict[str, np.ndarray]]) -> dict[str, np.ndarray]:
166
+ """Union the per-rank subdomains into one field set."""
167
+ merged: dict[str, np.ndarray] = {}
168
+ for name in set().union(*(p.keys() for p in parts)) if parts else ():
169
+ arrays = [p[name] for p in parts if name in p and np.size(p[name])]
170
+ if not arrays:
171
+ continue
172
+ try:
173
+ merged[name] = np.concatenate(arrays, axis=0)
174
+ except ValueError: # ragged ranks — a partial write; drop the field
175
+ continue
176
+ return merged
177
+
178
+
179
+ def read_fields(case_dir: str, time: str | None = None) -> FieldData:
180
+ procs = processor_dirs(case_dir)
181
+ root_times = _numeric_time_dirs(case_dir)
182
+ solved_at_root = [t for t in root_times if float(t) > 0.0]
183
+
184
+ internal: dict[str, np.ndarray] = {}
185
+ latest = time
186
+
187
+ if solved_at_root or not procs:
188
+ # Serial, or a parallel case the engineer has already reconstructed.
189
+ latest = time or (root_times[-1] if root_times else None)
190
+ if latest is not None and (solved_at_root or not procs):
191
+ internal = _read_one(case_dir, latest)
192
+ else:
193
+ # Decomposed and not reconstructed: the answer is in the ranks.
194
+ # Use rank 0's clock — every rank writes the same times.
195
+ proc_times = _numeric_time_dirs(procs[0])
196
+ latest = time or (proc_times[-1] if proc_times else None)
197
+ if latest is not None and float(latest) > 0.0:
198
+ internal = _concat([_read_one(p, latest) for p in procs])
199
+
200
+ # Rule 2. Reading `0/` and calling it the result is how a diverged run gets
201
+ # told its fields are plausible.
202
+ if latest is None or float(latest) <= 0.0:
203
+ return FieldData(time=0.0, internal={}, nu=None, inlet_speed=None)
204
+
205
+ nu = None
206
+ try:
207
+ from foamlib import FoamFile
208
+
209
+ from courant.case._foam_reader import _scalar
210
+
211
+ transport = os.path.join(case_dir, "constant/transportProperties")
212
+ with reading(transport): # VER-14: read for nu, whether or not it has one
213
+ nu = _scalar(FoamFile(transport)["nu"])
214
+ except Exception: # noqa: BLE001
215
+ pass
216
+
217
+ inlet_speed = None
218
+ if "U" in internal:
219
+ u = internal["U"]
220
+ mag = np.linalg.norm(u, axis=1) if u.ndim == 2 else np.abs(u)
221
+ if mag.size:
222
+ inlet_speed = float(np.percentile(mag, 95))
223
+
224
+ try:
225
+ t = float(latest)
226
+ except ValueError:
227
+ t = 0.0
228
+ return FieldData(time=t, internal=internal, nu=nu, inlet_speed=inlet_speed)
@@ -0,0 +1,84 @@
1
+ """Was this field clipped, and does it matter? THE ONE PLACE THIS IS ANSWERED.
2
+
3
+ `BoundingChecker`, `_unbounded_scheme_symptom` and the grade's `TurbulenceBoundsCheck` all
4
+ need it. The checker and the scheme symptom were unified in August; the grade still counted
5
+ every bounding event on its own. On `simpleFoam/T3A`, the first fresh tutorial run after v0.3,
6
+ that made an unmodified case grade C, for 1,001 events in which k's minimum was exactly 0.
7
+
8
+ Two facts decide it:
9
+ - **An excursion is a field that went negative.** OpenFOAM prints a bounding line when a
10
+ field reaches its floor. A minimum of exactly 0 is the floor touched: T3A's k in its laminar
11
+ region before transition. A minimum a few parts in a million below 0 is round-off: T3A's
12
+ gammaInt, at -3.7e-05 against a maximum of 1.0. Neither is unbounded transport. The
13
+ injected unbounded-scheme fault on pitzDaily clips epsilon to -2,741 against a maximum of
14
+ 80,809, which is 3.4%. pitzDaily's own startup reaches -205 against 33,174, which is 0.6%.
15
+ `ROUNDOFF` (0.1%) sits clear of both: 30 times below the fault and 6 times below the startup.
16
+ - **Severity comes from the tail.** A field still being clipped in the final fifth of the run
17
+ is persistent, and anything earlier is the solution relaxing. That is the convention
18
+ `CourantChecker` uses for the Courant number. The rule it replaces asked whether every
19
+ excursion fell in the first 10% of the run. That boundary was fitted to pitzDaily (1% against
20
+ 100%), and T3A's transition model stops clipping gammaInt at 10.4% of its 1,000 iterations,
21
+ then converges cleanly. A boundary that a healthy case crosses by 0.4% is not a physical
22
+ criterion; "is it still happening at the end" is.
23
+
24
+ An event without magnitudes (written before the parser kept them) counts as an excursion,
25
+ which is the behaviour it had before.
26
+ """
27
+
28
+ from __future__ import annotations
29
+
30
+ from courant.events.core import EventKind
31
+
32
+ ROUNDOFF = 1.0e-3
33
+
34
+ #: Clipping in the final fifth of the run is persistent; before it, the solution is relaxing.
35
+ #: The same tail `CourantChecker` judges the Courant number on. Measured: pitzDaily (healthy)
36
+ #: last clips on step 3 of 282, T3A (healthy) on step 104 of 1,000, and the unbounded-scheme
37
+ #: fault on step 300 of 300.
38
+ TAIL_FRACTION = 0.20
39
+ #: Kept for callers that name the old constants.
40
+ SETTLE_FRACTION = 1.0 - TAIL_FRACTION
41
+ SETTLE_MIN_STEPS = 3
42
+
43
+
44
+ def is_excursion(payload) -> bool:
45
+ """A bounding event in which the field genuinely went negative."""
46
+ lo = getattr(payload, "minimum", None)
47
+ if lo is None:
48
+ return True
49
+ if lo >= 0.0:
50
+ return False
51
+ scale = max(abs(getattr(payload, "maximum", None) or 0.0),
52
+ abs(getattr(payload, "average", None) or 0.0))
53
+ return scale == 0.0 or abs(lo) > ROUNDOFF * scale
54
+
55
+
56
+ def bounding_by_field(events) -> dict[str, tuple[int, bool]]:
57
+ """Per field: how many excursions, and whether they all happened during startup."""
58
+ steps = 0
59
+ counts: dict[str, int] = {}
60
+ last_step: dict[str, int] = {}
61
+ for e in events:
62
+ if e.kind == EventKind.RESIDUAL:
63
+ steps = steps + 1
64
+ elif (e.kind == EventKind.WARN and getattr(e.payload, "category", None) == "bounding"
65
+ and is_excursion(e.payload)):
66
+ f = e.payload.field or "?"
67
+ counts[f] = counts.get(f, 0) + e.payload.count
68
+ last_step[f] = steps
69
+ if not counts:
70
+ return {}
71
+ # With no residuals there is no run to be early or late in: report, never silence.
72
+ window = max(SETTLE_MIN_STEPS, steps * (1.0 - TAIL_FRACTION)) if steps else float("-inf")
73
+ return {f: (c, last_step.get(f, 0) <= window) for f, c in counts.items()}
74
+
75
+
76
+ def floor_clips_by_field(events) -> dict[str, int]:
77
+ """Bounding events that touched the floor without going negative: reported, never judged."""
78
+ out: dict[str, int] = {}
79
+ for e in events:
80
+ if (e.kind == EventKind.WARN and getattr(e.payload, "category", None) == "bounding"
81
+ and not is_excursion(e.payload)):
82
+ f = e.payload.field or "?"
83
+ out[f] = out.get(f, 0) + e.payload.count
84
+ return out
@@ -0,0 +1,369 @@
1
+ """Verification checks — deterministic physics audit (Tech Arch §7).
2
+
3
+ Two tiers:
4
+ * event/residual-based — run offline on the Watcher's history (divergence,
5
+ convergence quality, continuity/mass balance, turbulence bounds),
6
+ * field-based — need solution fields (conservation flux, y+, regime, plausibility);
7
+ they run live and SKIP (not fail) when fields are unavailable.
8
+
9
+ Pure functions over {events, config, fields}. No LLM. Each returns a
10
+ VerificationResult whose severity feeds the Trust Grade.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import math
16
+ from dataclasses import dataclass
17
+ from typing import Protocol
18
+
19
+ import numpy as np
20
+
21
+ from courant.case.config import CaseConfig
22
+ from courant.events import Event, EventKind
23
+ from courant.events.diverged import divergences
24
+ from courant.verification.fields import FieldData
25
+ from courant.verification.convergence import (
26
+ RESIDUAL_LOOSE,
27
+ RESIDUAL_TARGET,
28
+ solve_converged,
29
+ worst_final_residual,
30
+ )
31
+ from courant.verification.grade import VerificationResult, VSeverity
32
+
33
+ OK, MINOR, MAJOR, CRIT = (VSeverity.OK, VSeverity.MINOR, VSeverity.MAJOR,
34
+ VSeverity.CRITICAL)
35
+
36
+
37
+ @dataclass
38
+ class VerifyContext:
39
+ run_id: str
40
+ events: list[Event]
41
+ config: CaseConfig | None = None
42
+ fields: FieldData | None = None
43
+
44
+ def of(self, kind: EventKind) -> list[Event]:
45
+ return [e for e in self.events if e.kind == kind]
46
+
47
+ def last_residual(self) -> Event | None:
48
+ residuals = self.of(EventKind.RESIDUAL)
49
+ return residuals[-1] if residuals else None
50
+
51
+
52
+ def _result(code, name, severity, passed, **kw) -> VerificationResult:
53
+ return VerificationResult(check_code=code, check_name=name, severity=severity,
54
+ passed=passed, **kw)
55
+
56
+
57
+ def _skip(code, name, why) -> VerificationResult:
58
+ return VerificationResult(check_code=code, check_name=name, severity=OK,
59
+ passed=True, skipped=True, detail=why)
60
+
61
+
62
+ class VerificationCheck(Protocol):
63
+ code: str
64
+ name: str
65
+
66
+ def run(self, ctx: VerifyContext) -> VerificationResult:
67
+ ...
68
+
69
+
70
+ # ---------------------------------------------------------------------------
71
+ # Event / residual-based checks (offline-capable)
72
+ # ---------------------------------------------------------------------------
73
+
74
+ class StabilityCheck:
75
+ code, name = "stability.divergence", "Solution stability (no NaN/Inf)"
76
+
77
+ def run(self, ctx: VerifyContext) -> VerificationResult:
78
+ nan = divergences(ctx.events)
79
+ if nan:
80
+ return _result(self.code, self.name, CRIT, False,
81
+ detail=f"residual reached NaN/Inf on {nan[0].payload.field}",
82
+ evidence={"field": nan[0].payload.field})
83
+ return _result(self.code, self.name, OK, True, detail="no NaN/Inf residuals")
84
+
85
+
86
+ class CrashCheck:
87
+ code, name = "completion.crash", "Run completed without crashing"
88
+
89
+ def run(self, ctx: VerifyContext) -> VerificationResult:
90
+ crashes = ctx.of(EventKind.CRASH)
91
+ if crashes:
92
+ return _result(self.code, self.name, CRIT, False,
93
+ detail=f"solver crashed (tag={crashes[0].payload.tag})")
94
+ return _result(self.code, self.name, OK, True, detail="clean exit")
95
+
96
+
97
+ class ConvergenceCheck:
98
+ code, name = "convergence.residual", "Residuals converged below tolerance"
99
+ # Shared with the fix loop via `courant.verification.convergence`. Two copies
100
+ # of a threshold are two thresholds, and this pair is what decides whether a
101
+ # fix worked — the fix loop used to answer that question with "did the
102
+ # process exit 0", which is how a run that reached Co=4.6e+30 was reported
103
+ # as fixed.
104
+ TARGET, LOOSE = RESIDUAL_TARGET, RESIDUAL_LOOSE
105
+
106
+ def run(self, ctx: VerifyContext) -> VerificationResult:
107
+ last = ctx.last_residual()
108
+ if last is None:
109
+ return _skip(self.code, self.name, "no residual history")
110
+ # `worst_final_residual`, not a fourth hand-rolled max().
111
+ #
112
+ # This one dropped NaN and nothing else. `convergence.worst_final_residual`
113
+ # also drops infinities and **phase fractions** — and the omission had a
114
+ # live cost: an unmodified `interFoam/damBreak` was graded **C**, because
115
+ # `alpha.water` sits at 1.08e-02 while `p_rgh` settles to 5.3e-04. The
116
+ # initial residual of a volume fraction measures how far the interface
117
+ # MOVED, not how far the solve is from satisfying its equations, and on
118
+ # a free-surface run the interface moving is the entire point. Every
119
+ # customer doing VOF would have been told their correct run failed.
120
+ #
121
+ # That reasoning was already written down, in the module this now
122
+ # imports from. It just was not called from here.
123
+ worst = worst_final_residual(ctx.events)
124
+ if worst is None:
125
+ return _skip(self.code, self.name, "no residual values")
126
+
127
+ # **A transient run is judged on stability, by the same function the fix
128
+ # loop uses.** Sixth instance of one fact with two implementations, and
129
+ # the same fact as the fifth: `solve_converged` learned that a
130
+ # time-marching solve's final residual is a function of its timestep, so
131
+ # a residual bar is a steady-state criterion applied where its
132
+ # assumption does not hold — and this check kept its own copy of the old
133
+ # rule.
134
+ #
135
+ # The cost was Courant disagreeing with itself inside one report. On
136
+ # `pisoFoam/RAS/cavity` a CFL repair brought the Courant number to a
137
+ # stable 0.8, the fix loop called it converged, and this graded it C for
138
+ # a residual of 2.22e-02 — a number that is high only because the
139
+ # repaired timestep is 3.4x coarser than the tutorial's own.
140
+ #
141
+ # So it asks rather than re-deciding. The steady branch below is
142
+ # untouched, and a run with no config still gets the residual bar.
143
+ if ctx.config is not None and not ctx.config.is_steady():
144
+ stable, why = solve_converged(ctx.events, config=ctx.config)
145
+ return _result(
146
+ self.code, self.name,
147
+ OK if stable else MAJOR, stable, value=worst,
148
+ detail=(f"transient solve judged on stability rather than a "
149
+ f"residual threshold — {why} (final worst residual "
150
+ f"{worst:.2e})"))
151
+
152
+ if worst <= self.TARGET:
153
+ sev, passed = OK, True
154
+ elif worst <= self.LOOSE:
155
+ sev, passed = MINOR, True
156
+ else:
157
+ sev, passed = MAJOR, False
158
+ return _result(self.code, self.name, sev, passed, value=worst,
159
+ threshold=self.TARGET,
160
+ detail=f"final worst residual {worst:.2e} (target {self.TARGET:.0e})")
161
+
162
+
163
+ class ContinuityCheck:
164
+ """Reports the cumulative continuity error. Deliberately does not grade on it.
165
+
166
+ **IT USED TO, AND IT GRADED TWO OF OPENFOAM'S OWN TUTORIALS DOWN.**
167
+ `simpleFoam/pitzDaily` finishes with a cumulative continuity error of
168
+ **1.51**, which against a 1e-03 threshold is MAJOR — so Courant handed a C
169
+ to a case the OpenFOAM project ships as correct. Worse, the repaired run in
170
+ `pitzDaily::unbounded_scheme` reached 1.14 — *better than the tutorial* —
171
+ and was failed for it.
172
+
173
+ The number is dimensional and cumulative. It is a running sum in units of
174
+ volumetric flow, so its scale is set by the geometry and the inlet velocity
175
+ and by how many iterations have been run. Measured across this corpus, the
176
+ final cumulative error on healthy tutorials spans **4e-18 (icoFoam/cavity)
177
+ to 1.5 (pitzDaily)** — eighteen orders of magnitude, with nothing wrong in
178
+ any of them. No constant separates those, and picking one that happens to
179
+ fit the cases we have is fitting the corpus rather than the physics.
180
+
181
+ This is the same conclusion already reached for `CONV.MASS_IMBALANCE` in the
182
+ taxonomy, and for the same reason; see `docs/COVERAGE.md`. It simply had not
183
+ been applied here, where it was actively costing grades.
184
+
185
+ **What does grade conservation is `MassFluxCheck`**, which divides the net
186
+ boundary flux by the inflow and is therefore dimensionless — a real
187
+ imbalance shows up there as a fraction, on any case, at any scale. It needs
188
+ the solution fields, which is the honest cost: without them Courant reports
189
+ the continuity number and does not pretend to judge it.
190
+ """
191
+
192
+ code, name = "conservation.continuity", "Global continuity (mass) balance"
193
+
194
+ def run(self, ctx: VerifyContext) -> VerificationResult:
195
+ last = ctx.last_residual()
196
+ if last is None or last.payload.continuity is None:
197
+ return _skip(self.code, self.name, "no continuity data")
198
+ cum = last.payload.continuity.cumulative
199
+ if cum is None:
200
+ return _skip(self.code, self.name, "no cumulative continuity error")
201
+ mag = abs(cum)
202
+ # The one judgement that survives being scale-free: a continuity error
203
+ # that is not a number at all means the solve stopped being arithmetic.
204
+ if math.isnan(mag) or math.isinf(mag):
205
+ return _result(self.code, self.name, MAJOR, False, value=None,
206
+ detail="cumulative continuity error is not finite")
207
+ return _result(self.code, self.name, OK, True, value=mag,
208
+ detail=f"cumulative continuity error {cum:.2e} "
209
+ f"(reported, not graded — see MassFluxCheck)")
210
+
211
+
212
+ class TurbulenceBoundsCheck:
213
+ code, name = "bounds.turbulence", "Turbulence quantities not over-clipped"
214
+ TURB = {"k", "epsilon", "omega", "nut"}
215
+ MANY = 10
216
+
217
+ def run(self, ctx: VerifyContext) -> VerificationResult:
218
+ # The one definition (verification/bounding.py): only a field that went negative
219
+ # counts, and startup clipping is not judged as persistent. Counting every bounding
220
+ # line made the unmodified T3A tutorial grade C, for 1,001 floor clips at exactly 0.
221
+ from courant.verification.bounding import bounding_by_field, floor_clips_by_field
222
+
223
+ by = {f: v for f, v in bounding_by_field(ctx.events).items() if f in self.TURB}
224
+ n = sum(c for c, _ in by.values())
225
+ floors = sum(c for f, c in floor_clips_by_field(ctx.events).items() if f in self.TURB)
226
+ if n == 0:
227
+ detail = "no turbulence clipping" if not floors else (
228
+ f"no negative excursion ({floors} floor clips at or within round-off of zero)")
229
+ return _result(self.code, self.name, OK, True, detail=detail)
230
+ persistent = sorted(f for f, (_, settled) in by.items() if not settled)
231
+ sev = MAJOR if (persistent and n >= self.MANY) else MINOR
232
+ fields = sorted(by)
233
+ return _result(self.code, self.name, sev, sev is not MAJOR, value=float(n),
234
+ detail=f"{n} bounding excursions on {fields}"
235
+ + (f", still clipping late on {persistent}" if persistent else
236
+ ", all during startup"),
237
+ evidence={"fields": fields, "persistent": persistent})
238
+
239
+
240
+ # ---------------------------------------------------------------------------
241
+ # Field-based checks (live; skip when fields unavailable)
242
+ # ---------------------------------------------------------------------------
243
+
244
+ class MassFluxCheck:
245
+ code, name = "conservation.mass_flux", "Net boundary mass flux ~ 0"
246
+ LOOSE = 1e-2
247
+
248
+ def run(self, ctx: VerifyContext) -> VerificationResult:
249
+ if ctx.fields is None or not ctx.fields.patch_fluxes:
250
+ return _skip(self.code, self.name, "no field flux data")
251
+ fluxes = ctx.fields.patch_fluxes
252
+ net = sum(fluxes.values())
253
+ inflow = sum(-f for f in fluxes.values() if f < 0) or 1.0
254
+ rel = abs(net) / inflow
255
+ if rel <= 1e-3:
256
+ sev, passed = OK, True
257
+ elif rel <= self.LOOSE:
258
+ sev, passed = MINOR, True
259
+ else:
260
+ sev, passed = MAJOR, False
261
+ return _result(self.code, self.name, sev, passed, value=rel, threshold=1e-3,
262
+ detail=f"net/inflow flux imbalance {rel:.2e}")
263
+
264
+
265
+ class YPlusCheck:
266
+ code, name = "nearwall.yplus", "Near-wall y+ compatible with wall treatment"
267
+
268
+ def run(self, ctx: VerifyContext) -> VerificationResult:
269
+ if ctx.fields is None or ctx.fields.yplus is None:
270
+ return _skip(self.code, self.name, "no y+ field")
271
+ yplus = np.asarray(ctx.fields.yplus)
272
+ in_log_layer = float(np.mean((yplus >= 30) & (yplus <= 300)))
273
+ if in_log_layer >= 0.8:
274
+ sev, passed = OK, True
275
+ elif in_log_layer >= 0.5:
276
+ sev, passed = MINOR, True
277
+ else:
278
+ sev, passed = MAJOR, False
279
+ return _result(self.code, self.name, sev, passed, value=in_log_layer,
280
+ threshold=0.8,
281
+ detail=f"{in_log_layer:.0%} of wall faces in y+ [30,300]")
282
+
283
+
284
+ class RegimeCheck:
285
+ code, name = "regime.reynolds", "Flow regime matches turbulence modeling"
286
+ RE_TURBULENT = 2300.0
287
+
288
+ def run(self, ctx: VerifyContext) -> VerificationResult:
289
+ f = ctx.fields
290
+ if f is None or None in (f.inlet_speed, f.length_scale, f.nu) or f.nu == 0:
291
+ return _skip(self.code, self.name, "insufficient data for Reynolds number")
292
+ re = f.inlet_speed * f.length_scale / f.nu
293
+ laminar = ctx.config is not None and ctx.config.is_laminar()
294
+ if laminar and re > self.RE_TURBULENT:
295
+ return _result(self.code, self.name, MAJOR, False, value=re,
296
+ threshold=self.RE_TURBULENT,
297
+ detail=f"laminar model at Re={re:.0f} (turbulent regime)")
298
+ if not laminar and re < 1000:
299
+ return _result(self.code, self.name, MINOR, True, value=re,
300
+ detail=f"turbulence model at low Re={re:.0f}")
301
+ return _result(self.code, self.name, OK, True, value=re,
302
+ detail=f"Re={re:.0f} consistent with modeling")
303
+
304
+
305
+ class PlausibilityCheck:
306
+ code, name = "bounds.plausibility", "Field values physically plausible"
307
+
308
+ def run(self, ctx: VerifyContext) -> VerificationResult:
309
+ f = ctx.fields
310
+ if f is None or not f.internal:
311
+ return _skip(self.code, self.name, "no internal fields")
312
+ # A nan or inf anywhere in a solution field is a blown-up result, as a non-finite
313
+ # residual is (courant.events.diverged). Checked first: `np.min` of an array holding
314
+ # nan is nan, `nan < 0` is False, and a k field of nan read as "k non-negative".
315
+ for name in sorted(f.internal):
316
+ arr = np.asarray(f.internal[name], dtype=float)
317
+ bad = int(arr.size - np.count_nonzero(np.isfinite(arr)))
318
+ if bad:
319
+ return _result(self.code, self.name, MAJOR, False,
320
+ detail=f"non-finite {name} ({bad} of {arr.size} values "
321
+ f"nan or inf)")
322
+ for name in ("k", "epsilon", "omega", "T"):
323
+ arr = f.internal.get(name)
324
+ if arr is not None and np.size(arr) and np.min(np.asarray(arr)) < 0:
325
+ return _result(self.code, self.name, MAJOR, False,
326
+ value=float(np.min(arr)),
327
+ detail=f"negative {name} (min {float(np.min(arr)):.2e})")
328
+ # THE VELOCITY-SPIKE TEST IS NOT RUN, AND SAYING SO IS THE POINT.
329
+ #
330
+ # It compared `max|U|` against `f.inlet_speed` — which is the 95th
331
+ # percentile of *that same array*. The ratio of a distribution's maximum
332
+ # to its own 95th percentile sits near 1 whatever the values are, so the
333
+ # 10x threshold could not be reached. Measured on a decomposed cavity run
334
+ # that had diverged: max|U| 14.7 against a lid moving at 1 m/s, a true
335
+ # overspeed of 14.7x, and the check computed 1.27 and passed.
336
+ #
337
+ # A real reference scale is a *boundary* condition, not a statistic of
338
+ # the answer, and deriving one is not a one-line change: the obvious
339
+ # source is `0/U`, and on a lid-driven cavity, a dam break or a heated
340
+ # room that field is uniformly zero, so the naive version divides by
341
+ # nothing on three of the seven certified tutorials. That work needs its
342
+ # own evidence and its own certification run.
343
+ #
344
+ # Until then this check verifies what it can actually verify, and its
345
+ # detail line says which. An affirmative "fields within plausible
346
+ # bounds", printed on the strength of a comparison that cannot fail, is
347
+ # exactly the false reassurance this product exists to remove.
348
+ checked = [n for n in ("k", "epsilon", "omega", "T")
349
+ if n in f.internal and np.size(f.internal[n])]
350
+ if not checked:
351
+ return _skip(self.code, self.name,
352
+ "no boundable scalar fields; velocity scale needs a "
353
+ "boundary reference Courant does not read yet")
354
+ return _result(self.code, self.name, OK, True,
355
+ detail=f"{', '.join(checked)} non-negative "
356
+ f"(velocity scale not checked — needs a boundary "
357
+ f"reference)")
358
+
359
+
360
+ DEFAULT_CHECKS: list[VerificationCheck] = [
361
+ StabilityCheck(), CrashCheck(), ConvergenceCheck(), ContinuityCheck(),
362
+ TurbulenceBoundsCheck(), MassFluxCheck(), YPlusCheck(), RegimeCheck(),
363
+ PlausibilityCheck(),
364
+ ]
365
+
366
+
367
+ def run_checks(ctx: VerifyContext,
368
+ checks: list[VerificationCheck] | None = None) -> list[VerificationResult]:
369
+ return [c.run(ctx) for c in (checks or DEFAULT_CHECKS)]