From 22cc7b7f8130515a1cab23f533a4fd628eba38bf Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sun, 22 Nov 2026 00:50:41 +0900 Subject: [PATCH] Laid cores: relative core-core slip as an option of the core law CoreFrictionSpec(core_core_coupling="relative") is a coupled intralayer slip model of laid cores. Neighbouring cores touch at the same axial position, so the friction between them acts on their relative slip, while the filler and ring contacts keep the slip of each core against the plane section. The default, "absolute", is the earlier law and is unchanged, bit for bit. The n stations of the cores at one axial position form a group. A station's stress is an interlayer share, bounded by the Papailiou cap with the interlayer coefficient (mu_cf q_cf + mu_cs q_cs) / q, plus an intralayer share, bounded by sigma_0 mu_cc (q_cc / q) |sin b| min(psi, pi / n), and the intralayer shares of a group sum to zero. The return map is the closest point of the group on that set, exact through a scalar multiplier whose root is found from sorted breakpoints (mechanics/station_coupling.py, a NumPy path and a numba kernel that agree to round-off). For three cores in core-core contact only, slip starts at the same onset, the largest frozen friction stress is 2/3 and the full-slip moment sqrt(3)/2 of the absolute law, and full slip comes at 2 pi / (3 sqrt 3) = 1.209 times the onset instead of pi / 2. An independent field solver of the coupled axial equilibrium of the three cores (validation/scripts/coupled_core_slip_reference.py: one field per core, elastic-Coulomb contacts, semismooth Newton on the incremental energy) gives the same onset, full-slip curvature, moment-curvature, friction-force distribution and reversal loop with and without interlayer friction, to about 7e-5 of the full-slip moment. The core law, compute_mkappa, the bending-law export (group cap and slip transitions), the section properties, the core kinematics and the component states route through the coupled stations; core_station_history, core_station_bounds, core_full_slip_moment and core_full_slip_curvature are new. The relative law is direction-tied: the distributed model raises and "auto" keeps it on a non-planar path with a FrictionModelFallbackWarning. On the 66 kV template at 50 kN (bounded trefoil, 67 % of the core load on core-core contact) the section secant stiffness falls by 2.1-2.8 % between 2 and 10 times the core onset and the exported backbone by 0.5 % at 0.04 1/m; the 30 kV wire-screen bulk damage falls to 0.56-0.61 of the absolute value from 0.05 1/m. Armour and conductor damage are curvature driven and do not change. tests/test_core_coupled_slip.py adds 13 analytical and 13 independent-method tests, so the taxonomy counts of the validation report are 1278 and 92. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 32 + doc/local_analysis_guide.md | 34 +- doc/template_66kv.md | 14 + src/cablexsec/analysis/bending_law.py | 34 +- src/cablexsec/analysis/components.py | 37 +- src/cablexsec/analysis/kinematics.py | 8 +- src/cablexsec/analysis/section_properties.py | 3 +- src/cablexsec/api.py | 17 +- src/cablexsec/mechanics/core_friction.py | 288 ++++++- src/cablexsec/mechanics/core_kinematics.py | 10 +- src/cablexsec/mechanics/papailiou.py | 280 +++++++ src/cablexsec/mechanics/station_coupling.py | 279 +++++++ tests/test_core_coupled_slip.py | 706 ++++++++++++++++++ .../scripts/coupled_core_slip_reference.py | 313 ++++++++ validation/validation_report.md | 4 +- 15 files changed, 2019 insertions(+), 40 deletions(-) create mode 100644 src/cablexsec/mechanics/station_coupling.py create mode 100644 tests/test_core_coupled_slip.py create mode 100644 validation/scripts/coupled_core_slip_reference.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 511092a..7349a78 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,38 @@ All notable changes to CableXSec are recorded in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +### Added + +- `CoreFrictionSpec(core_core_coupling="relative")`: a coupled intralayer slip + model of laid cores. Neighbouring cores touch at the same axial position, so + the friction between them acts on their relative slip, while the filler and + ring contacts keep the slip of each core against the plane section. + - The stations of the cores at one axial position form a group whose + intralayer friction shares sum to zero. The intralayer share of a station + has the constant Coulomb bound `σ0 μ_cc (q_cc/q) |sin β| min(ψ, π/n)`, the + interlayer share the Papailiou cap with `μ_a = (μ_cf q_cf + μ_cs q_cs)/q`. + The return map is the closest point of the group + (`cablexsec.mechanics.station_coupling`, a NumPy path and a numba kernel + that agree to round-off). + - Three cores in core–core contact only: same slip onset, the largest frozen + friction stress 2/3 and the full-slip moment `√3/2` of the default law, + full slip at `2π/(3√3) = 1.209` times the onset instead of `π/2`. + - Verified against an independent field solver of the coupled axial + equilibrium of the cores (`validation/scripts/coupled_core_slip_reference.py`): + onset, full-slip curvature, moment–curvature, friction-force distribution + and reversal loop, with and without interlayer friction + (`tests/test_core_coupled_slip.py`). + - Routes: `core_friction_history`, `compute_mkappa`, the bending-law export + (group cap and transitions), the section properties, the core kinematics, + the component states and the screen, tape and sheath fatigue of the cores. + It is a direction-tied law: `friction_model="distributed"` raises and + `"auto"` keeps it on a non-planar path with a `FrictionModelFallbackWarning`. + - New helpers `core_station_history`, `core_station_bounds`, + `core_full_slip_moment` and `core_full_slip_curvature`. + - The default stays `"absolute"`; its results are unchanged, bit for bit. + ## [0.2.0] - 2026-11-21 The Python interfaces are versioned but may change before `1.0.0`. The evidence for diff --git a/doc/local_analysis_guide.md b/doc/local_analysis_guide.md index 87d6904..5e7caa8 100644 --- a/doc/local_analysis_guide.md +++ b/doc/local_analysis_guide.md @@ -901,7 +901,9 @@ for state in response.states: states of Section 13.1: `sigma_stick_*` (core held to the cable axis, `"stuck"`), `sigma_frictional_*` (the core friction law of Section 6.1 in closed form for a monotonic ramp, default `CoreFrictionSpec()`, μ = 0.2 on - every core contact) and `sigma_local_*` (free core slip: each core bends + every core contact; with `core_core_coupling="relative"` the end of a + 400-increment proportional ramp, since the coupled stations redistribute + their stress) and `sigma_local_*` (free core slip: each core bends about its own axis). The stuck state holds only below the slip curvature of the cores; on the IEA 66 kV template the cores slip at about 3e-4 1/m, so at any practical curvature the frictional state is close to free slip. @@ -978,6 +980,32 @@ print(core.loads, core.xi, core.mu_effective, core.stick_EI_Nm2) cores use the same direction-tied Papailiou cap and return map as the armour wires, so biaxial histories work (`cablexsec.mechanics.core_friction.core_friction_history`). +- Core–core coupling (`CoreFrictionSpec(core_core_coupling=...)`). By default + (`"absolute"`) every contact of a core, its neighbours included, resists the + slip of that core against the plane section, as for a helix on a fixed + cylinder: full slip at `π/2` times the onset curvature. `"relative"` is a + coupled intralayer slip model of laid cores: neighbouring cores touch at + the same axial position, so the friction between them resists their + relative slip `u_i − u_j`, while the filler and ring contacts keep the + absolute slip. The stations of the cores at one axial position form a + group whose intralayer friction shares sum to zero; the intralayer share of + a station is bounded by `σ0 μ_cc (q_cc/q) |sin β| min(ψ, π/n)` (`ψ` from the + neutral axis), the interlayer share by the Papailiou cap with + `μ_a = (μ_cf q_cf + μ_cs q_cs)/q`, and the return map is the closest point + of the group (`cablexsec.mechanics.station_coupling`). With core–core + contact only (three cores) slip starts at the same onset, the largest + frozen friction stress is 2/3 and the full-slip moment `√3/2` of the + absolute values, and full slip comes at `2π/(3√3) = 1.209` times the onset. + An independent field solver of the coupled axial equilibrium of the three + cores (`validation/scripts/coupled_core_slip_reference.py`) gives the same + onset, full-slip curvature, moment–curvature, friction-force distribution + and reversal loop, with and without interlayer friction + (`tests/test_core_coupled_slip.py`). It is a direction-tied law: + `friction_model="distributed"` raises and `"auto"` keeps it on a non-planar + path with a `FrictionModelFallbackWarning`. The stick state, the contact + loads and the onset are those of the default. The default stays + `"absolute"`; the effect on the shipped cables is in + [template_66kv.md](template_66kv.md) Section 4.1. - Friction model of the cores and profiles, as for the armour: `core_friction_history(..., friction_model="distributed")` solves each population with the distributed helix model of the armour (the axial force @@ -1033,7 +1061,9 @@ print(core.loads, core.xi, core.mu_effective, core.stick_EI_Nm2) `export_bending_law(..., core_friction=...)`. The cores stick and carry their parallel-axis term until slip onset `μ q / (ξ EA_core sin β cos β)` (Skeie and Sødahl 2012, Eq. 2.31) and all slip from - `q expm1(μ sin β π/2) / (ξ EA_core sin² β cos β)` (Papailiou 1997, Eq. 15); + `q expm1(μ sin β π/2) / (ξ EA_core sin² β cos β)` (Papailiou 1997, Eq. 15; + with `core_core_coupling="relative"` the full-slip curvature of the coupled + stations, `core_full_slip_curvature`); both curvatures are reported per case and are nodes of the backbone grid. With `CoreFrictionSpec(core_shear=False, strand_slip=False)` the backbone starts on `compute_stiffness(cable).ei_max_Nm2`; with the core insulation diff --git a/doc/template_66kv.md b/doc/template_66kv.md index 770d705..9f6adf2 100644 --- a/doc/template_66kv.md +++ b/doc/template_66kv.md @@ -258,6 +258,20 @@ What the comparison shows: Fig. 12b and Table 13), and no input is changed to follow either. - A synthetic 61-wire conductor (lay ratio 12, Table 2 copper friction 0.30) raises the half-height by a further 0.03 kN·m. +- **Core–core coupling.** With `CoreFrictionSpec(core_core_coupling="relative")` + (the coupled intralayer slip model of the local analysis guide, + Section 6.1) the friction between neighbouring cores acts on their relative + slip. At 50 kN with the default coefficients (0.2) the bounded trefoil puts + 67 % of the core contact load on the core–core contacts; the solved radial + state has no core–core contact force at that tension (98 % of the load is + on the filler), so the two options agree on it. On the bounded state the cores reach full slip at 1.22 instead of + 1.61 times their onset curvature, their full-slip friction moment is 9 % + lower and the range of the core-axis friction strain 22 % lower. The + section secant stiffness falls by 2.8, 2.5 and 2.1 % at 2, 5 and 10 times + the core onset (the stick value is unchanged), the cycle work at ±10 times + the onset by 2.4 %, and the exported backbone by 0.5 % at 0.04 1/m and + 0.1 % at 0.2 1/m. Armour and conductor damage are curvature driven and do + not change. ### 4.2 Energised cable: temperature history into clamping and fatigue diff --git a/src/cablexsec/analysis/bending_law.py b/src/cablexsec/analysis/bending_law.py index d075006..6b55a0f 100644 --- a/src/cablexsec/analysis/bending_law.py +++ b/src/cablexsec/analysis/bending_law.py @@ -1549,8 +1549,16 @@ def _state_law( def _group_caps(law: _MkappaLaw) -> FloatArray: """Planar full-slip friction moment of every friction group [N m].""" values = [_friction_cap(spec) for spec in law.layers] - if law.core_model is not None: - values += [_friction_cap(spec) for spec in law.core_model.populations] + model = law.core_model + if model is not None: + from cablexsec.mechanics.core_friction import ( # noqa: PLC0415 + core_full_slip_moment, + ) + + # The cores hold the bounds of their own law (relative coupling: the + # interlayer plus the intralayer bound), the profiles the Papailiou cap. + values.append(core_full_slip_moment(model)) + values += [_friction_cap(spec) for spec in model.populations[1:]] return np.asarray(values, dtype=np.float64) @@ -1601,14 +1609,26 @@ def _slip_transitions( if law.progressive is not None and law.progressive.density == "uniform": n = law.progressive.n_elements spread = 1.0 - law.progressive.spread * (1.0 - 1.0 / n) - specs = [(spec, spread) for spec in law.layers] - if law.core_model is not None: - specs += [(spec, 1.0) for spec in law.core_model.populations] + specs: list[tuple[HelicalLayerSpec, float, float | None]] = [ + (spec, spread, None) for spec in law.layers + ] + model = law.core_model + if model is not None: + from cablexsec.mechanics.core_friction import ( # noqa: PLC0415 + core_full_slip_curvature, + ) + + # The coupled stations of the relative core law have their own + # full-slip curvature (core_full_slip_curvature). + core_full = None if model.coupling is None else core_full_slip_curvature(model) + specs += [(model.population, 1.0, core_full)] + specs += [(spec, 1.0, None) for spec in model.populations[1:]] out = [] - for spec, factor in specs: + for spec, factor, full in specs: if friction_law is not None and friction_law.pressure_dependent: scale = float(friction_law.pressure_factor_at(spec.contact_pressure_Pa)) spec = dataclasses.replace(spec, mu=spec.mu * scale) + full = None if full is None else full * scale onset = slip_onset_curvature(spec) if not (math.isfinite(onset) and onset > 0.0): continue # no friction: the group is in full slip from zero @@ -1618,7 +1638,7 @@ def _slip_transitions( tension, onset * _compression_onset_factor(lam) * factor, onset, - full_slip_curvature(spec), + full_slip_curvature(spec) if full is None else full, ) ) return out diff --git a/src/cablexsec/analysis/components.py b/src/cablexsec/analysis/components.py index 56a6d4b..81826a2 100644 --- a/src/cablexsec/analysis/components.py +++ b/src/cablexsec/analysis/components.py @@ -97,7 +97,11 @@ ) from cablexsec.exceptions import CableInputError, CableSchemaError from cablexsec.materials import library -from cablexsec.mechanics.core_friction import CoreFrictionSpec, build_core_friction +from cablexsec.mechanics.core_friction import ( + CoreFrictionSpec, + build_core_friction, + core_station_history, +) from cablexsec.mechanics.core_kinematics import CORE_SLIP_STATES, CoreSlipState from cablexsec.mechanics.core_lay import core_angle, core_bending_components from cablexsec.mechanics.papailiou import wire_slip_stress_bounds @@ -133,6 +137,10 @@ ) """How the stress of a layer outside the load path is obtained, in words.""" +#: Increments of the proportional path of the coupled (relative) core law in +#: the frictional core state of one section. +_COUPLED_RAMP_SAMPLES = 400 + _STATE_WORDS = { "stuck": "stuck (cores held to the cable axis)", "frictional": "frictional core slip", @@ -478,6 +486,25 @@ def _core_axis( if kappa == 0.0: frictional = np.zeros(layer.n_cores) slipping = 0 + elif model.coupling is not None: + # Relative core-core coupling: the stations of one axial position + # redistribute their stress, so the monotonic state is the end of a + # proportional path from the stress-free state. + stations = np.arange(layer.n_cores) * model.spec.n_stations_per_core + ramp = np.linspace(0.0, 1.0, _COUPLED_RAMP_SAMPLES + 1)[1:] + history = core_station_history( + model, + ramp * kappa_x, + ramp * kappa_y, + initial_bending_angle=math.atan2(kappa_y, kappa_x), + ) + stress = np.asarray(history.stress_Pa)[stations, -1] + frictional = stress / population.E_wire_Pa + cosine = np.cos(phases - math.atan2(kappa_y, kappa_x)) + stick = population.k_f * population.r_helix_m * cosine * kappa + slipping = int( + np.count_nonzero(np.abs(stress - stick) > 1e-9 * (np.abs(stick) + 1.0)) + ) else: phi_bend = math.atan2(kappa_y, kappa_x) stations = np.arange(layer.n_cores) * model.spec.n_stations_per_core @@ -490,9 +517,11 @@ def _core_axis( return _CoreAxis( stuck, frictional, - f"core friction coefficient {model.mu_effective:.3g}, stick coefficient " - f"{model.xi:.3g}, contact line load {model.loads.total_N_per_m:.4g} N/m per " - f"core; {slipping} of {layer.n_cores} cores slipping in this section", + f"core friction coefficient {model.mu_effective:.3g}" + + (" (relative core-core slip)" if model.coupling is not None else "") + + f", stick coefficient {model.xi:.3g}, contact line load " + f"{model.loads.total_N_per_m:.4g} N/m per core; {slipping} of " + f"{layer.n_cores} cores slipping in this section", ) diff --git a/src/cablexsec/analysis/kinematics.py b/src/cablexsec/analysis/kinematics.py index 43c0d12..de98b96 100644 --- a/src/cablexsec/analysis/kinematics.py +++ b/src/cablexsec/analysis/kinematics.py @@ -111,6 +111,7 @@ from cablexsec.mechanics.core_friction import ( CoreFrictionSpec, build_core_friction, + core_station_history, resolve_core_friction, ) from cablexsec.mechanics.distributed_friction import distributed_friction_history @@ -789,12 +790,7 @@ def _core_field( model = build_core_friction(cable, spec, tension_N, contact_model=contact_model) population = model.population - history = wire_slip_history( - population, - drive.kx, - drive.ky, - direction_hold_fraction=spec.direction_hold_fraction, - ) + history = core_station_history(model, drive.kx, drive.ky) phi = np.asarray(population.phi_wires, dtype=np.float64) lay = cable.core_lay sign = _lay_sign(lay.lay_direction) if lay is not None else 1 diff --git a/src/cablexsec/analysis/section_properties.py b/src/cablexsec/analysis/section_properties.py index 0627595..1bc9255 100644 --- a/src/cablexsec/analysis/section_properties.py +++ b/src/cablexsec/analysis/section_properties.py @@ -87,6 +87,7 @@ from cablexsec.mechanics.core_friction import ( CoreFrictionSpec, build_core_friction, + core_full_slip_curvature, resolve_core_friction, ) from cablexsec.mechanics.papailiou import full_slip_curvature, slip_onset_curvature @@ -1111,7 +1112,7 @@ def _core_slip( model.mu_effective, model.xi, slip_onset_curvature(population), - full_slip_curvature(population), + core_full_slip_curvature(model), model.stick_EI_Nm2, None if fillers is None else fillers.line_load_N_per_m, None if fillers is None else slip_onset_curvature(fillers.population), diff --git a/src/cablexsec/api.py b/src/cablexsec/api.py index 6f0c35b..41cb3af 100644 --- a/src/cablexsec/api.py +++ b/src/cablexsec/api.py @@ -1109,7 +1109,12 @@ def compute_mkappa( else: method_extra = ( "; laid-core stick-slip (direction-tied Papailiou cap, " - f"{model.loads.source} core contact loads, stick coefficient " + + ( + "" + if model.coupling is None + else "relative core-core slip of neighbouring cores, " + ) + + f"{model.loads.source} core contact loads, stick coefficient " f"{model.xi:.3f}, effective friction coefficient " f"{model.mu_effective:.3f})" + ( @@ -1140,8 +1145,14 @@ def compute_mkappa( else "of the reference" ) + ", not changed by bending; the layers of a core move together; " - "core-core friction acts on the slip of each core relative to the " - "plane-section field", + + ( + "core-core friction acts on the slip of each core relative to the " + "plane-section field" + if model.coupling is None + else "core-core friction acts on the relative slip of neighbouring " + "cores (coupled stations, constant Coulomb bound of the core-core " + "load)" + ), "internal rings take the core contact line load by line-force " "conservation (upper estimate) and the cable curvature", ) diff --git a/src/cablexsec/mechanics/core_friction.py b/src/cablexsec/mechanics/core_friction.py index 5e87ee3..f506a49 100644 --- a/src/cablexsec/mechanics/core_friction.py +++ b/src/cablexsec/mechanics/core_friction.py @@ -144,6 +144,45 @@ The internal rings keep the [KarlsenHusoy2026] operator in every model. +Core--core coupling +------------------- +``CoreFrictionSpec(core_core_coupling=...)`` sets the slip on which the +core--core friction acts: + +* ``"absolute"`` (default): every contact of a core, the neighbouring cores + included, resists the slip of that core relative to the plane-section + field, like a helix on a fixed cylinder, with the load-weighted coefficient + ``mu_eff``. Under planar bending full slip comes at ``pi / 2`` times the + onset curvature. +* ``"relative"``: a coupled intralayer slip model of laid cores. The + neighbouring cores of the layer touch at the same axial position, and the + friction between two of them resists their relative slip ``u_i - u_j``; the + filler and ring contacts (interlayer) keep the absolute slip. The stations + of the ``n`` cores at one axial position form a group + (:mod:`cablexsec.mechanics.station_coupling`): the station stress is the + interlayer share, bounded as above with the interlayer coefficient + ``mu_a = (mu_cf q_cf + mu_cs q_cs) / q_core`` (the capstan form kept on this + share), plus the intralayer share, bounded by the constant Coulomb bound + ``sigma_0 mu_cc (q_cc / q_core) |sin beta| min(psi, pi / n)``, and the + intralayer shares of a group sum to zero. The return map is the closest + point of the group on that set. For three cores with core--core contact + only, slip starts at the same onset curvature, the largest frozen friction + stress at full slip is ``2/3`` of the absolute value (the stress plateaus + beyond ``pi / 3`` from the neutral axis), the full-slip moment is + ``sqrt(3)/2`` of the absolute one and full slip comes at + ``2 pi / (3 sqrt 3) = 1.209`` times the onset curvature. These match an + independent field solver of the coupled axial equilibrium of the cores + (``validation/scripts/coupled_core_slip_reference.py``) on monotonic and + reversed planar paths, with and without interlayer friction. Two cores + slip relative to each other in the sense of their absolute slip, and the + coupled law then differs from the absolute one only by the capstan term of + the core--core share. Without core--core load (a central filler) the two + options agree. The stick coefficient, the contact loads, the filler + profiles and the internal rings are the same in both. The relative coupling + is a direction-tied law: it takes no distributed model, and + ``friction_model="auto"`` keeps it on a non-planar path with a + :class:`~cablexsec.provenance.FrictionModelFallbackWarning`. + Contact loads over a tension history ------------------------------------ :func:`core_load_history` evaluates the core and profile contact loads of the @@ -175,8 +214,12 @@ * The layers of one core are bonded and move together axially; the core is a rod of rigidity ``EA_core`` whose interior shear enters only through ``xi``. -* Core--core friction is applied to the slip of each core relative to the - plane-section field, as are the filler and sheath contacts. +* With ``core_core_coupling="absolute"`` (default) core--core friction is + applied to the slip of each core relative to the plane-section field, as + are the filler and sheath contacts; ``"relative"`` applies it to the + relative slip of neighbouring cores (section "Core--core coupling"), with + the constant Coulomb bound of the core--core load (no capstan term on that + share) and pointwise station bounds, as the direction-tied law. * The contact width for ``k_s`` is the core perimeter. * Internal rings use the cable curvature times the helical-rod bending factor of the core lay; their external contact pressure is the core contact line @@ -214,12 +257,19 @@ from cablexsec.mechanics.papailiou import ( DIRECTION_HOLD_FRACTION, BendingWork, + WireSlipHistory, + coupled_slip_stress_bounds, + full_slip_curvature, wire_slip_history, wire_slip_stress_bounds, ) from cablexsec.mechanics.radial_cable import CableRadialState from cablexsec.mechanics.section_geometry import is_interstitial_filler from cablexsec.mechanics.section_state import SectionState +from cablexsec.mechanics.station_coupling import ( + StationCoupling, + project_station_groups, +) from cablexsec.mechanics.stiffness import axial_stiffness_by_layer, ea_fixed from cablexsec.mechanics.strand_slip import ( ConductorRing, @@ -234,9 +284,11 @@ ) __all__ = [ + "CORE_CORE_COUPLINGS", "CORE_FRICTION_MODELS", "CORE_LOAD_MODES", "CoreContactLoads", + "CoreCoreCoupling", "CoreFrictionHistory", "CoreFrictionModel", "CoreFrictionModelName", @@ -248,7 +300,11 @@ "build_core_friction", "core_contact_loads", "core_friction_history", + "core_full_slip_curvature", + "core_full_slip_moment", "core_load_history", + "core_station_bounds", + "core_station_history", "resolve_core_friction", ] @@ -261,6 +317,11 @@ #: history (:func:`core_load_history`) or hold the ``"reference"`` state. CoreLoadMode = Literal["follow", "reference"] CORE_LOAD_MODES: tuple[str, ...] = ("follow", "reference") +#: Slip on which the core--core friction acts (module notes): ``"absolute"`` +#: (each core against the plane section, default) or ``"relative"`` (the +#: relative slip of neighbouring cores). +CoreCoreCoupling = Literal["absolute", "relative"] +CORE_CORE_COUPLINGS: tuple[str, ...] = ("absolute", "relative") #: Solved tensions of a solved-model load history before it is interpolated. _SOLVED_LOAD_NODES = 33 @@ -314,6 +375,11 @@ class CoreFrictionSpec: mu_filler_profile : float or None Friction coefficient of the profile contacts (default: ``mu_core_filler``). + core_core_coupling : {"absolute", "relative"} + Slip on which the core--core friction acts (module notes, section + "Core--core coupling"): ``"absolute"`` (default) the slip of each core + relative to the plane section, ``"relative"`` the relative slip of + neighbouring cores (coupled stations; direction-tied law only). """ mu_core_filler: float = DEFAULT_CORE_MU @@ -329,6 +395,7 @@ class CoreFrictionSpec: central_filler: bool | None = None filler_profiles: bool = False mu_filler_profile: float | None = None + core_core_coupling: CoreCoreCoupling = "absolute" @property def filler_mu(self) -> float: @@ -348,6 +415,11 @@ def __post_init__(self) -> None: raise CableInputError("central_filler must be None, True or False") if not isinstance(self.filler_profiles, bool): raise CableInputError("filler_profiles must be True or False") + if self.core_core_coupling not in CORE_CORE_COUPLINGS: + raise CableInputError( + f"core_core_coupling must be one of {CORE_CORE_COUPLINGS}, " + f"got {self.core_core_coupling!r}" + ) for name in ("mu_strand", "mu_strand_outer", "mu_filler_profile"): value = getattr(self, name) if value is not None and (not math.isfinite(value) or value < 0.0): @@ -409,6 +481,13 @@ def mu_effective(self, spec: CoreFrictionSpec) -> float: + spec.mu_core_sheath * self.core_sheath_N_per_m ) / total + def mu_interlayer(self, spec: CoreFrictionSpec) -> float: + """Interlayer (filler and ring) friction over the total core load, + ``(mu_cf q_cf + mu_cs q_cs) / q_core`` (``mu_core_filler`` if + unloaded): the coefficient of the interlayer share of the relative + coupling, :meth:`mu_effective` with ``mu_core_core = 0``.""" + return self.mu_effective(dataclasses.replace(spec, mu_core_core=0.0)) + def _core_layers(cable: CableData) -> list[CylindricalOffsetLayer]: return [x for x in cable.layers if isinstance(x, CylindricalOffsetLayer)] @@ -644,6 +723,9 @@ class CoreFrictionModel: strand_rings: tuple[StrandRingFriction, ...] = field(default=()) tension_N: float = 0.0 fillers: FillerProfiles | None = None + #: Coupled station groups of ``core_core_coupling="relative"`` (``None``: + #: the absolute law). + coupling: StationCoupling | None = None @property def core_stick_EI_Nm2(self) -> float: @@ -918,6 +1000,16 @@ def build_core_friction( mu = loads.mu_effective(spec) n_st = n_cores * spec.n_stations_per_core area_core = math.pi * r_core**2 + coupling = None + if spec.core_core_coupling == "relative": + coupling = StationCoupling( + group_size=n_cores, + interlayer_mu=loads.mu_interlayer(spec), + intralayer_mu=spec.mu_core_core, + intralayer_pressure_Pa=n_cores + * loads.core_core_N_per_m + / (2.0 * math.pi * r_c), + ) population = HelicalLayerSpec( n_wires=n_st, r_helix_m=r_c, @@ -948,6 +1040,7 @@ def build_core_friction( if spec.filler_profiles else None ), + coupling=coupling, ) @@ -965,6 +1058,12 @@ class CoreLoadHistory: the most loaded sample. ``filler_profile_N_per_m`` and ``filler_pressure_Pa`` are those of the filler profiles (``None`` without them). ``contact_model`` names the model the loads come from. + + With ``core_core_coupling="relative"`` the core pressure and the capstan + coefficient are those of the interlayer share (the same rule with the + interlayer coefficient), and ``core_intralayer_pressure_Pa`` is the + pressure equivalent ``n q_cc / (2 pi r_c)`` of the core--core load at + every sample (``None`` for the absolute law). """ tension_N: FloatArray @@ -975,6 +1074,7 @@ class CoreLoadHistory: filler_profile_N_per_m: FloatArray | None = None filler_pressure_Pa: FloatArray | None = None core_mu_capstan: float | None = None + core_intralayer_pressure_Pa: FloatArray | None = None def _population_cap_per_pressure(spec: HelicalLayerSpec, mu: float) -> float: @@ -1054,17 +1154,30 @@ def follow(name: str) -> FloatArray: mu[positive] = weighted[positive] / total[positive] population = model.population pressure = model.n_cores * total / (2.0 * math.pi * model.r_offset_m) + # The capstan share: the whole load (absolute law) or the interlayer + # share (relative coupling, the coefficient with mu_core_core = 0). + share = mu reference_mu = float(population.mu) - if reference_mu <= 0.0 and np.any(mu[positive] > 0.0): + intralayer = None + if model.coupling is not None: + share = np.full(total.shape, spec.mu_core_filler) + interlayer = spec.mu_core_filler * filler + spec.mu_core_sheath * sheath + share[positive] = interlayer[positive] / total[positive] + reference_mu = float(model.coupling.interlayer_mu) + intralayer = np.asarray( + model.n_cores * core_core / (2.0 * math.pi * model.r_offset_m), + dtype=np.float64, + ) + if reference_mu <= 0.0 and np.any(share[positive] > 0.0): # A zero reference coefficient cannot carry the friction of later # samples: normalise by the coefficient of the most loaded sample. - reference_mu = float(mu[int(np.argmax(total))]) - if np.any(np.abs(mu - reference_mu) > 1e-12 * max(reference_mu, 1e-300)): + reference_mu = float(share[int(np.argmax(total))]) + if np.any(np.abs(share - reference_mu) > 1e-12 * max(reference_mu, 1e-300)): # The full-slip friction moment of the population at each sample's # coefficient over that at the normalising coefficient (positive # here unless every sample is frictionless). reference = _population_cap_per_pressure(population, reference_mu) - values, inverse = np.unique(mu, return_inverse=True) + values, inverse = np.unique(share, return_inverse=True) ratio = np.array( [ _population_cap_per_pressure(population, float(value)) / reference @@ -1088,6 +1201,7 @@ def follow(name: str) -> FloatArray: filler_profile_N_per_m=profile, filler_pressure_Pa=profile_pressure, core_mu_capstan=reference_mu, + core_intralayer_pressure_Pa=intralayer, ) @@ -1121,6 +1235,126 @@ def moment_Nm(self) -> FloatArray: return np.asarray(total) +def core_station_history( + model: CoreFrictionModel, + kappa_x: FloatArray, + kappa_y: FloatArray, + *, + initial_bending_angle: float = 0.0, + keep_cap: bool = False, +) -> WireSlipHistory: + """Direction-tied history of the core stations of ``model`` at its + reference loads: :func:`~cablexsec.mechanics.papailiou.wire_slip_history` + of the core population, with the coupled station groups of + ``core_core_coupling="relative"`` (module notes).""" + return wire_slip_history( + model.population, + kappa_x, + kappa_y, + initial_bending_angle=initial_bending_angle, + direction_hold_fraction=model.spec.direction_hold_fraction, + keep_cap=keep_cap, + coupling=model.coupling, + ) + + +def core_station_bounds( + model: CoreFrictionModel, phi_bend: float +) -> tuple[FloatArray, FloatArray]: + """Rising and falling friction-stress bounds of every core station [Pa] + for the bending direction ``phi_bend``: those of + :func:`~cablexsec.mechanics.papailiou.wire_slip_stress_bounds` (absolute + law), or the interlayer bounds plus the intralayer bound of the relative + coupling (the bound a station holds in full slip).""" + if model.coupling is None: + return wire_slip_stress_bounds(model.population, phi_bend) + upper, lower, cap = coupled_slip_stress_bounds( + model.population, model.coupling, phi_bend + ) + return np.asarray(upper + cap), np.asarray(lower + cap) + + +def core_full_slip_moment(model: CoreFrictionModel) -> float: + """Planar full-slip friction moment of the core population [N m]: every + station on the bound of its side (:func:`core_station_bounds`) under a + large curvature about ``phi_bend = 0``. The coupled stations of the + relative law hold the same bounds in full slip, whose intralayer shares + cancel in every group.""" + population = model.population + upper, lower = core_station_bounds(model, 0.0) + c = np.cos(population.phi_wires) + bound = np.where(c > 0.0, upper, lower) + return float( + population.A_wire_m2 + * math.cos(population.lay_angle_rad) + * population.r_helix_m + * np.sum(bound * np.abs(c)) + ) + + +#: Curvature samples of the monotonic path of :func:`core_full_slip_curvature` +#: (relative coupling) and bisections of its last interval. +_FULL_SLIP_SAMPLES = 2000 +_FULL_SLIP_BISECTIONS = 40 + + +def core_full_slip_curvature(model: CoreFrictionModel, phi_bend: float = 0.0) -> float: + """Curvature at which the last core station starts to slip [1/m]. + + Absolute law: :func:`~cablexsec.mechanics.papailiou.full_slip_curvature` + of the core population. Relative coupling: the stations of a group + redistribute their stress, so the point depends on the path; it is the + first curvature of a monotonic planar path from the stress-free state + (``phi_bend``, 2000 equal increments up to the value of independent + stations with the same bounds, refined by bisection of the last + increment) at which + every loaded station is on its bound. Zero without friction. + """ + population = model.population + if model.coupling is None: + return full_slip_curvature(population, phi_bend=phi_bend) + if not math.isfinite(phi_bend): + raise CableInputError("bending direction must be finite") + upper, lower, cap = coupled_slip_stress_bounds(population, model.coupling, phi_bend) + cosine = np.cos(population.phi_wires - phi_bend) + bound = np.where(cosine >= 0.0, upper, lower) + cap + loaded = np.abs(cosine) > 1.0e-12 + unit = population.k_f * population.r_helix_m * cosine + if not np.any(loaded) or not np.any(bound > 0.0): + return 0.0 + # Every station on its own bound: the independent-station value, the + # first bracket (doubled while the coupled stations stick beyond it). + top = float(np.max(bound[loaded] / np.abs(unit[loaded]))) + n = model.coupling.group_size + + def project(stress: FloatArray, step: float) -> FloatArray: + return project_station_groups(stress + step * unit, upper, lower, cap, n) + + def slipping(stress: FloatArray) -> bool: + side = np.abs(stress[loaded]) >= bound[loaded] * (1.0 - 1.0e-12) + return bool(np.all(side)) + + for _ in range(4): + steps = np.linspace(0.0, top, _FULL_SLIP_SAMPLES + 1) + stress = np.zeros_like(unit) + for k0, k1 in zip(steps[:-1], steps[1:], strict=True): + trial = project(stress, k1 - k0) + if slipping(trial): + lo, hi = float(k0), float(k1) + for _ in range(_FULL_SLIP_BISECTIONS): + mid = 0.5 * (lo + hi) + if slipping(project(stress, mid - k0)): + hi = mid + else: + lo = mid + return hi + stress = trial + top *= 2.0 # pragma: no cover - the first bracket held in every case + raise CableInputError( # pragma: no cover + "the coupled core stations did not reach full slip" + ) + + def _strand_history( model: CoreFrictionModel, kx: FloatArray, @@ -1177,6 +1411,18 @@ def _resolve_core_model( and curvature_path_out_of_plane_ratio(kx, ky) <= PLANAR_PATH_TOLERANCE ): return "direction_tied" + if model.coupling is not None: + reason = ( + "the relative core-core coupling (core_core_coupling='relative') " + "is a direction-tied law" + ) + if friction_model == "distributed": + raise CableInputError( + f"the distributed core law is not available: {reason}; use " + "friction_model='direction_tied' or core_core_coupling='absolute'" + ) + _warn_auto_fallback("the laid-core law", reason, stacklevel + 1) + return "direction_tied" rigid = [ f"the {name} (xi = {pop.xi:.6g})" for name, pop in zip( @@ -1255,7 +1501,12 @@ def core_friction_history( station) and substeps of at most ``max_increment`` slip-onset curvatures (the default of the distributed model), ``"auto"`` the direction-tied law on a planar path and the distributed law otherwise. The rings use - :func:`strand_slip_strain`. + :func:`strand_slip_strain`. A model with + ``core_core_coupling="relative"`` takes the coupled station groups of + :func:`~cablexsec.mechanics.papailiou.wire_slip_history` (direction-tied + only: ``"distributed"`` raises, ``"auto"`` keeps the direction-tied law + with a :class:`~cablexsec.provenance.FrictionModelFallbackWarning` on a + non-planar path); its load history must come from the same model. ``loads`` (:func:`core_load_history`, one sample per curvature sample) makes the contact loads follow a tension history; ``None`` holds the model's reference loads. All return moments in the material frame of the @@ -1280,7 +1531,26 @@ def core_friction_history( filler_pressure = loads.filler_pressure_Pa tension = loads.tension_N population = model.population - if ( + coupling = model.coupling + intralayer: FloatArray | None = None + if loads is not None and ( + (loads.core_intralayer_pressure_Pa is None) != (coupling is None) + ): + raise CableInputError( + "the core load history belongs to another core model " + "(its core-core coupling differs)" + ) + if coupling is not None: + if loads is not None: + intralayer = loads.core_intralayer_pressure_Pa + if ( + loads.core_mu_capstan is not None + and loads.core_mu_capstan != coupling.interlayer_mu + ): + coupling = dataclasses.replace( + coupling, interlayer_mu=loads.core_mu_capstan + ) + elif ( loads is not None and loads.core_mu_capstan is not None and loads.core_mu_capstan != population.mu @@ -1302,6 +1572,8 @@ def core_friction_history( contact_pressure_Pa=core_pressure, initial_bending_angle=initial_bending_angle, direction_hold_fraction=model.spec.direction_hold_fraction, + coupling=coupling, + intralayer_pressure_Pa=intralayer, ) core_moment, w = np.asarray(history.moment_Nm), history.work slip = history.slipping_count / float(model.population.n_wires) diff --git a/src/cablexsec/mechanics/core_kinematics.py b/src/cablexsec/mechanics/core_kinematics.py index c21a79f..88afd16 100644 --- a/src/cablexsec/mechanics/core_kinematics.py +++ b/src/cablexsec/mechanics/core_kinematics.py @@ -79,9 +79,9 @@ CoreFrictionSpec, _core_geometry, build_core_friction, + core_station_history, ) from cablexsec.mechanics.core_lay import core_angle -from cablexsec.mechanics.papailiou import wire_slip_history from cablexsec.mechanics.radial_cable import CableRadialState from cablexsec.mechanics.section_state import SectionState @@ -269,12 +269,8 @@ def core_kinematics( "the frictional state uses n_cores * n_stations_per_core stations " f"({population.n_wires}); set CoreFrictionSpec.n_stations_per_core" ) - history = wire_slip_history( - population, - kx, - ky, - initial_bending_angle=initial_bending_angle, - direction_hold_fraction=spec.direction_hold_fraction, + history = core_station_history( + model, kx, ky, initial_bending_angle=initial_bending_angle ) phase = np.asarray(population.phi_wires, dtype=np.float64) axis = np.asarray(history.stress_Pa / population.E_wire_Pa) diff --git a/src/cablexsec/mechanics/papailiou.py b/src/cablexsec/mechanics/papailiou.py index e14fa93..c5b2824 100644 --- a/src/cablexsec/mechanics/papailiou.py +++ b/src/cablexsec/mechanics/papailiou.py @@ -103,6 +103,10 @@ ) from cablexsec.mechanics.mkappa import HelicalLayerSpec from cablexsec.mechanics.return_mapping import CoulombElement +from cablexsec.mechanics.station_coupling import ( + StationCoupling, + project_station_groups, +) if TYPE_CHECKING: from cablexsec.mechanics.progressive_friction import ProgressiveFriction @@ -114,6 +118,7 @@ "compute_mkappa_papailiou", "DIRECTION_HOLD_FRACTION", "compute_mkappa_wire_slip_front", + "coupled_slip_stress_bounds", "direction_threshold_curvature", "full_slip_curvature", "slip_onset_curvature", @@ -123,6 +128,8 @@ ] FloatArray = NDArray[np.float64] +#: Interlayer upper, lower and intralayer bounds of coupled stations. +_Bounds3 = tuple[FloatArray, FloatArray, FloatArray] #: Default fraction ``f`` of the smallest slip-onset curvature below which the #: bending direction of the slip cap is held and blended (see @@ -425,6 +432,81 @@ def wire_slip_stress_bounds( _UNREACHABLE_CAP_PA = 1.0e300 +def coupled_slip_stress_bounds( + layer: HelicalLayerSpec, + coupling: StationCoupling, + phi_bend: float, + *, + contact_pressure_Pa: float | None = None, + intralayer_pressure_Pa: float | None = None, +) -> tuple[FloatArray, FloatArray, FloatArray]: + r"""Interlayer and intralayer bounds of coupled stations [Pa]. + + Returns ``(upper, lower, cap)``: the interlayer bounds of + :func:`wire_slip_stress_bounds` with the coupling's interlayer coefficient + at ``contact_pressure_Pa`` (default the layer's), and the intralayer bound + + .. math:: + + C = \sigma_0(P_c) \, \mu_{cc} |\sin a| \, g \min(\psi, \pi / n), + + with ``sigma_0`` of :func:`wire_slip_stress_cap` at the intralayer + pressure ``P_c`` (default the coupling's) and ``psi`` the angle of the + station from the neutral axis + (:mod:`cablexsec.mechanics.station_coupling`). + """ + interlayer = dataclasses.replace(layer, mu=coupling.interlayer_mu) + upper, lower = wire_slip_stress_bounds( + interlayer, phi_bend, contact_pressure_Pa=contact_pressure_Pa + ) + pressure = ( + coupling.intralayer_pressure_Pa + if intralayer_pressure_Pa is None + else intralayer_pressure_Pa + ) + sin_a = abs(math.sin(layer.lay_angle_rad)) + if pressure <= 0.0 or sin_a < 1.0e-12 or coupling.intralayer_mu <= 0.0: + return upper, lower, np.zeros(layer.n_wires, dtype=np.float64) + width = 2.0 * math.pi * layer.r_helix_m / layer.n_wires + rate = ( + layer.r_helix_m + * pressure + * width + * math.cos(layer.lay_angle_rad) + * coupling.intralayer_mu + / (layer.A_wire_m2 * sin_a) + ) + 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 - phi_bend) + psi = np.arcsin(np.clip(np.abs(cphi), 0.0, 1.0)) + cap = rate * g * np.minimum(psi, coupling.plateau_rad) + return upper, lower, np.asarray(cap, dtype=np.float64) + + +def _coupled_threshold_coefficient( + layer: HelicalLayerSpec, coupling: StationCoupling, hold_fraction: float +) -> tuple[float, float]: + """Direction-threshold coefficients of the interlayer pressure and of the + intralayer pressure (the threshold is ``(c_a P + c_c P_c) / k``).""" + interlayer = dataclasses.replace(layer, mu=coupling.interlayer_mu) + coefficient_a = _threshold_coefficient(interlayer, hold_fraction) + if hold_fraction == 0.0: + return coefficient_a, 0.0 + g_min = 1.0 if layer.shape_g is None else float(np.min(layer.shape_g)) + lam = coupling.interlayer_mu * abs(math.sin(layer.lay_angle_rad)) + intralayer = dataclasses.replace(layer, mu=coupling.intralayer_mu) + coefficient_c = ( + hold_fraction + * _compression_onset_factor(lam) + * _onset_coefficient(intralayer, max(g_min, 0.0)) + ) + return coefficient_a, coefficient_c + + def slip_onset_curvature( layer: HelicalLayerSpec, *, @@ -753,9 +835,23 @@ def wire_slip_history( keep_cap: bool = False, friction_law: FrictionLaw | None = None, time_s: FloatArray | None = None, + coupling: StationCoupling | None = None, + intralayer_pressure_Pa: FloatArray | None = None, ) -> WireSlipHistory: """Shared small-strain, mean-clamping update for bending and bulk fatigue. + Coupled stations. ``coupling`` + (:class:`~cablexsec.mechanics.station_coupling.StationCoupling`) makes the + stations of one axial position a group with the interlayer and intralayer + bounds of :func:`coupled_slip_stress_bounds` and the group return map of + :func:`~cablexsec.mechanics.station_coupling.project_station_groups` + (the laid cores with ``core_core_coupling="relative"``); the direction + hold below blends the three bounds alike, ``contact_pressure_Pa`` is then + the pressure of the interlayer bounds and ``intralayer_pressure_Pa`` that + of the intralayer bound (default the coupling's). ``keep_cap`` returns the + station bound ``upper + cap`` or ``lower + cap``. It takes no friction + law. ``None`` keeps the independent stations, bit for bit. + No spatial contact solve is introduced. The Papailiou bounds of :func:`wire_slip_stress_bounds` and a scalar spring-slider describe each physical wire: its friction stress stays in ``[-lower, upper]``. Their @@ -894,6 +990,25 @@ def wire_slip_history( raise CableInputError( "nonnegative pressure and positive stiffness are required" ) + if coupling is not None: + if law is not None: + raise CableInputError( + "coupled stations (relative core-core slip) take no friction law" + ) + return _coupled_wire_slip_history( + layer, + coupling, + kx, + ky, + pressure, + intralayer_pressure_Pa, + stiffness, + initial_bending_angle, + float(direction_hold_fraction), + keep_cap, + ) + if intralayer_pressure_Pa is not None: + raise CableInputError("an intralayer pressure needs a station coupling") if law is not None: return _law_wire_slip_history( layer, @@ -1046,6 +1161,171 @@ def oriented_cap( ) +def _coupled_wire_slip_history( + layer: HelicalLayerSpec, + coupling: StationCoupling, + kx: FloatArray, + ky: FloatArray, + pressure: FloatArray, + intralayer_pressure_Pa: FloatArray | None, + stiffness: FloatArray, + initial_bending_angle: float, + hold_fraction: float, + keep_cap: bool, +) -> WireSlipHistory: + """:func:`wire_slip_history` of coupled station groups (validated inputs). + + The same update as the independent stations with the three bounds of + :func:`coupled_slip_stress_bounds` and the group return map; the work + terms are those of the independent stations (the plastic work of each + group update is non-negative). + """ + count = kx.size + if layer.n_wires % coupling.group_size: + raise CableInputError( + f"{layer.n_wires} stations do not form groups of " + f"{coupling.group_size} cores" + ) + intralayer = ( + np.full(count, coupling.intralayer_pressure_Pa) + if intralayer_pressure_Pa is None + else np.asarray(intralayer_pressure_Pa, dtype=float) + ) + if intralayer.shape != kx.shape or not np.isfinite(intralayer).all(): + raise CableInputError( + "intralayer pressure must be finite and match curvature histories" + ) + if np.any(intralayer < 0): + raise CableInputError("nonnegative intralayer pressure is required") + coefficient_a, coefficient_c = _coupled_threshold_coefficient( + layer, coupling, hold_fraction + ) + 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 + weight = layer.A_wire_m2 * math.cos(layer.lay_angle_rad) + stress = np.empty((layer.n_wires, count)) + caps = np.empty((layer.n_wires, count)) if keep_cap else None + moment = np.empty((count, 2)) + slipping_count = np.empty(count, dtype=np.int64) + stored, friction, endpoint, remainder, material = ( + np.zeros(count) for _ in range(5) + ) + totals = np.zeros(4) + old_drive = np.zeros(layer.n_wires) + held = current = initial_bending_angle + zero = np.zeros(layer.n_wires) + + caches: dict[str, tuple[tuple[float, float, float] | None, _Bounds3]] = { + "held": (None, (zero, zero, zero)), + "current": (None, (zero, zero, zero)), + } + + def oriented(slot: str, angle: float, load: float, load_c: float) -> _Bounds3: + key, value = caches[slot] + if key != (angle, load, load_c): + value = coupled_slip_stress_bounds( + layer, + coupling, + angle, + contact_pressure_Pa=load, + intralayer_pressure_Pa=load_c, + ) + for part in value: + if ( + part.shape != (layer.n_wires,) + or not np.isfinite(part).all() + or np.any(part < 0) + ): + raise CableInputError( + "wire caps must be finite, nonnegative and match the population" + ) + caches[slot] = ((angle, load, load_c), 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[3] += ( + 0.5 + * weight + * (current_stiffness - element.k) + * (elastic_strain**2).sum() + ) + element.set_stiffness(current_stiffness) + old_stress, old_plastic = element.f, element.slip_total + load = float(pressure[index]) + load_c = float(intralayer[index]) + if x != 0 or y != 0: + current = math.atan2(y, x) + threshold = ( + coefficient_a * load + coefficient_c * load_c + ) / current_stiffness + magnitude = math.sqrt(x * x + y * y) + if magnitude >= threshold: + held = current + upper, lower, cap = oriented("held", held, load, load_c) + else: + blend = magnitude / threshold + upper, lower, cap = oriented("held", held, load, load_c) + if blend > 0.0: + now = oriented("current", current, load, load_c) + upper = (1.0 - blend) * upper + blend * now[0] + lower = (1.0 - blend) * lower + blend * now[1] + cap = (1.0 - blend) * cap + blend * now[2] + 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") + trial = element.f + element.k * increment + force = project_station_groups( + trial, upper, lower, cap, coupling.group_size + ) + slipping = force != trial + slip = np.where( + slipping, increment - (force - element.f) / element.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, lower, upper) + cap + moment[index] = weight * (force @ drive_map) + slipping_count[index] = np.count_nonzero(slipping) + stored[index] = weight * (force**2).sum() / (2 * current_stiffness) + totals[0] += weight * (force * (element.slip_total - old_plastic)).sum() + totals[1] += weight * (force * increment).sum() + totals[2] += ( + weight * ((force - old_stress) ** 2).sum() / (2 * current_stiffness) + ) + friction[index], endpoint[index], remainder[index], material[index] = ( + totals + ) + old_drive = drive + balance = endpoint + material - stored - friction - 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, 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), + caps, + ) + + def _law_threshold_layer(layer: HelicalLayerSpec, law: FrictionLaw) -> HelicalLayerSpec: """Layer with the smallest coefficient of the law (direction threshold; the smallest pressure factor included).""" diff --git a/src/cablexsec/mechanics/station_coupling.py b/src/cablexsec/mechanics/station_coupling.py new file mode 100644 index 0000000..3248a15 --- /dev/null +++ b/src/cablexsec/mechanics/station_coupling.py @@ -0,0 +1,279 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +r"""Coupled spring--slider stations of laid cores (relative intralayer slip). + +Used by :func:`cablexsec.mechanics.papailiou.wire_slip_history` when the +laid-core law takes ``CoreFrictionSpec(core_core_coupling="relative")`` +(:mod:`cablexsec.mechanics.core_friction`). Neighbouring cores of one layer +touch at the same axial position, and the friction between them acts on their +relative slip, so the stations of the core population that sit at one axial +position are not independent. + +Groups +------ +A population of ``K = n G`` stations at azimuths ``2 pi k / K`` stands for +``n`` cores; the ``n`` stations ``g, g + G, ..., g + (n - 1) G`` (azimuths +``2 pi / n`` apart) are the cores at one axial position, group ``g``. + +Bounds +------ +The friction stress of a station is the sum ``sigma = a + c`` of the friction +accumulated from the neutral axis over its interlayer contacts (filler, +bedding, sheath; the absolute slip of the core) and over its intralayer +contacts (the neighbouring cores; their relative slip): + +* ``-L <= a <= U``, the direction-tied bounds of the interlayer share (the + capstan form of :func:`~cablexsec.mechanics.papailiou.wire_slip_stress_bounds` + with the interlayer coefficient); +* ``-C <= c <= C``, ``C = sigma_0 mu_cc |sin b| g min(psi, pi / n)`` (constant + Coulomb bound of the core--core load, ``psi`` the angle of the station from + the neutral axis): the planar full-slip profile of the coupled law, whose + intralayer share grows at the full rate only over ``psi < pi / n``, where a + core slips against both neighbours in the same sense, and stays flat beyond, + where the two neighbours pull in opposite senses; +* ``c_g + c_{g+G} + ... = 0`` in every group: the friction between two + neighbours is an action and a reaction, so the intralayer shares of the + cores at one axial position cancel. + +The admissible set of a group is the Minkowski sum ``A + (B ∩ H)`` (``A`` the +interlayer box, ``B`` the intralayer box, ``H`` the zero-sum plane). Without +intralayer friction it is the box ``A`` and the return map is the clip of the +uncoupled law. + +Return map +---------- +The stations have equal stick stiffness, so the return map of a group is the +Euclidean closest point of the trial stress ``t`` on the admissible set. With +a multiplier ``nu`` of the zero-sum constraint, every station has the closed +form ``c = clip(t - U - nu, -C, C)`` for ``nu > 0`` and +``c = clip(t + L - nu, -C, C)`` for ``nu < 0``, then ``a = clip(t - c, -L, +U)``; ``nu = 0`` (the box clip ``clip(t, -(L + C), U + C)``) holds when +``sum clip(t - U, -C, C) <= 0 <= sum clip(t + L, -C, C)`` (to a round-off +margin of 1e-13 of the group's stress magnitudes, so that a group in stick +stays in stick exactly). Otherwise ``nu`` +is the root of the piecewise-linear, monotone ``sum c(nu) = 0``, found exactly +from its sorted breakpoints. The stress ``a + c`` is unique. The plastic work +of every update is non-negative (the set contains zero). + +Two implementations solve the same update: a NumPy path vectorised over the +groups and a compiled kernel (numba); they agree to round-off +(tests/test_core_coupled_slip.py). +""" + +from __future__ import annotations + +import math +from dataclasses import dataclass + +import numpy as np +from numpy.typing import NDArray + +from cablexsec._numba import HAVE_NUMBA, njit +from cablexsec.exceptions import CableInputError + +__all__ = [ + "StationCoupling", + "group_view", + "project_station_groups", +] + +FloatArray = NDArray[np.float64] + +#: Relative size of a zero-sum residual taken as round-off: a group whose box +#: clip leaves its intralayer shares out of balance by less than this times +#: the sum of its stress magnitudes keeps the box clip (stick stays stick). +_ROUND_OFF = 1.0e-13 + + +@dataclass(frozen=True) +class StationCoupling: + """Coupled groups of a station population (module notes). + + ``group_size`` is the number of cores ``n`` (stations per group), + ``interlayer_mu`` the load-weighted coefficient of the interlayer contacts + over the total core load (the capstan bound of the interlayer share takes + it with the total contact pressure), ``intralayer_mu`` the core--core + coefficient and ``intralayer_pressure_Pa`` the pressure equivalent + ``n q_cc / (2 pi r_c)`` of the core--core line load ``q_cc``. + """ + + group_size: int + interlayer_mu: float + intralayer_mu: float + intralayer_pressure_Pa: float + + def __post_init__(self) -> None: + n = self.group_size + if isinstance(n, bool) or not isinstance(n, int) or n < 2: + raise CableInputError("the coupled group size must be an integer >= 2") + for name in ("interlayer_mu", "intralayer_mu", "intralayer_pressure_Pa"): + value = getattr(self, name) + if not math.isfinite(value) or value < 0.0: + raise CableInputError(f"{name} must be finite and non-negative") + + @property + def plateau_rad(self) -> float: + """Angle from the neutral axis beyond which ``C`` is flat, ``pi / n``.""" + return math.pi / self.group_size + + +def group_view(values: FloatArray, group_size: int) -> FloatArray: + """Station values ``(K,)`` as groups ``(G, n)``: row ``g`` holds stations + ``g, g + G, ..., g + (n - 1) G`` (a view, no copy).""" + count = values.shape[0] + if count % group_size: + raise CableInputError( + f"{count} stations do not form groups of {group_size} cores" + ) + return values.reshape(group_size, count // group_size).T + + +def _root_numpy(d: FloatArray, cap: FloatArray) -> FloatArray: + """``nu > 0`` with ``sum clip(d - nu, -cap, cap) = 0`` row by row, for rows + whose sum at ``nu = 0`` is positive (so ``sum cap > 0``).""" + points = np.sort(np.concatenate((d - cap, d + cap), axis=1), axis=1) + values = np.sum( + np.clip(d[:, None, :] - points[:, :, None], -cap[:, None, :], cap[:, None, :]), + axis=2, + ) + # Non-increasing along the breakpoints, sum(cap) > 0 at the first and + # -sum(cap) < 0 at the last: the root lies after the last positive value. + upper = np.argmax(values <= 0.0, axis=1) + rows = np.arange(d.shape[0]) + x0, x1 = points[rows, upper - 1], points[rows, upper] + f0, f1 = values[rows, upper - 1], values[rows, upper] + return np.asarray(x0 + f0 * (x1 - x0) / (f0 - f1), dtype=np.float64) + + +def _project_numpy( + trial: FloatArray, upper: FloatArray, lower: FloatArray, cap: FloatArray +) -> FloatArray: + """NumPy path of :func:`project_station_groups` on ``(G, n)`` arrays.""" + out = np.clip(trial, -(lower + cap), upper + cap) + margin = _ROUND_OFF * np.sum(np.abs(trial) + upper + lower + cap, axis=1) + rising = np.sum(np.clip(trial - upper, -cap, cap), axis=1) > margin + falling = np.sum(np.clip(trial + lower, -cap, cap), axis=1) < -margin + for rows, sign in ((rising, 1.0), (falling, -1.0)): + if not np.any(rows): + continue + t, u, lo, c = trial[rows], upper[rows], lower[rows], cap[rows] + # Falling: the mirrored problem on -(t + L) has the same root form. + d = t - u if sign > 0.0 else -(t + lo) + nu = _root_numpy(d, c) + share = sign * np.clip(d - nu[:, None], -c, c) + out[rows] = np.clip(t - share, -lo, u) + share + return np.asarray(out, dtype=np.float64) + + +@njit(cache=True) +def _root_kernel(d: FloatArray, cap: FloatArray, points: FloatArray) -> float: + n = d.size + for i in range(n): + points[i] = d[i] - cap[i] + points[n + i] = d[i] + cap[i] + m = 2 * n + for i in range(1, m): # insertion sort (n is the core count) + key = points[i] + j = i - 1 + while j >= 0 and points[j] > key: + points[j + 1] = points[j] + j -= 1 + points[j + 1] = key + previous_x = points[0] + previous_f = 0.0 + for i in range(n): + previous_f += cap[i] + for k in range(1, m): + x = points[k] + f = 0.0 + for i in range(n): + v = d[i] - x + if v > cap[i]: + v = cap[i] + elif v < -cap[i]: + v = -cap[i] + f += v + if f <= 0.0: + return float(previous_x + previous_f * (x - previous_x) / (previous_f - f)) + previous_x = x + previous_f = f + return float(points[m - 1]) # pragma: no cover - unreachable (sum(cap) > 0) + + +@njit(cache=True) +def _project_kernel( + trial: FloatArray, + upper: FloatArray, + lower: FloatArray, + cap: FloatArray, + out: FloatArray, +) -> None: + """Compiled path of :func:`project_station_groups` on ``(G, n)`` arrays.""" + groups, n = trial.shape + d = np.empty(n) + c = np.empty(n) + points = np.empty(2 * n) + for g in range(groups): + rising = 0.0 + falling = 0.0 + margin = 0.0 + for i in range(n): + ci = cap[g, i] + v = trial[g, i] - upper[g, i] + rising += min(max(v, -ci), ci) + w = trial[g, i] + lower[g, i] + falling += min(max(w, -ci), ci) + margin += abs(trial[g, i]) + upper[g, i] + lower[g, i] + ci + margin *= _ROUND_OFF + if rising > margin: + sign = 1.0 + elif falling < -margin: + sign = -1.0 + else: + for i in range(n): + hi = upper[g, i] + cap[g, i] + lo = -(lower[g, i] + cap[g, i]) + out[g, i] = min(max(trial[g, i], lo), hi) + continue + for i in range(n): + c[i] = cap[g, i] + if sign > 0.0: + d[i] = trial[g, i] - upper[g, i] + else: + d[i] = -(trial[g, i] + lower[g, i]) + nu = _root_kernel(d, c, points) + for i in range(n): + share = sign * min(max(d[i] - nu, -c[i]), c[i]) + a = min(max(trial[g, i] - share, -lower[g, i]), upper[g, i]) + out[g, i] = a + share + + +def project_station_groups( + trial: FloatArray, + upper: FloatArray, + lower: FloatArray, + cap: FloatArray, + group_size: int, + *, + compiled: bool | None = None, +) -> FloatArray: + """Return map of the coupled station groups (module notes). + + ``trial``, ``upper``, ``lower`` (interlayer bounds, magnitudes) and ``cap`` + (intralayer bound ``C``) are per station, shape ``(K,)``; the result is + the stress of every station. ``compiled`` selects the numba kernel + (default: when numba is active) or the NumPy path. + """ + arrays = [ + group_view(np.ascontiguousarray(x, dtype=np.float64), group_size) + for x in (trial, upper, lower, cap) + ] + use_kernel = HAVE_NUMBA if compiled is None else compiled + if use_kernel: + t, u, lo, c = (np.ascontiguousarray(x) for x in arrays) + out = np.empty_like(t) + _project_kernel(t, u, lo, c, out) + else: + out = _project_numpy(*arrays) + # Back to station order (row g, column j is station j G + g). + return np.ascontiguousarray(out.T).reshape(-1) diff --git a/tests/test_core_coupled_slip.py b/tests/test_core_coupled_slip.py new file mode 100644 index 0000000..59e1c25 --- /dev/null +++ b/tests/test_core_coupled_slip.py @@ -0,0 +1,706 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Relative core--core slip of laid cores (``core_core_coupling="relative"``). + +The coupled station law of :mod:`cablexsec.mechanics.station_coupling` against +the independent field solver ``validation/scripts/coupled_core_slip_reference.py`` +(onset, full slip, moment, friction-stress distribution, reversal loop), its +limits, the agreement of the compiled and NumPy return maps, and the default +law, which is unchanged. +""" + +from __future__ import annotations + +import dataclasses +import math +import warnings + +import numpy as np +import pytest +from coupled_core_slip_reference import CoupledSlipReference, run_path + +import cablexsec as cx +from cablexsec.exceptions import CableInputError, CableSchemaError +from cablexsec.mechanics import station_coupling +from cablexsec.mechanics.core_friction import ( + CoreFrictionSpec, + build_core_friction, + core_friction_history, + core_full_slip_curvature, + core_full_slip_moment, + core_load_history, + core_station_bounds, + core_station_history, +) +from cablexsec.mechanics.mkappa import HelicalLayerSpec +from cablexsec.mechanics.papailiou import ( + coupled_slip_stress_bounds, + slip_onset_curvature, + wire_slip_history, +) +from cablexsec.mechanics.station_coupling import ( + StationCoupling, + group_view, + project_station_groups, +) +from cablexsec.provenance import FrictionModelFallbackWarning + +T = 50.0e3 +RELATIVE = CoreFrictionSpec(core_core_coupling="relative") +#: 2 pi / (3 sqrt 3): full slip over onset of three cores in core-core contact. +FULL_SLIP_RATIO = 2.0 * math.pi / (3.0 * math.sqrt(3.0)) + + +@pytest.fixture(scope="module") +def cable(): + return cx.load_cable(cx.iea_task49_66kv_yaml_path(), geometry_override=None) + + +def _population(n: int, spc: int, mu: float = 0.2) -> HelicalLayerSpec: + """Rigid stations of ``n`` cores, lay angle small enough that the capstan + term of the interlayer bound stays below 2e-4 relative.""" + return HelicalLayerSpec( + n_wires=n * spc, + r_helix_m=0.05, + lay_angle_rad=math.asin(1.0e-3), + E_wire_Pa=1.0e10, + A_wire_m2=1.0e-4, + xi=1.0, + mu=mu, + F_n_axi_N=100.0, + contact_pressure_Pa=1.0e5, + normal_load_is_line=True, + ) + + +def _library(share_cc: float, a: np.ndarray, *, n: int = 3, spc: int = 240): + """Coupled law at ``a = kappa / kappa_on``: interlayer coefficient + ``mu (1 - share)``, core-core coefficient ``mu`` on ``share`` of the load.""" + layer = _population(n, spc) + coupling = StationCoupling( + n, layer.mu * (1.0 - share_cc), layer.mu, layer.contact_pressure_Pa * share_cc + ) + on = slip_onset_curvature(layer) + history = wire_slip_history( + layer, + a * on, + np.zeros_like(a), + coupling=coupling, + direction_hold_fraction=0.0, + ) + return history, layer, on + + +# --------------------------------------------------------------------------- # +# Independent field solver (registered comparison) # +# --------------------------------------------------------------------------- # +CASES = { + # label: (b_a, b_c, core-core share of the capacity) + "intralayer": (0.0, 1.0, 1.0), + "mixed": (1.0, 0.5, 0.5), + "interlayer": (1.0, 0.0, 0.0), +} + + +@pytest.fixture(scope="module", params=sorted(CASES)) +def loop(request): + """Reference and library over 0 -> 1.7 -> -1.7 -> 1.7 (units of onset).""" + b_a, b_c, share = CASES[request.param] + ref = CoupledSlipReference(nodes=240, b_c=b_c, b_a=b_a) + up = np.concatenate([[0.5, 0.9, 0.98], np.arange(1.0025, 1.7 + 1e-9, 0.0075)]) + down = np.arange(1.7, -1.7 - 1e-9, -0.02)[1:] + back = np.arange(-1.7, 1.7 + 1e-9, 0.02)[1:] + path = np.concatenate([up, down, back]) + keep = tuple(int(np.argmin(np.abs(up - v))) for v in (0.98, 1.03, 1.1, 1.2, 1.5)) + out = run_path(ref, path * ref.a_cr, keep=keep) + history, layer, on = _library(share, path) + return request.param, ref, path, up.size, keep, out, history, layer, on + + +@pytest.mark.independent_method +def test_moment_curvature_and_reversal_match_the_field_solver(loop): + # Q3, Q5: moment along the loop within 3e-3 of the full-slip moment, cycle + # dissipation within 2 %. + _, ref, path, n_up, _, out, history, layer, on = loop + m_ref = out.moment / (0.5 * ref.n_cores * ref.a_cr) + m_lib = history.moment_Nm[:, 0] / (layer.EI_stick * on) + full = m_ref[n_up - 1] + assert np.max(np.abs(m_lib - m_ref)) <= 3e-3 * full + w_ref = out.dissipation / (2.0 * math.pi * 0.5 * ref.n_cores * ref.a_cr**2) + w_lib = history.work.friction_J_per_m / (layer.EI_stick * on**2) + cycle_ref = w_ref[-1] - w_ref[n_up - 1] + cycle_lib = w_lib[-1] - w_lib[n_up - 1] + assert cycle_lib == pytest.approx(cycle_ref, rel=0.02) + + +@pytest.mark.independent_method +def test_friction_stress_distribution_matches_the_field_solver(loop): + # Q4: the axial friction force along the pitch at 1.03, 1.1, 1.2, 1.5 onset. + name, ref, path, _, keep, out, history, layer, on = loop + theta = out.segment_azimuth[0] + plateau = ref.b_a * math.pi / 2 + 2.0 * ref.b_c * min(math.pi / 3, math.pi / 2) + phi = layer.phi_wires + for index in keep[1:]: + n_ref = np.interp(phi, theta, out.forces[index][0], period=2 * math.pi) + n_lib = history.stress_Pa[:, index] / (layer.k_f * layer.r_helix_m * on) + n_lib = n_lib * ref.a_cr + diff = np.abs(n_lib - n_ref) + assert np.sqrt(np.mean(diff**2)) <= 1e-2 * plateau, (name, path[index]) + assert np.max(diff) <= 4e-2 * plateau, (name, path[index]) + + +@pytest.mark.independent_method +def test_onset_matches_the_field_solver(loop): + # Q1: no macroscopic slip of the rigid-contact limit at 0.98 onset, slip at + # 1.03 onset; the library onset is the absolute one. + _, ref, path, _, keep, out, history, layer, on = loop + theta = out.segment_azimuth + k = min(ref.k_a if ref.b_a > 0 else ref.k_c, ref.k_c if ref.b_c > 0 else ref.k_a) + for index, below in ((keep[0], True), (keep[1], False)): + a = path[index] * ref.a_cr + slip = np.max(np.abs(out.forces[index] - a * np.cos(theta))) + assert (slip < 20.0 / k) if below else (slip > 100.0 / k) + assert history.slipping_count[keep[0]] == 0 + assert history.slipping_count[keep[1]] > 0 + + +def _reference_full_slip(b_a: float, b_c: float) -> float: + """First curvature (units of onset) at which the reference tangent of the + moment falls below 1e-3 of the stick tangent.""" + ref = CoupledSlipReference(nodes=360, b_c=b_c, b_a=b_a) + a = np.concatenate( + [[0.95], np.arange(1.0, 1.15, 0.01), np.arange(1.15, 1.45, 0.002)] + ) + out = run_path(ref, a * ref.a_cr) + m = out.moment / (0.5 * ref.n_cores * ref.a_cr) + tangent = np.diff(m) / np.diff(a) + flat = np.flatnonzero(tangent < 1e-3) + return float(a[flat[0]]) + + +def _library_full_slip(share: float) -> float: + a = np.linspace(0.0, 1.6, 6401) + history, layer, on = _library(share, a, spc=120) + history = wire_slip_history( + layer, + a * on, + 0 * a, + coupling=StationCoupling( + 3, layer.mu * (1 - share), layer.mu, layer.contact_pressure_Pa * share + ), + direction_hold_fraction=0.0, + keep_cap=True, + ) + loaded = np.abs(np.cos(layer.phi_wires)) > 1e-9 + stress = np.abs(history.stress_Pa[loaded]) + on_bound = np.all(stress >= history.cap_Pa[loaded] * (1 - 1e-12), axis=0) + return float(a[np.argmax(on_bound)]) + + +@pytest.mark.independent_method +@pytest.mark.parametrize(("b_a", "b_c", "share"), [(0.0, 1.0, 1.0), (1.0, 0.5, 0.5)]) +def test_full_slip_curvature_matches_the_field_solver(b_a, b_c, share): + # Q2: within 1 %; the pure intralayer value is 2 pi / (3 sqrt 3). + reference = _reference_full_slip(b_a, b_c) + library = _library_full_slip(share) + assert library == pytest.approx(reference, rel=0.01) + if share == 1.0: + assert library == pytest.approx(FULL_SLIP_RATIO, rel=2e-3) + assert reference == pytest.approx(FULL_SLIP_RATIO, rel=0.01) + + +def _closed_form_profile(psi: np.ndarray, b_a: float, b_c: float, n: int = 3): + """Planar full-slip friction force at the angle ``psi`` from the neutral + axis: interlayer b_a psi plus intralayer 2 b_c min(psi, pi / n).""" + return b_a * psi + 2.0 * b_c * np.minimum(psi, math.pi / n) + + +@pytest.mark.independent_method +@pytest.mark.parametrize(("b_a", "b_c", "share"), [(0.0, 1.0, 1.0), (1.0, 0.5, 0.5)]) +def test_full_slip_profile_and_moment_closed_form(b_a, b_c, share): + # Q6: the frozen full-slip profile of the reference and of the library. + ref = CoupledSlipReference(nodes=360, b_c=b_c, b_a=b_a) + a = np.array([0.9, 1.2, 1.5, 1.8, 2.0]) * ref.a_cr + out = run_path(ref, a, keep=(4,)) + theta = out.segment_azimuth[0] + psi = np.arcsin(np.abs(np.cos(theta))) + profile = np.sign(np.cos(theta)) * _closed_form_profile(psi, b_a, b_c) + scale = float(np.max(np.abs(profile))) + assert np.max(np.abs(out.forces[4][0] - profile)) <= 1e-3 * scale + history, layer, on = _library(share, a / ref.a_cr) + psi_l = np.arcsin(np.abs(np.cos(layer.phi_wires))) + profile_l = np.sign(np.cos(layer.phi_wires)) * _closed_form_profile(psi_l, b_a, b_c) + n_lib = history.stress_Pa[:, -1] / (layer.k_f * layer.r_helix_m * on) * ref.a_cr + assert np.max(np.abs(n_lib - profile_l)) <= 1e-3 * scale + # Pure intralayer: sqrt(3)/2 of the uncoupled full-slip moment. + if share == 1.0: + uncoupled = 4.0 / math.pi + assert out.moment[-1] / (1.5 * ref.a_cr) == pytest.approx( + math.sqrt(3) / 2 * uncoupled, rel=1e-3 + ) + + +# --------------------------------------------------------------------------- # +# Limits # +# --------------------------------------------------------------------------- # +def _planar_and_biaxial(): + t = np.linspace(0.0, 2.0, 121) + return 2.0e-3 * np.sin(np.pi * t), 0.6e-3 * np.sin(2 * np.pi * t) + + +@pytest.mark.analytical_sanity +@pytest.mark.parametrize("contact_model", ["bounded", "solved"]) +def test_no_core_core_friction_gives_the_interlayer_law(cable, contact_model): + spec = CoreFrictionSpec(mu_core_core=0.0, filler_profiles=True) + kx, ky = _planar_and_biaxial() + absolute = build_core_friction(cable, spec, T, contact_model=contact_model) + relative = build_core_friction( + cable, + dataclasses.replace(spec, core_core_coupling="relative"), + T, + contact_model=contact_model, + ) + a = core_friction_history(absolute, kx, ky) + b = core_friction_history(relative, kx, ky) + scale = float(np.max(np.abs(a.moment_Nm))) + assert np.max(np.abs(a.moment_Nm - b.moment_Nm)) <= 1e-12 * scale + assert b.work.friction_J_per_m[-1] == pytest.approx( + a.work.friction_J_per_m[-1], rel=1e-12 + ) + + +@pytest.mark.analytical_sanity +def test_no_core_core_load_gives_the_absolute_law(cable): + # A central filler takes the inward core loads: no core-core contact. + spec = CoreFrictionSpec(central_filler=True) + absolute = build_core_friction(cable, spec, T) + relative = build_core_friction( + cable, dataclasses.replace(spec, core_core_coupling="relative"), T + ) + assert absolute.loads.core_core_N_per_m == 0.0 + kx, ky = _planar_and_biaxial() + a = core_friction_history(absolute, kx, ky) + b = core_friction_history(relative, kx, ky) + scale = float(np.max(np.abs(a.moment_Nm))) + assert np.max(np.abs(a.moment_Nm - b.moment_Nm)) <= 1e-12 * scale + + +@pytest.mark.analytical_sanity +def test_pure_intralayer_cores_reach_full_slip_at_the_coupled_ratio(cable): + spec = CoreFrictionSpec( + mu_core_filler=0.0, + mu_core_sheath=0.0, + core_core_coupling="relative", + n_stations_per_core=240, + ) + model = build_core_friction(cable, spec, T) + assert model.coupling is not None + assert model.coupling.interlayer_mu == 0.0 + on = slip_onset_curvature(model.population) + assert core_full_slip_curvature(model) / on == pytest.approx( + FULL_SLIP_RATIO, rel=2e-3 + ) + # Full-slip moment: sqrt(3)/2 of the uncoupled one with the same + # (linear) bound. + upper, lower, cap = coupled_slip_stress_bounds( + model.population, model.coupling, 0.0 + ) + psi = np.arcsin(np.abs(np.cos(model.population.phi_wires))) + linear = cap / np.minimum(psi, math.pi / 3).clip(1e-300) * psi + c = np.abs(np.cos(model.population.phi_wires)) + ratio = np.sum(cap * c) / np.sum(linear * c) + assert ratio == pytest.approx(math.sqrt(3) / 2, rel=1e-4) + weight = ( + model.population.A_wire_m2 + * math.cos(model.population.lay_angle_rad) + * model.population.r_helix_m + ) + assert core_full_slip_moment(model) == pytest.approx( + weight * np.sum(cap * c), rel=1e-12 + ) + + +@pytest.mark.analytical_sanity +def test_two_cores_slip_as_the_absolute_law_without_capstan(): + # Two cores slip relative to each other in the sense of their absolute slip. + layer = _population(2, 90) + on = slip_onset_curvature(layer) + a = np.concatenate([np.linspace(0, 3, 61), np.linspace(3, -3, 121)[1:]]) + coupled = wire_slip_history( + layer, + a * on, + 0.3 * a * on, + coupling=StationCoupling(2, 0.0, layer.mu, layer.contact_pressure_Pa), + ) + absolute = wire_slip_history(layer, a * on, 0.3 * a * on) + scale = float(np.max(np.abs(absolute.moment_Nm))) + lam = layer.mu * math.sin(layer.lay_angle_rad) + assert lam <= 2e-4 + assert np.max(np.abs(coupled.moment_Nm - absolute.moment_Nm)) <= 5 * lam * scale + + +@pytest.mark.analytical_sanity +def test_cables_without_laid_core_family_are_rejected_alike(): + single = cx.load_cable(cx.inter_array_single_core_yaml_path()) + messages = [] + for spec in (CoreFrictionSpec(), RELATIVE): + with pytest.raises(CableSchemaError) as error: + build_core_friction(single, spec, T) + messages.append(str(error.value)) + assert messages[0] == messages[1] + + +@pytest.mark.analytical_sanity +def test_stick_state_and_onset_are_those_of_the_absolute_law(cable): + absolute = build_core_friction(cable, CoreFrictionSpec(), T) + relative = build_core_friction(cable, RELATIVE, T) + assert relative.stick_EI_Nm2 == absolute.stick_EI_Nm2 + assert relative.xi == absolute.xi + on = slip_onset_curvature(absolute.population) + k = np.linspace(0.0, 0.95 * on, 20) + a = core_friction_history(absolute, k, 0 * k) + b = core_friction_history(relative, k, 0 * k) + assert np.max(np.abs(a.moment_Nm - b.moment_Nm)) <= 1e-12 * float( + np.max(np.abs(a.moment_Nm)) + ) + # The bounds a station holds in full slip: interlayer plus intralayer. + upper, lower = core_station_bounds(relative, 0.3) + u_a, l_a, cap = coupled_slip_stress_bounds( + relative.population, relative.coupling, 0.3 + ) + np.testing.assert_array_equal(upper, u_a + cap) + np.testing.assert_array_equal(lower, l_a + cap) + + +# --------------------------------------------------------------------------- # +# Default law unchanged # +# --------------------------------------------------------------------------- # +#: The default law on dev e9b3f8f (before the coupling option): moment +#: components at two samples, final friction work, and the same with a +#: tension-following load history (66 kV template, filler profiles). +GOLDEN = { + "bounded": ( + -51.667575888214344, + -5.9973057283196995, + 0.20684780454609583, + -99.55404704200525, + 0.1910175589473319, + ), + "solved": ( + -35.8886511509267, + -6.336827311759066, + 0.17858448424133866, + -72.95869295260198, + 0.17278280109502678, + ), +} + + +@pytest.mark.analytical_sanity +@pytest.mark.parametrize("contact_model", ["bounded", "solved"]) +def test_default_law_is_unchanged(cable, contact_model): + model = build_core_friction( + cable, CoreFrictionSpec(filler_profiles=True), T, contact_model=contact_model + ) + assert model.coupling is None + t = np.linspace(0.0, 2.0, 81) + kx = 1.5e-3 * np.sin(np.pi * t) + ky = 0.4e-3 * np.sin(2 * np.pi * t) + h = core_friction_history(model, kx, ky) + loads = core_load_history( + cable, model, 30e3 + 40e3 * t, contact_model=contact_model + ) + assert loads.core_intralayer_pressure_Pa is None + h2 = core_friction_history(model, kx, ky, loads=loads) + values = ( + float(h.moment_Nm[40, 0]), + float(h.moment_Nm[60, 1]), + float(h.work.friction_J_per_m[-1]), + float(h2.moment_Nm[50, 0]), + float(h2.work.friction_J_per_m[-1]), + ) + # The solved trefoil comes from an iterative radial solve, which converges + # to its own tolerance (the compiled and the plain build differ by a few + # 1e-9); the bounded chain is closed form. + rtol = 1e-12 if contact_model == "bounded" else 1e-7 + np.testing.assert_allclose(values, GOLDEN[contact_model], rtol=rtol, atol=0) + # In the same run the default core law is the independent-station + # update, bit for bit. + direct = wire_slip_history( + model.population, + kx, + ky, + direction_hold_fraction=model.spec.direction_hold_fraction, + ) + np.testing.assert_array_equal(h.core_moment_Nm, direct.moment_Nm) + station = core_station_history(model, kx, ky) + np.testing.assert_array_equal(station.stress_Pa, direct.stress_Pa) + assert core_full_slip_moment(model) > 0.0 + + +# --------------------------------------------------------------------------- # +# Return map: compiled and NumPy paths # +# --------------------------------------------------------------------------- # +def _random_groups(rng, groups: int, n: int): + upper = rng.uniform(0.0, 1.0, (groups, n)) * (rng.random((groups, n)) > 0.2) + lower = upper * rng.uniform(0.5, 1.0, (groups, n)) + cap = rng.uniform(0.0, 1.5, (groups, n)) * (rng.random((groups, n)) > 0.1) + trial = rng.normal(0.0, 2.0, (groups, n)) + return trial, upper, lower, cap + + +def _stations(x: np.ndarray) -> np.ndarray: + return np.ascontiguousarray(x.T).reshape(-1) + + +@pytest.mark.analytical_sanity +@pytest.mark.parametrize("n", [2, 3, 4]) +def test_compiled_and_numpy_return_maps_agree_and_are_optimal(n): + rng = np.random.default_rng(7 + n) + trial, upper, lower, cap = _random_groups(rng, 400, n) + args = [_stations(x) for x in (trial, upper, lower, cap)] + fast = project_station_groups(*args, n, compiled=True) + slow = project_station_groups(*args, n, compiled=False) + scale = float(np.max(np.abs(args[0]))) + assert np.max(np.abs(fast - slow)) <= 1e-12 * scale + s = group_view(slow, n) + # Admissible: a decomposition a + c with sum(c) = 0 exists, and the result + # is the closest admissible point (variational inequality against random + # admissible points). + lo_c = np.maximum(s - upper, -cap) + hi_c = np.minimum(s + lower, cap) + tol = 1e-12 * scale + assert np.all(lo_c <= hi_c + tol) + assert np.all(lo_c.sum(axis=1) <= tol) + assert np.all(hi_c.sum(axis=1) >= -tol) + for _ in range(20): + a = rng.uniform(-lower, upper) + c = rng.uniform(-cap, cap) + c -= c.mean(axis=1, keepdims=True) + inside = np.all(np.abs(c) <= cap, axis=1) + y = a + c + inner = np.sum((trial - s) * (y - s), axis=1) + assert np.all(inner[inside] <= 1e-10 * scale**2) + # A point that is admissible is its own projection. + again = project_station_groups(_stations(s), *args[1:], n, compiled=False) + assert np.max(np.abs(again - slow)) <= 1e-12 * scale + + +@pytest.mark.analytical_sanity +def test_core_history_is_the_same_on_both_return_maps(cable, monkeypatch): + model = build_core_friction(cable, RELATIVE, T) + kx, ky = _planar_and_biaxial() + monkeypatch.setattr(station_coupling, "HAVE_NUMBA", True) + fast = core_friction_history(model, kx, ky) + monkeypatch.setattr(station_coupling, "HAVE_NUMBA", False) + slow = core_friction_history(model, kx, ky) + scale = float(np.max(np.abs(slow.moment_Nm))) + assert np.max(np.abs(fast.moment_Nm - slow.moment_Nm)) <= 1e-12 * scale + assert np.max(np.abs(fast.work.friction_J_per_m - slow.work.friction_J_per_m)) <= ( + 1e-12 * float(np.max(np.abs(slow.work.friction_J_per_m))) + ) + + +# --------------------------------------------------------------------------- # +# Routes and inputs # +# --------------------------------------------------------------------------- # +def test_relative_law_lowers_the_slip_moment_and_keeps_energy(cable): + absolute = build_core_friction(cable, CoreFrictionSpec(), T) + relative = build_core_friction(cable, RELATIVE, T) + assert relative.loads.core_core_N_per_m > 0.0 + on = slip_onset_curvature(absolute.population) + k = np.concatenate([np.linspace(0, 6 * on, 121), np.linspace(6 * on, -6 * on, 241)]) + a = core_friction_history(absolute, k, 0 * k) + b = core_friction_history(relative, k, 0 * k) + assert abs(b.core_moment_Nm[120, 0]) < abs(a.core_moment_Nm[120, 0]) + assert core_full_slip_moment(relative) == pytest.approx( + abs(b.core_moment_Nm[120, 0]), rel=1e-9 + ) + assert core_full_slip_curvature(relative) < core_full_slip_curvature(absolute) + balance = b.work.balance_residual_J_per_m + assert np.max(np.abs(balance)) <= 1e-9 * float(np.max(b.work.endpoint_work_J_per_m)) + assert np.all(np.diff(b.work.friction_J_per_m) >= -1e-15) + + +def test_relative_load_history_follows_the_core_core_load(cable): + model = build_core_friction(cable, RELATIVE, T) + tension = np.linspace(10e3, 120e3, 50) + loads = core_load_history(cable, model, tension) + assert loads.core_intralayer_pressure_Pa is not None + reference = model.coupling.intralayer_pressure_Pa + i = int(np.argmin(np.abs(tension - T))) + assert loads.core_intralayer_pressure_Pa[i] == pytest.approx(reference, rel=0.05) + assert np.all(np.diff(loads.core_intralayer_pressure_Pa) > 0.0) + on = slip_onset_curvature(model.population) + k = np.linspace(0.0, 5 * on, 50) + held = core_friction_history(model, k, 0 * k) + follow = core_friction_history(model, k, 0 * k, loads=loads) + assert abs(follow.core_moment_Nm[-1, 0]) > abs(held.core_moment_Nm[-1, 0]) + # A history of the absolute law does not fit the relative model, and back. + absolute = build_core_friction(cable, CoreFrictionSpec(), T) + other = core_load_history(cable, absolute, tension) + for m, h in ((model, other), (absolute, loads)): + with pytest.raises(CableInputError, match="core-core coupling differs"): + core_friction_history(m, k, 0 * k, loads=h) + + +def test_relative_load_history_with_an_unloaded_interlayer_reference(cable): + # Interlayer coefficient zero at the reference, positive later: the + # pressure is normalised by the most loaded sample. + spec = CoreFrictionSpec(mu_core_sheath=0.0, core_core_coupling="relative") + model = build_core_friction(cable, dataclasses.replace(spec, mu_core_filler=0.0), T) + assert model.coupling.interlayer_mu == 0.0 + loads = core_load_history(cable, dataclasses.replace(model, spec=spec), [T, 2 * T]) + assert loads.core_mu_capstan > 0.0 + assert np.all(np.isfinite(loads.core_pressure_Pa)) + + +def test_relative_law_is_direction_tied(cable): + model = build_core_friction(cable, RELATIVE, T) + t = np.linspace(0.0, 2 * np.pi, 60) + on = slip_onset_curvature(model.population) + kx, ky = 3 * on * np.cos(t), 3 * on * np.sin(t) + with pytest.raises(CableInputError, match="direction-tied law"): + core_friction_history(model, kx, ky, friction_model="distributed") + with pytest.warns(FrictionModelFallbackWarning, match="relative core-core"): + auto = core_friction_history(model, kx, ky, friction_model="auto") + assert auto.friction_model == "direction_tied" + with warnings.catch_warnings(): + warnings.simplefilter("error") + planar = core_friction_history(model, kx, 0 * ky, friction_model="auto") + assert planar.friction_model == "direction_tied" + + +def test_relative_specification_and_station_inputs(): + with pytest.raises(CableInputError, match="core_core_coupling"): + CoreFrictionSpec(core_core_coupling="neighbours") # type: ignore[arg-type] + for bad in ( + {"group_size": 1}, + {"group_size": True}, + {"interlayer_mu": -0.1}, + {"intralayer_pressure_Pa": math.inf}, + ): + values = { + "group_size": 3, + "interlayer_mu": 0.1, + "intralayer_mu": 0.2, + "intralayer_pressure_Pa": 1.0, + } + values.update(bad) + with pytest.raises(CableInputError): + StationCoupling(**values) + with pytest.raises(CableInputError, match="groups of 3"): + group_view(np.zeros(10), 3) + layer = _population(3, 4) + coupling = StationCoupling(3, 0.1, 0.2, 1e5) + k = np.linspace(0.0, 1e-3, 5) + with pytest.raises(CableInputError, match="friction law"): + wire_slip_history( + layer, + k, + k, + coupling=coupling, + friction_law=cx.FrictionLaw(static_factor=1.2, stick_time_s=0.0), + time_s=np.arange(5.0), + ) + with pytest.raises(CableInputError, match="needs a station coupling"): + wire_slip_history(layer, k, k, intralayer_pressure_Pa=np.ones(5)) + with pytest.raises(CableInputError, match="groups of 5"): + wire_slip_history( + _population(1, 12), k, k, coupling=StationCoupling(5, 0.1, 0.2, 1.0) + ) + with pytest.raises(CableInputError, match="intralayer pressure must"): + wire_slip_history(layer, k, k, coupling=coupling, intralayer_pressure_Pa=[1.0]) + with pytest.raises(CableInputError, match="nonnegative intralayer"): + wire_slip_history( + layer, k, k, coupling=coupling, intralayer_pressure_Pa=-np.ones(5) + ) + # Zero intralayer friction gives no intralayer bound; keep_cap reports + # the station bound of the side of the stress. + upper, lower, cap = coupled_slip_stress_bounds( + layer, dataclasses.replace(coupling, intralayer_mu=0.0), 0.0 + ) + assert not np.any(cap) + history = wire_slip_history( + layer, + 5 * k, + 0 * k, + coupling=coupling, + keep_cap=True, + direction_hold_fraction=0.0, + ) + assert history.cap_Pa is not None + assert np.all(np.abs(history.stress_Pa) <= history.cap_Pa * (1 + 1e-12)) + # Below the direction threshold the three bounds are blended. + tiny = wire_slip_history(layer, 1e-9 * k, 1e-9 * k[::-1], coupling=coupling) + assert np.all(tiny.slipping_count == 0) + + +def test_relative_routes_of_the_section(cable): + from cablexsec.analysis.components import _core_axis + from cablexsec.mechanics.core_kinematics import core_kinematics + from cablexsec.mechanics.section_state import solve_section_state + + on = slip_onset_curvature(build_core_friction(cable, RELATIVE, T).population) + k = np.linspace(0.0, 4 * on, 40) + for spec in (CoreFrictionSpec(), RELATIVE): + kin = core_kinematics( + cable, + k, + 0.2 * k, + state="frictional", + core_friction=spec, + contact_tension_N=T, + ) + assert kin.slipping is not None and kin.slipping[:, -1].any() + state = solve_section_state(cable, tension_N=T, contact_model="bounded") + layer = next(x for x in cable.layers if getattr(x, "r_offset_m", None)) + absolute = _core_axis(cable, layer, state, 4 * on, 0.0, CoreFrictionSpec()) + relative = _core_axis(cable, layer, state, 4 * on, 0.0, RELATIVE) + assert "relative core-core slip" in relative.note + np.testing.assert_allclose(relative.stuck, absolute.stuck) + # The core on the extreme fibre holds the plateau of the coupled profile. + assert abs(relative.frictional[0]) < abs(absolute.frictional[0]) + zero = _core_axis(cable, layer, state, 0.0, 0.0, RELATIVE) + assert not np.any(zero.frictional) + + +def test_coupled_stations_with_contact_shape_and_changing_stiffness(): + layer = _population(3, 8) + shaped = dataclasses.replace(layer, shape_g=np.ones(layer.n_wires)) + coupling = StationCoupling(3, 0.1, 0.2, 5e4) + for part, other in zip( + coupled_slip_stress_bounds(layer, coupling, 0.4), + coupled_slip_stress_bounds(shaped, coupling, 0.4), + strict=True, + ): + np.testing.assert_array_equal(part, other) + on = slip_onset_curvature(layer) + a = np.concatenate([np.linspace(0, 4, 41), np.linspace(4, -4, 81)[1:]]) + stiffness = layer.k_f * np.linspace(1.0, 0.8, a.size) + history = wire_slip_history( + shaped, a * on, 0.2 * a * on, coupling=coupling, stick_modulus_Pa=stiffness + ) + scale = float(np.max(np.abs(history.work.endpoint_work_J_per_m))) + assert np.max(np.abs(history.work.balance_residual_J_per_m)) <= 1e-9 * scale + assert np.any(history.material_work_J_per_m != 0.0) + + +def test_coupled_full_slip_curvature_inputs(cable): + free = CoreFrictionSpec( + mu_core_filler=0.0, + mu_core_core=0.0, + mu_core_sheath=0.0, + core_core_coupling="relative", + ) + model = build_core_friction(cable, free, T) + assert core_full_slip_curvature(model) == 0.0 + with pytest.raises(CableInputError, match="finite"): + core_full_slip_curvature(build_core_friction(cable, RELATIVE, T), math.nan) + absolute = build_core_friction(cable, CoreFrictionSpec(), T) + upper, lower = core_station_bounds(absolute, 0.2) + from cablexsec.mechanics.papailiou import wire_slip_stress_bounds + + reference = wire_slip_stress_bounds(absolute.population, 0.2) + np.testing.assert_array_equal(upper, reference[0]) + np.testing.assert_array_equal(lower, reference[1]) diff --git a/validation/scripts/coupled_core_slip_reference.py b/validation/scripts/coupled_core_slip_reference.py new file mode 100644 index 0000000..6cd08ea --- /dev/null +++ b/validation/scripts/coupled_core_slip_reference.py @@ -0,0 +1,313 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +r"""Independent field solver of the coupled axial slip of laid cores. + +Reference for ``CoreFrictionSpec(core_core_coupling="relative")`` +(:mod:`cablexsec.mechanics.core_friction`). It imports only NumPy and SciPy and +shares no code with the package. + +Model (normalised, one pitch, periodic). ``n`` equal cores; ``x`` is the +azimuth of core 0 along the pitch and core ``i`` sits at the azimuth +``theta_i = x + 2 pi i / n``. Each core has its own field (no symmetry +reduction): the slip ``u_i(x)`` relative to the plane section and the axial +force ``n_i = a cos(theta_i - phi_b) + u_i'`` (``a`` the curvature in units in +which the axial rigidity and the helix geometry are one). Equilibrium +``n_i' = -f_i``, with the contact forces per unit ``x``: + +* intralayer contacts between neighbours ``(i, j)`` at the same ``x``: an + elastic--Coulomb spring on the relative slip ``u_i - u_j`` (penalty ``k_c``, + bound ``b_c``); the force on ``j`` is minus the force on ``i``; +* an interlayer contact of every core (filler, bedding, sheath): an + elastic--Coulomb spring on the absolute slip ``u_i`` (``k_a``, ``b_a``). + +Bounds are linear Coulomb bounds (no capstan term). The rigid contact is the +limit of a large penalty. + +Discretisation: ``N`` nodes per core and pitch, ``h = 2 pi / N``; nodes carry +``u`` and the contact springs, segments ``j`` (between nodes ``j`` and +``j + 1``, at ``x = (j + 1/2) h``) carry ``n``. Each load increment minimises +the incremental energy + + sum_i sum_j h n_ij^2 / 2 + sum_springs h Huber_{k, b}(r - p_old) + +over the nodal slips (``r`` the spring's relative or absolute slip, ``p_old`` +its slip at the start of the increment; the Huber envelope is the exact +backward-Euler potential of a spring--slider), by semismooth Newton with Armijo +backtracking and sparse direct solves. The pitch mean of every core's slip is +held at zero by Lagrange multipliers: this fixes the slides of whole cores that +change no force (a common slide without interlayer friction, and per-core +slides in full slip). On a planar path from a stress-free state the slip of +every core has zero pitch mean, so the constraint changes nothing else. + +Outputs per sample: the section moment of the cores (pitch mean of +``n cos(theta - phi_b)`` summed over the cores; the stuck moment is +``n a / 2``), the dissipated work, the fraction of springs in stick, and on +request the force fields. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field + +import numpy as np +import scipy.sparse as sp +from numpy.typing import NDArray +from scipy.sparse.linalg import splu + +FloatArray = NDArray[np.float64] + +__all__ = ["CoupledSlipReference", "ReferencePath", "run_path"] + + +@dataclass(frozen=True) +class CoupledSlipReference: + """Cores, contacts and grid of the reference model. + + ``b_c`` is the bound of one intralayer contact (``n >= 3``: two contacts + per core; ``n = 2``: the single contact takes ``2 b_c``, so the per-core + capacity is ``b_a + 2 b_c`` in every case). ``a_cr = b_a + 2 b_c`` is the + uncoupled slip-onset curvature. + """ + + n_cores: int = 3 + nodes: int = 720 + b_c: float = 1.0 + b_a: float = 0.0 + k_c: float = 1.0e5 + k_a: float = 1.0e5 + + @property + def a_cr(self) -> float: + return self.b_a + 2.0 * self.b_c + + def contacts(self) -> list[tuple[int, int, float]]: + n = self.n_cores + if n == 2: + return [(0, 1, 2.0 * self.b_c)] if self.b_c > 0 else [] + if self.b_c <= 0: + return [] + return [(i, (i + 1) % n, self.b_c) for i in range(n)] + + +@dataclass +class ReferencePath: + """Results of :func:`run_path` (one entry per curvature sample).""" + + a: FloatArray + moment: FloatArray + dissipation: FloatArray + stick_fraction: FloatArray + newton_iterations: NDArray[np.int64] + forces: dict[int, FloatArray] = field(default_factory=dict) + contact_forces: dict[int, FloatArray] = field(default_factory=dict) + interlayer_forces: dict[int, FloatArray] = field(default_factory=dict) + segment_azimuth: FloatArray | None = None + + +def _huber(r: FloatArray, k: float, b: float) -> tuple[FloatArray, ...]: + """Value, slope and curvature of the Huber envelope at ``r``.""" + limit = b / k + inside = np.abs(r) <= limit + value = np.where(inside, 0.5 * k * r * r, b * np.abs(r) - 0.5 * b * limit) + slope = np.clip(k * r, -b, b) + # A spring on its bound at the start of an increment (|k r| = b after the + # last update) is taken as sticking; the Newton step then decides. + curvature = np.where(np.abs(k * r) <= b * (1.0 + 1e-12), k, 0.0) + return value, slope, curvature + + +class _Solver: + def __init__(self, ref: CoupledSlipReference, phi_b: float) -> None: + self.ref = ref + n, big_n = ref.n_cores, ref.nodes + self.n, self.N = n, big_n + self.h = 2.0 * np.pi / big_n + x_seg = (np.arange(big_n) + 0.5) * self.h + self.theta = x_seg[None, :] + 2.0 * np.pi * np.arange(n)[:, None] / n + self.shape = np.cos(self.theta - phi_b) # (n, N) + self.contacts = ref.contacts() + self.u = np.zeros((n, big_n)) + self.p_c = np.zeros((len(self.contacts), big_n)) + self.p_a = np.zeros((n, big_n)) + # Difference operator D u = (u_{j+1} - u_j) / h, periodic, per core. + eye = sp.identity(big_n, format="csr") + shift = sp.csr_matrix( + (np.ones(big_n), (np.arange(big_n), (np.arange(big_n) + 1) % big_n)), + shape=(big_n, big_n), + ) + d1 = (shift - eye) / self.h + self.D = sp.block_diag([d1] * n, format="csr") + self.K_axial = (self.h * (self.D.T @ self.D)).tocsr() + self.C = sp.block_diag( + [sp.csr_matrix(np.full((1, big_n), self.h))] * n, format="csr" + ) + + # Energy, gradient and generalised Hessian at the slip field ``u``. + def _parts(self, u: FloatArray, a: float, hess: bool): + ref, h = self.ref, self.h + force = a * self.shape + (self.D @ u.ravel()).reshape(u.shape) + energy = 0.5 * h * float(np.sum(force * force)) + grad = h * (self.D.T @ force.ravel()) + rows: list[FloatArray] = [] + cols: list[FloatArray] = [] + vals: list[FloatArray] = [] + nodes = np.arange(self.N) + for c, (i, j, b) in enumerate(self.contacts): + r = u[i] - u[j] - self.p_c[c] + value, slope, curv = _huber(r, ref.k_c, b) + energy += h * float(np.sum(value)) + grad_c = np.zeros_like(u) + grad_c[i] += h * slope + grad_c[j] -= h * slope + grad = grad + grad_c.ravel() + if hess: + wi, wj = i * self.N + nodes, j * self.N + nodes + for rr, cc, sgn in ( + (wi, wi, 1), + (wj, wj, 1), + (wi, wj, -1), + (wj, wi, -1), + ): + rows.append(rr) + cols.append(cc) + vals.append(sgn * h * curv) + if ref.b_a > 0.0: + r = u - self.p_a + value, slope, curv = _huber(r, ref.k_a, ref.b_a) + energy += h * float(np.sum(value)) + grad = grad + h * slope.ravel() + if hess: + idx = np.arange(self.n * self.N) + rows.append(idx) + cols.append(idx) + vals.append(h * curv.ravel()) + if not hess: + return energy, grad, None + size = self.n * self.N + extra = ( + sp.csr_matrix( + (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), + shape=(size, size), + ) + if vals + else sp.csr_matrix((size, size)) + ) + return energy, grad, (self.K_axial + extra).tocsc() + + def increment(self, a: float) -> int: + """Solve the increment to curvature ``a``; returns Newton iterations.""" + u = self.u.copy() + scale = max(abs(a), self.ref.a_cr, 1.0) * self.h + for iteration in range(1, 200): + energy, grad, hess = self._parts(u, a, True) + m = self.C.shape[0] + kkt = sp.bmat([[hess, self.C.T], [self.C, None]], format="csc") + rhs = np.concatenate([-grad, -(self.C @ u.ravel())]) + # Converged: projected gradient (gradient minus its multiplier part). + lam = np.linalg.lstsq(self.C.T.toarray(), -grad, rcond=None)[0] + residual = grad + self.C.T @ lam + if np.max(np.abs(residual)) <= 1e-10 * scale: + self.u = u + return iteration - 1 + try: + step = splu(kkt).solve(rhs)[: self.n * self.N] + except RuntimeError: # singular generalised Hessian: regularise + reg = kkt + sp.block_diag( + [sp.identity(self.n * self.N) * 1e-12, sp.csc_matrix((m, m))] + ) + step = splu(reg.tocsc()).solve(rhs)[: self.n * self.N] + slope0 = float(grad @ step) + t = 1.0 + while True: + trial = u + t * step.reshape(u.shape) + e_trial = self._parts(trial, a, False)[0] + if e_trial <= energy + 1e-4 * t * slope0 + 1e-15 * abs(energy): + break + t *= 0.5 + if t < 1e-12: + break + u = trial + raise RuntimeError("reference Newton did not converge") + + def commit( + self, a: float + ) -> tuple[float, float, FloatArray, FloatArray, FloatArray]: + """Update the slips; return work, stick fraction and the fields.""" + ref, h, u = self.ref, self.h, self.u + dissipation = 0.0 + stick = 0 + total = 0 + contact_f = np.zeros((len(self.contacts), self.N)) + for c, (i, j, b) in enumerate(self.contacts): + r = u[i] - u[j] - self.p_c[c] + slope = np.clip(ref.k_c * r, -b, b) + slipping = np.abs(ref.k_c * r) > b + new_p = np.where(slipping, u[i] - u[j] - slope / ref.k_c, self.p_c[c]) + dissipation += h * float( + np.sum(np.abs(slope) * np.abs(new_p - self.p_c[c])) + ) + self.p_c[c] = new_p + contact_f[c] = -slope # force on core i from core j + stick += int(np.count_nonzero(~slipping)) + total += self.N + inter_f = np.zeros((self.n, self.N)) + if ref.b_a > 0.0: + r = u - self.p_a + slope = np.clip(ref.k_a * r, -ref.b_a, ref.b_a) + slipping = np.abs(ref.k_a * r) > ref.b_a + new_p = np.where(slipping, u - slope / ref.k_a, self.p_a) + dissipation += h * float(np.sum(np.abs(slope) * np.abs(new_p - self.p_a))) + self.p_a = new_p + inter_f = -slope + stick += int(np.count_nonzero(~slipping)) + total += self.n * self.N + force = a * self.shape + (self.D @ u.ravel()).reshape(u.shape) + return dissipation, stick / max(total, 1), force, contact_f, inter_f + + +def run_path( + ref: CoupledSlipReference, + a_path: FloatArray, + *, + phi_b: float = 0.0, + keep: tuple[int, ...] = (), +) -> ReferencePath: + """Planar curvature path ``a_path`` (bending direction ``phi_b``).""" + a_path = np.asarray(a_path, dtype=np.float64) + solver = _Solver(ref, phi_b) + count = a_path.size + moment = np.zeros(count) + work = np.zeros(count) + stick = np.zeros(count) + iters = np.zeros(count, dtype=np.int64) + out = ReferencePath(a_path, moment, work, stick, iters) + out.segment_azimuth = solver.theta.copy() + total = 0.0 + previous = 0.0 + + def advance(a_from: float, a_to: float, depth: int) -> tuple[int, float, tuple]: + # Solve to ``a_to``; an increment that does not converge is split. + try: + used = solver.increment(a_to) + except RuntimeError: + if depth >= 12: + raise + mid = 0.5 * (a_from + a_to) + n1, d1, _ = advance(a_from, mid, depth + 1) + n2, d2, state = advance(mid, a_to, depth + 1) + return n1 + n2, d1 + d2, state + d, s, force, contact_f, inter_f = solver.commit(a_to) + return used, d, (s, force, contact_f, inter_f) + + for index, a in enumerate(a_path): + iters[index], d, (s, force, contact_f, inter_f) = advance(previous, float(a), 0) + previous = float(a) + total += d + work[index] = total + stick[index] = s + moment[index] = float(np.sum(force * solver.shape)) / ref.nodes + if index in keep: + out.forces[index] = force.copy() + out.contact_forces[index] = contact_f + out.interlayer_forces[index] = inter_f + return out diff --git a/validation/validation_report.md b/validation/validation_report.md index cd38394..772fe95 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -79,8 +79,8 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1265 passed` -- independent_method: `79 passed` +- analytical_sanity: `1278 passed` +- independent_method: `92 passed` - full_scale: `59 passed` Run `pytest -m ` to reproduce each group.