From 7e63dc09f8cfef0883654db118869a3c15a25eae Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Tue, 1 Dec 2026 11:16:18 +0900 Subject: [PATCH 1/2] fix: shorten the slowest validation tests; one SV11 prediction per report Two tests built the whole validation report for one or two rows: test_changed_wire_bending_fails_reported_comparison (sigma_B) and test_bending_work_report_compares_identical_measured_paths_and_units (BM1-loop, BM1-ID). The first was the longest test of the suite, 28-50 minutes on a CI runner and 74 minutes on a slow one, which left the Windows 3.11 job three minutes inside its 120-minute limit on dev. - run_validation: the sigma_B block and the BM1-loop/BM1-ID block move unchanged into _sigma_b_row and _bm1_rows; _rows calls them where the blocks were, so the report and its row order do not change. - The two tests call these builders. The check that the retired rows BM1-loop-uniform and CH-GJ stay out of the report reads the recorded report, which CI keeps equal to _rows(). - check_saevik2011: gate_values and split_values were lru_cache'd on their arguments, so gate_values() (the report's SV11 rows) and gate_values(MU_DECLARED) (audit_values) were two entries and every report computed the SV11 predictions twice. The caches are now keyed on the value of mu (_gate_values, _split_values); a new test pins it. Locally, single thread: sigma_B test 0.02 s, BM1 test 27 s, SV11 rows 286 s (gate_values 276 s plus audit_values 288 s before). Signed-off-by: Jae Hoon Seo --- tests/test_saevik2011_benchmark.py | 22 ++- tests/test_validation_report.py | 19 +- validation/scripts/check_saevik2011.py | 20 +- validation/scripts/run_validation.py | 264 +++++++++++++------------ 4 files changed, 189 insertions(+), 136 deletions(-) diff --git a/tests/test_saevik2011_benchmark.py b/tests/test_saevik2011_benchmark.py index 4cdf8fc..5d88da4 100644 --- a/tests/test_saevik2011_benchmark.py +++ b/tests/test_saevik2011_benchmark.py @@ -15,6 +15,7 @@ import math from collections import defaultdict from dataclasses import replace +from functools import lru_cache import check_saevik2011 as sv import numpy as np @@ -297,8 +298,8 @@ def __init__(self, name): def cache_clear(self): cleared.append(self.name) - monkeypatch.setattr(sv, "gate_values", Spy("gate")) - monkeypatch.setattr(sv, "split_values", Spy("split")) + monkeypatch.setattr(sv, "_gate_values", Spy("gate")) + monkeypatch.setattr(sv, "_split_values", Spy("split")) monkeypatch.setattr(sv, "cable", Spy("cable")) monkeypatch.setattr(sv, "TENDONS", sv.TENDONS) monkeypatch.setattr(sv, "K_ANCHOR_N_M", sv.K_ANCHOR_N_M) @@ -309,6 +310,23 @@ def cache_clear(self): assert cleared == ["cable", "gate", "split"] +def test_default_and_explicit_mu_share_one_cached_result(monkeypatch): + # The report calls gate_values() and audit_values calls gate_values(mu): + # both must reach one cache entry (they were two, and the SV11 predictions + # ran twice per report). + calls = [] + + @lru_cache(maxsize=2) + def counted(mu): + calls.append(mu) + return {"mu": mu} + + monkeypatch.setattr(sv, "_gate_values", counted) + assert sv.gate_values() is sv.gate_values(sv.MU_DECLARED) + assert sv.gate_values(mu=0.2) is sv.gate_values() + assert calls == [sv.MU_DECLARED] + + def test_held_inlet_keeps_the_contact_zone_curvature(): # A station in the held inlet takes the held curvature as its history, so # the normalised shape reproduces the beam's contact-zone curvature. diff --git a/tests/test_validation_report.py b/tests/test_validation_report.py index 785dad8..6bc5668 100644 --- a/tests/test_validation_report.py +++ b/tests/test_validation_report.py @@ -7,6 +7,7 @@ import pytest import run_validation +import cablexsec as cx from cablexsec._numba import HAVE_NUMBA #: Long friction histories run pure Python without numba (minutes per case). @@ -17,6 +18,10 @@ pytestmark = pytest.mark.analytical_sanity +def _menard(): + return cx.load_cable(cx.menard2023_yaml_path(), geometry_override=None) + + @needs_numba def test_changed_wire_bending_fails_reported_comparison(monkeypatch): original = run_validation.cx.compute_stress @@ -28,7 +33,10 @@ def incorrect_bending(*args, **kwargs): ) monkeypatch.setattr(run_validation.cx, "compute_stress", incorrect_bending) - row = next(r for r in run_validation._rows() if r.ident == "σ_B") + # The row's own builder, as _rows() calls it: building the whole report + # for one row was the longest test of the suite. + row = run_validation._sigma_b_row(_menard()) + assert row.ident == "σ_B" assert row.status == "FAIL" # Every state (mu = 0, stuck, slipping) reports the doubled bending. values = [float(part.split()[-1].rstrip("%")) for part in row.value.split(";")] @@ -37,7 +45,8 @@ def incorrect_bending(*args, **kwargs): @needs_numba def test_bending_work_report_compares_identical_measured_paths_and_units(): - rows = {r.ident: r for r in run_validation._rows()} + rows = {r.ident: r for r in run_validation._bm1_rows(_menard())} + assert set(rows) == {"BM1-loop", "BM1-ID"} row = rows["BM1-loop"] assert "matched experimental" in row.target # The clamping is identified on the measured work of range (a), not taken @@ -50,7 +59,11 @@ def test_bending_work_report_compares_identical_measured_paths_and_units(): assert "within 10%" in row.target assert row.status == "FAIL" assert rows["BM1-ID"].status == "FAIL" - assert "BM1-loop-uniform" not in rows and "CH-GJ" not in rows + # The retired rows stay out of the report (the recorded report equals + # _rows(); the CI checks that it is current). + report = run_validation.OUT.read_text(encoding="utf-8") + for retired in ("BM1-loop-uniform", "CH-GJ"): + assert f"| {retired} |" not in report _XSEC = run_validation.Row( diff --git a/validation/scripts/check_saevik2011.py b/validation/scripts/check_saevik2011.py index 8d10560..d4a63aa 100644 --- a/validation/scripts/check_saevik2011.py +++ b/validation/scripts/check_saevik2011.py @@ -115,8 +115,8 @@ def use_anchor(k_anchor_N_m: float | None) -> None: def _clear_results() -> None: """Drop every cached result that depends on the module settings.""" - gate_values.cache_clear() - split_values.cache_clear() + _gate_values.cache_clear() + _split_values.cache_clear() @dataclass(frozen=True) @@ -654,9 +654,16 @@ def plane_stations() -> tuple[str, ...]: return tuple(s for s, _x, az in stations() if az in (0.0, 180.0)) -@lru_cache(maxsize=2) def gate_values(mu: float = MU_DECLARED) -> dict: """SV11-PLANE and SV11-GJ metrics, bending-plane stations only (cached).""" + return _gate_values(float(mu)) + + +# The caches are keyed on the value of mu: lru_cache on the public functions +# keyed ``gate_values()`` and ``gate_values(MU_DECLARED)`` apart, so the +# report's SV11 rows computed every prediction twice. +@lru_cache(maxsize=2) +def _gate_values(mu: float) -> dict: plane = plane_stations() results = [predict_case(c, mu, only=plane) for c in load_cases()] return { @@ -913,7 +920,6 @@ def common(lc: int, v: dict, kind: str) -> float: SMALL_ANGLE_CASES = (7, 8) # 0.5 and 1 deg -@lru_cache(maxsize=1) def split_values(mu: float = MU_DECLARED) -> dict: """Where the termination increment of SV11 comes from (reported rows). @@ -924,7 +930,13 @@ def split_values(mu: float = MU_DECLARED) -> dict: unchanged; LC 14 and SV11-GJ against the registered correction. (c) Reach of SV11-PLANE: slip demand ``a_max`` of the correction at the small angles and the load cases whose sectional ratio is outside the band. + Cached on the value of mu. """ + return _split_values(float(mu)) + + +@lru_cache(maxsize=1) +def _split_values(mu: float) -> dict: plane = plane_stations() reg = gate_values(mu) ef = metrics( diff --git a/validation/scripts/run_validation.py b/validation/scripts/run_validation.py index 065202b..8480b1a 100644 --- a/validation/scripts/run_validation.py +++ b/validation/scripts/run_validation.py @@ -1490,6 +1490,141 @@ def p(key: str, out: dict[str, float | bool] = out) -> str: return rows +def _sigma_b_row(menard: CableData) -> Row: + """Radial-fibre bending stress of the wire at φ=0 against closed forms (σ_B).""" + # σ_B at φ=0: the normal curvature follows the wire's slip state, + # cos²a cos2a κ + (sin²a / r) σ_f / E. Without friction (μ = 0) it is + # Ménard Eq. 14; a stuck wire takes cos²a cos2a + ξ sin²a cos²a (cos⁴a + # at ξ = 1); a slipping wire adds the term of its friction stress. + name = next(iter(cx.compute_stress(menard, 0.03, tension_N=1.0e4).phi_deg)) + lyr = menard.get_layer(name) + e = library.get_property(lyr.material, "E_Pa") + a = lyr.lay_angle_rad + c2, s2 = math.cos(a) ** 2, math.sin(a) ** 2 + lox = c2 * math.cos(2 * a) + xi_b = next( + s.xi + for s in cable_to_mkappa_specs(menard, 1.0e4) + if math.isclose(s.r_helix_m, lyr.r_helix_m) + ) + errors_b = [] + stuck_b = slipping_b = True + for kappa_b, mu_b in ((0.03, 0.0), (1.0e-5, None), (0.03, None)): + sr = cx.compute_stress(menard, kappa_b, tension_N=1.0e4, mu=mu_b) + k0 = int(np.argmin(np.abs(sr.phi_deg[name]))) + sigma_f0 = float(sr.sigma_f_Pa[name][k0]) + if mu_b == 0.0: + coefficient = lox * sr.kappa_mag_1_m + elif kappa_b < 1e-3: + stuck_b = not bool(sr.slipping[name][k0]) + coefficient = (lox + xi_b * s2 * c2) * sr.kappa_mag_1_m + else: + slipping_b = bool(sr.slipping[name][k0]) + coefficient = lox * sr.kappa_mag_1_m + s2 / lyr.r_helix_m * sigma_f0 / e + closed = e * coefficient * (lyr.d_wire_m / 2) + errors_b.append(_pct(sr.sigma_B_Pa[name][k0], closed)) + return Row( + "1", + "σ_B", + "Radial-fibre bending at φ=0 (from the extension side): μ = 0 vs " + "Ménard Eq. 14; stuck wire vs cos²α cos2α + ξ sin²α cos²α (cos⁴α at " + "ξ = 1); slipping wire vs Eq. 14 + (sin²α / r) σ_f / E", + "< 1e-6% each", + "μ = 0 {:.2e}%; stuck {:.2e}%; slipping {:.2e}%".format(*errors_b), + "PASS" if max(errors_b) < 1e-6 and stuck_b and slipping_b else "FAIL", + ) + + +def _bm1_rows(menard: CableData) -> list[Row]: + """Ménard M-κ cycle rows: BM1-loop (identified on range a) and BM1-ID.""" + out: list[Row] = [] + # Menard and Cartraud fixed mu = 0.2 from the literature and tuned the + # radial pressure of their own FE model (0.3 MPa) on the +/-0.05 1/m cycle, + # range (a). That pressure is a parameter of their model, not a measured + # state, so it is not transferred: the clamping is identified on the + # measured cycle work of range (a) with this model, and the separate + # +/-0.10 1/m cycle, range (b), is predicted against the registered target. + from check_core_friction import ( # noqa: PLC0415 + _with_initial_pressure, + identify_initial_pressure, + identify_then_predict, + ) + + p_bm1 = identify_initial_pressure(menard, "a", None, "all_contacts") + menard_bm1 = _with_initial_pressure(menard, p_bm1, "all_contacts", "a") + phase_bm1 = np.linspace(0.0, 6.0 * np.pi, 1801) + kappa_bm1 = 0.1 * np.sin(phase_bm1) + bm1_prediction = cx.compute_mkappa( + menard_bm1, + kappa_bm1, + tension_N=0.0, + contact_model="bounded", + ) + measured_path = ROOT / "validation" / "paper_data" / "menard_fig16b_ordered.csv" + measured = np.genfromtxt(measured_path, delimiter=",", names=True) + stable_moment = bm1_prediction.moment_Nm[-601:] + model_min = float(np.min(stable_moment)) + model_max = float(np.max(stable_moment)) + measured_min = float(np.min(measured["moment_Nm"])) + measured_max = float(np.max(measured["moment_Nm"])) + measured_curvature = np.asarray(measured["curvature_1_per_m"], dtype=float) + measured_moment = np.asarray(measured["moment_Nm"], dtype=float) + measured_work = float( + np.mean(cycle_work(measured_curvature, measured_moment, crossing=0.0)) + ) + # In the test's own arrangement (four-point bench, M = Fa L1, curvature + # from a parabola through three LVDTs between the actuators; Menard and + # Cartraud 2023, Sec. 3). The measured curvature lies in the uniform-moment + # zone, so the result equals the uniform-curvature calculation. + arr_rmse, arr_work = _menard_four_point( + menard_bm1, measured_curvature, measured_moment + ) + arr_error = (arr_work / measured_work - 1.0) * 100.0 + out.append( + Row( + "2", + "BM1-loop", + "Ménard +/-0.10 M-kappa (range b), clamping identified on the " + "measured +/-0.05 cycle work (range a), four-point test arrangement " + "(Sec. 3: M = Fa L1, LVDT parabola)", + "ordered RMSE < 5%; matched experimental cycle work within 10%", + f"P0 {p_bm1 / 1e3:.1f} kPa; model {model_min:.0f}/{model_max:.0f} " + f"N·m and W={arr_work:.1f} J/m vs measured {measured_work:.1f} " + f"J/m; measured {measured_min:.0f}/{measured_max:.0f} N·m; " + f"ordered RMSE {arr_rmse:.2f}%; matched experimental work " + f"difference {arr_error:+.1f}%", + "PASS (identified on range a, then predicted)" + if arr_rmse < 5.0 and abs(arr_error) < 10.0 + else "FAIL", + ) + ) + + # Laid-core law with full contact accounting: P0 identified on range (b), + # ranges (a), (c)-(f) predicted (gap R1b; registered targets in + # doc/benchmarks.md). + ident = identify_then_predict() + id_rows = ident["rows"] + assert isinstance(id_rows, dict) + out.append( + Row( + "2", + "BM1-ID", + "Ménard laid cores, wedged trefoil and filler profiles (mu 0.2): " + "P0 identified on range (b) cycle work, ranges (a), (c)-(f) predicted", + "(b) ordered RMSE < 5%; (a), (c)-(f) cycle work within 20% and " + "ordered RMSE < 10%", + f"P0 {float(ident['pressure_Pa']) / 1e3:.1f} kPa; " + + "; ".join( + f"({tag}) {id_rows[tag]['work_error'] * 100:+.1f}% / " + f"{id_rows[tag]['rmse_percent']:.2f}%" + for tag in "abcdef" + ), + "PASS (identified, then predicted)" if ident["pass"] else "FAIL", + ) + ) + return out + + def _rows() -> list[Row]: rows: list[Row] = _normal_state_rows() menard = cx.load_cable(cx.menard2023_yaml_path(), geometry_override=None) @@ -1747,49 +1882,7 @@ def _rows() -> list[Row]: ) ) - # σ_B at φ=0: the normal curvature follows the wire's slip state, - # cos²a cos2a κ + (sin²a / r) σ_f / E. Without friction (μ = 0) it is - # Ménard Eq. 14; a stuck wire takes cos²a cos2a + ξ sin²a cos²a (cos⁴a - # at ξ = 1); a slipping wire adds the term of its friction stress. - name = next(iter(cx.compute_stress(menard, 0.03, tension_N=1.0e4).phi_deg)) - lyr = menard.get_layer(name) - e = library.get_property(lyr.material, "E_Pa") - a = lyr.lay_angle_rad - c2, s2 = math.cos(a) ** 2, math.sin(a) ** 2 - lox = c2 * math.cos(2 * a) - xi_b = next( - s.xi - for s in cable_to_mkappa_specs(menard, 1.0e4) - if math.isclose(s.r_helix_m, lyr.r_helix_m) - ) - errors_b = [] - stuck_b = slipping_b = True - for kappa_b, mu_b in ((0.03, 0.0), (1.0e-5, None), (0.03, None)): - sr = cx.compute_stress(menard, kappa_b, tension_N=1.0e4, mu=mu_b) - k0 = int(np.argmin(np.abs(sr.phi_deg[name]))) - sigma_f0 = float(sr.sigma_f_Pa[name][k0]) - if mu_b == 0.0: - coefficient = lox * sr.kappa_mag_1_m - elif kappa_b < 1e-3: - stuck_b = not bool(sr.slipping[name][k0]) - coefficient = (lox + xi_b * s2 * c2) * sr.kappa_mag_1_m - else: - slipping_b = bool(sr.slipping[name][k0]) - coefficient = lox * sr.kappa_mag_1_m + s2 / lyr.r_helix_m * sigma_f0 / e - closed = e * coefficient * (lyr.d_wire_m / 2) - errors_b.append(_pct(sr.sigma_B_Pa[name][k0], closed)) - rows.append( - Row( - "1", - "σ_B", - "Radial-fibre bending at φ=0 (from the extension side): μ = 0 vs " - "Ménard Eq. 14; stuck wire vs cos²α cos2α + ξ sin²α cos²α (cos⁴α at " - "ξ = 1); slipping wire vs Eq. 14 + (sin²α / r) σ_f / E", - "< 1e-6% each", - "μ = 0 {:.2e}%; stuck {:.2e}%; slipping {:.2e}%".format(*errors_b), - "PASS" if max(errors_b) < 1e-6 and stuck_b and slipping_b else "FAIL", - ) - ) + rows.append(_sigma_b_row(menard)) # GATE A (cross-engine): the per-wire σ_f assembly is the SAME Papailiou # slip-front compute_mkappa integrates, so the assembled moment recovers the @@ -2240,90 +2333,7 @@ def _comp_row(tier: str, ident: str, quantity: str, keys: tuple[str, ...]) -> Ro ) ) - # Menard and Cartraud fixed mu = 0.2 from the literature and tuned the - # radial pressure of their own FE model (0.3 MPa) on the +/-0.05 1/m cycle, - # range (a). That pressure is a parameter of their model, not a measured - # state, so it is not transferred: the clamping is identified on the - # measured cycle work of range (a) with this model, and the separate - # +/-0.10 1/m cycle, range (b), is predicted against the registered target. - from check_core_friction import ( # noqa: PLC0415 - _with_initial_pressure, - identify_initial_pressure, - identify_then_predict, - ) - - p_bm1 = identify_initial_pressure(menard, "a", None, "all_contacts") - menard_bm1 = _with_initial_pressure(menard, p_bm1, "all_contacts", "a") - phase_bm1 = np.linspace(0.0, 6.0 * np.pi, 1801) - kappa_bm1 = 0.1 * np.sin(phase_bm1) - bm1_prediction = cx.compute_mkappa( - menard_bm1, - kappa_bm1, - tension_N=0.0, - contact_model="bounded", - ) - measured_path = ROOT / "validation" / "paper_data" / "menard_fig16b_ordered.csv" - measured = np.genfromtxt(measured_path, delimiter=",", names=True) - stable_moment = bm1_prediction.moment_Nm[-601:] - model_min = float(np.min(stable_moment)) - model_max = float(np.max(stable_moment)) - measured_min = float(np.min(measured["moment_Nm"])) - measured_max = float(np.max(measured["moment_Nm"])) - measured_curvature = np.asarray(measured["curvature_1_per_m"], dtype=float) - measured_moment = np.asarray(measured["moment_Nm"], dtype=float) - measured_work = float( - np.mean(cycle_work(measured_curvature, measured_moment, crossing=0.0)) - ) - # In the test's own arrangement (four-point bench, M = Fa L1, curvature - # from a parabola through three LVDTs between the actuators; Menard and - # Cartraud 2023, Sec. 3). The measured curvature lies in the uniform-moment - # zone, so the result equals the uniform-curvature calculation. - arr_rmse, arr_work = _menard_four_point( - menard_bm1, measured_curvature, measured_moment - ) - arr_error = (arr_work / measured_work - 1.0) * 100.0 - rows.append( - Row( - "2", - "BM1-loop", - "Ménard +/-0.10 M-kappa (range b), clamping identified on the " - "measured +/-0.05 cycle work (range a), four-point test arrangement " - "(Sec. 3: M = Fa L1, LVDT parabola)", - "ordered RMSE < 5%; matched experimental cycle work within 10%", - f"P0 {p_bm1 / 1e3:.1f} kPa; model {model_min:.0f}/{model_max:.0f} " - f"N·m and W={arr_work:.1f} J/m vs measured {measured_work:.1f} " - f"J/m; measured {measured_min:.0f}/{measured_max:.0f} N·m; " - f"ordered RMSE {arr_rmse:.2f}%; matched experimental work " - f"difference {arr_error:+.1f}%", - "PASS (identified on range a, then predicted)" - if arr_rmse < 5.0 and abs(arr_error) < 10.0 - else "FAIL", - ) - ) - - # Laid-core law with full contact accounting: P0 identified on range (b), - # ranges (a), (c)-(f) predicted (gap R1b; registered targets in - # doc/benchmarks.md). - ident = identify_then_predict() - id_rows = ident["rows"] - assert isinstance(id_rows, dict) - rows.append( - Row( - "2", - "BM1-ID", - "Ménard laid cores, wedged trefoil and filler profiles (mu 0.2): " - "P0 identified on range (b) cycle work, ranges (a), (c)-(f) predicted", - "(b) ordered RMSE < 5%; (a), (c)-(f) cycle work within 20% and " - "ordered RMSE < 10%", - f"P0 {float(ident['pressure_Pa']) / 1e3:.1f} kPa; " - + "; ".join( - f"({tag}) {id_rows[tag]['work_error'] * 100:+.1f}% / " - f"{id_rows[tag]['rmse_percent']:.2f}%" - for tag in "abcdef" - ), - "PASS (identified, then predicted)" if ident["pass"] else "FAIL", - ) - ) + rows.extend(_bm1_rows(menard)) rows.extend(_zeidan_rows()) rows.extend(_hu_rows()) From e42d2a4021744416e706e4f576de4474769335d0 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Tue, 1 Dec 2026 11:39:18 +0900 Subject: [PATCH 2/2] validation report: full_scale test count 63 The new cache test in tests/test_saevik2011_benchmark.py carries the module's full_scale marker, so the taxonomy count of the report goes from 62 to 63. The CI check found no other change beyond round-off. Signed-off-by: Jae Hoon Seo --- validation/validation_report.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validation/validation_report.md b/validation/validation_report.md index 112853c..410463f 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -88,7 +88,7 @@ Every row is computed from published data or closed-form references in this repo - analytical_sanity: `1356 passed` - independent_method: `105 passed` -- full_scale: `62 passed` +- full_scale: `63 passed` Run `pytest -m ` to reproduce each group.