From b2770b3d28717534c7cb44f81df35df08a350e53 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 11:04:40 +0900 Subject: [PATCH 1/4] feat: static/dynamic and rate-dependent armour friction law Every contact pair had one rate-independent Coulomb coefficient. A FrictionLaw now gives each wire (direction-tied model) or helix node (distributed model) a factor on its coefficient where the kernel applies it: inside the capstan exponent of the wire bounds and on the whole node bound m (rho g + lam n). - Static/dynamic: static_factor until a wire slips in a stick episode, dynamic_factor while it slips and until it has stuck for stick_time_s, per-wire (per-node) stick timer, either order (breakaway peak or velocity strengthening). - Rate: R(v) = 1 + c ln(1 + v/v0) + v/v_eta on the dynamic factor; the viscous term is t = b sign(v) + eta v with eta = b/v_eta, solved as a backward-Euler (Perzyna) return by safeguarded Newton, unique for c >= 0 and exact per step. BendingWork.viscous_J_per_m carries the rate-dependent dissipation and the balance closes with it. The direction-tied slip rate is the plastic strain rate times r/|sin a|. - Direction-tied: NumPy reference in wire_slip_history and a compiled kernel in fast_slip; distributed: static/dynamic option with breakaway re-solve of the increment (rate terms refused). - compute_mkappa and compute_fatigue take friction_law and time_s; a law that depends on time is refused without sample times, time_s without such a law is refused. The progressive law, core friction, the termination clamp increment and the bending-law export (Masing/Iwan is rate independent) refuse a non-neutral law. - Neutral parameters keep the rate-independent code paths bit for bit. Tests: one-slider closed forms (breakaway peak, strengthening, healing, steady viscous loop area pi eta omega x0^2, steady logarithmic rate), energy identity to round-off, equal factors equal to a scaled mu, compiled kernel against the reference, entry-point refusals. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 18 + doc/api_python.rst | 11 + doc/concepts.md | 64 ++ release/check_coverage.py | 1 + src/cablexsec/__init__.py | 2 + src/cablexsec/analysis/bending_law.py | 21 +- src/cablexsec/analysis/fatigue.py | 77 +- src/cablexsec/api.py | 112 ++- .../mechanics/distributed_friction.py | 301 ++++++- src/cablexsec/mechanics/fast_slip.py | 181 +++- src/cablexsec/mechanics/friction_law.py | 596 +++++++++++++ src/cablexsec/mechanics/papailiou.py | 362 +++++++- tests/test_friction_law.py | 787 ++++++++++++++++++ validation/validation_report.md | 6 +- 14 files changed, 2472 insertions(+), 67 deletions(-) create mode 100644 src/cablexsec/mechanics/friction_law.py create mode 100644 tests/test_friction_law.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 8c376bd..0245eb0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -34,6 +34,24 @@ All notable changes to CableXSec are recorded in this file. The format follows curvature is about 1% of its peak, so the wire next to it stays in stick and the anchor condition does not reach the stations; the over-prediction is a curvature-gradient effect. Section records of the sea-state batch carry the new key; records without it load as rigid. +- A friction law with a static/dynamic and a rate-dependent coefficient (`FrictionLaw`, + `compute_mkappa(..., friction_law=, time_s=)`, `compute_fatigue(..., friction_law=, time_s=)`). + Before, every contact pair had one rate-independent Coulomb coefficient. The law gives each + wire (direction-tied model) or helix node (distributed model) a factor on its coefficient: + `static_factor` until it slips, `dynamic_factor` while it slips and until it has stuck for + `stick_time_s`, either order (`mu_s > mu_d` gives a breakaway peak, `mu_s < mu_d` velocity + strengthening), times `R(v) = 1 + c ln(1 + v/v0) + v/v_eta` at slip rate `v`. The last term + is a regularised Coulomb law `t = b sign(v) + eta v` with `eta = b/v_eta`, solved as a + backward-Euler (Perzyna) return that is exact for each step; `BendingWork.viscous_J_per_m` + reports its dissipation and the work balance closes with it to round-off. The direction-tied + kernel takes every option (NumPy reference and compiled kernel), the distributed kernel the + static/dynamic option; the progressive model, the laid-core friction and the termination + clamp increment refuse a non-neutral law, and so does the exported bending law (a Masing/Iwan + law is rate independent). A law that depends on time needs the sample times and is refused + without them. Neutral parameters reproduce every result bit for bit. `slider_history` runs + the law on one spring-slider: breakaway peak, healing, steady logarithmic rate and the + viscous loop area `pi eta omega x0^2` are tested in closed form. No rate-dependent friction + data of armour interfaces is in the validation set. - `compute_mkappa` can let the armour contact pressure follow the bending history: `contact_tension_history_N` sets the per-sample `P1+P2` from a tension history through the contact model (the histories `compute_fatigue` forms from `tension_N`), and diff --git a/doc/api_python.rst b/doc/api_python.rst index 02039b5..50fa53d 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -30,6 +30,17 @@ Bending and stress .. autofunction:: cablexsec.compute_stress .. autofunction:: cablexsec.compute_component_response +Friction law +------------ + +The static/dynamic and rate-dependent armour friction coefficient taken by +``compute_mkappa`` and ``compute_fatigue`` (``friction_law``, with ``time_s``), +and the single spring-slider that shows its closed forms. + +.. autoclass:: cablexsec.FrictionLaw + :members: rate_factor, describe, is_neutral, needs_time +.. autofunction:: cablexsec.mechanics.friction_law.slider_history + Fatigue ------- diff --git a/doc/concepts.md b/doc/concepts.md index 4966009..a5ab25a 100644 --- a/doc/concepts.md +++ b/doc/concepts.md @@ -201,6 +201,70 @@ follows the history: the stick stiffness, the full-slip stiffness and the contact loads of the laid cores stay at the reference state. The bending-test simulator and the exported bending law keep a fixed pressure. +## The friction coefficient can depend on slip state and rate + +By default every contact pair has one rate-independent Coulomb coefficient +`mu`. A `FrictionLaw` replaces it by an effective coefficient `m mu`, with a +factor `m` that each wire (direction-tied model) or helix node (distributed +model) carries on its own. The factor enters where the kernel uses `mu`: in +the capstan exponent of the wire bounds, `sigma0 g expm1(m lam psi)` and +`sigma0 g (1 - exp(-m lam psi))`, and on the whole node bound +`m (rho g + lam n)` of the distributed model. + +**Static and dynamic coefficient.** A wire keeps the static factor +`static_factor` (`mu_s / mu`) until it slips, then the dynamic factor +`dynamic_factor` (`mu_d / mu`) while it slips, and returns to the static one +after `stick_time_s` of stick. Each step is a backward-Euler return map with +the factor of the end of the step. A wire whose trial stress leaves the +interval of its current factor starts or continues a slip episode and is +returned to the dynamic interval. With `mu_s > mu_d` the loop has a breakaway +peak: the stress drops from the static to the dynamic bound in the step of +breakaway. With `mu_s < mu_d` (velocity strengthening) the stick episode ends +at the static bound without slip, and the wire continues elastically up to +the dynamic bound. A healing time of `inf` (default) never heals, `0` heals +after one stick step. + +**Rate dependence.** At slip rate `v` the dynamic factor becomes `m_d R(v)`, + +$$ +R(v) = 1 + c \ln(1 + v / v_0) + v / v_\eta , +$$ + +the logarithmic law `mu(v) = mu_d (1 + c ln(1 + v/v_0))` plus a regularised +(viscous) Coulomb term `t = b sign(v) + eta v` with `eta = b / v_eta`, a +Perzyna overstress proportional to the rate-independent bound `b`. The slip +increment `dp` of a slipping wire solves +`|sigma_trial| - k dp = B(m_d R(L dp / dt))` with `B` the bound on its side; +the left side falls and the right side rises with `dp`, so the root is +unique and the return is exact for the step. Only `c >= 0` is accepted +(velocity weakening loses this uniqueness). The direction-tied wire slips in +a reduced strain; its slip rate is that strain rate times `L = r / |sin a|`, +the wire length per radian of helix, which turns the extreme-fibre strain +`r kappa` into the largest slip displacement of a freely sliding wire. It is +a representative wire velocity, not a local one. The distributed model takes +the static/dynamic option only. + +**Energy.** The work of a slipping wire splits into the rate-independent +friction work `B(m_d) |dp|` and the rate-dependent (viscous) part +`[B(m_d R) - B(m_d)] |dp|`; `BendingWork.viscous_J_per_m` reports the second, +and the balance input work = stored energy + friction + viscous dissipation + +backward-Euler remainder closes to round-off. One slider driven at full slip +by `x0 sin(omega t)` dissipates `4 b x0` by friction and `pi eta omega x0^2` +by the viscous term per cycle (`slider_history` reproduces both). + +**Where it applies.** `compute_mkappa` and `compute_fatigue` take +`friction_law` with the sample times `time_s` when the law needs them (a rate +term or a finite positive healing time); without a time base such a law is +refused, and `time_s` without one is refused too. The stress-free start lies +one sampling interval before the first sample. The progressive (Iwan) model, +the laid-core friction, the termination clamp increment and the bending-test +simulator keep the rate-independent coefficient and refuse a non-neutral law. +The exported bending law refuses one as well: its parallel elastic-plastic +elements with Masing's rules are rate independent and cannot represent it. +Neutral parameters (`mu_s = mu_d = mu`, `c = 0`, `v_eta = inf`) leave every +result unchanged, bit for bit. No rate-dependent or static/dynamic friction +data of armour interfaces is in the validation set. + ## Fatigue is counted at fixed material points A fatigue crack starts at a point of the material, so CableXSec counts fatigue diff --git a/release/check_coverage.py b/release/check_coverage.py index a255a28..3911ab3 100644 --- a/release/check_coverage.py +++ b/release/check_coverage.py @@ -32,6 +32,7 @@ "tests/test_along_wire_test_inputs.py", "tests/test_along_wire_chain.py", "tests/test_friction_kernels.py", + "tests/test_friction_law.py", ) diff --git a/src/cablexsec/__init__.py b/src/cablexsec/__init__.py index 16179cd..725359e 100644 --- a/src/cablexsec/__init__.py +++ b/src/cablexsec/__init__.py @@ -184,6 +184,7 @@ ExtrapolationWarning, FatigueLayer, FatigueResult, + FrictionLaw, MkappaResult, PhysicalRangeError, ProgressiveFriction, @@ -523,6 +524,7 @@ "ContactQPResult", "CoreFrictionHistory", "CoreFrictionSpec", + "FrictionLaw", "ProgressiveFriction", "birdcage_buckling_detail", "cable_to_mkappa_specs", diff --git a/src/cablexsec/analysis/bending_law.py b/src/cablexsec/analysis/bending_law.py index dabae59..5056fe4 100644 --- a/src/cablexsec/analysis/bending_law.py +++ b/src/cablexsec/analysis/bending_law.py @@ -94,6 +94,7 @@ from numpy.typing import ArrayLike, NDArray from cablexsec.exceptions import CableInputError +from cablexsec.mechanics.friction_law import FrictionLaw from cablexsec.mechanics.papailiou import wire_slip_stress_bounds from cablexsec.provenance import Provenance @@ -851,7 +852,10 @@ def export_bending_law( **mkappa_options Passed to :func:`cablexsec.api.compute_mkappa` (``mu``, ``contact_model``, ``friction_model``, ``progressive``, - ``core_friction``); planar bending only. + ``core_friction``); planar bending only. A non-neutral + ``friction_law`` (static/dynamic or rate dependent) is refused: the + exported parallel elastic-plastic law with Masing's rules is rate + independent and cannot represent it. Notes ----- @@ -883,6 +887,21 @@ def export_bending_law( ): if name in mkappa_options: raise CableInputError(f"{name} is set by the export, not an option") + friction_law = mkappa_options.get("friction_law") + if friction_law is not None and ( + not isinstance(friction_law, FrictionLaw) or not friction_law.is_neutral + ): + # A static/dynamic or rate-dependent coefficient has no Masing/Iwan + # (rate-independent, parallel elastic-plastic) representation. + raise CableInputError( + "a non-neutral friction law cannot be exported as a Masing/Iwan " + "bending law (it is state or rate dependent); export the " + "rate-independent law" + ) + if "time_s" in mkappa_options: + raise CableInputError( + "time_s is not an export option: the exported backbone is rate independent" + ) if not slip_scale and ( slip_scale_reference_N is not None or slip_scale_tensions_N is not None diff --git a/src/cablexsec/analysis/fatigue.py b/src/cablexsec/analysis/fatigue.py index 131d624..f73bd28 100644 --- a/src/cablexsec/analysis/fatigue.py +++ b/src/cablexsec/analysis/fatigue.py @@ -96,6 +96,11 @@ distributed_wire_friction_stress, ) from cablexsec.mechanics.fast_slip import wire_friction_stress +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + active_friction_law, + friction_law_time_steps, +) from cablexsec.mechanics.mindlin_contact import ( MindlinContact, TransverseMap, @@ -514,11 +519,16 @@ def _wire_stress_series( distributed_max_increment: float = DEFAULT_MAX_INCREMENT, progressive: ProgressiveFriction | None = None, friction_out: list[FloatArray] | None = None, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> FloatArray: """Build ``sigma_total(phi_k, t)`` for every wire of one layer [Pa]. ``friction_out``, when given, receives the friction stress ``sigma_f`` - (for the component stress concentration factors). + (for the component stress concentration factors). ``friction_law`` and + ``time_s`` (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`) pass to + the direction-tied and distributed kernels; the progressive law refuses a + non-neutral law. Shape ``(n_wires, n_steps)``. ``sigma_total = sigma_A + sigma_B + sigma_f``. Curvatures are axial-strain-gradient components, not rotation-curvature @@ -585,6 +595,12 @@ def _wire_stress_series( raise CableInputError( "progressive settings require friction_model='progressive'" ) + law = active_friction_law(friction_law) + if law is not None and friction_model == "progressive": + raise CableInputError( + "a friction law acts on the single spring-slider per wire; the " + "progressive law is not implemented with it" + ) if friction_model == "progressive": # Progressive (Iwan) split of the direction-tied cap (gap G8). if stick_modulus_Pa is None and _FAST_SLIP: @@ -616,6 +632,8 @@ def _wire_stress_series( stick_modulus_Pa=stick_modulus_Pa, nodes_per_pitch=distributed_nodes_per_pitch, max_increment=distributed_max_increment, + friction_law=law, + time_s=time_s, ) elif stick_modulus_Pa is None and _FAST_SLIP: # Compiled force recursion, identical to wire_slip_history().stress_Pa @@ -626,6 +644,8 @@ def _wire_stress_series( kappa_y, contact_pressure_Pa=contact_pressure_Pa, direction_hold_fraction=direction_hold_fraction, + friction_law=law, + time_s=time_s, ) else: sigma_f_kt = wire_slip_history( @@ -635,6 +655,8 @@ def _wire_stress_series( contact_pressure_Pa=contact_pressure_Pa, stick_modulus_Pa=stick_modulus_Pa, direction_hold_fraction=direction_hold_fraction, + friction_law=law, + time_s=time_s, ).stress_Pa # sigma_A (tension) — [Nasution2014b] Eq. 5: sigma_A = E cos^2 a * N / EA_full. @@ -793,6 +815,8 @@ def wire_stress_field( curvature_gradient: tuple[FloatArray, FloatArray] | None = None, relief: LateralRelief | None = None, keep_friction: bool = False, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> WireStressField: """Recover the shared stress field once, retaining all preceding slip history. @@ -834,8 +858,26 @@ def wire_stress_field( estimate of the relief); it needs ``friction_model="distributed"``, whose bound follows the azimuth along each wire. ``None`` for all three leaves the field of a round wire unchanged, bit for bit. + + ``friction_law`` (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`) + sets a static/dynamic and rate-dependent coefficient of the armour + friction (direction-tied model; static/dynamic only for the distributed + model), with the sample times ``time_s`` when the law needs them. The + termination clamp increment is rate independent and is refused with a + non-neutral law. ``None`` or a neutral law leaves the field unchanged, + bit for bit. """ kx, ky = real_array(kappa_x, "kappa_x"), real_array(kappa_y, "kappa_y") + if ( + active_friction_law(friction_law) is not None + and isinstance(termination, TerminationSpec) + and termination.anchor != "none" + ): + raise CableInputError( + "the termination clamp increment is rate independent; it is not " + "combined with a non-neutral friction law" + ) + friction_law_time_steps(friction_law, time_s, kx.size) # checks the time base unrelieved_spec = layer.spec gradient = None if curvature_gradient is not None: @@ -882,6 +924,8 @@ def wire_stress_field( distributed_max_increment=distributed_max_increment, progressive=progressive, friction_out=friction_parts, + friction_law=friction_law, + time_s=time_s, ) spec = layer.spec increment = None @@ -1109,6 +1153,8 @@ def compute_fatigue( termination: TerminationSpec | Mapping[str, TerminationSpec] | None = None, progressive: ProgressiveFriction | None = None, count_from_sample: int = 0, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> FatigueResult: """Run the per-wire fatigue pipeline over a curvature/tension history. @@ -1195,6 +1241,17 @@ def compute_fatigue( bit for bit as before). Lets a record start from the stress-free section and drop the start-up from the damage. Not available with a contact-life branch. + friction_law : FrictionLaw, optional + Static/dynamic and rate-dependent armour friction coefficient + (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`), for the + direction-tied model and (static/dynamic only) the distributed model; + refused with the progressive model and a termination correction. The + contact-life branches keep their own rate-independent crossing + contact. ``None`` (default) or a neutral law gives the earlier + result, bit for bit. + time_s : numpy.ndarray, optional + Sample times [s] of the history, required by a law that depends on + time (slip rate or a finite healing time). Returns ------- @@ -1415,6 +1472,8 @@ def compute_fatigue( progressive=progressive, keep_friction=layer.component_scf is not None and not layer.component_scf.is_identity, + friction_law=friction_law, + time_s=time_s, ) if field.termination is not None and layer_termination is not None: clamp_summary[name] = _clamp_summary(layer_termination, field.termination) @@ -1687,6 +1746,22 @@ def compute_fatigue( ) if clamp_summary: prov = _termination_provenance(prov, clamp_summary) + law = active_friction_law(friction_law) + if law is not None: + prov = Provenance( + method=prov.method + + f"; armour friction coefficient: friction law ({law.describe()})", + citations=prov.citations, + gates=(*prov.gates, "tests/test_friction_law.py"), + limitations=( + *prov.limitations, + "friction law: no rate-dependent or static/dynamic friction data " + "of armour interfaces is in the validation set; the slip rate of " + "the direction-tied kernel is a representative wire value " + "(r / |sin a| times the plastic strain rate); the crossing " + "contact branches keep the rate-independent coefficient", + ), + ) if count_from: prov = dataclasses.replace( prov, diff --git a/src/cablexsec/api.py b/src/cablexsec/api.py index 3fafa4b..9aa32c0 100644 --- a/src/cablexsec/api.py +++ b/src/cablexsec/api.py @@ -173,6 +173,11 @@ ) from cablexsec.mechanics.core_kinematics import CoreSlipState from cablexsec.mechanics.distributed_friction import DEFAULT_MAX_INCREMENT +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + active_friction_law, + friction_law_time_steps, +) from cablexsec.mechanics.mindlin_contact import TransverseMap from cablexsec.mechanics.mkappa import HelicalLayerSpec from cablexsec.mechanics.papailiou import ( @@ -271,6 +276,7 @@ "ContactQPResult", "CoreFrictionSpec", "CriticalDistanceSpec", + "FrictionLaw", "ProgressiveFriction", "CoreFrictionHistory", # cable -> frozen-spec adapters @@ -455,6 +461,8 @@ class MkappaResult: Frictional work per cable-axis metre accumulated over the complete supplied history [J/m], including initialisation if supplied. Not mechanical work on an open path and not automatically a per-cycle loss. + Under a rate-dependent friction law it includes the rate-dependent + (viscous) part, ``work.viscous_J_per_m``. EI_apparent_Nm2 : float Secant bending stiffness over the loop [N·m²]. EI_max_Nm2, EI_min_Nm2 : float @@ -535,11 +543,23 @@ def run( self, kappa: FloatArray, contact_pressure_Pa: Sequence[FloatArray] | None = None, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> _MkappaRun: """Evaluate the law; ``contact_pressure_Pa`` is one armour ``P1+P2`` history per layer (order of ``layers``), ``None`` for fixed pressure. - The laid-core model keeps its own fixed contact loads.""" + The laid-core model keeps its own fixed contact loads. A non-neutral + ``friction_law`` (armour wires, direction-tied law) is refused with + the progressive law and the laid-core model.""" phi_bend = self.phi_bend + law = active_friction_law(friction_law) + if law is not None and ( + self.progressive is not None or self.core_model is not None + ): + raise CableSchemaError( + "a friction law is implemented for the direction-tied armour law " + "only; not with the progressive law or core friction" + ) if self.progressive is None: res = compute_mkappa_wire_slip_front( self.layers, @@ -547,6 +567,8 @@ def run( phi_bend=phi_bend, EI_min_Nm2=self.ei_min, contact_pressure_Pa=contact_pressure_Pa, + friction_law=law, + time_s=time_s, ) else: res = compute_mkappa_wire_slip_front( @@ -648,6 +670,8 @@ def compute_mkappa( progressive: ProgressiveFriction | None = None, contact_pressure_Pa: Mapping[str, FloatArray] | None = None, contact_tension_history_N: FloatArray | None = None, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> MkappaResult: r"""Moment-curvature hysteresis of a cable over a curvature history. @@ -745,6 +769,20 @@ def compute_mkappa( reference state is the first sample; the wire-yield range check uses the largest tension. Not with ``tension_N``, ``section_state``, ``radial_state`` or ``contact_pressure_Pa``. + friction_law : FrictionLaw, optional + Static/dynamic and rate-dependent armour friction coefficient + (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`) of every + armour wire: a static factor until a wire slips, a dynamic factor + while it slips and after it until it has stuck for the healing time, + and a logarithmic and viscous rate term. Only with the + direction-tied law and without ``core_friction``. ``work`` then + carries the rate-dependent dissipation in ``viscous_J_per_m``. + ``None`` (default) or a neutral law is the rate-independent law, bit + for bit. + time_s : numpy.ndarray, optional + Sample times [s] of ``kappa_history``, required by a law that depends + on time (a slip rate or a finite positive healing time); refused + otherwise. Returns ------- @@ -805,6 +843,20 @@ def compute_mkappa( if friction_model == "progressive" else None ) + if friction_law is not None and not isinstance(friction_law, FrictionLaw): + raise CableSchemaError("friction_law must be a FrictionLaw or None.") + law = active_friction_law(friction_law) + if law is not None and ( + friction_model != "direction_tied" or core_friction not in (None, False) + ): + raise CableSchemaError( + "a friction law is implemented for the direction-tied armour law " + "only; not with the progressive law or core friction" + ) + try: + friction_law_time_steps(law, time_s, kappa.size) + except CableInputError as error: + raise CableSchemaError(str(error)) from error tension_history = None if contact_tension_history_N is not None: if ( @@ -863,7 +915,7 @@ def compute_mkappa( pressure_history = _mkappa_pressure_history( contact_pressure_Pa, names, kappa.shape ) - law = _prepare_mkappa_law( + mkappa_law = _prepare_mkappa_law( cable, tension_N, mu=mu, @@ -910,11 +962,13 @@ def compute_mkappa( except (ValueError, KeyError): pass # no yield-strength armour: no curvature bound to check - run = law.run( + run = mkappa_law.run( kappa, None if pressure_history is None else [pressure_history[name] for name in names], + friction_law=law, + time_s=time_s, ) res, moment, work, ei_max = run.armour, run.moment_Nm, run.work, run.EI_max_Nm2 w_diss, core_history = run.W_diss_J_per_m, run.core_history @@ -924,6 +978,8 @@ def compute_mkappa( else "; progressive (Iwan) armour friction law, " + progressive_settings.describe() ) + if law is not None: + law_extra += "; armour friction law: " + law.describe() history_extra = ( "" if pressure_history is None @@ -943,7 +999,7 @@ def compute_mkappa( "contact loads and the wire-yield check use the reference state", ) ) - model = law.core_model + model = mkappa_law.core_model if model is None: # Armour-only law: the historical path, bitwise unchanged. method_extra = "" @@ -1027,6 +1083,16 @@ def compute_mkappa( "three-core state depends on the declared filler representation", *limitations_extra, *history_limitations, + *( + () + if law is None + else ( + "friction law: no rate-dependent or static/dynamic " + "friction data of armour interfaces is in the validation " + "set; the wire slip rate is the representative value " + "(r / |sin a|) times the plastic strain rate", + ) + ), ), ), ) @@ -1902,6 +1968,7 @@ def compute_fatigue( mean_stress: MeanStressOption | Mapping[str, MeanStressOption] | None = None, scf: ComponentSCF | Mapping[str, ComponentSCF] | None = None, count_from_sample: int = 0, + friction_law: FrictionLaw | None = None, ) -> FatigueResult: r"""Per-wire fatigue of a cable over a biaxial curvature (and tension) history. @@ -2035,7 +2102,8 @@ def compute_fatigue( for block-weighted damage. time_s : numpy.ndarray, optional Sample times [s] of the curvature record, placing it on the slow time - axis of a multi-node ``ThermalHistory``. + axis of a multi-node ``ThermalHistory``, and the time base of a + time-dependent ``friction_law``. Refused when neither uses it. sn_curves : dict[str, str or SNcurve], optional Bulk S-N curve per armour layer name, replacing the layer's ``bulk_sn`` (a registered name, see @@ -2056,6 +2124,15 @@ def compute_fatigue( stress-free section, and the bulk cycles are counted from this sample on (default 0, every sample, bit for bit as before). Not available with a contact-life branch or with ``section_states``. + friction_law : FrictionLaw, optional + Static/dynamic and rate-dependent armour friction coefficient + (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`), with the + sample times ``time_s`` when it depends on time: the direction-tied + model takes every option, the distributed model the static/dynamic + option; refused with the progressive model and a termination + correction. The crossing contact-life branches keep their + rate-independent coefficient. ``None`` (default) or a neutral law + gives the earlier result, bit for bit. Returns ------- @@ -2110,8 +2187,21 @@ def compute_fatigue( "strain, a frozen contact tension or a separate thermal stress " "conflict with it" ) - elif time_s is not None: - raise CableSchemaError("time_s is used only with a thermal history") + if friction_law is not None and not isinstance(friction_law, FrictionLaw): + raise CableSchemaError("friction_law must be a FrictionLaw or None.") + law = active_friction_law(friction_law) + law_time = law is not None and law.needs_time + if thermal is None and time_s is not None and not law_time: + raise CableSchemaError( + "time_s is used only with a thermal history or a time-dependent " + "friction law" + ) + if law_time: + try: + friction_law_time_steps(law, time_s, kx.size) + except CableInputError as error: + raise CableSchemaError(str(error)) from error + law_time_s = time_s if law_time else None if contact_model is None: contact_model = ( section_states[0].contact_model @@ -2225,6 +2315,8 @@ def compute_fatigue( termination=termination, progressive=progressive, sn_options=(sn_curves, mean_stress, scf), + friction_law=law, + time_s=law_time_s, ) reference_tension = ( @@ -2296,6 +2388,8 @@ def compute_fatigue( termination=termination, progressive=progressive, count_from_sample=count_from_sample, + friction_law=law, + time_s=law_time_s, ) if thermal_notes and result.provenance is not None: result = replace( @@ -2459,6 +2553,8 @@ def _fatigue_from_section_states( termination: TerminationSpec | Mapping[str, TerminationSpec] | None = None, progressive: ProgressiveFriction | None = None, sn_options: tuple[Any, Any, Any] = (None, None, None), + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> FatigueResult: """Use each normal equilibrium for wire stress, stiffness and contact. @@ -2528,6 +2624,8 @@ def _fatigue_from_section_states( partial_slip_cycles=partial_slip_cycles, termination=termination, progressive=progressive, + friction_law=friction_law, + time_s=time_s, ) # Called from compute_fatigue: point the warning at that caller. return _flag_unevaluated_curves(cable, initial, result, stacklevel=4) diff --git a/src/cablexsec/mechanics/distributed_friction.py b/src/cablexsec/mechanics/distributed_friction.py index bac4a1d..1aa7dcf 100644 --- a/src/cablexsec/mechanics/distributed_friction.py +++ b/src/cablexsec/mechanics/distributed_friction.py @@ -85,6 +85,11 @@ from cablexsec._numba import HAVE_NUMBA, njit from cablexsec.exceptions import CableInputError +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + active_friction_law, + friction_law_time_steps, +) if TYPE_CHECKING: from cablexsec.mechanics.mkappa import HelicalLayerSpec @@ -241,12 +246,14 @@ def _solve_capstan_newton( wy: FloatArray, wz: FloatArray, prev: FloatArray, + mfac: FloatArray, ) -> int: """Coupled semismooth Newton for the capstan bound ``b = b(n(v))``. Solves ``n_j - n_{j-1} = h clip(k_hat (z0_j + v_j), -b_j, b_j)`` with - ``b_j = rho g_j + lam (n_j + n_{j-1}) / 2`` directly (the same - equations as the fixed point on ``b``), using the tridiagonal generalised + ``b_j = m_j (rho g_j + lam (n_j + n_{j-1}) / 2)`` directly (the same + equations as the fixed point on ``b``; ``m_j`` the friction-law factor of + the node, one without a law), using the tridiagonal generalised Jacobian. Returns iterations, or -1 (caller falls back to the fixed point). """ n = y.size @@ -262,7 +269,7 @@ def _solve_capstan_newton( gap = math.inf for j in range(n): jm = j - 1 if j > 0 else n - 1 - b[j] = rho * gnode[j] + lam * 0.5 * (nn[j] + nn[jm]) + b[j] = mfac[j] * (rho * gnode[j] + lam * 0.5 * (nn[j] + nn[jm])) if b[j] < 0.0: b[j] = 0.0 excess = abs(khat * (z0[j] + v[j])) - b[j] @@ -280,7 +287,8 @@ def _solve_capstan_newton( else: state = 1.0 if r > 0.0 else -1.0 t = state * b[j] - # Signed capstan: db/dn = lam / 2 on both segments (zero if floored). + # Signed capstan: db/dn = m lam / 2 on both segments (zero if floored). + lm = lam * mfac[j] sm = 1.0 if b[j] > 0.0 else 0.0 sj = sm # The equations are linear for a fixed stick/slip state and sign @@ -300,9 +308,9 @@ def _solve_capstan_newton( d[j] = 2.0 / h + h * khat uc[j] = -1.0 / h else: - la[j] = -(1.0 / h + 0.5 * lam * state * sm) - d[j] = 2.0 / h + 0.5 * lam * state * (sm - sj) - uc[j] = -(1.0 / h - 0.5 * lam * state * sj) + la[j] = -(1.0 / h + 0.5 * lm * state * sm) + d[j] = 2.0 / h + 0.5 * lm * state * (sm - sj) + uc[j] = -(1.0 / h - 0.5 * lm * state * sj) if res <= tol or (same and any_elastic and res <= 1e6 * tol): return it if not math.isfinite(res): @@ -539,6 +547,9 @@ def _advance( work: FloatArray, stats: NDArray[np.int64], capstan_newton: bool, + mfac: FloatArray, + law: FloatArray, + lstate: FloatArray, ) -> bool: """One backward-Euler increment to ``(ax, ay, rho)``; False on failure. @@ -547,6 +558,12 @@ def _advance( failure), otherwise by the fixed point alone. ``energy`` accumulates [W_be, D, R]; ``work`` holds N-sized scratch rows. + ``mfac`` is the friction-law factor of every node's bound; ``law`` = + ``[active, m_s, m_d, t_stick, dt]`` and ``lstate`` = rows ``[healed, + timer]`` carry the static/dynamic state. A healed node whose trial + traction leaves its static bound breaks away: its factor becomes ``m_d`` + and the increment is solved again, until no node breaks away (each node + at most once per increment). """ n = u.size y = work[0] @@ -567,6 +584,8 @@ def _advance( la = work[15] uc = work[16] prev = work[17] + broke = work[18] + bend = work[19] # Residual scale: the largest term entering the force differences. scale = 1.0 for j in range(n): @@ -583,6 +602,136 @@ def _advance( if rho > scale: scale = rho tol = 1e-12 * h * scale + law_on = law[0] != 0.0 and law[1] != law[2] + for j in range(n): + broke[j] = 0.0 + for attempt in range(n + 1): + if attempt > 0: + for j in range(n): + v[j] = 0.0 + ncur[j] = nf[j] + if not _solve_increment( + y, + z0, + rho, + gnode, + khat, + lam, + h, + tol, + v, + b, + nn, + la, + d, + uc, + rhs, + dv, + cp, + wy, + wz, + prev, + vn, + vt, + ncur, + stats, + capstan_newton, + mfac, + ): + return False + if not law_on: + break + changed = False + for j in range(n): + if lstate[0, j] != 0.0: + jm = j - 1 if j > 0 else n - 1 + bj = mfac[j] * (rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm])) + if bj < 0.0: + bj = 0.0 + if abs(khat * (z0[j] + v[j])) > bj: + mfac[j] = law[2] + lstate[0, j] = 0.0 + broke[j] = 1.0 + changed = True + if not changed: + break + w_be = 0.0 + diss = 0.0 + rem = 0.0 + for j in range(n): + jm = j - 1 if j > 0 else n - 1 + bj = mfac[j] * (rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm])) + if bj < 0.0: + bj = 0.0 + bend[j] = bj + t = khat * (z0[j] + v[j]) + slipped = False + if t > bj: + t = bj + slipped = True + elif t < -bj: + t = -bj + slipped = True + unew = u[j] + v[j] + dp = (unew - t / khat) - p[j] + diss += h * t * dp + w_be += h * ncur[j] * (enew[j] - e[j]) + dn = ncur[j] - nf[j] + dt = t - tau[j] + rem += 0.5 * h * dn * dn + 0.5 * h * dt * dt / khat + u[j] = unew + p[j] += dp + tau[j] = t + nf[j] = ncur[j] + e[j] = enew[j] + if law_on: + if slipped or broke[j] != 0.0: + lstate[0, j] = 0.0 + lstate[1, j] = 0.0 + mfac[j] = law[2] + elif lstate[0, j] == 0.0: + lstate[1, j] += law[4] + if lstate[1, j] >= law[3]: + lstate[0, j] = 1.0 + mfac[j] = law[1] + energy[0] += w_be + energy[1] += diss + energy[2] += rem + return True + + +@njit(cache=True) +def _solve_increment( + y: FloatArray, + z0: FloatArray, + rho: float, + gnode: FloatArray, + khat: float, + lam: float, + h: float, + tol: float, + v: FloatArray, + b: FloatArray, + nn: FloatArray, + la: FloatArray, + d: FloatArray, + uc: FloatArray, + rhs: FloatArray, + dv: FloatArray, + cp: FloatArray, + wy: FloatArray, + wz: FloatArray, + prev: FloatArray, + vn: FloatArray, + vt: FloatArray, + ncur: FloatArray, + stats: NDArray[np.int64], + capstan_newton: bool, + mfac: FloatArray, +) -> bool: + """Solve the increment ``v`` (and the segment forces ``ncur``) for the + node factors ``mfac``; False if neither scheme converges.""" + n = y.size converged = False if lam > 0.0 and capstan_newton: for j in range(n): @@ -608,6 +757,7 @@ def _advance( wy, wz, prev, + mfac, ) if iters >= 0: if iters > stats[1]: @@ -624,7 +774,7 @@ def _advance( for it in range(0 if converged else _MAX_FIXED_POINT): for j in range(n): jm = j - 1 if j > 0 else n - 1 - b[j] = rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm]) + b[j] = mfac[j] * (rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm])) if b[j] < 0.0: b[j] = 0.0 iters = _solve_fixed_bound( @@ -653,37 +803,7 @@ def _advance( stats[5] += it + 1 converged = True break - if not converged: - return False - w_be = 0.0 - diss = 0.0 - rem = 0.0 - for j in range(n): - jm = j - 1 if j > 0 else n - 1 - bj = rho * gnode[j] + lam * 0.5 * (ncur[j] + ncur[jm]) - if bj < 0.0: - bj = 0.0 - t = khat * (z0[j] + v[j]) - if t > bj: - t = bj - elif t < -bj: - t = -bj - unew = u[j] + v[j] - dp = (unew - t / khat) - p[j] - diss += h * t * dp - w_be += h * ncur[j] * (enew[j] - e[j]) - dn = ncur[j] - nf[j] - dt = t - tau[j] - rem += 0.5 * h * dn * dn + 0.5 * h * dt * dt / khat - u[j] = unew - p[j] += dp - tau[j] = t - nf[j] = ncur[j] - e[j] = enew[j] - energy[0] += w_be - energy[1] += diss - energy[2] += rem - return True + return converged @njit(cache=True) @@ -703,6 +823,8 @@ def _distributed_kernel( capstan_newton: bool = True, record_index: NDArray[np.int64] | None = None, kinematics: FloatArray | None = None, + law: FloatArray | None = None, + dt_path: FloatArray | None = None, ) -> tuple[FloatArray, FloatArray, FloatArray, NDArray[np.int64], FloatArray]: """Normalised wire force history. @@ -716,6 +838,11 @@ def _distributed_kernel( ``kinematics`` (kept samples, 4, N) keep the helix field of chosen samples: the nodal displacement ``u``, the nodal slip ``p``, the slip of the step to the sample ``p - p_before`` and the segment force ``n``. + + ``law`` = ``[m_s, m_d, t_stick]`` (static and dynamic factors, healing + time) and ``dt_path`` (the duration of every sample step, divided equally + among its substeps) switch on the static/dynamic friction law; ``None`` + keeps a unit factor on every node. """ n = gnode.size h = 2.0 * math.pi / n @@ -736,7 +863,20 @@ def _distributed_kernel( snf = np.empty(n) stau = np.empty(n) se = np.empty(n) - work = np.zeros((18, n)) + work = np.zeros((20, n)) + mfac = np.ones(n) + smfac = np.ones(n) + lstate = np.zeros((2, n)) + slstate = np.zeros((2, n)) + lparams = np.zeros(5) + if law is not None: + lparams[0] = 1.0 + lparams[1] = law[0] + lparams[2] = law[1] + lparams[3] = law[2] + for j in range(n): + mfac[j] = law[0] + lstate[0, j] = 1.0 energy = np.zeros(3) senergy = np.zeros(3) stats = np.zeros(7, dtype=np.int64) @@ -763,9 +903,15 @@ def _distributed_kernel( se[j] = e[j] for k in range(3): senergy[k] = energy[k] + for j in range(n): + 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): ok = True + if dt_path is not None: + lparams[4] = dt_path[i] / nsub for s in range(1, nsub + 1): f = s / nsub if not _advance( @@ -787,6 +933,9 @@ def _distributed_kernel( work, stats, capstan_newton, + mfac, + lparams, + lstate, ): ok = False break @@ -800,6 +949,10 @@ def _distributed_kernel( e[j] = se[j] for k in range(3): energy[k] = senergy[k] + for j in range(n): + mfac[j] = smfac[j] + lstate[0, j] = slstate[0, j] + lstate[1, j] = slstate[1, j] nsub *= 2 if not ok: stats[0] = -(i + 1) @@ -813,9 +966,12 @@ def _distributed_kernel( for j in range(n): jm = j - 1 if j > 0 else n - 1 stored += 0.5 * h * (nf[j] * nf[j] + tau[j] * tau[j] / khat) - bj = rho1 * gnode[j] + lam * 0.5 * (nf[j] + nf[jm]) - if bj < 0.0: - bj = 0.0 + if law is None: + bj = rho1 * gnode[j] + lam * 0.5 * (nf[j] + nf[jm]) + if bj < 0.0: + bj = 0.0 + else: + bj = work[19, j] # bound of the last increment if bj > 0.0 and abs(tau[j]) >= bj * (1.0 - 1e-9): n_slip += 1 hist[i, 0] = energy[0] @@ -910,6 +1066,8 @@ def distributed_friction_history( max_increment: float = DEFAULT_MAX_INCREMENT, record_field: bool = False, field_samples: NDArray[np.int64] | None = None, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> DistributedFrictionHistory: """Friction stress of every wire from the distributed helix model [Pa]. @@ -941,6 +1099,19 @@ def distributed_friction_history( Samples (increasing indices) whose helix field of displacement, slip and force is kept (``kinematic_field``). The results are otherwise unchanged. + friction_law : FrictionLaw, optional + Static/dynamic friction law + (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`): every helix + node carries its own factor ``m_s`` or ``m_d`` on the whole bound + ``m (rho g + lam n)`` and its own stick timer. A healed node whose + trial traction leaves its static bound breaks away and the increment + is solved again with the dynamic factor (each node at most once per + increment). Rate-dependent terms are not implemented for this model + and are refused. ``None`` or a neutral law is the rate-independent + model, bit for bit. + time_s : numpy.ndarray, optional + Sample times [s] for a finite positive healing time; each sample step + is divided equally among its substeps. """ kx = np.ascontiguousarray(kappa_x, dtype=np.float64) ky = np.ascontiguousarray(kappa_y, dtype=np.float64) @@ -957,6 +1128,14 @@ def distributed_friction_history( count = kx.size n_nodes = _validated_nodes(spec, nodes_per_pitch) increment = _validated_increment(max_increment) + law = active_friction_law(friction_law) + if law is not None and law.rate_dependent: + raise CableInputError( + "the distributed friction model takes the static/dynamic option of a " + "friction law only; rate-dependent terms are implemented for the " + "direction-tied model" + ) + steps = friction_law_time_steps(law, time_s, count) pressure = ( np.full(count, float(spec.contact_pressure_Pa)) if contact_pressure_Pa is None @@ -1014,6 +1193,8 @@ def distributed_friction_history( "reference_pressure_Pa": p_ref, "stress_unit_Pa": stress_unit, } + if law is not None: + params["friction_law"] = law.describe() if zero or stress_unit == 0.0: zeros = np.zeros(count) params.update(kappa_on=math.inf, substeps=0, max_newton=0, max_fixed_point=0) @@ -1057,7 +1238,7 @@ def distributed_friction_history( raise CableInputError( "field samples must be increasing indices of the history" ) - if kept is None: + if kept is None and law is None: out, hist, slip, stats, fld = _distributed_kernel( kx / kappa_c, ky / kappa_c, @@ -1073,7 +1254,8 @@ def distributed_friction_history( bool(record_field), ) kinematics = None - else: + elif law is None: + assert kept is not None index = np.full(count, -1, dtype=np.int64) index[kept] = np.arange(kept.size) kinematics = np.zeros((kept.size, 4, n_nodes)) @@ -1094,6 +1276,31 @@ def distributed_friction_history( index, kinematics, ) + else: + index = np.full(count, -1, dtype=np.int64) + kinematics = None + if kept is not None: + index[kept] = np.arange(kept.size) + kinematics = np.zeros((kept.size, 4, n_nodes)) + out, hist, slip, stats, fld = _distributed_kernel( + kx / kappa_c, + ky / kappa_c, + pressure / p_ref, + khat, + lam, + gnode, + 0.0, + xi, + increment, + wire_index, + np.ascontiguousarray(wire_frac), + bool(record_field), + True, + index, + np.zeros((0, 4, n_nodes)) if kinematics is None else kinematics, + np.array([law.static_factor, law.dynamic_factor, law.stick_time_s]), + np.zeros(count) if steps is None else steps, + ) if stats[0] != 0: raise CableInputError( "distributed friction increment did not converge at sample " @@ -1141,6 +1348,8 @@ def distributed_wire_friction_stress( stick_modulus_Pa: FloatArray | None = None, nodes_per_pitch: int | None = None, max_increment: float = DEFAULT_MAX_INCREMENT, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> FloatArray: """Friction stress [Pa], shape (wires, samples); see :func:`distributed_friction_history`.""" @@ -1152,4 +1361,6 @@ def distributed_wire_friction_stress( stick_modulus_Pa=stick_modulus_Pa, nodes_per_pitch=nodes_per_pitch, max_increment=max_increment, + friction_law=friction_law, + time_s=time_s, ).stress_Pa diff --git a/src/cablexsec/mechanics/fast_slip.py b/src/cablexsec/mechanics/fast_slip.py index 68ed47e..55ed466 100644 --- a/src/cablexsec/mechanics/fast_slip.py +++ b/src/cablexsec/mechanics/fast_slip.py @@ -11,6 +11,12 @@ Work terms are not formed here; callers needing the moment or the energy balance use the reference routine. Regression tests compare the two. + +A non-neutral :class:`~cablexsec.mechanics.friction_law.FrictionLaw` runs a +second kernel with the per-wire static/dynamic state, stick timer and +rate-dependent return of the reference +(:func:`~cablexsec.mechanics.papailiou.wire_slip_history`); ``None`` or a +neutral law keeps the rate-independent kernel, bit for bit. """ from __future__ import annotations @@ -22,8 +28,16 @@ from numpy.typing import NDArray from cablexsec._numba import HAVE_NUMBA, njit +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + _bound, + _slip_magnitude, + active_friction_law, + friction_law_time_steps, +) from cablexsec.mechanics.papailiou import ( DIRECTION_HOLD_FRACTION, + _law_threshold_layer, _threshold_coefficient, ) @@ -142,6 +156,141 @@ def _stress_kernel( return stress +@njit(cache=True) +def _cap_parts( + phi: FloatArray, + angle: float, + pressure: float, + r_helix: float, + n_wires: int, + area: float, + lay_angle: float, + mu: float, + g: FloatArray, + scale: FloatArray, + x: FloatArray, +) -> None: + # Bounds of factor m: scale expm1(m x) (rising), -scale expm1(-m x). + sin_a = abs(math.sin(lay_angle)) + if pressure <= 0.0 or sin_a < 1.0e-12: + for w in range(phi.size): + scale[w] = 0.0 + x[w] = 0.0 + return + width = 2.0 * math.pi * r_helix / n_wires + sigma0 = r_helix * pressure * width * math.cos(lay_angle) / (area * sin_a**2) + for w in range(phi.size): + c = abs(math.cos(phi[w] - angle)) + if c > 1.0: + c = 1.0 + scale[w] = sigma0 * g[w] + x[w] = mu * sin_a * math.asin(c) + + +@njit(cache=True) +def _stress_kernel_law( + kx: FloatArray, + ky: FloatArray, + pressure: FloatArray, + k: float, + phi: FloatArray, + r_helix: float, + area: float, + lay_angle: float, + mu: float, + g: FloatArray, + angle0: float, + threshold_coefficient: float, + dt: FloatArray, + ms: float, + md: float, + t_stick: float, + rc: float, + v0: float, + inv_veta: float, +) -> FloatArray: + n_w = phi.size + n_t = kx.size + stress = np.empty((n_w, n_t)) + dm0 = r_helix * np.cos(phi) + dm1 = r_helix * np.sin(phi) + slip_length = r_helix / abs(math.sin(lay_angle)) + force = np.zeros(n_w) + old_drive = np.zeros(n_w) + healed = np.ones(n_w, dtype=np.bool_) + timer = np.zeros(n_w) + held = angle0 + current = angle0 + held_angle = math.nan + held_pressure = math.nan + scale = np.zeros(n_w) + x_held = np.zeros(n_w) + cur_angle = math.nan + cur_pressure = math.nan + cur_scale = np.zeros(n_w) + x_cur = np.zeros(n_w) + for i in range(n_t): + x = kx[i] + y = ky[i] + p = pressure[i] + if x != 0.0 or y != 0.0: + current = math.atan2(y, x) + threshold = threshold_coefficient * p / k + magnitude = math.sqrt(x * x + y * y) + blend = 0.0 + if magnitude >= threshold: + held = current + else: + blend = magnitude / threshold + if not (held == held_angle and p == held_pressure): + _cap_parts( + phi, held, p, r_helix, n_w, area, lay_angle, mu, g, scale, x_held + ) + held_angle = held + held_pressure = p + if blend > 0.0 and not (current == cur_angle and p == cur_pressure): + _cap_parts( + phi, current, p, r_helix, n_w, area, lay_angle, mu, g, cur_scale, x_cur + ) + cur_angle = current + cur_pressure = p + speed = slip_length / dt[i] + for w in range(n_w): + c0 = (1.0 - blend) * scale[w] + c1 = blend * scale[w] + xh = x_held[w] + xc = x_cur[w] if blend > 0.0 else xh + 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) + 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 + size = abs(trial) + dp = _slip_magnitude( + size, k, md, side, c0, xh, c1, xc, 0.0, speed, rc, v0, inv_veta + ) + if dp > 0.0: + # On the end-of-step bound of the slip rate. + v = speed * dp + m_end = md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) + force[w] = side * _bound(m_end, side, c0, xh, c1, xc, 0.0) + else: + force[w] = trial + healed[w] = False + timer[w] = 0.0 + else: + force[w] = trial + if not healed[w]: + timer[w] += dt[i] + if timer[w] >= t_stick: + healed[w] = True + old_drive[w] = drive + stress[w, i] = force[w] + return stress + + def wire_friction_stress( spec: HelicalLayerSpec, kappa_x: FloatArray, @@ -150,12 +299,15 @@ def wire_friction_stress( contact_pressure_Pa: FloatArray | None = None, initial_bending_angle: float = 0.0, direction_hold_fraction: float = DIRECTION_HOLD_FRACTION, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> FloatArray: """Friction stress [Pa], shape (wires, samples), for a constant stick stiffness. ``direction_hold_fraction`` is the fraction ``f`` of the smallest slip-onset curvature below which the cap direction is held; ``0`` gives the earlier - behaviour. + behaviour. ``friction_law`` and ``time_s`` as for + :func:`~cablexsec.mechanics.papailiou.wire_slip_history`. """ kx = np.ascontiguousarray(kappa_x, dtype=np.float64) ky = np.ascontiguousarray(kappa_y, dtype=np.float64) @@ -169,6 +321,33 @@ def wire_friction_stress( if spec.shape_g is None else np.ascontiguousarray(spec.shape_g, dtype=np.float64) ) + law = active_friction_law(friction_law) + if law is not None: + steps = friction_law_time_steps(law, time_s, kx.size) + return _stress_kernel_law( + kx, + ky, + pressure, + float(spec.k_f), + np.ascontiguousarray(spec.phi_wires, dtype=np.float64), + float(spec.r_helix_m), + float(spec.A_wire_m2), + float(spec.lay_angle_rad), + float(spec.mu), + g, + float(initial_bending_angle), + _threshold_coefficient( + _law_threshold_layer(spec, law), float(direction_hold_fraction) + ), + np.ones(kx.size) if steps is None else steps, + law.static_factor, + law.dynamic_factor, + law.stick_time_s, + law.rate_coefficient, + law.rate_reference_m_per_s, + law.inverse_viscous_velocity, + ) + friction_law_time_steps(None, time_s, kx.size) return _stress_kernel( kx, ky, diff --git a/src/cablexsec/mechanics/friction_law.py b/src/cablexsec/mechanics/friction_law.py new file mode 100644 index 0000000..70449bf --- /dev/null +++ b/src/cablexsec/mechanics/friction_law.py @@ -0,0 +1,596 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +r"""State- and rate-dependent friction coefficient of the armour slip kernels. + +The slip kernels of the package use one rate-independent Coulomb coefficient +``mu`` per contact pair. A :class:`FrictionLaw` replaces it by an effective +coefficient ``m mu`` with a dimensionless factor ``m`` that depends on the +slip state and the slip rate of every wire (direction-tied kernel) or helix +node (distributed kernel). The factor multiplies the coefficient where the +kernel applies it: inside the capstan exponent of the direction-tied bounds +(``sigma_0 g expm1(m lam psi)`` and ``sigma_0 g (1 - exp(-m lam psi))``, +:func:`~cablexsec.mechanics.papailiou.wire_slip_stress_bounds`) and on the +whole node bound ``b = m (rho g + lam n)`` of the distributed model, where +both terms are proportional to ``mu``. + +Static and dynamic coefficient +------------------------------ +``static_factor`` ``m_s`` holds until a wire first slips in a stick episode, +``dynamic_factor`` ``m_d`` while it slips, and ``m_s`` again once it has +stuck for ``stick_time_s`` (the healing time ``t_stick``). Each increment is +a backward-Euler return map with the factor of the end of the step: a wire +whose trial stress leaves the interval of its current factor (``m_s`` if +healed, ``m_d`` otherwise) starts or continues a slip episode, and its stress +is returned to the interval of ``m_d``. With ``m_s > m_d`` the loop shows a +breakaway peak (the stress drops from the static to the dynamic bound in the +step of breakaway). With ``m_s < m_d`` (velocity strengthening) a trial +stress between the two bounds ends the stick episode without slip and the +wire continues elastically up to the dynamic bound. The stick timer counts +the time of the completed stick steps after the last slip step; +``stick_time_s = inf`` (default) never heals, ``0`` heals after one stick +step. + +Rate dependence +--------------- +At slip rate ``v`` the dynamic factor becomes ``m_d R(v)`` with + +.. math:: + + R(v) = 1 + c \ln(1 + v / v_0) + v / v_\eta , + +``c`` = ``rate_coefficient`` (``mu(v) = mu_d (1 + c ln(1 + v/v_0))``: the +logarithmic law with ``mu_0 = mu_d`` and absolute slope ``c mu_d``), +``v_0`` = ``rate_reference_m_per_s`` and ``v_eta`` = +``viscous_velocity_m_per_s``. The last term is a regularised (viscous) +Coulomb law ``t = b sign(v) + eta v`` with ``eta = b / v_eta``: a Perzyna +overstress proportional to the rate-independent bound ``b``, so that the +parameter is a velocity in every kernel and an interface without contact +has no viscous resistance. The return is backward Euler: the slip increment +``dp`` of a slipping wire solves + +.. math:: + + |\sigma^{tr}| - k\, dp = B\big(m_d R(L\, dp / \Delta t)\big), + +``B(m)`` the bound of the side of the trial stress, by a safeguarded Newton +iteration; the left side falls and the right side rises with ``dp``, so the +root is unique and exact for the step (to round-off). Only ``c >= 0`` is +accepted: velocity weakening loses that uniqueness. The rate is that of the +kernel's slip variable in metres per second. The direction-tied kernel slips +in a reduced strain (the plastic part of the wire strain); it is converted +with ``L = r / |sin a|``, the wire length per radian of helix, which turns +the extreme-fibre strain ``r kappa`` into the largest slip displacement of a +freely sliding wire (at the neutral axis, ``r^2 kappa / |sin a|``). This +gives a representative, not a local, slip velocity of the wire. + +Energy. The work ``f dp`` of a slipping wire splits into the rate-independent +friction work ``s B(m_d) dp`` (``s`` the slip sign) and the rate-dependent +(viscous) part ``s [B(m_d R) - B(m_d)] dp``, both non-negative. The +incremental balance ``W = U + D_f + D_v + R`` (input work, stored energy, +friction and viscous dissipation, backward-Euler remainder) holds to +round-off for every law. + +Time base. A rate-dependent law, or a static/dynamic law with a finite +positive healing time, needs the sample times ``time_s`` (finite, strictly +rising). The stress-free start lies one sampling interval ``time_s[1] - +time_s[0]`` before the first sample. Entry points without a time base +refuse such a law. + +Neutral parameters (``m_s = m_d = 1``, ``c = 0``, ``v_eta = inf``) leave +every kernel on its rate-independent code path, bit for bit. +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +from cablexsec._numba import njit +from cablexsec.exceptions import CableInputError + +__all__ = [ + "FrictionLaw", + "SliderHistory", + "active_friction_law", + "friction_law_time_steps", + "slider_history", +] + +FloatArray = NDArray[np.float64] + +#: Largest exponent argument of the bounds (e^700 is finite in binary64). +_EXP_LIMIT = 700.0 +_MAX_NEWTON = 200 + + +@dataclass(frozen=True) +class FrictionLaw: + """Static/dynamic and rate-dependent friction coefficient (module notes). + + Parameters + ---------- + static_factor : float + ``m_s = mu_s / mu``: factor of a healed (sticking) contact, positive. + dynamic_factor : float + ``m_d = mu_d / mu``: factor while the contact slips, positive. + stick_time_s : float + Healing time ``t_stick`` [s] of stick after which the static factor + returns; ``inf`` (default) never heals, ``0`` heals after one stick + step. + rate_coefficient : float + ``c >= 0`` of ``R(v) = 1 + c ln(1 + v/v_0) + v/v_eta``. + rate_reference_m_per_s : float + ``v_0 > 0`` [m/s] of the logarithmic term. + viscous_velocity_m_per_s : float + ``v_eta > 0`` [m/s] of the viscous term (``eta = b / v_eta``); + ``inf`` (default) has no viscous term. + """ + + static_factor: float = 1.0 + dynamic_factor: float = 1.0 + stick_time_s: float = math.inf + rate_coefficient: float = 0.0 + rate_reference_m_per_s: float = 1.0e-3 + viscous_velocity_m_per_s: float = math.inf + + def __post_init__(self) -> None: + values = {} + for name in ( + "static_factor", + "dynamic_factor", + "stick_time_s", + "rate_coefficient", + "rate_reference_m_per_s", + "viscous_velocity_m_per_s", + ): + raw = getattr(self, name) + if isinstance(raw, (bool, np.bool_)) or not isinstance( + raw, (int, float, np.integer, np.floating) + ): + raise CableInputError(f"friction law {name} must be a real number") + values[name] = float(raw) + for name in ("static_factor", "dynamic_factor", "rate_reference_m_per_s"): + if not math.isfinite(values[name]) or values[name] <= 0.0: + raise CableInputError( + f"friction law {name} must be finite and positive" + ) + if math.isnan(values["stick_time_s"]) or values["stick_time_s"] < 0.0: + raise CableInputError("friction law stick_time_s must be >= 0 (or inf)") + rate = values["rate_coefficient"] + if not math.isfinite(rate) or rate < 0.0: + raise CableInputError( + "friction law rate_coefficient must be finite and >= 0 (velocity " + "weakening makes the backward-Euler return non-unique)" + ) + viscous = values["viscous_velocity_m_per_s"] + if math.isnan(viscous) or viscous <= 0.0: + raise CableInputError( + "friction law viscous_velocity_m_per_s must be positive (or inf)" + ) + for name, value in values.items(): + object.__setattr__(self, name, value) + + @property + def state_dependent(self) -> bool: + """True when the static and dynamic factors differ.""" + return self.static_factor != self.dynamic_factor + + @property + def rate_dependent(self) -> bool: + """True when ``R(v)`` is not identically one.""" + return self.rate_coefficient > 0.0 or math.isfinite( + self.viscous_velocity_m_per_s + ) + + @property + def is_neutral(self) -> bool: + """True when the law reproduces the rate-independent coefficient.""" + return ( + self.static_factor == 1.0 + and self.dynamic_factor == 1.0 + and not self.rate_dependent + ) + + @property + def needs_time(self) -> bool: + """True when the law needs the sample times of the history.""" + healing = self.state_dependent and 0.0 < self.stick_time_s < math.inf + return self.rate_dependent or healing + + @property + def minimum_factor(self) -> float: + """Smallest factor the law can give (``R >= 1``).""" + return min(self.static_factor, self.dynamic_factor) + + @property + def inverse_viscous_velocity(self) -> float: + """``1 / v_eta`` [s/m] (zero without a viscous term).""" + return 1.0 / self.viscous_velocity_m_per_s + + def rate_factor(self, slip_rate_m_per_s: float | FloatArray) -> FloatArray: + """``R(v)`` at the slip rate magnitude ``v`` [m/s].""" + v = np.abs(np.asarray(slip_rate_m_per_s, dtype=np.float64)) + return np.asarray( + 1.0 + + self.rate_coefficient * np.log1p(v / self.rate_reference_m_per_s) + + v * self.inverse_viscous_velocity + ) + + def describe(self) -> str: + """Short provenance text.""" + parts = [] + if self.state_dependent or self.static_factor != 1.0: + parts.append( + f"static factor {self.static_factor:g}, dynamic factor " + f"{self.dynamic_factor:g}, healing time {self.stick_time_s:g} s" + ) + if self.rate_coefficient > 0.0: + parts.append( + f"logarithmic rate term c = {self.rate_coefficient:g} with " + f"v0 = {self.rate_reference_m_per_s:g} m/s" + ) + if math.isfinite(self.viscous_velocity_m_per_s): + parts.append( + f"viscous term eta = b / {self.viscous_velocity_m_per_s:g} m/s" + ) + return "; ".join(parts) if parts else "neutral (rate-independent Coulomb)" + + +def active_friction_law(friction_law: FrictionLaw | None) -> FrictionLaw | None: + """The law, or ``None`` when it is absent or neutral (checked type).""" + if friction_law is None: + return None + if not isinstance(friction_law, FrictionLaw): + raise CableInputError("friction_law must be a FrictionLaw or None") + return None if friction_law.is_neutral else friction_law + + +def friction_law_time_steps( + friction_law: FrictionLaw | None, time_s: FloatArray | None, count: int +) -> FloatArray | None: + """Step durations [s] of a history for the law, or ``None`` when unused. + + ``dt[0] = time_s[1] - time_s[0]`` (the stress-free start one interval + before the first sample), ``dt[i] = time_s[i] - time_s[i - 1]``. + A law that needs time refuses a missing time base; ``time_s`` without + such a law is refused too (it would have no effect). + """ + law = active_friction_law(friction_law) + needs = law is not None and law.needs_time + if time_s is None: + if needs: + raise CableInputError( + "this friction law depends on time (slip rate or healing time): " + "give the sample times time_s" + ) + return None + if not needs: + raise CableInputError( + "time_s is used only by a rate-dependent friction law or one with a " + "finite positive healing time" + ) + if np.iscomplexobj(time_s): + raise CableInputError("time_s must be real") + t = np.asarray(time_s, dtype=np.float64) + if t.ndim != 1 or t.size != count or count < 2: + raise CableInputError( + "time_s must be a 1-D history matching the curvature samples (>= 2)" + ) + if not np.isfinite(t).all() or np.any(np.diff(t) <= 0.0): + raise CableInputError("time_s must be finite and rise strictly") + return np.ascontiguousarray(np.concatenate(([t[1] - t[0]], np.diff(t)))) + + +# --------------------------------------------------------------------------- # +# Scalar return (compiled with numba when available) # +# --------------------------------------------------------------------------- # +@njit(cache=True) +def _em1(y: float) -> float: + return math.expm1(min(y, _EXP_LIMIT)) + + +@njit(cache=True) +def _bound( + m: float, side: float, c0: float, x0: float, c1: float, x1: float, clin: float +) -> float: + """Bound of factor ``m``: ``c0 E(m x0) + c1 E(m x1) + clin m``. + + ``E(y) = expm1(y)`` on the rising side (``side > 0``) and + ``-expm1(-y)`` on the falling side (signed capstan). + """ + if side > 0.0: + return c0 * _em1(m * x0) + c1 * _em1(m * x1) + clin * m + return -(c0 * math.expm1(-m * x0) + c1 * math.expm1(-m * x1)) + clin * m + + +@njit(cache=True) +def _bound_slope( + m: float, side: float, c0: float, x0: float, c1: float, x1: float, clin: float +) -> float: + if side > 0.0: + return ( + c0 * x0 * math.exp(min(m * x0, _EXP_LIMIT)) + + c1 * x1 * math.exp(min(m * x1, _EXP_LIMIT)) + + clin + ) + return c0 * x0 * math.exp(-m * x0) + c1 * x1 * math.exp(-m * x1) + clin + + +@njit(cache=True) +def _slip_magnitude( + a: float, + k: float, + md: float, + side: float, + c0: float, + x0: float, + c1: float, + x1: float, + clin: float, + speed: float, + rc: float, + v0: float, + inv_veta: float, +) -> float: + """Slip ``dp >= 0`` of ``a - k dp = B(md R(speed dp))`` (zero if none). + + ``a`` is the trial stress magnitude, ``speed`` converts the slip + increment into the slip rate. Safeguarded Newton on ``[0, (a - B)/k]``. + """ + hi = (a - _bound(md, side, c0, x0, c1, x1, clin)) / k + if not hi > 0.0: + return 0.0 + if rc == 0.0 and inv_veta == 0.0: + return hi + lo = 0.0 + span = hi + x = hi + for _ in range(_MAX_NEWTON): + v = speed * x + m = md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) + g = a - k * x - _bound(m, side, c0, x0, c1, x1, clin) + if g == 0.0: + return x + if g > 0.0: + lo = x + else: + hi = x + slope = -k - _bound_slope(m, side, c0, x0, c1, x1, clin) * md * speed * ( + rc / (v0 + v) + inv_veta + ) + xn = x - g / slope + if not (lo < xn < hi): + xn = 0.5 * (lo + hi) + if abs(xn - x) <= 4.0e-16 * span or hi - lo <= 4.0e-16 * span: + return xn + x = xn + return x + + +def _slip_magnitude_array( + a: FloatArray, + k: float, + md: float, + side: FloatArray, + c0: FloatArray, + x0: FloatArray, + c1: FloatArray, + x1: FloatArray, + speed: float, + rc: float, + v0: float, + inv_veta: float, +) -> FloatArray: + """NumPy form of :func:`_slip_magnitude` over a population (reference).""" + + def bound(m: FloatArray) -> FloatArray: + up = c0 * np.expm1(np.minimum(m * x0, _EXP_LIMIT)) + c1 * np.expm1( + np.minimum(m * x1, _EXP_LIMIT) + ) + down = -(c0 * np.expm1(-m * x0) + c1 * np.expm1(-m * x1)) + return np.asarray(np.where(side > 0.0, up, down)) + + def slope(m: FloatArray) -> FloatArray: + up = c0 * x0 * np.exp(np.minimum(m * x0, _EXP_LIMIT)) + c1 * x1 * np.exp( + np.minimum(m * x1, _EXP_LIMIT) + ) + down = c0 * x0 * np.exp(-m * x0) + c1 * x1 * np.exp(-m * x1) + return np.asarray(np.where(side > 0.0, up, down)) + + hi = np.maximum((a - bound(np.full(a.shape, md))) / k, 0.0) + if (rc == 0.0 and inv_veta == 0.0) or not np.any(hi > 0.0): + return np.asarray(hi) + lo = np.zeros_like(hi) + span = hi.copy() + x = hi.copy() + active = hi > 0.0 + for _ in range(_MAX_NEWTON): + v = speed * x + m = md * (1.0 + rc * np.log1p(v / v0) + v * inv_veta) + g = a - k * x - bound(m) + lo = np.where(active & (g > 0.0), x, lo) + hi = np.where(active & (g < 0.0), x, hi) + d = -k - slope(m) * md * speed * (rc / (v0 + v) + inv_veta) + with np.errstate(divide="ignore", invalid="ignore"): + xn = np.where(g == 0.0, x, x - g / d) + bad = ~((lo < xn) & (xn < hi)) & (g != 0.0) + xn = np.where(bad, 0.5 * (lo + hi), xn) + done = ( + (g == 0.0) + | (np.abs(xn - x) <= 4.0e-16 * span) + | (hi - lo <= 4.0e-16 * span) + ) + x = np.where(active, xn, x) + active = active & ~done + if not np.any(active): + break + return np.asarray(x) + + +# --------------------------------------------------------------------------- # +# Single spring-slider # +# --------------------------------------------------------------------------- # +@njit(cache=True) +def _slider_kernel( + drive: FloatArray, + bound: FloatArray, + k: float, + dt: FloatArray, + ms: float, + md: float, + t_stick: float, + rc: float, + v0: float, + inv_veta: float, +) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray, FloatArray]: + """Force, total slip, friction and viscous work, remainder of one slider.""" + n = drive.size + force = np.empty(n) + slip = np.empty(n) + fric = np.empty(n) + visc = np.empty(n) + rem = np.empty(n) + f = 0.0 + p = 0.0 + d_old = 0.0 + healed = True + timer = 0.0 + wf = 0.0 + wv = 0.0 + wr = 0.0 + for i in range(n): + b = bound[i] + trial = f + k * (drive[i] - d_old) + mav = ms if healed else md + lim = mav * b + if trial >= -lim and trial <= lim: + fn = trial + dp = 0.0 + if not healed: + timer += dt[i] + if timer >= t_stick: + healed = True + else: + side = 1.0 if trial > 0.0 else -1.0 + mag = _slip_magnitude( + abs(trial), + k, + md, + side, + 0.0, + 0.0, + 0.0, + 0.0, + b, + 1.0 / dt[i], + rc, + v0, + inv_veta, + ) + fn = trial + if mag > 0.0: + # On the end-of-step bound of the slip rate; the slip closes + # the step. + v = mag / dt[i] + fn = side * md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) * b + mag = (abs(trial) - abs(fn)) / k + dp = side * mag + wf += md * b * mag + wv += (abs(fn) - md * b) * mag + healed = False + timer = 0.0 + wr += (fn - f) * (fn - f) / (2.0 * k) + f = fn + p += dp + d_old = drive[i] + force[i] = f + slip[i] = p + fric[i] = wf + visc[i] = wv + rem[i] = wr + return force, slip, fric, visc, rem + + +@dataclass(frozen=True) +class SliderHistory: + """History of one spring-slider (:func:`slider_history`). + + ``force_N`` and ``slip_m`` (total slip) per sample; cumulative works [J]: + ``input_work_J`` (``sum f dd``), ``stored_J`` (``f^2 / 2k``), + ``friction_J`` (rate-independent part), ``viscous_J`` (rate-dependent + part) and ``remainder_J`` (backward-Euler, ``sum df^2 / 2k``), with + ``balance_J = input - stored - friction - viscous - remainder``. + """ + + force_N: FloatArray + slip_m: FloatArray + input_work_J: FloatArray + stored_J: FloatArray + friction_J: FloatArray + viscous_J: FloatArray + remainder_J: FloatArray + balance_J: FloatArray + + +def slider_history( + displacement_m: FloatArray, + bound_N: float | FloatArray, + stiffness_N_per_m: float, + *, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, +) -> SliderHistory: + """One elastic spring in series with a slider under the friction law. + + The spring of stiffness ``k`` is driven by the displacement history from + a stress-free start; the slider's rate-independent bound ``b`` (constant + or per sample) is scaled by the law's factor, ``|f| <= m b``, with the + viscous term ``f = m_d b sign(v) + (b / v_eta) v`` in slip. The return + map is the one of the armour kernels (module notes), here with a bound + linear in the factor. ``None`` is the rate-independent slider. + """ + if np.iscomplexobj(displacement_m): + raise CableInputError("displacement must be real") + drive = np.ascontiguousarray(displacement_m, dtype=np.float64) + if drive.ndim != 1 or not drive.size or not np.isfinite(drive).all(): + raise CableInputError("displacement must be a finite nonempty 1-D history") + bound = np.ascontiguousarray( + np.broadcast_to(np.asarray(bound_N, dtype=np.float64), drive.shape) + ) + if not np.isfinite(bound).all() or np.any(bound < 0.0): + raise CableInputError("slider bound must be finite and non-negative") + k = float(stiffness_N_per_m) + if not math.isfinite(k) or k <= 0.0: + raise CableInputError("slider stiffness must be finite and positive") + law = active_friction_law(friction_law) + steps = friction_law_time_steps(law, time_s, drive.size) + if law is None: + law = FrictionLaw() + dt = np.ones(drive.size) if steps is None else steps + force, slip, fric, visc, rem = _slider_kernel( + drive, + bound, + k, + dt, + law.static_factor, + law.dynamic_factor, + law.stick_time_s, + law.rate_coefficient, + law.rate_reference_m_per_s, + law.inverse_viscous_velocity, + ) + work = np.cumsum(force * np.diff(drive, prepend=0.0)) + stored = force**2 / (2.0 * k) + return SliderHistory( + force, + slip, + work, + stored, + fric, + visc, + rem, + work - stored - fric - visc - rem, + ) diff --git a/src/cablexsec/mechanics/papailiou.py b/src/cablexsec/mechanics/papailiou.py index 5d49ced..772794f 100644 --- a/src/cablexsec/mechanics/papailiou.py +++ b/src/cablexsec/mechanics/papailiou.py @@ -84,6 +84,7 @@ from __future__ import annotations +import dataclasses import math from collections.abc import Sequence from dataclasses import dataclass @@ -93,6 +94,12 @@ from numpy.typing import NDArray from cablexsec.exceptions import CableInputError +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + _slip_magnitude_array, + active_friction_law, + friction_law_time_steps, +) from cablexsec.mechanics.mkappa import HelicalLayerSpec from cablexsec.mechanics.return_mapping import CoulombElement @@ -275,6 +282,11 @@ class BendingWork: that contribution enters the balance on the input side. Neither it nor the integration remainder is frictional dissipation. Open-path mechanical work must not be reported as loop loss. + + ``viscous_J_per_m`` is the rate-dependent part of the dissipation under a + rate-dependent :class:`~cablexsec.mechanics.friction_law.FrictionLaw` + (``None`` otherwise); ``friction_J_per_m`` is then the rate-independent + part, and the balance subtracts both. """ stored_J_per_m: FloatArray @@ -282,6 +294,14 @@ class BendingWork: endpoint_work_J_per_m: FloatArray integration_remainder_J_per_m: FloatArray balance_residual_J_per_m: FloatArray + viscous_J_per_m: FloatArray | None = None + + @property + def dissipation_J_per_m(self) -> FloatArray: + """Total interface dissipation, friction plus viscous [J/m].""" + if self.viscous_J_per_m is None: + return self.friction_J_per_m + return np.asarray(self.friction_J_per_m + self.viscous_J_per_m) @dataclass(frozen=True) @@ -577,6 +597,8 @@ def compute_mkappa_wire_slip_front( EI_min_Nm2: float = 0.0, progressive: ProgressiveFriction | None = None, contact_pressure_Pa: Sequence[FloatArray | None] | None = None, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> PapailiouWireResult: """Integrate one shared Papailiou return map over physical cable wires. @@ -594,11 +616,23 @@ def compute_mkappa_wire_slip_front( fixed ``contact_pressure_Pa``. The pressure moves only the friction bound; stick stiffness and ``EI_min`` stay those of the layer specifications. ``None`` for the whole argument keeps the fixed-pressure law. + + ``friction_law`` (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`) + and ``time_s`` pass to :func:`wire_slip_history`; a non-neutral law is + refused with ``progressive``. ``work.viscous_J_per_m`` and + ``W_diss_J_per_m`` then include the rate-dependent dissipation. """ kappa = np.asarray(kappa_history, dtype=np.float64) + law = active_friction_law(friction_law) + if law is not None and progressive is not None: + raise CableInputError( + "a friction law acts on the single spring-slider per wire; the " + "progressive law is not implemented with it" + ) moment = np.zeros(kappa.size, dtype=np.float64) slip_fraction = np.zeros(kappa.size, dtype=np.float64) stored, friction, endpoint, remainder = (np.zeros(kappa.size) for _ in range(4)) + viscous = None if law is None or not law.rate_dependent else np.zeros(kappa.size) total_wires = sum(layer.n_wires for layer in layers) or 1 if contact_pressure_Pa is not None and len(contact_pressure_Pa) != len(layers): raise CableInputError("one contact-pressure history (or None) per layer") @@ -613,6 +647,8 @@ def compute_mkappa_wire_slip_front( kappa * math.sin(phi_bend), contact_pressure_Pa=pressure, initial_bending_angle=phi_bend, + friction_law=law, + time_s=time_s, ) slipping: FloatArray | NDArray[np.int64] = history.slipping_count else: @@ -635,26 +671,40 @@ def compute_mkappa_wire_slip_front( friction += history.work.friction_J_per_m endpoint += history.work.endpoint_work_J_per_m remainder += history.work.integration_remainder_J_per_m + if viscous is not None and history.work.viscous_J_per_m is not None: + viscous += history.work.viscous_J_per_m slip_fraction += slipping / total_wires increments = np.diff(kappa, prepend=0.0) moment += EI_min_Nm2 * kappa stored += 0.5 * EI_min_Nm2 * kappa**2 endpoint += np.cumsum(EI_min_Nm2 * kappa * increments) remainder += np.cumsum(0.5 * EI_min_Nm2 * increments**2) + if viscous is None: + work = BendingWork( + stored, + friction, + endpoint, + remainder, + endpoint - stored - friction - remainder, + ) + else: + work = BendingWork( + stored, + friction, + endpoint, + remainder, + endpoint - stored - friction - viscous - remainder, + viscous, + ) + total = work.dissipation_J_per_m return PapailiouWireResult( kappa=kappa, moment_Nm=moment, - W_diss_J_per_m=float(friction[-1]) if friction.size else 0.0, + W_diss_J_per_m=float(total[-1]) if total.size else 0.0, EI_max_Nm2=sum(layer.EI_stick for layer in layers) + EI_min_Nm2, EI_min_Nm2=EI_min_Nm2, slip_fraction=slip_fraction, - work=BendingWork( - stored, - friction, - endpoint, - remainder, - endpoint - stored - friction - remainder, - ), + work=work, ) @@ -689,6 +739,8 @@ def wire_slip_history( initial_bending_angle: float = 0.0, direction_hold_fraction: float = DIRECTION_HOLD_FRACTION, keep_cap: bool = False, + friction_law: FrictionLaw | None = None, + time_s: FloatArray | None = None, ) -> WireSlipHistory: """Shared small-strain, mean-clamping update for bending and bulk fatigue. @@ -749,6 +801,19 @@ def wire_slip_history( much as the distributed bound does, but narrows the stress-drive loop of each wire. Frictional heat uses the distributed dissipation (:func:`~cablexsec.analysis.thermal_coupling.record_friction_work`). + + Friction law. ``friction_law`` + (:class:`~cablexsec.mechanics.friction_law.FrictionLaw`) scales the + coefficient of every wire by its static, dynamic and rate factor: the + bounds become ``sigma0 g expm1(m lam psi)`` and ``sigma0 g (1 - exp(-m lam + psi))`` (blended below the direction threshold as above), each wire keeps + its own stick timer, and the slip rate is ``(r / |sin a|) dp / dt`` with + ``dp`` the increment of the plastic drive (module notes of + :mod:`cablexsec.mechanics.friction_law`). The direction threshold uses + the smallest factor of the law. ``time_s`` gives the sample times when the + law needs them. ``work.viscous_J_per_m`` is the rate-dependent + dissipation of a rate-dependent law. ``None`` or a neutral law keeps the + rate-independent update, bit for bit. """ kx, ky = np.asarray(kappa_x, dtype=float), np.asarray(kappa_y, dtype=float) if ( @@ -762,8 +827,11 @@ def wire_slip_history( ) if not math.isfinite(initial_bending_angle): raise CableInputError("initial bending angle must be finite") + law = active_friction_law(friction_law) + steps = friction_law_time_steps(law, time_s, kx.size) threshold_coefficient = _threshold_coefficient( - layer, float(direction_hold_fraction) + layer if law is None else _law_threshold_layer(layer, law), + float(direction_hold_fraction), ) count = kx.size pressure = ( @@ -785,6 +853,19 @@ def wire_slip_history( raise CableInputError( "nonnegative pressure and positive stiffness are required" ) + if law is not None: + return _law_wire_slip_history( + layer, + kx, + ky, + pressure, + stiffness, + law, + steps, + initial_bending_angle, + threshold_coefficient, + keep_cap, + ) element = CoulombElement(k=float(stiffness[0]), shape=(layer.n_wires,)) directions = np.column_stack((np.cos(layer.phi_wires), np.sin(layer.phi_wires))) drive_map = layer.r_helix_m * directions @@ -924,6 +1005,269 @@ def oriented_cap( ) +def _law_threshold_layer(layer: HelicalLayerSpec, law: FrictionLaw) -> HelicalLayerSpec: + """Layer with the smallest coefficient of the law (direction threshold).""" + factor = law.minimum_factor + if factor == 1.0: + return layer + return dataclasses.replace(layer, mu=layer.mu * factor) + + +def _bound_parts( + layer: HelicalLayerSpec, angle: float, load: float +) -> tuple[FloatArray, FloatArray]: + """``(sigma0 g, mu |sin a| psi)`` of every wire: the bounds of factor ``m`` + are ``sigma0 g expm1(m x)`` and ``-sigma0 g expm1(-m x)``.""" + sin_a = abs(math.sin(layer.lay_angle_rad)) + if load <= 0.0 or sin_a < 1.0e-12: + zero = np.zeros(layer.n_wires, dtype=np.float64) + return zero, zero.copy() + width = 2.0 * math.pi * layer.r_helix_m / layer.n_wires + sigma0 = ( + layer.r_helix_m + * load + * width + * math.cos(layer.lay_angle_rad) + / (layer.A_wire_m2 * sin_a**2) + ) + g = ( + np.ones(layer.n_wires, dtype=np.float64) + if layer.shape_g is None + else np.asarray(layer.shape_g, dtype=np.float64) + ) + cphi = np.cos(layer.phi_wires - angle) + psi = np.arcsin(np.clip(np.abs(cphi), 0.0, 1.0)) + scale = np.asarray(sigma0 * g, dtype=np.float64) + x = np.asarray(layer.mu * sin_a * psi, dtype=np.float64) + if ( + scale.shape != (layer.n_wires,) + or not np.isfinite(scale).all() + or np.any(scale < 0) + or not np.isfinite(x).all() + ): + raise CableInputError( + "wire caps must be finite, nonnegative and match the population" + ) + return scale, x + + +def _law_bounds( + factor: FloatArray, + c0: FloatArray, + x0: FloatArray, + c1: FloatArray, + x1: FloatArray, +) -> tuple[FloatArray, FloatArray]: + """Rising and falling bounds of every wire at its factor.""" + upper = c0 * np.expm1(factor * x0) + c1 * np.expm1(factor * x1) + lower = -(c0 * np.expm1(-factor * x0) + c1 * np.expm1(-factor * x1)) + return np.asarray(upper), np.asarray(lower) + + +def _law_wire_slip_history( + layer: HelicalLayerSpec, + kx: FloatArray, + ky: FloatArray, + pressure: FloatArray, + stiffness: FloatArray, + law: FrictionLaw, + steps: FloatArray | None, + initial_bending_angle: float, + threshold_coefficient: float, + keep_cap: bool, +) -> WireSlipHistory: + """:func:`wire_slip_history` under a non-neutral friction law (reference).""" + count = kx.size + n_w = layer.n_wires + element = CoulombElement(k=float(stiffness[0]), shape=(n_w,)) + directions = np.column_stack((np.cos(layer.phi_wires), np.sin(layer.phi_wires))) + drive_map = layer.r_helix_m * directions + weight = layer.A_wire_m2 * math.cos(layer.lay_angle_rad) + slip_length = layer.r_helix_m / abs(math.sin(layer.lay_angle_rad)) + stress = np.empty((n_w, count)) + caps = np.empty((n_w, count)) if keep_cap else None + moment = np.empty((count, 2)) + slipping_count = np.empty(count, dtype=np.int64) + stored, friction, viscous, endpoint, remainder, material = ( + np.zeros(count) for _ in range(6) + ) + # friction, viscous, endpoint work, integration remainder, material work + totals = np.zeros(5) + old_drive = np.zeros(n_w) + held = current = initial_bending_angle + healed = np.ones(n_w, dtype=bool) + timer = np.zeros(n_w) + ms, md = law.static_factor, law.dynamic_factor + rc, v0 = law.rate_coefficient, law.rate_reference_m_per_s + inv_veta = law.inverse_viscous_velocity + rate = law.rate_dependent + cache: dict[str, tuple[tuple[float, float] | None, tuple[FloatArray, FloatArray]]] + zero = np.zeros(n_w) + cache = {"held": (None, (zero, zero)), "current": (None, (zero, zero))} + + def parts(slot: str, angle: float, load: float) -> tuple[FloatArray, FloatArray]: + key, value = cache[slot] + if key != (angle, load): + value = _bound_parts(layer, angle, load) + cache[slot] = ((angle, load), value) + return value + + with np.errstate(over="raise", invalid="raise", divide="raise"): + try: + for index, (x, y) in enumerate(zip(kx, ky, strict=True)): + current_stiffness = float(stiffness[index]) + if current_stiffness != element.k: + elastic_strain = element.f / element.k + totals[4] += ( + 0.5 + * weight + * (current_stiffness - element.k) + * (elastic_strain**2).sum() + ) + element.set_stiffness(current_stiffness) + old_stress = element.f + load = float(pressure[index]) + if x != 0 or y != 0: + current = math.atan2(y, x) + threshold = threshold_coefficient * load / current_stiffness + magnitude = math.sqrt(x * x + y * y) + blend = 0.0 + if magnitude >= threshold: + held = current + else: + blend = magnitude / threshold + scale, x_held = parts("held", held, load) + x_cur = x_held + if blend > 0.0: + x_cur = parts("current", current, load)[1] + c0 = (1.0 - blend) * scale + c1 = blend * scale + drive = drive_map @ np.array([x, y]) + increment = drive - old_drive + if not np.isfinite(increment).all(): + raise CableInputError("derived wire increment must be finite") + k = element.k + trial = element.f + k * increment + available = np.where(healed, ms, md) + upper, lower = _law_bounds(available, c0, x_held, c1, x_cur) + leaves = (trial > upper) | (trial < -lower) + side = np.where(trial > 0.0, 1.0, -1.0) + size = np.abs(trial) + dyn_upper, dyn_lower = _law_bounds( + np.full(n_w, md), c0, x_held, c1, x_cur + ) + dynamic = np.where(side > 0.0, dyn_upper, dyn_lower) + slips = leaves & (size > dynamic) + magnitude_slip = np.zeros(n_w) + if np.any(slips): + dt = 1.0 if steps is None else float(steps[index]) + with np.errstate(over="ignore", invalid="ignore"): + magnitude_slip[slips] = _slip_magnitude_array( + size[slips], + k, + md, + side[slips], + c0[slips], + x_held[slips], + c1[slips], + x_cur[slips], + slip_length / dt, + rc, + v0, + inv_veta, + ) + # Factor at the end of the step: the available one in stick, + # the dynamic one (times the rate factor) after leaving it. + end_factor = np.where(leaves, md, available) + if rate and np.any(slips): + dt = 1.0 if steps is None else float(steps[index]) + end_factor = np.where( + slips, + md * law.rate_factor(slip_length * magnitude_slip / dt), + end_factor, + ) + end_upper, end_lower = _law_bounds(end_factor, c0, x_held, c1, x_cur) + # A slipping wire sits on its end-of-step bound (exactly, as + # the rate-independent clip); the slip closes the step. + force = np.where( + slips, np.where(side > 0.0, end_upper, -end_lower), trial + ) + slip = np.where(slips, (trial - force) / k, 0.0) + element.f = force + element.slip_total = element.slip_total + slip + stress[:, index] = force + if caps is not None: + caps[:, index] = np.where(force < 0.0, end_lower, end_upper) + moment[index] = weight * (force @ drive_map) + slipping_count[index] = np.count_nonzero(force != trial) + stored[index] = weight * (force**2).sum() / (2 * current_stiffness) + dissipated = weight * (force * slip).sum() + if rate: + coulomb = weight * (dynamic * np.abs(slip))[slips].sum() + totals[0] += coulomb + totals[1] += dissipated - coulomb + else: + totals[0] += dissipated + totals[2] += weight * (force * increment).sum() + totals[3] += ( + weight * ((force - old_stress) ** 2).sum() / (2 * current_stiffness) + ) + ( + friction[index], + viscous[index], + endpoint[index], + remainder[index], + material[index], + ) = totals + # Stick timers: a step that leaves the current interval ends + # the stick episode; completed stick steps count towards + # healing. + dt_stick = 0.0 if steps is None else float(steps[index]) + waiting = ~leaves & ~healed + timer = np.where( + leaves, 0.0, np.where(waiting, timer + dt_stick, timer) + ) + healed = (healed & ~leaves) | (waiting & (timer >= law.stick_time_s)) + old_drive = drive + balance = endpoint + material - stored - friction - viscous - remainder + except FloatingPointError as error: + raise CableInputError( + "wire history exceeds floating-point range" + ) from error + if not all( + np.isfinite(v).all() + for v in ( + stress, + moment, + element.slip_total, + stored, + friction, + viscous, + endpoint, + remainder, + material, + balance, + ) + ): + raise CableInputError("wire history produced nonfinite results") + return WireSlipHistory( + stress, + moment, + slipping_count, + element.slip_total.copy(), + material, + BendingWork( + stored, + friction, + endpoint, + remainder, + balance, + viscous if rate else None, + ), + caps, + ) + + def _station_return( previous: FloatArray, increment: float | FloatArray, diff --git a/tests/test_friction_law.py b/tests/test_friction_law.py new file mode 100644 index 0000000..dd26997 --- /dev/null +++ b/tests/test_friction_law.py @@ -0,0 +1,787 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Static/dynamic and rate-dependent friction law of the armour slip kernels. + +Closed forms on one spring-slider (breakaway peak, velocity strengthening, +healing, steady viscous loop area ``pi eta omega x0^2``, steady logarithmic +rate), the energy identity with the viscous dissipation, neutral parameters +reproducing the rate-independent kernels bit for bit within each code path, +and the compiled direction-tied kernel against the NumPy reference. +""" + +from __future__ import annotations + +import dataclasses +import math + +import numpy as np +import pytest + +import cablexsec as cx +from cablexsec.analysis.bending_law import export_bending_law +from cablexsec.analysis.fatigue import compute_fatigue, wire_stress_field +from cablexsec.analysis.termination import TerminationSpec +from cablexsec.cable_adapters import cable_to_fatigue_layers +from cablexsec.exceptions import CableInputError, CableSchemaError +from cablexsec.mechanics import friction_law as flm +from cablexsec.mechanics.distributed_friction import ( + distributed_friction_history, + distributed_wire_friction_stress, +) +from cablexsec.mechanics.fast_slip import wire_friction_stress +from cablexsec.mechanics.friction_law import ( + FrictionLaw, + active_friction_law, + friction_law_time_steps, + slider_history, +) +from cablexsec.mechanics.mkappa import HelicalLayerSpec +from cablexsec.mechanics.papailiou import ( + compute_mkappa_wire_slip_front, + full_slip_curvature, + wire_slip_history, + wire_slip_stress_bounds, +) + +analytical = pytest.mark.analytical_sanity + +BREAKAWAY = FrictionLaw(static_factor=1.4, dynamic_factor=1.0) +STRENGTHENING = FrictionLaw(static_factor=0.8, dynamic_factor=1.15, stick_time_s=0.3) +RATE = FrictionLaw( + rate_coefficient=0.08, + rate_reference_m_per_s=2.0e-5, + viscous_velocity_m_per_s=4.0e-4, +) +COMBINED = FrictionLaw( + static_factor=1.25, + dynamic_factor=0.9, + stick_time_s=0.2, + rate_coefficient=0.05, + rate_reference_m_per_s=1.0e-5, + viscous_velocity_m_per_s=1.0e-3, +) +LAWS = [BREAKAWAY, STRENGTHENING, RATE, COMBINED] + + +def _spec(n_wires: int = 12, shape: bool = True) -> HelicalLayerSpec: + g = None + if shape: + phi = 2 * np.pi * np.arange(n_wires) / n_wires + g = 1.0 + 0.3 * np.cos(phi) + return HelicalLayerSpec( + n_wires=n_wires, + r_helix_m=0.05, + lay_angle_rad=0.4, + E_wire_Pa=2.0e11, + A_wire_m2=2.0e-5, + xi=0.3, + mu=0.2, + F_n_axi_N=0.0, + shape_g=g, + contact_pressure_Pa=2.0e6, + ) + + +def _history(spec: HelicalLayerSpec, n: int = 1200, seed: int = 4): + rng = np.random.default_rng(seed) + t = np.linspace(0.0, 12.0, n) + big = 3.0 * full_slip_curvature(spec) + kx = big * np.sin(2 * np.pi * 0.25 * t) + 0.01 * big * rng.standard_normal(n) + ky = 0.4 * big * np.sin(2 * np.pi * 0.13 * t) + kx[200:240] = 0.0 + ky[200:240] = 0.0 # held zero curvature: the direction is held + return t, kx, ky + + +def _time(law: FrictionLaw, t: np.ndarray) -> np.ndarray | None: + return t if law.needs_time else None + + +# --------------------------------------------------------------------------- # +# Settings # +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize( + "kwargs", + [ + {"static_factor": 0.0}, + {"dynamic_factor": -1.0}, + {"static_factor": math.inf}, + {"stick_time_s": -1.0}, + {"stick_time_s": math.nan}, + {"rate_coefficient": -0.1}, + {"rate_coefficient": math.inf}, + {"rate_reference_m_per_s": 0.0}, + {"viscous_velocity_m_per_s": 0.0}, + {"viscous_velocity_m_per_s": math.nan}, + {"static_factor": True}, + {"dynamic_factor": "1"}, + ], +) +def test_settings_are_checked(kwargs): + with pytest.raises(CableInputError): + FrictionLaw(**kwargs) + + +def test_settings_properties(): + neutral = FrictionLaw() + assert neutral.is_neutral and not neutral.needs_time + assert "neutral" in neutral.describe() + assert active_friction_law(None) is None + assert active_friction_law(neutral) is None + assert active_friction_law(BREAKAWAY) is BREAKAWAY + with pytest.raises(CableInputError): + active_friction_law("coulomb") # type: ignore[arg-type] + assert not BREAKAWAY.needs_time # never heals: no time base + assert not FrictionLaw(static_factor=1.2, stick_time_s=0.0).needs_time + assert FrictionLaw(static_factor=1.2, stick_time_s=1.0).needs_time + assert not FrictionLaw(stick_time_s=1.0).needs_time # equal factors + assert RATE.needs_time and RATE.rate_dependent and not RATE.state_dependent + scaled = FrictionLaw(static_factor=1.2, dynamic_factor=1.2) + assert not scaled.is_neutral and "static factor 1.2" in scaled.describe() + assert "viscous" in RATE.describe() and "logarithmic" in RATE.describe() + assert COMBINED.minimum_factor == 0.9 + assert FrictionLaw(static_factor=np.float64(1.1)).static_factor == 1.1 + np.testing.assert_allclose( + RATE.rate_factor(np.array([0.0, 1.0e-4])), + [1.0, 1.0 + 0.08 * math.log1p(5.0) + 0.25], + rtol=1e-15, + ) + + +def test_time_base_is_checked(): + t = np.linspace(0.0, 1.0, 5) + steps = friction_law_time_steps(RATE, t, 5) + assert steps is not None + np.testing.assert_array_equal(steps, np.full(5, 0.25)) + assert friction_law_time_steps(None, None, 5) is None + assert friction_law_time_steps(BREAKAWAY, None, 5) is None + with pytest.raises(CableInputError, match="give the sample times"): + friction_law_time_steps(RATE, None, 5) + with pytest.raises(CableInputError, match="used only"): + friction_law_time_steps(BREAKAWAY, t, 5) + with pytest.raises(CableInputError, match="used only"): + friction_law_time_steps(None, t, 5) + for bad in (t[:4], t[::-1], np.array([0.0, 0.1, 0.1, 0.2, 0.3])): + with pytest.raises(CableInputError): + friction_law_time_steps(RATE, bad, 5) + with pytest.raises(CableInputError, match="real"): + friction_law_time_steps(RATE, t + 0j, 5) + with pytest.raises(CableInputError): + friction_law_time_steps(RATE, np.array([0.0]), 1) + + +# --------------------------------------------------------------------------- # +# One spring-slider: closed forms # +# --------------------------------------------------------------------------- # +@analytical +def test_slider_breakaway_peak(): + """Monotonic loading: elastic to the static bound, then the dynamic bound.""" + k, b, step = 2.0e6, 10.0, 1.0e-7 + drive = step * np.arange(1, 201) + s = slider_history(drive, b, k, friction_law=BREAKAWAY) + first = int(np.argmax(np.abs(s.slip_m) > 0.0)) + np.testing.assert_allclose(s.force_N[:first], k * drive[:first], rtol=1e-14) + peak = s.force_N[first - 1] + assert 1.4 * b - k * step < peak <= 1.4 * b + np.testing.assert_allclose(s.force_N[first:], b, rtol=1e-15) + # The breakaway step releases the overshoot as friction work. + assert abs(s.balance_J).max() <= 1e-14 * s.input_work_J[-1] + assert np.all(s.viscous_J == 0.0) + + +@analytical +def test_slider_velocity_strengthening_has_no_drop(): + k, b, step = 2.0e6, 10.0, 1.0e-7 + drive = step * np.arange(1, 201) + s = slider_history(drive, b, k, friction_law=STRENGTHENING, time_s=drive * 10.0) + assert np.all(np.diff(s.force_N) >= -1e-12 * b) + # Elastic through the static bound, slip only at the dynamic bound. + first = int(np.argmax(np.abs(s.slip_m) > 0.0)) + np.testing.assert_allclose(s.force_N[:first], k * drive[:first], rtol=1e-14) + assert s.force_N[first - 1] > 0.8 * b + np.testing.assert_allclose(s.force_N[first:], 1.15 * b, rtol=1e-15) + + +@analytical +@pytest.mark.parametrize(("hold_s", "heals"), [(0.5, True), (0.1, False)]) +def test_slider_healing_time(hold_s, heals): + """After ``t_stick`` of stick the static bound returns (a second peak).""" + k, b, step = 2.0e6, 10.0, 1.0e-7 + law = FrictionLaw(static_factor=1.4, dynamic_factor=1.0, stick_time_s=0.3) + up = step * np.arange(1, 101) + hold = np.full(int(hold_s / 0.01), up[-1]) + drive = np.concatenate([up, hold, up[-1] + up]) + time = 0.01 * np.arange(drive.size) + s = slider_history(drive, b, k, friction_law=law, time_s=time) + second = s.force_N[up.size + hold.size :] + if heals: + assert second.max() > 1.3 * b + else: + assert second.max() <= b * (1 + 1e-15) + np.testing.assert_allclose(second[-1], b, rtol=1e-15) + + +@analytical +def test_slider_steady_viscous_loop_area(): + """Sinusoidal full slip: viscous work per cycle ``pi eta omega x0^2``.""" + b, k, x0, omega = 1.0, 1.0e10, 1.0e-3, 2 * math.pi + v_eta = 1.0e-3 + time = np.linspace(0.0, 3.0, 30_001) + s = slider_history( + x0 * np.sin(omega * time), + b, + k, + friction_law=FrictionLaw(viscous_velocity_m_per_s=v_eta), + time_s=time, + ) + i0 = int(np.searchsorted(time, 2.0)) + eta = b / v_eta + viscous = s.viscous_J[-1] - s.viscous_J[i0] + friction = s.friction_J[-1] - s.friction_J[i0] + assert viscous == pytest.approx(math.pi * eta * omega * x0**2, rel=1e-6) + assert friction == pytest.approx(4.0 * b * x0, rel=1e-5) + assert abs(s.balance_J).max() <= 1e-13 * s.input_work_J[-1] + + +@analytical +def test_slider_steady_logarithmic_rate(): + """Steady slip at ``v``: the force is ``m_d b R(v)`` (backward Euler exact).""" + b, k, v = 3.0, 1.0e7, 2.0e-4 + law = FrictionLaw( + dynamic_factor=1.1, + static_factor=1.1, + rate_coefficient=0.07, + rate_reference_m_per_s=1.0e-5, + viscous_velocity_m_per_s=5.0e-3, + ) + time = np.linspace(0.0, 1.0, 2001) + s = slider_history(v * time, b, k, friction_law=law, time_s=time) + expected = 1.1 * b * float(law.rate_factor(v)) + np.testing.assert_allclose(s.force_N[-500:], expected, rtol=1e-12) + assert abs(s.balance_J).max() <= 1e-13 * s.input_work_J[-1] + + +@analytical +@pytest.mark.parametrize("law", LAWS) +def test_slider_energy_identity(law): + rng = np.random.default_rng(7) + time = np.cumsum(rng.uniform(0.001, 0.02, 3000)) + drive = 2.0e-5 * np.cumsum(rng.standard_normal(3000)) + bound = 5.0 * (1.0 + 0.3 * np.sin(time)) + s = slider_history(drive, bound, 1.0e6, friction_law=law, time_s=_time(law, time)) + assert np.all(np.diff(s.friction_J) >= 0.0) + assert np.all(np.diff(s.viscous_J) >= -1e-18) + assert abs(s.balance_J).max() <= 1e-12 * max(s.input_work_J.max(), 1e-30) + + +def test_slider_inputs_and_neutral_coulomb(): + drive = 1.0e-5 * np.sin(np.linspace(0.0, 20.0, 400)) + s = slider_history(drive, 2.0, 1.0e6) + # Rate-independent Coulomb return. + f = 0.0 + previous = 0.0 + expected = [] + for d in drive: + f = min(max(f + 1.0e6 * (d - previous), -2.0), 2.0) + previous = d + expected.append(f) + np.testing.assert_allclose(s.force_N, expected, rtol=0, atol=1e-15 * 2.0) + for args in ( + (np.array([np.nan]), 1.0, 1.0), + (np.array([]), 1.0, 1.0), + (drive + 0j, 1.0, 1.0), + (drive, -1.0, 1.0), + (drive, 1.0, 0.0), + ): + with pytest.raises(CableInputError): + slider_history(*args) + + +def test_slip_return_array_matches_scalar(): + """The NumPy reference return and the compiled scalar return agree.""" + rng = np.random.default_rng(2) + n = 400 + side = np.where(rng.random(n) > 0.5, 1.0, -1.0) + c0 = rng.uniform(1e6, 5e7, n) + c1 = rng.uniform(0.0, 1e7, n) + x0 = rng.uniform(0.0, 0.3, n) + x1 = rng.uniform(0.0, 0.3, n) + a = 2.0 * (c0 + c1) * rng.uniform(0.0, 1.0, n) + k, md, speed = 4.0e10, 0.9, 50.0 + vec = flm._slip_magnitude_array( + a, k, md, side, c0, x0, c1, x1, speed, 0.06, 1e-5, 800.0 + ) + sca = np.array( + [ + flm._slip_magnitude( + a[i], + k, + md, + side[i], + c0[i], + x0[i], + c1[i], + x1[i], + 0.0, + speed, + 0.06, + 1e-5, + 800.0, + ) + for i in range(n) + ] + ) + np.testing.assert_allclose(vec, sca, rtol=0, atol=1e-13 * np.max(a) / k) + # Each root satisfies the backward-Euler equation. + v = speed * vec + m = md * (1 + 0.06 * np.log1p(v / 1e-5) + v * 800.0) + up = c0 * np.expm1(m * x0) + c1 * np.expm1(m * x1) + down = -(c0 * np.expm1(-m * x0) + c1 * np.expm1(-m * x1)) + bound = np.where(side > 0, up, down) + slipping = vec > 0 + np.testing.assert_allclose( + (a - k * vec)[slipping], bound[slipping], rtol=1e-12, atol=0 + ) + # Overflowing rates fall back to bisection and stay inside the bracket. + huge = flm._slip_magnitude( + 1e9, 1e9, 1.0, 1.0, 1e8, 0.3, 0.0, 0.0, 0.0, 1e12, 0.0, 1.0, 1e9 + ) + assert 0.0 < huge < (1e9 - 1e8 * math.expm1(0.3)) / 1e9 + + +# --------------------------------------------------------------------------- # +# Direction-tied kernel # +# --------------------------------------------------------------------------- # +def test_neutral_law_is_bitwise(): + spec = _spec() + t, kx, ky = _history(spec) + ref = wire_slip_history(spec, kx, ky) + neutral = wire_slip_history(spec, kx, ky, friction_law=FrictionLaw()) + np.testing.assert_array_equal(neutral.stress_Pa, ref.stress_Pa) + np.testing.assert_array_equal(neutral.moment_Nm, ref.moment_Nm) + np.testing.assert_array_equal( + neutral.work.friction_J_per_m, ref.work.friction_J_per_m + ) + assert neutral.work.viscous_J_per_m is None + np.testing.assert_array_equal( + wire_friction_stress(spec, kx, ky, friction_law=FrictionLaw()), + wire_friction_stress(spec, kx, ky), + ) + with pytest.raises(CableInputError, match="used only"): + wire_friction_stress(spec, kx, ky, time_s=t) + + +@pytest.mark.parametrize("factor", [0.7, 1.3]) +def test_equal_factors_scale_the_coefficient(factor): + """``m_s = m_d = m`` is the rate-independent law with ``m mu``.""" + spec = _spec() + _t, kx, ky = _history(spec) + law = FrictionLaw(static_factor=factor, dynamic_factor=factor) + scaled = dataclasses.replace(spec, mu=spec.mu * factor) + ref = wire_slip_history(scaled, kx, ky) + got = wire_slip_history(spec, kx, ky, friction_law=law) + scale = np.abs(ref.stress_Pa).max() + np.testing.assert_allclose(got.stress_Pa, ref.stress_Pa, rtol=0, atol=1e-12 * scale) + fast = wire_friction_stress(spec, kx, ky, friction_law=law) + np.testing.assert_allclose(fast, ref.stress_Pa, rtol=0, atol=1e-12 * scale) + + +@pytest.mark.parametrize("law", LAWS) +@pytest.mark.parametrize("varying_pressure", [False, True]) +def test_compiled_kernel_matches_reference(law, varying_pressure): + spec = _spec() + t, kx, ky = _history(spec) + pressure = None + if varying_pressure: + pressure = spec.contact_pressure_Pa * ( + 1 + 0.4 * np.sin(np.linspace(0, 9, t.size)) + ) + ref = wire_slip_history( + spec, + kx, + ky, + contact_pressure_Pa=pressure, + friction_law=law, + time_s=_time(law, t), + ) + fast = wire_friction_stress( + spec, + kx, + ky, + contact_pressure_Pa=pressure, + friction_law=law, + time_s=_time(law, t), + ) + scale = np.abs(ref.stress_Pa).max() + np.testing.assert_allclose(fast, ref.stress_Pa, rtol=0, atol=1e-12 * scale) + # The law changes the result (the history slips). + plain = wire_slip_history(spec, kx, ky, contact_pressure_Pa=pressure) + assert np.abs(ref.stress_Pa - plain.stress_Pa).max() > 1e-3 * scale + + +@analytical +@pytest.mark.parametrize("law", LAWS) +def test_kernel_energy_identity(law): + spec = _spec() + t, kx, ky = _history(spec) + h = wire_slip_history(spec, kx, ky, friction_law=law, time_s=_time(law, t)) + work = h.work + assert np.all(np.diff(work.friction_J_per_m) >= 0.0) + if law.rate_dependent: + assert work.viscous_J_per_m is not None + assert work.viscous_J_per_m[-1] > 0.0 + assert np.all( + np.diff(work.viscous_J_per_m) >= -1e-12 * work.viscous_J_per_m[-1] + ) + else: + assert work.viscous_J_per_m is None + scale = work.dissipation_J_per_m[-1] + assert np.abs(work.balance_residual_J_per_m).max() <= 1e-12 * scale + + +@analytical +def test_kernel_energy_identity_with_stiffness_change(): + spec = _spec() + t, kx, ky = _history(spec, n=600) + stiffness = spec.k_f * (1 + 0.2 * (t > 6.0)) + h = wire_slip_history( + spec, kx, ky, stick_modulus_Pa=stiffness, friction_law=COMBINED, time_s=t + ) + assert h.material_work_J_per_m[-1] != 0.0 + scale = h.work.dissipation_J_per_m[-1] + assert np.abs(h.work.balance_residual_J_per_m).max() <= 1e-12 * scale + + +@analytical +def test_kernel_breakaway_peak_at_the_extreme_fibre(): + """Planar monotonic bending: the extreme-fibre wire peaks at its static + capstan bound ``sigma0 g expm1(m_s lam pi/2)`` and drops to the dynamic one.""" + spec = _spec(shape=False) + kappa = np.linspace(0.0, 2.0 * full_slip_curvature(spec), 4001)[1:] + zero = np.zeros_like(kappa) + h = wire_slip_history(spec, kappa, zero, friction_law=BREAKAWAY, keep_cap=True) + wire = h.stress_Pa[0] + static = wire_slip_stress_bounds(dataclasses.replace(spec, mu=1.4 * spec.mu), 0.0)[ + 0 + ][0] + dynamic = wire_slip_stress_bounds(spec, 0.0)[0][0] + step = spec.k_f * spec.r_helix_m * (kappa[1] - kappa[0]) + assert static - step < wire.max() <= static + np.testing.assert_allclose(wire[-1], dynamic, rtol=1e-14) + # The kept cap is the bound of the end of each step. + assert h.cap_Pa is not None + assert np.all(np.abs(h.stress_Pa) <= h.cap_Pa * (1 + 1e-14)) + np.testing.assert_allclose(h.cap_Pa[0, -1], dynamic, rtol=1e-14) + # The strengthening order rises without a drop. + time = np.linspace(0.0, 4.0, kappa.size) + s = wire_slip_history(spec, kappa, zero, friction_law=STRENGTHENING, time_s=time) + assert np.all(np.diff(s.stress_Pa[0]) >= -1e-9 * dynamic) + + +def test_kept_cap_under_a_rate_law(): + spec = _spec() + t, kx, ky = _history(spec, n=400) + h = wire_slip_history(spec, kx, ky, friction_law=RATE, time_s=t, keep_cap=True) + assert h.cap_Pa is not None + slipping = h.cap_Pa * (1 - 1e-12) <= np.abs(h.stress_Pa) + assert slipping.any() + np.testing.assert_allclose( + np.abs(h.stress_Pa)[slipping], h.cap_Pa[slipping], rtol=1e-12 + ) + assert np.all(np.abs(h.stress_Pa) <= h.cap_Pa * (1 + 1e-12) + 1e-9) + + +def test_zero_contact_and_never_slipping_wires(): + spec = dataclasses.replace(_spec(), contact_pressure_Pa=0.0) + t, kx, ky = _history(_spec(), n=200) + h = wire_slip_history(spec, kx, ky, friction_law=COMBINED, time_s=t) + np.testing.assert_array_equal(h.stress_Pa, 0.0) + fast = wire_friction_stress(spec, kx, ky, friction_law=COMBINED, time_s=t) + np.testing.assert_array_equal(fast, 0.0) + assert h.work.viscous_J_per_m is not None + assert np.all(h.work.viscous_J_per_m == 0.0) + # Small curvature: every wire sticks; the law changes nothing. + small = 1e-3 * kx + a = wire_slip_history(_spec(), small, 0 * ky, friction_law=COMBINED, time_s=t) + b = wire_slip_history(_spec(), small, 0 * ky) + np.testing.assert_array_equal(a.stress_Pa, b.stress_Pa) + np.testing.assert_array_equal(a.work.friction_J_per_m, 0.0) + + +def test_rate_law_converges_with_the_time_step(): + """Halving the steps of the same path changes the loop at O(dt).""" + spec = _spec(shape=False) + big = 3.0 * full_slip_curvature(spec) + results = [] + for n in (201, 401, 801): + t = np.linspace(0.0, 4.0, n) + kx = big * np.sin(2 * np.pi * 0.5 * t) + h = wire_slip_history(spec, kx, 0 * kx, friction_law=RATE, time_s=t) + results.append(h.work.dissipation_J_per_m[-1]) + e1, e2 = abs(results[0] - results[1]), abs(results[1] - results[2]) + assert e2 < 0.6 * e1 + assert e2 < 1e-2 * results[2] + + +# --------------------------------------------------------------------------- # +# Distributed kernel (static/dynamic option) # +# --------------------------------------------------------------------------- # +def _short(spec, n=160): + t = np.linspace(0.0, 8.0, n) + big = 3.0 * full_slip_curvature(spec) + return ( + t, + big * np.sin(2 * np.pi * 0.25 * t), + 0.4 * big * np.cos(2 * np.pi * 0.13 * t), + ) + + +def test_distributed_neutral_and_scaled_law(): + spec = _spec() + t, kx, ky = _short(spec) + ref = distributed_friction_history(spec, kx, ky) + neutral = distributed_friction_history(spec, kx, ky, friction_law=FrictionLaw()) + np.testing.assert_array_equal(neutral.stress_Pa, ref.stress_Pa) + np.testing.assert_array_equal(neutral.dissipation_J_per_m, ref.dissipation_J_per_m) + m = 1.25 + law = FrictionLaw(static_factor=m, dynamic_factor=m) + got = distributed_friction_history( + spec, kx, ky, friction_law=law, max_increment=math.inf + ) + exp = distributed_friction_history( + dataclasses.replace(spec, mu=spec.mu * m), kx, ky, max_increment=math.inf + ) + scale = np.abs(exp.stress_Pa).max() + np.testing.assert_allclose(got.stress_Pa, exp.stress_Pa, rtol=0, atol=1e-10 * scale) + np.testing.assert_allclose( + got.dissipation_J_per_m, exp.dissipation_J_per_m, rtol=1e-10 + ) + assert "friction_law" in got.parameters + + +@analytical +@pytest.mark.parametrize( + "law", + [ + BREAKAWAY, + STRENGTHENING, + FrictionLaw(static_factor=1.3, dynamic_factor=0.9, stick_time_s=0.0), + ], +) +def test_distributed_static_dynamic_energy(law): + spec = _spec() + t, kx, ky = _short(spec) + h = distributed_friction_history( + spec, kx, ky, friction_law=law, time_s=_time(law, t), field_samples=[5, 50] + ) + ref = distributed_friction_history(spec, kx, ky) + scale = h.dissipation_J_per_m[-1] + assert np.abs(h.balance_residual_J_per_m).max() <= 1e-12 * scale + assert np.all(np.diff(h.dissipation_J_per_m) >= -1e-14 * scale) + assert ( + np.abs(h.stress_Pa - ref.stress_Pa).max() > 1e-3 * np.abs(ref.stress_Pa).max() + ) + assert h.kinematic_field is not None and h.kinematic_field.shape[0] == 2 + assert np.all(h.slip_fraction >= 0.0) and np.all(h.slip_fraction <= 1.0) + stress = distributed_wire_friction_stress( + spec, kx, ky, friction_law=law, time_s=_time(law, t) + ) + np.testing.assert_array_equal(stress, h.stress_Pa) + + +@analytical +def test_distributed_breakaway_peak(): + """Planar monotonic bending: up to the first slip the static law is the + model with ``m_s mu``; breakaway then lowers the bound below it.""" + spec = _spec(shape=False) + kappa = np.linspace(0.0, 3.0 * full_slip_curvature(spec), 300)[1:] + zero = np.zeros_like(kappa) + static = distributed_friction_history( + dataclasses.replace(spec, mu=1.4 * spec.mu), kappa, zero, max_increment=math.inf + ) + h = distributed_friction_history( + spec, kappa, zero, friction_law=BREAKAWAY, max_increment=math.inf + ) + first = int(np.argmax(static.slip_fraction > 0.0)) + assert first > 1 + scale = np.abs(static.stress_Pa).max() + np.testing.assert_allclose( + h.stress_Pa[:, :first], static.stress_Pa[:, :first], rtol=0, atol=1e-10 * scale + ) + assert h.stress_Pa[0, -1] < static.stress_Pa[0, -1] * (1 - 1e-3) + assert np.abs(h.balance_residual_J_per_m).max() <= 1e-12 * h.dissipation_J_per_m[-1] + + +def test_distributed_refuses_rate_terms(): + spec = _spec() + t, kx, ky = _short(spec, 20) + with pytest.raises(CableInputError, match="static/dynamic option"): + distributed_friction_history(spec, kx, ky, friction_law=RATE, time_s=t) + with pytest.raises(CableInputError, match="give the sample times"): + distributed_friction_history(spec, kx, ky, friction_law=STRENGTHENING) + # No friction: zero stress whatever the law. + free = dataclasses.replace(spec, mu=0.0) + h = distributed_friction_history(free, kx, ky, friction_law=BREAKAWAY) + np.testing.assert_array_equal(h.stress_Pa, 0.0) + + +# --------------------------------------------------------------------------- # +# Entry points # +# --------------------------------------------------------------------------- # +def _menard(): + return cx.load_cable(cx.menard2023_yaml_path(), geometry_override=None) + + +def test_compute_mkappa_with_a_law(): + cable = _menard() + time = np.linspace(0.0, 10.0, 2001) + kappa = 4.0e-3 * np.sin(2 * np.pi * time / 5.0) + ref = cx.compute_mkappa(cable, kappa) + neutral = cx.compute_mkappa(cable, kappa, friction_law=FrictionLaw()) + np.testing.assert_array_equal(neutral.moment_Nm, ref.moment_Nm) + assert neutral.W_diss_J_per_m == ref.W_diss_J_per_m + law = FrictionLaw(static_factor=1.3, dynamic_factor=1.0, stick_time_s=0.5) + r = cx.compute_mkappa(cable, kappa, friction_law=law, time_s=time) + assert ( + np.abs(r.moment_Nm - ref.moment_Nm).max() > 1e-3 * np.abs(ref.moment_Nm).max() + ) + assert r.work is not None + assert np.abs(r.work.balance_residual_J_per_m).max() <= 1e-12 * r.W_diss_J_per_m + assert r.provenance is not None and "friction law" in r.provenance.method + rate = cx.compute_mkappa(cable, kappa, friction_law=RATE, time_s=time) + assert rate.work is not None and rate.work.viscous_J_per_m is not None + assert rate.W_diss_J_per_m == pytest.approx( + rate.work.friction_J_per_m[-1] + rate.work.viscous_J_per_m[-1], rel=1e-15 + ) + assert rate.W_diss_J_per_m > ref.W_diss_J_per_m + assert ( + np.abs(rate.work.balance_residual_J_per_m).max() <= 1e-12 * rate.W_diss_J_per_m + ) + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"friction_law": RATE}, "give the sample times"), + ({"time_s": "t"}, "used only"), + ({"friction_law": BREAKAWAY, "time_s": "t"}, "used only"), + ({"friction_law": BREAKAWAY, "core_friction": True}, "direction-tied"), + ( + {"friction_law": BREAKAWAY, "friction_model": "progressive"}, + "direction-tied", + ), + ({"friction_law": "coulomb"}, "FrictionLaw"), + ], +) +def test_compute_mkappa_refusals(kwargs, match): + cable = _menard() + time = np.linspace(0.0, 1.0, 50) + kappa = 1.0e-3 * np.sin(time) + kwargs = {k: time if v == "t" else v for k, v in kwargs.items()} + with pytest.raises(CableSchemaError, match=match): + cx.compute_mkappa(cable, kappa, **kwargs) + + +def test_mkappa_law_refuses_the_progressive_route(): + spec = _spec() + kappa = np.linspace(0.0, 1e-3, 20) + with pytest.raises(CableInputError, match="progressive"): + compute_mkappa_wire_slip_front( + [spec], + kappa, + progressive=cx.ProgressiveFriction(), + friction_law=BREAKAWAY, + ) + + +def test_compute_fatigue_with_a_law(): + cable = _menard() + time = np.linspace(0.0, 100.0, 400) + kx = 0.02 * np.sin(2 * np.pi * time / 10.0) + ky = np.zeros_like(kx) + ref = cx.compute_fatigue(cable, kx, ky) + neutral = cx.compute_fatigue(cable, kx, ky, friction_law=FrictionLaw()) + for name, damage in ref.D_total_per_wire.items(): + np.testing.assert_array_equal(neutral.D_total_per_wire[name], damage) + got = cx.compute_fatigue(cable, kx, ky, friction_law=RATE, time_s=time) + assert got.provenance is not None and "friction law" in got.provenance.method + changed = any( + not np.array_equal(got.D_total_per_wire[name], damage) + for name, damage in ref.D_total_per_wire.items() + ) + assert changed + with pytest.raises(CableSchemaError, match="give the sample times"): + cx.compute_fatigue(cable, kx, ky, friction_law=RATE) + with pytest.raises(CableSchemaError, match="thermal history or a time-dependent"): + cx.compute_fatigue(cable, kx, ky, friction_law=BREAKAWAY, time_s=time) + with pytest.raises(CableSchemaError, match="FrictionLaw"): + cx.compute_fatigue(cable, kx, ky, friction_law=1.2) # type: ignore[arg-type] + with pytest.raises(CableInputError, match="progressive"): + cx.compute_fatigue( + cable, kx, ky, friction_law=BREAKAWAY, friction_model="progressive" + ) + with pytest.raises(CableInputError, match="static/dynamic option"): + cx.compute_fatigue( + cable, kx, ky, friction_law=RATE, time_s=time, friction_model="distributed" + ) + + +def test_compute_fatigue_section_states_with_a_law(): + cable = cx.load_cable( + cx.inter_array_single_core_yaml_path(), geometry_override=None + ) + time = np.linspace(0.0, 20.0, 12) + kx = 0.04 * np.sin(2 * np.pi * time / 10.0) + ky = np.zeros_like(kx) + tension = np.where(np.arange(time.size) % 2 == 0, 1.0e5, 2.0e5) + ref = cx.compute_fatigue(cable, kx, ky, tension_N=tension, contact_model="qp") + got = cx.compute_fatigue( + cable, + kx, + ky, + tension_N=tension, + contact_model="qp", + friction_law=COMBINED, + time_s=time, + ) + neutral = cx.compute_fatigue( + cable, kx, ky, tension_N=tension, contact_model="qp", friction_law=FrictionLaw() + ) + for name, damage in ref.D_total_per_wire.items(): + np.testing.assert_array_equal(neutral.D_total_per_wire[name], damage) + assert np.all(np.isfinite(got.D_total_per_wire[name])) + + +def test_fatigue_pipeline_refusals(): + cable = _menard() + layers = cable_to_fatigue_layers(cable, contact_tension_N=0) + time = np.linspace(0.0, 10.0, 50) + kx = 0.02 * np.sin(time) + ky = np.zeros_like(kx) + with pytest.raises(CableInputError, match="termination"): + wire_stress_field( + layers[0], + kx, + ky, + termination=TerminationSpec(distance_m=0.1), + friction_law=BREAKAWAY, + ) + with pytest.raises(CableInputError, match="used only"): + wire_stress_field(layers[0], kx, ky, time_s=time) + a = compute_fatigue(layers, kx, ky, friction_law=COMBINED, time_s=time) + b = compute_fatigue(layers, kx, ky) + assert set(a.D_total_per_wire) == set(b.D_total_per_wire) + + +def test_bending_law_export_refuses_a_law(): + cable = _menard() + args = {"tensions_N": [0.0], "kappa_max_1_m": 0.05, "n_points": 20} + with pytest.raises(CableInputError, match="Masing"): + export_bending_law(cable, friction_law=BREAKAWAY, **args) + with pytest.raises(CableInputError, match="Masing"): + export_bending_law(cable, friction_law="coulomb", **args) + with pytest.raises(CableInputError, match="time_s"): + export_bending_law(cable, time_s=np.zeros(20), **args) + neutral = export_bending_law(cable, friction_law=FrictionLaw(), **args) + plain = export_bending_law(cable, **args) + np.testing.assert_array_equal(neutral.moment_Nm, plain.moment_Nm) diff --git a/validation/validation_report.md b/validation/validation_report.md index 0b42c24..3d893dd 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -62,9 +62,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1110 passed, 3111 deselected` -- independent_method: `70 passed, 4151 deselected` -- full_scale: `27 passed, 4194 deselected` +- analytical_sanity: `1130 passed, 3155 deselected` +- independent_method: `70 passed, 4215 deselected` +- full_scale: `27 passed, 4258 deselected` Run `pytest -m ` to reproduce each group. From f2f6271cc9797b8b57afaafc18d639220d0da2c6 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 13:25:10 +0900 Subject: [PATCH 2/4] fix: friction-law return converges for steep rate terms; zero lay angle The slip return of a rate-dependent law took Newton steps from the rate-free root and bisected only when a step left the bracket. With a strong viscous term or a short step the bound rises steeply with the slip, the steps shrink to a vanishing share of the bracket, and after 200 iterations the unconverged iterate was returned: its bound (6.6e100 Pa for a trial stress of 1e8 Pa) became the wire stress. - Scalar (compiled) and NumPy returns: Newton steps only inside the bracket and only while the bracket at least halves every second iteration, bisection otherwise, so the bracket shrinks geometrically however steep the bound. Convergence on the residual at round-off of the trial stress or on the bracket at round-off of the slip itself. An unconverged return is NaN and is refused by every caller (wire_slip_history, wire_friction_stress, slider_history) instead of being consumed. - The end-of-step stress is the bound at the slip, never above the trial stress (_return_stress; the NumPy path clips the same way). - The bound exponent is capped at 600 (was 700) so that capped bounds and slopes stay finite in binary64: no overflow inside the bracket. - A zero lay angle has zero capstan bounds; the law paths divided by sin(a) for the slip length. Both paths now give that layer zero friction under any law, as the existing bound and onset helpers do. - wire_friction_stress refuses a law on a layer without stick stiffness, as the reference does. Tests (all fail before this change): the reported return case and a sweep of 864 extreme rate cases (residual <= 1e-14 of the trial stress, bound between the rate-free bound and the trial stress, NumPy equal to scalar); both kernels with a steep viscous term and 1e-6 s steps (stress within the elastic envelope, kernels agree to 1e-12, energy balance); refusal of an unresolved return; static/dynamic and rate laws on a zero-lay-angle layer, compiled and NumPy. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 4 +- src/cablexsec/mechanics/fast_slip.py | 27 +++- src/cablexsec/mechanics/friction_law.py | 152 +++++++++++++++------ src/cablexsec/mechanics/papailiou.py | 15 ++- tests/test_friction_law.py | 171 ++++++++++++++++++++++++ validation/validation_report.md | 6 +- 6 files changed, 321 insertions(+), 54 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0245eb0..cb40e2d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -42,7 +42,9 @@ All notable changes to CableXSec are recorded in this file. The format follows `stick_time_s`, either order (`mu_s > mu_d` gives a breakaway peak, `mu_s < mu_d` velocity strengthening), times `R(v) = 1 + c ln(1 + v/v0) + v/v_eta` at slip rate `v`. The last term is a regularised Coulomb law `t = b sign(v) + eta v` with `eta = b/v_eta`, solved as a - backward-Euler (Perzyna) return that is exact for each step; `BendingWork.viscous_J_per_m` + backward-Euler (Perzyna) return that is exact for each step (a bracketed Newton iteration + with bisection that converges however steep the rate term is, and a return that does not + converge is refused); `BendingWork.viscous_J_per_m` reports its dissipation and the work balance closes with it to round-off. The direction-tied kernel takes every option (NumPy reference and compiled kernel), the distributed kernel the static/dynamic option; the progressive model, the laid-core friction and the termination diff --git a/src/cablexsec/mechanics/fast_slip.py b/src/cablexsec/mechanics/fast_slip.py index 55ed466..8079455 100644 --- a/src/cablexsec/mechanics/fast_slip.py +++ b/src/cablexsec/mechanics/fast_slip.py @@ -28,9 +28,10 @@ from numpy.typing import NDArray from cablexsec._numba import HAVE_NUMBA, njit +from cablexsec.exceptions import CableInputError from cablexsec.mechanics.friction_law import ( FrictionLaw, - _bound, + _return_stress, _slip_magnitude, active_friction_law, friction_law_time_steps, @@ -214,7 +215,10 @@ def _stress_kernel_law( stress = np.empty((n_w, n_t)) dm0 = r_helix * np.cos(phi) dm1 = r_helix * np.sin(phi) - slip_length = r_helix / abs(math.sin(lay_angle)) + # Slip rate per plastic strain rate; a zero lay angle has no capstan + # friction (zero bounds), so its slip rate does not enter. + sin_a = abs(math.sin(lay_angle)) + slip_length = r_helix / sin_a if sin_a >= 1.0e-12 else 0.0 force = np.zeros(n_w) old_drive = np.zeros(n_w) healed = np.ones(n_w, dtype=np.bool_) @@ -271,11 +275,13 @@ def _stress_kernel_law( dp = _slip_magnitude( size, k, md, side, c0, xh, c1, xc, 0.0, speed, rc, v0, inv_veta ) - if dp > 0.0: + if not dp >= 0.0: + force[w] = math.nan # unresolved return: refused below + elif dp > 0.0: # On the end-of-step bound of the slip rate. - v = speed * dp - m_end = md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) - force[w] = side * _bound(m_end, side, c0, xh, c1, xc, 0.0) + force[w] = side * _return_stress( + size, md, side, c0, xh, c1, xc, 0.0, speed, rc, v0, inv_veta, dp + ) else: force[w] = trial healed[w] = False @@ -324,7 +330,9 @@ def wire_friction_stress( law = active_friction_law(friction_law) if law is not None: steps = friction_law_time_steps(law, time_s, kx.size) - return _stress_kernel_law( + if not float(spec.k_f) > 0.0: + raise CableInputError("a friction law needs a positive stick stiffness") + stress = _stress_kernel_law( kx, ky, pressure, @@ -347,6 +355,11 @@ def wire_friction_stress( law.rate_reference_m_per_s, law.inverse_viscous_velocity, ) + if not np.isfinite(stress).all(): + raise CableInputError( + "the friction-law return did not converge (slip rate out of range)" + ) + return stress friction_law_time_steps(None, time_s, kx.size) return _stress_kernel( kx, diff --git a/src/cablexsec/mechanics/friction_law.py b/src/cablexsec/mechanics/friction_law.py index 70449bf..3f07056 100644 --- a/src/cablexsec/mechanics/friction_law.py +++ b/src/cablexsec/mechanics/friction_law.py @@ -101,9 +101,15 @@ FloatArray = NDArray[np.float64] -#: Largest exponent argument of the bounds (e^700 is finite in binary64). -_EXP_LIMIT = 700.0 -_MAX_NEWTON = 200 +#: Largest exponent argument of the bounds: e^600 times any stress, slope or +#: rate scale of the kernels stays finite in binary64 (a capped bound is far +#: above every trial stress, so the bracket of the return is unchanged). +_EXP_LIMIT = 600.0 +_MAX_NEWTON = 400 +#: Converged residual of the return, relative to the trial stress. +_RESIDUAL = 2.0e-15 +#: Converged bracket, relative to its upper end. +_BRACKET = 4.0e-16 @dataclass(frozen=True) @@ -338,7 +344,16 @@ def _slip_magnitude( """Slip ``dp >= 0`` of ``a - k dp = B(md R(speed dp))`` (zero if none). ``a`` is the trial stress magnitude, ``speed`` converts the slip - increment into the slip rate. Safeguarded Newton on ``[0, (a - B)/k]``. + increment into the slip rate. The residual ``g(dp) = a - k dp - B`` falls + strictly from ``g(0) > 0`` to ``g(hi) <= 0`` at the rate-free root + ``hi = (a - B(md)) / k``, so the root is bracketed. Newton steps are taken + only inside the bracket and only while the bracket at least halves every + second iteration; otherwise the step bisects. The bracket therefore + shrinks geometrically however steep the bound is in ``dp`` (a strong + viscous term or a short step), and the iteration ends when the residual + is at round-off of ``a`` or the bracket at round-off of its upper end + (the slip itself, not the rate-free slip). NaN is + returned if neither is reached (callers refuse it). """ hi = (a - _bound(md, side, c0, x0, c1, x1, clin)) / k if not hi > 0.0: @@ -346,28 +361,55 @@ def _slip_magnitude( if rc == 0.0 and inv_veta == 0.0: return hi lo = 0.0 - span = hi x = hi + previous = 4.0 * hi for _ in range(_MAX_NEWTON): v = speed * x m = md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) g = a - k * x - _bound(m, side, c0, x0, c1, x1, clin) - if g == 0.0: - return x if g > 0.0: + if g <= _RESIDUAL * a: + return x lo = x - else: + elif g == 0.0 or -g <= _RESIDUAL * a: + return x + else: # negative, or not finite: the bound exceeds the trial stress hi = x + width = hi - lo + if width <= _BRACKET * hi: + return lo slope = -k - _bound_slope(m, side, c0, x0, c1, x1, clin) * md * speed * ( rc / (v0 + v) + inv_veta ) xn = x - g / slope - if not (lo < xn < hi): + if not (lo < xn < hi) or width > 0.5 * previous: xn = 0.5 * (lo + hi) - if abs(xn - x) <= 4.0e-16 * span or hi - lo <= 4.0e-16 * span: - return xn + previous = width x = xn - return x + return math.nan + + +@njit(cache=True) +def _return_stress( + a: float, + md: float, + side: float, + c0: float, + x0: float, + c1: float, + x1: float, + clin: float, + speed: float, + rc: float, + v0: float, + inv_veta: float, + dp: float, +) -> float: + """Stress magnitude at the end of a slip step: the bound of the slip rate, + never above the trial stress ``a``.""" + v = speed * dp + m = md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) + return min(_bound(m, side, c0, x0, c1, x1, clin), a) def _slip_magnitude_array( @@ -384,7 +426,11 @@ def _slip_magnitude_array( v0: float, inv_veta: float, ) -> FloatArray: - """NumPy form of :func:`_slip_magnitude` over a population (reference).""" + """NumPy form of :func:`_slip_magnitude` over a population (reference). + + The same bracketed, bisection-safeguarded Newton iteration, element by + element; an element that does not converge is NaN. + """ def bound(m: FloatArray) -> FloatArray: up = c0 * np.expm1(np.minimum(m * x0, _EXP_LIMIT)) + c1 * np.expm1( @@ -403,31 +449,36 @@ def slope(m: FloatArray) -> FloatArray: hi = np.maximum((a - bound(np.full(a.shape, md))) / k, 0.0) if (rc == 0.0 and inv_veta == 0.0) or not np.any(hi > 0.0): return np.asarray(hi) - lo = np.zeros_like(hi) - span = hi.copy() - x = hi.copy() - active = hi > 0.0 - for _ in range(_MAX_NEWTON): - v = speed * x - m = md * (1.0 + rc * np.log1p(v / v0) + v * inv_veta) - g = a - k * x - bound(m) - lo = np.where(active & (g > 0.0), x, lo) - hi = np.where(active & (g < 0.0), x, hi) - d = -k - slope(m) * md * speed * (rc / (v0 + v) + inv_veta) - with np.errstate(divide="ignore", invalid="ignore"): - xn = np.where(g == 0.0, x, x - g / d) - bad = ~((lo < xn) & (xn < hi)) & (g != 0.0) - xn = np.where(bad, 0.5 * (lo + hi), xn) - done = ( - (g == 0.0) - | (np.abs(xn - x) <= 4.0e-16 * span) - | (hi - lo <= 4.0e-16 * span) - ) - x = np.where(active, xn, x) - active = active & ~done - if not np.any(active): - break - return np.asarray(x) + with np.errstate(over="ignore", invalid="ignore", divide="ignore"): + lo = np.zeros_like(hi) + x = hi.copy() + out = np.where(hi > 0.0, np.nan, 0.0) + previous = 4.0 * hi + active = hi > 0.0 + for _ in range(_MAX_NEWTON): + v = speed * x + m = md * (1.0 + rc * np.log1p(v / v0) + v * inv_veta) + g = a - k * x - bound(m) + small = np.abs(g) <= _RESIDUAL * a + done = active & small + out = np.where(done, x, out) + active = active & ~small + rising = active & (g > 0.0) + lo = np.where(rising, x, lo) + hi = np.where(active & ~(g > 0.0), x, hi) + width = hi - lo + closed = active & (width <= _BRACKET * hi) + out = np.where(closed, lo, out) + active = active & ~closed + if not np.any(active): + break + d = -k - slope(m) * md * speed * (rc / (v0 + v) + inv_veta) + xn = x - g / d + bisect = ~((lo < xn) & (xn < hi)) | (width > 0.5 * previous) + xn = np.where(bisect, 0.5 * (lo + hi), xn) + previous = np.where(active, width, previous) + x = np.where(active, xn, x) + return np.asarray(out) # --------------------------------------------------------------------------- # @@ -491,11 +542,26 @@ def _slider_kernel( inv_veta, ) fn = trial - if mag > 0.0: + if not mag >= 0.0: + fn = math.nan # unresolved return: refused by the caller + elif mag > 0.0: # On the end-of-step bound of the slip rate; the slip closes # the step. - v = mag / dt[i] - fn = side * md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta) * b + fn = side * _return_stress( + abs(trial), + md, + side, + 0.0, + 0.0, + 0.0, + 0.0, + b, + 1.0 / dt[i], + rc, + v0, + inv_veta, + mag, + ) mag = (abs(trial) - abs(fn)) / k dp = side * mag wf += md * b * mag @@ -582,6 +648,10 @@ def slider_history( law.rate_reference_m_per_s, law.inverse_viscous_velocity, ) + if not np.isfinite(force).all(): + raise CableInputError( + "the friction-law return did not converge (slip rate out of range)" + ) work = np.cumsum(force * np.diff(drive, prepend=0.0)) stored = force**2 / (2.0 * k) return SliderHistory( diff --git a/src/cablexsec/mechanics/papailiou.py b/src/cablexsec/mechanics/papailiou.py index 772794f..1b43dc5 100644 --- a/src/cablexsec/mechanics/papailiou.py +++ b/src/cablexsec/mechanics/papailiou.py @@ -1083,7 +1083,10 @@ def _law_wire_slip_history( directions = np.column_stack((np.cos(layer.phi_wires), np.sin(layer.phi_wires))) drive_map = layer.r_helix_m * directions weight = layer.A_wire_m2 * math.cos(layer.lay_angle_rad) - slip_length = layer.r_helix_m / abs(math.sin(layer.lay_angle_rad)) + # Slip rate per plastic strain rate. A zero lay angle has no capstan + # friction (zero bounds, :func:`_bound_parts`): its rate does not enter. + sin_a = abs(math.sin(layer.lay_angle_rad)) + slip_length = layer.r_helix_m / sin_a if sin_a >= 1.0e-12 else 0.0 stress = np.empty((n_w, count)) caps = np.empty((n_w, count)) if keep_cap else None moment = np.empty((count, 2)) @@ -1176,6 +1179,11 @@ def parts(slot: str, angle: float, load: float) -> tuple[FloatArray, FloatArray] v0, inv_veta, ) + if not np.isfinite(magnitude_slip).all(): + raise CableInputError( + "the friction-law return did not converge (slip rate " + "out of range)" + ) # Factor at the end of the step: the available one in stick, # the dynamic one (times the rate factor) after leaving it. end_factor = np.where(leaves, md, available) @@ -1189,8 +1197,11 @@ def parts(slot: str, angle: float, load: float) -> tuple[FloatArray, FloatArray] end_upper, end_lower = _law_bounds(end_factor, c0, x_held, c1, x_cur) # A slipping wire sits on its end-of-step bound (exactly, as # the rate-independent clip); the slip closes the step. + # Never above the trial stress (the bound at a converged root). force = np.where( - slips, np.where(side > 0.0, end_upper, -end_lower), trial + slips, + side * np.minimum(np.where(side > 0.0, end_upper, end_lower), size), + trial, ) slip = np.where(slips, (trial - force) / k, 0.0) element.f = force diff --git a/tests/test_friction_law.py b/tests/test_friction_law.py index dd26997..aa489a0 100644 --- a/tests/test_friction_law.py +++ b/tests/test_friction_law.py @@ -785,3 +785,174 @@ def test_bending_law_export_refuses_a_law(): neutral = export_bending_law(cable, friction_law=FrictionLaw(), **args) plain = export_bending_law(cable, **args) np.testing.assert_array_equal(neutral.moment_Nm, plain.moment_Nm) + + +# --------------------------------------------------------------------------- # +# Robustness of the return (steep rate terms, zero lay angle) # +# --------------------------------------------------------------------------- # +def _return_check(a, k, md, side, c0, x0, speed, rc, v0, inv_veta): + """Slip of the scalar and NumPy returns and the bound at that slip.""" + dp = flm._slip_magnitude( + a, k, md, side, c0, x0, 0.0, 0.0, 0.0, speed, rc, v0, inv_veta + ) + v = speed * dp + bound = flm._bound( + md * (1.0 + rc * math.log1p(v / v0) + v * inv_veta), + side, + c0, + x0, + 0.0, + 0.0, + 0.0, + ) + vec = flm._slip_magnitude_array( + np.array([a]), + k, + md, + np.array([side]), + np.array([c0]), + np.array([x0]), + np.zeros(1), + np.zeros(1), + speed, + rc, + v0, + inv_veta, + )[0] + return dp, bound, vec + + +@analytical +def test_return_converges_with_a_steep_viscous_term(): + """A strong viscous term makes the bound rise steeply with the slip; the + return still meets its equation, and the stress stays below the trial.""" + a, k = 1.0e8, 6.0e10 + dp, stress, vec = _return_check(a, k, 1.0, 1.0, 1.0e6, 0.1, 100.0, 0.0, 1e-3, 1e5) + assert math.isfinite(dp) and 0.0 < dp < (a - 1.0e6 * math.expm1(0.1)) / k + assert stress <= a * (1 + 1e-14) + assert abs(a - k * dp - stress) <= 1e-14 * a + assert vec == pytest.approx(dp, rel=1e-12) + # The kernels' end-of-step stress: the bound, never above the trial. + end = flm._return_stress( + a, 1.0, 1.0, 1.0e6, 0.1, 0.0, 0.0, 0.0, 100.0, 0.0, 1e-3, 1e5, dp + ) + assert end == pytest.approx(stress, rel=1e-15) and end <= a + + +@analytical +@pytest.mark.parametrize("side", [1.0, -1.0]) +def test_return_sweep_of_extreme_rate_terms(side): + k, md, v0 = 6.0e10, 0.9, 1.0e-4 + cases = [] + for inv_veta in (0.0, 1.0, 1.0e3, 1.0e6, 1.0e9): + for rc in (0.0, 0.2): + if inv_veta == 0.0 and rc == 0.0: + continue + for speed in (1.0, 1.0e2, 1.0e4, 1.0e6): + for c0 in (1.0e5, 1.0e7): + for x0 in (0.01, 0.1, 0.3): + for ratio in (1.5, 1.0e3): + b0 = flm._bound(md, side, c0, x0, 0.0, 0.0, 0.0) + cases.append((ratio * b0, c0, x0, speed, rc, inv_veta)) + for a, c0, x0, speed, rc, inv_veta in cases: + dp, stress, vec = _return_check(a, k, md, side, c0, x0, speed, rc, v0, inv_veta) + b0 = flm._bound(md, side, c0, x0, 0.0, 0.0, 0.0) + assert math.isfinite(dp) and 0.0 <= dp <= (a - b0) / k + assert b0 <= stress <= a * (1 + 1e-14) + assert abs(a - k * dp - stress) <= 1e-14 * a + assert vec == pytest.approx(dp, rel=1e-12, abs=1e-300) + + +def test_kernels_with_a_steep_viscous_term_and_short_steps(): + spec = _spec() + law = FrictionLaw( + static_factor=1.2, + rate_coefficient=0.5, + rate_reference_m_per_s=1.0e-9, + viscous_velocity_m_per_s=1.0e-9, + ) + n = 400 + t = 1.0e-6 * np.arange(n) + big = 3.0 * full_slip_curvature(spec) + kx = big * np.sin(np.linspace(0.0, 4 * np.pi, n)) + ky = 0.3 * big * np.sin(np.linspace(0.0, 3 * np.pi, n)) + ref = wire_slip_history(spec, kx, ky, friction_law=law, time_s=t) + fast = wire_friction_stress(spec, kx, ky, friction_law=law, time_s=t) + # A spring-slider from rest cannot exceed the elastic stress of its path. + path = np.cumsum(np.hypot(np.diff(kx, prepend=0.0), np.diff(ky, prepend=0.0))) + envelope = spec.k_f * spec.r_helix_m * path + assert np.all(np.abs(ref.stress_Pa) <= envelope * (1 + 1e-12)) + scale = np.abs(ref.stress_Pa).max() + np.testing.assert_allclose(fast, ref.stress_Pa, rtol=0, atol=1e-12 * scale) + assert ref.work.viscous_J_per_m is not None and ref.work.viscous_J_per_m[-1] > 0 + # The steep rate term almost locks the wires: scale by the input work. + total = np.abs(ref.work.endpoint_work_J_per_m).max() + assert np.abs(ref.work.balance_residual_J_per_m).max() <= 1e-12 * total + s = slider_history(1e-3 * np.sin(1e3 * t), 1.0, 1e9, friction_law=law, time_s=t) + assert np.all( + np.abs(s.force_N) + <= 1e9 + * np.cumsum(np.abs(np.diff(1e-3 * np.sin(1e3 * t), prepend=0.0))) + * (1 + 1e-12) + ) + assert abs(s.balance_J).max() <= 1e-12 * s.input_work_J.max() + + +def test_unresolved_returns_are_refused(monkeypatch): + spec = _spec() + t, kx, ky = _history(spec, n=200) + monkeypatch.setattr(flm, "_MAX_NEWTON", 1) + a = np.array([1.0e8]) + out = flm._slip_magnitude_array( + a, + 6e10, + 1.0, + np.ones(1), + np.array([1e6]), + np.array([0.1]), + np.zeros(1), + np.zeros(1), + 100.0, + 0.0, + 1e-3, + 1e5, + ) + assert np.isnan(out).all() + with pytest.raises(CableInputError, match="did not converge"): + wire_slip_history(spec, kx, ky, friction_law=RATE, time_s=t) + monkeypatch.undo() + + import cablexsec.mechanics.fast_slip as fsm + + def unresolved(*args): + return np.full((spec.n_wires, kx.size), np.nan) + + monkeypatch.setattr(fsm, "_stress_kernel_law", unresolved) + with pytest.raises(CableInputError, match="did not converge"): + wire_friction_stress(spec, kx, ky, friction_law=RATE, time_s=t) + + def unresolved_slider(drive, *args): + nan = np.full(drive.size, np.nan) + return nan, nan, nan, nan, nan + + monkeypatch.setattr(flm, "_slider_kernel", unresolved_slider) + with pytest.raises(CableInputError, match="did not converge"): + slider_history(np.ones(3), 1.0, 1.0) + with pytest.raises(CableInputError, match="positive stick stiffness"): + wire_friction_stress( + dataclasses.replace(spec, xi=0.0), kx, ky, friction_law=BREAKAWAY + ) + + +@pytest.mark.parametrize("law", LAWS) +def test_zero_lay_angle_has_no_capstan_friction(law): + """A zero lay angle has zero bounds; a friction law keeps it that way.""" + spec = dataclasses.replace(_spec(), lay_angle_rad=0.0) + t, kx, ky = _history(_spec(), n=300) + plain = wire_slip_history(spec, kx, ky) + np.testing.assert_array_equal(plain.stress_Pa, 0.0) + ref = wire_slip_history(spec, kx, ky, friction_law=law, time_s=_time(law, t)) + np.testing.assert_array_equal(ref.stress_Pa, 0.0) + np.testing.assert_array_equal(ref.work.friction_J_per_m, 0.0) + fast = wire_friction_stress(spec, kx, ky, friction_law=law, time_s=_time(law, t)) + np.testing.assert_array_equal(fast, 0.0) diff --git a/validation/validation_report.md b/validation/validation_report.md index 3d893dd..666200e 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -62,9 +62,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1130 passed, 3155 deselected` -- independent_method: `70 passed, 4215 deselected` -- full_scale: `27 passed, 4258 deselected` +- analytical_sanity: `1133 passed, 3161 deselected` +- independent_method: `70 passed, 4224 deselected` +- full_scale: `27 passed, 4267 deselected` Run `pytest -m ` to reproduce each group. From d420031d49cd3d6e5e9a8c2e750d48385e4c669d Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 14:36:15 +0900 Subject: [PATCH 3/4] fix: friction-law bound on the slip side only; frozen thermal state with a timed law Two values were formed for both sides or consumers where only one is valid. - Direction-tied NumPy reference: the end-of-step bound of a slipping wire was evaluated on both sides at its rate factor. Under a strong viscous term the falling bound saturates at sigma0 g (a valid, finite return) while the rising exponential of the same factor overflows, so wire_slip_history raised for a finite solution (e.g. pressure 2e4 Pa, v_eta = 1e-9 m/s: falling bound 7.95e6 Pa, unused exponent 5401). The new _side_bound evaluates each wire on its own side only (with the scalar form's exponent cap); the kept cap of a slipping wire is that bound, and wires without slip, which carry no rate factor, keep both bounds. The NumPy return iteration evaluates bound and slope on each element's side only as well. The compiled kernel already evaluated one side (_bound). - compute_fatigue: time_s serves a ThermalHistory and a time-dependent friction law. A frozen ThermalState refuses any time_s, so a frozen state with a timed law always failed one of the two checks. The times now go to the friction kernel and, for a frozen state, not to the thermal helper; a frozen state given time_s without a timed law is still refused, and a ThermalHistory still takes the times. Tests (each fails before this change): the reported case on both curvature signs, compiled against the NumPy reference, compressed wires on the saturated bound, stresses within the trial stress, finite kept caps; compute_fatigue with a frozen ThermalState and a rate law, equal to the identical-block ThermalHistory, with the existing refusals. Signed-off-by: Jae Hoon Seo --- src/cablexsec/api.py | 9 ++- src/cablexsec/mechanics/friction_law.py | 51 ++++++++++---- src/cablexsec/mechanics/papailiou.py | 23 +++++-- tests/test_friction_law.py | 88 +++++++++++++++++++++++++ 4 files changed, 152 insertions(+), 19 deletions(-) diff --git a/src/cablexsec/api.py b/src/cablexsec/api.py index 9aa32c0..4de0043 100644 --- a/src/cablexsec/api.py +++ b/src/cablexsec/api.py @@ -2345,8 +2345,15 @@ def compute_fatigue( stick_history = None thermal_notes: tuple[str, ...] = () if thermal is not None: + # time_s serves two consumers: the slow time axis of a ThermalHistory + # and the friction law. A frozen ThermalState has no time axis, so + # times given for the law are not passed to it (alone they are still + # refused by the thermal helper). + thermal_time_s = ( + None if law_time and isinstance(thermal, ThermalState) else time_s + ) inputs = thermal_fatigue_inputs( - cable, layers, kx.size, tension, thermal, time_s=time_s + cable, layers, kx.size, tension, thermal, time_s=thermal_time_s ) if inputs.stick_modulus_Pa is not None and friction_model == "distributed": raise CableSchemaError( diff --git a/src/cablexsec/mechanics/friction_law.py b/src/cablexsec/mechanics/friction_law.py index 3f07056..ddd7014 100644 --- a/src/cablexsec/mechanics/friction_law.py +++ b/src/cablexsec/mechanics/friction_law.py @@ -412,6 +412,33 @@ def _return_stress( return min(_bound(m, side, c0, x0, c1, x1, clin), a) +def _side_bound( + factor: FloatArray, + side: FloatArray, + c0: FloatArray, + x0: FloatArray, + c1: FloatArray, + x1: FloatArray, +) -> FloatArray: + """Bound of every element on its own side at its factor (NumPy). + + ``c0 E(m x0) + c1 E(m x1)`` with ``E = expm1`` on the rising side + (``side > 0``) and ``E(y) = -expm1(-y)`` on the falling side, as + :func:`_bound`. Only the element's own side is evaluated: at a large rate + factor the falling bound saturates while the rising exponential would + overflow. The rising exponent is capped at ``_EXP_LIMIT`` like the scalar + form. + """ + rising = side > 0.0 + up_m = np.where(rising, factor, 0.0) + down_m = np.where(rising, 0.0, factor) + up = c0 * np.expm1(np.minimum(up_m * x0, _EXP_LIMIT)) + c1 * np.expm1( + np.minimum(up_m * x1, _EXP_LIMIT) + ) + down = -(c0 * np.expm1(-down_m * x0) + c1 * np.expm1(-down_m * x1)) + return np.asarray(np.where(rising, up, down)) + + def _slip_magnitude_array( a: FloatArray, k: float, @@ -432,19 +459,21 @@ def _slip_magnitude_array( element; an element that does not converge is NaN. """ + up_side = side > 0.0 + def bound(m: FloatArray) -> FloatArray: - up = c0 * np.expm1(np.minimum(m * x0, _EXP_LIMIT)) + c1 * np.expm1( - np.minimum(m * x1, _EXP_LIMIT) - ) - down = -(c0 * np.expm1(-m * x0) + c1 * np.expm1(-m * x1)) - return np.asarray(np.where(side > 0.0, up, down)) + return _side_bound(m, side, c0, x0, c1, x1) def slope(m: FloatArray) -> FloatArray: - up = c0 * x0 * np.exp(np.minimum(m * x0, _EXP_LIMIT)) + c1 * x1 * np.exp( - np.minimum(m * x1, _EXP_LIMIT) + # Each element on its own side only (the other side's exponential + # can be far out of range at a large rate factor). + mu = np.where(up_side, m, 0.0) + md_ = np.where(up_side, 0.0, m) + up = c0 * x0 * np.exp(np.minimum(mu * x0, _EXP_LIMIT)) + c1 * x1 * np.exp( + np.minimum(mu * x1, _EXP_LIMIT) ) - down = c0 * x0 * np.exp(-m * x0) + c1 * x1 * np.exp(-m * x1) - return np.asarray(np.where(side > 0.0, up, down)) + down = c0 * x0 * np.exp(-md_ * x0) + c1 * x1 * np.exp(-md_ * x1) + return np.asarray(np.where(up_side, up, down)) hi = np.maximum((a - bound(np.full(a.shape, md))) / k, 0.0) if (rc == 0.0 and inv_veta == 0.0) or not np.any(hi > 0.0): @@ -463,8 +492,8 @@ def slope(m: FloatArray) -> FloatArray: done = active & small out = np.where(done, x, out) active = active & ~small - rising = active & (g > 0.0) - lo = np.where(rising, x, lo) + gains = active & (g > 0.0) + lo = np.where(gains, x, lo) hi = np.where(active & ~(g > 0.0), x, hi) width = hi - lo closed = active & (width <= _BRACKET * hi) diff --git a/src/cablexsec/mechanics/papailiou.py b/src/cablexsec/mechanics/papailiou.py index 1b43dc5..ab32420 100644 --- a/src/cablexsec/mechanics/papailiou.py +++ b/src/cablexsec/mechanics/papailiou.py @@ -96,6 +96,7 @@ from cablexsec.exceptions import CableInputError from cablexsec.mechanics.friction_law import ( FrictionLaw, + _side_bound, _slip_magnitude_array, active_friction_law, friction_law_time_steps, @@ -1194,21 +1195,29 @@ def parts(slot: str, angle: float, load: float) -> tuple[FloatArray, FloatArray] md * law.rate_factor(slip_length * magnitude_slip / dt), end_factor, ) - end_upper, end_lower = _law_bounds(end_factor, c0, x_held, c1, x_cur) # A slipping wire sits on its end-of-step bound (exactly, as # the rate-independent clip); the slip closes the step. # Never above the trial stress (the bound at a converged root). - force = np.where( - slips, - side * np.minimum(np.where(side > 0.0, end_upper, end_lower), size), - trial, - ) + # Only the side of the slip is evaluated: at a large rate + # factor the falling bound saturates while the rising + # exponential of the same factor overflows. + end_bound = _side_bound(end_factor, side, c0, x_held, c1, x_cur) + force = np.where(slips, side * np.minimum(end_bound, size), trial) slip = np.where(slips, (trial - force) / k, 0.0) element.f = force element.slip_total = element.slip_total + slip stress[:, index] = force if caps is not None: - caps[:, index] = np.where(force < 0.0, end_lower, end_upper) + # Wires without slip carry no rate factor: both of their + # bounds are in range; a slipping wire's cap is its bound. + still_upper, still_lower = _law_bounds( + np.where(slips, md, end_factor), c0, x_held, c1, x_cur + ) + caps[:, index] = np.where( + slips, + end_bound, + np.where(force < 0.0, still_lower, still_upper), + ) moment[index] = weight * (force @ drive_map) slipping_count[index] = np.count_nonzero(force != trial) stored[index] = weight * (force**2).sum() / (2 * current_stiffness) diff --git a/tests/test_friction_law.py b/tests/test_friction_law.py index aa489a0..91f398a 100644 --- a/tests/test_friction_law.py +++ b/tests/test_friction_law.py @@ -956,3 +956,91 @@ def test_zero_lay_angle_has_no_capstan_friction(law): np.testing.assert_array_equal(ref.work.friction_J_per_m, 0.0) fast = wire_friction_stress(spec, kx, ky, friction_law=law, time_s=_time(law, t)) np.testing.assert_array_equal(fast, 0.0) + + +@pytest.mark.parametrize("sign", [1.0, -1.0]) +def test_saturating_falling_bound_under_a_steep_viscous_term(sign): + """At a large rate factor the falling bound saturates at a finite stress + while the rising exponential of the same factor overflows: only the side + of the slip is evaluated, in both kernels.""" + spec = dataclasses.replace(_spec(shape=False), contact_pressure_Pa=2.0e4) + law = FrictionLaw(viscous_velocity_m_per_s=1.0e-9) + kx = np.array([0.0, sign * 0.01]) + zero = np.zeros(2) + t = np.array([0.0, 1.0]) + ref = wire_slip_history(spec, kx, zero, friction_law=law, time_s=t, keep_cap=True) + fast = wire_friction_stress(spec, kx, zero, friction_law=law, time_s=t) + scale = np.abs(ref.stress_Pa).max() + np.testing.assert_allclose(fast, ref.stress_Pa, rtol=0, atol=1e-12 * scale) + # Wires driven well into compression sit on the saturated falling bound + # sigma0 g (the rate factor is huge); no stress exceeds its trial stress. + saturated, _x = _bound_parts_of(spec) + trial = spec.k_f * spec.r_helix_m * np.abs(np.cos(spec.phi_wires) * kx[1]) + compressed = (ref.stress_Pa[:, -1] < 0.0) & (trial > 2.0 * saturated) + assert compressed.any() + np.testing.assert_allclose( + -ref.stress_Pa[compressed, -1], saturated[compressed], rtol=1e-12 + ) + assert np.all(np.abs(ref.stress_Pa[:, -1]) <= trial * (1 + 1e-12) + 1e-9) + assert ref.cap_Pa is not None and np.isfinite(ref.cap_Pa).all() + np.testing.assert_allclose( + np.abs(ref.stress_Pa[compressed, -1]), ref.cap_Pa[compressed, -1], rtol=1e-12 + ) + + +def _bound_parts_of(spec): + from cablexsec.mechanics.papailiou import _bound_parts + + return _bound_parts(spec, 0.0, spec.contact_pressure_Pa) + + +def test_compute_fatigue_thermal_inputs_with_a_law(): + """time_s serves the thermal history and the law; a frozen ThermalState + takes no times, so the law's times are not passed to it.""" + from cablexsec.analysis.thermal_coupling import ThermalHistory + + cable = cx.load_cable(cx.iea_task49_66kv_yaml_path(), geometry_override=None) + n = 80 + t = np.arange(n, dtype=float) + kx = 0.004 * np.sin(2 * np.pi * t / 10) + ky = 0.002 * np.sin(2 * np.pi * t / 13 + 0.4) + tension = 50e3 + 5e3 * np.sin(2 * np.pi * t / 10) + hot = ThermalHistory.uniform(cable, [0.0, 40.0, 80.0], 45.0) + state = hot.blocks()[0].state + frozen = cx.compute_fatigue( + cable, kx, ky, tension_N=tension, thermal=state, friction_law=RATE, time_s=t + ) + history = cx.compute_fatigue( + cable, kx, ky, tension_N=tension, thermal=hot, friction_law=RATE, time_s=t + ) + plain = cx.compute_fatigue(cable, kx, ky, tension_N=tension, thermal=state) + for name, damage in frozen.D_total_per_wire.items(): + # Identical blocks: the history equals the frozen state. + np.testing.assert_allclose( + history.D_total_per_wire[name], damage, rtol=1e-12, atol=0 + ) + assert any( + not np.array_equal(frozen.D_total_per_wire[name], damage) + for name, damage in plain.D_total_per_wire.items() + ) + # A static law needs no times: the history still takes them, a frozen + # state refuses them (as without a law). + cx.compute_fatigue( + cable, kx, ky, tension_N=tension, thermal=hot, friction_law=BREAKAWAY, time_s=t + ) + with pytest.raises((CableInputError, CableSchemaError), match="time_s"): + cx.compute_fatigue(cable, kx, ky, tension_N=tension, thermal=state, time_s=t) + with pytest.raises((CableInputError, CableSchemaError), match="time_s"): + cx.compute_fatigue( + cable, + kx, + ky, + tension_N=tension, + thermal=state, + friction_law=BREAKAWAY, + time_s=t, + ) + with pytest.raises(CableSchemaError, match="give the sample times"): + cx.compute_fatigue( + cable, kx, ky, tension_N=tension, thermal=state, friction_law=RATE + ) From ba0fda463254b53a922a4d455c369ba65cdd358f Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 15:17:10 +0900 Subject: [PATCH 4/4] validation report: taxonomy counts as the CI runner collects them The parametrised friction-law tests add three more cases than were counted; the three taxonomy lines now give the deselected counts the CI coverage job collects (3164, 4227, 4270). Signed-off-by: Jae Hoon Seo --- validation/validation_report.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/validation/validation_report.md b/validation/validation_report.md index 666200e..e17e713 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -62,9 +62,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1133 passed, 3161 deselected` -- independent_method: `70 passed, 4224 deselected` -- full_scale: `27 passed, 4267 deselected` +- analytical_sanity: `1133 passed, 3164 deselected` +- independent_method: `70 passed, 4227 deselected` +- full_scale: `27 passed, 4270 deselected` Run `pytest -m ` to reproduce each group.