Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -529,6 +529,24 @@ 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 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
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
Expand Down
38 changes: 30 additions & 8 deletions src/cablexsec/mechanics/distributed_friction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand Down
5 changes: 3 additions & 2 deletions src/cablexsec/mechanics/fast_slip.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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)


Expand Down Expand Up @@ -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
Expand Down
18 changes: 18 additions & 0 deletions src/cablexsec/mechanics/friction_law.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@
from __future__ import annotations

import math
import sys
from dataclasses import dataclass

import numpy as np
Expand Down Expand Up @@ -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
Expand Down
17 changes: 12 additions & 5 deletions src/cablexsec/mechanics/progressive_friction.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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),
Expand All @@ -261,7 +268,7 @@ def progressive_caps(
spec.spread,
float(side),
)
)
return np.asarray(np.where(np.isfinite(caps), caps, _UNREACHABLE_CAP_PA))


# --------------------------------------------------------------------------- #
Expand Down
58 changes: 56 additions & 2 deletions tests/test_distributed_fast.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -245,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
Expand Down
71 changes: 68 additions & 3 deletions tests/test_robustness_inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,19 @@ 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(
cable, kx, ky, tension_N=ten, mu=1.0, friction_model="direction_tied"
)
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"
Expand All @@ -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

Expand Down
Loading