diff --git a/.github/scripts/rerun_unacquired.sh b/.github/scripts/rerun_unacquired.sh new file mode 100755 index 00000000..9f12284a --- /dev/null +++ b/.github/scripts/rerun_unacquired.sh @@ -0,0 +1,60 @@ +#!/usr/bin/env bash +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +# +# Rerun the jobs of a finished workflow run that never started because GitHub found no hosted +# runner for them. A job GitHub could not hand to a runner ends cancelled after about 15 minutes +# with the annotation "The job was not acquired by Runner of type hosted even after multiple +# attempts"; it happens when the macOS arm64 pool is short of capacity. Such a job ran none of +# our code, so rerunning it hides nothing. A job that ran and failed is never rerun. +# +# usage: rerun_unacquired.sh [--dry-run] +# +# The jobs are judged by their latest execution over all the run's attempts (the run's job list, +# filter=latest), not by the last attempt alone, which lists only the jobs it reran. When every +# job whose latest execution failed went unacquired, the run's failed jobs are rerun together +# (GitHub reruns every job whose latest execution failed, so these alone). When some job failed +# on its own, the run stays failed whatever happens, and only the first unacquired job is rerun, +# alone, so that its own result is known; the next completion of the run reruns the next one. +# Reruns stop at the fourth attempt. +set -euo pipefail + +repo=$1 +run=$2 +attempt=$3 +dry_run=${4:-} +max_attempt=4 + +if [ "$attempt" -ge "$max_attempt" ]; then + echo "run $run attempt $attempt: no further reruns (at most $max_attempt attempts)" + exit 0 +fi + +unacquired=() +ran=0 +jobs=$(gh api "repos/$repo/actions/runs/$run/jobs?filter=latest&per_page=100" --paginate \ + --jq '.jobs[] | select(.conclusion == "failure" or .conclusion == "cancelled" or .conclusion == "timed_out") + | [.id, .conclusion, .name] | @tsv') +while IFS=$'\t' read -r id conclusion name; do + [ -n "$id" ] || continue + if gh api "repos/$repo/check-runs/$id/annotations" --jq '.[].message' | grep -q 'was not acquired by Runner'; then + unacquired+=("$id") + echo "not started (no runner acquired): $name" + else + ran=$((ran + 1)) + echo "ran and ended $conclusion, left as it is: $name" + fi +done <<< "$jobs" + +if [ "${#unacquired[@]}" -eq 0 ]; then + echo "run $run (latest executions, attempt $attempt): no unacquired job" + exit 0 +fi + +if [ "$ran" -eq 0 ]; then + echo "rerunning the failed jobs of run $run (all ${#unacquired[@]} went unacquired)" + [ "$dry_run" = "--dry-run" ] || gh run rerun "$run" --repo "$repo" --failed +else + echo "rerunning job ${unacquired[0]} of run $run alone ($ran other job(s) failed on their own)" + [ "$dry_run" = "--dry-run" ] || gh api -X POST "repos/$repo/actions/jobs/${unacquired[0]}/rerun" --silent +fi diff --git a/.github/workflows/rerun-unacquired.yml b/.github/workflows/rerun-unacquired.yml new file mode 100644 index 00000000..01b7f008 --- /dev/null +++ b/.github/workflows/rerun-unacquired.yml @@ -0,0 +1,37 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +# +# Reruns the jobs of a failed CI run that GitHub never started because no hosted runner was +# acquired (the macOS arm64 pool runs short of capacity; such a job is cancelled after about +# 15 minutes and ran none of the repository's code). Jobs that ran and failed stay failed. The +# logic, with its limits, is in .github/scripts/rerun_unacquired.sh. A workflow_run workflow +# runs from the default branch's copy of this file. +name: rerun unacquired jobs + +on: + workflow_run: + workflows: [fortran, python, wheels] + types: [completed] + +permissions: + actions: write + checks: read + contents: read + +jobs: + rerun: + if: github.event.workflow_run.conclusion == 'failure' + runs-on: ubuntu-latest + timeout-minutes: 10 + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + sparse-checkout: .github/scripts + persist-credentials: false + - name: Rerun the jobs no runner picked up + env: + GH_TOKEN: ${{ github.token }} + REPO: ${{ github.repository }} + RUN_ID: ${{ github.event.workflow_run.id }} + RUN_ATTEMPT: ${{ github.event.workflow_run.run_attempt }} + run: bash .github/scripts/rerun_unacquired.sh "$REPO" "$RUN_ID" "$RUN_ATTEMPT" diff --git a/CHANGELOG.md b/CHANGELOG.md index 838c3f59..54c9e27a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,118 @@ All notable changes to CableDyn are recorded in this file. The format follows ## [Unreleased] +## [0.5.0] - 2026-12-04 + +### 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 + stops when the grid cannot give them those kinematics, where it warned once and ran on. It stops at the + static start or at the first CableDyn step at which a line node in the water lies outside the grid, + where SeaState gives it the kinematics of the grid boundary; the message gives the time and, line by + line, the number of such nodes and the deepest and shallowest of them. It also stops at the start when + the grid has `NX = 2` or `NY = 2` (three points across that axis) under waves that vary along the axis + (a long-crested sea not along the other axis, within 1e-4 deg, a short-crested sea, or supplied + `WaveMod 6` kinematics that differ across the axis, judged from the data) while the lines + sample the grid in the water: SeaState then interpolates across a large part of a wavelength for every + line node and hull member, also near a grid line, from which the sea sways the lines. + A grid with `NY = 2` under waves along x, or `NX = 2` under waves along y, still runs. The new + `OPTIONS waveGridCheck warn` turns both checks into the former warnings (`error`, the default, stops). + The r-test `MD_Shared` SeaState file of the OpenFAST tutorial, which covers only the platform, now stops + until its grid is enlarged as the tutorial describes. Runs that pass the checks give the same results, + bit for bit. +- In OpenFAST, CableDyn evaluates its output channels only at the steps OpenFAST writes (`DT_Out`, from + `TStart`) and when it linearizes, as AeroDyn and BeamDyn can, where it evaluated them at every output + call of every step (two to four per step in the tightly coupled solver). The loads are evaluated as + before. On the IEA-15 MW lazy-wave cable deck with 17 stations and torsion channels at DT = 0.025 s, + `DT_Out` = 0.05 s, the channels cost 12.6 s where they cost 53.1 s and the run 10 % less CPU time; the + `.out` and `.CD.out` are the same as before, bit for bit, also with the mooring supercycled and after a + restart from a checkpoint. This needs the OpenFAST integration patches of this release. +- The nodal twist of a finite-EI line costs less. Its residual no longer forms the Hessian of the + torque-tension coupling term, which only the tangent uses. An element's reference twist is taken + from the last evaluation when every input it reads is the same, bit for bit; in OpenFAST every output + call moves only the fairlead end, so all elements but the end ones are taken over. On the IEA-15 MW + lazy-wave cable deck (237 elements, torsion, DT = 0.0125 s, 400 s, operating rotor) the run takes + 9.00 min of CPU time where it took 9.79 min after the change above (11.23 min before both); the + `.out` and `.CD.out` are the same, bit for bit. + +- In OpenFAST, the lines on the SeaState grid route take the wave and current kinematics at their + positions at the sample time (the end of the CableDyn step): their committed positions advanced by + their velocity, taken from their last two committed positions. Before, they took them at the + committed positions of the step's start, one CableDyn step behind (a phase error of k v dtM). + Grid-route results change at that level, by design: on the r-test chain mooring of the OpenFAST + tutorial (Hs 6 m, Tp 12 s, 60 s, dtM 0.025 s) the fairlead-tension standard deviations move by less + than 0.001 % and the tensions by at most 200 N (0.002 standard deviations); on a chain and lazy-wave + cable mooring at dtM 0.0125 s over 300 s the standard deviations of tension, curvature and twist + move by less than 0.001 % and the largest differences are at the last printed digit. The wave-grid + guard and the provenance record check and report the positions sampled, so a node that a step's + motion carries out of the grid is found at that step. A checkpoint carries the position history, so + a restarted run continues bit for bit. The node-wise route (`SEASTATE_SPECTRAL`) has advanced its + nodes this way from the start. + +### Fixed + +- A Syrope rope at its running maximum had a band of slow strains, up to 9e-7 wide on the shipped table, + over which its recovered mean tension did not change, so every one of them was a rest point and rounding + chose the one a static start took. Two starts of the composite example that agreed to 1e-10 gave runs + that differed by up to 2.3e-4 of the channel maxima. The OWC recovery is now the exact inverse of + `eps_owc(T) - eps_fast(T)`, where it interpolated the slow strains of the table rows, and the working + curve meets it at one slow strain. Results of a rope loaded along its OWC change by about the size of + the former interpolation error (1.4e-4 on the composite example) and no longer depend on the spacing + of the OWC rows. On the OWC the recovery differs from MoorDyn's, which interpolates the rows. + A table with a row steeper than the fast spring at the row's start stops with a named error. + +- A single-section Syrope line was refused as slack where its chord strain lay below the zero-tension + strain of its `SYROPE IC` working curve, or its chord was shorter than the line, although its weight sags + it taut. It now starts as a composite line does, from the curve's alpha. Nine ropes from 39 kN to 236 kN + agree with an independent elastic catenary to 3.4e-6. A rope that carries no tension still stops with a + named error. + +- A Syrope line whose rest tension is a small part of its past one (a `SYROPE IC` `Tmax0` well above the + installed tension, as of a polyester mooring line after a storm that loaded it) failed to start when its + static secants, far below the working curve's tangent along the whole line, did not settle in 50 + iterations. From the thirtieth iteration on, the static start combines the stored solves of the whole line + (Anderson acceleration); a 644 m rope that stopped at a residual of 1.2e-10 after 50 iterations starts in + fewer than 40, with the same tensions. Lines that settled in fewer iterations start as before, bit for bit. + ## [0.4.3] - 2026-11-20 ### Added @@ -1412,7 +1524,8 @@ Corrections made during the pre-release review. values of the shipped example decks and states which tension (end element or `FairTen` end force) each comparison uses. -[Unreleased]: https://github.com/SMI-Lab-Inha/CableDyn/compare/v0.4.3...HEAD +[Unreleased]: https://github.com/SMI-Lab-Inha/CableDyn/compare/v0.5.0...HEAD +[0.5.0]: https://github.com/SMI-Lab-Inha/CableDyn/releases/tag/v0.5.0 [0.4.3]: https://github.com/SMI-Lab-Inha/CableDyn/releases/tag/v0.4.3 [0.4.2]: https://github.com/SMI-Lab-Inha/CableDyn/releases/tag/v0.4.2 [0.4.1]: https://github.com/SMI-Lab-Inha/CableDyn/releases/tag/v0.4.1 diff --git a/CITATION.cff b/CITATION.cff index 69442422..a1bd5c64 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -23,8 +23,8 @@ authors: repository-code: "https://github.com/SMI-Lab-Inha/CableDyn" url: "https://github.com/SMI-Lab-Inha/CableDyn" license: Apache-2.0 -version: 0.4.3 -date-released: 2026-11-20 +version: 0.5.0 +date-released: 2026-12-04 keywords: - mooring dynamics - cable dynamics diff --git a/CMakeLists.txt b/CMakeLists.txt index ddbfa291..81a17543 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -8,7 +8,7 @@ # cmake_minimum_required(VERSION 3.20) # VERSION is a bare numeric triple matching the release version. -project(CableDynCore VERSION 0.4.3 LANGUAGES C Fortran +project(CableDynCore VERSION 0.5.0 LANGUAGES C Fortran DESCRIPTION "CableDyn geometrically exact cable/mooring solver — Fortran core") option(CABLEDYN_ENABLE_COVERAGE "Instrument the GNU Fortran core for gcov/gcovr source coverage" OFF) @@ -419,7 +419,9 @@ add_library(cabledyn_obj OBJECT src/CableDyn_FatalReport.f90 src/CableDyn_Profile.f90 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 @@ -446,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 @@ -1294,6 +1297,33 @@ target_link_libraries(test_load_predictor PRIVATE cabledyn_core) add_test(NAME load_predictor COMMAND test_load_predictor) set_tests_properties(load_predictor PROPERTIES LABELS "fortran;unit;openfast") +# The rules of the coupled wave-grid guard (OPTION waveGridCheck): which wave directions a +# SeaState grid with NX or NY = 2 represents, and which nodes lie between its points; the option +# reaches the coupled aggregate from the mixed example deck. +add_executable(test_wave_grid tests/test_wave_grid.f90) +target_link_libraries(test_wave_grid PRIVATE cabledyn_core) +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/wave_grid) +add_test(NAME wave_grid COMMAND test_wave_grid ${CMAKE_SOURCE_DIR}/examples/iea15mw_umaine_mixed_cabledyn.dat + 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) @@ -2151,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). @@ -2336,8 +2386,14 @@ if(Python3_Interpreter_FOUND) OUTPUT_QUIET ERROR_QUIET) endif() if(_pybind_deps_rc EQUAL 0) + # The suite runs in a folder of its own: an in-memory deck (DeckFile.from_text) takes its side + # files (wave_frequencies.txt, current_profile.txt, ...) from the working directory, and tests + # such as wavekin_modes write theirs into the build folder while this one runs under ctest -j. + set(_cabledyn_python_test_cwd "${CMAKE_BINARY_DIR}/python_package_cwd") + file(MAKE_DIRECTORY "${_cabledyn_python_test_cwd}") add_test(NAME python_package - COMMAND ${Python3_EXECUTABLE} -m pytest ${CMAKE_CURRENT_SOURCE_DIR}/python/tests -q) + COMMAND ${Python3_EXECUTABLE} -m pytest ${CMAKE_CURRENT_SOURCE_DIR}/python/tests -q + WORKING_DIRECTORY "${_cabledyn_python_test_cwd}") if(WIN32 AND CABLEDYN_RUNTIME_DLLS) # Python 3.8+ deliberately ignores PATH for dependent-DLL resolution. # Exercise the self-contained deployment set whose shared library and GNU/OpenBLAS diff --git a/DEVELOPMENT.md b/DEVELOPMENT.md index 6cc9d3d4..efceefae 100644 --- a/DEVELOPMENT.md +++ b/DEVELOPMENT.md @@ -258,6 +258,13 @@ stack overflow while ElastoDyn initialises. checks that the CableDyn banner appears in the log, that the executable names itself `OpenFAST--CableDyn-`, and that the output is finite. +The SeaState wave-grid checks of the OpenFAST module (`OPTIONS waveGridCheck`) run only inside +OpenFAST. `validation/scripts/openfast_wave_grid_guard.py --exe --case-dir

