From 318734bfad27d4d9e8ae8f541e9b500487e2e0a9 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 11:03:28 +0900 Subject: [PATCH] feat: elastic anchor of an anchored armour wire (end-fitting compliance) Every route that anchors a wire held it rigidly (u = 0 at the anchor). A potted end fitting holds the wire end with a finite stiffness, so the anchor can now be a spring K per wire [N/m] at the anchor node, in parallel with the friction of the node's half segment: - termination correction: TerminationSpec(k_anchor_N_m=K), clamp and along-wire solvers, with or without a curvature field (the far-field reference is unchanged); - along-wire chain: along_wire_history(anchor_stiffness_N_m=(K0, K1)), WireChain.build, WireChainLayer.anchor_stiffness_hat; - along-wire bending test (beam solved with the wires): AlongWireSpec(k_anchor_N_m=(K_left, K_right)); - clamp-layer solver: anchored_wire_response / anchored_wire_field_response (anchor_stiffness, normalised K R / (EA sin a)). None (default) or inf is the rigid anchor on the unchanged code path; 0 is a free wire end. The rigid projection of the clamp layer is untouched; the spring and free ends use the node-wise projection of the along-wire solver, moved to clamp_layer and extended with an elastic first and last node (a convex soft term, still solved exactly). Closed form (uniform imposed strain, spring anchor, slip zone next to the anchor, rigid and elastic stick): anchor force within 1e-5 A, slip length within 1.2 h, dissipation within 5e-4. Clamp solver and chain agree to 5e-15; k = 0 equals the free end; the termination increment tends to the rigid one as 1/k; energy identity 2e-13 of the work; station Jacobian and two-way closed-cycle work checked (doc/benchmarks.md, TA-V1 to TA-V7). The guide derives a shear-lag estimate of K for a potted fitting (about 1e8 to 2e9 N/m per tendon, an order-of-magnitude estimate). The Saevik (2011) termination rows are re-run over the range as a reported sensitivity (validation/scripts/check_saevik2011_anchor.py): from the rigid anchor to a free wire end SV11-PLANE stays at median 1.62 and SV11-GJ at 1.80 (round-off), the along-wire variant at 3.11 and 4.19 (below 5e-4). The end fitting sits 2.3 m before the bellmouth at about 1% of its peak curvature, so the wire next to it stays in stick and the anchor does not reach the stations. No gate, default or registered value changes. Sea-state batch section records carry the key; records without it load with a rigid anchor. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 24 + doc/benchmarks.md | 81 +++ doc/file_formats.md | 2 +- doc/glossary.rst | 5 +- doc/local_analysis_guide.md | 47 +- src/cablexsec/analysis/along_wire_test.py | 33 +- src/cablexsec/analysis/fatigue.py | 4 +- src/cablexsec/analysis/termination.py | 90 ++- src/cablexsec/api.py | 3 +- src/cablexsec/mechanics/along_wire.py | 386 ++++++---- src/cablexsec/mechanics/clamp_layer.py | 424 ++++++++++- tests/test_anchor_compliance.py | 679 ++++++++++++++++++ tests/test_clamp_layer.py | 4 +- tests/test_clamp_progressive_inputs.py | 8 +- validation/scripts/check_saevik2011.py | 18 +- validation/scripts/check_saevik2011_anchor.py | 254 +++++++ validation/validation_report.md | 6 +- 17 files changed, 1865 insertions(+), 203 deletions(-) create mode 100644 tests/test_anchor_compliance.py create mode 100644 validation/scripts/check_saevik2011_anchor.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 7937ffc..8c376bd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,30 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Added +- An anchored armour wire can be held by an elastic anchor instead of a rigid one, in every + route that anchors a wire: the termination correction (`TerminationSpec(k_anchor_N_m=K)`, + clamp and along-wire solvers, with or without a curvature field), the along-wire chain + (`along_wire_history(..., anchor_stiffness_N_m=(K_start, K_end))`, `WireChain.build`) and + the along-wire bending test that solves the beam with the wires (`AlongWireSpec( + k_anchor_N_m=...)`); `anchored_wire_response` and `anchored_wire_field_response` take the + normalised stiffness `anchor_stiffness = K R/(EA sin α)`. `K` [N/m] is the axial force on + the wire end per unit axial displacement of the wire end at the anchor, per wire (the + potting of an end fitting). The anchor node carries the spring in parallel with the + friction of its half segment; `0` is a free wire end and `None` (default) or `inf` the rigid + anchor on the unchanged code path, so existing results are unchanged bit for bit. The local + analysis guide (Section 5, Step 6) derives a shear-lag estimate for a potted fitting, about + `1e8` to `2e9` N/m per tendon (an order-of-magnitude estimate, not a sourced value). Checked + against the closed form of a wire with a spring anchor next to a slip zone (anchor force, slip + length and dissipation, rigid and elastic stick), the free-end and rigid limits, two + independent kernels to round-off, the energy identity, the station Jacobian and the + closed-cycle work of a bending test (doc/benchmarks.md, TA-V1 to TA-V6). The Sævik (2011) + termination rows are reported over the stiffness range as a sensitivity study + (`validation/scripts/check_saevik2011_anchor.py`), not fitted and not gated: from the rigid anchor to a free wire end the termination-corrected + SV11-PLANE median stays 1.62 and SV11-GJ 1.80 (changes at round-off), the along-wire variant + 3.11 and 4.19 (changes below 5e-4). The end fitting sits 2.3 m before the bellmouth where the + curvature is about 1% of its peak, so the wire next to it stays in stick and the anchor + condition does not reach the stations; the over-prediction is a curvature-gradient effect. + Section records of the sea-state batch carry the new key; records without it load as rigid. - `compute_mkappa` can let the armour contact pressure follow the bending history: `contact_tension_history_N` sets the per-sample `P1+P2` from a tension history through the contact model (the histories `compute_fatigue` forms from `tension_N`), and diff --git a/doc/benchmarks.md b/doc/benchmarks.md index 071a18b..ee57323 100644 --- a/doc/benchmarks.md +++ b/doc/benchmarks.md @@ -1327,6 +1327,87 @@ scorecard row now passes on its own basis, through the signed capstan bound. Transverse slip and lateral tendon bending (Sævik 1992; Dong et al. 2017, 2025) were tested with gap G1 and change the ratios by 1–3 % only. +## Anchor compliance of the end fitting (TA) + +Option `k_anchor_N_m` of `TerminationSpec` and `AlongWireSpec`, +`anchor_stiffness_N_m` of `along_wire_history` and `WireChain.build`, and the +normalised `anchor_stiffness` of the clamp-layer solver; tests +`tests/test_anchor_compliance.py`; sensitivity script +`validation/scripts/check_saevik2011_anchor.py`. The anchor of every route +above is rigid (`u = 0`). A potted end fitting holds the wire end with a finite +stiffness `K` per wire (axial force per unit axial displacement of the wire +end), here a spring at the anchor node in parallel with the friction of the +node's half segment. Normalised, `k_a = K R/(EA sin α)` (`ξ EA` in the +`scaled` convention): the anchor is as compliant as `EA/K` of free wire. The +rigid anchor stays the default and runs the unchanged code path; nothing is +fitted. A shear-lag estimate of `K` for a potted fitting is derived in the +[local analysis guide](local_analysis_guide.md) (Section 5, Step 6): about +`1e8`–`2e9` N/m for a 5 × 12.5 mm tendon, `EA/K ≈ 0.007`–`0.16` m. It is an +order-of-magnitude estimate, not a value from a source. + +**Verification.** Closed form: a wire under a uniform imposed strain `A` +(from the virgin state, uniform bound `ρ`, interface stiffness `k̂ = β²`, +`β = ∞` for rigid stick) slips over `L` next to the anchor, with +`k_a ρ L²/2 + ρ(1 + k_a/β) L + k_a ρ/β² + ρ/β = A`; the anchor force is +`A − ρ/β − ρL`, the dissipation `ρ²(L²/(2β) + L³/6)`, and without slip the +anchor force is `k_a A/(k_a + β)`. `k_a → 0` is the free end, `k_a → ∞` the +rigid anchor. + +| ID | Class | Quantity | Target | Result | Status | +| --- | --- | --- | --- | --- | --- | +| TA-V1 | A | Closed form above, `A = 3`, `k_a` = 10, 1, 0.1, 0: clamp solver (rigid stick, 256 segments per pitch) and chain (rigid stick and `β = 2`, 512 per pitch): anchor force, slip length, dissipation | force within 1e-4 `A`; slip length within 1.5 `h`; dissipation within 2e-3 (clamp) and 5e-4 (chain) | force 1e-5 `A` or better; slip length within 1.2 `h`; dissipation 5e-4 (clamp), 4e-5 (chain) | PASS | +| TA-V2 | I | Clamp solver against the along-wire chain with the same spring anchor (cyclic curvature, `k_a` = 0, 0.3, 3) | < 1e-12 rel. | force 5e-15, dissipation 4e-16 | PASS | +| TA-V3 | A, I | Limits: `None`/`inf` the unchanged code path (clamp, field, chain, termination, bending test); `0` the free end (chain bitwise; clamp against the chain's free end); termination increment (Ménard, `k_a` = 0 to 1e6) between the free and the rigid result, monotone, both solvers agreeing | bitwise; < 1e-12; monotone, < 1e-4 at `k_a = 1e6` | bitwise; 4e-15; range 28.2, 31.1, 55.3, 63.0, 63.73, 63.74 MPa against rigid 63.74 (deviation 3.7e-7 at 1e6, falling as `1/k_a`); solvers 3e-15 | PASS | +| TA-V4 | I | Energy identity `W = ΔU + D + R` with elastic anchors (rigid and spring stick, with and without capstan, one and two springs) | round-off | 2e-13 of the work | PASS | +| TA-V5 | I | Station Jacobian with two elastic anchors against the finite difference in stick | < 1e-7 | yes | PASS | +| TA-V6 | I | Two-way bending test (two-pitch three-point specimen, anchored ends): `k_a` = 0 equals free ends; closed-cycle external work against wire friction work | bitwise; < 1% | bitwise; 0.89% (rigid 0.89%, free 0.91%); peak load 1551 (free) ≤ 1553–1555 ≤ 1555 N (rigid) | PASS | +| TA-V7 | I | Projections with spring ends (first, last, both) against a generic quadratic programme | < 1e-5 | yes | PASS | + +**Sævik (2011) sensitivity (reported, not gated).** The rows SV11-PLANE and +SV11-GJ (termination-corrected: clamp solver, `scaled`, anchor at the +end-fitting face) and the along-wire variant of gap T2 (`spring`, capstan +bound, all wires between the two end fittings, the beam curvature field at +every angle sample) re-run with an elastic anchor `K` per tendon at both end +fittings (`EA = 1.29e7 N`; `python validation/scripts/check_saevik2011_anchor.py +OUTPUT_JSON`, about 20 min on one thread). `K` is not fitted; the registered +rows keep the rigid anchor. + +| `K` per tendon [N/m] | `EA/K` [m] | SV11-PLANE median R (in band) | SV11-GJ | T2-SV-PLANE median R (in band) | T2-SV-GJ | +| --- | --- | --- | --- | --- | --- | +| rigid (registered) | 0 | 1.62 (3 of 14) | 1.80 | 3.11 (2 of 14) | 4.19 | +| 2e9 | 0.0065 | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | +| 5e8 | 0.026 | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | +| 1e8 | 0.13 | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | +| 1e7 | 1.3 | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | +| 1e6 | 13 | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | +| 0 (free wire end) | ∞ | 1.62 (3) | 1.80 | 3.11 (2) | 4.19 | + +The first four non-rigid rows span the potting estimate; the last three +extend it to a free end. The largest change of any per-case ratio is 3e-15 +(round-off) for the termination correction and 4.5e-4 for the along-wire +chain (at `K = 0`; 1.4e-4 at `1e8`). The along-wire values are a re-run with +the signed capstan bound (the T2 table above, 3.36 and 4.62, used the former +symmetric bound and has no script on record); per load case 0.44, 0.54, +0.74, 0.99 (0.5–2°), 4.96 and 1.91 (4°, LC 4 and LC 5), 3.16–3.51 (7.5°, 8° and +15° at 500 and 250 kN), +3.06–3.19 (24–32°), 2.67 (15°, 750 kN), 5.67 (15°, 17 MPa, LC 19). + +Why nothing moves: the end-fitting face lies 2.305 m before the curved +section, inside the straight bellmouth tube, where the beam curvature is about +1% of the bellmouth peak (LC 14, 15°: 2e-4 against 0.025 1/m). The wire next to +the anchor therefore stays in stick, apart from the first half segment, and the +anchor condition does not reach the stations: the rigid anchor of the +along-wire chain carries a range of 79 MPa (LC 14, ±8°, all 55 wires) against +875 MPa at station 2.1. The slip zones that make the corrected ranges start in +the bellmouth and are held there by a stuck stretch of wire, which acts as the +anchor whatever the fitting does. At this rig the termination correction is a +curvature-gradient effect, not an anchor effect; anchor compliance cannot +explain the over-prediction, and the SV11 and T2 decisions stand. The option +matters where the curvature at the anchor is high: on a Ménard layer with +uniform curvature from the anchor (TA-V3, 20 `κ_c`) the corrected range falls +by 1% at `k_a = 10` and by 13% at `k_a = 1`; for a potted fitting +(`K ≈ 1e8` N/m, `k_a ≈ 20` there) it is below 1%. + ## Torque balance and twist under tension (gap 3.5: TQ, TQ-KL, TQ-UJ) Script `validation/scripts/check_torque_balance.py`, tests `tests/test_torque_balance.py`, rows TQ, diff --git a/doc/file_formats.md b/doc/file_formats.md index 6939f72..2851b43 100644 --- a/doc/file_formats.md +++ b/doc/file_formats.md @@ -499,7 +499,7 @@ object with four keys: | --- | --- | | `cable` | a YAML path, or `bundled:` for a bundled cable such as `bundled:iea_task49_66kv` | | `runs` | `name`, `out_root`, `deck`, `probability`; optional `line_id`, `start_time_s`, `end_time_s` | -| `sections` | `name`, `arc_length_m`; optional `termination`, `thermal`, `fretting`, `sn_curves`, `mean_stress`, `scf` | +| `sections` | `name`, `arc_length_m`; optional `termination` (the fields of `TerminationSpec`, for example `distance_m` and `k_anchor_N_m`; a record without `k_anchor_N_m` has a rigid anchor), `thermal`, `fretting`, `sn_curves`, `mean_stress`, `scf` | | `options` | the fields of `SeaStateBatchOptions` | Relative paths are resolved against the folder of the JSON file, and unknown diff --git a/doc/glossary.rst b/doc/glossary.rst index 2157bca..282d9d0 100644 --- a/doc/glossary.rst +++ b/doc/glossary.rst @@ -31,7 +31,10 @@ Terms and abbreviations Armour wires held axially at an end fitting, a rig clamp or a clamped bend-stiffener root, so that friction builds up a mean wire force the sectional law cannot carry. The :term:`termination correction` and :func:`~cablexsec.simulate_rig_test` solve each - anchored wire with a Coulomb bound per unit length and axial slip only. + anchored wire with a Coulomb bound per unit length and axial slip only. The termination + correction and the :term:`along-wire model` can hold the wire end elastically instead + (``k_anchor_N_m``, the stiffness per wire of an end-fitting potting; ``0`` is a free + wire end); the rig-test anchor is rigid. annual damage The :term:`Miner sum` per year of service, weighted over the sea states of a diff --git a/doc/local_analysis_guide.md b/doc/local_analysis_guide.md index 8b17792..2f90b72 100644 --- a/doc/local_analysis_guide.md +++ b/doc/local_analysis_guide.md @@ -703,17 +703,51 @@ with the increment in `field.termination`. solver follows each wire's azimuth-dependent contact shape and takes the biaxial strain directly; with `stick="scaled"` and no capstan it equals the clamp solver to round-off. +- **Anchor compliance.** The anchor is rigid by default (`u = 0` at the + anchor). `k_anchor_N_m=K` holds each wire end with the force `K u` instead + (`K` in N/m per wire: the axial force on the wire end per unit axial + displacement of the wire end at the anchor), in parallel with the friction + of the first half segment; `0` is a free wire end, `None` or `inf` the + rigid anchor on the unchanged code path. All solvers (clamp, along-wire, + either under a curvature field) take it; the far-field reference is + unchanged. Normalised, `k_a = K R/(EA sin α)` (`ξ EA` for `"scaled"`): + the anchor is as compliant as a length `EA/K` of free wire, so it matters + only when `EA/K` is comparable with the boundary layer `ℓ_x`. + A closed form checks it: a wire under a uniform imposed strain `A` with + a spring anchor slips over `L` next to the anchor, with + `k_a ρ L²/2 + ρ(1 + k_a/β)L + k_a ρ/β² + ρ/β = A` (`β = √k̂`, `β = ∞` + for rigid stick), anchor force `A − ρ/β − ρL` and dissipation + `ρ²(L²/(2β) + L³/6)` ([benchmarks.md](benchmarks.md), TA-V1). +- **Estimating `K` for a potted end fitting.** This is an + order-of-magnitude estimate from shear lag, not a value from a source. A + wire of axial stiffness `EA` bonded over a length `L_e` in a potting of + shear modulus `G_p`, with an effective shear-layer thickness `t_p` over + the wire perimeter `p`, has the bond stiffness per unit length + `k_s = G_p p/t_p` and `u'' = λ² u` with `λ = √(k_s/EA)`; its loaded end has + `K_b = EA λ tanh(λ L_e)`, within 4 % of `√(EA k_s)` once `λ L_e > 2`. An + unbonded wire length `l_f` between the anchor plane and the start of the + bond adds `l_f/EA` in series: `1/K = 1/K_b + l_f/EA`. For a 5 × 12.5 mm + tendon (`EA = 1.3e7 N`, `p = 35 mm`), `G_p = 0.5`–`4 GPa` (unfilled to + filled epoxy, typical values) and `t_p = 0.5`–`5 mm` give `λ = 16`–`150 + 1/m` and `K_b ≈ 2e8`–`2e9 N/m` for `L_e ≥ 0.15 m`; 0.1 m of unbonded wire + lowers it to about `1e8 N/m`. A 5 mm round wire (`EA = 4e6 N`) gives + `K_b ≈ 8e7`–`7e8 N/m`. The anchor then behaves like `EA/K ≈ 0.007`–`0.16 + m` of extra free wire. A mechanical wedge or a hooked wire end changes + these numbers; measure or model the fitting when the result matters. - **Measured check.** Near the bellmouth of the Sævik (2011) riser the corrected ranges are 1.65 times the FBG measurements (median, clamp solver), 2.1 with the along-wire solver in the `"scaled"` convention and 3.4 with `"spring"` or `"rigid"`; the sectional ranges are 1.03 ([benchmarks.md](benchmarks.md), SV11 and T2). The anchored-wire Coulomb model is not - supported by these measurements. + supported by these measurements. An elastic anchor in the estimated range, + or a free wire end, does not change this (benchmarks.md, "Anchor compliance of the end + fitting", a reported sensitivity). What it does not represent: transverse slip (except the vector-Coulomb relief of `lateral_relief=` with the along-wire solver, Section 6.4), wire -flattening, interaction between layers, the stiffness of a bonded length -inside a fitting (put the anchor at its inner end), bending-induced pressure +flattening, interaction between layers, a bonded length inside a fitting as +a distributed bond (put the anchor at its inner end, or lump the bond into +`k_anchor_N_m`), bending-induced pressure redistribution and the change of wire and stick moduli over section states. It has not been compared with a helix finite-element model; the only measured comparison is the Sævik (2011) check above, which it does not @@ -958,7 +992,9 @@ print(test.loop_work_J_per_m(), test.along_wire.iterations.max()) - **Model.** Each wire: axial force `n = e + du/dφ`, friction line load bounded by the package's contact pressure (and capstan term), imposed strain `e = κ(x, t) R cos²α cos θ(x)` from the local curvature, ends anchored - (`u = 0`) or free (`n = 0`). The station moment is the elastic (full-slip) + (`u = 0`), elastically anchored (`AlongWireSpec(k_anchor_N_m=(K_left, + K_right))`, the end node held by `K u` in parallel with its friction; + Section 5, Step 6) or free (`n = 0`). The station moment is the elastic (full-slip) part plus `Σ A R cos α σ cos θ` of the wires at the station; equilibrium `M(x) = F m(x)` at every station (zero on overhangs) is solved by Newton on the station curvatures and the load with the exact station Jacobian of @@ -988,7 +1024,8 @@ The same solver is available for a section near a termination: `TerminationSpec(..., solver="along_wire", stick="spring", capstan=True)` (Section 5, Step 6), and on its own for a prescribed, non-proportional curvature field: `cx.along_wire_history(cx.WireChainLayer.from_layer_spec(spec), -x_m, kappa_x, ends=("anchored", "anchored"))`. +x_m, kappa_x, ends=("anchored", "anchored"))`, with +`anchor_stiffness_N_m=(K_start, K_end)` for elastic anchors. ### 6.4 Local tendon bending, transverse slip and lateral relief (gap G1) diff --git a/src/cablexsec/analysis/along_wire_test.py b/src/cablexsec/analysis/along_wire_test.py index 9e0c509..c7fa2ef 100644 --- a/src/cablexsec/analysis/along_wire_test.py +++ b/src/cablexsec/analysis/along_wire_test.py @@ -100,6 +100,12 @@ class AlongWireSpec: Uniform subdivision of every protocol interval. max_iterations : int Newton-type iterations per step before the step is halved. + k_anchor_N_m : (float or None, float or None) + Axial stiffness of the left and right anchors per wire [N/m] + (:meth:`~cablexsec.mechanics.along_wire.WireChain.build`): ``None`` + (default) or ``inf`` rigid, ``0`` a free wire end, finite an elastic + anchor (end fitting potting) in parallel with the end node's + friction. A finite value needs an ``"anchored"`` end. """ ends: tuple[str, str] = ("free", "free") @@ -110,12 +116,34 @@ class AlongWireSpec: sense: int = 1 substeps: int = 1 max_iterations: int = 60 + k_anchor_N_m: tuple[float | None, float | None] = (None, None) def __post_init__(self) -> None: ends = tuple(self.ends) if len(ends) != 2 or any(e not in END_CONDITIONS for e in ends): raise CableInputError(f"ends must be two of {END_CONDITIONS}") object.__setattr__(self, "ends", (str(ends[0]), str(ends[1]))) + anchors = tuple(self.k_anchor_N_m) + if len(anchors) != 2: + raise CableInputError("k_anchor_N_m must give one value per end") + checked: list[float | None] = [] + for kind, value in zip(ends, anchors, strict=True): + if value is None: + checked.append(None) + continue + if isinstance(value, (bool, np.bool_)) or not isinstance( + value, (int, float, np.integer, np.floating) + ): + raise CableInputError("k_anchor_N_m values must be numbers or None") + k_anchor = float(value) + if math.isnan(k_anchor) or k_anchor < 0: + raise CableInputError( + "k_anchor_N_m must be non-negative (None or inf: rigid anchor)" + ) + if kind != "anchored": + raise CableInputError("an anchor stiffness needs an anchored end") + checked.append(k_anchor) + object.__setattr__(self, "k_anchor_N_m", (checked[0], checked[1])) over = tuple(float(v) for v in self.overhang_m) if len(over) != 2 or any(not math.isfinite(v) or v < 0 for v in over): raise CableInputError("overhang_m must be two non-negative lengths") @@ -362,7 +390,7 @@ def dissipation_nodes(self, new: _State) -> FloatArray: return np.asarray(np.sum(d, axis=0) * self.lay.energy_unit_J) def stored(self, state: _State) -> tuple[float, FloatArray]: - _u, z, n, _t = state + u, z, n, _t = state lay = self.lay h = self.chain.h seg = 0.5 * h * np.sum(n * n, axis=0) @@ -371,6 +399,8 @@ def stored(self, state: _State) -> tuple[float, FloatArray]: 0.0, 0.5 * self.chain.weights * lay.k_hat * np.sum(z * z, axis=0), ) + if np.any(self.chain.spring > 0.0): + node = node + 0.5 * self.chain.spring * np.sum(u * u, axis=0) total = (float(np.sum(seg)) + float(np.sum(node))) * lay.energy_unit_J return total, np.asarray(node * lay.energy_unit_J) @@ -462,6 +492,7 @@ def embed(wv: FloatArray) -> FloatArray: length + oh_r, ends=spec.ends, segments_per_pitch=spec.segments_per_pitch, + anchor_stiffness_N_m=spec.k_anchor_N_m, ), x_all, ) diff --git a/src/cablexsec/analysis/fatigue.py b/src/cablexsec/analysis/fatigue.py index 0bbf4ed..131d624 100644 --- a/src/cablexsec/analysis/fatigue.py +++ b/src/cablexsec/analysis/fatigue.py @@ -1185,7 +1185,9 @@ def compute_fatigue( The clamp solver is planar: by default the increment follows the principal component of the history (``biaxial="principal"``), with ``"components"`` adding the minor component; the sectional friction - keeps the full biaxial law. ``None`` (default) gives the sectional + keeps the full biaxial law. The anchor is rigid unless + ``k_anchor_N_m`` gives its stiffness per wire (an end-fitting + potting). ``None`` (default) gives the sectional result, as does a section beyond the solved reach, bit for bit. count_from_sample : int, optional Lead-in: the friction state runs through the whole history, and the diff --git a/src/cablexsec/analysis/termination.py b/src/cablexsec/analysis/termination.py index 69cfd59..778942a 100644 --- a/src/cablexsec/analysis/termination.py +++ b/src/cablexsec/analysis/termination.py @@ -70,6 +70,20 @@ ``k_hat = xi / (1 - xi)`` with the full imposed strain, the distributed model's representation (Lutchansky shear lag at the anchor). +Anchor compliance +----------------- +``k_anchor_N_m`` replaces the rigid anchor (``u = 0`` at the anchor) by an +elastic one: the anchor holds the wire end with the force ``K u`` per wire +(``K`` [N/m], axial force per unit axial displacement of the wire end), in +parallel with the friction of the first half segment. ``None`` (default) or +``inf`` is the rigid anchor on the unchanged code path; ``0`` a free wire end +at the anchor. Normalised, ``k_a = K R / (E A sin a)`` with the chain's axial +stiffness ``E A`` (``xi E A`` for ``stick="scaled"``): the anchor is as +compliant as ``E A / K`` of free wire, to be compared with the boundary layer +``l_x``. It enters the anchored chain of every solver (the clamp solver, the +along-wire solver, and both under a curvature field); the far-field reference +is unchanged. Estimates for potted end fittings are in the termination guide. + ``solver="along_wire"`` uses :mod:`cablexsec.mechanics.along_wire`: every wire is solved along its own helix with its azimuth-dependent contact shape, the optional capstan bound (``capstan=True``, the package's signed bound) and the @@ -238,6 +252,10 @@ class TerminationSpec: per sample of the history, in the bending plane of the clamp solution. Replaces ``curvature_profile``; the history at the section (projected on that plane) must equal the field at ``distance_m``. + k_anchor_N_m : float or None + Axial stiffness of the anchor per wire [N/m] (module notes, "Anchor + compliance"): ``None`` (default) or ``inf`` rigid, ``0`` a free wire + end, finite an elastic anchor. Needs ``anchor="clamped"``. Notes ----- @@ -266,8 +284,22 @@ class TerminationSpec: capstan: bool = False curvature_field: CurvatureField | None = None lateral_relief: LateralRelief | None = None + k_anchor_N_m: float | None = None def __post_init__(self) -> None: + if self.k_anchor_N_m is not None: + if isinstance(self.k_anchor_N_m, (bool, np.bool_)) or not isinstance( + self.k_anchor_N_m, (int, float, np.integer, np.floating) + ): + raise CableInputError("k_anchor_N_m must be a number or None") + k_anchor = float(self.k_anchor_N_m) + if math.isnan(k_anchor) or k_anchor < 0: + raise CableInputError( + "k_anchor_N_m must be non-negative (None or inf: rigid anchor)" + ) + if self.anchor != "clamped": + raise CableInputError("k_anchor_N_m needs anchor='clamped'") + object.__setattr__(self, "k_anchor_N_m", k_anchor) if self.lateral_relief is not None: if not isinstance(self.lateral_relief, LateralRelief): raise CableInputError("lateral_relief must be a LateralRelief") @@ -575,6 +607,12 @@ def result( 0.0, "no friction-setting pressure or friction: no clamp effect", ) + anchor_hat: float | None = None + k_anchor = termination.k_anchor_N_m + if k_anchor is not None and math.isfinite(k_anchor): + anchor_hat = WireChainLayer.from_layer_spec( + spec, stick=termination.stick, capstan=False + ).anchor_stiffness_hat(k_anchor) if contact_pressure_Pa is None: rho_samples = np.ones(n_t) else: @@ -674,6 +712,7 @@ def result( part, kx, ky, + anchor_hat, ) return result( stress, @@ -682,7 +721,7 @@ def result( layer_m, reach, f"anchored-wire clamp increment under the {field.kind} curvature " - f"field ({termination.solver} solver)", + f"field ({termination.solver} solver{_anchor_note(termination)})", ) if termination.solver == "along_wire": @@ -704,6 +743,7 @@ def result( part, x_mid, h_x, + anchor_hat, ) return result( stress, @@ -712,7 +752,8 @@ def result( layer_m, reach, f"along-wire clamp increment ({termination.stick} stick, capstan " - f"{'on' if termination.capstan else 'off'}; biaxial strain direct)", + f"{'on' if termination.capstan else 'off'}; biaxial strain direct" + f"{_anchor_note(termination)})", ) for direction, load in zip(directions, loads, strict=True): @@ -756,6 +797,7 @@ def result( rho=rho, record=record, index=np.array([j_s], dtype=np.int64), + anchor_stiffness=anchor_hat, ) column = (sense * int(whole[k])) % spp stress[k] += sigma_u * gk * (n_rec[:, 0] - rows[:, column]) @@ -765,10 +807,19 @@ def result( a_max, layer_m, reach, - f"anchored-wire clamp increment, {termination.biaxial} mode", + f"anchored-wire clamp increment, {termination.biaxial} mode" + f"{_anchor_note(termination)}", ) +def _anchor_note(termination: TerminationSpec) -> str: + """``"; anchor K N/m per wire"`` for an elastic anchor, else empty.""" + k_anchor = termination.k_anchor_N_m + if k_anchor is None or math.isinf(k_anchor): + return "" + return f"; anchor {k_anchor:.3g} N/m per wire" + + def _field_increment( spec: HelicalLayerSpec, termination: TerminationSpec, @@ -788,6 +839,7 @@ def _field_increment( part: NDArray[np.int64], kx: FloatArray, ky: FloatArray, + anchor_hat: float | None = None, ) -> FloatArray: """Clamp increment under a non-proportional planar field [Pa] (gap P5). @@ -824,6 +876,7 @@ def _field_increment( sense, whole, part, + anchor_hat, ) for k in range(n_w): gk = float(g[k]) @@ -859,6 +912,7 @@ def _field_increment( rho=rho_samples, index=np.array([j_s], dtype=np.int64), substeps=counts, + anchor_stiffness=anchor_hat, ) column = (sense * int(whole[k])) % spp stress[k] = sigma_u * gk * (n_rec[:, 0] - rows[:, column]) @@ -881,6 +935,7 @@ def _along_wire_field( sense: int, whole: NDArray[np.int64], part: NDArray[np.int64], + anchor_hat: float | None = None, ) -> FloatArray: """Along-wire clamp increment under a planar field [Pa] (gap P5).""" layer = WireChainLayer.from_layer_spec( @@ -926,12 +981,12 @@ def run( fx: FloatArray, fy: FloatArray, rec: NDArray[np.int64], + anchored: bool = False, ) -> FloatArray: m = theta.size w = np.full(m + 1, h) w[0] = w[-1] = 0.5 * h - fixed = np.ones(m + 1, dtype=np.bool_) - fixed[1:-1] = False + fixed, spring = _anchor_nodes(m, anchored, anchor_hat) theta_node = np.r_[theta - 0.5 * sense * h, theta[-1] + 0.5 * sense * h] gnode = np.ascontiguousarray(layer.shape_at(theta_node)) out_n = np.zeros((fx.shape[0], rec.size)) @@ -957,6 +1012,7 @@ def run( out_n, out_e, stats, + spring, ) if status != 0: raise CableInputError( @@ -990,6 +1046,7 @@ def run( anc_x, anc_y, np.array([j_s], dtype=np.int64), + anchored=True, ) column = (sense * int(whole[k])) % spp stress[k] = layer.stress_unit_Pa * (n_anch[:, 0] - far[key][:, column]) @@ -1014,6 +1071,7 @@ def _along_wire_increment( part: NDArray[np.int64], x_mid: FloatArray | None = None, h_x: float | None = None, + anchor_hat: float | None = None, ) -> FloatArray: """Clamp increment of every wire with the along-wire solver [Pa]. @@ -1068,8 +1126,7 @@ def run( m = theta.size w = np.full(m + 1, h) w[0] = w[-1] = 0.5 * h - fixed = np.ones(m + 1, dtype=np.bool_) - fixed[1:-1] = False + fixed, spring = _anchor_nodes(m, anchored, anchor_hat) theta_node = np.r_[theta - 0.5 * sense * h, theta[-1] + 0.5 * sense * h] gnode = np.ascontiguousarray(layer.shape_at(theta_node)) if relief is not None: @@ -1103,6 +1160,7 @@ def run( out_n, out_e, stats, + spring, ) if status != 0: raise CableInputError( @@ -1139,3 +1197,21 @@ def run( column = (sense * int(whole[k])) % spp stress[k] = layer.stress_unit_Pa * (n_anch[:, 0] - far[key][:, column]) return stress + + +def _anchor_nodes( + m: int, anchored: bool, anchor_hat: float | None +) -> tuple[NDArray[np.bool_], FloatArray]: + """Fixed nodes and node springs of a chain of ``m`` segments. + + Both end nodes are rigid anchors, except the anchor node (node 0) of the + anchored chain with an elastic anchor (normalised stiffness + ``anchor_hat``; ``0`` a free end). + """ + fixed = np.ones(m + 1, dtype=np.bool_) + fixed[1:-1] = False + spring = np.zeros(m + 1) + if anchored and anchor_hat is not None: + fixed[0] = False + spring[0] = anchor_hat + return fixed, spring diff --git a/src/cablexsec/api.py b/src/cablexsec/api.py index a23d0e5..3fafa4b 100644 --- a/src/cablexsec/api.py +++ b/src/cablexsec/api.py @@ -2016,7 +2016,8 @@ def compute_fatigue( bend-stiffener root (all armour layers, or per layer name): the friction stress becomes the sectional value plus the anchored-wire clamp increment along the curvature history. The lay hand of each - layer comes from the cable. See + layer comes from the cable. The anchor is rigid unless + ``TerminationSpec.k_anchor_N_m`` gives its stiffness per wire. See :func:`cablexsec.analysis.fatigue.compute_fatigue` and doc/local_analysis_guide.md. thermal : ThermalHistory or ThermalState, optional diff --git a/src/cablexsec/mechanics/along_wire.py b/src/cablexsec/mechanics/along_wire.py index 3423fea..5278e52 100644 --- a/src/cablexsec/mechanics/along_wire.py +++ b/src/cablexsec/mechanics/along_wire.py @@ -29,7 +29,11 @@ relative to the core surface, ``p`` its sliding part, ``k_hat`` the normalised interface shear stiffness, ``lam`` the capstan coefficient and ``g`` the azimuthal contact shape. Ends: anchored (``u = 0``: end fitting, -grip, clamped stiffener root; the reaction is free) or free (``n = 0``). +grip, clamped stiffener root; the reaction is free), elastically anchored +(the end node is held by ``K u`` in parallel with its friction, ``K`` the +anchor stiffness per wire, normalised by +:meth:`WireChainLayer.anchor_stiffness_hat`; the end-fitting potting) or free +(``n = 0``). Stick stiffness (explicit, :data:`STICK_CONVENTIONS`) ----------------------------------------------------- @@ -71,7 +75,8 @@ nearest to sticking as a stick row (the tractions must balance), as the periodic model does. Energy (normalised, per wire): ``W_be = sum h n de`` equals ``Delta U + D + R`` to round-off every -increment, with ``U = sum h n^2 / 2 + sum w t^2 / (2 k_hat)``, ``D`` the +increment, with ``U = sum h n^2 / 2 + sum w t^2 / (2 k_hat)`` (plus +``k_a u^2 / 2`` at an elastic anchor), ``D`` the non-negative friction dissipation and ``R`` the backward-Euler remainder. One normalised energy unit is ``g_0^2 R / (E A sin a)`` joules per wire. @@ -104,7 +109,7 @@ from cablexsec._numba import HAVE_NUMBA, njit from cablexsec.exceptions import CableInputError -from cablexsec.mechanics.clamp_layer import _lower_bound, _upper_bound +from cablexsec.mechanics.clamp_layer import _project_ends from cablexsec.mechanics.tendon_bending import LateralRelief if TYPE_CHECKING: @@ -136,7 +141,6 @@ _MAX_NEWTON = 400 _MAX_FIXED_POINT = 400 _MAX_HALVINGS = 10 -_BIG = 1.0e30 # --------------------------------------------------------------------------- # @@ -201,15 +205,24 @@ def _residual( w: FloatArray, fixed: NDArray[np.bool_], m: int, + spring: FloatArray, + ua: FloatArray, ) -> float: - """Largest nodal equilibrium residual ``|n_i - n_{i-1} - w_i t_i|``.""" + """Largest nodal equilibrium residual ``|n_i - n_{i-1} - w_i t_i - s_i|``. + + ``s_i = spring_i (ua_i + v_i)`` is the force of an elastic anchor at the + node (zero where ``spring`` is zero). + """ worst = 0.0 for i in range(m + 1): if fixed[i]: continue right, left = _node_force_pair(y, v, h, m, i) t = _clip(k * (z[i] + v[i]), b[i]) - r = abs(right - left - w[i] * t) + r = right - left - w[i] * t + if spring[i] > 0.0: + r -= spring[i] * (ua[i] + v[i]) + r = abs(r) if r > worst: worst = r return worst @@ -226,6 +239,8 @@ def _objective( w: FloatArray, fixed: NDArray[np.bool_], m: int, + spring: FloatArray, + ua: FloatArray, ) -> float: f = 0.0 for j in range(m): @@ -239,6 +254,9 @@ def _objective( f += 0.5 * w[i] * k * r * r else: f += w[i] * (b[i] * abs(r) - b[i] * b[i] / (2.0 * k)) + if spring[i] > 0.0: + u = ua[i] + v[i] + f += 0.5 * spring[i] * u * u return f @@ -254,6 +272,8 @@ def _directional( w: FloatArray, fixed: NDArray[np.bool_], m: int, + spring: FloatArray, + ua: FloatArray, ) -> float: s = 0.0 for i in range(m + 1): @@ -261,7 +281,10 @@ def _directional( continue right, left = _node_force_pair(y, v, h, m, i) t = _clip(k * (z[i] + v[i]), b[i]) - s += (left - right + w[i] * t) * dv[i] + g = left - right + w[i] * t + if spring[i] > 0.0: + g += spring[i] * (ua[i] + v[i]) + s += g * dv[i] return s @@ -307,6 +330,8 @@ def _rows( d: FloatArray, up: FloatArray, rhs: FloatArray, + spring: FloatArray, + ua: FloatArray, ) -> None: """Newton rows of the fixed-bound increment on the current active set.""" for i in range(m + 1): @@ -347,6 +372,9 @@ def _rows( else: d[i] = c / h rhs[i] = f - w[i] * (b[i] if r > 0.0 else -b[i]) + if spring[i] > 0.0: + d[i] += spring[i] + rhs[i] -= spring[i] * ua[i] @njit(cache=True) @@ -390,8 +418,14 @@ def _solve_fixed_bound( tol: float, v: FloatArray, work: FloatArray, + spring: FloatArray, + ua: FloatArray, ) -> int: - """Increment ``v`` for a fixed bound; Newton iterations or -1.""" + """Increment ``v`` for a fixed bound; Newton iterations or -1. + + ``any_fixed`` is true when the chain is held (an anchored node or an + elastic anchor, ``spring > 0``, with previous displacement ``ua``). + """ vn = work[0] vt = work[1] dv = work[2] @@ -412,7 +446,7 @@ def _solve_fixed_bound( for j in range(m): v[j + 1] = v[j] - h * y[j] return 0 - res_old = _residual(y, z, v, b, k, h, w, fixed, m) + res_old = _residual(y, z, v, b, k, h, w, fixed, m, spring, ua) if res_old <= tol: return 0 # Round-off floor of long chains in slip (ill-conditioned Laplacian @@ -438,21 +472,23 @@ def _solve_fixed_bound( d, up, rhs, + spring, + ua, ) if not _thomas(lo, d, up, rhs, vn, cp, dp, mn): if secant: return -1 secant = True continue - res = _residual(y, z, vn, b, k, h, w, fixed, m) + res = _residual(y, z, vn, b, k, h, w, fixed, m, spring, ua) if res <= tol or ( res <= 1e6 * tol and _same_active_set(z, v, vn, b, k, fixed, m) ): for i in range(mn): v[i] = vn[i] return it + 1 - f0 = _objective(y, z, v, b, k, h, w, fixed, m) - f1 = _objective(y, z, vn, b, k, h, w, fixed, m) + f0 = _objective(y, z, v, b, k, h, w, fixed, m, spring, ua) + f1 = _objective(y, z, vn, b, k, h, w, fixed, m, spring, ua) if f1 <= f0 - 1e-14 * abs(f0) or ( res < 0.5 * res_old and f1 <= f0 + 1e-12 * abs(f0) ): @@ -464,7 +500,7 @@ def _solve_fixed_bound( continue for i in range(mn): dv[i] = vn[i] - v[i] - slope = _directional(y, z, v, dv, b, k, h, w, fixed, m) + slope = _directional(y, z, v, dv, b, k, h, w, fixed, m, spring, ua) accepted = False step = 0.5 if slope < 0.0: @@ -472,7 +508,7 @@ def _solve_fixed_bound( for i in range(mn): vt[i] = v[i] + step * dv[i] if ( - _objective(y, z, vt, b, k, h, w, fixed, m) + _objective(y, z, vt, b, k, h, w, fixed, m, spring, ua) <= f0 + 1e-4 * step * slope ): accepted = True @@ -487,7 +523,7 @@ def _solve_fixed_bound( continue for i in range(mn): v[i] = vt[i] - res_old = _residual(y, z, v, b, k, h, w, fixed, m) + res_old = _residual(y, z, v, b, k, h, w, fixed, m, spring, ua) secant = False return -1 @@ -520,124 +556,10 @@ def _project_var( xt: FloatArray, gt: FloatArray, ) -> None: - """Exact ``argmin 0.5 |n - y|^2`` over ``|n_i - n_{i-1}| <= cap_i``. - - ``cap`` has one entry per node (``M + 1``); interior node ``i`` lies - between segments ``i - 1`` and ``i``. A free end adds the ghost force - zero beyond it (``|n_0| <= cap_0``, ``|n_{M-1}| <= cap_M``); an anchored - end adds nothing. Slope-trick dynamic programme of - :func:`cablexsec.mechanics.clamp_layer.chain_projection` with node-wise - bounds and walls for free ends. - """ - m = y.size - lo = y[0] - hi = y[0] - for i in range(1, m): - lo = min(lo, y[i]) - hi = max(hi, y[i]) - if left_free: - lo = min(lo, -cap[0]) - hi = max(hi, cap[0]) - if cap[0] > 0.0: - size = 2 - xs[0] = -cap[0] - gs[0] = -cap[0] - y[0] - xs[1] = cap[0] - gs[1] = cap[0] - y[0] - else: - size = 1 - xs[0] = 0.0 - gs[0] = -y[0] - sl = _BIG - sr = _BIG - else: - size = 1 - xs[0] = y[0] - gs[0] = 0.0 - sl = 1.0 - sr = 1.0 - if right_free: - lo = min(lo, -cap[m]) - hi = max(hi, cap[m]) - for i in range(m): - if i > 0: - bound = cap[i] - x0 = xstar[i - 1] - k0 = _lower_bound(xs, size, x0) - k1 = _upper_bound(xs, size, x0) - # one-sided derivatives at the minimiser: a wall (free end) makes - # the derivative jump there, so they need not vanish - if k1 > k0: - g_left = gs[k0] - g_right = gs[k1 - 1] - elif k0 == 0: - g_left = g_right = gs[0] + sl * (x0 - xs[0]) - elif k0 == size: - g_left = g_right = gs[size - 1] + sr * (x0 - xs[size - 1]) - else: - x1 = xs[k0 - 1] - x2 = xs[k0] - g_left = g_right = gs[k0 - 1] + (gs[k0] - gs[k0 - 1]) * (x0 - x1) / ( - x2 - x1 - ) - g_left = min(g_left, 0.0) - g_right = max(g_right, 0.0) - t = 0 - for j in range(k0): - xt[t] = xs[j] - bound - gt[t] = gs[j] - t += 1 - if g_left < 0.0: - xt[t] = x0 - bound - gt[t] = g_left - t += 1 - xt[t] = x0 - bound - gt[t] = 0.0 - t += 1 - xt[t] = x0 + bound - gt[t] = 0.0 - t += 1 - if g_right > 0.0: - xt[t] = x0 + bound - gt[t] = g_right - t += 1 - for j in range(k1, size): - xt[t] = xs[j] + bound - gt[t] = gs[j] - t += 1 - yi = y[i] - for j in range(t): - gt[j] += xt[j] - yi - sl += 1.0 - sr += 1.0 - j0 = _lower_bound(xt, t, lo) - 1 - j0 = max(j0, 0) - j1 = _upper_bound(xt, t, hi) + 1 - j1 = min(j1, t) - size = j1 - j0 - for j in range(size): - xs[j] = xt[j0 + j] - gs[j] = gt[j0 + j] - k = _lower_bound(gs, size, 0.0) - if k == 0: - xstar[i] = xs[0] - gs[0] / sl - elif k == size: - xstar[i] = xs[size - 1] - gs[size - 1] / sr - else: - x1 = xs[k - 1] - x2 = xs[k] - g1 = gs[k - 1] - g2 = gs[k] - xstar[i] = x1 - g1 * (x2 - x1) / (g2 - g1) - last = xstar[m - 1] - if right_free: - last = _clip(last, cap[m]) - out[m - 1] = last - for i in range(m - 2, -1, -1): - value = xstar[i] - value = max(value, out[i + 1] - cap[i + 1]) - value = min(value, out[i + 1] + cap[i + 1]) - out[i] = value + """:func:`_project_ends` without elastic anchors.""" + _project_ends( + y, cap, left_free, right_free, out, xstar, xs, gs, xt, gt, 0.0, 0.0, 0.0, 0.0 + ) @njit(cache=True) @@ -665,16 +587,26 @@ def _increment( work: FloatArray, pwork: FloatArray, stats: NDArray[np.int64], + spring: FloatArray, ) -> bool: """One backward-Euler increment of one wire (old state is not modified). Elastic interface: ``v`` holds the initial guess of the slip increment and returns the solution. Rigid interface (``rigid``): exact projection of ``n_old + de`` (``v`` returns the slip increment from the forces). - ``energy`` returns ``[W_be, D, R]`` of the increment. + ``energy`` returns ``[W_be, D, R]`` of the increment. ``spring`` (per + node, normalised) holds elastic anchors at the end nodes (zero: none); + their force is ``spring u``. """ m = e_new.size mn = m + 1 + k0s = spring[0] + kms = spring[m] + springs = k0s > 0.0 or kms > 0.0 + s0_old = k0s * u_old[0] + sm_old = kms * u_old[m] + wl = 1.0 / (k0s * h) if k0s > 0.0 else 0.0 + wr = 1.0 / (kms * h) if kms > 0.0 else 0.0 y = work[9] b = work[10] ncur = work[11] @@ -708,21 +640,25 @@ def _increment( if rigid: for i in range(mn): cap[i] = w[i] * b[i] - _project_var( + _project_ends( y[:m], cap, - not fixed[0], - not fixed[m], + not fixed[0] and k0s == 0.0, + not fixed[m] and kms == 0.0, nn, pwork[0], pwork[1], pwork[2], pwork[3], pwork[4], + wl, + s0_old, + wr, + -sm_old, ) else: iters = _solve_fixed_bound( - y, z_old, b, k, h, w, fixed, any_fixed, m, tol, v, work + y, z_old, b, k, h, w, fixed, any_fixed, m, tol, v, work, spring, u_old ) if iters < 0: stats[2] += 1 @@ -761,11 +697,12 @@ def _increment( # Slip increment from the forces, zero at an anchored node or at the # node farthest from its bound; dissipation from the energy identity. ref = -1 - for i in range(mn): - if fixed[i]: - ref = i - break - if ref < 0: + if not springs: + for i in range(mn): + if fixed[i]: + ref = i + break + if ref < 0 and not springs: best = -math.inf for i in range(mn): right = ncur[i] if i < m else 0.0 @@ -779,12 +716,39 @@ def _increment( if i > 0: acc += h * (ncur[i - 1] - y[i - 1]) v[i] = acc - shift = v[ref] + s0_new = 0.0 + sm_new = 0.0 + if springs: + # anchor forces: the end node's friction takes what it can (the + # caps of the last projection), the spring the rest + if k0s > 0.0: + s0_new = ncur[0] - _clip(ncur[0] - s0_old, cap[0]) + if kms > 0.0: + s_end = -ncur[m - 1] + sm_new = s_end - _clip(s_end - sm_old, cap[m]) + if fixed[0]: + shift = v[0] + elif k0s > 0.0: + shift = v[0] - (s0_new - s0_old) / k0s + elif fixed[m]: + shift = v[m] + else: + shift = v[m] - (sm_new - sm_old) / kms + else: + shift = v[ref] stored0 = 0.0 stored1 = 0.0 for j in range(m): stored0 += 0.5 * h * n_old[j] * n_old[j] stored1 += 0.5 * h * ncur[j] * ncur[j] + if k0s > 0.0: + stored0 += 0.5 * s0_old * s0_old / k0s + stored1 += 0.5 * s0_new * s0_new / k0s + rem += 0.5 * (s0_new - s0_old) ** 2 / k0s + if kms > 0.0: + stored0 += 0.5 * sm_old * sm_old / kms + stored1 += 0.5 * sm_new * sm_new / kms + rem += 0.5 * (sm_new - sm_old) ** 2 / kms for i in range(mn): v[i] -= shift u_new[i] = u_old[i] + v[i] @@ -792,6 +756,10 @@ def _increment( right = ncur[i] if i < m else 0.0 left = ncur[i - 1] if i > 0 else 0.0 t_new[i] = 0.0 if fixed[i] else (right - left) / w[i] + if k0s > 0.0: + t_new[0] = (ncur[0] - s0_new) / w[0] + if kms > 0.0: + t_new[m] = (-ncur[m - 1] - sm_new) / w[m] energy[0] = w_be energy[1] = w_be - (stored1 - stored0) - rem energy[2] = rem @@ -809,6 +777,8 @@ def _increment( diss += w[i] * t * dpl dt = t - t_old[i] rem += 0.5 * w[i] * dt * dt / k + if spring[i] > 0.0: + rem += 0.5 * spring[i] * v[i] * v[i] z_new[i] = zn t_new[i] = t energy[0] = w_be @@ -829,9 +799,11 @@ def _stick_mask( any_fixed: bool, rigid: bool, out: NDArray[np.bool_], + spring: FloatArray, + u_old: FloatArray, ) -> None: """Converged stick set (one node sticks when nothing else holds a free - chain in full slip).""" + chain in full slip). An elastic anchor's force is not friction.""" m = n_new.size any_stick = False nearest = -1 @@ -843,7 +815,10 @@ def _stick_mask( if rigid: right = n_new[i] if i < m else 0.0 left = n_new[i - 1] if i > 0 else 0.0 - excess = abs(right - left) - w[i] * b[i] * (1.0 - 1e-9) + node = right - left + if spring[i] > 0.0: + node -= spring[i] * (u_old[i] + v[i]) + excess = abs(node) - w[i] * b[i] * (1.0 - 1e-9) else: excess = abs(k * (z_old[i] + v[i])) - b[i] * (1.0 - 1e-12) if excess < 0.0: @@ -867,6 +842,7 @@ def _tangent_rows( lo: FloatArray, d: FloatArray, up: FloatArray, + spring: FloatArray, ) -> None: for i in range(m + 1): lo[i] = 0.0 @@ -884,6 +860,8 @@ def _tangent_rows( if not fixed[i + 1]: up[i] = -1.0 / h d[i] = c / h + (w[i] * k if stick[i] else 0.0) + if spring[i] > 0.0: + d[i] += spring[i] @njit(cache=True) @@ -909,6 +887,7 @@ def _layer_step( t_new: FloatArray, energy: FloatArray, stats: NDArray[np.int64], + spring: FloatArray, ) -> int: """One increment of every wire of a layer; 0, or ``-(wire + 1)``.""" n_w = e_new.shape[0] @@ -940,6 +919,7 @@ def _layer_step( work, pwork, stats, + spring, ) if not ok: return -(q + 1) @@ -967,6 +947,8 @@ def _layer_jacobian( cos_st: FloatArray, scale: float, out: FloatArray, + spring: FloatArray, + u_old: FloatArray, ) -> bool: """Station Jacobian of the layer moment on the converged active set. @@ -1005,8 +987,21 @@ def _layer_jacobian( last[jj] = s for q in range(n_w): _bounds(n_new[q], gb[q], lam, m, b) - _stick_mask(z_old[q], v[q], n_new[q], b, k, w, fixed, any_fixed, rigid, stick) - _tangent_rows(stick, k, h, w, fixed, m, lo, d, up) + _stick_mask( + z_old[q], + v[q], + n_new[q], + b, + k, + w, + fixed, + any_fixed, + rigid, + stick, + spring, + u_old[q], + ) + _tangent_rows(stick, k, h, w, fixed, m, lo, d, up, spring) bet = d[0] if bet == 0.0 or not math.isfinite(bet): return False @@ -1083,7 +1078,7 @@ def chain_layer_jacobian( float(chain.h), chain.weights, chain.fixed, - chain.any_fixed, + chain.held, lay.rigid, chain.cos_seg, seg_i0, @@ -1093,6 +1088,8 @@ def chain_layer_jacobian( np.ascontiguousarray(cos_st), lay.lever_Nm / lay.kappa_c_1_m, out, + chain.spring, + state_old[0], ) if not ok: raise CableInputError("along-wire Jacobian is singular") @@ -1120,13 +1117,15 @@ def _wire_history( out_n: FloatArray, out_e: FloatArray, stats: NDArray[np.int64], + spring: FloatArray, ) -> int: """History of one wire driven by segment curvatures (units of kappa_c). ``kx, ky`` have shape (samples, segments), or (samples, 1) for a load common to all segments (``cs, sn`` then carry the shape); the imposed strain is ``kx cs + ky sn``. ``out_n`` (samples, records); ``out_e`` - (samples, 4) cumulative ``[W_be, D, U, R]``. Returns 0, or + (samples, 4) cumulative ``[W_be, D, U, R]``. ``spring`` holds the + elastic end anchors (per node, normalised; zero: none). Returns 0, or ``-(sample + 1)`` for the first sample that could not be advanced. """ n_t = kx.shape[0] @@ -1215,6 +1214,7 @@ def _wire_history( work, pwork, stats, + spring, ): ok = False break @@ -1252,6 +1252,8 @@ def _wire_history( for j in range(mn): if not fixed[j]: stored += 0.5 * w[j] * k * z[j] * z[j] + if spring[j] > 0.0: + stored += 0.5 * spring[j] * u[j] * u[j] out_e[i, 0] = energy[0] out_e[i, 1] = energy[1] out_e[i, 2] = stored @@ -1387,6 +1389,22 @@ def energy_unit_J(self) -> float: / (self.ea_N * math.sin(self.lay_angle_rad)) ) + def anchor_stiffness_hat(self, k_anchor_N_m: float) -> float: + """Normalised stiffness of an elastic wire anchor, ``K R / (E A sin a)``. + + ``K`` [N/m] is the axial force per unit axial displacement of the wire + end at the anchor (one wire); ``E A`` is :attr:`ea_N`, the chain's + work-conjugate axial stiffness (``xi E A`` for ``"scaled"``). The + ratio is the wire length per radian of helix angle, ``R / sin a``, + over the length ``E A / K`` of free wire that is as compliant as the + anchor. + """ + return ( + float(k_anchor_N_m) + * self.r_helix_m + / (self.ea_N * math.sin(self.lay_angle_rad)) + ) + def azimuth(self, x_m: FloatArray, wire: int | FloatArray) -> FloatArray: """Azimuth of wire(s) at axial position(s) ``x`` [rad].""" q = np.asarray(wire, dtype=np.float64) @@ -1540,6 +1558,10 @@ class WireChain: ``x_seg_m`` are segment midpoints, ``x_node_m`` nodes (``M + 1``); ``cos_seg``/``sin_seg`` and ``g_node`` have one row per wire. + ``spring`` (``M + 1``) holds the normalised stiffness of elastic end + anchors (:meth:`WireChainLayer.anchor_stiffness_hat`; zero elsewhere) and + ``anchor_stiffness_N_m`` the stiffness per wire as given to + :meth:`build` (``None``: rigid or no anchor). """ layer: WireChainLayer @@ -1555,6 +1577,12 @@ class WireChain: cos_seg: FloatArray sin_seg: FloatArray g_node: FloatArray + spring: FloatArray = field(default_factory=lambda: np.zeros(0)) + anchor_stiffness_N_m: tuple[float | None, float | None] = (None, None) + + def __post_init__(self) -> None: + if self.spring.size == 0: + object.__setattr__(self, "spring", np.zeros(self.segments + 1)) @classmethod def build( @@ -1566,9 +1594,16 @@ def build( ends: tuple[str, str] = ("anchored", "anchored"), segments_per_pitch: int = 64, wires: Sequence[int] | None = None, + anchor_stiffness_N_m: Sequence[float | None] = (None, None), ) -> WireChain: """Discretise ``[x_start, x_end]`` with at least ``segments_per_pitch`` - segments per pitch (rounded to a whole number over the length).""" + segments per pitch (rounded to a whole number over the length). + + ``anchor_stiffness_N_m`` gives the axial stiffness of each anchored + end per wire [N/m]: ``None`` or ``inf`` is the rigid anchor + (``u = 0``), a finite value an elastic anchor in parallel with the + end node's friction (force ``K u``), ``0`` a free end. + """ if not (math.isfinite(x_start_m) and math.isfinite(x_end_m)) or not ( x_end_m > x_start_m ): @@ -1594,6 +1629,28 @@ def build( fixed = np.zeros(m + 1, dtype=np.bool_) fixed[0] = ends_t[0] == "anchored" fixed[-1] = ends_t[1] == "anchored" + stiffness = tuple(anchor_stiffness_N_m) + if len(stiffness) != 2: + raise CableInputError("anchor_stiffness_N_m must give one value per end") + spring = np.zeros(m + 1) + given: list[float | None] = [] + for end, (kind, k_a) in enumerate(zip(ends_t, stiffness, strict=True)): + if k_a is None: + given.append(None) + continue + value = float(k_a) + if math.isnan(value) or value < 0.0: + raise CableInputError( + "anchor stiffness must be non-negative (None or inf: rigid)" + ) + if kind != "anchored": + raise CableInputError("an anchor stiffness needs an anchored end") + given.append(value) + if math.isinf(value): + continue + node = 0 if end == 0 else m + fixed[node] = False + spring[node] = layer.anchor_stiffness_hat(value) q = ( np.arange(layer.n_wires) if wires is None @@ -1617,12 +1674,19 @@ def build( cos_seg=np.ascontiguousarray(np.cos(th_seg)), sin_seg=np.ascontiguousarray(np.sin(th_seg)), g_node=np.ascontiguousarray(layer.shape_at(th_node)), + spring=spring, + anchor_stiffness_N_m=(given[0], given[1]), ) @property def any_fixed(self) -> bool: return bool(self.fixed.any()) + @property + def held(self) -> bool: + """An end is anchored, rigidly or elastically (no rigid-body slip).""" + return bool(self.fixed.any() or np.any(self.spring > 0.0)) + def record_weights(self, x_m: FloatArray) -> tuple[NDArray[np.int64], FloatArray]: """Linear interpolation of segment forces to positions (held at ends).""" x = np.asarray(x_m, dtype=np.float64) @@ -1668,7 +1732,7 @@ def chain_layer_step( float(chain.h), chain.weights, chain.fixed, - chain.any_fixed, + chain.held, lay.rigid, u0, z0, @@ -1681,6 +1745,7 @@ def chain_layer_step( t1, energy, stats, + chain.spring, ) if status != 0: raise CableInputError( @@ -1733,6 +1798,7 @@ def along_wire_history( wires: Sequence[int] | None = None, max_increment: float = 0.5, relief: LateralRelief | None = None, + anchor_stiffness_N_m: Sequence[float | None] = (None, None), ) -> AlongWireHistory: """Wire forces along a non-uniform, time-varying curvature field. @@ -1770,6 +1836,10 @@ def along_wire_history( largest curvature magnitude and the largest ``|dkappa/dx|`` of the history at that position, and the distance to the nearest anchored end (``None``: unchanged). + anchor_stiffness_N_m : (float or None, float or None) + Axial stiffness of each anchored end per wire [N/m] + (:meth:`WireChain.build`): ``None`` or ``inf`` rigid (default), ``0`` + free, finite an elastic anchor. """ x = np.asarray(x_m, dtype=np.float64) kx = np.asarray(kappa_x, dtype=np.float64) @@ -1795,7 +1865,13 @@ def along_wire_history( raise CableInputError("max_increment must be positive (inf: samples only)") lo, hi = (float(x[0]), float(x[-1])) if extent_m is None else extent_m chain = WireChain.build( - layer, lo, hi, ends=ends, segments_per_pitch=segments_per_pitch, wires=wires + layer, + lo, + hi, + ends=ends, + segments_per_pitch=segments_per_pitch, + wires=wires, + anchor_stiffness_N_m=anchor_stiffness_N_m, ) kc = layer.kappa_c_1_m @@ -1883,7 +1959,7 @@ def at_segments(field_: FloatArray) -> FloatArray: float(chain.h), chain.weights, chain.fixed, - chain.any_fixed, + chain.held, inc, layer.rigid, rec_j, @@ -1891,6 +1967,7 @@ def at_segments(field_: FloatArray) -> FloatArray: out_n, out_e, stats, + chain.spring, ) if status != 0: raise CableInputError( @@ -1916,6 +1993,7 @@ def at_segments(field_: FloatArray) -> FloatArray: "lam": float(layer.lam), "stick": layer.stick, "ends": chain.ends, + "anchor_stiffness_N_m": chain.anchor_stiffness_N_m, "max_increment": inc, "substeps": int(stats[3]), "max_newton": int(stats[0]), diff --git a/src/cablexsec/mechanics/clamp_layer.py b/src/cablexsec/mechanics/clamp_layer.py index 42adb8f..e756494 100644 --- a/src/cablexsec/mechanics/clamp_layer.py +++ b/src/cablexsec/mechanics/clamp_layer.py @@ -54,6 +54,16 @@ (no interaction between layers), planar proportional loading ``kappa(x, t) = kappa_ref(t) k_hat(x)``. The clamp is the anchoring plane of the armour; a bonded (epoxy) length inside a fitting is not frictional. + +Elastic anchor (``anchor_stiffness = k_a``): the first node is held by +``n_0 = k_a u_0 + f_0`` instead of ``u_0 = 0``, with its half segment's +friction ``|f_0| <= rho h / 2`` in parallel (the spring stores, the friction +dissipates). The increment adds ``soft(n_0 - s; rho h / 2)^2 / (2 k_a h)`` to +the projection (``s`` the previous anchor force), still solved exactly. +``k_a = 0`` is a free first node, ``None`` the rigid anchor above. With a +uniform imposed strain ``A`` and a uniform bound the slip zone next to the +anchor has the length ``L`` of ``k_a L^2 / 2 + L = A`` (``rho = 1``), the +anchor force is ``A - L`` and the dissipation ``L^3 / 6``. """ from __future__ import annotations @@ -69,6 +79,7 @@ __all__ = [ "CLAMP_LAW_COEFFICIENT", "HAVE_NUMBA", + "anchor_compliance", "anchored_wire_field_response", "anchored_wire_node_dissipation", "anchored_wire_response", @@ -255,9 +266,323 @@ def chain_projection_reference(y: FloatArray, bound: float) -> FloatArray: return out +#: Extrapolation slope of a wall (a free chain end: ``|n_end| <= cap``). +_WALL = 1.0e30 + + +@njit(cache=True) +def _g_at( + xs: FloatArray, gs: FloatArray, size: int, sl: float, sr: float, x: float +) -> float: + """Right-continuous value of the piecewise-linear derivative at ``x``.""" + k = _upper_bound(xs, size, x) + if k == 0: + return float(gs[0] + sl * (x - xs[0])) + if k == size: + return float(gs[size - 1] + sr * (x - xs[size - 1])) + x1 = xs[k - 1] + x2 = xs[k] + return float(gs[k - 1] + (gs[k] - gs[k - 1]) * (x - x1) / (x2 - x1)) + + +@njit(cache=True) +def _end_root( + xs: FloatArray, + gs: FloatArray, + size: int, + sl: float, + sr: float, + weight: float, + centre: float, + cap: float, +) -> float: + """Root of ``g(x) + weight soft(x - centre; cap)`` (elastic last node). + + ``g`` (breakpoints ``xs``, values ``gs``, outer slopes ``sl``, ``sr``) is + non-decreasing and the soft term is convex, so the sum is linear between + the merged breakpoints and the root is found by one sweep. + """ + a = centre - cap + b = centre + cap + have = False + p0 = 0.0 + h0 = 0.0 + j = 0 + q = 0 + while j < size or q < 2: + special = a if q == 0 else b + if q < 2 and (j >= size or special < xs[j]): + p = special + g = _g_at(xs, gs, size, sl, sr, p) + q += 1 + else: + p = xs[j] + g = gs[j] + j += 1 + if p > b: + g += weight * (p - b) + elif p < a: + g += weight * (p - a) + if g >= 0.0: + if not have: + return p - g / (sl + weight) + if p == p0: + return p + return p0 - h0 * (p - p0) / (g - h0) + have = True + p0 = p + h0 = g + return p0 - h0 / (sr + weight) + + +@njit(cache=True) +def _project_ends( + y: FloatArray, + cap: FloatArray, + left_free: bool, + right_free: bool, + out: FloatArray, + xstar: FloatArray, + xs: FloatArray, + gs: FloatArray, + xt: FloatArray, + gt: FloatArray, + wl: float, + cl: float, + wr: float, + cr: float, +) -> None: + """Exact ``argmin 0.5 |n - y|^2`` over ``|n_i - n_{i-1}| <= cap_i``. + + ``cap`` has one entry per node (``M + 1``); interior node ``i`` lies + between segments ``i - 1`` and ``i``. A free end adds the ghost force + zero beyond it (``|n_0| <= cap_0``, ``|n_{M-1}| <= cap_M``); an anchored + end adds nothing. Slope-trick dynamic programme of + :func:`cablexsec.mechanics.clamp_layer.chain_projection` with node-wise + bounds and walls for free ends. + + An elastic end anchor (complementary weight ``wl`` or ``wr`` > 0, zero for + none, with ``left_free``/``right_free`` false) adds the convex term + ``w soft(n_end - c; cap_end)^2 / 2``, ``soft(r; c) = sign(r) max(|r| - c, + 0)``: the end node's friction ``cap_end`` in parallel with a spring of + compliance ``w h`` whose previous force is ``cl`` at the first node and + ``-cr`` at the last (``cr`` is the centre for the last segment force, + which acts on the last node with the opposite sign). The first anchor + sets the starting derivative of the programme, the last one is solved in + the final root (:func:`_end_root`). + """ + m = y.size + lo = y[0] + hi = y[0] + for i in range(1, m): + lo = min(lo, y[i]) + hi = max(hi, y[i]) + if left_free: + lo = min(lo, -cap[0]) + hi = max(hi, cap[0]) + if cap[0] > 0.0: + size = 2 + xs[0] = -cap[0] + gs[0] = -cap[0] - y[0] + xs[1] = cap[0] + gs[1] = cap[0] - y[0] + else: + size = 1 + xs[0] = 0.0 + gs[0] = -y[0] + sl = _WALL + sr = _WALL + elif wl > 0.0: + lo = min(lo, cl - cap[0]) + hi = max(hi, cl + cap[0]) + if cap[0] > 0.0: + size = 2 + xs[0] = cl - cap[0] + gs[0] = xs[0] - y[0] + xs[1] = cl + cap[0] + gs[1] = xs[1] - y[0] + else: + size = 1 + xs[0] = cl + gs[0] = cl - y[0] + sl = 1.0 + wl + sr = 1.0 + wl + else: + size = 1 + xs[0] = y[0] + gs[0] = 0.0 + sl = 1.0 + sr = 1.0 + if right_free: + lo = min(lo, -cap[m]) + hi = max(hi, cap[m]) + elif wr > 0.0: + lo = min(lo, cr - cap[m]) + hi = max(hi, cr + cap[m]) + for i in range(m): + if i > 0: + bound = cap[i] + x0 = xstar[i - 1] + k0 = _lower_bound(xs, size, x0) + k1 = _upper_bound(xs, size, x0) + # one-sided derivatives at the minimiser: a wall (free end) makes + # the derivative jump there, so they need not vanish + if k1 > k0: + g_left = gs[k0] + g_right = gs[k1 - 1] + elif k0 == 0: + g_left = g_right = gs[0] + sl * (x0 - xs[0]) + elif k0 == size: + g_left = g_right = gs[size - 1] + sr * (x0 - xs[size - 1]) + else: + x1 = xs[k0 - 1] + x2 = xs[k0] + g_left = g_right = gs[k0 - 1] + (gs[k0] - gs[k0 - 1]) * (x0 - x1) / ( + x2 - x1 + ) + g_left = min(g_left, 0.0) + g_right = max(g_right, 0.0) + t = 0 + for j in range(k0): + xt[t] = xs[j] - bound + gt[t] = gs[j] + t += 1 + if g_left < 0.0: + xt[t] = x0 - bound + gt[t] = g_left + t += 1 + xt[t] = x0 - bound + gt[t] = 0.0 + t += 1 + xt[t] = x0 + bound + gt[t] = 0.0 + t += 1 + if g_right > 0.0: + xt[t] = x0 + bound + gt[t] = g_right + t += 1 + for j in range(k1, size): + xt[t] = xs[j] + bound + gt[t] = gs[j] + t += 1 + yi = y[i] + for j in range(t): + gt[j] += xt[j] - yi + sl += 1.0 + sr += 1.0 + j0 = _lower_bound(xt, t, lo) - 1 + j0 = max(j0, 0) + j1 = _upper_bound(xt, t, hi) + 1 + j1 = min(j1, t) + size = j1 - j0 + for j in range(size): + xs[j] = xt[j0 + j] + gs[j] = gt[j0 + j] + k = _lower_bound(gs, size, 0.0) + if k == 0: + xstar[i] = xs[0] - gs[0] / sl + elif k == size: + xstar[i] = xs[size - 1] - gs[size - 1] / sr + else: + x1 = xs[k - 1] + x2 = xs[k] + g1 = gs[k - 1] + g2 = gs[k] + xstar[i] = x1 - g1 * (x2 - x1) / (g2 - g1) + last = xstar[m - 1] + if right_free: + last = min(max(last, -cap[m]), cap[m]) + elif wr > 0.0: + last = _end_root(xs, gs, size, sl, sr, wr, cr, cap[m]) + out[m - 1] = last + for i in range(m - 2, -1, -1): + value = xstar[i] + value = max(value, out[i + 1] - cap[i + 1]) + value = min(value, out[i + 1] + cap[i + 1]) + out[i] = value + + # --------------------------------------------------------------------------- # # Incremental anchored-wire history # # --------------------------------------------------------------------------- # +def anchor_compliance(anchor_stiffness: float | None) -> float: + """Normalised anchor compliance ``1 / k_a`` of a first-node anchor. + + ``None`` or ``inf`` is the rigid anchor (compliance zero, the anchored + solver unchanged), ``0`` a free first node (compliance ``inf``). + """ + if anchor_stiffness is None: + return 0.0 + value = float(anchor_stiffness) + if math.isnan(value) or value < 0.0: + raise CableInputError( + "anchor stiffness must be non-negative (None or inf: rigid anchor)" + ) + if math.isinf(value): + return 0.0 + return math.inf if value == 0.0 else 1.0 / value + + +@njit(cache=True) +def _spring_step( + y: FloatArray, + bound: float, + h: float, + compliance: float, + force: float, + cap: FloatArray, + new: FloatArray, + xstar: FloatArray, + xs: FloatArray, + gs: FloatArray, + xt: FloatArray, + gt: FloatArray, +) -> tuple[float, float]: + """One projection with an elastic (or free) anchor at node 0. + + The first node carries half a node's friction (``bound / 2``) in + parallel with the anchor spring of compliance ``compliance`` (``inf``: a + free end); the far node is rigid, so the node slips are summed from it. + ``cap`` (``m + 1``) and the work arrays (``4 m + 8``) are overwritten. + Returns the friction dissipation of the increment and the new anchor + force. + """ + m = y.size + cap0 = 0.5 * bound + cap[0] = cap0 + for j in range(1, m): + cap[j] = bound + cap[m] = 0.0 + free = math.isinf(compliance) + weight = 0.0 if free else compliance / h + _project_ends( + y, cap, free, False, new, xstar, xs, gs, xt, gt, weight, force, 0.0, 0.0 + ) + # the free end carries no anchor force; else the friction takes its share + force = 0.0 if free else new[0] - min(max(new[0] - force, -cap0), cap0) + slip = 0.0 + dissipation = 0.0 + for j in range(m - 1, 0, -1): + slip -= h * (new[j] - y[j]) + dissipation += bound * abs(slip) + slip -= h * (new[0] - y[0]) + dissipation += cap0 * abs(slip) + return dissipation, force + + +def _spring_workspace(m: int) -> tuple[FloatArray, ...]: + """``cap``, ``new``, ``xstar`` and the four breakpoint arrays.""" + return ( + np.empty(m + 1), + np.empty(m), + np.empty(m), + np.empty(4 * m + 8), + np.empty(4 * m + 8), + np.empty(4 * m + 8), + np.empty(4 * m + 8), + ) + + @njit(cache=True) def _anchored_kernel( e_hat: FloatArray, @@ -269,6 +594,7 @@ def _anchored_kernel( index: NDArray[np.int64], out_n: FloatArray, out_ref: FloatArray, + compliance: float, ) -> float: m = e_hat.size n = np.zeros(m) @@ -276,23 +602,31 @@ def _anchored_kernel( y = np.empty(m) new = np.empty(m) xstar = np.empty(m) - xs = np.empty(2 * m + 4) - gs = np.empty(2 * m + 4) - xt = np.empty(2 * m + 4) - gt = np.empty(2 * m + 4) + xs = np.empty(4 * m + 8) + gs = np.empty(4 * m + 8) + xt = np.empty(4 * m + 8) + gt = np.empty(4 * m + 8) + cap = np.empty(m + 1) old = 0.0 dissipation = 0.0 + force = 0.0 row = 0 for i in range(load.size): step = load[i] - old bound = rho[i] * h for j in range(m): y[j] = n[j] + step * e_hat[j] - _project(y, bound, new, xstar, xs, gs, xt, gt) - slip = 0.0 - for j in range(m - 1): - slip += h * (new[j] - y[j]) - dissipation += bound * abs(slip) + if compliance > 0.0: + increment, force = _spring_step( + y, bound, h, compliance, force, cap, new, xstar, xs, gs, xt, gt + ) + dissipation += increment + else: + _project(y, bound, new, xstar, xs, gs, xt, gt) + slip = 0.0 + for j in range(m - 1): + slip += h * (new[j] - y[j]) + dissipation += bound * abs(slip) for j in range(m): n[j] = new[j] limit = rho[i] * cap_hat[j] @@ -316,6 +650,7 @@ def anchored_wire_response( cap_hat: FloatArray | None = None, record: NDArray[np.bool_] | None = None, index: NDArray[np.int64] | None = None, + anchor_stiffness: float | None = None, ) -> tuple[FloatArray, FloatArray, float]: """Incremental response of one wire anchored at both ends. @@ -339,6 +674,13 @@ def anchored_wire_response( Steps to record (default all). index : numpy.ndarray of int, optional Segments to record (default all). + anchor_stiffness : float or None, optional + Normalised stiffness ``k_a = K_a R / (E A sin a)`` of an elastic + anchor at the first node (``K_a`` [N/m] per wire, ``E A`` the chain's + axial stiffness): ``n_0 = k_a u_0 + f_0`` with the first node's half + friction ``|f_0| <= rho h / 2`` in parallel. ``None`` or ``inf`` + (default) is the rigid anchor of the module notes, on the unchanged + code path; ``0`` a free first node. The far node stays rigid. Returns ------- @@ -349,6 +691,7 @@ def anchored_wire_response( Friction dissipation over the path (normalised: ``g`` times slip ``w EA sin a / (g R)``, per wire). """ + compliance = anchor_compliance(anchor_stiffness) e = np.ascontiguousarray(e_hat, dtype=np.float64) path = np.ascontiguousarray(load, dtype=np.float64) if e.ndim != 1 or e.size < 2 or not np.isfinite(e).all(): @@ -385,7 +728,9 @@ def anchored_wire_response( out_n = np.zeros((rows, idx.size)) out_ref = np.zeros((rows, idx.size)) kernel = _anchored_kernel if HAVE_NUMBA else _anchored_numpy - dissipation = kernel(e, cap, path, ratio, float(h), flags, idx, out_n, out_ref) + dissipation = kernel( + e, cap, path, ratio, float(h), flags, idx, out_n, out_ref, compliance + ) return out_n, out_ref, float(dissipation) @@ -399,19 +744,27 @@ def _anchored_numpy( index: NDArray[np.int64], out_n: FloatArray, out_ref: FloatArray, + compliance: float, ) -> float: """NumPy path of :func:`_anchored_kernel` (used without ``numba``).""" n = np.zeros(e_hat.size) ref = np.zeros(e_hat.size) old = 0.0 dissipation = 0.0 + force = 0.0 row = 0 for i in range(load.size): step = load[i] - old bound = rho[i] * h y = n + step * e_hat - n = chain_projection_reference(y, bound) - dissipation += bound * float(np.abs(np.cumsum(h * (n - y))[:-1]).sum()) + if compliance > 0.0: + work = _spring_workspace(n.size) + increment, force = _spring_step(y, bound, h, compliance, force, *work) + n = work[1].copy() + dissipation += increment + else: + n = chain_projection_reference(y, bound) + dissipation += bound * float(np.abs(np.cumsum(h * (n - y))[:-1]).sum()) limit = rho[i] * cap_hat ref = np.clip(ref + step * e_hat, -limit, limit) old = load[i] @@ -436,6 +789,7 @@ def _field_kernel( index: NDArray[np.int64], out_n: FloatArray, out_ref: FloatArray, + compliance: float, ) -> float: n_s, m = drive.shape n = np.zeros(m) @@ -444,11 +798,13 @@ def _field_kernel( new = np.empty(m) de = np.empty(m) xstar = np.empty(m) - xs = np.empty(2 * m + 4) - gs = np.empty(2 * m + 4) - xt = np.empty(2 * m + 4) - gt = np.empty(2 * m + 4) + xs = np.empty(4 * m + 8) + gs = np.empty(4 * m + 8) + xt = np.empty(4 * m + 8) + gt = np.empty(4 * m + 8) + cap = np.empty(m + 1) dissipation = 0.0 + force = 0.0 for i in range(n_s): k = counts[i] r0 = rho[i - 1] if i > 0 else rho[0] @@ -460,11 +816,17 @@ def _field_kernel( bound = ((1.0 - w) * r0 + w * rho[i]) * h for j in range(m): y[j] = n[j] + de[j] - _project(y, bound, new, xstar, xs, gs, xt, gt) - slip = 0.0 - for j in range(m - 1): - slip += h * (new[j] - y[j]) - dissipation += bound * abs(slip) + if compliance > 0.0: + increment, force = _spring_step( + y, bound, h, compliance, force, cap, new, xstar, xs, gs, xt, gt + ) + dissipation += increment + else: + _project(y, bound, new, xstar, xs, gs, xt, gt) + slip = 0.0 + for j in range(m - 1): + slip += h * (new[j] - y[j]) + dissipation += bound * abs(slip) for j in range(m): n[j] = new[j] limit = bound / h * cap_hat[j] @@ -584,11 +946,13 @@ def _field_numpy( index: NDArray[np.int64], out_n: FloatArray, out_ref: FloatArray, + compliance: float, ) -> float: """NumPy path of :func:`_field_kernel` (used without ``numba``).""" n = np.zeros(c_hat.size) ref = np.zeros(c_hat.size) dissipation = 0.0 + force = 0.0 previous = np.zeros(c_hat.size) for i in range(drive.shape[0]): k = int(counts[i]) @@ -598,8 +962,14 @@ def _field_numpy( w = (q + 1.0) / k bound = ((1.0 - w) * r0 + w * rho[i]) * h y = n + de - n = chain_projection_reference(y, bound) - dissipation += bound * float(np.abs(np.cumsum(h * (n - y))[:-1]).sum()) + if compliance > 0.0: + work = _spring_workspace(n.size) + increment, force = _spring_step(y, bound, h, compliance, force, *work) + n = work[1].copy() + dissipation += increment + else: + n = chain_projection_reference(y, bound) + dissipation += bound * float(np.abs(np.cumsum(h * (n - y))[:-1]).sum()) limit = bound / h * cap_hat ref = np.clip(ref + de, -limit, limit) previous = drive[i] @@ -618,6 +988,7 @@ def anchored_wire_field_response( cap_hat: FloatArray | None = None, index: NDArray[np.int64] | None = None, substeps: NDArray[np.int64] | None = None, + anchor_stiffness: float | None = None, ) -> tuple[FloatArray, FloatArray, float]: """Anchored wire under a non-proportional curvature field (gap P5). @@ -632,9 +1003,12 @@ def anchored_wire_field_response( linearly. The path starts from the virgin state. Records are taken at every sample. ``substeps`` (per sample, at least the automatic count) fixes the subdivision, so that two runs can share one path. + ``anchor_stiffness`` is the elastic first-node anchor of + :func:`anchored_wire_response` (``None``: rigid). Returns ``(n, n_ref, dissipation)`` as :func:`anchored_wire_response`. """ + compliance = anchor_compliance(anchor_stiffness) a = np.ascontiguousarray(drive, dtype=np.float64) c = np.ascontiguousarray(c_hat, dtype=np.float64) if a.ndim != 2 or a.shape[1] < 2 or not np.isfinite(a).all(): @@ -677,7 +1051,9 @@ def anchored_wire_field_response( out_n = np.zeros((a.shape[0], idx.size)) out_ref = np.zeros((a.shape[0], idx.size)) kernel = _field_kernel if HAVE_NUMBA else _field_numpy - dissipation = kernel(a, c, cap, counts, ratio, float(h), idx, out_n, out_ref) + dissipation = kernel( + a, c, cap, counts, ratio, float(h), idx, out_n, out_ref, compliance + ) return out_n, out_ref, float(dissipation) diff --git a/tests/test_anchor_compliance.py b/tests/test_anchor_compliance.py new file mode 100644 index 0000000..6468b4e --- /dev/null +++ b/tests/test_anchor_compliance.py @@ -0,0 +1,679 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Elastic (compliant) wire anchors: closed forms, limits, energy, routes. + +A wire anchored at an end fitting is held by the potting with a finite +stiffness ``K`` [N/m per wire]. The anchored chains of the clamp solver, the +along-wire solver, the termination correction and the along-wire bending +test take it as a spring at the anchor node in parallel with the node's half +segment of friction. Closed form (uniform imposed strain ``A`` from the +virgin state, uniform bound ``rho``, normalised anchor stiffness ``k_a``, +interface stiffness ``k_hat = beta^2``; ``beta = inf`` for rigid stick): the +slip zone of length ``L`` next to the anchor solves + + k_a rho L^2 / 2 + rho (1 + k_a / beta) L + k_a rho / beta^2 + rho / beta - A = 0, + +the anchor force is ``S = A - rho / beta - rho L`` and the dissipation +``rho^2 (L^2 / (2 beta) + L^3 / 6)``; without slip ``S = k_a A / (k_a + +beta)``. ``k_a -> 0`` is the free end (``L = A / rho - 1 / beta``), +``k_a -> inf`` the rigid anchor. +""" + +from __future__ import annotations + +import math + +import numpy as np +import pytest +from scipy.optimize import minimize + +import cablexsec as cx +from cablexsec.analysis.beam_test import ( + AlongWireSection, + AlongWireSpec, + BendingProtocol, + ThreePoint, + simulate_bending_test, +) +from cablexsec.analysis.sea_state_batch import _termination_record +from cablexsec.analysis.termination import ( + TerminationSpec, + termination_friction_increment, +) +from cablexsec.exceptions import CableInputError +from cablexsec.mechanics import along_wire as aw +from cablexsec.mechanics import clamp_layer as cl +from cablexsec.mechanics.bend_restrictor import CurvatureField +from cablexsec.mechanics.papailiou import slip_onset_curvature +from cablexsec.provenance import Provenance + +pytestmark = pytest.mark.analytical_sanity +compiled = pytest.mark.skipif(not aw.HAVE_NUMBA, reason="needs the compiled kernels") + +A_LOAD = 3.0 + + +def _layer(k_hat: float = aw.RIGID_K_HAT) -> aw.WireChainLayer: + return aw.WireChainLayer( + name="unit", + n_wires=1, + r_helix_m=0.05, + lay_angle_rad=math.radians(30.0), + kappa_c_1_m=1.0, + k_hat=k_hat, + lam=0.0, + force_unit_N=1.0, + wire_area_m2=1.0, + ea_N=1.0, + ) + + +def _closed_form(k_a: float, beta: float, a: float, rho: float = 1.0): + """Anchor force, slip length and dissipation (module notes).""" + inv_b = 0.0 if math.isinf(beta) else 1.0 / beta + if k_a == 0.0: + length = max(a / rho - inv_b, 0.0) + if length == 0.0: + return 0.0, 0.0, 0.0 + force = 0.0 + else: + c2 = 0.5 * k_a * rho + c1 = rho * (1.0 + k_a * inv_b) + c0 = k_a * rho * inv_b**2 + rho * inv_b - a + if c0 >= 0.0: + return k_a * a / (k_a + beta), 0.0, 0.0 + length = (-c1 + math.sqrt(c1 * c1 - 4.0 * c2 * c0)) / (2.0 * c2) + force = a - rho * inv_b - rho * length + return force, length, rho**2 * (0.5 * length**2 * inv_b + length**3 / 6.0) + + +def _ramp(a: float = A_LOAD, steps: int = 120) -> np.ndarray: + return np.linspace(0.0, a, steps + 1)[1:] + + +def _cycle(amp: float, steps: int = 24) -> np.ndarray: + return np.r_[ + np.linspace(0, amp, steps + 1)[1:], + np.linspace(amp, -amp, 2 * steps + 1)[1:], + np.linspace(-amp, amp, 2 * steps + 1)[1:], + ] + + +def _soft(r: np.ndarray | float, c: float) -> np.ndarray: + return np.sign(r) * np.maximum(np.abs(r) - c, 0.0) + + +# --------------------------------------------------------------------------- # +# Projections # +# --------------------------------------------------------------------------- # +def _generic_projection(y, cap, left, right): + """SLSQP of the projection with elastic end anchors ``(weight, centre)``.""" + m = y.size + + def cost(z): + f = 0.5 * np.sum((z - y) ** 2) + if left is not None: + f += 0.5 * left[0] * _soft(z[0] - left[1], cap[0]) ** 2 + if right is not None: + f += 0.5 * right[0] * _soft(z[-1] - right[1], cap[-1]) ** 2 + return f + + def grad(z): + g = z - y + if left is not None: + g[0] += left[0] * _soft(z[0] - left[1], cap[0]) + if right is not None: + g[-1] += right[0] * _soft(z[-1] - right[1], cap[-1]) + return g + + rows, rhs = [], [] + for i in range(1, m): + r = np.zeros(m) + r[i], r[i - 1] = -1.0, 1.0 + rows += [r, -r] + rhs += [cap[i], cap[i]] + a_mat, b_vec = np.array(rows), np.array(rhs) + return minimize( + cost, + np.zeros(m), + jac=grad, + constraints=[ + {"type": "ineq", "fun": lambda z: b_vec + a_mat @ z, "jac": lambda z: a_mat} + ], + method="SLSQP", + options={"ftol": 1e-15, "maxiter": 2000}, + ).x + + +@pytest.mark.parametrize("seed", [3, 11]) +def test_spring_projections_match_a_generic_quadratic_programme(seed): + rng = np.random.default_rng(seed) + m = 7 + y = rng.normal(size=m) * 2.0 + cap = np.abs(rng.normal(size=m + 1)) * 0.4 + 0.05 + cap[0] = 0.0 if seed == 11 else cap[0] + left = (2.5, 0.3) + right = (0.7, -0.4) + work = [np.zeros(4 * m + 8) for _ in range(5)] + for lw, rw in ((left, None), (None, right), (left, right)): + out = np.empty(m) + cl._project_ends( + y, + cap, + False, + False, + out, + *work, + 0.0 if lw is None else lw[0], + 0.0 if lw is None else lw[1], + 0.0 if rw is None else rw[0], + 0.0 if rw is None else rw[1], + ) + ref = _generic_projection(y, cap, lw, rw) + assert np.abs(out - ref).max() < 1e-5 + # the clamp-layer spring step: uniform interior bound, half cap at node 0 + bound = 0.3 + caps = np.full(m + 1, bound) + caps[0] = 0.5 * bound + ref = _generic_projection(y, caps, (left[0] / 1.0, left[1]), None) + work = cl._spring_workspace(m) + _d, force = cl._spring_step(y, bound, 1.0, left[0], left[1], *work) + assert np.abs(work[1] - ref).max() < 1e-5 + assert force == pytest.approx( + work[1][0] - np.clip(work[1][0] - left[1], -0.15, 0.15) + ) + + +def test_right_end_root_handles_walls_and_coincident_breakpoints(): + # g with a jump at 0 (a free-end wall upstream) and the spring centre there + xs = np.array([-1.0, 0.0, 0.0, 2.0]) + gs = np.array([-3.0, -1.0, 0.5, 2.5]) + assert cl._end_root(xs, gs, 4, 1.0, 1.0, 2.0, 0.0, 0.0) == 0.0 + # roots beyond the last and before the first breakpoint + for shift, centre in ((-10.0, 5.0), (10.0, -5.0)): + g = gs + shift + root = cl._end_root(xs, g, 4, 1.0, 1.0, 1.0, centre, 0.5) + value = cl._g_at(xs, g, 4, 1.0, 1.0, root) + float(_soft(root - centre, 0.5)) + assert abs(value) < 1e-12 + assert (root > xs[-1]) if shift < 0 else (root < xs[0]) + + +# --------------------------------------------------------------------------- # +# Closed forms # +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize("k_a", [10.0, 1.0, 0.1, 0.0]) +def test_clamp_solver_spring_anchor_closed_form(k_a): + """Rigid stick: anchor force, slip length and dissipation.""" + h = 2.0 * math.pi / 256 + m = int(14.0 / h) + n, _ref, dissipation = cl.anchored_wire_response( + np.ones(m), _ramp(), h, anchor_stiffness=k_a + ) + force, length, d_exact = _closed_form(k_a, math.inf, A_LOAD) + last = n[-1] + # segment 0 carries the anchor force plus the first half segment's friction + assert last[0] - 0.5 * h == pytest.approx(force, abs=1e-4 * A_LOAD) + slipping = np.count_nonzero(np.abs(np.diff(last)) >= h * (1.0 - 1e-9)) + assert abs(slipping * h - length) <= 1.5 * h + assert dissipation == pytest.approx(d_exact, rel=2e-3, abs=1e-4) + + +@compiled +@pytest.mark.parametrize(("k_stick", "beta"), [(aw.RIGID_K_HAT, math.inf), (4.0, 2.0)]) +@pytest.mark.parametrize("k_a", [10.0, 1.0, 0.1, 0.0]) +def test_chain_spring_anchor_closed_form(k_stick, beta, k_a): + """Rigid and elastic (shear-lag) stick: the along-wire chain.""" + lay = _layer(k_stick) + chain = aw.WireChain.build( + lay, + 0.0, + 14.0 / (2.0 * math.pi) * lay.pitch_m, + segments_per_pitch=512, + anchor_stiffness_N_m=(k_a / lay.anchor_stiffness_hat(1.0), None), + ) + m = chain.segments + state = (np.zeros((1, m + 1)), np.zeros((1, m + 1)), np.zeros((1, m))) + state = (*state, np.zeros((1, m + 1))) + e_old = np.zeros((1, m)) + dissipation = 0.0 + for a in _ramp(): + e_new = np.full((1, m), a) + state, energy = aw.chain_layer_step( + chain, e_new, e_old, 1.0, state, np.zeros((1, m + 1)) + ) + e_old = e_new + dissipation += float(energy[0, 1]) + force, length, d_exact = _closed_form(k_a, beta, A_LOAD) + anchor = float(chain.spring[0] * state[0][0, 0]) + assert anchor == pytest.approx(force, abs=1e-4 * A_LOAD) + slipping = np.count_nonzero(np.abs(np.abs(state[3][0]) - 1.0) < 1e-9) + assert abs(slipping * chain.h - length) <= 1.5 * chain.h + assert dissipation == pytest.approx(d_exact, rel=5e-4, abs=1e-4) + + +@compiled +@pytest.mark.parametrize("k_a", [0.0, 0.3, 3.0]) +def test_clamp_and_chain_spring_anchors_agree(k_a): + """Two implementations of the same projection: round-off.""" + lay = _layer() + path = _cycle(6.0) + x = np.array([0.0, 6.0 * lay.pitch_m]) + hist = aw.along_wire_history( + lay, + x, + np.tile(path, (2, 1)), + segments_per_pitch=63, + max_increment=math.inf, + anchor_stiffness_N_m=(k_a / lay.anchor_stiffness_hat(1.0), None), + ) + n_cl, _ref, d_cl = cl.anchored_wire_response( + hist.chain.cos_seg[0].copy(), path, hist.chain.h, anchor_stiffness=k_a + ) + scale = np.abs(n_cl).max() + assert np.abs(hist.force[0].T - n_cl).max() < 1e-12 * scale + d_chain = hist.energy_J[0, -1, 1] / lay.energy_unit_J + assert d_chain == pytest.approx(d_cl, rel=1e-9) + + +def test_numpy_and_compiled_spring_kernels_agree(): + h = 2.0 * math.pi / 31 + m = 60 + phi = h * (np.arange(m) + 0.5) + e = np.cos(phi) + path = _cycle(5.0, 12) + rho = 1.0 + 0.2 * np.cos(np.arange(path.size)) + cap = np.arcsin(np.abs(np.cos(phi + 0.3))) + record = (np.arange(path.size) % 3 == 0).astype(np.int64) + index = np.array([0, 5, m - 1], dtype=np.int64) + rows = int(record.sum()) + drive = np.outer(path, 1.0 + 0.3 * np.sin(phi / 7.0)) + counts = np.full(path.size, 2, dtype=np.int64) + for compliance in (math.inf, 0.7, 1e-3): + outs = [np.zeros((rows, 3)) for _ in range(4)] + args = (e, cap, path, rho, h, record, index) + d1 = cl._anchored_kernel(*args, outs[0], outs[1], compliance) + d2 = cl._anchored_numpy(*args, outs[2], outs[3], compliance) + assert np.abs(outs[0] - outs[2]).max() < 1e-12 * np.abs(outs[0]).max() + assert d1 == pytest.approx(d2, rel=1e-12) + fouts = [np.zeros((path.size, 3)) for _ in range(4)] + fargs = (drive, np.cos(phi), cap, counts, rho, h, index) + f1 = cl._field_kernel(*fargs, fouts[0], fouts[1], compliance) + f2 = cl._field_numpy(*fargs, fouts[2], fouts[3], compliance) + assert np.abs(fouts[0] - fouts[2]).max() < 1e-12 * np.abs(fouts[0]).max() + assert f1 == pytest.approx(f2, rel=1e-12) + + +# --------------------------------------------------------------------------- # +# Limits # +# --------------------------------------------------------------------------- # +def test_rigid_anchor_is_the_unchanged_code_path(): + h = 2.0 * math.pi / 31 + m = 60 + e = np.cos(h * (np.arange(m) + 0.5)) + path = _cycle(5.0, 12) + base = cl.anchored_wire_response(e, path, h) + drive = np.outer(path, np.ones(m)) + field_base = cl.anchored_wire_field_response(drive, e, h) + for k_a in (None, math.inf): + same = cl.anchored_wire_response(e, path, h, anchor_stiffness=k_a) + assert np.array_equal(same[0], base[0]) and same[2] == base[2] + field = cl.anchored_wire_field_response(drive, e, h, anchor_stiffness=k_a) + assert np.array_equal(field[0], field_base[0]) + assert field[2] == field_base[2] + assert cl.anchor_compliance(None) == cl.anchor_compliance(math.inf) == 0.0 + assert cl.anchor_compliance(0.0) == math.inf + assert cl.anchor_compliance(4.0) == 0.25 + lay = _layer() + chain = aw.WireChain.build(lay, 0.0, lay.pitch_m, segments_per_pitch=16) + rigid = aw.WireChain.build( + lay, + 0.0, + lay.pitch_m, + segments_per_pitch=16, + anchor_stiffness_N_m=(math.inf, None), + ) + assert np.array_equal(chain.fixed, rigid.fixed) + assert not chain.spring.any() and not rigid.spring.any() + assert rigid.anchor_stiffness_N_m == (math.inf, None) + + +@compiled +def test_rigid_anchor_reproduces_the_chain_and_bending_test_bit_for_bit(): + lay = _layer(0.26) + x = np.array([0.0, 3.0 * lay.pitch_m]) + kx = np.tile(_cycle(4.0, 10), (2, 1)) + base = aw.along_wire_history(lay, x, kx, segments_per_pitch=16) + same = aw.along_wire_history( + lay, x, kx, segments_per_pitch=16, anchor_stiffness_N_m=(math.inf, None) + ) + assert np.array_equal(base.force, same.force) + assert np.array_equal(base.energy_J, same.energy_J) + sec = AlongWireSection((lay,), 2.0) + prot = BendingProtocol.cyclic( + "displacement", 0.02 * lay.pitch_m, n_cycles=1, samples_per_cycle=12 + ) + spec = AlongWireSpec(ends=("anchored", "anchored"), segments_per_pitch=16) + r0 = simulate_bending_test( + sec, ThreePoint(2 * lay.pitch_m), prot, stations_per_segment=6, along_wire=spec + ) + r1 = simulate_bending_test( + sec, + ThreePoint(2 * lay.pitch_m), + prot, + stations_per_segment=6, + along_wire=AlongWireSpec( + ends=("anchored", "anchored"), + segments_per_pitch=16, + k_anchor_N_m=(None, math.inf), + ), + ) + assert np.array_equal(r0.moment_Nm, r1.moment_Nm) + + +@compiled +def test_zero_stiffness_is_the_free_end(): + lay = _layer(0.26) + x = np.array([0.0, 3.0 * lay.pitch_m]) + kx = np.tile(_cycle(4.0, 10), (2, 1)) + free = aw.along_wire_history(lay, x, kx, ends=("free", "anchored")) + zero = aw.along_wire_history(lay, x, kx, anchor_stiffness_N_m=(0.0, None)) + assert np.array_equal(free.force, zero.force) + assert np.array_equal(free.energy_J, zero.energy_J) + # the clamp solver's zero-stiffness anchor against the chain's free end + rigid = _layer() + path = _cycle(6.0) + hist = aw.along_wire_history( + rigid, + np.array([0.0, 6.0 * rigid.pitch_m]), + np.tile(path, (2, 1)), + ends=("free", "anchored"), + segments_per_pitch=63, + max_increment=math.inf, + ) + n_cl, _ref, _d = cl.anchored_wire_response( + hist.chain.cos_seg[0].copy(), path, hist.chain.h, anchor_stiffness=0.0 + ) + assert np.abs(hist.force[0].T - n_cl).max() < 1e-12 * np.abs(n_cl).max() + + +@pytest.fixture(scope="module") +def menard_layer(): + cable = cx.load_cable(cx.menard2023_yaml_path(), geometry_override=None) + return cx.cable_to_fatigue_layers(cable, contact_tension_N=50e3)[0] + + +@compiled +def test_termination_solvers_agree_and_bracket_the_anchor_stiffness(menard_layer): + """Clamp and along-wire solvers (same convention) for every stiffness, + the rigid limit approached from below and the free end below every + finite anchor.""" + spec = menard_layer.spec + kc = slip_onset_curvature(spec) + kx = 20 * kc * np.sin(np.linspace(0, 4 * math.pi, 81)) + ea = spec.E_wire_Pa * spec.A_wire_m2 * spec.xi + unit = spec.r_helix_m / (ea * abs(math.sin(spec.lay_angle_rad))) + rigid = termination_friction_increment(spec, kx, 0 * kx, TerminationSpec(0.2)) + same = termination_friction_increment( + spec, kx, 0 * kx, TerminationSpec(0.2, k_anchor_N_m=math.inf) + ) + assert np.array_equal(rigid.stress_Pa, same.stress_Pa) + scale = np.abs(rigid.stress_Pa).max() + ranges = [] + errors = [] + for k_hat in (0.0, 0.1, 1.0, 10.0, 1e3, 1e6): + term = TerminationSpec(0.2, k_anchor_N_m=k_hat / unit) + a = termination_friction_increment(spec, kx, 0 * kx, term) + b = termination_friction_increment( + spec, + kx, + 0 * kx, + TerminationSpec(0.2, k_anchor_N_m=k_hat / unit, solver="along_wire"), + ) + assert np.abs(a.stress_Pa - b.stress_Pa).max() < 1e-12 * scale + assert "anchor" in a.note + ranges.append(float(np.ptp(a.stress_Pa, axis=1).max())) + errors.append(float(np.abs(a.stress_Pa - rigid.stress_Pa).max()) / scale) + assert all( + r1 <= r2 * (1 + 1e-9) for r1, r2 in zip(ranges, ranges[1:], strict=False) + ) + assert ranges[-1] <= float(np.ptp(rigid.stress_Pa, axis=1).max()) * (1 + 1e-9) + assert errors[-1] < 1e-4 + assert all(e2 <= e1 for e1, e2 in zip(errors, errors[1:], strict=False)) + + +@compiled +def test_termination_field_and_capstan_routes_take_the_anchor(menard_layer): + """A softer anchor lowers the clamp increment under a non-proportional + field (both solvers) and with the capstan bound.""" + spec = menard_layer.spec + kc = slip_onset_curvature(spec) + t = np.linspace(0, 4 * math.pi, 61) + kx = 15 * kc * np.sin(t) + x = np.linspace(0.0, 2.0, 41) + growth = 0.5 + 0.3 * np.sin(0.5 * t) + shape = 1.0 + growth[None, :] * (np.exp(-x[:, None]) - math.exp(-0.2)) + n = t.size + fld = CurvatureField( + x, + shape * kx[None, :], + None, + "test", + np.zeros(n), + np.zeros(n, dtype=np.int64), + np.zeros(n, dtype=bool), + math.inf, + np.zeros(n), + Provenance(method="test"), + ) + soft = 1e5 + options = ( + {"curvature_field": fld}, + {"curvature_field": fld, "solver": "along_wire"}, + {"solver": "along_wire", "stick": "spring", "capstan": True}, + ) + for option in options: + base = termination_friction_increment( + spec, kx, 0 * kx, TerminationSpec(0.2, **option) + ) + sprung = termination_friction_increment( + spec, kx, 0 * kx, TerminationSpec(0.2, k_anchor_N_m=soft, **option) + ) + assert sprung.applied and "anchor" in sprung.note + assert np.isfinite(sprung.stress_Pa).all() + assert ( + np.ptp(sprung.stress_Pa, axis=1).max() + < np.ptp(base.stress_Pa, axis=1).max() + ) + + +# --------------------------------------------------------------------------- # +# Energy and the two-way bending test # +# --------------------------------------------------------------------------- # +@compiled +@pytest.mark.parametrize("k_stick", [aw.RIGID_K_HAT, 0.26]) +@pytest.mark.parametrize("lam", [0.0, 0.3]) +def test_energy_identity_with_elastic_anchors(k_stick, lam): + lay = aw.WireChainLayer( + name="unit", + n_wires=3, + r_helix_m=0.05, + lay_angle_rad=math.radians(30.0), + kappa_c_1_m=1.0, + k_hat=k_stick, + lam=lam, + force_unit_N=1.0, + wire_area_m2=1.0, + ea_N=1.0, + ) + x = np.linspace(0.0, 4.0 * lay.pitch_m, 5) + shape = np.exp(-x / lay.pitch_m)[:, None] + kx = shape * _cycle(8.0, 16)[None, :] + unit = lay.anchor_stiffness_hat(1.0) + for stiffness in ((0.7 / unit, 2.0 / unit), (0.05 / unit, None)): + hist = aw.along_wire_history( + lay, x, kx, segments_per_pitch=24, anchor_stiffness_N_m=stiffness + ) + work = np.abs(hist.energy_J[..., 0]).max() + assert np.abs(hist.balance_residual_J).max() < 1e-12 * work + assert (np.diff(hist.energy_J[..., 1], axis=1) >= -1e-12 * work).all() + + +@compiled +def test_spring_anchor_jacobian_equals_the_finite_difference_in_stick(): + lay = _layer(0.26) + unit = lay.anchor_stiffness_hat(1.0) + chain = aw.WireChain.build( + lay, + 0.0, + lay.pitch_m, + segments_per_pitch=16, + anchor_stiffness_N_m=(0.8 / unit, 3.0 / unit), + ) + stations = 9 + x_all = np.linspace(0.0, chain.x_end_m, stations) + pos = np.clip(np.searchsorted(x_all, chain.x_seg_m, side="right") - 1, 0, 7) + frac = np.clip((chain.x_seg_m - x_all[pos]) / (x_all[pos + 1] - x_all[pos]), 0, 1) + j0, fj = chain.record_weights(x_all) + cos_st = np.cos(lay.azimuth(x_all[None, :], np.zeros((1, 1)))) + + def strain(kappa): + k_seg = kappa[pos] * (1.0 - frac) + kappa[pos + 1] * frac + return np.ascontiguousarray(chain.cos_seg * k_seg) + + def moment(n): + vals = n[:, j0] * (1.0 - fj) + n[:, j0 + 1] * fj + return lay.lever_Nm * np.sum(cos_st * vals, axis=0) + + def step(state, k_old, k_new): + guess = np.zeros_like(state[0]) + new, _ = aw.chain_layer_step( + chain, strain(k_new), strain(k_old), 20.0, state, guess + ) + return new, guess + + m = chain.segments + zero = (np.zeros((1, m + 1)), np.zeros((1, m + 1)), np.zeros((1, m))) + zero = (*zero, np.zeros((1, m + 1))) + kappa0 = 0.3 * np.cos(np.linspace(0.0, 1.0, stations)) + state1, _ = step(zero, np.zeros(stations), kappa0) + kappa1 = kappa0 + 0.1 + new, solution = step(state1, kappa0, kappa1) + jac = aw.chain_layer_jacobian( + chain, state1, solution, new[2], 20.0, pos, frac, j0, fj, cos_st + ) + base = moment(new[2]) + fd = np.empty_like(jac) + for j in range(stations): + kp = kappa1.copy() + kp[j] += 1e-3 + moved, _ = step(state1, kappa0, kp) + fd[:, j] = (moment(moved[2]) - base) / 1e-3 + np.testing.assert_allclose(jac, fd, rtol=0, atol=1e-7 * np.abs(fd).max()) + # rigid interface: the stick mask must not count the spring as friction + rigid = aw.WireChain.build( + _layer(), + 0.0, + lay.pitch_m, + segments_per_pitch=16, + anchor_stiffness_N_m=(0.8 / unit, None), + ) + zr = (np.zeros((1, m + 1)), np.zeros((1, m + 1)), np.zeros((1, m))) + zr = (*zr, np.zeros((1, m + 1))) + guess = np.zeros((1, m + 1)) + e1 = np.ascontiguousarray(rigid.cos_seg * 0.3) + new_r, _ = aw.chain_layer_step(rigid, e1, 0 * e1, 20.0, zr, guess) + jr = aw.chain_layer_jacobian( + rigid, zr, guess, new_r[2], 20.0, pos, frac, j0, fj, cos_st + ) + assert np.isfinite(jr).all() + + +@pytest.fixture(scope="module") +def cable33(): + return cx.load_cable(cx.inter_array_single_core_yaml_path()) + + +@compiled +def test_two_way_bending_test_with_elastic_end_fittings(cable33): + """Anchored short specimen: equilibrium, closed-cycle work against the + friction work, the free and rigid limits.""" + sec = AlongWireSection.from_cable(cable33) + lay = sec.layers[0] + p = max(layer.pitch_m for layer in sec.layers) + prot = BendingProtocol.cyclic( + "displacement", 0.02 * p, n_cycles=2, samples_per_cycle=40 + ) + + def run(ends, k_anchor): + return simulate_bending_test( + sec, + ThreePoint(2 * p), + prot, + stations_per_segment=8, + along_wire=AlongWireSpec( + ends=ends, + overhang_m=(0.2 * p, 0.2 * p), + segments_per_pitch=32, + k_anchor_N_m=k_anchor, + ), + ) + + anchored = ("anchored", "anchored") + k_mid = 1.0 / lay.anchor_stiffness_hat(1.0) # one radian of wire + free = run(("free", "free"), (None, None)) + zero = run(anchored, (0.0, 0.0)) + assert np.array_equal(free.moment_Nm, zero.moment_Nm) + rigid = run(anchored, (None, None)) + mid = run(anchored, (k_mid, k_mid)) + assert mid.equilibrium_residual < 1e-6 + cyc, fr = mid.cycle_external_work_J(), mid.cycle_friction_work_J() + assert fr is not None and abs(cyc - fr) / fr < 0.01 + peak = [float(np.abs(r.load_N).max()) for r in (free, mid, rigid)] + assert peak[0] <= peak[1] <= peak[2] + + +# --------------------------------------------------------------------------- # +# Inputs and records # +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize("bad", [-1.0, math.nan, True, "1e8"]) +def test_termination_anchor_stiffness_validation(bad): + with pytest.raises(CableInputError): + TerminationSpec(0.1, k_anchor_N_m=bad) + + +def test_anchor_stiffness_input_errors(): + with pytest.raises(CableInputError): + TerminationSpec(0.1, anchor="none", k_anchor_N_m=1e8) + assert TerminationSpec(0.1, k_anchor_N_m=2).k_anchor_N_m == 2.0 + for bad in ((-1.0, None), (math.nan, None), (True, None)): + with pytest.raises(CableInputError): + AlongWireSpec(ends=("anchored", "anchored"), k_anchor_N_m=bad) + with pytest.raises(CableInputError): + AlongWireSpec(k_anchor_N_m=(1e8, None)) # free ends + with pytest.raises(CableInputError): + AlongWireSpec(ends=("anchored", "anchored"), k_anchor_N_m=(1e8,)) # type: ignore[arg-type] + spec = AlongWireSpec(ends=("anchored", "free"), k_anchor_N_m=(5, None)) + assert spec.k_anchor_N_m == (5.0, None) + lay = _layer() + for ends, k in ( + (("free", "anchored"), (1e8, None)), + (("anchored", "anchored"), (-1.0, None)), + (("anchored", "anchored"), (1e8,)), + ): + with pytest.raises(CableInputError): + aw.WireChain.build(lay, 0.0, lay.pitch_m, ends=ends, anchor_stiffness_N_m=k) + with pytest.raises(CableInputError): + cl.anchor_compliance(-1.0) + with pytest.raises(CableInputError): + cl.anchored_wire_response( + np.ones(4), np.ones(2), 0.1, anchor_stiffness=math.nan + ) + + +def test_anchor_stiffness_survives_the_section_record(): + spec = TerminationSpec(0.3, k_anchor_N_m=2.5e8) + record = _termination_record(spec) + assert record["k_anchor_N_m"] == 2.5e8 + assert TerminationSpec(**record) == spec + record.pop("k_anchor_N_m") + assert TerminationSpec(**record).k_anchor_N_m is None # older records diff --git a/tests/test_clamp_layer.py b/tests/test_clamp_layer.py index a300b67..1ec33c7 100644 --- a/tests/test_clamp_layer.py +++ b/tests/test_clamp_layer.py @@ -233,8 +233,8 @@ def test_numpy_path_matches_kernel(): index = np.array([0, 5, m - 1], dtype=np.int64) rows = int(record.sum()) outs = [np.zeros((rows, 3)) for _ in range(4)] - d1 = cl._anchored_kernel(e, cap, path, rho, h, record, index, outs[0], outs[1]) - d2 = cl._anchored_numpy(e, cap, path, rho, h, record, index, outs[2], outs[3]) + d1 = cl._anchored_kernel(e, cap, path, rho, h, record, index, outs[0], outs[1], 0.0) + d2 = cl._anchored_numpy(e, cap, path, rho, h, record, index, outs[2], outs[3], 0.0) assert np.allclose(outs[0], outs[2], atol=1e-10) assert np.allclose(outs[1], outs[3], atol=1e-12) assert d1 == pytest.approx(d2, rel=1e-9) diff --git a/tests/test_clamp_progressive_inputs.py b/tests/test_clamp_progressive_inputs.py index e382a93..6f965c2 100644 --- a/tests/test_clamp_progressive_inputs.py +++ b/tests/test_clamp_progressive_inputs.py @@ -42,8 +42,12 @@ def test_field_numpy_fallback_matches_the_kernel(): rho = np.linspace(1.0, 0.9, drive.shape[0]) index = np.array([0, m // 2, m - 1], dtype=np.int64) outs = [np.zeros((drive.shape[0], index.size)) for _ in range(4)] - d1 = cl._field_kernel(drive, c_hat, cap, counts, rho, h, index, outs[0], outs[1]) - d2 = cl._field_numpy(drive, c_hat, cap, counts, rho, h, index, outs[2], outs[3]) + d1 = cl._field_kernel( + drive, c_hat, cap, counts, rho, h, index, outs[0], outs[1], 0.0 + ) + d2 = cl._field_numpy( + drive, c_hat, cap, counts, rho, h, index, outs[2], outs[3], 0.0 + ) np.testing.assert_allclose(outs[0], outs[2], atol=1e-10) np.testing.assert_allclose(outs[1], outs[3], atol=1e-12) assert d1 == pytest.approx(d2, rel=1e-9) diff --git a/validation/scripts/check_saevik2011.py b/validation/scripts/check_saevik2011.py index 43f892e..0092069 100644 --- a/validation/scripts/check_saevik2011.py +++ b/validation/scripts/check_saevik2011.py @@ -87,6 +87,7 @@ KAPPA_B0, KAPPA_B1 = 0.067, 0.11 # [Saevik2011] Eq. 88 GJ_HALF_ANGLE_DEG = 8.0 # [Gjosteen2027] LC 14, +-8 deg TENDONS = "round" # "round" (rows on record) or "rectangular" (gap G1) +K_ANCHOR_N_M: float | None = None # end-fitting anchor stiffness per wire (rigid) _POLYMER = {"round": "polymer_saevik2011", "rectangular": "polymer_saevik2011_rect"} @@ -100,6 +101,17 @@ def use_tendons(tendons: str) -> None: gate_values.cache_clear() +def use_anchor(k_anchor_N_m: float | None) -> None: + """Set the anchor stiffness of the termination correction (None: rigid). + + Sensitivity studies only (``check_saevik2011_anchor.py``); the registered + rows use the rigid anchor. + """ + global K_ANCHOR_N_M + K_ANCHOR_N_M = k_anchor_N_m + gate_values.cache_clear() + + @dataclass(frozen=True) class LoadCase: lc: int @@ -392,7 +404,11 @@ def station_ranges( ky = np.zeros_like(kx) term = None if profile is not None: - term = TerminationSpec(distance_m=x_s - X_ANCHOR_M, curvature_profile=profile) + term = TerminationSpec( + distance_m=x_s - X_ANCHOR_M, + curvature_profile=profile, + k_anchor_N_m=K_ANCHOR_N_M, + ) field = wire_stress_field(layer, kx, ky, termination=term) last = slice(kx.size - 4 * 60 - 1, kx.size) ratio = ( diff --git a/validation/scripts/check_saevik2011_anchor.py b/validation/scripts/check_saevik2011_anchor.py new file mode 100644 index 0000000..57be930 --- /dev/null +++ b/validation/scripts/check_saevik2011_anchor.py @@ -0,0 +1,254 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Sensitivity of the Sævik (2011) termination rows to the anchor stiffness. + +Reported, not gated (doc/benchmarks.md, "Anchor compliance of the end +fitting"). The registered rows SV11-PLANE and SV11-GJ (termination-corrected, +clamp solver, ``stick="scaled"``) and the along-wire variant of gap T2 +(``stick="spring"``, capstan bound, every wire between the two end fittings, +the beam curvature field at every angle sample) are re-run with an elastic +anchor of stiffness ``K`` per tendon at both end fittings, over a grid that +spans the potting estimate of the termination guide (``1e8``-``2e9`` N/m) +down to a free end. Nothing is fitted; the rigid anchor stays the default. + +Usage:: + + python validation/scripts/check_saevik2011_anchor.py OUTPUT_JSON + [--k 2e9 5e8 ...] [--skip-chain] [--cases 14 ...] + +The rigid anchor is ``inf`` in ``--k`` and ``null`` in the output. Thread +counts are set to one. +""" + +from __future__ import annotations + +import argparse +import json +import math +import os +import sys +import time +from pathlib import Path + +for _name in ( + "OMP_NUM_THREADS", + "MKL_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "NUMBA_NUM_THREADS", +): + os.environ.setdefault(_name, "1") + +import numpy as np # noqa: E402 + +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import check_saevik2011 as sv # noqa: E402 + +#: Anchor stiffness per tendon [N/m]; inf is the rigid anchor of the rows. +K_GRID = (math.inf, 2e9, 5e8, 1e8, 1e7, 1e6, 0.0) +LEVELS = 60 # angle samples per leg, as the station histories of the rows + + +def _label(k: float) -> float | None: + return None if math.isinf(k) else k + + +def one_way(k: float, mu: float = sv.MU_DECLARED) -> dict: + """SV11-PLANE and SV11-GJ, termination-corrected, with anchor ``k``.""" + sv.use_anchor(_label(k)) + try: + values = sv.gate_values(mu) + finally: + sv.use_anchor(None) + plane, gj = values["plane"], values["gjosteen"] + return { + "median_R": plane["median_R_termination"], + "in_band": plane["count_in_band_termination"], + "R_per_case": {str(lc): v["R_termination"] for lc, v in plane["cases"].items()}, + "gj_ratio": gj["ratio_termination"], + "gj_MPa": gj["plane_pred_MPa"], + } + + +def _field_table(beam: sv.Beam, half_deg: float) -> np.ndarray: + """Beam curvature at ``LEVELS + 1`` rocker angles from 0 to ``half``.""" + table = np.zeros((LEVELS + 1, beam.n)) + w = None + for j in range(1, LEVELS + 1): + w, k = beam.solve(math.radians(half_deg) * j / LEVELS, w) + table[j] = k + return table + + +def _chain_case( + case: sv.LoadCase, + k_values: tuple[float, ...], + mu: float, + half_deg: float | None, + names: tuple[str, ...], + anchor_diagnostic: bool = False, +) -> dict: + """Along-wire station ranges [Pa] of one load case for every ``k``. + + ``anchor_diagnostic`` adds, for the rigid anchor and every wire, the + largest wire stress at the near end fitting and its range over the last + cycle (``anchor_Pa``), against the largest station range. + """ + from cablexsec.mechanics.along_wire import ( # noqa: PLC0415 + WireChainLayer, + along_wire_history, + ) + + _state, layer, static = sv.section(case, mu) + moment, _ei_max, ei_min = sv.backbone(case, mu) + beam = sv.Beam(moment, ei_min, case.tension_N) + half = case.angle_range_deg / 2 if half_deg is None else half_deg + table = _field_table(beam, half) + angles = sv._history(1.0, LEVELS) # in units of the half angle + level = np.rint(np.abs(angles) * LEVELS).astype(np.int64) + field = (np.sign(angles)[None, :] * table[level].T).astype(np.float64) + chain_layer = WireChainLayer.from_layer_spec( + layer.spec, stick="spring", capstan=True + ) + stations = {s: (x, az) for s, x, az in sv.stations() if s in names} + n_w = chain_layer.n_wires + picks: dict[str, tuple[int, int, float]] = {} + for s, (x_s, az) in stations.items(): + theta0 = float(chain_layer.azimuth(np.array([x_s]), 0)[0]) + pos = ((math.radians(az) - theta0) % (2 * math.pi)) * n_w / (2 * math.pi) + i0 = int(math.floor(pos)) % n_w + picks[s] = (i0, (i0 + 1) % n_w, pos - math.floor(pos)) + wires = sorted({w for i0, i1, _f in picks.values() for w in (i0, i1)}) + rec = np.array([stations[s][0] for s in picks]) + last = slice(angles.size - 4 * LEVELS - 1, angles.size) + out: dict = {"static_Pa": static, "ranges_Pa": {}} + for k in k_values: + hist = along_wire_history( + chain_layer, + beam.x, + field, + extent_m=(sv.X_ANCHOR_M, sv.X_ANCHOR_M + sv.FREE_LENGTH_M), + ends=("anchored", "anchored"), + segments_per_pitch=64, + record_x_m=rec, + wires=wires, + max_increment=0.5, + anchor_stiffness_N_m=(_label(k), _label(k)), + ) + row = {w: i for i, w in enumerate(hist.wires.tolist())} + ranges = {} + for j, (s, (i0, i1, f)) in enumerate(picks.items()): + stress = (1 - f) * hist.stress_Pa[row[i0], j] + f * hist.stress_Pa[ + row[i1], j + ] + ranges[s] = float(np.ptp(stress[last])) + out["ranges_Pa"][str(_label(k))] = ranges + if anchor_diagnostic: + hist = along_wire_history( + chain_layer, + beam.x, + field, + extent_m=(sv.X_ANCHOR_M, sv.X_ANCHOR_M + sv.FREE_LENGTH_M), + ends=("anchored", "anchored"), + segments_per_pitch=64, + record_x_m=np.array([sv.X_ANCHOR_M]), + max_increment=0.5, + ) + at_anchor = hist.stress_Pa[:, 0, :] + out["anchor_Pa"] = { + "max_abs": float(np.abs(at_anchor).max()), + "max_range_last_cycle": float(np.ptp(at_anchor[:, last], axis=1).max()), + "largest_station_range": max( + max(r.values()) for r in out["ranges_Pa"].values() + ), + } + return out + + +def chain( + k_values: tuple[float, ...], cases: list[int] | None, mu: float +) -> tuple[dict, dict]: + """T2-SV-PLANE and T2-SV-GJ with the along-wire chain for every ``k``, + and the anchor diagnostic of LC 14 at +-8 deg.""" + meas = { + (int(r["load_case"]), r["station"]): float(r["measured"]) + for r in sv.measured_saevik() + } + plane = sv.plane_stations() + per_k: dict[str, dict] = {str(_label(k)): {"R_per_case": {}} for k in k_values} + for case in sv.load_cases(): + if cases is not None and case.lc not in cases: + continue + t0 = time.time() + res = _chain_case(case, k_values, mu, None, plane) + m = np.array([meas[(case.lc, s)] for s in plane]) + for key, ranges in res["ranges_Pa"].items(): + pred = np.array([ranges[s] for s in plane]) / res["static_Pa"] + per_k[key]["R_per_case"][str(case.lc)] = float(pred.mean() / m.mean()) + print(f"chain LC{case.lc} {time.time() - t0:.1f}s", flush=True) + for values in per_k.values(): + r = np.array(list(values["R_per_case"].values())) + values["median_R"] = float(np.median(r)) if r.size else math.nan + values["in_band"] = int(np.sum((r >= 0.70) & (r <= 1.43))) + if cases is None or 14 in cases: + lc14 = next(c for c in sv.load_cases() if c.lc == 14) + gj_names = ("2.1", "2.5", "3.1", "3.5") + res = _chain_case( + lc14, k_values, mu, sv.GJ_HALF_ANGLE_DEG, gj_names, anchor_diagnostic=True + ) + diagnostic = res["anchor_Pa"] + gj_meas = sv.measured_gjosteen() + for key, ranges in res["ranges_Pa"].items(): + pred = [ranges[s] / 1e6 for s in gj_names] + per_k[key]["gj_MPa"] = dict(zip(gj_names, pred, strict=True)) + per_k[key]["gj_ratio"] = float( + np.mean(pred) / np.mean([gj_meas[s] for s in gj_names]) + ) + else: + diagnostic = {} + return per_k, diagnostic + + +def main() -> None: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("output", type=Path) + parser.add_argument("--k", type=float, nargs="*", default=list(K_GRID)) + parser.add_argument("--mu", type=float, default=sv.MU_DECLARED) + parser.add_argument("--cases", type=int, nargs="*", default=None) + parser.add_argument("--skip-chain", action="store_true") + args = parser.parse_args() + k_values = tuple(float(k) for k in args.k) + t0 = time.time() + lay = sv.section(sv.load_cases()[0], args.mu)[1].spec + ea = lay.E_wire_Pa * lay.A_wire_m2 + out: dict = { + "mu": args.mu, + "EA_N": ea, + "xi": lay.xi, + "equivalent_length_m": { + str(_label(k)): (ea / k if k > 0 else math.inf) for k in k_values + }, + "one_way": {}, + } + for k in k_values: + out["one_way"][str(_label(k))] = one_way(k, args.mu) + v = out["one_way"][str(_label(k))] + print( + f"one-way K={k:g}: median R {v['median_R']:.3f}, {v['in_band']} of 14, " + f"GJ {v['gj_ratio']:.3f}", + flush=True, + ) + if not args.skip_chain: + out["chain"], out["anchor_diagnostic"] = chain(k_values, args.cases, args.mu) + for key, v in out["chain"].items(): + print( + f"chain K={key}: median R {v['median_R']:.3f}, {v['in_band']} of " + f"{len(v['R_per_case'])}, GJ {v.get('gj_ratio', math.nan):.3f}", + flush=True, + ) + print("anchor diagnostic (LC 14, +-8 deg, rigid):", out["anchor_diagnostic"]) + out["seconds"] = time.time() - t0 + args.output.write_text(json.dumps(out, indent=1), encoding="utf-8") + + +if __name__ == "__main__": + main() diff --git a/validation/validation_report.md b/validation/validation_report.md index 3ef22aa..0b42c24 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -62,9 +62,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1074 passed, 3111 deselected` -- independent_method: `70 passed, 4115 deselected` -- full_scale: `27 passed, 4158 deselected` +- analytical_sanity: `1110 passed, 3111 deselected` +- independent_method: `70 passed, 4151 deselected` +- full_scale: `27 passed, 4194 deselected` Run `pytest -m ` to reproduce each group.