Skip to content
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 9 additions & 2 deletions src/cablexsec/analysis/bending_law.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@
import dataclasses
import json
import math
import numbers
import warnings
from collections.abc import Sequence
from dataclasses import dataclass, field
Expand Down Expand Up @@ -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",
Expand Down
22 changes: 18 additions & 4 deletions src/cablexsec/analysis/fatigue.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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])
Expand Down Expand Up @@ -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:
Expand Down
31 changes: 31 additions & 0 deletions src/cablexsec/analysis/sea_state_batch.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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",
Expand Down
33 changes: 32 additions & 1 deletion src/cablexsec/cables/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@
SerializationInfo,
SerializerFunctionWrapHandler,
TypeAdapter,
ValidationError,
field_serializer,
field_validator,
model_serializer,
Expand Down Expand Up @@ -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.<index>``.
"""
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,
*,
Expand Down Expand Up @@ -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", {})),
Expand Down
162 changes: 96 additions & 66 deletions src/cablexsec/io/series.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand All @@ -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),
Expand Down
Loading
Loading