diff --git a/CHANGELOG.md b/CHANGELOG.md index fcfc170..1209f50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -544,6 +544,24 @@ All notable changes to CableXSec are recorded in this file. The format follows `warnings.simplefilter("ignore")`, dropping a wire-yield or clamping warning about the caller's own curvature; each distinct warning is now relayed once (`provenance.relayed_warnings`). +- Adversarial inputs of the public API (`tests/test_robustness_inputs.py`): a friction + coefficient so large that the capstan factor overflows (`mu = 1e6`) stopped the reference + return map ("wire history exceeds floating-point range") while the compiled kernels held the + wires stuck; both paths now give the stuck answer, and so does `compute_mkappa`, which raised + on both (on the 33 kV template its loop at `mu = 1e6` equals the one at `mu = 100`). The + critical fibre, wire and layer of `compute_fatigue` are the first of the values within 1e-12 + of the largest, so a round-off difference between the kernel paths no longer moves them (63 + deg on one, 243 deg on the other, at equal damage). `compute_thermal` refuses a negative + current, temperatures below absolute zero and a core count that is not a positive integer + (`n_cores = 0` divided by zero), and so does `thermal_network` (a NaN ambient built a network + of NaN temperatures) with its steady, transient and matrix states (negative currents, ambients + below absolute zero); `export_bending_law` refuses a non-integer `n_points` (was numpy's + `TypeError`). A layer's schema error names the layer, its index and the file instead of the + union of layer kinds. `read_series_csv` refuses a file that is not UTF-8 with + `CableSchemaError` (was `UnicodeDecodeError`) and skips rows of spaces or separators only; + both CSV readers refuse a cell that is not a decimal number (`float` alone took `1_0` as 10). + `SeaStateBatchOptions` checks `n_fibres`, `chunk_rows`, `mu`, `exposure_years` and + `design_fatigue_factor` before any run is read, and `SeaStateRun` its `line_id`. - The series shear stack of the armour stick coefficient ξ (`xi_for_layer`, Yun et al. 2020) stops at the layer's support. Walking inward, it adds each concentric cylindrical layer with a modulus (interstitial fillers still skipped) and stops at the first helical layer inside and diff --git a/src/cablexsec/analysis/bending_law.py b/src/cablexsec/analysis/bending_law.py index 737009c..d8e053b 100644 --- a/src/cablexsec/analysis/bending_law.py +++ b/src/cablexsec/analysis/bending_law.py @@ -86,6 +86,7 @@ import dataclasses import json import math +import numbers import warnings from collections.abc import Sequence from dataclasses import dataclass, field @@ -1193,8 +1194,14 @@ def export_bending_law( raise CableInputError("tensions_N must rise strictly") if not (math.isfinite(kappa_max_1_m) and kappa_max_1_m > 0): raise CableInputError("kappa_max_1_m must be finite and positive") - if n_points < 3: - raise CableInputError("n_points must be at least 3") + if ( + isinstance(n_points, bool) + or not isinstance(n_points, numbers.Integral) + or n_points < 3 + ): + raise CableInputError( + f"n_points must be an integer of at least 3: {n_points!r}" + ) for name in ( "tension_N", "phi_bend", diff --git a/src/cablexsec/analysis/fatigue.py b/src/cablexsec/analysis/fatigue.py index 004c8be..28d6081 100644 --- a/src/cablexsec/analysis/fatigue.py +++ b/src/cablexsec/analysis/fatigue.py @@ -353,6 +353,20 @@ def _warn_default_direction_tied(out_of_plane: float, stacklevel: int) -> None: ) +#: Values within this relative distance of the largest are a tie: the +#: critical fibre, wire and layer are the first of them, so a round-off +#: difference (compiled against reference kernels, or symmetric wires) does +#: not move the reported location. +_TIE_RTOL = 1e-12 + + +def _first_maximum(values: FloatArray) -> NDArray[np.intp]: + """Index of the first value of each row within ``_TIE_RTOL`` of its maximum.""" + peak = np.max(values, axis=1, keepdims=True) + near = values >= peak - _TIE_RTOL * np.abs(peak) + return np.asarray(np.argmax(near, axis=1)) + + def _check_distributed_bound(bound: str) -> None: if bound not in BOUND_FORMS: raise CableInputError( @@ -1900,11 +1914,11 @@ def compute_fatigue( if layer.termination and layer.SCF != 1.0 else fibre_damage[:, j] ) - critical_indices = np.argmax(fibre_damage, axis=1) + critical_indices = _first_maximum(fibre_damage) db = fibre_damage[np.arange(n_eval), critical_indices] d_fibre[name] = fibre_damage critical_fibre[name] = np.degrees(fibre_angles[critical_indices]) - adjusted_indices = np.argmax(amplified_damage, axis=1) + adjusted_indices = _first_maximum(amplified_damage) adjusted_db = amplified_damage[np.arange(n_eval), adjusted_indices] d_adjusted_fibre[name] = amplified_damage critical_adjusted_fibre[name] = np.degrees(fibre_angles[adjusted_indices]) @@ -1993,8 +2007,8 @@ def compute_fatigue( # Critical wire across all layers. crit_layer, crit_k, crit_val = "", 0, -1.0 for name, dvec in d_total.items(): - k = int(np.argmax(dvec)) - if dvec[k] > crit_val: + k = int(_first_maximum(dvec[None, :])[0]) + if dvec[k] > crit_val * (1.0 + _TIE_RTOL): crit_layer, crit_k, crit_val = name, k, float(dvec[k]) if crit_layer: diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index b996c87..e9b0b60 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -164,6 +164,12 @@ def __post_init__(self) -> None: raise CableInputError("run names must be nonempty and contain no slash") object.__setattr__(self, "out_root", Path(self.out_root)) object.__setattr__(self, "deck", Path(self.deck)) + if ( + isinstance(self.line_id, bool) + or not isinstance(self.line_id, int) + or self.line_id < 1 + ): + raise CableInputError(f"{self.name}: line_id must be a positive integer") if not math.isfinite(self.probability) or not 0.0 <= self.probability <= 1.0: raise CableInputError(f"{self.name}: probability must be in [0, 1]") if not math.isfinite(self.start_time_s) or self.start_time_s < 0: @@ -272,6 +278,31 @@ def __post_init__(self) -> None: or not 1 <= self.workers <= MAX_WORKERS ): raise CableInputError(f"workers must be an integer in [1, {MAX_WORKERS}]") + # The fatigue and long-term options are checked here, before any run is + # read, as compute_fatigue and compute_long_term_fatigue check them. + for name, count, low in ( + ("n_fibres", self.n_fibres, 4), + ("chunk_rows", self.chunk_rows, 16), + ): + if isinstance(count, bool) or not isinstance(count, int) or count < low: + raise CableInputError(f"{name} must be an integer of at least {low}") + for name, value in ( + ("exposure_years", self.exposure_years), + ("design_fatigue_factor", self.design_fatigue_factor), + ): + if isinstance(value, bool) or not ( + isinstance(value, int | float) and math.isfinite(value) and value > 0 + ): + raise CableInputError(f"{name} must be finite and positive") + if self.design_fatigue_factor < 1: + raise CableInputError("design_fatigue_factor must be at least one") + if self.mu is not None and ( + isinstance(self.mu, bool) + or not isinstance(self.mu, int | float) + or not math.isfinite(self.mu) + or self.mu < 0 + ): + raise CableInputError("mu must be finite and >= 0") for name in ( "curvature_check_rtol", "curvature_check_end_rtol", diff --git a/src/cablexsec/cables/schema.py b/src/cablexsec/cables/schema.py index d699b74..7150936 100644 --- a/src/cablexsec/cables/schema.py +++ b/src/cablexsec/cables/schema.py @@ -69,6 +69,7 @@ SerializationInfo, SerializerFunctionWrapHandler, TypeAdapter, + ValidationError, field_serializer, field_validator, model_serializer, @@ -2086,6 +2087,35 @@ def _read_yaml_mapping(path: Path) -> dict[str, Any]: ) +def _validate_layer(item: Any, index: int, source: str) -> Any: + """One layer of a cable file; an error names the layer and the file. + + Pydantic titles a layer's error with the union of every layer kind and + locates it within the kind only; the title here is the layer's index and + name, and the location starts at ``layers.``. + """ + try: + return _LAYER_ADAPTER.validate_python(item) + except ValidationError as error: + name = item.get("name") if isinstance(item, Mapping) else None + title = f"layer {index}{f' {name!r}' if name else ''} of {source}" + details: list[Any] = [] + for entry in error.errors(): + detail: dict[str, Any] = { + "type": entry["type"], + "loc": ("layers", index, *entry["loc"]), + "input": entry["input"], + } + if "ctx" in entry: + detail["ctx"] = entry["ctx"] + details.append(detail) + try: + renamed = ValidationError.from_exception_data(title, details) + except (TypeError, ValueError, KeyError): # an error kind it cannot rebuild + raise error from None + raise renamed from None + + def load_cable( yaml_path: str | Path, *, @@ -2162,7 +2192,8 @@ def load_cable( ) layers = tuple( - _LAYER_ADAPTER.validate_python(item) for item in raw.get("layers", []) + _validate_layer(item, index, path.name) + for index, item in enumerate(raw.get("layers", [])) ) return CableData( cable=CableMeta.model_validate(raw.get("cable", {})), diff --git a/src/cablexsec/io/series.py b/src/cablexsec/io/series.py index 0801115..63c2141 100644 --- a/src/cablexsec/io/series.py +++ b/src/cablexsec/io/series.py @@ -11,6 +11,8 @@ from __future__ import annotations import csv +import io +import re from dataclasses import dataclass, fields, replace from pathlib import Path from typing import Literal @@ -230,6 +232,21 @@ def write_series_csv(series: LoadCaseSeries, path: str | Path) -> Path: return p +#: A decimal number as a CSV cell spells one (``float`` alone also takes +#: ``1_000``); ``nan`` and ``inf`` pass, for the finite check to name them. +_NUMBER = re.compile( + r"\s*[+-]?(?:(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?|nan|inf|infinity)\s*", + re.IGNORECASE, +) + + +def parse_number(cell: str) -> float: + """One numeric CSV cell; ``ValueError`` for anything but a decimal number.""" + if not isinstance(cell, str) or not _NUMBER.fullmatch(cell): + raise ValueError(f"not a decimal number: {cell!r}") + return float(cell) + + def read_series_csv(path: str | Path) -> LoadCaseSeries: """Read the canonical exchange CSV written by :func:`write_series_csv`.""" p = Path(path) @@ -239,76 +256,89 @@ def read_series_csv(path: str | Path) -> LoadCaseSeries: strains = [] any_strain = False any_temp = False - with p.open("r", newline="", encoding="utf-8-sig") as fh: - reader = csv.DictReader(fh) - fields = set(reader.fieldnames or []) - if len(fields) != len(reader.fieldnames or []): - raise CableSchemaError( - f"series CSV {p.name} repeats a column name: {reader.fieldnames}" - ) - tension_columns = fields & { - "effective_tension_N", - "true_tension_N", - "axial_tension_N", - } - if len(tension_columns) != 1: - raise CableSchemaError( - "series CSV must contain exactly one named tension column" - ) - tension_column = tension_columns.pop() - strain_columns = fields & { - "direct_axial_strain", - "total_axial_strain", - "axial_strain", - } - if len(strain_columns) > 1: - raise CableSchemaError( - "series CSV must contain at most one named axial-strain column" - ) - strain_column = next(iter(strain_columns), "axial_strain") - strain_kind: Literal["direct", "total", "unspecified"] = ( - "direct" - if strain_column == "direct_axial_strain" - else "total" - if strain_column == "total_axial_strain" - else "unspecified" + try: + text = p.read_bytes().decode("utf-8-sig") + except UnicodeDecodeError: + raise CableSchemaError( + f"series CSV {p.name} is not UTF-8 text (write_series_csv writes UTF-8)" + ) from None + # A newline-preserving stream: a quoted cell keeps an embedded newline + # (and is refused), where split lines would join its parts. + reader = csv.DictReader(io.StringIO(text, newline="")) + fields = set(reader.fieldnames or []) + if len(fields) != len(reader.fieldnames or []): + raise CableSchemaError( + f"series CSV {p.name} repeats a column name: {reader.fieldnames}" ) - kind: Literal["effective", "true", "unspecified"] - kind = ( - "true" - if tension_column == "true_tension_N" - else ( - "effective" - if tension_column == "effective_tension_N" - else "unspecified" - ) + tension_columns = fields & { + "effective_tension_N", + "true_tension_N", + "axial_tension_N", + } + if len(tension_columns) != 1: + raise CableSchemaError( + "series CSV must contain exactly one named tension column" ) - missing = set(_CSV_COLUMNS[:3]) - fields - if missing: + tension_column = tension_columns.pop() + strain_columns = fields & { + "direct_axial_strain", + "total_axial_strain", + "axial_strain", + } + if len(strain_columns) > 1: + raise CableSchemaError( + "series CSV must contain at most one named axial-strain column" + ) + strain_column = next(iter(strain_columns), "axial_strain") + strain_kind: Literal["direct", "total", "unspecified"] = ( + "direct" + if strain_column == "direct_axial_strain" + else "total" + if strain_column == "total_axial_strain" + else "unspecified" + ) + kind: Literal["effective", "true", "unspecified"] + kind = ( + "true" + if tension_column == "true_tension_N" + else ("effective" if tension_column == "effective_tension_N" else "unspecified") + ) + missing = set(_CSV_COLUMNS[:3]) - fields + if missing: + raise CableSchemaError( + f"series CSV {p.name} missing columns {sorted(missing)}; " + f"found {reader.fieldnames}." + ) + for row in reader: + # DictReader keeps the cells beyond the header as a list under None. + surplus = row.pop(None, None) or [] + cells = [*row.values(), *surplus] + if not any((value or "").strip() for value in cells): + continue # a blank row (spaces or separators only) + if any(value.strip() for value in surplus): raise CableSchemaError( - f"series CSV {p.name} missing columns {sorted(missing)}; " - f"found {reader.fieldnames}." + f"series CSV {p.name}, line {reader.line_num}: more cells than the " + f"{len(reader.fieldnames or [])} columns of the header" ) - for row in reader: - try: - times.append(float(row["time_s"])) - kx.append(float(row["curvature_x_1_m"])) - ky.append(float(row["curvature_y_1_m"])) - ten.append(float(row[tension_column])) - strain_cell = (row.get(strain_column) or "").strip() - any_strain |= bool(strain_cell) - strains.append(float(strain_cell) if strain_cell else np.nan) - t_cell = (row.get("temperature_C") or "").strip() - if t_cell: - any_temp = True - temp.append(float(t_cell)) - else: - temp.append(np.nan) - except (TypeError, ValueError) as error: - raise CableSchemaError( - f"series CSV {p.name}, line {reader.line_num}: " - "expected numeric history values" - ) from error + try: + times.append(parse_number(row["time_s"])) + kx.append(parse_number(row["curvature_x_1_m"])) + ky.append(parse_number(row["curvature_y_1_m"])) + ten.append(parse_number(row[tension_column])) + strain_cell = (row.get(strain_column) or "").strip() + any_strain |= bool(strain_cell) + strains.append(parse_number(strain_cell) if strain_cell else np.nan) + t_cell = (row.get("temperature_C") or "").strip() + if t_cell: + any_temp = True + temp.append(parse_number(t_cell)) + else: + temp.append(np.nan) + except (TypeError, ValueError) as error: + raise CableSchemaError( + f"series CSV {p.name}, line {reader.line_num}: " + "expected numeric history values" + ) from error return LoadCaseSeries( time_s=np.asarray(times, dtype=np.float64), curvature_x_1_m=np.asarray(kx, dtype=np.float64), diff --git a/src/cablexsec/io/time_history_csv.py b/src/cablexsec/io/time_history_csv.py index 099b95a..5d59692 100644 --- a/src/cablexsec/io/time_history_csv.py +++ b/src/cablexsec/io/time_history_csv.py @@ -12,6 +12,7 @@ from __future__ import annotations import csv +import io import re from pathlib import Path from typing import Literal, cast @@ -20,7 +21,7 @@ from numpy.typing import NDArray from cablexsec.exceptions import CableSchemaError -from cablexsec.io.series import LoadCaseSeries +from cablexsec.io.series import LoadCaseSeries, parse_number from cablexsec.mechanics.section_conventions import rotation_to_strain_curvature from cablexsec.provenance import Provenance @@ -216,7 +217,9 @@ def _read_csv_rows(path: Path) -> tuple[list[tuple[int, list[str]]], list[str]]: raise CableSchemaError( f"{path.name}: not a text CSV (neither UTF-8 nor Windows-1252)." ) - reader = csv.reader(text.splitlines()) + # A newline-preserving stream: a quoted cell keeps an embedded newline + # (and is refused), where split lines would join its parts. + reader = csv.reader(io.StringIO(text, newline="")) all_rows = [(reader.line_num, r) for r in reader if any(cell.strip() for cell in r)] if not all_rows: raise CableSchemaError(f"{path.name}: empty CSV.") @@ -315,7 +318,7 @@ def _columns_to_arrays( for line, row in rows: for key, col in idx.items(): try: - out[key].append(float(row[col])) + out[key].append(parse_number(row[col])) except ValueError as exc: raise CableSchemaError( f"{source}: line {line} column {col + 1} is not numeric: " diff --git a/src/cablexsec/mechanics/papailiou.py b/src/cablexsec/mechanics/papailiou.py index 0d7df51..ff748d3 100644 --- a/src/cablexsec/mechanics/papailiou.py +++ b/src/cablexsec/mechanics/papailiou.py @@ -409,11 +409,22 @@ def wire_slip_stress_bounds( ) cphi = np.cos(layer.phi_wires - phi_bend) psi = np.arcsin(np.clip(np.abs(cphi), 0.0, 1.0)) - upper = sigma0 * g * np.expm1(layer.mu * sin_a * psi) + # A capstan factor beyond the floating-point range is a bound no wire + # stress reaches (the compiled bounds of fast_slip give it as inf): held + # at _UNREACHABLE_CAP_PA, not an overflow error of this reference path. + with np.errstate(over="ignore"): + upper = np.minimum( + sigma0 * g * np.expm1(layer.mu * sin_a * psi), _UNREACHABLE_CAP_PA + ) lower = -sigma0 * g * np.expm1(-layer.mu * sin_a * psi) return np.asarray(upper), np.asarray(lower) +#: The tension friction bound of a wire whose capstan factor overflows [Pa]: +#: finite, far above any wire stress, so the wire never slips. +_UNREACHABLE_CAP_PA = 1.0e300 + + def slip_onset_curvature( layer: HelicalLayerSpec, *, diff --git a/src/cablexsec/mechanics/thermal.py b/src/cablexsec/mechanics/thermal.py index a74f1b2..011afa5 100644 --- a/src/cablexsec/mechanics/thermal.py +++ b/src/cablexsec/mechanics/thermal.py @@ -73,6 +73,7 @@ import math from collections.abc import Sequence from dataclasses import dataclass +from numbers import Integral from typing import TYPE_CHECKING import numpy as np @@ -585,6 +586,10 @@ def _layer_heat_flows( return flows, t1, t2_scaled / float(n_conductors) +#: Absolute zero [°C]: the floor of a temperature input. +_ABSOLUTE_ZERO_C = -273.15 + + @uses_cable_materials def compute_thermal( cable: CableData, @@ -728,7 +733,7 @@ def compute_thermal( "(set them in the cable 'environment' block or pass overrides)." ) checks = { - "current_A": (current_A, False), + "current_A": (current_A, None), "conductor_temp_C": (conductor_temp_C, False), "ambient_C": (t_amb, False), "conductor_area_m2": (conductor_area_m2, True), @@ -745,7 +750,11 @@ def compute_thermal( raise CableInputError(f"compute_thermal: {name} must be positive") if positive is None and value < 0.0: raise CableInputError(f"compute_thermal: {name} must not be negative") - + for name, value in (("conductor_temp_C", conductor_temp_C), ("ambient_C", t_amb)): + if value < _ABSOLUTE_ZERO_C: + raise CableInputError( + f"compute_thermal: {name} = {value:g} °C is below absolute zero" + ) geo = _ladder_geometry(cable, n_cores) path, in_t1, n = geo.path, geo.in_t1, geo.n multi_core, geometry_notes = geo.multi_core, list(geo.geometry_notes) @@ -995,6 +1004,12 @@ def conductor_material_of(cable: CableData, given: str | None) -> tuple[str, str def _ladder_geometry(cable: CableData, n_cores: int | None) -> _LadderGeometry: """Concentric heat path, ``T1`` split and core counts of a cable definition.""" + if n_cores is not None and ( + isinstance(n_cores, bool) or not isinstance(n_cores, Integral) or n_cores < 1 + ): + raise CableInputError( + f"n_cores must be a positive integer (at least 1): {n_cores!r}" + ) n_geo = ( max((getattr(layer, "n_cores", 0) for layer in cable.layers), default=0) or 1 ) diff --git a/src/cablexsec/mechanics/thermal_network.py b/src/cablexsec/mechanics/thermal_network.py index b6f558b..1b32ba3 100644 --- a/src/cablexsec/mechanics/thermal_network.py +++ b/src/cablexsec/mechanics/thermal_network.py @@ -262,8 +262,8 @@ def steady_state( exists (thermal runaway of the coupled resistance). """ amb = self.ambient_C if ambient_C is None else float(ambient_C) - _check_finite(current_A, "current_A") - _check_finite(amb, "ambient_C") + _check_current(current_A) + _check_temperature(amb, "ambient_C") k, s = self._system(current_A, amb, resistance_temperature_C) if resistance_temperature_C is None: _check_stable(k, self.capacitance_J_mK) @@ -312,6 +312,8 @@ def transient( amb = _as_series( self.ambient_C if ambient_C is None else ambient_C, t, "ambient_C" ) + _check_current(cur) + _check_temperature(amb, "ambient_C") if scheme not in _SCHEMES: raise CableInputError(f"scheme must be one of {_SCHEMES}") _check_finite(max_step_s, "max_step_s") @@ -443,8 +445,8 @@ def system_matrices( ``K``). Copies, so callers may add their own sources. """ amb = self.ambient_C if ambient_C is None else float(ambient_C) - _check_finite(current_A, "current_A") - _check_finite(amb, "ambient_C") + _check_current(current_A) + _check_temperature(amb, "ambient_C") k, s = self._system(current_A, amb, resistance_temperature_C) return k.copy(), s.copy() @@ -508,6 +510,28 @@ def _check_finite(value: float, name: str) -> None: raise CableInputError(f"{name} must be finite") +#: Absolute zero [deg C]: the floor of a temperature input. +_ABSOLUTE_ZERO_C = -273.15 + + +def _check_temperature(value: float | FloatArray, name: str) -> None: + """Finite temperatures [deg C] at or above absolute zero.""" + values = np.asarray(value, dtype=np.float64) + if not np.isfinite(values).all(): + raise CableInputError(f"{name} must be finite") + if np.any(values < _ABSOLUTE_ZERO_C): + raise CableInputError(f"{name} must not lie below absolute zero (-273.15 °C)") + + +def _check_current(value: float | FloatArray) -> None: + """Finite, non-negative (RMS) conductor currents [A].""" + values = np.asarray(value, dtype=np.float64) + if not np.isfinite(values).all(): + raise CableInputError("current_A must be finite") + if np.any(values < 0.0): + raise CableInputError("current_A must not be negative (an RMS current)") + + def _as_series( values: Sequence[float] | FloatArray | float, t: FloatArray, name: str ) -> FloatArray: @@ -574,6 +598,7 @@ def thermal_network( ) if not (math.isfinite(t4) and t4 > 0): raise CableInputError("T4_external_Km_W must be positive and finite") + _check_temperature(t_amb, "ambient_C") if ( isinstance(n_per_layer, bool) or int(n_per_layer) != n_per_layer diff --git a/tests/test_robustness_inputs.py b/tests/test_robustness_inputs.py new file mode 100644 index 0000000..951369e --- /dev/null +++ b/tests/test_robustness_inputs.py @@ -0,0 +1,317 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Adversarial inputs of the public API: each case failed, or answered +differently with and without the compiled kernels, before 0.2.0. + +Every invalid input is refused early with a message naming it; every valid +one gives a finite answer, the same (to round-off) on both kernel paths. +""" + +from __future__ import annotations + +import math +from pathlib import Path + +import numpy as np +import pytest +import yaml +from _bundled import bundled +from pydantic import ValidationError + +import cablexsec as cx +from cablexsec.analysis.fatigue import _first_maximum +from cablexsec.analysis.sea_state_batch import SeaStateBatchOptions, SeaStateRun +from cablexsec.exceptions import CableInputError, CableSchemaError +from cablexsec.mechanics.papailiou import wire_slip_stress_bounds + +CABLE = "inter_array_single_core_33kv" + + +def _history(n=64): + t = np.linspace(0.0, 6.3, n) + return 0.02 * np.sin(t), 0.01 * np.cos(t), np.full(n, 2.0e5) + + +# --------------------------------------------------------------------------- # +# A very large friction coefficient # +# --------------------------------------------------------------------------- # +def test_very_large_mu_sticks_on_both_kernel_paths(monkeypatch): + """mu = 1e6 overflowed the capstan factor of the reference return map + ("wire history exceeds floating-point range") while the compiled path + held the wires stuck. Both now give the stuck answer, that of mu = 1.""" + cable = bundled(CABLE) + kx, ky, ten = _history() + reference = cx.compute_fatigue( + cable, kx, ky, tension_N=ten, mu=1.0, friction_model="direction_tied" + ) + import cablexsec.analysis.fatigue as fatigue + + # The compiled kernels where numba runs them, and the reference kernels. + for compiled in sorted({fatigue._FAST_SLIP, False}): + monkeypatch.setattr(fatigue, "_FAST_SLIP", compiled) + result = cx.compute_fatigue( + cable, kx, ky, tension_N=ten, mu=1e6, friction_model="direction_tied" + ) + for name, damage in result.D_total_per_wire.items(): + scale = float(np.max(reference.D_total_per_wire[name])) + np.testing.assert_allclose( + damage, reference.D_total_per_wire[name], rtol=0.0, atol=1e-12 * scale + ) + + +def test_overflowing_capstan_bound_is_finite_and_unreachable(): + from cablexsec.cable_adapters import cable_to_mkappa_specs + + spec = cable_to_mkappa_specs(bundled(CABLE), 1e5, mu=1e6)[0] + upper, lower = wire_slip_stress_bounds(spec, 0.0) + assert np.isfinite(upper).all() and np.max(upper) >= 1e300 + assert np.isfinite(lower).all() and np.all(lower >= 0.0) + + +# --------------------------------------------------------------------------- # +# Ties of the critical location # +# --------------------------------------------------------------------------- # +def test_critical_location_is_the_first_of_tied_values(): + """Damage at symmetric fibres differs by round-off between the kernel + paths; argmax then reported 63 deg on one path and 243 deg on the other. + Values within 1e-12 of the maximum are a tie, won by the first.""" + values = np.array([[1.0, 3.0, 3.0 * (1 + 1e-14), 2.0], [0.0, 0.0, 0.0, 0.0]]) + assert _first_maximum(values).tolist() == [1, 0] + assert _first_maximum(np.array([[1.0, 3.0, 3.0 * (1 + 1e-9)]])).tolist() == [2] + + +# --------------------------------------------------------------------------- # +# Thermal and bending-law arguments # +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"current_A": -1.0}, "current_A must not be negative"), + ({"ambient_C": -300.0}, "ambient_C = -300 °C is below absolute zero"), + ({"conductor_temp_C": -274.0}, "conductor_temp_C = -274 °C is below"), + ({"n_cores": 0}, "n_cores must be a positive integer"), + ({"n_cores": 1.5}, "n_cores must be a positive integer"), + ({"n_cores": True}, "n_cores must be a positive integer"), + ], +) +def test_thermal_arguments_are_checked(kwargs, match): + """A zero core count divided by zero (ZeroDivisionError); a negative + current and temperatures below absolute zero were accepted.""" + cable = bundled(CABLE) + with pytest.raises(CableInputError, match=match): + cx.compute_thermal( + cable, **{"current_A": 600.0, "conductor_area_m2": 3e-4, **kwargs} + ) + + +@pytest.mark.parametrize("n_points", [20.5, "20", True, 2]) +def test_bending_law_point_count_is_an_integer(n_points): + """A fractional point count raised numpy's TypeError.""" + with pytest.raises(CableInputError, match="n_points must be an integer"): + cx.export_bending_law( + bundled(CABLE), tensions_N=[0.0], kappa_max_1_m=0.1, n_points=n_points + ) + + +# --------------------------------------------------------------------------- # +# Cable definitions # +# --------------------------------------------------------------------------- # +def _yaml(tmp_path, change): + path = Path(cx.__file__).parent / "cables" / f"{CABLE}.yaml" + data = yaml.safe_load(path.read_text(encoding="utf-8")) + for layer in data["layers"]: + if layer["name"] == change[0]: + layer[change[1]] = change[2] + out = tmp_path / "cable.yaml" + out.write_text(yaml.safe_dump(data), encoding="utf-8") + return out + + +@pytest.mark.parametrize( + ("change", "where", "detail"), + [ + ( + ("xlpe_insulation", "r_outer_m", math.nan), + "layer 2 'xlpe_insulation'", + "finite", + ), + ( + ("inner_armour", "d_wire_m", -1.0), + "layer 6 'inner_armour'", + "d_wire_m must be > 0", + ), + ( + ("inner_armour", "lay_angle_deg", 90.0), + "layer 6 'inner_armour'", + r"\[0, 90\)", + ), + (("inner_armour", "n_wires", 2.5), "layer 6 'inner_armour'", "valid integer"), + ( + ("inner_armour", "n_wires", 0), + "layer 6 'inner_armour'", + "n_wires must be > 0", + ), + (("outer_armour", "bogus_key", 1), "layer 7 'outer_armour'", "Extra inputs"), + ], +) +def test_cable_errors_name_the_layer(tmp_path, change, where, detail): + """The error of a layer was titled with the union of every layer kind and + located within the kind only; it now names the layer and the file.""" + with pytest.raises(ValidationError) as caught: + cx.load_cable(_yaml(tmp_path, change), geometry_override=None) + text = str(caught.value) + assert f"for {where} of cable.yaml" in text + assert f"layers.{where.split()[1]}." in text + assert caught.match(detail) + + +@pytest.mark.parametrize( + "change", + [ + ("inner_armour", "lay_angle_deg", 1e-3), + ("inner_armour", "lay_angle_deg", 89.0), + ("inner_armour", "n_wires", 1), + ], +) +def test_extreme_but_valid_geometry_gives_a_finite_answer(tmp_path, change): + import warnings + + with warnings.catch_warnings(): + warnings.simplefilter("ignore") # an overfilled near-hoop layer warns + cable = cx.load_cable(_yaml(tmp_path, change), geometry_override=None) + kx, ky, ten = _history(32) + result = cx.compute_fatigue( + cable, kx, ky, tension_N=ten, friction_model="direction_tied" + ) + assert all(np.isfinite(v).all() for v in result.D_total_per_wire.values()) + assert np.isfinite(cx.compute_stiffness(cable).ei_min_Nm2) + + +# --------------------------------------------------------------------------- # +# Exchange CSV # +# --------------------------------------------------------------------------- # +_HEAD = "time_s,curvature_x_1_m,curvature_y_1_m,true_tension_N\n" +_ROWS = "".join(f"{0.1 * k:.6e},{0.01 * k:.6e},0,1.0e5\n" for k in range(5)) + + +@pytest.mark.parametrize( + "data", + [ + (_HEAD + _ROWS).encode(), + (_HEAD + _ROWS).replace("\n", "\r\n").encode(), + b"\xef\xbb\xbf" + (_HEAD + _ROWS).encode(), + (_HEAD + _ROWS + "\n , ,\n\n").encode(), + (_HEAD + _ROWS + ",,,,,,\n").encode(), # more blank cells than columns + (_HEAD + _ROWS.replace("e", "E")).encode(), + ], +) +def test_series_csv_reads_line_ends_bom_and_blank_rows(tmp_path, data): + path = tmp_path / "s.csv" + path.write_bytes(data) + series = cx.read_series_csv(path) + assert series.n_steps == 5 and series.tension_kind == "true" + + +@pytest.mark.parametrize( + ("data", "match"), + [ + ((_HEAD + _ROWS).encode("utf-16"), "not UTF-8 text"), + ("timé,x\n1,2\n".encode("latin-1"), "not UTF-8 text"), + ((_HEAD + _ROWS + "0.6,1_0,0,1e5\n").encode(), "line 7"), + ((_HEAD + _ROWS + "0.6,1e-2,0\n").encode(), "line 7"), + ((_HEAD + _ROWS + "0.6,1e-2,0,1e5,7\n").encode(), "line 7: more cells"), + ((_HEAD + _ROWS + '0.6,"1\n0",0,1e5\n').encode(), "expected numeric"), + ], +) +def test_series_csv_errors_name_the_file(tmp_path, data, match): + """A file that is not UTF-8 raised UnicodeDecodeError; a quoted cell with + a newline must not be read with its parts joined (1 and 0 as 10).""" + path = tmp_path / "s.csv" + path.write_bytes(data) + with pytest.raises(CableSchemaError, match=match): + cx.read_series_csv(path) + + +# --------------------------------------------------------------------------- # +# Sea-state batch options and runs # +# --------------------------------------------------------------------------- # +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"exposure_years": 0.0}, "exposure_years must be finite and positive"), + ({"exposure_years": math.nan}, "exposure_years"), + ({"design_fatigue_factor": 0.5}, "design_fatigue_factor must be at least one"), + ({"design_fatigue_factor": math.inf}, "design_fatigue_factor"), + ({"n_fibres": 2}, "n_fibres must be an integer of at least 4"), + ({"n_fibres": 8.0}, "n_fibres"), + ({"chunk_rows": 4}, "chunk_rows"), + ({"mu": -0.1}, "mu must be finite and >= 0"), + ({"mu": math.nan}, "mu must be finite"), + ], +) +def test_batch_options_are_checked_before_any_run(kwargs, match): + """These reached compute_fatigue or compute_long_term_fatigue only after + every run had been read and evaluated.""" + with pytest.raises(CableInputError, match=match): + SeaStateBatchOptions(**kwargs) + + +@pytest.mark.parametrize("line_id", [0, -1, True, 1.0]) +def test_batch_run_line_id_is_checked(tmp_path, line_id): + with pytest.raises(CableInputError, match="line_id must be a positive integer"): + SeaStateRun("r", tmp_path / "o", tmp_path / "d.dat", 1.0, line_id=line_id) + + +def test_very_large_mu_gives_the_stuck_moment_curvature_loop(): + """compute_mkappa with mu = 1e6 raised "wire history exceeds + floating-point range" on both kernel paths; the friction-limited wires + simply stick. They already stick at mu = 100 on this loop (the slip left + there does not depend on mu), so the two agree.""" + cable = bundled(CABLE) + kappa = np.concatenate([np.linspace(0, 0.05, 30), np.linspace(0.05, -0.05, 60)]) + stuck = cx.compute_mkappa(cable, kappa, tension_N=1e5, mu=100.0) + huge = cx.compute_mkappa(cable, kappa, tension_N=1e5, mu=1e6) + scale = float(np.max(np.abs(stuck.moment_Nm))) + np.testing.assert_allclose( + huge.moment_Nm, stuck.moment_Nm, rtol=0, atol=1e-12 * scale + ) + np.testing.assert_array_equal(huge.slip_fraction, stuck.slip_fraction) + + +def test_time_history_csv_keeps_a_quoted_newline(tmp_path): + """Split lines joined the parts of a quoted cell holding a newline.""" + path = tmp_path / "th.csv" + path.write_bytes(b'Time,x curvature,Wall tension\n0,0.01,100\n0.1,"1\n0",100\n') + with pytest.raises(CableSchemaError, match="column 2 is not numeric"): + cx.read_time_history_csv(path, curvature_y_col=None, tension_kind="true") + + +@pytest.mark.parametrize( + ("kwargs", "match"), + [ + ({"ambient_C": math.nan}, "ambient_C must be finite"), + ({"ambient_C": -400.0}, "below absolute zero"), + ({"n_cores": 1.5}, "n_cores must be a positive integer"), + ({"n_cores": 0}, "n_cores must be a positive integer"), + ], +) +def test_thermal_network_arguments_are_checked(kwargs, match): + """A NaN ambient built a network of NaN temperatures; an ambient below + absolute zero and a fractional core count were accepted.""" + with pytest.raises(CableInputError, match=match): + cx.thermal_network(bundled(CABLE), 3e-4, **kwargs) + + +def test_thermal_network_states_refuse_impossible_loads(): + network = cx.thermal_network(bundled(CABLE), 3e-4) + time = np.linspace(0.0, 3600.0, 7) + for call, match in ( + (lambda: network.steady_state(-600.0), "must not be negative"), + (lambda: network.steady_state(600.0, ambient_C=-300.0), "absolute zero"), + (lambda: network.transient(time, np.full(7, -1.0)), "must not be negative"), + (lambda: network.transient(time, 600.0, ambient_C=-280.0), "absolute zero"), + (lambda: network.system_matrices(600.0, ambient_C=math.nan), "finite"), + ): + with pytest.raises(CableInputError, match=match): + call() + assert np.isfinite(network.steady_state(600.0)).all()