test: signed interface-probe trace diagnostic (--probe-trace)

Test-only mechanism diagnostic, no pass gates. New pinned shear_probes.py:
24 fixed root-physical points on vertical/horizontal interface-normal
transects (>=8 root cells from corners), ACTIVE-leaf selection storing
level/i/j/actual centers, root-sync rho/ux/uy at root steps 0-128 and
1920-2048 (U512 every 4 lattice steps), analytic residuals at actual
centers, schedule/finite/600 kB validation. run_case: --probe-trace for
nested U128/U512/projected d3 and twin projected d2 (not with
--final-snapshot), shear_probes.py pin, probe-only steps skip metrics,
five qualification samples unchanged. shear_wave/shear_nested/shear_twin/
oracle byte-identical.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
ClaudeandClaude Opus 5.5 committed 2026-10-19 03:11:48 +00:00
1 parent 02bde0f751
commit 1e188e7419
4 files changed
+377 -3

No files matched your search

@@ -930,3 +930,189 @@ class TwinPresetTests(unittest.TestCase):
self.assertTrue(all(len(r["spurious_pressure_scaled_by_level"]) == 2 for r in rec["rows"]))
self.assertEqual(selectors, [("projected_linear", [list(self.twin.REFINEMENTS[0])])])
self.assertEqual(sorted(p.name for p in Path(tmp).iterdir()), ["projected_twin.json"])
class ProbeTraceTests(unittest.TestCase):
"""Signed interface-probe mechanism diagnostic (--probe-trace); no pass gates."""
def setUp(self):
import shear_nested
import shear_probes
import shear_twin
self.nested, self.probes, self.twin = shear_nested, shear_probes, shear_twin
def exact_arrays(self, masks, n, t):
"""Equilibrium of the exact wave at root-physical time t on a case grid of root N=n."""
out = []
for level, m in enumerate(masks):
x, y = centers(m.shape, level)
x, y = x * 128 / n, y * 128 / n
ux, uy, _ = sw.exact(x, y, t, 128, U * 128 / sw.RE)
out.append(sw.equilibrium(np.ones_like(ux), ux, uy))
return out
def test_frozen_history_identities(self):
for name, digest in (("shear_wave.py", "81d5c8ee60864372887cddf9239580c82fb6750d956038f1e3ee9de61aa4e877"),
("shear_nested.py", "fa6cfe87fb4df8c6d732c637c885276833c81973b950c7724d734f8fc350bcb0"),
("shear_twin.py", "1cbf37f18e89aea577581631c4565f51e68d22a3739b698816ef64acbf2b2bb4"),
("oracle.py", ORACLE_SHA256_EEC4677)):
self.assertEqual(hashlib.sha256((HERE / name).read_bytes()).hexdigest(), digest, name)
self.assertEqual(run_case.SHEAR_PROBES_SHA256,
hashlib.sha256((HERE / "shear_probes.py").read_bytes()).hexdigest())
def test_probe_selection_per_case(self):
sp = self.probes
self.assertEqual(len(sp.points()), 24)
corners = [(x, y) for level in (self.nested.REFINEMENTS[0],
[tuple(v / 2 for v in r) for r in self.nested.REFINEMENTS[1]])
for x0, y0, x1, y1 in level for x in (x0, x1) for y in (y0, y1)]
for _, _, (x, y) in sp.points():
self.assertGreaterEqual(min(math.hypot(x - cx, y - cy) for cx, cy in corners), 8.0)
pattern = [0, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2]
nested = sp.select(self.nested.leaf_masks())
self.assertEqual([p["level"] for p in nested], pattern * 2)
twin = sp.select(self.twin.leaf_masks())
self.assertEqual([p["level"] for p in twin], [min(v, 1) for v in pattern] * 2)
u128 = sp.select([np.ones((128, 128), bool)], 128)
u512 = sp.select([np.ones((512, 512), bool)], 512)
self.assertTrue(all(p["level"] == 0 for p in u128 + u512))
for case in (nested, twin, u128, u512):
for p in case:
# The stored center is the actual cell center containing the point (root units).
h = 1.0 / (2 ** p["level"]) if case is not u512 else 0.25
self.assertLessEqual(abs(p["center"][0] - p["point"][0]), h / 2)
self.assertLessEqual(abs(p["center"][1] - p["point"][1]), h / 2)
# Different grids give different centers: no pretended collocation.
self.assertNotEqual(u128[3]["center"], u512[3]["center"])
self.assertEqual(sp.case_steps(512)[:3], [0, 4, 8])
self.assertEqual(sp.case_steps(128), list(sp.STEPS))
def test_residuals_vanish_for_the_exact_field(self):
sp = self.probes
for masks, n in ((self.nested.leaf_masks(), 128), ([np.ones((512, 512), bool)], 512)):
probes = sp.select(masks, n)
trace = sp.new_trace(probes, U * n / sw.RE, ["x", n, len(masks), "c"])
for t in (0, 100, 2048):
trace["steps"].append(t)
trace["values"].append(sp.sample(self.exact_arrays(masks, n, t), probes))
for res in sp.residuals(trace):
self.assertLess(max(abs(v) for r in res for v in r), 1e-14)
def test_validate_schedule_values_and_cap(self):
sp = self.probes
probes = sp.select(self.nested.leaf_masks())
trace = sp.new_trace(probes, 0.0384, ["n", 128, 3, "projected_linear"])
trace["steps"] = list(sp.STEPS)
trace["values"] = [[1.0, 0.01, -0.02] * 24 for _ in sp.STEPS]
size = sp.validate(trace)
self.assertLess(size, sp.TRACE_MAX_BYTES)
realistic = dict(trace, values=[[1.0000012345678901, 0.012345678901234567,
-0.023456789012345678] * 24 for _ in sp.STEPS])
self.assertLess(sp.validate(realistic), sp.TRACE_MAX_BYTES)
for bad in (dict(trace, steps=trace["steps"][:-1]),
dict(trace, values=trace["values"][:-1] + [[float("nan")] * 72]),
dict(trace, probes=trace["probes"][:-1])):
with self.assertRaises(ValueError):
sp.validate(bad)
with patch.object(sp, "TRACE_MAX_BYTES", 1000):
with self.assertRaises(ValueError):
sp.validate(trace)
def test_probe_runner_options(self):
repo = Path(__file__).resolve().parents[3]
with tempfile.TemporaryDirectory() as tmp:
base = ["run_case.py", "--repo", str(repo), "--expected-revision", "f" * 40,
"--output", str(Path(tmp) / "case.json"), "--dry-run", "--re", "100",
"--flow", "shear_wave", "--probe-trace"]
nest = ["--diagnostic", run_case.NESTED_SHEAR]
tw = ["--diagnostic", run_case.TWIN_SHEAR]
proj = ["--explosion", "projected_linear"]
for extra, valid in (
(["--n", "128", "--depth", "1"] + nest, True),
(["--n", "512", "--depth", "1"] + nest, True),
(["--n", "128", "--depth", "3"] + proj + nest, True),
(["--n", "128", "--depth", "2"] + proj + tw, True),
(["--n", "128", "--depth", "3"] + nest, False), # constant d3
(["--n", "128", "--depth", "1"] + tw, False),
(["--n", "128", "--depth", "3"] + proj + nest + ["--final-snapshot"], False),
(["--n", "128", "--depth", "2"], False)):
argv = base + extra
with self.subTest(argv=argv), patch.object(sys, "argv", argv), \
patch.object(run_case, "verify_source", return_value={}) as verify, \
patch.object(run_case, "runtime_source", return_value={}), \
redirect_stdout(io.StringIO()), patch("sys.stderr", io.StringIO()):
if valid:
self.assertEqual(run_case.main(), 0)
self.assertIs(verify.call_args.kwargs["probes"], True)
else:
with self.assertRaises(SystemExit):
run_case.main()
def run_mocked(self, n, depth, diagnostic, scheme, masks):
from types import SimpleNamespace
from contextlib import nullcontext
arrays = self.exact_arrays(masks, n, 0.0)
counts = []
class FakeRun:
def __init__(self, *args, **kwargs):
self.step_count = 0
def __enter__(self):
return self
def __exit__(self, *args):
pass
def initialize(self, *given):
pass
def step(self, count):
self.step_count += count
counts.append(self.step_count)
def download(self):
return arrays[0] if depth == 1 else arrays
modules = {"CelerisLab.cuda.context": SimpleNamespace(CudaContext=FakeRun),
"CelerisLab.lbm.block_stepper": SimpleNamespace(PeriodicBlockStepper=FakeRun),
"CelerisLab.lbm.refinement_stepper": SimpleNamespace(FixedPatchStepper=FakeRun)}
repo = Path(__file__).resolve().parents[3]
with tempfile.TemporaryDirectory() as tmp:
output = Path(tmp) / "probe.json"
argv = ["run_case.py", "--repo", str(repo), "--re", "100", "--n", str(n),
"--depth", str(depth), "--explosion", scheme, "--flow", "shear_wave",
"--diagnostic", diagnostic, "--probe-trace", "--output", str(output),
"--expected-revision", "f" * 40, "--run-gpu"]
with patch.dict(sys.modules, modules), patch.object(sys, "argv", argv), \
patch.dict("os.environ", CUDA_VISIBLE_DEVICES="mock"), \
patch.object(run_case, "verify_source", return_value=dict(revision="f" * 40)), \
patch.object(run_case, "runtime_source", return_value={}), \
patch.object(run_case, "runtime_identity", return_value={}), \
patch.object(run_case, "build_capture", return_value=nullcontext()), \
redirect_stdout(io.StringIO()):
run_case.main()
return json.loads(output.read_text()), counts, sorted(p.name for p in Path(tmp).iterdir())
def test_mocked_probe_traces(self):
sp = self.probes
rec, counts, files = self.run_mocked(128, 3, run_case.NESTED_SHEAR, "projected_linear",
self.nested.leaf_masks())
trace = rec["probe_trace"]
self.assertEqual(trace["steps"], list(sp.STEPS))
self.assertEqual(len(trace["values"]), len(sp.STEPS))
self.assertLessEqual(trace["bytes"], sp.TRACE_MAX_BYTES)
self.assertEqual(trace["case"], [run_case.NESTED_SHEAR, 128, 3, "projected_linear"])
self.assertEqual(len(rec["rows"]), 5) # qualification samples preserved
self.assertEqual(files, ["probe.json"]) # no field dumps
self.assertEqual(sp.validate(trace) <= sp.TRACE_MAX_BYTES, True)
rec512, counts512, _ = self.run_mocked(512, 1, run_case.NESTED_SHEAR, "constant",
[np.ones((512, 512), bool)])
t512 = rec512["probe_trace"]
self.assertEqual(t512["steps"], list(sp.STEPS)) # root-physical times
self.assertEqual(t512["viscosity_root"], U * 128 / sw.RE)
self.assertEqual(t512["case_viscosity"], U * 512 / sw.RE)
self.assertIn(4 * 1920, counts512) # U512 advanced to 4x lattice steps
self.assertTrue(all(p["level"] == 0 for p in t512["probes"]))
res = sp.residuals(t512)
self.assertLess(abs(res[0][0][1]), 1e-14) # exact field at t=0 at actual centers