diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index b0360d7..f88bb5e 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -184,12 +184,14 @@ Functional kernels operating on arrays; most are not called directly by users. read-only storage on construction. CSV read/write; `fatigue_from_series`. - `time_history_csv.py`: time-history CSV exports, columns selected by header. - `cabledyn.py`: CableDyn deck and output files (standalone driver and - OpenFAST module). CableDyn writes curvature magnitudes only; the reader - reconstructs the curvature vector from the node tangent channels or - positions, projects it on a twist-free section frame (material twist added - on lines restrained in torsion), interpolates tension, forms hydrostatic - pressure, and checks every file, channel and unit against the deck - ([doc/global_local_guide.md](doc/global_local_guide.md)). + OpenFAST module). The reader reconstructs the curvature vector from the + node tangent channels or positions (the `Curv` magnitudes serve as a + check), projects it on a twist-free section frame (material twist added + where `Twist` channels are written), interpolates tension, forms + hydrostatic pressure, and checks every file, channel and unit against the + deck ([doc/global_local_guide.md](doc/global_local_guide.md)). +- `cabledyn_components.py`: station histories from the signed section-frame + curvature components `CurvX`/`CurvY` that CableDyn writes since 0.4.0. - `riflex_reader.py`: RIFLEX ASCII results. - `synthetic.py`: self-contained JONSWAP-style load-series generator. diff --git a/CHANGELOG.md b/CHANGELOG.md index 0744cb9..2579d29 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -286,6 +286,28 @@ All notable changes to CableXSec are recorded in this file. The format follows its plane stays planar. Over the 1 203 tests that reach the planarity test and the shipped fatigue examples and tutorials, no path other than the new checks changes its verdict. +- `read_cabledyn_sections` closes every output file it reads. The per-line `.p.out` and + `.t.out` readers were left open after a read (and after a failed one) until garbage + collection, which raised `ResourceWarning`. The files of one run must now also end on the same + row: a per-line file with more or fewer rows than the main table is rejected ("different row + counts"), where before the extra rows were dropped when the chunk boundaries hid them. +- `read_cabledyn_deck` reads the OPTIONS record forms of CableDyn: `value keyword [commentary]`, + positional records with the model first and the keyword after the numbers + (`uniform 0.0 0.6 0.0 current` was read as a keyword `0.0` with the value `uniform`), the + keyword-first `dynamic_solver` row, and a ` - ` description. The last record of a keyword + wins, as in CableDyn (the first won), and the aliases `gravity`, `WtrDnsty`/`water_density`, + `water_depth` and `dt` set `g`, `rhoW`, `WtrDpth` and `dtM` (they were ignored, so a deck + that set the water density as `WtrDnsty` got the default 1025 kg/m³ in the hydrostatic + pressure). +- `run_sea_state_batch` checks and digests `cable_source` before it reads any run; a missing + file failed only after every section of every run had been computed. +- The global–local guide (Sections 1, 2, 2.1 and 7), `ARCHITECTURE.md` and the CableDyn reader + describe CableDyn 0.4.x: node tension, curvature and bend moment recovered from nodal + equilibrium (since CableDyn 0.2.0), the signed section-axis components `CurvX`/`CurvY` and + torsion of lines restrained at one end (since 0.4.0), and the node tangent of finite-EI lines + in the `Dec`/`Azi` channels (since 0.4.2; the tangent reader places an end node's tangent half + an element inside the line on such output). The `compute_mkappa` docstring states that + `tension_N` is the true wall tension, as in `compute_fatigue`. - The slip of the distributed friction model over a full-slip increment (every helix node on its bound) is now unique. The equations fix the forces, the tractions and `u − p` there, but not a slide common to the displacement `u` and the slip `p` of all nodes; the solver left one node diff --git a/doc/global_local_guide.md b/doc/global_local_guide.md index 9cf590f..da13f18 100644 --- a/doc/global_local_guide.md +++ b/doc/global_local_guide.md @@ -5,8 +5,8 @@ Stage 1 of the global–local coupling is one way: CableDyn solves the global cable, CableXSec reads the histories of selected material sections and runs its local fatigue on them, as it does on other global results. The global bending -law stays CableDyn's (constant `EI`); the hysteretic two-way element is -stage 2 (Section 7). +law stays CableDyn's (linear elastic: the `EI` of the line type, tapered under a +bend stiffener); the hysteretic two-way element is stage 2 (Section 7). | Piece | Where | |---|---| @@ -17,8 +17,10 @@ stage 2 (Section 7). ## 1. What CableDyn writes -From the CableDyn manual (`doc/outputs.rst`, `doc/conventions.rst`) and the -writers in `src/CableDyn_DeckDriver.f90` (CableDyn v0.1.x): +From the CableDyn manual (`doc/driver_format.md`, `doc/outputs.rst`, +`doc/theory.rst`) for CableDyn 0.4.x. The genuine runs in `tests/data/cabledyn/` +were written by the CableDyn 0.1.0 driver; where a later release changed a +channel, the item says so. - **Files.** Standalone driver: `.out` (title line, header `Time(s)` and the deck `OUTPUTS` tokens, no units row); @@ -27,25 +29,43 @@ writers in `src/CableDyn_DeckDriver.f90` (CableDyn v0.1.x): `.static.out` and `.elements.out` (initial state and element reference arcs, cubic-Hermite route). OpenFAST (`CompMooring = 5`): `.CD.out` with a header `Time` and a units row, and - `.CD.static.out`; there are no per-line files. Fields are + `.CD.static.out`; there are no per-line position or tension files. + Fields are TAB-separated; values have 8 significant digits, time 17. The output step is always `dtM`. - **Order and frame.** Node 1 is End A (hang-off), node N End B; the parser swaps a line listed anchor first. Global axes are right-handed, `z` up, still water at `z = 0`, all SI, angles in degrees. -- **Curvature.** `CurvN` is a magnitude at nodes only (for finite-EI - lines the larger of the two one-sided element curvatures at an interior - node). No signed components and no material frame are written. -- **Tangent.** `LNDec` and `LNAzi` give the direction of the chord - between the neighbouring nodes (one-sided at the ends), End A to End B. +- **Curvature.** `CurvN` is the curvature magnitude at a node. On a + finite-EI line it is recovered from nodal equilibrium (since CableDyn 0.2.0): + the geometric curvature of the stretched line, `(1 + ε) BendMom / EI`, the + larger of the two sides at a section junction (`OutputRecovery element` + restores the larger one-sided element curvature). Since CableDyn 0.4.0 a + finite-EI line also writes the signed components `CurvXN` and + `CurvYN` on section axes (Section 2.1), with `CurvX² + CurvY² = + Curv²`. The reader of Section 2 rebuilds the vector from the geometry and + uses `Curv` as a check. +- **Tangent.** `LNDec` and `LNAzi` give a direction from End A to + End B. Up to CableDyn 0.4.1 it is the chord between the neighbouring nodes + (one-sided at the ends). From CableDyn 0.4.2 a finite-EI line writes the + node's own tangent, the cubic-Hermite tangent degree of freedom (at an end + clamped by a `Rigid` row, the direction the clamp holds); an `EI = 0` line + keeps the chord. The reader places every value at the mid-arc of the chord + (Section 2): at an interior node of a uniform mesh that is the node itself, + but the tangent of an end node of 0.4.2 output is then taken half an + element inside the line. - **Tension.** Effective tension of a solid line without contents - (`T_e = EA ε`). `.t.out` holds the element-midpoint axial force; - `TenN` the length-weighted mean of the two neighbouring element-mean - forces (an end node: the end force). On a curved coarse element the two - differ (Section 5). -- **Torsion.** Only on a line restrained in torsion at both ends: - `TorqN` (uniform along the line) and `TwistN`, the material twist - from End A in degrees. + (`T_e = EA ε`). On a finite-EI line `TenN` is the axial component of + the section force recovered from nodal equilibrium (since CableDyn 0.2.0; + `OutputRecovery element` restores the length-weighted mean of the two + neighbouring element-mean forces), and `.t.out` holds the axial resultant at + each segment midpoint; an end node reports the end force. On a curved coarse + element the two can differ (Section 5). +- **Torsion.** On a line solved in torsion: restrained at both ends or, since + CableDyn 0.4.0, at one end with the other free to twist. `TorqN` + (uniform along the line in statics; with the nodal twist of the 0.4.0 + dynamics it varies along the line) and `TwistN`, the material twist + accumulated from End A in degrees. - **Pressure.** Not written. ## 2. Section history @@ -76,9 +96,13 @@ twist: `frame="arc"` (default) transports them along the line from End A by minimal rotations between element chords, with the End-A axes transported in time; this is the material frame of a torque-free isotropic rod. `frame="section"` transports the section's own axes in time and needs only -the channels near the section. On a line restrained in torsion the axes are -turned right-handed about `t` by the `Twist` channel (a restrained line -without these channels is rejected). The hang-off's rotation about its own +the channels near the section. Where `Twist` channels bracket a section the +axes are turned right-handed about `t` by the material twist from End A. A +line restrained in torsion at both ends without these channels is rejected; a +line restrained at one end only is read with its `Twist` channels when they +are written; restrained at End B only, its End A turns freely with the line's +twist, which the reader, whose axes start at End A, does not represent. The +hang-off's rotation about its own tangent (vessel yaw at a vertical hang-off) is not visible in the geometry and is not represented. @@ -138,17 +162,23 @@ tolerance or refine the mesh. **Deck outputs.** `section_channels(deck, sections)` lists the `OUTPUTS` channels the tangent source needs for the section frame: `Dec`/`Azi` on the window, `Ten`, `Curv` and `p{x,y,z}` at the bracketing nodes, and -`Twist`/`Torq` on a restrained line. The arc frame also needs the line's `p` +`Twist`/`Torq` on a line restrained at both ends (request them too on a line +restrained at one end). The arc frame also needs the line's `p` flag. Adding `t` gives the element tensions. ### 2.1 CableDyn 0.4.0 signed curvature components -CableDyn 0.4.0 writes, per station, the effective -tension `Ten` and the curvature vector on two section axes, `CurvX` and -`CurvY` [1/m]. The vector points to the centre of curvature, so a fibre at -`(x, y)` has bending strain `−(CurvX·x + CurvY·y)`; `x` is the upper normal at -the hang-off, fixed in the hang-off axes and parallel-transported along the -line. The local route takes the strain gradient on the same axes: +Since CableDyn 0.4.0 a finite-EI line writes, at a node, the effective +tension `TenN` and the curvature vector on two section axes, +`CurvXN` and `CurvYN` [1/m]. The vector points to the centre of +curvature, so a fibre at `(x, y)` has bending strain `−(CurvX·x + CurvY·y)`. +On a line not restrained in torsion `x` starts as the upper normal at the +hang-off, fixed in the hang-off axes (in global axes at a pinned End A), and +is parallel-transported along the line; on a line restrained in torsion it +starts from the restrained end's torsion normal `Nx` (carried to End A when +only End B is restrained) and is turned by the line's twist (CableDyn +`doc/theory.rst`, curvature on the section axes). The +local route takes the strain gradient on the same axes: ```text g_x = −CurvX, g_y = −CurvY @@ -166,8 +196,11 @@ a turn from the `e1` of Section 2. Because the axes are fixed in the hang-off axes, the hang-off's rotation about its own tangent, which the tangent reconstruction of Section 2 cannot see, is carried. Tests: `tests/test_cabledyn_components.py` (sag, hog and out-of-plane signs, a -rotating plane, separators, a missing column). Reading the 0.4.0 `.out` files -directly follows once their channel names are fixed by a release. +rotating plane, separators, a missing column). The station reader takes one +station's columns under the names above; a CableDyn `.out` file holds them as +`TenN`, `CurvXN` and `CurvYN` for every requested node, so a +station is passed to `series_from_curvature_components` from its three +columns. `read_cabledyn_sections` does not read `CurvX`/`CurvY`. ## 3. Sea-state batch @@ -336,7 +369,8 @@ damage. ## 7. Stage 2 and limitations -Stage 1 is one way and uses CableDyn's constant `EI`. Stage 2 is the +Stage 1 is one way and uses CableDyn's linear-elastic bending (the `EI` of +the line type, tapered under a bend stiffener). Stage 2 is the two-way hysteretic element: the section's slip-dependent moment–curvature law (`xsec_stiffness`, the backbone of `compute_mkappa`) returned to CableDyn as an element constitutive law with history (biaxial stick–slip state per diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index fde4b41..284f4f9 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -851,6 +851,17 @@ def run_sea_state_batch( output = None if output_directory is None else Path(output_directory) if output is not None and output.exists(): raise FileExistsError(f"{output} exists; choose a new output directory") + # The cable file is digested before any run is read, so a wrong path + # fails at once rather than after every section is computed. + cable_file = None + if cable_source is not None: + source_path = Path(cable_source) + if not source_path.is_file(): + raise FileNotFoundError(f"cable_source {source_path} is not a file") + cable_file = { + "path": str(source_path.resolve()), + "sha256": _sha256_bytes(source_path.read_bytes()), + } basis = _resolve_basis(cable, opts.tension_basis) diameter = ( opts.external_diameter_m @@ -1013,13 +1024,6 @@ def run_sea_state_batch( import cablexsec # noqa: PLC0415 - cable_file = None - if cable_source is not None: - source_path = Path(cable_source) - cable_file = { - "path": str(source_path.resolve()), - "sha256": _sha256_bytes(source_path.read_bytes()), - } manifest: dict[str, Any] = { "format": "cablexsec-sea-state-batch", "version": 1, diff --git a/src/cablexsec/api.py b/src/cablexsec/api.py index 8ce9603..466c152 100644 --- a/src/cablexsec/api.py +++ b/src/cablexsec/api.py @@ -710,7 +710,14 @@ def compute_mkappa( kappa_history : numpy.ndarray Driven curvature time series [1/m]. tension_N : float, optional - Axial tension for the contact ``F_n`` [N]. + Axial tension for the contact ``F_n`` [N]: the true wall tension, the + force the layers carry, as ``tension_N`` of :func:`compute_fatigue`. + No external pressure acts in this call, so an effective tension from + a global model is converted first (sealed annulus ``T_e - p_o A_o``, + :func:`cablexsec.analysis.compression.true_wall_tension`; + :func:`cablexsec.compute_section_properties` does this per load case, + or pass a ``section_state`` or ``radial_state`` solved with the + pressure). Without external pressure the two are equal. mu : float, optional Armour friction coefficient (default: material ``mu_on_hdpe``). phi_bend : float, optional diff --git a/src/cablexsec/io/cabledyn.py b/src/cablexsec/io/cabledyn.py index b73d922..c842b95 100644 --- a/src/cablexsec/io/cabledyn.py +++ b/src/cablexsec/io/cabledyn.py @@ -12,15 +12,20 @@ What CableDyn writes, and what is derived here ---------------------------------------------- -CableDyn reports curvature as a magnitude only (``CurvN``), at nodes. It -does not write signed curvature components or a material frame. The curvature -*vector* is therefore reconstructed from the solved geometry: +CableDyn reports the curvature magnitude ``CurvN`` at nodes; since +0.4.0 a finite-EI line also writes signed components on section axes +(``CurvXN``, ``CurvYN``), which +:mod:`cablexsec.io.cabledyn_components` reads. This reader reconstructs the +curvature *vector* from the solved geometry and uses ``Curv`` as a check: * ``curvature_source="tangent"``: node tangents from the ``LNDec`` and ``LNAzi`` channels (written with 8 significant digits of the angle). - CableDyn forms these from the chord between the neighbouring nodes, so each - value is placed at the mid-arc of that chord (an end node at the mid-arc of - its element). A cubic spline through the tangents of a few nodes on either + Up to CableDyn 0.4.1 these are the chord between the neighbouring nodes, so + each value is placed at the mid-arc of that chord (an end node at the + mid-arc of its element). From 0.4.2 a finite-EI line writes the node's own + tangent: at an interior node of a uniform mesh the chord mid-arc is the + node, but an end tangent is then taken half an element inside the line. + A cubic spline through the tangents of a few nodes on either side of the section gives :math:`\mathbf{t}` and :math:`\boldsymbol{\kappa}=\mathbf{t}\times\mathrm{d}\mathbf{t}/\mathrm{d}s`. * ``curvature_source="positions"``: node positions from ``.Line.p.out`` (or @@ -91,7 +96,7 @@ import hashlib import math import re -from collections.abc import Iterator, Mapping, Sequence +from collections.abc import Generator, Mapping, Sequence from dataclasses import dataclass, field, replace from pathlib import Path from types import MappingProxyType @@ -285,6 +290,48 @@ def _strip_comment(text: str) -> str: return text.strip() +#: Keywords of the options the reader uses and their CableDyn aliases. +_OPTION_ALIASES: dict[str, tuple[str, ...]] = { + "g": ("g", "gravity"), + "rhoW": ("rhoW", "WtrDnsty", "water_density"), + "WtrDpth": ("WtrDpth", "water_depth"), + "dtM": ("dtM", "dt"), + "TMax": ("TMax",), + "adaptive_mesh": ("adaptive_mesh", "adaptivemesh"), +} + + +def _is_number(token: str) -> bool: + try: + float(token) + except ValueError: + return False + return True + + +def _option_record(row: Sequence[str]) -> tuple[str, str] | None: + """Keyword (case-folded) and value text of one OPTIONS row. + + CableDyn's record forms: ``value keyword [commentary]``; positional + records with the model name first and the keyword after the numbers + (``uniform 0.5 0 0 current``, ``airy 2.0 8.0 0.0 waves``); and + ``dynamic_solver`` with its keyword first. A ``-`` token starts a + description. The keyword is the first token after the first one that + is not a number; a row without one is not a record. + """ + tokens = list(row) + if "-" in tokens: + tokens = tokens[: tokens.index("-")] + if not tokens: + return None + if tokens[0].casefold() == "dynamic_solver": + return tokens[0].casefold(), " ".join(tokens[1:]) + for index in range(1, len(tokens)): + if not _is_number(tokens[index]): + return tokens[index].casefold(), " ".join(tokens[:index]) + return None + + def _float(token: str, what: str, path: Path) -> float: try: value = float(token) @@ -463,10 +510,15 @@ def read_cabledyn_deck(path: str | Path) -> CableDynDeck: reversed_by_parser=swap, ) + records = [ + record + for record in (_option_record(row) for row in blocks.get("options", [])) + if record is not None + ] + # Records apply in order: the last one of a keyword wins. options: dict[str, str] = {} - for row in blocks.get("options", []): - if len(row) >= 2: - options.setdefault(row[1].casefold(), row[0]) + for key, value in records: + options[key] = value channels = tuple( token for row in blocks.get("outputs", []) @@ -474,16 +526,22 @@ def read_cabledyn_deck(path: str | Path) -> CableDynDeck: ) defaults = [] + def last(name: str) -> str | None: + # The last record of the keyword or any of its aliases. + names = {alias.casefold() for alias in _OPTION_ALIASES.get(name, (name,))} + return next((value for key, value in reversed(records) if key in names), None) + def option(name: str, default: float | None) -> float | None: - if name.casefold() in options: - return _float(options[name.casefold()], f"option {name}", deck_path) + value = last(name) + if value is not None: + return _float(value, f"option {name}", deck_path) if default is not None: defaults.append(name) return default g = option("g", _DEFAULT_G) rho = option("rhoW", _DEFAULT_RHO_W) - adaptive = options.get("adaptive_mesh", options.get("adaptivemesh", "false")) + adaptive = last("adaptive_mesh") or "false" if adaptive.casefold() not in { "true", "t", @@ -608,10 +666,14 @@ def _line_table(path: Path, title_word: str, columns: Sequence[str]) -> _Table: def _chunks( table: _Table, columns: Sequence[int], chunk_rows: int -) -> Iterator[FloatArray]: +) -> Generator[FloatArray, None, None]: + """Rows of a table in chunks; the file is closed when the generator ends + or is closed.""" import pandas as pd # noqa: PLC0415 - reader = pd.read_csv( + order = {column: i for i, column in enumerate(sorted(set(columns)))} + pick = [order[column] for column in columns] + with pd.read_csv( table.path, sep="\t", header=None, @@ -621,16 +683,14 @@ def _chunks( engine="c", chunksize=chunk_rows, skipinitialspace=True, - ) - order = {column: i for i, column in enumerate(sorted(set(columns)))} - pick = [order[column] for column in columns] - for frame in reader: - values = frame.to_numpy(dtype=np.float64) - if not np.isfinite(values).all(): - raise CableSchemaError( - f"{table.path.name}: incomplete or non-finite row in the history" - ) - yield values[:, pick] + ) as reader: + for frame in reader: + values = frame.to_numpy(dtype=np.float64) + if not np.isfinite(values).all(): + raise CableSchemaError( + f"{table.path.name}: incomplete or non-finite row in the history" + ) + yield values[:, pick] def _channel_index(table: _Table) -> dict[tuple[str, int, int], int]: @@ -1325,7 +1385,9 @@ def want(kind: str, node: int) -> None: for node in tension_check_nodes: want("ten", node) - streams: list[Iterator[FloatArray]] = [_chunks(main, main_cols, chunk_rows)] + streams: list[Generator[FloatArray, None, None]] = [ + _chunks(main, main_cols, chunk_rows) + ] if positions_table is not None and pos_order: pos_cols = [0] + [ 1 + 3 * node + axis for node in pos_order for axis in range(3) @@ -1372,191 +1434,220 @@ def want(kind: str, node: int) -> None: def append(plan: _Plan, key: str, values: FloatArray) -> None: plan.data.setdefault(key, []).append(values) - iterator = zip(*streams, strict=False) - while True: - try: - chunk = next(iterator) - except StopIteration: - break - if len({part.shape[0] for part in chunk}) != 1: - raise CableSchemaError("CableDyn output files have different row counts") - time = chunk[0][:, 0] - for part in chunk[1:]: - scale = 1e-9 * max(1.0, float(np.max(np.abs(time)))) - if not np.allclose(part[:, 0], time, rtol=0.0, atol=scale): + # Every stream is closed on the way out (its file handle with it), also + # when a check below raises or the files end at different rows. + try: + while True: + parts = [next(stream, None) for stream in streams] + if all(part is None for part in parts): + break + if any(part is None for part in parts): raise CableSchemaError( - "time columns of the main and per-line files differ" + "CableDyn output files have different row counts" ) - values = chunk[0] - nt = time.size - positions = np.empty((nt, len(pos_order), 3)) - if positions_table is not None and pos_order: - positions = chunk[1][:, 1:].reshape(nt, len(pos_order), 3) - elif pos_order: - for node in pos_order: - for axis, kind in enumerate(("px", "py", "pz")): - positions[:, pos_slot[node], axis] = values[:, slot[(kind, node)]] - if tensions_table is not None: - elem_t = chunk[-1][:, 1:] - if first: - if "static" in paths and pos_order: - static = _static_profile(paths["static"], line_id) - if static.shape[0] != n_nodes: - raise CableSchemaError( - f"{paths['static'].name}: {static.shape[0]} nodes, " - f"expected {n_nodes}" - ) - max_t0_error = float(np.max(np.abs(static[pos_order] - positions[0]))) - if max_t0_error > 2e-6 * max(1.0, float(np.max(np.abs(static)))): + chunk = tuple(part for part in parts if part is not None) + if len({part.shape[0] for part in chunk}) != 1: + raise CableSchemaError( + "CableDyn output files have different row counts" + ) + time = chunk[0][:, 0] + for part in chunk[1:]: + time_tol = 1e-9 * max(1.0, float(np.max(np.abs(time)))) + if not np.allclose(part[:, 0], time, rtol=0.0, atol=time_tol): raise CableSchemaError( - "first position row differs from the static profile by " - f"{max_t0_error:.3g} m: files from different runs?" + "time columns of the main and per-line files differ" ) - if len(pos_order) > 1: - contiguous = [j for j in pos_order if j + 1 in pos_slot] - if contiguous: - chord = np.array( - [ - np.linalg.norm( - positions[0, pos_slot[j + 1]] - - positions[0, pos_slot[j]] - ) - for j in contiguous + values = chunk[0] + nt = time.size + positions = np.empty((nt, len(pos_order), 3)) + if positions_table is not None and pos_order: + positions = chunk[1][:, 1:].reshape(nt, len(pos_order), 3) + elif pos_order: + for node in pos_order: + for axis, kind in enumerate(("px", "py", "pz")): + positions[:, pos_slot[node], axis] = values[ + :, slot[(kind, node)] ] + if tensions_table is not None: + elem_t = chunk[-1][:, 1:] + if first: + if "static" in paths and pos_order: + static = _static_profile(paths["static"], line_id) + if static.shape[0] != n_nodes: + raise CableSchemaError( + f"{paths['static'].name}: {static.shape[0]} nodes, " + f"expected {n_nodes}" + ) + max_t0_error = float( + np.max(np.abs(static[pos_order] - positions[0])) ) - stretch = chord / reference_l0[contiguous] - 1.0 - stretch_range = (float(stretch.min()), float(stretch.max())) - if stretch_range[0] < -0.02 or stretch_range[1] > 0.05: + if max_t0_error > 2e-6 * max(1.0, float(np.max(np.abs(static)))): raise CableSchemaError( - "element chord/reference length - 1 spans " - f"{stretch_range}: " - "the deck sections do not describe the output mesh" + "first position row differs from the static profile by " + f"{max_t0_error:.3g} m: files from different runs?" ) - magnitude = float(np.max(np.abs(positions[0]))) - position_floor = ( - 0.5 - * 10.0 ** (math.floor(math.log10(max(magnitude, 1e-30))) - 7) - / float(np.min(reference_l0)) ** 2 - ) - # Element tension consistency (ordering check). - if tensions_table is not None and tension_check_nodes: - for node in tension_check_nodes: - channel = values[:, slot[("ten", node)]] - scale = np.maximum(np.abs(channel), 1.0) - for j, label in ((node, "match"), (n_nodes - 1 - node, "mirror")): - left, right = elem_t[:, ten_slot[j - 1]], elem_t[:, ten_slot[j]] - w_left, w_right = reference_l0[j - 1], reference_l0[j] - mean = (w_left * left + w_right * right) / (w_left + w_right) - error = np.abs(channel - mean) / scale - if label == "match": - tension_check = max(tension_check, float(np.max(error))) - tension_match += float(np.sum(error)) - else: - tension_mirror += float(np.sum(error)) - # Frame transport along the arc (all sections share it). - arc_e1: dict[int, FloatArray] = {} - if frame == "arc": - last = max(plan.element for plan in sections_plans) - chords = _unit( - positions[:, [pos_slot[j + 1] for j in range(last + 1)]] - - positions[:, [pos_slot[j] for j in range(last + 1)]], - "element chord", - ) - e1_a, state_a = _time_transport( - chords[:, 0], state_a, reference, f"line {line_id} End A" - ) - e1 = e1_a - arc_e1[0] = e1 - for k in range(1, last + 1): - e1 = _transport(e1, chords[:, k - 1], chords[:, k]) - arc_e1[k] = e1 - for plan in plans: - if source == "tangent": - dec = np.radians( - np.stack([values[:, slot[("dec", j)]] for j in plan.window], axis=1) - ) - azi = np.radians( - np.stack([values[:, slot[("azi", j)]] for j in plan.window], axis=1) - ) - samples = np.stack( - (np.sin(dec) * np.cos(azi), np.sin(dec) * np.sin(azi), np.cos(dec)), - axis=-1, - ) - value, d1, _ = _spline(chord_mid[plan.window], samples, plan.arc) - tangent = _unit(value, "section tangent") - kappa = np.cross(tangent, d1) - else: - window = positions[:, [pos_slot[j] for j in plan.window]] - value, d1, d2 = _spline(arcs[plan.window], window, plan.arc) - speed = np.linalg.norm(d1, axis=-1, keepdims=True) - tangent = d1 / speed - kappa = np.cross(d1, d2) / speed**3 - norm = np.linalg.norm(kappa, axis=-1) - append(plan, "norm", norm) - if plan.probe: - node = plan.node - append(plan, "channel", values[:, slot[("curv", node)]]) - continue + if len(pos_order) > 1: + contiguous = [j for j in pos_order if j + 1 in pos_slot] + if contiguous: + chord = np.array( + [ + np.linalg.norm( + positions[0, pos_slot[j + 1]] + - positions[0, pos_slot[j]] + ) + for j in contiguous + ] + ) + stretch = chord / reference_l0[contiguous] - 1.0 + stretch_range = (float(stretch.min()), float(stretch.max())) + if stretch_range[0] < -0.02 or stretch_range[1] > 0.05: + raise CableSchemaError( + "element chord/reference length - 1 spans " + f"{stretch_range}: " + "the deck sections do not describe the output mesh" + ) + magnitude = float(np.max(np.abs(positions[0]))) + position_floor = ( + 0.5 + * 10.0 ** (math.floor(math.log10(max(magnitude, 1e-30))) - 7) + / float(np.min(reference_l0)) ** 2 + ) + # Element tension consistency (ordering check). + if tensions_table is not None and tension_check_nodes: + for node in tension_check_nodes: + channel = values[:, slot[("ten", node)]] + scale = np.maximum(np.abs(channel), 1.0) + for j, label in ((node, "match"), (n_nodes - 1 - node, "mirror")): + left, right = elem_t[:, ten_slot[j - 1]], elem_t[:, ten_slot[j]] + w_left, w_right = reference_l0[j - 1], reference_l0[j] + mean = (w_left * left + w_right * right) / (w_left + w_right) + error = np.abs(channel - mean) / scale + if label == "match": + tension_check = max(tension_check, float(np.max(error))) + tension_match += float(np.sum(error)) + else: + tension_mirror += float(np.sum(error)) + # Frame transport along the arc (all sections share it). + arc_e1: dict[int, FloatArray] = {} if frame == "arc": - axis1 = _transport( - arc_e1[plan.element], chords[:, plan.element], tangent - ) - else: - axis1, state = _time_transport( - tangent, - state_section[plan.name], - reference, - f"section {plan.name!r}", + last = max(plan.element for plan in sections_plans) + chords = _unit( + positions[:, [pos_slot[j + 1] for j in range(last + 1)]] + - positions[:, [pos_slot[j] for j in range(last + 1)]], + "element chord", ) - state_section[plan.name] = state - axis2 = np.cross(tangent, axis1) - weight = (plan.arc - arcs[plan.element]) / reference_l0[plan.element] - if twist_available: - twist = np.radians( - (1 - weight) * values[:, slot[("twist", plan.element)]] - + weight * values[:, slot[("twist", plan.element + 1)]] + e1_a, state_a = _time_transport( + chords[:, 0], state_a, reference, f"line {line_id} End A" ) - cos, sin = np.cos(twist)[:, None], np.sin(twist)[:, None] - axis1, axis2 = cos * axis1 + sin * axis2, -sin * axis1 + cos * axis2 - append(plan, "twist", twist) - if torque_available: - append( - plan, - "torque", - (1 - weight) * values[:, slot[("torq", plan.element)]] - + weight * values[:, slot[("torq", plan.element + 1)]], - ) - append(plan, "kx", np.sum(kappa * axis1, axis=-1)) - append(plan, "ky", np.sum(kappa * axis2, axis=-1)) - if pos_order and plan.element in pos_slot and plan.element + 1 in pos_slot: - if source == "positions": - z = value[:, 2] + e1 = e1_a + arc_e1[0] = e1 + for k in range(1, last + 1): + e1 = _transport(e1, chords[:, k - 1], chords[:, k]) + arc_e1[k] = e1 + for plan in plans: + if source == "tangent": + dec = np.radians( + np.stack( + [values[:, slot[("dec", j)]] for j in plan.window], axis=1 + ) + ) + azi = np.radians( + np.stack( + [values[:, slot[("azi", j)]] for j in plan.window], axis=1 + ) + ) + samples = np.stack( + ( + np.sin(dec) * np.cos(azi), + np.sin(dec) * np.sin(azi), + np.cos(dec), + ), + axis=-1, + ) + value, d1, _ = _spline(chord_mid[plan.window], samples, plan.arc) + tangent = _unit(value, "section tangent") + kappa = np.cross(tangent, d1) else: - z = (1 - weight) * positions[ - :, pos_slot[plan.element], 2 - ] + weight * positions[:, pos_slot[plan.element + 1], 2] - append(plan, "z", z) - if use_segments: - if plan.arc <= midpoints[0]: - ten = elem_t[:, ten_slot[0]] - elif plan.arc >= midpoints[-1]: - ten = elem_t[:, ten_slot[n_nodes - 2]] + window = positions[:, [pos_slot[j] for j in plan.window]] + value, d1, d2 = _spline(arcs[plan.window], window, plan.arc) + speed = np.linalg.norm(d1, axis=-1, keepdims=True) + tangent = d1 / speed + kappa = np.cross(d1, d2) / speed**3 + norm = np.linalg.norm(kappa, axis=-1) + append(plan, "norm", norm) + if plan.probe: + node = plan.node + append(plan, "channel", values[:, slot[("curv", node)]]) + continue + if frame == "arc": + axis1 = _transport( + arc_e1[plan.element], chords[:, plan.element], tangent + ) else: - lower = int(np.searchsorted(midpoints, plan.arc, side="right") - 1) - w = (plan.arc - midpoints[lower]) / ( - midpoints[lower + 1] - midpoints[lower] + axis1, state = _time_transport( + tangent, + state_section[plan.name], + reference, + f"section {plan.name!r}", + ) + state_section[plan.name] = state + axis2 = np.cross(tangent, axis1) + weight = (plan.arc - arcs[plan.element]) / reference_l0[plan.element] + if twist_available: + twist = np.radians( + (1 - weight) * values[:, slot[("twist", plan.element)]] + + weight * values[:, slot[("twist", plan.element + 1)]] ) - ten = (1 - w) * elem_t[:, ten_slot[lower]] + w * elem_t[ - :, ten_slot[lower + 1] - ] - else: - ten = (1 - weight) * values[ - :, slot[("ten", plan.element)] - ] + weight * values[:, slot[("ten", plan.element + 1)]] - append(plan, "tension", ten) - append(plans[0], "time", time) - n_rows += nt - first = False + cos, sin = np.cos(twist)[:, None], np.sin(twist)[:, None] + axis1, axis2 = cos * axis1 + sin * axis2, -sin * axis1 + cos * axis2 + append(plan, "twist", twist) + if torque_available: + append( + plan, + "torque", + (1 - weight) * values[:, slot[("torq", plan.element)]] + + weight * values[:, slot[("torq", plan.element + 1)]], + ) + append(plan, "kx", np.sum(kappa * axis1, axis=-1)) + append(plan, "ky", np.sum(kappa * axis2, axis=-1)) + if ( + pos_order + and plan.element in pos_slot + and plan.element + 1 in pos_slot + ): + if source == "positions": + z = value[:, 2] + else: + z = (1 - weight) * positions[ + :, pos_slot[plan.element], 2 + ] + weight * positions[:, pos_slot[plan.element + 1], 2] + append(plan, "z", z) + if use_segments: + if plan.arc <= midpoints[0]: + ten = elem_t[:, ten_slot[0]] + elif plan.arc >= midpoints[-1]: + ten = elem_t[:, ten_slot[n_nodes - 2]] + else: + lower = int( + np.searchsorted(midpoints, plan.arc, side="right") - 1 + ) + w = (plan.arc - midpoints[lower]) / ( + midpoints[lower + 1] - midpoints[lower] + ) + ten = (1 - w) * elem_t[:, ten_slot[lower]] + w * elem_t[ + :, ten_slot[lower + 1] + ] + else: + ten = (1 - weight) * values[ + :, slot[("ten", plan.element)] + ] + weight * values[:, slot[("ten", plan.element + 1)]] + append(plan, "tension", ten) + append(plans[0], "time", time) + n_rows += nt + first = False + finally: + for stream in streams: + stream.close() if n_rows < 2: raise CableSchemaError(f"{paths['main'].name}: fewer than two output rows") diff --git a/tests/test_cabledyn_reader.py b/tests/test_cabledyn_reader.py index fa472e6..538934a 100644 --- a/tests/test_cabledyn_reader.py +++ b/tests/test_cabledyn_reader.py @@ -12,7 +12,9 @@ from __future__ import annotations +import gc import math +import warnings from pathlib import Path import numpy as np @@ -487,6 +489,57 @@ def test_files_from_different_runs_are_rejected(tmp_path): read_cabledyn_sections(root, deck, {"s": 5.0}) +def _read_without_open_files(*args, **kwargs): + """Read, collect, and fail on any file the read left open.""" + with warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always", ResourceWarning) + try: + return read_cabledyn_sections(*args, **kwargs) + finally: + gc.collect() + leaks = [w for w in caught if issubclass(w.category, ResourceWarning)] + assert not leaks, [str(w.message) for w in leaks] + + +def test_reader_closes_every_output_file(tmp_path): + # Main table and both per-line files, read in several chunks. + nt = 50 + positions = _bending_case(np.full(nt, 0.02), np.zeros(nt), nt) + root, deck = _write_case(tmp_path, positions, deck_kwargs={"t_max": 4.9}) + read = _read_without_open_files(root, deck, {"s": 5.0}, chunk_rows=16) + assert read.histories["s"].time_s.size == nt + # A per-line file with an extra row: rejected, and every file closed. + with open(f"{root}.Line1.t.out", "a", encoding="utf-8") as f: + f.write(_fmt([nt * 0.1, *np.full(N_ELEMENTS, 5000.0)]) + "\n") + with pytest.raises(CableSchemaError, match="different row counts"): + _read_without_open_files(root, deck, {"s": 5.0}, chunk_rows=16) + + +def test_deck_options_follow_the_record_forms(tmp_path): + # Positional records (model first, keyword after the numbers), commentary + # after a keyword, the keyword-first dynamic_solver, aliases and the last + # record of a keyword winning. + extra = ( + "uniform 0.0 0.6 0.0 current\n" + "airy 2.0 8.0 0.0 waves - regular waves\n" + "dynamic_solver 1e-8 1e-14 30 12\n" + "1000.0 WtrDnsty water density\n" + "35.0 WtrDpth - depth\n" + "40.0 water_depth\n" + "true adaptive_mesh\n" + ) + deck = read_cabledyn_deck(_deck(tmp_path / "o.dat", extra_options=extra)) + assert deck.options["current"] == "uniform 0.0 0.6 0.0" + assert deck.options["waves"] == "airy 2.0 8.0 0.0" + assert deck.options["dynamic_solver"] == "1e-8 1e-14 30 12" + assert not any(key[0].isdigit() for key in deck.options) + assert deck.rho_w_kg_m3 == 1000.0 # the alias set after rhoW 1025 + assert deck.water_depth_m == 40.0 # the last of WtrDpth / water_depth + assert deck.g_m_s2 == 9.81 and deck.dt_s == 0.1 and deck.t_max_s == 1.0 + assert deck.adaptive_mesh + assert deck.defaults_used == () + + def test_reversed_segment_order_is_rejected(tmp_path): nt = 3 positions = _bending_case(np.full(nt, 0.02), np.zeros(nt), nt) diff --git a/tests/test_sea_state_batch_inputs.py b/tests/test_sea_state_batch_inputs.py index b5a85e6..16016d1 100644 --- a/tests/test_sea_state_batch_inputs.py +++ b/tests/test_sea_state_batch_inputs.py @@ -270,3 +270,15 @@ def test_specification_must_be_an_object(tmp_path): path.write_text("[1, 2]", encoding="utf-8") with pytest.raises(CableInputError, match="must be an object"): load_batch_spec(path) + + +def test_cable_source_is_checked_before_any_run_is_read(tmp_path, cable): + # The runs point nowhere: a late check would fail reading them first. + runs = [SeaStateRun("r", tmp_path / "none", tmp_path / "none.dat", 1.0)] + with pytest.raises(FileNotFoundError, match=r"missing.yaml is not a file"): + run_sea_state_batch( + cable, + runs, + [SectionRequest("a", 2.0)], + cable_source=tmp_path / "missing.yaml", + )