diff --git a/CHANGELOG.md b/CHANGELOG.md index e7cb4f8..c20582a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,68 @@ All notable changes to CableXSec are recorded in this file. The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and the project uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## [Unreleased] + +## [0.2.3] - 2026-12-03 + +The Python interfaces are versioned but may change before `1.0.0`. The evidence for +every item below is in +[VALIDATION.md](https://github.com/SMI-Lab-Inha/CableXSec/blob/main/VALIDATION.md); its +generated table is reproduced by `python validation/scripts/run_validation.py`. The +mechanical, thermal, fatigue and contact results are unchanged. By default, +`read_cabledyn_sections` now refuses a run whose provenance record shows the analysed line +outside the wave grid or a wave-grid resolution finding (`wave_grid_check="warn"` reads it +with a warning); a run without a record reads as before. + +### 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 provenance file (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 file is found + beside each CableDyn result file (`x.CD.out` -> `x.CD.provenance.json`, `x.FarmCD.out` -> + `x.FarmCD.provenance.json`, `x.out` -> `x.CD.provenance.json`); a run with status `init` or + `stopped` warns and keeps its record. The record, with the analysed line, travels with + `CableDynRead.provenance`, every `CableDynSectionHistory`, the `LoadCaseSeries` of every reader + (`global_provenance=`), the exchange CSV (a `# global_provenance:` comment line), project files + 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 any + grid resolution finding (it concerns every line in the water), 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. +- `read_cabledyn_sections` reads FAST.Farm's CableDyn table `.FarmCD.out` (with + `.FarmCD.static.out` and its range file), which has the `.CD.out` layout, on the host's + clock; `checks["route"]` names it. A root with both a `.CD.out` and a `.FarmCD.out` is refused. +- 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. + +### Tests + +- The two slowest tests build only the validation rows they check (sigma_B; BM1-loop and + BM1-ID) instead of the whole report, and a report computes the SV11 predictions once + instead of twice (the caches of `check_saevik2011` are keyed on the value of the friction + coefficient). The report and its row order are unchanged. + +### Known limitations + +- The measured comparisons that failed in 0.2.2 (BM1-loop, BM1-ID, Z-EI, HU-3PB, WITZ-ID, + SV11-PLANE, SV11-GJ) still fail; their targets and tolerances are not relaxed. The + validation table has 73 rows: 50 pass, 7 fail, 13 are stated without a target, 1 is + partial (BM5), 1 not comparable and 1 not validated. + ## [0.2.2] - 2026-12-01 The Python interfaces are versioned but may change before `1.0.0`. The evidence for diff --git a/CITATION.cff b/CITATION.cff index 4448ce2..036fb34 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -23,8 +23,8 @@ authors: repository-code: "https://github.com/SMI-Lab-Inha/CableXSec" url: "https://github.com/SMI-Lab-Inha/CableXSec" license: Apache-2.0 -version: 0.2.2 -date-released: 2026-12-01 +version: 0.2.3 +date-released: 2026-12-03 keywords: - dynamic power cable - cross-section mechanics diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index ec17da5..a38a071 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -100,8 +100,8 @@ with absolute `https://github.com/SMI-Lab-Inha/CableXSec/blob/main/...` URLs. python -m build --outdir dist python -m twine check dist/* python -m venv wheel-test -wheel-test\Scripts\python -m pip install dist\cablexsec-0.2.2-py3-none-any.whl -wheel-test\Scripts\python release\smoke_test_wheel.py --version 0.2.2 +wheel-test\Scripts\python -m pip install dist\cablexsec-0.2.3-py3-none-any.whl +wheel-test\Scripts\python release\smoke_test_wheel.py --version 0.2.3 ``` The wheel contains only the `cablexsec` package (with its bundled cable definitions) diff --git a/README.md b/README.md index a9599a4..90be06b 100644 --- a/README.md +++ b/README.md @@ -17,7 +17,7 @@ damage of the armour, the conductor and the metallic sheaths. It reads the results of global analyses (CableDyn runs and time-history CSV exports such as those of OrcaFlex) and turns them into local stresses and damage, and it exports a hysteretic bending law for use in global analysis. The -current release is `v0.2.2`; interfaces are versioned and may change before `1.0.0`. +current release is `v0.2.3`; interfaces are versioned and may change before `1.0.0`. ## What CableXSec does @@ -74,7 +74,7 @@ Install the release wheel from the 3.12), or install straight from the repository: ```powershell -python -m pip install "cablexsec[fast] @ git+https://github.com/SMI-Lab-Inha/CableXSec.git@v0.2.2" +python -m pip install "cablexsec[fast] @ git+https://github.com/SMI-Lab-Inha/CableXSec.git@v0.2.3" ``` The `fast` extra adds `numba` for the compiled slip-stress and rainflow kernels; without it the @@ -154,7 +154,7 @@ in [`validation/`](validation/README.md), including the data of the companion jo ## Citation -If you use CableXSec in academic work, please cite the software release (CableXSec 0.2.2); +If you use CableXSec in academic work, please cite the software release (CableXSec 0.2.3); [CITATION.cff](CITATION.cff) contains the entry (GitHub **Cite this repository**) and the manual's [How to cite](https://cablexsec.readthedocs.io/en/latest/citing.html) page gives BibTeX. The journal article that describes the method is under review; its reference will be diff --git a/doc/api_python.rst b/doc/api_python.rst index 796237d..8372f83 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -65,3 +65,20 @@ 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, from_record, line, unknown_fields, known, wave_route, + all_resolution_findings +.. 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/citing.rst b/doc/citing.rst index 6314efc..590fbfc 100644 --- a/doc/citing.rst +++ b/doc/citing.rst @@ -12,15 +12,15 @@ Software release ---------------- Seo, J. H. (2026). *CableXSec: Component-resolved local cross-section mechanics of dynamic -power cables* (version 0.2.2) [Computer software]. https://github.com/SMI-Lab-Inha/CableXSec +power cables* (version 0.2.3) [Computer software]. https://github.com/SMI-Lab-Inha/CableXSec .. code-block:: bibtex - @software{CableXSec_0_2_2, + @software{CableXSec_0_2_3, author = {Seo, Jae Hoon}, title = {{CableXSec}: Component-resolved local cross-section mechanics of dynamic power cables}, - version = {0.2.2}, + version = {0.2.3}, year = {2026}, url = {https://github.com/SMI-Lab-Inha/CableXSec}, license = {Apache-2.0} 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..bc2a13c 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. @@ -509,7 +510,11 @@ reads, a fixed layout that keeps every kind: The first three columns and exactly one tension column are required. Values are written with full precision, so a series survives the round trip -unchanged. The bundled demonstration history +unchanged. A series that carries a global-analysis provenance record (below) +writes it first, as one comment line `# global_provenance: {...}` (the JSON +form of the record), which `read_series_csv` restores; a series without one, +or with one that records nothing (an export that names no solver), writes the +table alone. The bundled demonstration history `validation/paper_data/global_demo/global_history_si.csv` is in this format. ### Whitespace-column ASCII time history @@ -535,7 +540,8 @@ Driver and OpenFAST module runs write CableDyn 0.1.x output. `cx.read_cabledyn_sections(out_root, deck, {"name": arc_length_m, ...})` reads the output files of one run together with the deck: `.out`, `.Line.p.out`, `.Line.t.out`, `.static.out` and -`.elements.out`, or `.CD.out` from OpenFAST. It rebuilds the +`.elements.out`, or `.CD.out` from OpenFAST (`.FarmCD.out` +from FAST.Farm, the same layout). It rebuilds the signed curvature vector of each named section from the tangent channels or node positions. It returns a `CableDynSectionHistory` per section with the effective tension, rotation curvature components, hydrostatic pressure, @@ -572,6 +578,83 @@ 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 the record CableDyn writes beside its result file, named after the +result file without `.out` (`provenance_sidecar`): + +| Result file | Record | +| --- | --- | +| `x.CD.out` (OpenFAST) | `x.CD.provenance.json` | +| `x.FarmCD.out` (FAST.Farm) | `x.FarmCD.provenance.json` | +| `x.out` (standalone driver) | `x.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", + "restarted_from": null +} +``` + +| 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[].out_of_grid` points | a coordinate may be `null` | +| `lines[].resolution_flags` | a list of strings | +| `status` | `complete`; `init` for a run that did not finish, `stopped` for one that ended on an error (both read with an `UnfinishedRunWarning`; the record is kept) | +| `restarted_from` | the time [s] of the checkpoint the run restarted from, or `null` | + +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. A record that is not UTF-8 is read as Windows-1252 (else Latin-1), +with a note. 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 what the result file's name shows (CableDyn +and its host). 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 (the solver named first, when a line names +two). + +`record.to_record()` gives the JSON form written to the batch manifest and the +exchange CSV, with the record's `origin` (`sidecar`, `log`, `declared`, +`output` or `none`), the file read and its SHA-256, the analysed line +(`analysed_line`), the grid resolution findings a log states +(`resolution_findings`), and the list `unknown` of the key fields it does not +give; `GlobalProvenance.from_record` rebuilds the record. Project files save a +series with its record; a series without one is saved as before, so saved +analyses keep their fingerprints. 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 +670,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..bd81d02 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/` | @@ -34,6 +35,8 @@ torsion); where a later release changed a channel, the item says so. 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 position or tension files. + FAST.Farm writes the same two files as `.FarmCD.out` and + `.FarmCD.static.out`, read the same way. Fields are TAB-separated; values have 8 significant digits, time 17. The standalone output step is `dtM` and a run ends at `TMax` (a deck without `TMax`, or with @@ -488,9 +491,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 +528,89 @@ 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 beside its result +file, named after it without `.out` (`x.CD.out` gives `x.CD.provenance.json`, +`x.FarmCD.out` `x.FarmCD.provenance.json`, the standalone driver's `x.out` +`x.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 +result file alone, which shows only that CableDyn wrote it and in which +host. The log names the lines with nodes outside the grid and the lines that +sample a coarse grid in the water, but not their weighted velocity ratio. A +log message that names no lines or cuts its list short leaves the other lines +unknown, and so does a run under `waveGridCheck warn`: CableDyn then warns +once, so a line not named in that warning may have left the grid later. +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`) or ended on an error (`stopped`) warns +(`UnfinishedRunWarning`) and is kept; `restarted_from` records the checkpoint +a restarted run began from. + +**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 finding, on any line or stated for the run by a log: a + grid with three points across a sea that varies along that axis + interpolates the kinematics wherever the lines (and the hull members) + sample it in the water, so the finding concerns every line in the water, + named or not. The record gives no measure for it, so any finding 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 record also holds the analysed line, so the history's +provenance limitations and the provenance of `fatigue_from_series` give a +one-line summary of it, 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. The exchange CSV +(`write_series_csv`) and project files keep it with the series. + +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/doc/index.rst b/doc/index.rst index b3409d8..b99a6a3 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -14,7 +14,7 @@ turns them into the fatigue damage of the armour, the conductor and the metallic .. admonition:: Release status :class: note - CableXSec ``v0.2.2`` is the current release. It is distributed as a source + CableXSec ``v0.2.3`` is the current release. It is distributed as a source repository and a pure-Python wheel on the `GitHub release page `_. Every comparison with published data, including the comparisons that do not meet their diff --git a/doc/installation.rst b/doc/installation.rst index 6462adf..3748c1e 100644 --- a/doc/installation.rst +++ b/doc/installation.rst @@ -9,21 +9,21 @@ is distributed through its GitHub repository; it is not published on a package i From a release -------------- -Download ``cablexsec-0.2.2-py3-none-any.whl`` and ``SHA256SUMS.txt`` from the -`v0.2.2 release `_, compare +Download ``cablexsec-0.2.3-py3-none-any.whl`` and ``SHA256SUMS.txt`` from the +`v0.2.3 release `_, compare the checksum, and install the wheel with its optional extras: .. code-block:: powershell - Get-FileHash cablexsec-0.2.2-py3-none-any.whl -Algorithm SHA256 - python -m pip install "cablexsec-0.2.2-py3-none-any.whl[fast]" + Get-FileHash cablexsec-0.2.3-py3-none-any.whl -Algorithm SHA256 + python -m pip install "cablexsec-0.2.3-py3-none-any.whl[fast]" From the repository ------------------- .. code-block:: powershell - python -m pip install "cablexsec[fast] @ git+https://github.com/SMI-Lab-Inha/CableXSec.git@v0.2.2" + python -m pip install "cablexsec[fast] @ git+https://github.com/SMI-Lab-Inha/CableXSec.git@v0.2.3" or, for development, clone the repository and install it in editable mode (see :doc:`development`): diff --git a/doc/tutorials/04_contact_and_fretting.md b/doc/tutorials/04_contact_and_fretting.md index e92beb7..305402d 100644 --- a/doc/tutorials/04_contact_and_fretting.md +++ b/doc/tutorials/04_contact_and_fretting.md @@ -234,7 +234,7 @@ fretting life. Nor is it the {term}`Ruiz parameter` (Ruiz et al. 1984), which is formed from the local surface shear traction and slip and, in its second form, the local -tangential stress. CableXSec 0.2.2 does not compute Ruiz parameters. +tangential stress. CableXSec 0.2.3 does not compute Ruiz parameters. ## 8. The SWT critical plane next to a crossing @@ -298,7 +298,7 @@ Points nearer the surface at the edge itself need a higher quadrature order. converge; it never returns an unconverged stress. `compute_swt_cycle` also returns a formal life from a strain-life law -(`SWTLifeConstants`). The SWT constants registered in CableXSec 0.2.2 +(`SWTLifeConstants`). The SWT constants registered in CableXSec 0.2.3 (`sn_curves.SWT_LIFE`) are those of copper, and none are for armour steel, so the script passes a placeholder law and prints no life. With constants from a source, `result.life_cycles` gives it. diff --git a/pyproject.toml b/pyproject.toml index b8612bb..9e2057d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ build-backend = "setuptools.build_meta" [project] name = "cablexsec" -version = "0.2.2" +version = "0.2.3" description = "Component-resolved local cross-section mechanics and fatigue of dynamic power cables" readme = "README.md" requires-python = ">=3.11,<3.13" diff --git a/release/check_release_metadata.py b/release/check_release_metadata.py index 5eef8b0..67afc88 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -42,9 +42,11 @@ def capture(relative_path: str, pattern: str, label: str) -> str: ".yaml", } # Records of a past release keep the version they describe; the hook configuration -# pins tool versions, not CableXSec versions. +# pins tool versions, not CableXSec versions; test data under tests/data/ are files +# other programs wrote (run logs, exports), whose versions are theirs. HISTORICAL = re.compile( - r"^(CHANGELOG\.md|validation/RELEASE_\d+_\d+_\d+\.md|\.pre-commit-config\.yaml)$" + r"^(CHANGELOG\.md|validation/RELEASE_\d+_\d+_\d+\.md|\.pre-commit-config\.yaml" + r"|tests/data/.+)$" ) diff --git a/src/cablexsec/__init__.py b/src/cablexsec/__init__.py index b9aaf10..cc75ece 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,10 +337,12 @@ FrictionModelFallbackWarning, MissingClampingStateWarning, TorsionalStressWarning, + UnfinishedRunWarning, UnmodelledPolymerSofteningWarning, + WaveKinematicsWarning, ) -__version__ = "0.2.2" +__version__ = "0.2.3" from cablexsec.project import ( # noqa: E402 PROJECT_FORMAT_VERSION, @@ -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/_project_codec.py b/src/cablexsec/_project_codec.py index 3b3036c..0e9bc43 100644 --- a/src/cablexsec/_project_codec.py +++ b/src/cablexsec/_project_codec.py @@ -27,6 +27,13 @@ from cablexsec.api import MkappaResult, StiffnessResult from cablexsec.cables.schema import CableData from cablexsec.exceptions import CableInputError +from cablexsec.io.global_provenance import ( + GlobalProvenance, + LineWaveRecord, + OutOfGrid, + WaveGrid, + WaveRecord, +) from cablexsec.io.series import LoadCaseSeries from cablexsec.materials.sn_curves import SNcurve, SWTLifeConstants from cablexsec.mechanics.axisymmetric import AxisymmetricResult @@ -69,9 +76,19 @@ BendingLawExport, IwanBendingLaw, SlipScaleTable, + # The global-analysis provenance of a series. + GlobalProvenance, + WaveRecord, + WaveGrid, + LineWaveRecord, + OutOfGrid, ) } +#: Fields added after projects were saved: left out when unset, so that the +#: encoding, and the fingerprint of a saved analysis, stay as before. +_OMIT_WHEN_NONE = {("LoadCaseSeries", "global_provenance")} + @cache def _annotations(cls: type[Any]) -> dict[str, Any]: @@ -140,9 +157,16 @@ def pack(value: Any) -> Any: and is_dataclass(value) and not isinstance(value, type) ): + name = type(value).__name__ return { - "type": type(value).__name__, - "fields": {f.name: pack(getattr(value, f.name)) for f in fields(value)}, + "type": name, + "fields": { + f.name: pack(getattr(value, f.name)) + for f in fields(value) + if not ( + getattr(value, f.name) is None and (name, f.name) in _OMIT_WHEN_NONE + ) + }, } if isinstance(value, dict) and all(isinstance(k, str) for k in value): return {"mapping": {k: pack(v) for k, v in value.items()}} 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..7c95edf 100644 --- a/src/cablexsec/io/cabledyn.py +++ b/src/cablexsec/io/cabledyn.py @@ -4,8 +4,9 @@ Reads the standalone CableDyn driver files (``.out``, ``.Line.p.out``, ``.Line.t.out``, ``.static.out``, -``.elements.out``) or the OpenFAST module file ``.CD.out`` together -with the deck, and returns the history of selected material sections in the +``.elements.out``) or the OpenFAST module file ``.CD.out`` +(FAST.Farm ``.FarmCD.out``, the same layout) together with the deck, +and returns the history of selected material sections in the form the time-history CSV path of CableXSec produces: time, effective tension, two signed bending-curvature components in a local section frame, and, where the global model provides them, torsion and external pressure. The range graph @@ -190,6 +191,20 @@ 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: the record CableDyn writes beside its result file +(``.CD.provenance.json`` for ``.out`` and ``.CD.out``) when +it exists, else the wave-grid messages of the run log passed as ``log``, else +what the result file shows. It travels, with the line read, 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 any +grid resolution finding (which concerns every line in the water), is refused +(``wave_grid_check="error"``) or warned about (``"warn"``); nodes of other +lines outside the grid 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 +227,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 +2302,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 +2326,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 +2417,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 +2444,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 # --------------------------------------------------------------------------- # @@ -2517,11 +2550,20 @@ def _is_cabledyn_main_table(path: Path) -> bool: def _discover(out_root: Path, line_id: int) -> dict[str, Path]: standalone = Path(f"{out_root}.out") - coupled = Path(f"{out_root}.CD.out") + turbine = Path(f"{out_root}.CD.out") + farm = Path(f"{out_root}.FarmCD.out") + if turbine.is_file() and farm.is_file(): + raise CableSchemaError( + f"both {turbine.name} (OpenFAST) and {farm.name} (FAST.Farm) exist; " + "name one output root" + ) + # OpenFAST's .CD.out or FAST.Farm's .FarmCD.out: the same layout + # (CableDyn doc/outputs.rst), the host's clock. + coupled, prefix = (farm, ".FarmCD") if farm.is_file() else (turbine, ".CD") driver_run = standalone.is_file() if driver_run and coupled.is_file(): - # OpenFAST always writes its glue-code table .out next to - # CableDyn's .CD.out: only a CableDyn driver table there is a + # OpenFAST and FAST.Farm always write their glue-code table .out + # next to CableDyn's file: only a CableDyn driver table there is a # second CableDyn run under the same root. if _is_cabledyn_main_table(standalone): raise CableSchemaError( @@ -2546,15 +2588,16 @@ def _discover(out_root: Path, line_id: int) -> dict[str, Path]: elif coupled.is_file(): files["main"] = coupled for role, suffix in ( - ("static", ".CD.static.out"), - ("range", f".CD.Line{line_id}.range.out"), + ("static", f"{prefix}.static.out"), + ("range", f"{prefix}.Line{line_id}.range.out"), ): candidate = Path(f"{out_root}{suffix}") if candidate.is_file(): files[role] = candidate else: raise FileNotFoundError( - f"no CableDyn output {standalone.name} or {coupled.name} next to {out_root}" + f"no CableDyn output {standalone.name}, {turbine.name} or {farm.name} " + f"next to {out_root}" ) return files @@ -3120,14 +3163,18 @@ 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. Parameters ---------- out_root : str or pathlib.Path - Output root given to the driver (``.out`` and its line files) or - the OpenFAST root (``.CD.out``). + Output root given to the driver (``.out`` and its line files), + the OpenFAST root (``.CD.out``) or the FAST.Farm root + (``.FarmCD.out``). deck : str, pathlib.Path or CableDynDeck The deck that produced the run. sections : mapping of str to float @@ -3177,6 +3224,22 @@ 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`). The line's own + nodes outside the grid and any grid resolution finding count; nodes + of other lines outside the grid 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 ------- @@ -3241,9 +3304,27 @@ def read_cabledyn_sections( # The route that wrote the output: the standalone driver runs the deck's # 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") + main_name = paths["main"].name + farm_run = main_name.endswith(".FarmCD.out") + coupled_run = farm_run or main_name.endswith(".CD.out") + # The wave provenance first: a refused line fails before the output is read. + global_record = replace( + cabledyn_provenance(paths["main"], log=log), line_id=line_id + ) + 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)" + "FAST.Farm (.FarmCD.out)" + if farm_run + else "OpenFAST (.CD.out)" + if coupled_run + else "standalone driver (.out)" ) if not coupled_run and not ( deck_obj.t_max_s is not None and deck_obj.t_max_s > 0.0 @@ -4428,8 +4509,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 +4520,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..b569815 --- /dev/null +++ b/src/cablexsec/io/global_provenance.py @@ -0,0 +1,1450 @@ +# 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 beside its result file + (:func:`provenance_sidecar`: ``x.CD.out`` -> ``x.CD.provenance.json``, + ``x.FarmCD.out`` -> ``x.FarmCD.provenance.json``, ``x.out`` -> + ``x.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 result file itself shows (CableDyn and its host), + 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 when the record holds a grid resolution finding, which +concerns every line in the water. Nodes of other lines outside the grid (for +example mooring lines below it) 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, cast + +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"] +Point = tuple[float | None, float | None, float | None] + +_HOSTS = ("openfast", "fast.farm", "standalone", "capi") +_ROUTES = ("seastate_grid", "seastate_spectral", "deck", "none") +_GRID_CHECKS = ("error", "warn") +#: ``init`` until the run ends; ``stopped`` when it ended on an error. +_STATUSES = ("init", "complete", "stopped") +_UNFINISHED = ("init", "stopped") +_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, and any + coordinate of a point, may be ``None`` (not recorded). + """ + + n_nodes_max: int | None = None + first_time_s: float | None = None + deepest_xyz_m: Point | None = None + shallowest_xyz_m: Point | 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 outside(self) -> bool: + """Whether any node of the line was outside the grid.""" + return 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 + ) + + @property + def affected(self) -> bool: + """Whether any node was outside the grid or any resolution flag is set.""" + return self.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 result + file 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"``; ``"init"`` (the run did not finish) or ``"stopped"`` + (it ended on an error). + restarted_from_s : float or None + The time of the checkpoint the run restarted from. + waves : WaveRecord + Route, identity, 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 may leave out affected lines (a log message + cut short or without a per-line list, or the one warning of a run + under ``waveGridCheck warn``). + resolution_findings : tuple of str + Grid resolution findings of the run as a log states them; with the + per-line flags, :attr:`all_resolution_findings`. + line_id : int, str or None + The analysed line, set by the reader of its histories. + 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 + restarted_from_s: float | None = None + waves: WaveRecord = field(default_factory=WaveRecord) + grid: WaveGrid | None = None + lines: tuple[LineWaveRecord, ...] | None = None + lines_complete: bool = True + resolution_findings: tuple[str, ...] = () + line_id: int | str | None = None + 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 all_resolution_findings(self) -> tuple[str, ...]: + """Every grid resolution finding of the run, of any line, once each.""" + found = list(self.resolution_findings) + for item in self.lines or (): + found.extend(f for f in item.resolution_flags if f not in found) + return tuple(dict.fromkeys(found)) + + @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 the analysed line's findings. + + ``line_id`` defaults to the analysed line the reader recorded. + """ + line_id = self.line_id if line_id is None else line_id + 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: + findings = self.all_resolution_findings + parts.append( + f"line {line_id}: " + + ( + "resolution findings of the grid: " + "; ".join(findings) + if findings + else "no findings" + if self.lines is not None and self.lines_complete + else "not covered by the record" + ) + ) + else: + # A resolution finding concerns every line in the water, also + # when the record flags only another line. + others = tuple( + f + for f in self.all_resolution_findings + if f not in record.resolution_flags + ) + own = record.outside or bool(record.resolution_flags) + text = ( + _line_text(record) if own or not others else "inside the wave grid" + ) + if others: + text += "; resolution findings of the grid: " + "; ".join(others) + parts.append(f"line {line_id}: {text}") + 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.restarted_from_s is not None: + parts.append(f"restarted from t = {self.restarted_from_s:g} s") + if self.status in _UNFINISHED: + parts.append( + "the run did not finish" + + (" (it ended on an error)" if self.status == "stopped" else "") + ) + 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, manifests and exchange files.""" + 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, + "restarted_from": self.restarted_from_s, + "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, + "resolution_findings": list(self.resolution_findings), + "analysed_line": self.line_id, + "unknown": list(self.unknown_fields), + "notes": list(self.notes), + } + + @classmethod + def from_record(cls, data: Mapping[str, Any]) -> GlobalProvenance: + """Rebuild a record from :meth:`to_record` (manifest, exchange CSV).""" + top = _Fields(dict(data), "global_provenance", Path("global_provenance")) + origin = top.text("origin", ("sidecar", "log", "declared", "output", "none")) + if origin is None: + raise CableSchemaError("global_provenance: origin is required") + file = top.child("file") + notes = top.data.get("notes") or [] + findings = top.data.get("resolution_findings") or [] + for key, values in (("notes", notes), ("resolution_findings", findings)): + if not isinstance(values, list) or not all( + isinstance(v, str) for v in values + ): + raise CableSchemaError(f"global_provenance: {key} must be strings") + complete = top.data.get("lines_complete", True) + if not isinstance(complete, bool): + raise CableSchemaError("global_provenance: lines_complete must be a bool") + analysed = top.data.get("analysed_line") + if analysed is not None and ( + isinstance(analysed, bool) or not isinstance(analysed, int | str) + ): + raise CableSchemaError("global_provenance: analysed_line must be an id") + return cls( + origin=cast(Origin, origin), + solver=top.text("solver"), + solver_version=top.text("solver_version"), + host=top.text("host"), + host_version=top.text("host_version"), + status=top.text("status", _STATUSES), + restarted_from_s=top.number("restarted_from"), + waves=_waves(top.child("waves")), + grid=_grid(top.child("grid")), + lines=_lines(top), + lines_complete=complete, + resolution_findings=tuple(findings), + line_id=analysed, + origin_file=None if file is None else file.text("path"), + origin_sha256=None if file is None else file.text("sha256"), + notes=tuple(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: Point | None) -> str: + if xyz is None: + return "?" + return "(" + ", ".join("?" if v is None else 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 record.outside: + 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 # +# --------------------------------------------------------------------------- # +#: The result-file roots under which CableDyn names its record after the root +#: itself; any other root (the standalone driver's ``x.out``) takes ``.CD``. +_HOST_ROOTS = ((".FarmCD", "fast.farm"), (".CD", "openfast")) + + +def provenance_sidecar(result_file: str | Path) -> Path: + """The provenance file CableDyn writes beside a result file. + + The record's root is the result file's name without ``.out``: + ``x.CD.out`` (OpenFAST) gives ``x.CD.provenance.json``, ``x.FarmCD.out`` + (FAST.Farm) ``x.FarmCD.provenance.json``; the standalone driver's + ``x.out`` gives ``x.CD.provenance.json``. + """ + path = Path(result_file) + root = path.name[:-4] if path.name.endswith(".out") else path.name + if not root.endswith(tuple(suffix for suffix, _ in _HOST_ROOTS)): + root += ".CD" + return path.with_name(f"{root}.provenance.json") + + +def _host_of(result_file: Path) -> str: + root = result_file.name[:-4] if result_file.name.endswith(".out") else "" + for suffix, host in _HOST_ROOTS: + if root.endswith(suffix): + return host + return "standalone" + + +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) -> Point | None: + value = self.data.get(key) + if value is None: + return None + if ( + not isinstance(value, list) + or len(value) != 3 + or any( + v is not None + and ( + 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 (or nulls)") + x, y, z = (None if v is None else float(v) for v in value) + return (x, y, z) + + 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 _decode(raw: bytes) -> tuple[str, str | None]: + """The record's text and, when it is not UTF-8, a note saying so.""" + try: + return raw.decode("utf-8-sig"), None + except UnicodeDecodeError: + pass + for encoding in ("cp1252", "latin-1"): + try: + text = raw.decode(encoding) + except UnicodeDecodeError: + continue + return text, ( + f"the record is not UTF-8; read as {encoding}, so names outside " + "ASCII may differ from those the run used" + ) + raise AssertionError("latin-1 decodes every byte") # pragma: no cover + + +def read_cabledyn_provenance(path: str | Path) -> GlobalProvenance: + """Read and check a CableDyn provenance file (:func:`provenance_sidecar`). + + 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 whose ``status`` is ``"init"`` + (the run did not finish) or ``"stopped"`` (it ended on an error) is read + with an :class:`~cablexsec.provenance.UnfinishedRunWarning`. A file that + is not UTF-8 is read as Windows-1252 (else Latin-1), with a note. + + 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() + text, encoding_note = _decode(raw) + try: + data = json.loads(text) + except 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) + notes: list[str] = [] if encoding_note is None else [encoding_note] + if status in _UNFINISHED: + what = ( + "the run ended on an error" + if status == "stopped" + else "the run did not finish" + ) + notes.append( + f"the record has status {status!r}: {what}, so its findings cover " + "only the part of the run before it stopped" + ) + warnings.warn( + f"{p.name}: status {status!r}: the CableDyn run did not finish " + f"({what}); 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, + restarted_from_s=top.number("restarted_from"), + waves=_waves(top.child("waves")), + grid=_grid(top.child("grid")), + lines=_lines(top), + origin_file=str(p.resolve()), + origin_sha256=hashlib.sha256(raw).hexdigest(), + notes=tuple(notes), + ) + + +def _grid(fields: _Fields | None) -> WaveGrid | None: + if fields is None: + return None + return WaveGrid( + nx=fields.integer("nx"), + ny=fields.integer("ny"), + nz=fields.integer("nz"), + x_half_width_m=fields.number("x_half_width"), + y_half_width_m=fields.number("y_half_width"), + z_depth_m=fields.number("z_depth"), + wave_grid_check=fields.text("wave_grid_check", _GRID_CHECKS), + ) + + +def _lines(top: _Fields) -> tuple[LineWaveRecord, ...] | None: + raw_lines = top.data.get("lines") + if raw_lines is None: + return None + if not isinstance(raw_lines, list): + raise CableSchemaError( + f"{top.path.name}: {top.where}.lines must be a list or null" + ) + return tuple( + _line_record(_Fields(item, f"{top.where}.lines[{i}]", top.path)) + for i, item in enumerate(raw_lines) + ) + + +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:|$)" +) +# The resolution message: since CableDyn c09e755 it names every node of the +# lines in the water ("for the hull members and for the lines, which sample the +# grid in the water at N CableDyn nodes"); 35b0c8f named only the nodes between +# grid points. The sea is "long-crested waves at ...", "a short-crested sea +# (...)", "wave components in directions ..." or "externally supplied wave +# kinematics (WaveMod 6) that differ between the grid points across it". +_RESOLUTION = re.compile( + r"CableDyn mooring module: the SeaState wave-kinematics grid has " + r"(?P.+?) under (?P.+?), which vary along that axis: .*? " + r"(?:for the hull members and for the lines, which sample the grid in the " + r"water at (?P\d+) CableDyn nodes|(?P\d+) of the (?P\d+) " + r"CableDyn sampling nodes in the water lie between grid points there)\." + r"(?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