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,823 @@
|
|
|
1
|
+
"""One run's convergence: monitors, residuals and clock in; status, findings and data out.
|
|
2
|
+
|
|
3
|
+
TRD CONV-1, CONV-10, CONV-11. A pure function: `series.py` reads the files, and this module
|
|
4
|
+
only does arithmetic on what it is handed. A monitor that raises degrades to NOT_ASSESSABLE
|
|
5
|
+
with the exception type only (M1-E-2). One bad monitor never costs the run its assessment.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import bisect
|
|
11
|
+
import math
|
|
12
|
+
import re
|
|
13
|
+
from collections.abc import Mapping, Sequence
|
|
14
|
+
from dataclasses import dataclass, field
|
|
15
|
+
|
|
16
|
+
from courant.converge import sentences
|
|
17
|
+
from courant.converge import steady as st
|
|
18
|
+
from courant.converge import transient as tr
|
|
19
|
+
from courant.converge.exact import SCHEME, mean
|
|
20
|
+
from courant.converge.scale import Tolerance, is_coefficient, reference_scale, tolerance
|
|
21
|
+
|
|
22
|
+
PASS, WARN, FAIL, NOT_ASSESSABLE = "PASS", "WARN", "FAIL", "NOT_ASSESSABLE"
|
|
23
|
+
|
|
24
|
+
#: Monitor verdicts that make the module FAIL (M1-O-3).
|
|
25
|
+
_FAILING = frozenset({"UNSTEADY_UNDER_STEADY_SOLVER", "NOT_CONVERGED", "NOT_STATIONARY",
|
|
26
|
+
"DIVERGED", "CI_TOO_WIDE", "MONOTONE_DRIFT"})
|
|
27
|
+
_PHASE_FRACTION = re.compile(r"(^|[(:/])alpha\.")
|
|
28
|
+
NON_FINITE_FRACTION = 0.01 # E-3
|
|
29
|
+
DIVERGED_RATIO = 1.0e6 # E-4
|
|
30
|
+
EXCEED_RATIO = 1.0e3 # E-4: first index reported
|
|
31
|
+
|
|
32
|
+
#: The order findings are emitted in (M1-O-5), so the output is byte-stable.
|
|
33
|
+
ORDER = (
|
|
34
|
+
"CONV.ANSWER_UNCHANGED", "CONV.ANSWER_MOVED", "CONV.WASTE", "CONV.CORE_HOURS_NOT_COMPUTED",
|
|
35
|
+
"CONV.ALLOCATION", "CONV.ALLOCATION_NOT_COMPUTED", "CONV.REGIME_INFERRED",
|
|
36
|
+
"CONV.TRANSIENT_NO_INTENT", "CONV.STEADY_FIXED_POINT", "CONV.NOT_CONVERGED",
|
|
37
|
+
"CONV.UNSTEADY_STEADY", "CONV.ITERATION_OSCILLATION", "CONV.SMALL_OSCILLATION", "CONV.RESIDUAL_PLATEAU",
|
|
38
|
+
"CONV.RESIDUAL_FALLING", "CONV.CELIK_RESIDUAL_ORDERS", "CONV.TRANSIENT_STATIONARY",
|
|
39
|
+
"CONV.NOT_STATIONARY", "CONV.STATIONARITY_DISAGREE", "CONV.OSCILLATORY_BATCHES",
|
|
40
|
+
"CONV.CI_TOO_WIDE", "CONV.LOW_ESS", "CONV.BATCH_SKEW", "CONV.VARIANCE_DISAGREE",
|
|
41
|
+
"CONV.ZERO_MEAN_SCALE", "CONV.SIGN_CHANGE", "CONV.TRUNCATION_IN_TAIL",
|
|
42
|
+
"CONV.MONOTONE_DRIFT", "CONV.INSUFFICIENT_DATA", "CONV.CONSTANT_SERIES",
|
|
43
|
+
"CONV.NON_FINITE", "CONV.DIVERGED", "CONV.RESTART_OVERLAP", "CONV.MONITOR_UNREADABLE",
|
|
44
|
+
"CONV.RUN_KILLED", "CONV.NO_MONITORS", "CONV.MONITOR_CAP", "CONV.BUDGET_DECIMATED",
|
|
45
|
+
"CONV.NON_MONOTONE_CRITERION", "CONV.INTERNAL_ERROR",
|
|
46
|
+
)
|
|
47
|
+
_RANK = {code: i for i, code in enumerate(ORDER)}
|
|
48
|
+
|
|
49
|
+
METHOD_DRIFT = "Trailing-window OLS drift (closed form, exact window sums)"
|
|
50
|
+
METHOD_ACF = "Detrended autocorrelation, biased estimator; lag search 2..w/4"
|
|
51
|
+
METHOD_CELIK = "Celik, Ghia, Roache & Freitas (2008), J. Fluids Eng. 130(7) 078001, Preliminaries"
|
|
52
|
+
METHOD_SCALE = "Courant reference-scale ladder"
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
# ------------------------------------------------------------------ inputs
|
|
56
|
+
@dataclass(frozen=True)
|
|
57
|
+
class MonitorSeries:
|
|
58
|
+
id: str # "<object>/<file stem>:<column>"
|
|
59
|
+
column: str
|
|
60
|
+
source: str # case-relative path(s) the samples came from
|
|
61
|
+
times: Sequence[float]
|
|
62
|
+
values: Sequence[float]
|
|
63
|
+
vector: str | None = None # the parent vector, for an _x/_y/_z column
|
|
64
|
+
reader_findings: tuple = () # Findings from the reader (restarts, bad rows)
|
|
65
|
+
not_assessable: str | None = None # set by the reader when the samples are unusable
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@dataclass(frozen=True)
|
|
69
|
+
class Clock:
|
|
70
|
+
"""Per solver step, from the log: simulated time, ClockTime and ExecutionTime."""
|
|
71
|
+
times: Sequence[float] = ()
|
|
72
|
+
clock_s: Sequence[float | None] = ()
|
|
73
|
+
exec_s: Sequence[float | None] = ()
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
@dataclass(frozen=True)
|
|
77
|
+
class RunMeta:
|
|
78
|
+
regime: str | None = None # "steady" | "transient" | None
|
|
79
|
+
regime_basis: str = "unknown" # config | solver | inferred | unknown
|
|
80
|
+
regime_conflict: Mapping | None = None
|
|
81
|
+
ranks: int | None = None
|
|
82
|
+
ranks_basis: str = "unknown" # log_nprocs | serial | user | unknown
|
|
83
|
+
ended_by: str | None = None # "signal" | "crash" | None
|
|
84
|
+
last_complete_step: int | None = None
|
|
85
|
+
paths_searched: tuple[str, ...] = ()
|
|
86
|
+
monitors_ignored: tuple[str, ...] = ()
|
|
87
|
+
monitors_unselected: tuple[str, ...] = ()
|
|
88
|
+
selection: str = "all" # default_totals | user_patterns | all
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
@dataclass(frozen=True)
|
|
92
|
+
class Options:
|
|
93
|
+
tol_abs: Mapping[str, float] = field(default_factory=dict)
|
|
94
|
+
tol_rel: Mapping[str, float] = field(default_factory=dict)
|
|
95
|
+
ref_scale: Mapping[str, float] = field(default_factory=dict)
|
|
96
|
+
transient_average: bool = False
|
|
97
|
+
monitors: tuple[str, ...] = () # glob patterns over monitor ids or columns
|
|
98
|
+
max_monitors: int = 64
|
|
99
|
+
eval_budget: int = 2_000_000 # CONV-6: exact sums make an evaluation O(1); M1 sized 120,000 for blocked sums
|
|
100
|
+
cost_per_core_hour: float | None = None
|
|
101
|
+
ccf_ghz: float | None = None
|
|
102
|
+
|
|
103
|
+
def __post_init__(self) -> None:
|
|
104
|
+
both = sorted(set(self.tol_abs) & set(self.tol_rel))
|
|
105
|
+
if both:
|
|
106
|
+
raise ValueError(f"both an absolute and a relative tolerance were given for: "
|
|
107
|
+
f"{', '.join(both)} (CONV-8: two criteria are not merged)")
|
|
108
|
+
for table in (self.tol_abs, self.tol_rel, self.ref_scale):
|
|
109
|
+
bad = [k for k, v in table.items() if not (isinstance(v, (int, float)) and v > 0)]
|
|
110
|
+
if bad:
|
|
111
|
+
raise ValueError(f"tolerances and scales must be positive: {', '.join(sorted(bad))}")
|
|
112
|
+
|
|
113
|
+
def used(self) -> dict:
|
|
114
|
+
return {"tol_abs": dict(sorted(self.tol_abs.items())),
|
|
115
|
+
"tol_rel": dict(sorted(self.tol_rel.items())),
|
|
116
|
+
"ref_scale": dict(sorted(self.ref_scale.items())),
|
|
117
|
+
"transient_average": self.transient_average,
|
|
118
|
+
"monitors": list(self.monitors),
|
|
119
|
+
"max_monitors": self.max_monitors, "eval_budget": self.eval_budget,
|
|
120
|
+
"cost_per_core_hour": self.cost_per_core_hour, "ccf_ghz": self.ccf_ghz,
|
|
121
|
+
"drift_factor": st.DRIFT_FACTOR, "window_floor": st.WINDOW_FLOOR}
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
# ------------------------------------------------------------------ outputs
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class Finding:
|
|
127
|
+
code: str
|
|
128
|
+
severity: str # INFO | WARN | FAIL
|
|
129
|
+
monitor: str | None
|
|
130
|
+
method: str
|
|
131
|
+
threshold: Mapping
|
|
132
|
+
value: Mapping
|
|
133
|
+
message: str | None = None
|
|
134
|
+
|
|
135
|
+
def as_dict(self) -> dict:
|
|
136
|
+
return {"code": self.code, "severity": self.severity, "monitor": self.monitor,
|
|
137
|
+
"method": self.method, "threshold": dict(self.threshold),
|
|
138
|
+
"value": dict(self.value), "message": self.message}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@dataclass(frozen=True)
|
|
142
|
+
class Convergence:
|
|
143
|
+
status: str
|
|
144
|
+
regime: str | None
|
|
145
|
+
findings: tuple[Finding, ...]
|
|
146
|
+
data: Mapping
|
|
147
|
+
inputs: tuple = ()
|
|
148
|
+
|
|
149
|
+
def as_dict(self) -> dict:
|
|
150
|
+
return {"status": self.status, "regime": self.regime,
|
|
151
|
+
"findings": [f.as_dict() for f in self.findings],
|
|
152
|
+
"data": json_safe(self.data),
|
|
153
|
+
"inputs": [i if isinstance(i, dict) else i.model_dump() for i in self.inputs]}
|
|
154
|
+
|
|
155
|
+
@property
|
|
156
|
+
def counted(self) -> bool:
|
|
157
|
+
"""Whether this status may enter the verdict (CONV-7a, CONV-12)."""
|
|
158
|
+
return bool(self.data.get("enters_verdict"))
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def json_safe(obj):
|
|
162
|
+
"""Non-finite floats become null plus a `<key>_non_finite` sibling (M1-E-1)."""
|
|
163
|
+
if isinstance(obj, Mapping):
|
|
164
|
+
out = {}
|
|
165
|
+
for k in sorted(obj):
|
|
166
|
+
v = obj[k]
|
|
167
|
+
if isinstance(v, float) and not math.isfinite(v):
|
|
168
|
+
out[k] = None
|
|
169
|
+
out[f"{k}_non_finite"] = "nan" if math.isnan(v) else ("inf" if v > 0 else "-inf")
|
|
170
|
+
else:
|
|
171
|
+
out[k] = json_safe(v)
|
|
172
|
+
return out
|
|
173
|
+
if isinstance(obj, (list, tuple)):
|
|
174
|
+
return [None if isinstance(v, float) and not math.isfinite(v) else json_safe(v)
|
|
175
|
+
for v in obj]
|
|
176
|
+
return obj
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _fmt(x: float | None) -> str:
|
|
180
|
+
if x is None:
|
|
181
|
+
return "not available"
|
|
182
|
+
return f"{x:.6g}"
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
# ------------------------------------------------------------------ steps and clocks
|
|
186
|
+
def _steps(times: Sequence[float], clock: Clock, regime: str | None) -> tuple[list[int], str]:
|
|
187
|
+
"""The solver step of every monitor sample, and how it was decided."""
|
|
188
|
+
ct = list(clock.times)
|
|
189
|
+
if ct and times and ct[0] - 1e-9 <= times[0] and times[-1] <= ct[-1] + 1e-9 * max(1.0, abs(ct[-1])):
|
|
190
|
+
out = []
|
|
191
|
+
for t in times:
|
|
192
|
+
i = bisect.bisect_left(ct, t)
|
|
193
|
+
if i == len(ct) or (i > 0 and abs(ct[i - 1] - t) <= abs(ct[i] - t)):
|
|
194
|
+
i = i - 1
|
|
195
|
+
out.append(i + 1)
|
|
196
|
+
return out, "log_time"
|
|
197
|
+
if regime == "steady" and times and all(float(t).is_integer() for t in times):
|
|
198
|
+
return [int(t) for t in times], "time_as_iteration"
|
|
199
|
+
return list(range(1, len(times) + 1)), "sample_index"
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _clock_at(series: Sequence[float | None], step: int) -> float | None:
|
|
203
|
+
"""The clock at a 1-based step, linearly interpolated across missing entries."""
|
|
204
|
+
i = step - 1
|
|
205
|
+
if not series or i < 0 or i >= len(series):
|
|
206
|
+
return None
|
|
207
|
+
if series[i] is not None:
|
|
208
|
+
return series[i]
|
|
209
|
+
lo = next((j for j in range(i - 1, -1, -1) if series[j] is not None), None)
|
|
210
|
+
hi = next((j for j in range(i + 1, len(series)) if series[j] is not None), None)
|
|
211
|
+
if lo is None or hi is None:
|
|
212
|
+
return None
|
|
213
|
+
return series[lo] + (series[hi] - series[lo]) * (i - lo) / (hi - lo)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
# ------------------------------------------------------------------ one monitor
|
|
217
|
+
@dataclass
|
|
218
|
+
class _Mon:
|
|
219
|
+
series: MonitorSeries
|
|
220
|
+
verdict: str = NOT_ASSESSABLE
|
|
221
|
+
counts: bool = True
|
|
222
|
+
advisory_reason: str | None = None
|
|
223
|
+
row: dict = field(default_factory=dict)
|
|
224
|
+
findings: list = field(default_factory=list)
|
|
225
|
+
stop_step: int | None = None
|
|
226
|
+
stop_time: float | None = None
|
|
227
|
+
first_step: int | None = None
|
|
228
|
+
final_step: int | None = None
|
|
229
|
+
steps: list = field(default_factory=list)
|
|
230
|
+
step_basis: str = "sample_index"
|
|
231
|
+
decimated: bool = False
|
|
232
|
+
evaluations: int = 0
|
|
233
|
+
resolution: int = 1
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _clean(mon: _Mon) -> tuple[list[float], list[float]] | None:
|
|
237
|
+
"""Drop non-finite samples (E-3). None when too many or too late to assess."""
|
|
238
|
+
s = mon.series
|
|
239
|
+
bad = [i for i, v in enumerate(s.values) if not math.isfinite(v)]
|
|
240
|
+
if not bad:
|
|
241
|
+
return list(s.times), list(s.values)
|
|
242
|
+
n = len(s.values)
|
|
243
|
+
late = any(i >= n - max(1, n // 10) for i in bad)
|
|
244
|
+
severe = len(bad) > NON_FINITE_FRACTION * n or late
|
|
245
|
+
first = bad[0]
|
|
246
|
+
kind = "nan" if math.isnan(s.values[first]) else "inf"
|
|
247
|
+
mon.findings.append(Finding(
|
|
248
|
+
"CONV.NON_FINITE", FAIL if severe else WARN, s.id, "finite-value filter",
|
|
249
|
+
{"fraction": NON_FINITE_FRACTION},
|
|
250
|
+
{"series": s.id, "kind": kind, "count": len(bad), "of": n, "first_index": first,
|
|
251
|
+
"first_time": s.times[first], "in_final_tenth": late}))
|
|
252
|
+
mon.row["non_finite"] = {"count": len(bad), "of": n, "first_index": first}
|
|
253
|
+
if severe:
|
|
254
|
+
mon.verdict = NOT_ASSESSABLE
|
|
255
|
+
mon.row["not_assessable_reason"] = "NON_FINITE"
|
|
256
|
+
return None
|
|
257
|
+
keep = [i for i in range(n) if math.isfinite(s.values[i])]
|
|
258
|
+
return [s.times[i] for i in keep], [s.values[i] for i in keep]
|
|
259
|
+
|
|
260
|
+
|
|
261
|
+
def _scale_and_tol(mon: _Mon, window: Sequence[float], vector_mag: float | None,
|
|
262
|
+
options: Options):
|
|
263
|
+
s = mon.series
|
|
264
|
+
tol = tolerance(s.id, s.column, options.tol_abs, options.tol_rel)
|
|
265
|
+
user = options.ref_scale.get(s.id, options.ref_scale.get(s.column))
|
|
266
|
+
sc = reference_scale(window, user=user, vector_magnitude=vector_mag)
|
|
267
|
+
mon.row["tolerance"] = {"branch": tol.branch, "value": tol.value, "source": tol.source}
|
|
268
|
+
mon.row["scale"] = {"value": sc.value, "basis": sc.basis, "mean": sc.mean, "stdev": sc.stdev}
|
|
269
|
+
if sc.basis == "stdev":
|
|
270
|
+
mon.findings.append(Finding(
|
|
271
|
+
"CONV.ZERO_MEAN_SCALE", "INFO", s.id, METHOD_SCALE, {},
|
|
272
|
+
{"monitor": s.id, "mean": sc.mean, "stdev": sc.stdev, "scale_used": sc.value,
|
|
273
|
+
"scale_basis": sc.basis}))
|
|
274
|
+
if sc.basis == "mean" and window and min(window) < 0.0 < max(window):
|
|
275
|
+
crossings = sum_crossings(window)
|
|
276
|
+
mon.findings.append(Finding(
|
|
277
|
+
"CONV.SIGN_CHANGE", WARN, s.id, METHOD_SCALE, {},
|
|
278
|
+
{"monitor": s.id, "crossings": crossings, "window": len(window)}))
|
|
279
|
+
return tol, sc
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def sum_crossings(values: Sequence[float]) -> int:
|
|
283
|
+
return len([i for i in range(1, len(values)) if (values[i - 1] < 0.0) != (values[i] < 0.0)])
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _limit(tol: Tolerance, scale_value: float | None) -> float:
|
|
287
|
+
"""The absolute size of the tolerance: tol itself, or tol * R."""
|
|
288
|
+
if tol.branch == "absolute":
|
|
289
|
+
return tol.value
|
|
290
|
+
return tol.value * scale_value if scale_value else 0.0
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
def _delta(mon: _Mon, tol: Tolerance, scale_value: float | None, at_stop: float,
|
|
294
|
+
at_end: float) -> None:
|
|
295
|
+
s = mon.series
|
|
296
|
+
delta = abs(at_stop - at_end)
|
|
297
|
+
frac = delta / scale_value if scale_value else (0.0 if delta == 0.0 else math.inf)
|
|
298
|
+
counts = delta * 1.0e4 if is_coefficient(s.column) else None
|
|
299
|
+
ok = delta <= tol.value if tol.branch == "absolute" else frac <= tol.value
|
|
300
|
+
mon.row.update({"value_at_stop": at_stop, "value_at_end": at_end, "delta": delta,
|
|
301
|
+
"delta_fraction": frac if scale_value else None, "delta_counts": counts,
|
|
302
|
+
"delta_ok": ok})
|
|
303
|
+
if not scale_value:
|
|
304
|
+
mon.row["delta_fraction_non_finite"] = "undefined_zero_scale"
|
|
305
|
+
value = {"monitor": s.id, "value_at_stop": at_stop, "value_at_end": at_end, "delta": delta,
|
|
306
|
+
"delta_fraction": frac if scale_value else None, "delta_counts": counts}
|
|
307
|
+
if ok:
|
|
308
|
+
mon.findings.append(Finding("CONV.ANSWER_UNCHANGED", "INFO", s.id,
|
|
309
|
+
"Courant answer-unchanged delta",
|
|
310
|
+
{"tol": tol.value, "branch": tol.branch}, value))
|
|
311
|
+
else:
|
|
312
|
+
mon.verdict = "NOT_CONVERGED"
|
|
313
|
+
mon.findings.append(Finding("CONV.ANSWER_MOVED", FAIL, s.id,
|
|
314
|
+
"Courant answer-unchanged delta",
|
|
315
|
+
{"tol": tol.value, "branch": tol.branch}, value,
|
|
316
|
+
"The answer moved by more than its tolerance after the "
|
|
317
|
+
"stopping point, so it was not a stopping point."))
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def _steady(mon: _Mon, times, values, vector_mag, options: Options, budget: int) -> None:
|
|
321
|
+
s = mon.series
|
|
322
|
+
n = len(values)
|
|
323
|
+
mon.row["n"] = n
|
|
324
|
+
if n < st.WINDOW_FLOOR:
|
|
325
|
+
mon.verdict = "INSUFFICIENT_DATA"
|
|
326
|
+
mon.findings.append(Finding(
|
|
327
|
+
"CONV.INSUFFICIENT_DATA", WARN, s.id, METHOD_DRIFT, {"n_required": st.WINDOW_FLOOR},
|
|
328
|
+
{"monitor": s.id, "stage": "window", "n": n, "n_required": st.WINDOW_FLOOR},
|
|
329
|
+
sentences.INSUFFICIENT_DATA.format(
|
|
330
|
+
monitor=s.id, detail=f"It has {n} samples and the window rule needs "
|
|
331
|
+
f"{st.WINDOW_FLOOR}.")))
|
|
332
|
+
return
|
|
333
|
+
w = st.window_width(n)
|
|
334
|
+
window = values[n - w:]
|
|
335
|
+
tol, sc = _scale_and_tol(mon, window, vector_mag, options)
|
|
336
|
+
limit = _limit(tol, sc.value)
|
|
337
|
+
mon.row["window"] = w
|
|
338
|
+
if max(values) == min(values):
|
|
339
|
+
mon.findings.append(Finding("CONV.CONSTANT_SERIES", "INFO", s.id, "constant series",
|
|
340
|
+
{}, {"monitor": s.id, "value": values[0], "n": n}))
|
|
341
|
+
_converged(mon, w - 1, values, tol, sc.value)
|
|
342
|
+
return
|
|
343
|
+
drift = st.Drift(values, w)
|
|
344
|
+
last_drift = drift.drift(n - 1)
|
|
345
|
+
mon.row["drift_last"] = last_drift
|
|
346
|
+
mon.row["drift_last_rel"] = last_drift / sc.value if sc.value else None
|
|
347
|
+
tau = st.DRIFT_FACTOR * limit
|
|
348
|
+
osc = st.oscillation(st.detrend(window, drift.slope(n - 1)), limit)
|
|
349
|
+
mon.row["oscillation"] = {"tested": osc.tested, "lag": osc.lag, "acf": osc.acf,
|
|
350
|
+
"amplitude": osc.amplitude, "n_periods": osc.n_periods,
|
|
351
|
+
"fires": osc.fires, "reason": osc.reason}
|
|
352
|
+
smooth = 1
|
|
353
|
+
if osc.tested and osc.lag is not None and osc.lag <= st.ITERATION_LAG_MAX:
|
|
354
|
+
# CONV-6c: a period of two or three iterations is the steady iteration alternating,
|
|
355
|
+
# not a flow that is unsteady. It is judged by half its amplitude, the distance from
|
|
356
|
+
# the cycle mean to any sample, and values are read as means over one period.
|
|
357
|
+
tail = window[w - osc.n_periods * osc.lag:]
|
|
358
|
+
cycle_mean = mean(tail)
|
|
359
|
+
half = osc.amplitude / 2.0
|
|
360
|
+
rel = osc.amplitude / sc.value if sc.value else None
|
|
361
|
+
value = {"monitor": s.id, "lag": osc.lag, "acf": osc.acf, "amplitude": osc.amplitude,
|
|
362
|
+
"amplitude_rel": rel, "half_amplitude": half, "cycle_mean": cycle_mean}
|
|
363
|
+
if half > limit:
|
|
364
|
+
mon.verdict = "NOT_CONVERGED"
|
|
365
|
+
mon.findings.append(Finding(
|
|
366
|
+
"CONV.ITERATION_OSCILLATION", FAIL, s.id, METHOD_ACF,
|
|
367
|
+
{"acf": st.ACF_THRESHOLD, "half_amplitude": limit}, value,
|
|
368
|
+
sentences.ITERATION_OSCILLATION.format(
|
|
369
|
+
monitor=s.id, lag=osc.lag, amplitude=_fmt(osc.amplitude),
|
|
370
|
+
cycle_mean=_fmt(cycle_mean), half=_fmt(half), tol=_fmt(limit))))
|
|
371
|
+
return
|
|
372
|
+
mon.findings.append(Finding("CONV.ITERATION_OSCILLATION", "INFO", s.id, METHOD_ACF,
|
|
373
|
+
{"acf": st.ACF_THRESHOLD, "half_amplitude": limit}, value))
|
|
374
|
+
smooth = osc.lag
|
|
375
|
+
elif osc.fires:
|
|
376
|
+
tail = window[w - osc.n_periods * osc.lag:]
|
|
377
|
+
cycle_mean = mean(tail)
|
|
378
|
+
rel = osc.amplitude / sc.value if sc.value else None
|
|
379
|
+
mon.verdict = "UNSTEADY_UNDER_STEADY_SOLVER"
|
|
380
|
+
mon.findings.append(Finding(
|
|
381
|
+
"CONV.UNSTEADY_STEADY", FAIL, s.id, METHOD_ACF,
|
|
382
|
+
{"acf": st.ACF_THRESHOLD, "amplitude": limit},
|
|
383
|
+
{"monitor": s.id, "lag": osc.lag, "acf": osc.acf, "amplitude": osc.amplitude,
|
|
384
|
+
"amplitude_rel": rel, "period_samples": osc.lag, "n_periods_in_window": osc.n_periods,
|
|
385
|
+
"cycle_mean": cycle_mean},
|
|
386
|
+
sentences.NO_STOPPING_POINT_UNSTEADY.format(
|
|
387
|
+
period_steps=osc.lag, amplitude=_fmt(osc.amplitude), amplitude_rel=_fmt(rel),
|
|
388
|
+
n_periods=osc.n_periods, cycle_mean=_fmt(cycle_mean))))
|
|
389
|
+
return
|
|
390
|
+
elif osc.tested and osc.lag is not None:
|
|
391
|
+
mon.findings.append(Finding(
|
|
392
|
+
"CONV.SMALL_OSCILLATION", "INFO", s.id, METHOD_ACF,
|
|
393
|
+
{"acf": st.ACF_THRESHOLD, "amplitude": limit},
|
|
394
|
+
{"monitor": s.id, "lag": osc.lag, "acf": osc.acf, "amplitude": osc.amplitude}))
|
|
395
|
+
search = st.stopping_index(drift, tau, budget)
|
|
396
|
+
mon.evaluations = search.evaluations
|
|
397
|
+
if search.index is None:
|
|
398
|
+
r_first = reference_scale(values[:w]).value
|
|
399
|
+
if r_first and abs(values[-1]) > DIVERGED_RATIO * r_first:
|
|
400
|
+
first_exceed = next(i for i, v in enumerate(values) if abs(v) > EXCEED_RATIO * r_first)
|
|
401
|
+
mon.verdict = "DIVERGED"
|
|
402
|
+
mon.findings.append(Finding(
|
|
403
|
+
"CONV.DIVERGED", FAIL, s.id, "growth against the first window's scale",
|
|
404
|
+
{"ratio": DIVERGED_RATIO},
|
|
405
|
+
{"monitor": s.id, "first_exceed_index": first_exceed, "final_value": values[-1],
|
|
406
|
+
"reference_scale": r_first}))
|
|
407
|
+
return
|
|
408
|
+
if sc.basis == "stdev" and s.id not in options.ref_scale and s.column not in options.ref_scale:
|
|
409
|
+
mon.verdict = NOT_ASSESSABLE
|
|
410
|
+
mon.row["not_assessable_reason"] = "ZERO_MEAN_SCALE"
|
|
411
|
+
mon.findings.append(Finding("CONV.ZERO_MEAN_SCALE", WARN, s.id, METHOD_SCALE, {},
|
|
412
|
+
{"monitor": s.id, "stdev": sc.stdev},
|
|
413
|
+
sentences.ZERO_MEAN_SCALE.format(monitor=s.id)))
|
|
414
|
+
return
|
|
415
|
+
mon.verdict = "NOT_CONVERGED"
|
|
416
|
+
rel = last_drift / sc.value if sc.value else None
|
|
417
|
+
mon.findings.append(Finding(
|
|
418
|
+
"CONV.NOT_CONVERGED", FAIL, s.id, METHOD_DRIFT,
|
|
419
|
+
{"drift": tau, "drift_factor": st.DRIFT_FACTOR, "tol": tol.value, "branch": tol.branch},
|
|
420
|
+
{"monitor": s.id, "window": w, "drift": last_drift, "drift_rel": rel,
|
|
421
|
+
"final_value": values[-1]},
|
|
422
|
+
sentences.NOT_CONVERGED.format(monitor=s.id, drift_rel=_fmt(rel), window=w,
|
|
423
|
+
tol=_fmt(st.DRIFT_FACTOR * tol.value))))
|
|
424
|
+
return
|
|
425
|
+
mon.decimated, mon.resolution = search.decimated, search.resolution
|
|
426
|
+
_converged(mon, search.index, values, tol, sc.value, smooth)
|
|
427
|
+
mon.findings.append(Finding(
|
|
428
|
+
"CONV.STEADY_FIXED_POINT", "INFO", s.id, METHOD_DRIFT,
|
|
429
|
+
{"drift": tau, "drift_factor": st.DRIFT_FACTOR, "tol": tol.value, "branch": tol.branch},
|
|
430
|
+
{"monitor": s.id, "window": w, "drift_last": last_drift,
|
|
431
|
+
"converged_at_index": search.index, "evaluations": search.evaluations,
|
|
432
|
+
"resolution": search.resolution}))
|
|
433
|
+
|
|
434
|
+
|
|
435
|
+
def _converged(mon: _Mon, index: int, values, tol: Tolerance, scale_value, smooth: int = 1) -> None:
|
|
436
|
+
mon.verdict = "CONVERGED"
|
|
437
|
+
mon.row["stop_index"] = index
|
|
438
|
+
mon.stop_step = mon.steps[index]
|
|
439
|
+
if smooth > 1: # an iteration oscillation: read one period's mean
|
|
440
|
+
at_stop = mean(values[max(0, index - smooth + 1):index + 1])
|
|
441
|
+
at_end = mean(values[len(values) - smooth:])
|
|
442
|
+
mon.row["values_read_as"] = f"mean over {smooth} samples (one period of the iteration oscillation)"
|
|
443
|
+
else:
|
|
444
|
+
at_stop, at_end = values[index], values[-1]
|
|
445
|
+
_delta(mon, tol, scale_value, at_stop, at_end)
|
|
446
|
+
i = max(range(len(values)), key=lambda k: abs(values[k] - values[-1]))
|
|
447
|
+
mon.row["max_abs_deviation_index"] = i
|
|
448
|
+
|
|
449
|
+
|
|
450
|
+
def _transient(mon: _Mon, times, values, options: Options) -> None:
|
|
451
|
+
s = mon.series
|
|
452
|
+
n = len(values)
|
|
453
|
+
mon.row["n"] = n
|
|
454
|
+
if n < st.WINDOW_FLOOR:
|
|
455
|
+
mon.verdict = "INSUFFICIENT_DATA"
|
|
456
|
+
mon.findings.append(Finding(
|
|
457
|
+
"CONV.INSUFFICIENT_DATA", WARN, s.id, tr.METHOD_MSER, {"n_required": st.WINDOW_FLOOR},
|
|
458
|
+
{"monitor": s.id, "stage": "mser", "n": n, "n_required": st.WINDOW_FLOOR},
|
|
459
|
+
sentences.INSUFFICIENT_DATA.format(
|
|
460
|
+
monitor=s.id, detail=f"It has {n} samples and MSER-5 needs {st.WINDOW_FLOOR}.")))
|
|
461
|
+
return
|
|
462
|
+
if max(values) == min(values):
|
|
463
|
+
tol, sc = _scale_and_tol(mon, values, None, options)
|
|
464
|
+
mon.findings.append(Finding("CONV.CONSTANT_SERIES", "INFO", s.id, "constant series",
|
|
465
|
+
{}, {"monitor": s.id, "value": values[0], "n": n}))
|
|
466
|
+
_converged(mon, st.WINDOW_FLOOR - 1, values, tol, sc.value)
|
|
467
|
+
return
|
|
468
|
+
full = tr.mser5(values)
|
|
469
|
+
trunc = values[full.truncate_at:tr.MSER_BATCH * full.n_batches] if not full.insufficient else values
|
|
470
|
+
tol, sc = _scale_and_tol(mon, trunc, None, options)
|
|
471
|
+
limit_abs = tol.value if tol.branch == "absolute" else None
|
|
472
|
+
|
|
473
|
+
def settled_tail(vs=values) -> bool:
|
|
474
|
+
w = st.window_width(len(vs))
|
|
475
|
+
d = st.Drift(vs, w)
|
|
476
|
+
return not st.unsettled(d.drift(len(vs) - 1), st.DRIFT_FACTOR * _limit(tol, sc.value))
|
|
477
|
+
|
|
478
|
+
res = tr.assess_prefix(values, limit_abs, tol.value, sc.value, settled_tail)
|
|
479
|
+
ms = res.mser
|
|
480
|
+
mon.row["transient"] = {"mser_d_star": ms.d_star, "mser_n_batches": ms.n_batches,
|
|
481
|
+
"mser_tail_dropped": ms.tail_dropped,
|
|
482
|
+
"mser_two_pass_recomputations": ms.recomputations,
|
|
483
|
+
"truncation_index": ms.truncate_at if not ms.insufficient else None}
|
|
484
|
+
if res.verdict in ("INSUFFICIENT_DATA", "MONOTONE_DRIFT"):
|
|
485
|
+
mon.verdict = res.verdict
|
|
486
|
+
if res.stage == "mser_tail":
|
|
487
|
+
code = "CONV.MONOTONE_DRIFT" if res.verdict == "MONOTONE_DRIFT" else "CONV.TRUNCATION_IN_TAIL"
|
|
488
|
+
mon.findings.append(Finding(
|
|
489
|
+
code, FAIL if code == "CONV.MONOTONE_DRIFT" else WARN, s.id,
|
|
490
|
+
tr.METHOD_MSER + "; tail guard: second half (Courant)", {"fraction": 0.5},
|
|
491
|
+
{"monitor": s.id, "d_star": ms.d_star, "n_batches": ms.n_batches,
|
|
492
|
+
"post_transient_samples": tr.MSER_BATCH * (ms.n_batches - (ms.d_star or 0))}))
|
|
493
|
+
else:
|
|
494
|
+
detail = ("Its batch means are still strongly correlated (lag-1 correlation at least "
|
|
495
|
+
"0.5), or fewer than 20 batches remain after the transient."
|
|
496
|
+
if res.stage == "batching" else
|
|
497
|
+
"MSER-5 needs at least 40 batch means of five samples.")
|
|
498
|
+
mon.findings.append(Finding(
|
|
499
|
+
"CONV.INSUFFICIENT_DATA", WARN, s.id, tr.METHOD_BATCH,
|
|
500
|
+
{"batches_required": tr.BATCH_MIN},
|
|
501
|
+
{"monitor": s.id, "stage": res.stage, "n": n},
|
|
502
|
+
sentences.INSUFFICIENT_DATA.format(monitor=s.id, detail=detail)))
|
|
503
|
+
return
|
|
504
|
+
bt, sty = res.batches, res.stationarity
|
|
505
|
+
mon.row["transient"].update({
|
|
506
|
+
"batch_size": bt.size, "batch_count": bt.count, "rho1": bt.rho1, "mean": bt.mean,
|
|
507
|
+
"half_width": bt.half_width, "half_width_rel": bt.half_width / sc.value if sc.value else None,
|
|
508
|
+
"ess": bt.ess, "skew": bt.skew, "se": bt.se,
|
|
509
|
+
"geweke_z": sty.geweke_z, "vn_z": sty.vn_z})
|
|
510
|
+
stat_value = {"monitor": s.id, "geweke_z": sty.geweke_z, "vn_z": sty.vn_z, "n_a": sty.n_a,
|
|
511
|
+
"n_b": sty.n_b}
|
|
512
|
+
if sty.oscillatory_batches:
|
|
513
|
+
mon.findings.append(Finding("CONV.OSCILLATORY_BATCHES", WARN, s.id, tr.METHOD_STATIONARITY,
|
|
514
|
+
{"z": tr.Z_CRIT}, {"monitor": s.id, "vn_z": sty.vn_z,
|
|
515
|
+
"batch_size": bt.size}))
|
|
516
|
+
if bt.skew is not None and abs(bt.skew) > tr.SKEW_LIMIT:
|
|
517
|
+
mon.findings.append(Finding("CONV.BATCH_SKEW", WARN, s.id, tr.METHOD_BATCH,
|
|
518
|
+
{"skew": tr.SKEW_LIMIT},
|
|
519
|
+
{"monitor": s.id, "skew": bt.skew, "k": bt.count}))
|
|
520
|
+
if res.verdict == "NOT_STATIONARY":
|
|
521
|
+
mon.verdict = "NOT_STATIONARY"
|
|
522
|
+
mon.findings.append(Finding("CONV.NOT_STATIONARY", FAIL, s.id, tr.METHOD_STATIONARITY,
|
|
523
|
+
{"z": tr.Z_CRIT}, {**stat_value, "which_failed": sty.which_failed},
|
|
524
|
+
sentences.NOT_STATIONARY.format(monitor=s.id,
|
|
525
|
+
which_failed=sty.which_failed)))
|
|
526
|
+
if (abs(sty.geweke_z) < tr.Z_CRIT) != (sty.vn_z >= -tr.Z_CRIT):
|
|
527
|
+
mon.findings.append(Finding("CONV.STATIONARITY_DISAGREE", "INFO", s.id,
|
|
528
|
+
tr.METHOD_STATIONARITY, {"z": tr.Z_CRIT},
|
|
529
|
+
{**stat_value, "which_failed": sty.which_failed}))
|
|
530
|
+
return
|
|
531
|
+
mon.findings.append(Finding("CONV.TRANSIENT_STATIONARY", "INFO", s.id, tr.METHOD_STATIONARITY,
|
|
532
|
+
{"z": tr.Z_CRIT}, stat_value))
|
|
533
|
+
yt = values[ms.truncate_at:tr.MSER_BATCH * ms.n_batches]
|
|
534
|
+
se_spec = math.sqrt(max(0.0, tr.s0_bartlett(yt)) / len(yt))
|
|
535
|
+
mon.row["transient"]["spectral_se"] = se_spec
|
|
536
|
+
if bt.se and se_spec and max(se_spec / bt.se, bt.se / se_spec) > tr.SPECTRAL_RATIO:
|
|
537
|
+
mon.findings.append(Finding("CONV.VARIANCE_DISAGREE", WARN, s.id,
|
|
538
|
+
"Batch-means vs Bartlett spectral standard error",
|
|
539
|
+
{"ratio": tr.SPECTRAL_RATIO},
|
|
540
|
+
{"monitor": s.id, "se_batch": bt.se, "se_spectral": se_spec}))
|
|
541
|
+
if bt.ess is not None and bt.ess < tr.LOW_ESS:
|
|
542
|
+
mon.findings.append(Finding("CONV.LOW_ESS", WARN, s.id, tr.METHOD_BATCH, {"ess": tr.LOW_ESS},
|
|
543
|
+
{"monitor": s.id, "ess": bt.ess, "n_truncated": bt.n,
|
|
544
|
+
"batch_size": bt.size}))
|
|
545
|
+
if res.verdict == "CI_TOO_WIDE":
|
|
546
|
+
mon.verdict = "CI_TOO_WIDE"
|
|
547
|
+
mon.findings.append(Finding(
|
|
548
|
+
"CONV.CI_TOO_WIDE", FAIL, s.id, tr.METHOD_BATCH, {"tol": tol.value, "branch": tol.branch},
|
|
549
|
+
{"monitor": s.id, "mean": bt.mean, "half_width": bt.half_width, "k": bt.count,
|
|
550
|
+
"batch_size": bt.size, "ess": bt.ess}))
|
|
551
|
+
return
|
|
552
|
+
|
|
553
|
+
def ok(prefix) -> bool:
|
|
554
|
+
return tr.assess_prefix(prefix, limit_abs, tol.value, sc.value).verdict == "CONVERGED"
|
|
555
|
+
|
|
556
|
+
search = tr.stopping_prefix(values, ok)
|
|
557
|
+
mon.evaluations = search.evaluations
|
|
558
|
+
if search.index is None:
|
|
559
|
+
mon.verdict = "NOT_CONVERGED"
|
|
560
|
+
return
|
|
561
|
+
mon.resolution = search.resolution
|
|
562
|
+
if search.non_monotone_rounds:
|
|
563
|
+
mon.findings.append(Finding("CONV.NON_MONOTONE_CRITERION", "INFO", s.id, tr.METHOD_BATCH,
|
|
564
|
+
{"rounds": tr.SEARCH_ROUNDS},
|
|
565
|
+
{"monitor": s.id, "rounds_used": search.non_monotone_rounds}))
|
|
566
|
+
prefix = tr.assess_prefix(values[:search.index + 1], limit_abs, tol.value, sc.value)
|
|
567
|
+
at_stop = prefix.batches.mean if prefix.batches and prefix.batches.mean is not None else bt.mean
|
|
568
|
+
mon.verdict = "CONVERGED"
|
|
569
|
+
mon.row["stop_index"] = search.index
|
|
570
|
+
mon.stop_step = mon.steps[search.index]
|
|
571
|
+
_delta(mon, tol, sc.value, at_stop, bt.mean)
|
|
572
|
+
|
|
573
|
+
|
|
574
|
+
# ------------------------------------------------------------------ the module
|
|
575
|
+
def assess(monitors: Sequence[MonitorSeries], residuals: Mapping[str, Sequence[float]],
|
|
576
|
+
clock: Clock, meta: RunMeta, options: Options = Options(), inputs: tuple = ()) -> Convergence:
|
|
577
|
+
findings: list[Finding] = []
|
|
578
|
+
regime = meta.regime
|
|
579
|
+
if meta.regime_basis == "inferred":
|
|
580
|
+
findings.append(Finding("CONV.REGIME_INFERRED", "INFO", None, "Courant regime inference",
|
|
581
|
+
{}, {"regime": regime, "basis": meta.regime_basis}))
|
|
582
|
+
|
|
583
|
+
ordered = sorted(monitors, key=lambda m: m.id)
|
|
584
|
+
dropped = [m.id for m in ordered[options.max_monitors:]]
|
|
585
|
+
ordered = ordered[:options.max_monitors]
|
|
586
|
+
if dropped:
|
|
587
|
+
findings.append(Finding("CONV.MONITOR_CAP", WARN, None, "monitor cap",
|
|
588
|
+
{"max_monitors": options.max_monitors},
|
|
589
|
+
{"discovered": len(monitors), "assessed": len(ordered)}))
|
|
590
|
+
|
|
591
|
+
transient_advisory = regime == "transient" and not options.transient_average
|
|
592
|
+
if transient_advisory and ordered:
|
|
593
|
+
findings.append(Finding("CONV.TRANSIENT_NO_INTENT", "INFO", None, "CONV-7a", {}, {},
|
|
594
|
+
sentences.TRANSIENT_NO_INTENT))
|
|
595
|
+
|
|
596
|
+
# vector magnitudes over each sample, for components near zero (scale.py)
|
|
597
|
+
vectors: dict[str, list[MonitorSeries]] = {}
|
|
598
|
+
for m in ordered:
|
|
599
|
+
if m.vector:
|
|
600
|
+
vectors.setdefault(m.vector, []).append(m)
|
|
601
|
+
|
|
602
|
+
def magnitude(m: MonitorSeries, w: int) -> float | None:
|
|
603
|
+
sib = vectors.get(m.vector or "", [])
|
|
604
|
+
if len(sib) < 2 or len({len(x.values) for x in sib}) != 1:
|
|
605
|
+
return None
|
|
606
|
+
n = len(sib[0].values)
|
|
607
|
+
mags = [math.sqrt(math.fsum(x.values[i] * x.values[i] for x in sib)) for i in range(n - w, n)]
|
|
608
|
+
mags = [v for v in mags if math.isfinite(v)]
|
|
609
|
+
return mean(mags) if mags else None
|
|
610
|
+
|
|
611
|
+
mons: list[_Mon] = []
|
|
612
|
+
n_assessed = len([m for m in ordered if not _PHASE_FRACTION.search(m.id)])
|
|
613
|
+
budget = max(1, options.eval_budget // max(1, n_assessed))
|
|
614
|
+
for m in ordered:
|
|
615
|
+
mon = _Mon(m)
|
|
616
|
+
mon.findings.extend(m.reader_findings)
|
|
617
|
+
mons.append(mon)
|
|
618
|
+
if _PHASE_FRACTION.search(m.id):
|
|
619
|
+
mon.verdict, mon.counts, mon.advisory_reason = "EXCLUDED", False, "PHASE_FRACTION"
|
|
620
|
+
continue
|
|
621
|
+
if m.not_assessable:
|
|
622
|
+
mon.row["not_assessable_reason"] = m.not_assessable
|
|
623
|
+
continue
|
|
624
|
+
try:
|
|
625
|
+
cleaned = _clean(mon)
|
|
626
|
+
if cleaned is None:
|
|
627
|
+
continue
|
|
628
|
+
times, values = cleaned
|
|
629
|
+
mon.steps, mon.step_basis = _steps(times, clock, regime)
|
|
630
|
+
if mon.steps:
|
|
631
|
+
mon.first_step, mon.final_step = mon.steps[0], mon.steps[-1]
|
|
632
|
+
if regime == "transient":
|
|
633
|
+
if transient_advisory:
|
|
634
|
+
mon.counts, mon.advisory_reason = False, "TRANSIENT_NO_INTENT"
|
|
635
|
+
_transient(mon, times, values, options)
|
|
636
|
+
else:
|
|
637
|
+
w = st.window_width(len(values))
|
|
638
|
+
_steady(mon, times, values, magnitude(m, min(w, len(values))), options, budget)
|
|
639
|
+
except Exception as exc: # noqa: BLE001 - M1-E-2: one monitor never costs the run
|
|
640
|
+
mon.verdict = NOT_ASSESSABLE
|
|
641
|
+
mon.row["not_assessable_reason"] = "INTERNAL_ERROR"
|
|
642
|
+
mon.findings.append(Finding("CONV.INTERNAL_ERROR", WARN, m.id, "M1-E-2", {},
|
|
643
|
+
{"monitor": m.id, "exception": type(exc).__name__}))
|
|
644
|
+
|
|
645
|
+
for mon in mons:
|
|
646
|
+
findings.extend(mon.findings)
|
|
647
|
+
|
|
648
|
+
counting = [m for m in mons if m.counts]
|
|
649
|
+
assessed = [m for m in counting if m.verdict != NOT_ASSESSABLE]
|
|
650
|
+
hard_non_finite = any(f.code == "CONV.NON_FINITE" and f.severity == FAIL
|
|
651
|
+
for m in counting for f in m.findings)
|
|
652
|
+
if not ordered:
|
|
653
|
+
findings.append(Finding("CONV.NO_MONITORS", WARN, None, "monitor discovery", {},
|
|
654
|
+
{"paths_searched": list(meta.paths_searched)},
|
|
655
|
+
sentences.NOT_ASSESSABLE_NO_MONITORS.format(
|
|
656
|
+
paths=", ".join(meta.paths_searched) or "none")))
|
|
657
|
+
if not assessed and not hard_non_finite:
|
|
658
|
+
status = NOT_ASSESSABLE
|
|
659
|
+
elif hard_non_finite or any(m.verdict in _FAILING for m in assessed) or \
|
|
660
|
+
any(m.row.get("delta_ok") is False for m in assessed):
|
|
661
|
+
status = FAIL
|
|
662
|
+
elif any(m.verdict in (NOT_ASSESSABLE, "INSUFFICIENT_DATA") for m in counting) or \
|
|
663
|
+
any(m.decimated for m in counting) or meta.ended_by:
|
|
664
|
+
status = WARN
|
|
665
|
+
else:
|
|
666
|
+
status = PASS
|
|
667
|
+
|
|
668
|
+
# the global stopping point: the last quantity to settle (M1-F-6)
|
|
669
|
+
stops = {m.series.id: m.stop_step for m in counting if m.stop_step is not None}
|
|
670
|
+
all_stopped = bool(counting) and len(stops) == len(counting)
|
|
671
|
+
# M1-F-6: the run has stopped only when its last quantity has. A monitor without a
|
|
672
|
+
# stopping point means the run has none; the per-monitor points are still reported.
|
|
673
|
+
binding = max(sorted(stops), key=lambda k: stops[k]) if stops and all_stopped else None
|
|
674
|
+
converged_at = stops[binding] if binding else None
|
|
675
|
+
resolution = max([m.resolution for m in counting if m.stop_step is not None] or [1])
|
|
676
|
+
if any(m.decimated for m in counting):
|
|
677
|
+
findings.append(Finding("CONV.BUDGET_DECIMATED", WARN, None, "evaluation budget",
|
|
678
|
+
{"eval_budget": options.eval_budget},
|
|
679
|
+
{"evaluations_used": sum_int(m.evaluations for m in mons),
|
|
680
|
+
"step_resolution": resolution},
|
|
681
|
+
sentences.DECIMATED.format(step_resolution=resolution)))
|
|
682
|
+
|
|
683
|
+
waste = None
|
|
684
|
+
if status in (PASS, WARN) and all_stopped and binding and not meta.ended_by:
|
|
685
|
+
bmon = next(m for m in counting if m.series.id == binding)
|
|
686
|
+
waste = _waste(bmon, converged_at, clock, meta, options, findings)
|
|
687
|
+
if meta.ended_by:
|
|
688
|
+
sentence = sentences.RUN_KILLED if meta.ended_by == "signal" else sentences.RUN_CRASHED
|
|
689
|
+
findings.append(Finding("CONV.RUN_KILLED", WARN, None, "events", {},
|
|
690
|
+
{"ended_by": meta.ended_by,
|
|
691
|
+
"last_complete_step": meta.last_complete_step},
|
|
692
|
+
sentence.format(last_complete_step=meta.last_complete_step)))
|
|
693
|
+
|
|
694
|
+
res_table, res_findings = _residuals(residuals, status)
|
|
695
|
+
findings.extend(res_findings)
|
|
696
|
+
|
|
697
|
+
findings.sort(key=lambda f: (_RANK.get(f.code, len(ORDER)), f.monitor or ""))
|
|
698
|
+
data = {
|
|
699
|
+
"regime": regime, "regime_basis": meta.regime_basis,
|
|
700
|
+
"regime_conflict": dict(meta.regime_conflict) if meta.regime_conflict else None,
|
|
701
|
+
"enters_verdict": status in (PASS, WARN, FAIL) and not transient_advisory and bool(assessed),
|
|
702
|
+
"converged_at_step": converged_at, "step_resolution": resolution if converged_at else None,
|
|
703
|
+
"binding_monitor": binding,
|
|
704
|
+
"converged_at_step_by_monitor": dict(sorted(stops.items())),
|
|
705
|
+
"monitors": {m.series.id: {**m.row, "verdict": m.verdict, "counts": m.counts,
|
|
706
|
+
"advisory_reason": m.advisory_reason, "source": m.series.source,
|
|
707
|
+
"first_step": m.first_step, "final_step": m.final_step,
|
|
708
|
+
"step_basis": m.step_basis, "stop_step": m.stop_step}
|
|
709
|
+
for m in mons},
|
|
710
|
+
"residuals": res_table,
|
|
711
|
+
"waste": waste,
|
|
712
|
+
"monitors_dropped": dropped,
|
|
713
|
+
"monitors_ignored": list(meta.monitors_ignored),
|
|
714
|
+
"monitors_unselected": list(meta.monitors_unselected),
|
|
715
|
+
"monitor_selection": meta.selection,
|
|
716
|
+
"paths_searched": list(meta.paths_searched),
|
|
717
|
+
"budget": {"evaluations_used": sum_int(m.evaluations for m in mons),
|
|
718
|
+
"evaluation_budget": options.eval_budget,
|
|
719
|
+
"decimated": any(m.decimated for m in mons)},
|
|
720
|
+
"reduction": {"scheme": SCHEME},
|
|
721
|
+
"options_used": options.used(),
|
|
722
|
+
"ranks": meta.ranks, "ranks_basis": meta.ranks_basis,
|
|
723
|
+
}
|
|
724
|
+
return Convergence(status=status, regime=regime, findings=tuple(findings), data=data,
|
|
725
|
+
inputs=tuple(inputs))
|
|
726
|
+
|
|
727
|
+
|
|
728
|
+
def sum_int(values) -> int:
|
|
729
|
+
"""Integer totals only; floats are reduced by fsum elsewhere."""
|
|
730
|
+
total = 0
|
|
731
|
+
for v in values:
|
|
732
|
+
total = total + int(v)
|
|
733
|
+
return total
|
|
734
|
+
|
|
735
|
+
|
|
736
|
+
def _waste(bmon: _Mon, stop_step: int, clock: Clock, meta: RunMeta, options: Options,
|
|
737
|
+
findings: list) -> dict:
|
|
738
|
+
first, final = bmon.first_step, bmon.final_step
|
|
739
|
+
wasted_steps = final - stop_step
|
|
740
|
+
span = final - first
|
|
741
|
+
wall = cpu = None
|
|
742
|
+
if bmon.step_basis == "log_time":
|
|
743
|
+
c_end, c_stop = _clock_at(clock.clock_s, final), _clock_at(clock.clock_s, stop_step)
|
|
744
|
+
e_end, e_stop = _clock_at(clock.exec_s, final), _clock_at(clock.exec_s, stop_step)
|
|
745
|
+
wall = (c_end - c_stop) if c_end is not None and c_stop is not None else None
|
|
746
|
+
cpu = (e_end - e_stop) if e_end is not None and e_stop is not None else None
|
|
747
|
+
total_wall = None
|
|
748
|
+
if bmon.step_basis == "log_time":
|
|
749
|
+
c_first = _clock_at(clock.clock_s, first)
|
|
750
|
+
c_last = _clock_at(clock.clock_s, final)
|
|
751
|
+
total_wall = (c_last - c_first) if c_first is not None and c_last is not None else None
|
|
752
|
+
waste = {"converged_at_step": stop_step, "first_step": first, "final_step": final,
|
|
753
|
+
"wasted_steps": wasted_steps, "steps_total": span,
|
|
754
|
+
"wasted_fraction": (wasted_steps / span) if span > 0 else 0.0,
|
|
755
|
+
"wasted_wall_clock_s": wall, "wall_clock_total_s": total_wall,
|
|
756
|
+
"wasted_cpu_s": cpu, "cpu_basis": "ExecutionTime of rank 0",
|
|
757
|
+
"ranks": meta.ranks, "ranks_basis": meta.ranks_basis,
|
|
758
|
+
"wasted_core_hours": None, "wasted_cost": None, "cost_per_core_hour": options.cost_per_core_hour,
|
|
759
|
+
"wasted_auh": None, "ccf_ghz": options.ccf_ghz}
|
|
760
|
+
missing = []
|
|
761
|
+
if wall is None:
|
|
762
|
+
missing.append("the log carried no wall clock for the stopping point and the end")
|
|
763
|
+
if not meta.ranks:
|
|
764
|
+
missing.append("the core count is not known")
|
|
765
|
+
if not missing:
|
|
766
|
+
waste["wasted_core_hours"] = meta.ranks * wall / 3600.0
|
|
767
|
+
if options.cost_per_core_hour is not None:
|
|
768
|
+
waste["wasted_cost"] = waste["wasted_core_hours"] * options.cost_per_core_hour
|
|
769
|
+
if options.ccf_ghz is not None:
|
|
770
|
+
waste["wasted_auh"] = meta.ranks * wall * options.ccf_ghz / 3600.0
|
|
771
|
+
findings.append(Finding("CONV.ALLOCATION", "INFO", None,
|
|
772
|
+
"FIA 2026 Sporting Regulations Section F Art. F4.4.4 (iss. 06, 27 Feb 2026)",
|
|
773
|
+
{}, {"ncu": meta.ranks, "nss": wall, "ccf_ghz": options.ccf_ghz,
|
|
774
|
+
"wasted_auh": waste["wasted_auh"],
|
|
775
|
+
"wasted_mauh": waste["wasted_auh"] / 1.0e6},
|
|
776
|
+
sentences.ALLOCATION_DISCLAIMER))
|
|
777
|
+
else:
|
|
778
|
+
findings.append(Finding("CONV.CORE_HOURS_NOT_COMPUTED", "INFO", None, "CONV-10", {},
|
|
779
|
+
{"missing": missing},
|
|
780
|
+
sentences.CORE_HOURS_NOT_COMPUTED.format(missing="; ".join(missing))))
|
|
781
|
+
findings.append(Finding("CONV.WASTE", "INFO", None, "Courant waste figures", {},
|
|
782
|
+
{k: waste[k] for k in ("wasted_steps", "steps_total", "wasted_fraction",
|
|
783
|
+
"wasted_wall_clock_s", "wasted_cpu_s",
|
|
784
|
+
"wasted_core_hours")}))
|
|
785
|
+
return waste
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _residuals(residuals: Mapping[str, Sequence[float]], status: str):
|
|
789
|
+
table, findings = {}, []
|
|
790
|
+
by_field = {}
|
|
791
|
+
for name in sorted(residuals):
|
|
792
|
+
if _PHASE_FRACTION.search(name):
|
|
793
|
+
continue
|
|
794
|
+
r = st.residual_summary(name, residuals[name])
|
|
795
|
+
table[name] = {"n": r.n, "r_ref": r.r_ref, "r_final": r.r_final, "r_min": r.r_min,
|
|
796
|
+
"r_min_index": r.r_min_index, "ratio": r.ratio,
|
|
797
|
+
"orders_dropped_floor": r.orders_dropped_floor,
|
|
798
|
+
"orders_capped": r.orders_capped, "plateaued": r.plateaued,
|
|
799
|
+
"drift_rel": r.drift_rel}
|
|
800
|
+
if r.orders_dropped_floor is not None:
|
|
801
|
+
by_field[name] = r.orders_dropped_floor
|
|
802
|
+
if r.plateaued is True:
|
|
803
|
+
findings.append(Finding("CONV.RESIDUAL_PLATEAU", FAIL if status == FAIL else "INFO",
|
|
804
|
+
None, "Trailing-window OLS drift on residuals",
|
|
805
|
+
{"drift_rel": st.PLATEAU_DRIFT},
|
|
806
|
+
{"field": name, "r_final": r.r_final, "drift_rel": r.drift_rel}))
|
|
807
|
+
elif r.plateaued is False:
|
|
808
|
+
findings.append(Finding("CONV.RESIDUAL_FALLING", "INFO", None,
|
|
809
|
+
"Trailing-window OLS drift on residuals",
|
|
810
|
+
{"drift_rel": st.PLATEAU_DRIFT},
|
|
811
|
+
{"field": name, "r_final": r.r_final, "drift_rel": r.drift_rel}))
|
|
812
|
+
if by_field:
|
|
813
|
+
minimum = min(by_field.values())
|
|
814
|
+
sev = "INFO" if minimum >= 3 else WARN
|
|
815
|
+
msg = None
|
|
816
|
+
if 3 <= minimum < 4:
|
|
817
|
+
msg = "Every field dropped at least three orders; Celik et al. prefer four."
|
|
818
|
+
elif minimum < 3:
|
|
819
|
+
msg = "At least one field dropped fewer than three orders of magnitude."
|
|
820
|
+
findings.append(Finding("CONV.CELIK_RESIDUAL_ORDERS", sev, None, METHOD_CELIK,
|
|
821
|
+
{"orders": 3, "preferred_orders": 4},
|
|
822
|
+
{"by_field": dict(sorted(by_field.items())), "minimum": minimum}, msg))
|
|
823
|
+
return table, findings
|