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.
- courant/__init__.py +26 -0
- courant/case/__init__.py +0 -0
- courant/case/_foam_reader.py +269 -0
- courant/case/config.py +134 -0
- courant/case/mesh.py +135 -0
- courant/case/reads.py +90 -0
- courant/case/schemes.py +99 -0
- courant/case/solvers.py +170 -0
- courant/cli/__init__.py +0 -0
- courant/cli/commands/__init__.py +6 -0
- courant/cli/commands/audit.py +40 -0
- courant/cli/commands/convergence.py +68 -0
- courant/cli/commands/ctest.py +76 -0
- courant/cli/commands/doctor.py +162 -0
- courant/cli/commands/gate.py +88 -0
- courant/cli/commands/live.py +73 -0
- courant/cli/commands/mcp.py +57 -0
- courant/cli/commands/preflight.py +36 -0
- courant/cli/commands/spec.py +231 -0
- courant/cli/commands/tour.py +122 -0
- courant/cli/commands/update.py +213 -0
- courant/cli/commands/verify.py +222 -0
- courant/cli/config.py +244 -0
- courant/cli/guard.py +69 -0
- courant/cli/main.py +130 -0
- courant/cli/tail.py +351 -0
- courant/config.py +155 -0
- courant/converge/__init__.py +57 -0
- courant/converge/assess.py +823 -0
- courant/converge/exact.py +112 -0
- courant/converge/render.py +182 -0
- courant/converge/scale.py +87 -0
- courant/converge/sentences.py +82 -0
- courant/converge/series.py +413 -0
- courant/converge/steady.py +261 -0
- courant/converge/tables.py +1019 -0
- courant/converge/transient.py +314 -0
- courant/ctest/__init__.py +6 -0
- courant/ctest/build.py +82 -0
- courant/ctest/data/judge-v0.labels.jsonl +31 -0
- courant/ctest/data/judge-v0.tasks.jsonl.gz +0 -0
- courant/ctest/judges/__init__.py +27 -0
- courant/ctest/judges/constant.py +18 -0
- courant/ctest/judges/courant.py +23 -0
- courant/ctest/judges/llm.py +166 -0
- courant/ctest/run.py +74 -0
- courant/ctest/schema.py +46 -0
- courant/ctest/score.py +91 -0
- courant/ctest/splits.py +20 -0
- courant/data/__init__.py +46 -0
- courant/data/certification.json +1 -0
- courant/data/certified_codes.json +18 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.case.json +68 -0
- courant/data/demo/icoFoam_cavity__cfl_blowup.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__healthy.case.json +68 -0
- courant/data/demo/icoFoam_cavity__healthy.log.gz +0 -0
- courant/data/demo/icoFoam_cavity__transport_units.case.json +68 -0
- courant/data/demo/icoFoam_cavity__transport_units.log.gz +0 -0
- courant/data/demo/pitzDaily_fixed_budget.tar.gz +0 -0
- courant/data/schemas/audit.1.json +129 -0
- courant/data/schemas/cache.1.json +77 -0
- courant/data/schemas/convergence.1.json +112 -0
- courant/data/schemas/error-rates.1.json +53 -0
- courant/data/schemas/preflight.1.json +250 -0
- courant/data/schemas/record.1.json +155 -0
- courant/data/schemas/release-signature.1.json +39 -0
- courant/data/schemas/spec.1.json +258 -0
- courant/data/schemas/support.1.json +80 -0
- courant/data/schemas/verdict.1.json +716 -0
- courant/data/schemas/verdict.2.json +752 -0
- courant/diagnosis/__init__.py +0 -0
- courant/diagnosis/bundle.py +168 -0
- courant/diagnosis/checkers.py +919 -0
- courant/diagnosis/deterministic.py +110 -0
- courant/diagnosis/findings.py +107 -0
- courant/diagnosis/kb.py +188 -0
- courant/diagnosis/kb_data.py +253 -0
- courant/diagnosis/llm.py +299 -0
- courant/diagnosis/redact.py +425 -0
- courant/diagnosis/schema.py +83 -0
- courant/events/__init__.py +35 -0
- courant/events/core.py +194 -0
- courant/events/diverged.py +55 -0
- courant/gate/__init__.py +1 -0
- courant/gate/config.py +150 -0
- courant/gate/run.py +295 -0
- courant/live/__init__.py +16 -0
- courant/live/engine.py +155 -0
- courant/live/watch.py +164 -0
- courant/llm/__init__.py +59 -0
- courant/llm/allowlist.py +60 -0
- courant/llm/anthropic.py +137 -0
- courant/llm/budget.py +491 -0
- courant/llm/door.py +1071 -0
- courant/llm/errors.py +105 -0
- courant/llm/openrouter.py +118 -0
- courant/llm/policy.py +268 -0
- courant/llm/transport.py +48 -0
- courant/mcp/__init__.py +7 -0
- courant/mcp/server.py +113 -0
- courant/mcp/tools.py +177 -0
- courant/record/__init__.py +22 -0
- courant/record/filter.py +99 -0
- courant/record/record.py +149 -0
- courant/release.py +205 -0
- courant/signing.py +99 -0
- courant/spec/__init__.py +31 -0
- courant/spec/check.py +353 -0
- courant/spec/deck.py +455 -0
- courant/spec/extract.py +181 -0
- courant/spec/impossible.py +197 -0
- courant/spec/model.py +194 -0
- courant/taxonomy.py +219 -0
- courant/verification/__init__.py +30 -0
- courant/verification/_fluid_reader.py +228 -0
- courant/verification/bounding.py +84 -0
- courant/verification/checks.py +369 -0
- courant/verification/convergence.py +257 -0
- courant/verification/fields.py +38 -0
- courant/verification/grade.py +101 -0
- courant/verification/suite.py +30 -0
- courant/verify/__init__.py +37 -0
- courant/verify/about.py +100 -0
- courant/verify/audit.py +209 -0
- courant/verify/batch.py +141 -0
- courant/verify/cache.py +329 -0
- courant/verify/checks.py +37 -0
- courant/verify/html.py +330 -0
- courant/verify/ingest.py +115 -0
- courant/verify/junit.py +48 -0
- courant/verify/outcome.py +74 -0
- courant/verify/pack.py +106 -0
- courant/verify/pipeline.py +396 -0
- courant/verify/policy.py +167 -0
- courant/verify/preflight.py +166 -0
- courant/verify/render.py +174 -0
- courant/verify/schema.py +398 -0
- courant/verify/sentences.py +137 -0
- courant/verify/support.py +142 -0
- courant/verify/verdict2.py +235 -0
- courant/watcher/__init__.py +13 -0
- courant/watcher/anomaly.py +244 -0
- courant/watcher/exitcode.py +23 -0
- courant/watcher/parser.py +435 -0
- courant/watcher/watcher.py +49 -0
- courant_dev-0.5.0.dist-info/METADATA +146 -0
- courant_dev-0.5.0.dist-info/RECORD +152 -0
- courant_dev-0.5.0.dist-info/WHEEL +5 -0
- courant_dev-0.5.0.dist-info/entry_points.txt +3 -0
- courant_dev-0.5.0.dist-info/licenses/LICENSE +202 -0
- courant_dev-0.5.0.dist-info/licenses/NOTICE +4 -0
- courant_dev-0.5.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
"""One definition of "this solve converged", shared by everything that asks.
|
|
2
|
+
|
|
3
|
+
There were two, and they disagreed. The verification suite asked whether the
|
|
4
|
+
residuals actually came down. The fix loop asked whether the solver *exited
|
|
5
|
+
cleanly* — `RunStatus.COMPLETED`, which means only "no NaN event, no crash,
|
|
6
|
+
exit code 0".
|
|
7
|
+
|
|
8
|
+
Those are not the same question, and a real OpenFOAM run showed exactly how far
|
|
9
|
+
apart they are. A lid-driven cavity with `deltaT` 100× too large was given the
|
|
10
|
+
wrong fix (a scheme change instead of a timestep reduction). On the re-run the
|
|
11
|
+
Courant number climbed to 4.6e+30 and the cumulative continuity error reached
|
|
12
|
+
-3.0e+14 — the solution was physically meaningless. But icoFoam's linear solver
|
|
13
|
+
still converged *within each timestep*, so no residual was ever NaN, the run
|
|
14
|
+
reached `endTime`, and it exited 0. `COMPLETED` ⇒ "converged" ⇒ the fix loop
|
|
15
|
+
reported **success**.
|
|
16
|
+
|
|
17
|
+
Verification caught it and graded the run C. The fix loop had already declared
|
|
18
|
+
victory. In autopilot that is the worst failure this product can have: it
|
|
19
|
+
applies a wrong fix, watches the solution turn to garbage, and tells the
|
|
20
|
+
engineer it is fixed.
|
|
21
|
+
|
|
22
|
+
So "converged" lives here, once, and both callers use it. The thresholds are
|
|
23
|
+
the verification suite's own — importing them rather than restating them is the
|
|
24
|
+
point, because two copies of a number are two numbers.
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
from __future__ import annotations
|
|
28
|
+
|
|
29
|
+
import math
|
|
30
|
+
|
|
31
|
+
from courant.events import Event, EventKind
|
|
32
|
+
from courant.events.diverged import diverged, is_residual_climb
|
|
33
|
+
|
|
34
|
+
#: Worst final initial-residual accepted. `TARGET` is clean convergence;
|
|
35
|
+
#: `LOOSE` is "converged enough to be worth a human's attention", and is the bar
|
|
36
|
+
#: a fix has to clear. Both are the verification suite's thresholds.
|
|
37
|
+
RESIDUAL_TARGET = 1e-3
|
|
38
|
+
RESIDUAL_LOOSE = 1e-2
|
|
39
|
+
|
|
40
|
+
#: A Courant number above this is not a marginal stability question, it is a
|
|
41
|
+
#: solution that has stopped meaning anything. Deliberately far above legitimate
|
|
42
|
+
#: practice — implicit transient solvers happily run at Co of 5–50 — so this
|
|
43
|
+
#: never argues with a working setup. The real diverged run reached 1.8e+31.
|
|
44
|
+
COURANT_ABSURD = 1.0e4
|
|
45
|
+
|
|
46
|
+
#: The explicit stability limit, and the bar a **fixed-timestep transient** run
|
|
47
|
+
#: has to clear once it has settled.
|
|
48
|
+
#:
|
|
49
|
+
#: Measured over every transient run in the certification corpus, and the
|
|
50
|
+
#: separation is not close. Sustained Courant over the final fifth of the run:
|
|
51
|
+
#:
|
|
52
|
+
#: healthy icoFoam/cavity 0.85, pisoFoam/cavity 0.24,
|
|
53
|
+
#: planarContraction 0.18, rhoPimpleFoam/cavity 0.54,
|
|
54
|
+
#: buoyantPimpleFoam/hotRoom 0.68
|
|
55
|
+
#: faulted pisoFoam 2.33, planarContraction 1.76, rhoPimpleFoam 3.73,
|
|
56
|
+
#: icoFoam 8.92, hotRoom 1868
|
|
57
|
+
#:
|
|
58
|
+
#: Every healthy fixed-dt run is under 1; every broken one is over it. That is
|
|
59
|
+
#: not a fitted threshold, it is the textbook criterion the cases themselves
|
|
60
|
+
#: respect.
|
|
61
|
+
COURANT_STABILITY = 1.0
|
|
62
|
+
|
|
63
|
+
#: How far above its *own* declared `maxCo` an adaptive run may sit.
|
|
64
|
+
#:
|
|
65
|
+
#: A case with `adjustTimeStep yes` states its own stability criterion, and the
|
|
66
|
+
#: solver lands a little over it because it cannot subdivide a step exactly.
|
|
67
|
+
#: `interFoam/damBreak` declares maxCo 1 and settles at 1.083 — that is the
|
|
68
|
+
#: timestep controller working, not a violation, and comparing it to a fixed
|
|
69
|
+
#: constant would call a healthy tutorial broken.
|
|
70
|
+
COURANT_ADAPTIVE_SLACK = 1.35
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def courant_limit(config) -> tuple[float, str]:
|
|
75
|
+
"""The Courant number this run must settle under, and why (TRD VER-13). One definition.
|
|
76
|
+
|
|
77
|
+
A fixed-timestep run is held to the textbook `COURANT_STABILITY`. A run that controls its
|
|
78
|
+
own step (`adjustTimeStep yes` with a declared `maxCo`) is held to the criterion its author
|
|
79
|
+
declared, with the controller's slack. `solve_converged` and `CourantChecker` both ask
|
|
80
|
+
here, so the convergence verdict and the `cfl.*` findings cannot disagree about it. Before
|
|
81
|
+
this function they did. The checker held damBreak to 1.0 while the convergence verdict held
|
|
82
|
+
it to its maxCo, and an unmodified tutorial was a false alarm (RRD RM-01 v0 to v3).
|
|
83
|
+
|
|
84
|
+
A declared maxCo may tighten the limit. It may raise it past `COURANT_STABILITY` only when
|
|
85
|
+
PIMPLE iterates outer correctors (`nOuterCorrectors` > 1), which is what lets a transient
|
|
86
|
+
solve sit above Courant 1. With OpenFOAM's default of 1 the loop is PISO, and a maxCo of 10
|
|
87
|
+
is the setup error itself, not the run's criterion: `interFoam_damBreak::max_co_too_high`
|
|
88
|
+
settled at 1.48 and was held to 13.5, so it passed with no finding (certification, 0.5.0).
|
|
89
|
+
"""
|
|
90
|
+
adaptive = bool(getattr(config, "adjust_timestep", False)) if config is not None else False
|
|
91
|
+
declared = getattr(config, "max_co", None) if adaptive else None
|
|
92
|
+
if declared:
|
|
93
|
+
outer = getattr(config, "n_outer_correctors", None) or 1
|
|
94
|
+
if declared > COURANT_STABILITY and outer <= 1:
|
|
95
|
+
why = (f"the stability limit of {COURANT_STABILITY:g} (its maxCo of {declared:g} "
|
|
96
|
+
f"is above it, and nOuterCorrectors {outer} has no outer iteration to "
|
|
97
|
+
f"allow that)")
|
|
98
|
+
return COURANT_STABILITY * COURANT_ADAPTIVE_SLACK, why
|
|
99
|
+
return declared * COURANT_ADAPTIVE_SLACK, f"its own maxCo of {declared:g}"
|
|
100
|
+
return COURANT_STABILITY, f"the stability limit of {COURANT_STABILITY:g}"
|
|
101
|
+
|
|
102
|
+
#: Volume-fraction fields. Their initial residual measures how far the
|
|
103
|
+
#: *interface moved* since the previous step, not how far the solution is from
|
|
104
|
+
#: satisfying its equations — and on a transient free-surface run the interface
|
|
105
|
+
#: never stops moving, which is the entire point of the simulation.
|
|
106
|
+
#:
|
|
107
|
+
#: Including them makes the convergence verdict permanently negative on healthy
|
|
108
|
+
#: multiphase work. Measured on an unmodified `interFoam/damBreak`: `p_rgh`
|
|
109
|
+
#: settles to 5.3e-04 while `alpha.water` sits at 1.08e-02, so the run was
|
|
110
|
+
#: judged not-converged on the one field that was never going to settle. Every
|
|
111
|
+
#: customer running VOF would have been told their correct run had failed.
|
|
112
|
+
#:
|
|
113
|
+
#: Safe to exclude, and for a physical reason rather than a convenient one:
|
|
114
|
+
#: MULES bounds alpha in [0, 1] every step, so it cannot run away unnoticed. The
|
|
115
|
+
#: same fact justifies excluding it from the divergence-slope fit in
|
|
116
|
+
#: `courant/watcher/anomaly.py`.
|
|
117
|
+
#:
|
|
118
|
+
#: Reachable only since the parser learned to read dotted field names — before
|
|
119
|
+
#: that `alpha.water` was invisible and the question never arose.
|
|
120
|
+
def _is_phase_fraction(field: str) -> bool:
|
|
121
|
+
lowered = field.lower()
|
|
122
|
+
return lowered.startswith("alpha.") or lowered == "alphas"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _finite_values(mapping: dict[str, float | None]) -> list[float]:
|
|
126
|
+
return [v for name, v in mapping.items()
|
|
127
|
+
if v is not None and not math.isnan(v) and not math.isinf(v)
|
|
128
|
+
and not _is_phase_fraction(name)]
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def worst_final_residual(events: list[Event]) -> float | None:
|
|
132
|
+
"""The largest initial residual of the last step that reported any.
|
|
133
|
+
|
|
134
|
+
"Initial residual" rather than final: the initial residual of a step is how
|
|
135
|
+
far the *solution* was from satisfying the equations before that step's
|
|
136
|
+
linear solve. A final residual near zero only says the linear solver did its
|
|
137
|
+
job, which it does right up to the point the physics is nonsense — as the
|
|
138
|
+
run described in the module docstring demonstrates.
|
|
139
|
+
"""
|
|
140
|
+
for event in reversed(events):
|
|
141
|
+
if event.kind is not EventKind.RESIDUAL:
|
|
142
|
+
continue
|
|
143
|
+
values = _finite_values(event.payload.initial_residuals or {})
|
|
144
|
+
if values:
|
|
145
|
+
return max(values)
|
|
146
|
+
return None
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def peak_courant(events: list[Event]) -> float | None:
|
|
150
|
+
peak = None
|
|
151
|
+
for event in events:
|
|
152
|
+
if event.kind is not EventKind.RESIDUAL:
|
|
153
|
+
continue
|
|
154
|
+
value = event.payload.courant_max
|
|
155
|
+
if value is None or math.isnan(value):
|
|
156
|
+
continue
|
|
157
|
+
peak = value if peak is None else max(peak, value)
|
|
158
|
+
return peak
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def sustained_courant(events: list[Event], fraction: float = 0.2) -> float | None:
|
|
162
|
+
"""The worst Courant number over the final `fraction` of the run.
|
|
163
|
+
|
|
164
|
+
The peak is the wrong statistic for this question and the codebase has
|
|
165
|
+
learned that twice. `buoyantPimpleFoam/hotRoom` — a correct tutorial —
|
|
166
|
+
spikes to 25.7 on its second step as a 600 K floor patch relaxes into a
|
|
167
|
+
300 K room, then decays and sits at 0.68 for the remaining 990 steps.
|
|
168
|
+
Judged on the peak it is broken; judged on where it settled it is fine,
|
|
169
|
+
which is also what a real blow-up fails.
|
|
170
|
+
"""
|
|
171
|
+
values = [e.payload.courant_max for e in events
|
|
172
|
+
if e.kind is EventKind.RESIDUAL
|
|
173
|
+
and e.payload.courant_max is not None
|
|
174
|
+
and not math.isnan(e.payload.courant_max)]
|
|
175
|
+
if not values:
|
|
176
|
+
return None
|
|
177
|
+
return max(values[-max(1, int(len(values) * fraction)):])
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
def solve_converged(events: list[Event], *,
|
|
181
|
+
tolerance: float = RESIDUAL_LOOSE,
|
|
182
|
+
config=None) -> tuple[bool, str]:
|
|
183
|
+
"""Whether these events describe a converged solve, and why not if not.
|
|
184
|
+
|
|
185
|
+
Returns ``(converged, reason)``. The reason is recorded on the fix attempt,
|
|
186
|
+
so it has to name a number the engineer can check against the log rather
|
|
187
|
+
than say "did not converge".
|
|
188
|
+
|
|
189
|
+
Deliberately does not look at the exit code. A clean exit is necessary and
|
|
190
|
+
nowhere near sufficient — that conflation is the bug this module exists to
|
|
191
|
+
remove. Callers check status separately and both must hold.
|
|
192
|
+
|
|
193
|
+
**A TRANSIENT RUN IS NOT JUDGED BY A STEADY-STATE BAR.** Without `config`
|
|
194
|
+
this applies the residual threshold to everything, and that is wrong in both
|
|
195
|
+
directions on a time-marching solve:
|
|
196
|
+
|
|
197
|
+
* It failed correct repairs. On `pisoFoam/RAS/cavity` a CFL fix brought the
|
|
198
|
+
Courant number to 0.8 — a stable timestep — but landed 3.4x coarser than
|
|
199
|
+
the tutorial's own, and a transient run's final initial-residual is a
|
|
200
|
+
function of its timestep, so it finished at 2.22e-02 against a 1e-02 bar
|
|
201
|
+
and was reported as "not fixed".
|
|
202
|
+
* It passed genuinely broken ones. `interFoam/damBreak` with adaptivity
|
|
203
|
+
switched off ran at a sustained Courant of **6.05** and a final residual
|
|
204
|
+
of 1.34e-03 — comfortably inside the bar, and physically wrong. The
|
|
205
|
+
harness recorded it as a fault too weak to break the case.
|
|
206
|
+
|
|
207
|
+
So for a transient solve the question is stability, which is what a
|
|
208
|
+
time-marching scheme actually has to satisfy: did anything go non-finite,
|
|
209
|
+
and did the Courant number settle inside the limit that applies to this
|
|
210
|
+
case. `COURANT_STABILITY` for a fixed timestep; the case's own `maxCo` when
|
|
211
|
+
it is controlling the step itself, because that is the criterion its author
|
|
212
|
+
declared.
|
|
213
|
+
|
|
214
|
+
The steady branch is unchanged. A steady solve has no timestep and its
|
|
215
|
+
residual really is the convergence measure.
|
|
216
|
+
"""
|
|
217
|
+
if diverged(events):
|
|
218
|
+
return False, "residuals went NaN or infinite"
|
|
219
|
+
climbs = [e for e in events if is_residual_climb(e)]
|
|
220
|
+
if climbs:
|
|
221
|
+
# A soft divergence is a residual *trend* from the anomaly detector, not a non-finite
|
|
222
|
+
# value, so the run did not diverge (ADP-5); it is still not a converged solve. Saying
|
|
223
|
+
# "NaN" for it sent RRD RM-18 looking for a NaN that was not in the log.
|
|
224
|
+
p = climbs[0].payload
|
|
225
|
+
slope = f", slope {p.slope:.3g} decades/step" if p.slope is not None else ""
|
|
226
|
+
return False, (f"residual of {p.field or 'a field'} climbing (soft divergence at "
|
|
227
|
+
f"{p.residual:.3g}{slope})" if p.residual is not None
|
|
228
|
+
else f"residual of {p.field or 'a field'} climbing (soft divergence{slope})")
|
|
229
|
+
|
|
230
|
+
peak = peak_courant(events)
|
|
231
|
+
if peak is not None and peak > COURANT_ABSURD:
|
|
232
|
+
return False, (f"Courant number reached {peak:.2e} — above {COURANT_ABSURD:.0e} "
|
|
233
|
+
f"the solution is not physical, whatever the residuals say")
|
|
234
|
+
|
|
235
|
+
worst = worst_final_residual(events)
|
|
236
|
+
if worst is None:
|
|
237
|
+
return False, "the run reported no residuals"
|
|
238
|
+
|
|
239
|
+
steady = config is not None and config.is_steady()
|
|
240
|
+
if config is not None and not steady:
|
|
241
|
+
settled = sustained_courant(events)
|
|
242
|
+
if settled is not None:
|
|
243
|
+
limit, how = courant_limit(config)
|
|
244
|
+
if settled > limit:
|
|
245
|
+
return False, (f"Courant number settled at {settled:.3g}, above "
|
|
246
|
+
f"{how} — a transient solve that does not respect "
|
|
247
|
+
f"its timestep criterion is not converged, "
|
|
248
|
+
f"whatever the residuals say")
|
|
249
|
+
return True, (f"stable: Courant settled at {settled:.3g}"
|
|
250
|
+
if settled is not None else
|
|
251
|
+
f"stable: final worst residual {worst:.2e}")
|
|
252
|
+
|
|
253
|
+
if worst > tolerance:
|
|
254
|
+
return False, (f"final worst residual {worst:.2e} is above the "
|
|
255
|
+
f"{tolerance:.0e} convergence tolerance")
|
|
256
|
+
|
|
257
|
+
return True, f"final worst residual {worst:.2e}"
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""FieldData — a structured view of a run's solution fields (Tech Arch §7, §2.2).
|
|
2
|
+
|
|
3
|
+
The field-based verification checks (conservation, y+, regime, plausibility)
|
|
4
|
+
operate on this. It is populated live from a solved case (foamlib); offline
|
|
5
|
+
it is ``None`` and the field-based checks skip. Kept deliberately small — only the
|
|
6
|
+
quantities the verification suite needs.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@dataclass
|
|
17
|
+
class FieldData:
|
|
18
|
+
time: float
|
|
19
|
+
internal: dict[str, np.ndarray] = field(default_factory=dict) # field -> values
|
|
20
|
+
patch_fluxes: dict[str, float] = field(default_factory=dict) # patch -> signed phi
|
|
21
|
+
yplus: np.ndarray | None = None # per wall-face y+
|
|
22
|
+
length_scale: float | None = None # characteristic L
|
|
23
|
+
nu: float | None = None # kinematic viscosity
|
|
24
|
+
inlet_speed: float | None = None # reference |U|
|
|
25
|
+
|
|
26
|
+
def velocity_magnitude(self) -> np.ndarray | None:
|
|
27
|
+
u = self.internal.get("U")
|
|
28
|
+
if u is None:
|
|
29
|
+
return None
|
|
30
|
+
u = np.asarray(u)
|
|
31
|
+
return np.linalg.norm(u, axis=1) if u.ndim == 2 else np.abs(u)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_case(cls, case_dir: str, time: str | None = None) -> "FieldData": # pragma: no cover
|
|
35
|
+
"""Read solution fields from a solved case (live path)."""
|
|
36
|
+
from courant.verification._fluid_reader import read_fields
|
|
37
|
+
|
|
38
|
+
return read_fields(case_dir, time)
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"""Verification results + Trust Grade (Tech Arch §7, §7.1).
|
|
2
|
+
|
|
3
|
+
The verification suite is entirely deterministic code over the run's solution +
|
|
4
|
+
history. It produces an A-D Trust Grade where every deduction links to evidence.
|
|
5
|
+
The grade is computed by code alone — the LLM may explain it, never change it.
|
|
6
|
+
|
|
7
|
+
Grade rule: start at A; each check can only lower the grade.
|
|
8
|
+
CRITICAL -> D (fails physics)
|
|
9
|
+
MAJOR -> C (major concern)
|
|
10
|
+
MINOR -> B (minor notes)
|
|
11
|
+
OK -> no change
|
|
12
|
+
The final grade is the worst any single check forced.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from enum import Enum
|
|
18
|
+
|
|
19
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class VSeverity(str, Enum):
|
|
23
|
+
OK = "ok"
|
|
24
|
+
MINOR = "minor"
|
|
25
|
+
MAJOR = "major"
|
|
26
|
+
CRITICAL = "critical"
|
|
27
|
+
|
|
28
|
+
@property
|
|
29
|
+
def rank(self) -> int:
|
|
30
|
+
return {"ok": 0, "minor": 1, "major": 2, "critical": 3}[self.value]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class TrustGrade(str, Enum):
|
|
34
|
+
A = "A" # all pass
|
|
35
|
+
B = "B" # minor notes
|
|
36
|
+
C = "C" # major concern
|
|
37
|
+
D = "D" # fails physics
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def quality(self) -> int:
|
|
41
|
+
return {"A": 3, "B": 2, "C": 1, "D": 0}[self.value]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
# worst grade a check of a given severity permits
|
|
45
|
+
_SEVERITY_CAP = {
|
|
46
|
+
VSeverity.OK: TrustGrade.A,
|
|
47
|
+
VSeverity.MINOR: TrustGrade.B,
|
|
48
|
+
VSeverity.MAJOR: TrustGrade.C,
|
|
49
|
+
VSeverity.CRITICAL: TrustGrade.D,
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
class VerificationResult(BaseModel):
|
|
54
|
+
"""One deterministic physics check over the run."""
|
|
55
|
+
|
|
56
|
+
model_config = ConfigDict(frozen=True)
|
|
57
|
+
|
|
58
|
+
check_code: str # e.g. "conservation.mass"
|
|
59
|
+
check_name: str
|
|
60
|
+
severity: VSeverity
|
|
61
|
+
passed: bool
|
|
62
|
+
value: float | None = None
|
|
63
|
+
threshold: float | None = None
|
|
64
|
+
detail: str = "" # terse, evidence-bearing
|
|
65
|
+
evidence: dict = Field(default_factory=dict)
|
|
66
|
+
skipped: bool = False # e.g. needs solution fields not available
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def compute_grade(results: list[VerificationResult]) -> TrustGrade:
|
|
70
|
+
grade = TrustGrade.A
|
|
71
|
+
for r in results:
|
|
72
|
+
if r.skipped:
|
|
73
|
+
continue
|
|
74
|
+
cap = _SEVERITY_CAP[r.severity]
|
|
75
|
+
if cap.quality < grade.quality:
|
|
76
|
+
grade = cap
|
|
77
|
+
return grade
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class TrustReport(BaseModel):
|
|
81
|
+
"""The Trust Grade plus every check that produced it."""
|
|
82
|
+
|
|
83
|
+
model_config = ConfigDict(frozen=True)
|
|
84
|
+
|
|
85
|
+
run_id: str
|
|
86
|
+
grade: TrustGrade
|
|
87
|
+
results: list[VerificationResult]
|
|
88
|
+
|
|
89
|
+
@property
|
|
90
|
+
def deductions(self) -> list[VerificationResult]:
|
|
91
|
+
return [r for r in self.results
|
|
92
|
+
if not r.skipped and r.severity is not VSeverity.OK]
|
|
93
|
+
|
|
94
|
+
@property
|
|
95
|
+
def skipped(self) -> list[VerificationResult]:
|
|
96
|
+
return [r for r in self.results if r.skipped]
|
|
97
|
+
|
|
98
|
+
@classmethod
|
|
99
|
+
def from_results(cls, run_id: str,
|
|
100
|
+
results: list[VerificationResult]) -> "TrustReport":
|
|
101
|
+
return cls(run_id=run_id, grade=compute_grade(results), results=results)
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""The verification suite — run every check, compute the Trust Grade (Tech Arch §7)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Protocol
|
|
6
|
+
|
|
7
|
+
from courant.case.config import CaseConfig
|
|
8
|
+
from courant.verification.checks import VerifyContext, run_checks
|
|
9
|
+
from courant.verification.fields import FieldData
|
|
10
|
+
from courant.verification.grade import TrustReport
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class CompletedRun(Protocol):
|
|
14
|
+
"""What `verify_run` reads of a completed run: its id and its events (a sandbox
|
|
15
|
+
`RunResult` is one; the gate does not depend on the sandbox that produces it)."""
|
|
16
|
+
|
|
17
|
+
run_id: str
|
|
18
|
+
events: list
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def verify(ctx: VerifyContext) -> TrustReport:
|
|
22
|
+
return TrustReport.from_results(ctx.run_id, run_checks(ctx))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def verify_run(result: CompletedRun, config: CaseConfig | None = None,
|
|
26
|
+
fields: FieldData | None = None) -> TrustReport:
|
|
27
|
+
"""Grade a completed run from its events (+ optional config/solution fields)."""
|
|
28
|
+
ctx = VerifyContext(run_id=result.run_id, events=result.events,
|
|
29
|
+
config=config, fields=fields)
|
|
30
|
+
return verify(ctx)
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"""Courant Verify: a verdict on a completed simulation, with its evidence.
|
|
2
|
+
|
|
3
|
+
from courant.verify import verify_path
|
|
4
|
+
verdict = verify_path("./pitzDaily")
|
|
5
|
+
verdict.verdict # "accept" | "reject" | "insufficient" (courant.verdict/2)
|
|
6
|
+
verdict.basis # "validity" | "validity+conformance" | ...
|
|
7
|
+
verdict.to_v1() # the same decision as courant.verdict/1 (TRUSTWORTHY, ...)
|
|
8
|
+
|
|
9
|
+
Read-only: no case is edited, no solver is run, no socket is opened (INV-5).
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
from courant.verify.ingest import InputError, from_case_dir, from_log, from_path, with_spec
|
|
17
|
+
from courant.verify.pipeline import verify_inputs
|
|
18
|
+
from courant.verify.render import render_json, render_markdown, render_text
|
|
19
|
+
from courant.verify.schema import Reason, RunInputs, Verdict
|
|
20
|
+
from courant.verify.verdict2 import VerdictV2, load_verdict
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def verify_path(path: str | Path, case_json: str | Path | None = None, *,
|
|
24
|
+
spec: str | Path | None = None,
|
|
25
|
+
spec_locked_sha256: str | None = None) -> VerdictV2:
|
|
26
|
+
inputs = from_path(path, case_json)
|
|
27
|
+
if spec is not None:
|
|
28
|
+
inputs = with_spec(inputs, spec, spec_locked_sha256)
|
|
29
|
+
return verify_inputs(inputs)
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
__all__ = [
|
|
33
|
+
"InputError", "Reason", "RunInputs", "Verdict", "VerdictV2",
|
|
34
|
+
"from_case_dir", "from_log", "from_path", "load_verdict",
|
|
35
|
+
"render_json", "render_markdown", "render_text",
|
|
36
|
+
"verify_inputs", "verify_path", "with_spec",
|
|
37
|
+
]
|
courant/verify/about.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
"""The error rate travels with the verdict (TRD GATE-12).
|
|
2
|
+
|
|
3
|
+
`--about`, the HTML footer, the pack manifest and the Action's summary name the Courant version
|
|
4
|
+
and the rates published for it: false accepts and false alarms (RRD RM-01's definitions), the
|
|
5
|
+
abstentions apart, each with its denominator and 95% interval, and RM-21's non-accept rate where
|
|
6
|
+
it exists. Every figure is read from the packaged results (`courant/data/certification.json`,
|
|
7
|
+
a byte copy of the measured result RM-01; INV-7, CERT-3). None is typed here, and none
|
|
8
|
+
is written into the verdict, so a verdict's bytes do not change when a results file does.
|
|
9
|
+
|
|
10
|
+
A version with no measured rates says so: the packaged results name the verifier version they
|
|
11
|
+
were measured on, and a different version is not given that version's rates.
|
|
12
|
+
"""
|
|
13
|
+
|
|
14
|
+
from __future__ import annotations
|
|
15
|
+
|
|
16
|
+
SCHEMA = "courant.error-rates/1"
|
|
17
|
+
|
|
18
|
+
#: RM-21 (the non-accept rate on healthy runs, both forks) has no packaged result yet.
|
|
19
|
+
_NO_RM21 = ("not measured; RRD RM-21 is pre-registered and has no result yet, so the share of "
|
|
20
|
+
"healthy runs this gate does not accept is unknown")
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _rate(card: dict, key: str) -> dict | None:
|
|
24
|
+
r = card.get(key)
|
|
25
|
+
if not r:
|
|
26
|
+
return None
|
|
27
|
+
out = {k: r[k] for k in ("n", "of", "lo", "hi") if k in r}
|
|
28
|
+
return out if {"n", "of"} <= set(out) else None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def error_rates() -> dict:
|
|
32
|
+
"""The rates published for this build, as data (`courant.error-rates/1`)."""
|
|
33
|
+
from courant import __version__
|
|
34
|
+
from courant.data import certification
|
|
35
|
+
|
|
36
|
+
data = certification()
|
|
37
|
+
doc: dict = {"schema": SCHEMA, "courant_version": __version__, "measured": False,
|
|
38
|
+
"non_accept_rate_healthy": None, "non_accept_rate_note": _NO_RM21}
|
|
39
|
+
if data is None:
|
|
40
|
+
doc["note"] = "This build carries no certification results."
|
|
41
|
+
return doc
|
|
42
|
+
measured_on = data.get("verifier_version")
|
|
43
|
+
doc["measured_on"] = {"verifier_version": measured_on, "tag": data.get("tag"),
|
|
44
|
+
"date": data.get("date"), "corpus": data.get("corpus"),
|
|
45
|
+
"policy": data.get("policy"),
|
|
46
|
+
# what this build read: the packaged copy of RM-01's result
|
|
47
|
+
"source": "courant/data/certification.json"}
|
|
48
|
+
if measured_on != __version__:
|
|
49
|
+
doc["note"] = (f"No error rates are measured for courant {__version__}; the published "
|
|
50
|
+
f"results are for courant {measured_on}.")
|
|
51
|
+
return doc
|
|
52
|
+
card = (data.get("scorecard") or {}).get("all") or {}
|
|
53
|
+
far, frr, abstain = _rate(card, "far"), _rate(card, "frr"), _rate(card, "abstain")
|
|
54
|
+
if far is None or frr is None:
|
|
55
|
+
doc["note"] = "The packaged results do not state this build's error rates."
|
|
56
|
+
return doc
|
|
57
|
+
doc.update(measured=True, false_accepts=far, false_alarms=frr, abstentions=abstain)
|
|
58
|
+
return doc
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _pct(x: float) -> str:
|
|
62
|
+
return f"{100 * x:.0f}%"
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _ratio(r: dict) -> str:
|
|
66
|
+
s = f"{r['n']} of {r['of']}"
|
|
67
|
+
if "lo" in r and "hi" in r:
|
|
68
|
+
s += f" (95% interval {_pct(r['lo'])}–{_pct(r['hi'])})"
|
|
69
|
+
return s
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def sentences(doc: dict | None = None) -> list[str]:
|
|
73
|
+
"""The rates as plain sentences, one fact each, for `--about` and the Markdown summary."""
|
|
74
|
+
doc = doc or error_rates()
|
|
75
|
+
ver = doc["courant_version"]
|
|
76
|
+
if not doc["measured"]:
|
|
77
|
+
return [f"courant {ver}: " + doc.get("note", "no error rates are published for this version.")]
|
|
78
|
+
m = doc["measured_on"]
|
|
79
|
+
out = [f"courant {ver}, measured on {m['corpus']} ({m['date']}, policy {m['policy']}).",
|
|
80
|
+
f"Wrong results accepted: false accepts {_ratio(doc['false_accepts'])}.",
|
|
81
|
+
f"Good results rejected: false alarms {_ratio(doc['false_alarms'])}."]
|
|
82
|
+
if doc.get("abstentions"):
|
|
83
|
+
out.append(f"Abstentions, reported apart: insufficient on {_ratio(doc['abstentions'])}.")
|
|
84
|
+
out.append(f"Non-accept rate on healthy runs (RM-21): {doc['non_accept_rate_note']}.")
|
|
85
|
+
return out
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def render_text(doc: dict | None = None) -> str:
|
|
89
|
+
return "\n".join(sentences(doc)) + "\n"
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def render_markdown(doc: dict | None = None) -> str:
|
|
93
|
+
"""For a CI job summary (GATE-7): a heading and one bullet per fact."""
|
|
94
|
+
doc = doc or error_rates()
|
|
95
|
+
return "### Error rate\n\n" + "\n".join(f"- {s}" for s in sentences(doc)) + "\n"
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def footer(doc: dict | None = None) -> str:
|
|
99
|
+
"""The rates as plain text for the HTML report's footer."""
|
|
100
|
+
return "Error rate. " + " ".join(sentences(doc))
|