diff --git a/CHANGELOG.md b/CHANGELOG.md index cdbd2171..d7ec671d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,45 @@ All notable changes to CableDyn are recorded in this file. The format follows ## [Unreleased] +### Added + +- `OPTIONS SEASTATE_SPECTRAL WaterKin` (OpenFAST): the lines take SeaState's first-order waves from its + own wave components, evaluated at the line nodes, instead of interpolating its grid. At a grid vertex + and a wave step the values equal SeaState's grid to the round-off of its single-precision FFT; between + the vertices they are the sums of the components, not an interpolation, so a sea at any heading, long- or short-crested, needs no grid over the + lines and SeaState's grid can shrink to the hull. Each node evaluates the components once per wave + step at its position advanced to the middle of the step and interpolates by cubic Hermite polynomials + with the exact time derivatives; `OPTIONS waveKinTol` (default `1e-6`) lets each node drop the + components whose velocity and acceleration variances stay within that fraction of the totals at + every depth the node reaches, reported per node in `.CD.wavekin.out`; under Wheeler stretching + the elevation that maps a node's depth keeps, by the same bound, the short waves its kinematics + drop. Every SeaState stretching mode is reproduced; + second-order kinematics, `WaveMod = 6`, `WvCrntMod` 1 or 2, `CurrMod = 2` and a `WaveTimeShift` stop + the run with a message naming `SEASTATE_GRID`, which, like `SEASTATE` and a deck without a WaterKin + row, keeps the grid. A `CurrMod = 1` current is taken at each node's depth, in the static start as in + the steps, so neither depends on SeaState's vertical grid. `cabledyn_wavekin_check` (built in the + OpenFAST tree) compares the two routes at SeaState's grid vertices. + +- Every OpenFAST, FAST.Farm and standalone run writes a provenance record, `.CD.provenance.json` + (`.FarmCD.provenance.json`, `.CD.provenance.json`): JSON of schema + `cabledyn.provenance/1` with the host, the wave route, the sea (SeaState's `WaveMod`, direction, + wave step and period, depth, and a fingerprint of its components that identifies the sea exactly), + the SeaState grid and `waveGridCheck` mode on the grid route, and per deck line the wave-grid guard's + findings (with the weighted velocity ratio: the rms wave velocity at the line's shallowest node + outside the grid over that at the surface, from SeaState's components, also given in the guard's + message) and the variances the node-wise route drops. It is written at the start and replaced, in one + step, at the end (`complete`, or `stopped` after an error); a checkpoint carries its findings, so a + restarted run writes the same record but for `restarted_from`. Unknown values are `null`. Under + `waveGridCheck warn` the coverage check now goes on silently after its one warning, for the record, and + a restart no longer repeats the warning. + +- `integration/openfast/cabledyn_preflight.py` checks an OpenFAST case before it runs: line ends and hull + joints against the SeaState grid with a margin for the platform motion, `NX` or `NY` = 2 under a sea + that varies along that axis, the amplitude the grid keeps at the shortest wavelength that matters, + SeaState's stored memory and start-up peak (about 3 times the stored arrays), and whether + `SEASTATE_SPECTRAL` takes the case, with a hull-only grid for it. `integration/openfast/cabledyn_logscan.py` + reads the logs (and provenance records) of many runs and lists per line what the wave-grid guard found. + ### Changed - In OpenFAST, a coupled run whose lines take their wave or current kinematics from the SeaState grid now diff --git a/CMakeLists.txt b/CMakeLists.txt index 998a1eca..8bbf8ff0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -421,6 +421,7 @@ add_library(cabledyn_obj OBJECT src/CableDyn_LoadPredictor.f90 src/CableDyn_WaveGrid.f90 src/CableDyn_PathIO.f90 + src/CableDyn_Provenance.f90 src/CableDyn_Banner.f90 src/CableDyn_Linalg.f90 src/CableDyn_AD.f90 @@ -447,6 +448,7 @@ add_library(cabledyn_obj OBJECT src/CableDyn_Loads.f90 src/CableDyn_Bathymetry.f90 src/CableDyn_WaveMath.f90 + src/CableDyn_WaveNodewise.f90 src/CableDyn_Hydro.f90 src/CableDyn_WaveSpectra.f90 src/CableDyn_StreamWave.f90 @@ -1305,6 +1307,23 @@ add_test(NAME wave_grid COMMAND test_wave_grid ${CMAKE_SOURCE_DIR}/examples/iea1 WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/wave_grid) set_tests_properties(wave_grid PROPERTIES LABELS "fortran;unit;openfast") +# Node-wise first-order wave kinematics (WaterKin SEASTATE_SPECTRAL): Airy theory in SeaState's +# convention, exact time derivatives, the stretching modes, Hermite time interpolation, truncation. +add_executable(test_wave_nodewise tests/test_wave_nodewise.f90) +target_link_libraries(test_wave_nodewise PRIVATE cabledyn_core) +add_test(NAME wave_nodewise COMMAND test_wave_nodewise) +set_tests_properties(wave_nodewise PROPERTIES LABELS "fortran;unit;openfast") + +# The provenance record [.CD].provenance.json: the FNV-1a component fingerprint against +# reference values, nulls, seeds, line entries and the one-step replacement. +add_executable(test_provenance tests/test_provenance.f90) +target_link_libraries(test_provenance PRIVATE cabledyn_core) +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/provenance) +# a directory where the test writes a record: the replacement fails and must leave no .tmp +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/provenance/blocked.json) +add_test(NAME provenance COMMAND test_provenance WORKING_DIRECTORY ${CMAKE_BINARY_DIR}/provenance) +set_tests_properties(provenance PROPERTIES LABELS "fortran;unit") + # The same deck initialises without a static compression/mesh note: the touchdown # contact kink is element-local, the smoothed element-mean axial force is tensile. add_executable(test_flagship_compression_note tests/test_flagship_compression_note.f90) @@ -2162,6 +2181,26 @@ if(Python3_Interpreter_FOUND) TIMEOUT 600 ENVIRONMENT "${_cabledyn_python_test_environment}") + # The standalone provenance record: valid JSON of schema 1 for a still-water deck, a JONSWAP deck + # and a run that fails after parsing. + add_test(NAME provenance_sidecar + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_provenance_sidecar.py + --exe $ + --output ${CMAKE_BINARY_DIR}/provenance_sidecar) + set_tests_properties(provenance_sidecar PROPERTIES + LABELS "python;driver;integration" + TIMEOUT 600 + ENVIRONMENT "${_cabledyn_python_test_environment}") + + # The OpenFAST pre-flight checker and log scanner (integration/openfast) on synthetic cases. + add_test(NAME openfast_preflight_logscan + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_openfast_preflight_logscan.py + --output ${CMAKE_BINARY_DIR}/openfast_preflight_logscan) + set_tests_properties(openfast_preflight_logscan PROPERTIES + LABELS "python;openfast" + TIMEOUT 600 + ENVIRONMENT "${_cabledyn_python_test_environment}") + # Anchor uplift channels (AnchFz/AnchFH, TDPGrd): the analytic laid and suspended elastic # catenaries, the Point

F identity on every standalone route, and a surge that lifts the # anchor of a catenary (needs numpy). diff --git a/doc/driver_format.md b/doc/driver_format.md index 3f0fa313..56500003 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -1830,6 +1830,9 @@ aggregate route and in a mixed `EI = 0` + finite-EI standalone deck. **Host modes** (`WaveKinMod 2`/`SEASTATE`, `CurrentMod 2`) require aggregate/OpenFAST initialisation with a SeaState field; the standalone driver rejects them with `WaterKin WaveKinMod 2/SEASTATE is coupled-only`. +The deck OPTION itself may also read `SEASTATE_GRID` (the same as `SEASTATE`) or +`SEASTATE_SPECTRAL`, which evaluates the SeaState wave components at the nodes instead of its grid +(OpenFAST only; see the [OPTIONS reference](options.rst) and [OpenFAST](openfast.rst)). - Host waves may be combined with a file `CurrentMod 1` profile. - Current-only host mode removes host wave velocity and acceleration and uses still-water wetting. diff --git a/doc/faq.rst b/doc/faq.rst index a554942d..034dbcef 100644 --- a/doc/faq.rst +++ b/doc/faq.rst @@ -131,3 +131,40 @@ OpenFAST coupling final failure reports the simulated interval, ceiling, and maximum prescribed displacement increment. The profiler reports the recovery count. Use a checkpoint (``ChkptTime`` in the ``.fst`` file) to replay any event without rerunning the full transient. + +.. admonition:: Why does my coupled run stop over the SeaState grid when MoorDyn ran the same case? + :class: note + + The two differ in their defaults. A CableDyn deck without a WaterKin row takes SeaState's whole + wave and current field at its line nodes; MoorDyn without a ``WaterKin`` option keeps its lines + in still water, so its run never reads the grid at the lines. With ``SeaState WaterKin`` both + interpolate the same grid, but MoorDyn gives a node outside it the kinematics of the nearest + grid boundary and interpolates a grid with ``NX = 2`` or ``NY = 2`` across an oblique sea + without a word, while CableDyn stops (:ref:`openfast:SeaState grid`). The SeaState files of + many OpenFAST models are written for the platform alone: the r-test ``MD_Shared`` grid reaches + 100 m from the platform, the anchors lie 838 m away. There are three ways on: + + * ``SEASTATE_SPECTRAL WaterKin`` evaluates SeaState's wave components at the nodes; the lines + need no grid and the grid can stay at the hull + (:ref:`openfast:Wave kinematics at the nodes (SEASTATE_SPECTRAL)`). + * A grid over the lines, as :ref:`openfast:SeaState grid` sizes it; run + ``integration/openfast/cabledyn_preflight.py`` on the ``.fst`` first for its memory. + * ``SEASTATE_GRID WaterKin`` and ``warn waveGridCheck`` give the lines + the kinematics MoorDyn's lines get with ``SeaState WaterKin`` on the same grid, boundary + kinematics included, for a comparison of the line models alone. The warning comes once; the + provenance record (:ref:`outputs-provenance`) lists every line that left the grid and when. + These kinematics are not physical where the nodes leave the grid, so do not use the results + for design. + +.. admonition:: Does the hull shield the lines from the waves? + :class: note + + No. Both wave routes give each node the incident sea, SeaState's waves as they would be without + the platform, and SeaState's current; the change of the waves by the hull (diffraction and + radiation) and the hull's wake in the current are not applied to the lines. Away from the hull, + at more than about a column diameter, this is the usual and adequate assumption for moorings. + Closer, for example at the hang-off of a cable under a semi-submersible column, the waves + differ from the incident sea, and the loads there are those of open water. A node inside the + hull, such as on a cable run through an I-tube or a column, also receives the open-water loads: + start the line at the exit of the I-tube, with the restraint of the I-tube as its end + connection, so that no node lies inside the hull. diff --git a/doc/openfast.rst b/doc/openfast.rst index 3aa63b8c..7d665448 100644 --- a/doc/openfast.rst +++ b/doc/openfast.rst @@ -136,7 +136,11 @@ current in use, CableDyn evaluates that current at the levels of SeaState's vert and solves the equilibrium of every line, cable, point and body in it. A run therefore starts where a standalone deck with the same ``current`` starts, not from the still-water shape. The profile is linear in depth between the grid levels, so the start agrees with the first step's -current at the levels and very nearly between them. The dynamics then take the SeaState field +current at the levels and very nearly between them. A deck on ``SEASTATE_SPECTRAL``, whose steps +take the current at each node's depth rather than between the grid levels, starts in the profile +itself: CableDyn samples it at levels dense enough that the start does not depend on the grid +(a hull-only grid with ``NZ = 2`` would otherwise give it a straight line from the seabed to the +surface). The dynamics then take the SeaState field alone, and the current is not counted twice. Waves act from t = 0. A ``CurrMod = 2`` current or an InflowWind current field is known only through the run's samples: the start is then the still-water equilibrium, and the console says so. @@ -183,20 +187,24 @@ node outside it, at initialisation for the ``MD_Shared`` grid: CableDyn mooring module: 147 of the 153 CableDyn sampling nodes in the water lie outside the SeaState wave-kinematics grid at t = 0 s, where SeaState would give them the kinematics of the grid boundary, which are not physical there. By line: line 1, 49 nodes, deepest at (x, y, z) = - (-735.56, 0, -200.01) m, shallowest at (x, y, z) = (-77.518, 0, -41.866) m; line 2, 49 nodes, - deepest at (x, y, z) = (367.78, 637.01, -200.01) m, shallowest at (x, y, z) = (38.759, 67.132, - -41.866) m; line 3, ... . Farthest: x = -837.6 m (grid |x| <= X_HalfWidth = 100 m); y = 725.38 - m (grid |y| <= Y_HalfWidth = 100 m); z = -200.01 m (grid z >= -Z_Depth = -40 m). In the SeaState - input file enlarge X_HalfWidth, Y_HalfWidth and Z_Depth (Z_Depth at most WtrDpth + MSL2SWL, its - default) to cover the lines with margin for their motion, and raise NX, NY and NZ to keep the - grid spacing. To run on with those kinematics, set waveGridCheck warn in the OPTIONS of the - CableDyn deck. + (-735.56, 0, -200.01) m, shallowest at (x, y, z) = (-77.518, 0, -41.866) m, weighted velocity + ratio 0.19 at the shallowest node; line 2, 49 nodes, deepest at (x, y, z) = (367.78, 637.01, + -200.01) m, shallowest at (x, y, z) = (38.759, 67.132, -41.866) m, weighted velocity ratio 0.19 at + the shallowest node; line 3, ... . Farthest: x = -837.6 m (grid |x| <= X_HalfWidth = 100 m); + y = 725.38 m (grid |y| <= Y_HalfWidth = 100 m); z = -200.01 m (grid z >= -Z_Depth = -40 m). In the + SeaState input file enlarge X_HalfWidth, Y_HalfWidth and Z_Depth (Z_Depth at most WtrDpth + + MSL2SWL, its default) to cover the lines with margin for their motion, and raise NX, NY and NZ to + keep the grid spacing. To run on with those kinematics, set waveGridCheck warn in the OPTIONS of + the CableDyn deck. The message gives the time and, line by line, the number of nodes outside the grid with the -deepest and the shallowest of them. A node that leaves the grid during the run, as a line swings +deepest and the shallowest of them, and the weighted velocity ratio at the shallowest: the rms wave +velocity there over that at the surface (:ref:`outputs-provenance`), which says how much the wrong +kinematics of those nodes can matter. A node that leaves the grid during the run, as a line swings out with the platform, stops the run at that step. With ``waveGridCheck warn`` the message is a -warning, given once per run (also after a restart), and the run continues with the boundary -kinematics at those nodes. +warning, given once per run (a restart from a checkpoint does not repeat it), and the run +continues with the boundary kinematics at those nodes; the check goes on at every step for the +provenance record (:ref:`outputs-provenance`). At initialisation CableDyn also checks the grid against the directions of the sea. A grid with ``NX = 2`` or ``NY = 2`` has three points along that axis, ``X_HalfWidth`` (or ``Y_HalfWidth``) @@ -257,6 +265,112 @@ linearly across it to the seabed, so near the seabed it differs from a deck dept interval exceeds 5 % of the depth (``NZ`` below 33) and a line lies in it, an initialisation note states the interval and the ``NZ`` that would bring it under 5 %. +Wave kinematics at the nodes (SEASTATE_SPECTRAL) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``SEASTATE_SPECTRAL WaterKin`` in the deck's OPTIONS takes SeaState's own first-order wave +components and evaluates them at the line nodes, so the lines need no grid at all: no grid has +to reach the anchors, and a sea at any heading, long- or short-crested, costs the same. At a grid +vertex and a wave step the values equal SeaState's grid to the round-off of its single-precision +FFT; between the vertices they are the sums of the components themselves, where the grid +interpolates, less the components each node may drop under ``waveKinTol``. ``SEASTATE`` (or +``SEASTATE_GRID``) and a deck without a WaterKin row keep the grid. The formulas, the time +interpolation and the truncation are in :ref:`theory-nodewise-waves`. + +* **Grid for the hull.** HydroDyn's Morison members still read SeaState's grid, which SeaState + allocates as its input file asks. Shrink it to the hull: half-widths covering the members with + margin for the platform motion, and a spacing of a tenth of the shortest wavelength that matters + at the members or finer (SeaState's cubic interpolation keeps 99.6 % of the amplitude there). + With a coarse hull grid the lines are exact while the hull is interpolated, so the two can + disagree for reasons that are not errors. The wave-grid checks (``waveGridCheck``) apply to the + lines on the grid route only. +* **Time.** Each node evaluates the components at the two wave steps (SeaState's ``WaveDT``) + around the sample time, once per wave step, at its position advanced to the middle of the step, + and interpolates by cubic Hermite polynomials with the exact time derivatives in between. +* **Truncation.** ``waveKinTol`` (default ``1e-6``; ``0`` keeps every component) bounds the + velocity and the acceleration variance each node drops, each relative to its own total at the + node's depth, at every depth the node reaches. Deep nodes keep the few long waves that reach + them. The initialisation prints the range of components kept + and the largest dropped variances, and writes them per node to ``.CD.wavekin.out``. Under + Wheeler stretching (``WaveStMod = 3``) the elevation, which sets the depth a node's kinematics + are evaluated at, keeps the short waves a node drops from its kinematics whenever they move that + depth enough to matter, by the same tolerance (:ref:`theory-nodewise-waves`). +* **Cost.** A node sums its kept components at both ends of each wave step. For a one-hour sea of + 2407 components (``WaveDT = 0.2 s``, Tp 7.65 s) at 600 nodes on three catenaries and a cable in + 200 m of water, the nodes keep 420 components on average at the default ``waveKinTol`` (360 at + ``1e-4``: a deep node keeps the long waves that reach it, a node near the surface nearly all) and + the sums take about 80 s on one core (gfortran, baseline x86-64 build), some 6 % of a one-hour + coupled run of 20 to 25 minutes; the time interpolation between the wave steps adds 2 % to that. Keeping + every component (``waveKinTol = 0``) takes about 510 s. +* **Current.** SeaState's steady current (``CurrMod = 1``) is evaluated at the node from its + profile where SeaState's sampler would read it (the Wheeler depth under Wheeler stretching, the + still-water level above it under vertical or extrapolation stretching); a dynamic current field + is read as SeaState reads it. A WaterKin ``CurrentMod 1`` table is added as on the grid route. +* **Not supported** (the run stops at initialisation and names ``SEASTATE_GRID``): second-order + wave kinematics (``WvDiffQTF``, ``WvSumQTF``), ``WaveMod = 6`` (kinematics read from files), + wave-current interaction (``WvCrntMod`` 1 or 2), SeaState's user current (``CurrMod = 2``), a + ``WaveTimeShift``, and the C API, whose host supplies the kinematics itself. FAST.Farm's + ``Mod_WaveField = 2`` needs nothing further: SeaState shifts the phases of its components for + each turbine before the grid and the node-wise sums use them. +* **Restart and linearisation.** A checkpoint carries each node's values for its wave step, so a + restarted run continues as the uninterrupted one. SeaState linearises only in still water, where + the route has nothing to evaluate. + +Checking a case before it runs, and its logs after +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +``integration/openfast/cabledyn_preflight.py `` (Python, standard library only) reads +the ``.fst``, its SeaState and HydroDyn files and the CableDyn deck, and reports before the run: + +* whether the end points of every line and the hull's Morison joints lie inside the SeaState + grid, with a margin for the platform motion (``--margin``, 20 m by default); +* whether the grid has ``NX`` or ``NY`` = 2 under a sea that varies along that axis (the + wave-grid guard stops such a run), and, for the shortest wavelength that matters (the highest + frequency from ``WvLowCOff`` to ``WvHiCOff``, the band SeaState keeps, whose spectral density is at + least 1 % of the peak in that band), how much of its amplitude the grid keeps midway between grid + points along each axis, and the same at the peak period, which shows what most of the wave energy + keeps; +* the memory SeaState stores for its grid and its start-up peak; +* whether ``SEASTATE_SPECTRAL`` can take the case, and, for that route, a hull-only grid: the + hull's Morison joints plus the margin, at a tenth of the shortest wavelength at the deepest + joint, with its memory. Without Morison members the hull reads no grid (the WAMIT excitation + with ``ExctnDisp = 0`` is built from the wave components) and the smallest grid serves. + +It reads the files as CableDyn and OpenFAST do: an OpenFAST value from either of the first two +words of its row, without regard to case; the deck's sections under CableDyn's names, its +options under either spelling with the last row winning, and a WaterKin file for what the lines +take from SeaState (the guard checks only that); SeaState's rules for a short-crested sea and for +``WvCrntMod`` without a current; the component directions of ``WaveMod = 7`` and, for +``WaveMod = 6``, the supplied kinematics themselves (up to 256 MB; larger data are judged by +CableDyn at initialisation). It also stops on what fails CableDyn's initialisation whatever the +grid: a nonzero ``MSL2SWL`` or a SeaState ``WtrDpth`` other than the ``.fst``'s with SeaState +waves or current. It exits with 1 when the run would stop, 2 when a file cannot be read or the +case is not a CableDyn one. The check uses the line end points (a Body point at its body's +position plus its offset; an end above the still-water level carries no fluid load and is left +out), so a line's sag between them is judged by its deeper end; the guard in the run tests every +node at every step. + +**Memory.** SeaState stores, for each of the ``NStepWave + 1`` wave steps (``NStepWave`` is +``WaveTMax/WaveDT`` rounded up to an even number), at each of the (2 ``NX`` − 1)(2 ``NY`` − 1) +``NZ`` grid points, the velocity and acceleration (3 values each) and the dynamic pressure, three +more values with MacCamy-Fuchs (``MCFD > 0``), and at each of the (2 ``NX`` − 1)(2 ``NY`` − 1) +surface points the elevation, the seven extrapolation derivatives with ``WaveStMod = 2``, and the +elevation spectrum (2 (``NStepWave``/2 + 1) values), all in single precision (4 bytes). Its peak +while it builds the grid is about 3 times the stored arrays: the slope of the measured peak +working set against the stored arrays of four grids of 21 MB to 270 MB is 2.95 (gfortran build of +OpenFAST 2895884). Several runs started together can therefore need three times their steady +memory at once. + +``integration/openfast/cabledyn_logscan.py `` reads OpenFAST logs (``*.log`` in +a folder) and reports for each run its wave route, whether it ended normally or stopped, and per +line the guard's findings; it reads the provenance record of the same run +(:ref:`outputs-provenance`), which under ``waveGridCheck warn`` covers the whole run where the log +shows only the first warning: the record named after the log (``run.log`` and +``run.CD.provenance.json``), else the only record in the log's folder unless another log there is +named after it. ``--csv`` writes one row per run and line, with the weighted velocity ratio of +each line that left the grid. It exits with 1 on a guard finding and with 2 when no log could be +read (a missing or unreadable path is reported and skipped). + Run and confirm --------------- diff --git a/doc/options.rst b/doc/options.rst index 0c05450a..a1e2ac65 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -584,6 +584,15 @@ Finite-EI cable controls and runs on with SeaState's kinematics there (see :ref:`openfast:SeaState grid`) - OpenFAST (a run that samples SeaState); accepted and unused elsewhere - ``warn waveGridCheck`` + * - ``waveKinTol`` / ``wave_kin_tol`` + - real, – + - ``1e-6`` + - finite, at least 0 and below 1. With ``WaterKin SEASTATE_SPECTRAL``: each node keeps the + fewest wave components (in order of wavenumber) whose dropped velocity variance and dropped + acceleration variance are each at most this fraction of their totals at the node's depth; + ``0`` keeps every component (:ref:`theory-nodewise-waves`) + - OpenFAST with ``SEASTATE_SPECTRAL``; accepted and unused elsewhere + - ``1e-6 waveKinTol`` * - ``CDOutDt`` / ``cd_out_dt`` - real, s - ``0`` @@ -788,13 +797,15 @@ Ambient fluid and prescribed motion - ``vesselMotion``, ``vesselRAO`` - ``90.0|0.0|-14.0 vesselRef`` * - ``WaterKin`` / ``WaveKin`` - - ``0``/``none``, ``3``, ``7``, path, or ``SEASTATE`` + - ``0``/``none``, ``3``, ``7``, path, ``SEASTATE``, ``SEASTATE_GRID`` or ``SEASTATE_SPECTRAL`` - ``0`` (no WaterKin policy) - ``0`` or ``none`` means still water from this record; ``3`` and ``7`` are the MoorDyn-C modes that read ``wave_elevation.txt`` and ``wave_frequencies.txt`` in the deck folder; a value containing a letter (other than an exponent ``e``) is a MoorDyn-F WaterKin - filename; ``SEASTATE`` selects the host field. The other MoorDyn-C modes fail closed by - name. Mode rules are in :ref:`moordyn-c-wavekin` and :ref:`waterkin-file-modes` + filename; ``SEASTATE`` (or ``SEASTATE_GRID``) selects the host field on its grid, + ``SEASTATE_SPECTRAL`` the host's wave components evaluated at the nodes (OpenFAST only; see + :ref:`openfast:Wave kinematics at the nodes (SEASTATE_SPECTRAL)`). The other MoorDyn-C modes + fail closed by name. Mode rules are in :ref:`moordyn-c-wavekin` and :ref:`waterkin-file-modes` - ``3``/``7`` and file ``WaveKinMod 1``: standalone decks only; ``SEASTATE``, ``WaveKinMod 2``, and ``CurrentMod 2``: OpenFAST and C API hosts with a host fluid field - ``waterkin.dat WaterKin`` diff --git a/doc/outputs.rst b/doc/outputs.rst index 1b9cdef9..7cd47217 100644 --- a/doc/outputs.rst +++ b/doc/outputs.rst @@ -75,6 +75,9 @@ The driver names every file from the ```` argument. Which files appear - rejected (fail-closed) - -- +Every route also writes the provenance record ``.CD.provenance.json`` +(:ref:`outputs-provenance`). + The ``EI = 0`` dynamic routes never write ``.static.out``: use a separate static-only run of the same deck (remove ``dtM`` and ``TMax``) when the static range table is needed. A line or rod file is written only when the corresponding ``Outputs`` flag is set. The range graph @@ -1119,6 +1122,9 @@ output root: selected * - ``.FarmCD.static.out`` / ``.FarmCD.out`` - the same two files for a FAST.Farm run, named from the FAST.Farm output root + * - ``.CD.provenance.json`` (``.FarmCD.provenance.json``) + - the provenance record of the run (:ref:`outputs-provenance`); ``.CD.wavekin.out`` + lists, with ``WaterKin SEASTATE_SPECTRAL``, the wave components each node keeps * - ``.CD.rst.dat`` - temporary copy of the CableDyn deck, written in the ``MooringFile`` folder when a run restarts from a checkpoint; the module rebuilds its model from it and removes it after use @@ -1152,6 +1158,100 @@ a single-turbine run the module also prints every selected channel's static value to the screen after initialisation. A deck with no ``OUTPUTS`` section is valid but publishes no channels. +.. _outputs-provenance: + +Provenance record +----------------- + +Every run writes a machine-readable record of how it was made, for a tool that reads its results +(a cross-section analysis, a fatigue post-processor) to judge whether they are fit for use. It is +named from the run's output root, beside its CableDyn result file: + +* OpenFAST: ``.CD.provenance.json`` beside ``.CD.out``; +* FAST.Farm: ``.FarmCD.provenance.json`` beside ``.FarmCD.out``; +* standalone driver: ``.CD.provenance.json`` beside ``.out``. + +The C API writes no files and no record. The record is written when the run starts (``"status": +"init"``) and again when it ends (``"complete"`` after a normal end, ``"stopped"`` when it ended on +an error), each time to a temporary file that then replaces it, so a reader never sees half a +file. A run the wave-grid guard stops writes it, ``"stopped"``, at the stop, also during the +initialisation; a coupled run that stops on another error before its initialisation ends (a +rejected input) writes none, and the standalone driver writes it once the deck is read. Under +``waveGridCheck warn`` the record is also rewritten, still ``"init"``, when the guard gives its +warning. The JSON object, schema ``"cabledyn.provenance/1"``, holds these keys; a value CableDyn +does not know is ``null``, never a guess: + +.. list-table:: + :header-rows: 1 + :widths: 30 70 + + * - Key + - Value + * - ``schema``, ``cabledyn_version`` + - ``"cabledyn.provenance/1"``; the CableDyn version, as ``"0.4.3"`` + * - ``host``, ``host_version`` + - ``"openfast"``, ``"fast.farm"`` or ``"standalone"``; ``null`` (not known to CableDyn) + * - ``waves.route`` + - ``"seastate_grid"`` (the SeaState grid), ``"seastate_spectral"`` (``WaterKin + SEASTATE_SPECTRAL``), ``"deck"`` (the deck's own sea) or ``"none"`` (still water) + * - ``waves.wave_mod``, ``wave_dir_deg``, ``wave_dir_mod`` + - SeaState's ``WaveMod``, ``WaveDir`` and 1 for a short-crested sea (0 otherwise); on the + standalone route ``wave_mod`` is ``null`` and ``wave_dir_mod`` is 1 under ``WaveSpreading`` + * - ``waves.wave_seed``, ``wave_hs``, ``wave_tp``, ``source_file`` + - standalone: the ``WaveSeed`` (``[seed, null]``, for a ``jonswap`` row) and the ``waves`` row's + height and period; in OpenFAST ``null``, because SeaState keeps neither its seeds, nor + ``WaveHs`` and ``WaveTp``, nor the name of its input file where CableDyn can read them + * - ``waves.n_components``, ``component_fingerprint`` + - SeaState's first-order components with a nonzero amplitude, and a fingerprint that + identifies the sea exactly (spectrum, seed and directions together): the FNV-1a 64-bit hash, + as 16 lower-case hexadecimal digits, of the bytes as stored (single precision, + little-endian) of ``WaveElevC0`` in storage order (the real and imaginary parts of component + 0, 1, ... ``NStepWave/2``), then ``WaveDirArr`` (0 ... ``NStepWave/2``), then ``WaveDOmega``. + Two runs on the same sea carry the same fingerprint. ``null`` without components (still + water, ``WaveMod = 6``, the standalone route) + * - ``waves.wave_dt``, ``wave_tmax``, ``effective_water_depth``, ``wave_kin_tol`` + - SeaState's wave step, its repeat period (``NStepWave`` times the step), ``EffWtrDpth`` + (the standalone ``WtrDpth``), and ``waveKinTol`` on the node-wise route (else ``null``) + * - ``grid`` + - on the grid route: ``nx``, ``ny`` (SeaState's ``NX``, ``NY``, nodes on each half), + ``nz``, ``x_half_width``, ``y_half_width``, ``z_depth`` and ``wave_grid_check`` + (``"error"`` or ``"warn"``); else ``null`` + * - ``lines[]`` + - one entry per deck line: ``id`` (its ``LINES`` id; bodies, rods and points are not listed), + ``n_nodes`` (its sampling nodes in OpenFAST, else ``null``), ``out_of_grid`` (``null``, or + the guard's findings: ``n_nodes_max`` nodes outside at once, the ``first_time`` it found + one, the ``deepest_xyz`` and ``shallowest_xyz`` positions among them, and + ``weighted_velocity_ratio_max``, see below), ``resolution_flags`` (``[]``, or + ``["grid_coarse_across_waves"]`` when the grid has ``NX`` or ``NY`` = 2 under waves that + vary along that axis), and ``dropped_velocity_variance_max`` and + ``dropped_acceleration_variance_max`` (the node-wise route: the largest variances a node + of the line drops at its static position, relative to the totals at that depth; else ``null``) + * - ``restarted_from`` + - the time of the checkpoint a restarted run continued from, else ``null``. A checkpoint + carries the record's findings, so a restarted run writes the same record as the + uninterrupted one but for this key + * - ``status`` + - ``"init"``, ``"complete"`` or ``"stopped"`` + +Under ``waveGridCheck warn`` the coverage check goes on at every step after its one warning, so +the out-of-grid findings cover the whole run in both modes. + +``weighted_velocity_ratio_max`` says how much the waves still move the water where a line left the +grid: the rms wave-particle velocity magnitude (horizontal and vertical together) at the depth of +the line's shallowest node outside the grid, over its value at the still-water level. It is summed +over SeaState's own first-order components (their amplitudes from ``WaveElevC0``, frequencies +:math:`\omega_i = i\,\Delta\omega` with :math:`\Delta\omega` = ``WaveDOmega``) with the +finite-depth Airy transfer in ``EffWtrDpth``, +:math:`|\mathbf u_i|^2 \propto \omega_i^2 |A_i|^2 (D_{1,i}^2 + D_{2,i}^2)`, +:math:`D_1 = \cosh k(z+h)/\sinh kh`, :math:`D_2 = \sinh k(z+h)/\sinh kh`, which per component tends +to :math:`e^{kz}` in deep water; the depth is the node's own, without stretching, and the ratio is +1 at or above the still-water level. It only grows toward the surface, so the shallowest outside +node gives the largest value over the line's outside nodes and over the run. A value of 0.01 means +the nodes outside the grid see at most a hundredth of the surface wave velocity, so the boundary +kinematics SeaState gave them matter little; a value near 1 means the line left the grid near the +surface. It is ``null`` without wave components (still water, and ``WaveMod = 6``, whose kinematics +SeaState reads from files). The wave-grid guard's message gives the ratio at the shallowest node it reports, per line. + Reading and post-processing --------------------------- diff --git a/doc/theory.rst b/doc/theory.rst index 8cb0dda2..40591904 100644 --- a/doc/theory.rst +++ b/doc/theory.rst @@ -2079,6 +2079,90 @@ The optional ``rampTime`` :math:`T_r` multiplies every wave amplitude by acceleration then includes the ramp rate, :math:`r\,\dot{\mathbf u} + \dot r\,\mathbf u`. The current is not ramped, because the static initial condition already includes it. +.. _theory-nodewise-waves: + +SeaState waves at the nodes (OpenFAST) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +In OpenFAST, SeaState computes its first-order waves on a grid by an inverse real FFT of its +wave components and interpolates the grid at the points it is asked for. With ``WaterKin +SEASTATE_SPECTRAL`` CableDyn instead sums the same components at the line nodes. With +:math:`N` = ``NStepWave``, :math:`C_i` SeaState's complex amplitudes (``WaveElevC0``), +:math:`\beta_i` their directions (``WaveDirArr``), :math:`\omega_i = 2\pi i/(N\,\Delta t_w)` +for the wave step :math:`\Delta t_w`, :math:`k_i` SeaState's own wavenumbers in the depth +:math:`h` = ``EffWtrDpth``, and +:math:`\theta_i = \omega_i t - k_i (x\cos\beta_i + y\sin\beta_i)`, + +.. math:: + + \eta = \frac{\operatorname{Re} C_0}{N} + \sum_i \operatorname{Re}\!\left(A_i e^{j\theta_i}\right), + \qquad + (u, v) = \sum_i (\cos\beta_i, \sin\beta_i)\,\omega_i\, + \frac{\cosh k_i(z+h)}{\sinh k_i h}\operatorname{Re}\!\left(A_i e^{j\theta_i}\right), + + w = -\sum_i \omega_i\,\frac{\sinh k_i(z+h)}{\sinh k_i h}\operatorname{Im}\!\left(A_i e^{j\theta_i}\right), + \qquad + p_d = \rho g \left[\frac{\operatorname{Re} C_0}{N} + \sum_i + \frac{\cosh k_i(z+h)}{\cosh k_i h}\operatorname{Re}\!\left(A_i e^{j\theta_i}\right)\right], + +with :math:`A_i = 2C_i/N` (:math:`C_i/N` at the Nyquist frequency) and the accelerations the +time derivatives (a factor :math:`j\omega_i`). These are the sums the inverse FFT evaluates at +the grid points and wave steps, so at a grid vertex and a wave step the two routes agree to the +round-off of SeaState's single-precision FFT. The hyperbolic ratios are evaluated as +:math:`(e^{kz} \pm e^{-k(z+2h)})/(1 \mp e^{-2kh})`, which does not overflow in deep water. + +**Stretching** follows SeaState's sampler: without stretching (``WaveStMod = 0``) a node above +the still-water level has no kinematics; vertical stretching (1) takes the surface value above it; +extrapolation (2) adds :math:`z\,\partial/\partial z` at the surface, the derivatives SeaState +stores as ``PWave*0``; Wheeler stretching (3) evaluates at :math:`z' = h(h+z)/(h+\eta) - h` (at +most 0). A node below the seabed takes the seabed values. + +**Time.** A node evaluates the field once per wave step, at the two wave steps +:math:`t_n, t_{n+1}` that bracket the sample time, with the exact time derivatives (under Wheeler +stretching including the motion of :math:`z'` with :math:`\eta`), at its position advanced by +its velocity to the middle of the step. Within the step each quantity is the cubic Hermite +polynomial through the two values and derivatives, whose error on a component is at most +:math:`(\omega\Delta t_w)^4/384` of its amplitude. The position phase costs one sine and cosine +per node, component and wave step, the depth one or two exponentials; the time phases are shared +by all nodes. + +**Truncation.** The components are sorted by wavenumber. A node keeps the shortest prefix whose +dropped velocity variance, :math:`\sum \tfrac12\omega_i^2|A_i|^2 D_i(z)^2` over the dropped +components with :math:`D = \cosh k(z+h)/\sinh kh`, is at most ``waveKinTol`` times the velocity +variance of all components at the node's depth, and whose dropped acceleration variance (weight +:math:`\omega_i^4`) is at most ``waveKinTol`` times its own total there. Both bounds are relative +to the sea at that depth, not at the surface: a deep node sees only the long waves, and a bound +relative to the surface would let it drop a large part of what it sees. The prefix is tabulated +on 1024 depth levels. A dropped component has a larger wavenumber than every kept one and decays +faster with depth (:math:`\cosh k_j(z+h)/\cosh k_i(z+h)` falls with depth for :math:`k_j > k_i`), +so the dropped share of a prefix only falls with depth; a node takes the prefix of the level at +or above the shallowest depth it can reach within the step (under Wheeler stretching, under the +lowest elevation the sea can reach), and both bounds hold at every depth it reaches. + +Under Wheeler stretching the elevation sets the depth :math:`z'` at which the kept components are +evaluated, and a short wave too short to reach a node still moves the surface above it. The +elevation is therefore summed over its own prefix, at least the kept one. An elevation error +:math:`\delta\eta` moves :math:`z'` by :math:`(h+z')/(h+\eta)\,\delta\eta` and the kept velocity +by its vertical gradient times that. The elevation prefix is the shortest one for which the +variance of that velocity error, :math:`\sum_\text{kept} \tfrac12 k_i^2(D_{1,i}^2 + D_{2,i}^2) +\omega_i^2|A_i|^2 \cdot \bigl((h+z')/(h+\eta_\text{min})\bigr)^2 \cdot \sum_\text{dropped} +\tfrac12|A_j|^2`, is at most ``waveKinTol`` times the velocity variance at :math:`z'`, and the +same for the acceleration (weight :math:`\omega_i^4`, with the dropped elevation rate through the +moving depth). Both factors fall with depth, so the prefix of a node's shallowest mapped depth +serves every depth it reaches. A node at :math:`-30` m in 200 m of water under unit waves of 0.3 +and 3 rad/s drops the short wave from its kinematics but keeps it in its elevation; its velocity at +the crest then equals the full sum, where the kept wave's elevation alone put it 0.75 % off. +Without Wheeler stretching the elevation only decides the wetting, of nodes near the surface that +keep nearly every component, and takes the kept prefix. + +**Grid interpolation, for comparison.** SeaState interpolates its grid with Catmull-Rom cubics +in time (periodic) and in space, quadratically at the edges of the grid and between the three +points of an axis with ``NX`` or ``NY`` = 2. Midway between grid points spaced :math:`\Delta` +along the direction of a component of wavelength :math:`\lambda`, the cubic keeps +:math:`\tfrac98\cos(\varphi/2) - \tfrac18\cos(3\varphi/2)` of its amplitude, +:math:`\varphi = 2\pi\Delta/\lambda`: it loses 5.1 % at :math:`\Delta = \lambda/5`, 0.35 % at +:math:`\lambda/10` and 0.02 % at :math:`\lambda/20`. + Currents ~~~~~~~~ diff --git a/doc/tutorial_openfast.rst b/doc/tutorial_openfast.rst index c3c2b71d..9d26ff24 100644 --- a/doc/tutorial_openfast.rst +++ b/doc/tutorial_openfast.rst @@ -125,6 +125,12 @@ initialisation: 147 of its 153 line nodes lie outside the SeaState wave-kinemati line-1 fairlead tension standard deviation comes out 18 % too high. Grid sizing is described in :ref:`openfast:SeaState grid`. +Alternatively, keep the platform grid and change the deck's ``0 WaterKin`` row to +``SEASTATE_SPECTRAL WaterKin``: the lines then take SeaState's wave components at their nodes and +need no grid (:ref:`openfast:Wave kinematics at the nodes (SEASTATE_SPECTRAL)`); the hull's +Morison members still read the 100 m grid. ``integration/openfast/cabledyn_preflight.py`` checks +the ``.fst`` and reports the memory of either choice before the run. + 4. How CableDyn is wired in --------------------------- diff --git a/examples/cabledyn_options_reference.dat b/examples/cabledyn_options_reference.dat index 17d14a0a..106010ba 100644 --- a/examples/cabledyn_options_reference.dat +++ b/examples/cabledyn_options_reference.dat @@ -90,6 +90,8 @@ none waves - Wave model and parameters (m, s, deg) {none; airy; -- 0 nModes - Modal analysis: lowest natural modes per line {0=off; 1 to 1000} [default: 0] -- "WaterKin.dat" WaterKin - MoorDyn-F WaterKin file (standalone file modes or coupled host selectors) -- SEASTATE WaterKin - Full host SeaState field (OpenFAST aggregate only) +-- SEASTATE_SPECTRAL WaterKin - Host SeaState wave components evaluated at the nodes (OpenFAST only) +-- 1e-6 waveKinTol - SEASTATE_SPECTRAL: dropped share of the velocity and acceleration variance at each node's depth {0 to <1} [default: 1e-6] -- RK2 tScheme - MoorDyn compatibility only; accepted and ignored by CableDyn -- 0.001 dtIC - MoorDyn dynamic-relaxation compatibility only; accepted and ignored -- 60.0 TmaxIC - MoorDyn dynamic-relaxation compatibility only; accepted and ignored diff --git a/examples/openfast/CableDyn_UMaine.dat b/examples/openfast/CableDyn_UMaine.dat index 8287b830..cb8d63d8 100644 --- a/examples/openfast/CableDyn_UMaine.dat +++ b/examples/openfast/CableDyn_UMaine.dat @@ -47,7 +47,7 @@ dynamic_solver 1.0e-8 1.0e-14 30 12 - Relative tolerance, absolute tolerance, ma 0.025 dtM - CableDyn internal time step (s); set equal to the example glue DT [default: the glue DT] none current - Current model and velocity (m/s) {none; uniform; profile} [default: SeaState host field] none waves - Wave model, height, period, and direction (m, s, deg) {none; airy; jonswap} [default: SeaState host field] -0 WaterKin - Water-kinematics source {0/none; file; SEASTATE coupled only} [default: no policy/full host field] +0 WaterKin - Water-kinematics source {0/none; file; SEASTATE(_GRID) or SEASTATE_SPECTRAL coupled only} [default: no policy/full host field] -- Complete option/default reference: ../cabledyn_options_reference.dat and doc/options.rst. --------------------------- OUTPUTS ------------------------------------------- "FairTen1" diff --git a/examples/openfast/README.md b/examples/openfast/README.md index 1590671a..3ce6eee1 100644 --- a/examples/openfast/README.md +++ b/examples/openfast/README.md @@ -64,6 +64,11 @@ $ss = 'SeaState.dat' SeaState then needs about 4.6 GB of memory. The values in this file are for the enlarged grid. Grid sizing is described in the manual's OpenFAST page (SeaState grid). +Alternatively, keep the platform grid and change the deck's `0 WaterKin` row to +`SEASTATE_SPECTRAL WaterKin`: the lines then take SeaState's wave components at their nodes and +need no grid; the hull's Morison members still read the 100 m grid. `integration/openfast/cabledyn_preflight.py` +checks the `.fst` and reports the memory of either choice before the run. + ## Run ```powershell diff --git a/integration/openfast/cabledyn_logscan.py b/integration/openfast/cabledyn_logscan.py new file mode 100644 index 00000000..69c6ac75 --- /dev/null +++ b/integration/openfast/cabledyn_logscan.py @@ -0,0 +1,224 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Scan OpenFAST logs of coupled CableDyn runs for the wave route and the wave-grid guard. + +For every log (files, or folders searched for *.log; standard library only) it reports the wave +route the run took (SeaState grid or WaterKin SEASTATE_SPECTRAL), whether the run ended normally or +stopped, and, per line, the guard's findings: nodes outside the SeaState grid (count, time, deepest +and shallowest node) and the NX or NY = 2 resolution stop or warning. The provenance record of the +same run is read too and preferred for the per-line findings (under waveGridCheck warn the log shows +only the first warning, the record the whole run): .CD.provenance.json (or .FarmCD.) for a +log named after the run's root, else the only record in the log's folder unless another log there +is named after its root. + +usage: cabledyn_logscan.py ... [--csv out.csv] +exit code: 0 when no run has a guard finding, 1 when one has, 2 when no log could be read (a missing +or unreadable path is reported and skipped). +""" + +from __future__ import annotations + +import argparse +import csv +import json +import re +import sys +from pathlib import Path + +OUTSIDE = re.compile( + r"CableDyn mooring module: (\d+) of the (\d+) CableDyn sampling nodes in the water lie outside the " + r"SeaState wave-kinematics grid at t = ([0-9.Ee+-]+) s" +) +RESOLUTION = re.compile(r"the SeaState wave-kinematics grid has (N[XY] = 2 .*?) under (.*?), which vary") +BY_LINE = re.compile( + r"line (\d+), (\d+) nodes?, (?:deepest at|at) \(x, y, z\) = \(([^)]*)\) m" + r"(?:, shallowest at \(x, y, z\) = \(([^)]*)\) m)?" +) +SECTION_END = re.compile(r"(?: Farthest:| A grid with| In the SeaState| To run on| \(OPTIONS)") + + +def flat(text: str) -> str: + """The log as one line: OpenFAST wraps its messages at about 100 columns.""" + return " ".join(text.split()) + + +def scan(path: Path) -> dict[str, object]: + text = flat(path.read_text(encoding="utf-8", errors="replace")) + run: dict[str, object] = {"log": str(path), "lines": {}} + if "SEASTATE_SPECTRAL, waveKinTol" in text: + run["route"] = "seastate_spectral" + elif "interpolated on the SeaState grid" in text: + run["route"] = "seastate_grid" + else: + run["route"] = "unknown" + # OpenFAST and FAST.Farm end their logs alike + ended = re.search(r"(?:OpenFAST|FAST\.Farm) terminated normally|Aborting (?:OpenFAST|FAST\.Farm)", text) + if ended is None: + run["ended"] = "unknown" + else: + run["ended"] = "stopped" if ended.group(0).startswith("Aborting") else "normally" + lines: dict[int, dict[str, object]] = {} + for kind, pattern in (("outside", OUTSIDE), ("resolution", RESOLUTION)): + for match in pattern.finditer(text): + tail = text[match.end():] + cut = SECTION_END.search(tail) + section = tail[: cut.start()] if cut else tail[:4000] + if kind == "outside": + run.setdefault("first_outside_time", float(match.group(3))) + else: + run["resolution"] = f"{match.group(1)} under {match.group(2)}" + for entry in BY_LINE.finditer(section): + line = lines.setdefault(int(entry.group(1)), {}) + if kind == "outside": + line.setdefault("outside_first_time", float(match.group(3))) + line["outside_nodes"] = max(int(entry.group(2)), int(line.get("outside_nodes", 0))) + line.setdefault("deepest", entry.group(3)) + line.setdefault("shallowest", entry.group(4) or entry.group(3)) + else: + line["resolution"] = "grid_coarse_across_waves" + # the provenance record of this run, when it left one beside its log + record_path = record_for(path) + record = None + if record_path is not None: + try: + record = json.loads(record_path.read_text(encoding="utf-8")) + except (OSError, ValueError): + record = None + if isinstance(record, dict): + run["record"] = str(record_path) + run["record_status"] = record.get("status") + waves = record.get("waves") or {} + if run["route"] == "unknown" and waves.get("route"): + # a restarted run does not repeat the route line of its initialisation + run["route"] = waves["route"] + entries = record.get("lines") + for entry in entries if isinstance(entries, list) else []: + if not isinstance(entry, dict): + continue + try: + lid = int(entry["id"]) + except (KeyError, TypeError, ValueError): + continue # a line entry without a usable id + line = lines.setdefault(lid, {}) + oog = entry.get("out_of_grid") + if isinstance(oog, dict): + line["outside_nodes"] = oog.get("n_nodes_max") + line["outside_first_time"] = oog.get("first_time") + line["deepest"] = xyz_text(oog.get("deepest_xyz")) + line["shallowest"] = xyz_text(oog.get("shallowest_xyz")) + if isinstance(oog.get("weighted_velocity_ratio_max"), (int, float)): + line["velocity_ratio"] = oog["weighted_velocity_ratio_max"] + flags = entry.get("resolution_flags") + if isinstance(flags, list) and flags: + line["resolution"] = ",".join(str(f) for f in flags) + if all(isinstance(entry.get(k), (int, float)) for k in ( + "dropped_velocity_variance_max", "dropped_acceleration_variance_max")): + line["dropped_vel_var"] = entry["dropped_velocity_variance_max"] + line["dropped_acc_var"] = entry["dropped_acceleration_variance_max"] + run["lines"] = lines + return run + + +def xyz_text(values: object) -> str: + """A position of the record as text (a null coordinate, a non-finite one, as null).""" + if not isinstance(values, list): + return "" + return ", ".join(f"{v:g}" if isinstance(v, (int, float)) else "null" for v in values) + + +RECORD_SUFFIXES = (".CD.provenance.json", ".FarmCD.provenance.json") + + +def record_for(log: Path) -> Path | None: + """The provenance record of the run a log belongs to: .CD.provenance.json (or + .FarmCD.) when the log is named after the run's root; else the only record in the folder, + unless another log there is named after its root (that record is that log's). None when + neither holds: a log of another run never takes a record.""" + for suffix in RECORD_SUFFIXES: + named = log.with_name(log.stem + suffix) + if named.is_file(): + return named + records = [p for suffix in RECORD_SUFFIXES for p in sorted(log.parent.glob("*" + suffix))] + if len(records) != 1: + return None + root = records[0].name + for suffix in RECORD_SUFFIXES: + if root.endswith(suffix): + root = root[: -len(suffix)] + if any(other.stem == root for other in log.parent.glob("*.log")): + return None + return records[0] + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("paths", nargs="+", type=Path) + parser.add_argument("--csv", type=Path) + args = parser.parse_args(argv) + logs: list[Path] = [] + for p in args.paths: + if p.is_dir(): + logs.extend(sorted(p.rglob("*.log"))) + elif p.is_file(): + logs.append(p) + else: + print(f"{p}: no such log or folder") + runs = [] + for log in logs: + try: + runs.append(scan(log)) + except OSError as error: + print(f"{log}: cannot be read ({error})") + if not runs: + # exit 1 means a guard finding; nothing read is an input error + print("no log could be read") + return 2 + flagged = 0 + rows = [] + for run in runs: + lines = run["lines"] + assert isinstance(lines, dict) + # a run-level finding counts on its own: the guard also names rods, bodies and points + # outside the grid, which are not deck lines + run_level = "first_outside_time" in run or "resolution" in run + bad = run_level or any("outside_nodes" in v or "resolution" in v for v in lines.values()) + flagged += bad + print(f"{run['log']}: route {run['route']}, ended {run['ended']}" + + (f", record {run.get('record_status')}" if "record" in run else "") + + (": guard findings" if bad else ": no guard finding")) + if "first_outside_time" in run: + print(f" run: nodes outside the grid from t = {run['first_outside_time']} s") + if "resolution" in run: + print(f" run: {run['resolution']}") + if run_level: + rows.append({"log": run["log"], "route": run["route"], "ended": run["ended"], "line": "", + "outside_first_time": run.get("first_outside_time"), + "resolution": run.get("resolution")}) + for lid in sorted(lines): + v = lines[lid] + parts = [] + if "outside_nodes" in v: + parts.append(f"{v['outside_nodes']} nodes outside the grid from t = {v['outside_first_time']} s, " + f"deepest ({v['deepest']}), shallowest ({v['shallowest']})" + + (f", weighted velocity ratio {v['velocity_ratio']:.3g}" if "velocity_ratio" in v else "")) + if "resolution" in v: + parts.append(str(v["resolution"])) + if "dropped_acc_var" in v: + parts.append(f"drops at most {v['dropped_vel_var']:.2e} / {v['dropped_acc_var']:.2e} of the " + "velocity / acceleration variance") + if parts: + print(f" line {lid}: " + "; ".join(parts)) + rows.append({"log": run["log"], "route": run["route"], "ended": run["ended"], "line": lid, **v}) + if args.csv: + keys = ["log", "route", "ended", "line", "outside_nodes", "outside_first_time", "deepest", "shallowest", + "velocity_ratio", "resolution", "dropped_vel_var", "dropped_acc_var"] + with args.csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=keys, extrasaction="ignore") + writer.writeheader() + writer.writerows(rows) + return 1 if flagged else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/integration/openfast/cabledyn_preflight.py b/integration/openfast/cabledyn_preflight.py new file mode 100644 index 00000000..c557526d --- /dev/null +++ b/integration/openfast/cabledyn_preflight.py @@ -0,0 +1,781 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Pre-flight check of a coupled CableDyn case (CompMooring = 5) before it runs. + +Reads the OpenFAST .fst, its SeaState and HydroDyn files and the CableDyn deck (standard library +only), and reports, per line and for the hull: + +* coverage: whether the line end points, and the hull's Morison joints, lie inside the SeaState + grid in x, y and depth (with a margin for the platform motion, --margin); +* resolution: NX or NY = 2 under waves that vary along that axis (the wave-grid guard stops such a + run), and the grid spacing against the shortest wavelength that matters and the peak wavelength, + with the amplitude SeaState's Catmull-Rom interpolation keeps midway between grid points, + 9/8 cos(phi/2) - 1/8 cos(3 phi/2), phi = 2 pi spacing/wavelength (nothing from half a + wavelength on, where the grid aliases the wave); the JONSWAP peak shape DEFAULT is SeaState's; +* memory: the arrays SeaState stores for its grid and the start-up peak (stored memory times the + measured peak ratio, --peak-ratio); +* the wave route: the deck's WaterKin, and whether WaterKin SEASTATE_SPECTRAL can take the case + (what it refuses: second-order kinematics, WaveMod 6, WvCrntMod 1 or 2, CurrMod 2); +* a hull-only grid for the spectral route: half-widths over the hull joints plus the margin, a + spacing of a tenth of the shortest wavelength, and its memory. + +The files are read as CableDyn and OpenFAST read them (OpenFAST's GetWords and ChkParseData, +CableDyn's deck sections, option aliases and WaterKin file, SeaState's rules for spreading and +WvCrntMod); what the lines take from SeaState follows the deck's WaterKin, what the hull takes +follows SeaState. The line positions are the end points of each line (its points in the deck; +Coupled points at the platform's reference pose, Body points at their body's; an end above the +still-water level is left out), so a line's sag between them is judged by its deepest end and +the seabed. Run CableDyn for the exact check: the guard tests every node at every step. + +usage: cabledyn_preflight.py [--margin M] [--peak-ratio R] [--json out.json] +exit code: 0 when nothing stops the run, 1 when CableDyn would stop it (the wave-grid guard, or an +initialisation check), 2 on unreadable input or a case that is not a CableDyn one. +""" + +from __future__ import annotations + +import argparse +import json +import math +import sys +from dataclasses import dataclass, field +from pathlib import Path + +G = 9.80665 +# start-up peak of SeaState over its stored grid arrays: the slope of the peak working set against +# the stored arrays of four grids of 21 to 270 MB (2.95, gfortran build of OpenFAST 2895884; see +# doc/openfast.rst), rounded up +PEAK_RATIO = 3.0 +BYTES = 4 # SeaState stores its grid in single precision + + +class CaseError(ValueError): + """An input file of the case that the check cannot read (named in the message).""" + + +def get_words(line: str, ignore_quotes: bool = False) -> list[str]: + """The words of a line as OpenFAST's GetWords splits them: on spaces, tabs, commas and + semicolons; quotes group a word with spaces unless ignore_quotes (then they separate).""" + words: list[str] = [] + word = "" + quoted = False + for ch in line: + if ch in "\"'": + if ignore_quotes or quoted: + quoted = False + if word: + words.append(word) + word = "" + else: + quoted = True + continue + if ch in ",; \t" and not quoted: + if word: + words.append(word) + word = "" + continue + word += ch + if word: + words.append(word) + return words + + +def value_key(line: str) -> tuple[str, str] | None: + """The value and the key of a `value key - comment` row (the first two words, a quoted value + whole); None for a comment or a row with fewer than two words.""" + text = line.strip() + if not text or text.startswith(("!", "#")): + return None + words = get_words(text) + if len(words) < 2 or set(words[0]) == {"-"}: + return None # a separator line (a signed number such as -30 is a value) + return words[0], words[1] + + +class Values(dict): + """An OpenFAST input file's values by name, the names compared without case.""" + + def get(self, key: str, default=None): # type: ignore[override] + return super().get(key.lower(), default) + + def __getitem__(self, key: str) -> str: + return super().__getitem__(key.lower()) + + def __contains__(self, key: object) -> bool: + return isinstance(key, str) and super().__contains__(key.lower()) + + +def values(path: Path) -> Values: + """The values of an OpenFAST input file by name. OpenFAST reads each row's first two words + (GetWords: separated by spaces, tabs, commas or semicolons) and takes the variable name from + either of them, without regard to case (ChkParseData): "45 WaveDir", "WaveDir 45" and + "45, wavedir" all set WaveDir. The first row that names a variable gives its value.""" + out = Values() + for line in path.read_text(encoding="latin-1").splitlines(): + row = value_key(line) + if not row: + continue + first, second = row + out.setdefault(second.lower(), first) + if math.isnan(number(first, math.nan)) and first.lower() not in out: + # "WaveDir 45": the name first (a word that is not a number) + super(Values, out).__setitem__(first.lower(), second) + return out + + +def flag(raw: str | None) -> bool: + """A Fortran logical as OpenFAST reads it (list-directed): T, .T., TRUE, .TRUE. and the + like are true, F, .F., FALSE, .FALSE. false, without regard to case.""" + text = (raw or "").strip().strip("\"'").lstrip(".") + return text[:1].upper() == "T" + + +def setting(ss: Values, key: str, glue: Values, default: float) -> float: + """A SeaState number that may read "default" (the glue code's value, from the .fst).""" + raw = ss.get(key) + if raw is None or raw.strip("\"'").upper() == "DEFAULT": + return number(glue.get(key), default) + return number(raw, default) + + +def psf(n: int) -> int: + """The smallest number at least n whose prime factors are all among the first nine primes + (SeaState's PSF, which sizes its FFT).""" + m = max(n, 1) + while True: + r = m + for prime in (2, 3, 5, 7, 11, 13, 17, 19, 23): + while r % prime == 0: + r //= prime + if r == 1: + return m + m += 1 + + +def wave_steps(tmax: float, dt: float) -> int: + """SeaState's NStepWave: WaveTMax/WaveDT rounded up to an even number, then up to twice a + product of small factors.""" + if dt <= 0.0: + return 0 + n = math.ceil(tmax / dt) + n += n % 2 + return 2 * psf(max(n // 2, 1)) + + +def number(raw: str | None, default: float) -> float: + """A number as Fortran reads it (a D exponent too), or default.""" + if raw is None: + return default + try: + return float(raw.strip("\"'").replace("D", "E").replace("d", "e")) + except ValueError: + return default + + +@dataclass +class Deck: + points: dict[int, tuple[str, float, float, float]] = field(default_factory=dict) + lines: dict[int, tuple[int, int]] = field(default_factory=dict) + options: dict[str, str] = field(default_factory=dict) + # BODIES rows: id -> (attachment, x, y, z, roll, pitch, yaw) + bodies: dict[int, tuple[str, float, float, float, float, float, float]] = field(default_factory=dict) + + +# the section names of CableDyn's deck reader (CableDyn_DeckDriver set_section) +SECTIONS = { + "LINE TYPES": "TYPES", "LINETYPES": "TYPES", "LINE DICTIONARY": "TYPES", + "BODIES": "BODIES", "BODY": "BODIES", + "POINTS": "POINTS", "CONNECTION PROPERTIES": "POINTS", "POINT PROPERTIES": "POINTS", "CONNECTS": "POINTS", + "LINES": "LINES", "LINE PROPERTIES": "LINES", + "OPTIONS": "OPTIONS", "SOLVER OPTIONS": "OPTIONS", +} +# deck options CableDyn reads under one name (apply_option); the last row of either wins +OPTION_ALIASES = {"wavekin": "waterkin", "wave_grid_check": "wavegridcheck", "wave_kin_tol": "wavekintol", + "water_depth": "wtrdpth"} + + +def strip_comment(raw: str) -> str: + """A deck row without its comment, as CableDyn's reader strips it (scan_comment): from the + first # or !, or from a -- that starts a word on a row without a --- rule.""" + cut = len(raw) + for mark in ("#", "!"): + at = raw.find(mark) + if at >= 0: + cut = min(cut, at) + if "---" not in raw: + at = raw.find("--") + while at >= 0: + if at == 0 or raw[at - 1] in " \t": + cut = min(cut, at) + break + at = raw.find("--", at + 2) + return raw[:cut].strip() + + +def section_name(line: str) -> str | None: + """The section a header row opens (CableDyn's is_section_header and set_section): any row + holding --- is a header; its name is the row without dashes, upper case, spaces collapsed. + A blank name, END, a NEED... marker or an INPUT FILE banner closes the section (""); a + section the check does not read is named by itself.""" + if "---" not in line: + return None + name = " ".join(line.replace("-", " ").upper().split()) + if not name or name == "END" or "NEED" in name or "INPUT FILE" in name: + return "" + return SECTIONS.get(name, name) + + +def read_deck(path: Path) -> Deck: + """BODIES, POINTS, LINES and OPTIONS of a CableDyn deck (the rows the check needs).""" + deck = Deck() + section = "" + for raw in path.read_text(encoding="utf-8", errors="replace").splitlines(): + line = strip_comment(raw) + if not line: + continue + name = section_name(line) + if name is not None: + section = name + continue + parts = line.split() + if section == "POINTS" and parts[0].isdigit() and len(parts) >= 5: + try: + deck.points[int(parts[0])] = (parts[1], float(parts[2]), float(parts[3]), float(parts[4])) + except ValueError: + continue + elif section == "BODIES" and parts[0].isdigit() and len(parts) >= 8: + try: + deck.bodies[int(parts[0])] = (parts[1], *(float(v) for v in parts[2:8])) # type: ignore[assignment] + except ValueError: + continue + elif section == "LINES" and parts[0].isdigit() and len(parts) in (3, 4, 7): + # the row forms CableDyn reads: ID NodeA NodeB [Outputs], or stock MoorDyn's + # ID LineType AttachA AttachB UnstrLen NumSegs Outputs; a rod end (R1A) attaches + # to no point and is left out of the coverage check (0) + a, b = (parts[2], parts[3]) if len(parts) == 7 else (parts[1], parts[2]) + deck.lines[int(parts[0])] = (int(a) if a.isdigit() else 0, int(b) if b.isdigit() else 0) + elif section == "OPTIONS" and len(parts) >= 2: + row = value_key(line) + if row: + key = row[1].lower() + deck.options[OPTION_ALIASES.get(key, key)] = row[0] + return deck + + +def hull_joints(path: Path) -> list[tuple[float, float, float]]: + """The Morison member joints of a HydroDyn input file (the table after NJoints).""" + rows = path.read_text(encoding="latin-1").splitlines() + for i, row in enumerate(rows): + parts = row.split() + if len(parts) >= 2 and parts[1] == "NJoints": + try: + n = int(float(parts[0])) + joints = [] + for data in rows[i + 3 : i + 3 + n]: + cols = data.split() + joints.append((float(cols[1]), float(cols[2]), float(cols[3]))) + except (ValueError, IndexError) as error: + raise CaseError(f"{path}: the joint table after NJoints (line {i + 1}) is malformed: " + f"{error}") from error + if len(joints) != n: + raise CaseError(f"{path}: NJoints = {n} but the joint table has {len(joints)} rows") + return joints + return [] + + +def wavenumber(omega: float, depth: float) -> float: + k = omega * omega / G + for _ in range(60): + th = math.tanh(k * depth) + k -= (G * k * th - omega * omega) / (G * th + G * k * depth * (1.0 - th * th)) + return k + + +def jonswap(omega: float, hs: float, tp: float, gamma: float) -> float: + wp = 2.0 * math.pi / tp + sigma = 0.07 if omega <= wp else 0.09 + shape = math.exp(-0.5 * ((omega - wp) / (sigma * wp)) ** 2) + return (5.0 / 16.0) * hs * hs * wp**4 / omega**5 * math.exp(-1.25 * (wp / omega) ** 4) * gamma**shape + + +def peak_shape(ss: dict[str, str], hs: float, tp: float) -> float: + """WavePkShp, or for DEFAULT SeaState's (IEC 61400-3) value from Tp / sqrt(Hs).""" + raw = ss.get("WavePkShp", "DEFAULT") + if raw.strip('"').upper() != "DEFAULT": + return number(raw, 3.3) + ratio = tp / math.sqrt(hs) if hs > 0.0 else 5.0 + if ratio <= 3.6: + return 5.0 + if ratio >= 5.0: + return 1.0 + return math.exp(5.75 - 1.15 * ratio) + + +def wave_mod(ss: Values) -> int: + """SeaState's WaveMod as a number (a regular wave with a phase, 1P#, is 1).""" + digits = "" + for ch in (ss.get("WaveMod") or "0").strip("\"'"): + if not ch.isdigit(): + break + digits += ch + return int(digits) if digits else 0 + + +def peak_wavelength(ss: Values, depth: float) -> float | None: + """The wavelength at the peak period WaveTp (a regular wave, WaveMod 1, or a JONSWAP or + Pierson-Moskowitz spectrum, WaveMod 2), else None.""" + tp = number(ss.get("WaveTp"), 0.0) + if tp <= 0.0 or wave_mod(ss) not in (1, 2): + return None + return 2.0 * math.pi / wavenumber(2.0 * math.pi / tp, depth) + + +def shortest_wavelength(ss: Values, depth: float, z: float, + components: list[tuple[float, float, float]] | None = None) -> float | None: + """The shortest wavelength that matters at depth z: the highest frequency (from WvLowCOff to + WvHiCOff, the band SeaState keeps of a spectrum or of user components) whose spectral density + there, S(omega) exp(2 k z), is at least 1 % of the peak density in that band. A regular wave + (WaveMod 1) is its own; white noise (3) reaches WvHiCOff; user components (7, `components` as + omega, amplitude, direction) are judged from their amplitudes. None where the spectrum is not + known here (WaveMod 0, 4, 5, 6) or the band keeps nothing.""" + mod = wave_mod(ss) + lo = number(ss.get("WvLowCOff"), 0.0) + hi = number(ss.get("WvHiCOff"), 2.0 * math.pi) + tp = number(ss.get("WaveTp"), 0.0) + if mod == 1: + return 2.0 * math.pi / wavenumber(2.0 * math.pi / tp, depth) if tp > 0.0 else None + if mod == 3: + return 2.0 * math.pi / wavenumber(hi, depth) if hi > 0.0 else None + if mod == 7: + if not components: + return None + dens = [(w, a * a * math.exp(2.0 * wavenumber(w, depth) * min(z, 0.0))) + for w, a, _ in components if w > 0.0 and lo <= w <= hi] + peak = max((d for _, d in dens), default=0.0) + if peak <= 0.0: + return None + return 2.0 * math.pi / wavenumber(max(w for w, d in dens if d >= 0.01 * peak), depth) + if mod != 2: + return None + hs = number(ss.get("WaveHs"), 0.0) + if hs <= 0.0 or tp <= 0.0: + return None + gamma = peak_shape(ss, hs, tp) + omegas = [0.05 + 0.005 * i for i in range(2000) if lo <= 0.05 + 0.005 * i <= hi] + dens = [jonswap(w, hs, tp, gamma) * math.exp(2.0 * wavenumber(w, depth) * min(z, 0.0)) for w in omegas] + peak = max(dens) if dens else 0.0 + if peak <= 0.0: + return None + top = max(w for w, d in zip(omegas, dens) if d >= 0.01 * peak) + return 2.0 * math.pi / wavenumber(top, depth) + + +def multi_directional(ss: Values) -> bool: + """SeaState's WaveMultiDir (SeaState_Input): spreading (WaveDirMod 1) only for WaveMod 2, 3 + or 4, a nonzero WaveDirRange and more than one direction (WaveNDir, an even count raised to + the next odd one).""" + if int(number(ss.get("WaveDirMod"), 0)) != 1 or wave_mod(ss) not in (2, 3, 4): + return False + if number(ss.get("WaveDirRange"), 0.0) == 0.0: + return False + ndir = int(number(ss.get("WaveNDir"), 1)) + return ndir + (1 - ndir % 2) > 1 + + +def user_components(path: Path) -> list[tuple[float, float, float]]: + """The wave components of a WaveMod 7 file (SeaState WaveComp_ReadFile) as (omega rad/s, + amplitude m, direction deg): OpenFAST format omega, height, direction (deg), phase (deg); a + file whose first line starts "source: SEAFileGenerator.exe" holds frequency (Hz), + amplitude, direction (rad), phase (rad). Rows that are not four numbers are header rows.""" + rows = path.read_text(encoding="latin-1").splitlines() + sea = bool(rows) and rows[0].startswith("source: SEAFileGenerator.exe") + out = [] + for row in rows: + cols = get_words(row, ignore_quotes=True) + nums = [number(c, math.nan) for c in cols[:4]] + if len(cols) < 4 or any(math.isnan(v) for v in nums): + continue + if sea: + out.append((2.0 * math.pi * nums[0], nums[1], math.degrees(nums[2]))) + else: + out.append((nums[0], 0.5 * nums[1], nums[2])) + return out + + +EXTERNAL_LIMIT = 256 * 2**20 # bytes of WaveMod 6 data the check reads at most +FIELD_RTOL = 1.0e-5 # CableDyn's CD_WAVEGRID_FIELD_RTOL + + +def external_varies(root: Path, nx: int, ny: int) -> tuple[bool, bool] | None: + """Whether the WaveMod 6 kinematics (.Vxi ... .Azi, SeaState UserWaves_Init: 13 header + lines, then per time step, depth level and y one row of the x values) differ along x and + along y, as CableDyn judges them (CD_WaveGrid_Field_Varies: by more than 1e-5 of the + largest magnitude of the velocities, or of the accelerations). None when the files are + missing or too large to read here.""" + groups = ((".Vxi", ".Vyi", ".Vzi"), (".Axi", ".Ayi", ".Azi")) + paths = [root.with_name(root.name + ext) for group in groups for ext in group] + if not all(p.is_file() for p in paths) or sum(p.stat().st_size for p in paths) > EXTERNAL_LIMIT: + return None + npy, npx = 2 * ny - 1, 2 * nx - 1 + varies = [False, False] + for group in groups: + data = [] + for ext in group: + rows = root.with_name(root.name + ext).read_text(encoding="latin-1").splitlines()[13:] + for row in rows: + if row.strip(): + vals = [number(w, 0.0) for w in get_words(row, ignore_quotes=True)[:npx]] + data.append(vals + [0.0] * (npx - len(vals))) + if any(not math.isfinite(v) for row in data for v in row): + return (True, True) + tol = FIELD_RTOL * max((abs(v) for row in data for v in row), default=0.0) + for r, row in enumerate(data): + if any(abs(v - row[0]) > tol for v in row[1:]): + varies[0] = True + first = data[r - r % npy] + if r % npy and any(abs(a - b) > tol for a, b in zip(row, first)): + varies[1] = True + return varies[0], varies[1] + + +def waterkin_flags(deck: Deck, deck_path: Path) -> tuple[bool, bool, str]: + """Whether the lines take SeaState's waves and current, and the route, from the deck's + WaterKin (CableDyn_DeckDriver apply_option and read_waterkin_records): no policy, 0 or none, + a MoorDyn-C mode, SEASTATE or SEASTATE_GRID take both on the grid, SEASTATE_SPECTRAL both + at the nodes; a WaterKin file (a value with a letter other than an exponent e) takes the + waves for WaveKinMod 2 or SEASTATE (its line 4) and the current for CurrentMod 2 (line 15).""" + value = deck.options.get("waterkin", "0") + low = value.lower() + if low == "seastate_spectral": + return True, True, "seastate_spectral" + if low in ("seastate", "seastate_grid", "none") or not any(c.isalpha() and c not in "eE" for c in value): + return True, True, "seastate_grid" + path = deck_path.parent / value + try: + rows = path.read_text(encoding="utf-8-sig", errors="replace").splitlines() + wave_token = (rows[3].split() or [""])[0].strip("\"'").lower() + current_token = (rows[14].split() or [""])[0] + except (OSError, IndexError) as error: + raise CaseError(f"the WaterKin file {path} cannot be read as CableDyn reads it: {error}") from error + waves = wave_token == "seastate" or number(wave_token, -1) == 2 + current = number(current_token, -1) == 2 + return waves, current, "waterkin_file" + + +def kept_amplitude(spacing: float, wavelength: float) -> float: + """Catmull-Rom midway between grid points spaced `spacing` on a sinusoid of `wavelength`: the + fraction of the amplitude kept, 0 from half a wavelength on, where the grid points alias the wave.""" + phi = 2.0 * math.pi * spacing / wavelength + if phi >= math.pi: + return 0.0 + return max(0.0, 9.0 / 8.0 * math.cos(phi / 2.0) - 1.0 / 8.0 * math.cos(1.5 * phi)) + + +def axis_kept(lam: float, spacing: tuple[float, float], wave_dir: float, multi: bool) -> list[float]: + """The amplitude kept midway between grid points along x and y for waves of wavelength lam: + along each axis a long-crested sea at direction beta has the wavelength lam/|cos| (x) or + lam/|sin| (y); a short-crested one is taken at lam on both.""" + axis_lam = [lam, lam] + if not multi: + for k, trig in enumerate((math.cos, math.sin)): + c = abs(trig(math.radians(wave_dir))) + axis_lam[k] = lam / c if c > 1e-6 else math.inf + return [1.0 if math.isinf(a) else kept_amplitude(s, a) for s, a in zip(spacing, axis_lam)] + + +def shown(values: list[float]) -> list[str]: + return [f"{100 * k:.1f} %" if k > 0.0 else "nothing (over half a wavelength)" for k in values] + + +def grid_memory(nx: int, ny: int, nz: int, nsteps: int, stmod: int, mcf: bool) -> float: + """Bytes SeaState stores for its grid: velocity and acceleration (3 each), dynamic pressure, + MacCamy-Fuchs acceleration (3) when used, the surface elevation and its spectrum, and the + surface derivatives of extrapolation stretching (7).""" + vol = (2 * nx - 1) * (2 * ny - 1) * nz + srf = (2 * nx - 1) * (2 * ny - 1) + per_step = vol * (7 + (3 if mcf else 0)) + srf * (1 + (7 if stmod == 2 else 0)) + return float(BYTES) * (per_step * (nsteps + 1) + srf * 2 * (nsteps // 2 + 1)) + + +def along(direction: float, axis: int) -> bool: + d = direction % 180.0 + return (d <= 1e-4 or d >= 180.0 - 1e-4) if axis == 1 else abs(d - 90.0) <= 1e-4 + + +COUPLED_TYPES = {"coupled", "vessel", "cpld", "ves"} + + +def point_position(deck: Deck, pid: int, margin: float, notes: list[str], lid: int) \ + -> tuple[float, float, float, float] | None: + """A line end's position and its motion margin: a Coupled or Vessel point at its reference + pose with the margin, a fixed or free point as given, a Body point (a body-frame offset) + at its body's reference position plus the offset when the body is not rotated (with the + margin when the body is coupled); None, with a note, for an end the check cannot place.""" + if pid not in deck.points: + return None + kind, x, y, z = deck.points[pid] + low = kind.lower() + if low.startswith("body"): + body = deck.bodies.get(int(number(low[4:], 0))) + if body is None or any(abs(a) > 0.0 for a in body[4:7]): + notes.append(f"line {lid}: point {pid} sits on {kind}, which is " + f"{'missing' if body is None else 'rotated'}; that end is left out of the check") + return None + return (body[1] + x, body[2] + y, body[3] + z, margin if body[0].lower() in COUPLED_TYPES else 0.0) + if low.startswith("turbine"): + notes.append(f"line {lid}: point {pid} sits on {kind} (FAST.Farm); that end is left out of the check") + return None + return (x, y, z, margin if low in COUPLED_TYPES else 0.0) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("fst", type=Path) + parser.add_argument("--margin", type=float, default=20.0, help="platform motion margin (m)") + parser.add_argument("--peak-ratio", type=float, default=PEAK_RATIO) + parser.add_argument("--json", type=Path) + args = parser.parse_args(argv) + fst = args.fst + stops: list[str] = [] + notes: list[str] = [] + try: + f = values(fst) + # a case without SeaState (CompSeaSt 0) need not name a SeaState file that exists: its + # still-water values come from the .fst + seastate_on = f.get("CompSeaSt") is None or int(number(f.get("CompSeaSt"), 1)) != 0 + ss_path = fst.parent / f["SeaStFile"] if seastate_on else None + hd_path = fst.parent / f["HydroFile"] + deck_path = fst.parent / f["MooringFile"] + ss = values(ss_path) if ss_path is not None else Values() + deck = read_deck(deck_path) + joints = hull_joints(hd_path) if hd_path.is_file() else [] + host_wave, host_current, route = waterkin_flags(deck, deck_path) + except (KeyError, OSError, CaseError) as error: + print(f"cannot read the case: {error}") + return 2 + if f.get("CompMooring") is not None and int(number(f.get("CompMooring"), 5)) != 5: + print(f"cannot read the case: CompMooring = {f.get('CompMooring')}, not CableDyn (5)") + return 2 + if not seastate_on: + notes.append("CompSeaSt = 0: no SeaState, the lines are in still water and no grid is read") + depth = setting(ss, "WtrDpth", f, 0.0) + msl = setting(ss, "MSL2SWL", f, 0.0) + eff = depth + msl + xhw = number(ss.get("X_HalfWidth"), 0.0) + yhw = number(ss.get("Y_HalfWidth"), 0.0) + zd = setting(ss, "Z_Depth", Values(), eff) + nx = int(number(ss.get("NX"), 2)) + ny = int(number(ss.get("NY"), 2)) + nz = int(number(ss.get("NZ"), 2)) + dt = number(ss.get("WaveDT"), 0.25) + tmax = number(ss.get("WaveTMax"), 0.0) + nsteps = wave_steps(tmax, dt) + stmod = int(number(ss.get("WaveStMod"), 0)) + mod = wave_mod(ss) + curr_mod = int(number(ss.get("CurrMod"), 0)) + sea_waves = seastate_on and mod != 0 + sea_current = seastate_on and curr_mod != 0 + ambient = sea_waves or sea_current # CableDyn's wavefield_is_ambient + # what the lines take from SeaState (the deck's WaterKin; the guard checks only that) + line_waves = host_wave and sea_waves + line_current = host_current and sea_current + spectral = route == "seastate_spectral" + multi = multi_directional(ss) + wave_dir = number(ss.get("WaveDir"), 0.0) + guard = deck.options.get("wavegridcheck", "error") + warn_mode = guard.lower() == "warn" + report: dict[str, object] = {"fst": str(fst), "route": route, "line_waves": line_waves, + "line_current": line_current} + + # what stops CableDyn's initialisation in OpenFAST whatever the grid + if ambient and (host_wave or host_current) and msl != 0.0: + stops.append(f"MSL2SWL = {msl:g} m with SeaState waves or current: CableDyn samples SeaState at " + "positions relative to the mean sea level, which only MSL2SWL = 0 matches") + ss_depth = ss.get("WtrDpth") + if ambient and ss_depth is not None and ss_depth.strip("\"'").upper() != "DEFAULT": + glue_depth = number(f.get("WtrDpth"), math.nan) + if not math.isnan(glue_depth) and abs(number(ss_depth, glue_depth) - glue_depth) > 1e-3: + stops.append(f"SeaState WtrDpth {number(ss_depth, 0.0):g} m differs from the .fst WtrDpth " + f"{glue_depth:g} m, which CableDyn refuses") + if ambient and host_wave != host_current and curr_mod == 2: + stops.append("the WaterKin file takes SeaState's waves and current separately, which CurrMod 2 " + "(a user current) does not allow") + + # the wave components and their directions, as the guard judges them + components: list[tuple[float, float, float]] = [] + # WaveMod 6 and 7 read their files only with SeaState on (without it the wave mode reads 0) + kin_root = ss_path.parent / (ss.get("WvKinFile") or "") if ss_path is not None else fst.parent + if mod == 7: + try: + components = user_components(kin_root) + except OSError as error: + print(f"cannot read the case: the WaveMod 7 components: {error}") + return 2 + # SeaState zeroes the components outside WvLowCOff to WvHiCOff, and CableDyn's check sees + # only the components left + lo = number(ss.get("WvLowCOff"), 0.0) + hi = number(ss.get("WvHiCOff"), 2.0 * math.pi) + directions = [d for w, a, d in components if a != 0.0 and lo <= w <= hi] or [wave_dir] + # components along one line, either way (0 and 180 deg), vary along the same axes as one + # long-crested sea; only headings that differ modulo 180 deg make the sea vary along both + # (CD_WaveGrid_Coarse_Axes judges each direction modulo 180 deg too) + multi = multi or any(1e-4 < (d - directions[0]) % 180.0 < 180.0 - 1e-4 for d in directions) + wave_dir = directions[0] + else: + directions = [wave_dir] + + # coverage of the lines (grid route) and of the hull + def outside(x: float, y: float, z: float, margin: float, waves: bool, current: bool) -> list[str]: + out: list[str] = [] + if z > 0.0: + return out # above the still-water level: no fluid load, and the guard checks wet nodes only + if waves and abs(x) + margin > xhw: + out.append("x") + if waves and abs(y) + margin > yhw: + out.append("y") + # depth matters to the waves and to SeaState's current (uniform in x and y); a node + # below a grid that reaches the seabed is in the seabed + if (waves or current) and zd < eff - 1e-6 and z < -zd: + out.append("z") + return out + + lines_out = [] + for lid, (a, b) in sorted(deck.lines.items()): + ends = [e for e in (point_position(deck, p, args.margin, notes, lid) for p in (a, b)) if e] + problems = sorted({axis for x, y, z, m in ends + for axis in outside(x, y, max(z, -eff), m, line_waves, line_current)}) + lines_out.append({"line": lid, "outside_axes": problems}) + if problems and not spectral: + message = f"line {lid} reaches outside the SeaState grid in {', '.join(problems)}" + # waveGridCheck warn lets CableDyn run on with a warning, as for the resolution + (notes if warn_mode else stops).append(message + (" (waveGridCheck warn)" if warn_mode else "")) + report["lines"] = lines_out + # the hull reads SeaState as SeaState is set up, whatever the deck takes + hull_out = sorted({axis for x, y, z in joints + for axis in outside(x, y, z, args.margin, sea_waves, sea_current)}) + report["hull_outside_axes"] = hull_out + if hull_out: + notes.append(f"hull joints reach outside the SeaState grid in {', '.join(hull_out)} (HydroDyn " + "clamps them to the boundary)") + + # resolution across the waves (CableDyn's check_wavefield_resolution, lines on the grid route) + if line_waves and not spectral and (nx <= 2 or ny <= 2): + coarse_x = coarse_y = False + if mod == 6: + # supplied kinematics: no directions; the data say whether they vary across the axis + judged = external_varies(kin_root, nx, ny) + if judged is None: + notes.append("WaveMod 6: the supplied kinematics could not be read here (missing, or over " + f"{EXTERNAL_LIMIT // 2**20} MB), so NX or NY = 2 is not judged; CableDyn judges " + "it from the data at initialisation") + else: + coarse_x, coarse_y = nx <= 2 and judged[0], ny <= 2 and judged[1] + else: + coarse_x = nx <= 2 and (multi or any(not along(d, 2) for d in directions)) + coarse_y = ny <= 2 and (multi or any(not along(d, 1) for d in directions)) + if coarse_x or coarse_y: + which = " and ".join(a for a, c in (("NX", coarse_x), ("NY", coarse_y)) if c) + message = f"{which} = 2 under a sea that varies along that axis" + (notes if warn_mode else stops).append(message + (" (waveGridCheck warn)" if warn_mode else "")) + # the hull-only grid must resolve its shallowest wetted joint, where the short waves are + hull_top = min(max((z for _, _, z in joints), default=0.0), 0.0) + lam_hull = shortest_wavelength(ss, eff, hull_top, components) if sea_waves else None + lam_surface = shortest_wavelength(ss, eff, 0.0, components) if sea_waves else None + if sea_waves and lam_surface is None: + notes.append(f"WaveMod {mod}: the shortest wavelength is not judged here") + spacing = (xhw / (nx - 1) if nx > 1 else xhw, yhw / (ny - 1) if ny > 1 else yhw) + if lam_surface: + report["shortest_wavelength_m"] = lam_surface + report["grid_spacing_m"] = list(spacing) + report["mid_cell_amplitude_kept"] = axis_kept(lam_surface, spacing, wave_dir, multi) + lam_peak = peak_wavelength(ss, eff) + if lam_peak: + report["peak_wavelength_m"] = lam_peak + report["mid_cell_amplitude_kept_peak"] = axis_kept(lam_peak, spacing, wave_dir, multi) + # memory + mcf = number(ss.get("MCFD"), 0.0) > 0.0 + mem = grid_memory(nx, ny, nz, nsteps, stmod, mcf) if sea_waves else 0.0 + report["grid_memory_gb"] = mem / 1e9 + report["startup_peak_gb"] = args.peak_ratio * mem / 1e9 + + # the spectral route refuses what it cannot reproduce (CableDyn's nwk_setup): the wave items + # when the lines take SeaState's waves, CurrMod 2 when they take its current. SeaState turns + # WvCrntMod off without a current (CurrMod 0). + refusals = [] + waves_taken = sea_waves and host_wave + if waves_taken and (flag(ss.get("WvDiffQTF")) or flag(ss.get("WvSumQTF"))): + refusals.append("second-order kinematics") + if waves_taken and mod == 6: + refusals.append("WaveMod 6") + wv_crnt = int(number(ss.get("WvCrntMod"), 0)) if curr_mod != 0 else 0 + if waves_taken and wv_crnt != 0: + refusals.append("WvCrntMod 1 or 2") + if host_current and curr_mod == 2: + refusals.append("CurrMod 2") + report["spectral_supported"] = not refusals + report["spectral_refusals"] = refusals + if spectral and refusals: + stops.append("WaterKin SEASTATE_SPECTRAL refuses " + ", ".join(refusals)) + exctn_disp = number(values(hd_path).get("ExctnDisp"), 0.0) if hd_path.is_file() else 0.0 + if exctn_disp != 0.0 and sea_waves: + notes.append(f"ExctnDisp {exctn_disp:g}: the WAMIT excitation reads the SeaState surface grid at the " + "displaced platform, so keep the grid over the hull and its motion") + elif not joints and sea_waves: + notes.append("no Morison members: the hull reads no grid (WAMIT excitation with ExctnDisp = 0 " + "uses the components), so with SEASTATE_SPECTRAL the smallest grid (NX = NY = NZ = 2) " + "serves") + if joints and lam_hull: + hx = max(abs(x) for x, _, _ in joints) + args.margin + hy = max(abs(y) for _, y, _ in joints) + args.margin + hz = min(eff, -min(z for _, _, z in joints) + args.margin) + step = lam_hull / 10.0 + rnx, rny = math.ceil(hx / step) + 1, math.ceil(hy / step) + 1 + rnz = max(2, math.ceil(hz / step) + 1) + report["hull_only_grid"] = { + "X_HalfWidth": hx, "Y_HalfWidth": hy, "Z_Depth": hz, "NX": rnx, "NY": rny, "NZ": rnz, + "memory_gb": grid_memory(rnx, rny, rnz, nsteps, stmod, mcf) / 1e9, + "startup_peak_gb": args.peak_ratio * grid_memory(rnx, rny, rnz, nsteps, stmod, mcf) / 1e9, + } + report["stops"] = stops + report["notes"] = notes + + print(f"CableDyn pre-flight check of {fst}") + print(f" wave route: {report['route']} (lines take SeaState's waves: {'yes' if line_waves else 'no'}, " + f"current: {'yes' if line_current else 'no'}); SeaState grid NX {nx}, NY {ny}, NZ {nz}, half-widths " + f"{xhw:g} x {yhw:g} m, depth {zd:g} m; stored {mem / 1e9:.2f} GB, start-up peak about " + f"{args.peak_ratio * mem / 1e9:.2f} GB") + if lam_surface: + kept = report["mid_cell_amplitude_kept"] + assert isinstance(kept, list) + s = shown(kept) + print(f" shortest wavelength that matters at the surface {lam_surface:.1f} m; midway between grid " + f"points the {spacing[0]:.1f} m spacing in x keeps {s[0]} and the {spacing[1]:.1f} m spacing " + f"in y {s[1]} of its amplitude") + if "peak_wavelength_m" in report: + p = shown(report["mid_cell_amplitude_kept_peak"]) # type: ignore[arg-type] + print(f" at the peak period (wavelength {report['peak_wavelength_m']:.1f} m) they keep {p[0]} in x " + f"and {p[1]} in y") + for entry in lines_out: + state = "inside" if not entry["outside_axes"] else "outside in " + ", ".join(entry["outside_axes"]) + print(f" line {entry['line']}: end points {state}") + hull_state = "inside" if not hull_out else "outside in " + ", ".join(hull_out) + print(f" hull joints: {hull_state if joints else 'none (no Morison members)'}") + print(f" SEASTATE_SPECTRAL: {'supported' if not refusals else 'refuses ' + ', '.join(refusals)}") + if "hull_only_grid" in report: + hg = report["hull_only_grid"] + assert isinstance(hg, dict) + print(f" hull-only grid for SEASTATE_SPECTRAL: X_HalfWidth {hg['X_HalfWidth']:.0f}, Y_HalfWidth " + f"{hg['Y_HalfWidth']:.0f}, Z_Depth {hg['Z_Depth']:.0f}, NX {hg['NX']}, NY {hg['NY']}, NZ " + f"{hg['NZ']}: {hg['memory_gb']:.2f} GB, peak {hg['startup_peak_gb']:.2f} GB") + for note in notes: + print(f" note: {note}") + for stop in stops: + print(f" STOP: {stop}") + if args.json: + args.json.write_text(json.dumps(report, indent=2), encoding="utf-8") + return 1 if stops else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/integration/openfast/patches/0006-cabledyn-cmake.patch b/integration/openfast/patches/0006-cabledyn-cmake.patch index 27e0b64f..a94b8a0b 100644 --- a/integration/openfast/patches/0006-cabledyn-cmake.patch +++ b/integration/openfast/patches/0006-cabledyn-cmake.patch @@ -3,7 +3,7 @@ new file mode 100644 index 000000000..be1a9133b --- /dev/null +++ b/modules/cabledyn/CMakeLists.txt -@@ -0,0 +1,194 @@ +@@ -0,0 +1,199 @@ +# +# Copyright (C) 2026 Jae Hoon Seo, SMI Lab, Inha University +# @@ -179,6 +179,11 @@ index 000000000..be1a9133b + RUNTIME DESTINATION bin +) + ++# Vertex check of the node-wise wave kinematics (WaterKin SEASTATE_SPECTRAL) against SeaState's own ++# grid, with no coupled run: cabledyn_wavekin_check [WtrDpth] [PtfmLocationX PtfmLocationY] ++add_executable(cabledyn_wavekin_check ${CABLEDYN_ROOT}/src/openfast/CableDyn_WaveKin_Check.f90) ++target_link_libraries(cabledyn_wavekin_check cabledynlib versioninfolib) ++ +# Module regression cases (self-contained text inputs, copied to the build tree so the +# runs never write into the source tree): the driver fails loud -- nonzero exit -- on +# any module error or non-finite output, so exit status is the assertion. diff --git a/integration/openfast/patches/0023-fast-farm-end.patch b/integration/openfast/patches/0023-fast-farm-end.patch index 5348ac1f..f45974fc 100644 --- a/integration/openfast/patches/0023-fast-farm-end.patch +++ b/integration/openfast/patches/0023-fast-farm-end.patch @@ -1,8 +1,8 @@ diff --git a/glue-codes/fast-farm/src/FAST_Farm.f90 b/glue-codes/fast-farm/src/FAST_Farm.f90 -index c3d63ed75..c7ecdcedc 100644 +index c3d63ed75..d1b8615af 100644 --- a/glue-codes/fast-farm/src/FAST_Farm.f90 +++ b/glue-codes/fast-farm/src/FAST_Farm.f90 -@@ -160,6 +160,12 @@ type(All_FastFarm_Data) :: farm +@@ -160,6 +160,14 @@ type(All_FastFarm_Data) :: farm ! End: !............................................................................................................................... @@ -11,6 +11,8 @@ index c3d63ed75..c7ecdcedc 100644 + do i_turb = 1, farm%p%NumTurbines + farm%FWrap(i_turb)%m%Turbine%CD%m%HostComplete = .true. + end do ++ ! and so does the farm-level instance of the shared moorings ++ if (farm%p%MooringMod == 5) farm%CD%m%HostComplete = .true. + call FARM_End(farm, ErrStat, ErrMsg) diff --git a/python/cabledyn/deck_file.py b/python/cabledyn/deck_file.py index d3446bb9..529917da 100644 --- a/python/cabledyn/deck_file.py +++ b/python/cabledyn/deck_file.py @@ -264,6 +264,8 @@ "viv_phase_seed": "viv_phase_seed", "wavegridcheck": "wave_grid_check", "wave_grid_check": "wave_grid_check", + "wavekintol": "wave_kin_tol", + "wave_kin_tol": "wave_kin_tol", "rangestart": "range_start", "range_start": "range_start", "waveseed": "wave_seed", @@ -418,6 +420,9 @@ # Native TORS_NX_PARALLEL_TOL: smallest |Nx x Ez| of unit vectors (about 0.06 degrees off Ez). _TORSION_NORMAL_PARALLEL_TOL = 1.0e-3 _WATERKIN_FILENAME_LETTERS = frozenset("abcdfghijklmnopqrstuvwxyzABCDFGHIJKLMNOPQRSTUVWXYZ") +# WaterKin values that take the host SeaState field: on its grid (SEASTATE, SEASTATE_GRID) or +# evaluated at the nodes from its wave components (SEASTATE_SPECTRAL, the OpenFAST module) +_SEASTATE_WATERKIN = frozenset({"seastate", "seastate_grid", "seastate_spectral"}) # MoorDyn-C kinematics files the native reader opens by fixed name in the deck folder # (read_moordyn_c_kinematics): WaveKin 3, WaveKin 7 and Currents 1, 2 and 5. _MOORDYN_C_WAVE_FILES = {3: "wave_elevation.txt", 7: "wave_frequencies.txt"} @@ -433,7 +438,7 @@ def _moordyn_c_wave_kin(value: str | None) -> int: if value is None: return 0 value = _strip_quotes(value) - if value.lower() in {"none", "seastate"} or any( + if value.lower() in {"none", *_SEASTATE_WATERKIN} or any( character in _WATERKIN_FILENAME_LETTERS for character in value ): return 0 @@ -1416,6 +1421,12 @@ def _scalar_option_value_error(keyword: str, value: str) -> str | None: ) if key == "viv_phase_seed": return None if value.lower() in {"spread", "zero"} else "must be spread or zero" + if key == "wave_kin_tol": + try: + tol = _native_float(value) + except ValueError: + return "must be a number at least 0 and below 1" + return None if 0.0 <= tol < 1.0 else "must be at least 0 and below 1" if key == "wave_grid_check": return None if value.lower() in {"error", "warn"} else "must be error or warn" if key == "cable_statics": @@ -1520,14 +1531,14 @@ def _scalar_option_value_error(keyword: str, value: str) -> str | None: return None if round(numeric) in {0, 1, 2, 5} else "supports only mode 0, 1, 2 or 5" if key == "waterkin": lowered = value.lower() - if lowered in {"none", "seastate"} or any( + if lowered in {"none", *_SEASTATE_WATERKIN} or any( character in _WATERKIN_FILENAME_LETTERS for character in value ): return None try: numeric = _native_float(value) except ValueError: - return "requires 0/none, SEASTATE, or a filename" + return "requires 0/none, SEASTATE, SEASTATE_GRID, SEASTATE_SPECTRAL, or a filename" if ( math.isfinite(numeric) and abs(numeric - round(numeric)) < 1.0e-9 @@ -4099,9 +4110,11 @@ def effective(key: str, default: float) -> float: waterkin_option = option_by_key.get("waterkin") waterkin_value = "" if waterkin_option is None else waterkin_option.values[0] # A WaterKin file may carry the waves (its WaveKinMod is read at run time). - has_waterkin_file = waterkin_value.lower() not in {"", "none", "seastate"} and any( - character in _WATERKIN_FILENAME_LETTERS for character in waterkin_value - ) + has_waterkin_file = waterkin_value.lower() not in { + "", + "none", + *_SEASTATE_WATERKIN, + } and any(character in _WATERKIN_FILENAME_LETTERS for character in waterkin_value) if has_waterkin_file and motion_source == "vesselrao": has_waterkin_file = self._waterkin_wave_mode(waterkin_value) in {None, 1} has_trains = any(o.keyword.lower() in _WAVETRAIN_KEYWORDS for o in options) @@ -4215,7 +4228,7 @@ def effective(key: str, default: float) -> float: waterkin_ref = option_by_key.get("waterkin") waterkin_text = "" if waterkin_ref is None else waterkin_ref.values[0] has_record = bool(mdc_wave_kin) or ( - waterkin_text.lower() not in {"", "none", "seastate"} + waterkin_text.lower() not in {"", "none", *_SEASTATE_WATERKIN} and any(character in _WATERKIN_FILENAME_LETTERS for character in waterkin_text) and self._waterkin_wave_mode(waterkin_text) in {None, 1} ) @@ -6126,7 +6139,7 @@ def number(key: str) -> float | None: waterkin_row = option_by_key.get("waterkin") if waterkin_row is not None and not mdc_wave_kin: value = waterkin_row.values[0] - if value.lower() not in {"", "none", "seastate"} and any( + if value.lower() not in {"", "none", *_SEASTATE_WATERKIN} and any( character in _WATERKIN_FILENAME_LETTERS for character in value ): record_dir = self._check_waterkin_file( @@ -7333,7 +7346,7 @@ def rebased(value: str) -> str: continue is_waterkin = path_group == "waterkin" if is_waterkin: - if value.lower() in {"none", "seastate"}: + if value.lower() in {"none", *_SEASTATE_WATERKIN}: continue try: _native_float(value) diff --git a/python/tests/test_deck_file.py b/python/tests/test_deck_file.py index b1c8a74d..cd9f6295 100644 --- a/python/tests/test_deck_file.py +++ b/python/tests/test_deck_file.py @@ -676,6 +676,8 @@ def test_unknown_scalar_option_keyword_fails_closed(tmp_path): ("0", "viv_phase_seed", "spread or zero"), ("strict", "waveGridCheck", "error or warn"), ("1", "wave_grid_check", "error or warn"), + ("1", "waveKinTol", "below 1"), + ("-1e-3", "wave_kin_tol", "below 1"), ("nodal", "OutputRecovery", "equilibrium or element"), ("mode2", "axialDampingRatio", "segment or mode1"), ("element", "axial_damping_ratio", "segment or mode1"), @@ -766,6 +768,8 @@ def test_zero_e_exponent_waterkin_mode_is_accepted(tmp_path): "ZERO viv_phase_seed", "warn waveGridCheck", "ERROR wave_grid_check", + "0 waveKinTol", + "1e-6 wave_kin_tol", "equilibrium OutputRecovery", "element output_recovery", "segment axialDampingRatio", @@ -3210,7 +3214,10 @@ def test_stock_line_row_is_the_single_section_occurrence(tmp_path): ("inf bending_quadrature_order", "must be an integer in [1, 6]"), ("5 current", "OPTION current requires a supported positional mode"), ("abc currents", "OPTION currents must be numeric"), - ("1e WaterKin", "requires 0/none, SEASTATE, or a filename"), + ( + "1e WaterKin", + "requires 0/none, SEASTATE, SEASTATE_GRID, SEASTATE_SPECTRAL, or a filename", + ), ("dynamic_solver 0 1e-14 30 12", "dynamic_solver needs positive finite tolerances"), ("uniform inf 0 0 current", "positional option values must be finite plain numbers"), ("airy 2 x 0 waves", "positional option values must be finite plain numbers"), diff --git a/release/build_static_windows.ps1 b/release/build_static_windows.ps1 index 12807d28..637d09a5 100644 --- a/release/build_static_windows.ps1 +++ b/release/build_static_windows.ps1 @@ -450,7 +450,9 @@ try { $runLog = $run.Text Write-Host $runLog if ($run.ExitCode -ne 0) { throw "openfast.exe smoke case failed`n$runLog" } - if ($runLog -notmatch 'lie outside the SeaState wave-kinematics grid at t = 0 s \(warned once\)') { + # CableDyn wraps its long messages to the screen width, so a phrase may break at any space + $runFlat = $runLog -replace '\s+', ' ' + if ($runFlat -notmatch 'lie outside the SeaState wave-kinematics grid at t = 0 s \(warned once\)') { throw "openfast.exe did not report the platform-only SeaState grid of the smoke case`n$runLog" } if ($runLog -notmatch 'Running CableDyn \(' -or $runLog -notmatch 'OpenFAST terminated normally') { @@ -461,7 +463,7 @@ try { } if ($runLog -notmatch 'Created CableDyn model:' -or $runLog -notmatch 'Line 1 fairlead effective tension:' -or - $runLog -notmatch ('Requested CableDyn OUTPUTS at t = 0 s \(equilibrium pose, SeaState ' + + $runFlat -notmatch ('Requested CableDyn OUTPUTS at t = 0 s \(equilibrium pose, SeaState ' + 'kinematics at t = 0\):') -or $runLog -notmatch 'FairTen1\s*=') { throw "openfast.exe did not print the CableDyn initialization and requested-output reports`n$runLog" diff --git a/src/CableDyn_Banner.f90 b/src/CableDyn_Banner.f90 index 76ef2c87..33aba0c8 100644 --- a/src/CableDyn_Banner.f90 +++ b/src/CableDyn_Banner.f90 @@ -11,7 +11,7 @@ MODULE CableDyn_Banner USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: output_unit IMPLICIT NONE PRIVATE - PUBLIC :: CD_BANNER_NLINE, CD_Banner_Line, CD_Print_Banner + PUBLIC :: CD_BANNER_NLINE, CD_Banner_Line, CD_Print_Banner, CD_Version INTEGER, PARAMETER :: CD_BANNER_NLINE = 9 @@ -45,6 +45,15 @@ PURE FUNCTION CD_Banner_Line(i) RESULT(s) END SELECT END FUNCTION CD_Banner_Line + PURE FUNCTION CD_Version() RESULT(v) + !! The CableDyn version the banner names (its second line, after the "v"), as in "0.4.3". + CHARACTER(:), ALLOCATABLE :: v, s + INTEGER :: k + s = CD_Banner_Line(2) + k = INDEX(s, ' v') + v = TRIM(ADJUSTL(s(k + 2:))) + END FUNCTION CD_Version + SUBROUTINE CD_Print_Banner(unit) !! Write the whole banner to `unit` (default: standard output). Used by the standalone !! driver; the OpenFAST module announces itself through DispNVD and does not print this diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 71efe002..1bf20110 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -571,6 +571,15 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, rotating, err CALL CD_AGG_End(new_agg, es, em) RETURN END IF + IF (new_agg%host_wave_nodewise) THEN + ! the node-wise route evaluates the wave components of an OpenFAST SeaState field; a C API + ! host hands over its fluid kinematics itself + CALL CD_AGG_End(new_agg, es, em) + CALL set_status(h, CD_C_BAD_INPUT, caller//': WaterKin SEASTATE_SPECTRAL evaluates the wave components '// & + 'of an OpenFAST SeaState field; a C API host supplies the fluid kinematics itself (use '// & + 'WaterKin SEASTATE)', err_stat) + RETURN + END IF nm = CD_AGG_NMovingPoints(new_agg, es, em) ! Allocate the new route's workspace before releasing the old route, so an ! allocation failure leaves the handle's previous model in place. diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 607e6da0..78f16576 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -166,6 +166,8 @@ MODULE CableDyn_DeckDriver CD_RQ_CURVATURE, CD_RQ_BEND, CD_RQ_DECLINATION, CD_RQ_CLEARANCE, CD_TDP_N, & CD_RQ_TORQUE, CD_RQ_TWIST USE CableDyn_Conventions, ONLY: CD_Body_Rotation + USE CableDyn_Provenance, ONLY: CD_Prov, CD_Prov_Write + USE CableDyn_Banner, ONLY: CD_Version USE CableDyn_RigidKinematics, ONLY: CD_Rigid_Advance_Newmark, CD_RIGID_OK, CD_RIGID_NEWMARK_GAMMA, & CD_RIGID_NEWMARK_BETA USE CableDyn_SO3, ONLY: CD_Log_SO3, CD_Exp_SO3 @@ -818,6 +820,11 @@ MODULE CableDyn_DeckDriver ! WaveKin 3 cut); negative ('none') keeps them up to the Nyquist frequency of dtWave REAL(wp) :: wv_hi_cutoff = 0.5_wp*TWO_PI LOGICAL :: waterkin_seastate = .FALSE. + ! WaterKin SEASTATE_SPECTRAL: the host waves evaluated node by node from its components + LOGICAL :: waterkin_nodewise = .FALSE. + ! OPTION waveKinTol: the truncation tolerance of the node-wise route (dropped velocity and + ! acceleration variances, each relative to its surface total) + REAL(wp) :: wave_kin_tol = 1.0e-6_wp LOGICAL :: waterkin_host_wave = .FALSE. LOGICAL :: waterkin_host_current = .FALSE. LOGICAL :: has_wave = .FALSE. @@ -1316,6 +1323,9 @@ MODULE CableDyn_DeckDriver ! default true for backward-compatible direct SeaState sampling. LOGICAL :: host_wave_enabled = .FALSE. LOGICAL :: host_current_enabled = .FALSE. + ! WaterKin SEASTATE_SPECTRAL and OPTION waveKinTol (see CD_AGG_ModuleType%host_wave_nodewise) + LOGICAL :: host_wave_nodewise = .FALSE. + REAL(wp) :: wave_kin_tol = 1.0e-6_wp LOGICAL :: cable_load_feedback = .TRUE. ! Deck OPTION predictLoads (the OpenFAST shell; see CD_AGG_ModuleType%predict_loads) LOGICAL :: predict_loads = .TRUE. @@ -8125,7 +8135,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi n_turbines, turbine_ref_pos, farm_ptfm_init, forbid_deck_ambient, run_tmax, & range_files, host_orientation, static_current, prescribed_motion, & static_run, deck_current, deck_turbines, static_deck_current, & - range_discard_root) + range_discard_root, static_current_nodewise) !! Parse a MIXED deck ONCE and partition its lines into {EI=0 mooring} and !! {finite-EI cable}, returning the raw parts the OpenFAST aggregate facade wraps: !! the EI=0 mooring SYSTEM built from the mooring subset (over ALL deck points, the @@ -8213,8 +8223,11 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi ! EI = 0 lines, finite-EI cables) take it as a deck current profile, so the coupled start ! is the equilibrium in that current, as a standalone deck's is in its current OPTION. The ! dynamics take the host field alone: the profile goes into a copy of the options that - ! only the static builders see. - REAL(wp), INTENT(IN), OPTIONAL :: static_current(:, :) + ! only the static builders see. static_current_nodewise: the same current sampled for a + ! deck on WaterKin SEASTATE_SPECTRAL, whose steps take it at each node's depth rather than + ! between SeaState's grid levels; such a deck's static solves take it in place of + ! static_current. + REAL(wp), INTENT(IN), OPTIONAL :: static_current(:, :), static_current_nodewise(:, :) ! prescribed_motion: the caller marches the deck's own motionFile or vesselMotion table ! (the standalone driver on a mixed deck of lines between Fixed/Coupled/Vessel points): ! the table is read into agg%motion in the moving-set order instead of being refused. @@ -8259,6 +8272,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi TYPE(DeckOptions) :: opts_static ! the deck's steady current of static_deck_current, kept for the static builders LOGICAL :: keep_static_current, kept_has_current, kept_has_profile + REAL(wp), ALLOCATABLE :: host_static_current(:, :) REAL(wp) :: kept_velocity(3) REAL(wp), ALLOCATABLE :: kept_profile_z(:), kept_profile_velocity(:, :) CHARACTER(NAMELEN), ALLOCATABLE :: channels(:) @@ -8396,6 +8410,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi agg%cable_load_feedback = opts%cable_load_feedback agg%predict_loads = opts%predict_loads agg%wave_grid_warn = opts%wave_grid_warn + agg%wave_kin_tol = opts%wave_kin_tol agg%cd_out_dt = opts%cd_out_dt agg%max_strain = opts%max_strain @@ -8455,7 +8470,8 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi 'host fluid field (external_fluid) would double-count the current'); RETURN END IF END IF - IF (nturb > 0 .OR. PRESENT(ptfm_init) .OR. PRESENT(static_current)) THEN + IF (nturb > 0 .OR. PRESENT(ptfm_init) .OR. PRESENT(static_current) .OR. & + PRESENT(static_current_nodewise)) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: a deck-owned current (deck_current) takes no '// & 'platform placement, farm or host current'); RETURN END IF @@ -8503,6 +8519,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi IF (opts%has_waterkin_file .OR. opts%waterkin_seastate) THEN agg%host_wave_enabled = opts%waterkin_host_wave agg%host_current_enabled = opts%waterkin_host_current + agg%host_wave_nodewise = opts%waterkin_nodewise IF (opts%waterkin_current_mode == 1 .AND. opts%has_current_profile .AND. & .NOT. opts%waterkin_host_current) THEN agg%host_current_profile_z = opts%current_profile_z @@ -8842,26 +8859,31 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi opts_static%current_profile_velocity = kept_profile_velocity END IF END IF - IF (PRESENT(static_current)) THEN + ! the host's steady current as the deck's route takes it in its steps + IF (PRESENT(static_current)) host_static_current = static_current + IF (PRESENT(static_current_nodewise)) THEN + IF (opts%waterkin_nodewise) host_static_current = static_current_nodewise + END IF + IF (ALLOCATED(host_static_current)) THEN IF (.NOT. opts%external_fluid) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: static_current needs the host fluid field '// & '(external_fluid)'); RETURN END IF - IF (SIZE(static_current, 1) /= 4 .OR. SIZE(static_current, 2) < 2) THEN + IF (SIZE(host_static_current, 1) /= 4 .OR. SIZE(host_static_current, 2) < 2) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: static_current must be shaped (4, n >= 2): '// & 'z, ux, uy, uz'); RETURN END IF - IF (.NOT. ALL(IEEE_IS_FINITE(static_current))) THEN + IF (.NOT. ALL(IEEE_IS_FINITE(host_static_current))) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: static_current must be finite'); RETURN END IF - IF (ANY(static_current(1, 2:) <= static_current(1, :SIZE(static_current, 2) - 1))) THEN + IF (ANY(host_static_current(1, 2:) <= host_static_current(1, :SIZE(host_static_current, 2) - 1))) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: static_current levels must ascend in z'); RETURN END IF IF (agg%host_current_enabled .AND. .NOT. (opts%has_current .OR. opts%has_current_profile)) THEN opts_static%has_current = .TRUE. opts_static%has_current_profile = .TRUE. - opts_static%current_profile_z = static_current(1, :) - opts_static%current_profile_velocity = static_current(2:4, :) + opts_static%current_profile_z = host_static_current(1, :) + opts_static%current_profile_velocity = host_static_current(2:4, :) END IF END IF @@ -9680,6 +9702,8 @@ SUBROUTINE CD_End_Deck_Aggregate(agg) agg%n_turbines = 0 agg%host_wave_enabled = .FALSE. agg%host_current_enabled = .FALSE. + agg%host_wave_nodewise = .FALSE. + agg%wave_kin_tol = 1.0e-6_wp agg%cable_load_feedback = .TRUE. agg%predict_loads = .TRUE. agg%wave_grid_warn = .FALSE. @@ -10018,17 +10042,73 @@ SUBROUTINE CD_Run_Deck_Driver(deck_path, out_root, converged, ErrStat, ErrMsg) LOGICAL, INTENT(OUT) :: converged INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg - CALL run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg) + TYPE(CD_Prov) :: prov + INTEGER :: prov_es + CHARACTER(1024) :: prov_em + CALL run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg, prov) + ! the provenance record .CD.provenance.json (CableDyn_Provenance), written by the run at + ! its start and completed here, also after an error + IF (LEN_TRIM(prov%host) > 0) THEN + IF (ErrStat == CD_DECKDRV_OK) THEN + CALL CD_Prov_Write(prov, TRIM(out_root)//'.CD.provenance.json', 'complete', prov_es, prov_em) + ELSE + CALL CD_Prov_Write(prov, TRIM(out_root)//'.CD.provenance.json', 'stopped', prov_es, prov_em) + END IF + IF (prov_es /= 0) WRITE (output_unit, '(A)') ' Note: '//TRIM(prov_em) + END IF ! the verification probe serves one run, whichever route it took and however it ended probe_armed = .FALSE. END SUBROUTINE CD_Run_Deck_Driver - SUBROUTINE run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg) - !! CD_Run_Deck_Driver's body. + SUBROUTINE standalone_provenance(opts, lines, prov) + !! The provenance record of a standalone run (CableDyn_Provenance): the deck's own sea -- a + !! waves row's height, period, direction and, for a JONSWAP row, its WaveSeed; spreading makes + !! it short-crested -- and one entry per line. A WaterKin file or wave trains give the route + !! "deck" with the values the record cannot state as one sea left null. No grid, no guard. + TYPE(DeckOptions), INTENT(IN) :: opts + TYPE(DeckLine), INTENT(IN) :: lines(:) + TYPE(CD_Prov), INTENT(OUT) :: prov + INTEGER :: i + prov%cabledyn_version = CD_Version() + prov%host = 'standalone' + prov%route = 'none' + IF (opts%has_wave) THEN + prov%route = 'deck' + IF (opts%wave_kind == WAVE_AIRY .OR. opts%wave_kind == WAVE_JONSWAP .OR. opts%wave_kind == WAVE_STREAM) THEN + prov%has_hs = .TRUE. + prov%hs = opts%wave_height + prov%has_tp = .TRUE. + prov%tp = opts%wave_period + prov%has_dir = .TRUE. + prov%dir = opts%wave_direction + prov%has_dir_mod = .TRUE. + prov%dir_mod = MERGE(1, 0, opts%wave_spreading > CD_ZERO) + IF (opts%wave_kind == WAVE_JONSWAP) THEN + prov%has_seed = .TRUE. + prov%seed(1) = int_to_str(opts%wave_seed) + END IF + END IF + END IF + IF (opts%has_wtrdpth) THEN + prov%has_depth = .TRUE. + prov%depth = opts%wtrdpth + END IF + ALLOCATE (prov%lines(SIZE(lines))) + DO i = 1, SIZE(lines) + prov%lines(i)%id = lines(i)%id + ALLOCATE (prov%lines(i)%flags(0)) + END DO + END SUBROUTINE standalone_provenance + + SUBROUTINE run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg, prov) + !! CD_Run_Deck_Driver's body; prov receives the provenance record of the run. CHARACTER(*), INTENT(IN) :: deck_path, out_root LOGICAL, INTENT(OUT) :: converged INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg + TYPE(CD_Prov), INTENT(OUT) :: prov + INTEGER :: prov_es + CHARACTER(1024) :: prov_em TYPE(DeckLineType), ALLOCATABLE :: types(:) TYPE(DeckBody), ALLOCATABLE :: bodies(:) @@ -10061,6 +10141,9 @@ SUBROUTINE run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg) CALL parse_deck(deck_path, types, bodies, rod_types, rods, points, lines, sections, opts, channels, & ErrStat, ErrMsg, failures=fails) IF (ErrStat /= 0) RETURN + CALL standalone_provenance(opts, lines, prov) + CALL CD_Prov_Write(prov, TRIM(out_root)//'.CD.provenance.json', 'init', prov_es, prov_em) + IF (prov_es /= 0) WRITE (output_unit, '(A)') ' Note: '//TRIM(prov_em) CALL deck_start_notes(lines, channels, opts, opts%has_dtm .AND. opts%has_tmax .AND. opts%tmax > CD_ZERO, .TRUE.) IF (ANY([(line_torsion_active(lines(li)), li=1, SIZE(lines))])) THEN IF (opts%has_tmax .AND. opts%tmax > CD_ZERO .AND. .NOT. opts%alpha_force_blend) THEN @@ -19127,6 +19210,15 @@ SUBROUTINE apply_option(line, opts, ErrStat, ErrMsg) END SELECT CASE ('cable_load_feedback', 'cableloadfeedback') CALL rd_bool(val, opts%cable_load_feedback, ErrStat, ErrMsg) + CASE ('wavekintol', 'wave_kin_tol') + CALL rd(val, x1, ErrStat, ErrMsg) + IF (ErrStat == 0) THEN + IF (.NOT. (x1 >= CD_ZERO .AND. x1 < CD_ONE)) THEN + CALL fail(ErrStat, ErrMsg, 'OPTION waveKinTol must be at least 0 and below 1') + ELSE + opts%wave_kin_tol = x1 + END IF + END IF CASE ('predict_loads', 'predictloads') CALL rd_bool(val, opts%predict_loads, ErrStat, ErrMsg) CASE ('wavegridcheck', 'wave_grid_check') @@ -19338,7 +19430,11 @@ SUBROUTINE apply_option(line, opts, ErrStat, ErrMsg) ! Dequote FIRST, then classify: a quoted reserved value ("SEASTATE", "none") ! must hit its keyword branch, never the filename path. dval = strip_quotes(val) - IF (to_lower(TRIM(dval)) == 'seastate') THEN + ! SEASTATE and SEASTATE_GRID take the host field on its grid, SEASTATE_SPECTRAL evaluates the + ! host's wave components at the nodes (the OpenFAST module; see CD_AGG_ModuleType%host_wave_nodewise) + opts%waterkin_nodewise = to_lower(TRIM(dval)) == 'seastate_spectral' + IF (to_lower(TRIM(dval)) == 'seastate' .OR. to_lower(TRIM(dval)) == 'seastate_grid' .OR. & + opts%waterkin_nodewise) THEN ! Defer the coupled-only contract until the entry point has supplied its ! external_fluid capability. This lets stock MoorDyn-F decks containing ! `SEASTATE WaterKin` pass unchanged through the OpenFAST facade while the diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index 80e7ddf3..57c56f52 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -216,6 +216,11 @@ MODULE CableDyn_OpenFAST_Aggregate LOGICAL :: built_extfluid = .FALSE. ! Init declared host-driven ambient fluid (external_fluid) LOGICAL :: host_wave_enabled = .FALSE. LOGICAL :: host_current_enabled = .FALSE. + ! WaterKin SEASTATE_SPECTRAL: the OpenFAST shell evaluates the host wave components at the + ! nodes (CableDyn_WaveNodewise) instead of interpolating the SeaState grid; wave_kin_tol is its + ! truncation tolerance (OPTION waveKinTol) + LOGICAL :: host_wave_nodewise = .FALSE. + REAL(wp) :: wave_kin_tol = 1.0e-6_wp REAL(wp), ALLOCATABLE :: host_current_profile_z(:) REAL(wp), ALLOCATABLE :: host_current_profile_velocity(:, :) ! FAST.Farm: turbine count (0 = plain mode) and the driving turbine per moving slot @@ -308,7 +313,8 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi ptfm_init, external_fluid, coupled_positions, & n_turbines, turbine_ref_pos, farm_ptfm_init, forbid_deck_ambient, run_tmax, & range_files, host_orientation, static_current, prescribed_motion, static_run, & - deck_current, deck_turbines, static_deck_current, range_discard_root) + deck_current, deck_turbines, static_deck_current, range_discard_root, & + static_current_nodewise) !! Build the aggregate from ONE mixed deck: partition its lines into {EI=0 mooring} !! and {finite-EI cable}, wrap the mooring subset into a CD_FMF, and own one CD_HFMF !! per cable. Same signature philosophy as CD_FMF_Init_From_Deck (host environment @@ -350,8 +356,9 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi ! which a finite-EI line restrained in torsion requires (see CD_Init_Deck_Aggregate) LOGICAL, INTENT(IN), OPTIONAL :: host_orientation ! static_current (4, n): the host's steady current (z, ux, uy, uz by ascending z) for the - ! static solves only (see CD_Init_Deck_Aggregate) - REAL(wp), INTENT(IN), OPTIONAL :: static_current(:, :) + ! static solves only (see CD_Init_Deck_Aggregate); static_current_nodewise, the same + ! current for a deck on WaterKin SEASTATE_SPECTRAL + REAL(wp), INTENT(IN), OPTIONAL :: static_current(:, :), static_current_nodewise(:, :) ! prescribed_motion: the caller marches the deck's own motionFile or vesselMotion table ! (CD_AGG_MotionKinematics; the standalone driver, see CD_Init_Deck_Aggregate) LOGICAL, INTENT(IN), OPTIONAL :: prescribed_motion @@ -415,12 +422,15 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi static_current=static_current, prescribed_motion=prescribed_motion, & static_run=static_run, deck_current=deck_current, & deck_turbines=deck_turbines, static_deck_current=static_deck_current, & - range_discard_root=range_discard_root) + range_discard_root=range_discard_root, & + static_current_nodewise=static_current_nodewise) IF (PRESENT(external_fluid)) THEN candidate%built_extfluid = external_fluid END IF candidate%host_wave_enabled = parts%host_wave_enabled candidate%host_current_enabled = parts%host_current_enabled + candidate%host_wave_nodewise = parts%host_wave_nodewise + candidate%wave_kin_tol = parts%wave_kin_tol candidate%cable_load_feedback = parts%cable_load_feedback candidate%predict_loads = parts%predict_loads candidate%wave_grid_warn = parts%wave_grid_warn diff --git a/src/CableDyn_PathIO.f90 b/src/CableDyn_PathIO.f90 index 500cee6d..f05180e1 100644 --- a/src/CableDyn_PathIO.f90 +++ b/src/CableDyn_PathIO.f90 @@ -14,7 +14,7 @@ MODULE CableDyn_PathIO PRIVATE PUBLIC :: CD_Get_Argument, CD_Native_Path, CD_Open_Input, CD_Open_Read, CD_Open_Write, CD_Path_Openable - PUBLIC :: CD_Path_Is_Device, CD_Lock_Path + PUBLIC :: CD_Path_Is_Device, CD_Lock_Path, CD_Path_Replace PUBLIC :: CD_Strip_BOM !> CD_Native_Path status: converted, a reserved device name, a name the ANSI code @@ -68,6 +68,12 @@ FUNCTION c_path_probe(in, in_len, for_output) RESULT(n) BIND(C, name='cabledyn_p INTEGER(C_INT), VALUE :: in_len, for_output INTEGER(C_INT) :: n END FUNCTION c_path_probe + FUNCTION c_path_replace(a, a_len, b, b_len) RESULT(n) BIND(C, name='cabledyn_path_replace') + IMPORT :: C_INT, C_CHAR + CHARACTER(KIND=C_CHAR), INTENT(IN) :: a(*), b(*) + INTEGER(C_INT), VALUE :: a_len, b_len + INTEGER(C_INT) :: n + END FUNCTION c_path_replace END INTERFACE CONTAINS @@ -210,6 +216,14 @@ SUBROUTINE CD_Open_Write(unit, name, ios, status) END IF END SUBROUTINE CD_Open_Write + LOGICAL FUNCTION CD_Path_Replace(from, to) RESULT(ok) + !! Move the file `from` over `to` in one step (MoveFileEx with replacement on Windows, rename + !! elsewhere), both runtime spellings as an OPEN takes them; .FALSE. when it fails, and then + !! `from` is removed. On Windows a reader holding `to` open is waited for up to a second. + CHARACTER(*), INTENT(IN) :: from, to + ok = c_path_replace(from, INT(LEN_TRIM(from), C_INT), to, INT(LEN_TRIM(to), C_INT)) == 0_C_INT + END FUNCTION CD_Path_Replace + LOGICAL FUNCTION CD_Path_Openable(name, for_output) RESULT(openable) !! Whether the system opens name (a runtime spelling, trailing blanks ignored) for !! reading an existing file or, with for_output, for writing (a missing file is then diff --git a/src/CableDyn_Provenance.f90 b/src/CableDyn_Provenance.f90 new file mode 100644 index 00000000..b7bcd258 --- /dev/null +++ b/src/CableDyn_Provenance.f90 @@ -0,0 +1,353 @@ +! File: src/CableDyn_Provenance.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +MODULE CableDyn_Provenance + !! The provenance sidecar .CD.provenance.json (schema "cabledyn.provenance/1"): a + !! machine-readable record of the run that produced a CableDyn output -- the host, the wave + !! route and the sea it took, the SeaState grid on the grid route, and per line the guard's + !! out-of-grid and resolution findings and the variances the node-wise route dropped -- for a + !! downstream tool (a cross-section analysis) to judge whether the line results it reads are + !! fit for use. It is written at initialisation (status "init") and rewritten at the end of + !! the run (status "complete"), each time to a temporary file that then replaces the record, + !! so a reader never sees half a file. A value CableDyn does not know is null, never guessed. + !! + !! The sea's component fingerprint identifies the sea exactly without its seed: FNV-1a 64-bit + !! over the bytes of the host's components as stored (CD_Fingerprint_*), so two runs on the + !! same sea carry the same fingerprint. + USE CableDyn_Precision, ONLY: wp + USE CableDyn_PathIO, ONLY: CD_Open_Write, CD_Path_Replace + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT8, INT64, REAL32 + IMPLICIT NONE + PRIVATE + + PUBLIC :: CD_ProvLine, CD_Prov, CD_Prov_Write, CD_Fingerprint, CD_Fingerprint_Init, CD_Fingerprint_Add, & + CD_Fingerprint_Hex + + CHARACTER(*), PARAMETER, PUBLIC :: CD_PROV_SCHEMA = 'cabledyn.provenance/1' + + !> per line; a negative count, an empty string or has_* = .FALSE. writes null + TYPE :: CD_ProvLine + INTEGER :: id = 0 + INTEGER :: n_nodes = 0 + LOGICAL :: has_oog = .FALSE. !< the guard found nodes of the line outside the grid + INTEGER :: oog_n_nodes_max = 0 + REAL(wp) :: oog_first_time = 0.0_wp + REAL(wp) :: oog_deepest(3) = 0.0_wp, oog_shallowest(3) = 0.0_wp + LOGICAL :: has_wvr = .FALSE. !< the weighted velocity ratio is known (wave components) + REAL(wp) :: wvr = 0.0_wp !< rms wave velocity at the shallowest outside node / surface + CHARACTER(64), ALLOCATABLE :: flags(:) !< resolution flags of the line + LOGICAL :: has_drop = .FALSE. !< node-wise route: the dropped variances + REAL(wp) :: drop_v_max = 0.0_wp, drop_a_max = 0.0_wp + END TYPE CD_ProvLine + + TYPE :: CD_Prov + CHARACTER(32) :: cabledyn_version = '' + CHARACTER(16) :: host = '' !< openfast | fast.farm | standalone | capi + CHARACTER(64) :: host_version = '' + CHARACTER(24) :: route = 'none' !< seastate_grid | seastate_spectral | deck | none + LOGICAL :: has_wave_mod = .FALSE. + INTEGER :: wave_mod = 0 + LOGICAL :: has_seed = .FALSE. + CHARACTER(32) :: seed(2) = '' + LOGICAL :: has_hs = .FALSE., has_tp = .FALSE., has_dir = .FALSE., has_dir_mod = .FALSE. + REAL(wp) :: hs = 0.0_wp, tp = 0.0_wp, dir = 0.0_wp + INTEGER :: dir_mod = 0 + LOGICAL :: has_ncomp = .FALSE., has_wave_dt = .FALSE., has_wave_tmax = .FALSE., has_depth = .FALSE. + INTEGER :: ncomp = 0 + REAL(wp) :: wave_dt = 0.0_wp, wave_tmax = 0.0_wp, depth = 0.0_wp + LOGICAL :: has_tol = .FALSE. + REAL(wp) :: tol = 0.0_wp + CHARACTER(1024) :: source_file = '' + CHARACTER(16) :: fingerprint = '' + LOGICAL :: has_grid = .FALSE. + INTEGER :: nx = 0, ny = 0, nz = 0 + REAL(wp) :: x_half_width = 0.0_wp, y_half_width = 0.0_wp, z_depth = 0.0_wp + CHARACTER(8) :: grid_check = 'error' + LOGICAL :: has_restart = .FALSE. !< the run was restarted from a checkpoint + REAL(wp) :: restarted_from = 0.0_wp !< at this time (s) + TYPE(CD_ProvLine), ALLOCATABLE :: lines(:) + END TYPE CD_Prov + + !> FNV-1a 64-bit as four 16-bit limbs, least significant first (exact integer arithmetic) + TYPE :: CD_Fingerprint + INTEGER(INT64) :: limb(4) = [INT(Z'2325', INT64), INT(Z'8422', INT64), INT(Z'9CE4', INT64), INT(Z'CBF2', INT64)] + LOGICAL :: used = .FALSE. + END TYPE CD_Fingerprint + +CONTAINS + + PURE SUBROUTINE CD_Fingerprint_Init(h) + TYPE(CD_Fingerprint), INTENT(OUT) :: h + h%limb = [INT(Z'2325', INT64), INT(Z'8422', INT64), INT(Z'9CE4', INT64), INT(Z'CBF2', INT64)] + h%used = .FALSE. + END SUBROUTINE CD_Fingerprint_Init + + PURE SUBROUTINE CD_Fingerprint_Add(h, x) + !! Hash the bytes of the single-precision values x, in array element order, each value's + !! bytes as stored (little-endian IEEE on x86-64 and arm64): for every byte b, + !! h = (h XOR b) * 1099511628211 mod 2^64. + TYPE(CD_Fingerprint), INTENT(INOUT) :: h + REAL(REAL32), INTENT(IN) :: x(:) + INTEGER(INT8), ALLOCATABLE :: bytes(:) + INTEGER :: i + IF (SIZE(x) == 0) RETURN + bytes = TRANSFER(x, [0_INT8]) + DO i = 1, SIZE(bytes) + h%limb(1) = IEOR(h%limb(1), IAND(INT(bytes(i), INT64), 255_INT64)) + CALL times_prime(h%limb) + END DO + h%used = .TRUE. + END SUBROUTINE CD_Fingerprint_Add + + PURE FUNCTION CD_Fingerprint_Hex(h) RESULT(s) + !! The hash as 16 lower-case hexadecimal digits. + TYPE(CD_Fingerprint), INTENT(IN) :: h + CHARACTER(16) :: s + CHARACTER(16), PARAMETER :: HEX = '0123456789abcdef' + INTEGER :: k, d, j + INTEGER(INT64) :: v + DO k = 1, 4 + v = h%limb(5 - k) + DO j = 1, 4 + d = INT(IAND(ISHFT(v, -4*(4 - j)), 15_INT64)) + s(4*(k - 1) + j:4*(k - 1) + j) = HEX(d + 1:d + 1) + END DO + END DO + END FUNCTION CD_Fingerprint_Hex + + PURE SUBROUTINE times_prime(a) + !! a = a * 0x100000001b3 mod 2^64 on 16-bit limbs (the prime's limbs: 0x01b3, 0, 0x0100, 0) + INTEGER(INT64), INTENT(INOUT) :: a(4) + INTEGER(INT64) :: r(4), carry + INTEGER :: k + r(1) = a(1)*435_INT64 + r(2) = a(2)*435_INT64 + r(3) = a(3)*435_INT64 + a(1)*256_INT64 + r(4) = a(4)*435_INT64 + a(2)*256_INT64 + carry = 0_INT64 + DO k = 1, 4 + r(k) = r(k) + carry + carry = ISHFT(r(k), -16) + r(k) = IAND(r(k), 65535_INT64) + END DO + a = r + END SUBROUTINE times_prime + + SUBROUTINE CD_Prov_Write(prov, path, status, ErrStat, ErrMsg) + !! Write the record with `status` ("init" or "complete") to path: to path//'.tmp' first, + !! which then replaces path. ErrStat /= 0 when either step fails (the run goes on; the + !! caller reports it). + TYPE(CD_Prov), INTENT(IN) :: prov + CHARACTER(*), INTENT(IN) :: path, status + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + INTEGER :: un, ios, i, k + CHARACTER(:), ALLOCATABLE :: tmp + LOGICAL :: replaced + CHARACTER(*), PARAMETER :: I2 = ' ', I4 = ' ', I6 = ' ', I8 = ' ' + + ErrStat = 0 + ErrMsg = '' + tmp = TRIM(path)//'.tmp' + CALL CD_Open_Write(un, tmp, ios) + IF (ios /= 0) THEN + ErrStat = 1 + ErrMsg = 'could not write the provenance record '//tmp + RETURN + END IF + WRITE (un, '(A)') '{' + WRITE (un, '(A)') I2//'"schema": '//js(CD_PROV_SCHEMA)//',' + WRITE (un, '(A)') I2//'"cabledyn_version": '//js(prov%cabledyn_version)//',' + WRITE (un, '(A)') I2//'"host": '//js(prov%host)//',' + WRITE (un, '(A)') I2//'"host_version": '//js(prov%host_version)//',' + WRITE (un, '(A)') I2//'"waves": {' + WRITE (un, '(A)') I4//'"route": '//js(prov%route)//',' + WRITE (un, '(A)') I4//'"wave_mod": '//ji(prov%wave_mod, prov%has_wave_mod)//',' + IF (prov%has_seed) THEN + WRITE (un, '(A)') I4//'"wave_seed": ['//seed_value(prov%seed(1))//', '//seed_value(prov%seed(2))//'],' + ELSE + WRITE (un, '(A)') I4//'"wave_seed": null,' + END IF + WRITE (un, '(A)') I4//'"wave_hs": '//jr(prov%hs, prov%has_hs)//',' + WRITE (un, '(A)') I4//'"wave_tp": '//jr(prov%tp, prov%has_tp)//',' + WRITE (un, '(A)') I4//'"wave_dir_deg": '//jr(prov%dir, prov%has_dir)//',' + WRITE (un, '(A)') I4//'"wave_dir_mod": '//ji(prov%dir_mod, prov%has_dir_mod)//',' + WRITE (un, '(A)') I4//'"n_components": '//ji(prov%ncomp, prov%has_ncomp)//',' + WRITE (un, '(A)') I4//'"component_fingerprint": '//js(prov%fingerprint)//',' + WRITE (un, '(A)') I4//'"wave_dt": '//jr_single(prov%wave_dt, prov%has_wave_dt)//',' + WRITE (un, '(A)') I4//'"wave_tmax": '//jr_single(prov%wave_tmax, prov%has_wave_tmax)//',' + WRITE (un, '(A)') I4//'"effective_water_depth": '//jr(prov%depth, prov%has_depth)//',' + WRITE (un, '(A)') I4//'"wave_kin_tol": '//jr(prov%tol, prov%has_tol)//',' + WRITE (un, '(A)') I4//'"source_file": '//js(prov%source_file) + WRITE (un, '(A)') I2//'},' + IF (prov%has_grid) THEN + WRITE (un, '(A)') I2//'"grid": {' + WRITE (un, '(A)') I4//'"nx": '//ji(prov%nx, .TRUE.)//', "ny": '//ji(prov%ny, .TRUE.)//', "nz": '// & + ji(prov%nz, .TRUE.)//',' + WRITE (un, '(A)') I4//'"x_half_width": '//jr(prov%x_half_width, .TRUE.)//', "y_half_width": '// & + jr(prov%y_half_width, .TRUE.)//', "z_depth": '//jr(prov%z_depth, .TRUE.)//',' + WRITE (un, '(A)') I4//'"wave_grid_check": '//js(prov%grid_check) + WRITE (un, '(A)') I2//'},' + ELSE + WRITE (un, '(A)') I2//'"grid": null,' + END IF + WRITE (un, '(A)') I2//'"lines": [' + IF (ALLOCATED(prov%lines)) THEN + DO i = 1, SIZE(prov%lines) + ASSOCIATE (ln => prov%lines(i)) + WRITE (un, '(A)') I4//'{' + WRITE (un, '(A)') I6//'"id": '//ji(ln%id, .TRUE.)//', "n_nodes": '//ji(ln%n_nodes, ln%n_nodes > 0)//',' + IF (ln%has_oog) THEN + WRITE (un, '(A)') I6//'"out_of_grid": {' + WRITE (un, '(A)') I8//'"n_nodes_max": '//ji(ln%oog_n_nodes_max, .TRUE.)//', "first_time": '// & + jr(ln%oog_first_time, .TRUE.)//',' + WRITE (un, '(A)') I8//'"deepest_xyz": '//jvec(ln%oog_deepest)//', "shallowest_xyz": '// & + jvec(ln%oog_shallowest)//',' + WRITE (un, '(A)') I8//'"weighted_velocity_ratio_max": '//jr(ln%wvr, ln%has_wvr) + WRITE (un, '(A)') I6//'},' + ELSE + WRITE (un, '(A)') I6//'"out_of_grid": null,' + END IF + IF (ALLOCATED(ln%flags)) THEN + IF (SIZE(ln%flags) > 0) THEN + WRITE (un, '(A)', ADVANCE='NO') I6//'"resolution_flags": [' + DO k = 1, SIZE(ln%flags) + IF (k > 1) WRITE (un, '(A)', ADVANCE='NO') ', ' + WRITE (un, '(A)', ADVANCE='NO') js(ln%flags(k)) + END DO + WRITE (un, '(A)') '],' + ELSE + WRITE (un, '(A)') I6//'"resolution_flags": [],' + END IF + ELSE + WRITE (un, '(A)') I6//'"resolution_flags": [],' + END IF + WRITE (un, '(A)') I6//'"dropped_velocity_variance_max": '//jr(ln%drop_v_max, ln%has_drop)//',' + WRITE (un, '(A)') I6//'"dropped_acceleration_variance_max": '//jr(ln%drop_a_max, ln%has_drop) + IF (i < SIZE(prov%lines)) THEN + WRITE (un, '(A)') I4//'},' + ELSE + WRITE (un, '(A)') I4//'}' + END IF + END ASSOCIATE + END DO + END IF + WRITE (un, '(A)') I2//'],' + WRITE (un, '(A)') I2//'"restarted_from": '//jr(prov%restarted_from, prov%has_restart)//',' + WRITE (un, '(A)') I2//'"status": '//js(status) + WRITE (un, '(A)') '}' + CLOSE (un, IOSTAT=ios) + replaced = .FALSE. + IF (ios == 0) replaced = CD_Path_Replace(tmp, TRIM(path)) + IF (.NOT. replaced) THEN + ErrStat = 1 + ErrMsg = 'could not replace the provenance record '//TRIM(path) + END IF + END SUBROUTINE CD_Prov_Write + + ! --------------------------------------------------------------------------------------------- + + FUNCTION js(s) RESULT(o) + !! A JSON string, or null for an empty one; backslash, quote and control characters escaped. + CHARACTER(*), INTENT(IN) :: s + CHARACTER(:), ALLOCATABLE :: o + INTEGER :: i, c + CHARACTER(6) :: u + IF (LEN_TRIM(s) == 0) THEN + o = 'null' + RETURN + END IF + o = '"' + DO i = 1, LEN_TRIM(s) + c = IACHAR(s(i:i)) + IF (s(i:i) == '"' .OR. s(i:i) == '\') THEN + o = o//'\'//s(i:i) + ELSE IF (c < 32) THEN + WRITE (u, '(A,Z4.4)') '\u', c + o = o//u + ELSE + o = o//s(i:i) + END IF + END DO + o = o//'"' + END FUNCTION js + + FUNCTION seed_value(s) RESULT(o) + !! A wave seed as written: a JSON number when it is an integer, else a string. + CHARACTER(*), INTENT(IN) :: s + CHARACTER(:), ALLOCATABLE :: o + CHARACTER(:), ALLOCATABLE :: t + INTEGER :: k + t = TRIM(ADJUSTL(s)) + k = 1 + IF (LEN(t) > 0) THEN + IF (t(1:1) == '+' .OR. t(1:1) == '-') k = 2 + END IF + IF (LEN(t) >= k) THEN + IF (VERIFY(t(k:), '0123456789') == 0) THEN + o = t + IF (o(1:1) == '+') o = o(2:) + RETURN + END IF + END IF + o = js(t) + END FUNCTION seed_value + + FUNCTION ji(v, has) RESULT(o) + INTEGER, INTENT(IN) :: v + LOGICAL, INTENT(IN) :: has + CHARACTER(:), ALLOCATABLE :: o + CHARACTER(24) :: b + IF (.NOT. has) THEN + o = 'null' + RETURN + END IF + WRITE (b, '(I0)') v + o = TRIM(b) + END FUNCTION ji + + FUNCTION jr(v, has) RESULT(o) + !! A JSON number with 17 significant digits (the value round-trips), or null. + REAL(wp), INTENT(IN) :: v + LOGICAL, INTENT(IN) :: has + CHARACTER(:), ALLOCATABLE :: o + CHARACTER(32) :: b + IF (.NOT. has .OR. .NOT. (ABS(v) <= HUGE(v))) THEN + o = 'null' + RETURN + END IF + WRITE (b, '(ES24.16E3)') v + o = TRIM(ADJUSTL(b)) + END FUNCTION jr + + FUNCTION jr_single(v, has) RESULT(o) + !! A value SeaState holds in single precision (its wave step) as the shortest number that + !! reads back to the same single-precision value (0.2, not 0.200000003), or null. + REAL(wp), INTENT(IN) :: v + LOGICAL, INTENT(IN) :: has + CHARACTER(:), ALLOCATABLE :: o + CHARACTER(32) :: b + CHARACTER(16) :: fmt + REAL(REAL32) :: s, back + INTEGER :: d, ios + IF (.NOT. has .OR. .NOT. (ABS(v) <= REAL(HUGE(s), wp))) THEN + o = 'null' + RETURN + END IF + s = REAL(v, REAL32) + DO d = 1, 9 + WRITE (fmt, '(A,I0,A)') '(ES30.', d, 'E3)' + WRITE (b, fmt) s + READ (b, *, IOSTAT=ios) back + IF (ios == 0 .AND. .NOT. (ABS(back - s) > 0.0_REAL32)) EXIT + END DO + o = TRIM(ADJUSTL(b)) + END FUNCTION jr_single + + FUNCTION jvec(v) RESULT(o) + REAL(wp), INTENT(IN) :: v(3) + CHARACTER(:), ALLOCATABLE :: o + o = '['//jr(v(1), .TRUE.)//', '//jr(v(2), .TRUE.)//', '//jr(v(3), .TRUE.)//']' + END FUNCTION jvec + +END MODULE CableDyn_Provenance diff --git a/src/CableDyn_WaveNodewise.f90 b/src/CableDyn_WaveNodewise.f90 new file mode 100644 index 00000000..503cf4e9 --- /dev/null +++ b/src/CableDyn_WaveNodewise.f90 @@ -0,0 +1,696 @@ +! File: src/CableDyn_WaveNodewise.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +MODULE CableDyn_WaveNodewise + !! First-order wave kinematics evaluated at a point from a host's wave components, without a + !! grid: the node-wise route of the OpenFAST module (WaterKin SEASTATE_SPECTRAL). The components + !! are SeaState's own (WaveElevC0, WaveDirArr, its wavenumbers), and the sums reproduce the + !! inverse real FFT with which SeaState fills its grid, so at a grid vertex and a wave step the + !! values equal the grid's. With N = NStepWave, omega_i = 2 pi i/(N WaveDT) and + !! theta_i = omega_i t - k_i (x cos beta_i + y sin beta_i): + !! + !! eta = (1/N) Re C_0 + sum_i Re(A_i e^{j theta_i}), A_i = w_i C_i/N, + !! w_i = 2, and 1 for the component at the Nyquist frequency (i = N/2); + !! u, v = sum cos/sin beta_i omega_i D1_i(z) Re(A_i e^{j theta_i}), + !! w = -sum omega_i D2_i(z) Im(A_i e^{j theta_i}), + !! a = the time derivative of the velocity (a factor j omega_i), + !! pdyn = rho g [(1/N) Re C_0 + sum D3_i(z) Re(A_i e^{j theta_i})], + !! + !! with D1 = cosh k(z+h)/sinh kh, D2 = sinh k(z+h)/sinh kh, D3 = cosh k(z+h)/cosh kh, written as + !! (e^{kz} +- e^{-k(z+2h)})/(1 -+ e^{-2kh}) so that deep components do not overflow. The + !! component at zero frequency carries no velocity (SeaState gives it 0 * HUGE = 0). + !! + !! Stretching follows SeaState's access rules (SeaSt_WaveField WaveField_GetNodeWaveKin, called + !! with the node forced into the water): WaveStMod 0 evaluates at min(z, 0) (the caller zeroes + !! a node above the still-water level); 1 at min(z, 0); 2 above the still-water level the value + !! at z = 0 plus z times its vertical derivative there (SeaState's PWave*0 terms); 3 at the + !! Wheeler depth z' = h (h + z)/(h + eta) - h, at most 0. A node below the seabed takes the + !! seabed values (SeaState's grid clamps there). + !! + !! Time: the field is evaluated at the two wave steps t_n = n WaveDT and t_n+1 that bracket the + !! sample time, at one position per node and interval (the caller's choice), with the exact time + !! derivatives (under Wheeler stretching including the motion of the mapped depth), and + !! interpolated between them by cubic Hermite polynomials (CD_NWK_Hermite). + !! + !! Truncation: the components are sorted by wavenumber. A node at depth z keeps the shortest + !! prefix whose dropped velocity variance, sum 0.5 omega^2 |A|^2 D1(z)^2 over the dropped + !! components, is at most tol times the velocity variance of all components at that depth, and + !! whose dropped acceleration variance (omega^4) is at most tol times its own total there. The + !! prefix is tabulated on NLEV depth levels from the seabed to the surface. A dropped component + !! has a larger wavenumber than every kept one and decays faster with depth, so the dropped share + !! of a prefix only falls with depth: a node takes the prefix of the level at or above the + !! shallowest depth it can reach, and both bounds hold at every depth it reaches. tol = 0 keeps + !! every component. + !! + !! Under Wheeler stretching the elevation sets the mapped depth, z' = h (h + z)/(h + eta) - h, of + !! the kept components, and a short wave too short to reach the node still moves the surface. + !! The elevation there is summed over its own prefix, at least the kept one: an elevation error + !! d eta moves z' by (h + z')/(h + eta) d eta and the kept velocity by its vertical gradient + !! times that, so the prefix is the shortest one for which the variance of that velocity error, + !! sum k^2 (D1^2 + D2^2) |A|^2 omega^2 / 2 over the kept components times ((h + z')/(h + eta_min))^2 + !! times the dropped elevation variance, is at most tol times the velocity variance at z', and + !! the same for the acceleration (weights omega^4, and the dropped elevation rate through the + !! moving depth). Both factors fall with depth, so the prefix of the node's shallowest mapped + !! depth serves every depth it reaches. It is tabulated with the kept prefix (pe_of_p). Without + !! Wheeler stretching the elevation only decides the wetting, of a node near the surface that + !! keeps nearly every component, and takes the kept prefix. + !! + !! Cost per node and wave step: one block sine/cosine of the position phase over the retained + !! components (CD_Wave_SinCos), and one or two block exponentials (two under Wheeler + !! stretching, at each end's mapped depth), then the sums, each in CD_WAVE_LANES interleaved + !! partial sums added in a fixed order (CD_Wave_Sum_Lanes): the result does not depend on the + !! thread count or the compiler's vector width. No allocation after CD_NWK_Init. The field holds + !! the workspaces of the evaluation, so CD_NWK_Eval is not reentrant: one field serves one thread + !! at a time (the OpenFAST module evaluates its nodes in turn). + USE CableDyn_Precision, ONLY: wp + USE CableDyn_WaveMath, ONLY: CD_Wave_SinCos, CD_Wave_Exp, CD_Wave_Sum_Lanes, CD_WAVE_LANES + IMPLICIT NONE + PRIVATE + + PUBLIC :: CD_NWK_Field, CD_NWK_Init, CD_NWK_Set_Step, CD_NWK_Set_Times, CD_NWK_Eval, CD_NWK_Hermite + PUBLIC :: CD_NWK_Prefix, CD_NWK_Dropped, CD_NWK_End, CD_NWK_Velocity_Ratio + + INTEGER, PARAMETER, PUBLIC :: CD_NWK_OK = 0, CD_NWK_BADINPUT = 1 + !> quantities: 1-3 velocity, 4-6 acceleration, 7 free-surface elevation, 8 dynamic pressure + INTEGER, PARAMETER, PUBLIC :: CD_NWK_NQ = 8 + INTEGER, PARAMETER :: NLEV = 1024 + REAL(wp), PARAMETER :: TWO_PI = 6.28318530717958647692_wp + REAL(wp), PARAMETER :: EX_FLUSH = -708.0_wp !< exponents at or below it give 0 (depth_factors) + INTEGER, PARAMETER, PUBLIC :: CD_NWK_MAX_COMPONENTS = 100000 !< the most components the route takes + + TYPE :: CD_NWK_Field + INTEGER :: m = 0 !< components with a nonzero amplitude + INTEGER :: stmod = 0 !< SeaState WaveStMod + INTEGER :: nstep = 0 !< SeaState NStepWave + REAL(wp) :: dt = 0.0_wp, h = 0.0_wp, rho_g = 0.0_wp, tol = 0.0_wp + REAL(wp) :: eta0 = 0.0_wp !< the zero-frequency term (1/N) Re C_0 + REAL(wp) :: zeta_bound = 0.0_wp !< |eta - eta0| <= zeta_bound + REAL(wp) :: var_v = 0.0_wp, var_a = 0.0_wp !< surface velocity and acceleration variances + ! the components, sorted by k + REAL(wp), ALLOCATABLE :: ar(:), ai(:), om(:), kk(:), cb(:), sb(:), dsh(:), dch(:), e2h(:) + INTEGER, ALLOCATABLE :: src(:) !< SeaState index of each component + ! the truncation table: prefix per depth level, uniform from -h (level 1) to 0 (level NLEV) + INTEGER, ALLOCATABLE :: plev(:) + ! the elevation prefix of a node that keeps p components (Wheeler stretching; else p) + INTEGER, ALLOCATABLE :: pe_of_p(:) + ! the wave step the time phasors hold, and the phasors exp(j omega t) at its two ends + INTEGER :: step = -HUGE(1) + REAL(wp) :: ta = 0.0_wp + REAL(wp), ALLOCATABLE :: ca(:), sa(:), cbe(:), sbe(:) + ! workspaces + REAL(wp), ALLOCATABLE :: th(:), cs(:), sn(:), ex(:), ee(:), rr(:, :), ii(:, :), d1(:), d2(:), d3(:), d4(:) + END TYPE CD_NWK_Field + +CONTAINS + + SUBROUTINE CD_NWK_Init(f, c_re, c_im, dir_deg, k, nstep, wave_dt, depth, rho, g, stmod, tol, ErrStat, ErrMsg) + !! Build the field from SeaState's components, indexed 0 .. N/2 as WaveElevC0(1:2, :), + !! WaveDirArr(:) (deg) and the wavenumbers k (SeaState's WaveNumber of each frequency, in + !! the depth `depth` = EffWtrDpth). + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + REAL(wp), INTENT(IN) :: c_re(0:), c_im(0:), dir_deg(0:), k(0:) + INTEGER, INTENT(IN) :: nstep, stmod + REAL(wp), INTENT(IN) :: wave_dt, depth, rho, g, tol + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + INTEGER :: n2, i, j, m, lev, p + INTEGER, ALLOCATABLE :: idx(:) + REAL(wp) :: wgt, d2r, a2, z, tail_v, tail_a, e, loc_v, loc_a + REAL(wp) :: lo, c2, gv, ga, e1, e2, gk, tail_e, tail_r + INTEGER :: pe + REAL(wp), ALLOCATABLE :: kv(:), wv(:), wa(:), ez(:), we(:), wr(:) + + ErrStat = CD_NWK_OK + ErrMsg = '' + CALL CD_NWK_End(f) + n2 = nstep/2 + IF (nstep < 2 .OR. MOD(nstep, 2) /= 0 .OR. .NOT. (wave_dt > 0.0_wp) .OR. .NOT. (depth > 0.0_wp) .OR. & + UBOUND(c_re, 1) < n2 .OR. UBOUND(c_im, 1) < n2 .OR. UBOUND(dir_deg, 1) < n2 .OR. UBOUND(k, 1) < n2 .OR. & + stmod < 0 .OR. stmod > 3 .OR. .NOT. (tol >= 0.0_wp .AND. tol < 1.0_wp)) THEN + ErrStat = CD_NWK_BADINPUT + ErrMsg = 'CD_NWK_Init: inconsistent wave components (NStepWave, WaveDT, depth, array bounds, WaveStMod or tol)' + RETURN + END IF + f%nstep = nstep + f%dt = wave_dt + f%h = depth + f%rho_g = rho*g + f%stmod = stmod + f%tol = tol + f%eta0 = c_re(0)/REAL(nstep, wp) + m = COUNT([(c_re(i)**2 + c_im(i)**2 > 0.0_wp, i=1, n2)]) + IF (m > CD_NWK_MAX_COMPONENTS) THEN + ErrStat = CD_NWK_BADINPUT + WRITE (ErrMsg, '(A,I0,A,I0,A)') 'CD_NWK_Init: ', m, ' wave components exceed the ', CD_NWK_MAX_COMPONENTS, & + ' the node-wise route takes (each node sums them at every wave step); shorten WaveTMax or narrow '// & + 'WvLowCOff to WvHiCOff' + RETURN + END IF + ALLOCATE (idx(m), kv(m)) + j = 0 + DO i = 1, n2 + IF (.NOT. (c_re(i)**2 + c_im(i)**2 > 0.0_wp)) CYCLE + IF (.NOT. (k(i) > 0.0_wp)) THEN + ErrStat = CD_NWK_BADINPUT + ErrMsg = 'CD_NWK_Init: a wave component has no positive wavenumber' + RETURN + END IF + j = j + 1 + idx(j) = i + kv(j) = k(i) + END DO + CALL sort_by_key(kv, idx) + f%m = m + ALLOCATE (f%ar(m), f%ai(m), f%om(m), f%kk(m), f%cb(m), f%sb(m), f%dsh(m), f%dch(m), f%e2h(m), f%src(m), & + f%ca(m), f%sa(m), f%cbe(m), f%sbe(m), f%th(m), f%cs(m), f%sn(m), f%ex(2*m), f%ee(2*m), & + f%rr(m, 2), f%ii(m, 2), f%d1(m), f%d2(m), f%d3(m), f%d4(m), f%plev(NLEV)) + d2r = TWO_PI/360.0_wp + f%zeta_bound = 0.0_wp + DO j = 1, m + i = idx(j) + wgt = 2.0_wp + IF (i == n2) wgt = 1.0_wp + f%src(j) = i + f%ar(j) = wgt*c_re(i)/REAL(nstep, wp) + f%ai(j) = wgt*c_im(i)/REAL(nstep, wp) + f%om(j) = TWO_PI*REAL(i, wp)/(REAL(nstep, wp)*wave_dt) + f%kk(j) = k(i) + f%cb(j) = COS(d2r*dir_deg(i)) + f%sb(j) = SIN(d2r*dir_deg(i)) + f%e2h(j) = EXP(-2.0_wp*k(i)*depth) + f%dsh(j) = 1.0_wp/(1.0_wp - f%e2h(j)) + f%dch(j) = 1.0_wp/(1.0_wp + f%e2h(j)) + f%zeta_bound = f%zeta_bound + SQRT(f%ar(j)**2 + f%ai(j)**2) + END DO + ! surface variances and the truncation table + ALLOCATE (wv(m), wa(m)) + f%var_v = 0.0_wp + f%var_a = 0.0_wp + DO j = 1, m + a2 = 0.5_wp*(f%ar(j)**2 + f%ai(j)**2) + wv(j) = a2*f%om(j)**2 + wa(j) = a2*f%om(j)**4 + e = (1.0_wp + f%e2h(j))*f%dsh(j) ! D1(0) = coth kh + f%var_v = f%var_v + wv(j)*e*e + f%var_a = f%var_a + wa(j)*e*e + END DO + ALLOCATE (ez(m)) + DO lev = 1, NLEV + IF (tol <= 0.0_wp .OR. m == 0) THEN + f%plev(lev) = m + CYCLE + END IF + z = -depth + depth*REAL(lev - 1, wp)/REAL(NLEV - 1, wp) + ! the variances at this depth: the bound is relative to them, not to the surface totals + loc_v = 0.0_wp + loc_a = 0.0_wp + DO j = 1, m + ez(j) = ((EXP(f%kk(j)*z) + EXP(-f%kk(j)*(z + 2.0_wp*depth)))*f%dsh(j))**2 + loc_v = loc_v + wv(j)*ez(j) + loc_a = loc_a + wa(j)*ez(j) + END DO + tail_v = 0.0_wp + tail_a = 0.0_wp + p = m + DO j = m, 1, -1 + IF (tail_v + wv(j)*ez(j) > tol*loc_v .OR. tail_a + wa(j)*ez(j) > tol*loc_a) EXIT + tail_v = tail_v + wv(j)*ez(j) + tail_a = tail_a + wa(j)*ez(j) + p = j - 1 + END DO + f%plev(lev) = p + END DO + ! a prefix never shrinks toward the surface (the table is monotone by construction; enforce it) + DO lev = 2, NLEV + f%plev(lev) = MAX(f%plev(lev), f%plev(lev - 1)) + END DO + ! the elevation prefix under Wheeler stretching (see the module header): at each level, of the + ! components beyond the kept prefix those whose elevation moves the mapped depth too little to + ! matter; per kept prefix the largest over the levels that give it + ALLOCATE (f%pe_of_p(0:m)) + f%pe_of_p = -1 + lo = depth + f%eta0 - f%zeta_bound ! h + eta at its lowest + IF (stmod == 3 .AND. tol > 0.0_wp .AND. m > 0 .AND. lo > 0.0_wp) THEN + ALLOCATE (we(m), wr(m)) + DO j = 1, m + we(j) = 0.5_wp*(f%ar(j)**2 + f%ai(j)**2) + wr(j) = we(j)*f%om(j)**2 + END DO + DO lev = 1, NLEV + z = -depth + depth*REAL(lev - 1, wp)/REAL(NLEV - 1, wp) + p = f%plev(lev) + loc_v = 0.0_wp + loc_a = 0.0_wp + gv = 0.0_wp + ga = 0.0_wp + DO j = 1, m + e1 = (EXP(f%kk(j)*z) + EXP(-f%kk(j)*(z + 2.0_wp*depth)))*f%dsh(j) + loc_v = loc_v + wv(j)*e1*e1 + loc_a = loc_a + wa(j)*e1*e1 + IF (j > p) CYCLE + e2 = (EXP(f%kk(j)*z) - EXP(-f%kk(j)*(z + 2.0_wp*depth)))*f%dsh(j) + gk = f%kk(j)**2*(e1*e1 + e2*e2) + gv = gv + wv(j)*gk + ga = ga + wa(j)*gk + END DO + c2 = ((depth + z)/lo)**2 + pe = m + tail_e = 0.0_wp + tail_r = 0.0_wp + DO j = m, p + 1, -1 + IF (c2*gv*(tail_e + we(j)) > tol*loc_v .OR. & + c2*(ga*(tail_e + we(j)) + gv*(tail_r + wr(j))) > tol*loc_a) EXIT + tail_e = tail_e + we(j) + tail_r = tail_r + wr(j) + pe = j - 1 + END DO + f%pe_of_p(p) = MAX(f%pe_of_p(p), pe) + END DO + END IF + ! a prefix no level gives keeps every elevation component under Wheeler stretching + DO j = 0, m + IF (f%pe_of_p(j) < 0) f%pe_of_p(j) = MERGE(m, j, stmod == 3) + END DO + END SUBROUTINE CD_NWK_Init + + SUBROUTINE CD_NWK_End(f) + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + IF (ALLOCATED(f%ar)) DEALLOCATE (f%ar, f%ai, f%om, f%kk, f%cb, f%sb, f%dsh, f%dch, f%e2h, f%src, f%ca, f%sa, & + f%cbe, f%sbe, f%th, f%cs, f%sn, f%ex, f%ee, f%rr, f%ii, f%d1, f%d2, f%d3, & + f%d4, f%plev) + IF (ALLOCATED(f%pe_of_p)) DEALLOCATE (f%pe_of_p) + f%m = 0 + f%step = -HUGE(1) + END SUBROUTINE CD_NWK_End + + PURE INTEGER FUNCTION CD_NWK_Prefix(f, z_shallow) RESULT(p) + !! The components a node keeps when it can reach no shallower than z_shallow (m: all). + TYPE(CD_NWK_Field), INTENT(IN) :: f + REAL(wp), INTENT(IN) :: z_shallow + INTEGER :: lev + REAL(wp) :: s + IF (f%m == 0) THEN + p = 0 + RETURN + END IF + s = (MIN(MAX(z_shallow, -f%h), 0.0_wp) + f%h)/f%h*REAL(NLEV - 1, wp) + lev = MIN(NLEV, MAX(1, CEILING(s - 1.0e-12_wp) + 1)) + p = f%plev(lev) + END FUNCTION CD_NWK_Prefix + + SUBROUTINE CD_NWK_Dropped(f, z, p, drop_v, drop_a) + !! The velocity and acceleration variances a node at depth z drops when it keeps the first p + !! components, each relative to its own total at that depth. + TYPE(CD_NWK_Field), INTENT(IN) :: f + REAL(wp), INTENT(IN) :: z + INTEGER, INTENT(IN) :: p + REAL(wp), INTENT(OUT) :: drop_v, drop_a + INTEGER :: j + REAL(wp) :: zc, e, a2, loc_v, loc_a + drop_v = 0.0_wp + drop_a = 0.0_wp + loc_v = 0.0_wp + loc_a = 0.0_wp + zc = MIN(MAX(z, -f%h), 0.0_wp) + DO j = 1, f%m + a2 = 0.5_wp*(f%ar(j)**2 + f%ai(j)**2) + e = ((EXP(f%kk(j)*zc) + EXP(-f%kk(j)*(zc + 2.0_wp*f%h)))*f%dsh(j))**2 + loc_v = loc_v + a2*f%om(j)**2*e + loc_a = loc_a + a2*f%om(j)**4*e + IF (j <= p) CYCLE + drop_v = drop_v + a2*f%om(j)**2*e + drop_a = drop_a + a2*f%om(j)**4*e + END DO + IF (loc_v > 0.0_wp) drop_v = drop_v/loc_v + IF (loc_a > 0.0_wp) drop_a = drop_a/loc_a + END SUBROUTINE CD_NWK_Dropped + + PURE REAL(wp) FUNCTION CD_NWK_Velocity_Ratio(w, k, depth, z) RESULT(r) + !! The rms wave-particle velocity magnitude (horizontal and vertical) at depth z over its value + !! at the still-water level, for components of weights w = |A|^2 omega^2 (any common factor) and + !! wavenumbers k in water of depth `depth`, with the finite-depth Airy transfer: per component + !! D1^2 + D2^2 = 2 (e^{2kz} + e^{-2k(z+2h)}) / (1 - e^{-2kh})^2 (D1 = cosh k(z+h)/sinh kh, + !! D2 = sinh k(z+h)/sinh kh), which tends to 2 e^{2kz} in deep water and does not overflow. z + !! is clamped to the water column; -1 when the weights are all zero. + REAL(wp), INTENT(IN) :: w(:), k(:), depth, z + REAL(wp) :: zc, num, den, s + INTEGER :: j + zc = MIN(MAX(z, -depth), 0.0_wp) + num = 0.0_wp + den = 0.0_wp + DO j = 1, MIN(SIZE(w), SIZE(k)) + IF (.NOT. (w(j) > 0.0_wp .AND. k(j) > 0.0_wp)) CYCLE + s = (1.0_wp - EXP(-2.0_wp*k(j)*depth))**2 + num = num + w(j)*(EXP(2.0_wp*k(j)*zc) + EXP(-2.0_wp*k(j)*(zc + 2.0_wp*depth)))/s + den = den + w(j)*(1.0_wp + EXP(-4.0_wp*k(j)*depth))/s + END DO + r = -1.0_wp + IF (den > 0.0_wp) r = SQRT(num/den) + END FUNCTION CD_NWK_Velocity_Ratio + + SUBROUTINE CD_NWK_Set_Step(f, n) + !! Hold the time phasors exp(j omega t) of wave steps n and n + 1 (shared by every node). + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + INTEGER, INTENT(IN) :: n + INTEGER :: j, nm + REAL(wp) :: ph + IF (n == f%step .OR. f%m == 0) THEN + f%step = n + f%ta = REAL(n, wp)*f%dt + RETURN + END IF + f%step = n + f%ta = REAL(n, wp)*f%dt + ! omega_j t_n = 2 pi i n/N exactly: reduce i n modulo N in integers first + nm = MODULO(n, f%nstep) + DO j = 1, f%m + ph = TWO_PI*REAL(MODULO(INT(f%src(j), KIND=8)*INT(nm, KIND=8), INT(f%nstep, KIND=8)), wp)/REAL(f%nstep, wp) + f%th(j) = ph + END DO + CALL CD_Wave_SinCos(f%m, f%th, f%sa, f%ca) + nm = MODULO(n + 1, f%nstep) + DO j = 1, f%m + f%th(j) = TWO_PI*REAL(MODULO(INT(f%src(j), KIND=8)*INT(nm, KIND=8), INT(f%nstep, KIND=8)), wp)/ & + REAL(f%nstep, wp) + END DO + CALL CD_Wave_SinCos(f%m, f%th, f%sbe, f%cbe) + END SUBROUTINE CD_NWK_Set_Step + + SUBROUTINE CD_NWK_Set_Times(f, ta, tb) + !! Hold the time phasors of two arbitrary times ta and tb (tests and diagnostics; the run uses + !! CD_NWK_Set_Step, whose phases at the wave steps are exact). Marks no wave step as held. + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + REAL(wp), INTENT(IN) :: ta, tb + f%step = -HUGE(1) + f%ta = ta + IF (f%m == 0) RETURN + f%th(1:f%m) = f%om*ta + CALL CD_Wave_SinCos(f%m, f%th, f%sa, f%ca) + f%th(1:f%m) = f%om*tb + CALL CD_Wave_SinCos(f%m, f%th, f%sbe, f%cbe) + END SUBROUTINE CD_NWK_Set_Times + + SUBROUTINE CD_NWK_Eval(f, x, y, z, p, val, der) + !! The quantities (CD_NWK_NQ) and their time derivatives at the two ends of the held wave + !! step (val(:, e), der(:, e), e = 1 at t_n, 2 at t_n+1) at the point (x, y, z), from the first + !! p components (the elevation under Wheeler stretching from its own prefix, pe_of_p(p), at + !! least p). Stretching per f%stmod (see the module header); a node above the still-water + !! level is not zeroed here (WaveStMod 0 evaluates at the surface; the caller decides). + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + REAL(wp), INTENT(IN) :: x, y, z + INTEGER, INTENT(IN) :: p + REAL(wp), INTENT(OUT) :: val(CD_NWK_NQ, 2), der(CD_NWK_NQ, 2) + REAL(wp) :: zb, ze(2), zeta(2), dzeta(2), dzdt(2), s(CD_NWK_NQ), sd(CD_NWK_NQ), sz(CD_NWK_NQ), szt(CD_NWK_NQ) + REAL(wp) :: h + INTEGER :: j, e, np, ne + LOGICAL :: shared, extrap + + val = 0.0_wp + der = 0.0_wp + val(7, :) = f%eta0 + val(8, :) = f%rho_g*f%eta0 + np = MIN(MAX(p, 0), f%m) + IF (np == 0) RETURN + h = f%h + ne = MAX(np, MIN(f%pe_of_p(np), f%m)) + ! the position phase and the complex amplitude at both ends + DO j = 1, ne + f%th(j) = -f%kk(j)*(x*f%cb(j) + y*f%sb(j)) + END DO + CALL CD_Wave_SinCos(ne, f%th, f%sn, f%cs) + DO j = 1, ne + ! e^{j(theta_x + omega t)} = (cs + j sn)(ca + j sa), times A = ar + j ai + CALL cmul3(f%ar(j), f%ai(j), f%cs(j), f%sn(j), f%ca(j), f%sa(j), f%rr(j, 1), f%ii(j, 1)) + CALL cmul3(f%ar(j), f%ai(j), f%cs(j), f%sn(j), f%cbe(j), f%sbe(j), f%rr(j, 2), f%ii(j, 2)) + END DO + ! the free-surface elevation and its rate at both ends + DO e = 1, 2 + zeta(e) = f%eta0 + lane_sum(ne, f%rr(:, e)) + dzeta(e) = -lane_dot(ne, f%om, f%ii(:, e)) + END DO + ! the evaluation depths + zb = MAX(z, -h) + extrap = f%stmod == 2 .AND. z > 0.0_wp + dzdt = 0.0_wp + DO e = 1, 2 + IF (f%stmod == 3) THEN + ze(e) = 0.0_wp + IF (h + zeta(e) > 0.0_wp) THEN + ze(e) = h*(h + z)/(h + zeta(e)) - h + IF (ze(e) < 0.0_wp) THEN + dzdt(e) = -h*(h + z)/(h + zeta(e))**2*dzeta(e) + ELSE + ze(e) = 0.0_wp + END IF + END IF + IF (ze(e) <= -h) THEN + ze(e) = -h + dzdt(e) = 0.0_wp + END IF + ELSE + ze(e) = MIN(zb, 0.0_wp) + END IF + END DO + shared = .NOT. (ABS(ze(1) - ze(2)) > 0.0_wp) + DO e = 1, 2 + IF (e == 1 .OR. .NOT. shared) CALL depth_factors(f, np, ze(e)) + CALL sums(f, np, e, s, sd, sz, szt, f%stmod == 3 .OR. extrap, extrap) + IF (extrap) THEN + val(:, e) = s + z*sz + der(:, e) = sd + z*szt + ELSE IF (f%stmod == 3) THEN + val(:, e) = s + der(:, e) = sd + sz*dzdt(e) + ELSE + val(:, e) = s + der(:, e) = sd + END IF + val(7, e) = zeta(e) + der(7, e) = dzeta(e) + val(8, e) = val(8, e) + f%rho_g*f%eta0 + END DO + END SUBROUTINE CD_NWK_Eval + + PURE SUBROUTINE CD_NWK_Hermite(val, der, dt, s, q) + !! Cubic Hermite interpolation at the fraction s in [0, 1] of the wave step dt between the + !! end values val(:, 1:2) with the end time derivatives der(:, 1:2). + REAL(wp), INTENT(IN) :: val(:, :), der(:, :), dt, s + REAL(wp), INTENT(OUT) :: q(:) + REAL(wp) :: s2, s3, h00, h10, h01, h11 + s2 = s*s + s3 = s2*s + h00 = 2.0_wp*s3 - 3.0_wp*s2 + 1.0_wp + h10 = s3 - 2.0_wp*s2 + s + h01 = -2.0_wp*s3 + 3.0_wp*s2 + h11 = s3 - s2 + q = h00*val(:, 1) + h10*dt*der(:, 1) + h01*val(:, 2) + h11*dt*der(:, 2) + END SUBROUTINE CD_NWK_Hermite + + ! --------------------------------------------------------------------------------------------- + + PURE SUBROUTINE cmul3(ar, ai, c1, s1, c2, s2, re, im) + !! (ar + j ai)(c1 + j s1)(c2 + j s2) + REAL(wp), INTENT(IN) :: ar, ai, c1, s1, c2, s2 + REAL(wp), INTENT(OUT) :: re, im + REAL(wp) :: c, s + c = c1*c2 - s1*s2 + s = s1*c2 + c1*s2 + re = ar*c - ai*s + im = ar*s + ai*c + END SUBROUTINE cmul3 + + SUBROUTINE depth_factors(f, np, z) + !! D1..D4 of the first np components at depth z (-h <= z <= 0). + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + INTEGER, INTENT(IN) :: np + REAL(wp), INTENT(IN) :: z + INTEGER :: j + REAL(wp) :: a, b + ! an exponent below EX_FLUSH gives 0: exp(-708) is under 1e-307 of the amplitude, and the + ! clamp keeps the block exponential on its vector path (no libm call, no subnormals) + DO j = 1, np + f%ex(j) = MAX(f%kk(j)*z, EX_FLUSH) + f%ex(np + j) = MAX(-f%kk(j)*(z + 2.0_wp*f%h), EX_FLUSH) + END DO + CALL CD_Wave_Exp(2*np, f%ex, f%ee) + DO j = 1, 2*np + f%ee(j) = MERGE(0.0_wp, f%ee(j), f%ex(j) <= EX_FLUSH) + END DO + DO j = 1, np + a = f%ee(j) + f%ee(np + j) + b = f%ee(j) - f%ee(np + j) + f%d1(j) = a*f%dsh(j) + f%d2(j) = b*f%dsh(j) + f%d3(j) = a*f%dch(j) + f%d4(j) = b*f%dch(j) + END DO + END SUBROUTINE depth_factors + + SUBROUTINE sums(f, np, e, s, sd, sz, szt, want_z, want_zt) + !! The quantities s, their time derivatives sd, and on request their vertical derivatives sz + !! and the time derivatives of those szt, at end e, from the held depth factors. + TYPE(CD_NWK_Field), INTENT(IN) :: f + INTEGER, INTENT(IN) :: np, e + REAL(wp), INTENT(OUT) :: s(CD_NWK_NQ), sd(CD_NWK_NQ), sz(CD_NWK_NQ), szt(CD_NWK_NQ) + LOGICAL, INTENT(IN) :: want_z, want_zt + INTEGER, PARAMETER :: NS = 29 + REAL(wp) :: lane(CD_WAVE_LANES, NS), w1, w2, w3, r, q, k + INTEGER :: i0, l, j, nl, n + + n = 16 + IF (want_z) n = 24 + IF (want_zt) n = NS + ! only the lanes and columns this call uses + lane(1:MIN(CD_WAVE_LANES, np), 1:n) = 0.0_wp + DO i0 = 1, np, CD_WAVE_LANES + nl = MIN(CD_WAVE_LANES, np - i0 + 1) + DO l = 1, nl + j = i0 + l - 1 + r = f%rr(j, e) + q = f%ii(j, e) + w1 = f%om(j) + w2 = w1*w1 + w3 = w2*w1 + ! values + lane(l, 1) = lane(l, 1) + w1*f%cb(j)*f%d1(j)*r + lane(l, 2) = lane(l, 2) + w1*f%sb(j)*f%d1(j)*r + lane(l, 3) = lane(l, 3) - w1*f%d2(j)*q + lane(l, 4) = lane(l, 4) - w2*f%cb(j)*f%d1(j)*q + lane(l, 5) = lane(l, 5) - w2*f%sb(j)*f%d1(j)*q + lane(l, 6) = lane(l, 6) - w2*f%d2(j)*r + lane(l, 7) = lane(l, 7) + f%d3(j)*r + ! time derivatives of the accelerations and of the pressure + lane(l, 8) = lane(l, 8) - w3*f%cb(j)*f%d1(j)*r + lane(l, 9) = lane(l, 9) - w3*f%sb(j)*f%d1(j)*r + lane(l, 10) = lane(l, 10) + w3*f%d2(j)*q + lane(l, 11) = lane(l, 11) - w1*f%d3(j)*q + END DO + IF (n > 16) THEN + DO l = 1, nl + j = i0 + l - 1 + r = f%rr(j, e) + q = f%ii(j, e) + w1 = f%om(j) + w2 = w1*w1 + k = f%kk(j) + ! vertical derivatives: dD1/dz = k D2, dD2/dz = k D1, dD3/dz = k D4 + lane(l, 17) = lane(l, 17) + w1*f%cb(j)*k*f%d2(j)*r + lane(l, 18) = lane(l, 18) + w1*f%sb(j)*k*f%d2(j)*r + lane(l, 19) = lane(l, 19) - w1*k*f%d1(j)*q + lane(l, 20) = lane(l, 20) - w2*f%cb(j)*k*f%d2(j)*q + lane(l, 21) = lane(l, 21) - w2*f%sb(j)*k*f%d2(j)*q + lane(l, 22) = lane(l, 22) - w2*k*f%d1(j)*r + lane(l, 23) = lane(l, 23) + k*f%d4(j)*r + END DO + END IF + IF (n > 24) THEN + DO l = 1, nl + j = i0 + l - 1 + r = f%rr(j, e) + q = f%ii(j, e) + w1 = f%om(j) + w3 = w1*w1*w1 + k = f%kk(j) + lane(l, 25) = lane(l, 25) - w3*f%cb(j)*k*f%d2(j)*r + lane(l, 26) = lane(l, 26) - w3*f%sb(j)*k*f%d2(j)*r + lane(l, 27) = lane(l, 27) + w3*k*f%d1(j)*q + lane(l, 28) = lane(l, 28) - w1*k*f%d4(j)*q + END DO + END IF + END DO + nl = MIN(CD_WAVE_LANES, np) + s(1) = CD_Wave_Sum_Lanes(lane(:, 1), nl) + s(2) = CD_Wave_Sum_Lanes(lane(:, 2), nl) + s(3) = CD_Wave_Sum_Lanes(lane(:, 3), nl) + s(4) = CD_Wave_Sum_Lanes(lane(:, 4), nl) + s(5) = CD_Wave_Sum_Lanes(lane(:, 5), nl) + s(6) = CD_Wave_Sum_Lanes(lane(:, 6), nl) + s(7) = 0.0_wp ! the elevation is set by the caller + s(8) = f%rho_g*CD_Wave_Sum_Lanes(lane(:, 7), nl) + sd(1:3) = s(4:6) + sd(4) = CD_Wave_Sum_Lanes(lane(:, 8), nl) + sd(5) = CD_Wave_Sum_Lanes(lane(:, 9), nl) + sd(6) = CD_Wave_Sum_Lanes(lane(:, 10), nl) + sd(7) = 0.0_wp + sd(8) = f%rho_g*CD_Wave_Sum_Lanes(lane(:, 11), nl) + sz = 0.0_wp + szt = 0.0_wp + IF (n > 16) THEN + DO j = 1, 6 + sz(j) = CD_Wave_Sum_Lanes(lane(:, 16 + j), nl) + END DO + sz(8) = f%rho_g*CD_Wave_Sum_Lanes(lane(:, 23), nl) + END IF + IF (n > 24) THEN + szt(1:3) = sz(4:6) + szt(4) = CD_Wave_Sum_Lanes(lane(:, 25), nl) + szt(5) = CD_Wave_Sum_Lanes(lane(:, 26), nl) + szt(6) = CD_Wave_Sum_Lanes(lane(:, 27), nl) + szt(8) = f%rho_g*CD_Wave_Sum_Lanes(lane(:, 28), nl) + END IF + END SUBROUTINE sums + + REAL(wp) FUNCTION lane_sum(n, a) RESULT(total) + INTEGER, INTENT(IN) :: n + REAL(wp), INTENT(IN) :: a(:) + REAL(wp) :: lane(CD_WAVE_LANES) + INTEGER :: i0, l + lane = 0.0_wp + DO i0 = 1, n, CD_WAVE_LANES + DO l = 1, MIN(CD_WAVE_LANES, n - i0 + 1) + lane(l) = lane(l) + a(i0 + l - 1) + END DO + END DO + total = CD_Wave_Sum_Lanes(lane, MIN(CD_WAVE_LANES, n)) + END FUNCTION lane_sum + + REAL(wp) FUNCTION lane_dot(n, a, b) RESULT(total) + INTEGER, INTENT(IN) :: n + REAL(wp), INTENT(IN) :: a(:), b(:) + REAL(wp) :: lane(CD_WAVE_LANES) + INTEGER :: i0, l + lane = 0.0_wp + DO i0 = 1, n, CD_WAVE_LANES + DO l = 1, MIN(CD_WAVE_LANES, n - i0 + 1) + lane(l) = lane(l) + a(i0 + l - 1)*b(i0 + l - 1) + END DO + END DO + total = CD_Wave_Sum_Lanes(lane, MIN(CD_WAVE_LANES, n)) + END FUNCTION lane_dot + + SUBROUTINE sort_by_key(key, idx) + !! Stable ascending sort of key, carrying idx (insertion into a merge; m is a few thousand). + REAL(wp), INTENT(INOUT) :: key(:) + INTEGER, INTENT(INOUT) :: idx(:) + REAL(wp), ALLOCATABLE :: kt(:) + INTEGER, ALLOCATABLE :: it(:) + INTEGER :: n, width, lo, mid, hi, i, j, k + n = SIZE(key) + IF (n < 2) RETURN + ALLOCATE (kt(n), it(n)) + width = 1 + DO WHILE (width < n) + DO lo = 1, n, 2*width + mid = MIN(lo + width - 1, n) + hi = MIN(lo + 2*width - 1, n) + i = lo + j = mid + 1 + DO k = lo, hi + IF (i <= mid .AND. (j > hi .OR. key(MIN(i, n)) <= key(MIN(j, n)))) THEN + kt(k) = key(i) + it(k) = idx(i) + i = i + 1 + ELSE + kt(k) = key(j) + it(k) = idx(j) + j = j + 1 + END IF + END DO + END DO + key = kt + idx = it + width = 2*width + END DO + END SUBROUTINE sort_by_key + +END MODULE CableDyn_WaveNodewise diff --git a/src/cabledyn_path.c b/src/cabledyn_path.c index 3ba1983a..205481e2 100644 --- a/src/cabledyn_path.c +++ b/src/cabledyn_path.c @@ -29,6 +29,10 @@ * whether the system opens a runtime spelling for reading or for writing, asked * before the Fortran OPEN so that an OPEN that would fail is never attempted * (see CD_Path_Openable in src/CableDyn_PathIO.f90). + * cabledyn_path_replace + * a written file moved over another in one step (the provenance record), so a reader + * sees the old file or the new one, never half of one; a reader holding the old file open + * is waited for up to a second (Windows), and a failed move removes the written file. * * On other systems names are UTF-8 byte strings that the runtime opens unchanged, * so the conversion is the identity and the lock uses an advisory flock(). @@ -57,6 +61,7 @@ int cabledyn_path_native(const char *in, int in_len, int for_output, int reserve int cabledyn_path_is_device(const char *in, int in_len); int cabledyn_path_lock(const char *in, int in_len); int cabledyn_path_probe(const char *in, int in_len, int for_output); +int cabledyn_path_replace(const char *from, int from_len, const char *to, int to_len); /* The name s[0..n) as a NUL-terminated copy (malloc), or NULL. */ static char *terminated(const char *s, int n) { @@ -436,8 +441,33 @@ int cabledyn_path_probe(const char *in, int in_len, int for_output) { return 0; } +/* 0 when the runtime spelling from[0..from_len) now replaces to[0..to_len) (created when + * missing), else 1. */ +int cabledyn_path_replace(const char *from, int from_len, const char *to, int to_len) { + char *a = terminated(from, from_len); + char *b = terminated(to, to_len); + int ok = 0, attempt; + if (a != NULL && b != NULL) { + /* a reader holding the old file open (a sharing or lock violation) lets go within moments: + * try again for up to a second before giving up */ + for (attempt = 0; attempt < 40; ++attempt) { + DWORD err; + ok = MoveFileExA(a, b, MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH) != 0; + if (ok) break; + err = GetLastError(); + if (err != ERROR_SHARING_VIOLATION && err != ERROR_ACCESS_DENIED && err != ERROR_LOCK_VIOLATION) break; + Sleep(25); + } + if (!ok) DeleteFileA(a); /* no temporary file is left behind */ + } + free(a); + free(b); + return ok ? 0 : 1; +} + #else /* !_WIN32 */ +#include #include #include #include @@ -524,4 +554,18 @@ int cabledyn_path_lock(const char *in, int in_len) { return CD_LOCK_FAILED; } +/* 0 when from[0..from_len) now replaces to[0..to_len), else 1 (rename is atomic on POSIX). */ +int cabledyn_path_replace(const char *from, int from_len, const char *to, int to_len) { + char *a = terminated(from, from_len); + char *b = terminated(to, to_len); + int ok = 0; + if (a != NULL && b != NULL) { + ok = rename(a, b) == 0; + if (!ok) remove(a); /* no temporary file is left behind */ + } + free(a); + free(b); + return ok ? 0 : 1; +} + #endif diff --git a/src/openfast/CableDyn_OF.f90 b/src/openfast/CableDyn_OF.f90 index 3a58f22e..142fdd3f 100644 --- a/src/openfast/CableDyn_OF.f90 +++ b/src/openfast/CableDyn_OF.f90 @@ -140,6 +140,14 @@ MODULE CableDyn USE CableDyn_WaveGrid, ONLY: CD_WaveGrid_Coarse_Axes, CD_WaveGrid_Field_Varies, CD_WAVEGRID_DIR_TOL, & CD_WAVEGRID_COARSE_HALF_NODES, CD_WAVEGRID_FIELD_RTOL USE IfW_FlowField_Types, ONLY: Grid3D_FieldType + USE IfW_FlowField, ONLY: IfW_FlowField_GetVelAcc + USE Waves, ONLY: WaveNumber + USE CableDyn_Provenance, ONLY: CD_Prov, CD_Prov_Write, CD_Fingerprint, CD_Fingerprint_Init, CD_Fingerprint_Add, & + CD_Fingerprint_Hex + USE CableDyn_Banner, ONLY: CD_Version + USE CableDyn_WaveNodewise, ONLY: CD_NWK_Field, CD_NWK_Init, CD_NWK_Set_Step, CD_NWK_Eval, CD_NWK_Hermite, & + CD_NWK_Prefix, CD_NWK_Dropped, CD_NWK_End, CD_NWK_NQ, CD_NWK_OK, & + CD_NWK_Velocity_Ratio IMPLICIT NONE @@ -275,6 +283,8 @@ END FUNCTION cd_cpu_guard_armed ! TRUE once the warning that sampling nodes lie outside the SeaState wave-kinematics grid has ! been issued (OPTION waveGridCheck warn): one warning per run (check_wavefield_grid). LOGICAL :: grid_warned = .FALSE. + ! the coverage check flagged nodes on its last sample (fx_flag), warned or not + LOGICAL :: grid_flag_new = .FALSE. LOGICAL :: curr_grid_warned = .FALSE. !< the dynamic current-field grid check has warned ! CHECKPOINT-RESTART identity: serial is the generation stamp minted at ! Init/rebuild and mirrored into other%restart_serial; t_commit is the time of the @@ -311,12 +321,34 @@ END FUNCTION cd_cpu_guard_armed REAL(wp) :: prof_t_restore = 0.0_wp REAL(wp) :: prof_t_wave_kin = 0.0_wp, prof_t_wave_check = 0.0_wp REAL(wp) :: prof_t_wave_set = 0.0_wp + ! WaterKin SEASTATE_SPECTRAL (nwk_setup, sample_nodewise): the node-wise field of the SeaState + ! wave components (CableDyn_WaveNodewise), and per sampling node the wave step it holds + ! (nwk_step), the components it keeps (nwk_p), the values and time derivatives at both ends of + ! that step (nwk_val, nwk_der: CD_NWK_NQ x 2 x nfluid), and its positions at the last two + ! sample times (nwk_x at nwk_t, nwk_xl at nwk_tl), whose difference is its velocity. The + ! IfW workspaces serve a dynamic current field. + LOGICAL :: nwk_on = .FALSE. + TYPE(CD_NWK_Field) :: nwk + INTEGER(IntKi), ALLOCATABLE :: nwk_step(:), nwk_p(:) + REAL(wp), ALLOCATABLE :: nwk_val(:,:,:), nwk_der(:,:,:), nwk_x(:,:), nwk_xl(:,:) + REAL(DbKi) :: nwk_t = -1.0_DbKi, nwk_tl = -1.0_DbKi + REAL(ReKi), ALLOCATABLE :: nwk_pos(:,:), nwk_dcv(:,:), nwk_dca(:,:) + ! the dropped variances of each node at its static position (velocity, acceleration; nwk_setup) + REAL(wp), ALLOCATABLE :: nwk_drop(:,:) + ! the weights |A|^2 omega^2 (up to a common factor) and wavenumbers of SeaState's components + ! and its depth, for the weighted velocity ratio of the out-of-grid record (vel_ratio) + REAL(wp), ALLOCATABLE :: vr_w(:), vr_k(:) + REAL(wp) :: vr_h = 0.0_wp + ! the provenance record .CD.provenance.json (prov_init, prov_note, prov_write) + TYPE(CD_Prov) :: prov + CHARACTER(1024) :: prov_path = '' END TYPE CD_OF_Instance TYPE(CD_OF_Instance), ALLOCATABLE, SAVE :: Inst(:) INTEGER(IntKi), SAVE :: g_serial = 0 ! monotonic generation counter (Init/rebuild mints) PUBLIC :: CD_Init + PUBLIC :: CD_NWK_From_WaveField PUBLIC :: CD_UpdateStates PUBLIC :: CD_CalcOutput PUBLIC :: CD_CalcContStateDeriv @@ -648,6 +680,7 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er LOGICAL :: host_seastate, host_table CHARACTER(16) :: host_kin REAL(wp), ALLOCATABLE :: static_cur(:,:) ! the host's steady current for the static start + REAL(wp), ALLOCATABLE :: static_cur_nw(:,:) ! the same for a deck on SEASTATE_SPECTRAL CHARACTER(ChanLen) :: chan_hdr, chan_unt CHARACTER(1024) :: native_root CHARACTER(CD_INIT_NOTE_LEN) :: init_note @@ -899,6 +932,9 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er CALL seastate_static_current( InitInp%WaveField, static_cur, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN + CALL seastate_static_current( InitInp%WaveField, static_cur_nw, ErrStat2, ErrMsg2, nodewise=.TRUE. ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN IF (InitInp%WaveField%Current_InitInput%CurrMod /= 0_IntKi .AND. & InitInp%WaveField%Current_InitInput%CurrMod /= 1_IntKi .OR. InitInp%WaveField%hasCurrField) & CALL WrScr( ' Note: CableDyn starts from its still-water statics: of the SeaState currents only '// & @@ -908,7 +944,8 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er env_gravity=REAL(InitInp%g, wp), env_rho_water=REAL(InitInp%rhoW, wp), & env_wtrdpth=REAL(InitInp%WtrDepth, wp), ptfm_init=REAL(ptfm6, wp), & external_fluid=use_extf, run_tmax=REAL(InitInp%Tmax, wp), & - host_orientation=.TRUE., static_current=static_cur, range_files=.TRUE., & + host_orientation=.TRUE., static_current=static_cur, & + static_current_nodewise=static_cur_nw, range_files=.TRUE., & range_discard_root=TRIM(native_root) ) END IF IF (es /= CD_AGG_OK) THEN @@ -1072,6 +1109,17 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er CALL WrScr( ' CableDyn: the WaterKin file takes no SeaState waves or current (WaveKinMod 0, '// & 'CurrentMod 0): the mooring lines are in still water.' ) END IF + ! the wave route: SeaState's grid, or its components evaluated at the nodes (nwk_setup says so) + CALL nwk_setup( Inst(id), InitInp%WaveField, REAL(InitInp%g, wp), TRIM(native_root)//'.wavekin.out', & + ErrStat2, ErrMsg2 ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN + ! the provenance record, before the guard's checks below can note lines in it + CALL prov_init( Inst(id), InitInp%WaveField, .TRUE., native_root ) + IF (Inst(id)%agg%host_wave_enabled .AND. .NOT. Inst(id)%nwk_on .AND. & + InitInp%WaveField%WaveMod /= WaveMod_None) & + CALL WrScr( ' CableDyn: the line wave kinematics are interpolated on the SeaState grid (WaterKin '// & + 'SEASTATE_GRID; SEASTATE_SPECTRAL evaluates them at the nodes).' ) ! Seed the held fields at t = 0 (the static-IC positions): with supercycling ! (nsuper > 1) the first mooring advance happens only at the END of the first ! interval, and every CalcOutput before it would otherwise serve loads from the @@ -1084,10 +1132,18 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er IF (ErrStat >= AbortErrLev) RETURN ! the grid's resolution across the waves, on the static positions just sampled (the ! coverage is checked in sample_wavefield, here and at every mooring step) - CALL check_wavefield_resolution( Inst(id), InitInp%WaveField, ErrStat2, ErrMsg2 ) - CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) - IF (ErrStat >= AbortErrLev) RETURN - CALL note_seastate_deep_interval( Inst(id), InitInp%WaveField ) + ! (the node-wise route reads no grid for the lines) + IF (.NOT. Inst(id)%nwk_on) THEN + CALL check_wavefield_resolution( Inst(id), InitInp%WaveField, ErrStat2, ErrMsg2 ) + IF (ErrStat2 /= ErrID_None) CALL prov_note( Inst(id), 'resolution', 0.0_DbKi, .TRUE., & + ErrStat2 >= AbortErrLev ) + ! the checkpoint mirror again, now with the resolution finding (a checkpoint before the + ! first mooring solve carries it) + IF (ErrStat2 < AbortErrLev) CALL save_held_fluid( Inst(id), other ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN + CALL note_seastate_deep_interval( Inst(id), InitInp%WaveField ) + END IF END IF ! The coupling mesh carries ONLY the host-prescribed (Coupled/Vessel) points. @@ -1540,6 +1596,9 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er CALL WrScr( ' CableDyn: no deck OUTPUTS requested; no CableDyn result columns will be written.' ) END IF END IF + ! the provenance record (written once the run is set up; route none without a SeaState field) + IF (LEN_TRIM(Inst(id)%prov_path) == 0) CALL prov_init( Inst(id), InitInp%WaveField, .FALSE., native_root ) + CALL prov_write( Inst(id), 'init' ) END SUBROUTINE CD_Init @@ -1607,6 +1666,7 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) INTEGER(IntKi) :: id, old_id, stale_id, i, es, ncp, nlines, il, ndofl, nin, k, ic, csz, koff LOGICAL :: use_extf, profile_requested, preserve_profile, same_run REAL(wp), ALLOCATABLE :: static_cur(:,:) ! the host's steady current for the static start + REAL(wp), ALLOCATABLE :: static_cur_nw(:,:) ! the same for a deck on SEASTATE_SPECTRAL LOGICAL :: restored ! held fluid fields restored from the checkpoint CHARACTER(ErrMsgLen) :: em INTEGER(IntKi) :: ErrStat2 @@ -1672,12 +1732,16 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) CALL seastate_static_current( p%WaveField, static_cur, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN + CALL seastate_static_current( p%WaveField, static_cur_nw, ErrStat2, ErrMsg2, nodewise=.TRUE. ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN END IF CALL CD_AGG_Init_From_Deck( Inst(id)%agg, TRIM(rst_deck), REAL(p%dtM0, wp), es, em, & env_gravity=REAL(p%g, wp), env_rho_water=REAL(p%rhoW, wp), & env_wtrdpth=REAL(p%WtrDpth, wp), external_fluid=use_extf, & ptfm_init=REAL(p%PtfmInit, wp), run_tmax=REAL(p%Tmax, wp), & - host_orientation=.TRUE., static_current=static_cur, range_files=.TRUE. ) + host_orientation=.TRUE., static_current=static_cur, & + static_current_nodewise=static_cur_nw, range_files=.TRUE. ) CALL delete_file( rst_deck ) IF (es /= CD_AGG_OK) THEN CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: checkpoint rebuild: '//TRIM(em), & @@ -1738,6 +1802,12 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) ErrStat, ErrMsg, RoutineName ) RETURN END IF + ! the node-wise route: its field again (its cache comes with the held fields below) + CALL nwk_setup( Inst(id), p%WaveField, REAL(p%g, wp), '', ErrStat2, ErrMsg2 ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN + ! the provenance record, whose run state comes with the held fields below + CALL prov_init( Inst(id), p%WaveField, .TRUE., TRIM(p%RootName) ) END IF ! the WriteOutput channel buffer (CalcOutput evaluates the deck channels into it ! every reporting step; Init sizes it from the aggregate's channel count) @@ -1894,10 +1964,23 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) CALL release_instance( id ) RETURN END IF + ! The same run restoring one of its own states (CalcSteady's operating points) did not restart: + ! its provenance record goes on with everything the run has found, and says no restart. + IF (same_run) THEN + Inst(id)%prov = Inst(old_id)%prov + Inst(id)%grid_warned = Inst(old_id)%grid_warned + END IF ! The rebuilt instance supersedes the one the checkpoint replaced (and the provisional ! instance of a fresh process): release their aggregates and workspaces. IF (old_id >= 1_IntKi .AND. old_id <= SIZE(Inst) .AND. old_id /= id) CALL release_instance( old_id ) IF (stale_id > 0_IntKi) CALL release_instance( stale_id ) + ! the provenance record of a run without SeaState fields (with them it was set up above and its + ! run state restored with the held fields); it says where the run restarted + IF (LEN_TRIM(Inst(id)%prov_path) == 0) CALL prov_init( Inst(id), p%WaveField, .FALSE., TRIM(p%RootName) ) + IF (.NOT. same_run) THEN + Inst(id)%prov%has_restart = .TRUE. + Inst(id)%prov%restarted_from = REAL(other%t_commit, wp) + END IF ! adopt the restored identity (the OtherState is authoritative across the restart) Inst(id)%serial = other%restart_serial Inst(id)%t_commit = other%t_commit @@ -2064,7 +2147,10 @@ SUBROUTINE CD_UpdateStates( t, n, u, t_array, p, x, xd, z, other, m, ErrStat, Er ! state and re-samples at the same committed positions. IF (Inst(id)%use_extfluid) THEN IF (Inst(id)%prof_enabled) CALL SYSTEM_CLOCK(prof_phase0) - CALL sample_wavefield( Inst(id), p, m, t + p%dtCoupling, ErrStat2, ErrMsg2 ) + ! (the positions are those of the interval start, the last commit; the node-wise route + ! advances them from there, the grid route samples them as they are) + CALL sample_wavefield( Inst(id), p, m, t + p%dtCoupling, ErrStat2, ErrMsg2, & + t_positions=Inst(id)%t_commit ) IF (ErrStat2 < AbortErrLev) CALL save_held_fluid( Inst(id), other ) IF (Inst(id)%prof_enabled) THEN CALL SYSTEM_CLOCK(prof_c1) @@ -2149,7 +2235,7 @@ SUBROUTINE CD_UpdateStates( t, n, u, t_array, p, x, xd, z, other, m, ErrStat, Er END SUBROUTINE CD_UpdateStates !---------------------------------------------------------------------------------------------------------------------------------- - SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) + SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init, t_positions ) !! Sample the SeaState WaveField at every mooring line node's committed position -- !! fluid velocity (waves + current), fluid acceleration, and the local free-surface !! elevation -- and prescribe them to the aggregate for the coming advance. Nodes @@ -2163,18 +2249,20 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) INTEGER(IntKi), INTENT( OUT) :: ErrStat CHARACTER(*), INTENT( OUT) :: ErrMsg LOGICAL, OPTIONAL, INTENT(IN ) :: at_init !< the Init seeding call (see check_wavefield_grid) + REAL(DbKi), OPTIONAL, INTENT(IN ) :: t_positions !< the time of the committed positions (default t_sample) character(*), parameter :: RoutineName = 'sample_wavefield' INTEGER(IntKi) :: i, l, es, nodeInWater, n_current_nodes INTEGER(IntKi) :: prof_c0, prof_c1, prof_rate LOGICAL :: init_call, timed + REAL(DbKi) :: t_pos REAL(SiKi) :: zeta1, zeta2, zeta, pdyn, fv(3), fa(3), famcf(3) REAL(SiKi) :: wave_zeta1, wave_zeta2, wave_zeta, wave_pdyn REAL(SiKi) :: wave_fv(3), wave_fa(3), wave_famcf(3) REAL(wp) :: profile_fv(3), steady_fv_wp(3), grid_z REAL(SiKi) :: steady_fv(3), grid_fv(3), grid_weight - ! check_grid: the grid check runs on this sample (always under OPTION waveGridCheck error, the - ! default; until its one warning under warn). It reads the SeaState free-surface elevation + ! check_grid: the grid check runs on this sample (every sample: under OPTION waveGridCheck + ! warn, after its one warning, for the provenance record only). It reads the SeaState free-surface elevation ! as sampled at each node (inst_e%fx_zeta, kept also when the host waves are off and fx_wl ! takes the still-water level): SeaState's Wheeler stretching interpolates the current at ! the depth mapped with it. @@ -2220,7 +2308,31 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) ErrStat, ErrMsg, RoutineName ) RETURN END IF - check_grid = .NOT. inst_e%grid_warned + IF (inst_e%nwk_on) THEN + ! WaterKin SEASTATE_SPECTRAL: the SeaState components evaluated at the nodes, no grid + IF (timed) CALL SYSTEM_CLOCK(prof_c0, prof_rate) + t_pos = t_sample + IF (PRESENT(t_positions)) t_pos = t_positions + CALL sample_nodewise( inst_e, p%WaveField, t_sample, t_pos, ErrStat2, ErrMsg2 ) + CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) + IF (ErrStat >= AbortErrLev) RETURN + IF (timed) THEN + CALL SYSTEM_CLOCK(prof_c1) + inst_e%prof_t_wave_kin = inst_e%prof_t_wave_kin + REAL(prof_c1 - prof_c0, wp)/REAL(prof_rate, wp) + prof_c0 = prof_c1 + END IF + IF (.NOT. inst_e%curr_grid_warned) CALL check_current_field_grid( inst_e, p%WaveField, t_sample ) + CALL CD_AGG_SetFluidFields( inst_e%agg, inst_e%fx_vel, inst_e%fx_acc, inst_e%fx_wl, es, em, & + dynamic_pressure=inst_e%fx_pd ) + IF (timed) THEN + CALL SYSTEM_CLOCK(prof_c1) + inst_e%prof_t_wave_set = inst_e%prof_t_wave_set + REAL(prof_c1 - prof_c0, wp)/REAL(prof_rate, wp) + END IF + IF (es /= CD_AGG_OK) & + CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: '//TRIM(em), ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + check_grid = .TRUE. IF (timed) CALL SYSTEM_CLOCK(prof_c0, prof_rate) DO i = 1, inst_e%nfluid IF (.NOT. inst_e%agg%host_wave_enabled .AND. .NOT. inst_e%agg%host_current_enabled) THEN @@ -2325,9 +2437,13 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) ! Grid coverage: checked on the positions just sampled (with their free-surface ! elevations), at Init (the static equilibrium) and then every mooring step: to the end of ! the run, which it stops at the first node outside (OPTION waveGridCheck error, the - ! default), or until its one warning (waveGridCheck warn). + ! default), or warning once and then silently noting the nodes outside in the provenance + ! record (waveGridCheck warn), which is written at once when the check reports. IF (check_grid) THEN + inst_e%grid_flag_new = .FALSE. CALL check_wavefield_grid( inst_e, p%WaveField, t_sample, init_call, ErrStat2, ErrMsg2 ) + IF (inst_e%grid_flag_new) CALL prov_note( inst_e, 'out_of_grid', t_sample, ErrStat2 /= ErrID_None, & + ErrStat2 >= AbortErrLev ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN END IF @@ -2467,6 +2583,9 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, ErrStat, ErrMsg END IF END DO IF (nout == 0_IntKi) RETURN + inst_e%grid_flag_new = .TRUE. + ! after its one warning (waveGridCheck warn) the check goes on for the provenance record only + IF (inst_e%grid_warned) RETURN ! the farthest node per direction, and the SeaState inputs that would cover it nin = 0_IntKi @@ -2523,7 +2642,7 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, ErrStat, ErrMsg 'their motion, and raise '//TRIM(refine)//' to keep the grid spacing.' ! SetErrStat appends the message to ErrMsg after a line break and the routine name room = LEN(ErrMsg) - LEN(RoutineName) - 2 - LEN(head) - LEN(option) - LEN(fix) - CALL flagged_nodes_by_line( inst_e, room - 16, by_line ) + CALL flagged_nodes_by_line( inst_e, room - 16, by_line, with_ratio=.TRUE. ) msg = head IF (LEN(by_line) > 0) msg = msg//' By line: '//by_line//'.' IF (LEN(msg) + LEN(fix) + LEN(option) + 12 + LEN_TRIM(farthest) <= LEN(ErrMsg) - LEN(RoutineName) - 2) & @@ -2685,16 +2804,18 @@ SUBROUTINE check_wavefield_resolution( inst_e, wf, ErrStat, ErrMsg ) END SUBROUTINE check_wavefield_resolution - SUBROUTINE flagged_nodes_by_line( inst_e, budget, report ) + SUBROUTINE flagged_nodes_by_line( inst_e, budget, report, with_ratio ) !! The sampling nodes flagged in inst_e%fx_flag, by line, in the order of the fluid blocks !! (CD_AGG_GetFluidNodePositions: the EI = 0 lines, the finite-EI cables, then the Rigid6 !! body reference points, the rod stations and the buoy points): per line the count and the !! positions of the deepest and the shallowest flagged node, '; '-separated. An item that !! would take the report past `budget` characters is left out and counted in a closing - !! 'and N more'. + !! 'and N more'. With with_ratio, a line item also gives the weighted velocity ratio at its + !! shallowest flagged node (vel_ratio) when SeaState has wave components. TYPE(CD_OF_Instance), INTENT(IN ) :: inst_e INTEGER(IntKi), INTENT(IN ) :: budget CHARACTER(:), ALLOCATABLE, INTENT(OUT) :: report + LOGICAL, OPTIONAL, INTENT(IN ) :: with_ratio INTEGER(IntKi) :: b, i, n, ideep, ishal, nskip CHARACTER(:), ALLOCATABLE :: item @@ -2722,6 +2843,12 @@ SUBROUTINE flagged_nodes_by_line( inst_e, budget, report ) item = TRIM(fluid_block_label(inst_e%agg, b))//', '//TRIM(Num2LStr(n))//' nodes, deepest at '// & node_position(ideep)//', shallowest at '//node_position(ishal) END IF + IF (PRESENT(with_ratio)) THEN + IF (with_ratio .AND. vel_ratio( inst_e, REAL(inst_e%fx_xyz(3, ishal), wp) ) >= 0.0_wp) & + item = item//', weighted velocity ratio '//ratio_text( vel_ratio( inst_e, & + REAL(inst_e%fx_xyz(3, ishal), wp) ) )// & + TRIM(MERGE(' at the shallowest node', ' at the node ', n > 1_IntKi)) + END IF IF (LEN(report) + LEN(item) + 2 > budget) THEN nskip = nskip + 1_IntKi CYCLE @@ -2733,6 +2860,22 @@ SUBROUTINE flagged_nodes_by_line( inst_e, budget, report ) CONTAINS + FUNCTION ratio_text(r) RESULT(s) + !! two significant digits: 0.37, 0.012, 3.1E-04 + REAL(wp), INTENT(IN) :: r + CHARACTER(:), ALLOCATABLE :: s + CHARACTER(16) :: b + IF (r >= 0.1_wp) THEN + WRITE (b, '(F0.2)') r + ELSE IF (r >= 0.01_wp) THEN + WRITE (b, '(F0.3)') r + ELSE + WRITE (b, '(ES8.1)') r + END IF + s = TRIM(ADJUSTL(b)) + IF (s(1:1) == '.') s = '0'//s + END FUNCTION ratio_text + FUNCTION node_position(i) RESULT(s) INTEGER(IntKi), INTENT(IN) :: i CHARACTER(:), ALLOCATABLE :: s @@ -2780,6 +2923,634 @@ FUNCTION fluid_block_label( agg, b ) RESULT(label) END IF END FUNCTION fluid_block_label + SUBROUTINE CD_NWK_From_WaveField( wf, g, tol, f, ErrStat, ErrMsg ) + !! Build the node-wise field (CableDyn_WaveNodewise) from SeaState's first-order wave + !! components: WaveElevC0 (re, im per frequency i = 0 .. NStepWave/2), WaveDirArr, the + !! wavenumbers SeaState itself uses (its WaveNumber of omega_i = i WaveDOmega in single + !! precision, in the depth EffWtrDpth), NStepWave, the wave step (the time spacing of the + !! volume grid), WaveStMod and the water density. The vertex check of the route + !! (CableDyn_WaveKin_Check) builds its field with this same routine. + TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf + REAL(wp), INTENT(IN ) :: g, tol + TYPE(CD_NWK_Field), INTENT(INOUT) :: f + INTEGER(IntKi), INTENT( OUT) :: ErrStat + CHARACTER(*), INTENT( OUT) :: ErrMsg + character(*), parameter :: RoutineName = 'CD_NWK_From_WaveField' + INTEGER(IntKi) :: i, n2, es + CHARACTER(1024) :: em + REAL(wp), ALLOCATABLE :: cre(:), cim(:), dir(:), kv(:) + + ErrStat = ErrID_None + ErrMsg = '' + n2 = wf%NStepWave2 + IF (.NOT. (ALLOCATED(wf%WaveElevC0) .AND. ALLOCATED(wf%WaveDirArr))) THEN + CALL SetErrStat( ErrID_Fatal, 'SeaState keeps no wave components (WaveElevC0, WaveDirArr).', & + ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + IF (LBOUND(wf%WaveElevC0, 2) /= 0 .OR. UBOUND(wf%WaveElevC0, 2) < n2 .OR. & + LBOUND(wf%WaveDirArr, 1) /= 0 .OR. UBOUND(wf%WaveDirArr, 1) < n2) THEN + CALL SetErrStat( ErrID_Fatal, 'the SeaState wave components do not span 0 .. NStepWave/2.', & + ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + ALLOCATE (cre(0:n2), cim(0:n2), dir(0:n2), kv(0:n2)) + DO i = 0, n2 + cre(i) = REAL(wf%WaveElevC0(1, i), wp) + cim(i) = REAL(wf%WaveElevC0(2, i), wp) + dir(i) = REAL(wf%WaveDirArr(i), wp) + kv(i) = REAL(WaveNumber(REAL(i, SiKi)*wf%WaveDOmega, REAL(g, ReKi), wf%EffWtrDpth), wp) + END DO + CALL CD_NWK_Init( f, cre, cim, dir, kv, INT(wf%NStepWave), REAL(wf%VolGridParams%delta(1), wp), & + REAL(wf%EffWtrDpth, wp), REAL(wf%WtrDens, wp), g, INT(wf%WaveStMod), tol, es, em ) + IF (es /= CD_NWK_OK) CALL SetErrStat( ErrID_Fatal, TRIM(em), ErrStat, ErrMsg, RoutineName ) + END SUBROUTINE CD_NWK_From_WaveField + + SUBROUTINE nwk_setup( inst_e, wf, g, report_file, ErrStat, ErrMsg ) + !! WaterKin SEASTATE_SPECTRAL: refuse what the node-wise route cannot reproduce from the + !! SeaState components, build the field and the per-node cache (CD_Init and the checkpoint + !! rebuild). With report_file the kept components and the dropped variances of every node at + !! its static position are written to it and summarised on the screen. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf + REAL(wp), INTENT(IN ) :: g + CHARACTER(*), INTENT(IN ) :: report_file + INTEGER(IntKi), INTENT( OUT) :: ErrStat + CHARACTER(*), INTENT( OUT) :: ErrMsg + character(*), parameter :: RoutineName = 'nwk_setup' + CHARACTER(*), PARAMETER :: ALT = ' Use WaterKin SEASTATE_GRID (or SEASTATE), which samples the SeaState grid.' + CHARACTER(*), PARAMETER :: HEAD = 'CableDyn mooring module: WaterKin SEASTATE_SPECTRAL evaluates SeaState''s '// & + 'first-order wave components at the line nodes and cannot reproduce ' + INTEGER(IntKi) :: nf, i, b, un, ios, pmin, pmax + REAL(wp) :: dv, da, dvmax, damax, z + LOGICAL :: waves + + ErrStat = ErrID_None + ErrMsg = '' + inst_e%nwk_on = inst_e%agg%host_wave_nodewise + IF (.NOT. inst_e%nwk_on) RETURN + waves = inst_e%agg%host_wave_enabled .AND. wf%WaveMod /= WaveMod_None + IF (waves .AND. ALLOCATED(wf%WaveElev2)) THEN + CALL SetErrStat( ErrID_Fatal, HEAD//'second-order wave kinematics (WvDiffQTF, WvSumQTF).'//ALT, & + ErrStat, ErrMsg, RoutineName ) + ELSE IF (waves .AND. wf%WaveMod == WaveMod_ExtFull) THEN + CALL SetErrStat( ErrID_Fatal, HEAD//'WaveMod 6, whose kinematics SeaState reads from files.'//ALT, & + ErrStat, ErrMsg, RoutineName ) + ELSE IF (waves .AND. wf%WvCrntMod /= 0_IntKi) THEN + CALL SetErrStat( ErrID_Fatal, HEAD//'the wave-current interaction of WvCrntMod '// & + TRIM(Num2LStr(wf%WvCrntMod))//'.'//ALT, ErrStat, ErrMsg, RoutineName ) + ELSE IF (inst_e%agg%host_current_enabled .AND. wf%Current_InitInput%CurrMod == 2_IntKi) THEN + CALL SetErrStat( ErrID_Fatal, HEAD//'the user current of CurrMod 2, which SeaState keeps on its grid '// & + 'only.'//ALT, ErrStat, ErrMsg, RoutineName ) + ELSE IF (waves .AND. ABS(wf%WaveTimeShift) > 0.0_DbKi) THEN + CALL SetErrStat( ErrID_Fatal, HEAD//'a WaveTimeShift, which SeaState applies to its kinematics but not '// & + 'to its elevation.'//ALT, ErrStat, ErrMsg, RoutineName ) + END IF + IF (ErrStat >= AbortErrLev) RETURN + nf = inst_e%nfluid + IF (ALLOCATED(inst_e%nwk_step)) DEALLOCATE (inst_e%nwk_step, inst_e%nwk_p, inst_e%nwk_val, inst_e%nwk_der, & + inst_e%nwk_x, inst_e%nwk_xl, inst_e%nwk_pos, inst_e%nwk_dcv, & + inst_e%nwk_dca) + ALLOCATE (inst_e%nwk_step(nf), inst_e%nwk_p(nf), inst_e%nwk_val(CD_NWK_NQ, 2, nf), & + inst_e%nwk_der(CD_NWK_NQ, 2, nf), inst_e%nwk_x(3, nf), inst_e%nwk_xl(3, nf), & + inst_e%nwk_pos(3, 1), inst_e%nwk_dcv(3, 1), inst_e%nwk_dca(3, 1), STAT=ios) + IF (ios /= 0) THEN + CALL SetErrStat( ErrID_Fatal, 'Could not allocate the node-wise wave workspace.', ErrStat, ErrMsg, & + RoutineName ) + RETURN + END IF + inst_e%nwk_step = -HUGE(1_IntKi) + inst_e%nwk_p = 0_IntKi + inst_e%nwk_val = 0.0_wp + inst_e%nwk_der = 0.0_wp + inst_e%nwk_x = 0.0_wp + inst_e%nwk_xl = 0.0_wp + inst_e%nwk_t = -1.0_DbKi + inst_e%nwk_tl = -1.0_DbKi + CALL CD_NWK_End( inst_e%nwk ) + IF (.NOT. waves) RETURN + CALL CD_NWK_From_WaveField( wf, g, inst_e%agg%wave_kin_tol, inst_e%nwk, ErrStat, ErrMsg ) + IF (ErrStat >= AbortErrLev) RETURN + IF (LEN_TRIM(report_file) == 0) RETURN + + ! the components each node keeps at its static position, and what it drops + CALL CD_AGG_GetFluidNodePositions( inst_e%agg, inst_e%fx_xyz, ios, ErrMsg ) + IF (ios /= CD_AGG_OK) THEN + CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: '//TRIM(ErrMsg), ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + IF (ALLOCATED(inst_e%nwk_drop)) DEALLOCATE (inst_e%nwk_drop) + ALLOCATE (inst_e%nwk_drop(2, nf)) + inst_e%nwk_drop = 0.0_wp + CALL GetNewUnit( un ) + OPEN (un, FILE=TRIM(report_file), STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + IF (ios /= 0) un = -1 + IF (un > 0) THEN + WRITE (un, '(A)') '# CableDyn node-wise wave kinematics (WaterKin SEASTATE_SPECTRAL): the components each '// & + 'sampling node keeps at its static position and the velocity and acceleration variances '// & + 'it drops, each relative to its total at the node depth' + WRITE (un, '(A,I0,A,ES10.3)') '# components ', inst_e%nwk%m, ', waveKinTol ', inst_e%nwk%tol + WRITE (un, '(A)') 'Object'//TAB//'Node'//TAB//'X'//TAB//'Y'//TAB//'Z'//TAB//'Kept'//TAB//'DroppedVelVar'// & + TAB//'DroppedAccVar' + END IF + pmin = HUGE(1_IntKi) + pmax = 0_IntKi + dvmax = 0.0_wp + damax = 0.0_wp + DO b = 1, SIZE(inst_e%agg%fl_off) - 1 + DO i = inst_e%agg%fl_off(b) + 1, MIN(inst_e%agg%fl_off(b + 1), nf) + z = nwk_eval_depth( inst_e%nwk, inst_e%fx_xyz(3, i), 0.0_wp ) + inst_e%nwk_p(i) = CD_NWK_Prefix( inst_e%nwk, z ) + CALL CD_NWK_Dropped( inst_e%nwk, inst_e%fx_xyz(3, i), inst_e%nwk_p(i), dv, da ) + inst_e%nwk_drop(:, i) = [dv, da] + pmin = MIN(pmin, inst_e%nwk_p(i)) + pmax = MAX(pmax, inst_e%nwk_p(i)) + dvmax = MAX(dvmax, dv) + damax = MAX(damax, da) + IF (un > 0) WRITE (un, '(A,A,I0,3(A,ES14.6E3),A,I0,2(A,ES11.3E3))') & + TRIM(fluid_block_label(inst_e%agg, b)), & + TAB, i - inst_e%agg%fl_off(b), TAB, inst_e%fx_xyz(1, i), TAB, inst_e%fx_xyz(2, i), TAB, & + inst_e%fx_xyz(3, i), TAB, inst_e%nwk_p(i), TAB, dv, TAB, da + END DO + END DO + IF (un > 0) CLOSE (un) + IF (pmin > pmax) pmin = 0_IntKi + CALL WrScr( ' CableDyn: the SeaState waves are evaluated at the nodes from '//TRIM(Num2LStr(inst_e%nwk%m))// & + ' wave components (WaterKin SEASTATE_SPECTRAL, waveKinTol = '//TRIM(Num2LStr(inst_e%nwk%tol))// & + '): the nodes keep '//TRIM(Num2LStr(pmin))//' to '//TRIM(Num2LStr(pmax))//', and drop at most '// & + TRIM(Num2LStr(dvmax))//' of the velocity variance and '//TRIM(Num2LStr(damax))// & + ' of the acceleration variance at their depth; per node in '//TRIM(report_file)//'.' ) + inst_e%nwk_p = 0_IntKi + END SUBROUTINE nwk_setup + + PURE REAL(wp) FUNCTION nwk_eval_depth( f, z, rise ) RESULT(ze) + !! The shallowest depth at which a node at z, which may rise by `rise` within the wave step, is + !! evaluated: z itself (at most 0) without stretching or with vertical or extrapolation + !! stretching, the Wheeler depth under the lowest elevation the sea can reach with Wheeler + !! stretching. The node's kept components are those of this depth. + TYPE(CD_NWK_Field), INTENT(IN) :: f + REAL(wp), INTENT(IN) :: z, rise + REAL(wp) :: zs, lo + zs = MIN(z + MAX(rise, 0.0_wp), 0.0_wp) + ze = zs + IF (f%stmod == 3) THEN + lo = f%h + f%eta0 - f%zeta_bound + ze = 0.0_wp + IF (lo > 0.0_wp) ze = MIN(f%h*(f%h + zs)/lo - f%h, 0.0_wp) + END IF + END FUNCTION nwk_eval_depth + + SUBROUTINE sample_nodewise( inst_e, wf, t_sample, t_pos, ErrStat, ErrMsg ) + !! WaterKin SEASTATE_SPECTRAL: the fluid fields at t_sample from the sampling nodes' positions + !! just read (fx_xyz), which are those of time t_pos (the committed start of the mooring + !! interval whose end is t_sample). A node evaluates the SeaState components at the two wave steps that + !! bracket t_sample once per step, at its position advanced by its velocity to the middle of + !! the step (CD_NWK_Eval, the components of its depth), and every sample inside the step + !! interpolates those values with their exact time derivatives (CD_NWK_Hermite). The steady + !! current of SeaState (CurrMod 1) is evaluated at the node from its profile, where SeaState's + !! sampler would read it: at the node depth, at the still-water level above it under vertical + !! or extrapolation stretching, at the Wheeler depth under Wheeler stretching, at the seabed + !! below it; a dynamic current field is read as SeaState reads it. Node velocities are the + !! difference of the positions at the last two distinct position times, and a node is advanced + !! from t_pos; positions of an earlier time (a retry) restart that history and the cache. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf + REAL(DbKi), INTENT(IN ) :: t_sample, t_pos + INTEGER(IntKi), INTENT( OUT) :: ErrStat + CHARACTER(*), INTENT( OUT) :: ErrMsg + character(*), parameter :: RoutineName = 'sample_nodewise' + INTEGER(IntKi) :: i, n, es, stmod + REAL(wp) :: dt, s, v(3), xm(3), q(CD_NWK_NQ), z, zc, h, zeta, cur(3), profile_fv(3) + LOGICAL :: waves, wet + CHARACTER(ErrMsgLen) :: em + + ErrStat = ErrID_None + ErrMsg = '' + waves = inst_e%agg%host_wave_enabled .AND. inst_e%nwk%m > 0 + h = REAL(wf%EffWtrDpth, wp) + stmod = wf%WaveStMod + ! the sample history (node velocities) + IF (t_pos > inst_e%nwk_t) THEN + IF (inst_e%nwk_t >= 0.0_DbKi) THEN + inst_e%nwk_xl = inst_e%nwk_x + inst_e%nwk_tl = inst_e%nwk_t + ELSE + inst_e%nwk_xl = inst_e%fx_xyz + inst_e%nwk_tl = t_pos + END IF + inst_e%nwk_x = inst_e%fx_xyz + inst_e%nwk_t = t_pos + ELSE IF (t_pos < inst_e%nwk_t) THEN + inst_e%nwk_x = inst_e%fx_xyz + inst_e%nwk_xl = inst_e%fx_xyz + inst_e%nwk_t = t_pos + inst_e%nwk_tl = t_pos + inst_e%nwk_step = -HUGE(1_IntKi) + END IF + n = 0_IntKi + s = 0.0_wp + dt = 0.0_wp + IF (waves) THEN + dt = inst_e%nwk%dt + n = INT(FLOOR(REAL(t_sample, wp)/dt + 1.0E-9_wp), IntKi) + s = MIN(MAX((REAL(t_sample, wp) - REAL(n, wp)*dt)/dt, 0.0_wp), 1.0_wp) + CALL CD_NWK_Set_Step( inst_e%nwk, INT(n) ) + END IF + DO i = 1, inst_e%nfluid + z = inst_e%fx_xyz(3, i) + q = 0.0_wp + IF (waves) THEN + IF (inst_e%nwk_step(i) /= n) THEN + v = 0.0_wp + IF (inst_e%nwk_t > inst_e%nwk_tl) v = (inst_e%nwk_x(:, i) - inst_e%nwk_xl(:, i))/ & + REAL(inst_e%nwk_t - inst_e%nwk_tl, wp) + xm = inst_e%fx_xyz(:, i) + v*(REAL(n, wp)*dt + 0.5_wp*dt - REAL(t_pos, wp)) + inst_e%nwk_p(i) = CD_NWK_Prefix( inst_e%nwk, & + nwk_eval_depth( inst_e%nwk, MAX(z, xm(3)), ABS(v(3))*0.5_wp*dt ) ) + CALL CD_NWK_Eval( inst_e%nwk, xm(1), xm(2), xm(3), INT(inst_e%nwk_p(i)), inst_e%nwk_val(:, :, i), & + inst_e%nwk_der(:, :, i) ) + inst_e%nwk_step(i) = n + END IF + CALL CD_NWK_Hermite( inst_e%nwk_val(:, :, i), inst_e%nwk_der(:, :, i), dt, s, q ) + END IF + ! SeaState zeroes a node above the still-water level without stretching (WaveStMod 0) + wet = .NOT. (stmod == 0_IntKi .AND. z > 0.0_wp) + zeta = q(7) + IF (.NOT. wet) q(1:6) = 0.0_wp + IF (.NOT. wet) q(8) = 0.0_wp + cur = 0.0_wp + IF (inst_e%agg%host_current_enabled .AND. wet) THEN + IF (wf%Current_InitInput%CurrMod /= 0_IntKi) THEN + zc = MIN(z, 0.0_wp) + IF (stmod == 3_IntKi .AND. h + zeta > 0.0_wp) zc = MIN(h*(h + z)/(h + zeta) - h, 0.0_wp) + zc = MAX(zc, -h) + CALL CD_SeaState_Steady_Current(zc, h, INT(wf%Current_InitInput%CurrMod), & + REAL(wf%Current_InitInput%CurrSSV0, wp), REAL(wf%Current_InitInput%CurrSSDir, wp), & + REAL(wf%Current_InitInput%CurrNSRef, wp), REAL(wf%Current_InitInput%CurrNSV0, wp), & + REAL(wf%Current_InitInput%CurrNSDir, wp), REAL(wf%Current_InitInput%CurrDIV, wp), & + REAL(wf%Current_InitInput%CurrDIDir, wp), cur, es, em) + IF (es /= CD_HYDRO_OK) THEN + CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: SeaState current: '//TRIM(em), & + ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + END IF + IF (wf%hasCurrField) THEN + inst_e%nwk_pos(:, 1) = REAL(inst_e%fx_xyz(:, i), ReKi) + CALL IfW_FlowField_GetVelAcc( wf%CurrField, -1_IntKi, t_sample, inst_e%nwk_pos, inst_e%nwk_dcv, & + inst_e%nwk_dca, es, em, PosOffset=[0.0_ReKi, 0.0_ReKi, wf%EffWtrDpth] ) + IF (es >= AbortErrLev) THEN + CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: dynamic current field: '//TRIM(em), & + ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + cur = cur + REAL(inst_e%nwk_dcv(:, 1), wp) + q(4:6) = q(4:6) + REAL(inst_e%nwk_dca(:, 1), wp) + END IF + END IF + q(1:3) = q(1:3) + cur + IF (ALLOCATED(inst_e%agg%host_current_profile_z)) THEN + CALL CD_Current_Profile_Velocity(z, inst_e%agg%host_current_profile_z, & + inst_e%agg%host_current_profile_velocity, profile_fv, es, em) + IF (es /= CD_HYDRO_OK) THEN + CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: host-wave/file-current profile: '// & + TRIM(em), ErrStat, ErrMsg, RoutineName ) + RETURN + END IF + q(1:3) = q(1:3) + profile_fv + END IF + inst_e%fx_vel(:, i) = q(1:3) + inst_e%fx_acc(:, i) = q(4:6) + inst_e%fx_wl(i) = 0.0_wp + inst_e%fx_pd(i) = 0.0_wp + IF (waves) THEN + inst_e%fx_wl(i) = zeta + inst_e%fx_pd(i) = q(8) + END IF + END DO + END SUBROUTINE sample_nodewise + + PURE INTEGER(IntKi) FUNCTION nwk_mirror_size( inst_e ) RESULT(n) + !! The node-wise cache carried in the OtherState after the held fields (save_held_fluid): + !! per node its wave step and kept components, the values and derivatives at both ends, and + !! its last two sampled positions; then the two sample times. + TYPE(CD_OF_Instance), INTENT(IN) :: inst_e + n = 0_IntKi + IF (inst_e%nwk_on) n = inst_e%nfluid*(2_IntKi + 4_IntKi*CD_NWK_NQ + 6_IntKi) + 2_IntKi + END FUNCTION nwk_mirror_size + + SUBROUTINE nwk_pack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(IN ) :: inst_e + REAL(DbKi), INTENT(INOUT) :: buf(:) + INTEGER(IntKi) :: i, k, nq + nq = CD_NWK_NQ + k = 0_IntKi + DO i = 1, inst_e%nfluid + buf(k + 1) = REAL(inst_e%nwk_step(i), DbKi) + buf(k + 2) = REAL(inst_e%nwk_p(i), DbKi) + buf(k + 3:k + 2 + 2*nq) = RESHAPE(REAL(inst_e%nwk_val(:, :, i), DbKi), [2*nq]) + buf(k + 3 + 2*nq:k + 2 + 4*nq) = RESHAPE(REAL(inst_e%nwk_der(:, :, i), DbKi), [2*nq]) + buf(k + 3 + 4*nq:k + 5 + 4*nq) = REAL(inst_e%nwk_x(:, i), DbKi) + buf(k + 6 + 4*nq:k + 8 + 4*nq) = REAL(inst_e%nwk_xl(:, i), DbKi) + k = k + 8_IntKi + 4_IntKi*nq + END DO + buf(k + 1) = inst_e%nwk_t + buf(k + 2) = inst_e%nwk_tl + END SUBROUTINE nwk_pack + + SUBROUTINE nwk_unpack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + REAL(DbKi), INTENT(IN ) :: buf(:) + INTEGER(IntKi) :: i, k, nq + nq = CD_NWK_NQ + k = 0_IntKi + DO i = 1, inst_e%nfluid + inst_e%nwk_step(i) = NINT(buf(k + 1), IntKi) + inst_e%nwk_p(i) = NINT(buf(k + 2), IntKi) + inst_e%nwk_val(:, :, i) = RESHAPE(REAL(buf(k + 3:k + 2 + 2*nq), wp), [nq, 2]) + inst_e%nwk_der(:, :, i) = RESHAPE(REAL(buf(k + 3 + 2*nq:k + 2 + 4*nq), wp), [nq, 2]) + inst_e%nwk_x(:, i) = REAL(buf(k + 3 + 4*nq:k + 5 + 4*nq), wp) + inst_e%nwk_xl(:, i) = REAL(buf(k + 6 + 4*nq:k + 8 + 4*nq), wp) + k = k + 8_IntKi + 4_IntKi*nq + END DO + inst_e%nwk_t = buf(k + 1) + inst_e%nwk_tl = buf(k + 2) + END SUBROUTINE nwk_unpack + + SUBROUTINE prov_init( inst_e, wf, use_wf, root ) + !! The provenance record of this instance (CableDyn_Provenance): the host, the wave route and + !! the sea as the SeaState field holds it, the grid on the grid route, and one entry per + !! deck line. SeaState keeps no WaveHs, WaveTp, seeds or input-file name in its field, so + !! those are null; the component fingerprint identifies the sea instead. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + TYPE(SeaSt_WaveFieldType), POINTER, INTENT(IN) :: wf + LOGICAL, INTENT(IN ) :: use_wf + CHARACTER(*), INTENT(IN ) :: root + TYPE(CD_Fingerprint) :: fp + INTEGER(IntKi) :: i, n, nl, b, k + LOGICAL :: waves + + inst_e%prov_path = TRIM(root)//'.provenance.json' + inst_e%prov = CD_Prov() + IF (ALLOCATED(inst_e%vr_w)) DEALLOCATE (inst_e%vr_w, inst_e%vr_k) + inst_e%prov%cabledyn_version = CD_Version() + inst_e%prov%host = 'openfast' + IF (inst_e%agg%n_turbines > 0) inst_e%prov%host = 'fast.farm' + waves = .FALSE. + IF (use_wf .AND. ASSOCIATED(wf)) waves = inst_e%agg%host_wave_enabled .AND. wf%WaveMod /= WaveMod_None + IF (waves) THEN + inst_e%prov%route = 'seastate_grid' + IF (inst_e%nwk_on) inst_e%prov%route = 'seastate_spectral' + inst_e%prov%has_wave_mod = .TRUE. + inst_e%prov%wave_mod = INT(wf%WaveMod) + inst_e%prov%has_dir = wf%WaveMod /= WaveMod_ExtFull + inst_e%prov%dir = REAL(wf%WaveDir, wp) + inst_e%prov%has_dir_mod = .TRUE. + inst_e%prov%dir_mod = MERGE(1, 0, wf%WaveMultiDir) + inst_e%prov%has_wave_dt = .TRUE. + inst_e%prov%wave_dt = REAL(wf%VolGridParams%delta(1), wp) + inst_e%prov%has_wave_tmax = .TRUE. + inst_e%prov%wave_tmax = REAL(wf%NStepWave, wp)*REAL(wf%VolGridParams%delta(1), wp) + inst_e%prov%has_depth = .TRUE. + inst_e%prov%depth = REAL(wf%EffWtrDpth, wp) + IF (inst_e%nwk_on) THEN + inst_e%prov%has_tol = .TRUE. + inst_e%prov%tol = inst_e%nwk%tol + END IF + IF (wf%WaveMod /= WaveMod_ExtFull .AND. ALLOCATED(wf%WaveElevC0) .AND. ALLOCATED(wf%WaveDirArr)) THEN + n = 0_IntKi + DO i = LBOUND(wf%WaveElevC0, 2) + 1, UBOUND(wf%WaveElevC0, 2) + IF (wf%WaveElevC0(1, i)**2 + wf%WaveElevC0(2, i)**2 > 0.0_SiKi) n = n + 1_IntKi + END DO + inst_e%prov%has_ncomp = .TRUE. + inst_e%prov%ncomp = INT(n) + IF (n > 0_IntKi) THEN + ! WaveElevC0 in storage order (re, im of component 0, 1, ...), WaveDirArr, WaveDOmega + CALL CD_Fingerprint_Init( fp ) + CALL CD_Fingerprint_Add( fp, RESHAPE(wf%WaveElevC0, [SIZE(wf%WaveElevC0)]) ) + CALL CD_Fingerprint_Add( fp, wf%WaveDirArr ) + CALL CD_Fingerprint_Add( fp, [wf%WaveDOmega] ) + inst_e%prov%fingerprint = CD_Fingerprint_Hex( fp ) + ! the weights and wavenumbers of the weighted velocity ratio (vel_ratio) + CALL vr_setup( inst_e, wf ) + END IF + END IF + IF (.NOT. inst_e%nwk_on) THEN + inst_e%prov%has_grid = .TRUE. + inst_e%prov%nx = INT((wf%VolGridParams%n(2) + 1_IntKi)/2_IntKi) + inst_e%prov%ny = INT((wf%VolGridParams%n(3) + 1_IntKi)/2_IntKi) + inst_e%prov%nz = INT(wf%VolGridParams%n(4)) + inst_e%prov%x_half_width = -REAL(wf%VolGridParams%pZero(2), wp) + inst_e%prov%y_half_width = -REAL(wf%VolGridParams%pZero(3), wp) + inst_e%prov%z_depth = REAL(wf%GridDepth, wp) + inst_e%prov%grid_check = MERGE('warn ', 'error', inst_e%agg%wave_grid_warn) + END IF + END IF + ! one entry per deck line, with its sampling nodes and the variances its nodes dropped + nl = 0_IntKi + IF (ALLOCATED(inst_e%agg%line_obj_index)) nl = COUNT(inst_e%agg%line_obj_index > 0) + ALLOCATE (inst_e%prov%lines(nl)) + k = 0_IntKi + IF (nl > 0_IntKi) THEN + DO i = 1, SIZE(inst_e%agg%line_obj_index) + IF (inst_e%agg%line_obj_index(i) < 1) CYCLE + k = k + 1_IntKi + inst_e%prov%lines(k)%id = INT(i) + ALLOCATE (inst_e%prov%lines(k)%flags(0)) + b = prov_line_block( inst_e%agg, INT(i, IntKi) ) + IF (b > 0_IntKi .AND. ALLOCATED(inst_e%agg%fl_off)) THEN + inst_e%prov%lines(k)%n_nodes = inst_e%agg%fl_off(b + 1) - inst_e%agg%fl_off(b) + IF (inst_e%nwk_on .AND. ALLOCATED(inst_e%nwk_drop) .AND. inst_e%prov%has_tol) THEN + inst_e%prov%lines(k)%has_drop = .TRUE. + inst_e%prov%lines(k)%drop_v_max = MAXVAL(inst_e%nwk_drop(1, inst_e%agg%fl_off(b) + 1: & + inst_e%agg%fl_off(b + 1))) + inst_e%prov%lines(k)%drop_a_max = MAXVAL(inst_e%nwk_drop(2, inst_e%agg%fl_off(b) + 1: & + inst_e%agg%fl_off(b + 1))) + END IF + END IF + END DO + END IF + END SUBROUTINE prov_init + + SUBROUTINE vr_setup( inst_e, wf ) + !! The weights |A_i|^2 omega_i^2 (without the common factor (WaveDOmega/NStepWave)^2) and the + !! wavenumbers of SeaState's first-order components, in its depth EffWtrDpth, for vel_ratio. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf + INTEGER(IntKi) :: i, n2 + REAL(wp) :: wgt, g + IF (ALLOCATED(inst_e%vr_w)) DEALLOCATE (inst_e%vr_w, inst_e%vr_k) + n2 = wf%NStepWave2 + IF (n2 < 1_IntKi .OR. UBOUND(wf%WaveElevC0, 2) < n2) RETURN + g = 9.80665_wp + IF (wf%WtrDens > 0.0_ReKi) g = REAL(wf%RhoXg, wp)/REAL(wf%WtrDens, wp) + ALLOCATE (inst_e%vr_w(n2), inst_e%vr_k(n2)) + DO i = 1, n2 + wgt = 2.0_wp + IF (i == n2) wgt = 1.0_wp + inst_e%vr_w(i) = (wgt*REAL(i, wp))**2*(REAL(wf%WaveElevC0(1, i), wp)**2 + REAL(wf%WaveElevC0(2, i), wp)**2) + inst_e%vr_k(i) = REAL(WaveNumber(REAL(i, SiKi)*wf%WaveDOmega, REAL(g, ReKi), wf%EffWtrDpth), wp) + END DO + inst_e%vr_h = REAL(wf%EffWtrDpth, wp) + END SUBROUTINE vr_setup + + REAL(wp) FUNCTION vel_ratio( inst_e, z ) RESULT(r) + !! The weighted velocity ratio at depth z: the rms wave-particle velocity magnitude there over + !! that at the still-water level, from SeaState's components with the finite-depth Airy + !! transfer (CD_NWK_Velocity_Ratio), at the node's own depth (no stretching); -1 without + !! components (still water, WaveMod 6). + TYPE(CD_OF_Instance), INTENT(IN) :: inst_e + REAL(wp), INTENT(IN) :: z + r = -1.0_wp + IF (ALLOCATED(inst_e%vr_w)) r = CD_NWK_Velocity_Ratio( inst_e%vr_w, inst_e%vr_k, inst_e%vr_h, z ) + END FUNCTION vel_ratio + + PURE INTEGER(IntKi) FUNCTION prov_line_block( agg, line_id ) RESULT(b) + !! The fluid block (CD_AGG_GetFluidNodePositions) of deck line line_id; 0 when it has none. + TYPE(CD_AGG_ModuleType), INTENT(IN) :: agg + INTEGER(IntKi), INTENT(IN) :: line_id + b = 0_IntKi + IF (.NOT. (ALLOCATED(agg%line_obj_index) .AND. ALLOCATED(agg%line_is_cable))) RETURN + IF (line_id < 1 .OR. line_id > SIZE(agg%line_obj_index)) RETURN + IF (agg%line_obj_index(line_id) < 1) RETURN + b = agg%line_obj_index(line_id) + IF (agg%line_is_cable(line_id)) b = agg%fl_nlines + b + END FUNCTION prov_line_block + + SUBROUTINE prov_note( inst_e, kind, t_event, write_now, stopping ) + !! Record in the provenance record the lines whose sampling nodes the wave-grid guard just + !! flagged (inst_e%fx_flag): kind 'out_of_grid' (with the time, the count and the deepest and + !! shallowest flagged node) or 'resolution' (the flag "grid_coarse_across_waves"). The record + !! is rewritten at once when write_now (the guard reported), else at the end of the run; when + !! the guard stops the run (stopping) it is written "stopped" at once, since a run stopped at + !! initialisation does not reach CD_End. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + CHARACTER(*), INTENT(IN ) :: kind + REAL(DbKi), INTENT(IN ) :: t_event + LOGICAL, INTENT(IN ) :: write_now, stopping + INTEGER(IntKi) :: k, b, i, n + CHARACTER(64), ALLOCATABLE :: grown(:) + IF (.NOT. ALLOCATED(inst_e%prov%lines) .OR. .NOT. ALLOCATED(inst_e%fx_flag)) RETURN + DO k = 1, SIZE(inst_e%prov%lines) + b = prov_line_block( inst_e%agg, INT(inst_e%prov%lines(k)%id, IntKi) ) + IF (b < 1_IntKi .OR. .NOT. ALLOCATED(inst_e%agg%fl_off)) CYCLE + n = 0_IntKi + ASSOCIATE (ln => inst_e%prov%lines(k)) + DO i = inst_e%agg%fl_off(b) + 1, MIN(inst_e%agg%fl_off(b + 1), inst_e%nfluid) + IF (.NOT. inst_e%fx_flag(i)) CYCLE + n = n + 1_IntKi + IF (kind == 'out_of_grid') THEN + IF (.NOT. ln%has_oog) THEN + ln%has_oog = .TRUE. + ln%oog_first_time = REAL(t_event, wp) + ln%oog_deepest = inst_e%fx_xyz(:, i) + ln%oog_shallowest = inst_e%fx_xyz(:, i) + END IF + IF (inst_e%fx_xyz(3, i) < ln%oog_deepest(3)) ln%oog_deepest = inst_e%fx_xyz(:, i) + IF (inst_e%fx_xyz(3, i) > ln%oog_shallowest(3)) ln%oog_shallowest = inst_e%fx_xyz(:, i) + END IF + END DO + ! the weighted velocity ratio grows toward the surface: its largest value over the line's + ! outside nodes is that of the shallowest one + IF (n > 0_IntKi .AND. kind == 'out_of_grid') THEN + ln%wvr = vel_ratio( inst_e, ln%oog_shallowest(3) ) + ln%has_wvr = ln%wvr >= 0.0_wp + END IF + IF (n > 0_IntKi .AND. kind == 'out_of_grid') ln%oog_n_nodes_max = MAX(ln%oog_n_nodes_max, INT(n)) + IF (n > 0_IntKi .AND. kind == 'resolution') THEN + IF (.NOT. ANY(ln%flags == 'grid_coarse_across_waves')) THEN + ALLOCATE (grown(SIZE(ln%flags) + 1)) + grown(1:SIZE(ln%flags)) = ln%flags + grown(SIZE(grown)) = 'grid_coarse_across_waves' + CALL MOVE_ALLOC(grown, ln%flags) + END IF + END IF + END ASSOCIATE + END DO + IF (stopping) THEN + CALL prov_write( inst_e, 'stopped' ) + ELSE IF (write_now) THEN + CALL prov_write( inst_e, 'init' ) + END IF + END SUBROUTINE prov_note + + PURE INTEGER(IntKi) FUNCTION prov_mirror_size( inst_e ) RESULT(n) + !! The run state of the provenance record carried in the OtherState after the node-wise cache + !! (save_held_fluid), so that a restarted run reports what the uninterrupted one does: the + !! coverage check's one-warning flag, then per line the out-of-grid record, the resolution + !! flag, the dropped-variance maxima and the weighted velocity ratio. + TYPE(CD_OF_Instance), INTENT(IN) :: inst_e + n = 1_IntKi + IF (ALLOCATED(inst_e%prov%lines)) n = n + 15_IntKi*SIZE(inst_e%prov%lines) + END FUNCTION prov_mirror_size + + SUBROUTINE prov_pack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(IN ) :: inst_e + REAL(DbKi), INTENT(INOUT) :: buf(:) + INTEGER(IntKi) :: k, j + buf(1) = MERGE(1.0_DbKi, 0.0_DbKi, inst_e%grid_warned) + IF (.NOT. ALLOCATED(inst_e%prov%lines)) RETURN + DO k = 1, SIZE(inst_e%prov%lines) + j = 1_IntKi + 15_IntKi*(k - 1_IntKi) + ASSOCIATE (ln => inst_e%prov%lines(k)) + buf(j + 1) = MERGE(1.0_DbKi, 0.0_DbKi, ln%has_oog) + buf(j + 2) = REAL(ln%oog_n_nodes_max, DbKi) + buf(j + 3) = REAL(ln%oog_first_time, DbKi) + buf(j + 4:j + 6) = REAL(ln%oog_deepest, DbKi) + buf(j + 7:j + 9) = REAL(ln%oog_shallowest, DbKi) + buf(j + 10) = 0.0_DbKi + IF (ALLOCATED(ln%flags)) THEN + IF (ANY(ln%flags == 'grid_coarse_across_waves')) buf(j + 10) = 1.0_DbKi + END IF + buf(j + 11) = MERGE(1.0_DbKi, 0.0_DbKi, ln%has_drop) + buf(j + 12) = REAL(ln%drop_v_max, DbKi) + buf(j + 13) = REAL(ln%drop_a_max, DbKi) + buf(j + 14) = MERGE(1.0_DbKi, 0.0_DbKi, ln%has_wvr) + buf(j + 15) = REAL(ln%wvr, DbKi) + END ASSOCIATE + END DO + END SUBROUTINE prov_pack + + SUBROUTINE prov_unpack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + REAL(DbKi), INTENT(IN ) :: buf(:) + INTEGER(IntKi) :: k, j + inst_e%grid_warned = buf(1) > 0.5_DbKi + IF (.NOT. ALLOCATED(inst_e%prov%lines)) RETURN + DO k = 1, SIZE(inst_e%prov%lines) + j = 1_IntKi + 15_IntKi*(k - 1_IntKi) + ASSOCIATE (ln => inst_e%prov%lines(k)) + ln%has_oog = buf(j + 1) > 0.5_DbKi + ln%oog_n_nodes_max = NINT(buf(j + 2)) + ln%oog_first_time = REAL(buf(j + 3), wp) + ln%oog_deepest = REAL(buf(j + 4:j + 6), wp) + ln%oog_shallowest = REAL(buf(j + 7:j + 9), wp) + IF (ALLOCATED(ln%flags)) DEALLOCATE (ln%flags) + IF (buf(j + 10) > 0.5_DbKi) THEN + ln%flags = [CHARACTER(64) :: 'grid_coarse_across_waves'] + ELSE + ALLOCATE (ln%flags(0)) + END IF + ln%has_drop = buf(j + 11) > 0.5_DbKi + ln%drop_v_max = REAL(buf(j + 12), wp) + ln%drop_a_max = REAL(buf(j + 13), wp) + ln%has_wvr = buf(j + 14) > 0.5_DbKi + ln%wvr = REAL(buf(j + 15), wp) + END ASSOCIATE + END DO + END SUBROUTINE prov_unpack + + SUBROUTINE prov_write( inst_e, status ) + !! Write the provenance record; a failure is reported on the screen and does not stop the run. + TYPE(CD_OF_Instance), INTENT(IN) :: inst_e + CHARACTER(*), INTENT(IN) :: status + INTEGER :: es + CHARACTER(1024) :: em + IF (LEN_TRIM(inst_e%prov_path) == 0) RETURN + CALL CD_Prov_Write( inst_e%prov, TRIM(inst_e%prov_path), status, es, em ) + IF (es /= 0) CALL WrScr( ' CableDyn: '//TRIM(em)//'.' ) + END SUBROUTINE prov_write + SUBROUTINE note_seastate_deep_interval( inst_e, wf ) !! Say at initialisation, once per run (a restart rebuilds without passing here), when the !! deepest interval of the SeaState depth grid is coarse and a line lies in it. The levels @@ -3188,16 +3959,22 @@ SUBROUTINE save_held_fluid( inst_e, other ) !! restart serves its loads from the same fields (restore_held_fluid). TYPE(CD_OF_Instance), INTENT(IN ) :: inst_e TYPE(CD_OtherStateType), INTENT(INOUT) :: other - INTEGER(IntKi) :: nf + INTEGER(IntKi) :: nf, nn, np nf = inst_e%nfluid + ! the node-wise route (WaterKin SEASTATE_SPECTRAL) appends its cache, then the provenance + ! record its run state + nn = nwk_mirror_size( inst_e ) + np = prov_mirror_size( inst_e ) IF (ALLOCATED(other%fluid_held)) THEN - IF (SIZE(other%fluid_held) /= 8*nf) DEALLOCATE (other%fluid_held) + IF (SIZE(other%fluid_held) /= 8*nf + nn + np) DEALLOCATE (other%fluid_held) END IF - IF (.NOT. ALLOCATED(other%fluid_held)) ALLOCATE (other%fluid_held(8*nf)) + IF (.NOT. ALLOCATED(other%fluid_held)) ALLOCATE (other%fluid_held(8*nf + nn + np)) other%fluid_held(1:3*nf) = RESHAPE(REAL(inst_e%fx_vel, DbKi), [3*nf]) other%fluid_held(3*nf + 1:6*nf) = RESHAPE(REAL(inst_e%fx_acc, DbKi), [3*nf]) other%fluid_held(6*nf + 1:7*nf) = REAL(inst_e%fx_wl, DbKi) other%fluid_held(7*nf + 1:8*nf) = REAL(inst_e%fx_pd, DbKi) + IF (nn > 0_IntKi) CALL nwk_pack( inst_e, other%fluid_held(8*nf + 1:8*nf + nn) ) + CALL prov_pack( inst_e, other%fluid_held(8*nf + nn + 1:8*nf + nn + np) ) END SUBROUTINE save_held_fluid SUBROUTINE restore_held_fluid( inst_e, other, restored, ErrStat, ErrMsg ) @@ -3209,14 +3986,18 @@ SUBROUTINE restore_held_fluid( inst_e, other, restored, ErrStat, ErrMsg ) LOGICAL, INTENT( OUT) :: restored INTEGER(IntKi), INTENT( OUT) :: ErrStat CHARACTER(*), INTENT( OUT) :: ErrMsg - INTEGER(IntKi) :: nf, es + INTEGER(IntKi) :: nf, es, nn, np CHARACTER(ErrMsgLen) :: em ErrStat = ErrID_None ErrMsg = '' restored = .FALSE. nf = inst_e%nfluid + nn = nwk_mirror_size( inst_e ) + np = prov_mirror_size( inst_e ) IF (.NOT. ALLOCATED(other%fluid_held)) RETURN - IF (SIZE(other%fluid_held) /= 8*nf) RETURN + IF (SIZE(other%fluid_held) /= 8*nf + nn + np) RETURN + IF (nn > 0_IntKi) CALL nwk_unpack( inst_e, other%fluid_held(8*nf + 1:8*nf + nn) ) + CALL prov_unpack( inst_e, other%fluid_held(8*nf + nn + 1:8*nf + nn + np) ) inst_e%fx_vel = RESHAPE(REAL(other%fluid_held(1:3*nf), wp), [3, nf]) inst_e%fx_acc = RESHAPE(REAL(other%fluid_held(3*nf + 1:6*nf), wp), [3, nf]) inst_e%fx_wl = REAL(other%fluid_held(6*nf + 1:7*nf), wp) @@ -3880,6 +4661,12 @@ SUBROUTINE CD_End(u, p, x, xd, z, other, y, m, ErrStat , ErrMsg) IF (ALLOCATED(Inst)) THEN IF (m%CDInst >= 1 .AND. m%CDInst <= SIZE(Inst)) THEN IF (Inst(m%CDInst)%active) THEN + ! the provenance record: complete, or stopped when the run ended on an error + IF (m%HostComplete) THEN + CALL prov_write( Inst(m%CDInst), 'complete' ) + ELSE + CALL prov_write( Inst(m%CDInst), 'stopped' ) + END IF ! The range graphs cover the whole run, so a run that ended on an error writes none ! (as the standalone driver, which writes them on completion). The glue comes here ! after an abort too, so the host says which it was (m%HostComplete): a run can also @@ -5802,6 +6589,15 @@ SUBROUTINE release_instance( k, ErrStat, ErrMsg ) END IF IF (ALLOCATED(Inst(k)%fx_xyz)) DEALLOCATE (Inst(k)%fx_xyz, Inst(k)%fx_vel, Inst(k)%fx_acc, & Inst(k)%fx_wl, Inst(k)%fx_pd, Inst(k)%fx_zeta, Inst(k)%fx_flag) + IF (ALLOCATED(Inst(k)%nwk_step)) DEALLOCATE (Inst(k)%nwk_step, Inst(k)%nwk_p, Inst(k)%nwk_val, & + Inst(k)%nwk_der, Inst(k)%nwk_x, Inst(k)%nwk_xl, Inst(k)%nwk_pos, & + Inst(k)%nwk_dcv, Inst(k)%nwk_dca) + CALL CD_NWK_End( Inst(k)%nwk ) + Inst(k)%nwk_on = .FALSE. + IF (ALLOCATED(Inst(k)%nwk_drop)) DEALLOCATE (Inst(k)%nwk_drop) + IF (ALLOCATED(Inst(k)%vr_w)) DEALLOCATE (Inst(k)%vr_w, Inst(k)%vr_k) + Inst(k)%prov_path = '' + IF (ALLOCATED(Inst(k)%prov%lines)) DEALLOCATE (Inst(k)%prov%lines) Inst(k)%use_extfluid = .FALSE. Inst(k)%nfluid = 0 Inst(k)%grid_warned = .FALSE. @@ -5833,27 +6629,64 @@ END FUNCTION wavefield_is_ambient !> and very nearly between them. Left unallocated -- a still-water start -- without a !> nonzero CurrMod 1 current; a CurrMod 2 current or an InflowWind current field is known !> only through the run's samples (CD_Init notes it). - SUBROUTINE seastate_static_current( wf, prof, ErrStat, ErrMsg ) + !> nodewise: the profile of a deck on WaterKin SEASTATE_SPECTRAL (static_current_nodewise), + !> whose steps evaluate the current at each node's depth (sample_nodewise), not on the grid: + !> levels at which linear interpolation follows the profile itself, whatever the grid. They + !> are uniform in ((z + h)/h)^(1/7), so the 1/7 power law grows by CurrSSV0/NPOW from one to + !> the next, and include the seabed, the still-water level and the near-surface knee at + !> -CurrNSRef, between which the other parts are linear in z. + SUBROUTINE seastate_static_current( wf, prof, ErrStat, ErrMsg, nodewise ) TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf REAL(wp), ALLOCATABLE, INTENT( OUT) :: prof(:,:) INTEGER(IntKi), INTENT( OUT) :: ErrStat CHARACTER(*), INTENT( OUT) :: ErrMsg + LOGICAL, OPTIONAL, INTENT(IN ) :: nodewise + INTEGER(IntKi), PARAMETER :: NPOW = 200 INTEGER(IntKi) :: k, nz, m, es - REAL(wp) :: zk, v(3) + REAL(wp) :: zk, v(3), h, zn + REAL(wp), ALLOCATABLE :: zs(:) + LOGICAL :: exact, knee CHARACTER(1024) :: em ErrStat = ErrID_None ErrMsg = '' IF (wf%Current_InitInput%CurrMod /= 1_IntKi) RETURN - nz = wf%VolGridParams%n(4) - IF (nz < 2) RETURN + exact = .FALSE. + IF (PRESENT(nodewise)) exact = nodewise + h = REAL(wf%EffWtrDpth, wp) + IF (exact) THEN + IF (.NOT. h > 0.0_wp) RETURN + zn = -REAL(wf%Current_InitInput%CurrNSRef, wp) + knee = zn > -h .AND. zn < 0.0_wp + ALLOCATE (zs(NPOW + 2)) + nz = 0 + DO k = 0, NPOW + zk = -h + h*(REAL(k, wp)/REAL(NPOW, wp))**7 + IF (k == NPOW) zk = 0.0_wp + IF (knee .AND. zn < zk) THEN + nz = nz + 1 + zs(nz) = zn + knee = .FALSE. + END IF + nz = nz + 1 + zs(nz) = zk + END DO + ELSE + nz = wf%VolGridParams%n(4) + IF (nz < 2) RETURN + ALLOCATE (zs(nz)) + DO k = 0, nz - 1 + zs(k + 1) = REAL(wf%GridDepth, wp)*(SIN(REAL(wf%VolGridParams%pZero(4) + k*wf%VolGridParams%delta(4), & + wp)) - 1.0_wp) + END DO + END IF ALLOCATE (prof(4, nz)) m = 0 - DO k = 0, nz - 1 - zk = REAL(wf%GridDepth, wp)*(SIN(REAL(wf%VolGridParams%pZero(4) + k*wf%VolGridParams%delta(4), wp)) - 1.0_wp) + DO k = 1, nz + zk = zs(k) IF (m > 0) THEN IF (.NOT. zk > prof(1, m)) CYCLE END IF - CALL CD_SeaState_Steady_Current(zk, REAL(wf%EffWtrDpth, wp), 1, & + CALL CD_SeaState_Steady_Current(zk, h, 1, & REAL(wf%Current_InitInput%CurrSSV0, wp), REAL(wf%Current_InitInput%CurrSSDir, wp), & REAL(wf%Current_InitInput%CurrNSRef, wp), REAL(wf%Current_InitInput%CurrNSV0, wp), & REAL(wf%Current_InitInput%CurrNSDir, wp), REAL(wf%Current_InitInput%CurrDIV, wp), & diff --git a/src/openfast/CableDyn_WaveKin_Check.f90 b/src/openfast/CableDyn_WaveKin_Check.f90 new file mode 100644 index 00000000..6ccb0c6b --- /dev/null +++ b/src/openfast/CableDyn_WaveKin_Check.f90 @@ -0,0 +1,209 @@ +! File: src/openfast/CableDyn_WaveKin_Check.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +PROGRAM CableDyn_WaveKin_Check + !! Vertex check of the node-wise wave kinematics (WaterKin SEASTATE_SPECTRAL) against SeaState's + !! own grid, with no coupled run: SeaState is initialised from an input file, the node-wise field + !! is built from its components exactly as the CableDyn OpenFAST module builds it + !! (CD_NWK_From_WaveField), and at every grid vertex in the water (a stride of them on large + !! grids) and a set of wave steps the velocity, acceleration, dynamic pressure and free-surface + !! elevation are compared with the stored grid. With wave stretching (WaveStMod 1 to 3) the + !! stretched values are compared with SeaState's own sampler (WaveField_GetNodeWaveKin) at + !! points above or beside the vertices where the sampler reads grid levels only. + !! + !! cabledyn_wavekin_check [WtrDpth] [PtfmLocationX PtfmLocationY] + !! + !! A PtfmLocation pair applies FAST.Farm's Mod_WaveField = 2 phase shift. The program prints, per + !! quantity, the largest difference relative to the largest grid magnitude, and stops with a + !! nonzero code when one exceeds TOL (single-precision FFT round-off of the grid). + USE NWTC_Library + USE SeaState + USE SeaState_Types + USE SeaSt_WaveField, ONLY: WaveField_GetNodeWaveKin + USE GridInterp_Types, ONLY: GridInterp_MiscVarType + USE CableDyn_Precision, ONLY: wp + USE CableDyn_WaveNodewise, ONLY: CD_NWK_Field, CD_NWK_Set_Step, CD_NWK_Eval, CD_NWK_NQ + USE CableDyn, ONLY: CD_NWK_From_WaveField + IMPLICIT NONE + + REAL(wp), PARAMETER :: TOL = 1.0E-5_wp + TYPE(SeaSt_InitInputType) :: InitInp + TYPE(SeaSt_InputType) :: u + TYPE(SeaSt_ParameterType) :: p + TYPE(SeaSt_ContinuousStateType) :: x + TYPE(SeaSt_DiscreteStateType) :: xd + TYPE(SeaSt_ConstraintStateType) :: z + TYPE(SeaSt_OtherStateType) :: other + TYPE(SeaSt_OutputType) :: y + TYPE(SeaSt_MiscVarType) :: m + TYPE(SeaSt_InitOutputType) :: InitOut + TYPE(CD_NWK_Field) :: f + TYPE(GridInterp_MiscVarType) :: gm + REAL(DbKi) :: interval + INTEGER(IntKi) :: ErrStat, nx, ny, nz, nt, i, j, k, it, nsel, steps(8), st, ix, iy, q + CHARACTER(ErrMsgLen) :: ErrMsg + CHARACTER(1024) :: arg + REAL(wp) :: val(CD_NWK_NQ, 2), der(CD_NWK_NQ, 2), xv, yv, zv, h, dz, gmax(4), dmax(4) + REAL(wp) :: smax(4), sdmax(4), zp, zlev, zeta + REAL(SiKi) :: z1, z2, zt, pd, fv(3), fa(3), fam(3) + INTEGER(IntKi) :: inwater, stride(2), stmod + LOGICAL :: fail + + CALL NWTC_Init() + IF (COMMAND_ARGUMENT_COUNT() < 1) THEN + WRITE (*, '(A)') 'usage: cabledyn_wavekin_check [WtrDpth] [PtfmLocationX PtfmLocationY]' + STOP 2 + END IF + CALL GET_COMMAND_ARGUMENT(1, InitInp%InputFile) + InitInp%defWtrDpth = 200.0_ReKi + IF (COMMAND_ARGUMENT_COUNT() >= 2) THEN + CALL GET_COMMAND_ARGUMENT(2, arg) + READ (arg, *) InitInp%defWtrDpth + END IF + InitInp%WaveFieldMod = 0 + InitInp%PtfmLocationX = 0.0_ReKi + InitInp%PtfmLocationY = 0.0_ReKi + IF (COMMAND_ARGUMENT_COUNT() >= 4) THEN + CALL GET_COMMAND_ARGUMENT(3, arg) + READ (arg, *) InitInp%PtfmLocationX + CALL GET_COMMAND_ARGUMENT(4, arg) + READ (arg, *) InitInp%PtfmLocationY + InitInp%WaveFieldMod = 2 + END IF + InitInp%UseInputFile = .TRUE. + InitInp%OutRootName = 'wavekin_check' + InitInp%Gravity = 9.80665_ReKi + InitInp%defWtrDens = 1025.0_ReKi + InitInp%defMSL2SWL = 0.0_ReKi + InitInp%TMax = 10.0_DbKi + InitInp%WaveTimeShift = 0.0_DbKi + InitInp%HasIce = .FALSE. + InitInp%hasCurrField = .FALSE. + InitInp%MHK = 0 + interval = 0.025_DbKi + CALL SeaSt_Init(InitInp, u, p, x, xd, z, other, y, m, interval, InitOut, ErrStat, ErrMsg) + IF (ErrStat >= AbortErrLev) THEN + WRITE (*, '(A)') 'FAIL: SeaState init: '//TRIM(ErrMsg) + STOP 1 + END IF + CALL CD_NWK_From_WaveField(p%WaveField, REAL(InitInp%Gravity, wp), 0.0_wp, f, ErrStat, ErrMsg) + IF (ErrStat >= AbortErrLev) THEN + WRITE (*, '(A)') 'FAIL: node-wise field: '//TRIM(ErrMsg) + STOP 1 + END IF + nt = p%WaveField%NStepWave + nx = p%WaveField%VolGridParams%n(2) + ny = p%WaveField%VolGridParams%n(3) + nz = p%WaveField%VolGridParams%n(4) + h = REAL(p%WaveField%EffWtrDpth, wp) + dz = REAL(p%WaveField%VolGridParams%delta(4), wp) + WRITE (*, '(A,I0,A,I0,A,I0,A,I0,A,I0,A,I0)') 'SeaState grid ', nx, ' x ', ny, ' x ', nz, ', ', nt, & + ' wave steps, WaveStMod ', p%WaveField%WaveStMod, ', components ', f%m + steps = [0, 1, 2, 7, nt/3, nt/2 + 1, nt - 2, nt - 1] + ! the grid holds the kinematics unstretched: compare the field without stretching there + stmod = f%stmod + f%stmod = 0 + nsel = 8 + stride = [MAX(1, nx/12), MAX(1, ny/12)] + gmax = 0.0_wp + dmax = 0.0_wp + DO it = 1, nsel + st = steps(it) + CALL CD_NWK_Set_Step(f, st) + DO j = 1, ny, stride(2) + yv = REAL(p%WaveField%VolGridParams%pZero(3) + (j - 1)*p%WaveField%VolGridParams%delta(3), wp) + DO i = 1, nx, stride(1) + xv = REAL(p%WaveField%VolGridParams%pZero(2) + (i - 1)*p%WaveField%VolGridParams%delta(2), wp) + ! the elevation at the vertex + CALL CD_NWK_Eval(f, xv, yv, 0.0_wp, f%m, val, der) + CALL acc(4, val(7, 1), REAL(p%WaveField%WaveElev1(st, i, j), wp)) + DO k = 1, nz + zv = REAL(p%WaveField%GridDepth, wp)*(SIN(REAL(k - 1, wp)*dz) - 1.0_wp) + IF (zv < -h - 1.0E-6_wp*h .OR. zv > 0.0_wp) CYCLE + CALL CD_NWK_Eval(f, xv, yv, MAX(zv, -h), f%m, val, der) + DO q = 1, 3 + CALL acc(1, val(q, 1), REAL(p%WaveField%WaveVel(st, i, j, k, q), wp)) + CALL acc(2, val(q + 3, 1), REAL(p%WaveField%WaveAcc(st, i, j, k, q), wp)) + END DO + CALL acc(3, val(8, 1), REAL(p%WaveField%WaveDynP(st, i, j, k), wp)) + END DO + END DO + END DO + END DO + f%stmod = stmod + fail = .FALSE. + CALL report('velocity', 1) + CALL report('acceleration', 2) + CALL report('dynamic pressure', 3) + CALL report('elevation', 4) + + ! stretched values: against SeaState's sampler where it reads grid levels only (at a vertex in x + ! and y, at a wave step, and at z = 0 above the still-water level for WaveStMod 1 and 2, at a + ! Wheeler-mapped depth that is a grid level for WaveStMod 3) + IF (p%WaveField%WaveStMod > 0) THEN + smax = 0.0_wp + sdmax = 0.0_wp + DO it = 1, nsel + st = steps(it) + CALL CD_NWK_Set_Step(f, st) + DO iy = 1, ny, stride(2) + yv = REAL(p%WaveField%VolGridParams%pZero(3) + (iy - 1)*p%WaveField%VolGridParams%delta(3), wp) + DO ix = 1, nx, stride(1) + xv = REAL(p%WaveField%VolGridParams%pZero(2) + (ix - 1)*p%WaveField%VolGridParams%delta(2), wp) + zeta = REAL(p%WaveField%WaveElev1(st, ix, iy), wp) + DO k = 1, 3 + IF (p%WaveField%WaveStMod == 3) THEN + zlev = REAL(p%WaveField%GridDepth, wp)*(SIN(REAL(nz - k, wp)*dz) - 1.0_wp) + zp = (zlev + h)*(h + zeta)/h - h + ELSE + zp = 0.4_wp*REAL(k, wp) + END IF + CALL WaveField_GetNodeWaveKin(p%WaveField, gm, REAL(st, DbKi)*REAL(f%dt, DbKi), & + REAL([xv, yv, zp], ReKi), .TRUE., .FALSE., inwater, z1, z2, zt, pd, & + fv, fa, fam, ErrStat, ErrMsg) + CALL CD_NWK_Eval(f, xv, yv, zp, f%m, val, der) + DO q = 1, 3 + smax(1) = MAX(smax(1), ABS(REAL(fv(q), wp))) + sdmax(1) = MAX(sdmax(1), ABS(val(q, 1) - REAL(fv(q), wp))) + smax(2) = MAX(smax(2), ABS(REAL(fa(q), wp))) + sdmax(2) = MAX(sdmax(2), ABS(val(q + 3, 1) - REAL(fa(q), wp))) + END DO + smax(3) = MAX(smax(3), ABS(REAL(pd, wp))) + sdmax(3) = MAX(sdmax(3), ABS(val(8, 1) - REAL(pd, wp))) + END DO + END DO + END DO + END DO + gmax(1:3) = smax(1:3) + dmax(1:3) = sdmax(1:3) + CALL report('stretched velocity', 1) + CALL report('stretched acceleration', 2) + CALL report('stretched pressure', 3) + END IF + IF (fail) THEN + WRITE (*, '(A)') 'FAIL: the node-wise kinematics differ from the SeaState grid beyond the tolerance' + STOP 1 + END IF + WRITE (*, '(A)') 'PASS: the node-wise kinematics equal the SeaState grid at its vertices and wave steps' + +CONTAINS + + SUBROUTINE acc(kq, a, b) + INTEGER(IntKi), INTENT(IN) :: kq + REAL(wp), INTENT(IN) :: a, b + gmax(kq) = MAX(gmax(kq), ABS(b)) + dmax(kq) = MAX(dmax(kq), ABS(a - b)) + END SUBROUTINE acc + + SUBROUTINE report(name, kq) + CHARACTER(*), INTENT(IN) :: name + INTEGER(IntKi), INTENT(IN) :: kq + REAL(wp) :: r + r = 0.0_wp + IF (gmax(kq) > 0.0_wp) r = dmax(kq)/gmax(kq) + WRITE (*, '(2X,A,T28,A,ES10.3,A,ES10.3,A,ES10.3)') name, 'max |grid| ', gmax(kq), ' max |diff| ', dmax(kq), & + ' relative ', r + IF (r > TOL) fail = .TRUE. + END SUBROUTINE report + +END PROGRAM CableDyn_WaveKin_Check diff --git a/tests/test_openfast_aggregate.f90 b/tests/test_openfast_aggregate.f90 index 3b472d30..4b3b4bfe 100644 --- a/tests/test_openfast_aggregate.f90 +++ b/tests/test_openfast_aggregate.f90 @@ -5019,7 +5019,7 @@ SUBROUTINE case_static_current() TYPE(CD_AGG_ModuleType) :: agg_w, agg_c, agg_u REAL(wp), PARAMETER :: DT = 0.05_wp REAL(wp), PARAMETER :: UC(3) = [0.4_wp, 0.3_wp, 0.0_wp] - REAL(wp) :: prof(4, 2), r0(3, 3), vel(3, 3), acc(3, 3), lu(3, 3), lc3(3, 3), v3(3, 3), a3(3, 3) + REAL(wp) :: prof(4, 2), prof0(4, 2), r0(3, 3), vel(3, 3), acc(3, 3), lu(3, 3), lc3(3, 3), v3(3, 3), a3(3, 3) REAL(wp) :: drift(2) INTEGER :: es CHARACTER(1024) :: em @@ -5079,6 +5079,43 @@ SUBROUTINE case_static_current() CALL CD_AGG_End(agg_w, es, em) CALL CD_AGG_End(agg_c, es, em) + ! (2b) the route picks the profile: a deck on WaterKin SEASTATE_SPECTRAL starts in + ! static_current_nodewise, one on the grid route in static_current (the other profile is + ! still water here, so a start that took it would differ from the deck-current start) + prof0(:, 1) = [-300.0_wp, 0.0_wp, 0.0_wp, 0.0_wp] + prof0(:, 2) = [0.0_wp, 0.0_wp, 0.0_wp, 0.0_wp] + CALL CD_AGG_Init_From_Deck(agg_u, 'agg_sc_deck.dat', DT, es, em) + CALL require(es == CD_AGG_OK, 'static-current:route-deck-current-init: '//TRIM(em)) + IF (es == CD_AGG_OK) THEN + CALL CD_AGG_CalcOutput(agg_u, es, em) + CALL CD_AGG_GetMovingPointMesh(agg_u, r0, vel, acc, lu, es, em) + END IF + CALL CD_AGG_End(agg_u, es, em) + CALL write_volturnus_deck('agg_sc_spectral.dat', extra_option='SEASTATE_SPECTRAL WaterKin', & + extra_option2='0.05 dtM', extra_option3='60.0 TMax') + CALL write_volturnus_deck('agg_sc_grid.dat', extra_option='SEASTATE_GRID WaterKin', & + extra_option2='0.05 dtM', extra_option3='60.0 TMax') + CALL CD_AGG_Init_From_Deck(agg_c, 'agg_sc_spectral.dat', DT, es, em, external_fluid=.TRUE., & + static_current=prof0, static_current_nodewise=prof) + CALL require(es == CD_AGG_OK, 'static-current:spectral-init: '//TRIM(em)) + IF (es == CD_AGG_OK) THEN + CALL CD_AGG_CalcOutput(agg_c, es, em) + CALL CD_AGG_GetMovingPointMesh(agg_c, r0, v3, a3, lc3, es, em) + CALL require(nan_max_abs(lc3 - lu) <= 1.0e-9_wp*nan_max_abs(lu), & + 'static-current:spectral-route-starts-in-the-nodewise-profile') + END IF + CALL CD_AGG_End(agg_c, es, em) + CALL CD_AGG_Init_From_Deck(agg_c, 'agg_sc_grid.dat', DT, es, em, external_fluid=.TRUE., & + static_current=prof, static_current_nodewise=prof0) + CALL require(es == CD_AGG_OK, 'static-current:grid-init: '//TRIM(em)) + IF (es == CD_AGG_OK) THEN + CALL CD_AGG_CalcOutput(agg_c, es, em) + CALL CD_AGG_GetMovingPointMesh(agg_c, r0, v3, a3, lc3, es, em) + CALL require(nan_max_abs(lc3 - lu) <= 1.0e-9_wp*nan_max_abs(lu), & + 'static-current:grid-route-starts-in-the-grid-profile') + END IF + CALL CD_AGG_End(agg_c, es, em) + ! (3) contract CALL CD_AGG_Init_From_Deck(agg_c, 'agg_sc_mixed.dat', DT, es, em, static_current=prof) CALL require(es /= CD_AGG_OK .AND. INDEX(em, 'external_fluid') > 0, & diff --git a/tests/test_openfast_preflight_logscan.py b/tests/test_openfast_preflight_logscan.py new file mode 100644 index 00000000..c55731cc --- /dev/null +++ b/tests/test_openfast_preflight_logscan.py @@ -0,0 +1,581 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""The OpenFAST pre-flight checker and log scanner (integration/openfast), on synthetic cases. + +* pre-flight: a grid that covers the lines with NY = 2 under waves along x passes; the same grid + under waves at 30 deg stops (NY = 2 across the sea) unless the deck sets waveGridCheck warn; a + grid of 100 m half-widths stops on the line ends outside it, but not on the node-wise route; + the node-wise route refuses WvCrntMod 1; the stored memory follows the documented formula and the + Catmull-Rom amplitude midway between grid points is 9/8 cos(phi/2) - 1/8 cos(3 phi/2); +* log scanner: the guard messages of a stopped run (wrapped at 100 columns, as OpenFAST prints + them) give the per-line count, time and nodes, and a provenance record beside the log is read; + a FAST.Farm log ends normally and takes its route from its record. + +usage: test_openfast_preflight_logscan.py --output

+""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import math +import shutil +import sys +import textwrap +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] + + +def load(name: str): + return load_path(ROOT / "integration" / "openfast" / f"{name}.py", name) + + +def load_path(path: Path, name: str): + spec = importlib.util.spec_from_file_location(name, path) + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + # registered first: its dataclasses look their module up while being defined + sys.modules[name] = module + spec.loader.exec_module(module) + return module + + +def write_case(folder: Path, seastate: dict[str, str], deck_extra: str = "", waterkin: str = "0") -> Path: + folder.mkdir(parents=True, exist_ok=True) + base = { + "WtrDpth": "200", "MSL2SWL": "0", "X_HalfWidth": "900", "Y_HalfWidth": "900", "Z_Depth": '"default"', + "NX": "37", "NY": "2", "NZ": "11", "WaveMod": "2", "WaveStMod": "0", "WvCrntMod": "0", + "WaveTMax": "200", "WaveDT": "0.2", "WaveHs": "6", "WaveTp": "12", "WavePkShp": "DEFAULT", + "WvLowCOff": "0.3", "WvHiCOff": "1.57", "WaveDir": "0", "WaveDirMod": "0", "WaveDirRange": "0", + "WvDiffQTF": "FALSE", "WvSumQTF": "FALSE", "CurrMod": "0", "MCFD": "0", + } + base.update(seastate) + (folder / "SeaState.dat").write_text( + "SeaState\n" + "".join(f"{v:>12} {k} - x\n" for k, v in base.items()), encoding="ascii" + ) + (folder / "HydroDyn.dat").write_text("HydroDyn\n 0 NJoints - x\n", encoding="ascii") + (folder / "case.fst").write_text( + '"SeaState.dat" SeaStFile - x\n"HydroDyn.dat" HydroFile - x\n"deck.dat" MooringFile - x\n' + "200 WtrDpth - x\n", + encoding="ascii", + ) + deck = textwrap.dedent( + f"""\ + --------------------- CableDyn Input File ----------------- + title + --------------------- POINTS ------------------------------- + ID Type X Y Z + (-) (-) (m) (m) (m) + 1 Coupled -58 0 -14 + 2 Fixed -837.6 0 -200 + 3 Coupled 29 50.2 -14 + 4 Fixed 418.8 725.4 -200 + --------------------- LINES -------------------------------- + ID NodeA NodeB Outputs + (-) (-) (-) (-) + 1 1 2 - + 2 3 4 - + --------------------- OPTIONS ------------------------------ + 0.025 dtM + {waterkin} WaterKin + {deck_extra} + --------------------- OUTPUTS ------------------------------ + END + """ + ) + (folder / "deck.dat").write_text(deck, encoding="ascii") + return folder / "case.fst" + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + pre = load("cabledyn_preflight") + scan = load("cabledyn_logscan") + out = args.output + failures = [] + + def check(ok: bool, what: str) -> None: + if not ok: + failures.append(what) + + check(pre.main([str(write_case(out / "aligned", {})), "--margin", "0"]) == 0, "aligned NY = 2 passes") + check(pre.main([str(write_case(out / "oblique", {"WaveDir": "30"})), "--margin", "0"]) == 1, + "NY = 2 under 30 deg stops") + check(pre.main([str(write_case(out / "oblique_warn", {"WaveDir": "30"}, "warn waveGridCheck")), + "--margin", "0"]) == 0, "waveGridCheck warn turns it into a note") + small = {"X_HalfWidth": "100", "Y_HalfWidth": "100", "Z_Depth": "40", "NX": "2", "NZ": "2"} + check(pre.main([str(write_case(out / "small", small))]) == 1, "line ends outside a 100 m grid stop") + report = out / "small_spectral.json" + check(pre.main([str(write_case(out / "small_spectral", small, waterkin="SEASTATE_SPECTRAL")), + "--json", str(report)]) == 0, "the node-wise route needs no grid over the lines") + data = json.loads(report.read_text(encoding="utf-8")) + check(data["spectral_supported"] is True and data["route"] == "seastate_spectral", "spectral route reported") + doppler = write_case(out / "doppler", {"WvCrntMod": "1", "CurrMod": "1"}, waterkin="SEASTATE_SPECTRAL") + check(pre.main([str(doppler)]) == 1, "the node-wise route refuses WvCrntMod 1 with a current") + # stored memory: 73 x 3 x 11 points, 1000 + 1 steps, 7 values, the surface and its spectrum + expected = 4 * ((73 * 3 * 11 * 7 + 73 * 3) * 1001 + 73 * 3 * 2 * 501) + check(abs(pre.grid_memory(37, 2, 11, 1000, 0, False) - expected) < 1.0, "the stored-memory formula") + phi = 2 * math.pi * 0.1 + check(abs(pre.kept_amplitude(10.0, 100.0) - (9 / 8 * math.cos(phi / 2) - 1 / 8 * math.cos(1.5 * phi))) < 1e-12, + "the Catmull-Rom mid-cell amplitude") + check(abs(pre.kept_amplitude(10.0, 100.0) - 0.99647) < 1e-4, "0.35 % lost at a tenth of the wavelength") + check(pre.kept_amplitude(100.0, 40.9) == 0.0, "nothing kept beyond half a wavelength (aliased)") + + # the shortest wavelength is judged on the band SeaState keeps, WvLowCOff to WvHiCOff + band = {"WaveMod": "2", "WaveHs": "6", "WaveTp": "12", "WavePkShp": "DEFAULT", "WvLowCOff": "0", "WvHiCOff": "6.28"} + full = pre.shortest_wavelength(band, 200.0, 0.0) + band["WvLowCOff"] = "2" + cut = pre.shortest_wavelength(band, 200.0, 0.0) + check(full is not None and abs(full - 22.8) < 0.1 and cut is not None and abs(cut - 2.44) < 0.01, + f"a low cut above the peak judges the kept band (22.8 m whole, 2.44 m from 2 rad/s): {full}, {cut}") + band["WvLowCOff"] = "7" + check(pre.shortest_wavelength(band, 200.0, 0.0) is None, "a band that keeps nothing has no shortest wavelength") + comps = [(0.5, 3.0, 0.0), (3.0, 1.0, 0.0)] + user = {"WaveMod": "7", "WvLowCOff": "0", "WvHiCOff": "6.28"} + both = pre.shortest_wavelength(user, 200.0, 0.0, comps) + user["WvHiCOff"] = "2" + below = pre.shortest_wavelength(user, 200.0, 0.0, comps) + check(both is not None and below is not None and both < 7.0 and below > 200.0, + f"user components above WvHiCOff are not judged: {both}, {below}") + + # log scanner + log_dir = out / "logs" + log_dir.mkdir(parents=True, exist_ok=True) + (log_dir / "a.CD.provenance.json").unlink(missing_ok=True) # from an earlier run of this test + message = ( + " FAST_Solution:CD_UpdateStates:sample_wavefield:check_wavefield_grid:CableDyn mooring module: 3 of the 31 " + "CableDyn sampling nodes in the water lie outside the SeaState wave-kinematics grid at t = 4.175 s, " + "where SeaState would give them the kinematics of the grid boundary, which are not physical there. " + "By line: line 7, 3 nodes, deepest at (x, y, z) = (60.1, 0, -20) m, shallowest at (x, y, z) = " + "(60.2, 0, -14.6) m. Farthest: x = 60.2 m (grid |x| <= X_HalfWidth = 60 m). Aborting OpenFAST." + ) + (log_dir / "a.log").write_text("\n".join(textwrap.wrap(message, 100)) + "\n", encoding="utf-8") + run = scan.scan(log_dir / "a.log") + line = run["lines"].get(7, {}) + check(run["ended"] == "stopped" and line.get("outside_nodes") == 3 and line.get("outside_first_time") == 4.175, + f"scanner reads the wrapped guard message: {run}") + check(line.get("deepest") == "60.1, 0, -20" and line.get("shallowest") == "60.2, 0, -14.6", + "scanner reads the deepest and shallowest node") + record = {"status": "stopped", "lines": [{"id": 7, "out_of_grid": {"n_nodes_max": 5, "first_time": 4.175, + "deepest_xyz": [60.1, 0.0, -25.0], "shallowest_xyz": [60.2, 0.0, -14.6]}, + "resolution_flags": [], "dropped_velocity_variance_max": None, + "dropped_acceleration_variance_max": None}]} + (log_dir / "a.CD.provenance.json").write_text(json.dumps(record), encoding="utf-8") + run = scan.scan(log_dir / "a.log") + check(run["lines"][7]["outside_nodes"] == 5 and run.get("record_status") == "stopped", + "the provenance record beside the log is preferred") + check(scan.main([str(log_dir)]) == 1, "the scanner exits 1 on a guard finding") + farm_dir = out / "farm_logs" + farm_dir.mkdir(parents=True, exist_ok=True) + (farm_dir / "f.log").write_text(" CableDyn initialization completed.\n FAST.Farm terminated normally.\n", + encoding="utf-8") + (farm_dir / "f.FarmCD.provenance.json").write_text( + json.dumps({"status": "complete", "waves": {"route": "none"}, "lines": []}), encoding="utf-8") + run = scan.scan(farm_dir / "f.log") + check(run["ended"] == "normally" and run["route"] == "none" and run.get("record_status") == "complete", + f"a FAST.Farm log and its record: {run}") + check(scan.main([str(farm_dir)]) == 0, "the scanner exits 0 without a guard finding") + # two runs in one folder: each log takes its own record, never the other's + two_dir = out / "two_runs" + two_dir.mkdir(parents=True, exist_ok=True) + clean = " CableDyn initialization completed.\n OpenFAST terminated normally.\n" + (two_dir / "A.log").write_text(clean, encoding="utf-8") + (two_dir / "B.log").write_text(clean, encoding="utf-8") + (two_dir / "A.CD.provenance.json").write_text(json.dumps( + {"status": "complete", "lines": [{"id": 1, "out_of_grid": None, "resolution_flags": []}]}), encoding="utf-8") + (two_dir / "B.CD.provenance.json").write_text(json.dumps(record), encoding="utf-8") + run = scan.scan(two_dir / "A.log") + check(run.get("record", "").endswith("A.CD.provenance.json") and "outside_nodes" not in run["lines"].get(1, {}) + and 7 not in run["lines"], f"a log takes the record of its own run: {run}") + check(scan.main([str(two_dir / "A.log")]) == 0, "a clean run beside a stopped one exits 0") + # one record and a log named after another root: not taken; a line entry without an id is skipped + other_dir = out / "other_run" + other_dir.mkdir(parents=True, exist_ok=True) + (other_dir / "A.log").write_text(clean, encoding="utf-8") + (other_dir / "B.log").write_text(clean, encoding="utf-8") + (other_dir / "B.CD.provenance.json").write_text(json.dumps( + {"status": "complete", "lines": [{"out_of_grid": None}, {"id": 2, "out_of_grid": None}]}), encoding="utf-8") + check("record" not in scan.scan(other_dir / "A.log"), "another run's record is not taken") + check(scan.scan(other_dir / "B.log").get("record_status") == "complete", "a line entry without an id is skipped") + + # SeaState's wave steps, quoted paths with spaces, malformed hull tables, refusals gated on waves + check(pre.wave_steps(200.0, 0.2) == 1000 and pre.wave_steps(4200.0, 0.2) == 21000, "even products of small factors") + check(pre.wave_steps(403.6, 0.2) == 2024, "NStepWave/2 = 1009 (prime) rounds up to 1012 = 4 x 11 x 23") + check(pre.value_key('"my dir/SeaState.dat" SeaStFile - x') == ("my dir/SeaState.dat", "SeaStFile"), + "a quoted path keeps its spaces") + bad = write_case(out / "bad_hull", {}) + (bad.parent / "HydroDyn.dat").write_text("HydroDyn\n 2 NJoints - x\nh\n(-)\n 1 0.0 0.0\n", encoding="ascii") + check(pre.main([str(bad)]) == 2, "a malformed joint table is a named input error (exit 2)") + report = out / "still_qtf.json" + check(pre.main([str(write_case(out / "still_qtf", {"WaveMod": "0", "WvDiffQTF": "TRUE"}, + waterkin="SEASTATE_SPECTRAL")), "--json", str(report)]) == 0, + "second-order flags without waves are not refused") + + # waveGridCheck warn lets line ends outside the grid run, as CableDyn does + report = out / "small_warn.json" + check(pre.main([str(write_case(out / "small_warn", small, "warn waveGridCheck")), "--json", str(report)]) == 0, + "waveGridCheck warn turns line ends outside the grid into a note") + data = json.loads(report.read_text(encoding="utf-8")) + check(not data["stops"] and any("outside the SeaState grid" in n for n in data["notes"]), + "the coverage finding is kept as a note") + # the hull-only grid resolves the shallowest wetted joint (one above the water counts as the surface) + hull = write_case(out / "hull_depths", {}, waterkin="SEASTATE_SPECTRAL") + (hull.parent / "HydroDyn.dat").write_text( + "HydroDyn\n 3 NJoints - x\nh\n(-)\n 1 0.0 0.0 -50.0\n 2 0.0 0.0 -5.0\n 3 0.0 0.0 10.0\n", + encoding="ascii") + report = out / "hull_depths.json" + check(pre.main([str(hull), "--json", str(report), "--margin", "0"]) == 0, "the hull-depth case runs") + data = json.loads(report.read_text(encoding="utf-8")) + grid, surface = data["hull_only_grid"], data["shortest_wavelength_m"] + check(grid["NZ"] == max(2, math.ceil(grid["Z_Depth"] / (surface / 10.0)) + 1), + "the hull-only grid is spaced for the surface wavelength, not the deepest joint's") + + # a guard finding that names no deck line (a rod outside the grid) still flags the run + rod_dir = out / "rod_logs" + rod_dir.mkdir(parents=True, exist_ok=True) + rod = message.replace("line 7, 3 nodes", "rod 2, 3 nodes").replace(" Aborting OpenFAST.", "") + (rod_dir / "r.log").write_text("\n".join(textwrap.wrap(rod, 100)) + "\n OpenFAST terminated normally.\n", + encoding="utf-8") + check(scan.scan(rod_dir / "r.log")["lines"] == {}, "a rod is not a deck line") + check(scan.main([str(rod_dir)]) == 1, "a run-level guard finding sets the exit status") + + # a signed value is read (a separator line is not), and both spellings of the guard option count + check(pre.value_key(" -30 WaveDir - x") == ("-30", "WaveDir"), "a negative value is read") + check(pre.value_key("---------------------- SEA STATE ---") is None, "a separator line is skipped") + check(pre.main([str(write_case(out / "oblique_neg", {"WaveDir": "-30"})), "--margin", "0"]) == 1, + "NY = 2 under -30 deg stops") + check(pre.main([str(write_case(out / "small_warn_alias", small, "warn wave_grid_check"))]) == 0, + "warn wave_grid_check is the same option") + # the converged-grid script's warn row replaces the deck's own guard setting + conv = load_path(ROOT / "validation" / "scripts" / "openfast_wavekin_converged.py", "openfast_wavekin_converged") + deck_path = out / "guard_deck.dat" + deck_path.write_text("x\n--- OPTIONS ---\n0.025 dtM\nSEASTATE WaterKin\nerror waveGridCheck\n" + "error wave_grid_check\n", encoding="latin-1") + conv.set_waterkin(deck_path, "SEASTATE_GRID", "warn waveGridCheck\n") + guard_rows = [r for r in deck_path.read_text(encoding="latin-1").splitlines() if "grid_check" in r.lower() + or "gridcheck" in r.lower()] + check(guard_rows == ["warn waveGridCheck"], f"one guard row, warn: {guard_rows}") + + # a cable submerged below the waves (every node under z_cut, no hull joint) still gets a grid: + # the margin about the origin, at least one spacing, with every node outside it + deep = write_case(out / "deep_size", {"WtrDpth": "1000", "Z_Depth": '"default"'}) + wavekin = deep.parent / "deep.CD.wavekin.out" + wavekin.write_text("Object\tNode\tX\tY\tZ\tKept\nLine1\t1\t-300\t0\t-900\t1\nLine1\t2\t-310\t5\t-920\t1\n", + encoding="utf-8") + grid_json = deep.parent / "deep_grid.json" + rc = conv.main(["size", "--fst", str(deep), "--wavekin", str(wavekin), "--margin", "20", + "--json", str(grid_json)]) + deep_grid = json.loads(grid_json.read_text(encoding="utf-8"))["seastate"] if rc == 0 else {} + check(rc == 0 and float(deep_grid.get("X_HalfWidth", 0)) >= 20.0 and float(deep_grid.get("Y_HalfWidth", 0)) >= 20.0 + and int(deep_grid.get("NX", 0)) >= 2, f"a grid for a cable below the waves: {deep_grid}") + # its two-point x axis lies along the waves (WaveDir 0), so the halving check refines it; y lies + # across a long-crested sea and keeps its two points + deep_halved = json.loads(grid_json.read_text(encoding="utf-8"))["halved"] if rc == 0 else {} + check(deep_grid.get("NX") == "2" and deep_halved.get("NX") == "3" and deep_halved.get("NY") == deep_grid.get("NY"), + f"a two-point axis along the waves is halved: {deep_grid} -> {deep_halved}") + # the same sea with a CurrMod 1 current: the current varies down to the seabed, so the grid + # keeps the whole depth (not z_cut) and the halving check refines its levels too + deep_cur = write_case(out / "deep_current", {"WtrDpth": "1000", "Z_Depth": '"default"', "CurrMod": "1", + "CurrSSV0": "1", "CurrSSDir": "0", "CurrNSRef": "20", + "CurrNSV0": "0", "CurrNSDir": "0", "CurrDIV": "0", "CurrDIDir": "0"}) + (deep_cur.parent / "deep.CD.wavekin.out").write_text(wavekin.read_text(encoding="utf-8"), encoding="utf-8") + cur_json = deep_cur.parent / "deep_grid.json" + rc = conv.main(["size", "--fst", str(deep_cur), "--wavekin", str(deep_cur.parent / "deep.CD.wavekin.out"), + "--margin", "20", "--json", str(cur_json)]) + cur_out = json.loads(cur_json.read_text(encoding="utf-8")) if rc == 0 else {"seastate": {}, "halved": {}} + check(rc == 0 and cur_out["seastate"].get("Z_Depth") == '"default"' + and int(cur_out["halved"].get("NZ", 0)) == 2 * int(cur_out["seastate"].get("NZ", 0)) - 1, + f"with a current the grid keeps the whole depth and halves z: {cur_out}") + # a near-surface current only (zero below CurrNSRef) and a depth-independent one need no full + # depth: the grid stops at z_cut (326 m here), or at CurrNSRef when that lies deeper, and z is + # not halved by default + for ns_ref, div, expect in (("20", "0", "326"), ("500", "0", "500"), ("20", "0.5", "326")): + near = write_case(out / f"near_current_{ns_ref}_{div}", + {"WtrDpth": "1000", "Z_Depth": '"default"', "CurrMod": "1", "CurrSSV0": "0", + "CurrSSDir": "0", "CurrNSRef": ns_ref, "CurrNSV0": "0.08", "CurrNSDir": "0", + "CurrDIV": div, "CurrDIDir": "0"}) + (near.parent / "deep.CD.wavekin.out").write_text(wavekin.read_text(encoding="utf-8"), encoding="utf-8") + near_json = near.parent / "deep_grid.json" + rc = conv.main(["size", "--fst", str(near), "--wavekin", str(near.parent / "deep.CD.wavekin.out"), + "--margin", "20", "--json", str(near_json)]) + near_out = json.loads(near_json.read_text(encoding="utf-8")) if rc == 0 else {"seastate": {}, "halved": {}} + check(rc == 0 and near_out["seastate"].get("Z_Depth") == expect + and near_out["halved"].get("NZ") == near_out["seastate"].get("NZ"), + f"near-surface current (CurrNSRef {ns_ref}, CurrDIV {div}): Z_Depth {expect}, z not halved: {near_out}") + + # a hull joint shallower than every node sets the spacing: the grid serves the hull too + hull_size = write_case(out / "hull_size", {}) + hull_kin = hull_size.parent / "hull.CD.wavekin.out" + hull_kin.write_text("Object\tNode\tX\tY\tZ\tKept\nLine1\t1\t-300\t0\t-100\t1\nLine1\t2\t-310\t5\t-120\t1\n", + encoding="utf-8") + spacings = [] + for joints_table in (" 0 NJoints - x\n", " 1 NJoints - x\nh\n(-)\n 1 0.0 0.0 -5.0\n"): + (hull_size.parent / "HydroDyn.dat").write_text("HydroDyn\n" + joints_table, encoding="ascii") + hull_json = hull_size.parent / "hull_grid.json" + rc_hull = conv.main(["size", "--fst", str(hull_size), "--wavekin", str(hull_kin), "--json", str(hull_json)]) + spacings.append(json.loads(hull_json.read_text(encoding="utf-8"))["spacing_m"] if rc_hull == 0 else math.nan) + check(spacings[1] < 0.5 * spacings[0], + f"a joint at -5 m spaces the grid finer than nodes at -100 m alone: {spacings}") + # waves along y (WaveDir 90): by default the halving refines y, which they vary along, not the + # uniform x; a --halve that refines nothing stops rather than compare a grid with itself + rc_y = conv.main(["size", "--fst", str(hull_size), "--wavekin", str(hull_kin), "--wave-dir", "90", + "--json", str(hull_json)]) + y_out = json.loads(hull_json.read_text(encoding="utf-8")) if rc_y == 0 else {"seastate": {}, "halved": {}} + check(rc_y == 0 and y_out["seastate"].get("NX") == "2" and y_out["halved"].get("NX") == "2" + and int(y_out["halved"].get("NY", 0)) == 2 * int(y_out["seastate"].get("NY", 0)) - 1, + f"waves along y: the default halving refines y: {y_out}") + try: + conv.main(["size", "--fst", str(hull_size), "--wavekin", str(hull_kin), "--wave-dir", "90", "--halve", "x"]) + check(False, "a halving along x alone under waves along y is refused") + except SystemExit as stop: + check("refines no axis" in str(stop), f"the refusal names the cause: {stop}") + + # an indented dtM row still takes the options, and a deck without one is a named error + deck_path.write_text("x\n--- OPTIONS ---\n 0.025 dtM\n", encoding="latin-1") + conv.set_waterkin(deck_path, "SEASTATE_SPECTRAL", "") + check("SEASTATE_SPECTRAL WaterKin" in deck_path.read_text(encoding="latin-1"), + "the WaterKin row is added after an indented dtM") + # a quoted WaterKin file name with a space is replaced whole + deck_path.write_text('x\n--- OPTIONS ---\n0.025 dtM\n"water kin.dat" WaterKin\n', encoding="latin-1") + conv.set_waterkin(deck_path, "SEASTATE_GRID", "") + rows = [pre.value_key(r) for r in deck_path.read_text(encoding="latin-1").splitlines()] + check(("SEASTATE_GRID", "WaterKin") in rows and not any(r and "kin.dat" in r[0] for r in rows), + f"a quoted WaterKin file name is replaced whole: {rows}") + deck_path.write_text("x\n", encoding="latin-1") + try: + conv.set_waterkin(deck_path, "SEASTATE_SPECTRAL", "") + check(False, "a deck without dtM is refused") + except SystemExit: + pass + # stock MoorDyn seven-column LINES rows are checked like CableDyn's own + stock = write_case(out / "stock_lines", small) + deck_text = (stock.parent / "deck.dat").read_text(encoding="ascii") + deck_text = deck_text.replace("1 1 2 -\n", "1 main 1 2 850 50 -\n").replace("2 3 4 -\n", "2 main 3 4 850 50 -\n") + (stock.parent / "deck.dat").write_text(deck_text, encoding="ascii") + report = out / "stock_lines.json" + pre.main([str(stock), "--json", str(report)]) + stock_lines = json.loads(report.read_text(encoding="utf-8"))["lines"] + check(len(stock_lines) == 2 and all(entry["outside_axes"] for entry in stock_lines), + f"seven-column LINES rows are read and checked: {stock_lines}") + + # still water without current reads no grid: a shallow Z_Depth is no finding (CableDyn skips it) + shallow = {"Z_Depth": "40", "NZ": "2"} + check(pre.main([str(write_case(out / "still_shallow", {"WaveMod": "0", **shallow})), "--margin", "0"]) == 0, + "still water with a shallow grid passes") + check(pre.main([str(write_case(out / "current_shallow", {"WaveMod": "0", "CurrMod": "1", **shallow})), + "--margin", "0"]) == 1, "a shallow grid under SeaState's current stops") + + # --- the tools read cases as CableDyn and OpenFAST do (each check failed before its fix) --- + def runs(case: Path, *extra: str) -> tuple[int, dict]: + report = case.parent / "report.json" + report.unlink(missing_ok=True) + code = pre.main([str(case), "--json", str(report), *extra]) + return code, json.loads(report.read_text(encoding="utf-8")) if report.exists() else {} + + def waterkin_file(folder: Path, wavekinmod: str, currentmod: str) -> None: + rows = ["MoorDyn v2 water kinematics", "x", "--- waves ---", f"{wavekinmod} WaveKinMod", '"" WaveKinFile', + "0.25 dtWave", "0 WaveDir", "- x", "1", "- y", "1", "- z", "1", "--- current ---", + f"{currentmod} CurrentMod", "z ux uy", "(m) (m/s) (m/s)", "0 0.5 0", "-200 0 0"] + (folder / "kin.dat").write_text("\n".join(rows) + "\n", encoding="ascii") + + def item_A() -> None: + # A: a WaterKin file decides what the lines take; neither waves nor current: the grid is not read + wk = write_case(out / "waterkin_file", small, waterkin="kin.dat") + waterkin_file(wk.parent, "0", "1") + code, data = runs(wk) + check(code == 0 and not data["line_waves"] and not data["line_current"], + f"a WaterKin file without SeaState waves or current: the lines read no grid ({code})") + waterkin_file(wk.parent, "SEASTATE", "1") + check(runs(wk)[0] == 1, "a WaterKin file taking SeaState's waves: the grid coverage counts") + + def item_B() -> None: + # B: WaveMod 6 is judged from the supplied data, WaveMod 7 from its component directions + ext = write_case(out / "external", {"WaveMod": "6", "WaveDir": "30", "WvKinFile": "ext", "NX": "2", "NY": "2", + "X_HalfWidth": "900", "Y_HalfWidth": "900", "NZ": "2"}) + + def external_data(folder: Path, along_y: bool) -> None: + header = ["x"] * 13 + for ext_name in (".Vxi", ".Vyi", ".Vzi", ".Axi", ".Ayi", ".Azi"): + rows = [] + for step in range(3): + for _ in range(2): # z levels + for j in range(3): # y points + base = math.cos(0.3 * step + (0.5 * j if along_y else 0.0)) + rows.append(" ".join(f"{base + (0.0 if along_y else 0.2 * i):.6e}" for i in range(3))) + (folder / f"ext{ext_name}").write_text("\n".join(header + rows) + "\n", encoding="ascii") + + external_data(ext.parent, along_y=False) + code, data = runs(ext, "--margin", "0") + check(code == 1 and any("NX" in s and "NY" not in s for s in data["stops"]), + f"WaveMod 6 varying along x only: NX = 2 stops, NY = 2 does not, whatever WaveDir says ({data.get('stops')})") + comp = write_case(out / "components", {"WaveMod": "7", "WaveDir": "30", "WvKinFile": "comp.txt"}) + (comp.parent / "comp.txt").write_text("omega H dir phase\n0.5 2.0 0.0 0.0\n0.7 1.0 0.0 30.0\n", encoding="ascii") + check(runs(comp, "--margin", "0")[0] == 0, "WaveMod 7 components along x on NY = 2 pass, WaveDir ignored") + (comp.parent / "comp.txt").write_text("omega H dir phase\n0.5 2.0 0.0 0.0\n0.7 1.0 45.0 30.0\n", encoding="ascii") + check(runs(comp, "--margin", "0")[0] == 1, "WaveMod 7 with a component at 45 deg on NY = 2 stops") + # a component SeaState removes (above WvHiCOff = 1.57 rad/s) does not count + (comp.parent / "comp.txt").write_text("omega H dir phase\n0.5 2.0 0.0 0.0\n2.0 1.0 45.0 30.0\n", encoding="ascii") + check(runs(comp, "--margin", "0")[0] == 0, "WaveMod 7: an oblique component above WvHiCOff does not stop NY = 2") + # components at 0 and 180 deg are uniform in y, as CableDyn's check judges them (modulo 180) + (comp.parent / "comp.txt").write_text("omega H dir phase\n0.5 2.0 0.0 0.0\n0.7 1.0 180.0 30.0\n", encoding="ascii") + check(runs(comp, "--margin", "0")[0] == 0, "WaveMod 7: components at 0 and 180 deg pass NY = 2") + # at 90 and 270 deg they are uniform in x: NX = 2 passes there, NY = 2 (along the waves) stops + (comp.parent / "comp.txt").write_text("omega H dir phase\n0.5 2.0 90.0 0.0\n0.7 1.0 270.0 30.0\n", encoding="ascii") + code, data = runs(comp, "--margin", "0") + check(code == 1 and not any("NX" in s for s in data.get("stops", [])), + f"WaveMod 7: components at 90 and 270 deg stop NY = 2 only, not NX: {data.get('stops')}") + + def item_1() -> None: + # 1: MSL2SWL with SeaState waves stops CableDyn's initialisation + check(runs(write_case(out / "msl", {"MSL2SWL": "1.5"}), "--margin", "0")[0] == 1, "MSL2SWL = 1.5 m stops") + + def item_3() -> None: + # 3: spreading counts only for WaveMod 2, 3 or 4 and more than one direction + spread = {"WaveDirMod": "1", "WaveDirRange": "60", "WaveNDir": "5"} + check(runs(write_case(out / "spread_regular", {"WaveMod": "1", **spread}), "--margin", "0")[0] == 0, + "WaveDirMod 1 on a regular wave (WaveMod 1) is not short-crested") + check(runs(write_case(out / "spread_one", {**spread, "WaveNDir": "1"}), "--margin", "0")[0] == 0, + "WaveDirMod 1 with one direction is not short-crested") + check(runs(write_case(out / "spread", spread), "--margin", "0")[0] == 1, "a short-crested sea on NY = 2 stops") + + def item_4() -> None: + # 4: WvCrntMod without a current is off in SeaState + code, data = runs(write_case(out / "wvcrnt_still", {"WvCrntMod": "1"}, waterkin="SEASTATE_SPECTRAL")) + check(code == 0 and data["spectral_supported"], "WvCrntMod 1 with CurrMod 0 is not refused") + + def item_5() -> None: + # 5: Fortran spellings of a logical + for spelling in (".TRUE.", ".T.", "t", "True"): + code, data = runs(write_case(out / "qtf", {"WvDiffQTF": spelling}, waterkin="SEASTATE_SPECTRAL")) + check("second-order kinematics" in data.get("spectral_refusals", []), f"WvDiffQTF {spelling} is true") + + def item_6() -> None: + # 6: OpenFAST takes the name from either word, without regard to case, commas and semicolons separating + for row in ("WaveDir 30", "30 wavedir", "30, WaveDir", "30;WAVEDIR"): + case = write_case(out / "words", {}) + text = (case.parent / "SeaState.dat").read_text(encoding="ascii") + (case.parent / "SeaState.dat").write_text(text.replace(" 0 WaveDir - x", row), encoding="ascii") + check(runs(case, "--margin", "0")[0] == 1, f"'{row}' sets WaveDir 30 (NY = 2 stops)") + + def item_7() -> None: + # 7: the two spellings of an option are one option, the last row winning + check(runs(write_case(out / "alias_last", {"WaveDir": "30"}, "warn waveGridCheck\nerror wave_grid_check"), + "--margin", "0")[0] == 1, "error wave_grid_check after warn waveGridCheck: the guard stops") + + def item_8() -> None: + # 8: CableDyn's section names and its header rule + named = write_case(out / "section_names", small) + text = (named.parent / "deck.dat").read_text(encoding="ascii") + text = text.replace("--------------------- POINTS -------------------------------", + "------- CONNECTION PROPERTIES ------- # MoorDyn v1 name") + text = text.replace("--------------------- LINES --------------------------------", "- - --- LINE PROPERTIES") + (named.parent / "deck.dat").write_text(text, encoding="ascii") + code, data = runs(named) + check(code == 1 and len(data["lines"]) == 2 and all(e["outside_axes"] for e in data["lines"]), + f"CONNECTION PROPERTIES and LINE PROPERTIES sections are read ({data.get('lines')})") + + def item_9() -> None: + # 9: a Body point is an offset from its body + body = write_case(out / "body_point", {"X_HalfWidth": "300", "Y_HalfWidth": "300", "Z_Depth": "40", + "NX": "2", "NZ": "2"}) + text = (body.parent / "deck.dat").read_text(encoding="ascii") + text = text.replace("--------------------- POINTS", "--------------------- BODIES ---\nID Type X Y Z r p y M V\n" + "1 Coupled 500 0 0 0 0 0 1e6 0 0 0 0 0 0\n--------------------- POINTS") + text = text.replace("1 Coupled -58 0 -14\n2 Fixed -837.6 0 -200\n", "1 Body1 0 0 -10\n2 Fixed -100 0 -30\n") + text = text.replace("2 3 4 -\n", "") + (body.parent / "deck.dat").write_text(text, encoding="ascii") + code, data = runs(body, "--margin", "0") + check(data.get("lines", [{}])[0].get("outside_axes") == ["x"], + f"a Body1 point at 500 m lies outside a 300 m grid ({data.get('lines')})") + + def item_11() -> None: + # 11: a missing log is reported, and no readable log is an input error + check(scan.main([str(out / "no_such.log")]) == 2, "a missing log exits 2") + + def item_12() -> None: + # 12: the converged-grid script edits the OPTIONS rows only, never a comment + deck_path.write_text("--- OPTIONS ---\n# 0.1 dtM\n! SEASTATE WaterKin\n0.025 dtM\n--- OUTPUTS ---\n" + "SEASTATE WaterKin\n", encoding="latin-1") + conv.set_waterkin(deck_path, "SEASTATE_SPECTRAL", "warn waveGridCheck\n") + rows = deck_path.read_text(encoding="latin-1").splitlines() + check(rows[1:3] == ["# 0.1 dtM", "! SEASTATE WaterKin"] and rows[3:6] == ["0.025 dtM", + "SEASTATE_SPECTRAL WaterKin", "warn waveGridCheck"] and rows[-1] == "SEASTATE WaterKin", + f"comments and other sections are left alone: {rows}") + + def item_13() -> None: + # 13: the module files resolve from the .fst folder and stay inside the copy + nested = out / "nested_case" + inner = write_case(nested / "run", {}) + (nested / "grid.json").write_text(json.dumps({"seastate": {"NX": "41"}, "halved": {"NX": "81"}}), encoding="utf-8") + conv.prepare(argparse.Namespace(grid=nested / "grid.json", case_dir=nested, fst="run/case.fst", + out=out / "nested_out", tmax=None)) + check("41 NX" in (out / "nested_out" / "reference" / "run" / "SeaState.dat").read_text(encoding="ascii"), + "prepare edits the SeaState file next to the .fst") + text = inner.read_text(encoding="ascii").replace('"SeaState.dat"', '"../../outside.dat"') + inner.write_text(text, encoding="ascii") + try: + conv.prepare(argparse.Namespace(grid=nested / "grid.json", case_dir=nested, fst="run/case.fst", + out=out / "nested_out", tmax=None)) + check(False, "a SeaState file outside the case is refused") + except SystemExit: + pass + inner.write_text(text.replace('"../../outside.dat"', '"SeaState.dat"'), encoding="ascii") + # an output folder that is the case, holds it or lies inside it is refused before anything is + # deleted: a case folder named "reference" under --out, and --out inside the case + named = out / "overlap" / "reference" + if named.exists(): + shutil.rmtree(named) + shutil.copytree(nested, named) + for case_dir, out_dir, what in ((named, named.parent, "the case is an output folder"), + (named, named / "sub", "the output lies inside the case")): + try: + conv.prepare(argparse.Namespace(grid=nested / "grid.json", case_dir=case_dir, fst="run/case.fst", + out=out_dir, tmax=None)) + check(False, f"overlapping folders are refused: {what}") + except SystemExit as stop: + check("overlaps" in str(stop), f"the refusal names the overlap ({what}): {stop}") + check((named / "run" / "case.fst").exists(), f"the case survives a refused prepare ({what})") + + def item_S() -> None: + # own sweep: another mooring module is not checked; without SeaState nothing reads a grid; + # an end above the still-water level carries no fluid load and the guard skips it + other = write_case(out / "moordyn", small) + other.write_text(other.read_text(encoding="ascii") + "3 CompMooring - x\n", encoding="ascii") + check(pre.main([str(other)]) == 2, "CompMooring 3 is not a CableDyn case") + still = write_case(out / "no_seastate", small) + still.write_text(still.read_text(encoding="ascii") + "0 CompSeaSt - x\n", encoding="ascii") + check(pre.main([str(still)]) == 0, "CompSeaSt 0: no grid is read") + # nor the SeaState file, which a case without SeaState need not have + unused = write_case(out / "no_seastate_file", small) + unused.write_text(unused.read_text(encoding="ascii").replace('"SeaState.dat"', '"unused"') + + "0 CompSeaSt - x\n", encoding="ascii") + check(pre.main([str(unused)]) == 0, "CompSeaSt 0: a SeaStFile that does not exist is not opened") + dry = write_case(out / "dry_end", {"X_HalfWidth": "100", "Y_HalfWidth": "100"}) + text = (dry.parent / "deck.dat").read_text(encoding="ascii") + text = text.replace("2 Fixed -837.6 0 -200\n", "2 Fixed -837.6 0 5\n").replace("2 3 4 -\n", "") + (dry.parent / "deck.dat").write_text(text, encoding="ascii") + check(runs(dry, "--margin", "0")[1].get("lines", [{}])[0].get("outside_axes") == [], + "a line end above the still-water level is not checked against the grid") + + for tag, item in (("S", item_S), ("A", item_A), ("B", item_B), ("1", item_1), ("3", item_3), ("4", item_4), ("5", item_5), + ("6", item_6), ("7", item_7), ("8", item_8), ("9", item_9), ("11", item_11), ("12", item_12), + ("13", item_13)): + try: + item() + except Exception as error: # an item that raises fails, the others still run + failures.append(f"item {tag} raised {type(error).__name__}: {error}") + + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS: pre-flight checker and log scanner") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_provenance.f90 b/tests/test_provenance.f90 new file mode 100644 index 00000000..2eafdd2d --- /dev/null +++ b/tests/test_provenance.f90 @@ -0,0 +1,130 @@ +! File: tests/test_provenance.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +PROGRAM test_provenance + !! The provenance record (CableDyn_Provenance): + !! * the component fingerprint is FNV-1a 64-bit over the bytes as stored: the empty input + !! gives the offset basis cbf29ce484222325, the bytes "abcd" fc179f83ee0724dd and the + !! single-precision values 1, -2.5, 3.25 01970969efc013e8 (reference values of the + !! algorithm, computed independently); + !! * the record is written with null for what is unknown, a seed as written (a number or a + !! string), the line entries, and replaced in one step: a second write leaves the new + !! status and no temporary file. + USE CableDyn_Precision, ONLY: wp + USE CableDyn_Provenance + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT8, INT32, REAL32 + IMPLICIT NONE + + TYPE(CD_Fingerprint) :: h + TYPE(CD_Prov) :: p + INTEGER :: nfail, es, u, ios, nbytes + CHARACTER(256) :: em + CHARACTER(:), ALLOCATABLE :: text + LOGICAL :: there + CHARACTER(*), PARAMETER :: PATH = 'provenance_test.CD.provenance.json' + + nfail = 0 + CALL CD_Fingerprint_Init(h) + CALL require(CD_Fingerprint_Hex(h) == 'cbf29ce484222325', 'FNV-1a offset basis') + CALL CD_Fingerprint_Add(h, TRANSFER([97_INT8, 98_INT8, 99_INT8, 100_INT8], [0.0_REAL32])) + CALL require(CD_Fingerprint_Hex(h) == 'fc179f83ee0724dd', 'FNV-1a of "abcd": '//CD_Fingerprint_Hex(h)) + CALL CD_Fingerprint_Init(h) + CALL CD_Fingerprint_Add(h, [1.0_REAL32, -2.5_REAL32, 3.25_REAL32]) + CALL require(CD_Fingerprint_Hex(h) == '01970969efc013e8', 'FNV-1a of three singles: '//CD_Fingerprint_Hex(h)) + + p%cabledyn_version = '9.9.9' + p%host = 'openfast' + p%route = 'seastate_grid' + p%has_wave_mod = .TRUE. + p%wave_mod = 2 + p%has_seed = .TRUE. + p%seed = ['123456789', 'RANLUX '] + p%has_dir = .TRUE. + p%dir = 30.0_wp + p%fingerprint = '0123456789abcdef' + p%has_grid = .TRUE. + p%nx = 37 + p%ny = 2 + p%nz = 11 + p%grid_check = 'warn' + p%has_wave_dt = .TRUE. + p%wave_dt = REAL(0.2_REAL32, wp) ! SeaState's single-precision wave step + ALLOCATE (p%lines(2)) + p%lines(1)%id = 1 + p%lines(1)%n_nodes = 51 + p%lines(1)%has_oog = .TRUE. + p%lines(1)%oog_n_nodes_max = 49 + p%lines(1)%oog_deepest = [-735.5_wp, 0.0_wp, -200.0_wp] + p%lines(1)%oog_shallowest = [-77.5_wp, 0.0_wp, -41.9_wp] + p%lines(1)%has_wvr = .TRUE. + p%lines(1)%wvr = 0.375_wp + p%lines(1)%flags = [CHARACTER(64) :: 'grid_coarse_across_waves'] + p%lines(2)%id = 4 + ALLOCATE (p%lines(2)%flags(0)) + CALL CD_Prov_Write(p, PATH, 'init', es, em) + CALL require(es == 0, 'the first write: '//TRIM(em)) + CALL CD_Prov_Write(p, PATH, 'complete', es, em) + CALL require(es == 0, 'the second write: '//TRIM(em)) + INQUIRE (FILE=PATH//'.tmp', EXIST=there) + CALL require(.NOT. there, 'no temporary file is left') + OPEN (NEWUNIT=u, FILE=PATH, ACCESS='STREAM', FORM='UNFORMATTED', ACTION='READ', IOSTAT=ios) + CALL require(ios == 0, 'the record opens') + IF (ios == 0) THEN + INQUIRE (UNIT=u, SIZE=nbytes) + ALLOCATE (CHARACTER(MAX(nbytes, 1)) :: text) + READ (u, IOSTAT=ios) text + CALL require(ios == 0, 'the record reads') + CLOSE (u) + CALL has('"schema": "cabledyn.provenance/1"') + CALL has('"cabledyn_version": "9.9.9"') + CALL has('"host_version": null') + CALL has('"wave_seed": [123456789, "RANLUX"]') + CALL has('"wave_hs": null') + CALL has('"wave_dir_deg": 3.0000000000000000E+001') + CALL has('"component_fingerprint": "0123456789abcdef"') + CALL has('"nx": 37, "ny": 2, "nz": 11') + CALL has('"wave_grid_check": "warn"') + CALL has('"id": 1, "n_nodes": 51') + CALL has('"n_nodes_max": 49') + CALL has('"weighted_velocity_ratio_max": 3.7500000000000000E-001') + CALL has('"resolution_flags": ["grid_coarse_across_waves"]') + CALL has('"id": 4, "n_nodes": null') + CALL has('"out_of_grid": null') + CALL has('"resolution_flags": []') + CALL has('"dropped_velocity_variance_max": null') + CALL has('"restarted_from": null') + CALL has('"wave_dt": 2.0E-001') + CALL has('"status": "complete"') + END IF + ! a record that cannot replace its target (a directory of that name, made by CMake) fails + ! and leaves no temporary file + CALL CD_Prov_Write(p, 'blocked.json', 'init', es, em) + CALL require(es /= 0, 'a failed replacement is reported') + INQUIRE (FILE='blocked.json.tmp', EXIST=there) + CALL require(.NOT. there, 'a failed replacement leaves no temporary file') + OPEN (NEWUNIT=u, FILE=PATH, STATUS='OLD', IOSTAT=ios) + IF (ios == 0) CLOSE (u, STATUS='DELETE') + + IF (nfail > 0) THEN + WRITE (*, '(A,I0,A)') 'FAIL: ', nfail, ' assertion(s) failed' + ERROR STOP 1 + END IF + WRITE (*, '(A)') 'PASS: provenance record (FNV-1a fingerprint, nulls, seeds, lines, atomic rewrite)' + +CONTAINS + + SUBROUTINE require(ok, what) + LOGICAL, INTENT(IN) :: ok + CHARACTER(*), INTENT(IN) :: what + IF (.NOT. ok) THEN + nfail = nfail + 1 + WRITE (*, '(A)') 'FAIL: '//what + END IF + END SUBROUTINE require + + SUBROUTINE has(s) + CHARACTER(*), INTENT(IN) :: s + CALL require(INDEX(text, s) > 0, 'the record holds '//s) + END SUBROUTINE has + +END PROGRAM test_provenance diff --git a/tests/test_provenance_sidecar.py b/tests/test_provenance_sidecar.py new file mode 100644 index 00000000..61fda3f2 --- /dev/null +++ b/tests/test_provenance_sidecar.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""The standalone provenance record .CD.provenance.json is valid JSON of schema 1. + +Gate, on the driver's own output: a static deck without waves gives route "none" and its line ids; +the same deck with a JONSWAP waves row and a WaveSeed gives route "deck" with the row's height, +period and direction and the seed as a number; a deck that fails after parsing leaves the record +with status "stopped". Every key of schema "cabledyn.provenance/1" is present, unknown values are +null, and no temporary file is left. + +usage: test_provenance_sidecar.py --exe --output +""" + +from __future__ import annotations + +import argparse +import json +import re +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +DECK = ROOT / "examples" / "chain_catenary_r3_100m.dat" +WAVE_KEYS = { + "route", "wave_mod", "wave_seed", "wave_hs", "wave_tp", "wave_dir_deg", "wave_dir_mod", + "n_components", "component_fingerprint", "wave_dt", "wave_tmax", "effective_water_depth", + "wave_kin_tol", "source_file", +} +LINE_KEYS = { + "id", "n_nodes", "out_of_grid", "resolution_flags", "dropped_velocity_variance_max", + "dropped_acceleration_variance_max", +} + + +def run(exe: Path, deck: Path, root: Path) -> int: + proc = subprocess.run([str(exe), str(deck), str(root)], capture_output=True, text=True) + return proc.returncode + + +def record(root: Path) -> dict: + path = Path(str(root) + ".CD.provenance.json") + if Path(str(path) + ".tmp").exists(): + raise AssertionError("a temporary provenance file was left") + data = json.loads(path.read_text(encoding="utf-8")) + top = { + "schema", "cabledyn_version", "host", "host_version", "waves", "grid", "lines", + "restarted_from", "status", + } + if set(data) != top or set(data["waves"]) != WAVE_KEYS: + raise AssertionError(f"keys differ from schema 1: {sorted(data)} {sorted(data['waves'])}") + if any(set(line) != LINE_KEYS for line in data["lines"]): + raise AssertionError("a line entry has other keys than schema 1") + if data["schema"] != "cabledyn.provenance/1" or data["host"] != "standalone": + raise AssertionError(f"schema or host: {data['schema']} {data['host']}") + return data + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--exe", type=Path, required=True) + parser.add_argument("--output", type=Path, required=True) + args = parser.parse_args() + args.output.mkdir(parents=True, exist_ok=True) + failures = [] + text = DECK.read_text(encoding="utf-8") + + still = args.output / "still" + if run(args.exe, DECK, still) != 0: + failures.append("the still-water deck runs") + else: + data = record(still) + if data["waves"]["route"] != "none" or data["grid"] is not None or data["status"] != "complete": + failures.append(f"still water: {data['waves']['route']} {data['status']}") + if [line["id"] for line in data["lines"]] != [1] or data["waves"]["wave_hs"] is not None: + failures.append("still water: line ids and null wave values") + + wavy = args.output / "wavy.dat" + deck = re.sub(r"(?m)^(\S+\s+WtrDpth\b.*)$", r"\1\n0.1 dtM\n2.0 TMax\n7 WaveSeed", text, count=1) + deck = re.sub(r"(?m)^none\s+waves\b.*$", "jonswap 2.0 8.0 3.3 30.0 waves", deck, count=1) + wavy.write_text(deck, encoding="utf-8") + if run(args.exe, wavy, args.output / "wavy") != 0: + failures.append("the JONSWAP deck runs") + else: + data = record(args.output / "wavy") + waves = data["waves"] + if (waves["route"], waves["wave_hs"], waves["wave_tp"], waves["wave_dir_deg"], waves["wave_seed"], + waves["wave_dir_mod"]) != ("deck", 2.0, 8.0, 30.0, [7, None], 0): + failures.append(f"JONSWAP deck: {waves}") + + broken = args.output / "broken.dat" + # a bathymetry file that does not exist: the deck parses, the run then fails loading it + broken.write_text( + re.sub(r"(?m)^\S+\s+WtrDpth\b.*$", "missing.txt bathymetryFile", text, count=1), + encoding="utf-8", + ) + if run(args.exe, broken, args.output / "broken") == 0: + failures.append("the deck with a missing bathymetry file fails") + elif record(args.output / "broken")["status"] != "stopped": + failures.append("a run that fails after parsing leaves status stopped") + + if failures: + print("FAIL: " + "; ".join(failures)) + return 1 + print("PASS: the standalone provenance record follows schema 1 (route none, deck sea, stopped run)") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_wave_nodewise.f90 b/tests/test_wave_nodewise.f90 new file mode 100644 index 00000000..6e559276 --- /dev/null +++ b/tests/test_wave_nodewise.f90 @@ -0,0 +1,411 @@ +! File: tests/test_wave_nodewise.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +PROGRAM test_wave_nodewise + !! The node-wise wave kinematics (CableDyn_WaveNodewise) against closed forms: + !! * one component in finite depth and one in deep water: elevation, velocity, acceleration + !! and dynamic pressure equal linear (Airy) theory in SeaState's convention to 1e-12, at both + !! ends of a wave step, with the zero-frequency term and the Nyquist weight 1/N; + !! * the time derivatives equal central differences, also under Wheeler stretching, where they + !! include the motion of the mapped depth; + !! * extrapolation stretching (WaveStMod 2) adds z times the vertical derivative at the surface, + !! vertical stretching (1) takes the surface value, Wheeler stretching (3) the value at + !! h (h + z)/(h + eta) - h; + !! * cubic Hermite interpolation over a wave step is exact at the ends and within (omega dt)^4 + !! of the field between them; + !! * truncation: the kept prefix grows toward the surface, the dropped velocity and acceleration + !! variances, relative to the totals at the node's depth, stay within the tolerance there and + !! at every depth below, and tol = 0 keeps every component. + USE CableDyn_Precision, ONLY: wp + USE CableDyn_WaveNodewise + IMPLICIT NONE + + REAL(wp), PARAMETER :: PI = 3.14159265358979323846_wp, G = 9.80665_wp, RHO = 1025.0_wp + INTEGER, PARAMETER :: N = 1000, N2 = N/2 + REAL(wp), PARAMETER :: DT = 0.5_wp + REAL(wp) :: cre(0:N2), cim(0:N2), dir(0:N2), kv(0:N2) + TYPE(CD_NWK_Field) :: f + INTEGER :: nfail, es, i + CHARACTER(256) :: em + + nfail = 0 + + CALL single_component(50.0_wp, 64, 30.0_wp, 'finite depth') + CALL single_component(3000.0_wp, 120, -150.0_wp, 'deep water') + CALL derivatives() + CALL stretching() + CALL hermite() + CALL truncation() + CALL wheeler_truncation() + CALL limits() + CALL velocity_ratio() + + IF (nfail > 0) THEN + WRITE (*, '(A,I0,A)') 'FAIL: ', nfail, ' assertion(s) failed' + ERROR STOP 1 + END IF + WRITE (*, '(A)') 'PASS: node-wise wave kinematics against Airy theory, derivatives, stretching, Hermite, truncation' + +CONTAINS + + SUBROUTINE require(ok, what) + LOGICAL, INTENT(IN) :: ok + CHARACTER(*), INTENT(IN) :: what + IF (.NOT. ok) THEN + nfail = nfail + 1 + WRITE (*, '(A)') 'FAIL: '//what + END IF + END SUBROUTINE require + + REAL(wp) FUNCTION wavenumber(om, h) RESULT(k) + REAL(wp), INTENT(IN) :: om, h + INTEGER :: it + k = om*om/G + DO it = 1, 100 + k = k - (G*k*TANH(k*h) - om*om)/(G*TANH(k*h) + G*k*h/COSH(k*h)**2) + END DO + END FUNCTION wavenumber + + SUBROUTINE clear() + cre = 0.0_wp + cim = 0.0_wp + dir = 0.0_wp + kv = 0.0_wp + END SUBROUTINE clear + + SUBROUTINE put(i, a, phi, beta, h) + !! component i with amplitude a, phase phi and direction beta (deg) + INTEGER, INTENT(IN) :: i + REAL(wp), INTENT(IN) :: a, phi, beta, h + cre(i) = a*COS(phi)*REAL(N, wp)/2.0_wp + cim(i) = a*SIN(phi)*REAL(N, wp)/2.0_wp + dir(i) = beta + kv(i) = wavenumber(2.0_wp*PI*REAL(i, wp)/(REAL(N, wp)*DT), h) + END SUBROUTINE put + + SUBROUTINE single_component(h, ic, beta, tag) + REAL(wp), INTENT(IN) :: h, beta + INTEGER, INTENT(IN) :: ic + CHARACTER(*), INTENT(IN) :: tag + REAL(wp), PARAMETER :: A = 1.3_wp, PHI = 0.7_wp, X = 13.0_wp, Y = -7.0_wp, Z = -11.0_wp, ETA0 = 0.1_wp + REAL(wp) :: val(CD_NWK_NQ, 2), der(CD_NWK_NQ, 2), ref(CD_NWK_NQ), om, k, b, th, t, c1, c2, c3, scale + INTEGER :: e, nstep, q + CALL clear() + CALL put(ic, A, PHI, beta, h) + cre(0) = ETA0*REAL(N, wp) + cre(N2) = 0.02_wp*REAL(N, wp) ! Nyquist: weight 1/N + dir(N2) = 0.0_wp + kv(N2) = wavenumber(PI/DT, h) + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, h, RHO, G, 0, 0.0_wp, es, em) + CALL require(es == CD_NWK_OK, tag//': init '//TRIM(em)) + CALL require(f%m == 2, tag//': two components kept') + nstep = 37 + CALL CD_NWK_Set_Step(f, nstep) + CALL CD_NWK_Eval(f, X, Y, Z, f%m, val, der) + om = 2.0_wp*PI*REAL(ic, wp)/(REAL(N, wp)*DT) + k = kv(ic) + b = beta*PI/180.0_wp + c1 = COSH(k*(Z + h))/SINH(k*h) + c2 = SINH(k*(Z + h))/SINH(k*h) + c3 = COSH(k*(Z + h))/COSH(k*h) + IF (k*h > 200.0_wp) THEN + c1 = EXP(k*Z) + c2 = EXP(k*Z) + c3 = EXP(k*Z) + END IF + DO e = 1, 2 + t = REAL(nstep + e - 1, wp)*DT + th = om*t - k*(X*COS(b) + Y*SIN(b)) + PHI + ref(1) = A*om*COS(b)*c1*COS(th) + ref(2) = A*om*SIN(b)*c1*COS(th) + ref(3) = -A*om*c2*SIN(th) + ref(4) = -A*om*om*COS(b)*c1*SIN(th) + ref(5) = -A*om*om*SIN(b)*c1*SIN(th) + ref(6) = -A*om*om*c2*COS(th) + ! the Nyquist component: 0.02 cos(pi t/DT - k_N x) (x along 0 deg) in the elevation, pressure, + ! and velocity; at the wave steps t = n DT its time factor is +-1 + ref(7) = ETA0 + A*COS(th) + 0.02_wp*COS(PI*REAL(nstep + e - 1, wp) - kv(N2)*X) + ref(8) = RHO*G*(ETA0 + A*c3*COS(th)) + scale = A*MAX(1.0_wp, om*om) + DO q = 1, 6 + CALL require(ABS(val(q, e) - (ref(q) + nyq_vel(q, e, h, nstep))) <= 1.0e-12_wp*scale, & + tag//': quantity '//CHAR(48 + q)//' at end '//CHAR(48 + e)) + END DO + CALL require(ABS(val(7, e) - ref(7)) <= 1.0e-12_wp*scale, tag//': elevation') + CALL require(ABS(val(8, e) - ref(8) - nyq_p(e, h, nstep)) <= 1.0e-12_wp*RHO*G*scale, tag//': pressure') + END DO + END SUBROUTINE single_component + + REAL(wp) FUNCTION nyq_vel(q, e, h, nstep) RESULT(v) + !! the Nyquist component's contribution (amplitude 0.02, along x, zero phase) + INTEGER, INTENT(IN) :: q, e, nstep + REAL(wp), INTENT(IN) :: h + REAL(wp) :: om, k, th, c1, c2 + om = PI/DT + k = kv(N2) + th = PI*REAL(nstep + e - 1, wp) - k*13.0_wp + c1 = (EXP(k*(-11.0_wp)) + EXP(-k*(-11.0_wp + 2.0_wp*h)))/(1.0_wp - EXP(-2.0_wp*k*h)) + c2 = (EXP(k*(-11.0_wp)) - EXP(-k*(-11.0_wp + 2.0_wp*h)))/(1.0_wp - EXP(-2.0_wp*k*h)) + SELECT CASE (q) + CASE (1) + v = 0.02_wp*om*c1*COS(th) + CASE (3) + v = -0.02_wp*om*c2*SIN(th) + CASE (4) + v = -0.02_wp*om*om*c1*SIN(th) + CASE (6) + v = -0.02_wp*om*om*c2*COS(th) + CASE DEFAULT + v = 0.0_wp + END SELECT + END FUNCTION nyq_vel + + REAL(wp) FUNCTION nyq_p(e, h, nstep) RESULT(v) + INTEGER, INTENT(IN) :: e, nstep + REAL(wp), INTENT(IN) :: h + REAL(wp) :: k, th + k = kv(N2) + th = PI*REAL(nstep + e - 1, wp) - k*13.0_wp + v = RHO*G*0.02_wp*COS(th)*(EXP(k*(-11.0_wp)) + EXP(-k*(-11.0_wp + 2.0_wp*h)))/(1.0_wp + EXP(-2.0_wp*k*h)) + END FUNCTION nyq_p + + SUBROUTINE three_components(h, stmod, tol) + REAL(wp), INTENT(IN) :: h, tol + INTEGER, INTENT(IN) :: stmod + CALL clear() + CALL put(40, 0.8_wp, 0.3_wp, 10.0_wp, h) + CALL put(70, 0.5_wp, 1.9_wp, 50.0_wp, h) + CALL put(110, 0.2_wp, -2.2_wp, -35.0_wp, h) + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, h, RHO, G, stmod, tol, es, em) + CALL require(es == CD_NWK_OK, 'three components: init '//TRIM(em)) + END SUBROUTINE three_components + + SUBROUTINE derivatives() + REAL(wp), PARAMETER :: T0 = 123.4_wp, D = 1.0e-4_wp + REAL(wp) :: v0(CD_NWK_NQ, 2), d0(CD_NWK_NQ, 2), vp(CD_NWK_NQ, 2), dp(CD_NWK_NQ, 2), fd, sc + REAL(wp) :: zs(3) + INTEGER :: st, q, iz + zs = [-8.0_wp, -0.3_wp, 0.4_wp] + DO st = 0, 3 + CALL three_components(60.0_wp, st, 0.0_wp) + DO iz = 1, 3 + CALL CD_NWK_Set_Times(f, T0, T0) + CALL CD_NWK_Eval(f, 5.0_wp, 9.0_wp, zs(iz), f%m, v0, d0) + CALL CD_NWK_Set_Times(f, T0 - D, T0 + D) + CALL CD_NWK_Eval(f, 5.0_wp, 9.0_wp, zs(iz), f%m, vp, dp) + DO q = 1, CD_NWK_NQ + fd = (vp(q, 2) - vp(q, 1))/(2.0_wp*D) + sc = MAX(1.0_wp, MAXVAL(ABS(d0(1:7, 1)))) + IF (q == 8) sc = MAX(1.0_wp, ABS(d0(8, 1)), RHO*G) + CALL require(ABS(d0(q, 1) - fd) <= 1.0e-6_wp*sc, 'time derivative of quantity '//CHAR(48 + q)// & + ', WaveStMod '//CHAR(48 + st)//', depth '//CHAR(48 + iz)) + CALL require(v0(q, 1) == v0(q, 2), 'both ends at the same time agree') + END DO + END DO + END DO + END SUBROUTINE derivatives + + SUBROUTINE stretching() + REAL(wp), PARAMETER :: T0 = 77.0_wp, ZP = 0.6_wp, D = 1.0e-5_wp + REAL(wp) :: v1(CD_NWK_NQ, 2), d1(CD_NWK_NQ, 2), v0(CD_NWK_NQ, 2), dz(CD_NWK_NQ, 2), v2(CD_NWK_NQ, 2) + REAL(wp) :: v3(CD_NWK_NQ, 2), d3(CD_NWK_NQ, 2), vw(CD_NWK_NQ, 2), zeta, zmap, h + INTEGER :: q + h = 60.0_wp + ! vertical stretching: above the still-water level the surface value + CALL three_components(h, 1, 0.0_wp) + CALL CD_NWK_Set_Times(f, T0, T0) + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, ZP, f%m, v1, d1) + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, 0.0_wp, f%m, v0, d1) + CALL require(ALL(v1 == v0), 'WaveStMod 1 takes the surface value above the still-water level') + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, -D, f%m, dz, d1) + ! extrapolation: surface value plus z times the vertical derivative there + CALL three_components(h, 2, 0.0_wp) + CALL CD_NWK_Set_Times(f, T0, T0) + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, ZP, f%m, v2, d1) + DO q = 1, 6 + CALL require(ABS(v2(q, 1) - (v0(q, 1) + ZP*(v0(q, 1) - dz(q, 1))/D)) <= 1.0e-5_wp*MAX(1.0_wp, ABS(v0(q, 1))), & + 'WaveStMod 2 extrapolates quantity '//CHAR(48 + q)) + END DO + CALL require(ABS(v2(8, 1) - (v0(8, 1) + ZP*(v0(8, 1) - dz(8, 1))/D)) <= 1.0e-5_wp*RHO*G, & + 'WaveStMod 2 extrapolates the pressure') + CALL require(v2(7, 1) == v0(7, 1), 'the elevation is not stretched') + ! Wheeler: the value at the mapped depth + CALL three_components(h, 3, 0.0_wp) + CALL CD_NWK_Set_Times(f, T0, T0) + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, -5.0_wp, f%m, v3, d3) + zeta = v3(7, 1) + zmap = h*(h - 5.0_wp)/(h + zeta) - h + CALL three_components(h, 1, 0.0_wp) + CALL CD_NWK_Set_Times(f, T0, T0) + CALL CD_NWK_Eval(f, 1.0_wp, 2.0_wp, zmap, f%m, vw, d3) + CALL require(MAXVAL(ABS(v3(1:6, 1) - vw(1:6, 1))) <= 1.0e-12_wp*MAX(1.0_wp, MAXVAL(ABS(vw(1:6, 1)))), & + 'WaveStMod 3 evaluates at the Wheeler depth') + END SUBROUTINE stretching + + SUBROUTINE hermite() + REAL(wp) :: val(CD_NWK_NQ, 2), der(CD_NWK_NQ, 2), ve(CD_NWK_NQ, 2), q(CD_NWK_NQ), s, t0, err, bound + INTEGER :: k + CALL three_components(60.0_wp, 0, 0.0_wp) + CALL CD_NWK_Set_Step(f, 211) + CALL CD_NWK_Eval(f, 3.0_wp, -4.0_wp, -6.0_wp, f%m, val, der) + CALL CD_NWK_Hermite(val, der, DT, 0.0_wp, q) + CALL require(ALL(q == val(:, 1)), 'Hermite is exact at the start of the step') + CALL CD_NWK_Hermite(val, der, DT, 1.0_wp, q) + CALL require(MAXVAL(ABS(q - val(:, 2))) <= 1.0e-12_wp*RHO*G, 'Hermite is exact at the end of the step') + t0 = 211.0_wp*DT + DO k = 1, 9 + s = REAL(k, wp)/10.0_wp + CALL CD_NWK_Hermite(val, der, DT, s, q) + CALL CD_NWK_Set_Times(f, t0 + s*DT, t0 + s*DT) + CALL CD_NWK_Eval(f, 3.0_wp, -4.0_wp, -6.0_wp, f%m, ve, der) + CALL CD_NWK_Set_Step(f, 210) ! force a re-hold of step 211 + CALL CD_NWK_Set_Step(f, 211) + CALL CD_NWK_Eval(f, 3.0_wp, -4.0_wp, -6.0_wp, f%m, val, der) + ! the error of cubic Hermite on a sinusoid: (omega dt)^4/384 of its amplitude, summed + err = ABS(q(1) - ve(1, 1)) + bound = 0.0_wp + DO i = 1, f%m + bound = bound + (f%om(i)*DT)**4/384.0_wp*f%om(i)*SQRT(f%ar(i)**2 + f%ai(i)**2)* & + COSH(f%kk(i)*(60.0_wp - 6.0_wp))/SINH(f%kk(i)*60.0_wp) + END DO + CALL require(err <= 1.01_wp*bound, 'Hermite within (omega dt)^4/384 inside the step') + END DO + END SUBROUTINE hermite + + SUBROUTINE truncation() + REAL(wp) :: dv, da, z, vf(CD_NWK_NQ, 2), vt(CD_NWK_NQ, 2), dd(CD_NWK_NQ, 2) + INTEGER :: k, p, pprev, j + REAL(wp) :: a, h + h = 200.0_wp + CALL clear() + DO j = 20, 250 + a = 0.05_wp*EXP(-((REAL(j, wp) - 80.0_wp)/40.0_wp)**2) + CALL put(j, a, 0.37_wp*REAL(j, wp), 0.0_wp, h) + END DO + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, h, RHO, G, 0, 1.0e-4_wp, es, em) + CALL require(es == CD_NWK_OK, 'truncation: init') + pprev = -1 + DO k = 0, 40 + z = -h + h*REAL(k, wp)/40.0_wp + p = CD_NWK_Prefix(f, z) + CALL require(p >= pprev, 'the kept prefix grows toward the surface') + pprev = p + CALL CD_NWK_Dropped(f, z, p, dv, da) + CALL require(dv <= 1.0e-4_wp .AND. da <= 1.0e-4_wp, 'the dropped variances stay within the tolerance') + ! a node whose shallowest reach is z keeps that prefix at every depth below it, and the + ! dropped variances, relative to the totals at each of those depths, stay within the tolerance + DO j = 1, 8 + CALL CD_NWK_Dropped(f, z - REAL(j, wp)**2, p, dv, da) + CALL require(dv <= 1.0e-4_wp .AND. da <= 1.0e-4_wp, 'the bound holds below the shallowest reach') + END DO + END DO + CALL CD_NWK_Dropped(f, -h, 0, dv, da) + CALL require(ABS(dv - 1.0_wp) < 1.0e-12_wp .AND. ABS(da - 1.0_wp) < 1.0e-12_wp, & + 'the dropped share is relative to the totals at that depth') + CALL require(CD_NWK_Prefix(f, -h) < f%m, 'a deep node drops components') + CALL require(CD_NWK_Prefix(f, -150.0_wp) < CD_NWK_Prefix(f, 0.0_wp), 'deeper nodes keep fewer') + CALL CD_NWK_Set_Step(f, 5) + CALL CD_NWK_Eval(f, 0.0_wp, 0.0_wp, -120.0_wp, f%m, vf, dd) + CALL CD_NWK_Eval(f, 0.0_wp, 0.0_wp, -120.0_wp, CD_NWK_Prefix(f, -120.0_wp), vt, dd) + CALL require(ABS(vt(1, 1) - vf(1, 1)) <= 0.05_wp*SQRT(f%var_v), 'a truncated sum stays close to the full one') + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, h, RHO, G, 0, 0.0_wp, es, em) + CALL require(CD_NWK_Prefix(f, -h) == f%m, 'tol = 0 keeps every component') + CALL CD_NWK_End(f) + END SUBROUTINE truncation + + SUBROUTINE wheeler_truncation() + !! Under Wheeler stretching a short wave that does not reach the node still moves the surface, + !! and so the depth its long waves are evaluated at: 200 m of water, unit amplitudes at 0.30 + !! and 3.0 rad/s with coincident crests, a node at -30 m. The node drops the short wave from its + !! kinematics, but not from its elevation: at the crest the truncated velocity equals the full + !! sum within the tolerance (it was 0.75 % off with the elevation of the kept wave alone). + REAL(wp), PARAMETER :: H = 200.0_wp, ZN = -30.0_wp + REAL(wp) :: vf(CD_NWK_NQ, 2), vt(CD_NWK_NQ, 2), dd(CD_NWK_NQ, 2), zs, lo + INTEGER :: p + CALL clear() + CALL put(24, 1.0_wp, 0.0_wp, 0.0_wp, H) + CALL put(239, 1.0_wp, 0.0_wp, 0.0_wp, H) + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, H, RHO, G, 3, 1.0e-6_wp, es, em) + CALL require(es == CD_NWK_OK, 'Wheeler truncation: init') + ! the shallowest mapped depth of the node, under the lowest elevation the sea can reach + lo = H + f%eta0 - f%zeta_bound + zs = H*(H + ZN)/lo - H + p = CD_NWK_Prefix(f, zs) + CALL require(p == 1, 'Wheeler truncation: the node drops the short wave from its kinematics') + CALL CD_NWK_Set_Times(f, 0.0_wp, 0.0_wp) + CALL CD_NWK_Eval(f, 0.0_wp, 0.0_wp, ZN, f%m, vf, dd) + CALL CD_NWK_Eval(f, 0.0_wp, 0.0_wp, ZN, p, vt, dd) + CALL require(ABS(vt(7, 1) - vf(7, 1)) <= 1.0e-12_wp, 'Wheeler truncation: the elevation keeps the short wave') + CALL require(ABS(vt(1, 1) - vf(1, 1)) <= 1.0e-3_wp*ABS(vf(1, 1)), & + 'Wheeler truncation: the velocity at the crest equals the full sum within the tolerance') + ! without stretching the elevation decides only the wetting and takes the kept prefix + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, H, RHO, G, 0, 1.0e-6_wp, es, em) + CALL require(f%pe_of_p(1) == 1, 'WaveStMod 0: the elevation takes the kept prefix') + CALL CD_NWK_End(f) + END SUBROUTINE wheeler_truncation + + SUBROUTINE limits() + !! more components than CD_NWK_MAX_COMPONENTS stop with a named error; in very deep water a + !! short wave's depth factor underflows to exactly 0 instead of a subnormal + INTEGER, PARAMETER :: NB = 2*(CD_NWK_MAX_COMPONENTS + 1) + REAL(wp), ALLOCATABLE :: br(:), bi(:), bd(:), bk(:) + REAL(wp) :: val(CD_NWK_NQ, 2), der(CD_NWK_NQ, 2) + TYPE(CD_NWK_Field) :: fb + ALLOCATE (br(0:NB/2), bi(0:NB/2), bd(0:NB/2), bk(0:NB/2)) + br = 1.0_wp + bi = 0.0_wp + bd = 0.0_wp + bk = 1.0_wp + CALL CD_NWK_Init(fb, br, bi, bd, bk, NB, 0.1_wp, 100.0_wp, RHO, G, 0, 0.0_wp, es, em) + CALL require(es /= CD_NWK_OK .AND. INDEX(em, 'exceed') > 0, 'too many components stop with a named error') + CALL CD_NWK_End(fb) + CALL clear() + CALL put(400, 0.01_wp, 0.0_wp, 0.0_wp, 1000.0_wp) + CALL put(10, 1.0_wp, 0.0_wp, 0.0_wp, 1000.0_wp) + CALL CD_NWK_Init(f, cre, cim, dir, kv, N, DT, 1000.0_wp, RHO, G, 0, 0.0_wp, es, em) + CALL CD_NWK_Set_Step(f, 3) + CALL CD_NWK_Eval(f, 0.0_wp, 0.0_wp, -900.0_wp, f%m, val, der) + CALL require(ALL(ABS(val(1:6, :)) < HUGE(1.0_wp)) .AND. ABS(val(1, 1)) > 0.0_wp, & + 'a deep node with an underflowing short wave keeps the long wave') + CALL CD_NWK_End(f) + END SUBROUTINE limits + + SUBROUTINE velocity_ratio() + !! the weighted velocity ratio against hand computations: one component, sqrt(cosh 2k(z+h) / + !! cosh 2kh); a JONSWAP set summed directly with cosh and sinh; the deep-water limit; clamping + REAL(wp), PARAMETER :: H = 60.0_wp, Z = -17.0_wp, HS = 4.0_wp, TP = 8.0_wp + REAL(wp) :: w(1), k(1), r, ref, om, sw(200), sk(200), num, den, s, wp_, sig, d1, d2, d10, d20 + INTEGER :: j + k(1) = 0.07_wp + w(1) = 3.0_wp + r = CD_NWK_Velocity_Ratio(w, k, H, Z) + ref = SQRT(COSH(2.0_wp*k(1)*(Z + H))/COSH(2.0_wp*k(1)*H)) + CALL require(ABS(r - ref) < 1.0e-12_wp*ref, 'one component: sqrt(cosh 2k(z+h) / cosh 2kh)') + num = 0.0_wp + den = 0.0_wp + wp_ = 2.0_wp*PI/TP + DO j = 1, 200 + om = 0.02_wp*REAL(j, wp) + sig = MERGE(0.07_wp, 0.09_wp, om <= wp_) + s = 5.0_wp/16.0_wp*HS**2*wp_**4/om**5*EXP(-1.25_wp*(wp_/om)**4)*3.3_wp**EXP(-0.5_wp*((om/wp_ - 1.0_wp)/sig)**2) + sk(j) = wavenumber(om, H) + sw(j) = 2.0_wp*s*0.02_wp*om**2 ! |A|^2 omega^2 with |A|^2 = 2 S d omega + d1 = COSH(sk(j)*(Z + H))/SINH(sk(j)*H) + d2 = SINH(sk(j)*(Z + H))/SINH(sk(j)*H) + d10 = COSH(sk(j)*H)/SINH(sk(j)*H) + d20 = 1.0_wp + num = num + sw(j)*(d1**2 + d2**2) + den = den + sw(j)*(d10**2 + d20**2) + END DO + r = CD_NWK_Velocity_Ratio(sw, sk, H, Z) + CALL require(ABS(r - SQRT(num/den)) < 1.0e-10_wp, 'a JONSWAP set: the direct finite-depth sum') + CALL require(ABS(CD_NWK_Velocity_Ratio(sw, sk, H, 0.0_wp) - 1.0_wp) < 1.0e-12_wp .AND. & + ABS(CD_NWK_Velocity_Ratio(sw, sk, H, 5.0_wp) - 1.0_wp) < 1.0e-12_wp, & + '1 at the still-water level and above it') + k(1) = 0.5_wp + r = CD_NWK_Velocity_Ratio(w, k, 4000.0_wp, -30.0_wp) + CALL require(ABS(r - EXP(0.5_wp*(-30.0_wp))) < 1.0e-12_wp, 'deep water: e^{kz}, no overflow') + CALL require(CD_NWK_Velocity_Ratio([0.0_wp], k, H, Z) < 0.0_wp, '-1 without components') + END SUBROUTINE velocity_ratio + +END PROGRAM test_wave_nodewise diff --git a/validation/scripts/openfast_wave_grid_guard.py b/validation/scripts/openfast_wave_grid_guard.py index 40fd89aa..2cc8ed31 100644 --- a/validation/scripts/openfast_wave_grid_guard.py +++ b/validation/scripts/openfast_wave_grid_guard.py @@ -186,10 +186,10 @@ def rows(name: str) -> list[str]: (out / "wave.Elev").write_text("\n".join(header + elev) + "\n", encoding="ascii") -def prepare(case_dir: Path, work: Path, name: str, mode: str) -> Path: +def prepare(case_dir: Path, work: Path, name: str, mode: str, suffix: str = "") -> Path: """A case folder: the turbine files with the pose reset, the SeaState edits and the deck.""" edits, deck, tmax, _ = CASES[name] - folder = work / f"{name}_{mode}" + folder = work / f"{name}_{mode}{suffix}" if folder.exists(): shutil.rmtree(folder) shutil.copytree(case_dir, folder) @@ -273,13 +273,16 @@ def main() -> int: if args.base_exe: for name, mode in BIT_IDENTICAL: new = args.work / f"{name}_{mode}" - base = prepare(args.case_dir, args.work, name, f"{mode}_base") - if mode == "warn": # the earlier build knows no waveGridCheck: run it without the row + base = prepare(args.case_dir, args.work, name, mode, "_base") + code, log = run(args.base_exe, base) + if mode == "warn" and "unknown OPTION keyword" in log: + # a build before the guard knows no waveGridCheck and only warned: drop the row deck_path = base / CASES[name][1] deck_path.write_text( - re.sub(r"(?m)^warn\s+waveGridCheck.*\n", "", deck_path.read_text(encoding="ascii")), encoding="ascii" + re.sub(r"(?m)^warn\s+waveGridCheck.*\n", "", deck_path.read_text(encoding="ascii")), + encoding="ascii", ) - code, log = run(args.base_exe, base) + code, log = run(args.base_exe, base) (base / "run.log").write_text(log, encoding="utf-8") same = code == 0 for suffix in (".out", ".CD.out"): diff --git a/validation/scripts/openfast_wavekin_compare.py b/validation/scripts/openfast_wavekin_compare.py new file mode 100644 index 00000000..4aeb51e8 --- /dev/null +++ b/validation/scripts/openfast_wavekin_compare.py @@ -0,0 +1,103 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Compare a WaterKin SEASTATE_SPECTRAL run with a reference run on a converged SeaState grid. + +Both runs are the same coupled OpenFAST case and sea (same seed); the reference takes its line +kinematics from a SeaState grid refined until halving its spacing changes nothing, the other from +the wave components at the nodes. For each named channel of the two CableDyn records +(.CD.out) the script compares, after the start-up transient: + +* the standard deviation (pass: within --std-tol, 1 %); +* the damage-equivalent range of the rainflow cycles for the Wohler exponent --wohler (pass: + within --del-tol, 2 %); +* for the channels named with --p99, the 99th percentile of the absolute value (pass: within + --p99-tol, 3 %). + +The thresholds are those fixed before the runs. It exits with 1 when a comparison fails and +writes the table as CSV with --csv. + +usage: openfast_wavekin_compare.py --reference .CD.out --spectral .CD.out + --channels FairTen1,L4HangTen,L4MaxCurv [--p99 L4MaxCurv] [--t-start 600] [--csv out.csv] +""" + +from __future__ import annotations + +import argparse +import csv +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "python")) +from cabledyn import read_output # noqa: E402 +from cabledyn.fatigue import damage_equivalent_range, rainflow_cycles # noqa: E402 + + +def window(path: Path, channel: str, t_start: float) -> np.ndarray: + table = read_output(path) + time = np.asarray(table.time) + values = np.asarray(table.column(channel), dtype=float) + keep = time >= t_start - 1e-9 + if not keep.any(): + raise SystemExit(f"{path}: no rows from t = {t_start} s") + return values[keep] + + +def del_range(values: np.ndarray, wohler: float) -> float: + return damage_equivalent_range(rainflow_cycles(values), wohler_exponent=wohler, reference_cycles=1.0e6) + + +def rel(a: float, b: float) -> float: + return abs(a - b) / abs(b) if b != 0.0 else (0.0 if a == 0.0 else float("inf")) + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--reference", type=Path, required=True, help="CableDyn record of the converged-grid run") + parser.add_argument("--spectral", type=Path, required=True, help="CableDyn record of the node-wise run") + parser.add_argument("--channels", required=True, help="comma-separated channels to compare") + parser.add_argument("--p99", default="", help="comma-separated channels whose 99th percentile is compared") + parser.add_argument("--t-start", type=float, default=0.0, help="start of the compared window (s)") + parser.add_argument("--wohler", type=float, default=3.0) + parser.add_argument("--std-tol", type=float, default=0.01) + parser.add_argument("--del-tol", type=float, default=0.02) + parser.add_argument("--p99-tol", type=float, default=0.03) + parser.add_argument("--csv", type=Path) + args = parser.parse_args(argv) + channels = [c.strip() for c in args.channels.split(",") if c.strip()] + p99 = {c.strip() for c in args.p99.split(",") if c.strip()} + rows = [] + failed = False + for channel in channels + sorted(p99 - set(channels)): + ref = window(args.reference, channel, args.t_start) + spe = window(args.spectral, channel, args.t_start) + if ref.size != spe.size: + raise SystemExit(f"{channel}: {ref.size} reference rows against {spe.size} spectral rows") + measures = [] + if channel in channels: + measures += [("std", float(np.std(ref)), float(np.std(spe)), args.std_tol), + ("DEL", del_range(ref, args.wohler), del_range(spe, args.wohler), args.del_tol)] + if channel in p99: + measures.append(("p99|x|", float(np.percentile(np.abs(ref), 99.0)), + float(np.percentile(np.abs(spe), 99.0)), args.p99_tol)) + for name, a, b, tol in measures: + r = rel(b, a) + ok = r <= tol + failed |= not ok + rows.append({"channel": channel, "measure": name, "reference": a, "spectral": b, + "relative_difference": r, "tolerance": tol, "pass": ok}) + print(f"{channel:>16} {name:>7}: reference {a:.6e}, spectral {b:.6e}, " + f"{100 * r:.3f} % (<= {100 * tol:g} %) {'ok' if ok else 'FAIL'}") + if args.csv: + with args.csv.open("w", newline="", encoding="utf-8") as handle: + writer = csv.DictWriter(handle, fieldnames=list(rows[0])) + writer.writeheader() + writer.writerows(rows) + print("FAIL" if failed else "PASS: the node-wise run agrees with the converged grid") + return 1 if failed else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validation/scripts/openfast_wavekin_converged.py b/validation/scripts/openfast_wavekin_converged.py new file mode 100644 index 00000000..fcd28983 --- /dev/null +++ b/validation/scripts/openfast_wavekin_converged.py @@ -0,0 +1,360 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Set up the converged-grid reference for a node-wise wave validation (WaterKin SEASTATE_SPECTRAL). + +The reference is the same coupled case on the SeaState grid, refined until halving its spacing +changes nothing. A grid that fine over a whole mooring does not fit in memory, but the waves die +out with depth: the grid needs to span horizontally only the nodes where they still matter, and +the deeper nodes outside it get SeaState's boundary values, which are as small there. The node +positions come from a node-wise run of the case (its .CD.wavekin.out lists every sampling +node at the static position). + + size the reference grid: the spacing a --fraction of the shortest wavelength that matters at + the shallowest node or hull joint (the highest frequency whose spectral density there is + at least 1 % of the peak); half-widths over the hull joints and the nodes above z_cut, where the + horizontal wave-velocity variance of the sea falls to --decay of its surface value, plus + --margin; Z_Depth at z_cut (deeper nodes take the values of the grid bottom, whose + variance is under --decay), at least down to CurrNSRef with a near-surface current + (zero below it), the whole depth with a current that varies down to the seabed (CurrSSV0, + or a CurrMod 2 user current); as many cosine depth levels as keep every interval within + the spacing. A long-crested sea at direction beta has the wavelength lambda/|cos beta| + along x and lambda/|sin beta| along y, so the spacing grows along each axis by that factor + (2 points across a sea along x or y). It prints the SeaState rows and the memory SeaState + stores (and its start-up peak, 3 times that), also for the halving check along --halve + (by default every horizontal axis the waves vary along, and z with a current down to the + seabed; an axis across a long-crested sea keeps its 2 points, any other is refined, and + a choice that refines nothing stops); --wave-dir and --wave-tmax size for another + heading or wave period. + prepare three copies of the case: reference (SEASTATE_GRID on that grid, waveGridCheck warn for + the deep nodes outside it), halved (the same at half the spacing along the --halve axes) + and spectral (SEASTATE_SPECTRAL on the same grid, so the hull sees the same waves in all + three). Compare reference with halved (convergence) and spectral with reference + (validation) with openfast_wavekin_compare.py. + +usage: openfast_wavekin_converged.py size --fst --wavekin .CD.wavekin.out + [--fraction 20] [--margin 20] [--decay 1e-6] [--json grid.json] + openfast_wavekin_converged.py prepare --case-dir --fst --grid grid.json + --out [--tmax T] +""" + +from __future__ import annotations + +import argparse +import importlib.util +import json +import math +import re +import shutil +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] + + +def load_preflight(): + spec = importlib.util.spec_from_file_location( + "cabledyn_preflight", ROOT / "integration" / "openfast" / "cabledyn_preflight.py") + assert spec is not None and spec.loader is not None + module = importlib.util.module_from_spec(spec) + # registered first: its dataclasses look their module up while being defined + sys.modules[spec.name] = module + spec.loader.exec_module(module) + return module + + +pf = load_preflight() + + +def read_nodes(path: Path) -> list[tuple[float, float, float]]: + """The sampling-node positions of a .CD.wavekin.out (Object Node X Y Z Kept ...).""" + nodes = [] + for line in path.read_text(encoding="utf-8").splitlines(): + parts = line.split("\t") + if line.startswith("#") or len(parts) < 5 or parts[0] == "Object": + continue + nodes.append((float(parts[2]), float(parts[3]), float(parts[4]))) + if not nodes: + raise SystemExit(f"{path}: no node rows") + return nodes + + +def velocity_variance_depth(ss: dict[str, str], depth: float, decay: float) -> float | None: + """The depth z_cut (m, negative) below which the horizontal wave-velocity variance of the sea + stays under `decay` of its value at the still-water level: sum of S(omega) omega^2 + (cosh k(z + h) / cosh k h)^2 over the spectrum (JONSWAP, WvLowCOff to WvHiCOff).""" + hs = pf.number(ss.get("WaveHs"), 0.0) + tp = pf.number(ss.get("WaveTp"), 0.0) + if hs <= 0.0 or tp <= 0.0: + return None + lo = pf.number(ss.get("WvLowCOff"), 0.0) + hi = pf.number(ss.get("WvHiCOff"), 2.0 * math.pi) + gamma = pf.peak_shape(ss, hs, tp) + comps = [(pf.jonswap(w, hs, tp, gamma) * w * w, pf.wavenumber(w, depth)) + for w in (0.05 + 0.005 * i for i in range(2000)) if lo <= w <= hi] + + def ratio(z: float) -> float: + top = sum(s for s, _ in comps) + # (cosh k(z + h) / cosh k h)^2 without overflow: exp(2kz) (1 + e^{-2k(z+h)})^2 / (1 + e^{-2kh})^2 + return sum(s * math.exp(2.0 * k * z) * ((1.0 + math.exp(-2.0 * k * (z + depth))) + / (1.0 + math.exp(-2.0 * k * depth))) ** 2 + for s, k in comps) / top + + if ratio(-depth) > decay: + return -depth + lo_z, hi_z = -depth, 0.0 + for _ in range(60): + mid = 0.5 * (lo_z + hi_z) + # the ratio grows towards the surface: above the cut it exceeds decay + lo_z, hi_z = (lo_z, mid) if ratio(mid) > decay else (mid, hi_z) + return lo_z + + +def depth_levels(nz: int, z_depth: float) -> list[float]: + """SeaState's cosine depth levels, from the still-water level down to -z_depth.""" + theta = math.pi / (2 * (nz - 1)) + return [(math.cos(k * theta) - 1.0) * z_depth for k in range(nz)] + + +def size(args: argparse.Namespace) -> int: + fst = args.fst + f = pf.values(fst) + ss = pf.values(fst.parent / f["SeaStFile"]) + joints = pf.hull_joints(fst.parent / f["HydroFile"]) if (fst.parent / f["HydroFile"]).exists() else [] + nodes = read_nodes(args.wavekin) + depth = pf.setting(ss, "WtrDpth", f, 0.0) + pf.setting(ss, "MSL2SWL", f, 0.0) + if pf.wave_mod(ss) != 2: + raise SystemExit(f"WaveMod {pf.wave_mod(ss)}: the sizing needs a JONSWAP or Pierson-Moskowitz sea (WaveMod 2)") + # the grid serves the sampling nodes and the hull's Morison joints alike: the shallowest of + # either sets the shortest wavelength (a joint above the water counts as the surface) + z_top = min(0.0, max(z for _, _, z in nodes + joints)) + lam_short = pf.shortest_wavelength(ss, depth, z_top) + z_cut = velocity_variance_depth(ss, depth, args.decay) + if not lam_short or z_cut is None: + raise SystemExit("the sea has no spectrum to size a grid for (WaveMod 2 with WaveHs and WaveTp)") + near = [(x, y) for x, y, z in nodes if z >= z_cut] + [(x, y) for x, y, _ in joints] + wave_dir = pf.number(ss.get("WaveDir"), 0.0) if args.wave_dir is None else args.wave_dir + multi = pf.multi_directional(ss) # SeaState's rule for a short-crested sea + # along each axis a long-crested sea at direction beta has the wavelength lambda/|cos| (x) or + # lambda/|sin| (y); a short-crested one is taken at lambda on both, as is the vertical + spacing = lam_short / args.fraction + # with no node above z_cut and no hull joint (a cable submerged below the waves) every node takes + # the grid-bottom values: the grid keeps the margin about the origin, and at least one spacing + x_half = max(max((abs(x) for x, _ in near), default=0.0) + args.margin, spacing) + y_half = max(max((abs(y) for _, y in near), default=0.0) + args.margin, spacing) + sx, sy = spacing, spacing + if not multi: + cx, cy = abs(math.cos(math.radians(wave_dir))), abs(math.sin(math.radians(wave_dir))) + sx = spacing / cx if cx > 1e-6 else math.inf + sy = spacing / cy if cy > 1e-6 else math.inf + nx = 2 if math.isinf(sx) else math.ceil(x_half / sx) + 1 + ny = 2 if math.isinf(sy) else math.ceil(y_half / sy) + 1 + # the grid reaches z_cut: deeper nodes take its bottom values, whose variance is under decay. + # A SeaState current must also be right below the grid, where the grid route gives the nodes + # its bottom value and the spectral route the profile at their depth. Of CurrMod 1, the 1/7 + # power law (CurrSSV0) varies down to the seabed, as a CurrMod 2 user current may: such a grid + # keeps the whole depth. The near-surface current (CurrNSV0) is zero below CurrNSRef, so the + # grid reaches that depth; the depth-independent one (CurrDIV) is the same at every depth. + curr_mod = int(pf.number(ss.get("CurrMod"), 0)) + full_depth = curr_mod == 2 or (curr_mod == 1 and pf.number(ss.get("CurrSSV0"), 0.0) != 0.0) + z_need = -z_cut + if curr_mod == 1 and pf.number(ss.get("CurrNSV0"), 0.0) != 0.0: + z_need = max(z_need, pf.number(ss.get("CurrNSRef"), 0.0)) + z_depth = depth if full_depth else min(depth, math.ceil(z_need)) + nz = 2 + while max(a - b for a, b in zip(depth_levels(nz, z_depth), depth_levels(nz, z_depth)[1:])) > spacing: + nz += 1 + dt = pf.number(ss.get("WaveDT"), 0.25) + tmax = pf.number(ss.get("WaveTMax"), 0.0) if args.wave_tmax is None else args.wave_tmax + nsteps = pf.wave_steps(tmax, dt) + stmod = int(pf.number(ss.get("WaveStMod"), 0)) + mcf = pf.number(ss.get("MCFD"), 0.0) > 0.0 + memory = pf.grid_memory(nx, ny, nz, nsteps, stmod, mcf) + # the halving check: half the spacing along the axes named in --halve; only an axis across a + # long-crested sea (the waves uniform along it) keeps its two points, a two-point axis the + # waves vary along is refined too + # by default every horizontal axis the waves vary along, and z too with a current that varies + # down to the seabed (the power law's levels are what the halving must show converge) + if args.halve is not None: + halve = args.halve + else: + halve = ("x" if not math.isinf(sx) else "") + ("y" if not math.isinf(sy) else "") + ("z" if full_depth else "") + hx = 2 * nx - 1 if "x" in halve and not math.isinf(sx) else nx + hy = 2 * ny - 1 if "y" in halve and not math.isinf(sy) else ny + hz = 2 * nz - 1 if "z" in halve else nz + if (hx, hy, hz) == (nx, ny, nz): + raise SystemExit(f"--halve {halve or '(none)'} refines no axis the waves vary along (WaveDir {wave_dir:g}: " + f"{'x' if not math.isinf(sx) else ''}{'y' if not math.isinf(sy) else ''}), so the halved " + "grid would equal the reference") + halved = pf.grid_memory(hx, hy, hz, nsteps, stmod, mcf) + outside = sum(1 for x, y, z in nodes if abs(x) > x_half or abs(y) > y_half or z < -z_depth) + grid = {"X_HalfWidth": f"{x_half:.1f}", "Y_HalfWidth": f"{y_half:.1f}", + "Z_Depth": f"{z_depth:g}" if z_depth < depth else '"default"', + "NX": str(nx), "NY": str(ny), "NZ": str(nz)} + if args.wave_dir is not None: + grid["WaveDir"] = f"{wave_dir:g}" + if args.wave_tmax is not None: + grid["WaveTMax"] = f"{tmax:g}" + print(f"shortest wavelength that matters at z = {z_top:.1f} m: {lam_short:.1f} m; spacing {spacing:.2f} m " + f"(1/{args.fraction:g}) along the waves, {sx:.2f} m in x, {sy:.2f} m in y") + print(f"the wave-velocity variance falls to {args.decay:g} of its surface value at z = {z_cut:.1f} m; " + f"{outside} of {len(nodes)} nodes lie outside the grid, all below that depth") + if full_depth: + print(f"SeaState has a current that varies down to the seabed (CurrMod {curr_mod}" + f"{', CurrSSV0' if curr_mod == 1 else ''}): the grid keeps the whole depth, and the halving check " + "refines z too unless --halve says otherwise") + elif z_need > -z_cut: + print(f"SeaState's near-surface current reaches CurrNSRef = {z_need:g} m, below z_cut: the grid reaches it") + print("SeaState rows: " + ", ".join(f"{k} {v}" for k, v in grid.items())) + print(f"NStepWave {nsteps}: stored {memory / 1e9:.2f} GB (start-up peak about {pf.PEAK_RATIO * memory / 1e9:.2f} " + f"GB); halved in {halve} (NX {hx}, NY {hy}, NZ {hz}) {halved / 1e9:.2f} GB (peak about " + f"{pf.PEAK_RATIO * halved / 1e9:.2f} GB)") + if args.json: + args.json.write_text(json.dumps({"seastate": grid, "halved": {"NX": str(hx), "NY": str(hy), "NZ": str(hz)}, + "spacing_m": spacing, "z_cut_m": z_cut, "memory_gb": memory / 1e9, + "halved_memory_gb": halved / 1e9}, indent=2), encoding="utf-8") + return 0 + + +def set_value(path: Path, key: str, value: str) -> None: + """Set an OpenFAST input value: the row whose first two words (separated by spaces, tabs, + commas or semicolons) are the value and the name, in either order, the name without regard + to case (OpenFAST's GetWords and ChkParseData).""" + lines = path.read_text(encoding="latin-1").splitlines() + name = re.escape(key) + value_first = re.compile(rf"^(\s*)(\"[^\"]*\"|'[^']*'|[^\s,;]+)([\s,;]+{name})(?=[\s,;]|$)", re.I) + name_first = re.compile(rf"^(\s*{name}[\s,;]+)(\"[^\"]*\"|'[^']*'|[^\s,;]+)", re.I) + hits = [] + for i, line in enumerate(lines): + if line.lstrip().startswith(("!", "#")): + continue + if value_first.match(line): + hits.append((i, value_first, lambda m: f"{m.group(1)}{value}{m.group(3)}")) + elif name_first.match(line): + hits.append((i, name_first, lambda m: f"{m.group(1)}{value}")) + if len(hits) != 1: + raise SystemExit(f"{path.name}: expected one {key} row, found {len(hits)}") + i, pattern, repl = hits[0] + lines[i] = pattern.sub(repl, lines[i], count=1) + path.write_text("\n".join(lines) + "\n", encoding="latin-1") + + +def set_waterkin(deck: Path, value: str, extra: str = "") -> None: + """The deck's WaterKin row set to value (added after dtM when there is none), plus extra rows, + in its OPTIONS section only and never in a comment (CableDyn's reader strips # and ! and the + -- that starts a word). An inserted guard setting replaces the deck's (WaterKin, WaveKin, + waveGridCheck and wave_grid_check are read under one name each, the last row winning).""" + lines = deck.read_text(encoding="latin-1").splitlines() + section = "" + waterkin_rows, guard_rows, dtm_row = [], [], None + for i, raw in enumerate(lines): + text = pf.strip_comment(raw) + if not text: + continue + name = pf.section_name(text) + if name is not None: + section = name + continue + if section != "OPTIONS": + continue + row = pf.value_key(text) + if not row: + continue + key = pf.OPTION_ALIASES.get(row[1].lower(), row[1].lower()) + if key == "waterkin": + waterkin_rows.append(i) + elif key == "wavegridcheck": + guard_rows.append(i) + elif key == "dtm" and dtm_row is None: + dtm_row = i + add = [] + if waterkin_rows: + # every WaterKin row says the same, so the last one (the one CableDyn keeps) does; a quoted + # value (a file name with spaces) is replaced whole + for i in waterkin_rows: + lines[i] = re.sub(r"""^(\s*)("[^"]*"|'[^']*'|\S+)""", lambda m: f"{m.group(1)}{value}", lines[i], + count=1) + else: + add.append(f"{value} WaterKin") + add += [row for row in extra.splitlines() if row.strip()] + if any(re.search(r"(?i)\bwave_?grid_?check\b", row) for row in add): + for i in sorted(guard_rows, reverse=True): + del lines[i] + if dtm_row is not None and i < dtm_row: + dtm_row -= 1 + if add: + if dtm_row is None: + raise SystemExit(f"{deck.name}: no dtM row in OPTIONS to add the options after ({add!r})") + lines[dtm_row + 1 : dtm_row + 1] = add + deck.write_text("\n".join(lines) + "\n", encoding="latin-1") + + +def inside(root: Path, base: Path, name: str, what: str) -> Path: + """A file the case names, resolved as OpenFAST resolves it (from the folder `base` of the file + that names it), refused when it lies outside the copy of the case (`root`).""" + path = (base / name).resolve() + if not path.is_relative_to(root.resolve()): + raise SystemExit(f"{what} {name} lies outside the case folder {root}; the copy would not hold it") + return path + + +def prepare(args: argparse.Namespace) -> int: + grid = json.loads(args.grid.read_text(encoding="utf-8")) + # each copy replaces its folder: refuse, before anything is deleted, a folder that is the case, + # holds it, or lies inside it (the copy would then delete the case or copy into itself) + source = args.case_dir.resolve() + for tag in ("reference", "halved", "spectral"): + dest = (args.out / tag).resolve() + if dest == source or dest in source.parents or source in dest.parents: + raise SystemExit(f"the output folder {dest} overlaps the case folder {source}: choose an --out " + "outside the case and not above it") + for tag, rows, waterkin, extra in ( + ("reference", grid["seastate"], "SEASTATE_GRID", "warn waveGridCheck\n"), + ("halved", {**grid["seastate"], **grid["halved"]}, "SEASTATE_GRID", "warn waveGridCheck\n"), + ("spectral", grid["seastate"], "SEASTATE_SPECTRAL", ""), + ): + folder = args.out / tag + if folder.exists(): + shutil.rmtree(folder) + shutil.copytree(args.case_dir, folder) + fst = inside(folder, folder, args.fst, "the .fst") + f = pf.values(fst) + # OpenFAST resolves the module files from the folder of the .fst + seastate = inside(folder, fst.parent, f["SeaStFile"], "SeaStFile") + mooring = inside(folder, fst.parent, f["MooringFile"], "MooringFile") + for key, value in rows.items(): + set_value(seastate, key, value) + if args.tmax is not None: + set_value(fst, "TMax", str(args.tmax)) + set_waterkin(mooring, waterkin, extra) + print(f"prepared {folder} ({waterkin}; " + ", ".join(f"{k} {v}" for k, v in rows.items()) + ")") + return 0 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + sub = parser.add_subparsers(dest="command", required=True) + s = sub.add_parser("size") + s.add_argument("--fst", type=Path, required=True) + s.add_argument("--wavekin", type=Path, required=True) + s.add_argument("--fraction", type=float, default=20.0) + s.add_argument("--margin", type=float, default=20.0) + s.add_argument("--decay", type=float, default=1e-6) + s.add_argument("--halve", default=None, + help="the axes the halving check refines (x, y, z or a mix; default the horizontal axes the " + "waves vary along, and z with a current that varies down to the seabed)") + s.add_argument("--wave-dir", type=float, help="size for this wave direction instead of the file's (deg)") + s.add_argument("--wave-tmax", type=float, help="size for this WaveTMax instead of the file's (s)") + s.add_argument("--json", type=Path) + p = sub.add_parser("prepare") + p.add_argument("--case-dir", type=Path, required=True) + p.add_argument("--fst", required=True) + p.add_argument("--grid", type=Path, required=True) + p.add_argument("--out", type=Path, required=True) + p.add_argument("--tmax", type=float) + args = parser.parse_args(argv) + return size(args) if args.command == "size" else prepare(args) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validation/scripts/openfast_wavekin_route.py b/validation/scripts/openfast_wavekin_route.py new file mode 100644 index 00000000..937445c2 --- /dev/null +++ b/validation/scripts/openfast_wavekin_route.py @@ -0,0 +1,280 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Coupled checks of the node-wise wave route (WaterKin SEASTATE_SPECTRAL) in OpenFAST. + +The IEA-15 MW UMaine model of the OpenFAST tutorial (the r-test ``MD_Shared`` turbine-1 files, pose +reset) with ``examples/openfast/CableDyn_UMaine.dat``, short runs on small SeaState grids +(``WaveTMax`` 200 s): + + agree the tutorial grid (900 m half-widths, 25 m spacing, waves along x), where the grid + route is valid, run on both routes for 60 s: the fairlead tensions agree in mean and + standard deviation (reported; within 2 % required, a smoke check, not validation); + oblique waves at 30 deg on the platform-only MD_Shared grid: the spectral route runs (the + grid route stops there, see openfast_wave_grid_guard.py); + restart the spectral route (also in a CurrMod 1 current on two grid levels), and the grid + route under waveGridCheck warn on the platform-only grid, checkpointed at 10 s and + restarted: from 10 s to 20 s the output rows equal those of the uninterrupted run, + byte for byte, and the provenance records (.CD.provenance.json) are the same + but for restarted_from; + current in a 1 m/s CurrMod 1 current on a full-depth grid of two levels, the spectral route + starts in the current profile: its line tensions at t = 0 are within 0.25 % of the + grid route's on 81 levels, while the grid route on the two levels is 1 % or more off; + refused second-order kinematics (WvDiffQTF) and wave-current interaction (WvCrntMod 1 with a + current) stop at initialisation with a message naming SEASTATE_GRID; + record the grid route on the platform-only grid, which the wave-grid guard stops at + initialisation, leaves a provenance record "stopped" with every line out of the grid. + +usage: openfast_wavekin_route.py --exe --case-dir --work +""" + +from __future__ import annotations + +import argparse +import json +import math +import re +import shutil +import subprocess +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[2] +ED = "IEA-15-240-RWT-UMaineSemi_ElastoDynT1.dat" +HD = "IEA-15-240-RWT-UMaineSemi_HydroDynT1.dat" +SS = "SeaState.dat" +FST = "case.fst" +DECK = "CableDyn_UMaine.dat" +LIGHT = {"WaveTMax": "200"} +COVER = {"X_HalfWidth": "900", "Y_HalfWidth": "900", "Z_Depth": '"default"', "NX": "37", "NY": "2", "NZ": "11"} +# a 1 m/s CurrMod 1 current (the 1/7 power law) under small waves, on a full-depth grid +CURRENT = {**LIGHT, "Z_Depth": '"default"', "WaveHs": "0.1", "CurrMod": "1", "CurrSSV0": "1.0", "CurrSSDir": "0", + "CurrNSRef": "20", "CurrNSV0": "0", "CurrNSDir": "0", "CurrDIV": "0", "CurrDIDir": "0"} + + +def set_value(path: Path, key: str, value: str) -> None: + lines = path.read_text(encoding="latin-1").splitlines() + pattern = re.compile(rf"^(\s*)(\S+)(\s+{re.escape(key)}\b)") + hits = [i for i, line in enumerate(lines) if pattern.match(line)] + if len(hits) != 1: + raise SystemExit(f"{path.name}: expected one {key} row, found {len(hits)}") + lines[hits[0]] = pattern.sub(lambda m: f"{m.group(1)}{value}{m.group(3)}", lines[hits[0]]) + path.write_text("\n".join(lines) + "\n", encoding="latin-1") + + +def prepare(case_dir: Path, folder: Path, seastate: dict[str, str], tmax: float, waterkin: str, + fst: dict[str, str] | None = None, deck_rows: str = "") -> Path: + if folder.exists(): + shutil.rmtree(folder) + shutil.copytree(case_dir, folder) + for key in ("PtfmSurge", "PtfmSway", "PtfmHeave", "PtfmRoll", "PtfmPitch", "PtfmYaw"): + set_value(folder / ED, key, "0") + set_value(folder / HD, "PtfmRefY", "0") + for key, value in seastate.items(): + set_value(folder / SS, key, value) + shutil.copy(ROOT / "examples/openfast/IEA-15-UMaine_CompMooring5_CableDyn.fst", folder / FST) + set_value(folder / FST, "TMax", str(tmax)) + for key, value in (fst or {}).items(): + set_value(folder / FST, key, value) + deck = (ROOT / "examples/openfast" / DECK).read_text(encoding="utf-8") + deck = re.sub(r"(?m)^0(\s+)WaterKin\b", waterkin + r"\1WaterKin", deck, count=1) + if deck_rows: + deck = re.sub(r"(?m)^(\S+\s+dtM\b.*)$", lambda m: m.group(1) + "\n" + deck_rows, deck, count=1) + (folder / DECK).write_text(deck, encoding="ascii") + return folder + + +def run(exe: Path, folder: Path, args: list[str]) -> tuple[int, str]: + proc = subprocess.run([str(exe), *args], cwd=folder, capture_output=True, text=True, errors="replace") + log = proc.stdout + proc.stderr + (folder / ("run.log" if args == [FST] else "restart.log")).write_text(log, encoding="utf-8") + return proc.returncode, log + + +def table(path: Path) -> tuple[list[str], list[list[float]]]: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + start = next(i for i, line in enumerate(lines) if line.split()[:1] == ["Time"]) + header = lines[start].split() + rows = [] + for line in lines[start + 2:]: + parts = line.split() + if len(parts) == len(header): + rows.append([float(v) for v in parts]) + return header, rows + + +def rows_from(path: Path, t0: float) -> list[str]: + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + start = next(i for i, line in enumerate(lines) if line.split()[:1] == ["Time"]) + out = [] + for line in lines[start + 2:]: + parts = line.split() + try: + if float(parts[0]) > t0 + 1.0e-9: + out.append(line) + except (IndexError, ValueError): + continue + return out + + +def stats(values: list[float]) -> tuple[float, float]: + mean = sum(values) / len(values) + return mean, math.sqrt(sum((v - mean) ** 2 for v in values) / len(values)) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--exe", type=Path, required=True) + parser.add_argument("--case-dir", type=Path, required=True) + parser.add_argument("--work", type=Path, required=True) + args = parser.parse_args() + args.work.mkdir(parents=True, exist_ok=True) + failures: list[str] = [] + + # agree: both routes on a grid that is valid for the lines + results = {} + for route in ("SEASTATE_GRID", "SEASTATE_SPECTRAL"): + folder = prepare(args.case_dir, args.work / f"agree_{route.lower()}", {**COVER, **LIGHT}, 60.0, route) + code, log = run(args.exe, folder, [FST]) + if code != 0: + failures.append(f"agree {route}") + print(f"agree {route}: FAIL exit {code}\n ..." + " ".join(log.split())[-1500:]) + continue + header, rows = table(folder / "case.out") + results[route] = { + name: stats([r[header.index(name)] for r in rows if r[0] >= 10.0]) + for name in ("FairTen1", "FairTen2", "FairTen3") + } + if len(results) == 2: + for name in ("FairTen1", "FairTen2", "FairTen3"): + (mg, sg), (ms, ss) = results["SEASTATE_GRID"][name], results["SEASTATE_SPECTRAL"][name] + dm, ds = abs(ms - mg) / abs(mg), abs(ss - sg) / max(sg, 1e-30) + ok = dm <= 0.02 and ds <= 0.02 + print(f"agree {name}: mean {mg:.6e} / {ms:.6e} ({dm:.2%}), std {sg:.6e} / {ss:.6e} ({ds:.2%})" + f" {'ok' if ok else 'FAIL'}") + if not ok: + failures.append(f"agree {name}") + + # oblique on the platform-only grid + folder = prepare(args.case_dir, args.work / "oblique", {**LIGHT, "WaveDir": "30"}, 5.0, "SEASTATE_SPECTRAL") + code, log = run(args.exe, folder, [FST]) + ok = code == 0 and "OpenFAST terminated normally" in log and "SEASTATE_SPECTRAL" in log + print(f"oblique 30 deg on the platform grid: {'runs' if ok else 'FAIL'}") + if not ok: + failures.append("oblique") + print(" ..." + " ".join(log.split())[-1500:]) + + # restart: the node-wise route, and the grid route under waveGridCheck warn on the platform-only + # grid (out-of-grid events before and after the checkpoint in the provenance record) + for tag, seastate, waterkin, rows in ( + ("spectral", {**COVER, **LIGHT, "WaveDir": "0"}, "SEASTATE_SPECTRAL", ""), + ("spectral current", {**COVER, **CURRENT, "NZ": "2"}, "SEASTATE_SPECTRAL", ""), + ("grid warn", {**LIGHT, "WaveDir": "0"}, "SEASTATE_GRID", "warn waveGridCheck"), + ): + name = tag.replace(" ", "_") + base = prepare(args.case_dir, args.work / f"restart_ref_{name}", seastate, 20.0, waterkin, + deck_rows=rows) + code_a, _ = run(args.exe, base, [FST]) + rst = prepare(args.case_dir, args.work / f"restart_run_{name}", seastate, 20.0, waterkin, + {"ChkptTime": "10.0"}, deck_rows=rows) + code_b, _ = run(args.exe, rst, [FST]) + chk = sorted(rst.glob("case.*.chkp")) + ok = code_a == 0 and code_b == 0 and bool(chk) + same_record = False + if ok: + first = chk[0].name[: -len(".chkp")] + for out in ("case.out", "case.CD.out"): + shutil.copy(rst / out, rst / f"full_{out}") + code_c, _ = run(args.exe, rst, ["-restart", first]) + ok = code_c == 0 + t0 = float(first.split(".")[-1]) * 0.025 + for out in ("case.out", "case.CD.out"): + # OpenFAST appends the restarted rows to its .out after those of the first run; + # CableDyn starts its .CD.out afresh at the checkpoint: compare the last rows + ref_rows = rows_from(base / out, t0) + ok = ok and rows_from(rst / out, t0)[-len(ref_rows) :] == ref_rows + ok = ok and rows_from(base / out, t0) == rows_from(rst / f"full_{out}", t0) + # the provenance records agree but for the one key restarted_from + ref = json.loads((base / "case.CD.provenance.json").read_text(encoding="utf-8")) + new = json.loads((rst / "case.CD.provenance.json").read_text(encoding="utf-8")) + same_record = ( + ref.pop("restarted_from") is None + and abs(new.pop("restarted_from") - t0) < 1.0e-9 + and ref == new + and ref["status"] == "complete" + ) + if tag == "grid warn": + same_record = same_record and any(line["out_of_grid"] for line in ref["lines"]) + else: + same_record = same_record and all( + line["dropped_velocity_variance_max"] is not None for line in ref["lines"] + ) + print(f"restart at 10 s ({tag}): {'continues bit for bit' if ok else 'FAIL'}, provenance record " + f"{'the same' if same_record else 'FAIL'}") + if not (ok and same_record): + failures.append(f"restart {tag}") + + # current start: in a CurrMod 1 current on a full-depth grid of two levels (the seabed and the + # surface), the spectral route starts in the current profile itself, as the grid route does on + # a fine grid (NZ 81), and not in the straight line the two levels give the grid route + starts = {} + for tag, route, nz in (("spectral NZ 2", "SEASTATE_SPECTRAL", "2"), ("grid NZ 2", "SEASTATE_GRID", "2"), + ("grid NZ 81", "SEASTATE_GRID", "81")): + folder = prepare(args.case_dir, args.work / f"current_start_{tag.replace(' ', '_')}", + {**CURRENT, "NZ": nz}, 0.1, route, + deck_rows="warn waveGridCheck" if route == "SEASTATE_GRID" else "") + code, log = run(args.exe, folder, [FST]) + if code != 0: + print(f"current start {tag}: FAIL exit {code}\n ..." + " ".join(log.split())[-1500:]) + continue + header, rows = table(folder / "case.CD.out") + starts[tag] = {name: rows[0][header.index(name)] for name in ("FairTen1", "AnchTen1", "FairTen2", "AnchTen2")} + ok = len(starts) == 3 + if ok: + ref = starts["grid NZ 81"] + dev = {tag: max(abs(v - ref[k]) / ref[k] for k, v in starts[tag].items()) for tag in starts} + ok = dev["spectral NZ 2"] <= 0.0025 and dev["grid NZ 2"] >= 0.01 + print(f"current start: the line tensions at t = 0 differ from those of the grid route on NZ 81 by at most " + f"{dev['spectral NZ 2']:.3%} on the spectral route with NZ 2 (grid route with NZ 2: " + f"{dev['grid NZ 2']:.3%}) {'ok' if ok else 'FAIL'}") + if not ok: + failures.append("current start") + + # refused + for tag, edits in ( + ("second order", {**COVER, **LIGHT, "WvDiffQTF": "TRUE"}), + ("wave-current", {**COVER, **LIGHT, "WvCrntMod": "1", "CurrMod": "1", "CurrDIV": "0.5"}), + ): + folder = prepare(args.case_dir, args.work / f"refused_{tag.replace(' ', '_')}", edits, 1.0, + "SEASTATE_SPECTRAL") + code, log = run(args.exe, folder, [FST]) + flat = " ".join(log.split()) + ok = code != 0 and "SEASTATE_SPECTRAL" in flat and "SEASTATE_GRID" in flat + print(f"refused {tag}: {'stops by name' if ok else 'FAIL'}") + if not ok: + failures.append(f"refused {tag}") + print(" ..." + flat[-1500:]) + + # the provenance record of a run the guard stops at initialisation: the grid route on the + # platform-only grid (default waveGridCheck error) + folder = prepare(args.case_dir, args.work / "record_stopped", {**LIGHT, "WaveDir": "0"}, 1.0, "SEASTATE_GRID") + code, _ = run(args.exe, folder, [FST]) + record_path = folder / "case.CD.provenance.json" + record = json.loads(record_path.read_text(encoding="utf-8")) if record_path.exists() else {} + lines = record.get("lines") or [] + ok = (code != 0 and record.get("status") == "stopped" and bool(lines) + and all(entry.get("out_of_grid") for entry in lines)) + print(f"record of a run the guard stops: {'stopped, lines out of the grid' if ok else 'FAIL'}") + if not ok: + failures.append("record stopped") + print(f" exit {code}, record {record}") + + if failures: + print("FAIL: " + ", ".join(failures)) + return 1 + print("PASS: the node-wise wave route runs, agrees, restarts and refuses as required") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/validation/scripts/openfast_wavekin_vertex.py b/validation/scripts/openfast_wavekin_vertex.py new file mode 100644 index 00000000..c93ef8a9 --- /dev/null +++ b/validation/scripts/openfast_wavekin_vertex.py @@ -0,0 +1,129 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Vertex exactness of the node-wise wave kinematics (WaterKin SEASTATE_SPECTRAL), no coupled run. + +For each case a SeaState input is derived from a base file (the r-test ``MD_Shared`` +``SeaState.dat`` of the OpenFAST tutorial) and given to ``cabledyn_wavekin_check`` (built in the +OpenFAST tree with CableDyn, target ``cabledyn_wavekin_check``). The checker initialises SeaState, +builds the node-wise field from its components as the CableDyn module does, and compares the +velocity, acceleration, dynamic pressure and elevation with SeaState's grid at the grid vertices and +a set of wave steps; with stretching (WaveStMod 1 to 3) also the stretched values with SeaState's own +sampler where it reads grid levels only. It fails when a difference exceeds 1e-5 of the largest grid +value of that quantity (the single-precision round-off of SeaState's FFT). + +Cases: long-crested JONSWAP at 0, 30 and 90 deg in 50 m and 200 m of water and in 1000 m (deep +components, k h > 89.4); a short-crested sea (WaveDirMod 1); a regular wave (WaveMod 1); a +constrained wave (ConstWaveMod 1); WaveStMod 1, 2 and 3; FAST.Farm's Mod_WaveField = 2 phase shift +(a turbine at (500, -300) m). The grids are small (WaveTMax 200 s, 13 x 13 x 10 points). + +usage: openfast_wavekin_vertex.py --check --seastate + --work +""" + +from __future__ import annotations + +import argparse +import re +import subprocess +import sys +from pathlib import Path + +BASE = { + "WaveMod": "2", + "WaveStMod": "0", + "WvCrntMod": "0", + "WaveTMax": "200", + "WaveDT": "0.2", + "WaveHs": "6.0", + "WaveTp": "10", + "WaveDir": "0", + "WaveDirMod": "0", + "X_HalfWidth": "120", + "Y_HalfWidth": "120", + "Z_Depth": '"default"', + "NX": "7", + "NY": "7", + "NZ": "10", + "CurrMod": "0", + "WvDiffQTF": "FALSE", + "WvSumQTF": "FALSE", + "ConstWaveMod": "0", +} + +# name: (SeaState edits, water depth, extra checker arguments) +CASES: dict[str, tuple[dict[str, str], float, list[str]]] = { + "lc0_h50": ({}, 50.0, []), + "lc30_h200": ({"WaveDir": "30"}, 200.0, []), + "lc90_h200": ({"WaveDir": "90"}, 200.0, []), + "lc30_h1000": ({"WaveDir": "30", "WvHiCOff": "2.5"}, 1000.0, []), + "short_h200": ( + {"WaveDirMod": "1", "WaveDirSpread": "2", "WaveNDir": "5", "WaveDirRange": "90"}, + 200.0, + [], + ), + "regular_h200": ({"WaveMod": "1", "WaveHs": "4", "WaveDir": "45"}, 200.0, []), + "constrained_h200": ( + {"ConstWaveMod": "1", "CrestHmax": "14", "CrestTime": "60", "WaveDir": "30"}, + 200.0, + [], + ), + "stretch1_h200": ({"WaveStMod": "1", "WaveDir": "30"}, 200.0, []), + "stretch2_h200": ({"WaveStMod": "2", "WaveDir": "30"}, 200.0, []), + "stretch3_h200": ({"WaveStMod": "3", "WaveDir": "30"}, 200.0, []), + "farm_shift_h200": ({"WaveDir": "30"}, 200.0, ["500", "-300"]), +} + + +def set_value(text: str, key: str, value: str, name: str) -> str: + pattern = re.compile(rf"(?m)^(\s*)(\S+)(\s+{re.escape(key)}\b)") + if len(pattern.findall(text)) != 1: + raise SystemExit(f"{name}: expected one {key} row in the base SeaState file") + return pattern.sub(lambda m: f"{m.group(1)}{value}{m.group(3)}", text) + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--check", type=Path, required=True) + parser.add_argument("--seastate", type=Path, required=True) + parser.add_argument("--work", type=Path, required=True) + parser.add_argument("--only", nargs="*", default=None) + args = parser.parse_args() + args.work.mkdir(parents=True, exist_ok=True) + base = args.seastate.read_text(encoding="latin-1") + failures = [] + for name, (edits, depth, extra) in CASES.items(): + if args.only and name not in args.only: + continue + text = base + for key, value in {**BASE, **edits}.items(): + text = set_value(text, key, value, name) + folder = args.work / name + folder.mkdir(exist_ok=True) + (folder / "SeaState.dat").write_text(text, encoding="latin-1") + proc = subprocess.run( + [str(args.check), "SeaState.dat", str(depth), *extra], + cwd=folder, + capture_output=True, + text=True, + errors="replace", + ) + log = proc.stdout + proc.stderr + (folder / "check.log").write_text(log, encoding="utf-8") + rows = [line for line in log.splitlines() if "relative" in line or "SeaState grid" in line] + verdict = "PASS" if proc.returncode == 0 and "PASS:" in log else "FAIL" + print(f"{name:20s} {verdict}") + for row in rows: + print(" " + row.strip()) + if verdict != "PASS": + failures.append(name) + print(" " + "\n ".join(log.splitlines()[-8:])) + if failures: + print("FAIL: " + ", ".join(failures)) + return 1 + print("PASS: the node-wise kinematics equal the SeaState grid at its vertices in every case") + return 0 + + +if __name__ == "__main__": + sys.exit(main())