From f8438f5fd8a6fed08d1143dbc356bca530f7bad3 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 20 Nov 2026 14:35:36 +0900 Subject: [PATCH 1/3] fix: a repeated sample keeps the distributed state; capstan bounds overflow to inf as Python A constant curvature cycled in the distributed helix model. The compiled kernel started a sample that repeats the last one from the increment of the last substep and converged to a drift of the Newton tolerance (2e-6 Pa per sample on the 33 kV template's inner armour at 0.01 1/m and 200 kN), which compute_fatigue counted as 1e-58 damage where the reference kernel gave 0. Both kernels also moved the segment forces by one ulp on such a sample (1e-69 damage on the outer armour). Under the Coulomb bound a repeated sample now keeps the state in both kernels, with no substep; under a friction law it is still solved (a node can heal while it sticks), the compiled kernel starting it from a zero increment as the reference does. Run as Python (without numba), the compiled direction-tied and progressive kernels raised OverflowError from math.expm1 where compiled they return inf. friction_law._expm1_or_inf gives inf past log(DBL_MAX) on both, bit for bit equal to math.expm1 below it. Without numba this made compute_fatigue(..., friction_model="progressive", mu=1e6) fail. The reference progressive history holds such a sub-element cap at 1e300 Pa, as the reference Papailiou bound does, so it sticks where the compiled kernel does. Compiled results are unchanged. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 17 +++++ .../mechanics/distributed_friction.py | 38 +++++++--- src/cablexsec/mechanics/fast_slip.py | 5 +- src/cablexsec/mechanics/friction_law.py | 18 +++++ .../mechanics/progressive_friction.py | 17 +++-- tests/test_distributed_fast.py | 52 ++++++++++++++ tests/test_robustness_inputs.py | 71 ++++++++++++++++++- 7 files changed, 200 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 582f962..3e89ddb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -529,6 +529,23 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Fixed +- A constant curvature cycles nothing in the distributed helix model. A sample that repeats the + last one under the Coulomb bound now keeps the state in both kernels: its outputs equal the + last sample's bit for bit and it takes no substep. Before, the compiled kernel started such a + sample from the increment of the last substep and converged to a drift of the Newton + tolerance (2e-6 Pa per sample on the 33 kV template's inner armour at 0.01 1/m and 200 kN), + counted as 1e-58 damage where the reference kernel gave 0. Both kernels also moved the + segment forces by one ulp on a repeated sample (1e-69 damage on the outer armour), and the + critical angle of such a damage was arbitrary. Under a friction law a repeated sample is + still solved, since a node can heal while it sticks; the compiled kernel now starts it from + a zero increment, as the reference does. Only exactly repeated samples change. +- The capstan bounds of the compiled direction-tied and progressive kernels give `inf` past + the floating-point range when the kernels run as Python, as they do compiled + (`friction_law._expm1_or_inf`). Before, `math.expm1` raised `OverflowError` there. Without + numba this made `compute_fatigue(..., friction_model="progressive", mu=1e6)` fail. The + reference progressive history holds such a sub-element cap at 1e300 Pa, as the reference + Papailiou bound does, so it sticks where the compiled kernel sticks: at `mu = 1e6` both + give the damage of `mu = 3e4` on the probe history. Compiled results are unchanged. - CableDyn deck reader mirrors CableDyn's record checks: a section header CableDyn does not know is refused with the deck line (was skipped silently), as are a record over 512 bytes without a comment, a NUL or non-ASCII whitespace diff --git a/src/cablexsec/mechanics/distributed_friction.py b/src/cablexsec/mechanics/distributed_friction.py index 9fc072c..295e52e 100644 --- a/src/cablexsec/mechanics/distributed_friction.py +++ b/src/cablexsec/mechanics/distributed_friction.py @@ -64,11 +64,14 @@ ``1e-12 h`` times the largest force term). Sample increments larger than ``max_increment`` (in units of ``kappa_on``) are subdivided by linear interpolation of curvature and pressure; an increment that fails to converge is -repeated with twice as many substeps. With numba the increments are solved by +repeated with twice as many substeps. A sample that repeats the last one +(curvature and pressure unchanged) keeps the state under the Coulomb bound, +without a solve; under a friction law it is solved, since a node can heal +while it sticks. With numba the increments are solved by a faster kernel with the same equations, tests and fall-backs: Newton starts -from the increment of the last substep and the factorisation of its Jacobian -is kept between solves (section "Fast compiled kernel"); the results agree -with the reference kernel to round-off. +from the increment of the last substep (from zero on a repeated sample) and +the factorisation of its Jacobian is kept between solves (section "Fast +compiled kernel"); the results agree with the reference kernel to round-off. Full slip: when every node of an increment is on its bound, the equations fix the forces, the tractions and ``u - p``, but not a slide ``c`` common to the @@ -1034,8 +1037,15 @@ def _distributed_kernel( smfac[j] = mfac[j] slstate[0, j] = lstate[0, j] slstate[1, j] = lstate[1, j] - ok = False - for _attempt in range(_MAX_HALVINGS + 1): + # A sample that repeats the last one under the Coulomb bound (no + # friction law) leaves the state as it is: its increment is zero. + # Solving it would only move the segment forces by round-off, and + # those moves are counted as stress cycles at a constant curvature. + still = law is None and ax1 == ax0 and ay1 == ay0 and rho1 == rho0 + if still: + nsub = 0 + ok = still + for _attempt in range(0 if still else _MAX_HALVINGS + 1): ok = True if dt_path is not None: lparams[4] = dt_path[i] / nsub @@ -1921,9 +1931,21 @@ def _distributed_kernel_fast( smfac[j] = mfac[j] slstate[0, j] = lstate[0, j] slstate[1, j] = lstate[1, j] - ok = False - for _attempt in range(_MAX_HALVINGS + 1): + # As in the reference kernel, a repeated sample under the Coulomb bound + # keeps the state. Under a friction law it is solved, its increment + # started from zero as in the reference (its exact increment absent a + # change of the law state), not from the increment of the last + # substep, which converges to a drift of the Newton tolerance. + repeat = ax1 == ax0 and ay1 == ay0 and rho1 == rho0 + still = repeat and law is None + if still: + nsub = 0 + ok = still + for _attempt in range(0 if still else _MAX_HALVINGS + 1): ok = True + if repeat: + for j in range(n): + vlast[j] = 0.0 if dt_path is not None: lparams[4] = dt_path[i] / nsub for s in range(1, nsub + 1): diff --git a/src/cablexsec/mechanics/fast_slip.py b/src/cablexsec/mechanics/fast_slip.py index beb788c..c861d78 100644 --- a/src/cablexsec/mechanics/fast_slip.py +++ b/src/cablexsec/mechanics/fast_slip.py @@ -32,6 +32,7 @@ from cablexsec.exceptions import CableInputError from cablexsec.mechanics.friction_law import ( FrictionLaw, + _expm1_or_inf, _pressure_factor, _return_stress, _slip_magnitude, @@ -104,7 +105,7 @@ def _cap_into( if c > 1.0: c = 1.0 psi = math.asin(c) - out[0, w] = sigma0 * g[w] * math.expm1(mu * sin_a * psi) + out[0, w] = sigma0 * g[w] * _expm1_or_inf(mu * sin_a * psi) out[1, w] = -sigma0 * g[w] * math.expm1(-mu * sin_a * psi) @@ -335,7 +336,7 @@ def _stress_kernel_law( drive = dm0[w] * x + dm1[w] * y trial = force[w] + k * (drive - old_drive[w]) m = ms if healed[w] else md - upper = c0 * math.expm1(m * xh) + c1 * math.expm1(m * xc) + upper = c0 * _expm1_or_inf(m * xh) + c1 * _expm1_or_inf(m * xc) lower = -(c0 * math.expm1(-m * xh) + c1 * math.expm1(-m * xc)) if trial > upper or trial < -lower: side = 1.0 if trial > 0.0 else -1.0 diff --git a/src/cablexsec/mechanics/friction_law.py b/src/cablexsec/mechanics/friction_law.py index 27e995f..d4fb249 100644 --- a/src/cablexsec/mechanics/friction_law.py +++ b/src/cablexsec/mechanics/friction_law.py @@ -105,6 +105,7 @@ from __future__ import annotations import math +import sys from dataclasses import dataclass import numpy as np @@ -408,6 +409,23 @@ def _em1(y: float) -> float: return math.expm1(min(y, _EXP_LIMIT)) +#: Largest argument of a finite ``expm1`` in binary64, ``log(DBL_MAX)``. +_EXPM1_MAX = math.log(sys.float_info.max) + + +@njit(cache=True) +def _expm1_or_inf(x: float) -> float: + """``math.expm1(x)``, and ``inf`` beyond the binary64 range. + + Compiled, ``math.expm1`` already returns ``inf`` there; run as Python + (without numba) it raises ``OverflowError``. With this guard the two + agree, bit for bit, at every argument. + """ + if x > _EXPM1_MAX: + return math.inf + return math.expm1(x) + + @njit(cache=True) def _pressure_factor(p: float, table: FloatArray) -> float: """``f(p)`` of a pressure table (rows ``[P, f]``, shape (2, K)): linear diff --git a/src/cablexsec/mechanics/progressive_friction.py b/src/cablexsec/mechanics/progressive_friction.py index 5ee2986..02d8c10 100644 --- a/src/cablexsec/mechanics/progressive_friction.py +++ b/src/cablexsec/mechanics/progressive_friction.py @@ -75,7 +75,9 @@ from cablexsec._numba import njit from cablexsec.exceptions import CableInputError +from cablexsec.mechanics.friction_law import _expm1_or_inf from cablexsec.mechanics.papailiou import ( + _UNREACHABLE_CAP_PA, DIRECTION_HOLD_FRACTION, BendingWork, WireSlipHistory, @@ -207,11 +209,11 @@ def _caps_kernel( q = (j + 1.0) / n_el if j + 1 == n_el: q = 1.0 - upper = side * math.expm1(side * lam * math.asin(q * c)) + upper = side * _expm1_or_inf(side * lam * math.asin(q * c)) out[w, j] = base * scale * (upper - lower) lower = upper else: - cap = base * side * math.expm1(side * lam * math.asin(c)) + cap = base * side * _expm1_or_inf(side * lam * math.asin(c)) for j in range(n_el): out[w, j] = cap * (1.0 + spread * (2.0 * (j + 0.5) / n_el - 1.0)) return out @@ -245,8 +247,13 @@ def progressive_caps( if layer.shape_g is None else np.ascontiguousarray(layer.shape_g, dtype=np.float64) ) - return np.asarray( - _caps_kernel( + # A sub-element whose capstan factor is beyond the floating-point range + # (inf, or inf - inf between two such cumulative bounds) has a cap no wire + # stress reaches: held at _UNREACHABLE_CAP_PA, as the bound of + # papailiou.wire_slip_stress_bounds, so the reference history sticks there + # as the compiled kernel does, instead of an overflow error. + with np.errstate(over="ignore", invalid="ignore"): + caps = _caps_kernel( np.ascontiguousarray(layer.phi_wires, dtype=np.float64), float(phi_bend), float(pressure), @@ -261,7 +268,7 @@ def progressive_caps( spec.spread, float(side), ) - ) + return np.asarray(np.where(np.isfinite(caps), caps, _UNREACHABLE_CAP_PA)) # --------------------------------------------------------------------------- # diff --git a/tests/test_distributed_fast.py b/tests/test_distributed_fast.py index ca648bd..a882d80 100644 --- a/tests/test_distributed_fast.py +++ b/tests/test_distributed_fast.py @@ -144,6 +144,58 @@ def test_fast_kernel_matches_reference_with_friction_law(): _assert_close(fast, ref) +def _held_path(steps=STEPS): + """A ramp past the slip onset, a hold, a reversal and a second hold.""" + q = steps // 4 + ax = np.concatenate( + ( + np.linspace(0.0, 4.0, q), + np.full(q, 4.0), + np.linspace(4.0, -2.0, q), + np.full(steps - 3 * q, -2.0), + ) + ) + return ax, 0.3 * ax, q + + +@pytest.mark.parametrize("lam", [0.127, 0.0], ids=["signed", "uniform"]) +def test_a_repeated_sample_keeps_the_state(lam): + """Under the Coulomb bound a sample that repeats the last one leaves the + state as it is, in both kernels: its outputs equal the last sample's bit + for bit and it takes no substep. Solved, it moved the forces by round-off + (the fast kernel by the Newton tolerance), which counted as cycles.""" + ax, ay, q = _held_path() + held = np.r_[q : 2 * q, 3 * q : ax.size] + runs = {} + for kernel in (dfm._distributed_kernel, dfm._distributed_kernel_fast): + run = _run(kernel, ax, ay, lam=lam) + out, hist, slip, stats, fld = run[0] + for i in held: + assert np.array_equal(out[:, i], out[:, i - 1]) + assert np.array_equal(fld[i], fld[i - 1]) + assert np.array_equal(hist[i], hist[i - 1]) + assert slip[i] == slip[i - 1] + runs[kernel] = run + assert stats[0] == 0 + fast, ref = runs[dfm._distributed_kernel_fast], runs[dfm._distributed_kernel] + _assert_close(fast, ref) + moving = _run(dfm._distributed_kernel, ax + 1e-3 * np.arange(ax.size), ay) + assert moving[0][3][3] > ref[0][3][3] # the held samples took no substep + + +def test_a_repeated_sample_under_a_friction_law_is_solved_from_zero(): + """With a friction law a repeated sample can change the law state (a node + heals while it sticks), so it is solved; the fast kernel starts it from a + zero increment, as the reference does.""" + ax, ay, _q = _held_path() + rho = np.ones(ax.size) + law = (np.array([1.3, 1.0, 0.05]), np.full(ax.size, 0.01), None, 0.0) + options = {"nodes": 48, "rho": rho, "law": law} + ref = _run(dfm._distributed_kernel, ax, ay, **options) + fast = _run(dfm._distributed_kernel_fast, ax, ay, **options) + _assert_close(fast, ref) + + def test_fast_kernel_on_a_small_helix(): # Fewer than three nodes go to the reference kernel unchanged. ax, ay = _paths("rotating", steps=40) diff --git a/tests/test_robustness_inputs.py b/tests/test_robustness_inputs.py index 951369e..be4db5b 100644 --- a/tests/test_robustness_inputs.py +++ b/tests/test_robustness_inputs.py @@ -38,7 +38,9 @@ def _history(n=64): def test_very_large_mu_sticks_on_both_kernel_paths(monkeypatch): """mu = 1e6 overflowed the capstan factor of the reference return map ("wire history exceeds floating-point range") while the compiled path - held the wires stuck. Both now give the stuck answer, that of mu = 1.""" + held the wires stuck. Both now give the stuck answer, that of mu = 1. + The kernel of the compiled path also runs as Python without numba, where + ``math.expm1`` raised ``OverflowError`` instead of returning ``inf``.""" cable = bundled(CABLE) kx, ky, ten = _history() reference = cx.compute_fatigue( @@ -46,8 +48,9 @@ def test_very_large_mu_sticks_on_both_kernel_paths(monkeypatch): ) import cablexsec.analysis.fatigue as fatigue - # The compiled kernels where numba runs them, and the reference kernels. - for compiled in sorted({fatigue._FAST_SLIP, False}): + # The kernel of fast_slip (compiled, or as Python without numba) and the + # reference return map. + for compiled in (False, True): monkeypatch.setattr(fatigue, "_FAST_SLIP", compiled) result = cx.compute_fatigue( cable, kx, ky, tension_N=ten, mu=1e6, friction_model="direction_tied" @@ -59,6 +62,68 @@ def test_very_large_mu_sticks_on_both_kernel_paths(monkeypatch): ) +def test_very_large_mu_sticks_in_the_progressive_model(): + """The progressive kernel runs as Python without numba, where the capstan + factor at mu = 1e6 raised ``OverflowError``; compiled it gave the stuck + answer, which mu = 3e4 already reaches on this history.""" + cable = bundled(CABLE) + kx, ky, ten = _history() + stuck = cx.compute_fatigue( + cable, kx, ky, tension_N=ten, mu=3e4, friction_model="progressive" + ) + huge = cx.compute_fatigue( + cable, kx, ky, tension_N=ten, mu=1e6, friction_model="progressive" + ) + for name, damage in huge.D_total_per_wire.items(): + scale = float(np.max(stuck.D_total_per_wire[name])) + np.testing.assert_allclose( + damage, stuck.D_total_per_wire[name], rtol=0.0, atol=1e-12 * scale + ) + + +def test_expm1_guard_is_the_compiled_expm1_at_every_argument(): + """``_expm1_or_inf`` is ``math.expm1`` up to log(DBL_MAX) and ``inf`` + beyond it, compiled and run as Python alike.""" + from cablexsec.mechanics.friction_law import _EXPM1_MAX, _expm1_or_inf + + python = getattr(_expm1_or_inf, "py_func", _expm1_or_inf) + beyond = math.nextafter(_EXPM1_MAX, math.inf) + for guard in (_expm1_or_inf, python): + for x in (-1e6, -1.0, 0.0, 1e-300, 1.0, 700.0, _EXPM1_MAX): + assert guard(x) == math.expm1(x) + assert math.isfinite(guard(_EXPM1_MAX)) + assert guard(beyond) == math.inf and guard(1e6) == math.inf + assert math.isnan(guard(math.nan)) + with pytest.raises(OverflowError): + math.expm1(beyond) + + +@pytest.mark.parametrize("fast", [False, True], ids=["reference", "fast"]) +def test_constant_curvature_gives_no_distributed_damage(monkeypatch, fast): + """A constant curvature and tension cycle nothing. The compiled kernel + started each repeated sample from the increment of the last substep and + converged to a drift of the Newton tolerance (2e-6 Pa per sample on the + inner armour), counted as 1e-58 damage; both kernels moved the segment + forces by round-off on a repeated sample (1e-69 damage on the outer + armour). A repeated sample now keeps the state on both kernels.""" + from cablexsec.mechanics import distributed_friction as dfm + + monkeypatch.setattr(dfm, "_FAST_KERNEL", fast) + cable = bundled(CABLE) + n = 24 + result = cx.compute_fatigue( + cable, + np.full(n, 0.01), + np.zeros(n), + tension_N=np.full(n, 2e5), + friction_model="distributed", + distributed_max_increment=0.5, + ) + for name, damage in result.D_total_per_wire.items(): + assert np.all(damage == 0.0), name + assert np.all(result.D_bulk_with_termination_per_fibre[name] == 0.0), name + + def test_overflowing_capstan_bound_is_finite_and_unreachable(): from cablexsec.cable_adapters import cable_to_mkappa_specs From fded8f11c2e13fba510f7195d0480829c0d049c3 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 20 Nov 2026 15:33:25 +0900 Subject: [PATCH 2/3] docs: repeated samples also move the later samples at round-off Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3e89ddb..d43bf15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -538,7 +538,8 @@ All notable changes to CableXSec are recorded in this file. The format follows segment forces by one ulp on a repeated sample (1e-69 damage on the outer armour), and the critical angle of such a damage was arbitrary. Under a friction law a repeated sample is still solved, since a node can heal while it sticks; the compiled kernel now starts it from - a zero increment, as the reference does. Only exactly repeated samples change. + a zero increment, as the reference does. Only histories with exactly repeated samples + change: the repeated samples themselves, and the later ones at round-off. - The capstan bounds of the compiled direction-tied and progressive kernels give `inf` past the floating-point range when the kernels run as Python, as they do compiled (`friction_law._expm1_or_inf`). Before, `math.expm1` raised `OverflowError` there. Without From 439624bfd2098eb50abd267a31820241d4324a09 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 20 Nov 2026 15:59:06 +0900 Subject: [PATCH 3/3] test: the fall-back count starts after the stress-free first sample The interpreted fall-back test counts fixed-point calls. Its first sample repeats the stress-free start (zero curvature), which now keeps the state without a solve, so the failing call falls on sample 4 instead of 3. Signed-off-by: Jae Hoon Seo --- tests/test_distributed_fast.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/tests/test_distributed_fast.py b/tests/test_distributed_fast.py index a882d80..f5092ff 100644 --- a/tests/test_distributed_fast.py +++ b/tests/test_distributed_fast.py @@ -297,8 +297,10 @@ def fixed_point_failing_after_three(*args): (out, _h, _s, stats, _f), _ = _run( dfm._distributed_kernel_fast, ax, ay, lam=lam, nodes=16, max_increment=math.inf ) - assert stats[0] == -4 # samples 0-2 advanced, sample 3 not, after 12 halvings - np.testing.assert_allclose(out[:, :3], ref[0][0][:, :3], rtol=0, atol=1e-12) + # Sample 0 repeats the stress-free start (zero curvature) and needs no + # solve; samples 1-3 take the three calls, sample 4 fails after 12 halvings. + assert stats[0] == -5 + np.testing.assert_allclose(out[:, :4], ref[0][0][:, :4], rtol=0, atol=1e-12) @python_kernels