From 39c1f819f51e3b9a3b9b9d6ed20fc0b055f2886d Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 19 Nov 2026 15:52:07 +0900 Subject: [PATCH 1/2] perf: fused fixed-fibre counting and one-pass stress field in compute_fatigue compute_fatigue counts every fixed fibre of a layer in one compiled pass (fast_rainflow.fibre_miner_damage): each fibre history is reduced to its turning points while it is formed from the field components, without branches, the reversal scan feeds the three-point stack directly, and one count serves the unit and the termination stress-range factor. The fibre histories are no longer formed in NumPy. The stress field of wire_stress_field is assembled in one compiled pass (fast_field.assemble_wire_field) with the operations of the NumPy expressions in the same order; without numba the NumPy path computes the local bending stress once instead of twice and no longer forms the per-wire copies of the axial and thermal stress. The direction-tied friction kernel keeps its bounds in place instead of allocating them at every sample. All damage is bit for bit equal to the previous build on the throughput workload (one-hour sea state, 66 kV template, every case) and in the suite; entries where the reference would raise are recomputed on the reference path in the order of the former loop. The sea-state batch has no upper limit on the worker count (the pool starts at most one worker per run); MAX_WORKERS is removed. validation/scripts/benchmark_throughput.py records the one-core throughput of the sea-state path, the damage differences from an earlier build and the batch time against the worker count; tests/test_fast_fatigue_path.py checks the fused path against the arithmetic it replaces. Signed-off-by: Jae Hoon Seo --- ARCHITECTURE.md | 12 +- CHANGELOG.md | 24 ++ doc/global_local_guide.md | 6 +- doc/local_analysis_guide.md | 11 +- release/check_coverage.py | 1 + src/cablexsec/analysis/fast_field.py | 151 +++++++++ src/cablexsec/analysis/fast_rainflow.py | 294 +++++++++++++++++ src/cablexsec/analysis/fatigue.py | 250 ++++++++++---- src/cablexsec/analysis/sea_state_batch.py | 14 +- src/cablexsec/cli.py | 4 +- src/cablexsec/mechanics/fast_slip.py | 86 +++-- tests/test_fast_fatigue_path.py | 346 ++++++++++++++++++++ tests/test_sea_state_batch.py | 11 +- validation/README.md | 1 + validation/scripts/benchmark_throughput.py | 359 +++++++++++++++++++++ 15 files changed, 1464 insertions(+), 106 deletions(-) create mode 100644 src/cablexsec/analysis/fast_field.py create mode 100644 tests/test_fast_fatigue_path.py create mode 100644 validation/scripts/benchmark_throughput.py diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index f88bb5e..0974976 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -151,6 +151,7 @@ Functional kernels operating on arrays; most are not called directly by users. | `sn_assessment.py` | `ComponentSCF` (axial, friction, normal and lateral bending factors, mean and dynamic) and the corrected Miner sum (`corrected_damage`, `corrected_damage_rows`): stress factor, mean-stress correction and thickness factor per rainflow cycle; used by the armour, conductor, sheath and tape routes | | `termination.py` | `TerminationSpec` and `termination_friction_increment`: anchored-wire clamp increment of the friction stress for a section near an end fitting or clamped stiffener root (`clamp_layer` solver along the principal, optionally also the minor, curvature direction, or `solver="along_wire"` with `stick`, `capstan` and `lateral_relief`; `curvature_field=` for a non-proportional field; far-field reference from the same discrete solver, so the sectional result is recovered away from the anchor) | | `fast_rainflow.py` | Compiled rainflow counting and Miner damage for many histories (see below) | +| `fast_field.py` | Compiled one-pass assembly of the fixed-fibre wire stress field of `wire_stress_field` (see below) | | `long_term.py` | `compute_long_term_fatigue`: probability- and duration-weighted damage at fixed fibres before hotspot selection | | `sea_state_batch.py` | `run_sea_state_batch`: CableDyn runs with probabilities to weighted annual damage and life per section (reader, `compute_fatigue` with optional clamp, thermal, fretting and user S-N options, `compute_long_term_fatigue`), optional capacity check of every section and run (`CapacityBatchCheck`); spawned workers with one thread each, JSON specification, manifest with input digests; console command `cablexsec-batch` ([doc/global_local_guide.md](doc/global_local_guide.md), stage 1) | | `critical_plane.py` | `compute_swt_cycle`: sampled SWT critical planes for one closed cycle at one point | @@ -303,8 +304,17 @@ kernels of their own, each with a reference path: `miner_rows` applies the same counter to the bulk Miner sums of `compute_fatigue` (including a termination stress-range factor) when `numba` is active; rows where the reference `miner_damage` would raise are - rerun on the reference path. `rainflow_counter="reference"` keeps the + rerun on the reference path. `fibre_miner_damage`, which `compute_fatigue` + uses, gives the same sums at every fixed fibre of a wire stress field + without forming the fibre histories: each history is reduced to its turning + points while it is formed (without branches), the reversal scan feeds the + three-point stack directly, and one count serves the unit and the + termination stress-range factor. `rainflow_counter="reference"` keeps the reference counter available. +- `analysis/fast_field.py` (`assemble_wire_field`) forms the mean, radial and + edge components of the wire stress field in one pass, with the operations + of the NumPy expressions it replaces in the same order (the trigonometric + factors are evaluated by NumPy and passed in), so the field is unchanged. `fast_rainflow.rainflow_table` returns the same cycles with their sample indices (range, mean, count, start, end) for the fretting module, which also diff --git a/CHANGELOG.md b/CHANGELOG.md index a038d82..001b549 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,12 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Added +- `validation/scripts/benchmark_throughput.py`: one-core throughput of sea-state fatigue on + the 66 kV template (direction-tied and distributed models, every wire or 12 positions, 4 or + 32 fibres), the damage differences from an earlier build, and the sea-state batch time + against the worker count. `tests/test_fast_fatigue_path.py` checks the fused counting and + field assembly against the arithmetic they replace (no wall-clock assertion). + - Reported rows SV11-SPLIT, SV11-REACH and SV11-EQ88: where the SV11 termination increment comes from. With the bellmouth curvature imposed uniformly from the end-fitting face the end-fitting anchor alone moves the SV11-PLANE median from 1.00 to 1.01 and SV11-GJ from 1.24 @@ -339,6 +345,24 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Changed +- `compute_fatigue` is 2.3–3.0 times faster on the direction-tied model, with every damage + value bit for bit unchanged. One-hour sea state on the 66 kV template (20 000 samples, both + armour layers, numba, one thread, `validation/scripts/benchmark_throughput.py`): all 284 + wires 0.88 s → 0.29 s (4 fibres) and 2.42 s → 0.90 s (32 fibres, 13.3 → 4.9 ns per fibre + sample); 12 positions per layer 0.068 s → 0.029 s. The fixed fibres of a layer are counted in + one compiled pass (`fast_rainflow.fibre_miner_damage`): each fibre history is reduced to its + turning points while it is formed, the reversal scan feeds the three-point stack directly, + and one count serves the unit and the termination stress-range factor; entries where the + reference sum would raise are recomputed on the reference path in the former order. The + stress field is assembled in one compiled pass (`fast_field.assemble_wire_field`, the NumPy + operations in the same order); without numba the NumPy path forms the local bending stress + once instead of twice. The distributed model is limited by its increment solver (22 s of + 23 s), as before. +- `SeaStateBatchOptions(workers=...)` and `cablexsec-batch --workers` have no upper limit + (`MAX_WORKERS` is removed); the pool starts at most one worker per run. On 48 one-hour runs + the batch takes 43.3, 23.5, 13.0 and 7.8 s with 1, 2, 4 and 8 workers; the remainder is the + start-up of each worker (about 2 s: imports and loading the compiled kernels). + - The rows that compare with the measured loops of Ménard and Cartraud (2023), BM1-loop, BM1-loop-uniform and BM1-ID, are stated, not gated (status INFO, the verdict against the registered target kept): the test is an unreliable reference. The benchmark register states the diff --git a/doc/global_local_guide.md b/doc/global_local_guide.md index 1ea5f15..1043dec 100644 --- a/doc/global_local_guide.md +++ b/doc/global_local_guide.md @@ -346,8 +346,10 @@ result.sections["sag"].long_term.annual_damage, result.sections["sag"].life_year the wider tolerance; a 10-column row gives no `GJ` and is not compared. A mismatch stops the batch unless `allow_property_mismatch=True` is declared, and the comparison is written to the manifest either way. -- Workers: `workers` processes (at most `MAX_WORKERS = 8`), one numerical - thread each, spawned; results do not depend on the worker count. +- Workers: `workers` processes, one numerical thread each, spawned, at most + one per run; there is no upper limit, so choose the count for the machine + (the runs are independent and the batch scales with the worker count while + there are runs for every worker). Results do not depend on the worker count. - Output folder (must not exist): `manifest.json` (SHA-256 of every CableDyn file and deck, the cable definition and YAML file, options, property check, reader checks per run, results, and `inputs_sha256` over all of them); diff --git a/doc/local_analysis_guide.md b/doc/local_analysis_guide.md index dd5dda0..b920829 100644 --- a/doc/local_analysis_guide.md +++ b/doc/local_analysis_guide.md @@ -1532,10 +1532,13 @@ histories. On one thread the Step 3 path takes 0.76 s per section-hour for 118 wires × 32 fibres and 42 001 samples (600 s initialisation plus a 3600 s retained hour); `parallel=True` spreads wires over threads. -`compute_fatigue` uses the compiled slip kernel and, through -`fast_rainflow.miner_rows`, the compiled counter for each fibre; its damage is -bitwise equal to the reference counter, still available with -`rainflow_counter="reference"`. +`compute_fatigue` uses the compiled slip kernel, assembles the stress field in +one compiled pass (`fast_field.assemble_wire_field`) and counts every fixed +fibre with `fast_rainflow.fibre_miner_damage`, the compiled counter applied to +each fibre history as it is formed; its damage is bitwise equal to the +reference counter, still available with `rainflow_counter="reference"`. +`validation/scripts/benchmark_throughput.py` records the one-core throughput +of this route on a one-hour sea state of the 66 kV template. The pure-Python routines remain the reference implementation. `tests/test_fast_slip.py` and `tests/test_fast_rainflow.py` require the diff --git a/release/check_coverage.py b/release/check_coverage.py index 9dce36f..8080e4e 100644 --- a/release/check_coverage.py +++ b/release/check_coverage.py @@ -26,6 +26,7 @@ "tests/test_fast_rainflow.py", "tests/test_fast_slip.py", "tests/test_compiled_counter.py", + "tests/test_fast_fatigue_path.py", "tests/test_progressive_friction.py", "tests/test_fretting_regime.py", "tests/test_strand_slip.py", diff --git a/src/cablexsec/analysis/fast_field.py b/src/cablexsec/analysis/fast_field.py new file mode 100644 index 0000000..5fd62e3 --- /dev/null +++ b/src/cablexsec/analysis/fast_field.py @@ -0,0 +1,151 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Compiled assembly of the fixed-fibre wire stress field. + +:func:`assemble_wire_field` forms the three components of +:class:`cablexsec.analysis.fatigue.WireStressField` (``mean_Pa``, +``radial_Pa``, ``tangential_Pa``) from the friction stress, the per-sample +axial and thermal stress and the curvature history in one pass, with the +arithmetic of the NumPy expressions it replaces, operation for operation: +the local bending stress of +:func:`cablexsec.mechanics.wire_stress.local_bending_fibre_stress` at the +outward radial fibre and at the edge (fibre angle ``pi/2``), the outward +total ``((sigma_A + sigma_B) + sigma_f) + sigma_T`` plus any termination +increment, and ``mean = outward - radial``. The trigonometric factors are +evaluated by NumPy, as in the reference expressions, and passed in. The +results are equal to the NumPy path bit for bit +(``tests/test_fast_fatigue_path.py``). + +Without numba (or with ``CABLEXSEC_DISABLE_NUMBA=1``) the NumPy expressions +are used instead (see :mod:`cablexsec._numba`). +""" + +from __future__ import annotations + +import math + +import numpy as np +from numpy.typing import NDArray + +from cablexsec._numba import HAVE_NUMBA, njit + +__all__ = ["HAVE_NUMBA", "assemble_wire_field"] + +FloatArray = NDArray[np.float64] + + +@njit(cache=True) +def _assemble_kernel( + kx: FloatArray, + ky: FloatArray, + cos_phi: FloatArray, + sin_phi: FloatArray, + coef_radial: FloatArray, + coef_edge: FloatArray, + c_radial: float, + c_tangential: float, + cos_outward: float, + sin_outward: float, + cos_edge: float, + sin_edge: float, + axial: FloatArray, + friction: FloatArray, + thermal: FloatArray, + extra: FloatArray, + has_extra: bool, +) -> tuple[FloatArray, FloatArray, FloatArray]: + n_w, n_t = friction.shape + mean = np.empty((n_w, n_t)) + radial = np.empty((n_w, n_t)) + edge = np.empty((n_w, n_t)) + for w in range(n_w): + cp = cos_phi[w] + sp = sin_phi[w] + for i in range(n_t): + x = kx[i] + y = ky[i] + rb = c_radial * (x * cp + y * sp) + tb = c_tangential * ((-x) * sp + y * cp) + sb = coef_radial[i] * (rb * cos_outward + tb * sin_outward) + out = ((axial[i] + sb) + friction[w, i]) + thermal[i] + if has_extra: + out = out + extra[w, i] + radial[w, i] = sb + edge[w, i] = coef_edge[i] * (rb * cos_edge + tb * sin_edge) + mean[w, i] = out - sb + return mean, radial, edge + + +def assemble_wire_field( + kappa_x: FloatArray, + kappa_y: FloatArray, + phi: FloatArray, + modulus_Pa: float | FloatArray, + depth_m: float, + width_m: float, + lay_angle_rad: float, + axial_Pa: FloatArray, + friction_Pa: FloatArray, + thermal_Pa: FloatArray, + extra_Pa: FloatArray | None = None, +) -> tuple[FloatArray, FloatArray, FloatArray]: + """``(mean, radial, tangential)`` of the wire stress field [Pa]. + + Equal bit for bit to the NumPy expressions :: + + radial = local_bending_fibre_stress(kx, ky, phi[:, None], E, depth, a) + tangential = local_bending_fibre_stress( + kx, ky, phi[:, None], E, width, a, pi / 2 + ) + outward = axial[None, :] + radial + friction + thermal[None, :] + outward = outward + extra # when given + mean = outward - radial + + ``modulus_Pa`` is a constant or one value per sample; ``axial_Pa`` and + ``thermal_Pa`` hold one value per sample, ``friction_Pa`` and + ``extra_Pa`` one row per wire. + """ + kx = np.ascontiguousarray(kappa_x, dtype=np.float64) + ky = np.ascontiguousarray(kappa_y, dtype=np.float64) + friction = np.ascontiguousarray(friction_Pa, dtype=np.float64) + n_t = kx.size + angle = np.asarray(phi, dtype=np.float64)[:, None] + cos_phi = np.ascontiguousarray(np.cos(angle)[:, 0]) + sin_phi = np.ascontiguousarray(np.sin(angle)[:, 0]) + # Factors exactly as local_bending_fibre_stress forms them. + c, s = math.cos(lay_angle_rad), math.sin(lay_angle_rad) + c_radial = c * c * math.cos(2 * lay_angle_rad) + c_tangential = c * (1 + s * s) + modulus = np.asarray(modulus_Pa) + coef_radial = np.ascontiguousarray( + np.broadcast_to(modulus * depth_m / 2, (n_t,)), dtype=np.float64 + ) + coef_edge = np.ascontiguousarray( + np.broadcast_to(modulus * width_m / 2, (n_t,)), dtype=np.float64 + ) + outward_theta = np.asarray(0.0) + edge_theta = np.asarray(math.pi / 2) + extra = ( + np.zeros((0, 0)) + if extra_Pa is None + else np.ascontiguousarray(extra_Pa, dtype=np.float64) + ) + return _assemble_kernel( + kx, + ky, + cos_phi, + sin_phi, + coef_radial, + coef_edge, + c_radial, + c_tangential, + float(np.cos(outward_theta)), + float(np.sin(outward_theta)), + float(np.cos(edge_theta)), + float(np.sin(edge_theta)), + np.ascontiguousarray(axial_Pa, dtype=np.float64), + friction, + np.ascontiguousarray(thermal_Pa, dtype=np.float64), + extra, + extra_Pa is not None, + ) diff --git a/src/cablexsec/analysis/fast_rainflow.py b/src/cablexsec/analysis/fast_rainflow.py index 5769b7a..2fb66dc 100644 --- a/src/cablexsec/analysis/fast_rainflow.py +++ b/src/cablexsec/analysis/fast_rainflow.py @@ -29,11 +29,17 @@ stress-range factor, and flags any row for which the reference would raise (non-finite or non-positive amplified range, S-N life outside floating-point range) so that the caller can rerun it on the reference path. + +:func:`fibre_miner_damage` gives the same sums at every fixed fibre of a +(wire, time) stress field without forming the fibre histories: each history +is reduced to its turning points while it is formed from the field +components, and one count serves every stress-range factor. """ from __future__ import annotations import math +from collections.abc import Sequence from typing import TYPE_CHECKING import numpy as np @@ -48,6 +54,7 @@ "HAVE_NUMBA", "fatigue_rows", "fibre_fatigue", + "fibre_miner_damage", "miner_rows", "rainflow_table", ] @@ -522,6 +529,293 @@ def miner_rows( return damage, (flags != 0.0) | ~np.isfinite(damage) +# --------------------------------------------------------------------------- # +# Fused fixed-fibre Miner damage (compute_fatigue) # +# --------------------------------------------------------------------------- # +@njit(cache=True) +def _cycle_damage( + span: float, + factor: float, + m1: float, + log_c1: float, + m2: float, + log_c2: float, + knee: float, + threshold: float, +) -> tuple[float, bool]: + """``(1 / life, flag)`` of one counted range, as :func:`_add_cycle`. + + The range is scaled as ``span / 1e6 * factor``; the flag marks where the + reference Miner sum raises (see :func:`_add_cycle`). + """ + stress = span / 1.0e6 * factor + life = _cycles_to_failure(stress, m1, log_c1, m2, log_c2, knee, threshold) + thresholded = threshold >= 0.0 and stress <= threshold + flag = not (0.0 < stress < math.inf) or not (thresholded or 0.0 < life < math.inf) + return life, flag + + +@njit(cache=True) +def _count_turning_points( + red: FloatArray, + k: int, + stack: FloatArray, + factor0: float, + factor1: float, + two: bool, + out: FloatArray, + m1: float, + log_c1: float, + m2: float, + log_c2: float, + knee: float, + threshold: float, +) -> None: + """Steps 2 and 3 of :func:`_count_one` on the turning points ``red[:k]``. + + The reversal scan feeds the three-point stack directly, point by point, + and the Miner sums of one or two range factors are accumulated in cycle + order: ``out = (damage0, damage1, flag0, flag1)``. ``k >= 2``. + """ + d0 = 0.0 + d1 = 0.0 + g0 = False + g1 = False + head = 0 + top = 0 + x = red[1] + d_last = x - red[0] + x_next = x + for j in range(1, k + 1): + # The reversal scan: red[0], the reversals of red[1:k-1], red[k-1]. + if j == 1: + value = red[0] + elif j < k: + x_next = red[j] + if x_next == x: + continue + d_next = x_next - x + reversal = d_last * d_next < 0 + value = x + x = x_next + d_last = d_next + if not reversal: + continue + else: + value = x_next + stack[top] = value + top += 1 + while top - head >= 3: + x1 = stack[top - 3] + x2 = stack[top - 2] + x3 = stack[top - 1] + if abs(x3 - x2) < abs(x2 - x1): + break + if top - head == 3: + span = abs(stack[head] - stack[head + 1]) + count = 0.5 + head += 1 + else: + span = abs(x1 - x2) + count = 1.0 + top -= 3 + stack[top] = x3 + top += 1 + if span > 0: + life, flag = _cycle_damage( + span, factor0, m1, log_c1, m2, log_c2, knee, threshold + ) + g0 = g0 or flag + d0 += count / life + if two: + life, flag = _cycle_damage( + span, factor1, m1, log_c1, m2, log_c2, knee, threshold + ) + g1 = g1 or flag + d1 += count / life + while top - head > 1: + span = abs(stack[head] - stack[head + 1]) + if span > 0: + life, flag = _cycle_damage( + span, factor0, m1, log_c1, m2, log_c2, knee, threshold + ) + g0 = g0 or flag + d0 += 0.5 / life + if two: + life, flag = _cycle_damage( + span, factor1, m1, log_c1, m2, log_c2, knee, threshold + ) + g1 = g1 or flag + d1 += 0.5 / life + head += 1 + out[0] = d0 + out[1] = d1 + out[2] = 1.0 if g0 else 0.0 + out[3] = 1.0 if g1 else 0.0 + + +@njit(cache=True) +def _fibre_miner_kernel( + mean: FloatArray, + radial: FloatArray, + tangential: FloatArray, + normal_offsets: FloatArray, + lateral_offsets: FloatArray, + start: int, + factor0: float, + factor1: float, + two: bool, + m1: float, + log_c1: float, + m2: float, + log_c2: float, + knee: float, + threshold: float, +) -> tuple[FloatArray, FloatArray]: + """Miner damage of every (factor, wire, fibre) without forming histories. + + The fibre stress ``(mean + radial n) + tangential l`` (the arithmetic of + :meth:`WireStressField.at_fibre`) of samples ``start:`` is reduced to its + plateau-preserving turning points while it is formed (step 1 of + :func:`_count_one`, without branches), then counted by + :func:`_count_turning_points`. ``n_t - start >= 2``. + """ + n_w, n_t = mean.shape + n_f = normal_offsets.size + damage = np.zeros((2, n_w, n_f)) + flags = np.zeros((2, n_w, n_f)) + red = np.empty(n_t - start + 1) + stack = np.empty(n_t - start + 1) + out = np.zeros(4) + for w in range(n_w): + mw = mean[w] + rw = radial[w] + tw = tangential[w] + # Largest component magnitudes (NaN gives inf): a fibre whose bound is + # not finite may hold a non-finite sample and is left to the reference. + big_m = 0.0 + big_r = 0.0 + big_t = 0.0 + for i in range(start, n_t): + a = abs(mw[i]) + if not a <= big_m: + big_m = a if a == a else math.inf + a = abs(rw[i]) + if not a <= big_r: + big_r = a if a == a else math.inf + a = abs(tw[i]) + if not a <= big_t: + big_t = a if a == a else math.inf + for f in range(n_f): + c = normal_offsets[f] + sl = lateral_offsets[f] + unsafe = not big_m + big_r * abs(c) + big_t * abs(sl) < 1.0e300 + prev = mw[start] + rw[start] * c + tw[start] * sl + red[0] = prev + k = np.int64(1) + rising_before = np.int64(0) + changed = np.int64(0) + for i in range(start + 1, n_t): + x = mw[i] + rw[i] * c + tw[i] * sl + moved = np.int64(x != prev) + rising = np.int64(x > prev) + # A turning point at the previous sample: the record moved, + # it had moved before, and the direction changed. + red[k] = prev + k += moved & changed & (rising ^ rising_before) + rising_before = (rising_before & (1 - moved)) | (rising & moved) + changed |= moved + prev = x + red[k] = prev + k += 1 + # A record that never moves gives one zero range, which is skipped. + _count_turning_points( + red, + int(k), + stack, + factor0, + factor1, + two, + out, + m1, + log_c1, + m2, + log_c2, + knee, + threshold, + ) + damage[0, w, f] = out[0] + damage[1, w, f] = out[1] + flags[0, w, f] = 1.0 if unsafe or out[2] != 0.0 else 0.0 + flags[1, w, f] = 1.0 if unsafe or out[3] != 0.0 else 0.0 + return damage, flags + + +def fibre_miner_damage( + mean_Pa: FloatArray, + radial_Pa: FloatArray, + tangential_Pa: FloatArray, + normal_offsets: FloatArray, + lateral_offsets: FloatArray, + sn_curve: SNcurve, + stress_range_factors: Sequence[float], + *, + start: int = 0, +) -> tuple[FloatArray, NDArray[np.bool_]]: + """Miner damage at fixed fibres, shape (factor, wire, fibre), and rerun flags. + + The history of fibre ``f`` of wire ``w`` is + ``(mean + radial * normal_offsets[f]) + tangential * lateral_offsets[f]`` + over samples ``start:``, the arithmetic of + :meth:`cablexsec.analysis.fatigue.WireStressField.at_fibre`; it is counted + as :func:`miner_rows` counts that history with each of the one or two + stress-range factors, cycle for cycle and in the same summation order, + without forming it, and one count serves both factors. Flagged entries + (and entries with a non-finite total) must be recomputed on the + reference path, as for :func:`miner_rows`. Inputs are assumed validated + (matching two-dimensional components, curve in MPa, finite positive + factors). + """ + arrays = [ + np.ascontiguousarray(a, dtype=np.float64) + for a in (mean_Pa, radial_Pa, tangential_Pa) + ] + if arrays[0].ndim != 2 or any(a.shape != arrays[0].shape for a in arrays): + raise ValueError("matching two-dimensional stress components required") + normal = np.ascontiguousarray(normal_offsets, dtype=np.float64) + lateral = np.ascontiguousarray(lateral_offsets, dtype=np.float64) + if normal.ndim != 1 or lateral.shape != normal.shape: + raise ValueError("one normal and one lateral offset per fibre required") + factors = [float(value) for value in stress_range_factors] + if len(factors) not in (1, 2): + raise ValueError("one or two stress-range factors required") + if not 0 <= start <= arrays[0].shape[1] - 2: + raise ValueError("at least two samples from start are required") + params = _curve_parameters(sn_curve) + mean, radial, tangential = arrays + two = len(factors) == 2 + rows = slice(0, 2 if two else 1) + try: + damage, flags = _fibre_miner_kernel( + mean, + radial, + tangential, + normal, + lateral, + int(start), + factors[0], + factors[-1], + two, + *params, + ) + except (ZeroDivisionError, OverflowError): + # Interpreted kernels raise where compiled arithmetic gives 0 or inf. + shape = (len(factors), mean.shape[0], normal.size) + return np.zeros(shape), np.ones(shape, dtype=np.bool_) + damage = damage[rows] + return damage, (flags[rows] != 0.0) | ~np.isfinite(damage) + + # --------------------------------------------------------------------------- # # Cycle table with sample indices (fretting regime assessment) # # --------------------------------------------------------------------------- # diff --git a/src/cablexsec/analysis/fatigue.py b/src/cablexsec/analysis/fatigue.py index 5a2a484..a31e07f 100644 --- a/src/cablexsec/analysis/fatigue.py +++ b/src/cablexsec/analysis/fatigue.py @@ -61,14 +61,15 @@ import warnings from collections.abc import Iterator, Mapping, Sequence from dataclasses import dataclass, field -from typing import Literal +from typing import Any, Literal, NamedTuple import numpy as np import rainflow from numpy.typing import NDArray from cablexsec._numba import HAVE_NUMBA -from cablexsec.analysis.fast_rainflow import miner_rows +from cablexsec.analysis.fast_field import assemble_wire_field +from cablexsec.analysis.fast_rainflow import fibre_miner_damage, miner_rows from cablexsec.analysis.fretting_swt import ( PartialSlipCycles, swt_driver_from_contact, @@ -131,6 +132,7 @@ # attributes, so that tests can force the reference paths). _FAST_SLIP = HAVE_NUMBA _FAST_RAINFLOW = HAVE_NUMBA +_FAST_FIELD = HAVE_NUMBA RainflowCounter = Literal["auto", "compiled", "reference"] FrictionModel = Literal["auto", "direction_tied", "distributed", "progressive"] @@ -724,6 +726,58 @@ class FatigueResult: # Stress time series per wire (consumes the frozen core) # # --------------------------------------------------------------------------- # def _wire_stress_series( + layer: FatigueLayer, + kappa_x: FloatArray, + kappa_y: FloatArray, + tension_N: FloatArray | None, + EA_full_N: float | None, + thermal_stress_Pa: FloatArray | None, + contact_pressure_Pa: FloatArray | None, + *, + wire_modulus_Pa: FloatArray | None = None, + wires: IntArray | None = None, + **options: Any, +) -> FloatArray: + """``sigma_total(phi_k, t)`` at the outward radial fibre of every wire [Pa]. + + Shape ``(n_wires, n_steps)``; ``sigma_total = sigma_A + sigma_B + sigma_f + + sigma_T`` with the parts of :func:`_wire_stress_parts` (same options) + and the local bending stress at the outer face (``t/2`` for a + rectangular or profiled wire, gap G1). + """ + parts = _wire_stress_parts( + layer, + kappa_x, + kappa_y, + tension_N, + EA_full_N, + thermal_stress_Pa, + contact_pressure_Pa, + wire_modulus_Pa=wire_modulus_Pa, + wires=wires, + **options, + ) + spec = layer.spec + phi = spec.phi_wires if wires is None else spec.phi_wires[wires] + d_wire = ( + 2.0 * math.sqrt(spec.A_wire_m2 / math.pi) + if spec.section is None + else 2.0 * spec.section.half_thickness_m + ) + sigma_B_kt = local_bending_fibre_stress( + kappa_x, + kappa_y, + phi[:, None], + spec.E_wire_Pa if wire_modulus_Pa is None else wire_modulus_Pa, + d_wire, + spec.lay_angle_rad, + ) + return np.asarray( + parts.axial[None, :] + sigma_B_kt + parts.friction + parts.thermal[None, :] + ) + + +def _wire_stress_parts( layer: FatigueLayer, kappa_x: FloatArray, kappa_y: FloatArray, @@ -746,8 +800,8 @@ def _wire_stress_series( time_s: FloatArray | None = None, distributed_bound: DistributedBound = "signed", wires: IntArray | None = None, -) -> FloatArray: - """Build ``sigma_total(phi_k, t)`` for every wire of one layer [Pa]. +) -> _StressParts: + """Friction, axial and thermal parts of ``sigma_total(phi_k, t)`` [Pa]. ``wires`` (indices) builds those rows only, in that order, equal to the same rows of the full field: the direction-tied kernel evaluates only @@ -759,7 +813,10 @@ def _wire_stress_series( the direction-tied and distributed kernels; the progressive law refuses a non-neutral law. - Shape ``(n_wires, n_steps)``. ``sigma_total = sigma_A + sigma_B + sigma_f``. + ``sigma_total = sigma_A + sigma_B + sigma_f + sigma_T``: the friction + stress has shape ``(n_wires, n_steps)``; ``sigma_A`` and ``sigma_T`` are + the same for every wire and are returned once per sample. + :func:`wire_stress_field` adds the local bending stress ``sigma_B``. Curvatures are axial-strain-gradient components, not rotation-curvature components. A prescribed axial_strain is the stress-driving uniaxial strain, an alternative to true material force/EA, not geometric total @@ -798,29 +855,9 @@ def _wire_stress_series( "axial strain must be finite and match curvature histories" ) _validate_tension(tension_N, EA_full_N, kappa_x.shape) - phi = spec.phi_wires # (n_wires,) - if wires is not None: - phi = phi[wires] n_steps = kappa_x.size a = spec.lay_angle_rad - # Outward radial-fibre stress is retained by this helper. The fatigue - # driver adds the other fixed circumference fibres after solving slip once. - # A rectangular or profiled wire (gap G1) has its outer face at t/2. - d_wire = ( - 2.0 * math.sqrt(spec.A_wire_m2 / math.pi) - if spec.section is None - else 2.0 * spec.section.half_thickness_m - ) - sigma_B_kt = local_bending_fibre_stress( - kappa_x, - kappa_y, - phi[:, None], - spec.E_wire_Pa if wire_modulus_Pa is None else wire_modulus_Pa, - d_wire, - a, - ) - friction_model, _reason = _resolve_friction_model( # type: ignore[assignment] friction_model, spec, @@ -907,25 +944,35 @@ def _wire_stress_series( if wires is not None and not wires_done: sigma_f_kt = np.ascontiguousarray(sigma_f_kt[wires]) # sigma_A (tension) — [Nasution2014b] Eq. 5: sigma_A = E cos^2 a * N / EA_full. - sigma_A_kt = np.zeros((phi.size, n_steps), dtype=np.float64) + # The same for every wire: one value per sample, accumulated in the order + # of the terms. + sigma_A_t = np.zeros(n_steps, dtype=np.float64) if normal_stress_Pa is not None: - sigma_A_kt += np.asarray(normal_stress_Pa)[None, :] + sigma_A_t += np.asarray(normal_stress_Pa) if axial_strain is not None: e_ax = layer.E_eff_axial_Pa or spec.E_wire_Pa - sigma_A_kt += (e_ax * math.cos(a) ** 2 * axial_strain)[None, :] + sigma_A_t += e_ax * math.cos(a) ** 2 * axial_strain if tension_N is not None: assert EA_full_N is not None # validated before stress recovery e_ax = layer.E_eff_axial_Pa or spec.E_wire_Pa - sigma_A_t = e_ax * math.cos(a) ** 2 * np.asarray(tension_N) / EA_full_N - sigma_A_kt += sigma_A_t[None, :] + sigma_A_t += e_ax * math.cos(a) ** 2 * np.asarray(tension_N) / EA_full_N - sigma_T_kt = np.zeros((phi.size, n_steps), dtype=np.float64) + sigma_T_t = np.zeros(n_steps, dtype=np.float64) if thermal_stress_Pa is not None: - sigma_T_kt += np.asarray(thermal_stress_Pa, dtype=np.float64)[None, :] + sigma_T_t += np.asarray(thermal_stress_Pa, dtype=np.float64) + sigma_f_kt = np.asarray(sigma_f_kt, dtype=np.float64) if friction_out is not None: - friction_out.append(np.asarray(sigma_f_kt, dtype=np.float64)) - return np.asarray(sigma_A_kt + sigma_B_kt + sigma_f_kt + sigma_T_kt) + friction_out.append(sigma_f_kt) + return _StressParts(sigma_f_kt, sigma_A_t, sigma_T_t) + + +class _StressParts(NamedTuple): + """Parts of the wire stress from :func:`_wire_stress_parts` [Pa].""" + + friction: FloatArray # (wire, sample) + axial: FloatArray # (sample,), the same for every wire + thermal: FloatArray # (sample,), the same for every wire @dataclass(frozen=True) @@ -1193,7 +1240,7 @@ def wire_stress_field( layer, spec=dataclasses.replace(layer.spec, shape_g=relieved) ) friction_parts: list[FloatArray] | None = [] if keep_friction else None - outward = _wire_stress_series( + parts = _wire_stress_parts( layer, kx, ky, @@ -1218,6 +1265,7 @@ def wire_stress_field( ) spec = layer.spec increment = None + extra = None if termination is not None: if not isinstance(termination, TerminationSpec): raise CableInputError("termination must be a TerminationSpec or None") @@ -1234,7 +1282,7 @@ def wire_stress_field( increment, stress_Pa=np.ascontiguousarray(increment.stress_Pa[wires]) ) if increment.applied: - outward = outward + increment.stress_Pa + extra = increment.stress_Pa if friction_parts: friction_parts[0] = friction_parts[0] + increment.stress_Pa friction = friction_parts[0] if friction_parts else None @@ -1246,24 +1294,47 @@ def wire_stress_field( depth = 2 * spec.section.half_thickness_m width = 2 * spec.section.half_width_m phi_eval = spec.phi_wires if wires is None else spec.phi_wires[wires] - radial = local_bending_fibre_stress( - kx, - ky, - phi_eval[:, None], - modulus, - depth, - spec.lay_angle_rad, - ) - tangential = local_bending_fibre_stress( - kx, - ky, - phi_eval[:, None], - modulus, - width, - spec.lay_angle_rad, - math.pi / 2, - ) - mean = outward - radial + if _FAST_FIELD: + # One compiled pass, equal bit for bit to the expressions below. + mean, radial, tangential = assemble_wire_field( + kx, + ky, + phi_eval, + modulus, + depth, + width, + spec.lay_angle_rad, + parts.axial, + parts.friction, + parts.thermal, + extra, + ) + else: + # Outward radial fibre (y_n = t/2) and edge (y_l = b/2); a rectangular + # or profiled wire (gap G1) has its outer face at t/2. + radial = local_bending_fibre_stress( + kx, + ky, + phi_eval[:, None], + modulus, + depth, + spec.lay_angle_rad, + ) + tangential = local_bending_fibre_stress( + kx, + ky, + phi_eval[:, None], + modulus, + width, + spec.lay_angle_rad, + math.pi / 2, + ) + outward = ( + parts.axial[None, :] + radial + parts.friction + parts.thermal[None, :] + ) + if extra is not None: + outward = outward + extra + mean = outward - radial if transverse is None: return WireStressField( mean, radial, tangential, increment, spec.section, friction_Pa=friction @@ -1436,6 +1507,53 @@ def _contact_force_histories( # --------------------------------------------------------------------------- # # Full pipeline # # --------------------------------------------------------------------------- # +def _fused_fibre_damage( + field: WireStressField, + fibre_angles: NDArray[np.floating[Any]], + count_from: int, + layer: FatigueLayer, + amplify: bool, + fibre_damage: FloatArray, + amplified_damage: FloatArray, +) -> None: + """Fill the fibre damage of :func:`compute_fatigue` in one compiled pass. + + Equal, entry for entry, to the reference loop: :func:`_miner_damage_rows` + with the compiled counter on ``field.at_fibre(theta)[:, count_from:]`` + for the unit factor and, with ``amplify``, the termination SCF + (:func:`~cablexsec.analysis.fast_rainflow.fibre_miner_damage`). Entries + where the reference would raise are recomputed on the reference path in + the order of that loop, so errors are identical as well. + """ + offsets = np.array( + [field.fibre_offsets(float(theta)) for theta in fibre_angles], + dtype=np.float64, + ).reshape(-1, 2) + factors = [1.0, layer.SCF] if amplify else [1.0] + damage, rerun = fibre_miner_damage( + field.mean_Pa, + field.radial_Pa, + field.tangential_Pa, + offsets[:, 0], + offsets[:, 1], + layer.sn_bulk, + factors, + start=count_from, + ) + for j in np.flatnonzero(rerun.any(axis=(0, 1))): + history = field.at_fibre(float(fibre_angles[j]))[:, count_from:] + for q, factor in enumerate(factors): + for k in np.flatnonzero(rerun[q, :, j]): + damage[q, k, j] = miner_damage( + history[k], + layer.sn_bulk, + layer.sigma_UTS_Pa, + stress_range_factor=float(factor), + ) + fibre_damage[:] = damage[0] + amplified_damage[:] = damage[1] if amplify else damage[0] + + def compute_fatigue( layers: list[FatigueLayer], kappa_x: FloatArray, @@ -1841,7 +1959,6 @@ def compute_fatigue( wires = selected[name] rows = np.arange(spec.n_wires, dtype=np.int64) if wires is None else wires n_eval = rows.size - sigma_kt = field.at_fibre(0.0) fibre_damage = np.empty((n_eval, n_fibres)) amplified_damage = np.empty_like(fibre_damage) corrected = needs_correction( @@ -1852,7 +1969,20 @@ def compute_fatigue( if spec.section is None else 2.0 * spec.section.half_thickness_m ) - for j, theta in enumerate(fibre_angles): + amplify = layer.termination and layer.SCF != 1.0 + # Compiled counter, uncorrected curve: every fibre in one fused pass. + fused = not corrected and compiled + if fused: + _fused_fibre_damage( + field, + fibre_angles, + count_from, + layer, + amplify, + fibre_damage, + amplified_damage, + ) + for j, theta in enumerate(() if fused else fibre_angles): if not corrected: history = field.at_fibre(theta) if count_from: @@ -1864,7 +1994,7 @@ def compute_fatigue( _miner_damage_rows( history, layer.sn_bulk, layer.sigma_UTS_Pa, layer.SCF, compiled ) - if layer.termination and layer.SCF != 1.0 + if amplify else fibre_damage[:, j] ) continue @@ -1894,7 +2024,7 @@ def compute_fatigue( thickness_m=thickness, compiled=compiled, ) - if layer.termination and layer.SCF != 1.0 + if amplify else fibre_damage[:, j] ) critical_indices = np.argmax(fibre_damage, axis=1) @@ -1947,7 +2077,7 @@ def compute_fatigue( ).damage elif layer.swt_const is not None and layer.contact_p0_Pa > 0.0: # Legacy copper estimate: every bulk-stress cycle at gross sliding. - n_cycles = _cycle_count(sigma_kt) + n_cycles = _cycle_count(field.at_fibre(0.0)) g = ( np.ones(spec.n_wires) if layer.contact_shape_g is None @@ -1966,7 +2096,7 @@ def compute_fatigue( df[k] = float(n_cycles[k]) / n_f elif layer.sn_fretting is not None and layer.K_t_contact_N_per_m > 0.0: # Custom steel slip-amplitude curve, when explicitly supplied. - n_cycles = _cycle_count(sigma_kt) + n_cycles = _cycle_count(field.at_fibre(0.0)) delta_star_um = _fretting_amplitudes_um( layer, kx, diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index fcced0b..9e48045 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -38,9 +38,10 @@ Parallel execution ------------------ -Runs are processed in worker processes (``workers``, at most -:data:`MAX_WORKERS`), each limited to one numerical thread. Results do not -depend on the worker count. The output directory, if given, must not exist: +Runs are processed in worker processes (``workers``; the pool holds at most +one worker per run), each limited to one numerical thread. The worker count +has no upper limit here: choose it for the machine. Results do not depend on +the worker count. The output directory, if given, must not exist: results are written once, with a manifest of SHA-256 digests of every input file, the cable definition and the options. """ @@ -100,8 +101,6 @@ FloatArray = NDArray[np.float64] TensionBasis = Literal["auto", "true", "effective"] -#: Hard cap on worker processes of one batch. -MAX_WORKERS = 8 _THREAD_VARIABLES = ( "OMP_NUM_THREADS", "OPENBLAS_NUM_THREADS", @@ -111,7 +110,6 @@ ) __all__ = [ - "MAX_WORKERS", "CapacityBatchCheck", "SeaStateBatchOptions", "SeaStateBatchResult", @@ -230,9 +228,9 @@ def __post_init__(self) -> None: if ( isinstance(self.workers, bool) or not isinstance(self.workers, int) - or not 1 <= self.workers <= MAX_WORKERS + or self.workers < 1 ): - raise CableInputError(f"workers must be an integer in [1, {MAX_WORKERS}]") + raise CableInputError("workers must be a positive integer") if self.tension_basis not in ("auto", "true", "effective"): raise CableInputError("tension_basis must be auto, true or effective") if self.external_diameter_m is not None and not ( diff --git a/src/cablexsec/cli.py b/src/cablexsec/cli.py index b6e1a8a..b9cf33d 100644 --- a/src/cablexsec/cli.py +++ b/src/cablexsec/cli.py @@ -41,7 +41,6 @@ def batch_main(argv: list[str] | None = None) -> int: os.environ.setdefault(name, "1") from cablexsec.analysis.sea_state_batch import ( - MAX_WORKERS, load_batch_spec, run_sea_state_batch, ) @@ -56,7 +55,8 @@ def batch_main(argv: list[str] | None = None) -> int: parser.add_argument( "--workers", type=int, - help=f"worker processes (1 to {MAX_WORKERS}); overrides the specification", + help="worker processes (at least 1, one thread each; at most one per run " + "is started); overrides the specification", ) args = parser.parse_args(argv) cable, runs, sections, options, cable_path = load_batch_spec(args.spec) diff --git a/src/cablexsec/mechanics/fast_slip.py b/src/cablexsec/mechanics/fast_slip.py index bb8f16e..beb788c 100644 --- a/src/cablexsec/mechanics/fast_slip.py +++ b/src/cablexsec/mechanics/fast_slip.py @@ -65,14 +65,38 @@ def _cap( mu: float, g: FloatArray, ) -> FloatArray: + """Bounds of every wire, rows (tension, compression); see :func:`_cap_into`.""" + out = np.zeros((2, phi.size)) + _cap_into(phi, angle, pressure, r_helix, n_wires, area, lay_angle, mu, g, out) + return out + + +@njit(cache=True) +def _cap_into( + phi: FloatArray, + angle: float, + pressure: float, + r_helix: float, + n_wires: int, + area: float, + lay_angle: float, + mu: float, + g: FloatArray, + out: FloatArray, +) -> None: # Row 0: tension bound sigma0 g expm1(lam psi); row 1: compression bound # sigma0 g (1 - exp(-lam psi)) (capstan on the wire's own force). - out = np.zeros((2, phi.size)) if pressure <= 0.0: - return out + for w in range(phi.size): + out[0, w] = 0.0 + out[1, w] = 0.0 + return sin_a = abs(math.sin(lay_angle)) if sin_a < 1.0e-12: - return out + for w in range(phi.size): + out[0, w] = 0.0 + out[1, w] = 0.0 + return width = 2.0 * math.pi * r_helix / n_wires sigma0 = r_helix * pressure * width * math.cos(lay_angle) / (area * sin_a**2) for w in range(phi.size): @@ -82,7 +106,6 @@ def _cap( psi = math.asin(c) out[0, w] = sigma0 * g[w] * math.expm1(mu * sin_a * psi) out[1, w] = -sigma0 * g[w] * math.expm1(-mu * sin_a * psi) - return out @njit(cache=True) @@ -102,7 +125,9 @@ def _stress_kernel( n_total: int, ) -> FloatArray: # phi and g hold the evaluated wires; n_total is the layer's wire count, - # which sets the tributary width of each wire. + # which sets the tributary width of each wire. The bounds are kept in + # place and recomputed only when the bending direction or the pressure + # changes. n_w = phi.size n_t = kx.size stress = np.empty((n_w, n_t)) @@ -118,7 +143,6 @@ def _stress_kernel( cur_angle = math.nan cur_pressure = math.nan cur_cap = np.zeros((2, n_w)) - cap = np.zeros((2, n_w)) for i in range(n_t): x = kx[i] y = ky[i] @@ -133,35 +157,43 @@ def _stress_kernel( else: blend = magnitude / threshold if not (held == held_angle and p == held_pressure): - held_cap = _cap(phi, held, p, r_helix, n_total, area, lay_angle, mu, g) + _cap_into(phi, held, p, r_helix, n_total, area, lay_angle, mu, g, held_cap) held_angle = held held_pressure = p if blend > 0.0: if not (current == cur_angle and p == cur_pressure): - cur_cap = _cap( - phi, current, p, r_helix, n_total, area, lay_angle, mu, g + _cap_into( + phi, current, p, r_helix, n_total, area, lay_angle, mu, g, cur_cap ) cur_angle = current cur_pressure = p - for s in range(2): - for w in range(n_w): - cap[s, w] = (1.0 - blend) * held_cap[s, w] + blend * cur_cap[s, w] + for w in range(n_w): + upper = (1.0 - blend) * held_cap[0, w] + blend * cur_cap[0, w] + lower = (1.0 - blend) * held_cap[1, w] + blend * cur_cap[1, w] + drive = dm0[w] * x + dm1[w] * y + trial = force[w] + k * (drive - old_drive[w]) + if trial > upper: + force[w] = upper + elif trial < -lower: + force[w] = -lower + else: + force[w] = trial + old_drive[w] = drive + stress[w, i] = force[w] else: - for s in range(2): - for w in range(n_w): - cap[s, w] = held_cap[s, w] - for w in range(n_w): - drive = dm0[w] * x + dm1[w] * y - inc = drive - old_drive[w] - trial = force[w] + k * inc - if trial > cap[0, w]: - force[w] = cap[0, w] - elif trial < -cap[1, w]: - force[w] = -cap[1, w] - else: - force[w] = trial - old_drive[w] = drive - stress[w, i] = force[w] + for w in range(n_w): + upper = held_cap[0, w] + lower = held_cap[1, w] + drive = dm0[w] * x + dm1[w] * y + trial = force[w] + k * (drive - old_drive[w]) + if trial > upper: + force[w] = upper + elif trial < -lower: + force[w] = -lower + else: + force[w] = trial + old_drive[w] = drive + stress[w, i] = force[w] return stress diff --git a/tests/test_fast_fatigue_path.py b/tests/test_fast_fatigue_path.py new file mode 100644 index 0000000..6e23b11 --- /dev/null +++ b/tests/test_fast_fatigue_path.py @@ -0,0 +1,346 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""The fused fatigue path equals the reference arithmetic it replaces. + +``fibre_miner_damage`` counts every fixed fibre of a stress field without +forming the fibre histories; ``assemble_wire_field`` forms the field in one +pass. Both must reproduce the expressions they replace (the compiled counter +on ``WireStressField.at_fibre`` histories, cycle for cycle, and the NumPy +field expressions), so that ``compute_fatigue`` is unchanged. Timings are +recorded by ``validation/scripts/benchmark_throughput.py``; no wall-clock +assertion is made here. +""" + +from __future__ import annotations + +import json +import math +import warnings +from dataclasses import replace + +import benchmark_throughput as benchmark +import numpy as np +import pytest + +import cablexsec as cx +import cablexsec.analysis.fatigue as fatigue +from cablexsec.analysis.fast_field import assemble_wire_field +from cablexsec.analysis.fast_rainflow import fibre_miner_damage, miner_rows +from cablexsec.analysis.fatigue import FatigueLayer, compute_fatigue, wire_stress_field +from cablexsec.analysis.termination import TerminationSpec +from cablexsec.exceptions import CableInputError +from cablexsec.materials.sn_curves import SN_CURVES, SNcurve +from cablexsec.mechanics.mkappa import HelicalLayerSpec +from cablexsec.mechanics.wire_stress import local_bending_fibre_stress + +CURVES = [ + SN_CURVES["saevik_2011_flat_steel"], + SN_CURVES["dnv_rpc203_t_curve"], + SNcurve( + name="test_threshold", + stress_unit="MPa", + m1=3.0, + log_C1=12.0, + m2=5.0, + log_C2=15.5, + threshold=5.0, + ), +] + + +def _field(n_t=240, seed=11): + """Field components with plateaus, constant and monotonic rows.""" + rng = np.random.default_rng(seed) + t = np.linspace(0.0, 1.0, n_t) + mean = np.vstack( + [ + 40e6 * np.sin(9 * t) + rng.normal(0, 5e6, n_t), + np.round(rng.normal(0, 30e6, n_t) / 10e6) * 10e6, # plateaus, ties + np.full(n_t, 7e6), # constant + np.linspace(-20e6, 50e6, n_t), # monotonic + np.zeros(n_t), + ] + ) + radial = np.vstack( + [ + 25e6 * np.cos(17 * t), + np.zeros(n_t), + np.zeros(n_t), + np.zeros(n_t), + 30e6 * np.sin(23 * t), + ] + ) + tangential = np.vstack( + [ + rng.normal(0, 8e6, n_t), + np.round(rng.normal(0, 20e6, n_t) / 10e6) * 10e6, + np.zeros(n_t), + np.zeros(n_t), + 10e6 * np.cos(5 * t), + ] + ) + return mean, radial, tangential + + +def _offsets(n_fibres): + angles = np.arange(n_fibres) * (2 * math.pi / n_fibres) + return ( + np.array([math.cos(a) for a in angles]), + np.array([math.sin(a) for a in angles]), + ) + + +@pytest.mark.parametrize("curve", CURVES, ids=lambda c: c.name) +@pytest.mark.parametrize("start", [0, 1, 37, 238]) +@pytest.mark.parametrize("factors", [[1.0], [1.0, 1.7], [1.0, 0.3]]) +def test_fibre_damage_equals_the_compiled_counter_on_fibre_histories( + curve, start, factors +): + mean, radial, tangential = _field() + normal, lateral = _offsets(6) + damage, rerun = fibre_miner_damage( + mean, radial, tangential, normal, lateral, curve, factors, start=start + ) + assert damage.shape == rerun.shape == (len(factors), 5, 6) + for j in range(6): + # WireStressField.at_fibre arithmetic for the same fibre. + history = (mean + radial * normal[j] + tangential * lateral[j])[:, start:] + for q, factor in enumerate(factors): + expected, flags = miner_rows(history, curve, factor) + assert np.array_equal(damage[q, :, j], expected) # bitwise + assert np.array_equal(rerun[q, :, j], flags) + + +def test_fibre_damage_leaves_non_finite_fibres_to_the_reference(): + mean, radial, tangential = _field() + normal, lateral = _offsets(4) + radial[1, 50] = math.nan + _, rerun = fibre_miner_damage( + mean, radial, tangential, normal, lateral, CURVES[0], [1.0, 2.0] + ) + assert rerun[:, 1, :].all() # NaN times any offset + assert not rerun[:, [0, 2, 3, 4], :].any() + radial[1, 50] = 0.0 + tangential[3, 10] = math.inf # times the zero lateral offset of fibre 0: NaN + _, rerun = fibre_miner_damage( + mean, radial, tangential, normal, lateral, CURVES[0], [1.0] + ) + # An infinite range has a zero life, which stops the kernel: every entry + # is then left to the reference, as for miner_rows. + assert rerun[:, 3, :].all() + + +def test_fibre_damage_rejects_malformed_input(): + mean, radial, tangential = _field() + normal, lateral = _offsets(4) + with pytest.raises(ValueError, match="two-dimensional"): + fibre_miner_damage( + mean, radial[:2], tangential, normal, lateral, CURVES[0], [1] + ) + with pytest.raises(ValueError, match="offset"): + fibre_miner_damage( + mean, radial, tangential, normal, lateral[:2], CURVES[0], [1] + ) + with pytest.raises(ValueError, match="factors"): + fibre_miner_damage(mean, radial, tangential, normal, lateral, CURVES[0], []) + with pytest.raises(ValueError, match="two samples"): + fibre_miner_damage( + mean, radial, tangential, normal, lateral, CURVES[0], [1], start=239 + ) + + +def _spec(n_wires=8, **extra): + return HelicalLayerSpec( + n_wires=n_wires, + r_helix_m=0.05, + lay_angle_rad=0.3, + E_wire_Pa=200e9, + A_wire_m2=math.pi * 0.002**2, + xi=0.8, + mu=0.15, + F_n_axi_N=2e3, + **extra, + ) + + +def _history(n=260, seed=4): + rng = np.random.default_rng(seed) + t = np.linspace(0, 120, n) + kx = 0.02 * np.sin(2 * np.pi * 0.07 * t) + 0.003 * rng.standard_normal(n) + ky = 0.01 * np.cos(2 * np.pi * 0.043 * t) + 0.002 * rng.standard_normal(n) + return kx, ky, 2e5 + 4e4 * np.sin(np.linspace(0, 9, n)) + + +def _assert_same(a, b): + for name in ( + "D_bulk_per_wire", + "D_term_per_wire", + "D_total_per_wire", + "D_bulk_per_fibre", + "fibre_critical_deg_per_wire", + "D_bulk_with_termination_per_fibre", + "termination_fibre_critical_deg_per_wire", + ): + left, right = getattr(a, name), getattr(b, name) + assert left.keys() == right.keys() + for key in left: + assert np.array_equal(left[key], right[key]), (name, key) + assert a.critical_layer == b.critical_layer + assert a.fibre_critical_deg == b.fibre_critical_deg + + +@pytest.mark.parametrize( + "options", + [ + {"count_from_sample": 40}, + {"wire_positions": 3}, + {"count_from_sample": 7, "wire_positions": [0.0, 200.0]}, + ], + ids=["lead_in", "positions", "both"], +) +def test_compute_fatigue_fused_counter_equals_the_reference_loop(options): + kx, ky, tension = _history() + layer = FatigueLayer( + spec=_spec(), + sn_bulk=CURVES[1], + sigma_UTS_Pa=1e9, + name="armour", + SCF=1.4, + termination=True, + ) + layers = [layer, replace(layer, name="plain", termination=False)] + runs = [ + compute_fatigue( + layers, + kx, + ky, + tension_N=tension, + EA_full_N=4e8, + n_fibres=7, + rainflow_counter=counter, + **options, + ) + for counter in ("reference", "compiled") + ] + _assert_same(*runs) + assert runs[0].D_term_per_wire["armour"].max() > 0 + + +@pytest.mark.filterwarnings("ignore:overflow encountered:RuntimeWarning") +def test_fused_counter_raises_the_reference_error(): + kx, ky, _ = _history(60) + layer = FatigueLayer( + spec=_spec(4), + sn_bulk=SNcurve(name="steep", stress_unit="MPa", m1=3.0, log_C1=12.0), + sigma_UTS_Pa=1e9, + SCF=1e300, + termination=True, + ) + for counter in ("reference", "compiled"): + with pytest.raises(CableInputError, match="floating-point range"): + compute_fatigue([layer], kx, ky, n_fibres=4, rainflow_counter=counter) + + +def _field_pair(monkeypatch, layer, kx, ky, **kwargs): + monkeypatch.setattr(fatigue, "_FAST_FIELD", True) + fast = wire_stress_field(layer, kx, ky, **kwargs) + monkeypatch.setattr(fatigue, "_FAST_FIELD", False) + plain = wire_stress_field(layer, kx, ky, **kwargs) + return fast, plain + + +def _assert_close_fields(fast, plain): + # Same IEEE operations in the same order (bitwise equal where checked); + # compared to 1e-12 of the field scale across platforms. + for name in ("mean_Pa", "radial_Pa", "tangential_Pa"): + a, b = getattr(fast, name), getattr(plain, name) + scale = max(float(np.abs(b).max()), 1.0) + np.testing.assert_allclose(a, b, rtol=0, atol=1e-12 * scale, err_msg=name) + + +def test_assembled_field_equals_the_numpy_expressions(monkeypatch): + kx, ky, tension = _history() + layer = FatigueLayer(spec=_spec(), sn_bulk=CURVES[0], sigma_UTS_Pa=1e9) + modulus = 200e9 * (1 + 0.01 * np.sin(np.linspace(0, 5, kx.size))) + for kwargs in ( + {"tension_N": tension, "EA_full_N": 4e8}, + { + "tension_N": tension, + "EA_full_N": 4e8, + "thermal_stress_Pa": 5e6 * np.cos(np.linspace(0, 3, kx.size)), + "wire_modulus_Pa": modulus, + "wires": np.array([1, 4, 6]), + }, + { + "normal_stress_Pa": 9e7 + 1e7 * np.sin(np.linspace(0, 7, kx.size)), + "keep_friction": True, + }, + { + "termination": TerminationSpec( + distance_m=0.5, + segments_per_pitch=8, + max_increment=2.0, + reach_lengths=1.0, + ) + }, + ): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + fast, plain = _field_pair(monkeypatch, layer, kx, ky, **kwargs) + _assert_close_fields(fast, plain) + + +def test_assembly_reproduces_local_bending_at_both_fibres(): + kx, ky, _ = _history(50) + phi = np.linspace(0, 2 * math.pi, 5, endpoint=False) + friction = np.zeros((5, kx.size)) + zeros = np.zeros(kx.size) + mean, radial, tangential = assemble_wire_field( + kx, ky, phi, 200e9, 0.004, 0.006, 0.3, zeros, friction, zeros + ) + radial_ref = local_bending_fibre_stress(kx, ky, phi[:, None], 200e9, 0.004, 0.3) + edge_ref = local_bending_fibre_stress( + kx, ky, phi[:, None], 200e9, 0.006, 0.3, math.pi / 2 + ) + scale = float(np.abs(radial_ref).max()) + np.testing.assert_allclose(radial, radial_ref, rtol=0, atol=1e-12 * scale) + np.testing.assert_allclose(tangential, edge_ref, rtol=0, atol=1e-12 * scale) + np.testing.assert_allclose(mean, 0.0, rtol=0, atol=1e-12 * scale) + + +def test_benchmark_script_reports_cases_and_differences(tmp_path, monkeypatch): + first, second = tmp_path / "a", tmp_path / "b" + for output, extra in ((first, []), (second, ["--reference", str(first)])): + monkeypatch.setattr( + benchmark.sys, + "argv", + [ + "benchmark", + "--output", + str(output), + "--steps", + "500", + "--repeat", + "1", + "--cases", + "direction_tied_12pos_f4", + *extra, + ], + ) + assert benchmark.main() == 0 + report = json.loads((second / "throughput.json").read_text(encoding="utf-8")) + (row,) = report["cases"] + assert row["case"] == "direction_tied_12pos_f4" + assert row["series"] == 2 * 12 * 4 # two armour layers, 12 wires, 4 fibres + assert len(row["seconds"]) == 1 and row["ns_per_series_step"] > 0 + differences = report["differences_from_reference"] + assert differences and all(d["bitwise_equal"] for d in differences.values()) + + +def test_benchmark_batch_writes_readable_runs(): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + cable = cx.load_cable(cx.iea_task49_66kv_yaml_path()) + batch = benchmark.time_batch(cable, [1], runs=2, steps=41, dt=0.18) + assert batch["annual_damage_independent_of_workers"] + assert batch["rows"][0]["workers"] == 1 and batch["rows"][0]["efficiency"] == 1.0 diff --git a/tests/test_sea_state_batch.py b/tests/test_sea_state_batch.py index 02db635..de149d6 100644 --- a/tests/test_sea_state_batch.py +++ b/tests/test_sea_state_batch.py @@ -289,9 +289,16 @@ def test_compressive_material_force_is_named(tmp_path, cable, stiffness): run_sea_state_batch(cable, runs, [SectionRequest("a", 2.0)], options=options) -def test_worker_cap(cable): +@pytest.mark.parametrize("workers", [0, -1, True, 2.0]) +def test_worker_count_must_be_a_positive_integer(workers): with pytest.raises(CableInputError, match="workers"): - SeaStateBatchOptions(workers=99) + SeaStateBatchOptions(workers=workers) + + +def test_worker_count_has_no_library_cap(): + # The machine sets the useful count; the pool starts one worker per run + # at most. + assert SeaStateBatchOptions(workers=99).workers == 99 def test_tangent_placement_reaches_the_reader(tmp_path, cable): diff --git a/validation/README.md b/validation/README.md index 6d5141a..466d8b1 100644 --- a/validation/README.md +++ b/validation/README.md @@ -53,6 +53,7 @@ registered measured comparisons listed in [`VALIDATION.md`](../VALIDATION.md#sum | `concentric_conductor_bend.py` | Bending reference with coupled axial slip in concentric wire rings | | `helical_hertz_reference.py` | Independent local Hertz reference for helically swept circular sections | | `benchmark_fatigue_counter.py`, `profile_release.py` | Timing of the fatigue counter and call profiles on public inputs | +| `benchmark_throughput.py` | One-core throughput of sea-state fatigue on the 66 kV template (direction-tied and distributed models, all wires or 12 positions, 4 or 32 fibres), damage differences from an earlier build, and the sea-state batch against the worker count | | `fowt_construction.py`, `fowt_section_checks.py` | Construction and mass inputs of the floating-wind application, and the bending-range check of the metallic sheath | The tests in `tests/` import these scripts by name; `tests/conftest.py` puts this folder diff --git a/validation/scripts/benchmark_throughput.py b/validation/scripts/benchmark_throughput.py new file mode 100644 index 0000000..80ea31d --- /dev/null +++ b/validation/scripts/benchmark_throughput.py @@ -0,0 +1,359 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Throughput of the sea-state fatigue path on one core. + +Run as ``python validation/scripts/benchmark_throughput.py --output DIR`` +with ``NUMBA_NUM_THREADS=1`` (and the other thread variables at ``1``) on a +quiet machine. The workload is a one-hour synthetic sea state on the 66 kV +template (:func:`cablexsec.iea_task49_66kv_yaml_path`): irregular curvature +components ``kappa_x`` and ``kappa_y`` (peak period 10 s, standard deviations +0.004 and 0.002 1/m) and tension ``100 +- 10 kN``, ``--steps`` samples at +``--dt`` seconds. Each case calls :func:`cablexsec.compute_fatigue` on every +armour wire, or on 12 positions per layer, with the direction-tied or the +distributed friction model and 4 or 32 fibres per wire. Timings exclude +imports, cable loading and the compilation of the kernels (a short warm-up +call); every case reports the minimum of ``--repeat`` calls and the time per +series-step (one stress evaluation and its share of the counting at one +fibre of one wire at one sample). + +The damage of every case is written to ``damage.npz``; ``--reference`` names +the output directory of an earlier run (another build) and records the +largest absolute and relative differences of every array. + +``--batch-workers`` also times :func:`cablexsec.run_sea_state_batch` over +``--batch-runs`` synthetic CableDyn runs (written to a temporary folder) for +each worker count and checks that the annual damage does not depend on it. +""" + +from __future__ import annotations + +import argparse +import hashlib +import json +import math +import os +import platform +import sys +import tempfile +import warnings +from datetime import UTC, datetime +from pathlib import Path +from time import perf_counter +from typing import Any + +import numpy as np +from numpy.typing import NDArray +from profile_release import positive_int, source_digest + +import cablexsec as cx +from cablexsec._numba import kernels_compiled, numba_version + +FloatArray = NDArray[np.float64] + +#: compute_fatigue options of each case. +CASES: dict[str, dict[str, Any]] = { + "direction_tied_f4": {"friction_model": "direction_tied", "n_fibres": 4}, + "direction_tied_f32": {"friction_model": "direction_tied", "n_fibres": 32}, + "direction_tied_12pos_f4": { + "friction_model": "direction_tied", + "n_fibres": 4, + "wire_positions": 12, + }, + "distributed_f4": {"friction_model": "distributed", "n_fibres": 4}, + "distributed_f32": {"friction_model": "distributed", "n_fibres": 32}, + "distributed_12pos_f4": { + "friction_model": "distributed", + "n_fibres": 4, + "wire_positions": 12, + }, +} +THREAD_VARIABLES = ( + "OMP_NUM_THREADS", + "OPENBLAS_NUM_THREADS", + "MKL_NUM_THREADS", + "NUMBA_NUM_THREADS", +) + + +def sea_state( + steps: int, dt: float, seed: int +) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray]: + """Time, ``kappa_x``, ``kappa_y`` [1/m] and tension [N] of one sea state.""" + rng = np.random.default_rng(seed) + t = np.arange(steps) * dt + f = np.linspace(0.04, 0.3, 200) + spectrum = np.exp(-(((f - 0.1) / 0.02) ** 2)) + 0.1 * np.exp( + -(((f - 0.2) / 0.05) ** 2) + ) + amplitude = np.sqrt(spectrum) + amplitude /= np.sqrt(0.5 * (amplitude**2).sum()) + + def component(std: float) -> FloatArray: + phase = rng.uniform(0.0, 2.0 * math.pi, f.size) + waves = np.cos(2.0 * math.pi * f[None, :] * t[:, None] + phase[None, :]) + return np.asarray(std * (amplitude[None, :] * waves).sum(axis=1)) + + return t, component(0.004), component(0.002), 100e3 + component(10e3) + + +def time_cases( + cable: cx.CableData, + names: list[str], + steps: int, + dt: float, + repeat: int, +) -> tuple[list[dict[str, Any]], dict[str, FloatArray]]: + _, kx, ky, tension = sea_state(500, dt, 1) + for name in names: # compile and load every kernel the cases use + cx.compute_fatigue(cable, kx, ky, tension_N=tension, **CASES[name]) + _, kx, ky, tension = sea_state(steps, dt, 7) + rows, arrays = [], {} + for name in names: + seconds = [] + for _ in range(repeat): + start = perf_counter() + result = cx.compute_fatigue(cable, kx, ky, tension_N=tension, **CASES[name]) + seconds.append(perf_counter() - start) + series = sum(int(v.size) for v in result.D_bulk_per_fibre.values()) + best = min(seconds) + rows.append( + { + "case": name, + "options": dict(CASES[name]), + "seconds": seconds, + "seconds_min": best, + "series": series, + "ns_per_series_step": best / (series * steps) * 1e9, + "D_total_max": max( + float(v.max()) for v in result.D_total_per_wire.values() + ), + } + ) + for layer, values in result.D_bulk_per_fibre.items(): + arrays[f"{name}/{layer}/D_bulk_per_fibre"] = values + for layer, values in result.D_total_per_wire.items(): + arrays[f"{name}/{layer}/D_total_per_wire"] = values + print( + f"{name:26s} {best:8.3f} s {rows[-1]['ns_per_series_step']:8.2f} ns/series-step", + flush=True, + ) + return rows, arrays + + +def differences( + arrays: dict[str, FloatArray], reference: Path +) -> dict[str, dict[str, float]]: + """Largest absolute and relative differences from an earlier run.""" + out = {} + with np.load(reference / "damage.npz") as old: + for key, values in arrays.items(): + if key not in old.files: + continue + before = old[key] + diff = np.abs(values - before) + scale = np.abs(before) + relative = np.divide(diff, scale, out=np.zeros_like(diff), where=scale > 0) + out[key] = { + "max_abs": float(diff.max(initial=0.0)), + "max_rel": float(relative.max(initial=0.0)), + "bitwise_equal": bool(np.array_equal(values, before)), + } + return out + + +# --------------------------------------------------------------------------- # +# Sea-state batch over synthetic CableDyn runs # +# --------------------------------------------------------------------------- # +def _fmt(values: Any) -> str: + return "\t".join(f"{v: .16E}" for v in values) + + +def write_run( + folder: Path, + root: str, + steps: int, + dt: float, + seed: int, + ea: float, + ei: float, + n_elements: int = 10, + length: float = 10.0, +) -> tuple[Path, Path]: + """One CableDyn run: a bent arc whose curvature and plane follow a sea state.""" + _, a, b, tension = sea_state(steps, dt, seed) + kappa = 0.03 + 0.5 * a # positive arc curvature [1/m] + turn = 20.0 * b # rotation of the bending plane [rad] + s = length * np.arange(n_elements + 1) / n_elements + t0 = np.array([1.0, 0.0, 0.0]) + deck = folder / f"{root}.dat" + deck.write_text( + "--------------------- CableDyn Input File ---\n" + "synthetic throughput benchmark\n" + "--------------------- LINE TYPES ---\n" + "TypeName Diam MassDenInAir EA BA EI Cd_n Cd_t Ca_n Ca_t\n" + "(-) (m) (kg/m) (N) (-) (N-m2) (-) (-) (-) (-)\n" + f"cable 0.2 40.0 {ea!r} 0.0 {ei!r} 1.2 0.1 1.0 0.0\n" + "--------------------- POINTS ---\n" + "ID Type X Y Z\n(-) (-) (m) (m) (m)\n" + "1 Coupled 0 0 -10\n2 Fixed 10 0 -12\n" + "--------------------- LINES ---\n" + "ID NodeA NodeB Outputs\n(-) (-) (-) (-)\n" + "1 1 2 pt\n" + "--------------------- SECTIONS ---\n" + "LineID LineType Length NumSegs\n(-) (-) (m) (-)\n" + f"1 cable {length} {n_elements}\n" + "--------------------- OPTIONS ---\n" + "9.81 g - gravity\n1025.0 rhoW - density\n" + f"{dt} dtM - step\n{(steps - 1) * dt} TMax - duration\n" + "--------------------- OUTPUTS ---\n" + "--------------------- need this line ---\n", + encoding="utf-8", + ) + nodes = n_elements + 1 + positions = np.empty((steps, nodes, 3)) + for k in range(steps): + binormal = np.array([0.0, math.cos(turn[k]), math.sin(turn[k])]) + normal = np.cross(binormal, t0) + theta = kappa[k] * s + arc = np.sin(theta)[:, None] * t0 + (1.0 - np.cos(theta))[:, None] * normal + positions[k] = np.array([0.0, 0.0, -10.0]) + arc / kappa[k] + time = np.arange(steps) * dt + with open(folder / f"{root}.out", "w", encoding="utf-8") as f: + f.write("# CableDyn driver output (synthetic)\nTime(s)\n") + for k in range(steps): + f.write(_fmt([time[k]]) + "\n") + with open(folder / f"{root}.Line1.p.out", "w", encoding="utf-8") as f: + f.write("# CableDyn line node positions; public node order EndA -> EndB\n") + names = [f"Node{j}{c}(m)" for j in range(1, nodes + 1) for c in "XYZ"] + f.write("\t".join(["Time(s)", *names]) + "\n") + for k in range(steps): + f.write(_fmt([time[k], *positions[k].ravel()]) + "\n") + with open(folder / f"{root}.Line1.t.out", "w", encoding="utf-8") as f: + f.write("# CableDyn segment tensions; public order EndA -> EndB\n") + names = [f"Segment{e}Tension(N)" for e in range(1, nodes)] + f.write("\t".join(["Time(s)", *names]) + "\n") + for k in range(steps): + f.write(_fmt([time[k], *np.full(nodes - 1, tension[k])]) + "\n") + with open(folder / f"{root}.static.out", "w", encoding="utf-8") as f: + f.write("CableDyn standalone static configuration (synthetic)\n") + f.write("LineID\tNode\tArcLength\tX\tY\tZ\tTension\tCurvature\n") + f.write("(-)\t(-)\t(m)\t(m)\t(m)\t(m)\t(N)\t(1/m)\n") + for j in range(nodes): + f.write(f"1\t{j + 1}\t0.0\t" + _fmt(positions[0, j]) + "\t1.0E+005\t0.0\n") + return folder / root, deck + + +def time_batch( + cable: cx.CableData, workers: list[int], runs: int, steps: int, dt: float +) -> dict[str, Any]: + stiffness = cx.compute_stiffness(cable) + options: dict[str, Any] = { + "friction_model": "direction_tied", + "tension_basis": "true", + "chunk_rows": 4096, + } + with tempfile.TemporaryDirectory() as tmp: + folder = Path(tmp) + batch_runs = [] + for i in range(runs): + root, deck = write_run( + folder, + f"ss{i}", + steps, + dt, + 100 + i, + stiffness.ea_fixed_N, + stiffness.ei_min_Nm2, + ) + batch_runs.append(cx.SeaStateRun(f"ss{i}", root, deck, 1.0 / runs)) + sections = [cx.SectionRequest("mid", 5.0)] + rows, reference = [], None + for count in workers: + start = perf_counter() + result = cx.run_sea_state_batch( + cable, + batch_runs, + sections, + options=cx.SeaStateBatchOptions(workers=count, **options), + ) + seconds = perf_counter() - start + damage = result.sections["mid"].long_term.annual_damage_per_fibre + if reference is None: + reference = damage + for layer, values in damage.items(): + np.testing.assert_allclose( + values, reference[layer], rtol=1e-10, atol=0.0 + ) + rows.append({"workers": count, "seconds": seconds}) + print(f"batch workers {count:3d}: {seconds:8.2f} s", flush=True) + base = rows[0]["seconds"] * rows[0]["workers"] + for row in rows: + row["speed_up_vs_first"] = rows[0]["seconds"] / row["seconds"] + row["efficiency"] = base / (row["seconds"] * row["workers"]) + return { + "runs": runs, + "steps": steps, + "dt_s": dt, + "sections": 1, + "options": options, + "rows": rows, + "annual_damage_independent_of_workers": True, + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--output", type=Path, required=True) + parser.add_argument("--steps", type=positive_int, default=20000) + parser.add_argument("--dt", type=float, default=0.18) + parser.add_argument("--repeat", type=positive_int, default=3) + parser.add_argument( + "--cases", nargs="+", choices=sorted(CASES), default=list(CASES) + ) + parser.add_argument("--reference", type=Path) + parser.add_argument("--batch-workers", type=positive_int, nargs="*", default=[]) + parser.add_argument("--batch-runs", type=positive_int, default=16) + parser.add_argument("--batch-steps", type=positive_int, default=3601) + args = parser.parse_args() + if args.steps < 500: + parser.error("at least 500 steps are required") + args.output.mkdir(parents=True, exist_ok=False) + warnings.simplefilter("ignore") + cable = cx.load_cable(cx.iea_task49_66kv_yaml_path()) + report: dict[str, Any] = { + "utc": datetime.now(UTC).isoformat(), + "source_sha256": source_digest(), + "benchmark_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), + "source_version": cx.__version__, + "python": sys.version, + "platform": platform.platform(), + "processor": platform.processor(), + "numpy": np.__version__, + "numba": numba_version(), + "kernels_compiled": kernels_compiled(), + "threads": {key: os.environ.get(key) for key in THREAD_VARIABLES}, + "cable": "iea_task49_66kv", + "wires": sum(int(layer.n_wires) for layer in cable.helical_layers), + "steps": args.steps, + "dt_s": args.dt, + "repeat": args.repeat, + "history": "sea_state(steps, dt, seed=7) of this script", + } + rows, arrays = time_cases(cable, args.cases, args.steps, args.dt, args.repeat) + report["cases"] = rows + np.savez(args.output / "damage.npz", **arrays) + if args.reference is not None: + report["differences_from_reference"] = differences(arrays, args.reference) + report["reference"] = str(args.reference) + if args.batch_workers: + report["batch"] = time_batch( + cable, args.batch_workers, args.batch_runs, args.batch_steps, args.dt + ) + (args.output / "throughput.json").write_text( + json.dumps(report, indent=2), encoding="utf-8" + ) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) From 040fe9b0d5e88c9879421f024b88e9e18aff88c4 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 20 Nov 2026 11:49:38 +0900 Subject: [PATCH 2/2] docs: throughput numbers measured against dev e74e01f The CHANGELOG entry gives the timings of the throughput benchmark against dev e74e01f without this change, measured in one session on one machine: direction-tied 2.5 to 2.8 times faster, distributed 29.2 s to 27.5 s, batch of 48 runs 107.6 s to 42.6 s on one worker and 61.1 s to 26.9 s on two. All 24 damage arrays of the benchmark are bitwise equal to that build with numba, and the 12 of the direction-tied cases without numba. The 16 persistent cache slots of the batch workers stay as they were now that the worker count has no upper limit. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a3d2da..582f962 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -394,23 +394,25 @@ All notable changes to CableXSec are recorded in this file. The format follows ### Changed -- `compute_fatigue` is 2.3–3.0 times faster on the direction-tied model, with every damage +- `compute_fatigue` is 2.5–2.8 times faster on the direction-tied model, with every damage value bit for bit unchanged. One-hour sea state on the 66 kV template (20 000 samples, both armour layers, numba, one thread, `validation/scripts/benchmark_throughput.py`): all 284 - wires 0.88 s → 0.29 s (4 fibres) and 2.42 s → 0.90 s (32 fibres, 13.3 → 4.9 ns per fibre - sample); 12 positions per layer 0.068 s → 0.029 s. The fixed fibres of a layer are counted in + wires 0.73 s → 0.27 s (4 fibres) and 2.34 s → 0.84 s (32 fibres, 12.9 → 4.6 ns per fibre + sample); 12 positions per layer 0.068 s → 0.027 s. The fixed fibres of a layer are counted in one compiled pass (`fast_rainflow.fibre_miner_damage`): each fibre history is reduced to its turning points while it is formed, the reversal scan feeds the three-point stack directly, and one count serves the unit and the termination stress-range factor; entries where the reference sum would raise are recomputed on the reference path in the former order. The stress field is assembled in one compiled pass (`fast_field.assemble_wire_field`, the NumPy operations in the same order); without numba the NumPy path forms the local bending stress - once instead of twice. The distributed model is limited by its increment solver (22 s of - 23 s), as before. + once instead of twice. The distributed model is limited by its increment solver, as before + (29.2 s → 27.5 s on all wires with 4 fibres). - `SeaStateBatchOptions(workers=...)` and `cablexsec-batch --workers` have no upper limit - (`MAX_WORKERS` is removed); the pool starts at most one worker per run. On 48 one-hour runs - the batch takes 43.3, 23.5, 13.0 and 7.8 s with 1, 2, 4 and 8 workers; the remainder is the - start-up of each worker (about 2 s: imports and loading the compiled kernels). + (`MAX_WORKERS` is removed); the pool starts at most one worker per run, and the 16 + persistent numba cache slots of the workers stay as they were (a worker beyond them gets a + temporary cache). On 48 one-hour runs the batch takes 42.6 s with 1 worker and 26.9 s with + 2 (107.6 s and 61.1 s before); the rest of the time at many workers is the start-up of each + worker (about 2 s: imports and loading the compiled kernels). - The laid-core and filler-profile contact loads follow the tension history by default: `compute_neutral_axes(..., core_loads="follow")` with `tension_N` or `contact_tension_N`, and