+--work ` runs the IEA-15 MW model of the OpenFAST tutorial (the r-test `MD_Shared` turbine-1 +files in ``) under grids that must stop the run by default and run with `waveGridCheck warn`, +and under grids that must run; with `--base-exe` (an `openfast.exe` built from the previous CableDyn +sources) it also requires the same output as that build where the run passes. + An `openfast.exe` built this way through CMake does not embed the UTF-8 active-code-page manifest (`app/utf8_code_page.manifest`), so on Windows it may not open input files in folders whose names the system code page cannot spell. The diff --git a/README.md b/README.md index a9d6998c..6555321a 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ lifting off the seabed lie inside the formulation. It runs as a standalone program, as a mooring module of OpenFAST and FAST.Farm (`CompMooring = 5`), through a C interface, or from Python. -The current stable release is `v0.4.3`; interfaces are versioned and may change before `1.0.0`. +The current stable release is `v0.5.0`; interfaces are versioned and may change before `1.0.0`. ## What CableDyn does @@ -89,8 +89,8 @@ Unsupported combinations stop with a named error rather than running approximate |---|---| | `CableDyn_driver.exe` | Standalone solver for Windows x64 (AVX2 processor) | | `openfast.exe` | OpenFAST with CableDyn available as `CompMooring = 5` | - | `cabledyn-0.4.3-py3-none-any.whl` | Python package (pre- and post-processing, batch runs) | - | `cabledyn-0.4.3.tar.gz` | Python source distribution | + | `cabledyn-0.5.0-py3-none-any.whl` | Python package (pre- and post-processing, batch runs) | + | `cabledyn-0.5.0.tar.gz` | Python source distribution | | `SHA256SUMS.txt` | Checksums for the assets above | Both executables are statically linked, need no installer, compiler, or runtime @@ -128,7 +128,7 @@ Unsupported combinations stop with a named error rather than running approximate cabledyn-run examples\wd0050_chain.dat wd0050 ``` - The pure Python wheel on the release page (`cabledyn-0.4.3-py3-none-any.whl`) + The pure Python wheel on the release page (`cabledyn-0.5.0-py3-none-any.whl`) carries no driver: `cabledyn-run` then needs `--executable .\CableDyn_driver.exe`, the `CABLEDYN_DRIVER` environment variable, or the driver on `PATH`. A source build names the driver `cabledyn` (see [Build from source](#build-from-source)); @@ -202,7 +202,7 @@ If you use CableDyn in academic work, please cite: > offshore wind. *Ocean Engineering* 368 (Part 2), 128332, 2026. > -To identify the software version, also cite the release (CableDyn 0.4.3). +To identify the software version, also cite the release (CableDyn 0.5.0). The [citation file](https://cabledyn.readthedocs.io/en/latest/citing.html) contains both entries (GitHub **Cite this repository**); BibTeX is on the manual's [How to cite](https://cabledyn.readthedocs.io/en/latest/citing.html) page. diff --git a/RELEASE.md b/RELEASE.md index 4d17a314..06d34116 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -104,7 +104,7 @@ The build fails if either executable imports a non-system DLL or lacks the UTF-8 active-code-page manifest (`release/check_static_windows_binary.ps1`), or if the standalone and `CompMooring = 5` smoke cases fail with a system-only `PATH` or from a folder named in mixed scripts. It also fails unless `openfast.exe -v` names the -executable `OpenFAST-v5.0.0-CableDyn-0.4.3`: the OpenFAST base and the CableDyn version, +executable `OpenFAST-v5.0.0-CableDyn-0.5.0`: the OpenFAST base and the CableDyn version, never a `-dirty` describe of the patched tree. The release workflow (`.github/workflows/release-windows-static.yml`) produces diff --git a/VALIDATION.md b/VALIDATION.md index ea5cf05f..311e418c 100644 --- a/VALIDATION.md +++ b/VALIDATION.md @@ -328,7 +328,7 @@ the tow tests it predicts). Inputs, reduction scripts, results, and source prove over the full 30-condition period-radius matrix, cycle-maximum upper-end force has RMSE 1.58 N, mean absolute percentage error 3.11%, Pearson correlation 0.993, and Lin concordance 0.989. Two phase-averaged measured histories had - waveform RMSEs of 5.93% and 2.56% of their force ranges with 0.3.0 (not rerun for 0.4.0, 0.4.1, 0.4.2 or 0.4.3). + waveform RMSEs of 5.93% and 2.56% of their force ranges with 0.3.0 (not rerun for 0.4.0, 0.4.1, 0.4.2, 0.4.3 or 0.5.0). Halving the mesh length and the time step changes the mean cycle maximum by at most 0.29% and 0.27%. The 0.3125 ms step resolves the segment axial modes that the snap loads excite (and the axial diff --git a/doc/capi.rst b/doc/capi.rst index 1f1e7d51..96bfebba 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -122,12 +122,12 @@ files directly, as shown below. - Library files - Header * - Linux - - ``lib/libcabledyn.so.0.4.3``, the soname link ``libcabledyn.so.1``, and the development + - ``lib/libcabledyn.so.0.5.0``, the soname link ``libcabledyn.so.1``, and the development link ``libcabledyn.so``. ``lib`` is the platform ``CMAKE_INSTALL_LIBDIR``, which can be ``lib64`` or a multiarch directory. - ``include/CableDyn_CAPI.h`` * - macOS - - ``lib/libcabledyn.0.4.3.dylib``, ``lib/libcabledyn.1.dylib``, ``lib/libcabledyn.dylib`` + - ``lib/libcabledyn.0.5.0.dylib``, ``lib/libcabledyn.1.dylib``, ``lib/libcabledyn.dylib`` - ``include/CableDyn_CAPI.h`` * - Windows, GNU toolchain - ``bin/libcabledyn.dll`` and the import library ``lib/libcabledyn.dll.a``. The GNU @@ -257,7 +257,7 @@ ABI and versioning - the same four numbers, reported by the loaded library * - ``CableDyn_GetVersionString`` - runtime - - ``"CableDyn 0.4.3 C-ABI 1"`` + - ``"CableDyn 0.5.0 C-ABI 1"`` * - shared-library ``SOVERSION`` - 1 - soname ``libcabledyn.so.1`` or install name ``libcabledyn.1.dylib``. The Windows DLL @@ -830,7 +830,7 @@ Version queries - ``char *`` - ``version_len`` - yes: no-op - - receives ``"CableDyn 0.4.3 C-ABI 1"``, truncated to ``version_len - 1`` characters and + - receives ``"CableDyn 0.5.0 C-ABI 1"``, truncated to ``version_len - 1`` characters and ``NUL``-terminated * - ``version_len`` - in diff --git a/doc/citing.rst b/doc/citing.rst index cc88f09d..12bfc1eb 100644 --- a/doc/citing.rst +++ b/doc/citing.rst @@ -53,7 +53,7 @@ software]. https://github.com/SMI-Lab-Inha/CableDyn } When results depend on a particular release, quote the version reported in the solver banner -(``CableDyn v0.4.3``) together with the options recorded for the run. +(``CableDyn v0.5.0``) together with the options recorded for the run. Relation to the journal article ------------------------------- diff --git a/doc/coupling_boundary.md b/doc/coupling_boundary.md index 5c441a73..a93cfab3 100644 --- a/doc/coupling_boundary.md +++ b/doc/coupling_boundary.md @@ -117,7 +117,7 @@ Rules shared by every entry point: The interface ships as the versioned shared library `libcabledyn` (`cabledyn.dll` in an Intel Fortran and MSVC build; CMake target `cabledyn_shared`) with the installed header; it reports -CableDyn 0.4.3 and C ABI version 1, minor extension 4. The Python package uses the same library. +CableDyn 0.5.0 and C ABI version 1, minor extension 4. The Python package uses the same library. ### Concurrency diff --git a/doc/driver_format.md b/doc/driver_format.md index c7131b8b..56500003 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -342,9 +342,10 @@ and `BA = BA_s|BA_d`: or `EXP`), `k1`, and `k2` rows as `value name`. `OWC` names the original-working-curve table, resolved relative to the settings file: a `strain tension` table of at least two numeric rows. - `BA_d` enters the slow-state rate; the physical damping contribution is `BA_s*d(eps_slow)/dt`. -- A Syrope type requires `EI = 0`. A Syrope line is either a single section, taut at - initialisation, or a composite line whose other sections are linear-elastic `EI = 0` sections (a - chain–polyester–chain mooring), with every Syrope element in tension at initialisation. It runs +- A Syrope type requires `EI = 0`. A Syrope line is either a single section or a composite line + whose other sections are linear-elastic `EI = 0` sections (a chain–polyester–chain mooring), with + every Syrope element in tension at initialisation: a line its weight sags taut starts even where + its chord is shorter than the line. It runs on a dynamic deck (`dtM`/`TMax`) and takes the seabed, `bathymetryFile`, Morison loads, current, waves, host fluid fields and VIV of any `EI = 0` line, and active line control of a Syrope segment on the OpenFAST route ([CONTROL](#control-optional-openfast-line-control)). @@ -1829,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/index.rst b/doc/index.rst index 1646dcc0..7b9f913d 100644 --- a/doc/index.rst +++ b/doc/index.rst @@ -14,12 +14,13 @@ with MoorDyn-C, MoorDyn-F, and OrcaFlex on common reference cases. .. admonition:: Release status :class: note - CableDyn ``v0.4.3`` is the current stable release. It is on PyPI with wheels that carry the - solver (``pip install cabledyn``). It adds in-line, higher-harmonic and wake-oscillator VIV, - amplitude-dependent VIV coefficients and cross-flow damping, a VIV frame for cables moved - through the water, and bending and Rayleigh damping of finite-EI cables, each validated - against published riser and power-cable tests; it makes the coupled outputs of a cable - restrained in torsion several times cheaper, and lets a finite-EI line end on a free point. + CableDyn ``v0.5.0`` is the current stable release. It is on PyPI with wheels that carry the + solver (``pip install cabledyn``). In OpenFAST the lines can take SeaState's waves from its + wave components at the line nodes, with no grid over the lines (``SEASTATE_SPECTRAL``), + validated against converged grids; a run whose SeaState grid cannot carry the lines' + kinematics now stops, the grid is sampled where the nodes are at the sample time, and every + run writes a provenance record. Coupled runs of a cable with the nodal twist take about a + fifth less CPU time with unchanged results, and Syrope lines start from more states. Every comparative-accuracy statement is linked to a passing benchmark in :doc:`validation`. The project remains below ``1.0.0``, so public APIs may evolve between minor releases. @@ -55,8 +56,8 @@ Download to first result in five minutes ---------------------------------------- #. Download ``CableDyn_driver.exe``, ``SHA256SUMS.txt``, and **Source code (zip)** (for the - ``examples`` folder) from the `v0.4.3 release - `_ and verify the checksum — + ``examples`` folder) from the `v0.5.0 release + `_ and verify the checksum — :doc:`installation`. No installer and no runtime DLLs. #. Put ``CableDyn_driver.exe`` in a working folder, unzip the source archive, and copy its ``examples`` folder next to the executable. diff --git a/doc/installation.rst b/doc/installation.rst index 55a0a069..7c4898a6 100644 --- a/doc/installation.rst +++ b/doc/installation.rst @@ -6,8 +6,8 @@ Installation There are two ways to get CableDyn: * **Windows release (recommended for users).** Two single-file executables and a Python wheel, - attached to the `v0.4.3 GitHub release - `_. No installer, no compiler, + attached to the `v0.5.0 GitHub release + `_. No installer, no compiler, and no runtime DLLs. Start here if you want a first result in five minutes. * **Build from source** (Windows, Linux, macOS). Needed for the C/Python in-process API, for development, and on every platform other than Windows x64. @@ -35,11 +35,11 @@ What is on the release page - OpenFAST v5.0.0 (maintained by NLR, the National Laboratory of the Rockies, formerly NREL) with CableDyn built in as ``CompMooring = 5``; stock MoorDyn (``CompMooring = 3``) is still available in the same binary (:doc:`openfast`). It names - itself ``OpenFAST-v5.0.0-CableDyn-0.4.3`` (``openfast.exe -v`` and the start of every run). - * - ``cabledyn-0.4.3-py3-none-any.whl`` + itself ``OpenFAST-v5.0.0-CableDyn-0.5.0`` (``openfast.exe -v`` and the start of every run). + * - ``cabledyn-0.5.0-py3-none-any.whl`` - the pure-Python package: deck editing, case generation, driver automation, result readers, fatigue and spectral post-processing (:doc:`python`) - * - ``cabledyn-0.4.3.tar.gz`` + * - ``cabledyn-0.5.0.tar.gz`` - the Python source distribution (same package as the wheel) * - ``SHA256SUMS.txt`` - SHA-256 checksums of the four files above @@ -65,7 +65,7 @@ Download and verify ~~~~~~~~~~~~~~~~~~~ 1. Create a folder, for example ``C:\CableDyn``, and download into it ``CableDyn_driver.exe``, - ``openfast.exe`` (only if you will couple with OpenFAST), ``cabledyn-0.4.3-py3-none-any.whl`` + ``openfast.exe`` (only if you will couple with OpenFAST), ``cabledyn-0.5.0-py3-none-any.whl`` (only if you will use Python), ``SHA256SUMS.txt``, and ``Source code (zip)``. 2. Verify every downloaded asset against ``SHA256SUMS.txt`` in PowerShell: @@ -85,8 +85,8 @@ Download and verify OK CableDyn_driver.exe OK openfast.exe - OK cabledyn-0.4.3-py3-none-any.whl - not downloaded cabledyn-0.4.3.tar.gz + OK cabledyn-0.5.0-py3-none-any.whl + not downloaded cabledyn-0.5.0.tar.gz ``not downloaded`` only reports an asset you chose to skip. @@ -95,7 +95,7 @@ Download and verify ``(Get-FileHash .\CableDyn_driver.exe -Algorithm SHA256).Hash`` with its line in ``SHA256SUMS.txt`` (the comparison is case-insensitive). -3. Unzip ``Source code (zip)``. It expands to a folder such as ``CableDyn-0.4.3``; copy (or move) +3. Unzip ``Source code (zip)``. It expands to a folder such as ``CableDyn-0.5.0``; copy (or move) its ``examples`` folder into ``C:\CableDyn`` so the layout is:: C:\CableDyn\ @@ -121,7 +121,7 @@ Check that it runs .. code-block:: text =================================================================== - CableDyn v0.4.3 + CableDyn v0.5.0 Geometrically exact finite-element statics and dynamics of mooring lines and dynamic power cables for floating offshore wind ------------------------------------------------------------------- @@ -177,8 +177,8 @@ the CableDyn shared library and the standalone driver, so the package runs decks release executables. On another platform pip builds from the source distribution, which needs a Fortran compiler and LAPACK. -The pure Python wheel on the release page (``cabledyn-0.4.3-py3-none-any.whl``) carries no -solver; install it with ``py -m pip install .\cabledyn-0.4.3-py3-none-any.whl``. The package +The pure Python wheel on the release page (``cabledyn-0.5.0-py3-none-any.whl``) carries no +solver; install it with ``py -m pip install .\cabledyn-0.5.0-py3-none-any.whl``. The package finds the driver in this order: #. an explicit path, ``CableDynDriver(r"C:\CableDyn\CableDyn_driver.exe")`` or @@ -273,7 +273,7 @@ The script downloads the LAPACK source from its release tag and verifies its SHA integration to OpenFAST itself (do not pre-apply it), builds both executables, rejects any non-system DLL import, runs a standalone and a coupled ``CompMooring = 5`` / ``CompMooring = 3`` smoke case with a system-only ``PATH``, and writes -``SHA256SUMS.txt`` into ``build-static-release\dist``. The v0.4.3 assets were built from +``SHA256SUMS.txt`` into ``build-static-release\dist``. The v0.5.0 assets were built from OpenFAST revision ``2895884d2be01862173c88d70f86b358d2f1a50a`` and smoke-tested against ``r-test`` revision ``dd5feaaaa500ba7283140107806300d551cff0a7``. diff --git a/doc/openfast.rst b/doc/openfast.rst index 780e37cd..5c7416f9 100644 --- a/doc/openfast.rst +++ b/doc/openfast.rst @@ -126,7 +126,9 @@ Fluid source ~~~~~~~~~~~~ With no WaterKin policy (``0 WaterKin``, the default), CableDyn samples the complete enabled -SeaState wave and current field at its line nodes and refreshes it every CableDyn step. A +SeaState wave and current field at its line nodes and refreshes it every CableDyn step, at the +end of the step and at the nodes' positions then: their positions at the last committed step +advanced by their velocity (from their last two committed positions). A WaterKin file can select file waves, a file depth-dependent current, host waves, or host current independently where the field is separable. Unsupported or double-counted combinations fail during initialisation. The selector matrix is in :doc:`options` and :doc:`driver_format`. @@ -136,7 +138,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. @@ -161,7 +167,9 @@ only the platform. The r-test ``MD_Shared`` file used in :doc:`tutorial_openfast grid; and * ``NX``, ``NY`` and ``NZ`` raised with the extents to keep the grid spacing: a horizontal spacing of about a tenth of the peak wavelength or less. A long-crested sea (``WaveDirMod = - 0``) that travels along x does not vary in y, so ``NY = 2`` is enough for it. + 0``) that travels along x (``WaveDir`` 0° or 180°) does not vary in y, so ``NY = 2`` is enough + for it, and ``NX = 2`` for one along y (90° or 270°). Any other sea, a long-crested one at + another heading or a short-crested one, varies along both axes and needs both resolved. SeaState holds the whole time history of the grid in memory, so memory and initialisation time grow with (2 ``NX`` − 1)(2 ``NY`` − 1) ``NZ`` ``WaveTMax`` / ``WaveDT``. For the @@ -172,18 +180,64 @@ or using ``NZ = 16`` changes the 10–70 s platform and fairlead-tension statist 0.1 %. The ``MD_Shared`` grid gives a line-1 fairlead tension standard deviation 18 % too high (0.136 MN instead of 0.115 MN). -CableDyn compares its nodes with the grid at the static equilibrium and at every CableDyn step. -At the first node found outside it prints one warning and continues: +CableDyn compares its nodes with the grid at the static equilibrium and at every CableDyn step, +and by default (``OPTIONS waveGridCheck error``) stops the run at the first step that finds a +node outside it, at initialisation for the ``MD_Shared`` grid: .. code-block:: text - WARNING: CableDyn mooring module: 147 of the 153 CableDyn sampling nodes in the water lie - outside the SeaState wave-kinematics grid at t = 0 s (warned once). SeaState clamps them to - the grid boundary, so their fluid kinematics and loads are not physical. 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. + 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, 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, 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 (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``) +apart, and SeaState interpolates the kinematics across the axis between them. That is exact only +for waves that do not vary along the axis: ``NY = 2`` for a long-crested sea along x and +``NX = 2`` for one along y, each within 1e-4°. Under any other sea, when the lines sample the grid +in the water at all, the run stops by default: + +.. code-block:: text + + CableDyn mooring module: the SeaState wave-kinematics grid has NY = 2 (3 points 900 m apart in y) + under long-crested waves at 30 deg, which vary along that axis: SeaState interpolates them + between the three grid points, over distances that are a large part of a wavelength or more, + for the hull members and for the lines, which sample the grid in the water at 153 CableDyn + nodes. By line: line 1, 51 nodes, deepest at (x, y, z) = (-735.56, 0, -200.01) m, shallowest at + (x, y, z) = (-58, 0, -14) m; line 2, ... ; line 3, ... . A grid with NY = 2 represents only + waves along x (0 or 180 deg) and one with NX = 2 only waves along y (90 or 270 deg), within + 1e-4 deg; in the SeaState input file raise the count so that the spacing resolves the shortest + wavelength that matters at the lines (a tenth of it or finer). To run on with the interpolated + kinematics, set waveGridCheck warn in the OPTIONS of the CableDyn deck. + +The directions are those of SeaState's wave components (the spread of ``WaveDirMod = 1``, the +component directions of ``WaveMod = 7``). Externally supplied kinematics (``WaveMod = 6``) have no +components, and SeaState does not use ``WaveDir`` in that mode, so there the supplied ``WaveVel`` +and ``WaveAcc`` are compared across the three grid points of the coarse axis: the check stops the +run when they differ by more than 1e-5 of their largest magnitude, and passes a field that is the +same at every point along that axis (waves along the other axis). A line lying on a +grid line across the coarse axis, such as one along ``y = 0``, is no exception: a node off it by a +small part of the half-width is already wrong in phase, and the sea sways the line off it. The +hull's Morison members read the same grid, so their kinematics are interpolated across the axis +too. ``waveGridCheck warn`` turns this check into a warning. Only nodes in the water are checked: a node above the free surface carries no fluid load, whatever kinematics SeaState would give it, so a suspended cable or jumper above the water may @@ -213,6 +267,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 --------------- @@ -223,7 +383,7 @@ Run and confirm Before trusting a run, confirm in the console: -#. ``Running CableDyn (v0.4.3, ...)`` and ``Parsing CableDyn input file: ``; +#. ``Running CableDyn (v0.5.0, ...)`` and ``Parsing CableDyn input file: ``; #. the ``dtM`` line and the model inventory (``Created CableDyn model: ... line object(s)``); #. for every line, the converged fairlead effective tension, force vector, inclination, declination, and azimuth at the static equilibrium — printed unconditionally, whether or not diff --git a/doc/options.rst b/doc/options.rst index 915adc9f..a1e2ac65 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -573,6 +573,26 @@ Finite-EI cable controls (see :doc:`openfast`) - OpenFAST - ``False predictLoads`` + * - ``waveGridCheck`` / ``wave_grid_check`` + - mode + - ``error`` + - ``error`` or ``warn`` (case-insensitive). The checks of the SeaState grid the lines take their + wave and current kinematics from: a line node in the water outside the grid (at the static + start or at any CableDyn step), and ``NX = 2`` or ``NY = 2`` under waves that vary along that + axis while the lines sample the grid in the water (at the start). ``error`` stops the + run with a message that gives the time and, by line, the nodes concerned; ``warn`` warns once + 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`` @@ -777,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..2e0f7909 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.5.0"`` + * - ``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/quickstart.rst b/doc/quickstart.rst index 89c3a6ae..9103509a 100644 --- a/doc/quickstart.rst +++ b/doc/quickstart.rst @@ -18,7 +18,7 @@ and the ``examples`` folder (from the release's **Source code (zip)**) side by s .. code-block:: powershell Set-Location C:\CableDyn - .\CableDyn_driver.exe --version # prints the v0.4.3 banner, exit code 0 + .\CableDyn_driver.exe --version # prints the v0.5.0 banner, exit code 0 2. Solve a mooring line ----------------------- @@ -38,7 +38,7 @@ The run takes well under a second: .. code-block:: text =================================================================== - CableDyn v0.4.3 + CableDyn v0.5.0 Geometrically exact finite-element statics and dynamics of mooring lines and dynamic power cables for floating offshore wind ------------------------------------------------------------------- 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/troubleshooting.rst b/doc/troubleshooting.rst index f89f972d..4c815711 100644 --- a/doc/troubleshooting.rst +++ b/doc/troubleshooting.rst @@ -344,11 +344,11 @@ Model data ``EI = 0``. * - ``a LINE TYPES BA entry cannot have more bar-separated values than its EA entry`` - write ``BA`` as one value for a plain EA and at most ``Bs|Bd`` for a viscoelastic EA. - * - ``a Syrope line does not support finite-EI bending`` / ``a Syrope line must be a single - section`` / ``must be taut at init`` / ``has no static output`` - - a Syrope line is one ``EI = 0`` section, taut at initialisation, marched with - ``dtM``/``TMax``; it takes the seabed, Morison loads, current, waves and host fluid of any - ``EI = 0`` line. Adjust the model accordingly. + * - ``a Syrope line does not support finite-EI bending`` / ``is slack at init`` + - a Syrope line has ``EI = 0`` and carries tension in every Syrope element at initialisation + (a chord shorter than the line is fine where its weight sags it taut). It takes the seabed, + Morison loads, current, waves and host fluid of any ``EI = 0`` line. Shorten the line or + raise the pretension. * - ``Syrope alpha and beta ... must be positive`` / ``the Syrope BA column needs two parts`` / ``the Syrope settings file needs OWC, WCType, k1, and k2 rows`` - see the Syrope column rules in :doc:`driver_format`: ``EA = SYROPE:|alpha|beta`` @@ -698,17 +698,28 @@ Warnings and notes that do not stop a run line takes up by its shape; the torque follows from it. A non-zero descent count means the straight or untwisted branch was unstable at the imposed twist and the solve moved to a buckled shape; check the shape and the ``Twist`` channel. - * - ``WARNING: CableDyn mooring module: of the CableDyn sampling nodes in the water - lie outside the SeaState wave-kinematics grid at t = ... s (warned once)`` (OpenFAST) + * - ``CableDyn mooring module: of the CableDyn sampling nodes in the water lie outside + the SeaState wave-kinematics grid at t = ... s`` (OpenFAST; an error, or with + ``waveGridCheck warn`` a warning given once) - the SeaState grid (``X_HalfWidth``, ``Y_HalfWidth``, ``Z_Depth``) does not cover the lines in the water (nodes above the free surface carry no fluid load and are not - counted), and SeaState gives the nodes outside it the kinematics of the grid boundary: waves - out of phase beyond a half-width, kinematics that are too strong below ``Z_Depth``. The - message names the farthest node in each direction. Enlarge the listed inputs in the - SeaState file past the farthest anchor (``Z_Depth`` to the water depth, its default) and - raise ``NX``, ``NY``, ``NZ`` to keep the spacing. A SeaState file written for the - platform alone, such as the r-test ``MD_Shared`` file, triggers it. See - :ref:`openfast:SeaState grid` for sizes and memory. + counted), and SeaState would give the nodes outside it the kinematics of the grid boundary: + waves out of phase beyond a half-width, kinematics that are too strong below ``Z_Depth``. + The message lists the nodes outside by line, with the deepest and shallowest of them, and + the farthest node in each direction. Enlarge the listed inputs in the SeaState file past + the farthest anchor (``Z_Depth`` to the water depth, its default) and raise ``NX``, ``NY``, + ``NZ`` to keep the spacing. A SeaState file written for the platform alone, such as the + r-test ``MD_Shared`` file, triggers it. ``OPTIONS waveGridCheck warn`` runs on with the + boundary kinematics. See :ref:`openfast:SeaState grid` for sizes and memory. + * - ``CableDyn mooring module: the SeaState wave-kinematics grid has NY = 2 (3 points ... m apart + in y) under ...`` (OpenFAST; an error, or with ``waveGridCheck warn`` a warning) + - the grid has three points across an axis along which the waves vary: ``NY = 2`` under a + sea not along x, or ``NX = 2`` under a sea not along y (a long-crested sea at another + heading, or a short-crested sea), while the lines sample the grid in the water. SeaState + interpolates across a large part of a wavelength for every line node and hull member, also + near a grid line, from which the sea sways the lines. Raise ``NY`` (or ``NX``) so + that the spacing resolves the shortest wavelength that matters at the lines. See + :ref:`openfast:SeaState grid`. * - ``Note: LINE is stretched to a static strain of ... % at the fairlead`` - the fairlead tension over the EA of the End A section exceeds ``maxStrain`` (when the OPTION is given and positive) or 10 % (when it is not given or is ``0``, which disables diff --git a/doc/tutorial_openfast.rst b/doc/tutorial_openfast.rst index 726b26fa..ec7416e3 100644 --- a/doc/tutorial_openfast.rst +++ b/doc/tutorial_openfast.rst @@ -119,10 +119,17 @@ outside the grid the kinematics of the grid boundary. Enlarge the grid to cover This sets ``X_HalfWidth`` and ``Y_HalfWidth`` to 900 m, ``Z_Depth`` to the water depth, 37 grid points along each half of x (25 m spacing) and 11 in depth. ``NY`` stays 2 because the long-crested sea travels along x and does not vary in y. SeaState then needs about 4.6 GB of -memory and several seconds to generate the grid. Without this step the run still completes, but -CableDyn warns that 147 of its 153 line nodes lie outside the SeaState wave-kinematics grid, and -the line-1 fairlead tension standard deviation comes out 18 % too high. Grid sizing is -described in :ref:`openfast:SeaState grid`. +memory and several seconds to generate the grid. Without this step CableDyn stops at +initialisation: 147 of its 153 line nodes lie outside the SeaState wave-kinematics grid. With +``waveGridCheck warn`` in the deck's OPTIONS it runs on with the boundary kinematics, and the +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 --------------------------- @@ -168,7 +175,7 @@ The CableDyn part of the console (other modules' lines trimmed): .. code-block:: text - Running CableDyn (v0.4.3, 2026-11-20). + Running CableDyn (v0.5.0, 2026-12-04). CableDyn: geometrically exact finite-element statics and dynamics of mooring lines and dynamic power cables. ... CableDyn time step dtM = 2.50000E-02 s (1 x glue DT; deck dtM) @@ -201,8 +208,8 @@ Check, in order: #. ``Running CableDyn (`` — the CableDyn-enabled executable is in use. A stock OpenFAST rejects ``CompMooring = 5`` during input validation. -#. The line inventory (3 lines, 6 points) and ``dtM``, and no ``WARNING: CableDyn mooring module: - ... lie outside the SeaState wave-kinematics grid`` line (step 3). +#. The line inventory (3 lines, 6 points) and ``dtM``. A SeaState grid that does not cover the + lines stops the run at initialisation (step 3). #. The initial fairlead tensions: 2.437 MN per line, with the line tangent 55.7° below horizontal, as in the standalone ``spread_3line_chain.dat`` of :doc:`tutorial_spread`. The tension is the magnitude of the line-end force, which includes the fairlead node's share of diff --git a/examples/cabledyn_options_reference.dat b/examples/cabledyn_options_reference.dat index b8038759..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 @@ -98,6 +100,7 @@ none waves - Wave model and parameters (m, s, deg) {none; airy; -- 0 WriteLog - MoorDyn logging compatibility only; accepted and ignored -- 0.1 dtOut - MoorDyn output-cadence compatibility only; accepted and ignored -- 0.1 CDOutDt - OpenFAST/FAST.Farm: .CD.out row interval, a whole multiple of the CableDyn step [default: 0 = every step] +-- warn waveGridCheck - OpenFAST: a SeaState grid that misses or under-resolves the line nodes {error=stop; warn} [default: error] -- 0 Currents - MoorDyn-C current mode {0=none; 1=current_profile.txt} [default: 0] -- 0.25 dtWave - MoorDyn-C WaveKin 3 resampling step (s) [default: 0.25] -- 3.14159 WvHiCOff - High cut-off of an elevation record, WaveKinMod 1 or WaveKin 3 (rad/s) {value; none} [default: 3.14159] 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 7dac9f6d..8b3c1e37 100644 --- a/examples/openfast/README.md +++ b/examples/openfast/README.md @@ -49,7 +49,8 @@ The initial CableDyn fairlead tensions are then the ~2.4 MN chain pretension. The `MD_Shared` `SeaState.dat` computes the wave kinematics on a grid that covers only the platform (`X_HalfWidth = Y_HalfWidth = 100 m`, `Z_Depth = 40 m`), while the anchors lie 838 m away on the 200 m seabed. SeaState gives every line node outside the grid the kinematics of the -grid boundary, and CableDyn warns about it. Enlarge the grid: +grid boundary, and CableDyn stops at initialisation (`OPTIONS waveGridCheck warn` runs on with +a warning instead). Enlarge the grid: ```powershell $ss = 'SeaState.dat' @@ -63,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 @@ -70,7 +76,7 @@ Grid sizing is described in the manual's OpenFAST page (SeaState grid). .\openfast.exe IEA-15-UMaine_CompMooring3_MoorDyn.fst # MoorDyn ``` -The CableDyn run log identifies the module with `Running CableDyn (v0.4.3, 2026-11-20)` and +The CableDyn run log identifies the module with `Running CableDyn (v0.5.0, 2026-12-04)` and prints the converged fairlead state of each line, as the standalone driver does: ```text diff --git a/integration/openfast/README.md b/integration/openfast/README.md index 10adb328..2e1037ec 100644 --- a/integration/openfast/README.md +++ b/integration/openfast/README.md @@ -9,7 +9,7 @@ who only run coupled cases should use the released `openfast.exe` and the The patches in [`patches/`](patches/) apply to the public OpenFAST upstream commit `2895884d2be01862173c88d70f86b358d2f1a50a` (the OpenFAST v5.0.0 release, used by -CableDyn v0.4.3). They add only the OpenFAST host integration; the CableDyn sources come from +CableDyn v0.5.0). They add only the OpenFAST host integration; the CableDyn sources come from this repository. | File | Purpose | @@ -67,7 +67,7 @@ ifx default, `/fp:fast`, may reassociate sums and flush subnormals to zero. OpenFAST names its version with `git describe --dirty`, which would read `v5.0.0-dirty` on the patched tree. A CableDyn-enabled executable names itself `OpenFAST--CableDyn-` instead, here -`OpenFAST-v5.0.0-CableDyn-0.4.3` (printed by `openfast.exe -v` and at the start of every run). +`OpenFAST-v5.0.0-CableDyn-0.5.0` (printed by `openfast.exe -v` and at the start of every run). The OpenFAST part is `git describe --tags --abbrev=8` of the checked-out commit, the unpatched base; the CableDyn part is the project version in the CableDyn `CMakeLists.txt`. Patch `0021` sets it in the CMake build, and `integrate_openfast_vs_solution.ps1` in the 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..c543a31a --- /dev/null +++ b/integration/openfast/cabledyn_preflight.py @@ -0,0 +1,791 @@ +#!/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 = [] + # whether a line end lies in the water (at or below the still-water level, as outside() takes + # it): CableDyn checks the resolution only when a line node samples the water + wet_end = False + 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] + wet_end = wet_end or any(z <= 0.0 for _, _, z, _ in ends) + 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" + if not wet_end: + # CableDyn's check returns when no line node samples the water; with every line + # end above it, only a line that sags into the water between its ends does + notes.append(message + ": every line end lies above the still-water level, so CableDyn " + "stops only if a line node between its ends is in the water") + else: + (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/0009-fast-funcs.patch b/integration/openfast/patches/0009-fast-funcs.patch index 6c844044..5ee1ee23 100644 --- a/integration/openfast/patches/0009-fast-funcs.patch +++ b/integration/openfast/patches/0009-fast-funcs.patch @@ -1,5 +1,5 @@ diff --git a/modules/openfast-library/src/FAST_Funcs.f90 b/modules/openfast-library/src/FAST_Funcs.f90 -index ff46ce942..46e7a09e1 100644 +index ff46ce942..323baf77c 100644 --- a/modules/openfast-library/src/FAST_Funcs.f90 +++ b/modules/openfast-library/src/FAST_Funcs.f90 @@ -104,6 +104,13 @@ use MoorDyn, only: MD_JacobianPInput, & @@ -60,19 +60,22 @@ index ff46ce942..46e7a09e1 100644 case (Module_Orca) call FAST_CopyStates(ModData, T, STATE_CURR, STATE_PRED, MESH_UPDATECOPY, ErrStat2, ErrMsg2) if (Failed()) return -@@ -827,6 +857,11 @@ subroutine FAST_CalcOutput(ModData, Mappings, ThisTime, iInput, iState, T, ErrSt +@@ -827,6 +857,14 @@ subroutine FAST_CalcOutput(ModData, Mappings, ThisTime, iInput, iState, T, ErrSt T%MD%x(iState), T%MD%xd(iState), T%MD%z(iState), T%MD%OtherSt(iState), & T%MD%y, T%MD%m, ErrStat2, ErrMsg2) + case (Module_CD) ++ ! CableDyn evaluates its deck channels only when this step's outputs are written (or the ++ ! glue linearizes); its loads are evaluated on every call. + call CD_CalcOutput(ThisTime, T%CD%Input(iInput), T%CD%p, & + T%CD%x(iState), T%CD%xd(iState), T%CD%z(iState), T%CD%OtherSt(iState), & -+ T%CD%y, T%CD%m, ErrStat2, ErrMsg2) ++ T%CD%y, T%CD%m, ErrStat2, ErrMsg2, & ++ CalcWriteOutput=CalcWriteOutputLoc .and. (T%y_FAST%WriteThisStep .or. T%p_FAST%Linearize)) + case (Module_Orca) call Orca_CalcOutput(ThisTime, T%Orca%Input(iInput), T%Orca%p, & T%Orca%x(iState), T%Orca%xd(iState), T%Orca%z(iState), T%Orca%OtherSt(iState), & -@@ -937,6 +972,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & +@@ -937,6 +975,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & call MAP_VarsPackInput(ModData%Vars, T%MAP%Input(iInput), u_op) case (Module_MD) call MD_VarsPackInput(ModData%Vars, T%MD%Input(iInput), u_op) @@ -81,7 +84,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_ExtInfw) ! call ExtInfw_VarsPackInput(ModData%Vars, T%ExtInfw%Input(iIndex), u_op) case (Module_Orca) -@@ -994,6 +1031,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & +@@ -994,6 +1034,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & call MAP_VarsPackOutput(ModData%Vars, T%MAP%y, y_op) case (Module_MD) call MD_VarsPackOutput(ModData%Vars, T%MD%y, y_op) @@ -90,7 +93,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_ExtInfw) call ExtInfw_VarsPackOutput(ModData%Vars, T%ExtInfw%y, y_op) case (Module_Orca) -@@ -1050,6 +1089,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & +@@ -1050,6 +1092,8 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & call MAP_VarsPackContState(ModData%Vars, T%MAP%x(iState), x_op) case (Module_MD) call MD_VarsPackContState(ModData%Vars, T%MD%x(iState), x_op) @@ -99,7 +102,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_ExtInfw) ! call ExtInfw_VarsPackContState(ModData%Vars, T%ExtInfw%x(StateIndex), x_op) case (Module_Orca) -@@ -1181,6 +1222,13 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & +@@ -1181,6 +1225,13 @@ subroutine FAST_GetOP(ModData, ThisTime, iInput, iState, T, ErrStat, ErrMsg, & if (Failed()) return call MD_VarsPackContStateDeriv(ModData%Vars, T%MD%m%dxdt_lin, dx_op) @@ -113,7 +116,7 @@ index ff46ce942..46e7a09e1 100644 ! case (Module_ExtInfw) ! call ExtInfw_VarsPackContStateDeriv(ModData%Vars, T%ExtInfw%x(StateIndex), dx_op) -@@ -1274,6 +1322,8 @@ subroutine FAST_SetOP(ModData, iInput, iState, T, ErrStat, ErrMsg, & +@@ -1274,6 +1325,8 @@ subroutine FAST_SetOP(ModData, iInput, iState, T, ErrStat, ErrMsg, & call MAP_VarsUnpackInput(ModData%Vars, u_op, T%MAP%Input(iInput)) case (Module_MD) call MD_VarsUnpackInput(ModData%Vars, u_op, T%MD%Input(iInput)) @@ -122,7 +125,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_ExtInfw) ! call ExtInfw_VarsUnpackInput(ModData%Vu_op, ars, T%ExtInfw%Input(InputIndex)) case (Module_Orca) -@@ -1325,6 +1375,8 @@ subroutine FAST_SetOP(ModData, iInput, iState, T, ErrStat, ErrMsg, & +@@ -1325,6 +1378,8 @@ subroutine FAST_SetOP(ModData, iInput, iState, T, ErrStat, ErrMsg, & call MAP_VarsUnpackContState(ModData%Vars, x_op, T%MAP%x(iState)) case (Module_MD) call MD_VarsUnpackContState(ModData%Vars, x_op, T%MD%x(iState)) @@ -131,7 +134,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_ExtInfw) ! call ExtInfw_VarsUnpackContState(ModData%Vars, x_op, T%ExtInfw%x(StateIndex)) case (Module_Orca) -@@ -1426,6 +1478,11 @@ subroutine FAST_JacobianPInput(ModData, ThisTime, iInput, iState, T, ErrStat, Er +@@ -1426,6 +1481,11 @@ subroutine FAST_JacobianPInput(ModData, ThisTime, iInput, iState, T, ErrStat, Er T%MD%z(iState), T%MD%OtherSt(iState), T%MD%y, T%MD%m, ErrStat2, ErrMsg2, & dYdu=dYdu, dXdu=dXdu) @@ -143,7 +146,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_SD) call SD_JacobianPInput(ModData%Vars, ThisTime, T%SD%Input(iInput), T%SD%p, T%SD%x(iState), T%SD%xd(iState), & T%SD%z(iState), T%SD%OtherSt(iState), T%SD%y, T%SD%m, ErrStat2, ErrMsg2, & -@@ -1545,6 +1602,13 @@ subroutine FAST_JacobianPContState(ModData, ThisTime, iInput, iState, T, ErrStat +@@ -1545,6 +1605,13 @@ subroutine FAST_JacobianPContState(ModData, ThisTime, iInput, iState, T, ErrStat T%MD%y, T%MD%m, ErrStat2, ErrMsg2, & dYdx=dYdx, dXdx=dXdx) @@ -157,7 +160,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_SD) call SD_JacobianPContState(ModData%Vars, ThisTime, T%SD%Input(iInput), T%SD%p, & T%SD%x(iState), T%SD%xd(iState), & -@@ -1715,6 +1779,13 @@ subroutine FAST_CopyStates(ModData, T, iSrc, iDst, CtrlCode, ErrStat, ErrMsg) +@@ -1715,6 +1782,13 @@ subroutine FAST_CopyStates(ModData, T, iSrc, iDst, CtrlCode, ErrStat, ErrMsg) call MD_CopyConstrState(T%MD%z(iSrc), T%MD%z(iDst), CtrlCode, ErrStat2, ErrMsg2); if (Failed()) return call MD_CopyOtherState(T%MD%OtherSt(iSrc), T%MD%OtherSt(iDst), CtrlCode, ErrStat2, ErrMsg2); if (Failed()) return @@ -171,7 +174,7 @@ index ff46ce942..46e7a09e1 100644 case (Module_Orca) call Orca_CopyContState(T%Orca%x(iSrc), T%Orca%x(iDst), CtrlCode, ErrStat2, ErrMsg2); if (Failed()) return -@@ -1842,6 +1913,9 @@ subroutine FAST_CopyInput(ModData, T, iSrc, iDst, CtrlCode, ErrStat, ErrMsg) +@@ -1842,6 +1916,9 @@ subroutine FAST_CopyInput(ModData, T, iSrc, iDst, CtrlCode, ErrStat, ErrMsg) case (Module_MD) call MD_CopyInput(T%MD%Input(iSrc), T%MD%Input(iDst), CtrlCode, ErrStat2, ErrMsg2) @@ -181,7 +184,7 @@ index ff46ce942..46e7a09e1 100644 ! case (Module_ExtInfw) case (Module_Orca) -@@ -2004,6 +2078,10 @@ subroutine FAST_ModEnd(Mods, T, ErrStat, ErrMsg) +@@ -2004,6 +2081,10 @@ subroutine FAST_ModEnd(Mods, T, ErrStat, ErrMsg) call MD_End(T%MD%Input(1), T%MD%p, T%MD%x(STATE_CURR), T%MD%xd(STATE_CURR), T%MD%z(STATE_CURR), & T%MD%OtherSt(STATE_CURR), T%MD%y, T%MD%m, ErrStat2, ErrMsg2) @@ -192,4 +195,3 @@ index ff46ce942..46e7a09e1 100644 case (Module_Orca) call Orca_End(T%Orca%Input(1), T%Orca%p, T%Orca%x(STATE_CURR), T%Orca%xd(STATE_CURR), & T%Orca%z(STATE_CURR), T%Orca%OtherSt(STATE_CURR), T%Orca%y, T%Orca%m, ErrStat2, ErrMsg2) - 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/pyproject.toml b/pyproject.toml index 2c5f381c..9b7147e1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,7 +12,7 @@ build-backend = "scikit_build_core.build" [project] name = "cabledyn" -version = "0.4.3" +version = "0.5.0" description = "Python tools for CableDyn, a geometrically exact finite-element solver for mooring lines and dynamic power cables" readme = "python/README.md" requires-python = ">=3.10" diff --git a/python/README.md b/python/README.md index 762e218c..3d6b3a86 100644 --- a/python/README.md +++ b/python/README.md @@ -25,7 +25,7 @@ Fortran compiler and LAPACK. The pure Python wheel attached to each [GitHub release](https://github.com/SMI-Lab-Inha/CableDyn/releases/latest) -(`cabledyn-0.4.3-py3-none-any.whl`) carries no solver. `CableDynDriver` finds the +(`cabledyn-0.5.0-py3-none-any.whl`) carries no solver. `CableDynDriver` finds the driver from an explicit path, then the `CABLEDYN_DRIVER` environment variable, then the driver inside the package, then `PATH`; the in-process `CableDyn` class uses the library inside the package, or one named by `CABLEDYN_LIBRARY` or found in diff --git a/python/cabledyn/__init__.py b/python/cabledyn/__init__.py index 63070260..e46a51e6 100644 --- a/python/cabledyn/__init__.py +++ b/python/cabledyn/__init__.py @@ -300,7 +300,7 @@ "viv_response", ] -__version__ = "0.4.3" +__version__ = "0.5.0" def __getattr__(name: str) -> Any: diff --git a/python/cabledyn/deck_file.py b/python/cabledyn/deck_file.py index 14be1592..529917da 100644 --- a/python/cabledyn/deck_file.py +++ b/python/cabledyn/deck_file.py @@ -262,6 +262,10 @@ "cd_out_dt": "cd_out_dt", "vivphaseseed": "viv_phase_seed", "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", @@ -416,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"} @@ -431,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 @@ -1414,6 +1421,14 @@ 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": return ( None @@ -1516,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 @@ -4095,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) @@ -4211,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} ) @@ -6122,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( @@ -7329,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/pyproject.toml b/python/pyproject.toml index cb544a53..3d29e096 100644 --- a/python/pyproject.toml +++ b/python/pyproject.toml @@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta" [project] name = "cabledyn" -version = "0.4.3" +version = "0.5.0" description = "Python tools for CableDyn, a geometrically exact finite-element solver for mooring lines and dynamic power cables" readme = "README.md" requires-python = ">=3.10" diff --git a/python/tests/test_deck_file.py b/python/tests/test_deck_file.py index 10493675..cd9f6295 100644 --- a/python/tests/test_deck_file.py +++ b/python/tests/test_deck_file.py @@ -674,6 +674,10 @@ def test_unknown_scalar_option_keyword_fails_closed(tmp_path): ("relaxed", "cable_statics", "continuation or sequenced"), ("random", "VIVphaseSeed", "spread or zero"), ("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"), @@ -762,6 +766,10 @@ def test_zero_e_exponent_waterkin_mode_is_accepted(tmp_path): "sequenced cableStatics", "spread VIVphaseSeed", "ZERO viv_phase_seed", + "warn waveGridCheck", + "ERROR wave_grid_check", + "0 waveKinTol", + "1e-6 wave_kin_tol", "equilibrium OutputRecovery", "element output_recovery", "segment axialDampingRatio", @@ -3206,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 a9fa02d1..637d09a5 100644 --- a/release/build_static_windows.ps1 +++ b/release/build_static_windows.ps1 @@ -419,6 +419,19 @@ try { Copy-Item -LiteralPath (Join-Path $CableDynRoot 'examples\openfast\IEA-15-UMaine_CompMooring5_CableDyn.fst') ` -Destination $fst Copy-Item -LiteralPath (Join-Path $CableDynRoot 'examples\openfast\CableDyn_UMaine.dat') -Destination $smokeDir + # The MD_Shared SeaState grid covers the platform only, so the wave-grid check would stop the + # run at initialisation. This 1 s smoke case checks the executable, not the line loads: it keeps + # the light grid and turns the check into its warning (OPTIONS waveGridCheck warn), which the + # log must then show. + $smokeDeck = Join-Path $smokeDir 'CableDyn_UMaine.dat' + $deckLines = Get-Content -LiteralPath $smokeDeck + $dtmHits = @($deckLines | Where-Object { $_ -match '^\s*\S+\s+dtM\b' }).Count + if ($dtmHits -ne 1) { throw "expected one dtM row in the smoke deck CableDyn_UMaine.dat; found $dtmHits" } + $deckLines = foreach ($line in $deckLines) { + $line + if ($line -match '^\s*\S+\s+dtM\b') { 'warn waveGridCheck - smoke case on the platform-only MD_Shared grid' } + } + $deckLines | Set-Content -LiteralPath $smokeDeck -Encoding ascii $fstLines = Get-Content -LiteralPath $fst $replaced = 0 $fstLines = foreach ($line in $fstLines) { @@ -437,6 +450,11 @@ try { $runLog = $run.Text Write-Host $runLog if ($run.ExitCode -ne 0) { throw "openfast.exe smoke case failed`n$runLog" } + # 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') { throw "openfast.exe did not prove CableDyn identity and normal termination`n$runLog" } @@ -445,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/release/check_release_metadata.py b/release/check_release_metadata.py index ed3b8ebe..98f033d6 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -26,8 +26,8 @@ def capture(relative_path: str, pattern: str, label: str) -> str: return match.group(1) -# Spellings that name a CableDyn release: "CableDyn 0.4.3", "CableDyn v0.4.3", "v0.4.3", -# "cabledyn-0.4.3-py3-none-any.whl", ".../releases/tag/v0.4.3" and "libcabledyn.so.0.4.3". +# Spellings that name a CableDyn release: "CableDyn 0.5.0", "CableDyn v0.5.0", "v0.5.0", +# "cabledyn-0.5.0-py3-none-any.whl", ".../releases/tag/v0.5.0" and "libcabledyn.so.0.5.0". VERSION_REFERENCE = re.compile( r"(?i)(?:cabledyn[ _-]+v?|cabledyn-|releases/tag/v|libcabledyn\.(?:so\.)?|(? Minor extension level of ABI 1: 1 adds the in-process object queries, 2 the host-coupling !> calls (initialization at host positions, state save/restore, the coupled layout query), 3 !> the host rotations (initialization for a host that turns its coupled points, their @@ -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_CAPI.h b/src/CableDyn_CAPI.h index fd60e974..928c255a 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -44,8 +44,8 @@ #define CD_C_NOT_INITIALIZED 5 #define CABLEDYN_CAPI_VERSION_MAJOR 0 -#define CABLEDYN_CAPI_VERSION_MINOR 4 -#define CABLEDYN_CAPI_VERSION_PATCH 3 +#define CABLEDYN_CAPI_VERSION_MINOR 5 +#define CABLEDYN_CAPI_VERSION_PATCH 0 #define CABLEDYN_CAPI_ABI_VERSION 1 #ifdef __cplusplus diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 7e54eab4..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. @@ -831,6 +838,9 @@ MODULE CableDyn_DeckDriver ! OpenFAST supercycling (dtM > DT): extrapolate the coupled loads between dtM solves from the ! last two (CableDyn_LoadPredictor); FALSE holds the last solve's loads LOGICAL :: predict_loads = .TRUE. + ! OPTION waveGridCheck: TRUE (warn) downgrades the coupled wave-grid guard of the OpenFAST shell + ! from a fatal error (error, the default) to a warning + LOGICAL :: wave_grid_warn = .FALSE. ! OPTION CDOutDt [s]: the interval of the coupled .CD.out rows, a whole multiple of the ! CableDyn step; 0 (the default) writes a row after every committed step REAL(wp) :: cd_out_dt = CD_ZERO @@ -1313,9 +1323,14 @@ 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. + ! Deck OPTION waveGridCheck (the OpenFAST shell; see CD_AGG_ModuleType%wave_grid_warn) + LOGICAL :: wave_grid_warn = .FALSE. ! Deck OPTION CDOutDt (the OpenFAST shell; see CD_AGG_ModuleType%cd_out_dt) REAL(wp) :: cd_out_dt = CD_ZERO ! OPTION maxStrain, for the per-step plausibility guard of the coupled EI=0 lines. @@ -8120,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 @@ -8208,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. @@ -8254,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(:) @@ -8390,6 +8409,8 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi agg%n_turbines = nturb 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 @@ -8449,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 @@ -8497,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 @@ -8836,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 @@ -9674,8 +9702,11 @@ 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. agg%cd_out_dt = CD_ZERO agg%max_strain = 0.5_wp IF (ALLOCATED(agg%host_current_profile_z)) DEALLOCATE (agg%host_current_profile_z) @@ -10011,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(:) @@ -10054,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 @@ -11093,7 +11183,7 @@ END SUBROUTINE init_one_model RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts, model, ErrStat, ErrMsg, & bathymetry) - !! Build one Syrope line model: a line of one or more Syrope sections, alone (taut at init) or + !! Build one Syrope line model: a line of one or more Syrope sections, alone or !! between plain EI = 0 sections (a chain-polyester-chain mooring), with the seabed, !! hydrodynamics and fluid fields of any EI = 0 line (init_one_model builds it). Builds each !! Syrope section's working-curve constitutive from the parse-resolved OWC data and solves the @@ -11111,7 +11201,8 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts !! from the mean off the curve, and their slow strains settled the line after the start: a !! 991 m single-section rope at rest moved its fairlead tension by 3.4e-4 in 1 s). A !! single-section line starts the iteration from the secant at the strain its taut geometry - !! fixes, a composite line from the curve's alpha. The tension, which the chains' weight and + !! fixes, a composite line, or a chord strain without tension on the rest curve (a line its + !! weight sags taut), from the curve's alpha. The tension, which the chains' weight and !! the geometry largely fix, keeps this update a contraction where a strain update can !! overshoot. TYPE(DeckLineType), INTENT(IN) :: types(:) @@ -11126,6 +11217,8 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts TYPE(CD_BathymetryType), INTENT(IN), OPTIONAL :: bathymetry INTEGER, PARAMETER :: MAX_ITER_COMPOSITE = 50 + ! the line-wide step replaces the element steps from this iteration on, over this many stored solves + INTEGER, PARAMETER :: ITER_LINE_STEP = 30, N_STORED = 6 ! per section in deck order (End A first): its line type, element count and, for a Syrope ! section, its constitutive data; per element (internal order, anchor first): its section, ! whether it is a Syrope element and its static secant EA @@ -11133,10 +11226,10 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts INTEGER, ALLOCATABLE :: sec_type(:), sec_nseg(:), el_sec(:) LOGICAL, ALLOCATABLE :: sec_syr(:), sis(:) REAL(wp), ALLOCATABLE :: sec_el(:), cand_el(:), sslow(:), stmax(:), t_static(:), eps_prev(:), t_prev(:), & - step_prev(:) + step_prev(:), map_el(:), x_hist(:, :), g_hist(:, :), x_line(:) REAL(wp) :: anchor(3), fairlead(3), eps0, t_ref, total_l0, t_hist, t_mean_static REAL(wp) :: eps_e, change, secant, eps_now, d_eps, d_t, eps_r, t_r, acc - LOGICAL :: have_acc + LOGICAL :: have_acc, have_line INTEGER :: ne, e, es, n_owc, iter, nsec, j, k, isec, st LOGICAL :: composite, converged CHARACTER(1024) :: em @@ -11209,12 +11302,14 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts t_hist = CD_ZERO IF (ln%has_syrope_ic) t_hist = ln%syrope_tmax0 ALLOCATE (sec_el(ne), cand_el(ne), stype(ne), sis(ne), sslow(ne), stmax(ne), t_static(ne), eps_prev(ne), & - t_prev(ne), step_prev(ne)) + t_prev(ne), step_prev(ne), map_el(ne), x_hist(ne, N_STORED), g_hist(ne, N_STORED), x_line(ne)) sis = .FALSE. sslow = CD_ZERO stmax = CD_ZERO step_prev = CD_ZERO sec_el = CD_ZERO + x_hist = CD_ZERO + g_hist = CD_ZERO DO e = 1, ne IF (.NOT. sec_syr(el_sec(e))) CYCLE sis(e) = .TRUE. @@ -11226,10 +11321,9 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts ! OWC secant EA that makes the static solve land at that strain total_l0 = SUM(l0) eps0 = NORM2(fairlead - anchor)/total_l0 - CD_ONE - IF (.NOT. (eps0 > CD_ZERO)) THEN - CALL release_syrope(.TRUE.) - CALL fail(ErrStat, ErrMsg, 'a Syrope line must be taut at init (stretched length > unstretched)'); RETURN - END IF + END IF + ! (a chord shorter than the line starts from the curve's alpha below, as a composite line) + IF (.NOT. composite .AND. eps0 > CD_ZERO) THEN ! the OWC table must cover the initial strain: the interpolation would clamp at ! the end rows and the line would start silently mis-tensioned IF (.NOT. strain_in_table(1, eps0)) THEN @@ -11241,16 +11335,12 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts CALL release_syrope(.TRUE.) CALL fail(ErrStat, ErrMsg, 'SYROPE IC working curve: '//TRIM(em)); RETURN END IF - IF (.NOT. (t_ref > CD_ZERO)) THEN - WRITE (s_eps, '(ES10.3)') eps0 - CALL release_syrope(.TRUE.) - CALL fail(ErrStat, ErrMsg, 'the Syrope line is slack on its SYROPE IC working curve: the initial '// & - 'strain '//TRIM(ADJUSTL(s_eps))//' is below the zero-tension strain of the Tmax0 curve; '// & - 'lower Tmax0 or shorten the line'); RETURN - END IF secant = t_ref/eps0 sec_el = secant - ELSE + END IF + ! A chord strain below the rest curve's zero-tension strain is not a slack line: the sag of its + ! weight stretches it further. The start is then a composite line's. + IF (.NOT. (secant > CD_ZERO)) THEN ! a first solve with each Syrope element at its placeholder stiffness (the working curve's ! alpha); the tension update below takes it to the curve DO e = 1, ne @@ -11278,6 +11368,7 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts ! each Syrope element: the curve's strain at its tension change = CD_ZERO cand_el = sec_el + map_el = sec_el DO e = 1, ne IF (.NOT. sis(e)) CYCLE isec = el_sec(e) @@ -11305,6 +11396,7 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts ELSE cand_el(e) = t_static(e)/eps_e END IF + map_el(e) = cand_el(e) ! the residual: how far the element's (strain, tension) sits off its curve change = MAX(change, ABS(cand_el(e) - sec_el(e))/sec_el(e)) ! The tension update contracts by 1 - (secant / tangent) of the curve, slowly where the @@ -11356,6 +11448,25 @@ RECURSIVE SUBROUTINE init_one_syrope_model(types, ln, sections, points, l0, opts converged = .TRUE. EXIT END IF + ! The element steps are slow where the secant is far below the tangent along the whole + ! line (a low rest tension on a working curve of a high Tmax0): the elements share the + ! line's strain, which no element step sees. From ITER_LINE_STEP on, the next secants + ! are the combination of the stored solves (secants in, tension update out) that + ! minimises the relative residual (Anderson acceleration); else the element steps stand. + DO k = N_STORED, 2, -1 + x_hist(:, k) = x_hist(:, k - 1) + g_hist(:, k) = g_hist(:, k - 1) + END DO + x_hist(:, 1) = sec_el + g_hist(:, 1) = map_el + have_line = .FALSE. + IF (iter >= ITER_LINE_STEP) CALL line_step(MIN(iter, N_STORED), x_line, have_line) + IF (have_line) THEN + DO e = 1, ne + IF (sis(e)) step_prev(e) = x_line(e) - sec_el(e) + END DO + cand_el = x_line + END IF sec_el = cand_el END BLOCK END DO @@ -11533,6 +11644,68 @@ SUBROUTINE response_root(isec_, eps_k, t_k, d_eps_, d_t_, eps_out, t_out) IF (es_c /= CD_SYROPE_OK) eps_out = -CD_ONE END SUBROUTINE response_root + SUBROUTINE line_step(n_hist, x_new, ok) + !! The secants that minimise the relative residual of the tension update over the affine + !! combinations of the newest n_hist solves (x_hist, g_hist, newest first): least squares by + !! modified Gram-Schmidt on the residual differences, a difference dependent on the earlier + !! ones left out. ok = .FALSE. where no difference is left or a secant would fall outside + !! half to twice the newest one. + INTEGER, INTENT(IN) :: n_hist + REAL(wp), INTENT(OUT) :: x_new(:) + LOGICAL, INTENT(OUT) :: ok + REAL(wp) :: f_new(SIZE(x_new)), q(SIZE(x_new), N_STORED), dg(SIZE(x_new), N_STORED) + REAL(wp) :: r(N_STORED, N_STORED), rhs(N_STORED), coef(N_STORED), w, nrm0, nrm + INTEGER :: i, j, m_, el + ok = .FALSE. + x_new = x_hist(:, 1) + f_new = CD_ZERO + DO el = 1, SIZE(x_new) + IF (sis(el)) f_new(el) = (g_hist(el, 1) - x_hist(el, 1))/x_hist(el, 1) + END DO + m_ = 0 + r = CD_ZERO + DO j = 2, n_hist + m_ = m_ + 1 + q(:, m_) = CD_ZERO + dg(:, m_) = CD_ZERO + DO el = 1, SIZE(x_new) + IF (.NOT. sis(el)) CYCLE + w = (g_hist(el, j) - x_hist(el, j))/x_hist(el, 1) + q(el, m_) = f_new(el) - w + dg(el, m_) = g_hist(el, 1) - g_hist(el, j) + END DO + nrm0 = NORM2(q(:, m_)) + DO i = 1, m_ - 1 + r(i, m_) = DOT_PRODUCT(q(:, i), q(:, m_)) + q(:, m_) = q(:, m_) - r(i, m_)*q(:, i) + END DO + nrm = NORM2(q(:, m_)) + IF (.NOT. (nrm > 1.0e-6_wp*nrm0)) THEN + m_ = m_ - 1 + CYCLE + END IF + r(m_, m_) = nrm + q(:, m_) = q(:, m_)/nrm + END DO + IF (m_ < 1) RETURN + DO i = 1, m_ + rhs(i) = DOT_PRODUCT(q(:, i), f_new) + END DO + DO i = m_, 1, -1 + coef(i) = rhs(i) + DO j = i + 1, m_ + coef(i) = coef(i) - r(i, j)*coef(j) + END DO + coef(i) = coef(i)/r(i, i) + END DO + DO el = 1, SIZE(x_new) + IF (.NOT. sis(el)) CYCLE + x_new(el) = g_hist(el, 1) - DOT_PRODUCT(coef(1:m_), dg(el, 1:m_)) + IF (.NOT. (x_new(el) >= 0.5_wp*x_hist(el, 1) .AND. x_new(el) <= 2.0_wp*x_hist(el, 1))) RETURN + END DO + ok = .TRUE. + END SUBROUTINE line_step + LOGICAL FUNCTION strain_in_table(isec_, eps) RESULT(ok) !! Whether strain eps lies in section isec_'s OWC table (the interpolation clamps at its end !! rows, so a strain outside would start the line silently mis-tensioned); fails otherwise. @@ -19037,8 +19210,26 @@ 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') + SELECT CASE (TRIM(to_lower(val))) + CASE ('error') + opts%wave_grid_warn = .FALSE. + CASE ('warn') + opts%wave_grid_warn = .TRUE. + CASE DEFAULT + CALL fail(ErrStat, ErrMsg, 'OPTION waveGridCheck "'//TRIM(val)//'" must be error or warn') + END SELECT CASE ('tensile_safety', 'tensilesafety') CALL rd_tensile_mode(val, opts%tensile_mode, ErrStat, ErrMsg) CASE ('tensile_strain_tolerance', 'tensilestraintolerance') @@ -19239,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_HermiteCableDynamic.f90 b/src/CableDyn_HermiteCableDynamic.f90 index 50c8a607..103ba248 100644 --- a/src/CableDyn_HermiteCableDynamic.f90 +++ b/src/CableDyn_HermiteCableDynamic.f90 @@ -195,6 +195,9 @@ MODULE CableDyn_HermiteCableDynamic INTEGER, PARAMETER :: KL_D = 11, KU_D = 11 ! Half-bandwidth of the nodal-twist tangent in 7-DOF-per-node order ([r, m, phi] per node). INTEGER, PARAMETER :: KB7 = 13 + ! Inputs of the twist_reference memo per element (tw_mk): 12 DOFs, 2 unit tangents, tw_beta, + ! l0 and the coupling. + INTEGER, PARAMETER :: TW_MEMO_KEY = 21 INTEGER, PARAMETER :: LDAB_D = 2*KL_D + KU_D + 1 ! First row of the stored band. Rows 1..KL_D are the factorization's fill-in space: every ! band array is allocated with them zero and only an LU factor (ws_Keffb) ever writes them, @@ -652,6 +655,16 @@ MODULE CableDyn_HermiteCableDynamic ! and whose unit node tangents are the reference's, bit for bit, keeps its reference twist. REAL(wp), ALLOCATABLE :: tw_sq(:), tw_rq(:) LOGICAL :: tw_rq_ok = .FALSE. + ! A memo of twist_reference without the Hessian at an element away from a rigid end, for + ! assemble_twist: tw_mk(:, e) the inputs it reads there (the element's 12 DOFs, the reference + ! unit tangents of its two nodes, tw_beta, l0, the coupling), tw_mqo(e) the quadrature order, + ! tw_mv(:, e) the results (rho, beta, g). An assembly takes the results only when every input + ! is bitwise the memo's (tw_mo), so it can never be stale. A host's frame-only transfer + ! (CD_HermiteCable_Dyn_Set_Torsion_Frames, every OpenFAST output call) assembles every element + ! at the committed shape; all but the elements at the moved end nodes then hit. + REAL(wp), ALLOCATABLE :: tw_mk(:, :), tw_mv(:, :) + INTEGER, ALLOCATABLE :: tw_mqo(:) + LOGICAL, ALLOCATABLE :: tw_mo(:) ! tw_som(:, k): the angular velocity of end frame k over the running step, log(R_{n+1} ! R_n^T)/dt (R = [d n d x n]); tw_om: that of the committed step. A turning frame twists ! the element at a rigid end through rho, and the torsional damping takes that rate. @@ -11115,7 +11128,8 @@ SUBROUTINE twist_reference(model, e, q_cfg, ends, want_hess, rho, beta, g, h, Er cpl = CD_ZERO IF (ALLOCATED(model%torsion%couple)) cpl = model%torsion%couple(e) IF (ABS(cpl) > CD_ZERO) THEN - CALL CD_HermiteTorsion_Stretch_Derivatives(qe, model%l0(e), ls, gs, hs, model%torsion%quadrature_order) + CALL CD_HermiteTorsion_Stretch_Derivatives(qe, model%l0(e), ls, gs, hs, model%torsion%quadrature_order, & + want_hess=want_hess) rho = rho + cpl*(ls - model%l0(e)) g = g + cpl*gs IF (want_hess) h = h + cpl*hs @@ -11252,7 +11266,8 @@ SUBROUTINE assemble_twist(model, q_cfg, v_cfg, want_residual, want_tangent, R, K ! length-rate share of the damping (active line control): l0_dot/l0, the element's tangent ! handles (m in the 12-DOF layout, the r slots zero) and the angle stiffness it leaves REAL(wp) :: rr, mv(12), gmv(12), kel_t, cpl - LOGICAL :: ctrl_rate, one_node + LOGICAL :: ctrl_rate, one_node, memo + REAL(wp) :: key(TW_MEMO_KEY) INTEGER :: e, iend, node, b, i, j, es, e_lo, e_hi CHARACTER(1024) :: em @@ -11288,8 +11303,31 @@ SUBROUTINE assemble_twist(model, q_cfg, v_cfg, want_residual, want_tangent, R, K ! an element at a rigid end twists through rho as its end frame turns: its damping rate ! takes d rho/dw . omega of the frames (the tangent keeps the rate's q-dependence through ! g only, as the frame's share of it is of order omega dt) + memo = .NOT. want_tangent .AND. ALLOCATED(model%tw_mo) .AND. & + .NOT. ((e == 1 .AND. model%tw_rigid(1)) .OR. (e == model%ne .AND. model%tw_rigid(2))) IF (turning .AND. kd > CD_ZERO .AND. (e == 1 .OR. e == model%ne)) THEN CALL twist_reference(model, e, q_cfg, ends, want_tangent, rho, beta, g, h, es, em, end_w=ew) + ELSE IF (memo) THEN + ! (twist_reference reads, away from a rigid end, exactly the inputs of the key) + CALL tw_memo_inputs(model, e, q_cfg, key) + IF (model%tw_mo(e) .AND. model%tw_mqo(e) == model%torsion%quadrature_order .AND. & + ALL(bits_equal(key, model%tw_mk(:, e)))) THEN + rho = model%tw_mv(1, e) + beta = model%tw_mv(2, e) + g = model%tw_mv(3:14, e) + es = CD_HCDYN_OK + ELSE + CALL twist_reference(model, e, q_cfg, ends, .FALSE., rho, beta, g, h, es, em) + model%tw_mo(e) = es == CD_HCDYN_OK + IF (model%tw_mo(e)) THEN + model%tw_mk(:, e) = key + model%tw_mqo(e) = model%torsion%quadrature_order + model%tw_mv(1, e) = rho + model%tw_mv(2, e) = beta + model%tw_mv(3:14, e) = g + END IF + END IF + ew = CD_ZERO ELSE CALL twist_reference(model, e, q_cfg, ends, want_tangent, rho, beta, g, h, es, em) ew = CD_ZERO @@ -11573,8 +11611,10 @@ SUBROUTINE tw_init(model, mt, ErrStat, ErrMsg) ALLOCATE (model%tw_eg(12, ne), model%tw_ehv(12, ne), model%tw_ek(ne), model%tw_ed(ne), model%tw_me(ne)) ALLOCATE (model%tw_K7(3*KB7 + 1, 7*nn), model%tw_x7(7*nn), model%tw_ipiv(7*nn)) ALLOCATE (model%tw_su(3, nn), model%tw_stn(3, nn), model%tw_sbeta(ne), model%tw_sq(6*nn), model%tw_rq(6*nn)) + ALLOCATE (model%tw_mk(TW_MEMO_KEY, ne), model%tw_mv(14, ne), model%tw_mqo(ne), model%tw_mo(ne)) ALLOCATE (model%ws_recovery_tw(tw_pack_size(model))) END IF + model%tw_mo = .FALSE. model%tw_pn = CD_ZERO; model%tw_wn = CD_ZERO; model%tw_an = CD_ZERO; model%tw_pk = CD_ZERO model%tw_wk = CD_ZERO; model%tw_ak = CD_ZERO; model%tw_ptrial = CD_ZERO; model%tw_dp = CD_ZERO model%tw_G = CD_ZERO; model%tw_Gt = CD_ZERO; model%tw_Rk = CD_ZERO; model%tw_Rt = CD_ZERO @@ -11730,12 +11770,30 @@ SUBROUTINE tw_release(model) IF (ALLOCATED(model%tw_K7)) DEALLOCATE (model%tw_K7, model%tw_x7, model%tw_ipiv) IF (ALLOCATED(model%tw_su)) DEALLOCATE (model%tw_su, model%tw_stn, model%tw_sbeta) IF (ALLOCATED(model%tw_sq)) DEALLOCATE (model%tw_sq, model%tw_rq) + IF (ALLOCATED(model%tw_mk)) DEALLOCATE (model%tw_mk, model%tw_mv, model%tw_mqo, model%tw_mo) model%tw_rq_ok = .FALSE. IF (ALLOCATED(model%ws_recovery_tw)) DEALLOCATE (model%ws_recovery_tw) IF (ALLOCATED(model%snap_tw)) DEALLOCATE (model%snap_tw) IF (ALLOCATED(model%snap_tw_fcR)) DEALLOCATE (model%snap_tw_fcR) END SUBROUTINE tw_release + PURE SUBROUTINE tw_memo_inputs(model, e, q_cfg, key) + !! The inputs twist_reference reads at an element e away from a rigid end (see tw_mk): the + !! element's 12 DOFs of q_cfg, the reference unit tangents of its nodes, tw_beta(e), l0(e) + !! and the coupling (zero when there is none, as twist_reference takes it). + TYPE(CD_HermiteCableDynType), INTENT(IN) :: model + INTEGER, INTENT(IN) :: e + REAL(wp), INTENT(IN) :: q_cfg(:) + REAL(wp), INTENT(OUT) :: key(TW_MEMO_KEY) + key(1:12) = q_cfg(6*e - 5:6*e + 6) + key(13:15) = model%tw_tn(:, e) + key(16:18) = model%tw_tn(:, e + 1) + key(19) = model%tw_beta(e) + key(20) = model%l0(e) + key(21) = CD_ZERO + IF (ALLOCATED(model%torsion%couple)) key(21) = model%torsion%couple(e) + END SUBROUTINE tw_memo_inputs + SUBROUTINE tw_advance_reference(model, q_new, ends_new, ErrStat, ErrMsg) !! The twist reference at q_new with the frames ends_new, into the commit scratch: the !! reference twists and end-frame references (the step's own formulas, so the committed diff --git a/src/CableDyn_HermiteTorsion.f90 b/src/CableDyn_HermiteTorsion.f90 index 8929f748..ebfbf82a 100644 --- a/src/CableDyn_HermiteTorsion.f90 +++ b/src/CableDyn_HermiteTorsion.f90 @@ -1641,15 +1641,21 @@ PURE REAL(wp) FUNCTION CD_HermiteTorsion_Element_Stretch(qe, L, quadrature_order CALL element_stretch(qe, L, order, .FALSE., ls, g, h) END FUNCTION CD_HermiteTorsion_Element_Stretch - PURE SUBROUTINE CD_HermiteTorsion_Stretch_Derivatives(qe, L, ls, grad, hess, quadrature_order) + PURE SUBROUTINE CD_HermiteTorsion_Stretch_Derivatives(qe, L, ls, grad, hess, quadrature_order, want_hess) !! CD_HermiteTorsion_Element_Stretch with its gradient and Hessian over the 12 DOFs. + !! want_hess = .FALSE. leaves the Hessian zero (the residual needs the gradient alone); ls and + !! grad are the same either way. REAL(wp), INTENT(IN) :: qe(12), L REAL(wp), INTENT(OUT) :: ls, grad(12), hess(12, 12) INTEGER, INTENT(IN), OPTIONAL :: quadrature_order + LOGICAL, INTENT(IN), OPTIONAL :: want_hess INTEGER :: order + LOGICAL :: hs order = NG_DEFAULT IF (PRESENT(quadrature_order)) order = quadrature_order - CALL element_stretch(qe, L, order, .TRUE., ls, grad, hess) + hs = .TRUE. + IF (PRESENT(want_hess)) hs = want_hess + CALL element_stretch(qe, L, order, hs, ls, grad, hess) END SUBROUTINE CD_HermiteTorsion_Stretch_Derivatives PURE SUBROUTINE element_stretch(qe, L, order, want_hess, ls, grad, hess) diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index d7384dc6..57c56f52 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -166,6 +166,11 @@ MODULE CableDyn_OpenFAST_Aggregate ! Deck OPTION predictLoads: the OpenFAST shell extrapolates the coupled loads between ! supercycled solves (TRUE) or holds the last solve's (FALSE) LOGICAL :: predict_loads = .TRUE. + ! Deck OPTION waveGridCheck: the OpenFAST shell stops (FALSE, the default) or warns (TRUE) when + ! the SeaState grid it samples the line kinematics from does not cover the nodes in the water or + ! has too few points across an oblique or short-crested sea (check_wavefield_grid, + ! check_wavefield_resolution) + LOGICAL :: wave_grid_warn = .FALSE. ! Deck OPTION CDOutDt [s]: the OpenFAST shell writes a .CD.out row at every whole multiple ! of it (a whole multiple of the CableDyn step); 0 writes one after every committed step REAL(wp) :: cd_out_dt = CD_ZERO @@ -211,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 @@ -303,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 @@ -345,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 @@ -410,14 +422,18 @@ 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 candidate%cd_out_dt = parts%cd_out_dt candidate%max_strain = parts%max_strain IF (ALLOCATED(parts%host_current_profile_z)) THEN 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_Syrope.f90 b/src/CableDyn_Syrope.f90 index 3fd1718c..bd2bf203 100644 --- a/src/CableDyn_Syrope.f90 +++ b/src/CableDyn_Syrope.f90 @@ -188,10 +188,16 @@ SUBROUTINE CD_Syrope_Init(td, owc_strain, owc_tension, wc_mod, p1, p2, alpha, be RETURN END IF DO i = 2, n - IF (td%owc_slow(i) <= td%owc_slow(i - 1)) THEN + ! Within a row the slow strain is convex in the tension, so it increases throughout where it + ! does at the row's start: the row's slope dT/deps must lie below the fast spring's stiffness + ! alpha + beta T there (a row that falls first and then rises has increasing ends, and no + ! inverse). + IF (td%owc_slow(i) <= td%owc_slow(i - 1) .OR. & + .NOT. (owc_tension(i) - owc_tension(i - 1) < (alpha + beta*owc_tension(i - 1))* & + (owc_strain(i) - owc_strain(i - 1)))) THEN CALL CD_Syrope_End(td) CALL fail(ErrStat, ErrMsg, 'the OWC slow-spring static strain must be strictly increasing '// & - '(the alpha/beta fast spring is too soft for this table)') + 'along every row (the alpha/beta fast spring is too soft for this table)') RETURN END IF END DO @@ -335,6 +341,9 @@ SUBROUTINE CD_Syrope_Working_Curve(td, t_max, wc_strain, wc_tension, wc_slow, Er END SELECT wc_slow(i) = wc_strain(i) - CD_Syrope_Fast_Strain(td, wc_tension(i)) END DO + ! the top sample is the OWC's slow strain at t_max, to the bit: the branches join at one slow + ! strain, the divider (the sampled value differs from it by rounding) + wc_slow(CD_SYROPE_NWC) = CD_Syrope_Branch_Divider(td, t_max) IF (.NOT. (CD_All_Finite(wc_tension) .AND. CD_All_Finite(wc_slow))) THEN CALL fail(ErrStat, ErrMsg, 'the working curve has non-finite samples at this T_max (degenerate '// & 'shape parameters)') @@ -379,10 +388,11 @@ SUBROUTINE CD_Syrope_Find_Strains(td, on_wc, wc_strain, wc_tension, t_mean, & !! The static strain split at a mean tension: !! total curve strain, the fast-spring share, and the slow-spring share. !! on_wc selects the working curve (t_mean below the running max) vs the - !! OWC frontier. This is MoorDyn's exact-log partition; the kernel recovers - !! T_mean by interpolating the node-sampled slow table, so seeding a state - !! from slow_strain misses the rest point by the fast spring's interpolation - !! error. CD_Syrope_Slow_At_Mean returns the exact rest-point slow strain. + !! OWC frontier. This is MoorDyn's exact-log partition. On the working curve + !! the kernel recovers T_mean by interpolating the node-sampled slow table, so + !! seeding a state from slow_strain misses the rest point there by the fast + !! spring's interpolation error. CD_Syrope_Slow_At_Mean returns the exact + !! rest-point slow strain. TYPE(CD_SyropeType), INTENT(IN) :: td LOGICAL, INTENT(IN) :: on_wc REAL(wp), INTENT(IN) :: wc_strain(CD_SYROPE_NWC), wc_tension(CD_SYROPE_NWC), t_mean @@ -398,8 +408,8 @@ END SUBROUTINE CD_Syrope_Find_Strains PURE REAL(wp) FUNCTION CD_Syrope_Slow_At_Mean(td, on_wc, wc_tension, wc_slow, t_mean) RESULT(slow) !! The slow-spring strain whose kernel recovery returns exactly t_mean: the - !! inverse of the piecewise-linear T_mean(eps_slow) interpolation on the - !! selected branch table. With it, eps = eps_curve(t_mean) and zero strain + !! inverse of the working curve's piecewise-linear T_mean(eps_slow) + !! interpolation, or of the OWC's exact recovery. With it, eps = eps_curve(t_mean) and zero strain !! rate is an exact rest point (tension t_mean, zero slow-strain rate). TYPE(CD_SyropeType), INTENT(IN) :: td LOGICAL, INTENT(IN) :: on_wc @@ -407,7 +417,7 @@ PURE REAL(wp) FUNCTION CD_Syrope_Slow_At_Mean(td, on_wc, wc_tension, wc_slow, t_ IF (on_wc) THEN slow = interp(t_mean, wc_tension, wc_slow) ELSE - slow = interp(t_mean, td%owc_tension, td%owc_slow) + slow = CD_Syrope_Slow_At_Tmax(td, t_mean) END IF END FUNCTION CD_Syrope_Slow_At_Mean @@ -490,7 +500,7 @@ SUBROUTINE CD_Syrope_Rate_And_Tension(td, on_wc, wc_strain, wc_tension, wc_slow, t_mean = interp(slow_eps, wc_slow, wc_tension) eps_static = interp(t_mean, wc_tension, wc_strain) ELSE - t_mean = interp(slow_eps, td%owc_slow, td%owc_tension) + t_mean = owc_tension_at_slow(td, slow_eps) eps_static = interp(t_mean, td%owc_tension, td%owc_strain) END IF k1 = td%alpha + td%beta*t_mean @@ -601,8 +611,8 @@ SUBROUTINE CD_Syrope_State_Advance(td, on_wc, wc_strain, wc_tension, wc_slow, sl END DO ! The safeguarded Newton step can creep along one side of the bracket when the root lies ! closer to a kink of the rate than its difference interval h, where the slope of - ! T_mean(eps_slow) changes (the top sample of the working curve, beyond which its - ! interpolation clamps at T_max, as when a rope rests on its OWC at its running maximum): + ! T_mean(eps_slow) changes (the top sample of the working curve, where the OWC takes over, + ! as when a rope rests on its OWC at its running maximum): ! the difference quotient straddles the kink, and every step lands inside the bracket and ! moves only that end. Finish then by bisection, which halves the bracket every iteration ! (R is continuous on it, so the bracket closes on its root) until the residual test is met. @@ -657,13 +667,12 @@ END SUBROUTINE CD_Syrope_State_Advance PURE REAL(wp) FUNCTION CD_Syrope_Branch_Divider(td, t_max) RESULT(divider) !! The slow strain dividing the working-curve and OWC branches at the running - !! maximum t_max: the OWC recovery's exact inverse at t_max, so the recovered - !! mean tension is continuous across the switch (the working curve clamps at - !! t_max up to the divider, the OWC returns t_max at it). It lies at or above - !! CD_Syrope_Slow_At_Tmax (the exact-log value; equal at table rows). + !! maximum t_max: the OWC's slow strain at t_max (CD_Syrope_Slow_At_Tmax), which + !! is also the top sample of the working curve's slow strains, so the recovered + !! mean tension is continuous across the switch. TYPE(CD_SyropeType), INTENT(IN) :: td REAL(wp), INTENT(IN) :: t_max - divider = interp(t_max, td%owc_tension, td%owc_slow) + divider = CD_Syrope_Slow_At_Tmax(td, t_max) END FUNCTION CD_Syrope_Branch_Divider SUBROUTINE CD_Syrope_Static_Tension(td, t_max, eps, tension, ErrStat, ErrMsg) @@ -751,9 +760,7 @@ END SUBROUTINE CD_Syrope_Slow_For_Tension PURE REAL(wp) FUNCTION CD_Syrope_Slow_At_Tmax(td, t_max) RESULT(slow_at) !! The exact-log slow-spring static strain at the running maximum tension: !! eps_owc(t_max) minus the fast-spring strain at t_max (the regenerated working - !! curve and the OWC coincide at t_max). It is not the branch divider the model - !! uses, which is CD_Syrope_Branch_Divider (the interpolated inverse, at or above - !! this value). + !! curve and the OWC coincide at t_max). TYPE(CD_SyropeType), INTENT(IN) :: td REAL(wp), INTENT(IN) :: t_max slow_at = interp(t_max, td%owc_tension, td%owc_strain) - CD_Syrope_Fast_Strain(td, t_max) @@ -918,8 +925,9 @@ PURE SUBROUTINE rate_slow_partial(td, on_wc, wc_strain, wc_tension, wc_slow, slo r_s, dtm_ds) !! Partial derivatives, at fixed (eps, deps), of the slow-strain rate !! r = (K1*(eps - eps_static(T_mean)) + c2*deps)/(c1 + c2) and of T_mean with - !! respect to the slow strain, on the same piecewise-linear segments the - !! kernel interpolates (zero slope where the interpolation clamps). + !! respect to the slow strain, of the kernel's own recovery: the piecewise-linear + !! segments of the working curve or the OWC's exact inverse (zero slope where + !! the recovery clamps). TYPE(CD_SyropeType), INTENT(IN) :: td LOGICAL, INTENT(IN) :: on_wc REAL(wp), INTENT(IN) :: wc_strain(CD_SYROPE_NWC), wc_tension(CD_SYROPE_NWC), wc_slow(CD_SYROPE_NWC) @@ -931,13 +939,64 @@ PURE SUBROUTINE rate_slow_partial(td, on_wc, wc_strain, wc_tension, wc_slow, slo de_dtm = interp_slope(t_mean, wc_tension, wc_strain) eps_static = interp(t_mean, wc_tension, wc_strain) ELSE - dtm_ds = interp_slope(slow_eps, td%owc_slow, td%owc_tension) + dtm_ds = owc_tension_slope(td, slow_eps, t_mean) de_dtm = interp_slope(t_mean, td%owc_tension, td%owc_strain) eps_static = interp(t_mean, td%owc_tension, td%owc_strain) END IF r_s = (td%beta*dtm_ds*(eps - eps_static) - (td%alpha + td%beta*t_mean)*de_dtm*dtm_ds)/(td%c1 + td%c2) END SUBROUTINE rate_slow_partial + PURE REAL(wp) FUNCTION owc_tension_at_slow(td, slow) RESULT(t_mean) + !! The OWC tension at a slow-spring strain: the exact inverse of eps_owc(T) - eps_fast(T), with + !! eps_owc linear between the table rows, constant beyond the first and last one. A straight + !! line between the rows' slow strains would reach a running maximum above its exact slow + !! strain by up to the fast spring's curvature over the row (about 1e-6): between the two, the + !! recovered tension would not change and every slow strain would be a rest point of a rope at + !! its running maximum, the rounding of a static start choosing one. The row's residual is + !! convex in T (the fast strain is concave) and its chord rises, so Newton from the row's upper + !! end falls monotonically to the root. + TYPE(CD_SyropeType), INTENT(IN) :: td + REAL(wp), INTENT(IN) :: slow + REAL(wp) :: de_dt, t, dt_ + INTEGER :: i, n, it + n = SIZE(td%owc_slow) + IF (slow <= td%owc_slow(1)) THEN + t_mean = td%owc_tension(1) + RETURN + END IF + IF (slow >= td%owc_slow(n)) THEN + t_mean = td%owc_tension(n) + RETURN + END IF + DO i = 2, n - 1 + IF (slow <= td%owc_slow(i)) EXIT + END DO + de_dt = (td%owc_strain(i) - td%owc_strain(i - 1))/(td%owc_tension(i) - td%owc_tension(i - 1)) + t = td%owc_tension(i) + DO it = 1, 60 + dt_ = (td%owc_strain(i - 1) + de_dt*(t - td%owc_tension(i - 1)) - CD_Syrope_Fast_Strain(td, t) - slow)/ & + (de_dt - CD_ONE/(td%alpha + td%beta*t)) + t = t - dt_ + IF (.NOT. (ABS(dt_) > 8.0_wp*EPSILON(CD_ONE)*ABS(t))) EXIT + END DO + t_mean = MIN(MAX(t, td%owc_tension(i - 1)), td%owc_tension(i)) + END FUNCTION owc_tension_at_slow + + PURE REAL(wp) FUNCTION owc_tension_slope(td, slow, t_mean) RESULT(dtm_ds) + !! d T_mean/d eps_slow of owc_tension_at_slow (zero on the clamped ends), t_mean its value at slow. + TYPE(CD_SyropeType), INTENT(IN) :: td + REAL(wp), INTENT(IN) :: slow, t_mean + INTEGER :: i, n + n = SIZE(td%owc_slow) + dtm_ds = CD_ZERO + IF (slow <= td%owc_slow(1) .OR. slow >= td%owc_slow(n)) RETURN + DO i = 2, n - 1 + IF (slow <= td%owc_slow(i)) EXIT + END DO + dtm_ds = CD_ONE/((td%owc_strain(i) - td%owc_strain(i - 1))/(td%owc_tension(i) - td%owc_tension(i - 1)) - & + CD_ONE/(td%alpha + td%beta*t_mean)) + END FUNCTION owc_tension_slope + PURE REAL(wp) FUNCTION interp_slope(x, xp, fp) RESULT(dydx) !! The slope of the segment interp uses at x (zero on the clamped ends). REAL(wp), INTENT(IN) :: x, xp(:), fp(:) diff --git a/src/CableDyn_WaveGrid.f90 b/src/CableDyn_WaveGrid.f90 new file mode 100644 index 00000000..106a59da --- /dev/null +++ b/src/CableDyn_WaveGrid.f90 @@ -0,0 +1,157 @@ +! File: src/CableDyn_WaveGrid.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +MODULE CableDyn_WaveGrid + !! The rules by which the coupled route judges a gridded wave field (the OpenFAST SeaState + !! grid) against the sea it carries: the wave-grid guard of the + !! OpenFAST shell (check_wavefield_grid and check_wavefield_resolution in + !! src/openfast/CableDyn_OF.f90, OPTION waveGridCheck). Pure functions of plain numbers, so + !! the rules are tested without OpenFAST (tests/test_wave_grid.f90). + !! + !! SeaState's horizontal grid has NX points on each half of [-X_HalfWidth, X_HalfWidth] (its + !! input NX; 2 NX - 1 points in all, spaced X_HalfWidth/(NX - 1)), and likewise in y. With + !! NX = 2 there are three points, at -X_HalfWidth, 0 and X_HalfWidth, and a node between two of + !! them gets an interpolation of their kinematics across a whole half-width (SeaState's + !! GridInterp takes the quadratic through the three points). That is exact only for a field + !! constant along x: a long-crested sea travelling along y. A sea whose components travel in + !! any other direction varies along x, and the interpolation across the half-width, often a + !! large part of a wavelength, is wrong in amplitude and phase. The same holds for NY = 2 + !! unless every component travels along x. + !! + !! A direction is along x when it is a multiple of 180 deg and along y when it is 90 deg plus + !! a multiple of 180 deg, each within CD_WAVEGRID_DIR_TOL. At 1e-4 deg, a direction that is + !! taken as aligned changes the phase across a half-width h by at most k h sin(1e-4 deg), less + !! than 2e-6 k h: 1e-5 rad over half a wavelength. + !! + !! Externally supplied kinematics (SeaState WaveMod 6) carry no component directions, and + !! SeaState does not use WaveDir in that mode: the grid data are the sea. A coarse axis is then + !! judged from the data themselves (CD_WaveGrid_Field_Varies): the field must be the same at + !! every grid point along that axis, within CD_WAVEGRID_FIELD_RTOL of its largest magnitude. + USE CableDyn_Precision, ONLY: wp + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: REAL32 + IMPLICIT NONE + PRIVATE + + PUBLIC :: CD_WaveGrid_Along_Axis, CD_WaveGrid_Coarse_Axes, CD_WaveGrid_Field_Varies, CD_WaveGrid_Advance + + !> the tolerance on a wave direction taken as along a grid axis (deg) + REAL(wp), PARAMETER, PUBLIC :: CD_WAVEGRID_DIR_TOL = 1.0E-4_wp + !> the tolerance, relative to the field's largest magnitude, within which supplied grid + !> kinematics count as the same along an axis (single-precision data written as text) + REAL(wp), PARAMETER, PUBLIC :: CD_WAVEGRID_FIELD_RTOL = 1.0E-5_wp + !> the largest SeaState NX or NY (points on each half of the axis) that the guard calls coarse + INTEGER, PARAMETER, PUBLIC :: CD_WAVEGRID_COARSE_HALF_NODES = 2 + +CONTAINS + + PURE LOGICAL FUNCTION CD_WaveGrid_Along_Axis(direction, axis) RESULT(along) + !! Whether a wave direction (deg, from +x toward +y, the direction of travel) is along the + !! grid axis `axis` (1: x, 2: y) within CD_WAVEGRID_DIR_TOL. Either sense counts: 0 and + !! 180 deg are along x, 90 and 270 deg along y. A non-finite direction is along neither. + REAL(wp), INTENT(IN) :: direction + INTEGER, INTENT(IN) :: axis + REAL(wp) :: d + + along = .FALSE. + IF (.NOT. (ABS(direction) <= HUGE(direction))) RETURN + d = MODULO(direction, 180.0_wp) + IF (axis == 1) THEN + along = d <= CD_WAVEGRID_DIR_TOL .OR. d >= 180.0_wp - CD_WAVEGRID_DIR_TOL + ELSE IF (axis == 2) THEN + along = ABS(d - 90.0_wp) <= CD_WAVEGRID_DIR_TOL + END IF + END FUNCTION CD_WaveGrid_Along_Axis + + PURE SUBROUTINE CD_WaveGrid_Coarse_Axes(half_nodes, directions, coarse) + !! The grid axes too coarse for the sea: coarse(1) when the grid has + !! CD_WAVEGRID_COARSE_HALF_NODES or fewer points on each half of x (SeaState NX) and a + !! component travels in a direction other than along y; coarse(2) likewise for y (NY) and + !! a direction other than along x. `directions` holds the direction (deg) of every component + !! the sea carries: one for a long-crested sea, the spread of a short-crested one. With no + !! direction (a still sea) no axis is coarse. + INTEGER, INTENT(IN) :: half_nodes(2) + REAL(wp), INTENT(IN) :: directions(:) + LOGICAL, INTENT(OUT) :: coarse(2) + INTEGER :: i + + coarse = .FALSE. + DO i = 1, SIZE(directions) + IF (half_nodes(1) <= CD_WAVEGRID_COARSE_HALF_NODES .AND. .NOT. CD_WaveGrid_Along_Axis(directions(i), 2)) & + coarse(1) = .TRUE. + IF (half_nodes(2) <= CD_WAVEGRID_COARSE_HALF_NODES .AND. .NOT. CD_WaveGrid_Along_Axis(directions(i), 1)) & + coarse(2) = .TRUE. + END DO + END SUBROUTINE CD_WaveGrid_Coarse_Axes + + PURE LOGICAL FUNCTION CD_WaveGrid_Field_Varies(f, axis, rtol) RESULT(varies) + !! Whether a gridded field f(time, x, y, z, component) -- SeaState's WaveVel or WaveAcc layout + !! -- differs along the grid axis `axis` (1: x, 2: y) by more than rtol times its largest + !! magnitude at any time, point or component. A field that is zero everywhere, or with a single + !! point along the axis, does not vary; nor does any field for an axis other than 1 or 2. A + !! non-finite value along the axis counts as varying. + REAL(REAL32), INTENT(IN) :: f(:, :, :, :, :) + INTEGER, INTENT(IN) :: axis + REAL(wp), INTENT(IN) :: rtol + INTEGER :: it, ix, iy, iz, ic + REAL(wp) :: tol, a, b + + varies = .FALSE. + IF (axis /= 1 .AND. axis /= 2) RETURN + IF (SIZE(f, axis + 1) < 2) RETURN + tol = 0.0_wp + DO ic = 1, SIZE(f, 5) + DO iz = 1, SIZE(f, 4) + DO iy = 1, SIZE(f, 3) + DO ix = 1, SIZE(f, 2) + DO it = 1, SIZE(f, 1) + a = REAL(f(it, ix, iy, iz, ic), wp) + IF (.NOT. (ABS(a) <= HUGE(a))) THEN + varies = .TRUE. + RETURN + END IF + tol = MAX(tol, ABS(a)) + END DO + END DO + END DO + END DO + END DO + tol = rtol*tol + DO ic = 1, SIZE(f, 5) + DO iz = 1, SIZE(f, 4) + DO iy = 1, SIZE(f, 3) + DO ix = 1, SIZE(f, 2) + IF (axis == 1 .AND. ix == 1) CYCLE + IF (axis == 2 .AND. iy == 1) CYCLE + DO it = 1, SIZE(f, 1) + a = REAL(f(it, ix, iy, iz, ic), wp) + IF (axis == 1) THEN + b = REAL(f(it, 1, iy, iz, ic), wp) + ELSE + b = REAL(f(it, ix, 1, iz, ic), wp) + END IF + IF (ABS(a - b) > tol) THEN + varies = .TRUE. + RETURN + END IF + END DO + END DO + END DO + END DO + END DO + END FUNCTION CD_WaveGrid_Field_Varies + + PURE FUNCTION CD_WaveGrid_Advance(x, x_last, t, t_last, t_target) RESULT(xs) + !! The positions x of time t advanced to t_target by the velocity (x - x_last)/(t - t_last) of + !! the positions x_last of the earlier time t_last: where the wave field is sampled for a + !! sample time other than the time of the positions. x itself without a history (t_last not + !! before t) or at its own time. + REAL(wp), INTENT(IN) :: x(:, :), x_last(:, :), t, t_last, t_target + REAL(wp) :: xs(SIZE(x, 1), SIZE(x, 2)) + IF (t > t_last .AND. ABS(t_target - t) > 0.0_wp) THEN + xs = x + (x - x_last)/(t - t_last)*(t_target - t) + ELSE + xs = x + END IF + END FUNCTION CD_WaveGrid_Advance + +END MODULE CableDyn_WaveGrid 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 51d158d7..02e70f0f 100644 --- a/src/openfast/CableDyn_OF.f90 +++ b/src/openfast/CableDyn_OF.f90 @@ -136,8 +136,19 @@ MODULE CableDyn CD_Set_System_Line_Friction_Anchors, & CD_Recompute_System_Acceleration, CD_SYSTEM_OK USE SeaSt_WaveField, ONLY: WaveField_GetNodeWaveKin - USE SeaSt_WaveField_Types, ONLY: WaveMod_None + USE SeaSt_WaveField_Types, ONLY: WaveMod_None, WaveMod_ExtFull + USE CableDyn_WaveGrid, ONLY: CD_WaveGrid_Coarse_Axes, CD_WaveGrid_Field_Varies, CD_WaveGrid_Advance, & + 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 @@ -150,7 +161,7 @@ MODULE CableDyn ! the kinds of first-order linearization state (lin_state_map) INTEGER(IntKi), PARAMETER :: LIN1_VE = 1, LIN1_SYROPE = 2 - TYPE(ProgDesc), PARAMETER :: CableDyn_ProgDesc = ProgDesc( 'CableDyn', 'v0.4.3', '2026-11-20' ) + TYPE(ProgDesc), PARAMETER :: CableDyn_ProgDesc = ProgDesc( 'CableDyn', 'v0.5.0', '2026-12-04' ) INTERFACE ! 1 when the CableDyn core targets x86-64-v3 (CABLEDYN_TARGET_AVX2) and carries the ! start-up processor check of src/cabledyn_cpu_guard.c; the reference also keeps that @@ -201,6 +212,9 @@ END FUNCTION cd_cpu_guard_armed ! change, so held loads/channels are recomputed only after a new solve commit. LOGICAL :: loads_cached = .FALSE. INTEGER(IntKi) :: loads_at_n = -1 + ! ws_chan holds the channels of the cached loads' state (a call that skipped them, or + ! loads served without them, leaves it .FALSE.; cleared with loads_cached) + LOGICAL :: chan_cached = .FALSE. REAL(wp), ALLOCATABLE :: ws_chan(:) ! the committed-step row of the .CD.out when it evaluates its own channels (CD_CalcOutput) REAL(wp), ALLOCATABLE :: ws_rowchan(:) @@ -266,9 +280,21 @@ END FUNCTION cd_cpu_guard_armed LOGICAL :: use_extfluid = .FALSE. INTEGER(IntKi) :: nfluid = 0 REAL(wp), ALLOCATABLE :: fx_xyz(:,:), fx_vel(:,:), fx_acc(:,:), fx_wl(:), fx_pd(:) - ! TRUE once the warning that sampling nodes lie outside the SeaState wave-kinematics - ! grid has been issued: one warning per run (check_wavefield_grid). + ! the wave-grid guard's workspace (check_wavefield_grid): the SeaState free-surface elevation + ! as sampled at each node, and the nodes it flags + REAL(wp), ALLOCATABLE :: fx_zeta(:) + LOGICAL, ALLOCATABLE :: fx_flag(:) + ! the grid route samples SeaState at the nodes' positions advanced to the sample time (fx_smp): + ! the positions read (fx_xyz) are those of the last commit, the start of the mooring interval + ! whose end is sampled; the advance takes each node's velocity from its positions at the last + ! two distinct commit times (smp_x at smp_t, smp_xl at smp_tl), carried through a checkpoint + REAL(wp), ALLOCATABLE :: fx_smp(:,:), smp_x(:,:), smp_xl(:,:) + REAL(DbKi) :: smp_t = -1.0_DbKi, smp_tl = -1.0_DbKi + ! 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 @@ -305,12 +331,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 @@ -642,6 +690,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 @@ -893,6 +942,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 '// & @@ -902,7 +954,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 @@ -1033,7 +1086,9 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er END IF ALLOCATE (Inst(id)%fx_xyz(3, Inst(id)%nfluid), Inst(id)%fx_vel(3, Inst(id)%nfluid), & Inst(id)%fx_acc(3, Inst(id)%nfluid), Inst(id)%fx_wl(Inst(id)%nfluid), & - Inst(id)%fx_pd(Inst(id)%nfluid), STAT=ErrStat2) + Inst(id)%fx_pd(Inst(id)%nfluid), Inst(id)%fx_zeta(Inst(id)%nfluid), & + Inst(id)%fx_flag(Inst(id)%nfluid), Inst(id)%fx_smp(3, Inst(id)%nfluid), & + Inst(id)%smp_x(3, Inst(id)%nfluid), Inst(id)%smp_xl(3, Inst(id)%nfluid), STAT=ErrStat2) IF (ErrStat2 /= 0) THEN CALL SetErrStat( ErrID_Fatal, 'Could not allocate the ambient-fluid sampling workspace.', & ErrStat, ErrMsg, RoutineName ) @@ -1065,6 +1120,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 @@ -1075,7 +1141,20 @@ SUBROUTINE CD_Init(InitInp, u, p, x, xd, z, other, y, m, DTcoupling, InitOut, Er 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 ) + ! 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) + ! (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. @@ -1528,6 +1607,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 @@ -1595,6 +1677,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 @@ -1660,12 +1743,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), & @@ -1719,12 +1806,20 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) Inst(id)%nfluid = CD_AGG_NFluidNodes( Inst(id)%agg, es, em ) ALLOCATE (Inst(id)%fx_xyz(3, Inst(id)%nfluid), Inst(id)%fx_vel(3, Inst(id)%nfluid), & Inst(id)%fx_acc(3, Inst(id)%nfluid), Inst(id)%fx_wl(Inst(id)%nfluid), & - Inst(id)%fx_pd(Inst(id)%nfluid), STAT=ErrStat2) + Inst(id)%fx_pd(Inst(id)%nfluid), Inst(id)%fx_zeta(Inst(id)%nfluid), & + Inst(id)%fx_flag(Inst(id)%nfluid), Inst(id)%fx_smp(3, Inst(id)%nfluid), & + Inst(id)%smp_x(3, Inst(id)%nfluid), Inst(id)%smp_xl(3, Inst(id)%nfluid), STAT=ErrStat2) IF (ErrStat2 /= 0) THEN CALL SetErrStat( ErrID_Fatal, 'Could not allocate the ambient-fluid workspace (rebuild).', & 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) @@ -1881,10 +1976,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 @@ -1892,6 +2000,7 @@ SUBROUTINE rebuild_from_checkpoint( t, u1, p, x, other, m, ErrStat, ErrMsg ) Inst(id)%last_n = -1_IntKi Inst(id)%last_solve_n = -1_IntKi Inst(id)%loads_cached = .FALSE. + Inst(id)%chan_cached = .FALSE. Inst(id)%restored_unserved = Inst(id)%nsuper > 1_IntKi ! the load predictor's previous commit (shift_predictor_loads) Inst(id)%pred_t = other%pred_t @@ -2040,18 +2149,21 @@ SUBROUTINE CD_UpdateStates( t, n, u, t_array, p, x, xd, z, other, m, ErrStat, Er TRIM(em), ErrStat, ErrMsg, RoutineName ) RETURN END IF - ! SeaState ambient fluid: sample the WaveField at the line nodes' committed - ! positions, at the END of this mooring interval (where the implicit step - ! prescribes the boundary), and hold the fields over the step. The advance - ! runs on the LAST glue substep of the interval, so the interval end is + ! SeaState ambient fluid: sample the WaveField at the line nodes' positions at the + ! END of this mooring interval (where the implicit step prescribes the boundary), + ! advanced there from their committed positions, and hold the fields over the step. + ! The advance runs on the LAST glue substep of the interval, so the interval end is ! t + p%dtCoupling -- the SAME time the coupled-kinematics interpolation ! above uses (t + dt_moor from here would sit almost a full mooring step in ! the future under supercycling, phase-shifting the wave kinematics). ! Runs AFTER the snapshot: a correction re-entry restores the step-start - ! state and re-samples at the same committed positions. + ! state and re-samples from 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 read are those of the interval start, the last commit; both routes + ! advance them from there to the sample time) + 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) @@ -2098,6 +2210,7 @@ SUBROUTINE CD_UpdateStates( t, n, u, t_array, p, x, xd, z, other, m, ErrStat, Er ! cache is invalidated on every successful advance (bit-identical for the ! normal path -- last_solve_n moved anyway -- and correct for corrections). Inst(id)%loads_cached = .FALSE. + Inst(id)%chan_cached = .FALSE. ! (a row at every native_every-th glue step: OPTIONS CDOutDt) Inst(id)%native_pending = Inst(id)%native_un > 0_IntKi .AND. & MOD(n + 1_IntKi, Inst(id)%native_every) == 0_IntKi @@ -2136,8 +2249,9 @@ 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 ) - !! Sample the SeaState WaveField at every mooring line node's committed position -- + SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init, t_positions ) + !! Sample the SeaState WaveField at every mooring line node -- at its committed position + !! advanced to t_sample (advance_sample_positions) -- !! fluid velocity (waves + current), fluid acceleration, and the local free-surface !! elevation -- and prescribe them to the aggregate for the coming advance. Nodes !! are forced in-water for kinematics (forceNodeInWater = .TRUE., the MoorDyn @@ -2150,21 +2264,24 @@ 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 - ! the SeaState free-surface elevation as sampled at each node (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. Only the grid check reads it, so - ! it exists only until that check has warned. - REAL(wp), ALLOCATABLE :: wl_sampled(:) + ! 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. + LOGICAL :: check_grid CHARACTER(ErrMsgLen) :: em INTEGER(IntKi) :: ErrStat2 CHARACTER(ErrMsgLen) :: ErrMsg2 @@ -2186,6 +2303,10 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: '//TRIM(em), ErrStat, ErrMsg, RoutineName ) RETURN END IF + ! the positions the guard and the provenance record check and report (fx_smp): on the grid + ! route those SeaState is asked at, the positions read advanced to the sample time below; on + ! the node-wise route the positions read + inst_e%fx_smp = inst_e%fx_xyz ! SeaState measures its wave field and grid from the still-water level, and its node ! queries take SWL-relative positions; the mooring samples it at positions relative to the ! mean sea level, which coincide only for MSL2SWL = 0. Checked here, where the deck's @@ -2206,7 +2327,35 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) ErrStat, ErrMsg, RoutineName ) RETURN END IF - IF (.NOT. inst_e%grid_warned) ALLOCATE (wl_sampled(inst_e%nfluid)) + 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 + ! the grid route samples at the positions advanced to the sample time (fx_smp) + t_pos = t_sample + IF (PRESENT(t_positions)) t_pos = t_positions + CALL advance_sample_positions( inst_e, t_sample, t_pos ) + 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 @@ -2218,13 +2367,13 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) nodeInWater = 0_IntKi ELSE CALL WaveField_GetNodeWaveKin( p%WaveField, m%WaveField_m, t_sample, & - REAL(inst_e%fx_xyz(:, i), ReKi), .TRUE., & + REAL(inst_e%fx_smp(:, i), ReKi), .TRUE., & inst_e%agg%host_current_enabled, nodeInWater, & zeta1, zeta2, zeta, pdyn, fv, fa, famcf, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) IF (ErrStat >= AbortErrLev) RETURN END IF - IF (ALLOCATED(wl_sampled)) wl_sampled(i) = REAL(zeta, wp) + IF (check_grid) inst_e%fx_zeta(i) = REAL(zeta, wp) steady_fv = 0.0_SiKi IF (nodeInWater /= 0_IntKi .AND. & (.NOT. inst_e%agg%host_wave_enabled .OR. .NOT. inst_e%agg%host_current_enabled)) THEN @@ -2236,7 +2385,7 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) ! Below SWL and for Wheeler stretching, retain the same four ! vertical grid nodes and interpolation weights as the sampler. n_current_nodes = 4 - IF (p%WaveField%WaveStMod < 3_IntKi .AND. inst_e%fx_xyz(3, i) > 0.0_wp) & + IF (p%WaveField%WaveStMod < 3_IntKi .AND. inst_e%fx_smp(3, i) > 0.0_wp) & n_current_nodes = 1 DO l = 1, n_current_nodes IF (n_current_nodes == 1) THEN @@ -2271,7 +2420,7 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) ! subtract both, then restore the analytically reconstructed steady ! current. The remainder from the first sample is dynamic current. CALL WaveField_GetNodeWaveKin( p%WaveField, m%WaveField_m, t_sample, & - REAL(inst_e%fx_xyz(:, i), ReKi), .TRUE., .FALSE., nodeInWater, & + REAL(inst_e%fx_smp(:, i), ReKi), .TRUE., .FALSE., nodeInWater, & wave_zeta1, wave_zeta2, wave_zeta, wave_pdyn, wave_fv, wave_fa, & wave_famcf, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) @@ -2284,7 +2433,7 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) fv = fv - steady_fv END IF IF (ALLOCATED(inst_e%agg%host_current_profile_z)) THEN - CALL CD_Current_Profile_Velocity(REAL(inst_e%fx_xyz(3, i), wp), & + CALL CD_Current_Profile_Velocity(REAL(inst_e%fx_smp(3, i), wp), & inst_e%agg%host_current_profile_z, & inst_e%agg%host_current_profile_velocity, & profile_fv, es, em) @@ -2308,12 +2457,18 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) 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 - ! Grid coverage: checked on the positions just sampled (with their free-surface - ! elevations), at Init (the static equilibrium) and then every mooring step until the one - ! warning has been issued. - IF (.NOT. inst_e%grid_warned) THEN - CALL check_wavefield_grid( inst_e, p%WaveField, t_sample, init_call, wl_sampled, ErrStat2, ErrMsg2 ) + ! Grid coverage: checked on the positions just sampled (fx_smp, with the free-surface + ! elevations sampled there), 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 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 IF (.NOT. inst_e%curr_grid_warned) CALL check_current_field_grid( inst_e, p%WaveField, t_sample ) IF (timed) THEN @@ -2333,21 +2488,89 @@ SUBROUTINE sample_wavefield( inst_e, p, m, t_sample, ErrStat, ErrMsg, at_init ) END SUBROUTINE sample_wavefield !---------------------------------------------------------------------------------------------------------------------------------- - SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, wl_sampled, ErrStat, ErrMsg ) - !! Warn, once per run, when sampling nodes lie outside the SeaState wave-kinematics grid. - !! The volume grid spans X_HalfWidth and Y_HalfWidth about the origin of the global frame - !! the nodes are sampled in (FAST.Farm runs in still water and never samples) and Z_Depth - !! below the SWL. Beyond it SeaState clamps the position to the grid boundary (GridInterp - !! SetIndex horizontally, the depth mapping of WaveField_Interp_Setup4D vertically), so - !! the node receives the kinematics of the nearest boundary point -- out of phase - !! horizontally, too strong below Z_Depth. SeaState's own clamping notice is generic, names - !! no node, and is issued once, at the Init sample, where the glue drops it. The extents are - !! read from the WaveField's volume-grid parameters, i.e. exactly the grid the sampler - !! interpolates. Excursions below 1 % of the boundary grid spacing are ignored. Below a - !! grid that reaches the seabed (Z_Depth = WtrDpth + MSL2SWL, the SeaState maximum) a node - !! is in the seabed and the seabed kinematics are the right ones. SeaState's current is + SUBROUTINE advance_sample_positions( inst_e, t_sample, t_pos ) + !! The grid route's sample positions (fx_smp): the committed positions just read (fx_xyz), + !! which belong to t_pos (the last commit, the start of the mooring interval), advanced to + !! t_sample (its end) by each node's velocity, the difference of its positions at the last + !! two distinct position times (smp_x at smp_t, smp_xl at smp_tl). Without that history (the + !! first sample, or positions of an earlier time: a retry or a rewind, which restart it) and + !! when t_sample is t_pos, the positions are sampled as read. The node-wise route advances its + !! evaluation points the same way (sample_nodewise). + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + REAL(DbKi), INTENT(IN ) :: t_sample, t_pos + IF (t_pos > inst_e%smp_t) THEN + IF (inst_e%smp_t >= 0.0_DbKi) THEN + inst_e%smp_xl = inst_e%smp_x + inst_e%smp_tl = inst_e%smp_t + ELSE + inst_e%smp_xl = inst_e%fx_xyz + inst_e%smp_tl = t_pos + END IF + inst_e%smp_x = inst_e%fx_xyz + inst_e%smp_t = t_pos + ELSE IF (t_pos < inst_e%smp_t) THEN + inst_e%smp_x = inst_e%fx_xyz + inst_e%smp_xl = inst_e%fx_xyz + inst_e%smp_t = t_pos + inst_e%smp_tl = t_pos + END IF + ! smp_x holds the positions just read (fx_xyz) at smp_t = t_pos + inst_e%fx_smp = CD_WaveGrid_Advance( inst_e%smp_x, inst_e%smp_xl, REAL(inst_e%smp_t, wp), & + REAL(inst_e%smp_tl, wp), REAL(t_sample, wp) ) + END SUBROUTINE advance_sample_positions + + PURE INTEGER(IntKi) FUNCTION smp_mirror_size( inst_e ) RESULT(n) + !! The grid route's position history (advance_sample_positions) carried in the OtherState after + !! the node-wise cache: per node its last two positions, then the two times. + TYPE(CD_OF_Instance), INTENT(IN) :: inst_e + n = 0_IntKi + IF (ALLOCATED(inst_e%smp_x) .AND. .NOT. inst_e%nwk_on) n = 6_IntKi*inst_e%nfluid + 2_IntKi + END FUNCTION smp_mirror_size + + SUBROUTINE smp_pack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(IN ) :: inst_e + REAL(DbKi), INTENT(INOUT) :: buf(:) + INTEGER(IntKi) :: nf + nf = inst_e%nfluid + buf(1:3*nf) = RESHAPE(REAL(inst_e%smp_x, DbKi), [3*nf]) + buf(3*nf + 1:6*nf) = RESHAPE(REAL(inst_e%smp_xl, DbKi), [3*nf]) + buf(6*nf + 1) = inst_e%smp_t + buf(6*nf + 2) = inst_e%smp_tl + END SUBROUTINE smp_pack + + SUBROUTINE smp_unpack( inst_e, buf ) + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + REAL(DbKi), INTENT(IN ) :: buf(:) + INTEGER(IntKi) :: nf + nf = inst_e%nfluid + inst_e%smp_x = RESHAPE(REAL(buf(1:3*nf), wp), [3, nf]) + inst_e%smp_xl = RESHAPE(REAL(buf(3*nf + 1:6*nf), wp), [3, nf]) + inst_e%smp_t = buf(6*nf + 1) + inst_e%smp_tl = buf(6*nf + 2) + END SUBROUTINE smp_unpack + + SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, ErrStat, ErrMsg ) + !! The wave-grid guard on coverage: sampling nodes in the water that lie outside the SeaState + !! wave-kinematics grid. The volume grid spans X_HalfWidth and Y_HalfWidth about the origin + !! of the global frame the nodes are sampled in (FAST.Farm runs in still water and never + !! samples) and Z_Depth below the SWL. Beyond it SeaState clamps the position to the grid + !! boundary (GridInterp SetIndex horizontally, the depth mapping of WaveField_Interp_Setup4D + !! vertically), so the node receives the kinematics of the nearest boundary point -- out of + !! phase horizontally, too strong below Z_Depth. SeaState's own clamping notice is generic, + !! names no node, and is issued once, at the Init sample, where the glue drops it. The + !! extents are read from the WaveField's volume-grid parameters, i.e. exactly the grid the + !! sampler interpolates. Excursions below 1 % of the boundary grid spacing are ignored. + !! Below a grid that reaches the seabed (Z_Depth = WtrDpth + MSL2SWL, the SeaState maximum) a + !! node is in the seabed and the seabed kinematics are the right ones. SeaState's current is !! uniform in x and y, so the horizontal check applies to waves only. !! + !! Under OPTION waveGridCheck error (the default) a node outside is a fatal error, at Init + !! (the static equilibrium, t = 0) or at the first mooring step whose sample finds one: the + !! run stops there, and the message gives the time. Under waveGridCheck warn it is a + !! warning, given once per run, and the nodes keep the boundary kinematics. The message + !! lists, by line (or body, rod, buoy point), the nodes outside with the deepest and the + !! shallowest of them. + !! !! Only nodes in the water are checked: a node above the free surface carries no fluid !! load whatever kinematics it is given, so a suspended cable or jumper above the water !! outside the grid is no error. A node is in the water at or below the free-surface @@ -2355,28 +2578,27 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, wl_sampled, ErrS !! off), which decides its wetting in CableDyn, and, without wave stretching !! (WaveStMod = 0), at or below the still-water level too, above which SeaState gives a !! node zero kinematics without reading the grid. Called after the nodes' sampling, on the - !! positions just sampled. Cost: a few comparisons per node per mooring step until the - !! warning. at_init marks the Init call, at the static equilibrium (t = 0). + !! positions just sampled, with the SeaState elevations sampled there (fx_zeta). Cost: a few + !! comparisons per node per mooring step. !! - !! The message states first that it is given once, so that a caller's message buffer that - !! cuts its tail keeps that; the farthest-node details are left out if the message would not - !! fit the remaining length of ErrMsg. + !! The message is built to fit the room left in ErrMsg: the option that downgrades the error + !! is always in it, the per-line list is cut short ('and N more') before it would overflow, + !! and the farthest-node details are left out if they would not fit. TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf REAL(DbKi), INTENT(IN ) :: t_sample LOGICAL, INTENT(IN ) :: at_init - REAL(wp), INTENT(IN ) :: wl_sampled(:) !< SeaState elevation as sampled per node INTEGER(IntKi), INTENT( OUT) :: ErrStat CHARACTER(*), INTENT( OUT) :: ErrMsg character(*), parameter :: RoutineName = 'check_wavefield_grid' - LOGICAL :: waves, grid_current, check_xy(2), check_z, outside + LOGICAL :: waves, grid_current, check_xy(2), check_z, outside, fatal INTEGER(IntKi) :: i, k, nout, nin, nwet, room REAL(wp) :: lo(2), hi(2), tol(2), zbot, tol_z, ex, ex_max(3), at_max(3), surface REAL(wp) :: zq, dep CHARACTER(11) :: inp(3), res(3) CHARACTER(1024) :: farthest, enlarge, refine - CHARACTER(:), ALLOCATABLE :: head, msg + CHARACTER(:), ALLOCATABLE :: head, fix, option, by_line, msg ErrStat = ErrID_None ErrMsg = '' @@ -2401,20 +2623,21 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, wl_sampled, ErrS ex_max = 0.0_wp at_max = 0.0_wp DO i = 1, inst_e%nfluid + inst_e%fx_flag(i) = .FALSE. ! nodes above the free surface carry no fluid load (see above) surface = inst_e%fx_wl(i) IF (wf%WaveStMod == 0_IntKi) surface = MIN(surface, 0.0_wp) - IF (inst_e%fx_xyz(3, i) > surface) CYCLE + IF (inst_e%fx_smp(3, i) > surface) CYCLE nwet = nwet + 1_IntKi outside = .FALSE. DO k = 1, 2 IF (.NOT. check_xy(k)) CYCLE - ex = MAX(lo(k) - inst_e%fx_xyz(k, i), inst_e%fx_xyz(k, i) - hi(k)) + ex = MAX(lo(k) - inst_e%fx_smp(k, i), inst_e%fx_smp(k, i) - hi(k)) IF (ex > tol(k)) THEN outside = .TRUE. IF (ex > ex_max(k)) THEN ex_max(k) = ex - at_max(k) = inst_e%fx_xyz(k, i) + at_max(k) = inst_e%fx_smp(k, i) END IF END IF END DO @@ -2423,23 +2646,30 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, wl_sampled, ErrS ! the depth mapped linearly from [-EffWtrDpth, wave elevation] to [-EffWtrDpth, 0] with ! the elevation it sampled -- also for the current of a current-only host mode, whose ! fx_wl is the still-water level - zq = inst_e%fx_xyz(3, i) + zq = inst_e%fx_smp(3, i) IF (wf%WaveMod /= WaveMod_None .AND. wf%WaveStMod == 3_IntKi) THEN dep = REAL(wf%EffWtrDpth, wp) - IF (dep + wl_sampled(i) > 0.0_wp) zq = MIN(dep*(dep + zq)/(dep + wl_sampled(i)) - dep, 0.0_wp) + IF (dep + inst_e%fx_zeta(i) > 0.0_wp) & + zq = MIN(dep*(dep + zq)/(dep + inst_e%fx_zeta(i)) - dep, 0.0_wp) END IF ex = zbot - zq IF (ex > tol_z) THEN outside = .TRUE. IF (ex > ex_max(3)) THEN ex_max(3) = ex - at_max(3) = inst_e%fx_xyz(3, i) + at_max(3) = inst_e%fx_smp(3, i) END IF END IF END IF - IF (outside) nout = nout + 1_IntKi + IF (outside) THEN + nout = nout + 1_IntKi + inst_e%fx_flag(i) = .TRUE. + 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 @@ -2478,25 +2708,933 @@ SUBROUTINE check_wavefield_grid( inst_e, wf, t_sample, at_init, wl_sampled, ErrS END DO IF (ex_max(3) > 0.0_wp) enlarge = TRIM(enlarge)//' (Z_Depth at most WtrDpth + MSL2SWL, its default)' - inst_e%grid_warned = .TRUE. + fatal = .NOT. inst_e%agg%wave_grid_warn head = 'CableDyn mooring module: '//TRIM(Num2LStr(nout))//' of the '//TRIM(Num2LStr(nwet))// & ' CableDyn sampling nodes in the water lie outside the SeaState wave-kinematics grid at t = '// & - TRIM(Num2LStr(t_sample))//' s (warned once). SeaState clamps them to the grid boundary, so '// & - 'their fluid kinematics and loads are not physical.' - msg = head//' Farthest: '//TRIM(farthest(3:))//'. In the SeaState input file enlarge '//TRIM(enlarge)// & - ' to cover the lines with margin for their motion, and raise '//TRIM(refine)// & - ' to keep the grid spacing.' + TRIM(Num2LStr(t_sample))//' s' + IF (fatal) THEN + head = head//', where SeaState would give them the kinematics of the grid boundary, which are not '// & + 'physical there.' + option = ' To run on with those kinematics, set waveGridCheck warn in the OPTIONS of the CableDyn deck.' + ELSE + inst_e%grid_warned = .TRUE. + head = head//' (warned once). SeaState clamps them to the grid boundary, so their fluid kinematics '// & + 'and loads are not physical.' + option = ' (OPTIONS waveGridCheck warn; the default, error, stops the run here.)' + END IF + fix = ' In the SeaState input file enlarge '//TRIM(enlarge)//' to cover the lines with margin for '// & + '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_TRIM(ErrMsg) - LEN(RoutineName) - 2 - IF (LEN(msg) > room) msg = head//' Enlarge '//TRIM(enlarge)//' in the SeaState input file.' - CALL SetErrStat( ErrID_Warn, msg, ErrStat, ErrMsg, RoutineName ) - ! The OpenFAST glue does not print module initialization warnings (FAST_InitializeAll_T - ! passes its status on to FAST_InitMappings, which resets it), so the Init check also - ! writes the warning to the screen, as the deck dtM warning does. A warning raised - ! during the time march reaches the screen through the glue's error check. - IF (at_init) CALL WrScr( ' WARNING: '//msg ) + room = LEN(ErrMsg) - LEN(RoutineName) - 2 - LEN(head) - LEN(option) - LEN(fix) + 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) & + msg = msg//' Farthest: '//TRIM(farthest(3:))//'.' + msg = msg//fix//option + IF (fatal) THEN + CALL SetErrStat( ErrID_Fatal, msg, ErrStat, ErrMsg, RoutineName ) + ELSE + CALL SetErrStat( ErrID_Warn, msg, ErrStat, ErrMsg, RoutineName ) + ! The OpenFAST glue does not print module initialization warnings (FAST_InitializeAll_T + ! passes its status on to FAST_InitMappings, which resets it), so the Init check also + ! writes the warning to the screen, as the deck dtM warning does. A warning raised + ! during the time march reaches the screen through the glue's error check. + IF (at_init) CALL WrScr( ' WARNING: '//msg ) + END IF END SUBROUTINE check_wavefield_grid + SUBROUTINE check_wavefield_resolution( inst_e, wf, ErrStat, ErrMsg ) + !! The wave-grid guard on resolution across the waves, at initialisation (once per run: a + !! checkpoint restart, whose run passed it, rebuilds without it). A SeaState grid with NX = 2 + !! has three points along x (-X_HalfWidth, 0, X_HalfWidth), and SeaState's GridInterp + !! interpolates the kinematics between them with the quadratic through the three + !! (CableDyn_WaveGrid). That is exact only for waves that do not vary along x, a long-crested + !! sea travelling along y; likewise NY = 2 only for a sea along x. Under any other sea -- a + !! long-crested one in another direction, a short-crested one, or components in several + !! directions -- every point interpolated across that axis, the line nodes and the hull's Morison + !! members alike, receives an interpolation over a large part of a wavelength, wrong in + !! amplitude and phase. A node near a grid line at Init is no exception: one off it by a small + !! part of the half-width is already wrong in phase, and the sea sways the lines off it. + !! + !! The sea's directions are those of its first-order components with a nonzero amplitude + !! (WaveDirArr where WaveElevC0 is nonzero: one direction for a long-crested sea, the spread + !! of WaveDirMod 1, the component directions of WaveMod 7), or WaveDir if no component has an + !! amplitude. A direction is along an axis within CD_WAVEGRID_DIR_TOL (1e-4 deg). Externally + !! supplied kinematics (WaveMod 6) have no components, and SeaState does not use WaveDir in + !! that mode: a coarse axis is then judged from the supplied WaveVel and WaveAcc themselves, + !! which must be the same at the three grid points across it (CD_WaveGrid_Field_Varies, + !! within CD_WAVEGRID_FIELD_RTOL of their largest magnitude). It applies when the lines sample the grid in the + !! water, by the wet-node rule of check_wavefield_grid on the static positions just sampled; + !! the message lists those nodes by line. + !! + !! Under OPTION waveGridCheck error (the default) it is a fatal error; under warn + !! a warning, written to the screen too (the glue drops Init warnings). Only the waves are + !! concerned: SeaState's current is uniform in x and y. + TYPE(CD_OF_Instance), INTENT(INOUT) :: inst_e + TYPE(SeaSt_WaveFieldType), INTENT(IN ) :: wf + INTEGER(IntKi), INTENT( OUT) :: ErrStat + CHARACTER(*), INTENT( OUT) :: ErrMsg + + character(*), parameter :: RoutineName = 'check_wavefield_resolution' + CHARACTER(1), PARAMETER :: AXIS_NAME(2) = ['x', 'y'], AXIS_UPPER(2) = ['X', 'Y'] + LOGICAL :: coarse(2), fatal + INTEGER(IntKi) :: i, k, i0, i1, ndir, nwet, room, half(2) + REAL(wp) :: delta(2), surface, dmin, dmax + REAL(wp), ALLOCATABLE :: dirs(:) + CHARACTER(:), ALLOCATABLE :: head, sea, grid, fix, option, by_line, msg + + ErrStat = ErrID_None + ErrMsg = '' + IF (.NOT. (inst_e%agg%host_wave_enabled .AND. wf%WaveMod /= WaveMod_None)) RETURN + DO k = 1, 2 + half(k) = (wf%VolGridParams%n(k + 1) + 1_IntKi)/2_IntKi + delta(k) = REAL(wf%VolGridParams%delta(k + 1), wp) + END DO + IF (ALL(half > CD_WAVEGRID_COARSE_HALF_NODES)) RETURN + + ! externally supplied kinematics (WaveMod 6): no component directions, and SeaState does not + ! use WaveDir in that mode, so a coarse axis is judged from the supplied grid data + IF (wf%WaveMod == WaveMod_ExtFull) THEN + coarse = .FALSE. + DO k = 1, 2 + IF (half(k) > CD_WAVEGRID_COARSE_HALF_NODES) CYCLE + IF (ALLOCATED(wf%WaveVel)) coarse(k) = CD_WaveGrid_Field_Varies( wf%WaveVel, k, CD_WAVEGRID_FIELD_RTOL ) + IF (.NOT. coarse(k) .AND. ALLOCATED(wf%WaveAcc)) & + coarse(k) = CD_WaveGrid_Field_Varies( wf%WaveAcc, k, CD_WAVEGRID_FIELD_RTOL ) + END DO + IF (.NOT. ANY(coarse)) RETURN + END IF + + ! the directions of the components the sea carries + ndir = 0_IntKi + IF (wf%WaveMod /= WaveMod_ExtFull .AND. ALLOCATED(wf%WaveDirArr) .AND. ALLOCATED(wf%WaveElevC0)) THEN + i0 = MAX(LBOUND(wf%WaveDirArr, 1), LBOUND(wf%WaveElevC0, 2)) + i1 = MIN(UBOUND(wf%WaveDirArr, 1), UBOUND(wf%WaveElevC0, 2)) + ALLOCATE (dirs(MAX(1_IntKi, i1 - i0 + 1_IntKi))) + DO i = i0, i1 + IF (wf%WaveElevC0(1, i) == 0.0_SiKi .AND. wf%WaveElevC0(2, i) == 0.0_SiKi) CYCLE + ndir = ndir + 1_IntKi + dirs(ndir) = REAL(wf%WaveDirArr(i), wp) + END DO + ELSE + ALLOCATE (dirs(1)) + END IF + IF (ndir == 0_IntKi) THEN + ndir = 1_IntKi + dirs(1) = REAL(wf%WaveDir, wp) + END IF + IF (wf%WaveMod /= WaveMod_ExtFull) THEN + CALL CD_WaveGrid_Coarse_Axes( half, dirs(1:ndir), coarse ) + IF (.NOT. ANY(coarse)) RETURN + END IF + + ! the nodes that sample the grid in the water + nwet = 0_IntKi + DO i = 1, inst_e%nfluid + inst_e%fx_flag(i) = .FALSE. + surface = inst_e%fx_wl(i) + IF (wf%WaveStMod == 0_IntKi) surface = MIN(surface, 0.0_wp) + IF (inst_e%fx_smp(3, i) > surface) CYCLE + nwet = nwet + 1_IntKi + inst_e%fx_flag(i) = .TRUE. + END DO + IF (nwet == 0_IntKi) RETURN + + dmin = MINVAL(dirs(1:ndir)) + dmax = MAXVAL(dirs(1:ndir)) + IF (wf%WaveMod == WaveMod_ExtFull) THEN + sea = 'externally supplied wave kinematics (WaveMod 6) that differ between the grid points across it' + ELSE IF (wf%WaveMultiDir) THEN + sea = 'a short-crested sea (directions '//TRIM(Num2LStr(dmin))//' to '//TRIM(Num2LStr(dmax))//' deg)' + ELSE IF (dmax - dmin <= CD_WAVEGRID_DIR_TOL) THEN + sea = 'long-crested waves at '//TRIM(Num2LStr(dmin))//' deg' + ELSE + sea = 'wave components in directions from '//TRIM(Num2LStr(dmin))//' to '//TRIM(Num2LStr(dmax))//' deg' + END IF + grid = '' + DO k = 1, 2 + IF (.NOT. coarse(k)) CYCLE + IF (LEN(grid) > 0) grid = grid//' and ' + grid = grid//'N'//AXIS_UPPER(k)//' = '//TRIM(Num2LStr(half(k)))//' (3 points '// & + TRIM(Num2LStr(delta(k)))//' m apart in '//AXIS_NAME(k)//')' + END DO + fatal = .NOT. inst_e%agg%wave_grid_warn + head = 'CableDyn mooring module: the SeaState wave-kinematics grid has '//grid//' under '//sea// & + ', which vary along that axis: SeaState interpolates them between the three grid points, '// & + 'over distances that are a large part of a wavelength or more, for the hull members and for '// & + 'the lines, which sample the grid in the water at '//TRIM(Num2LStr(nwet))//' CableDyn nodes.' + fix = ' A grid with NY = 2 represents only waves along x (0 or 180 deg) and one with NX = 2 only '// & + 'waves along y (90 or 270 deg), within 1e-4 deg; in the SeaState input file raise the count so '// & + 'that the spacing resolves the shortest wavelength that matters at the lines (a tenth of it '// & + 'or finer).' + IF (fatal) THEN + option = ' To run on with the interpolated kinematics, set waveGridCheck warn in the OPTIONS of '// & + 'the CableDyn deck.' + ELSE + option = ' (OPTIONS waveGridCheck warn; the default, error, stops the run here.)' + END IF + room = LEN(ErrMsg) - LEN(RoutineName) - 2 - LEN(head) - LEN(option) - LEN(fix) + CALL flagged_nodes_by_line( inst_e, room - 16, by_line ) + msg = head + IF (LEN(by_line) > 0) msg = msg//' By line: '//by_line//'.' + msg = msg//fix//option + IF (fatal) THEN + CALL SetErrStat( ErrID_Fatal, msg, ErrStat, ErrMsg, RoutineName ) + ELSE + CALL SetErrStat( ErrID_Warn, msg, ErrStat, ErrMsg, RoutineName ) + CALL WrScr( ' WARNING: '//msg ) + END IF + + END SUBROUTINE check_wavefield_resolution + + 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'. 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 + + report = '' + nskip = 0_IntKi + IF (.NOT. ALLOCATED(inst_e%agg%fl_off)) RETURN + DO b = 1, SIZE(inst_e%agg%fl_off) - 1 + n = 0_IntKi + ideep = 0_IntKi + ishal = 0_IntKi + 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 (ideep == 0_IntKi) THEN + ideep = i + ishal = i + END IF + IF (inst_e%fx_smp(3, i) < inst_e%fx_smp(3, ideep)) ideep = i + IF (inst_e%fx_smp(3, i) > inst_e%fx_smp(3, ishal)) ishal = i + END DO + IF (n == 0_IntKi) CYCLE + IF (n == 1_IntKi) THEN + item = TRIM(fluid_block_label(inst_e%agg, b))//', 1 node, at '//node_position(ideep) + ELSE + 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_smp(3, ishal), wp) ) >= 0.0_wp) & + item = item//', weighted velocity ratio '//ratio_text( vel_ratio( inst_e, & + REAL(inst_e%fx_smp(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 + END IF + IF (LEN(report) > 0) report = report//'; ' + report = report//item + END DO + IF (nskip > 0_IntKi) report = report//'; and '//TRIM(Num2LStr(nskip))//' more' + + 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 + s = '(x, y, z) = ('//TRIM(Num2LStr(inst_e%fx_smp(1, i)))//', '//TRIM(Num2LStr(inst_e%fx_smp(2, i)))// & + ', '//TRIM(Num2LStr(inst_e%fx_smp(3, i)))//') m' + END FUNCTION node_position + + END SUBROUTINE flagged_nodes_by_line + + FUNCTION fluid_block_label( agg, b ) RESULT(label) + !! The name of fluid block b of the aggregate (CD_AGG_GetFluidNodePositions): 'line ' with + !! the deck's LINES id for an EI = 0 line or a finite-EI cable, else the body, rod or buoy + !! point with its position among those of the deck. + TYPE(CD_AGG_ModuleType), INTENT(IN) :: agg + INTEGER(IntKi), INTENT(IN) :: b + CHARACTER(64) :: label + INTEGER(IntKi) :: k, obj + LOGICAL :: cable + + label = '' + IF (b <= agg%fl_nlines + agg%ncable) THEN + cable = b > agg%fl_nlines + obj = b + IF (cable) obj = b - agg%fl_nlines + IF (ALLOCATED(agg%line_obj_index) .AND. ALLOCATED(agg%line_is_cable)) THEN + DO k = 1, SIZE(agg%line_obj_index) + IF (agg%line_obj_index(k) == obj .AND. (agg%line_is_cable(k) .EQV. cable)) THEN + label = 'line '//TRIM(Num2LStr(k)) + RETURN + END IF + END DO + END IF + IF (cable) THEN + label = 'finite-EI cable '//TRIM(Num2LStr(obj))//' of the deck' + ELSE + label = 'EI = 0 line '//TRIM(Num2LStr(obj))//' of the deck' + END IF + ELSE IF (b <= agg%fl_nlines + agg%ncable + agg%fl_nbody) THEN + label = 'Rigid6 body '//TRIM(Num2LStr(b - agg%fl_nlines - agg%ncable))//' of the deck' + ELSE IF (b <= agg%fl_nlines + agg%ncable + agg%fl_nbody + agg%fl_nrod) THEN + label = 'rod '//TRIM(Num2LStr(b - agg%fl_nlines - agg%ncable - agg%fl_nbody))//' of the deck' + ELSE + label = 'buoy point '//TRIM(Num2LStr(b - agg%fl_nlines - agg%ncable - agg%fl_nbody - agg%fl_nrod))// & + ' of the deck' + 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_smp(:, i) + ln%oog_shallowest = inst_e%fx_smp(:, i) + END IF + IF (inst_e%fx_smp(3, i) < ln%oog_deepest(3)) ln%oog_deepest = inst_e%fx_smp(:, i) + IF (inst_e%fx_smp(3, i) > ln%oog_shallowest(3)) ln%oog_shallowest = inst_e%fx_smp(:, 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 @@ -2524,7 +3662,7 @@ SUBROUTINE note_seastate_deep_interval( inst_e, wf ) interval = depth*SIN(REAL(wf%VolGridParams%delta(4), wp)) IF (depth < REAL(wf%EffWtrDpth, wp) - 0.01_wp*interval) RETURN IF (interval <= SEASTATE_DEEP_INTERVAL*depth) RETURN - nodes = COUNT(inst_e%fx_xyz(3, 1:inst_e%nfluid) < interval - depth) + nodes = COUNT(inst_e%fx_smp(3, 1:inst_e%nfluid) < interval - depth) IF (nodes == 0_IntKi) RETURN CALL WrScr( ' Note: the deepest interval of the SeaState depth grid is '//TRIM(Num2LStr(interval))// & ' m (NZ = '//TRIM(Num2LStr(nz))//', Z_Depth = '//TRIM(Num2LStr(depth))//' m), over '// & @@ -2563,8 +3701,8 @@ SUBROUTINE check_current_field_grid( inst_e, wf, t_sample ) ey = 0.0_wp DO i = 1, inst_e%nfluid surface = MIN(inst_e%fx_wl(i), 0.0_wp) - IF (inst_e%fx_xyz(3, i) > MAX(inst_e%fx_wl(i), surface)) CYCLE - pos = [inst_e%fx_xyz(1, i), inst_e%fx_xyz(2, i), inst_e%fx_xyz(3, i) + dep] + IF (inst_e%fx_smp(3, i) > MAX(inst_e%fx_wl(i), surface)) CYCLE + pos = [inst_e%fx_smp(1, i), inst_e%fx_smp(2, i), inst_e%fx_smp(3, i) + dep] IF (wf%CurrField%RotateWindBox) THEN rel = MATMUL(REAL(wf%CurrField%RotToWind, wp), pos - REAL(wf%CurrField%RefPosition, wp)) + & REAL(wf%CurrField%RefPosition, wp) @@ -2591,7 +3729,7 @@ SUBROUTINE check_current_field_grid( inst_e, wf, t_sample ) END SUBROUTINE check_current_field_grid !---------------------------------------------------------------------------------------------------------------------------------- - SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) + SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg, CalcWriteOutput ) REAL(DbKi) , INTENT(IN ) :: t TYPE( CD_InputType ) , INTENT(IN ) :: u TYPE( CD_ParameterType ) , INTENT(IN ) :: p @@ -2603,6 +3741,10 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) TYPE(CD_MiscVarType) , INTENT(INOUT) :: m INTEGER(IntKi) , INTENT(INOUT) :: ErrStat CHARACTER(*) , INTENT(INOUT) :: ErrMsg + !> .FALSE. when the caller will not write y%WriteOutput from this call (the OpenFAST glue passes + !! its WriteThisStep, as for AeroDyn and BeamDyn): the deck channels are then not evaluated and + !! y%WriteOutput keeps its last values. Absent: evaluated on every call. The loads are unaffected. + LOGICAL, OPTIONAL , INTENT(IN ) :: CalcWriteOutput character(*), parameter :: RoutineName = 'CD_CalcOutput' INTEGER(IntKi) :: ErrStat2, es, id, i, n_chan @@ -2613,6 +3755,7 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) LOGICAL :: fresh, state_overlaid ! the channels this call evaluated are those of the committed state as it stands LOGICAL :: chan_committed + LOGICAL :: want_chan ! evaluate the deck channels in this call ! Report this call's OWN status: clear at entry (ErrStat is INTENT(INOUT) and ! every SetErrStat below only ACCUMULATES, so on the all-success path an @@ -2640,6 +3783,8 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) END IF state_overlaid = .FALSE. chan_committed = .FALSE. + want_chan = .TRUE. + IF (PRESENT(CalcWriteOutput)) want_chan = CalcWriteOutput ! Evaluate the loads the mooring exerts on the coupling points. At nsuper = 1 (the ! mooring stepping at the glue rate) the CURRENT coupled kinematics are transferred @@ -2709,7 +3854,9 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) ! Supercycled: the committed state changes only when a mooring step completes, so the ! held loads/channels are re-evaluated only then (serving the cache is bit-identical ! to re-evaluating the unchanged state, at 1/nsuper of the evaluations). - fresh = (.NOT. Inst(id)%loads_cached) .OR. (Inst(id)%loads_at_n /= Inst(id)%last_solve_n) + ! A call that wants the channels re-evaluates when the cached loads were taken without them. + fresh = (.NOT. Inst(id)%loads_cached) .OR. (Inst(id)%loads_at_n /= Inst(id)%last_solve_n) .OR. & + (want_chan .AND. p%NumOuts > 0 .AND. .NOT. Inst(id)%chan_cached) END IF IF (fresh) THEN @@ -2757,7 +3904,7 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) ! one row: the line-wide values several of a cable's channels read (its element twists, ! node torques, ...) are evaluated once for the row (CD_AGG_EvalChannels). IF (Inst(id)%prof_enabled) CALL SYSTEM_CLOCK(prof_phase0) - IF (p%NumOuts > 0) THEN + IF (p%NumOuts > 0 .AND. want_chan) THEN CALL CD_AGG_EvalChannels( Inst(id)%agg, Inst(id)%ws_chan, n_chan, es, em ) IF (es /= CD_AGG_OK) THEN CALL SetErrStat( ErrID_Fatal, 'CableDyn mooring module: output channel evaluation failed: '// & @@ -2769,14 +3916,16 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) RETURN END IF END IF - ! supercycled, the state evaluated is the committed one itself (no overlay) - chan_committed = .NOT. state_overlaid + ! supercycled, the state evaluated is the committed one itself (no overlay); channels + ! skipped in this call leave ws_chan stale, so a row due now evaluates its own + chan_committed = .NOT. state_overlaid .AND. want_chan IF (Inst(id)%prof_enabled) THEN CALL SYSTEM_CLOCK(prof_c1) Inst(id)%prof_t_channels = Inst(id)%prof_t_channels + & REAL(prof_c1 - prof_phase0, wp)/REAL(prof_rate, wp) END IF Inst(id)%loads_cached = .TRUE. + Inst(id)%chan_cached = want_chan Inst(id)%loads_at_n = Inst(id)%last_solve_n Inst(id)%restored_unserved = .FALSE. END IF @@ -2886,9 +4035,11 @@ SUBROUTINE CD_CalcOutput( t, u, p, x, xd, z, other, y, m, ErrStat, ErrMsg ) END IF END IF END IF - DO i = 1, p%NumOuts - y%WriteOutput(i) = REAL(Inst(id)%ws_chan(i), ReKi) - END DO + IF (want_chan) THEN + DO i = 1, p%NumOuts + y%WriteOutput(i) = REAL(Inst(id)%ws_chan(i), ReKi) + END DO + END IF IF (Inst(id)%prof_enabled) THEN CALL SYSTEM_CLOCK(prof_c1) @@ -2905,16 +4056,24 @@ 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, ng nf = inst_e%nfluid + ! the node-wise route (WaterKin SEASTATE_SPECTRAL) appends its cache, the grid route its + ! position history, then the provenance record its run state + ng = smp_mirror_size( inst_e ) + nn = nwk_mirror_size( inst_e ) + ng + 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 > ng) CALL nwk_pack( inst_e, other%fluid_held(8*nf + 1:8*nf + nn - ng) ) + IF (ng > 0_IntKi) CALL smp_pack( inst_e, other%fluid_held(8*nf + nn - ng + 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 ) @@ -2926,14 +4085,20 @@ 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, ng CHARACTER(ErrMsgLen) :: em ErrStat = ErrID_None ErrMsg = '' restored = .FALSE. nf = inst_e%nfluid + ng = smp_mirror_size( inst_e ) + nn = nwk_mirror_size( inst_e ) + ng + 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 > ng) CALL nwk_unpack( inst_e, other%fluid_held(8*nf + 1:8*nf + nn - ng) ) + IF (ng > 0_IntKi) CALL smp_unpack( inst_e, other%fluid_held(8*nf + nn - ng + 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) @@ -3119,6 +4284,7 @@ SUBROUTINE serve_committed_loads( inst_e, ErrStat, ErrMsg ) RETURN END IF inst_e%loads_cached = .TRUE. + inst_e%chan_cached = .FALSE. ! loads only (see above) inst_e%loads_at_n = inst_e%last_solve_n inst_e%restored_unserved = .FALSE. END SUBROUTINE serve_committed_loads @@ -3525,6 +4691,7 @@ SUBROUTINE restore() CALL reload_interiors_ary( Inst(id), m, Inst(id)%ws_lsave, t_clock, ErrStat2, ErrMsg2 ) CALL SetErrStat( ErrStat2, ErrMsg2, ErrStat, ErrMsg, RoutineName ) Inst(id)%loads_cached = .FALSE. + Inst(id)%chan_cached = .FALSE. END SUBROUTINE restore END SUBROUTINE lin_eval @@ -3597,6 +4764,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 @@ -5518,7 +6691,19 @@ SUBROUTINE release_instance( k, ErrStat, ErrMsg ) Inst(k)%u_interp_ready = .FALSE. 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_wl, Inst(k)%fx_pd, Inst(k)%fx_zeta, Inst(k)%fx_flag, & + Inst(k)%fx_smp, Inst(k)%smp_x, Inst(k)%smp_xl) + Inst(k)%smp_t = -1.0_DbKi + Inst(k)%smp_tl = -1.0_DbKi + 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. @@ -5550,27 +6735,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_c_api.f90 b/tests/test_c_api.f90 index 6368bd2c..28c647aa 100644 --- a/tests/test_c_api.f90 +++ b/tests/test_c_api.f90 @@ -59,7 +59,7 @@ SUBROUTINE case_version() abi_version = -1_C_INT msg = 'x' CALL CableDyn_GetVersion(major, minor, patch, abi_version) - CALL require(major == 0_C_INT .AND. minor == 4_C_INT .AND. patch == 3_C_INT .AND. abi_version == 1_C_INT, & + CALL require(major == 0_C_INT .AND. minor == 5_C_INT .AND. patch == 0_C_INT .AND. abi_version == 1_C_INT, & 'c-api-version:tuple') CALL CableDyn_GetVersionString(C_LOC(msg), INT(SIZE(msg), C_INT)) CALL require(INDEX(c_text(msg), 'CableDyn') == 1 .AND. INDEX(c_text(msg), 'C-ABI 1') > 0, & 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..9ee3d457 --- /dev/null +++ b/tests/test_openfast_preflight_logscan.py @@ -0,0 +1,592 @@ +#!/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 + + +DEFAULT_POINTS = ("1 Coupled -58 0 -14", "2 Fixed -837.6 0 -200", "3 Coupled 29 50.2 -14", "4 Fixed 418.8 725.4 -200") +# every line end above the still-water level +DRY_POINTS = ("1 Coupled -58 0 14", "2 Fixed -837.6 0 5", "3 Coupled 29 50.2 14", "4 Fixed 418.8 725.4 5") + + +def write_case(folder: Path, seastate: dict[str, str], deck_extra: str = "", waterkin: str = "0", + points: tuple[str, ...] = DEFAULT_POINTS) -> 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) + POINT_ROWS + --------------------- LINES -------------------------------- + ID NodeA NodeB Outputs + (-) (-) (-) (-) + 1 1 2 - + 2 3 4 - + --------------------- OPTIONS ------------------------------ + 0.025 dtM + {waterkin} WaterKin + {deck_extra} + --------------------- OUTPUTS ------------------------------ + END + """ + ) + deck = deck.replace("POINT_ROWS", "\n".join(points)) + (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") + # CableDyn checks the resolution only when a line node samples the water: with every line end + # above it the checker notes the coarse axis rather than stopping + dry = out / "oblique_dry.json" + check(pre.main([str(write_case(out / "oblique_dry", {"WaveDir": "30"}, points=DRY_POINTS)), "--margin", "0", + "--json", str(dry)]) == 0, "NY = 2 under 30 deg with every line end dry is a note") + check(any("above the still-water level" in n for n in json.loads(dry.read_text(encoding="utf-8"))["notes"]), + "the dry-ends note is reported") + 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_syrope.f90 b/tests/test_syrope.f90 index c9a658ce..637e01af 100644 --- a/tests/test_syrope.f90 +++ b/tests/test_syrope.f90 @@ -69,6 +69,7 @@ PROGRAM test_syrope CALL case_quadratic() CALL case_exp() CALL case_owc_branch_and_running_max() + CALL case_branches_join() CALL case_interp_clamps() CALL case_projected_state_advance() CALL case_state_advance_at_wc_top() @@ -150,6 +151,12 @@ SUBROUTINE case_fail_closed() CALL require(es /= CD_SYROPE_OK .AND. INDEX(em, 'non-finite') > 0, 'fail:owc-nonfinite-slow') END BLOCK CALL CD_Syrope_End(td) + ! a row whose slow strain falls at its start and rises at its end: its ends increase, yet it + ! has no inverse (row slope 1.6e8 N, fast stiffness 1.53e8 N at the start and 1.76e8 N at the end) + CALL CD_Syrope_Init(td, [0.0_wp, 6.25e-3_wp], [0.0_wp, 1.0e6_wp], CD_SYROPE_WC_LINEAR, 0.5_wp, 0.0_wp, & + ALPHA, BETA, C1, C2, es, em) + CALL require(6.25e-3_wp > LOG(1.0_wp + BETA/ALPHA*1.0e6_wp)/BETA, 'fail:the row ends increase') + CALL require(es /= CD_SYROPE_OK .AND. INDEX(em, 'along every row') > 0, 'fail:a row without an inverse') END SUBROUTINE case_fail_closed SUBROUTINE case_degenerate_wc() @@ -275,7 +282,9 @@ END SUBROUTINE write_reference_row SUBROUTINE case_owc_branch_and_running_max() !! Committed mean tension AT/ABOVE the running max selects the OWC branch, !! and the recovered mean tension above T_max is the caller's regeneration - !! event: the regenerated curve matches the production formula. + !! event: the regenerated curve matches the production formula. The recovery is the + !! exact inverse of eps_owc(T) - eps_fast(T) (values by bisection in Python), where + !! MoorDyn interpolates the slow strains of the table rows. TYPE(CD_SyropeType) :: td REAL(wp) :: ws(CD_SYROPE_NWC), wt(CD_SYROPE_NWC), wsl(CD_SYROPE_NWC) REAL(wp) :: st, fa, sl, dsl, ten, tm @@ -291,18 +300,78 @@ SUBROUTINE case_owc_branch_and_running_max() CALL CD_Syrope_Rate_And_Tension(td, .FALSE., ws, wt, wsl, sl, 0.045_wp, 5.0e-5_wp, & dsl, ten, tm, es, em) CALL require(es == CD_SYROPE_OK, 'owc:rate-ok') - CALL require(close_rel(dsl, 1.2606308143959109e-05_wp), 'owc:rate') - CALL require(close_rel(ten, 3130162.871313756_wp), 'owc:tension') - CALL require(close_rel(tm, 2499847.4641158003_wp), 'owc:tmean-recovered') + CALL require(close_rel(dsl, 1.2597923741103403e-05_wp), 'owc:rate') + CALL require(close_rel(ten, 3129896.18705517_wp), 'owc:tension') + CALL require(close_rel(tm, 2.5e6_wp), 'owc:tmean-recovered') ! the running-max event: t_mean exceeded the 2.0e6 T_max -> regenerate CALL require(tm > 2.0e6_wp, 'owc:event-detected') CALL CD_Syrope_Working_Curve(td, tm, ws, wt, wsl, es, em) CALL require(es == CD_SYROPE_OK, 'owc:regenerated') - CALL require(close_rel(ws(1), 0.022011076961851315_wp), 'owc:regen-eps-min') - CALL require(close_rel(wt(23), 1896436.0072602627_wp), 'owc:regen-T23') + CALL require(close_rel(ws(1), 0.022011895413436695_wp), 'owc:regen-eps-min') + CALL require(close_rel(wt(23), 1896551.724137931_wp), 'owc:regen-T23') CALL CD_Syrope_End(td) END SUBROUTINE case_owc_branch_and_running_max + SUBROUTINE case_branches_join() + !! The working curve and the OWC meet at one slow strain for any running maximum: its top + !! sample is the divider to the bit, the OWC returns T_max there, and the recovered mean + !! tension changes on both sides of it (no band of slow strains that are all rest points of + !! a rope at its running maximum). And the recovery does not depend on the spacing of the + !! OWC rows: the same curve on eight times as many rows gives the same tension. + TYPE(CD_SyropeType) :: td, tf + INTEGER, PARAMETER :: NSUB = 8, NF = 29*NSUB + 1, NT = 200 + REAL(wp) :: ws(CD_SYROPE_NWC), wt(CD_SYROPE_NWC), wsl(CD_SYROPE_NWC), ef(NF), tnf(NF) + REAL(wp) :: tmax, d, dp, rate, ten, t_at, t_below, t_above, t_fine, off_at, off_fine, rise + INTEGER :: es, i, k, j, n_curve + LOGICAL :: joined + CHARACTER(200) :: em + CALL CD_Syrope_Init(td, OWC_EPS, OWC_TEN, CD_SYROPE_WC_EXP, 0.2_wp, 1.5_wp, ALPHA, BETA, C1, C2, es, em) + CALL require(es == CD_SYROPE_OK, 'join:init') + DO i = 1, 29 + DO j = 1, NSUB + k = (i - 1)*NSUB + j + ef(k) = OWC_EPS(i) + (OWC_EPS(i + 1) - OWC_EPS(i))*REAL(j - 1, wp)/REAL(NSUB, wp) + tnf(k) = OWC_TEN(i) + (OWC_TEN(i + 1) - OWC_TEN(i))*REAL(j - 1, wp)/REAL(NSUB, wp) + END DO + END DO + ef(NF) = OWC_EPS(30) + tnf(NF) = OWC_TEN(30) + CALL CD_Syrope_Init(tf, ef, tnf, CD_SYROPE_WC_EXP, 0.2_wp, 1.5_wp, ALPHA, BETA, C1, C2, es, em) + CALL require(es == CD_SYROPE_OK, 'join:init fine table') + joined = .TRUE. + off_at = 0.0_wp + off_fine = 0.0_wp + rise = HUGE(1.0_wp) + n_curve = 0 + DO i = 1, NT + tmax = 0.8e6_wp + (4.2e6_wp - 0.8e6_wp)*REAL(i - 1, wp)/REAL(NT - 1, wp) + CALL CD_Syrope_Working_Curve(td, tmax, ws, wt, wsl, es, em) + IF (es /= CD_SYROPE_OK) CYCLE ! an inadmissible running maximum has no curve + n_curve = n_curve + 1 + d = CD_Syrope_Branch_Divider(td, tmax) + joined = joined .AND. bits_same(wsl(CD_SYROPE_NWC), d) + CALL CD_Syrope_Rate_And_Tension(td, .FALSE., ws, wt, wsl, d, 0.0_wp, 0.0_wp, rate, ten, t_at, es, em) + off_at = MAX(off_at, ABS(t_at - tmax)/tmax) + dp = d - 1.0e-9_wp + CALL CD_Syrope_Rate_And_Tension(td, .TRUE., ws, wt, wsl, dp, 0.0_wp, 0.0_wp, rate, ten, t_below, es, em) + dp = d + 1.0e-9_wp + CALL CD_Syrope_Rate_And_Tension(td, .FALSE., ws, wt, wsl, dp, 0.0_wp, 0.0_wp, rate, ten, t_above, es, em) + rise = MIN(rise, t_at - t_below, t_above - t_at) + dp = d + 1.0e-4_wp + CALL CD_Syrope_Rate_And_Tension(tf, .FALSE., ws, wt, wsl, dp, 0.0_wp, 0.0_wp, rate, ten, t_fine, es, em) + CALL CD_Syrope_Rate_And_Tension(td, .FALSE., ws, wt, wsl, dp, 0.0_wp, 0.0_wp, rate, ten, t_above, es, em) + off_fine = MAX(off_fine, ABS(t_fine - t_above)/t_above) + END DO + WRITE (*, '(A,I0,A,ES9.2,A,ES9.2,A,ES9.2)') ' branches join at ', n_curve, ' running maxima: OWC off T_max by ', & + off_at, ', smallest rise over 1e-9 of slow strain ', rise, ' N, eight times the rows differ by ', off_fine + CALL require(n_curve > NT/2, 'join:most running maxima have a curve') + CALL require(joined .AND. off_at <= 1.0e-13_wp, 'join:one slow strain at the running maximum') + CALL require(rise > 1.0e-3_wp, 'join:no band of rest points') + CALL require(off_fine <= 1.0e-12_wp, 'join:independent of the row spacing') + CALL CD_Syrope_End(td) + CALL CD_Syrope_End(tf) + END SUBROUTINE case_branches_join + SUBROUTINE case_interp_clamps() !! Piecewise-linear interpolation clamps at both table ends. TYPE(CD_SyropeType) :: td @@ -359,13 +428,12 @@ SUBROUTINE case_projected_state_advance() END SUBROUTINE case_projected_state_advance SUBROUTINE case_state_advance_at_wc_top() - !! A rope held at rest on its OWC at its running maximum: the backward-Euler root lies just - !! above the top sample of the working curve's slow strains, where T_mean(eps_slow) stops - !! rising (it clamps at T_max up to the branch divider), closer to it than the Newton - !! step's difference interval. The state of a run (LINEAR, k1 = 0.5, BA_s|BA_d = 1e6|1e5, - !! a line hauled in and held) on which the safeguarded Newton step crept 80 iterations - !! along that kink and the solve failed; the bisection that finishes the solve meets the - !! residual test, between the kink and the divider, at the curve's top tension. + !! A rope held at rest on its OWC at its running maximum: the backward-Euler root lies at the + !! top sample of the working curve's slow strains, where the slope of T_mean(eps_slow) + !! changes, closer to it than the Newton step's difference interval. The state of a run + !! (LINEAR, k1 = 0.5, BA_s|BA_d = 1e6|1e5, a line hauled in and held) on which the + !! safeguarded Newton step crept 80 iterations along that kink and the solve failed; the + !! solve meets the residual test there, at the curve's top tension. TYPE(CD_SyropeType) :: td REAL(wp), PARAMETER :: TMAX = 1.7790941510791376e6_wp, SLOW0 = 2.0004433178640910e-2_wp, & EPS = 3.0303024894996432e-2_wp, DEPS = -1.4208693414705444e-13_wp, DT = 5.0e-2_wp @@ -387,8 +455,9 @@ SUBROUTINE case_state_advance_at_wc_top() residual = slow_next - SLOW0 - DT*rate WRITE (*, '(A,ES16.9,A,ES10.3,A,ES12.5,A)') ' wc-top: slow strain ', slow_next, ', residual ', residual, & ', mean tension ', mean, ' N' - CALL require(ABS(residual) <= 5.0e-13_wp .AND. slow_next > wsl(CD_SYROPE_NWC) .AND. slow_next < divider .AND. & - bits_same(mean, wt(CD_SYROPE_NWC)) .AND. bits_same(mean, t_mean), 'wc-top:root at the curve top') + CALL require(ABS(residual) <= 5.0e-13_wp .AND. ABS(slow_next - divider) <= 1.0e-8_wp .AND. & + ABS(mean - wt(CD_SYROPE_NWC)) <= 1.0e-6_wp*wt(CD_SYROPE_NWC) .AND. bits_same(mean, t_mean), & + 'wc-top:root at the curve top') CALL CD_Syrope_End(td) END SUBROUTINE case_state_advance_at_wc_top diff --git a/tests/test_syrope_composite.f90 b/tests/test_syrope_composite.f90 index 92ded4e3..2bf4016a 100644 --- a/tests/test_syrope_composite.f90 +++ b/tests/test_syrope_composite.f90 @@ -25,11 +25,18 @@ PROGRAM test_syrope_composite !! 8. A lightly loaded SYROPE IC rope near its working curve's zero-tension strain, where the !! plain secant update contracts slowly: the accelerated update lands every element on the !! Tmax0 working curve. + !! 9. A long inclined single-section rope (60 elements, 644 m) whose rest tension is a small part + !! of its past one on a linear working curve: the secants are a fifth and less of the + !! tangent along the whole line, where the element steps alone ran out of iterations. + !! 10. The same rope where its chord strain lies below the zero-tension strain of the past + !! tension's curve, or the chord is shorter than the rope: the weight sags it taut, and its + !! tensions are those of an elastic catenary (Python, 60 chords on the same rest curve). + !! A weightless rope there carries nothing and stops with a named error. USE CableDyn_Precision, ONLY: wp USE CableDyn_DeckDriver, ONLY: CD_Init_Deck_Models, CD_Run_Deck_Driver, CD_DECKDRV_OK USE CableDyn_Model, ONLY: CD_ModelType, CD_End_Model, CD_Get_Model_Tension USE CableDyn_Syrope, ONLY: CD_SyropeType, CD_Syrope_Init, CD_Syrope_End, CD_Syrope_Static_Tension, & - CD_SYROPE_WC_EXP, CD_SYROPE_OK + CD_SYROPE_WC_EXP, CD_SYROPE_WC_LINEAR, CD_SYROPE_OK IMPLICIT NONE INTEGER, PARAMETER :: NOWC = 30, NE_A = 25, NE_P = 40, NE_F = 12 @@ -134,6 +141,19 @@ PROGRAM test_syrope_composite ! zero-tension strain (about 53 kN), where the plain secant update contracts slowly CALL taut_rope(20.2_wp, '16.70', 'a lightly loaded preconditioned rope', tmax0=2.5e6_wp) + ! 9. the slow case of the whole line (with the element steps alone 2.60, 2.83 and 2.89 MN ran out of + ! iterations) + CALL long_rope(2.60e6_wp) + CALL long_rope(2.83e6_wp) + CALL long_rope(2.86e6_wp) + CALL long_rope(2.89e6_wp) + ! 10. a chord strain below the curve's zero-tension strain, and a chord shorter than the rope + CALL long_rope(3.5e6_wp, 643.7681_wp, [1.2200562146866004e5_wp, 1.2979380872515342e5_wp]) + CALL long_rope(4.5e6_wp, 643.7681_wp, [7.975073758336593e4_wp, 8.752111037376584e4_wp]) + CALL long_rope(2.83e6_wp, 660.0_wp, [4.757422030236737e4_wp, 5.620254324506163e4_wp]) + CALL long_rope(1.8e6_wp, 665.0_wp, [4.807701264159228e4_wp, 5.676431216195525e4_wp]) + CALL long_rope(3.5e6_wp, 643.7681_wp, mass='16.926') + CALL finish() CONTAINS @@ -245,6 +265,105 @@ SUBROUTINE taut_rope(span, mass, what, tmax0) IF (PRESENT(tmax0)) CALL CD_Syrope_End(td) END SUBROUTINE taut_rope + SUBROUTINE long_rope(tmax0, length, catenary, mass) + !! A 643.77 m polyester rope between an anchor at 700 m and a fairlead at 58 m radius in 150 m of + !! water, on the linear working curve (slope 156 MN) of a past tension tmax0: every element + !! lands on that curve. With length (the seabed then out of reach) the extreme tensions are + !! catenary's; with mass (a weightless rope) the line stops by name. + REAL(wp), INTENT(IN) :: tmax0 + REAL(wp), INTENT(IN), OPTIONAL :: length, catenary(2) + CHARACTER(*), INTENT(IN), OPTIONAL :: mass + INTEGER, PARAMETER :: NR = 4, NE = 60 + ! an original working curve of 12 MN breaking strength (strain, tension) + REAL(wp), PARAMETER :: R_EPS(NR) = [0.0_wp, 0.010_wp, 0.037_wp, 0.080_wp] + REAL(wp), PARAMETER :: R_TEN(NR) = [0.0_wp, 0.9e6_wp, 2.83e6_wp, 6.5e6_wp] + TYPE(CD_ModelType), ALLOCATABLE :: ml(:) + TYPE(CD_SyropeType) :: td + REAL(wp) :: ten(NE), eps_k, wst, tcurve + INTEGER :: u, k + CHARACTER(32) :: s_tmax0, s_len, s_mass + OPEN (NEWUNIT=u, FILE='csyr_long_owc.dat', STATUS='REPLACE', ACTION='WRITE') + WRITE (u, '(A)') 'Strain Tension' + WRITE (u, '(A)') '(-) (N)' + DO k = 1, NR + WRITE (u, '(ES14.6,1X,ES14.6)') R_EPS(k), R_TEN(k) + END DO + CLOSE (u) + OPEN (NEWUNIT=u, FILE='csyr_long_settings.dat', STATUS='REPLACE', ACTION='WRITE') + WRITE (u, '(A)') 'csyr_long_owc.dat OWC - Original working-curve table file' + WRITE (u, '(A)') 'LINEAR WCType - Working-curve formulation' + WRITE (u, '(A)') '1.56e8 k1 - Working-curve slope (N)' + WRITE (u, '(A)') '0.0 k2 - unused' + CLOSE (u) + WRITE (s_tmax0, '(ES23.16)') tmax0 + s_len = '643.7681' + IF (PRESENT(length)) WRITE (s_len, '(F10.4)') length + s_mass = '23.0' + IF (PRESENT(mass)) s_mass = mass + OPEN (NEWUNIT=u, FILE='csyr_long.dat', STATUS='REPLACE', ACTION='WRITE') + WRITE (u, '(A)') 'long single-section Syrope test deck' + WRITE (u, '(A)') '--- LINE TYPES ---' + WRITE (u, '(A)') 'Name Diam Mass EA BA EI Cdn Cdt Can Cat' + WRITE (u, '(A)') '(-) (m) (kg/m) (N) (-) (Nm2) (-) (-) (-) (-)' + WRITE (u, '(A)') 'rope 0.145 '//TRIM(s_mass)//' "SYROPE:csyr_long_settings.dat|2.22e8|33.0" '// & + '2.952e9|1.0e5 0.0 1.2 0.2 1.0 0.0' + WRITE (u, '(A)') '--- POINTS ---' + WRITE (u, '(A)') 'ID Type X Y Z Mass Vol CdA Ca' + WRITE (u, '(A)') '(-) (-) (m) (m) (m) (kg) (m3) (m2) (-)' + WRITE (u, '(A)') '1 Fixed -700.0 0.0 -150.0 0 0 0 0' + WRITE (u, '(A)') '2 Vessel -58.0 0.0 -14.0 0 0 0 0' + WRITE (u, '(A)') '--- LINES ---' + WRITE (u, '(A)') 'ID NodeA NodeB Outputs' + WRITE (u, '(A)') '(-) (-) (-) (-)' + WRITE (u, '(A)') '1 2 1 -' + WRITE (u, '(A)') '--- SYROPE IC ---' + WRITE (u, '(A)') 'Line(s) Tmax0 Tmean0' + WRITE (u, '(A)') '(-) (N) (N)' + WRITE (u, '(A)') '1 '//TRIM(ADJUSTL(s_tmax0))//' 6.0e5' + WRITE (u, '(A)') '--- SECTIONS ---' + WRITE (u, '(A)') 'LineID LineType Length NumSegs' + WRITE (u, '(A)') '(-) (-) (m) (-)' + WRITE (u, '(A)') '1 rope '//TRIM(ADJUSTL(s_len))//' 60' + WRITE (u, '(A)') '--- OPTIONS ---' + WRITE (u, '(A)') '9.80665 g' + WRITE (u, '(A)') '1025.0 rhoW' + WRITE (u, '(A)') MERGE('600.0 WtrDpth', '150.0 WtrDpth', PRESENT(length)) + WRITE (u, '(A)') '--- OUTPUTS ---' + WRITE (u, '(A)') 'FairTen1' + WRITE (u, '(A)') '--- end ---' + CLOSE (u) + CALL CD_Init_Deck_Models('csyr_long.dat', ml, es, em) + IF (PRESENT(mass)) THEN + CALL require(es /= CD_DECKDRV_OK .AND. (INDEX(em, 'slack at init') > 0 .OR. INDEX(em, 'did not converge') > 0 .OR. & + INDEX(em, 'static solve failed') > 0), & + 'a weightless slack rope stops by name: '//TRIM(em)) + RETURN + END IF + CALL require(es == CD_DECKDRV_OK, 'the long rope of Tmax0 '//TRIM(ADJUSTL(s_tmax0))//' N builds: '//TRIM(em)) + IF (es /= CD_DECKDRV_OK) RETURN + CALL CD_Syrope_Init(td, R_EPS, R_TEN, CD_SYROPE_WC_LINEAR, 1.56e8_wp, 0.0_wp, 2.22e8_wp, 33.0_wp, & + 2.952e9_wp, 1.0e5_wp, es, em) + CALL require(es == CD_SYROPE_OK, 'reference linear working curve: '//TRIM(em)) + ASSOCIATE (md => ml(1)) + CALL CD_Get_Model_Tension(md, ten, es, em) + wst = 0.0_wp + DO k = 1, md%n_elem + eps_k = NORM2(md%q(3*md%elem_conn(2, k) - 2:3*md%elem_conn(2, k)) - & + md%q(3*md%elem_conn(1, k) - 2:3*md%elem_conn(1, k)))/md%l0(k) - 1.0_wp + CALL CD_Syrope_Static_Tension(td, tmax0, eps_k, tcurve, es, em) + wst = MAX(wst, ABS(tcurve - ten(k))/ten(k)) + END DO + PRINT '(A,ES10.3,A,ES12.5,A,ES12.5,A,ES10.3)', ' long rope, Tmax0 ', tmax0, ': tensions ', MINVAL(ten), & + ' to ', MAXVAL(ten), ' N, elements off their rest curve by at most ', wst + CALL require(wst <= 1.0e-8_wp, 'every element of the long rope sits on its Tmax0 working curve') + IF (PRESENT(catenary)) CALL require(ABS(MINVAL(ten) - catenary(1)) <= 1.0e-5_wp*catenary(1) .AND. & + ABS(MAXVAL(ten) - catenary(2)) <= 1.0e-5_wp*catenary(2), & + 'the sagging rope has the tensions of the elastic catenary') + END ASSOCIATE + CALL CD_End_Model(ml(1), es, em) + CALL CD_Syrope_End(td) + END SUBROUTINE long_rope + SUBROUTINE tmax0_curve() !! SYROPE IC Tmax0 = 2.5 MN: the polyester's mean tension is the Tmax0 working curve's at its !! mean strain. diff --git a/tests/test_syrope_control.f90 b/tests/test_syrope_control.f90 index db15c97e..f0f39091 100644 --- a/tests/test_syrope_control.f90 +++ b/tests/test_syrope_control.f90 @@ -366,16 +366,14 @@ END FUNCTION kernel_tension SUBROUTINE kernel_rate(slow, eps, deps, tmax, rate, ten) !! MoorDyn's Syrope segment law (MoorDyn-C Line::getStateDeriv, MoorDyn-F Line_GetStateDeriv, !! ElasticMod 4) in strain form: the mean tension from the slow strain on the working curve - !! of tmax (30 samples) below the OWC's slow strain at tmax and on the OWC from it, + !! of tmax (30 samples) below the OWC's slow strain at tmax and on the OWC from it (there the + !! exact inverse of eps_owc(T) - eps_fast(T), by bisection; MoorDyn interpolates its rows), !! K1 = alpha + beta T_mean, d(eps_slow)/dt = (K1 (eps - eps_curve(T_mean)) + BA_d deps)/(BA_s + !! BA_d) and T = T_mean (eps >= 0) + BA_s d(eps_slow)/dt, clamped at zero (a line cannot push). REAL(wp), INTENT(IN) :: slow, eps, deps, tmax REAL(wp), INTENT(OUT) :: rate, ten - REAL(wp) :: we(NWC), wt(NWC), ws(NWC), os(NOWC), e_max, e_min, t_mean, e_curve + REAL(wp) :: we(NWC), wt(NWC), ws(NWC), e_max, e_min, t_mean, e_curve, lo, hi INTEGER :: k - DO k = 1, NOWC - os(k) = OWC_EPS(k) - fast_strain(OWC_TEN(k)) - END DO e_max = owc_e(tmax) e_min = OWC_EPS(1) + K1W*(e_max - OWC_EPS(1)) DO k = 1, NWC @@ -383,11 +381,21 @@ SUBROUTINE kernel_rate(slow, eps, deps, tmax, rate, ten) wt(k) = tmax*(we(k) - e_min)/(e_max - e_min) ws(k) = we(k) - fast_strain(wt(k)) END DO - IF (slow < lin(tmax, OWC_TEN, os)) THEN + IF (slow < e_max - fast_strain(tmax)) THEN t_mean = lin(slow, ws, wt) e_curve = lin(t_mean, wt, we) ELSE - t_mean = lin(slow, os, OWC_TEN) + lo = OWC_TEN(1) + hi = OWC_TEN(NOWC) + DO k = 1, 200 + t_mean = 0.5_wp*(lo + hi) + IF (owc_e(t_mean) - fast_strain(t_mean) < slow) THEN + lo = t_mean + ELSE + hi = t_mean + END IF + END DO + t_mean = 0.5_wp*(lo + hi) e_curve = lin(t_mean, OWC_TEN, OWC_EPS) END IF rate = ((ALPHA + BETA*t_mean)*(eps - e_curve) + BA_D*deps)/(BA_S + BA_D) diff --git a/tests/test_wave_grid.f90 b/tests/test_wave_grid.f90 new file mode 100644 index 00000000..b1803c6e --- /dev/null +++ b/tests/test_wave_grid.f90 @@ -0,0 +1,224 @@ +! File: tests/test_wave_grid.f90 +! SPDX-License-Identifier: Apache-2.0 +! Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +PROGRAM test_wave_grid + !! The rules of the coupled wave-grid guard (CableDyn_WaveGrid): + !! * a direction is along x at multiples of 180 deg and along y at 90 deg plus multiples of + !! 180 deg, within 1e-4 deg, in either sense and for negative angles; + !! * NY = 2 is coarse for every long-crested sea not along x (30, 60 and 90 deg) and for a + !! short-crested sea; NX = 2 for every sea not along y; an aligned sea (NY = 2 at 0 or + !! 180 deg, NX = 2 at 90 or 270 deg) and a finer grid (NX = NY = 3) are never coarse; + !! * positions read at one time and sampled at another are advanced by their velocity; + !! * OPTION waveGridCheck reaches the coupled aggregate (the mixed IEA-15 MW example deck, the + !! first argument): error by default and as written, warn as written, any other value is + !! refused by name. + USE CableDyn_Precision, ONLY: wp + USE CableDyn_WaveGrid, ONLY: CD_WaveGrid_Along_Axis, CD_WaveGrid_Coarse_Axes, CD_WaveGrid_Field_Varies, & + CD_WAVEGRID_DIR_TOL, CD_WAVEGRID_FIELD_RTOL, CD_WaveGrid_Advance + USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_End, CD_AGG_OK + USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_VALUE, IEEE_QUIET_NAN + USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: REAL32 + IMPLICIT NONE + + INTEGER :: nfail, k + CHARACTER(1024) :: deck + LOGICAL :: coarse(2) + REAL(wp) :: spread(7), nan + REAL(REAL32), ALLOCATABLE :: field(:, :, :, :, :) + + nfail = 0 + + ! directions along an axis + CALL require(CD_WaveGrid_Along_Axis(0.0_wp, 1), '0 deg is along x') + CALL require(CD_WaveGrid_Along_Axis(180.0_wp, 1), '180 deg is along x') + CALL require(CD_WaveGrid_Along_Axis(-180.0_wp, 1), '-180 deg is along x') + CALL require(CD_WaveGrid_Along_Axis(360.0_wp, 1), '360 deg is along x') + CALL require(CD_WaveGrid_Along_Axis(0.5_wp*CD_WAVEGRID_DIR_TOL, 1), 'half the tolerance is along x') + CALL require(CD_WaveGrid_Along_Axis(180.0_wp - 0.5_wp*CD_WAVEGRID_DIR_TOL, 1), & + '180 deg less half the tolerance is along x') + CALL require(.NOT. CD_WaveGrid_Along_Axis(2.0_wp*CD_WAVEGRID_DIR_TOL, 1), 'twice the tolerance is not along x') + CALL require(.NOT. CD_WaveGrid_Along_Axis(30.0_wp, 1), '30 deg is not along x') + CALL require(.NOT. CD_WaveGrid_Along_Axis(90.0_wp, 1), '90 deg is not along x') + CALL require(CD_WaveGrid_Along_Axis(90.0_wp, 2), '90 deg is along y') + CALL require(CD_WaveGrid_Along_Axis(270.0_wp, 2), '270 deg is along y') + CALL require(CD_WaveGrid_Along_Axis(-90.0_wp, 2), '-90 deg is along y') + CALL require(.NOT. CD_WaveGrid_Along_Axis(90.0_wp + 2.0_wp*CD_WAVEGRID_DIR_TOL, 2), & + '90 deg plus twice the tolerance is not along y') + CALL require(.NOT. CD_WaveGrid_Along_Axis(0.0_wp, 2), '0 deg is not along y') + CALL require(.NOT. CD_WaveGrid_Along_Axis(60.0_wp, 2), '60 deg is not along y') + nan = IEEE_VALUE(nan, IEEE_QUIET_NAN) + CALL require(.NOT. (CD_WaveGrid_Along_Axis(nan, 1) .OR. CD_WaveGrid_Along_Axis(nan, 2)), & + 'a NaN direction is along neither axis') + CALL require(.NOT. CD_WaveGrid_Along_Axis(0.0_wp, 3), 'there is no third axis') + + ! long-crested seas: NY = 2 across the waves + CALL CD_WaveGrid_Coarse_Axes([37, 2], [0.0_wp], coarse) + CALL require(.NOT. ANY(coarse), 'NY = 2 at 0 deg is not coarse') + CALL CD_WaveGrid_Coarse_Axes([37, 2], [180.0_wp], coarse) + CALL require(.NOT. ANY(coarse), 'NY = 2 at 180 deg is not coarse') + CALL CD_WaveGrid_Coarse_Axes([37, 2], [30.0_wp], coarse) + CALL require(coarse(2) .AND. .NOT. coarse(1), 'NY = 2 at 30 deg is coarse in y only') + CALL CD_WaveGrid_Coarse_Axes([37, 2], [60.0_wp], coarse) + CALL require(coarse(2) .AND. .NOT. coarse(1), 'NY = 2 at 60 deg is coarse in y only') + CALL CD_WaveGrid_Coarse_Axes([37, 2], [90.0_wp], coarse) + CALL require(coarse(2) .AND. .NOT. coarse(1), 'NY = 2 at 90 deg is coarse in y') + ! NX = 2 + CALL CD_WaveGrid_Coarse_Axes([2, 73], [90.0_wp], coarse) + CALL require(.NOT. ANY(coarse), 'NX = 2 at 90 deg is not coarse') + CALL CD_WaveGrid_Coarse_Axes([2, 73], [270.0_wp], coarse) + CALL require(.NOT. ANY(coarse), 'NX = 2 at 270 deg is not coarse') + CALL CD_WaveGrid_Coarse_Axes([2, 73], [0.0_wp], coarse) + CALL require(coarse(1) .AND. .NOT. coarse(2), 'NX = 2 at 0 deg is coarse in x only') + CALL CD_WaveGrid_Coarse_Axes([2, 73], [45.0_wp], coarse) + CALL require(coarse(1) .AND. .NOT. coarse(2), 'NX = 2 at 45 deg is coarse in x only') + CALL CD_WaveGrid_Coarse_Axes([2, 2], [45.0_wp], coarse) + CALL require(ALL(coarse), 'NX = NY = 2 at 45 deg is coarse in both') + CALL CD_WaveGrid_Coarse_Axes([3, 3], [45.0_wp], coarse) + CALL require(.NOT. ANY(coarse), 'NX = NY = 3 is never coarse') + + ! short-crested seas: a spread of directions about 0 deg (WaveDirMod 1) or 90 deg + spread = [(-30.0_wp + 10.0_wp*REAL(k, wp), k=0, 6)] + CALL CD_WaveGrid_Coarse_Axes([37, 2], spread, coarse) + CALL require(coarse(2) .AND. .NOT. coarse(1), 'NY = 2 under a short-crested sea about 0 deg is coarse in y') + CALL CD_WaveGrid_Coarse_Axes([2, 37], spread, coarse) + CALL require(coarse(1) .AND. .NOT. coarse(2), 'NX = 2 under a short-crested sea about 0 deg is coarse in x') + CALL CD_WaveGrid_Coarse_Axes([2, 37], spread + 90.0_wp, coarse) + CALL require(coarse(1), 'NX = 2 under a short-crested sea about 90 deg is coarse in x') + CALL CD_WaveGrid_Coarse_Axes([37, 37], spread, coarse) + CALL require(.NOT. ANY(coarse), 'a fine grid under a short-crested sea is not coarse') + CALL CD_WaveGrid_Coarse_Axes([2, 2], spread(1:0), coarse) + CALL require(.NOT. ANY(coarse), 'a sea with no component is never coarse') + + ! supplied kinematics (WaveMod 6), judged from the data: f(time, x, y, z, component) on a 3 x 3 x 2 + ! grid, a wave along y (the same at every x), along x, and the same with round-off and a NaN + ALLOCATE (field(4, 3, 3, 2, 3)) + field = 0.0_REAL32 + CALL require(.NOT. (CD_WaveGrid_Field_Varies(field, 1, CD_WAVEGRID_FIELD_RTOL) .OR. & + CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL)), 'a zero field varies along no axis') + CALL wave_along(field, 2) + CALL require(.NOT. CD_WaveGrid_Field_Varies(field, 1, CD_WAVEGRID_FIELD_RTOL), 'a wave along y does not vary along x') + CALL require(CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL), 'a wave along y varies along y') + CALL wave_along(field, 1) + CALL require(CD_WaveGrid_Field_Varies(field, 1, CD_WAVEGRID_FIELD_RTOL), 'a wave along x varies along x') + CALL require(.NOT. CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL), 'a wave along x does not vary along y') + field(2, 1, 3, 1, 1) = field(2, 1, 3, 1, 1)*(1.0_REAL32 + 1.0E-6_REAL32) + CALL require(.NOT. CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL), & + 'a difference below the tolerance does not vary') + field(2, 1, 3, 1, 1) = field(2, 1, 3, 1, 1) + 1.0E-3_REAL32*MAXVAL(ABS(field)) + CALL require(CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL), 'a difference above the tolerance varies') + CALL wave_along(field, 1) + field(3, 2, 2, 2, 2) = REAL(nan, REAL32) + CALL require(CD_WaveGrid_Field_Varies(field, 2, CD_WAVEGRID_FIELD_RTOL), 'a NaN in the field counts as varying') + CALL wave_along(field, 1) + CALL require(.NOT. CD_WaveGrid_Field_Varies(field(:, :, 1:1, :, :), 2, CD_WAVEGRID_FIELD_RTOL), & + 'a single point along the axis does not vary') + CALL require(.NOT. CD_WaveGrid_Field_Varies(field, 3, CD_WAVEGRID_FIELD_RTOL), 'there is no third axis') + + ! the sample positions: nodes moving at a constant velocity, read at the start of a mooring + ! step and sampled at its end, are sampled where they are at that time + BLOCK + REAL(wp) :: x0(3, 2), u(3, 2), xs(3, 2) + x0 = RESHAPE([10.0_wp, -4.0_wp, -30.0_wp, 60.0_wp, 2.0_wp, -14.0_wp], [3, 2]) + u = RESHAPE([0.8_wp, -0.3_wp, 0.5_wp, -1.2_wp, 0.0_wp, 2.0_wp], [3, 2]) + xs = CD_WaveGrid_Advance(x0 + u*1.025_wp, x0 + u*1.0_wp, 1.025_wp, 1.0_wp, 1.05_wp) + CALL require(MAXVAL(ABS(xs - (x0 + u*1.05_wp))) < 1.0e-12_wp, 'a sample position belongs to the sample time') + xs = CD_WaveGrid_Advance(x0, x0, 1.0_wp, 1.0_wp, 1.05_wp) + CALL require(.NOT. ANY(ABS(xs - x0) > 0.0_wp), 'without a history the positions are sampled as read') + xs = CD_WaveGrid_Advance(x0 + u, x0, 1.0_wp, 0.5_wp, 1.0_wp) + CALL require(.NOT. ANY(ABS(xs - (x0 + u)) > 0.0_wp), 'at their own time the positions are sampled as read') + END BLOCK + + ! the deck option, through the aggregate the OpenFAST shell reads it from + IF (COMMAND_ARGUMENT_COUNT() < 1) THEN + WRITE (*, '(A)') 'FAIL: the mixed example deck path argument is required' + ERROR STOP 1 + END IF + CALL GET_COMMAND_ARGUMENT(1, deck) + CALL check_option('', .TRUE., .FALSE., '') + CALL check_option('error waveGridCheck', .TRUE., .FALSE., '') + CALL check_option('warn waveGridCheck', .TRUE., .TRUE., '') + CALL check_option('WARN wave_grid_check - downgraded', .TRUE., .TRUE., '') + CALL check_option('strict waveGridCheck', .FALSE., .FALSE., 'OPTION waveGridCheck "strict" must be error or warn') + + IF (nfail > 0) THEN + WRITE (*, '(A,I0,A)') 'FAIL: ', nfail, ' assertion(s) failed' + ERROR STOP 1 + END IF + WRITE (*, '(A)') 'PASS: the wave-grid guard rules (directions along the axes, coarse axes) '// & + 'and OPTION waveGridCheck' + +CONTAINS + + SUBROUTINE check_option(row, accepted, warn, message) + !! A copy of the deck with `row` after its dtM row (none for an empty row), in the working + !! directory: initialised as the coupled aggregate, it is accepted or refused with `message`, + !! and an accepted deck carries wave_grid_warn = warn. + CHARACTER(*), INTENT(IN) :: row, message + LOGICAL, INTENT(IN) :: accepted, warn + CHARACTER(*), PARAMETER :: COPY = 'wave_grid_option.dat' + TYPE(CD_AGG_ModuleType), ALLOCATABLE :: agg + CHARACTER(4096) :: line + CHARACTER(1024) :: em + INTEGER :: uin, uout, ios, es + + OPEN (NEWUNIT=uin, FILE=TRIM(deck), STATUS='OLD', ACTION='READ', IOSTAT=ios) + CALL require(ios == 0, 'the deck opens: '//TRIM(deck)) + IF (ios /= 0) RETURN + OPEN (NEWUNIT=uout, FILE=COPY, STATUS='REPLACE', ACTION='WRITE', IOSTAT=ios) + CALL require(ios == 0, 'the deck copy opens') + IF (ios /= 0) THEN + CLOSE (uin) + RETURN + END IF + DO + READ (uin, '(A)', IOSTAT=ios) line + IF (ios /= 0) EXIT + WRITE (uout, '(A)') TRIM(line) + IF (INDEX(line, ' dtM ') > 0 .AND. LEN(row) > 0) WRITE (uout, '(A)') row + END DO + CLOSE (uin) + CLOSE (uout) + ALLOCATE (agg) + CALL CD_AGG_Init_From_Deck(agg, COPY, 0.025_wp, es, em) + IF (accepted) THEN + CALL require(es == CD_AGG_OK, '"'//row//'" is accepted: '//TRIM(em)) + IF (es == CD_AGG_OK) CALL require(agg%wave_grid_warn .EQV. warn, '"'//row//'" sets waveGridCheck') + ELSE + CALL require(es /= CD_AGG_OK .AND. INDEX(em, message) > 0, '"'//row//'" is refused by name: '//TRIM(em)) + END IF + CALL CD_AGG_End(agg, es, em) + END SUBROUTINE check_option + + SUBROUTINE wave_along(f, axis) + !! A long-crested wave travelling along grid axis `axis` (1: x, 2: y), with a different + !! amplitude per component and depth, sampled at four times on a grid 30 m apart. + REAL(REAL32), INTENT(OUT) :: f(:, :, :, :, :) + INTEGER, INTENT(IN) :: axis + INTEGER :: it, ix, iy, iz, ic + REAL(wp) :: s + + DO ic = 1, SIZE(f, 5) + DO iz = 1, SIZE(f, 4) + DO iy = 1, SIZE(f, 3) + DO ix = 1, SIZE(f, 2) + DO it = 1, SIZE(f, 1) + s = 30.0_wp*REAL(MERGE(ix, iy, axis == 1), wp) + f(it, ix, iy, iz, ic) = REAL(REAL(ic, wp)*EXP(-0.1_wp*REAL(iz, wp))* & + COS(0.069_wp*s - 0.8_wp*REAL(it, wp)), REAL32) + END DO + END DO + END DO + END DO + END DO + END SUBROUTINE wave_along + + 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 + +END PROGRAM test_wave_grid 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/RELEASE_0_5_0.md b/validation/RELEASE_0_5_0.md new file mode 100644 index 00000000..4585438a --- /dev/null +++ b/validation/RELEASE_0_5_0.md @@ -0,0 +1,115 @@ + + +# CableDyn v0.5.0 release record + +This record lists what was built and tested for the v0.5.0 release: the source commit, +toolchains, dependency pins, test results and asset hashes. Case definitions and pass criteria +are in [`VALIDATION.md`](../VALIDATION.md). The OpenFAST and r-test pins and the reference LAPACK +are those of [v0.4.3](RELEASE_0_4_3.md); the 23 OpenFAST patches are those of this release. + +## Source and pins + +| Item | Value | +| --- | --- | +| CableDyn | `0.5.0` (2026-12-04), C ABI 1, minor extension 4 | +| Source | The release tree (`release/0.5.0` at `e807c2b`): dev with #190 to #198, the version, the experiment records of the release, and the fix of the Codex review of the release PR (#199) to the pre-flight checker. The final Windows assets were built from `d41ecd2`, which has the same solver, driver, OpenFAST-module and Python-package sources (the later commit changes only `integration/openfast/cabledyn_preflight.py` and its test); the PyPI distributions from `e807c2b`. The gates below ran on this tree or on the version commit `a0d93fd`, which has the same sources but for those two files and the records. This record is added afterwards | +| OpenFAST base | `2895884d2be01862173c88d70f86b358d2f1a50a`; the 23 patches of [`integration/openfast/patches`](../integration/openfast/patches) applied to a clean checkout by `prepare_openfast_source.ps1` | +| OpenFAST r-test | `dd5feaaaa500ba7283140107806300d551cff0a7` | +| Reference LAPACK/BLAS | 3.12.1, release-tag archive with SHA-256 `2ca6407a001a474d4d4d35f3a61550156050c48016d949f0da0529c0aa052422`, built with IFX for x86-64-v3 (`/fp:precise /arch:CORE-AVX2`) | + +## Toolchains + +| Item | Version | +| --- | --- | +| GNU Fortran (test builds) | conda-forge GCC 16.2.0, with OpenBLAS 0.3.33 and LAPACK from the conda environment | +| Intel Fortran (Windows release) | IFX 2025.3.2, `/fp:precise /arch:CORE-AVX2 /Qfma-` (value-safe floating point, x86-64-v3, no contraction into fused multiply-adds), `/Qauto` (thread-safe local storage) | +| Microsoft C/C++ | Visual Studio 2022 (release workflow) | +| Python wheels | scikit-build-core; cibuildwheel (Linux `manylinux_2_28`, macOS arm64); IFX static build on Windows (`release/build_windows_wheel.ps1`) | +| Python and packaging | Python 3.13 (release workflow and the clean environments of the checks below) | + +## Test results + +| Gate | Result | +| --- | --- | +| GNU Release CTest, including the slow tier (Windows, local, fresh build directory, OpenBLAS Prescott kernel) | 438 of 439 before the experiment rerun. The one failure is `validation_records`, which needs provenance records that name the release; it passes on the release tree. 0 compiler warnings | +| GNU Debug CTest (`-fcheck=all`), including the slow tier (Windows, local, fresh build directory) | 438 of 439, with the same `validation_records` row; 0 compiler warnings | +| Fortran fast tier on two OpenBLAS kernels (Prescott, Haswell), on the merged changes of this release | 350 of 350 on each (the branches of #197 and #198) | +| CI matrix of the release tree (#199 at `e807c2b`) | Linux and Windows, Release and Debug (the pull-request Debug tier); the Prescott round-off job with the example fallback scan; Python 3.10 and 3.13 on three platforms with coverage and strict type checks; the wheel builds; Sphinx; all passed. Codex review of the release tree: one finding (the pre-flight checker stopped on a coarse grid axis when no line end was in the water, where CableDyn runs), fixed in `e807c2b` with a test; the re-review found no issues and no thread is open | +| Release metadata | `check_release_metadata.py` passed (CableDyn v0.5.0, 2026-12-04) | +| Release-tree audit, pre-commit | passed | +| Experimental comparisons ([`experiments`](experiments/README.md)) | Holcombe (12 cases) and Bergdahl (30 primary and 8 refinement cases) rerun with a GNU Release build of the release sources (`cabledyn.exe` SHA-256 `4047ffad2ac64901052ebe2ba16a253ea15395193fe37c8e8bae92ae79388098`). Both reproduce their summaries, metrics, refinement figures and the hashed Holcombe static profiles byte for byte. The Bergdahl waveform comparison was not rerun (its measured series was not available); its files and metrics are those of v0.3.0, as `provenance.json` states | +| Bodies suite (102 metrics) | 102 of 102 pass with the same GNU Release build | +| OpenFAST build gate (`integration/openfast/openfast_build_gate.ps1`, a GNU double-precision OpenFAST of the release sources; the IEA-15 MW mixed `CompMooring = 5` case in a JONSWAP sea) | passed: the module compiles, names itself `OpenFAST-v5.0.0-CableDyn-0.5.0` and runs with finite output | +| OpenFAST linearisation (`validation/scripts/openfast_lin_ab.py`, IEA-15 MW UMaine twin decks with the r-test `MD_Shared` turbine-1 inputs prepared as `examples/openfast/README.md` describes, and the mixed cable deck) | passed with the release `openfast.exe` (single precision). The CableDyn mooring block is symmetric to 7.2e-6. Surge stiffness is 7.721e4 N/m. The dominant fairlead-block entries agree with MoorDyn-F to 1.1e-3, and every entry above 1 % of its block to 2.9e-3. The platform 6×6 stiffness agrees to 1.03e-3 with MoorDyn-F's quasi-static reduction, and the mixed cable deck's point stiffness to its static solves to 1.05e-4. It also passed with the GNU double-precision build (symmetry 7.2e-6, 6×6 to 1.04e-3, cable deck to 1.04e-4); its `.lin` files are those of the build before #198, bit for bit, but for their time stamps | +| Shipped examples, v0.4.3 against the release sources (GNU Release builds, OpenBLAS Haswell kernel, every output file compared) | all 66 decks run with both, with no fallback note. 129 of 131 output files are byte-identical. The two Syrope composite examples (`composite_chain_syrope_chain.dat`, `composite_ve_syrope_jonswap.dat`) change by at most 1.4e-4 of a column's largest value, the anchor and fairlead tensions of the Syrope line, as the CHANGELOG states for the exact OWC recovery (#191) | +| Coupled run time (#198) | on an operating IEA-15 MW deck with three chains and a 237-element lazy-wave cable with the nodal twist (DT = 0.0125 s, 400 s, one thread, GNU builds) the simulation CPU time falls from 10.83 to 8.84 min against the build before #198, the outputs unchanged bit for bit; the steps are in the CHANGELOG | +| L5 wall-clock records ([`performance`](performance/README.md)) | not re-measured. The records of `VALIDATION.md` and `validation/performance` are those of the v0.4.2 drivers | + +## Windows executable gates + +Every gate of `build_static_windows.ps1` passed in the release workflow (`release-windows-static.yml`, +run 47225769640, on `d41ecd2`; the preflight run 47211453797 on `a0d93fd` passed the same gates). The +smoke runs used a system-only `PATH`. + +| Gate | Result | +| --- | --- | +| Compiler | IFX 2025.3.2 (minimum 2025.3) | +| OpenFAST solution build | one pass: 34 projects succeeded, 0 failed | +| `CableDyn_driver.exe` imports | `KERNEL32.dll`, `SHELL32.dll` and `imagehlp.dll` only; stack reserve 268,435,456 bytes; `--version` reports `Build x86-64-v3 (AVX2)` | +| `openfast.exe` imports | `KERNEL32.dll` and `imagehlp.dll` only; `-v` reports `OpenFAST-v5.0.0-CableDyn-0.5.0` | +| Processor check | both executables stop at start with exit 3 and the message on a simulated missing x86-64-v3 feature, on the preflight and on the final assets | +| Standalone smoke | the shallow-chain static deck (`chain_catenary_shallow_30m.dat`) converges | +| Memory growth over a 10x longer run | 2.7 -> 2.7 MiB (`dynamic_chain_current.dat`), 21.5 -> 21.8 MiB (`lozon_gomex80_power_cable.dat`); limit +16 MiB | +| Exit contract | a run states the exit contract after the banner; a refused input ends stderr with the closing line | +| `CompMooring = 5` smoke | CableDyn banner, `dtM` 0.025 s (one glue step), t = 0 fairlead tensions 2.436 / 2.436 / 2.436 MN, the wave-grid guard's findings for the r-test grid, normal termination | + +## Clean-machine test + +A self-contained check ran the release assets from a folder whose path holds spaces, an +accented letter and Hangul, with a system-only `PATH`. It checks: + +- the checksums of the four files and the manifest; +- that both executables start and name 0.5.0, and that both stop at start on a simulated missing + processor feature; +- every shipped example deck (66, including the `moordynC_*` folders, each run from its own + folder) with the release `CableDyn_driver.exe`, with no fallback note; +- four `CompMooring = 5` runs; +- the Python wheel in a new conda environment, where it imports as 0.5.0 and runs the release + driver. + +The four runs are: + +- a 70 s JONSWAP sea with mixed chains and a cable; +- a 400 s line failure (line 1 breaks at 100 s; the platform drifts 142 m); +- a checkpoint at 30 s with a restart whose last 10 s of output (400 rows) must be + bit-identical; +- a checkpoint between two mooring steps (`dtM` = 2 `DT`, at 30.025 s) whose restart must + match the rest of the run (198 rows) bit for bit. + +The model inputs were rebuilt from the r-test revision above. All checks passed on the +preflight assets and on the final assets. The Windows wheel of the PyPI preflight, installed into +a new conda environment, passed `release/smoke_test_wheel.py` (library, driver, build x86-64-v3). + +## Python distribution + +The PyPI distribution is built by `.github/workflows/wheels.yml`; each wheel is installed into a +clean environment and smoke-tested on its own platform (the library and the driver it carries +load and run a deck, and the driver reports the expected build). The preflight run (47227353390, +on `e807c2b`) built the files below for the TestPyPI upload; the release run rebuilds them from +the tag before the upload. + +| File | SHA-256 (preflight) | +| --- | --- | +| `cabledyn-0.5.0.tar.gz` | `2dbf3d79c0cea2a3c614ac5ba757a27a04ef6a0281ce1c3e3b11907de68636ee` | +| `cabledyn-0.5.0-py3-none-win_amd64.whl` | `155d76bbe168c2d43b9dcc3e4f79d9e67c16685e92b9e51100e2394e0ee149d9` | +| `cabledyn-0.5.0-py3-none-macosx_15_0_arm64.whl` | `764854f0bc0b759b98efe1f988d1db95426154eb8180d527584f1630d949af57` | +| `cabledyn-0.5.0-py3-none-manylinux_2_27_x86_64.manylinux_2_28_x86_64.whl` | `6188f9853fcc2785ed0da5c7fa1d9b168438430e728687b96f62bcf711f8dead` | + +## Assets + +| File | SHA-256 | +| --- | --- | +| `CableDyn_driver.exe` | `4dfb4f963807d4f99cfddd404d0de28d587b58d77932a271aa74a3ee56fefa07` | +| `openfast.exe` | `2032cf7927d8d3c66d04f262be909f7feb542e2b1321c97adefb6aab1f10e876` | +| `cabledyn-0.5.0-py3-none-any.whl` | `24fa4e652846bafe763dba0a9920c557791d55b246369baf94bd53aa0c395f52` | +| `cabledyn-0.5.0.tar.gz` | `f34825dce6314ba65f6981a979b862cdad238f81e0d3a3f7d6cec63e4b6fc1cf` | diff --git a/validation/experiments/bergdahl/README.md b/validation/experiments/bergdahl/README.md index c597323a..b7a44038 100644 --- a/validation/experiments/bergdahl/README.md +++ b/validation/experiments/bergdahl/README.md @@ -76,8 +76,8 @@ mean absolute percentage error of 3.11%, a mean bias of +0.47 N, a Pearson corre conditions, halving the nominal element length and the time step changes the mean cycle maximum by no more than 0.29% and 0.27%, respectively. The phase-averaged force histories had RMSEs of 5.93% and 2.56% of the measured force range with 0.3.0; that comparison was not rerun for -0.4.0, 0.4.1, 0.4.2 or 0.4.3 (its waveform files and metrics are the 0.3.0 run's, `provenance.json`). The -0.4.1, 0.4.2 and 0.4.3 reruns reproduce the 0.4.0 force maxima, metrics and refinement summaries byte for byte. The line's upper +0.4.0, 0.4.1, 0.4.2, 0.4.3 or 0.5.0 (its waveform files and metrics are the 0.3.0 run's, `provenance.json`). The +0.4.1, 0.4.2, 0.4.3 and 0.5.0 reruns reproduce the 0.4.0 force maxima, metrics and refinement summaries byte for byte. The line's upper end lies 0.3 m above the still-water level, so 0.4.0's dry weight of the part above the surface changed the results: the RMSE from 1.583 N to 1.577 N and the mean absolute percentage error from 3.13% to 3.11%. The waveform CSVs carry the measured phase averages computed from the diff --git a/validation/experiments/bergdahl/provenance.json b/validation/experiments/bergdahl/provenance.json index c70a0eaa..225e13ad 100644 --- a/validation/experiments/bergdahl/provenance.json +++ b/validation/experiments/bergdahl/provenance.json @@ -1,8 +1,8 @@ { - "CableDyn_release": "v0.4.3", - "validation_date": "2026-11-20", + "CableDyn_release": "v0.5.0", + "validation_date": "2026-12-04", "executable_name": "cabledyn.exe", - "executable_sha256": "84a1f1ff4fda48cca59afcf7313b023425e45d7229a1e7db5199310e52fb14de", + "executable_sha256": "4047ffad2ac64901052ebe2ba16a253ea15395193fe37c8e8bae92ae79388098", "compiler": "GNU Fortran 16.2.0", "build_type": "Release", "platform": "Windows 11 x86-64", @@ -22,5 +22,5 @@ "waveform_metrics_sha256": "0fb6015cb30aa2bbb1cd8951b603f9201af50372ee6d3633a72fc70ea5280d1a", "refinement_summary_sha256": "75342ed4f3ebe2d7acb19af56394e24e6ce909bb3df7445bf3a1d884280f9eb6", "waveform_comparison_release": "v0.3.0", - "waveform_comparison_note": "not rerun with 0.4.0, 0.4.1, 0.4.2 or 0.4.3: the supplement expData.dat was not available when the record was rerun; the waveform files and metrics are those of the v0.3.0 run" + "waveform_comparison_note": "not rerun with 0.4.0, 0.4.1, 0.4.2, 0.4.3 or 0.5.0: the supplement expData.dat was not available when the record was rerun; the waveform files and metrics are those of the v0.3.0 run" } diff --git a/validation/experiments/holcombe/provenance.json b/validation/experiments/holcombe/provenance.json index 7b8ba627..43d7e36b 100644 --- a/validation/experiments/holcombe/provenance.json +++ b/validation/experiments/holcombe/provenance.json @@ -1,8 +1,8 @@ { - "CableDyn_release": "v0.4.3", - "validation_date": "2026-11-20", + "CableDyn_release": "v0.5.0", + "validation_date": "2026-12-04", "executable_name": "cabledyn.exe", - "executable_sha256": "84a1f1ff4fda48cca59afcf7313b023425e45d7229a1e7db5199310e52fb14de", + "executable_sha256": "4047ffad2ac64901052ebe2ba16a253ea15395193fe37c8e8bae92ae79388098", "compiler": "GNU Fortran 16.2.0", "build_type": "Release", "platform": "Windows 11 x86-64", diff --git a/validation/scripts/openfast_wave_grid_guard.py b/validation/scripts/openfast_wave_grid_guard.py new file mode 100644 index 00000000..8134be93 --- /dev/null +++ b/validation/scripts/openfast_wave_grid_guard.py @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Coupled check of the SeaState wave-grid guard (OPTIONS waveGridCheck) in OpenFAST. + +The IEA-15 MW UMaine model of the OpenFAST tutorial (the r-test ``MD_Shared`` turbine-1 files, +pose reset as in doc/tutorial_openfast.rst) runs with ``examples/openfast/CableDyn_UMaine.dat`` +under SeaState grids that do and do not serve its lines. Every case is short (``TMax`` 1 s, the +mid-run case 60 s) and its grid small (``WaveTMax`` 200 s), so the whole set needs well under +1 GB. + +Cases that must STOP by default (``waveGridCheck error``) and RUN with ``waveGridCheck warn``: + + outside the MD_Shared grid (100 m half-widths, 40 m deep): nodes outside at t = 0; + ny2_oblique a grid covering the lines with NY = 2 under long-crested waves at 30 deg (line 1, which + lies along y = 0, is reported with the others); + ny2_short the same grid under a short-crested sea (WaveDirMod 1, 5 directions over 60 deg); + midrun one 178 m chain from a platform point at x = 58 m to an anchor 176 m below and + 18 m inboard, the platform's only line, on a grid 2 m wider in x than that point: + the platform drifts down-wave (+x, about 8 m in 60 s) and carries nodes out during + the run, which stops at t > 0. + + ext_oblique the covering grid with NY = 2 under supplied kinematics (WaveMod 6, HydroDyn PotMod 0) + of a wave at 30 deg, with WaveDir left at 0 (unused in that mode): judged from the data. + +Cases that must RUN by default, with no guard message: + + ny2_along_x the covering grid with NY = 2 under waves at 0 deg (the tutorial grid); + nx2_along_y NX = 2, NY = 37 under waves at 90 deg; + ext_along_x the covering grid with NY = 2 under supplied kinematics of a wave at 0 deg. + +Each stopping case's message must name the time, a line, the node count, the deepest and the +shallowest node, and the option that downgrades it. With ``--base-exe`` (a reference openfast.exe +with the same grid sampling: a build at or after the commit that samples the grid at the positions +of the sample time; an earlier build samples a mooring step behind and differs by design), the two +running cases and the ``outside`` and ``ny2_oblique`` cases under ``warn`` must give the same +``.out`` and ``.CD.out`` data rows as that build, byte for byte: the guard and its record do not +change a result. + +usage: openfast_wave_grid_guard.py --exe --case-dir + --work [--base-exe ] +""" + +from __future__ import annotations + +import argparse +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" + +COVER = {"X_HalfWidth": "900", "Y_HalfWidth": "900", "Z_Depth": '"default"', "NX": "37", "NY": "2", "NZ": "11"} +LIGHT = {"WaveTMax": "200"} +# WaveMod 6 reads WaveTMax/WaveDT + 1 records of the whole grid from text files; keep them small +EXTERNAL = {"WaveMod": "6", "WaveTMax": "20", "WaveDT": "0.25", "WvKinFile": '"ext/wave"'} + +HANGING_DECK = """--------------------- CableDyn Input File ------------------------------------ +One chain from a point of the IEA-15 MW UMaine platform at x = 58 m to an anchor below it (wave-grid guard) +--------------------------- LINE TYPES ---------------------------------------- +Name Diam Mass EA BA EI Cdn Cdt Can Cat +(-) (m) (kg/m) (N) (-) (Nm2) (-) (-) (-) (-) +main 0.333 685.00 3.27e9 -1.0 0.0 2.0 0.4 0.82 0.27 +--------------------------- POINTS -------------------------------------------- +ID Type X Y Z +(-) (-) (m) (m) (m) +1 Coupled 58.000 0.000 -14.000 +2 Fixed 40.000 0.000 -190.000 +--------------------------- LINES --------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 1 2 - +--------------------------- SECTIONS ------------------------------------------ +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 main 178.0 30 +--------------------------- OPTIONS ------------------------------------------- +3.0e6 kBot - Seabed penalty stiffness base (Pa/m) +3.0e5 cBot - Seabed normal damping base (Pa-s/m) +0.025 dtM - CableDyn internal time step (s) +--------------------------- OUTPUTS ------------------------------------------- +"FairTen1" +END +--------------------------- need this line ------------------------------------ +""" + +# case: (SeaState edits, deck, TMax, stops by default) +CASES = { + "outside": ({**LIGHT}, DECK, 1.0, True), + "ny2_oblique": ({**COVER, **LIGHT, "WaveDir": "30"}, DECK, 1.0, True), + "ny2_short": ( + {**COVER, **LIGHT, "WaveDirMod": "1", "WaveDirSpread": "1", "WaveNDir": "5", "WaveDirRange": "60"}, + DECK, + 1.0, + True, + ), + "midrun": ( + {**LIGHT, "X_HalfWidth": "60", "Y_HalfWidth": "60", "Z_Depth": '"default"', "NX": "7", "NY": "7", "NZ": "11"}, + "hanging.dat", + 60.0, + True, + ), + "ny2_along_x": ({**COVER, **LIGHT}, DECK, 1.0, False), + "nx2_along_y": ({**COVER, **LIGHT, "NX": "2", "NY": "37", "WaveDir": "90"}, DECK, 1.0, False), + # supplied kinematics (WaveMod 6, written by write_external): SeaState does not use WaveDir in + # this mode, so the guard judges the grid from the data; WaveDir is left at 0 on purpose + "ext_oblique": ({**COVER, **EXTERNAL}, DECK, 1.0, True), + "ext_along_x": ({**COVER, **EXTERNAL}, DECK, 1.0, False), +} +# the direction (deg) of the long-crested wave written into each WaveMod 6 case's files +EXTERNAL_DIR = {"ext_oblique": 30.0, "ext_along_x": 0.0} +BIT_IDENTICAL = [("ny2_along_x", "error"), ("nx2_along_y", "error"), ("outside", "warn"), ("ny2_oblique", "warn")] + + +def set_value(path: Path, key: str, value: str) -> None: + """Replace the value of the one row `` ...`` of an OpenFAST input file.""" + lines = path.read_text(encoding="latin-1").splitlines() # byte for byte + 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 write_external(folder: Path, direction_deg: float) -> None: + """The WaveMod 6 files of a long-crested Airy wave (1 m amplitude, 10 s, travelling at + ``direction_deg``) on the COVER grid, in SeaState's layout: 13 header lines, then for every + time step, depth level (z = (cos(k dtheta) - 1) Z_Depth) and y, one row of the x values.""" + depth, half = 200.0, 900.0 + nx, ny, nz = int(COVER["NX"]), int(COVER["NY"]), int(COVER["NZ"]) + tmax, dt = float(EXTERNAL["WaveTMax"]), float(EXTERNAL["WaveDT"]) + xs = [-half + i * half / (nx - 1) for i in range(2 * nx - 1)] + ys = [-half + j * half / (ny - 1) for j in range(2 * ny - 1)] + dth = math.pi / (2 * (nz - 1)) + zs = [(math.cos(k * dth) - 1.0) * depth for k in range(nz)] + omega = 2.0 * math.pi / 10.0 + k_wave = omega**2 / 9.80665 # omega^2 = g k tanh(k h), by fixed point + for _ in range(50): + k_wave = omega**2 / (9.80665 * math.tanh(k_wave * depth)) + cb, sb = math.cos(math.radians(direction_deg)), math.sin(math.radians(direction_deg)) + steps = round(tmax / dt) + out = folder / "ext" + out.mkdir() + header = [f"wave-grid guard test: Airy wave at {direction_deg} deg"] + ["-"] * 12 + + def phase(t: float, x: float, y: float) -> float: + return omega * t - k_wave * (x * cb + y * sb) + + def rows(name: str) -> list[str]: + lines = [] + for m in range(steps + 1): + for z in zs: + ch = math.cosh(k_wave * (z + depth)) / math.sinh(k_wave * depth) + sh = math.sinh(k_wave * (z + depth)) / math.sinh(k_wave * depth) + cp = 1025.0 * 9.80665 * math.cosh(k_wave * (z + depth)) / math.cosh(k_wave * depth) + for y in ys: + values = [] + for x in xs: + p = phase(m * dt, x, y) + # u = omega ch cos p (along the heading), w = omega sh sin p + value = { + "Vxi": omega * ch * math.cos(p) * cb, + "Vyi": omega * ch * math.cos(p) * sb, + "Vzi": omega * sh * math.sin(p), + "Axi": -(omega**2) * ch * math.sin(p) * cb, + "Ayi": -(omega**2) * ch * math.sin(p) * sb, + "Azi": omega**2 * sh * math.cos(p), + "DynP": cp * math.cos(p), + }[name] + values.append(f"{value:.7e}") + lines.append(" ".join(values)) + return lines + + for name in ("Vxi", "Vyi", "Vzi", "Axi", "Ayi", "Azi", "DynP"): + (out / f"wave.{name}").write_text("\n".join(header + rows(name)) + "\n", encoding="ascii") + elev = [ + " ".join(f"{math.cos(phase(m * dt, x, y)):.7e}" for x in xs) for m in range(steps + 1) for y in ys + ] + (out / "wave.Elev").write_text("\n".join(header + elev) + "\n", encoding="ascii") + + +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}{suffix}" + 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 edits.items(): + set_value(folder / SS, key, value) + if name in EXTERNAL_DIR: # SeaState refuses WaveMod 6 with potential flow + set_value(folder / HD, "PotMod", "0") + write_external(folder, EXTERNAL_DIR[name]) + shutil.copy(ROOT / "examples/openfast/IEA-15-UMaine_CompMooring5_CableDyn.fst", folder / FST) + set_value(folder / FST, "TMax", str(tmax)) + if deck == DECK: + text = (ROOT / "examples/openfast" / DECK).read_text(encoding="utf-8") + else: + text = HANGING_DECK + set_value(folder / FST, "MooringFile", f'"{deck}"') + if mode == "warn": + text = re.sub(r"(?m)^(\S+\s+dtM\b.*)$", r"\1\nwarn waveGridCheck - downgrade the wave-grid guard", text, count=1) + (folder / deck).write_text(text, encoding="ascii") + return folder + + +def run(exe: Path, folder: Path) -> tuple[int, str]: + proc = subprocess.run([str(exe), FST], cwd=folder, capture_output=True, text=True, errors="replace") + return proc.returncode, proc.stdout + proc.stderr + + +def data_rows(path: Path) -> list[str]: + """The rows of an output table from its 'Time' header on (the preamble names the build).""" + lines = path.read_text(encoding="utf-8", errors="replace").splitlines() + start = next((i for i, line in enumerate(lines) if line.split()[:1] == ["Time"]), 0) + return lines[start:] + + +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) + parser.add_argument("--base-exe", type=Path) + args = parser.parse_args() + args.work.mkdir(parents=True, exist_ok=True) + failures: list[str] = [] + + for name, (_, deck, _, stops) in CASES.items(): + for mode in ("error", "warn") if stops else ("error",): + folder = prepare(args.case_dir, args.work, name, mode) + code, log = run(args.exe, folder) + (folder / "run.log").write_text(log, encoding="utf-8") + log = " ".join(log.split()) # OpenFAST wraps the messages + guard = re.search(r"CableDyn mooring module: (\d+ of the \d+ CableDyn sampling nodes|the SeaState wave-kin)", log) + tag = f"{name} [{mode}]" + if stops and mode == "error": + ok = code != 0 and guard is not None and "waveGridCheck warn" in log + ok = ok and re.search(r"line \d+, \d+ nodes?, (deepest at|at) \(x, y, z\)", log) is not None + if name != "midrun" and "lie outside" in log: + ok = ok and "at t = 0 s" in log + if name == "midrun": + times = [float(t) for t in re.findall(r"wave-kinematics grid at t = ([0-9.Ee+-]+) s", log)] + ok = ok and bool(times) and times[0] > 0.0 + if name.startswith("ny2") or name == "ext_oblique": + # every line sampling the grid in the water counts, line 1 along y = 0 too + ok = ok and "NY = 2 (3 points" in log and "line 1, 51 nodes" in log + if name == "ext_oblique": + ok = ok and "externally supplied wave kinematics (WaveMod 6)" in log + if name == "outside": + ok = ok and "shallowest at" in log + print(f"{tag:22s} exit {code}: {'stops as required' if ok else 'FAIL'}") + elif stops: + ok = code == 0 and "OpenFAST terminated normally" in log and guard is not None + print(f"{tag:22s} exit {code}: {'runs with the warning' if ok else 'FAIL'}") + else: + ok = code == 0 and "OpenFAST terminated normally" in log and guard is None + print(f"{tag:22s} exit {code}: {'runs, no guard message' if ok else 'FAIL'}") + if not ok: + failures.append(tag) + print(" ..." + log[-2000:]) + + if args.base_exe: + for name, mode in BIT_IDENTICAL: + new = args.work / f"{name}_{mode}" + 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", + ) + 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"): + a, b = new / f"case{suffix}", base / f"case{suffix}" + same = same and a.exists() and b.exists() and data_rows(a) == data_rows(b) + tag = f"{name} [{mode}] vs base" + print(f"{tag:22s} {'bit-identical data rows' if same else 'FAIL: differs'}") + if not same: + failures.append(tag) + + if failures: + print("FAIL: " + ", ".join(failures)) + return 1 + print("PASS: the wave-grid guard stops, warns and passes as required") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) 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())