From c6f9b1fec166d6b1664c4daba888b6dd5ab93b70 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 2 Dec 2026 17:05:58 +0900 Subject: [PATCH 1/7] feat: carry the global run's provenance and check the line's wave grid The tension and curvature histories CableXSec reads do not show how the global run formed the line's wave kinematics. In a coupled OpenFAST or FAST.Farm run CableDyn can take them from the SeaState grid: a node outside the grid gets the kinematics of the grid boundary, and a grid with three points across the wave direction interpolates over a large part of a wavelength. CableDyn now stops such runs by default, but waveGridCheck warn lets them finish and older runs never had the check, so a fatigue result could rest on wrong kinematics with nothing in the report to say so. Every set of global histories now carries a GlobalProvenance record: the solver (CableDyn with its version and host, or a declared program such as OrcaFlex 11.6e), the wave route, the fingerprint of the wave components (the sea's identity where a coupled run records no seed), the seed and input file of a standalone run, the grid, and per line the nodes outside the grid, the resolution flags and the spectrally weighted velocity ratio. read_cabledyn_sections reads it from CableDyn's .CD.provenance.json (schema cabledyn.provenance/1, checked field by field; other versions are refused by name, unknown keys ignored, an unfinished run warns), or from the wave-grid messages of a run log, and otherwise records the fields as unknown instead of failing. The record travels with CableDynRead, every section history, the LoadCaseSeries of every reader and the provenance of fatigue_from_series. The policy acts on the analysed line only. Nodes of that line outside the grid with a weighted velocity ratio above wave_grid_tolerance (default 0.01; any node when the ratio is not recorded), or a resolution flag on it, raise WaveKinematicsError under wave_grid_check="error", the default, which matches CableDyn's own default, or warn with WaveKinematicsWarning under "warn". Mooring lines below the grid pass silently and are recorded, so a run whose only grid misses are deep mooring spans reads as before. The sea-state batch passes the options and a per-run log through, writes each run's record and policy outcome to the manifest, and names the runs without a record once in its notes, which cablexsec-batch prints. The record and the options check the read: they enter neither inputs_sha256 nor the assessment digests, so existing digests stay. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 27 + doc/api_python.rst | 16 + doc/cli.rst | 9 +- doc/file_formats.md | 69 +- doc/global_local_guide.md | 81 +- src/cablexsec/__init__.py | 23 +- src/cablexsec/analysis/sea_state_batch.py | 67 +- src/cablexsec/cli.py | 5 +- src/cablexsec/exceptions.py | 17 + src/cablexsec/io/__init__.py | 13 + src/cablexsec/io/ascii_columns_reader.py | 15 +- src/cablexsec/io/cabledyn.py | 65 +- src/cablexsec/io/cabledyn_components.py | 29 +- src/cablexsec/io/global_provenance.py | 1246 +++++++++++++++++ src/cablexsec/io/series.py | 15 + src/cablexsec/io/time_history_csv.py | 9 + src/cablexsec/provenance.py | 27 + .../bad_fingerprint.CD.provenance.json | 58 + .../provenance/bad_route.CD.provenance.json | 58 + .../provenance/bad_type.CD.provenance.json | 58 + .../provenance/cable_resolution_error.log | 28 + tests/data/provenance/clean.log | 15 + .../grid_cable_no_ratio.CD.provenance.json | 64 + .../grid_cable_outside.CD.provenance.json | 86 ++ ...grid_cable_outside_deep.CD.provenance.json | 72 + .../grid_cable_resolution.CD.provenance.json | 60 + .../provenance/grid_clean.CD.provenance.json | 63 + .../grid_moorings_outside.CD.provenance.json | 86 ++ tests/data/provenance/init.CD.provenance.json | 58 + tests/data/provenance/moorings_warn.log | 26 + tests/data/provenance/old_format.log | 21 + .../provenance/schema_v2.CD.provenance.json | 58 + .../provenance/spectral.CD.provenance.json | 50 + .../standalone_deck.CD.provenance.json | 53 + tests/data/provenance/truncated_warn.log | 21 + tests/test_global_provenance.py | 655 +++++++++ validation/validation_report.md | 2 +- 37 files changed, 3310 insertions(+), 15 deletions(-) create mode 100644 src/cablexsec/io/global_provenance.py create mode 100644 tests/data/provenance/bad_fingerprint.CD.provenance.json create mode 100644 tests/data/provenance/bad_route.CD.provenance.json create mode 100644 tests/data/provenance/bad_type.CD.provenance.json create mode 100644 tests/data/provenance/cable_resolution_error.log create mode 100644 tests/data/provenance/clean.log create mode 100644 tests/data/provenance/grid_cable_no_ratio.CD.provenance.json create mode 100644 tests/data/provenance/grid_cable_outside.CD.provenance.json create mode 100644 tests/data/provenance/grid_cable_outside_deep.CD.provenance.json create mode 100644 tests/data/provenance/grid_cable_resolution.CD.provenance.json create mode 100644 tests/data/provenance/grid_clean.CD.provenance.json create mode 100644 tests/data/provenance/grid_moorings_outside.CD.provenance.json create mode 100644 tests/data/provenance/init.CD.provenance.json create mode 100644 tests/data/provenance/moorings_warn.log create mode 100644 tests/data/provenance/old_format.log create mode 100644 tests/data/provenance/schema_v2.CD.provenance.json create mode 100644 tests/data/provenance/spectral.CD.provenance.json create mode 100644 tests/data/provenance/standalone_deck.CD.provenance.json create mode 100644 tests/data/provenance/truncated_warn.log create mode 100644 tests/test_global_provenance.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 820788d..114a2e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,33 @@ All notable changes to CableXSec are recorded in this file. The format follows ## [Unreleased] +### Added + +- Global-analysis provenance (`cablexsec.io.global_provenance`): every set of global histories + carries a `GlobalProvenance` record of the run that produced it: the global solver (CableDyn + with its version and host program, or a declared program such as `OrcaFlex 11.6e`), the wave + route (`seastate_grid`, `seastate_spectral`, `deck` or `none`), the fingerprint of the wave + components (which identifies the sea where a coupled run records no seed), the seed and input + file of a standalone run, and per line the nodes outside the wave-kinematics grid, the grid resolution flags and the + spectrally weighted velocity ratio. `read_cabledyn_sections` reads it from CableDyn's + `.CD.provenance.json` (schema `cabledyn.provenance/1`, checked field by field; another + version is refused by name, and an unfinished run warns with `UnfinishedRunWarning`), or from + the wave-grid messages of the run log (`log=`, `read_cabledyn_log`). The record travels with + `CableDynRead.provenance`, every `CableDynSectionHistory`, the `LoadCaseSeries` of every reader + (`global_provenance=`) and the provenance of `fatigue_from_series`. +- Wave-grid policy for the analysed line (`check_wave_kinematics`): a line whose record shows + nodes outside the wave grid with a spectrally weighted velocity ratio above + `wave_grid_tolerance` (default 0.01; any node outside when the ratio is not recorded), or a + grid resolution flag, is refused with `WaveKinematicsError` (`wave_grid_check="error"`, the + default) or warned about with `WaveKinematicsWarning` (`"warn"`). Nodes of other lines outside + the grid pass without a warning and are recorded. A missing record never fails a read: its + fields are recorded as unknown. +- Sea-state batch: `SeaStateBatchOptions.wave_grid_check` and `wave_grid_tolerance`, + `SeaStateRun.log` (run key `log` in JSON); the manifest writes each run's record + (`runs[i].global_provenance`) and policy outcome (`runs[i].checks.wave_kinematics`), and names + the runs without a record once in `notes`, which `cablexsec-batch` prints. The options and the + record do not enter `inputs_sha256` or the assessment digests. + ## [0.2.2] - 2026-12-01 The Python interfaces are versioned but may change before `1.0.0`. The evidence for diff --git a/doc/api_python.rst b/doc/api_python.rst index 796237d..38c5db0 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -65,3 +65,19 @@ Global results .. autofunction:: cablexsec.read_cabledyn_range_graph .. autofunction:: cablexsec.read_cabledyn_lift .. autofunction:: cablexsec.run_sea_state_batch + +Global-analysis provenance +-------------------------- + +.. automodule:: cablexsec.io.global_provenance + :no-members: + +.. autoclass:: cablexsec.GlobalProvenance + :members: summary, to_record, line, unknown_fields, known, wave_route +.. autofunction:: cablexsec.read_cabledyn_provenance +.. autofunction:: cablexsec.read_cabledyn_log +.. autofunction:: cablexsec.check_wave_kinematics +.. autoclass:: cablexsec.io.global_provenance.WaveKinematicsAssessment +.. autoclass:: cablexsec.WaveKinematicsWarning +.. autoclass:: cablexsec.UnfinishedRunWarning +.. autoclass:: cablexsec.WaveKinematicsError diff --git a/doc/cli.rst b/doc/cli.rst index f305f9e..62dc6f8 100644 --- a/doc/cli.rst +++ b/doc/cli.rst @@ -16,13 +16,16 @@ Computes the weighted annual armour damage from a set of CableDyn sea-state runs shipped with the package), the CableDyn runs with their probabilities and retained windows, the material sections and the options; :func:`cablexsec.analysis.sea_state_batch.load_batch_spec` documents every key. The output directory must not exist. It receives ``manifest.json`` (input -digests, checks, options and results), the annual fixed-fibre damage of every section and the -section history of every run. ``--workers`` overrides the number of worker processes of the +digests, checks, options, the provenance of every run and results), the annual fixed-fibre +damage of every section and the section history of every run. ``--workers`` overrides the number of worker processes of the specification; each worker runs with one thread (``OMP_NUM_THREADS`` and the related variables default to ``1``). The console prints one line per section with the arc length, the annual damage, the life in -years and the critical layer, followed by the SHA-256 digest of the inputs. The +years and the critical layer, then a ``note:`` line naming the runs whose global-analysis +provenance is unknown (no CableDyn provenance file and no run log), if any, and the SHA-256 +digest of the inputs. A run whose line had wave kinematics outside the wave grid stops the batch +or warns, as ``wave_grid_check`` in the options sets (:doc:`global_local_guide`, Section 3.1). The :doc:`global_local_guide` explains the specification, the sign conventions of the CableDyn section tables and the interpretation of the results. diff --git a/doc/file_formats.md b/doc/file_formats.md index fe48c00..890581d 100644 --- a/doc/file_formats.md +++ b/doc/file_formats.md @@ -407,6 +407,7 @@ Every reader returns a `LoadCaseSeries`, the history of one cable section: | `axial_strain`, `axial_strain_kind` | – | optional strain; `direct`, `total` or `unspecified` | | `temperature_C` | °C | optional; `None` for an isothermal record | | `source`, `provenance` | – | where the record came from | +| `global_provenance` | – | how the global run was made (solver, wave route, per-line wave-grid findings; below) | The arrays are read-only copies. `dataclasses.replace` makes an edited series. @@ -572,6 +573,65 @@ from CableDyn's section `x` axis. `right_handed=False` reverses `y` for a left-handed triad. `cablexsec.io.series_from_curvature_components` builds the same series from arrays. +### Global-analysis provenance + +Every reader attaches a `GlobalProvenance` record +(`cablexsec.io.global_provenance`) to what it returns. For a CableDyn run it +reads, next to the output, the file `.CD.provenance.json` that CableDyn +writes (for `x3.CD.out`, `x3.CD.provenance.json`). Schema version 1: + +```json +{ + "schema": "cabledyn.provenance/1", + "cabledyn_version": "0.4.4", + "host": "openfast", + "host_version": "4.1.2", + "waves": {"route": "seastate_grid", "wave_mod": 2, "wave_seed": null, + "component_fingerprint": "9f3c2a71b4e05d18", + "wave_hs": null, "wave_tp": null, "wave_dir_deg": 30.0, "wave_dir_mod": 0, + "n_components": 2400, "wave_dt": 0.2, "wave_tmax": 3600.0, + "effective_water_depth": 200.0, "wave_kin_tol": null, + "source_file": null}, + "grid": {"nx": 40, "ny": 40, "nz": 16, "x_half_width": 250.0, + "y_half_width": 250.0, "z_depth": 120.0, "wave_grid_check": "error"}, + "lines": [{"id": 1, "n_nodes": 101, "out_of_grid": null, "resolution_flags": [], + "dropped_velocity_variance_max": null, + "dropped_acceleration_variance_max": null}], + "status": "complete" +} +``` + +| Key | Values | +| --- | --- | +| `schema` | `cabledyn.provenance/1`; another version or schema is refused by name | +| `host` | `openfast`, `fast.farm`, `standalone` or `capi` | +| `waves.route` | `seastate_grid`, `seastate_spectral`, `deck` or `none` | +| `waves.wave_seed` | a list of integers or strings (`RANLUX`); `null` in a coupled run, as are `wave_hs`, `wave_tp` and `source_file` (SeaState does not pass them on); a standalone run gives what its deck has | +| `waves.component_fingerprint` | 16 hexadecimal digits, the 64-bit FNV-1a hash of the wave components: equal fingerprints mean the same sea; `null` for still water and `WaveMod` 6. Where the seed is `null` it is the identity of the sea in reports | +| `grid` | `null`, or the grid with `wave_grid_check` `error` or `warn` | +| `lines[].out_of_grid` | `null`, or `n_nodes_max`, `first_time` [s], `deepest_xyz` and `shallowest_xyz` [m], `weighted_velocity_ratio_max` | +| `lines[].resolution_flags` | a list of strings | +| `status` | `complete`, or `init` for a run that did not finish (read with an `UnfinishedRunWarning`) | + +Any field may be `null`, which records it as unknown. A defined field of +another type, or an enumerated field with another value, is refused with its +path named (`record.lines[0].n_nodes`); keys the schema does not define are +ignored. Without the file, `read_cabledyn_sections(..., log=...)` reads the +wave-grid messages of the run log instead (`read_cabledyn_log`), and without +either the record holds only that CableDyn wrote the output. An exported +history records no wave route: `read_time_history_csv`, `read_ascii_columns` +and `read_cabledyn_station_table` take `global_provenance="OrcaFlex 11.6e"` +(or a `GlobalProvenance`) to declare the program, and the last two read a +comment line that names it. + +`record.to_record()` gives the JSON form written to the batch manifest, with +the record's `origin` (`sidecar`, `log`, `declared`, `output` or `none`), the +file read and its SHA-256, and the list `unknown` of the key fields it does not +give. The wave-grid policy for the analysed line +([global–local guide](global_local_guide.md) Section 3.1) is +`check_wave_kinematics(record, line_id, wave_grid_check="error", +wave_grid_tolerance=0.01)`. + ### Synthetic records `cx.jonswap_series(...)` generates a record whose curvature has the shape of a @@ -587,14 +647,19 @@ object with four keys: | Key | Content | | --- | --- | | `cable` | a YAML path, or `bundled:` for a bundled cable such as `bundled:iea_task49_66kv` | -| `runs` | `name`, `out_root`, `deck`, `probability`; optional `line_id`, `start_time_s`, `end_time_s` | +| `runs` | `name`, `out_root`, `deck`, `probability`; optional `line_id`, `start_time_s`, `end_time_s`, `hang_off_rotation`, `log` (the run log, read for CableDyn's wave-grid messages when there is no provenance file) | | `sections` | `name`, `arc_length_m`; optional `termination` (the fields of `TerminationSpec`, for example `distance_m` and `k_anchor_N_m`; a record without `k_anchor_N_m` has a rigid anchor), `thermal`, `fretting`, `sn_curves`, `mean_stress`, `scf` | | `options` | the fields of `SeaStateBatchOptions` | Relative paths are resolved against the folder of the JSON file, and unknown keys are rejected. The output folder receives `manifest.json`, with the SHA-256 digests of every input, the options, checks and results, together -with `
_annual_damage.npz` and `
__history.npz`. +with `
_annual_damage.npz` and `
__history.npz`. In the +manifest, `runs[i].global_provenance` is the run's provenance record (above), +`runs[i].checks.wave_kinematics` the wave-grid policy outcome for the run's +line (`status` `pass`, `affected` or `unknown`, `reasons`, `notes`, +`other_lines_affected`), `wave_grid_check` the policy options, and `notes` +names, once, the runs whose provenance is unknown. Section 3 of the [global–local guide](global_local_guide.md) gives an example. diff --git a/doc/global_local_guide.md b/doc/global_local_guide.md index cea66ff..257eea6 100644 --- a/doc/global_local_guide.md +++ b/doc/global_local_guide.md @@ -12,6 +12,7 @@ bend stiffener); the hysteretic two-way element is stage 2 (Section 7). |---|---| | Reader | `cablexsec.io.cabledyn`: `read_cabledyn_deck`, `read_cabledyn_sections`, `section_channels`, `CableDynSectionHistory`, `read_cabledyn_range_graph`, `read_cabledyn_lift` | | Sea-state batch | `cablexsec.analysis.sea_state_batch`: `run_sea_state_batch`, `SeaStateRun`, `SectionRequest`, `SeaStateBatchOptions`, `load_batch_spec` | +| Run provenance | `cablexsec.io.global_provenance`: `GlobalProvenance`, `read_cabledyn_provenance`, `read_cabledyn_log`, `check_wave_kinematics` (Section 3.1) | | Command line | `cablexsec-batch batch.json --output-directory ` | | Tests | `tests/test_cabledyn_reader.py`, `tests/test_cabledyn_outputs.py`, `tests/test_sea_state_batch.py`; genuine CableDyn output in `tests/data/cabledyn/` | @@ -488,9 +489,15 @@ result.sections["sag"].long_term.annual_damage, result.sections["sag"].life_year `CABLEXSEC_BATCH_CACHE_DIR` to move it), so later batches start warm; a slot is held by one worker at a time, a worker beyond the 16 slots gets a temporary cache, and deleting the folder only costs a recompilation. +- Wave kinematics: each run's provenance is read with its histories and the + run's line is checked against the wave grid (Section 3.1); + `wave_grid_check` (`"error"`, default, or `"warn"`) and + `wave_grid_tolerance` (default 0.01) set the policy, and a run's `log` + (key `log` in JSON) is read when CableDyn wrote no provenance file. - 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); + reader checks per run, the provenance of every run, results, and + `inputs_sha256` over the inputs of the results); `
_annual_damage.npz` (per layer, wire and fibre); `
__history.npz` (columns as the `local_response` histories of local recovery: `time_s`, `effective_tension_N`, `true_tension_N`, @@ -519,6 +526,78 @@ The command line takes the same inputs as JSON: Paths are relative to the JSON file; unknown keys are rejected. +### 3.1 Global-analysis provenance and the wave grid + +The histories of a global run do not show how the line's wave kinematics were +formed. In a coupled OpenFAST or FAST.Farm run CableDyn can take them from the +SeaState grid: a node outside the grid then gets the kinematics of the grid +boundary, and a grid with only three points across the wave direction +interpolates over a large part of a wavelength. CableDyn stops such runs by +default, but `waveGridCheck warn` lets them finish, and runs made before the +check never had it. CableXSec therefore reads, with every set of histories, a +record of how the run was made (`GlobalProvenance`): + +| Field | Content | +|---|---| +| solver | `cabledyn` with its version and host (`openfast`, `fast.farm`, `standalone`, `capi`) and the host version; `orcaflex` or another declared program for an export | +| wave route | `seastate_grid`, `seastate_spectral`, `deck` or `none` | +| waves | the fingerprint of the wave components (16 hexadecimal digits: equal fingerprints, same sea), direction, component count, wave time step and duration, effective water depth, the truncation tolerance of the spectral route; for a standalone run also the seed (integers or names such as `RANLUX`), `Hs`, `Tp` and input file, which a coupled run does not record (SeaState does not pass them on) | +| grid | `NX`, `NY`, `NZ`, half-widths, `Z_Depth` and CableDyn's `waveGridCheck` mode | +| per line | nodes outside the grid (largest count, first time, deepest and shallowest node, largest spectrally weighted velocity ratio), grid resolution flags, and on the spectral route the largest dropped velocity and acceleration variance | + +The record comes from, in order: the file CableDyn writes next to its output, +`.CD.provenance.json` (schema `cabledyn.provenance/1`); the wave-grid +messages of the run log, when the log is passed (`log=` of +`read_cabledyn_sections`, `SeaStateRun.log`, the run key `log` in JSON); or the +output alone, which shows only that CableDyn wrote it (and the standalone +driver for `.out`). The log names the lines with nodes outside the grid +or between grid points, but not their weighted velocity ratio; a log message +that names no lines, or cuts its list short, leaves the other lines unknown. +A record of another schema version, or with a field of the wrong type or an +unknown value of an enumerated field, is refused with the field named; keys the +schema does not define are ignored. A record of a run that did not finish +(`status` `init`) warns (`UnfinishedRunWarning`). + +**Policy.** Only the analysed line counts. The read is refused +(`WaveKinematicsError`; `wave_grid_check="error"`, the default) or warned about +(`WaveKinematicsWarning`; `"warn"`) when the record shows that line with + +- nodes outside the grid whose largest spectrally weighted velocity ratio (the + rms wave velocity at the node over that at the surface, integrated over the + sea's spectrum) exceeds `wave_grid_tolerance` (default 0.01; a record without + the ratio, such as a log, counts any node outside), or +- a grid resolution flag (the record gives no measure for these, so any flag + counts). + +At a ratio of 0.01 the wave velocity at the node is a hundredth of that at the +surface, and the wave drag, quadratic in it, about a ten-thousandth. Nodes of +other lines outside the grid, such as the deep spans of mooring lines, pass +without a warning and are recorded (`other_lines_affected`). A record that does +not cover the line (no provenance, or a log that does not name every line) +passes with the status `unknown`. + +**Where it appears.** `CableDynRead.provenance` and every +`CableDynSectionHistory.global_provenance` hold the record, and the series of +`to_load_case_series` carry it on. `checks["wave_kinematics"]` holds the policy +outcome (`status` `pass`, `affected` or `unknown`, the reasons, notes and other +lines). The history's provenance limitations and the provenance of +`fatigue_from_series` give a one-line summary, for example +`global analysis: CableDyn 0.4.4 (OpenFAST 4.1.2); waves seastate_grid, +components 9f3c2a71b4e05d18; line 1: inside the wave grid, no resolution +flags`, where the fingerprint stands for the seed a coupled run does not +record (a standalone run gives `seed 123456789, RANLUX`). The batch manifest writes the record of every run under +`runs[i].global_provenance` and the outcome under +`runs[i].checks.wave_kinematics`; runs without a record are named once in the +manifest's `notes`, which the command line prints. The record checks the read +and does not enter `inputs_sha256` or the assessment digests. + +Exported histories (`read_time_history_csv`, `read_ascii_columns`, +`read_cabledyn_station_table`) carry a record too. An export does not record +its wave route, so those fields stay unknown: `global_provenance="OrcaFlex +11.6e"` declares the program and its version, and a comment line of an ASCII +export or a station table that names them (`# OrcaFlex 11.6e`, `# CableDyn +0.4.3`) is read. + ## 4. Verification | Check | Result | diff --git a/src/cablexsec/__init__.py b/src/cablexsec/__init__.py index b9aaf10..5842b31 100644 --- a/src/cablexsec/__init__.py +++ b/src/cablexsec/__init__.py @@ -263,7 +263,12 @@ XsecStiffnessResult, xsec_stiffness, ) -from cablexsec.exceptions import CableInputError, CableLookupError, CableSolverError +from cablexsec.exceptions import ( + CableInputError, + CableLookupError, + CableSolverError, + WaveKinematicsError, +) from cablexsec.io import ( LoadCaseSeries, fatigue_from_series, @@ -276,6 +281,12 @@ read_time_history_csv, write_series_csv, ) +from cablexsec.io.global_provenance import ( + GlobalProvenance, + check_wave_kinematics, + read_cabledyn_log, + read_cabledyn_provenance, +) from cablexsec.materials.library import register_material, unregister_material from cablexsec.materials.mean_stress import MEAN_STRESS_METHODS, MeanStressSpec from cablexsec.materials.sn_curves import ( @@ -326,7 +337,9 @@ FrictionModelFallbackWarning, MissingClampingStateWarning, TorsionalStressWarning, + UnfinishedRunWarning, UnmodelledPolymerSofteningWarning, + WaveKinematicsWarning, ) __version__ = "0.2.2" @@ -573,6 +586,11 @@ "read_cabledyn_lift", "read_cabledyn_range_graph", "read_cabledyn_sections", + # global-analysis provenance (solver, waves, wave grid) + "GlobalProvenance", + "check_wave_kinematics", + "read_cabledyn_log", + "read_cabledyn_provenance", "run_sea_state_batch", "SeaStateRun", "SectionRequest", @@ -608,6 +626,8 @@ "MissingClampingStateWarning", "TorsionalStressWarning", "UnmodelledPolymerSofteningWarning", + "UnfinishedRunWarning", + "WaveKinematicsWarning", "CableXSecError", "CableInputError", "CableLookupError", @@ -615,6 +635,7 @@ "CableSchemaError", "BlockedSNCurveError", "PhysicalRangeError", + "WaveKinematicsError", ] # Public functions that take a cable read its own materials in its material diff --git a/src/cablexsec/analysis/sea_state_batch.py b/src/cablexsec/analysis/sea_state_batch.py index 0e419e3..2d5ddb4 100644 --- a/src/cablexsec/analysis/sea_state_batch.py +++ b/src/cablexsec/analysis/sea_state_batch.py @@ -50,6 +50,18 @@ 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. + +Global-analysis provenance +-------------------------- +Every run's provenance (:mod:`cablexsec.io.global_provenance`: solver, wave +route and seed, the per-line wave-grid findings) is read with its histories, +from CableDyn's ``.CD.provenance.json`` or the run's ``log``, and +written to the manifest (``runs[i].global_provenance``, with the policy +outcome for the run's line under ``checks.wave_kinematics``). A run whose line +has nodes outside the wave grid above ``wave_grid_tolerance``, or a grid +resolution flag, stops the batch (``wave_grid_check="error"``, the default) +or warns (``"warn"``); nodes of other lines do not. Runs without a record are +listed once in the manifest's ``notes``. """ from __future__ import annotations @@ -108,6 +120,11 @@ read_cabledyn_deck, read_cabledyn_sections, ) +from cablexsec.io.global_provenance import ( + DEFAULT_WAVE_GRID_TOLERANCE, + WaveGridCheck, + unknown_runs_note, +) from cablexsec.provenance import TorsionalStressWarning FloatArray = NDArray[np.float64] @@ -147,7 +164,9 @@ class SeaStateRun: ``hang_off_rotation`` is the run's ``hang_off_rotation`` of :func:`~cablexsec.io.cabledyn.read_cabledyn_sections` (the turn of the holder of a line restrained in torsion at End A): ``None``, ``"none"``, - or an array with one entry per output row. + or an array with one entry per output row. ``log`` is the run's log, read + for CableDyn's wave-grid messages when the run has no + ``.CD.provenance.json``. """ name: str @@ -158,12 +177,15 @@ class SeaStateRun: start_time_s: float = 0.0 end_time_s: float | None = None hang_off_rotation: Any = field(default=None, compare=False) + log: Path | None = None def __post_init__(self) -> None: if not self.name.strip() or "/" in self.name or "\\" in self.name: 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 self.log is not None: + object.__setattr__(self, "log", Path(self.log)) if ( isinstance(self.line_id, bool) or not isinstance(self.line_id, int) @@ -249,6 +271,14 @@ class SeaStateBatchOptions: default ``False`` a section whose history has a twist rate warns (:class:`~cablexsec.provenance.TorsionalStressWarning`) that its torsional stress is omitted, and the result is that of earlier releases. + + ``wave_grid_check`` and ``wave_grid_tolerance`` are the wave-grid policy + of :func:`~cablexsec.io.cabledyn.read_cabledyn_sections`: a run whose line + had nodes outside the wave grid with a spectrally weighted velocity ratio + above the tolerance (any node when the record has no ratio), or a grid + resolution flag, stops the batch (``"error"``, default) or warns + (``"warn"``, :class:`~cablexsec.provenance.WaveKinematicsWarning`). They + check the read and are left out of the assessment digests. """ n_fibres: int = 32 @@ -280,6 +310,10 @@ class SeaStateBatchOptions: twist_stress: bool = False workers: int = 1 chunk_rows: int = 4096 + #: Wave-grid policy of the read + #: (:func:`~cablexsec.io.global_provenance.check_wave_kinematics`). + wave_grid_check: WaveGridCheck = "error" + wave_grid_tolerance: float = DEFAULT_WAVE_GRID_TOLERANCE def __post_init__(self) -> None: if ( @@ -336,6 +370,15 @@ def __post_init__(self) -> None: raise CableInputError("property_rtol must be positive") if not math.isfinite(self.torsion_rtol) or self.torsion_rtol <= 0: raise CableInputError("torsion_rtol must be positive") + if self.wave_grid_check not in ("error", "warn"): + raise CableInputError("wave_grid_check must be 'error' or 'warn'") + if ( + isinstance(self.wave_grid_tolerance, bool) + or not isinstance(self.wave_grid_tolerance, int | float) + or not math.isfinite(self.wave_grid_tolerance) + or self.wave_grid_tolerance < 0 + ): + raise CableInputError("wave_grid_tolerance must be a finite number >= 0") object.__setattr__( self, "reference_vector", tuple(float(v) for v in self.reference_vector) ) @@ -800,6 +843,9 @@ def _evaluate(task: _Task) -> dict[str, Any]: curvature_check_rtol=opts.curvature_check_rtol, curvature_check_end_rtol=opts.curvature_check_end_rtol, curvature_check_atol_1_m=opts.curvature_check_atol_1_m, + log=run.log, + wave_grid_check=opts.wave_grid_check, + wave_grid_tolerance=opts.wave_grid_tolerance, ) results: dict[str, Any] = {} histories: dict[str, CableDynSectionHistory] = {} @@ -916,6 +962,7 @@ def _evaluate(task: _Task) -> dict[str, Any]: "results": results, "histories": histories, "checks": dict(read.checks), + "provenance": read.provenance, "files": [ { "role": f.role, @@ -1044,6 +1091,7 @@ def _mismatches(record: Mapping[str, Any]) -> list[str]: "start_time_s", "end_time_s", "hang_off_rotation", + "log", } _SECTION_KEYS = { "name", @@ -1098,7 +1146,7 @@ def load_batch_spec( [...], "options": {...}}``. Run keys: ``name``, ``out_root``, ``deck``, ``probability``, optional ``line_id``, ``start_time_s``, ``end_time_s``, ``hang_off_rotation`` (``"none"`` or nested lists, one entry per output - row). + row), ``log`` (the run's log, for its wave-grid messages). Section keys: ``name``, ``arc_length_m``, optional ``termination`` (the :class:`TerminationSpec` fields), ``thermal`` (the :class:`ThermalState` fields), ``fretting``, ``sn_curves`` (layer to registered curve name), @@ -1144,6 +1192,7 @@ def resolve(value: str) -> Path: if record.get("end_time_s") is None else float(record["end_time_s"]), hang_off_rotation=record.get("hang_off_rotation"), + log=None if record.get("log") is None else resolve(record["log"]), ) ) sections = [] @@ -1311,6 +1360,8 @@ def run_sea_state_batch( "curvature_check_rtol", "curvature_check_end_rtol", "curvature_check_atol_1_m", + "wave_grid_check", + "wave_grid_tolerance", ): # A check of the read, not an input of the result: the digests of # existing assessments stay. @@ -1436,6 +1487,10 @@ def run_sea_state_batch( "end_rtol": opts.curvature_check_end_rtol, "atol_1_m": opts.curvature_check_atol_1_m, }, + "wave_grid_check": { + "check": opts.wave_grid_check, + "tolerance": opts.wave_grid_tolerance, + }, "workers": opts.workers, "tension_basis": basis, "external_diameter_m": diameter, @@ -1449,6 +1504,7 @@ def run_sea_state_batch( "hang_off_rotation": _hang_off_record(run.hang_off_rotation), "files": outcome["files"], "checks": outcome["checks"], + "global_provenance": outcome["provenance"].to_record(), } for run, outcome in zip(runs, outcomes, strict=True) ], @@ -1474,6 +1530,13 @@ def run_sea_state_batch( for name, result in results.items() }, } + note = unknown_runs_note( + { + run.name: outcome["provenance"] + for run, outcome in zip(runs, outcomes, strict=True) + } + ) + manifest["notes"] = [] if note is None else [note] if capacity is not None: manifest["capacity_check"] = { "envelope_source": capacity.envelope.source, diff --git a/src/cablexsec/cli.py b/src/cablexsec/cli.py index b9cf33d..29860c5 100644 --- a/src/cablexsec/cli.py +++ b/src/cablexsec/cli.py @@ -11,7 +11,8 @@ and retained windows, the material sections and the options (see :func:`cablexsec.analysis.sea_state_batch.load_batch_spec` and the global-to-local guide of the manual). The output directory must not exist; it -receives ``manifest.json`` (input digests, checks, options and results), the +receives ``manifest.json`` (input digests, checks, options, the provenance +of every run and results), the annual fixed-fibre damage of every section and the section history of every run. """ @@ -79,6 +80,8 @@ def batch_main(argv: list[str] | None = None) -> int: f"{section.long_term.annual_damage:>13.4e}{life:>12} " f"{section.long_term.critical_layer}" ) + for note in result.manifest["notes"]: + print(f"note: {note}") print(f"inputs sha256 {result.manifest['inputs_sha256']}") return 0 diff --git a/src/cablexsec/exceptions.py b/src/cablexsec/exceptions.py index 4f94214..8fac65c 100644 --- a/src/cablexsec/exceptions.py +++ b/src/cablexsec/exceptions.py @@ -22,6 +22,9 @@ a hard error, distinct from the *soft* extrapolation warning of :mod:`cablexsec.provenance` +:class:`WaveKinematicsError` the global run gave the analysed line wave + kinematics outside its wave grid or from an + under-resolved grid (a ``CableSchemaError``) ========================== ================================================== ``BlockedSNCurveError`` and ``PhysicalRangeError`` also subclass the builtin @@ -47,6 +50,7 @@ "CableLookupError", "CableSolverError", "PhysicalRangeError", + "WaveKinematicsError", ] @@ -97,3 +101,16 @@ class PhysicalRangeError(CableXSecError, ValueError): which a model was validated. Catchable as ``CableXSecError`` or ``ValueError``. """ + + +class WaveKinematicsError(CableSchemaError): + """The analysed line of a global run had wave kinematics it should not have. + + Raised by :func:`cablexsec.io.global_provenance.check_wave_kinematics` (and + so by :func:`cablexsec.io.cabledyn.read_cabledyn_sections` and the + sea-state batch) under ``wave_grid_check="error"``, the default, when the + run's provenance record shows nodes of the analysed line outside the wave + kinematics grid above the tolerance, or a grid resolution flag on that + line. ``wave_grid_check="warn"`` turns it into a + :class:`cablexsec.provenance.WaveKinematicsWarning`. + """ diff --git a/src/cablexsec/io/__init__.py b/src/cablexsec/io/__init__.py index dd6bc22..ffb31f9 100644 --- a/src/cablexsec/io/__init__.py +++ b/src/cablexsec/io/__init__.py @@ -25,6 +25,9 @@ ``CurvY``), sign-mapped to the strain gradient. - :func:`~cablexsec.io.series.fatigue_from_series` — map a series onto :func:`cablexsec.compute_fatigue`. +- :mod:`~cablexsec.io.global_provenance` — how the global run was made + (solver, wave route and seed, per-line wave-grid findings), carried with + every history, and the wave-grid policy for the analysed line. """ from __future__ import annotations @@ -44,6 +47,12 @@ read_cabledyn_station_table, series_from_curvature_components, ) +from cablexsec.io.global_provenance import ( + GlobalProvenance, + check_wave_kinematics, + read_cabledyn_log, + read_cabledyn_provenance, +) from cablexsec.io.series import ( LoadCaseSeries, fatigue_from_series, @@ -57,11 +66,15 @@ "CableDynLift", "CableDynRangeGraph", "CableDynSectionHistory", + "GlobalProvenance", "LoadCaseSeries", + "check_wave_kinematics", "fatigue_from_series", "jonswap_series", "read_cabledyn_deck", "read_cabledyn_lift", + "read_cabledyn_log", + "read_cabledyn_provenance", "read_cabledyn_range_graph", "read_cabledyn_sections", "read_cabledyn_station_table", diff --git a/src/cablexsec/io/ascii_columns_reader.py b/src/cablexsec/io/ascii_columns_reader.py index 970c5bb..b038681 100644 --- a/src/cablexsec/io/ascii_columns_reader.py +++ b/src/cablexsec/io/ascii_columns_reader.py @@ -23,6 +23,7 @@ from numpy.typing import NDArray from cablexsec.exceptions import CableSchemaError +from cablexsec.io.global_provenance import GlobalProvenance, declared_provenance from cablexsec.io.series import LoadCaseSeries from cablexsec.mechanics.section_conventions import rotation_to_strain_curvature from cablexsec.provenance import Provenance @@ -45,6 +46,7 @@ def read_ascii_columns( tension_scale_to_N: float = 1.0, tension_kind: Literal["true", "effective", "unspecified"] = "unspecified", curvature_convention: Literal["strain_gradient", "rotation"] = "strain_gradient", + global_provenance: GlobalProvenance | str | None = None, ) -> LoadCaseSeries: r"""Read a whitespace-column ASCII time history into a :class:`LoadCaseSeries`. @@ -69,6 +71,12 @@ def read_ascii_columns( ``rotation`` for right-handed rod rotation components (fibre strain ``k_x*y - k_y*x``); the reader then maps them to the section strain gradient ``(-k_y, k_x)``. Verify the source convention. + global_provenance : GlobalProvenance or str, optional + The global run's record (:mod:`cablexsec.io.global_provenance`), or a + declaration of the solver, such as ``"OrcaFlex 11.6e"``. Without it a + comment line naming the solver and its version is taken; failing that + every field is unknown, which the record and the fatigue provenance + state. Returns ------- @@ -105,9 +113,13 @@ def read_ascii_columns( raise CableSchemaError( f"{p.name}: not a text file (neither UTF-8 nor Windows-1252)." ) from None + comments: list[str] = [] for ln, line in enumerate(text.splitlines(), start=1): s = line.strip() - if not s or s.startswith(comment_prefixes): + if s.startswith(comment_prefixes): + comments.append(s) + continue + if not s: continue fields = s.split() for key, col in chosen.items(): @@ -140,6 +152,7 @@ def read_ascii_columns( temperature_C=arr.get("temp"), tension_kind=tension_kind, source=p.name, + global_provenance=declared_provenance(global_provenance, comments=comments), provenance=Provenance( method="whitespace-column ASCII time-history reader (positional columns)", citations=(), diff --git a/src/cablexsec/io/cabledyn.py b/src/cablexsec/io/cabledyn.py index cb261f9..69efb7f 100644 --- a/src/cablexsec/io/cabledyn.py +++ b/src/cablexsec/io/cabledyn.py @@ -190,6 +190,18 @@ bend stiffener, the sleeve's share, and its conversion would need a torsional law where the twist rate is the global model's own kinematics. +Wave-kinematics provenance +-------------------------- +The run's provenance (:mod:`cablexsec.io.global_provenance`) is read before +the histories: CableDyn's ``.CD.provenance.json`` when it exists, else +the wave-grid messages of the run log passed as ``log``, else what the output +shows. It travels with every history (``global_provenance``) and the read +(:attr:`CableDynRead.provenance`), and ``checks["wave_kinematics"]`` holds the +policy outcome for the line read: a line with nodes outside the wave grid +above ``wave_grid_tolerance``, or with a grid resolution flag, is refused +(``wave_grid_check="error"``) or warned about (``"warn"``); other lines and an +unknown record pass. + Every required file, column and channel is checked by name and unit; a missing one raises :class:`~cablexsec.exceptions.CableSchemaError` naming it. """ @@ -212,6 +224,13 @@ from numpy.typing import ArrayLike, NDArray from cablexsec.exceptions import CableSchemaError +from cablexsec.io.global_provenance import ( + DEFAULT_WAVE_GRID_TOLERANCE, + GlobalProvenance, + WaveGridCheck, + cabledyn_provenance, + check_wave_kinematics, +) from cablexsec.io.series import LoadCaseSeries from cablexsec.mechanics.section_conventions import ( rotation_to_strain_curvature, @@ -2280,6 +2299,9 @@ class CableDynSectionHistory: :func:`cablexsec.compute_fatigue` and :func:`cablexsec.compute_conductor_fatigue`. ``None`` when the channels are not written. + global_provenance : GlobalProvenance or None + How the run was made: solver, wave route and seed, and the line's + wave-grid findings (:mod:`cablexsec.io.global_provenance`). """ name: str @@ -2301,6 +2323,7 @@ class CableDynSectionHistory: source: str provenance: Provenance twist_rate_per_m: FloatArray | None = None + global_provenance: GlobalProvenance | None = None def __post_init__(self) -> None: n = np.asarray(self.time_s).size @@ -2391,6 +2414,7 @@ def to_load_case_series(self, external_area_m2: float) -> LoadCaseSeries: source=self.source, provenance=self.provenance, tension_kind="true", + global_provenance=self.global_provenance, ) def to_columns(self, external_area_m2: float) -> dict[str, FloatArray]: @@ -2417,13 +2441,19 @@ def to_columns(self, external_area_m2: float) -> dict[str, FloatArray]: @dataclass(frozen=True) class CableDynRead: - """Section histories of one run, the files read and the consistency checks.""" + """Section histories of one run, the files read and the consistency checks. + + ``provenance`` is the run's global-analysis record + (:mod:`cablexsec.io.global_provenance`); ``checks["wave_kinematics"]`` + holds the wave-grid policy outcome for the line read. + """ histories: Mapping[str, CableDynSectionHistory] files: tuple[CableDynFile, ...] deck: CableDynDeck line_id: int checks: Mapping[str, Any] = field(default_factory=dict) + provenance: GlobalProvenance | None = None # --------------------------------------------------------------------------- # @@ -3120,6 +3150,9 @@ def read_cabledyn_sections( curvature_check_atol_1_m: float | None = None, chunk_rows: int = 4096, hang_off_rotation: ArrayLike | Literal["none"] | None = None, + log: str | Path | None = None, + wave_grid_check: WaveGridCheck = "error", + wave_grid_tolerance: float = DEFAULT_WAVE_GRID_TOLERANCE, ) -> CableDynRead: """Read the histories of named material sections from one CableDyn run. @@ -3177,6 +3210,21 @@ def read_cabledyn_sections( ``BodyRx/Ry/Rz`` channels, and refuses a vessel, platform or turbine holder, whose turn the output does not record. Only a line CableDyn solves in torsion with End A restrained takes it. + log : str or pathlib.Path, optional + The run's log (host screen output), read for CableDyn's wave-grid + messages when there is no ``.CD.provenance.json`` + (:func:`~cablexsec.io.global_provenance.read_cabledyn_log`). + wave_grid_check : {"error", "warn"} + What a line read with wave kinematics outside the wave grid, or from + an under-resolved grid, does: raise + :class:`~cablexsec.exceptions.WaveKinematicsError` (default) or warn + (:class:`~cablexsec.provenance.WaveKinematicsWarning`). Only the line + read counts; other lines and an unknown record pass + (:func:`~cablexsec.io.global_provenance.check_wave_kinematics`). + wave_grid_tolerance : float + Largest accepted spectrally weighted velocity ratio (rms wave velocity + over that at the surface) of the line's nodes outside the grid; + default 0.01. A record without the ratio counts any node outside. Returns ------- @@ -3242,6 +3290,18 @@ def read_cabledyn_sections( # own clock (static without TMax or with TMax 0); OpenFAST marches on the # host's clock whatever the deck's TMax. coupled_run = paths["main"].name.endswith(".CD.out") + # The wave provenance first: a refused line fails before the output is read. + global_record = cabledyn_provenance( + root, log=log, host=None if coupled_run else "standalone" + ) + checks["wave_kinematics"] = check_wave_kinematics( + global_record, + line_id, + wave_grid_check=wave_grid_check, + wave_grid_tolerance=wave_grid_tolerance, + where=paths["main"].name, + stacklevel=3, + ).to_record() checks["route"] = ( "OpenFAST (.CD.out)" if coupled_run else "standalone driver (.out)" ) @@ -4428,8 +4488,10 @@ def share(item: dict[str, Any]) -> float: else "external pressure declared zero", "histories inherit the global model's discretisation, " "environmental and boundary assumptions", + global_record.summary(line_id), ), ), + global_provenance=global_record, ) return CableDynRead( histories=MappingProxyType(histories), @@ -4437,6 +4499,7 @@ def share(item: dict[str, Any]) -> float: deck=deck_obj, line_id=line_id, checks=MappingProxyType(checks), + provenance=global_record, ) diff --git a/src/cablexsec/io/cabledyn_components.py b/src/cablexsec/io/cabledyn_components.py index 96ecfd3..1e253e5 100644 --- a/src/cablexsec/io/cabledyn_components.py +++ b/src/cablexsec/io/cabledyn_components.py @@ -35,6 +35,7 @@ from numpy.typing import ArrayLike from cablexsec.exceptions import CableSchemaError +from cablexsec.io.global_provenance import GlobalProvenance, declared_provenance from cablexsec.io.series import LoadCaseSeries from cablexsec.provenance import Provenance @@ -54,6 +55,7 @@ def series_from_curvature_components( *, right_handed: bool = True, source: str = "CableDyn 0.4.0 station history", + global_provenance: GlobalProvenance | str | None = None, ) -> LoadCaseSeries: """A :class:`LoadCaseSeries` from CableDyn's signed curvature components. @@ -69,6 +71,10 @@ def series_from_curvature_components( ``False`` reverses ``y``. source : str, optional Provenance label (file name, record, station). + global_provenance : GlobalProvenance or str, optional + The run's record (:mod:`cablexsec.io.global_provenance`), or a solver + declaration such as ``"CableDyn 0.4.3"``; ``None`` records CableDyn + with every other field unknown. """ cx_ = np.asarray(curv_x_1_m, dtype=np.float64) cy_ = np.asarray(curv_y_1_m, dtype=np.float64) @@ -92,6 +98,9 @@ def series_from_curvature_components( tension_N=np.asarray(effective_tension_N, dtype=np.float64), tension_kind="effective", source=source, + global_provenance=declared_provenance( + "CableDyn" if global_provenance is None else global_provenance + ), provenance=Provenance( method=( "CableDyn 0.4.0 curvature components to strain gradient: " @@ -118,7 +127,10 @@ def _column(fields: Sequence[str], names: Sequence[str], what: str, path: Path) def read_cabledyn_station_table( - path: str | Path, *, right_handed: bool = True + path: str | Path, + *, + right_handed: bool = True, + global_provenance: GlobalProvenance | str | None = None, ) -> LoadCaseSeries: """Read one station table written from CableDyn 0.4.0. @@ -129,11 +141,23 @@ def read_cabledyn_station_table( space). Blank lines are skipped and lines starting with ``#`` are comments. Every data row must have as many columns as the header. Other columns are ignored. + + ``global_provenance`` is the run's record + (:mod:`cablexsec.io.global_provenance`) or a solver declaration; without + it a comment line naming the solver and its version (``# CableDyn + 0.4.3``) is taken, else CableDyn with every other field unknown. """ p = Path(path) + text = p.read_text(encoding="utf-8") + record = declared_provenance( + global_provenance, + comments=[ln[1:].strip() for ln in text.splitlines() if ln.startswith("#")], + ) + if global_provenance is None and record.solver is None: + record = declared_provenance("CableDyn") numbered = [ (number, ln) - for number, ln in enumerate(p.read_text(encoding="utf-8").splitlines(), 1) + for number, ln in enumerate(text.splitlines(), 1) if ln.strip() and not ln.startswith("#") ] if len(numbered) < 3: @@ -173,4 +197,5 @@ def read_cabledyn_station_table( data[:, 3], right_handed=right_handed, source=p.name, + global_provenance=record, ) diff --git a/src/cablexsec/io/global_provenance.py b/src/cablexsec/io/global_provenance.py new file mode 100644 index 0000000..24fbc1a --- /dev/null +++ b/src/cablexsec/io/global_provenance.py @@ -0,0 +1,1246 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +r"""Provenance of global-analysis histories: solver, waves and wave grid. + +A global dynamic analysis hands CableXSec tension and curvature histories, but +the histories do not say how the line's wave kinematics were formed. In a +coupled run a line can take its wave kinematics from a precomputed grid: a +node outside the grid then receives the kinematics of the grid boundary, and a +grid too coarse across the wave direction interpolates over a large part of a +wavelength. :class:`GlobalProvenance` records, per run and per line: + +* the global solver (name, version, host program and its version); +* the wave route (``seastate_grid``, ``seastate_spectral``, ``deck`` or + ``none``), the wave seed and input file where the run records them (a + standalone run), and the fingerprint of the wave components, which + identifies the sea where the seed is not recorded (a coupled run); +* on the grid route, the grid and, for every line, the nodes found outside it, + the grid resolution flags and the spectrally weighted velocity ratio of the + nodes outside (their rms wave velocity over that at the surface). + +Sources, in order: + +1. the record CableDyn writes next to its output, ``.CD.provenance.json`` + (schema ``cabledyn.provenance/1``, :func:`read_cabledyn_provenance`); +2. failing that, the wave-grid messages of a CableDyn run log + (:func:`read_cabledyn_log`), when one is given; +3. failing that, what the output itself shows (CableDyn, and the standalone + driver when it wrote ``.out``), with every other field unknown. + +A missing record never fails a read: the unknown fields are listed +(:attr:`GlobalProvenance.unknown_fields`) and the report says so. + +Policy (:func:`check_wave_kinematics`). Only the analysed line counts. The run +is refused (``wave_grid_check="error"``, the default) or warned about +(``"warn"``, :class:`~cablexsec.provenance.WaveKinematicsWarning`) when the +record shows that line with nodes outside the grid whose spectrally weighted +velocity ratio exceeds ``wave_grid_tolerance`` (default +:data:`DEFAULT_WAVE_GRID_TOLERANCE`, 1 %; a record without the ratio counts +any node outside), or with a grid resolution flag. Nodes of other lines (for +example mooring lines below the grid) are recorded and pass silently, as does +a line whose record is unknown. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +import warnings +from collections.abc import Mapping, Sequence +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any, Literal + +from cablexsec.exceptions import CableSchemaError, WaveKinematicsError +from cablexsec.provenance import UnfinishedRunWarning, WaveKinematicsWarning + +__all__ = [ + "DEFAULT_WAVE_GRID_TOLERANCE", + "PROVENANCE_SCHEMA", + "GlobalProvenance", + "LineWaveRecord", + "OutOfGrid", + "WaveGrid", + "WaveGridCheck", + "WaveKinematicsAssessment", + "WaveRecord", + "assess_wave_kinematics", + "cabledyn_provenance", + "check_wave_kinematics", + "declared_provenance", + "provenance_sidecar", + "read_cabledyn_log", + "read_cabledyn_provenance", + "solver_from_text", + "unknown_runs_note", +] + +#: The record schema this release reads. +PROVENANCE_SCHEMA = "cabledyn.provenance/1" +_SCHEMA_FAMILY = "cabledyn.provenance/" + +#: Default largest spectrally weighted velocity ratio (rms wave velocity at a +#: node over that at the surface) of the analysed line's nodes outside the wave +#: grid that is accepted: at 1 % the wave velocity there, and with it the error +#: of the boundary kinematics the node receives, is a hundredth of that at the +#: surface, and the wave drag (quadratic in velocity) about a ten-thousandth. +DEFAULT_WAVE_GRID_TOLERANCE = 0.01 + +WaveGridCheck = Literal["error", "warn"] +Origin = Literal["sidecar", "log", "declared", "output", "none"] + +_HOSTS = ("openfast", "fast.farm", "standalone", "capi") +_ROUTES = ("seastate_grid", "seastate_spectral", "deck", "none") +_GRID_CHECKS = ("error", "warn") +_STATUSES = ("init", "complete") +_FINGERPRINT = re.compile(r"[0-9A-Fa-f]{16}") + + +# --------------------------------------------------------------------------- # +# Records # +# --------------------------------------------------------------------------- # +@dataclass(frozen=True) +class OutOfGrid: + """Nodes of one line found outside the wave grid during the run. + + ``n_nodes_max`` is the largest number outside at one time, ``first_time_s`` + the first time any was, ``deepest_xyz_m``/``shallowest_xyz_m`` the deepest + and shallowest of them, and ``weighted_velocity_ratio_max`` the largest + spectrally weighted velocity ratio among them. Any field may be ``None`` + (not recorded). + """ + + n_nodes_max: int | None = None + first_time_s: float | None = None + deepest_xyz_m: tuple[float, float, float] | None = None + shallowest_xyz_m: tuple[float, float, float] | None = None + weighted_velocity_ratio_max: float | None = None + + def to_record(self) -> dict[str, Any]: + """The JSON form, in the field names of the CableDyn record.""" + return { + "n_nodes_max": self.n_nodes_max, + "first_time": self.first_time_s, + "deepest_xyz": None + if self.deepest_xyz_m is None + else list(self.deepest_xyz_m), + "shallowest_xyz": None + if self.shallowest_xyz_m is None + else list(self.shallowest_xyz_m), + "weighted_velocity_ratio_max": self.weighted_velocity_ratio_max, + } + + +@dataclass(frozen=True) +class LineWaveRecord: + """The wave-kinematics findings of one line (or body, rod, buoy) of a run. + + ``line_id`` is the deck ``LINES`` id where the record gives one, else the + record's label (for example ``"rod 1 of the deck"``). + """ + + line_id: int | str | None + n_nodes: int | None = None + out_of_grid: OutOfGrid | None = None + resolution_flags: tuple[str, ...] = () + dropped_velocity_variance_max: float | None = None + dropped_acceleration_variance_max: float | None = None + + @property + def affected(self) -> bool: + """Whether any node was outside the grid or any resolution flag is set.""" + outside = self.out_of_grid is not None and ( + self.out_of_grid.n_nodes_max is None or self.out_of_grid.n_nodes_max > 0 + ) + return outside or bool(self.resolution_flags) + + def to_record(self) -> dict[str, Any]: + """The JSON form, in the field names of the CableDyn record.""" + return { + "id": self.line_id, + "n_nodes": self.n_nodes, + "out_of_grid": None + if self.out_of_grid is None + else self.out_of_grid.to_record(), + "resolution_flags": list(self.resolution_flags), + "dropped_velocity_variance_max": self.dropped_velocity_variance_max, + "dropped_acceleration_variance_max": self.dropped_acceleration_variance_max, + } + + +@dataclass(frozen=True) +class WaveGrid: + """The wave-kinematics grid of a grid-route run and the guard's mode.""" + + nx: int | None = None + ny: int | None = None + nz: int | None = None + x_half_width_m: float | None = None + y_half_width_m: float | None = None + z_depth_m: float | None = None + wave_grid_check: str | None = None + + def to_record(self) -> dict[str, Any]: + """The JSON form, in the field names of the CableDyn record.""" + return { + "nx": self.nx, + "ny": self.ny, + "nz": self.nz, + "x_half_width": self.x_half_width_m, + "y_half_width": self.y_half_width_m, + "z_depth": self.z_depth_m, + "wave_grid_check": self.wave_grid_check, + } + + +@dataclass(frozen=True) +class WaveRecord: + """The sea of a run: route, identity, input file and spectrum parameters. + + ``component_fingerprint`` is CableDyn's 64-bit FNV-1a hash of the wave + components (16 hexadecimal digits): two runs with the same fingerprint + had the same sea. A coupled run records no seed, height, period or input + file (SeaState does not pass them on); the fingerprint then identifies + the sea (:attr:`identity`). + """ + + route: str | None = None + seed: tuple[int | str, ...] | None = None + source_file: str | None = None + component_fingerprint: str | None = None + wave_mod: int | None = None + hs_m: float | None = None + tp_s: float | None = None + direction_deg: float | None = None + direction_mod: int | None = None + n_components: int | None = None + dt_s: float | None = None + t_max_s: float | None = None + effective_water_depth_m: float | None = None + wave_kin_tol: float | None = None + + @property + def identity(self) -> str | None: + """The sea's identity for a report: its seed, else its fingerprint.""" + if self.seed is not None: + return "seed " + ", ".join(str(s) for s in self.seed) + if self.component_fingerprint is not None: + return f"components {self.component_fingerprint}" + return None + + def to_record(self) -> dict[str, Any]: + """The JSON form, in the field names of the CableDyn record.""" + return { + "route": self.route, + "wave_mod": self.wave_mod, + "wave_seed": None if self.seed is None else list(self.seed), + "component_fingerprint": self.component_fingerprint, + "wave_hs": self.hs_m, + "wave_tp": self.tp_s, + "wave_dir_deg": self.direction_deg, + "wave_dir_mod": self.direction_mod, + "n_components": self.n_components, + "wave_dt": self.dt_s, + "wave_tmax": self.t_max_s, + "effective_water_depth": self.effective_water_depth_m, + "wave_kin_tol": self.wave_kin_tol, + "source_file": self.source_file, + } + + +@dataclass(frozen=True) +class WaveKinematicsAssessment: + """The policy outcome for the analysed line (:func:`check_wave_kinematics`). + + ``status`` is ``"pass"`` (the record covers the line and it is not + affected above the tolerance), ``"affected"`` (refused or warned about), + ``"unknown"`` (the record does not say: no record, or a log that names only + some lines). ``reasons`` say why the line is affected; ``notes`` record + findings that pass (nodes outside below the tolerance, other lines). + """ + + line_id: int | str + check: WaveGridCheck + tolerance: float + status: Literal["pass", "affected", "unknown"] + reasons: tuple[str, ...] = () + notes: tuple[str, ...] = () + other_lines_affected: tuple[str, ...] = () + + def to_record(self) -> dict[str, Any]: + """The JSON form written to reports.""" + return { + "line_id": self.line_id, + "wave_grid_check": self.check, + "wave_grid_tolerance": self.tolerance, + "status": self.status, + "reasons": list(self.reasons), + "notes": list(self.notes), + "other_lines_affected": list(self.other_lines_affected), + } + + +#: The top-level fields whose absence makes a record "unknown" in a report. +_KEY_FIELDS = ( + "solver", + "solver_version", + "host", + "wave_route", + "sea_identity", + "lines", +) + + +@dataclass(frozen=True) +class GlobalProvenance: + """How the global run that produced a set of histories was made. + + Attributes + ---------- + origin : {"sidecar", "log", "declared", "output", "none"} + Where the record comes from: CableDyn's provenance file, a run log, a + declaration by the caller or a comment line of the export, the output + files alone, or nothing at all. + solver, solver_version : str or None + ``"cabledyn"``, ``"orcaflex"`` or the name declared; ``None`` unknown. + host, host_version : str or None + The program CableDyn ran in: ``"openfast"``, ``"fast.farm"``, + ``"standalone"`` or ``"capi"``. + status : str or None + ``"complete"``, or ``"init"`` for a run that did not finish. + waves : WaveRecord + Route, seed, input file and sea parameters (fields ``None`` when not + recorded). + grid : WaveGrid or None + The wave grid of a grid-route run. + lines : tuple of LineWaveRecord, or None + Per-line findings; ``None`` when the source does not list lines. + lines_complete : bool + ``False`` when the source lists only some of the affected lines (a log + message cut short, or one without a per-line list). + origin_file, origin_sha256 : str or None + The file read and its SHA-256. + notes : tuple of str + What the reader could not establish, and why. + """ + + origin: Origin + solver: str | None = None + solver_version: str | None = None + host: str | None = None + host_version: str | None = None + status: str | None = None + waves: WaveRecord = field(default_factory=WaveRecord) + grid: WaveGrid | None = None + lines: tuple[LineWaveRecord, ...] | None = None + lines_complete: bool = True + origin_file: str | None = None + origin_sha256: str | None = None + notes: tuple[str, ...] = () + + @property + def wave_route(self) -> str | None: + """The wave route, ``None`` when not recorded.""" + return self.waves.route + + @property + def unknown_fields(self) -> tuple[str, ...]: + """The key fields the record does not give (empty for a full record). + + ``sea_identity`` is the wave seed or, when the run records none (a + coupled run), the fingerprint of the wave components. + """ + values = { + "solver": self.solver, + "solver_version": self.solver_version, + "host": self.host, + "wave_route": self.waves.route, + "sea_identity": self.waves.identity, + "lines": self.lines, + } + unknown = [name for name in _KEY_FIELDS if values[name] is None] + if self.waves.route in ("none", "deck") and "lines" in unknown: + # Without host waves on a grid there are no per-line grid findings. + unknown.remove("lines") + if self.waves.route == "none" and "sea_identity" in unknown: + unknown.remove("sea_identity") # still water has no sea to identify + return tuple(unknown) + + @property + def known(self) -> bool: + """Whether the record gives the wave route (a sidecar or a usable log).""" + return self.waves.route is not None + + def line(self, line_id: int | str) -> LineWaveRecord | None: + """The record of a line by its deck id (or label), ``None`` if absent.""" + for item in self.lines or (): + if _same_id(item.line_id, line_id): + return item + return None + + def summary(self, line_id: int | str | None = None) -> str: + """One line for a report: solver, waves and, given a line, its findings.""" + if not self.known: + unknown = ", ".join(self.unknown_fields) or "none" + solver = _solver_text(self) + prefix = f"{solver}; " if solver else "" + return ( + f"global-analysis provenance unknown ({prefix}not recorded: " + f"{unknown}; {'; '.join(self.notes) if self.notes else 'no record'})" + ) + parts = [_solver_text(self) or "solver unknown"] + waves = f"waves {self.waves.route}" + if self.waves.identity is not None: + waves += f", {self.waves.identity}" + if self.waves.seed is not None and self.waves.component_fingerprint: + waves += f" (components {self.waves.component_fingerprint})" + if self.waves.source_file: + waves += f", from {self.waves.source_file}" + parts.append(waves) + if line_id is not None and self.waves.route == "seastate_grid": + record = self.line(line_id) + if record is None: + parts.append( + f"line {line_id}: " + + ( + "no findings" + if self.lines is not None and self.lines_complete + else "not covered by the record" + ) + ) + else: + parts.append(f"line {line_id}: {_line_text(record)}") + if line_id is not None and self.waves.route == "seastate_spectral": + record = self.line(line_id) + velocity = None if record is None else record.dropped_velocity_variance_max + acceleration = ( + None if record is None else record.dropped_acceleration_variance_max + ) + if velocity is not None and acceleration is not None: + parts.append( + f"line {line_id}: dropped velocity and acceleration variance " + f"up to {velocity:.3g} and {acceleration:.3g} of the sea's" + ) + if self.status == "init": + parts.append("the run did not finish") + source = Path(self.origin_file).name if self.origin_file else self.origin + return f"global analysis: {'; '.join(parts)} (provenance from {source})" + + def to_record(self) -> dict[str, Any]: + """The JSON form written to reports and manifests.""" + return { + "origin": self.origin, + "file": None + if self.origin_file is None + else {"path": self.origin_file, "sha256": self.origin_sha256}, + "solver": self.solver, + "solver_version": self.solver_version, + "host": self.host, + "host_version": self.host_version, + "status": self.status, + "waves": self.waves.to_record(), + "grid": None if self.grid is None else self.grid.to_record(), + "lines": None + if self.lines is None + else [item.to_record() for item in self.lines], + "lines_complete": self.lines_complete, + "unknown": list(self.unknown_fields), + "notes": list(self.notes), + } + + +def _same_id(a: int | str | None, b: int | str) -> bool: + return a is not None and str(a).strip() == str(b).strip() + + +def _solver_text(record: GlobalProvenance) -> str: + names = {"cabledyn": "CableDyn", "orcaflex": "OrcaFlex"} + if record.solver is None: + return "" + text = names.get(record.solver, record.solver) + if record.solver_version: + text += f" {record.solver_version}" + if record.host: + hosts = {"openfast": "OpenFAST", "fast.farm": "FAST.Farm", "capi": "C API"} + host = hosts.get(record.host, record.host) + text += f" ({host}" + ( + f" {record.host_version})" if record.host_version else ")" + ) + return text + + +def _xyz_text(xyz: tuple[float, float, float] | None) -> str: + return "?" if xyz is None else "(" + ", ".join(f"{v:.6g}" for v in xyz) + ") m" + + +def _line_text(record: LineWaveRecord) -> str: + parts = [] + out = record.out_of_grid + if out is not None and (out.n_nodes_max is None or out.n_nodes_max > 0): + count = "nodes" if out.n_nodes_max is None else f"{out.n_nodes_max} node(s)" + text = f"{count} outside the wave grid" + if out.first_time_s is not None: + text += f" from t = {out.first_time_s:g} s" + if out.deepest_xyz_m is not None: + text += f", deepest at {_xyz_text(out.deepest_xyz_m)}" + if out.shallowest_xyz_m is not None: + text += f", shallowest at {_xyz_text(out.shallowest_xyz_m)}" + ratio = out.weighted_velocity_ratio_max + text += ( + ", weighted velocity ratio not recorded" + if ratio is None + else f", weighted velocity ratio up to {ratio:.3g}" + ) + parts.append(text) + if record.resolution_flags: + parts.append("resolution flags: " + "; ".join(record.resolution_flags)) + return "; ".join(parts) if parts else "inside the wave grid, no resolution flags" + + +# --------------------------------------------------------------------------- # +# CableDyn provenance file # +# --------------------------------------------------------------------------- # +def provenance_sidecar(out_root: str | Path) -> Path: + """The provenance file CableDyn writes for an output root.""" + return Path(f"{out_root}.CD.provenance.json") + + +class _Fields: + """Typed access to one JSON object, naming the key path in errors.""" + + def __init__(self, data: Any, where: str, path: Path) -> None: + if not isinstance(data, dict): + raise CableSchemaError(f"{path.name}: {where} must be a JSON object") + self.data: dict[str, Any] = data + self.where = where + self.path = path + + def _error(self, key: str, what: str) -> CableSchemaError: + value = self.data.get(key) + return CableSchemaError( + f"{self.path.name}: {self.where}.{key} must be {what} or null, " + f"not {value!r}" + ) + + def text(self, key: str, choices: Sequence[str] | None = None) -> str | None: + value = self.data.get(key) + if value is None: + return None + if not isinstance(value, str): + raise self._error(key, "a string") + if choices is not None and value not in choices: + raise CableSchemaError( + f"{self.path.name}: {self.where}.{key} is {value!r}; " + f"{PROVENANCE_SCHEMA} allows {', '.join(repr(c) for c in choices)}" + ) + return value + + def integer(self, key: str) -> int | None: + value = self.data.get(key) + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int): + raise self._error(key, "an integer") + return value + + def number(self, key: str) -> float | None: + value = self.data.get(key) + if value is None: + return None + if isinstance(value, bool) or not isinstance(value, int | float): + raise self._error(key, "a number") + if not math.isfinite(value): + raise self._error(key, "a finite number") + return float(value) + + def point(self, key: str) -> tuple[float, float, float] | None: + value = self.data.get(key) + if value is None: + return None + if ( + not isinstance(value, list) + or len(value) != 3 + or any( + isinstance(v, bool) + or not isinstance(v, int | float) + or not math.isfinite(v) + for v in value + ) + ): + raise self._error(key, "a list of three finite numbers") + return (float(value[0]), float(value[1]), float(value[2])) + + def child(self, key: str) -> _Fields | None: + value = self.data.get(key) + if value is None: + return None + return _Fields(value, f"{self.where}.{key}", self.path) + + +def read_cabledyn_provenance(path: str | Path) -> GlobalProvenance: + """Read and check a CableDyn provenance file (``.CD.provenance.json``). + + The check is strict on what the schema defines and tolerant of the rest: + every defined field must have its type (or be ``null``), an enumerated + field one of its values, and ``schema`` must be + :data:`PROVENANCE_SCHEMA`; keys the schema does not define are ignored, so + a later CableDyn may add fields. A record with ``status`` ``"init"`` (the + run did not finish) is read with an + :class:`~cablexsec.provenance.UnfinishedRunWarning`. + + Raises + ------ + FileNotFoundError + When the file does not exist. + cablexsec.exceptions.CableSchemaError + For a file that is not JSON, another schema or schema version, or a + field of the wrong type or value. + """ + p = Path(path) + if not p.is_file(): + raise FileNotFoundError(f"CableDyn provenance file not found: {p}") + raw = p.read_bytes() + try: + data = json.loads(raw.decode("utf-8-sig")) + except (UnicodeDecodeError, json.JSONDecodeError) as error: + raise CableSchemaError( + f"{p.name}: not a JSON provenance record ({error})" + ) from None + top = _Fields(data, "record", p) + schema = top.data.get("schema") + if not isinstance(schema, str): + raise CableSchemaError( + f"{p.name}: no 'schema' string; a CableDyn provenance record names " + f"{PROVENANCE_SCHEMA!r}" + ) + if schema != PROVENANCE_SCHEMA: + if schema.startswith(_SCHEMA_FAMILY): + raise CableSchemaError( + f"{p.name}: schema {schema!r}; this CableXSec reads " + f"{PROVENANCE_SCHEMA!r}. Use a CableXSec release that reads " + "this version, or rerun with a CableDyn that writes version 1." + ) + raise CableSchemaError( + f"{p.name}: schema {schema!r} is not a CableDyn provenance record " + f"({PROVENANCE_SCHEMA!r})" + ) + status = top.text("status", _STATUSES) + waves = _waves(top.child("waves")) + grid_fields = top.child("grid") + grid = ( + None + if grid_fields is None + else WaveGrid( + nx=grid_fields.integer("nx"), + ny=grid_fields.integer("ny"), + nz=grid_fields.integer("nz"), + x_half_width_m=grid_fields.number("x_half_width"), + y_half_width_m=grid_fields.number("y_half_width"), + z_depth_m=grid_fields.number("z_depth"), + wave_grid_check=grid_fields.text("wave_grid_check", _GRID_CHECKS), + ) + ) + raw_lines = top.data.get("lines") + lines: tuple[LineWaveRecord, ...] | None = None + if raw_lines is not None: + if not isinstance(raw_lines, list): + raise CableSchemaError(f"{p.name}: record.lines must be a list or null") + lines = tuple( + _line_record(_Fields(item, f"record.lines[{i}]", p)) + for i, item in enumerate(raw_lines) + ) + notes: list[str] = [] + if status == "init": + notes.append( + "the record has status 'init': the run did not finish, so its " + "findings cover only the part of the run before it stopped" + ) + warnings.warn( + f"{p.name}: status 'init': the CableDyn run did not finish; its " + "wave-kinematics findings cover only the part before it stopped", + UnfinishedRunWarning, + stacklevel=2, + ) + return GlobalProvenance( + origin="sidecar", + solver="cabledyn", + solver_version=top.text("cabledyn_version"), + host=top.text("host", _HOSTS), + host_version=top.text("host_version"), + status=status, + waves=waves, + grid=grid, + lines=lines, + origin_file=str(p.resolve()), + origin_sha256=hashlib.sha256(raw).hexdigest(), + notes=tuple(notes), + ) + + +def _waves(fields: _Fields | None) -> WaveRecord: + if fields is None: + return WaveRecord() + seed_value = fields.data.get("wave_seed") + seed: tuple[int | str, ...] | None = None + if seed_value is not None: + if not isinstance(seed_value, list) or any( + isinstance(s, bool) or not isinstance(s, int | str) for s in seed_value + ): + raise CableSchemaError( + f"{fields.path.name}: {fields.where}.wave_seed must be a list of " + f"integers or strings, or null, not {seed_value!r}" + ) + seed = tuple(seed_value) + fingerprint = fields.text("component_fingerprint") + if fingerprint is not None: + if not _FINGERPRINT.fullmatch(fingerprint): + raise CableSchemaError( + f"{fields.path.name}: {fields.where}.component_fingerprint must be " + f"16 hexadecimal digits (a 64-bit FNV-1a hash), or null, not " + f"{fingerprint!r}" + ) + fingerprint = fingerprint.lower() + return WaveRecord( + route=fields.text("route", _ROUTES), + seed=seed, + source_file=fields.text("source_file"), + component_fingerprint=fingerprint, + wave_mod=fields.integer("wave_mod"), + hs_m=fields.number("wave_hs"), + tp_s=fields.number("wave_tp"), + direction_deg=fields.number("wave_dir_deg"), + direction_mod=fields.integer("wave_dir_mod"), + n_components=fields.integer("n_components"), + dt_s=fields.number("wave_dt"), + t_max_s=fields.number("wave_tmax"), + effective_water_depth_m=fields.number("effective_water_depth"), + wave_kin_tol=fields.number("wave_kin_tol"), + ) + + +def _line_record(fields: _Fields) -> LineWaveRecord: + identifier = fields.data.get("id") + if identifier is not None and ( + isinstance(identifier, bool) or not isinstance(identifier, int | str) + ): + raise CableSchemaError( + f"{fields.path.name}: {fields.where}.id must be an integer or a " + f"string, or null, not {identifier!r}" + ) + out = fields.child("out_of_grid") + flags = fields.data.get("resolution_flags") + if flags is not None and ( + not isinstance(flags, list) or any(not isinstance(f, str) for f in flags) + ): + raise CableSchemaError( + f"{fields.path.name}: {fields.where}.resolution_flags must be a list " + f"of strings or null, not {flags!r}" + ) + return LineWaveRecord( + line_id=identifier, + n_nodes=fields.integer("n_nodes"), + out_of_grid=None + if out is None + else OutOfGrid( + n_nodes_max=out.integer("n_nodes_max"), + first_time_s=out.number("first_time"), + deepest_xyz_m=out.point("deepest_xyz"), + shallowest_xyz_m=out.point("shallowest_xyz"), + weighted_velocity_ratio_max=out.number("weighted_velocity_ratio_max"), + ), + resolution_flags=tuple(flags or ()), + dropped_velocity_variance_max=fields.number("dropped_velocity_variance_max"), + dropped_acceleration_variance_max=fields.number( + "dropped_acceleration_variance_max" + ), + ) + + +# --------------------------------------------------------------------------- # +# CableDyn run log # +# --------------------------------------------------------------------------- # +_NUM = r"[-+]?(?:\d+\.?\d*|\.\d+)(?:[EeDd][-+]?\d+)?" +_XYZ = rf"\(x, y, z\) = \(({_NUM}), ({_NUM}), ({_NUM})\) m" +_COVERAGE = re.compile( + r"CableDyn mooring module: (?P\d+) of the (?P\d+) CableDyn sampling " + r"nodes in the water lie outside the SeaState wave-kinematics grid at " + rf"t = (?P{_NUM}) s(?P.*?)(?=CableDyn mooring module:|$)" +) +_RESOLUTION = re.compile( + r"CableDyn mooring module: the SeaState wave-kinematics grid has " + r"(?P.+?) under (?P.+?), which vary along that axis: .*? " + r"(?P\d+) of the (?P\d+) CableDyn sampling nodes in the water lie " + r"between grid points there\.(?P.*?)(?=CableDyn mooring module:|$)" +) +_BY_LINE_COVERAGE = re.compile(r" By line: (.*?)\.(?= Farthest:| In the SeaState)") +_BY_LINE_RESOLUTION = re.compile(r" By line: (.*?)\.(?= A grid with)") +_ITEM = re.compile( + rf"^(?P