From 698bfd2766b3d1166bcf946f97fa4161b82bc818 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 06:01:56 +0900 Subject: [PATCH 1/3] feat: slip scaling variable of the exported bending law The exported bending law held one contact state per tension and was interpolated between tensions, with no rule for its slider states when the tension changes. export_bending_law(..., slip_scale=True) now adds BendingLawExport.slip_scale, a SlipScaleTable: - the law at a reference tension split into friction groups, one per structural armour layer and laid_cores for the core lay stage, each with its Iwan elements (k_i, kappa_y,i), plus EI_slip; - the cap R_g of every group (its planar full-slip friction moment) over a table of tensions and, optionally, external pressures (solved section states), the group scale rho_g = R_g / R_g,ref, the single cap-weighted scale s = sum R_g / sum R_g,ref, and the derivatives d/dT and d/dp_e (central differences of the contact model). Why it is exact per group: the direction-tied wire is a spring-slider of fixed stiffness k_f = xi E cos^2 a whose bounds are proportional to its layer's P1+P2. The return map is positively homogeneous, so a group whose bounds scale by rho obeys M(kappa; rho) = rho M(kappa / rho; 1) over any history (the signed capstan bound included), and its Iwan elements keep k_i while their yield curvatures become rho kappa_y,i. Under a changing state every element follows the return map with the new cap, e_i <- clip(e_i + dkappa, -rho kappa_y,i, rho kappa_y,i), the rule the fatigue kernels and the contact-tension history of compute_mkappa apply to every wire (SlipScaleTable.moment, law_at, dissipated_energy). The caps come from the scalar-tension contact states of compute_mkappa (pressure only; no crossed-wire line loads), so layer stacks whose contact histories are refused still export a scale. Tests (tests/test_bending_law_slip_scale.py): - compute_mkappa at 70 kN is the 20 kN law with the bound scaled over a loop history, cores included (66 kV template, every group ~ T): 4e-16; - every group law decomposed at 60 kN on the grid rho_g kappa is the 10 kN group law with yield curvatures times rho_g (Menard, layers scaling by 2.06 and 1.40; 33 kV three-core with cores): < 1e-13; - with symmetric wire bounds on a grid through every wire's slip curvature, the scaled law under a tension cycle inside bending cycles is compute_mkappa with the contact-tension history, moment and work, to 1e-14; - with the signed bound it misses the history route by at most 1.02 times the fixed-tension Iwan residual (Menard 0.17 %, 66 kV 0.11 % of the range); the frozen law misses by 19 % and 43 %; - table values and slopes, the pressure axis, JSON/CSV, project round trip, input checks, a falling cap at fixed curvature. One scale for all groups is exact when the groups scale alike and keeps the stick stiffness and full-slip moment otherwise. Largest error against the per-group law over 10-150 kN (backbone and cycles to 1.5 times full slip): 66 kV 0; 33 kV three-core 0.10 % (0.29 % with cores); Menard 12 %; with an external pressure of 0-2 MPa 21 % (66 kV), 12 % (33 kV), 19 % (Menard). Torque is not a table variable, and the internal-ring slip of resolved strands is refused. Format: the JSON law with a slip scale is cablexsec.bending_law/2 (a new slip_scale object, version-1 fields unchanged); without one it stays version 1. SlipScaleTable.to_csv writes the table. BendingLawSettings passes the new options. The project codec accepts a missing field that has a default, so project files written before slip_scale existed still load. export_bending_law refuses contact_pressure_Pa and contact_tension_history_N as options. Fixed: the docs and provenance claimed the exported Iwan law follows compute_mkappa exactly. The signed capstan bound makes each wire's slip interval asymmetric, which no Masing element carries; the residual is about 0.1 % of the moment range near full slip (0.02 % at mu = 0.02, 0.017 % with symmetric bounds on Menard). New validation row MX-scale (tier 1): 4.1e-16; 8.3e-14; ratio 1.02 against < 1e-12; < 1e-12; <= 1.25. Docs: global-local guide Section 8.1, file formats, concepts, benchmark register, VALIDATION.md, changelog. Signed-off-by: Jae Hoon Seo --- ARCHITECTURE.md | 2 +- CHANGELOG.md | 29 + VALIDATION.md | 1 + doc/benchmarks.md | 17 +- doc/concepts.md | 11 +- doc/file_formats.md | 46 +- doc/global_local_guide.md | 93 ++- doc/project_guide.md | 2 +- src/cablexsec/__init__.py | 2 + src/cablexsec/_project_codec.py | 25 +- src/cablexsec/analysis/bending_law.py | 844 +++++++++++++++++++++++++- src/cablexsec/io/global_export.py | 4 +- src/cablexsec/project.py | 12 + tests/test_bending_law_slip_scale.py | 638 +++++++++++++++++++ validation/scripts/run_validation.py | 127 ++++ validation/validation_report.md | 7 +- 16 files changed, 1816 insertions(+), 44 deletions(-) create mode 100644 tests/test_bending_law_slip_scale.py diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f9a01c0..b0360d7 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -167,7 +167,7 @@ Functional kernels operating on arrays; most are not called directly by users. | `conductor_fatigue.py` | `assess_conductor_fatigue` behind `compute_conductor_fatigue`: ring-by-ring strand-slip strain, bulk Miner sums (optional user S-N options), opt-in trellis SWT fretting (not validated) and strain life above yield | | `compression.py` | `compression_screen`, `compute_compression_capacity`: armour in compression; lateral buckling lower bound (Sævik–Thorsen Eq. 19) and round-wire limit with cyclic-curvature knock-down (Li–Vaz), friction first-slip gate, radial (bird-cage) buckling of the armour stack on the outboard sheath and tape foundation with hoop-capacity and yield interaction (Eq. 35), DNV-RP-F401 utilisation factors, combined tension/compression–curvature curve ([doc/uls_guide.md](doc/uls_guide.md)) | | `coiling.py` | `compute_coiling`: a cable coiled into a static tank (curvature 2/D with one twist per winding, Chae, Nam and Shim 2023); the twisted section solved first (radial, axial and torsional), then the bending turned through each winding on fixed fibres; per armour layer the extreme wire stresses, the friction stress, the contact pressure, the radial-buckling (bird-caging) capacity in wire stress and the first-yield check (beyond first yield the result says the elastic stresses are not valid); the friction-free lateral bound is reported, not used; unbonded flexible pipes are refused and counter-helical (non-coilable) armour is flagged | -| `bending_law.py` | `export_bending_law`, `IwanBendingLaw`, `BendingLawExport`: the section moment–curvature backbone at several tensions decomposed into an exact Iwan law (parallel elastic–perfectly plastic elements) for global solvers; tension interpolation; JSON, CSV and kN–m table writers ([doc/global_local_guide.md](doc/global_local_guide.md) Section 8) | +| `bending_law.py` | `export_bending_law`, `IwanBendingLaw`, `BendingLawExport`, `SlipScaleTable`: the section moment–curvature backbone at several tensions decomposed into an Iwan law (parallel elastic–perfectly plastic elements) for global solvers; tension interpolation or the slip scaling variable (per-group yield curvatures scaled by the friction caps over tension and external pressure); JSON, CSV and kN–m table writers ([doc/global_local_guide.md](doc/global_local_guide.md) Section 8) | | `sheave.py` | `compute_sheave`: a cable pulled over a sheave; groove line and global pressure, cosine groove distribution and run-on contact (Feyrer 2015), wire stresses, capacity utilisation and per-passage damage from the section analyses | | `electrical_life.py` | `compute_electrical_life`: coaxial field and relative water-tree ageing factor | | `curve_comparison.py` | Sequence-preserving comparison of measured cyclic curves (benchmark support) | diff --git a/CHANGELOG.md b/CHANGELOG.md index 0ecb723..7937ffc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -26,9 +26,38 @@ All notable changes to CableXSec are recorded in this file. The format follows moment) and closes the work balance (1.1e-15 of the friction work). `SectionLaw` and the bending-test simulator keep a fixed pressure (their leg solver evaluates trial curvatures without a sample time), and so does the exported bending law. +- The exported bending law can carry a slip scaling variable: `export_bending_law(..., + slip_scale=True)` adds `BendingLawExport.slip_scale`, a `SlipScaleTable` with the law at a + reference tension split into friction groups (one per armour layer, `laid_cores` for the core + lay stage) and each group's scale `ρ_g = R_g/R_g,ref` of its full-slip friction moment over a + table of tensions and, optionally, external pressures (`slip_scale_tensions_N`, + `slip_scale_external_pressure_Pa`), with the single cap-weighted scale `s` and the derivatives + `∂/∂T` and `∂/∂p_e`. The friction bounds of the direction-tied law are proportional to `P1+P2` + at fixed stick stiffness, so a group's law at another state is the reference law with fixed + element stiffnesses and yield curvatures times `ρ_g`, and under a changing state every element + follows the return map with the new cap (`SlipScaleTable.moment`, `.law_at`, + `.dissipated_energy`). New validation row MX-scale: the section law is homogeneous in the + bound (4e-16), the group yield curvatures scale exactly (8e-14), and a tension cycle inside the + bending cycles adds nothing to the fixed-tension residual of the Iwan law (ratio 1.02; with + symmetric wire bounds the scaled law is the contact-tension history of `compute_mkappa` to + 1e-14). One scale for all groups is exact when they scale alike (66 kV template, tension) and + misses the per-group law by up to 0.3 % (33 kV three-core), 12 % (Ménard) and 21 % (66 kV with + external pressure). The JSON law with a slip scale is format `cablexsec.bending_law/2` (a new + `slip_scale` object; version-1 fields unchanged); `SlipScaleTable.to_csv` writes the table. + Torque is not a table variable, and the internal-ring slip of resolved strands is refused. + Project files written before `BendingLawExport.slip_scale` existed still load: the project + codec accepts a missing field that has a default. `export_bending_law` refuses + `contact_pressure_Pa` and `contact_tension_history_N` as options. ### Fixed +- The exported bending law no longer claims to follow `compute_mkappa` exactly. With the signed + capstan bound the slip interval of a wire is asymmetric (the falling bound is the rising one + times `exp(−λψ)`), which no Masing element carries; the Iwan law misses the section law's loops + by about 0.1 % of the moment range on bending cycles near full slip (0.08–0.26 % on the 66 kV, + Ménard and 33 kV three-core templates), and by 0.02 % at μ = 0.02. The provenance of + `export_bending_law` and `cabledyn_bending_law`, the module notes and the global–local guide + say so; the law itself is unchanged. - The frictional heat of `compute_thermal_fatigue` (`frictional_heat_W_m`, `pi2` and `friction_temperature_rise_K` of every block) is now the dissipation of the distributed helix friction law, whatever friction law the fatigue uses. It was the work of the diff --git a/VALIDATION.md b/VALIDATION.md index 084b3fd..de4c69a 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -41,6 +41,7 @@ afterwards: a comparison that misses its target is reported as failed. | **σ_B** | Radial-fibre bending stress | Ménard and Cartraud (2023), Eq. 14 | 0 | <1e-6 % | Pass | | **M-rec, M-rec-3core** | Assembled per-wire moment against the section engine | cross-engine | 0.000 % | <2 % | Pass | | **MK-Tcyc** | Moment–curvature law with tension cycling inside the bending cycles; work balance under the changing friction bound | fatigue-path friction stress, same kernels | 3.4e-16; 1.1e-15 | <1e-12 | Pass | +| **MX-scale** | Exported bending law with a slip scaling variable: bound homogeneity, scaled group yield curvatures, tension cycle inside the bending cycles | `compute_mkappa` at another tension; contact-tension history | 4.1e-16; 8.3e-14; ratio 1.02 | <1e-12; <1e-12; ≤1.25 | Pass | | **slip-onset** | First wire to slip lies at the neutral axis (compression side, ψ ≈ 3λ/2) | Raoof; Papailiou | \|cos\| = 0.156 | \|cos\| < 0.2 | Pass | | **xsec-K** | Coupling tangent bounds | EI_max, EI_min limits | ≤6.3e-13 % | <0.01 % | Pass | | **QP-KKT, QP-Lamé** | Concentric contact complementarity; shrink-fit compliances | KKT conditions; compound cylinder | 1.9e-13 N; 1.3e-16 | <1e-8 N; <1e-6 | Pass | diff --git a/doc/benchmarks.md b/doc/benchmarks.md index 42c16a1..4b32931 100644 --- a/doc/benchmarks.md +++ b/doc/benchmarks.md @@ -104,7 +104,7 @@ model) is the full construction. | Along-wire redistribution (gap T2): periodic and clamp-layer limits, termination round-off, energy, refinement | A, I | PASS | | Gap T2 against Sævik (2011), Gjøsteen et al. (2027), Hu, Ménard and Witz | M | Not explained (former capstan bound throughout): Sævik near-bellmouth median ratio 3.36 (2.12 in the clamp convention) against 1.65 for the clamp correction and 1.03 sectional; Hu area +65%, share 11%; Ménard work −3 to +3 points by range; end conditions immaterial | | Two-way anchored termination: Sævik rig beam solved with the anchored along-wire chains of both armours | M | FAIL as registered (former capstan bound): median ratio 1.18 (9 of 14 in band), absolute 1.46; anchored over-prediction falls from 3.09 one-way (same stick setting) and 1.65 (clamp correction); curvature redistributes along the bellmouth instead of falling (TC-3 fails); hang-off rule stays sectional | -| Hysteretic bending law for global analysis (gap MX): Iwan law from the exported backbone against `compute_mkappa` | I | MX-1 PASS (≤ 0.05 % of the moment range, work ≤ 0.02 %), MX-3 PASS; MX-2 FAIL (tension interpolation 3.9 % at 100 kN spacing; 0.27 % at 20 kN); MX-5 (global program) open | +| Hysteretic bending law for global analysis (gap MX): Iwan law from the exported backbone against `compute_mkappa` | I | MX-1 PASS (≤ 0.05 % of the moment range, work ≤ 0.02 %), MX-3 PASS, MX-scale PASS (slip scaling variable); MX-2 FAIL (tension interpolation 3.9 % at 100 kN spacing; 0.27 % at 20 kN); MX-5 (global program) open | | Cable over a sheave (gap SH): Feyrer (2015) Examples 3.2 and 3.4, groove factors, consistency with the section analyses | A, I | SH-1, SH-2, SH-3 PASS; no measured cable-over-sheave data held | | Gap T1, benchmarks in their published arrangements | M | Hu three-point: transition share in its band (32.8–39.4% against 33.8%), loop area FAIL (+37% Papailiou cap, +64% Karlsen-Husøy; +4.9%/+28% at uniform curvature compared a different quantity); Ménard four-point unchanged; Witz arrangement not documented, basis unchanged | | Torque balance (gap 3.5): Feyrer (2015) and Knapp (1981) closed forms, mirror lay, `xsec_stiffness` consistency | A, I | PASS | @@ -137,6 +137,7 @@ All rows are verification, not validation. Source: the scorecard | M-rec | I | Assembled per-wire moment vs `compute_mkappa`, single core | < 2% | 0.000% | PASS | | M-rec-3core | I | As M-rec, offset-core geometry | < 2% | 0.000% | PASS | | MK-Tcyc | I | `compute_mkappa` with a contact-tension history cycling inside the bending cycles vs the moment of the fatigue-path friction stress on the same history; work-balance residual over the friction work | < 1e-12 rel.; < 1e-12 rel. | 3.4e-16; 1.1e-15 | PASS | +| MX-scale | I | Slip-scaled bending law: `compute_mkappa` at 70 kN vs the 20 kN law with the bound scaled (66 kV, cores); group elements at 60 kN vs the 10 kN elements with yield curvatures scaled (Ménard); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 rel.; < 1e-12 rel.; ratio ≤ 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | | slip-onset | A | First wire to slip lies at the neutral axis (with the signed bound on the compression side, ψ ≈ 3λ/2) | abs(cos) < 0.2 | 0.156 (0.000 with the former bound) | PASS | | xsec-K | A | Tangent bounds EI_max (κ→0) and EI_min (κ→∞) | < 0.01% | 0; 7.4e-12% | PASS | | QP-KKT | A | Concentric contact complementarity | < 1e-8 N | 1.9e-13 N | PASS | @@ -659,10 +660,16 @@ guide [global_local_guide.md](global_local_guide.md), Section 8. | MX-3 | I | Stick tangent, full-slip slope and virgin backbone of the decomposition | 1e-16 to 2e-14 | PASS | | MX-4 | I | Progressive law, Ménard at 50 kN | ≤ 0.06 % of the range, work ≤ 0.02 % | reported | | MX-5 | MM | Hysteretic bending of a global program with the exported table | not run | open | - -The law is exact for planar bending at fixed contact pressure because the armour laws are parallel spring–sliders; -the only approximations are the backbone discretisation and the interpolation in tension. Biaxial bending is -outside it (per-wire, direction-tied response in CableXSec). +| MX-scale | I | Slip scaling variable (`slip_scale=True`): bound homogeneity of `compute_mkappa` (66 kV, 20 → 70 kN, cores); group elements at 60 kN against the 10 kN elements with yield curvatures times `ρ_g` (Ménard); tension cycle 10–70 kN inside ±0.03 1/m bending, scaled law against the contact-tension history over the fixed-tension residual | 4.1e-16; 8.3e-14; 1.02 (symmetric wire bounds on a breakpoint grid: 8e-15, work 7e-15) | PASS | +| MX-scale-1 | I | One scale for all groups against the per-group law, 10–150 kN (reference 10 kN), backbone and cycles to 1.5 times full slip | 66 kV 0; 33 kV three-core 0.10 % (0.29 % with cores); Ménard 12 %; with p_e 0–2 MPa: 66 kV 21 %, 33 kV 12 %, Ménard 19 % | reported | + +The armour laws are parallel spring–sliders at fixed contact pressure, so the Iwan law follows Masing's rules; it is +exact when every wire's slip interval is symmetric. The signed capstan bound makes the interval asymmetric (the +falling bound is the rising one times `exp(−λψ)`), and the MX-1 residual comes from that besides the backbone +discretisation (bending at ±0.03 1/m on the Ménard cable: 0.14 % of the range at 10 kN with 300 points, 0.02 % with +symmetric bounds). The interpolation in tension is the other approximation; the slip scale replaces it with the +exact scaling of the friction caps (MX-scale; guide Section 8.1). Biaxial bending is outside it (per-wire, +direction-tied response in CableXSec). ## Cable over a sheave (gap SH) diff --git a/doc/concepts.md b/doc/concepts.md index 79d6d08..4966009 100644 --- a/doc/concepts.md +++ b/doc/concepts.md @@ -272,9 +272,14 @@ moment–curvature curve at a set of tensions and decomposes it into parallel elastic–perfectly-plastic elements, an Iwan model. For planar bending at fixed contact pressure the armour law is itself a set of parallel spring–sliders, so the exported law follows Masing's rules and reproduces `compute_mkappa`, -memory of earlier reversals included. The law is planar, and tension and -annulus state are fixed within one law. Export tension levels no more than -about 20 kN apart (Section 8 of the global–local guide). +memory of earlier reversals included, to about 0.1 % of the moment range (the +asymmetric slip interval of the signed capstan bound). The law is planar, and +tension and annulus state are fixed within one law. Export tension levels no +more than about 20 kN apart, or export the slip scale (`slip_scale=True`): +tension and external pressure scale the friction caps of each armour layer and +of the cores, not their stiffness, so one law with scaled yield curvatures +covers the table and its sliders follow a changing tension (Section 8 of the +global–local guide). ## Every result says where it came from diff --git a/doc/file_formats.md b/doc/file_formats.md index db59fa1..6939f72 100644 --- a/doc/file_formats.md +++ b/doc/file_formats.md @@ -18,7 +18,7 @@ and the rules it is checked against. | CableDyn 0.4.0 station table | `cablexsec.io.read_cabledyn_station_table` | CableDyn | CSV, tab or whitespace | | Sea-state batch specification | `cablexsec-batch`, `load_batch_spec` | (by hand) | JSON | | Project | `Project.load` | `Project.save` | JSON | -| Hysteretic bending law | — | `BendingLawExport.to_csv`, `.to_json` | CSV, JSON | +| Hysteretic bending law | — | `BendingLawExport.to_csv`, `.to_json`, `SlipScaleTable.to_csv` | CSV, JSON | ## Every file follows three rules @@ -556,7 +556,8 @@ objects and the stale-result checks. The first column is the curvature [1/m]; each further column is the moment [N m] at the tension named in its heading (`M_N_Nm`). -- `to_json(path)`: an object with `format` (`cablexsec.bending_law/1`), +- `to_json(path)`: an object with `format` (`cablexsec.bending_law/1`; `/2` + with a slip scale, below), `hysteresis_rule` (`masing_iwan`), `planar_only`, `tension_N`, `kappa_1_m`, `moment_Nm` (one backbone per tension), `ei_slip_Nm2` (the full-slip stiffness per tension), `elements` (the stiffness and yield curvature of the @@ -570,6 +571,47 @@ The law is planar and its contact state is fixed at each tension. Between tensions it is interpolated linearly, as Section 8 of the [global–local guide](global_local_guide.md) explains. +### Slip scale (format version 2) + +`export_bending_law(..., slip_scale=True)` adds the slip scaling variable +(`BendingLawExport.slip_scale`, a `SlipScaleTable`; guide Section 8.1). The +JSON law then has `format` `cablexsec.bending_law/2` and one more object, +`slip_scale`; every version-1 field is unchanged, and a law without a slip +scale is still written as version 1, byte for byte as before. The object holds: + +| Key | Content | +| --- | --- | +| `rule` | `yield_curvature_scaling` | +| `variables` | `["tension_N"]`, or `["tension_N", "external_pressure_Pa"]` with a pressure axis | +| `reference_tension_N`, `reference_external_pressure_Pa` | state of the reference law | +| `tension_N`, `external_pressure_Pa` | table axes (`external_pressure_Pa` is `null` without a pressure axis) | +| `ei_slip_Nm2` | full-slip stiffness [N m²] | +| `reference_elements` | `stiffness_Nm2`, `yield_curvature_1_m` of all groups merged at the reference | +| `scale` | single scale `s`, one row per tension, one column per pressure (one column without a pressure axis) | +| `dscale_dtension_1_per_N` | `∂s/∂T` [1/N], same shape | +| `dscale_dexternal_pressure_1_per_Pa` | `∂s/∂p_e` [1/Pa], same shape (pressure axis only) | +| `groups` | one object per friction group: `name` (the armour layer, or `laid_cores`), `kind` (`armour_layer` or `laid_cores`), `reference_cap_Nm`, the group's `stiffness_Nm2` and reference `yield_curvature_1_m`, its `scale` `ρ_g` and the derivatives `dscale_dtension_1_per_N` and `dscale_dexternal_pressure_1_per_Pa` | + +At a state with group scales `ρ_g` the law is `M = ei_slip_Nm2 κ + Σ k_i e_i` +over all group elements, with every element of group `g` updated by +`e_i ← clip(e_i + Δκ, −ρ_g κ_y,i, ρ_g κ_y,i)` (the return map with the cap of +the current state). A reader that carries one scale uses `reference_elements` +and `scale` in place of `ρ_g`; that is exact only when the groups scale alike +(guide Section 8.1). The table is interpolated linearly in tension and +pressure; the derivatives are those of the contact model at the table states. + +`SlipScaleTable.to_csv(path)` writes the table as CSV, one row per state +(tension, then pressure): + +```text +tension_N,external_pressure_Pa,s,ds_dT_1_per_N,s_inner_armour,ds_dT_inner_armour_1_per_N,s_outer_armour,ds_dT_outer_armour_1_per_N +2.000000000e+04,0.000000000e+00,1.000000000e+00,5.000000000e-05,... +``` + +With a pressure axis the columns `ds_dpe_1_per_Pa` and +`ds_dpe__1_per_Pa` follow each `ds_dT` column. `Project` files store the +table with the law; project files written before it existed still load. + `cablexsec.io.global_export` also writes the section properties of a set of load cases as neutral CSV tables (`section_properties_csv`, `bending_tables_csv`), each preceded by comment lines starting with `# ` that diff --git a/doc/global_local_guide.md b/doc/global_local_guide.md index 46de18e..cece7d6 100644 --- a/doc/global_local_guide.md +++ b/doc/global_local_guide.md @@ -372,8 +372,12 @@ Two findings shape stage 2: set of tensions it computes the virgin moment–curvature backbone with `compute_mkappa` and decomposes it into parallel elastic, perfectly plastic elements (an Iwan model, Iwan 1966) plus the full-slip stiffness. For planar bending at fixed contact pressure the default and the progressive armour laws are themselves sets of parallel -spring–sliders, so the Iwan law follows Masing's rules exactly and reproduces `compute_mkappa` on any planar -history, including the memory of earlier reversals. +spring–sliders, so the Iwan law follows Masing's rules and reproduces `compute_mkappa` on planar histories, +including the memory of earlier reversals. It is exact when every wire's slip interval is symmetric. The signed +capstan bound (Papailiou 1997) makes it asymmetric: the falling bound of a wire is its rising bound times +`exp(-λψ)`, which no Masing element carries. The residual is about 0.1 % of the moment range on bending cycles +near full slip (Ménard ±0.03 1/m: 0.14 % at 10 kN, 0.16 % at 70 kN; 66 kV template 0.08–0.11 %; 33 kV +three-core 0.26 %) and falls with the friction coefficient (66 kV at μ = 0.02: 0.02 %). ```python import numpy as np @@ -395,12 +399,85 @@ reproduces `compute_mkappa` within 0.05 % of the moment range and the work withi an irregular history, for the Ménard cable at 0 and 50 kN and the 66 kV template at 50 kN; the decomposition identities hold to round-off. Interpolation in tension is the limiting step: between levels 100 kN apart the backbone at the midpoint is missed by 3.9 % of the moment range (Ménard; registered target FAIL), 1.5 % at 50 kN, -0.27 % at 20 kN and 0.07 % at 10 kN. Export tension levels no more than about 20 kN apart. +0.27 % at 20 kN and 0.07 % at 10 kN. Export tension levels no more than about 20 kN apart, or use the slip scale +below. + +### 8.1 Slip scaling variable + +The tension and the external pressure change the armour contact pressure `P1+P2`, not the stick stiffness +`k_f = ξ E cos²α`. In the direction-tied law every wire is a spring–slider whose friction bounds are proportional to +its layer's `P1+P2`, and the return map `f ← clip(f + k Δd, −ρ l, ρ u)` is positively homogeneous. A layer whose +bounds scale by `ρ` therefore obeys `M(κ; ρ) = ρ M(κ/ρ; 1)` over any curvature history, loops and the asymmetric +capstan bound included, and its Iwan elements keep their stiffnesses `k_i` while their yield curvatures become +`ρ κ_y,i`. With `slip_scale=True` the export carries this form as `BendingLawExport.slip_scale`, a `SlipScaleTable`: + +- the law at a reference tension split into friction groups, one per structural armour layer and `laid_cores` for + the core lay stage, each with its elements (`k_i`, `κ_y,i`), plus the full-slip stiffness `EI_slip`; +- the cap `R_g` of every group (its planar full-slip friction moment) over a table of tensions and, optionally, + external pressures, the group scale `ρ_g = R_g / R_g,ref`, the single cap-weighted scale + `s = Σ R_g / Σ R_g,ref`, and their derivatives `∂/∂T` and `∂/∂p_e` (central differences of the contact model, + one-sided at zero; the bounded chain is affine, so they are its slopes). + +```python +export = cx.export_bending_law( + cable, tensions_N=[10e3, 70e3], kappa_max_1_m=0.036, n_points=300, + slip_scale=True, slip_scale_tensions_N=np.linspace(10e3, 70e3, 7), + slip_scale_external_pressure_Pa=[0.0, 1e6, 2e6], # optional pressure axis +) +table = export.slip_scale +law = table.law_at(35e3, 0.5e6) # scaled law at one state +moment = table.moment(kappa, tension, pressure) # sliders follow the changing caps +table.to_csv("slip_scale.csv") # s, rho_g and derivatives per state +``` + +Slider update. When the state changes, every element follows the return map with the new cap, +`e_i ← clip(e_i + Δκ, −ρ_g κ_y,i, ρ_g κ_y,i)` and `M = EI_slip κ + Σ k_i e_i`: the slip state is carried across, a +falling cap clips a sticking or slipping element at fixed curvature (friction work, `k_i |e_1| |e_0 − e_1|` in the +backward-Euler form the section law reports) and a rising cap leaves it where it is. This is the rule the fatigue +kernels and `compute_mkappa(..., contact_tension_history_N=...)` apply to every wire. + +Checks (`tests/test_bending_law_slip_scale.py`; row MX-scale of the [benchmark register](benchmarks.md)): + +- `compute_mkappa` at 70 kN equals the 20 kN law with the bound scaled, `EI κ + ρ F(κ/ρ)`, over a loop history on + the 66 kV template (no manufacturing clamping, so both layers and the cores scale by `T`): 4e-16 of the moment. +- Every group law decomposed at 60 kN on the grid `ρ_g κ` is the 10 kN group law with fixed `k_i` and yield + curvatures times `ρ_g` (Ménard, layers scaling by 2.06 and 1.40; 33 kV three-core with its cores): below 1e-13. +- With symmetric wire bounds and a grid through every wire's slip curvature, the scaled law under a tension cycle + (10–70 kN) inside bending cycles is the contact-tension history of `compute_mkappa`, moment and friction work, + to 1e-14. With the signed bound the scaled law misses the history route by at most 1.02 times the + fixed-tension residual above (Ménard 0.17 %, 66 kV 0.11 %); the law frozen at the reference misses by 19 % and + 43 %. + +One scale or one per group. The single scale `s` keeps the stick stiffness and the full-slip moment exact and is +exact when every group scales alike. Otherwise it misplaces the transition. Largest error of the single-scale law +against the per-group law over 10–150 kN, reference 10 kN, on the virgin backbone and on cycles up to 1.5 times the +full-slip curvature (moment in % of the range; work per cycle at 1.5 times full slip): + +| Template | Tension only | Tension and p_e 0–2 MPa | +| --- | --- | --- | +| 66 kV IEA Task 49 | 0 (both layers ∝ T) | 21 %; work 32 % | +| 66 kV with cores | 0 (cores ∝ T too) | not run | +| 33 kV three-core | 0.10 %; work 0.14 % | 12 %; work 16 % | +| 33 kV three-core with cores | 0.29 %; work 0.36 % | not run | +| Ménard | 12 %; work 11 % | 19 %; work 19 % | + +The external pressure adds the same `P1+P2` to layers whose tension parts differ (on the 66 kV template, with no +clamping, `ρ` is 467 for the inner and 1 735 for the outer layer at 10 kN and 2 MPa), so a pressure axis needs the +per-group scales. A group of scale `ρ` reproduces its law at the state up to `ρ κ_max`; beyond, the full-slip slope +continues, as in every exported law. The default reference is the smallest exported tension at which every group +has contact, so caps that rise with tension give `ρ ≥ 1`. + +Limits of the scale. The laid-core group scales with its own contact load; it is exact while the load-weighted +friction coefficient of its contacts is unchanged (one contact type, or equal coefficients, as by default). The +internal-ring slip of resolved strands (`strand_layers`) has no cap scaling and is refused. Torque is not a table +variable: the section states that carry a torque (the coupled qp and solved models with a free twist) differ at +zero torque from the fixed-twist states of the backbones, and a torque moves the `P1+P2` of contra-wound layers in +opposite senses. The stick stiffness and `EI_slip` are those of the reference state; at a different temperature the +moduli change, which the scale does not represent. Limits. The law is planar. CableXSec's biaxial response is per wire and tied to the current bending direction; a global solver that applies an isotropic hysteretic law to the resultant curvature makes an assumption the section -model does not. Tension and annulus state are fixed within one law; the section law itself can follow a tension -history within a bending cycle (`compute_mkappa(..., contact_tension_history_N=...)`), but the exported law has no -rule yet for its slider states when the tension changes. Whether a global program's hysteretic bending option -applies Masing's rules to the exported table is target MX-5, open until checked; CableDyn does not yet have a -bending-law interface (its stage 2, Section 7). +model does not. Tension and annulus state are fixed within one law of the tension table; the slip scale (Section +8.1) carries the change of the friction caps with tension and external pressure. Whether a global program's +hysteretic bending option applies Masing's rules to the exported table is target MX-5, open until checked; CableDyn +does not yet have a bending-law interface (its stage 2, Section 7). diff --git a/doc/project_guide.md b/doc/project_guide.md index a09da00..aa4cd23 100644 --- a/doc/project_guide.md +++ b/doc/project_guide.md @@ -132,7 +132,7 @@ the installed registries, and new runs use the installed library. | `capacity` | `CapacitySettings` (tension sweep) | no | `CapacityResult` | | `coiling` | `CoilingSettings` (static tank) | no | `CoilingResult` | | `conductor_fatigue` | `ConductorFatigueSettings` (curvatures, true tension) | yes | `ConductorFatigueResult` | -| `bending_law` | `BendingLawSettings` (export for global analysis) | no | `BendingLawExport` | +| `bending_law` | `BendingLawSettings` (export for global analysis, optional slip scale) | no | `BendingLawExport` | ## Preflight report diff --git a/src/cablexsec/__init__.py b/src/cablexsec/__init__.py index 5c6540a..16179cd 100644 --- a/src/cablexsec/__init__.py +++ b/src/cablexsec/__init__.py @@ -52,6 +52,7 @@ from cablexsec.analysis.bending_law import ( BendingLawExport, IwanBendingLaw, + SlipScaleTable, export_bending_law, ) from cablexsec.analysis.capacity_check import ( @@ -327,6 +328,7 @@ __all__ = [ "BendingLawExport", "IwanBendingLaw", + "SlipScaleTable", "export_bending_law", "LayerSlipCurvatures", "armour_slip_curvatures", diff --git a/src/cablexsec/_project_codec.py b/src/cablexsec/_project_codec.py index cb85892..3b3036c 100644 --- a/src/cablexsec/_project_codec.py +++ b/src/cablexsec/_project_codec.py @@ -8,13 +8,17 @@ import math import types from collections.abc import Mapping -from dataclasses import fields, is_dataclass +from dataclasses import MISSING, fields, is_dataclass from functools import cache from typing import Any, Literal, Union, get_args, get_origin, get_type_hints import numpy as np -from cablexsec.analysis.bending_law import BendingLawExport, IwanBendingLaw +from cablexsec.analysis.bending_law import ( + BendingLawExport, + IwanBendingLaw, + SlipScaleTable, +) from cablexsec.analysis.capacity import CapacityResult from cablexsec.analysis.coiling import CoilingLayerResult, CoilingResult from cablexsec.analysis.conductor_fatigue import ConductorFatigueResult @@ -64,6 +68,7 @@ StrandSlipParameters, BendingLawExport, IwanBendingLaw, + SlipScaleTable, ) } @@ -182,14 +187,26 @@ def unpack(value: Any) -> Any: if keys == {"type", "fields"} and isinstance(value["type"], str): cls = _TYPES.get(value["type"]) payload = value["fields"] + # A field added later with a default may be absent from files written + # before it existed; every other field must be present. + names = {f.name for f in fields(cls)} if cls is not None else set() + required = ( + { + f.name + for f in fields(cls) + if f.default is MISSING and f.default_factory is MISSING + } + if cls is not None + else set() + ) if ( cls is not None and isinstance(payload, dict) - and set(payload) == {f.name for f in fields(cls)} + and required <= set(payload) <= names ): decoded = {k: unpack(v) for k, v in payload.items()} for name, annotation in _annotations(cls).items(): - if not _matches(decoded[name], annotation): + if name in decoded and not _matches(decoded[name], annotation): raise CableInputError( f"invalid project field {cls.__name__}.{name}" ) diff --git a/src/cablexsec/analysis/bending_law.py b/src/cablexsec/analysis/bending_law.py index 32cfdd1..5ab8f2f 100644 --- a/src/cablexsec/analysis/bending_law.py +++ b/src/cablexsec/analysis/bending_law.py @@ -3,9 +3,14 @@ r"""Hysteretic bending law of a cable section for global analysis (gap MX). In planar bending at fixed contact pressure the default armour law gives every -wire an elastic, perfectly plastic spring--slider with a fixed cap, in parallel -with the elastic full-slip stiffness. The section law is then an Iwan parallel -model, which obeys Masing's rules exactly ([Iwan1966]). A piecewise-linear +wire an elastic, perfectly plastic spring--slider with a fixed slip interval, +in parallel with the elastic full-slip stiffness. With symmetric intervals the +section law is an Iwan parallel model, which obeys Masing's rules exactly +([Iwan1966]). The signed capstan bound of [Papailiou1997] makes the interval +of a wire asymmetric (its falling bound is the rising one times +``exp(-lam psi)``), so an Iwan law fitted to the virgin backbone misses the +section law's loops by a residual (about 0.1 % of the moment range on +bending cycles near full slip; global--local guide, Section 8). A piecewise-linear virgin backbone ``M(kappa)`` with non-increasing tangent decomposes uniquely into parallel elastic, perfectly plastic elements: @@ -32,10 +37,48 @@ exported law to the resultant curvature uses an assumption the section model does not make. Tension and annulus state are held fixed within one law. +Slip scaling variable +--------------------- +With ``slip_scale=True`` the export also carries a :class:`SlipScaleTable`: +the law at a reference state split into friction groups (one per structural +armour layer and one for the laid-core stage), and the scale of every group +over a table of tensions and, optionally, external pressures. In the +direction-tied law every wire of a group is a spring--slider of fixed +stiffness ``k_f = xi E cos^2 a`` whose friction bounds are proportional to +the group's friction-setting pressure ``P1+P2`` (``sigma_0`` of +:func:`~cablexsec.mechanics.papailiou.wire_slip_stress_bounds`; for the +laid cores, to their contact line load while its load-weighted friction +coefficient is unchanged). The return map +``f <- clip(f + k d, -rho l, rho u)`` is positively homogeneous, so a group +whose bounds scale by ``rho`` obeys + +.. math:: + + M_g(\kappa; \rho) = \rho\, M_g(\kappa/\rho; 1) + +over any curvature history, and its Iwan elements keep their stiffnesses +while their yield curvatures scale: ``rho sum k_i clip(kappa/rho, ..., +kappa_y,i) = sum k_i clip(kappa, ..., rho kappa_y,i)``. The group scale is +``rho_g = R_g / R_g,ref`` with ``R_g`` the group's planar full-slip friction +moment (its cap). For a changing scale every element follows the return map +with the new cap, the rule the fatigue kernels apply to every wire: + +.. math:: + + e_i \leftarrow \operatorname{clip}(e_i + \Delta\kappa, -\rho_g \kappa_{y,i}, + \rho_g \kappa_{y,i}), \qquad M = EI_{slip}\,\kappa + \sum_i k_i e_i . + +The single scale ``s = sum_g R_g / sum_g R_g,ref`` (cap-weighted) is exact +when every group scales alike; otherwise it keeps the stick stiffness and the +full-slip moment exact and misplaces the transition (quantified in the +global--local guide, Section 8). + References ---------- [Iwan1966] W.D. Iwan, A distributed-element model for hysteresis and its steady-state dynamic response, J. Appl. Mech. 33 (1966) 893-900. +[Papailiou1997] Eqs. (9)-(15) (the signed capstan bound; +:mod:`cablexsec.mechanics.papailiou`). """ from __future__ import annotations @@ -51,14 +94,18 @@ from numpy.typing import ArrayLike, NDArray from cablexsec.exceptions import CableInputError +from cablexsec.mechanics.papailiou import wire_slip_stress_bounds from cablexsec.provenance import Provenance if TYPE_CHECKING: from cablexsec.cables.schema import CableData + from cablexsec.mechanics.mkappa import HelicalLayerSpec __all__ = [ + "CORE_GROUP", "BendingLawExport", "IwanBendingLaw", + "SlipScaleTable", "export_bending_law", ] @@ -68,6 +115,12 @@ #: section law); larger rises are rejected as a non-Masing backbone. _TANGENT_RISE_TOLERANCE = 1e-6 +#: Name of the friction group of the laid-core stage in a :class:`SlipScaleTable`. +CORE_GROUP = "laid_cores" + +#: Relative step of the central differences of the group caps. +_DIFFERENCE_STEP = 1e-4 + @dataclass(frozen=True) class IwanBendingLaw: @@ -144,6 +197,13 @@ def from_backbone( "backbone tangent rises: the section law is not of Masing type here" ) tangent = np.minimum.accumulate(tangent) + # A full-slip plateau of a friction-only backbone (ei_slip_Nm2 = 0) + # may fall below zero by rounding; such noise is zero. + tangent = np.where( + (tangent < 0.0) & (tangent > -_TANGENT_RISE_TOLERANCE * scale), + 0.0, + tangent, + ) if not (math.isfinite(ei_slip_Nm2) and ei_slip_Nm2 >= 0): raise CableInputError("ei_slip_Nm2 must be finite and >= 0") tail = min(float(ei_slip_Nm2), float(tangent[-1])) @@ -195,9 +255,454 @@ def dissipated_energy(self, kappa_history: ArrayLike) -> float: return work +def _ratio(values: FloatArray, reference: float) -> FloatArray: + return np.asarray(values / reference, dtype=np.float64) + + +def _bracket( + grid: FloatArray, values: FloatArray, label: str +) -> tuple[NDArray[np.intp], NDArray[np.intp], FloatArray]: + """Lower and upper grid index and weight of every value (linear).""" + if not np.isfinite(values).all(): + raise CableInputError(f"{label} must be finite") + if np.any(values < grid[0]) or np.any(values > grid[-1]): + raise CableInputError( + f"{label} outside the table range {grid[0]:g}-{grid[-1]:g}" + ) + if grid.size == 1: + zero = np.zeros(values.shape, dtype=np.intp) + return zero, zero, np.zeros(values.shape) + lower = np.clip(np.searchsorted(grid, values) - 1, 0, grid.size - 2) + weight = (values - grid[lower]) / (grid[lower + 1] - grid[lower]) + return lower, lower + 1, weight + + +@dataclass(frozen=True) +class SlipScaleTable: + r"""Slip scaling variable of an exported law over tension and pressure. + + The law at the reference state is split into friction groups: one per + structural armour layer (named after it) and :data:`CORE_GROUP` for the + laid-core stage. ``group_laws[g]`` holds the group's elements (fixed + stiffness ``k_i``, reference yield curvature ``kappa_y,i``; no elastic + part), ``ei_slip_Nm2`` the elastic full-slip stiffness. At a state with + group caps ``R_g`` the law is the reference law with the yield curvatures + of group ``g`` multiplied by ``rho_g = R_g / R_g,ref``; with one scale for + all groups it is ``s = sum_g R_g / sum_g R_g,ref``. + + A changing state moves the caps, not the stiffnesses. Each element then + follows the return map with the new cap, + ``e_i <- clip(e_i + d kappa, -rho kappa_y,i, rho kappa_y,i)``: its slip + state is carried across, a falling cap clips the element at fixed + curvature (friction work) and a rising cap leaves a sticking element + unchanged (:meth:`moment`). + + The group laws come from backbones on the export's curvature grid, so a + group of scale ``rho`` reproduces its law at the state up to + ``rho kappa_max``; beyond, the full-slip slope continues. The state is + interpolated linearly in the table (bilinearly with a pressure axis). + + Attributes + ---------- + reference_tension_N, reference_external_pressure_Pa : float + State of the reference law. + tension_N : numpy.ndarray + Table tensions [N], strictly ascending. + external_pressure_Pa : numpy.ndarray or None + Table external pressures [Pa], strictly ascending; ``None`` when the + table runs over tension only (at the reference external pressure). + group_names : tuple of str + Armour layer names, then :data:`CORE_GROUP` when the cores slip. + group_laws : tuple of IwanBendingLaw + Elements of every group at the reference state (``ei_slip_Nm2`` 0). + ei_slip_Nm2 : float + Full-slip (elastic) stiffness [N m^2], independent of the state. + reference_cap_Nm : numpy.ndarray + Full-slip friction moment ``R_g`` of every group at the reference [N m]. + group_cap_Nm : numpy.ndarray + ``R_g`` at every table state, shape (groups, tensions, pressures) [N m]; + one pressure column without a pressure axis. + group_cap_dT_Nm_per_N : numpy.ndarray + ``dR_g/dT`` [N m/N], same shape (central differences of the contact + model, one-sided at zero tension). + group_cap_dpe_Nm_per_Pa : numpy.ndarray or None + ``dR_g/dp_e`` [N m/Pa], same shape; ``None`` without a pressure axis. + """ + + reference_tension_N: float + reference_external_pressure_Pa: float + tension_N: FloatArray + external_pressure_Pa: FloatArray | None + group_names: tuple[str, ...] + group_laws: tuple[IwanBendingLaw, ...] + ei_slip_Nm2: float + reference_cap_Nm: FloatArray + group_cap_Nm: FloatArray + group_cap_dT_Nm_per_N: FloatArray + group_cap_dpe_Nm_per_Pa: FloatArray | None = None + + def __post_init__(self) -> None: + t = np.asarray(self.tension_N, dtype=np.float64) + p = ( + None + if self.external_pressure_Pa is None + else np.asarray(self.external_pressure_Pa, dtype=np.float64) + ) + for grid, label in ((t, "tension_N"), (p, "external_pressure_Pa")): + if grid is None: + continue + if ( + grid.ndim != 1 + or grid.size < 1 + or not np.isfinite(grid).all() + or np.any(grid < 0.0) + or np.any(np.diff(grid) <= 0.0) + ): + raise CableInputError( + f"{label} of a slip-scale table must be finite, non-negative " + "and strictly ascending" + ) + n_groups = len(self.group_names) + if n_groups < 1 or len(self.group_laws) != n_groups: + raise CableInputError("one law per friction group is required") + if len(set(self.group_names)) != n_groups: + raise CableInputError("friction group names must be distinct") + reference = np.asarray(self.reference_cap_Nm, dtype=np.float64) + if ( + reference.shape != (n_groups,) + or not np.isfinite(reference).all() + or np.any(reference <= 0.0) + ): + raise CableInputError( + "every friction group needs a finite, positive reference cap" + ) + shape = (n_groups, t.size, 1 if p is None else p.size) + cap = np.asarray(self.group_cap_Nm, dtype=np.float64) + d_t = np.asarray(self.group_cap_dT_Nm_per_N, dtype=np.float64) + if cap.shape != shape or d_t.shape != shape: + raise CableInputError(f"group caps and derivatives need shape {shape}") + if not (np.isfinite(cap).all() and np.isfinite(d_t).all()): + raise CableInputError("group caps and derivatives must be finite") + if np.any(cap < 0.0): + raise CableInputError("group caps must be non-negative") + d_p = None + if p is None: + if self.group_cap_dpe_Nm_per_Pa is not None: + raise CableInputError( + "a pressure derivative needs an external-pressure axis" + ) + else: + if self.group_cap_dpe_Nm_per_Pa is None: + raise CableInputError( + "an external-pressure axis needs the pressure derivative" + ) + d_p = np.asarray(self.group_cap_dpe_Nm_per_Pa, dtype=np.float64) + if d_p.shape != shape or not np.isfinite(d_p).all(): + raise CableInputError( + f"the pressure derivative must be finite with shape {shape}" + ) + values = [self.reference_tension_N, self.reference_external_pressure_Pa] + if not np.isfinite(values).all() or min(values) < 0.0: + raise CableInputError("the reference state must be finite and >= 0") + if not (math.isfinite(self.ei_slip_Nm2) and self.ei_slip_Nm2 >= 0.0): + raise CableInputError("ei_slip_Nm2 must be finite and >= 0") + object.__setattr__(self, "tension_N", t) + object.__setattr__(self, "external_pressure_Pa", p) + object.__setattr__(self, "group_names", tuple(self.group_names)) + object.__setattr__(self, "group_laws", tuple(self.group_laws)) + object.__setattr__(self, "reference_cap_Nm", reference) + object.__setattr__(self, "group_cap_Nm", cap) + object.__setattr__(self, "group_cap_dT_Nm_per_N", d_t) + object.__setattr__(self, "group_cap_dpe_Nm_per_Pa", d_p) + + # Scales at the table states ------------------------------------------ + @property + def group_scale(self) -> FloatArray: + """``rho_g`` at every table state, shape (groups, tensions, pressures).""" + return self.group_cap_Nm / self.reference_cap_Nm[:, None, None] + + @property + def group_scale_dT_1_per_N(self) -> FloatArray: + """``d rho_g / dT`` [1/N] at every table state.""" + return self.group_cap_dT_Nm_per_N / self.reference_cap_Nm[:, None, None] + + @property + def group_scale_dpe_1_per_Pa(self) -> FloatArray | None: + """``d rho_g / dp_e`` [1/Pa] at every table state (pressure axis only).""" + if self.group_cap_dpe_Nm_per_Pa is None: + return None + return self.group_cap_dpe_Nm_per_Pa / self.reference_cap_Nm[:, None, None] + + @property + def scale(self) -> FloatArray: + """Single cap-weighted scale ``s``, shape (tensions, pressures).""" + return _ratio(self.group_cap_Nm.sum(axis=0), self.reference_cap_Nm.sum()) + + @property + def scale_dT_1_per_N(self) -> FloatArray: + """``ds/dT`` [1/N] at every table state.""" + return _ratio( + self.group_cap_dT_Nm_per_N.sum(axis=0), self.reference_cap_Nm.sum() + ) + + @property + def scale_dpe_1_per_Pa(self) -> FloatArray | None: + """``ds/dp_e`` [1/Pa] at every table state (pressure axis only).""" + if self.group_cap_dpe_Nm_per_Pa is None: + return None + return _ratio( + self.group_cap_dpe_Nm_per_Pa.sum(axis=0), self.reference_cap_Nm.sum() + ) + + # Scales at arbitrary states ------------------------------------------ + def group_scales( + self, + tension_N: ArrayLike, + external_pressure_Pa: ArrayLike | None = None, + *, + per_group: bool = True, + ) -> FloatArray: + """Group scales at states, shape (groups, samples). + + Bilinear interpolation of the group caps in the table (exact for the + bounded contact chain, which is affine in tension and pressure). With + ``per_group=False`` every group takes the single scale ``s``. Without + a pressure axis ``external_pressure_Pa`` must be ``None`` (the + reference external pressure). + """ + t = np.atleast_1d(np.asarray(tension_N, dtype=np.float64)) + if t.ndim != 1: + raise CableInputError("tension must be a scalar or a 1-D history") + i0, i1, wt = _bracket(self.tension_N, t, "tension") + cap = self.group_cap_Nm + if self.external_pressure_Pa is None: + if external_pressure_Pa is not None: + raise CableInputError( + "the table has no external-pressure axis; it holds the " + "reference external pressure" + ) + values = (1.0 - wt) * cap[:, i0, 0] + wt * cap[:, i1, 0] + else: + if external_pressure_Pa is None: + p = np.full(t.shape, self.reference_external_pressure_Pa) + else: + p = np.broadcast_to( + np.asarray(external_pressure_Pa, dtype=np.float64), t.shape + ) + j0, j1, wp = _bracket(self.external_pressure_Pa, p, "external pressure") + values = (1.0 - wt) * (1.0 - wp) * cap[:, i0, j0] + wt * (1.0 - wp) * cap[ + :, i1, j0 + ] + values = ( + values + (1.0 - wt) * wp * cap[:, i0, j1] + wt * wp * cap[:, i1, j1] + ) + if per_group: + return np.asarray(values / self.reference_cap_Nm[:, None]) + single = values.sum(axis=0) / self.reference_cap_Nm.sum() + return np.asarray(np.broadcast_to(single, values.shape).copy()) + + def _elements(self) -> tuple[FloatArray, FloatArray, NDArray[np.intp]]: + k = np.concatenate([law.stiffness_Nm2 for law in self.group_laws]) + y = np.concatenate([law.yield_curvature_1_m for law in self.group_laws]) + group = np.concatenate( + [ + np.full(law.stiffness_Nm2.size, g, dtype=np.intp) + for g, law in enumerate(self.group_laws) + ] + ) + return k, y, group + + def law_at( + self, + tension_N: float, + external_pressure_Pa: float | None = None, + *, + per_group: bool = True, + ) -> IwanBendingLaw: + """The scaled law at one state (elements of equal yield merged).""" + rho = self.group_scales( + [tension_N], + None if external_pressure_Pa is None else [external_pressure_Pa], + per_group=per_group, + )[:, 0] + k, y, group = self._elements() + y = y * rho[group] + keep = y > 0.0 + yields, index = np.unique(y[keep], return_inverse=True) + stiffness = np.zeros(yields.size) + np.add.at(stiffness, index, k[keep]) + return IwanBendingLaw(self.ei_slip_Nm2, stiffness, yields) + + def _history( + self, + kappa_history: ArrayLike, + tension_history_N: ArrayLike, + external_pressure_history_Pa: ArrayLike | None, + per_group: bool, + ) -> tuple[FloatArray, float]: + kappa = np.asarray(kappa_history, dtype=np.float64) + if kappa.ndim != 1 or not np.isfinite(kappa).all(): + raise CableInputError("curvature history must be a finite 1-D array") + tension = np.asarray(tension_history_N, dtype=np.float64) + if tension.shape != kappa.shape: + raise CableInputError("tension history must match the curvature history") + if external_pressure_history_Pa is not None: + pressure = np.asarray(external_pressure_history_Pa, dtype=np.float64) + if pressure.shape != kappa.shape: + raise CableInputError( + "external-pressure history must match the curvature history" + ) + else: + pressure = None + rho = self.group_scales(tension, pressure, per_group=per_group) + k, y, group = self._elements() + bound = y[:, None] * rho[group] # (elements, samples) + e = np.zeros_like(k) + out = np.empty_like(kappa) + work = 0.0 + previous = 0.0 + for n, value in enumerate(kappa): + trial = e + (value - previous) + clipped = np.clip(trial, -bound[:, n], bound[:, n]) + work += float(np.sum(k * np.abs(clipped) * np.abs(trial - clipped))) + e = clipped + previous = value + out[n] = self.ei_slip_Nm2 * value + float(e @ k) + return out, work + + def moment( + self, + kappa_history: ArrayLike, + tension_history_N: ArrayLike, + external_pressure_history_Pa: ArrayLike | None = None, + *, + per_group: bool = True, + ) -> FloatArray: + """Moment history [N m] under curvature and state histories. + + From the virgin state; every element follows the return map with the + cap of the current sample (see the class notes). ``per_group=False`` + applies the single scale ``s`` to all groups. + """ + return self._history( + kappa_history, tension_history_N, external_pressure_history_Pa, per_group + )[0] + + def dissipated_energy( + self, + kappa_history: ArrayLike, + tension_history_N: ArrayLike, + external_pressure_history_Pa: ArrayLike | None = None, + *, + per_group: bool = True, + ) -> float: + """Slider work over the histories [J/m]. + + Every slip increment counts at the element's new force, as in + :meth:`IwanBendingLaw.dissipated_energy`. A cap that falls below an + element's force at fixed curvature adds ``k |e_1| |e_0 - e_1|`` (the + backward-Euler estimate the section law reports). + """ + return self._history( + kappa_history, tension_history_N, external_pressure_history_Pa, per_group + )[1] + + def record(self) -> dict[str, Any]: + """The ``slip_scale`` object of the JSON law (format version 2).""" + rho = self.group_scale + rho_t = self.group_scale_dT_1_per_N + rho_p = self.group_scale_dpe_1_per_Pa + reference = self.law_at( + self.reference_tension_N, + None + if self.external_pressure_Pa is None + else self.reference_external_pressure_Pa, + ) + groups = [] + for g, (name, law) in enumerate( + zip(self.group_names, self.group_laws, strict=True) + ): + item: dict[str, Any] = { + "name": name, + "kind": "laid_cores" if name == CORE_GROUP else "armour_layer", + "reference_cap_Nm": float(self.reference_cap_Nm[g]), + "stiffness_Nm2": law.stiffness_Nm2.tolist(), + "yield_curvature_1_m": law.yield_curvature_1_m.tolist(), + "scale": rho[g].tolist(), + "dscale_dtension_1_per_N": rho_t[g].tolist(), + } + if rho_p is not None: + item["dscale_dexternal_pressure_1_per_Pa"] = rho_p[g].tolist() + groups.append(item) + out: dict[str, Any] = { + "rule": "yield_curvature_scaling", + "variables": ["tension_N"] + + ([] if self.external_pressure_Pa is None else ["external_pressure_Pa"]), + "reference_tension_N": self.reference_tension_N, + "reference_external_pressure_Pa": self.reference_external_pressure_Pa, + "tension_N": self.tension_N.tolist(), + "external_pressure_Pa": None + if self.external_pressure_Pa is None + else self.external_pressure_Pa.tolist(), + "ei_slip_Nm2": self.ei_slip_Nm2, + "reference_elements": { + "stiffness_Nm2": reference.stiffness_Nm2.tolist(), + "yield_curvature_1_m": reference.yield_curvature_1_m.tolist(), + }, + "scale": self.scale.tolist(), + "dscale_dtension_1_per_N": self.scale_dT_1_per_N.tolist(), + "groups": groups, + } + if rho_p is not None: + dp = self.scale_dpe_1_per_Pa + assert dp is not None + out["dscale_dexternal_pressure_1_per_Pa"] = dp.tolist() + return out + + def csv_text(self) -> str: + """One row per table state: the scales and their derivatives.""" + pressures = ( + np.array([self.reference_external_pressure_Pa]) + if self.external_pressure_Pa is None + else self.external_pressure_Pa + ) + header = ["tension_N", "external_pressure_Pa", "s", "ds_dT_1_per_N"] + if self.external_pressure_Pa is not None: + header.append("ds_dpe_1_per_Pa") + for name in self.group_names: + header += [f"s_{name}", f"ds_dT_{name}_1_per_N"] + if self.external_pressure_Pa is not None: + header.append(f"ds_dpe_{name}_1_per_Pa") + rho, rho_t = self.group_scale, self.group_scale_dT_1_per_N + rho_p, s_p = self.group_scale_dpe_1_per_Pa, self.scale_dpe_1_per_Pa + s, s_t = self.scale, self.scale_dT_1_per_N + rows = [",".join(header)] + for i, tension in enumerate(self.tension_N): + for j, pressure in enumerate(pressures): + row = [tension, pressure, s[i, j], s_t[i, j]] + if s_p is not None: + row.append(s_p[i, j]) + for g in range(len(self.group_names)): + row += [rho[g, i, j], rho_t[g, i, j]] + if rho_p is not None: + row.append(rho_p[g, i, j]) + rows.append(",".join(f"{float(v):.9e}" for v in row)) + return "\n".join(rows) + "\n" + + def to_csv(self, path: str | Path) -> Path: + """Write :meth:`csv_text`.""" + out = Path(path) + out.write_text(self.csv_text(), encoding="utf-8") + return out + + @dataclass(frozen=True) class BendingLawExport: - """Backbones and Iwan laws of one cable at a set of tensions.""" + """Backbones and Iwan laws of one cable at a set of tensions. + + ``slip_scale`` holds the slip scaling variable of the law + (:class:`SlipScaleTable`) when the export was asked for it. + """ tension_N: FloatArray kappa_1_m: FloatArray @@ -206,6 +711,7 @@ class BendingLawExport: laws: tuple[IwanBendingLaw, ...] provenance: Provenance settings: dict[str, Any] = field(default_factory=dict) + slip_scale: SlipScaleTable | None = None def law_at(self, tension_N: float) -> IwanBendingLaw: """Law at a tension within the exported range (linear interpolation).""" @@ -238,9 +744,15 @@ def to_json(self, path: str | Path) -> Path: return out def json_text(self) -> str: - """The text :meth:`to_json` writes.""" - record = { - "format": "cablexsec.bending_law/1", + """The text :meth:`to_json` writes. + + Format version 1 without a slip scale (unchanged); version 2 adds the + ``slip_scale`` object and leaves every version-1 field as it was. + """ + record: dict[str, Any] = { + "format": "cablexsec.bending_law/1" + if self.slip_scale is None + else "cablexsec.bending_law/2", "hysteresis_rule": "masing_iwan", "planar_only": True, "tension_N": self.tension_N.tolist(), @@ -258,6 +770,8 @@ def json_text(self) -> str: "method": self.provenance.method, "limitations": list(self.provenance.limitations), } + if self.slip_scale is not None: + record["slip_scale"] = self.slip_scale.record() return json.dumps(record, indent=1) def backbone_table_kNm(self, tension_N: float) -> list[tuple[float, float]]: @@ -283,6 +797,10 @@ def export_bending_law( kappa_max_1_m: float, n_points: int = 200, spacing: str = "geometric", + slip_scale: bool = False, + slip_scale_reference_N: float | None = None, + slip_scale_tensions_N: Sequence[float] | None = None, + slip_scale_external_pressure_Pa: Sequence[float] | None = None, **mkappa_options: Any, ) -> BendingLawExport: """Hysteretic bending law of a cable for global analysis. @@ -301,10 +819,40 @@ def export_bending_law( spacing : {"geometric", "linear"}, optional Point spacing. ``"geometric"`` resolves the stick-to-slip transition at small curvature (default). + slip_scale : bool, optional + Also export the slip scaling variable (:class:`SlipScaleTable`, + ``BendingLawExport.slip_scale``): the law at a reference state split + into friction groups and the scale of every group over a table of + states. Default ``False`` (the export is unchanged). + slip_scale_reference_N : float, optional + Reference tension of the scaled law (default: the smallest of + ``tensions_N`` at which every friction group has contact). The group + laws use the export's curvature grid, and a group of scale ``rho`` + reproduces its law at the state up to ``rho kappa_max_1_m``; beyond, + the full-slip slope continues as in every exported law. With caps + that rise with tension the smallest tension gives ``rho >= 1``. + slip_scale_tensions_N : sequence of float, optional + Ascending tensions of the table [N] (default ``tensions_N``). + slip_scale_external_pressure_Pa : sequence of float, optional + Ascending external pressures of the table [Pa]. ``None`` (default) + runs the table over tension only, at the cable's initial external + pressure, with the contact states of :func:`compute_mkappa`. With a + pressure axis every state, the reference included, is a solved + section state (``solve_section_state`` for the bounded and qp contact + models, ``solve_cable_radial_state`` for the solved model). **mkappa_options Passed to :func:`cablexsec.api.compute_mkappa` (``mu``, ``contact_model``, ``friction_model``, ``progressive``, ``core_friction``); planar bending only. + + Notes + ----- + Torque is not a table variable: the section states that carry a torque + (the coupled qp and solved models with a free twist) differ at zero torque + from the fixed-twist states of the exported backbones, and a torque moves + the ``P1+P2`` of contra-wound layers in opposite senses. The internal-ring + slip of resolved strands (``strand_layers``) has no cap scaling and is + refused with ``slip_scale``. """ from cablexsec.api import compute_mkappa # noqa: PLC0415 @@ -317,9 +865,22 @@ def export_bending_law( raise CableInputError("kappa_max_1_m must be finite and positive") if n_points < 3: raise CableInputError("n_points must be at least 3") - for name in ("tension_N", "phi_bend", "section_state", "radial_state"): + for name in ( + "tension_N", + "phi_bend", + "section_state", + "radial_state", + "contact_pressure_Pa", + "contact_tension_history_N", + ): if name in mkappa_options: raise CableInputError(f"{name} is set by the export, not an option") + if not slip_scale and ( + slip_scale_reference_N is not None + or slip_scale_tensions_N is not None + or slip_scale_external_pressure_Pa is not None + ): + raise CableInputError("the slip_scale_* options need slip_scale=True") if spacing == "geometric": kappa = np.concatenate( [[0.0], np.geomspace(kappa_max_1_m * 1e-4, kappa_max_1_m, n_points - 1)] @@ -339,7 +900,39 @@ def export_bending_law( moments[i, 0] = 0.0 ei_slip[i] = float(result.EI_min_Nm2) laws.append(IwanBendingLaw.from_backbone(kappa, moments[i], ei_slip[i])) + table = ( + _slip_scale_table( + cable, + kappa, + reference_N=None + if slip_scale_reference_N is None + else float(slip_scale_reference_N), + candidates_N=t, + tensions_N=t if slip_scale_tensions_N is None else slip_scale_tensions_N, + external_pressure_Pa=slip_scale_external_pressure_Pa, + options=mkappa_options, + ) + if slip_scale + else None + ) cores = mkappa_options.get("core_friction") not in (None, False) + scale_method = "" + scale_limitations: tuple[str, ...] = () + if table is not None: + scale_method = ( + "; slip scaling variable: the reference law split into one friction " + "group per armour layer" + + (" and the laid cores" if cores else "") + + ", yield curvatures scaled by each group's full-slip friction moment " + "relative to the reference at fixed element stiffnesses" + ) + scale_limitations = ( + "slip scale: exact per group for the direction-tied armour law (caps " + "proportional to P1+P2 at fixed stick stiffness), for the laid-core " + "group while its load-weighted friction coefficient is unchanged; one " + "scale for all groups is exact only when the groups scale alike; " + "torque is not a table variable", + ) provenance = Provenance( method=( "virgin moment-curvature backbone of compute_mkappa at each tension" @@ -350,7 +943,8 @@ def export_bending_law( else "" ) + ", decomposed into parallel elastic, perfectly plastic elements " - "(Iwan model, Masing's rules exact for the planar direction-tied law)" + "(Iwan model; Masing's rules, exact for symmetric wire slip intervals)" + + scale_method ), citations=("[Iwan1966]",), limitations=( @@ -359,8 +953,17 @@ def export_bending_law( "tension and annulus state fixed within one law; between exported " "tensions the backbone is interpolated linearly", "beyond the largest exported curvature the full-slip slope continues", + *scale_limitations, ), ) + settings: dict[str, Any] = { + "kappa_max_1_m": float(kappa_max_1_m), + "n_points": int(n_points), + "spacing": spacing, + **{k: repr(v) for k, v in mkappa_options.items()}, + } + if table is not None: + settings["slip_scale_reference_N"] = table.reference_tension_N return BendingLawExport( tension_N=t, kappa_1_m=kappa, @@ -368,10 +971,221 @@ def export_bending_law( ei_slip_Nm2=ei_slip, laws=tuple(laws), provenance=provenance, - settings={ - "kappa_max_1_m": float(kappa_max_1_m), - "n_points": int(n_points), - "spacing": spacing, - **{k: repr(v) for k, v in mkappa_options.items()}, - }, + settings=settings, + slip_scale=table, + ) + + +def _friction_cap(spec: HelicalLayerSpec) -> float: + """Planar full-slip friction moment of one wire population [N m]. + + Every wire at the bound on the side of its drive under a large positive + curvature about ``phi_bend = 0``: the rising (tension) bound where + ``cos(phi) > 0``, the falling bound where ``cos(phi) < 0``, with the moment + arm of :func:`~cablexsec.mechanics.papailiou.wire_slip_history`. + """ + upper, lower = wire_slip_stress_bounds(spec, 0.0) + c = np.cos(spec.phi_wires) + bound = np.where(c > 0.0, upper, lower) + return float( + spec.A_wire_m2 + * math.cos(spec.lay_angle_rad) + * spec.r_helix_m + * np.sum(bound * np.abs(c)) + ) + + +def _ascending(values: ArrayLike, label: str) -> FloatArray: + grid = np.asarray(values, dtype=np.float64) + if ( + grid.ndim != 1 + or grid.size < 1 + or not np.isfinite(grid).all() + or np.any(grid < 0.0) + or np.any(np.diff(grid) <= 0.0) + ): + raise CableInputError(f"{label} must be finite, non-negative and rise strictly") + return grid + + +def _slip_scale_table( + cable: CableData, + kappa: FloatArray, + *, + reference_N: float | None, + candidates_N: FloatArray, + tensions_N: ArrayLike, + external_pressure_Pa: ArrayLike | None, + options: dict[str, Any], +) -> SlipScaleTable: + """Reference group laws and group caps over the table states.""" + from cablexsec.api import _prepare_mkappa_law # noqa: PLC0415 + from cablexsec.cable_adapters import structural_armour_layers # noqa: PLC0415 + from cablexsec.mechanics.core_friction import ( # noqa: PLC0415 + core_friction_history, + resolve_core_friction, + ) + from cablexsec.mechanics.papailiou import ( # noqa: PLC0415 + compute_mkappa_wire_slip_front, + ) + from cablexsec.mechanics.progressive_friction import ( # noqa: PLC0415 + ProgressiveFriction, + ) + from cablexsec.mechanics.radial_cable import ( # noqa: PLC0415 + solve_cable_radial_state, + ) + from cablexsec.mechanics.section_state import ( # noqa: PLC0415 + solve_section_state, + ) + + tensions = _ascending(tensions_N, "slip_scale_tensions_N") + pressures = ( + None + if external_pressure_Pa is None + else _ascending(external_pressure_Pa, "slip_scale_external_pressure_Pa") + ) + if reference_N is not None and not ( + math.isfinite(reference_N) and reference_N >= 0.0 + ): + raise CableInputError("slip_scale_reference_N must be finite and >= 0") + contact_model = options.get("contact_model") or "bounded" + friction_model = options.get("friction_model", "direction_tied") + common: dict[str, Any] = { + "mu": options.get("mu"), + "phi_bend": 0.0, + "core_spec": resolve_core_friction(options.get("core_friction")), + "progressive": (options.get("progressive") or ProgressiveFriction()) + if friction_model == "progressive" + else None, + } + reference_pe = float(cable.initial_state.external_pressure_Pa) + + def prepare(tension: float, pressure: float | None) -> Any: + if pressure is None: + return _prepare_mkappa_law( + cable, + tension, + contact_model=contact_model, + section_state=None, + radial_state=None, + **common, + ) + if contact_model == "solved": + radial = solve_cable_radial_state( + cable, tension, external_pressure_Pa=pressure + ) + return _prepare_mkappa_law( + cable, + radial.tension_N, + contact_model="solved", + section_state=None, + radial_state=radial, + **common, + ) + state = solve_section_state( + cable, tension_N=tension, p_ext_Pa=pressure, contact_model=contact_model + ) + return _prepare_mkappa_law( + cable, + state.tension_N, + contact_model=contact_model, + section_state=state, + radial_state=None, + **common, + ) + + def caps(tension: float, pressure: float | None) -> FloatArray: + law = prepare(tension, pressure) + values = [_friction_cap(spec) for spec in law.layers] + if law.core_model is not None: + values.append(_friction_cap(law.core_model.population)) + return np.asarray(values, dtype=np.float64) + + reference_pressure = None if pressures is None else reference_pe + if reference_N is None: + # The smallest exported tension at which every group has contact: + # with caps rising with tension the scales are then >= 1. + reference_N = next( + ( + float(value) + for value in candidates_N + if np.all(caps(float(value), reference_pressure) > 0.0) + ), + float(candidates_N[-1]), + ) + reference = prepare(reference_N, reference_pressure) + names = [layer.name for layer in structural_armour_layers(cable)] + backbones = [ + compute_mkappa_wire_slip_front( + [spec], + kappa, + phi_bend=0.0, + EI_min_Nm2=0.0, + progressive=reference.progressive, + ).moment_Nm + for spec in reference.layers + ] + core = reference.core_model + if core is not None: + if core.strand_rings: + raise CableInputError( + "the internal-ring slip of resolved strands has no cap scaling; " + "export the slip scale with CoreFrictionSpec(strand_slip=False)" + ) + names.append(CORE_GROUP) + history = core_friction_history( + core, + kappa, + np.zeros_like(kappa), + ) + backbones.append(history.moment_Nm[:, 0]) + reference_cap = caps(reference_N, reference_pressure) + empty = [ + name for name, value in zip(names, reference_cap, strict=True) if value <= 0 + ] + if empty: + raise CableInputError( + f"no friction at the reference tension {reference_N:g} N in " + f"{', '.join(empty)}; choose a reference with contact" + ) + group_laws = [] + for backbone in backbones: + values = np.asarray(backbone, dtype=np.float64).copy() + values[0] = 0.0 + group_laws.append(IwanBendingLaw.from_backbone(kappa, values, 0.0)) + columns: list[float | None] = ( + [None] if pressures is None else [float(p) for p in pressures] + ) + shape = (len(names), tensions.size, len(columns)) + cap, d_t = np.empty(shape), np.empty(shape) + d_p = None if pressures is None else np.empty(shape) + h_t = _DIFFERENCE_STEP * max(float(tensions[-1]), reference_N, 1e3) + h_p = ( + 0.0 if pressures is None else _DIFFERENCE_STEP * max(float(pressures[-1]), 1e5) + ) + for i, value in enumerate(tensions): + tension = float(value) + low_t, high_t = max(tension - h_t, 0.0), tension + h_t + for j, pressure in enumerate(columns): + cap[:, i, j] = caps(tension, pressure) + d_t[:, i, j] = (caps(high_t, pressure) - caps(low_t, pressure)) / ( + high_t - low_t + ) + if d_p is not None and pressure is not None: + low_p, high_p = max(pressure - h_p, 0.0), pressure + h_p + d_p[:, i, j] = (caps(tension, high_p) - caps(tension, low_p)) / ( + high_p - low_p + ) + return SlipScaleTable( + reference_tension_N=float(reference_N), + reference_external_pressure_Pa=reference_pe, + tension_N=tensions, + external_pressure_Pa=pressures, + group_names=tuple(names), + group_laws=tuple(group_laws), + ei_slip_Nm2=float(reference.ei_min), + reference_cap_Nm=reference_cap, + group_cap_Nm=cap, + group_cap_dT_Nm_per_N=d_t, + group_cap_dpe_Nm_per_Pa=d_p, ) diff --git a/src/cablexsec/io/global_export.py b/src/cablexsec/io/global_export.py index 79bf98d..a60738b 100644 --- a/src/cablexsec/io/global_export.py +++ b/src/cablexsec/io/global_export.py @@ -360,8 +360,8 @@ def cabledyn_bending_law( method=( "virgin moment-curvature backbone of each load case " "(compute_section_properties), decomposed into parallel elastic, " - "perfectly plastic elements (Iwan model, Masing's rules exact for " - "the planar direction-tied law)" + "perfectly plastic elements (Iwan model; Masing's rules, exact for " + "symmetric wire slip intervals)" ), citations=("[Iwan1966]", "[Papailiou1997]"), limitations=( diff --git a/src/cablexsec/project.py b/src/cablexsec/project.py index 9da7505..6cc83e3 100644 --- a/src/cablexsec/project.py +++ b/src/cablexsec/project.py @@ -187,6 +187,14 @@ class BendingLawSettings(_Settings): mu: float | None = Field(default=None, ge=0) contact_model: Literal["bounded", "qp", "solved"] = "bounded" friction_model: Literal["direction_tied", "progressive"] = "direction_tied" + slip_scale: bool = False + slip_scale_reference_N: float | None = Field(default=None, ge=0, strict=False) + slip_scale_tensions_N: tuple[float, ...] | None = Field( + default=None, min_length=1, strict=False + ) + slip_scale_external_pressure_Pa: tuple[float, ...] | None = Field( + default=None, min_length=1, strict=False + ) AnalysisSettings = Annotated[ @@ -481,6 +489,10 @@ def bending_law(self, settings: BendingLawSettings) -> BendingLawExport: mu=options.mu, contact_model=options.contact_model, friction_model=options.friction_model, + slip_scale=options.slip_scale, + slip_scale_reference_N=options.slip_scale_reference_N, + slip_scale_tensions_N=options.slip_scale_tensions_N, + slip_scale_external_pressure_Pa=options.slip_scale_external_pressure_Pa, ) diff --git a/tests/test_bending_law_slip_scale.py b/tests/test_bending_law_slip_scale.py new file mode 100644 index 0000000..c550013 --- /dev/null +++ b/tests/test_bending_law_slip_scale.py @@ -0,0 +1,638 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Gap a2: slip scaling variable of the exported bending law. + +The direction-tied armour law has fixed stick stiffnesses and friction bounds +proportional to each layer's ``P1+P2``, so a layer whose bounds scale by +``rho`` obeys ``M(kappa; rho) = rho M(kappa / rho; 1)`` over any history, and +its Iwan elements keep their stiffnesses while their yield curvatures scale. +""" + +from __future__ import annotations + +import json +import math +from dataclasses import replace + +import numpy as np +import pytest + +import cablexsec as cx +import cablexsec.analysis.bending_law as bending_law +import cablexsec.mechanics.papailiou as papailiou +from cablexsec._project_codec import pack, unpack +from cablexsec.analysis.bending_law import ( + CORE_GROUP, + SlipScaleTable, + export_bending_law, +) +from cablexsec.api import _prepare_mkappa_law +from cablexsec.cable_adapters import armour_contact_pressure +from cablexsec.exceptions import CableInputError + +pytestmark = [ + pytest.mark.analytical_sanity, + pytest.mark.filterwarnings( + "ignore::cablexsec.provenance.MissingClampingStateWarning" + ), +] + + +def _cable(path): + return cx.load_cable(path, geometry_override=None) + + +@pytest.fixture(scope="module") +def menard(): + return _cable(cx.menard2023_yaml_path()) + + +@pytest.fixture(scope="module") +def iea66(): + return _cable(cx.iea_task49_66kv_yaml_path()) + + +def _table(cable, kappa, reference_N, tensions_N, pressures=None, **options): + return bending_law._slip_scale_table( + cable, + np.asarray(kappa, dtype=np.float64), + reference_N=reference_N, + candidates_N=np.array([reference_N]), + tensions_N=tensions_N, + external_pressure_Pa=pressures, + options=options, + ) + + +def _grid(kappa_max, n=160): + return np.concatenate([[0.0], np.geomspace(kappa_max * 1e-4, kappa_max, n - 1)]) + + +def _history(n=1200, amplitude=0.03, phase=0.1): + t = np.arange(n) + # Incommensurate bending and tension cycles; the phase keeps the samples + # off the stick/slip breakpoints. + kappa = amplitude * np.sin(2.0 * np.pi * t / 200.0 + phase) + tension = 1.0e4 + 6.0e4 * np.sin(np.pi * t / 370.0) ** 2 + return kappa, tension + + +def test_section_law_is_homogeneous_in_the_friction_bound(iea66): + # The 66 kV template has no manufacturing clamping: P1+P2 of both armour + # layers and the core contact load are proportional to the tension, so + # every group scales by T2 / T1 and M(kappa; T2) = EI k + rho F(k / rho; T1) + # over a loop history, cores included. + t1, t2 = 2.0e4, 7.0e4 + rho = t2 / t1 + kappa = ( + 4e-4 + * np.sin(np.linspace(0.0, 5.0 * np.pi, 700) + 0.1) + * np.linspace(0.3, 1.0, 700) + ) + table = _table(iea66, _grid(1e-3), t1, [t1, t2], core_friction=True) + assert table.group_names == ("inner_armour", "outer_armour", CORE_GROUP) + np.testing.assert_allclose(table.group_scale[:, 1, 0], rho, rtol=1e-12) + at_t2 = cx.compute_mkappa(iea66, kappa, tension_N=t2, core_friction=True) + at_t1 = cx.compute_mkappa(iea66, kappa / rho, tension_N=t1, core_friction=True) + ei = at_t2.EI_min_Nm2 + predicted = ei * kappa + rho * (np.asarray(at_t1.moment_Nm) - ei * kappa / rho) + scale = np.max(np.abs(at_t2.moment_Nm)) + assert np.max(np.abs(predicted - at_t2.moment_Nm)) < 1e-12 * scale + + +@pytest.mark.parametrize( + ("path", "core"), + [ + (cx.menard2023_yaml_path(), None), + (cx.inter_array_three_core_yaml_path(), True), + ], +) +def test_group_yield_curvatures_scale_exactly(path, core): + # Every group law at T2, decomposed from its own backbone on the grid + # rho_g kappa, is the reference group law with fixed stiffnesses and + # yield curvatures times rho_g (layers with different rho_g included). + cable = _cable(path) + kappa = _grid(0.3, 200) + reference = _table(cable, kappa, 1.0e4, [1.0e4, 6.0e4], core_friction=core) + rho = reference.group_scale[:, 1, 0] + assert np.ptp(rho) > 1e-3 # the groups do scale differently + for g, name in enumerate(reference.group_names): + state = _table(cable, kappa * rho[g], 6.0e4, [6.0e4], core_friction=core) + a, b = reference.group_laws[g], state.group_laws[g] + assert state.group_names[g] == name + k_scale = np.max(a.stiffness_Nm2) + assert np.max(np.abs(a.stiffness_Nm2 - b.stiffness_Nm2)) < 1e-12 * k_scale + np.testing.assert_allclose( + b.yield_curvature_1_m, rho[g] * a.yield_curvature_1_m, rtol=1e-12 + ) + assert state.reference_cap_Nm[g] == pytest.approx( + rho[g] * reference.reference_cap_Nm[g], rel=1e-12 + ) + + +def test_single_scale_reproduces_the_export_when_groups_scale_alike(iea66): + # Public route: the law exported at T2 on the curvature grid scaled by s + # is the reference law with every yield curvature times s. + t1, t2, kappa_max = 2.0e4, 6.0e4, 2e-3 + s = t2 / t1 + export = export_bending_law( + iea66, + tensions_N=[t1, t2], + kappa_max_1_m=kappa_max, + n_points=120, + slip_scale=True, + ) + table = export.slip_scale + assert table is not None and table.reference_tension_N == t1 + np.testing.assert_allclose(table.scale[:, 0], [1.0, s], rtol=1e-12) + direct = export_bending_law( + iea66, tensions_N=[t2], kappa_max_1_m=s * kappa_max, n_points=120 + ).laws[0] + scaled = table.law_at(t2, per_group=False) + np.testing.assert_allclose( + scaled.yield_curvature_1_m, direct.yield_curvature_1_m, rtol=1e-12 + ) + k_scale = np.max(direct.stiffness_Nm2) + assert np.max(np.abs(scaled.stiffness_Nm2 - direct.stiffness_Nm2)) < 1e-12 * k_scale + assert scaled.ei_slip_Nm2 == pytest.approx(direct.ei_slip_Nm2, rel=1e-12) + # At the reference the merged groups are the exported law. + merged = table.law_at(t1) + moment = merged.backbone(export.kappa_1_m) + assert np.max(np.abs(moment - export.moment_Nm[0])) < 1e-12 * np.ptp( + export.moment_Nm[0] + ) + + +def _symmetric_bounds(monkeypatch): + original = papailiou.wire_slip_stress_bounds + + def symmetric(layer, phi_bend, *, contact_pressure_Pa=None): + upper, _ = original(layer, phi_bend, contact_pressure_Pa=contact_pressure_Pa) + return upper, upper.copy() + + monkeypatch.setattr(papailiou, "wire_slip_stress_bounds", symmetric) + monkeypatch.setattr(bending_law, "wire_slip_stress_bounds", symmetric) + return symmetric + + +def _breakpoint_grid(cable, tension_N, bounds, kappa_top): + """Curvature grid through the slip curvature of every wire.""" + law = _prepare_mkappa_law( + cable, + tension_N, + mu=None, + phi_bend=0.0, + contact_model="bounded", + section_state=None, + radial_state=None, + core_spec=None, + progressive=None, + ) + yields = [] + for spec in law.layers: + upper, _ = bounds(spec, 0.0) + c = np.abs(np.cos(spec.phi_wires)) + loaded = (c > 1e-12) & (upper > 0.0) + yields.append(upper[loaded] / (spec.k_f * spec.r_helix_m * c[loaded])) + y = np.sort(np.concatenate(yields)) + # Wires of equal |cos| share a slip curvature up to rounding: keep one + # point per cluster, so no tangent is formed over a rounding gap. + start = np.concatenate([[True], np.diff(y) > 1e-9 * y[1:]]) + cluster = np.cumsum(start) - 1 + points = np.array([y[cluster == i].max() for i in range(cluster[-1] + 1)]) + return np.concatenate([[0.0], points, [kappa_top]]) + + +def test_slider_rule_is_the_history_route_for_symmetric_bounds(menard, monkeypatch): + # The key identity. With symmetric wire bounds every wire is an Iwan + # element, and on a grid through every wire's slip curvature the + # decomposition is exact. A tension cycle inside the bending cycles then + # gives the same moment and friction work through the scaled law (every + # element's return map with the new cap) as through compute_mkappa with + # the contact-tension history (every wire's return map with the new + # bound): two layers that scale differently, caps falling and rising in + # stick and in slip. + bounds = _symmetric_bounds(monkeypatch) + kappa_grid = _breakpoint_grid(menard, 1.0e4, bounds, 0.1) + table = _table(menard, kappa_grid, 1.0e4, np.linspace(1.0e4, 7.0e4, 7)) + kappa, tension = _history() + result = cx.compute_mkappa(menard, kappa, contact_tension_history_N=tension) + moment = table.moment(kappa, tension) + scale = np.max(np.abs(result.moment_Nm)) + assert np.max(np.abs(moment - result.moment_Nm)) < 1e-12 * scale + assert result.work is not None + work = result.work.friction_J_per_m[-1] + assert table.dissipated_energy(kappa, tension) == pytest.approx(work, rel=1e-12) + # The rule matters: the law frozen at the reference misses by 10-20 %. + frozen = table.moment(kappa, np.full_like(tension, 1.0e4)) + assert np.max(np.abs(frozen - result.moment_Nm)) > 0.05 * scale + + +@pytest.mark.parametrize( + ("path", "amplitude", "n_points"), + [ + (cx.menard2023_yaml_path(), 0.03, 300), + (cx.iea_task49_66kv_yaml_path(), 3e-4, 300), + ], +) +def test_tension_cycle_adds_nothing_to_the_fixed_tension_residual( + path, amplitude, n_points +): + # With the signed capstan bound the falling bound of a wire is its + # rising bound times exp(-lam psi): its slip interval is asymmetric, so + # the section law is not exactly of Masing type and every exported Iwan + # law misses compute_mkappa loops by a residual. Under a tension cycle + # inside the bending cycles the scaled law misses the history route by no + # more than that residual at the two ends of the tension range. + cable = _cable(path) + kappa, tension = _history(amplitude=amplitude) + export = export_bending_law( + cable, + tensions_N=[1.0e4, 7.0e4], + kappa_max_1_m=1.2 * amplitude, + n_points=n_points, + slip_scale=True, + slip_scale_tensions_N=np.linspace(1.0e4, 7.0e4, 7), + ) + table = export.slip_scale + assert table is not None + history = np.asarray( + cx.compute_mkappa(cable, kappa, contact_tension_history_N=tension).moment_Nm + ) + span = np.ptp(history) + residual = [] + for level in (1.0e4, 7.0e4): + fixed = np.asarray(cx.compute_mkappa(cable, kappa, tension_N=level).moment_Nm) + law = table.moment(kappa, np.full_like(kappa, level)) + residual.append(np.max(np.abs(law - fixed)) / np.ptp(fixed)) + scaled = table.moment(kappa, tension) + deviation = np.max(np.abs(scaled - history)) / span + assert deviation <= 1.25 * max(residual) + assert deviation < 5e-3 + frozen = table.moment(kappa, np.full_like(tension, table.reference_tension_N)) + assert np.max(np.abs(frozen - history)) / span > 20 * deviation + + +def test_single_scale_error_with_layers_that_scale_differently(menard): + # Menard, 10 -> 70 kN: inner P1+P2 x 2.3, outer x 1.6. The cap-weighted + # single scale keeps the stick stiffness and the full-slip moment but + # misplaces the transition by several percent of the moment range. + kappa = _grid(0.05, 200) + table = _table(menard, kappa, 1.0e4, [1.0e4, 7.0e4]) + exact = table.law_at(7.0e4) + single = table.law_at(7.0e4, per_group=False) + assert single.ei_stick_Nm2 == pytest.approx(exact.ei_stick_Nm2, rel=1e-12) + full_slip = float(exact.stiffness_Nm2 @ exact.yield_curvature_1_m) + assert float(single.stiffness_Nm2 @ single.yield_curvature_1_m) == pytest.approx( + full_slip, rel=1e-12 + ) + k = np.linspace(0.0, 0.05, 1001) + error = np.max(np.abs(single.backbone(k) - exact.backbone(k))) / np.ptp( + exact.backbone(k) + ) + assert 0.02 < error < 0.2 + + +def test_scale_values_and_derivatives(iea66, menard): + # Bounded chain: P1+P2 affine in tension, so the cap is too and the + # central differences give its slope. + table = _table(iea66, _grid(1e-3), 2.0e4, [0.0, 2.0e4, 1.0e5]) + np.testing.assert_allclose(table.scale[:, 0], [0.0, 1.0, 5.0], atol=1e-12) + np.testing.assert_allclose(table.scale_dT_1_per_N, 1.0 / 2.0e4, rtol=1e-6) + np.testing.assert_allclose(table.group_scale_dT_1_per_N, 1.0 / 2.0e4, rtol=1e-6) + assert table.scale_dpe_1_per_Pa is None + assert table.group_scale_dpe_1_per_Pa is None + # Ménard: each layer's slope is the slope of its own P1+P2. + pressures = [armour_contact_pressure(menard, t) for t in (1.0e4, 7.0e4)] + table = _table(menard, _grid(0.05), 1.0e4, [1.0e4, 7.0e4]) + for g, name in enumerate(table.group_names): + slope = (pressures[1][name] - pressures[0][name]) / 6.0e4 + np.testing.assert_allclose( + table.group_scale_dT_1_per_N[g], slope / pressures[0][name], rtol=1e-6 + ) + np.testing.assert_allclose( + table.group_scale[g, :, 0], + [1.0, pressures[1][name] / pressures[0][name]], + rtol=1e-12, + ) + # Interpolation between table rows is linear in the caps. + rho = table.group_scales([4.0e4])[:, 0] + np.testing.assert_allclose(rho, table.group_scale[:, :, 0].mean(axis=1), rtol=1e-12) + single = table.group_scales([4.0e4], per_group=False)[:, 0] + np.testing.assert_allclose(single, table.scale[:, 0].mean(), rtol=1e-12) + + +def test_external_pressure_axis(menard): + # A pressure axis evaluates solved section states. At the reference + # pressure they give the caps of the tension-only table; the bounded + # chain is affine in the external pressure as well. + p0 = menard.initial_state.external_pressure_Pa + pressures = [p0, p0 + 1.0e6, p0 + 2.0e6] + kappa = _grid(0.05, 60) + plain = _table(menard, kappa, 1.0e4, [1.0e4, 5.0e4]) + table = _table(menard, kappa, 1.0e4, [1.0e4, 5.0e4], pressures) + np.testing.assert_allclose( + table.reference_cap_Nm, plain.reference_cap_Nm, rtol=1e-12 + ) + np.testing.assert_allclose( + table.group_cap_Nm[:, :, 0], plain.group_cap_Nm[:, :, 0], rtol=1e-12 + ) + for g in range(len(table.group_names)): + k, k_ref = table.group_laws[g], plain.group_laws[g] + np.testing.assert_allclose(k.stiffness_Nm2, k_ref.stiffness_Nm2, rtol=1e-12) + d_p = table.group_scale_dpe_1_per_Pa + assert d_p is not None and table.scale_dpe_1_per_Pa is not None + slope = np.diff(table.group_scale, axis=2) / 1.0e6 + np.testing.assert_allclose(d_p[:, :, :2], slope, rtol=1e-6) + np.testing.assert_allclose(d_p[:, :, 2], slope[:, :, 1], rtol=1e-6) + # Bilinear interpolation of an affine state is exact. + rho = table.group_scales([3.0e4], [p0 + 0.5e6])[:, 0] + expected = table.group_scale[:, :, :2].mean(axis=(1, 2)) + np.testing.assert_allclose(rho, expected, rtol=1e-12) + # A pressure history drives the moment like a tension history. + kappa_h, tension_h = _history(400, amplitude=0.02) + tension_h = np.clip(tension_h, 1.0e4, 5.0e4) + pressure_h = p0 + 1.5e6 * np.sin(np.linspace(0.0, 3.0, 400)) ** 2 + moment = table.moment(kappa_h, tension_h, pressure_h) + assert np.isfinite(moment).all() + with pytest.raises(CableInputError, match="no external-pressure axis"): + plain.group_scales([2e4], [p0]) + with pytest.raises(CableInputError, match="outside the table"): + table.group_scales([2e4], [p0 + 3e6]) + + +def test_cap_is_the_full_slip_friction_moment(menard): + # The analytic cap equals each group backbone far beyond full slip. + kappa = np.concatenate([[0.0], np.geomspace(1e-5, 2.0, 300)]) + table = _table(menard, kappa, 3.0e4, [3.0e4]) + for g, law in enumerate(table.group_laws): + assert law.backbone(np.array([2.0]))[0] == pytest.approx( + table.reference_cap_Nm[g], rel=1e-9 + ) + + +def test_json_csv_and_project_round_trip(iea66, tmp_path): + plain = export_bending_law( + iea66, tensions_N=[2e4, 6e4], kappa_max_1_m=2e-3, n_points=30 + ) + record = json.loads(plain.json_text()) + assert record["format"] == "cablexsec.bending_law/1" and "slip_scale" not in record + assert plain.slip_scale is None + export = export_bending_law( + iea66, + tensions_N=[2e4, 6e4], + kappa_max_1_m=2e-3, + n_points=30, + slip_scale=True, + slip_scale_tensions_N=[2e4, 4e4, 6e4], + slip_scale_external_pressure_Pa=[0.0, 1e6], + ) + table = export.slip_scale + assert table is not None + record = json.loads(export.to_json(tmp_path / "law.json").read_text("utf-8")) + assert record["format"] == "cablexsec.bending_law/2" + for key in ("tension_N", "moment_Nm", "elements", "ei_slip_Nm2", "kappa_1_m"): + assert record[key] == json.loads(plain.json_text())[key] + block = record["slip_scale"] + assert block["rule"] == "yield_curvature_scaling" + assert block["variables"] == ["tension_N", "external_pressure_Pa"] + assert np.asarray(block["scale"]).shape == (3, 2) + assert [g["name"] for g in block["groups"]] == list(table.group_names) + assert block["groups"][0]["kind"] == "armour_layer" + np.testing.assert_allclose(block["dscale_dtension_1_per_N"], table.scale_dT_1_per_N) + merged = table.law_at(2e4, 0.0) + assert block["reference_elements"]["yield_curvature_1_m"] == ( + merged.yield_curvature_1_m.tolist() + ) + text = table.to_csv(tmp_path / "scale.csv").read_text("utf-8").splitlines() + assert text[0].startswith("tension_N,external_pressure_Pa,s,ds_dT_1_per_N,ds_dpe") + assert "s_inner_armour" in text[0] and len(text) == 1 + 3 * 2 + row = np.array(text[2].split(","), dtype=float) + assert row[0] == 2e4 and row[1] == 1e6 + assert row[2] == pytest.approx(table.scale[0, 1], rel=1e-8) + tension_only = export_bending_law( + iea66, tensions_N=[2e4, 6e4], kappa_max_1_m=2e-3, n_points=30, slip_scale=True + ) + assert tension_only.slip_scale is not None + lines = tension_only.slip_scale.csv_text().splitlines() + assert lines[0].split(",")[:4] == [ + "tension_N", + "external_pressure_Pa", + "s", + "ds_dT_1_per_N", + ] + assert "ds_dpe" not in lines[0] + # Project codec: the table round-trips, and a payload written before the + # field existed (no "slip_scale") still decodes. + decoded = unpack(pack(export)) + assert decoded.slip_scale is not None + np.testing.assert_array_equal(decoded.slip_scale.group_cap_Nm, table.group_cap_Nm) + payload = pack(plain) + del payload["fields"]["slip_scale"] + assert unpack(payload).slip_scale is None + missing = pack(plain) + del missing["fields"]["laws"] + with pytest.raises(CableInputError): + unpack(missing) + + +def test_project_settings_pass_the_slip_scale(iea66): + from cablexsec.project import BendingLawSettings, CableModel + + model = CableModel(iea66) + settings = BendingLawSettings( + tensions_N=(2e4, 6e4), + kappa_max_1_m=2e-3, + n_points=20, + slip_scale=True, + slip_scale_reference_N=2e4, + ) + export = model.bending_law(settings) + assert export.slip_scale is not None + assert export.slip_scale.reference_tension_N == 2e4 + + +def test_export_checks(iea66): + args = {"tensions_N": [0.0, 2e4], "kappa_max_1_m": 1e-3, "n_points": 20} + with pytest.raises(CableInputError, match="need slip_scale=True"): + export_bending_law(iea66, slip_scale_reference_N=2e4, **args) + for name in ("contact_tension_history_N", "contact_pressure_Pa"): + with pytest.raises(CableInputError, match="set by the export"): + export_bending_law(iea66, **args, **{name: None}) + # No contact at zero tension on this template: the default reference is + # the first tension with contact, and zero itself is refused. + export = export_bending_law(iea66, slip_scale=True, **args) + assert export.slip_scale is not None + assert export.slip_scale.reference_tension_N == 2e4 + np.testing.assert_allclose(export.slip_scale.scale[:, 0], [0.0, 1.0], atol=1e-15) + # Without contact the scaled law is the full-slip stiffness alone. + bare = export.slip_scale.law_at(0.0) + assert bare.stiffness_Nm2.size == 0 + assert bare.ei_stick_Nm2 == export.slip_scale.ei_slip_Nm2 + with pytest.raises(CableInputError, match="no friction at the reference"): + export_bending_law(iea66, slip_scale=True, slip_scale_reference_N=0.0, **args) + with pytest.raises(CableInputError, match="slip_scale_tensions_N"): + export_bending_law( + iea66, slip_scale=True, slip_scale_tensions_N=[2e4, 1e4], **args + ) + with pytest.raises(CableInputError, match="slip_scale_external_pressure_Pa"): + export_bending_law( + iea66, slip_scale=True, slip_scale_external_pressure_Pa=[-1.0], **args + ) + with pytest.raises(CableInputError, match="slip_scale_reference_N"): + export_bending_law( + iea66, slip_scale=True, slip_scale_reference_N=math.nan, **args + ) + + +def test_strand_rings_are_refused(): + cable = _cable(cx.thies2016_yaml_path()) + with pytest.raises(CableInputError, match="strand"): + export_bending_law( + cable, + tensions_N=[2e4], + kappa_max_1_m=0.05, + n_points=20, + slip_scale=True, + core_friction=True, + ) + + +def test_history_and_table_checks(iea66): + table = _table(iea66, _grid(1e-3, 40), 2.0e4, [2.0e4, 6.0e4]) + with pytest.raises(CableInputError, match="outside the table"): + table.group_scales([1.0e4]) + with pytest.raises(CableInputError, match="finite"): + table.group_scales([math.nan]) + with pytest.raises(CableInputError, match="1-D"): + table.group_scales(np.zeros((2, 2)) + 3e4) + with pytest.raises(CableInputError, match="tension history must match"): + table.moment(np.zeros(3), np.full(2, 3e4)) + with pytest.raises(CableInputError, match="curvature history"): + table.moment(np.zeros((2, 2)), np.full(2, 3e4)) + with pytest.raises(CableInputError, match="external-pressure history"): + table.moment(np.zeros(3), np.full(3, 3e4), np.zeros(2)) + with pytest.raises(CableInputError, match="no external-pressure axis"): + table.moment(np.zeros(3), np.full(3, 3e4), np.zeros(3)) + one = _table(iea66, _grid(1e-3, 40), 2.0e4, [2.0e4]) + np.testing.assert_allclose(one.group_scales([2.0e4]), 1.0) + with pytest.raises(CableInputError, match="outside"): + one.group_scales([2.1e4]) + # Constructor checks. + good = {f: getattr(table, f) for f in table.__dataclass_fields__} + cases = [ + ({"tension_N": np.array([2e4, 1e4])}, "strictly ascending"), + ({"group_names": ("a",)}, "one law per friction group"), + ({"group_names": ("a", "a")}, "distinct"), + ({"reference_cap_Nm": np.array([1.0, 0.0])}, "positive reference cap"), + ({"group_cap_Nm": np.zeros((2, 3, 1))}, "shape"), + ({"group_cap_Nm": -table.group_cap_Nm}, "non-negative"), + ({"group_cap_dT_Nm_per_N": table.group_cap_dT_Nm_per_N * np.nan}, "finite"), + ({"group_cap_dpe_Nm_per_Pa": table.group_cap_dT_Nm_per_N}, "pressure axis"), + ({"reference_tension_N": -1.0}, "reference state"), + ({"ei_slip_Nm2": -1.0}, "ei_slip_Nm2"), + ({"external_pressure_Pa": np.array([0.0])}, "pressure derivative"), + ] + for change, match in cases: + with pytest.raises(CableInputError, match=match): + SlipScaleTable(**{**good, **change}) + with pytest.raises(CableInputError, match="pressure derivative must be finite"): + SlipScaleTable( + **{ + **good, + "external_pressure_Pa": np.array([0.0]), + "group_cap_dpe_Nm_per_Pa": np.zeros((2, 1, 1)), + } + ) + + +def test_falling_cap_at_fixed_curvature_does_slider_work(iea66): + # Hold the curvature in full slip and lower the tension: every element + # is clipped to the new cap; the work of one step is k e1 (e0 - e1). + table = _table(iea66, _grid(1e-3, 60), 2.0e4, [1.0e4, 2.0e4]) + kappa = np.array([5e-4, 5e-4]) + tension = np.array([2.0e4, 1.0e4]) + law = table.law_at(2.0e4) + before = table.moment(kappa[:1], tension[:1]) + after = table.moment(kappa, tension) + full = law.ei_slip_Nm2 * 5e-4 + float(law.stiffness_Nm2 @ law.yield_curvature_1_m) + assert before[0] == pytest.approx(full, rel=1e-12) + expected = law.ei_slip_Nm2 * 5e-4 + 0.5 * (full - law.ei_slip_Nm2 * 5e-4) + assert after[1] == pytest.approx(expected, rel=1e-12) + k, y = law.stiffness_Nm2, law.yield_curvature_1_m + step = float(np.sum(k * (0.5 * y) * (0.5 * y))) + loading = table.dissipated_energy(kappa[:1], tension[:1]) + assert table.dissipated_energy(kappa, tension) - loading == pytest.approx( + step, rel=1e-12 + ) + # Raising the cap back leaves the clipped elements where they are. + again = table.moment(np.full(3, 5e-4), np.array([2.0e4, 1.0e4, 2.0e4])) + assert again[2] == pytest.approx(after[1], rel=1e-12) + + +def test_replace_keeps_the_table(iea66): + export = export_bending_law( + iea66, tensions_N=[2e4], kappa_max_1_m=1e-3, n_points=20, slip_scale=True + ) + again = replace(export, settings={}) + assert again.slip_scale is export.slip_scale + + +def _touching_alternate_wires(): + """Three touching armour layers laid alternately (two crossing interfaces in + the middle one, which the crossed-wire line loads refuse).""" + from cablexsec.cables.schema import CableData, CableMeta, HelicalLayer + + layers = tuple( + HelicalLayer( + name=f"wire-{i}", + material="galvanised_steel_armour", + n_wires=12 * (i + 1), + d_wire_m=0.002, + r_helix_m=0.02 + 0.002 * i, + lay_angle_deg=20 + 10 * i, + lay_direction="left_hand" if i == 1 else "right_hand", + ) + for i in range(3) + ) + return CableData(cable=CableMeta(name="touching alternate wires"), layers=layers) + + +@pytest.mark.parametrize( + ("contact_model", "pressures"), + # (the solved model of this sheath-free synthetic stack meets a singular + # sparse factor in some environments, also without the slip scale) + [("bounded", None), ("bounded", [0.0, 1e6])], +) +def test_slip_scale_uses_the_pressure_only_route(contact_model, pressures): + # The scale evaluates P1+P2 with the scalar-tension contact states of + # compute_mkappa, never the crossed-wire line loads, so a stack whose + # contact histories are refused still exports it. + cable = _touching_alternate_wires() + with pytest.raises(cx.CableSchemaError): + cx.armour_contact_histories(cable, np.array([1.0e4])) + export = export_bending_law( + cable, + tensions_N=[1.0e4, 3.0e4], + kappa_max_1_m=0.06, + n_points=60, + contact_model=contact_model, + slip_scale=True, + slip_scale_external_pressure_Pa=pressures, + ) + table = export.slip_scale + assert table is not None + assert table.group_names == ("wire-0", "wire-1", "wire-2") + for i, tension in enumerate(export.tension_N): + got = table.law_at(tension, None if pressures is None else 0.0) + np.testing.assert_allclose( + got.ei_stick_Nm2, export.laws[i].ei_stick_Nm2, rtol=1e-12 + ) + if contact_model == "bounded" and pressures is None: + kappa, tension = _history(600, amplitude=0.05) + tension = 1.0e4 + 2.0e4 * np.sin(np.pi * np.arange(600) / 370.0) ** 2 + history = np.asarray( + cx.compute_mkappa(cable, kappa, contact_tension_history_N=tension).moment_Nm + ) + scaled = table.moment(kappa, tension) + assert np.max(np.abs(scaled - history)) < 0.02 * np.ptp(history) diff --git a/validation/scripts/run_validation.py b/validation/scripts/run_validation.py index 622ab49..29ccd23 100644 --- a/validation/scripts/run_validation.py +++ b/validation/scripts/run_validation.py @@ -726,6 +726,110 @@ def _mkappa_tension_cycle(cable: CableData) -> tuple[float, float]: return deviation, balance +def _slip_scale_identities(menard: CableData) -> tuple[float, float, float]: + """Slip scaling variable of the exported bending law (gap a2). + + 1. 66 kV template (no manufacturing clamping, so both armour layers and + the cores scale by T2/T1): compute_mkappa at 70 kN against + ``EI k + rho F(k / rho)`` from 20 kN over a loop history, cores + included; largest difference over the largest moment. + 2. Menard, 10 and 60 kN (the layers scale by 1.40 and 2.06): every group + law decomposed at 60 kN on the grid ``rho_g kappa`` against the 10 kN + group law with fixed stiffnesses and yield curvatures times ``rho_g``; + largest relative difference. + 3. Menard, bending at +-0.03 1/m with the tension 10 + 60 sin^2(pi t / + 370) kN: largest difference of the scaled law from compute_mkappa with + the contact-tension history, over the larger fixed-tension residual of + the same Iwan law at 10 and 70 kN (the signed capstan bound makes each + wire's slip interval asymmetric, which no Masing element carries). + """ + from cablexsec.analysis.bending_law import ( # noqa: PLC0415 + _slip_scale_table, + ) + + def table( + cable: CableData, kappa: np.ndarray, reference: float, tensions: list[float] + ) -> cx.SlipScaleTable: + return _slip_scale_table( + cable, + kappa, + reference_N=reference, + candidates_N=np.array([reference]), + tensions_N=tensions, + external_pressure_Pa=None, + options={"core_friction": True} if cable is not menard else {}, + ) + + iea = cx.load_cable(cx.iea_task49_66kv_yaml_path(), geometry_override=None) + rho = 7.0e4 / 2.0e4 + kappa = ( + 4e-4 + * np.sin(np.linspace(0.0, 5.0 * np.pi, 700) + 0.1) + * np.linspace(0.3, 1.0, 700) + ) + high = cx.compute_mkappa(iea, kappa, tension_N=7.0e4, core_friction=True) + low = cx.compute_mkappa(iea, kappa / rho, tension_N=2.0e4, core_friction=True) + ei = high.EI_min_Nm2 + scaled = ei * kappa + rho * (np.asarray(low.moment_Nm) - ei * kappa / rho) + homogeneity = float( + np.max(np.abs(scaled - high.moment_Nm)) / np.max(np.abs(high.moment_Nm)) + ) + + grid = np.concatenate([[0.0], np.geomspace(1e-5, 0.3, 199)]) + reference = table(menard, grid, 1.0e4, [1.0e4, 6.0e4]) + group = 0.0 + for g in range(len(reference.group_names)): + factor = float(reference.group_scale[g, 1, 0]) + state = table(menard, grid * factor, 6.0e4, [6.0e4]) + a, b = reference.group_laws[g], state.group_laws[g] + group = max( + group, + float(np.max(np.abs(a.stiffness_Nm2 - b.stiffness_Nm2))) + / float(np.max(a.stiffness_Nm2)), + float( + np.max( + np.abs(factor * a.yield_curvature_1_m - b.yield_curvature_1_m) + / b.yield_curvature_1_m + ) + ), + ) + + t = np.arange(1200) + bending = 0.03 * np.sin(2.0 * np.pi * t / 200.0 + 0.1) + tension = 1.0e4 + 6.0e4 * np.sin(np.pi * t / 370.0) ** 2 + export = cx.export_bending_law( + menard, + tensions_N=[1.0e4, 7.0e4], + kappa_max_1_m=0.036, + n_points=300, + slip_scale=True, + slip_scale_tensions_N=np.linspace(1.0e4, 7.0e4, 7), + ) + law = export.slip_scale + assert law is not None + history = np.asarray( + cx.compute_mkappa(menard, bending, contact_tension_history_N=tension).moment_Nm + ) + deviation = float( + np.max(np.abs(law.moment(bending, tension) - history)) / np.ptp(history) + ) + residual = 0.0 + for level in (1.0e4, 7.0e4): + fixed = np.asarray( + cx.compute_mkappa(menard, bending, tension_N=level).moment_Nm + ) + residual = max( + residual, + float( + np.max( + np.abs(law.moment(bending, np.full_like(bending, level)) - fixed) + ) + / np.ptp(fixed) + ), + ) + return homogeneity, group, deviation / residual + + def _rows() -> list[Row]: rows: list[Row] = _normal_state_rows() menard = cx.load_cable(cx.menard2023_yaml_path(), geometry_override=None) @@ -1042,6 +1146,29 @@ def _rows() -> list[Row]: ) ) + # Slip scaling variable of the exported bending law (gap a2): the section + # law is homogeneous in the friction bound; group yield curvatures scale + # exactly; a tension cycle inside the bending cycles adds nothing to the + # fixed-tension residual of the Iwan law. + sc_homog, sc_group, sc_ratio = _slip_scale_identities(menard) + rows.append( + Row( + "1", + "MX-scale", + "Exported law with a slip scaling variable: compute_mkappa at T2 vs " + "the T1 law with the bound scaled (66 kV, cores included); group " + "elements at T2 vs the T1 elements with yield curvatures scaled " + "(Menard, two layers); tension cycle inside the bending cycles, " + "scaled law vs the contact-tension history over the fixed-tension " + "Iwan residual", + "< 1e-12 relative; < 1e-12 relative; ratio <= 1.25", + f"{sc_homog:.1e}; {sc_group:.1e}; {sc_ratio:.2f}", + "PASS" + if sc_homog < 1e-12 and sc_group < 1e-12 and sc_ratio <= 1.25 + else "FAIL", + ) + ) + # GATE B (distinguishing physics): slip starts at the NEUTRAL AXIS, per the # Raoof (1989b,1992) strain-gauge observation and Papailiou — not the extreme # fibre (which the retired Coulomb loop predicts). The first-to-slip wire's diff --git a/validation/validation_report.md b/validation/validation_report.md index cc39e70..fe9639a 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -26,6 +26,7 @@ Every row is computed from published data or closed-form references in this repo | 1 | M-rec | Assembled per-wire moment vs compute_mkappa (cross-engine, single-core) | < 2% | 0.000% | PASS | | 1 | M-rec-3core | Cross-engine moment vs compute_mkappa with offset-core geometry and shared mean armour pressure | < 2% | 0.000% | PASS | | 1 | MK-Tcyc | compute_mkappa with a tension history cycling within the bending cycles vs the fatigue-path friction stress on the same history; work balance under the changing friction bound | < 1e-12 relative; < 1e-12 relative | 3.4e-16; 1.1e-15 | PASS | +| 1 | MX-scale | Exported law with a slip scaling variable: compute_mkappa at T2 vs the T1 law with the bound scaled (66 kV, cores included); group elements at T2 vs the T1 elements with yield curvatures scaled (Menard, two layers); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 relative; < 1e-12 relative; ratio <= 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | | 1 | slip-onset | First-to-slip wire at the neutral axis (|cos| → 0, compression side at psi ≈ 3 lam/2; Raoof/Papailiou, not extreme-fibre loop) | |cos| < 0.2 | |cos|=0.156 | PASS | | 1 | xsec-K | Coupling tangent bounds (κ→0=EI_max, κ→∞=EI_min); slip-front local slope | < 0.01% | κ0:3.16e-14% / κ∞:5.99e-13% | PASS | | 1 | QP-KKT | Concentric contact max|normal line force times gap| (common extension, twist and radial equilibrium) | < 1e-8 N | 1.9e-13 (q>=0: True) | PASS | @@ -61,9 +62,9 @@ Every row is computed from published data or closed-form references in this repo ## Test taxonomy (full gate suite) -- analytical_sanity: `1052 passed, 3111 deselected` -- independent_method: `70 passed, 4093 deselected` -- full_scale: `27 passed, 4136 deselected` +- analytical_sanity: `1072 passed, 3111 deselected` +- independent_method: `70 passed, 4113 deselected` +- full_scale: `27 passed, 4156 deselected` Run `pytest -m ` to reproduce each group. From a13ddbe6f10585fdcbe1e8c49da4f4c5579ffb82 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 08:54:29 +0900 Subject: [PATCH 2/3] MX-scale: the group-element identity holds to round-off, target 1e-9 The group element stiffnesses are differences of fitted slopes, so the identity holds to a few hundred machine epsilons: 8.3e-14 here, 1.1e-13 on the CI runner, where the report checker read it as a real change against the 1e-12 target. The target is now 1e-9 (round-off for the checker); a wrong scaling misses it by orders of magnitude. Signed-off-by: Jae Hoon Seo --- VALIDATION.md | 2 +- doc/benchmarks.md | 2 +- validation/scripts/run_validation.py | 8 +++++--- validation/validation_report.md | 2 +- 4 files changed, 8 insertions(+), 6 deletions(-) diff --git a/VALIDATION.md b/VALIDATION.md index de4c69a..9f44e04 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -41,7 +41,7 @@ afterwards: a comparison that misses its target is reported as failed. | **σ_B** | Radial-fibre bending stress | Ménard and Cartraud (2023), Eq. 14 | 0 | <1e-6 % | Pass | | **M-rec, M-rec-3core** | Assembled per-wire moment against the section engine | cross-engine | 0.000 % | <2 % | Pass | | **MK-Tcyc** | Moment–curvature law with tension cycling inside the bending cycles; work balance under the changing friction bound | fatigue-path friction stress, same kernels | 3.4e-16; 1.1e-15 | <1e-12 | Pass | -| **MX-scale** | Exported bending law with a slip scaling variable: bound homogeneity, scaled group yield curvatures, tension cycle inside the bending cycles | `compute_mkappa` at another tension; contact-tension history | 4.1e-16; 8.3e-14; ratio 1.02 | <1e-12; <1e-12; ≤1.25 | Pass | +| **MX-scale** | Exported bending law with a slip scaling variable: bound homogeneity, scaled group yield curvatures, tension cycle inside the bending cycles | `compute_mkappa` at another tension; contact-tension history | 4.1e-16; 8.3e-14; ratio 1.02 | <1e-12; <1e-9; ≤1.25 | Pass | | **slip-onset** | First wire to slip lies at the neutral axis (compression side, ψ ≈ 3λ/2) | Raoof; Papailiou | \|cos\| = 0.156 | \|cos\| < 0.2 | Pass | | **xsec-K** | Coupling tangent bounds | EI_max, EI_min limits | ≤6.3e-13 % | <0.01 % | Pass | | **QP-KKT, QP-Lamé** | Concentric contact complementarity; shrink-fit compliances | KKT conditions; compound cylinder | 1.9e-13 N; 1.3e-16 | <1e-8 N; <1e-6 | Pass | diff --git a/doc/benchmarks.md b/doc/benchmarks.md index 4b32931..071a18b 100644 --- a/doc/benchmarks.md +++ b/doc/benchmarks.md @@ -137,7 +137,7 @@ All rows are verification, not validation. Source: the scorecard | M-rec | I | Assembled per-wire moment vs `compute_mkappa`, single core | < 2% | 0.000% | PASS | | M-rec-3core | I | As M-rec, offset-core geometry | < 2% | 0.000% | PASS | | MK-Tcyc | I | `compute_mkappa` with a contact-tension history cycling inside the bending cycles vs the moment of the fatigue-path friction stress on the same history; work-balance residual over the friction work | < 1e-12 rel.; < 1e-12 rel. | 3.4e-16; 1.1e-15 | PASS | -| MX-scale | I | Slip-scaled bending law: `compute_mkappa` at 70 kN vs the 20 kN law with the bound scaled (66 kV, cores); group elements at 60 kN vs the 10 kN elements with yield curvatures scaled (Ménard); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 rel.; < 1e-12 rel.; ratio ≤ 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | +| MX-scale | I | Slip-scaled bending law: `compute_mkappa` at 70 kN vs the 20 kN law with the bound scaled (66 kV, cores); group elements at 60 kN vs the 10 kN elements with yield curvatures scaled (Ménard); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 rel.; < 1e-9 rel.; ratio ≤ 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | | slip-onset | A | First wire to slip lies at the neutral axis (with the signed bound on the compression side, ψ ≈ 3λ/2) | abs(cos) < 0.2 | 0.156 (0.000 with the former bound) | PASS | | xsec-K | A | Tangent bounds EI_max (κ→0) and EI_min (κ→∞) | < 0.01% | 0; 7.4e-12% | PASS | | QP-KKT | A | Concentric contact complementarity | < 1e-8 N | 1.9e-13 N | PASS | diff --git a/validation/scripts/run_validation.py b/validation/scripts/run_validation.py index 29ccd23..81e949e 100644 --- a/validation/scripts/run_validation.py +++ b/validation/scripts/run_validation.py @@ -736,7 +736,9 @@ def _slip_scale_identities(menard: CableData) -> tuple[float, float, float]: 2. Menard, 10 and 60 kN (the layers scale by 1.40 and 2.06): every group law decomposed at 60 kN on the grid ``rho_g kappa`` against the 10 kN group law with fixed stiffnesses and yield curvatures times ``rho_g``; - largest relative difference. + largest relative difference. The element stiffnesses are differences + of fitted slopes, so this identity holds to a few hundred machine + epsilons, which differ between platforms (8e-14 and 1.1e-13). 3. Menard, bending at +-0.03 1/m with the tension 10 + 60 sin^2(pi t / 370) kN: largest difference of the scaled law from compute_mkappa with the contact-tension history, over the larger fixed-tension residual of @@ -1161,10 +1163,10 @@ def _rows() -> list[Row]: "(Menard, two layers); tension cycle inside the bending cycles, " "scaled law vs the contact-tension history over the fixed-tension " "Iwan residual", - "< 1e-12 relative; < 1e-12 relative; ratio <= 1.25", + "< 1e-12 relative; < 1e-9 relative; ratio <= 1.25", f"{sc_homog:.1e}; {sc_group:.1e}; {sc_ratio:.2f}", "PASS" - if sc_homog < 1e-12 and sc_group < 1e-12 and sc_ratio <= 1.25 + if sc_homog < 1e-12 and sc_group < 1e-9 and sc_ratio <= 1.25 else "FAIL", ) ) diff --git a/validation/validation_report.md b/validation/validation_report.md index fe9639a..1c89707 100644 --- a/validation/validation_report.md +++ b/validation/validation_report.md @@ -26,7 +26,7 @@ Every row is computed from published data or closed-form references in this repo | 1 | M-rec | Assembled per-wire moment vs compute_mkappa (cross-engine, single-core) | < 2% | 0.000% | PASS | | 1 | M-rec-3core | Cross-engine moment vs compute_mkappa with offset-core geometry and shared mean armour pressure | < 2% | 0.000% | PASS | | 1 | MK-Tcyc | compute_mkappa with a tension history cycling within the bending cycles vs the fatigue-path friction stress on the same history; work balance under the changing friction bound | < 1e-12 relative; < 1e-12 relative | 3.4e-16; 1.1e-15 | PASS | -| 1 | MX-scale | Exported law with a slip scaling variable: compute_mkappa at T2 vs the T1 law with the bound scaled (66 kV, cores included); group elements at T2 vs the T1 elements with yield curvatures scaled (Menard, two layers); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 relative; < 1e-12 relative; ratio <= 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | +| 1 | MX-scale | Exported law with a slip scaling variable: compute_mkappa at T2 vs the T1 law with the bound scaled (66 kV, cores included); group elements at T2 vs the T1 elements with yield curvatures scaled (Menard, two layers); tension cycle inside the bending cycles, scaled law vs the contact-tension history over the fixed-tension Iwan residual | < 1e-12 relative; < 1e-9 relative; ratio <= 1.25 | 4.1e-16; 8.3e-14; 1.02 | PASS | | 1 | slip-onset | First-to-slip wire at the neutral axis (|cos| → 0, compression side at psi ≈ 3 lam/2; Raoof/Papailiou, not extreme-fibre loop) | |cos| < 0.2 | |cos|=0.156 | PASS | | 1 | xsec-K | Coupling tangent bounds (κ→0=EI_max, κ→∞=EI_min); slip-front local slope | < 0.01% | κ0:3.16e-14% / κ∞:5.99e-13% | PASS | | 1 | QP-KKT | Concentric contact max|normal line force times gap| (common extension, twist and radial equilibrium) | < 1e-8 N | 1.9e-13 (q>=0: True) | PASS | From 5e0fb29b642796a98da7ab6f4e01b0204ba65d73 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Mon, 16 Nov 2026 09:01:50 +0900 Subject: [PATCH 3/3] The reference elements of a slip-scaled law serialise when the reference lies off the table axes record() built the reference elements through law_at() at the reference state, which the table refuses when its tension or pressure axis does not hold that state (the default reference is the first exported tension with contact, and the pressure reference is the cable's own). json_text() and to_json() then failed on an export that was otherwise valid. At the reference every group scale is 1, so SlipScaleTable.reference_law() now merges the group elements unscaled, and law_at() shares that merge. Test: a tension axis starting above the reference and a pressure axis excluding the cable's external pressure both serialise (both failed before), and reference_law() equals law_at() at the reference on a table that holds it. Signed-off-by: Jae Hoon Seo --- src/cablexsec/analysis/bending_law.py | 20 ++++++--- tests/test_bending_law_slip_scale.py | 61 +++++++++++++++++++++++++++ validation/validation_report.md | 6 +-- 3 files changed, 78 insertions(+), 9 deletions(-) diff --git a/src/cablexsec/analysis/bending_law.py b/src/cablexsec/analysis/bending_law.py index 5ab8f2f..dabae59 100644 --- a/src/cablexsec/analysis/bending_law.py +++ b/src/cablexsec/analysis/bending_law.py @@ -525,6 +525,19 @@ def law_at( None if external_pressure_Pa is None else [external_pressure_Pa], per_group=per_group, )[:, 0] + return self._merged(rho) + + def reference_law(self) -> IwanBendingLaw: + """The law at the reference state, where every group scale is 1. + + Built from the group laws alone, so it exists when the reference + state lies outside the table's axes (the default reference is the + first exported tension with contact). + """ + return self._merged(np.ones(len(self.group_laws))) + + def _merged(self, rho: FloatArray) -> IwanBendingLaw: + """The group elements with yield curvatures times ``rho[g]``, merged.""" k, y, group = self._elements() y = y * rho[group] keep = y > 0.0 @@ -612,12 +625,7 @@ def record(self) -> dict[str, Any]: rho = self.group_scale rho_t = self.group_scale_dT_1_per_N rho_p = self.group_scale_dpe_1_per_Pa - reference = self.law_at( - self.reference_tension_N, - None - if self.external_pressure_Pa is None - else self.reference_external_pressure_Pa, - ) + reference = self.reference_law() groups = [] for g, (name, law) in enumerate( zip(self.group_names, self.group_laws, strict=True) diff --git a/tests/test_bending_law_slip_scale.py b/tests/test_bending_law_slip_scale.py index c550013..04027a3 100644 --- a/tests/test_bending_law_slip_scale.py +++ b/tests/test_bending_law_slip_scale.py @@ -452,6 +452,67 @@ def test_project_settings_pass_the_slip_scale(iea66): assert export.slip_scale.reference_tension_N == 2e4 +@pytest.mark.parametrize( + "axes", + [ + {"slip_scale_tensions_N": [3e4, 6e4]}, + { + "slip_scale_tensions_N": [2e4, 6e4], + "slip_scale_external_pressure_Pa": [1e6, 2e6], + }, + ], + ids=["tension_axis", "pressure_axis"], +) +def test_reference_outside_the_table_axes_serialises(iea66, axes): + # The default reference (20 kN, the cable's own external pressure) lies + # outside these axes: the table refuses it as a state, but the reference + # elements are the group elements at scale 1 and still serialise. + export = export_bending_law( + iea66, + tensions_N=[2e4, 6e4], + kappa_max_1_m=2e-3, + n_points=30, + slip_scale=True, + **axes, + ) + table = export.slip_scale + assert table is not None and table.reference_tension_N == 2e4 + with pytest.raises(CableInputError): + table.law_at( + table.reference_tension_N, + None + if table.external_pressure_Pa is None + else table.reference_external_pressure_Pa, + ) + block = json.loads(export.json_text())["slip_scale"] + reference = table.reference_law() + assert ( + block["reference_elements"]["stiffness_Nm2"] == reference.stiffness_Nm2.tolist() + ) + assert block["reference_elements"]["yield_curvature_1_m"] == ( + reference.yield_curvature_1_m.tolist() + ) + # The same merge as law_at on a table that holds the reference state. + inside = export_bending_law( + iea66, + tensions_N=[2e4, 6e4], + kappa_max_1_m=2e-3, + n_points=30, + slip_scale=True, + slip_scale_tensions_N=[2e4, 6e4], + ).slip_scale + assert inside is not None + at_reference = inside.law_at(inside.reference_tension_N) + np.testing.assert_allclose( + inside.reference_law().stiffness_Nm2, at_reference.stiffness_Nm2, rtol=1e-12 + ) + np.testing.assert_allclose( + inside.reference_law().yield_curvature_1_m, + at_reference.yield_curvature_1_m, + rtol=1e-12, + ) + + def test_export_checks(iea66): args = {"tensions_N": [0.0, 2e4], "kappa_max_1_m": 1e-3, "n_points": 20} with pytest.raises(CableInputError, match="need slip_scale=True"): diff --git a/validation/validation_report.md b/validation/validation_report.md index 1c89707..3ef22aa 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: `1072 passed, 3111 deselected` -- independent_method: `70 passed, 4113 deselected` -- full_scale: `27 passed, 4156 deselected` +- analytical_sanity: `1074 passed, 3111 deselected` +- independent_method: `70 passed, 4115 deselected` +- full_scale: `27 passed, 4158 deselected` Run `pytest -m ` to reproduce each group.