From ea15cff246583b0994e8b991d9ba1e87f9cae344 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 28 Oct 2026 06:31:48 +0900 Subject: [PATCH 1/4] fix(driver): TMax = 0 checks the static start of any dynamic deck Checking the static start of a dynamic deck meant editing it down: with dtM and TMax removed, the deck stopped on its first dynamic input with a message about a dynamic run, and with TMax = 0 a RangeStart or a motion record longer than the run was refused. Now: - motionFile (point and TURBINES rows) and vesselMotion records may run past TMax. Rows after TMax are parsed, range-checked and placed on the dtM grid (to 100 eps max(1, t)), and are not used, so a long record also serves a shorter run. Off-grid rows and rows before 0 are still refused. - RangeStart is accepted at TMax = 0, where the range graphs hold the t = 0 row; after a TMax > 0 it is still refused. - A standalone deck without TMax whose error asks for dtM and TMax (or for a dynamic deck) ends with "to check a dynamic deck's static start only, give dtM with TMax = 0", in the driver and in the Python deck validator. Every shipped dynamic example runs at TMax = 0. On both shipped motion-record decks, a 1 s run on the 36 s record writes the same output, byte for byte, as one on the record cut to 1 s (static_check). A TURBINES record 2 s longer than TMax gives the same run (shared_anchor). Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 7 ++ CMakeLists.txt | 12 +++ doc/driver_format.md | 7 +- doc/file_formats.rst | 9 ++- doc/modeling.rst | 3 +- doc/options.rst | 7 +- doc/troubleshooting.rst | 9 ++- python/cabledyn/deck_file.py | 24 +++++- python/tests/test_deck_file.py | 9 ++- src/CableDyn_DeckDriver.f90 | 69 +++++++++++----- tests/test_shared_anchor.f90 | 14 +++- tests/test_static_check.py | 142 +++++++++++++++++++++++++++++++++ 12 files changed, 270 insertions(+), 42 deletions(-) create mode 100644 tests/test_static_check.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 6af9ee14..ad7ea169 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -53,6 +53,13 @@ All notable changes to CableDyn are recorded in this file. The format follows ### Changed +- `TMax = 0` checks the static start of any dynamic deck as it stands: a `motionFile` or + `vesselMotion` record may run past `TMax` (its later rows are checked on the `dtM` grid and + not used, so a long record also serves a shorter run), and `RangeStart` is accepted at + `TMax = 0`, where the range graphs hold the `t = 0` row. A standalone deck without `TMax` that + asks for the march now says so: its error ends "to check a dynamic deck's static start only, + give dtM with TMax = 0". + - Under a bend stiffener, `BendMomN` (and the `BendMoment` columns of the static profile, range graphs and element file) report the cable's own moment, the line type's EI times the curvature; lines without stiffeners are unchanged. diff --git a/CMakeLists.txt b/CMakeLists.txt index 163a0b51..0409e213 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1613,6 +1613,18 @@ if(Python3_Interpreter_FOUND) message(STATUS "range_graph_tdp: skipped (numpy not importable in ${Python3_EXECUTABLE})") endif() + # TMax = 0 checks the static start of a dynamic deck: vesselMotion and motionFile records + # that outlast TMax, RangeStart at TMax = 0, and the hint of a deck without dtM and TMax. + add_test(NAME static_check + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_static_check.py + --exe $ + --examples ${CMAKE_CURRENT_SOURCE_DIR}/examples + --output ${CMAKE_BINARY_DIR}/static_check) + set_tests_properties(static_check PROPERTIES + LABELS "python;driver;integration;static;dynamic" + TIMEOUT 600 + ENVIRONMENT "${_cabledyn_python_test_environment}") + # Anchor uplift channels (AnchFz/AnchFH, TDPGrd): the analytic laid and suspended elastic # catenaries, the Point

F identity on every standalone route, and a surge that lifts the # anchor of a catenary (needs numpy). diff --git a/doc/driver_format.md b/doc/driver_format.md index 14bf2e29..82c34340 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -1261,7 +1261,8 @@ about the line tangent pointing into the line from that end. Either way it impos (where the inward tangent is `Ez`) and the opposite sense to `Pretwist(B)` at End B (where it is `−Ez`). The roll is 0 at `t = 0` and is given on every row of the point or on none. Header lines must be comments. `time` must -lie on the `0, dtM, 2·dtM, …, TMax` grid and `point_id` must be a prescribed point. Each +lie on the `0, dtM, 2·dtM, …` grid (rows after `TMax` are read and not used) and `point_id` must be +a prescribed point. Each (point, time) pair appears once, every prescribed point needs a row at every grid time, and rows may appear in any order. See also [Auxiliary file formats](file_formats.rst). @@ -1287,8 +1288,8 @@ moment follows the vessel rotation. Rotations use the OrcaFlex vessel convention: `R = Rz(yaw)·Ry(pitch)·Rx(roll)`, right-handed about the vessel x (roll), y (pitch) and z (yaw) axes, applied yaw, then pitch, then roll. -**`vesselMotion` record.** One row per `dtM` grid time from 0 to `TMax`, in any order, in one -of two forms for the whole file: +**`vesselMotion` record.** One row per `dtM` grid time from 0 to `TMax`, in any order (rows on +the grid after `TMax` are read and not used), in one of two forms for the whole file: ```text time x y z roll pitch yaw vx vy vz wx wy wz ax ay az alx aly alz (19 values) diff --git a/doc/file_formats.rst b/doc/file_formats.rst index 4915efae..7c2e37a3 100644 --- a/doc/file_formats.rst +++ b/doc/file_formats.rst @@ -211,10 +211,11 @@ The model grid is ``t_k = k·dtM`` for ``k = 0 … TMax/dtM``, and ``TMax`` must whole multiple of ``dtM``. The file is checked against this grid: * Each ``time`` must match a grid time to within ``100·ε·max(1, TMax)``, where ε is - double-precision machine epsilon. Times off the grid, before ``0``, or after - ``TMax`` are rejected (``time is outside the dtM/TMax grid``). Write times with - enough digits to hit the grid exactly. A file that runs past ``TMax`` must be cut - to length. + double-precision machine epsilon. Times off the grid or before ``0`` are rejected + (``time is outside the dtM/TMax grid``). Write times with enough digits to hit the + grid exactly. A file may run past ``TMax``: its rows after ``TMax`` are checked + (on the ``dtM`` grid, to within ``100·ε·max(1, time)``) and not used, so a long + record serves a shorter run and ``TMax = 0`` checks the static start. * Every eligible point needs exactly one row at every grid time. A repeated point/time pair is rejected (``duplicate row for point at this time``). A missing pair is rejected once the whole file has been read (``motionFile must diff --git a/doc/modeling.rst b/doc/modeling.rst index 46d7e51a..a7c00699 100644 --- a/doc/modeling.rst +++ b/doc/modeling.rst @@ -199,7 +199,8 @@ resolves the wave a snap does not trigger them, and at 0.5 ms the cable takes no Begin with the smallest model that should equilibrate: -#. omit ``dtM``/``TMax`` for an ``EI = 0`` static-only checkout; +#. omit ``dtM``/``TMax`` for an ``EI = 0`` static-only checkout, or set ``TMax = 0`` to check + the static start of a dynamic deck with all its other options; #. verify endpoint order, length, submerged weight, and seabed elevation; #. request endpoint tensions and the static along-arc profile; #. inspect contact, touchdown, curvature, and symmetry; then diff --git a/doc/options.rst b/doc/options.rst index 0783b8a3..0766cedf 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -269,14 +269,17 @@ Clock and initial condition - real, s - absent (static-only) - finite, ≥ 0 and an integer multiple of ``dtM``. ``TMax = 0`` runs the dynamic - initialisation and writes the ``t = 0`` row + initialisation and writes the ``t = 0`` row: the static start of a dynamic deck, checked + with every other option kept (motion records longer than ``TMax`` and a later + ``RangeStart`` included) - standalone only; OpenFAST uses the host ``TMax``. Do not copy the host duration into a coupled deck - ``600.0 TMax`` * - ``RangeStart`` / ``range_start`` - real, s - ``0`` - - finite, ≥ 0 and ≤ ``TMax``. First output time accumulated into the range graphs + - finite, ≥ 0 and ≤ ``TMax`` (any value at ``TMax = 0``, where the graphs hold the + ``t = 0`` row). First output time accumulated into the range graphs (``.Line.range.out``, ``LINES`` ``Outputs`` flag ``r``), so a start-up transient is left out. Needs ``TMax`` and at least one line with the ``r`` flag - standalone only diff --git a/doc/troubleshooting.rst b/doc/troubleshooting.rst index 92b59cfb..5ebb7d05 100644 --- a/doc/troubleshooting.rst +++ b/doc/troubleshooting.rst @@ -199,8 +199,13 @@ Clock, motion, and environment - a deck that mixes ``EI = 0`` and finite-EI lines writes no modal files. Run the modal analysis on a deck whose lines are all ``EI = 0`` or all finite-EI. * - motionFile ``time is outside the dtM/TMax grid`` - - every row time must be ``k·dtM`` for ``0 ≤ k ≤ TMax/dtM``. Resample the history onto the - ``dtM`` grid. + - every row time must be ``k·dtM`` with ``k ≥ 0`` (rows after ``TMax`` are not used). + Resample the history onto the ``dtM`` grid. + * - ``... requires dtM and TMax; to check a dynamic deck's static start only, give dtM with + TMax = 0`` + - the deck asks for the march (motion, current, waves, bodies, rods, finite-EI sections, + ``RangeStart`` ...) without ``TMax``. Keep the deck and set ``TMax = 0``: the run solves + the static start and writes the ``t = 0`` row. * - ``motionFile must provide every Coupled/Vessel point at every dtM time`` (or ``every eligible prescribed point``) - the file is missing at least one (point, time) pair. Every prescribed point needs a row at diff --git a/python/cabledyn/deck_file.py b/python/cabledyn/deck_file.py index 24fb33c1..7ade3115 100644 --- a/python/cabledyn/deck_file.py +++ b/python/cabledyn/deck_file.py @@ -321,6 +321,10 @@ _DISABLED_MOTION_FILE_VALUES = frozenset({"0", "none"}) # Alternative prescribed-motion sources (native apply_option): only one may be active. _MOTION_SOURCE_KEYWORDS = ("motionfile", "vesselmotion", "vesselrao") +# Native STATIC_CHECK_HINT: appended to the errors that ask a standalone deck without TMax for +# the march (those naming one of the cues). +_STATIC_CHECK_HINT = "; to check a dynamic deck's static start only, give dtM with TMax = 0" +_STATIC_CHECK_CUES = ("dtM and TMax", "requires dtM", "require dtM", "dynamic deck (TMax)") _END_CONNECTION_ENDS = { "a": "a", "enda": "a", @@ -2335,6 +2339,20 @@ def validate(self) -> None: DeckFormatError If the deck violates the native deck contract. """ + try: + self._validate() + except DeckFormatError as exc: + if self.caller_driven or not any(cue in str(exc) for cue in _STATIC_CHECK_CUES): + raise + # native finalize_and_validate: a standalone deck without TMax that asks for the + # march is told how to check its static start + try: + self.option("TMax") + except KeyError: + raise DeckFormatError(f"{exc}{_STATIC_CHECK_HINT}") from None + raise + + def _validate(self) -> None: required = {"LINE TYPES", "POINTS", "LINES"} if not self._rows("LINES") and (self._rows("RODS") or self._rows("BODIES")): # native finalize_and_validate: a deck whose rows declare bodies or rods and @@ -3929,9 +3947,9 @@ def is_body_kind(kind: str, pinned: bool) -> bool: raise DeckFormatError( f"{self._label}: OPTION RangeStart needs a dynamic deck (TMax)" ) - if _native_float(range_start.values[0]) > _native_float( - option_by_key["tmax"].values[0] - ): + tmax_value = _native_float(option_by_key["tmax"].values[0]) + # at TMax = 0 (a dynamic deck's static start) the range graphs hold the t = 0 row + if _native_float(range_start.values[0]) > tmax_value and tmax_value > 0.0: raise DeckFormatError( f"{self._label}: OPTION RangeStart exceeds TMax: the range window would hold " "no output time" diff --git a/python/tests/test_deck_file.py b/python/tests/test_deck_file.py index d1452838..063253ea 100644 --- a/python/tests/test_deck_file.py +++ b/python/tests/test_deck_file.py @@ -1825,7 +1825,7 @@ def test_active_friction_clock_dependency_is_route_aware(tmp_path): path = tmp_path / "route-friction.dat" path.write_text(source, encoding="utf-8") - with pytest.raises(DeckFormatError, match="frictionMu requires dtM and TMax"): + with pytest.raises(DeckFormatError, match=r"frictionMu requires dtM and TMax.*TMax = 0"): DeckFile.read(path) DeckFile.read(path, caller_driven=True) @@ -1862,8 +1862,10 @@ def test_host_route_does_not_relax_deck_owned_kinematics_clock(tmp_path, option_ path.write_text(source, encoding="utf-8") for caller_driven in (False, True): - with pytest.raises(DeckFormatError, match=message): + with pytest.raises(DeckFormatError, match=message) as err: DeckFile.read(path, caller_driven=caller_driven) + # the standalone error says how to check the deck's static start; the host route's not + assert ("give dtM with TMax = 0" in str(err.value)) is not caller_driven def test_current_needs_the_deck_clock_only_on_the_standalone_route(tmp_path): @@ -2470,6 +2472,9 @@ def test_range_flag_and_range_start_follow_native_rules(): DeckFile.from_text(_edit(_DYNAMIC, ("10.0 TMax\n", "10.0 TMax\n2.5 RangeStart\n"))) with pytest.raises(DeckFormatError, match="exceeds TMax"): DeckFile.from_text(_edit(ranged, ("2.5 RangeStart", "12.0 RangeStart"))) + # TMax = 0 checks the static start of the dynamic deck: its range graphs hold the t = 0 row + zero = DeckFile.from_text(_edit(ranged, ("10.0 TMax", "0.0 TMax"))) + assert zero.option("RangeStart").values == ("2.5",) with pytest.raises(DeckFormatError, match="must be >= 0"): DeckFile.from_text(_edit(ranged, ("2.5 RangeStart", "-1.0 RangeStart"))) with pytest.raises(DeckFormatError, match="needs a dynamic deck"): diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index a60b4dc4..7bf2a723 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -318,6 +318,11 @@ MODULE CableDyn_DeckDriver CHARACTER(*), PARAMETER :: ROW_VALUES_FMT = TIME_COLUMN_FMT(1:LEN(TIME_COLUMN_FMT) - 1)//',*(A,ES15.7E3))' ! Largest step count a dtM/TMax (or motion-file) grid may index with default INTEGER. REAL(wp), PARAMETER :: MAX_GRID_STEPS = REAL(HUGE(1) - 1, wp) + ! motion_grid_index of a record row on the dtM grid after TMax (read, then not used) + INTEGER, PARAMETER :: MOTION_PAST_TMAX = -1 + ! appended to the dtM/TMax-required errors of a standalone deck without TMax + CHARACTER(*), PARAMETER :: STATIC_CHECK_HINT = & + '; to check a dynamic deck''s static start only, give dtM with TMax = 0' INTEGER, PARAMETER :: MOTION_POINT_ROWS = 0, MOTION_VESSEL_FILE = 1, MOTION_VESSEL_RAO = 2 ! Largest WaterKin WaveKinMod-1 record (TMax/dtWave samples) reduced to Fourier components. REAL(wp), PARAMETER :: MAX_WAVE_SAMPLES = 1.0e6_wp @@ -8222,7 +8227,7 @@ SUBROUTINE run_deck_driver(deck_path, out_root, converged, ErrStat, ErrMsg) ! reserve-point detach machinery. Every other branch fails closed by name. IF (SIZE(fails) > 0) THEN IF (.NOT. (opts%has_dtm .AND. opts%has_tmax)) THEN - CALL fail(ErrStat, ErrMsg, 'FAILURE requires a dynamic deck (dtM and TMax)'); RETURN + CALL fail(ErrStat, ErrMsg, 'FAILURE requires a dynamic deck (dtM and TMax)'//STATIC_CHECK_HINT); RETURN END IF IF (deck_has_finite_ei(types, sections)) THEN CALL fail(ErrStat, ErrMsg, 'FAILURE is not supported on finite-EI decks'); RETURN @@ -11227,7 +11232,7 @@ SUBROUTINE solve_one_line(ln, sections, types, points, opts, q, tension, converg IF (sections(j)%line_id /= ln%id) CYCLE IF (types(sections(j)%ltype)%is_syrope) THEN CALL fail(ErrStat, ErrMsg, 'a Syrope line has no static output; provide dtM and TMax to run the '// & - 'dynamic working-curve path'); RETURN + 'dynamic working-curve path'//STATIC_CHECK_HINT); RETURN END IF END DO @@ -15807,6 +15812,11 @@ SUBROUTINE finalize_and_validate(types, bodies, rod_types, rods, points, lines, CALL finalize_checks(types, bodies, rod_types, rods, points, lines, sections, opts, channels, & caller_driven, allow_static_finite_ei, ErrStat, ErrMsg, channel_lines, at_line) + ! a standalone deck without TMax that asks for the march: say how to check its static start + IF (ErrStat /= 0 .AND. .NOT. caller_driven .AND. .NOT. opts%has_tmax) THEN + IF (INDEX(ErrMsg, 'dtM and TMax') > 0 .OR. INDEX(ErrMsg, 'dynamic deck (TMax)') > 0) & + ErrMsg = TRIM(ErrMsg)//STATIC_CHECK_HINT + END IF IF (ErrStat /= 0) CALL add_deck_line(at_line, ErrMsg) END SUBROUTINE finalize_and_validate @@ -15846,7 +15856,8 @@ SUBROUTINE finalize_checks(types, bodies, rod_types, rods, points, lines, sectio IF (.NOT. opts%has_tmax) THEN CALL fail(ErrStat, ErrMsg, 'OPTION RangeStart needs a dynamic deck (TMax)'); RETURN END IF - IF (opts%range_start > opts%tmax) THEN + ! at TMax = 0 (a dynamic deck's static start) the range graphs hold the t = 0 row + IF (opts%range_start > opts%tmax .AND. opts%tmax > CD_ZERO) THEN CALL fail(ErrStat, ErrMsg, 'OPTION RangeStart exceeds TMax: the range window would hold no output time') RETURN END IF @@ -31980,16 +31991,14 @@ SUBROUTINE read_motion_file(path, points, opts, motion, ErrStat, ErrMsg, include CALL add_row_context('motionFile', lineno, line, ErrMsg) RETURN END IF - it = 0 - IF (ABS(trow(1)/opts%dtM) < MAX_GRID_STEPS) it = NINT(trow(1)/opts%dtM) + 1 - grid_ok = it >= 1 .AND. it <= motion%n_time - IF (grid_ok) grid_ok = ABS(motion%time(it) - trow(1)) <= tol - IF (.NOT. grid_ok) THEN + it = motion_grid_index(trow(1), opts%dtM, motion, tol) + IF (it == 0) THEN CLOSE (unit) CALL fail(ErrStat, ErrMsg, 'time is outside the dtM/TMax grid') CALL add_row_context('motionFile', lineno, line, ErrMsg) RETURN END IF + IF (it == MOTION_PAST_TMAX) CYCLE IF (.NOT. ALLOCATED(turb_seen)) THEN ALLOCATE (turb_seen(SIZE(opts%turb_ref, 2), motion%n_time), STAT=ios) IF (ios /= 0) THEN @@ -32053,13 +32062,8 @@ SUBROUTINE read_motion_file(path, points, opts, motion, ErrStat, ErrMsg, include CALL add_row_context('motionFile', lineno, line, ErrMsg) RETURN END IF - ! Nested tests: Fortran does not guarantee short-circuit evaluation, so the time - ! index is range-checked before motion%time(it) is referenced. - it = 0 - IF (ABS(t/opts%dtM) < MAX_GRID_STEPS) it = NINT(t/opts%dtM) + 1 - grid_ok = it >= 1 .AND. it <= motion%n_time - IF (grid_ok) grid_ok = ABS(motion%time(it) - t) <= tol - IF (.NOT. grid_ok) THEN + it = motion_grid_index(t, opts%dtM, motion, tol) + IF (it == 0) THEN CLOSE (unit) CALL fail(ErrStat, ErrMsg, 'time is outside the dtM/TMax grid') CALL add_row_context('motionFile', lineno, line, ErrMsg) @@ -32078,6 +32082,7 @@ SUBROUTINE read_motion_file(path, points, opts, motion, ErrStat, ErrMsg, include CALL add_row_context('motionFile', lineno, line, ErrMsg) RETURN END IF + IF (it == MOTION_PAST_TMAX) CYCLE IF (seen(ip, it)) THEN CLOSE (unit) CALL fail(ErrStat, ErrMsg, 'duplicate row for point '//TRIM(int_to_str(pid))// & @@ -32192,7 +32197,6 @@ SUBROUTINE read_vessel_record(path, opts, motion, rref, vref, aref, ErrStat, Err INTEGER :: unit, ios, lineno, ntok, nform, row_status, it, off REAL(wp) :: row(20), tol, qn LOGICAL, ALLOCATABLE :: seen(:) - LOGICAL :: grid_ok ErrStat = CD_DECKDRV_OK; ErrMsg = '' ALLOCATE (seen(motion%n_time)) @@ -32239,16 +32243,14 @@ SUBROUTINE read_vessel_record(path, opts, motion, rref, vref, aref, ErrStat, Err CALL add_row_context('vesselMotion file', lineno, line, ErrMsg) RETURN END IF - it = 0 - IF (ABS(row(1)/opts%dtM) < MAX_GRID_STEPS) it = NINT(row(1)/opts%dtM) + 1 - grid_ok = it >= 1 .AND. it <= motion%n_time - IF (grid_ok) grid_ok = ABS(motion%time(it) - row(1)) <= tol - IF (.NOT. grid_ok) THEN + it = motion_grid_index(row(1), opts%dtM, motion, tol) + IF (it == 0) THEN CLOSE (unit) CALL fail(ErrStat, ErrMsg, 'time is outside the dtM/TMax grid') CALL add_row_context('vesselMotion file', lineno, line, ErrMsg) RETURN END IF + IF (it == MOTION_PAST_TMAX) CYCLE IF (seen(it)) THEN CLOSE (unit) CALL fail(ErrStat, ErrMsg, 'duplicate row at this time') @@ -33809,6 +33811,7 @@ SUBROUTINE range_setup(rset, lines, channels, opts, nnodes, by_id, ErrStat, ErrM LOGICAL, ALLOCATABLE :: want_r(:), want_t(:) INTEGER :: i, k, n, line_id, comp, es CHARACTER(1024) :: em + REAL(wp) :: t_start n = SIZE(nnodes) ALLOCATE (ids(n), want_r(n), want_t(n)) @@ -33831,7 +33834,10 @@ SUBROUTINE range_setup(rset, lines, channels, opts, nnodes, by_id, ErrStat, ErrM IF (.NOT. by_id) k = find_line(lines, line_id) IF (k >= 1 .AND. k <= n) want_t(k) = .TRUE. END DO - CALL CD_Range_Setup(rset, ids, nnodes, want_r, want_t, opts%range_start, opts%has_wtrdpth, -opts%wtrdpth, & + ! TMax = 0 (a static start check) puts the t = 0 row in the range graphs whatever RangeStart says + t_start = opts%range_start + IF (opts%has_tmax) t_start = MIN(t_start, opts%tmax) + CALL CD_Range_Setup(rset, ids, nnodes, want_r, want_t, t_start, opts%has_wtrdpth, -opts%wtrdpth, & es, em, bathymetry=bathymetry) CALL range_status(es, em, ErrStat, ErrMsg) IF (ErrStat /= CD_DECKDRV_OK .OR. .NOT. ALLOCATED(rset%lines)) RETURN @@ -37506,6 +37512,25 @@ SUBROUTINE grid_step_count(tmax, dt, nstep, ok) ok = .TRUE. END SUBROUTINE grid_step_count + INTEGER FUNCTION motion_grid_index(t, dt, motion, tol) RESULT(it) + !! Index of a record row's time t on the dtM grid motion%time (within tol), 0 when t is + !! off the grid or before 0, and MOTION_PAST_TMAX when t lies on the grid after TMax: a + !! record longer than the run is read to TMax, so TMax = 0 checks a dynamic deck's start. + REAL(wp), INTENT(IN) :: t, dt, tol + TYPE(MotionTable), INTENT(IN) :: motion + INTEGER :: k + it = 0 + IF (.NOT. ABS(t/dt) < MAX_GRID_STEPS) RETURN + k = NINT(t/dt) + IF (k < 0) RETURN + ! nested tests: Fortran does not short-circuit, so k is range-checked before motion%time + IF (k < motion%n_time) THEN + IF (ABS(motion%time(k + 1) - t) <= tol) it = k + 1 + ELSE IF (ABS(REAL(k, wp)*dt - t) <= 100.0_wp*EPSILON(CD_ONE)*MAX(CD_ONE, ABS(t))) THEN + it = MOTION_PAST_TMAX + END IF + END FUNCTION motion_grid_index + INTEGER FUNCTION scan_comment(buf) RESULT(p) !! First comment char to strip: `#`/`!` anywhere, or `--` only when it starts !! a whitespace-delimited comment. Section-header dash rules (`---`) survive. diff --git a/tests/test_shared_anchor.f90 b/tests/test_shared_anchor.f90 index f7bda633..badf4880 100644 --- a/tests/test_shared_anchor.f90 +++ b/tests/test_shared_anchor.f90 @@ -210,7 +210,7 @@ END SUBROUTINE check_fixed_anchor SUBROUTINE check_turbines_section() !! Turbine J at FAIR(:, J) - [0, 0, -10] with its fairlead at local (0, 0, -10); turbine 1 !! surges as write_motion's fairlead 1, written as a per-turbine record. - REAL(wp), ALLOCATABLE :: a(:, :), b(:, :) + REAL(wp), ALLOCATABLE :: a(:, :), b(:, :), c(:, :) INTEGER :: u, j LOGICAL :: ok @@ -268,6 +268,13 @@ SUBROUTINE check_turbines_section() CALL write_turbine_motion(0) CALL run('shared_turbines.dat', 'shared_turbines', 8, a, ok) IF (.NOT. ok) RETURN + ! a record that runs 2 s past TMax is read to TMax: the same run, bit for bit + CALL write_turbine_motion(5) + CALL run('shared_turbines.dat', 'shared_turbines_long', 8, c, ok) + IF (.NOT. ok) RETURN + CALL require(SIZE(c, 2) == SIZE(a, 2), 'TURBINES record longer than TMax: the run has TMax''s rows') + IF (SIZE(c, 2) /= SIZE(a, 2)) RETURN + CALL require(.NOT. MAXVAL(ABS(c - a)) > 0.0_wp, 'TURBINES record longer than TMax: rows after TMax unused') CALL write_deck('shared_anchor_all.dat', [.TRUE., .TRUE., .TRUE.], .FALSE., .TRUE., .TRUE.) CALL run('shared_anchor_all.dat', 'shared_anchor_all', 8, b, ok) IF (.NOT. ok) RETURN @@ -281,7 +288,8 @@ END SUBROUTINE check_turbines_section SUBROUTINE write_turbine_motion(variant) !! The per-turbine records; variant 1: J = 1.5 on the first row, 2: J = 4 (no such - !! TURBINES row), 3: q0 = 0.5 (not a unit quaternion), 4: turbine 2's first row twice. + !! TURBINES row), 3: q0 = 0.5 (not a unit quaternion), 4: turbine 2's first row twice, + !! 5: the record runs to 12 s, 2 s past the deck's TMax. INTEGER, INTENT(IN) :: variant CHARACTER(16) :: jtok INTEGER :: u, j, k @@ -289,7 +297,7 @@ SUBROUTINE write_turbine_motion(variant) OPEN (NEWUNIT=u, FILE='shared_turbines.motion', STATUS='REPLACE', ACTION='WRITE') WRITE (u, '(A)') '# time J x y z q0 q1 q2 q3 vx vy vz wx wy wz ax ay az alx aly alz' w = 2.0_wp*3.14159265358979323846_wp/20.0_wp - DO k = 0, 100 + DO k = 0, MERGE(120, 100, variant == 5) t = 0.1_wp*REAL(k, wp) DO j = 1, 3 x = FAIR(1, j) diff --git a/tests/test_static_check.py b/tests/test_static_check.py new file mode 100644 index 00000000..38036bcc --- /dev/null +++ b/tests/test_static_check.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""TMax = 0 checks the static start of a dynamic deck, and records may outlast TMax. + +Gates, on the shipped lazy-wave decks driven by a vesselMotion record and by a motionFile +(both 36 s records at dtM 0.05 s): + +* a run to TMax = 1 s on the full record writes the same output, byte for byte, as one on + the record cut to 1 s: rows after TMax are read and not used; +* a row after TMax that is off the dtM grid is still refused; +* TMax = 0 runs either deck, RangeStart 12 s included, and writes the t = 0 row of the + 1 s run, with the range graph of that row; +* RangeStart after a TMax > 0 is still refused; +* without dtM and TMax the deck stops on its first dynamic input, and the message says to + give dtM with TMax = 0. + +usage: test_static_check.py --exe --examples --output

+""" + +from __future__ import annotations + +import argparse +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +FAILURES: list[str] = [] +HINT = "to check a dynamic deck's static start only, give dtM with TMax = 0" + + +def check(ok: bool, message: str) -> None: + print(("PASS: " if ok else "FAIL: ") + message) + if not ok: + FAILURES.append(message) + + +def set_option(text: str, key: str, value: str | None) -> str: + """Set the value of OPTION ``key`` (``None`` removes the row).""" + pattern = re.compile(r"^\s*\S+\s+" + key + r"\b.*$", re.M | re.I) + assert len(pattern.findall(text)) == 1, key + return pattern.sub("" if value is None else f"{value} {key}", text) + + +def cut_record(src: Path, dst: Path, tmax: float) -> None: + """Copy a motion record keeping its comments and the rows up to tmax.""" + keep = [line for line in src.read_text().splitlines() + if line.lstrip().startswith("#") or not line.strip() or float(line.split()[0]) <= tmax + 1e-9] + dst.write_text("\n".join(keep) + "\n") + + +def run(exe: str, cwd: Path, name: str, text: str) -> subprocess.CompletedProcess: + (cwd / f"{name}.dat").write_text(text, encoding="utf-8", newline="\n") + return subprocess.run([exe, f"{name}.dat", name], cwd=cwd, capture_output=True, text=True, + env=dict(os.environ, OMP_NUM_THREADS="1")) + + +def data_rows(path: Path) -> list[str]: + lines = path.read_text().splitlines() + head = next(i for i, line in enumerate(lines) if line.startswith("Time")) + return [line for line in lines[head + 1:] if line.strip() and not line.lstrip().startswith("(")] + + +def case(exe: str, examples: Path, out: Path, deck_name: str, record: str, keyword: str) -> None: + work = out / deck_name + work.mkdir(parents=True) + text = (examples / f"{deck_name}.dat").read_text(encoding="utf-8") + src = examples / record + shutil.copy(src, work / "full.txt") + cut_record(src, work / "cut.txt", 1.0) + text = set_option(text, keyword, "full.txt") + if "RangeStart" not in text: + text = text.replace(f"full.txt {keyword}", f"full.txt {keyword}\n12.0 RangeStart", 1) + # line 1 writes its range graph (LINES ID NodeA NodeB Outputs) + text = re.sub(r"^(1\s+1\s+2\s+)\S+$", r"\1r", text, count=1, flags=re.M) + + one = set_option(set_option(text, "TMax", "1.0"), "RangeStart", "0.5") + p_full = run(exe, work, "full", one) + p_cut = run(exe, work, "cut", one.replace(f"full.txt {keyword}", f"cut.txt {keyword}")) + ok = p_full.returncode == 0 and p_cut.returncode == 0 + check(ok, f"{deck_name}: TMax = 1 s runs on the 36 s record and on the record cut to 1 s " + f"(exit {p_full.returncode}, {p_cut.returncode})") + if not ok: + print(p_full.stderr[-1500:], p_cut.stderr[-1500:]) + return + same = (work / "full.out").read_bytes() == (work / "cut.out").read_bytes() + check(same, f"{deck_name}: the run on the longer record writes the same output byte for byte") + + off = (work / "full.txt").read_text().splitlines() + last = next(line for line in reversed(off) if line.strip() and not line.startswith("#")).split() + last[0] = f"{float(last[0]) + 0.025:.3f}" + (work / "off.txt").write_text("\n".join(off + [" ".join(last)]) + "\n") + p_off = run(exe, work, "off", one.replace(f"full.txt {keyword}", f"off.txt {keyword}")) + check(p_off.returncode != 0 and "time is outside the dtM/TMax grid" in p_off.stderr, + f"{deck_name}: an off-grid row after TMax is refused") + + p_zero = run(exe, work, "zero", set_option(text, "TMax", "0.0")) + check(p_zero.returncode == 0, f"{deck_name}: TMax = 0 with RangeStart 12 s checks the static start " + f"(exit {p_zero.returncode})") + if p_zero.returncode != 0: + print(p_zero.stderr[-1500:]) + return + rows = data_rows(work / "zero.out") + check(len(rows) == 1 and rows[0] == data_rows(work / "full.out")[0], + f"{deck_name}: TMax = 0 writes the t = 0 row of the 1 s run") + graph = (work / "zero.Line1.range.out").read_text().splitlines() + check("1 samples from t =" in graph[0] and any(line[:1].isdigit() for line in graph), + f"{deck_name}: and the range graph of that row") + + p_late = run(exe, work, "late", set_option(one, "RangeStart", "2.0")) + check(p_late.returncode != 0 and "RangeStart exceeds TMax" in p_late.stderr, + f"{deck_name}: RangeStart after a TMax > 0 is still refused") + + p_none = run(exe, work, "none", set_option(set_option(text, "TMax", None), "dtM", None)) + check(p_none.returncode != 0 and HINT in p_none.stderr, + f"{deck_name}: without dtM and TMax the message says to give dtM with TMax = 0") + + +def main() -> int: + ap = argparse.ArgumentParser() + ap.add_argument("--exe", required=True) + ap.add_argument("--examples", required=True) + ap.add_argument("--output", required=True) + args = ap.parse_args() + out = Path(args.output) + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + examples = Path(args.examples) + case(args.exe, examples, out, "lazy_wave_vessel_motion", "data/vessel/vessel_surge_heave_pitch_12s_dt005.txt", + "vesselMotion") + case(args.exe, examples, out, "lozon_gomex80_power_cable_motion", "data/lozon/gomex80_heave_3m_12s_dt005.txt", + "motionFile") + print(f"{len(FAILURES)} failure(s)") + return 1 if FAILURES else 0 + + +if __name__ == "__main__": + sys.exit(main()) From d3d3ef6da1919022bcd633ac8a11508ce8336525 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 28 Oct 2026 15:03:00 +0900 Subject: [PATCH 2/4] perf(waves): faster elevation-record waves and WaveKinFile reading A WaterKin elevation history (WaveKinMod 1) is reduced to about TMax/(2 dtWave) Fourier components, up to the Nyquist frequency of dtWave: 600 for a 300 s run at 0.25 s, against the 200 of a jonswap sea. Every node summed all of them with a cos, a sin and two exps each, so a lazy-wave cable ran 2.9 times slower than with the jonswap option. CD_Component_Wave_Kinematics takes an optional tail_sums table: the sums over j >= i of a_j omega_j, a_j omega_j^2 and a_j omega_j^2/k_j, for a table whose k does not decrease. On -depth <= z' <= 0 both depth ratios fall as k grows, so the cosh ratio of the last summed component times the tail sums bounds the rest of the velocity, acceleration and pressure sums; they stop once that bound is below half an ulp of the magnitude already summed. The elevation still sums every component. The sums run in blocks of 32 in component order, so without tail_sums the result is bit for bit the same, and the underflow fallback reuses the block's exponentials instead of recomputing two per component. The deck driver builds the table, and the exp(-2kd) table it already kept for jonswap, for the elevation-history components and for jonswap. On a 1024-element lazy-wave cable over 300 s, a record at dtWave 0.25 s runs in 103 s instead of 226 s and one at 0.1 s in 189 s instead of about 660 s, with output identical to the printed digits; the jonswap run changes in its eighth printed digit. Reading the WaveKinFile appended one row at a time, copying the whole record per row: a 10 s run on a 168,000-row record took 107 s. The rows now grow by doubling, and the same run takes 3.5 s. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 10 +- doc/file_formats.rst | 5 + doc/theory.rst | 13 ++ src/CableDyn_DeckDriver.f90 | 57 ++++++-- src/CableDyn_Hydro.f90 | 187 ++++++++++++++----------- tests/test_hermite_irregular_waves.f90 | 66 +++++++++ 6 files changed, 248 insertions(+), 90 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ad7ea169..f44cd557 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -59,7 +59,12 @@ All notable changes to CableDyn are recorded in this file. The format follows `TMax = 0`, where the range graphs hold the `t = 0` row. A standalone deck without `TMax` that asks for the march now says so: its error ends "to check a dynamic deck's static start only, give dtM with TMax = 0". - +- Deck waves from a WaterKin elevation history (`WaveKinMod 1`) run two to four times faster. + Below the surface, the velocity and acceleration sums stop once the components still to come, + too short to reach that depth, cannot change them beyond round-off. On a 1024-element lazy-wave + cable over 300 s, a record at `dtWave` 0.25 s (600 components) runs in 103 s instead of 226 s, + and one at 0.1 s in 189 s instead of about 660 s, with output identical to the printed digits. + A `jonswap` sea changes at round-off. - Under a bend stiffener, `BendMomN` (and the `BendMoment` columns of the static profile, range graphs and element file) report the cable's own moment, the line type's EI times the curvature; lines without stiffeners are unchanged. @@ -75,6 +80,9 @@ All notable changes to CableDyn are recorded in this file. The format follows ### Fixed +- Reading a WaterKin `WaveKinFile` no longer slows with the square of its length: the rows grow + by doubling instead of copying the whole record per row. A 10 s run on a 168,000-row record + took 107 s and now takes 3.5 s. - A weightless or near-neutral taut finite-EI line (a neutrally buoyant cable, a tendon) failed its static solve, even straight along its chord: the convergence test scaled the residual by the line's weight alone, far below the round-off of its axial forces. A taut line's scale now diff --git a/doc/file_formats.rst b/doc/file_formats.rst index 7c2e37a3..d029174d 100644 --- a/doc/file_formats.rst +++ b/doc/file_formats.rst @@ -564,6 +564,11 @@ two columns: * ``TMax / dtWave`` may be at most 10\ :sup:`6` samples; a longer record is rejected (``WaterKin TMax/dtWave needs more than 1000000 wave samples``) because the one-time reduction grows with the square of the sample count. +* The record gives about ``TMax / (2 dtWave)`` components, 600 for a 300 s run at + ``dtWave`` 0.25 s, against the 200 of a ``jonswap`` sea. Every node sums all of them for its + surface elevation. Below the surface, the components too short to reach the node's depth + are dropped once they cannot change its velocity and acceleration beyond round-off + (:ref:`theory-waves`). A coarser ``dtWave`` still shortens the run. Example ~~~~~~~ diff --git a/doc/theory.rst b/doc/theory.rst index 11c57108..5cc02c5a 100644 --- a/doc/theory.rst +++ b/doc/theory.rst @@ -828,6 +828,8 @@ configuration derivative in the tangent. The Hermite path evaluates the consiste holds it over the step. The spatial gradient of the wave field is omitted from the tangent on both paths; the residual is exact, so the converged state is unaffected. +.. _theory-waves: + Waves ~~~~~ @@ -892,6 +894,17 @@ commensurate, the record does not repeat (an equally spaced comb would repeat af its component table (amplitude, frequency, phase), for example a WaterKin ``WaveKinMod`` 1 elevation history, which is reduced once to its Fourier components on the run time base. +Every point sums every component of the elevation. The velocity, acceleration and dynamic +pressure sums run in order of increasing :math:`k_i`. For :math:`-h \le z' \le 0` both depth +ratios :math:`\cosh k(z' + h)/\sinh kh` and :math:`\sinh k(z' + h)/\sinh kh` fall as +:math:`k` grows, so the cosh ratio of the last summed component times the remaining +:math:`\sum_{j \ge i} a_j\omega_j`, :math:`\sum a_j\omega_j^2` and :math:`\sum a_j\omega_j^2/k_j` +bounds the rest of each sum. The sums stop once those bounds are below half an ulp of the +magnitudes already summed. A deep point therefore skips the short components that have +decayed to nothing there, and the result changes at round-off only. This matters for an +elevation history, whose :math:`T_{max}/(2\,\Delta t_{wave})` components reach the Nyquist +frequency of ``dtWave``. + **Regular nonlinear waves.** A ``stream`` wave is Dean's stream-function wave (:ref:`Dean, 1965 `) solved numerically by the Fourier method of :ref:`Rienecker & Fenton (1981) `. In the frame moving with the celerity diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 7bf2a723..74d7706a 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -581,6 +581,8 @@ MODULE CableDyn_DeckDriver REAL(wp) :: jonswap_k(CD_JONSWAP_COMPONENTS) = CD_ZERO ! exp(-2 jonswap_k wtrdpth), fixed with the table (CD_Component_Wave_Kinematics exp_m2kd) REAL(wp) :: jonswap_e2kd(CD_JONSWAP_COMPONENTS) = CD_ZERO + ! CD_Component_Wave_Kinematics tail_sums of the table (set_component_tail) + REAL(wp), ALLOCATABLE :: jonswap_tail(:, :) REAL(wp) :: jonswap_amplitude(CD_JONSWAP_COMPONENTS) = CD_ZERO ! Random-phase, bin-jittered JONSWAP synthesis (OPTION WaveSeed, a positive integer; ! the same seed always gives the same sea). @@ -615,6 +617,8 @@ MODULE CableDyn_DeckDriver ! irregular seas; wave_eta_mean carries the zero-frequency waterline offset. REAL(wp), ALLOCATABLE :: wave_component_omega(:), wave_component_k(:) REAL(wp), ALLOCATABLE :: wave_component_amplitude(:), wave_component_phase(:) + ! exp(-2 k (wtrdpth + wave_eta_mean)) and the tail_sums of the table (CD_Component_Wave_Kinematics) + REAL(wp), ALLOCATABLE :: wave_component_e2kd(:), wave_component_tail(:, :) REAL(wp) :: wave_eta_mean = CD_ZERO ! N-level vertical current profile (ascending z): from the two-point deck ! OPTION row or a MoorDyn WaterKin file's CurrentMod-1 depth table. @@ -12418,7 +12422,7 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma CHARACTER(1024) :: why REAL(wp) :: te_row(2), tr, dt, tol, angle, ca, sa, scale, frac REAL(wp) :: cos_step, sin_step, cos_j, sin_j, cos_next, trig_norm - REAL(wp), ALLOCATABLE :: times(:), eta_rows(:), sample_eta(:) + REAL(wp), ALLOCATABLE :: times(:), eta_rows(:), sample_eta(:), grown(:) LOGICAL :: data_started ErrStat = CD_DECKDRV_OK @@ -12438,7 +12442,9 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma CALL fail(ErrStat, ErrMsg, 'cannot open the WaterKin WaveKinFile: '//TRIM(path)// & input_open_reason(path, why)); RETURN END IF - ALLOCATE (times(0), eta_rows(0)) + ! the rows grow by doubling (appending one row at a time copies the whole record per row) + ALLOCATE (times(1024), eta_rows(1024)) + nraw = 0 data_started = .FALSE. lineno = 0 DO @@ -12463,11 +12469,21 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma CYCLE END IF data_started = .TRUE. - times = [times, te_row(1)] - eta_rows = [eta_rows, te_row(2)] + nraw = nraw + 1 + IF (nraw > SIZE(times)) THEN + ALLOCATE (grown(2*SIZE(times))) + grown(1:nraw - 1) = times(1:nraw - 1) + CALL MOVE_ALLOC(grown, times) + ALLOCATE (grown(2*SIZE(eta_rows))) + grown(1:nraw - 1) = eta_rows(1:nraw - 1) + CALL MOVE_ALLOC(grown, eta_rows) + END IF + times(nraw) = te_row(1) + eta_rows(nraw) = te_row(2) END DO CLOSE (unit) - nraw = SIZE(times) + times = times(1:nraw) + eta_rows = eta_rows(1:nraw) IF (nraw < 4) THEN CALL fail(ErrStat, ErrMsg, 'WaterKin WaveKinFile needs at least four `time elevation` rows'); RETURN END IF @@ -29101,7 +29117,7 @@ SUBROUTINE deck_wave_kinematics(opts, x, y, z, time, eta, velocity, acceleration opts%jonswap_omega, opts%jonswap_k, opts%jonswap_amplitude, & opts%jonswap_phase, eta, velocity, acceleration, ErrStat, ErrMsg, & inputs_validated=.TRUE., amplitude_scale=ramp, pdyn=pdyn, & - exp_m2kd=opts%jonswap_e2kd) + exp_m2kd=opts%jonswap_e2kd, tail_sums=opts%jonswap_tail) CASE (WAVE_SEA) CALL CD_Sea_Kinematics(opts%sea, x, y, z, time, opts%wtrdpth, ramp, eta, velocity, acceleration, & ErrStat, ErrMsg, pdyn) @@ -29115,14 +29131,16 @@ SUBROUTINE deck_wave_kinematics(opts, x, y, z, time, eta, velocity, acceleration opts%wave_component_omega, opts%wave_component_k, & opts%wave_component_amplitude, opts%wave_component_phase, & eta, velocity, acceleration, ErrStat, ErrMsg, inputs_validated=.TRUE., & - amplitude_scale=ramp, pdyn=pdyn) + amplitude_scale=ramp, pdyn=pdyn, exp_m2kd=opts%wave_component_e2kd, & + tail_sums=opts%wave_component_tail) ELSE CALL CD_Component_Wave_Kinematics(x, y, z - opts%wave_eta_mean, time, & opts%wtrdpth + opts%wave_eta_mean, opts%wave_direction, .TRUE., & opts%wave_component_omega, opts%wave_component_k, & opts%wave_component_amplitude, opts%wave_component_phase, & eta, velocity, acceleration, ErrStat, ErrMsg, inputs_validated=.TRUE., & - pdyn=pdyn) + pdyn=pdyn, exp_m2kd=opts%wave_component_e2kd, & + tail_sums=opts%wave_component_tail) END IF eta = eta + opts%wave_eta_mean CASE DEFAULT @@ -29488,6 +29506,7 @@ SUBROUTINE precompute_deck_wave(opts, ErrStat, ErrMsg) opts%wave_seed, opts%jonswap_omega, opts%jonswap_k, opts%jonswap_amplitude, & opts%jonswap_phase, ErrStat, ErrMsg) opts%jonswap_e2kd = EXP(-2.0_wp*(opts%jonswap_k*opts%wtrdpth)) + CALL set_component_tail(opts%jonswap_omega, opts%jonswap_k, opts%jonswap_amplitude, opts%jonswap_tail) CASE (WAVE_SEA) CALL CD_Sea_Synthesise(opts%sea, opts%wtrdpth, opts%g, opts%wave_seed, ErrStat, ErrMsg) CASE (WAVE_STREAM) @@ -29509,6 +29528,11 @@ SUBROUTINE precompute_deck_wave(opts, ErrStat, ErrMsg) opts%wave_component_k(k), ErrStat, ErrMsg) IF (ErrStat /= CD_DECKDRV_OK) EXIT END DO + IF (ErrStat == CD_DECKDRV_OK) THEN + opts%wave_component_e2kd = EXP(-2.0_wp*(opts%wave_component_k*(opts%wtrdpth + opts%wave_eta_mean))) + CALL set_component_tail(opts%wave_component_omega, opts%wave_component_k, opts%wave_component_amplitude, & + opts%wave_component_tail) + END IF CASE DEFAULT CALL fail(ErrStat, ErrMsg, 'unsupported wave kind during deck wave precompute') RETURN @@ -29520,6 +29544,23 @@ SUBROUTINE precompute_deck_wave(opts, ErrStat, ErrMsg) opts%wave_cache_ready = .TRUE. END SUBROUTINE precompute_deck_wave + SUBROUTINE set_component_tail(omega, k, amplitude, tail) + !! The tail_sums of CD_Component_Wave_Kinematics: tail(:, i) sums a_j omega_j, a_j omega_j^2 + !! and a_j omega_j^2/k_j over j >= i. Left unallocated (every component summed) unless k + !! does not decrease, which the bound needs. + REAL(wp), INTENT(IN) :: omega(:), k(:), amplitude(:) + REAL(wp), ALLOCATABLE, INTENT(OUT) :: tail(:, :) + INTEGER :: i, n + n = SIZE(k) + IF (n < 2) RETURN + IF (ANY(k(2:n) < k(1:n - 1))) RETURN + ALLOCATE (tail(3, n)) + tail(:, n) = amplitude(n)*[omega(n), omega(n)*omega(n), omega(n)*omega(n)/k(n)] + DO i = n - 1, 1, -1 + tail(:, i) = tail(:, i + 1) + amplitude(i)*[omega(i), omega(i)*omega(i), omega(i)*omega(i)/k(i)] + END DO + END SUBROUTINE set_component_tail + SUBROUTINE update_system_point_hydro(system, points, opts, time, work, ErrStat, ErrMsg) !! Update lumped Free/Connect point fluid kinematics for current and deck waves. TYPE(CD_SystemType), INTENT(INOUT) :: system diff --git a/src/CableDyn_Hydro.f90 b/src/CableDyn_Hydro.f90 index 1f4287b5..52d069f6 100644 --- a/src/CableDyn_Hydro.f90 +++ b/src/CableDyn_Hydro.f90 @@ -1939,7 +1939,7 @@ END SUBROUTINE CD_JONSWAP_Wave_Kinematics_Precomputed SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretch, & omega_comp, k_comp, amplitude, phase, & eta, velocity, acceleration, ErrStat, ErrMsg, inputs_validated, & - amplitude_scale, pdyn, exp_m2kd) + amplitude_scale, pdyn, exp_m2kd, tail_sums) !! Evaluate linear irregular-wave kinematics from a CALLER-SUPPLIED component table: !! the general (arbitrary length, explicit per-component phase) form of the fixed-size !! deterministic-phase JONSWAP evaluator above, sharing its conventions exactly -- @@ -1965,6 +1965,13 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc !! depend on the buffer. exp_m2kd is the caller's table of EXP(-2 k_comp(i) depth) for this !! depth (constant for a fixed table): it replaces the per-call exponential with the same !! value, so the result is bit-identical. + !! tail_sums(:, i) holds the sums over components j >= i of a_j omega_j, a_j omega_j^2 and + !! a_j omega_j^2/k_j, for a table whose k_comp does not decrease. On -depth <= z_eval <= 0 + !! both depth ratios fall as k grows, so the cosh ratio of the last summed component times + !! tail_sums bounds the rest of the velocity, acceleration and pressure sums. The sums stop + !! once that bound is below half an ulp of the magnitude already summed: a deep point drops + !! the short components that have decayed to nothing there, and the result changes at + !! round-off only. The elevation always sums every component. REAL(wp), INTENT(IN) :: x, y, z, t, depth, direction_deg LOGICAL, INTENT(IN) :: stretch REAL(wp), INTENT(IN) :: omega_comp(:), k_comp(:), amplitude(:), phase(:) @@ -1976,14 +1983,17 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc ! the linear dynamic pressure per unit density (sum over the components of ! (omega^2/k) a cosh(k(z+h))/sinh(kh) cos(theta)), as in CD_Airy_Wave_Kinematics_Precomputed REAL(wp), INTENT(OUT), OPTIONAL :: pdyn - REAL(wp), INTENT(IN), OPTIONAL :: exp_m2kd(:) - INTEGER :: i, n, nb, n_small - REAL(wp) :: omega, k, amp - REAL(wp) :: cb, sb, x_along, theta, z_eval, cosh_ratio, sinh_ratio - INTEGER, PARAMETER :: NBUF = 1024 - REAL(wp) :: scl, c_i, s_i, kd, kz, e_kz, e_neg2kd, e_neg, denom - REAL(wp) :: cth(NBUF), sth(NBUF), ch(NBUF), sh(NBUF) - LOGICAL :: trust_inputs, at_bed + REAL(wp), INTENT(IN), OPTIONAL :: exp_m2kd(:), tail_sums(:, :) + INTEGER :: i, n, nb, n_small, i0, j, nk + REAL(wp) :: amp + REAL(wp) :: cb, sb, x_along, theta, z_eval + ! the elevation keeps the cosines of the first NBUF components; the velocity sums run in + ! blocks of NBLK (NBUF a multiple of NBLK, so a block lies wholly inside or past the buffer) + INTEGER, PARAMETER :: NBUF = 1024, NBLK = 32 + REAL(wp), PARAMETER :: HALF_ULP = 0.5_wp*EPSILON(CD_ONE) + REAL(wp) :: scl, e_neg, denom + REAL(wp) :: cth(NBUF), bc(NBLK), bs(NBLK), ch(NBLK), sh(NBLK), mag(3), rest(3) + LOGICAL :: trust_inputs, at_bed, use_tail, small(NBLK) eta = CD_ZERO velocity = CD_ZERO @@ -2004,6 +2014,12 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc RETURN END IF END IF + IF (PRESENT(tail_sums)) THEN + IF (SIZE(tail_sums, 1) /= 3 .OR. SIZE(tail_sums, 2) /= n) THEN + CALL fail(ErrStat, ErrMsg, 'tail_sums must be shaped (3, n) for the component-wave arrays') + RETURN + END IF + END IF ! Fortran does not require short-circuit evaluation: keep the O(n) scans inside a ! separate branch so the setup-validated hot path portably skips them at -O0 too. IF (.NOT. trust_inputs) THEN @@ -2043,14 +2059,10 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc sb = SIN(direction_deg*DEG2RAD) x_along = x*cb + y*sb nb = MIN(n, NBUF) - ! Cosine and sine in separate loops: a compiler fuses COS and SIN of one argument into a - ! sincos call, which in the MinGW runtime costs several times a cos plus a sin. + ! the elevation sums every component (Wheeler stretching needs the total eta) DO i = 1, nb cth(i) = COS(k_comp(i)*x_along - omega_comp(i)*t + phase(i)) END DO - DO i = 1, nb - sth(i) = SIN(k_comp(i)*x_along - omega_comp(i)*t + phase(i)) - END DO DO i = 1, nb eta = eta + (scl*amplitude(i))*cth(i) END DO @@ -2072,78 +2084,91 @@ SUBROUTINE CD_Component_Wave_Kinematics(x, y, z, t, depth, direction_deg, stretc ELSE z_eval = z END IF - ! Depth-profile ratios of the buffered components: the expressions of profile_ratios, - ! with its seabed test (a function of z_eval and depth only) evaluated once. + ! Depth-profile ratios: the expressions of profile_ratios, with its seabed test (a function + ! of z_eval and depth only) evaluated once. at_bed = ABS(z_eval + depth) <= 8.0_wp*EPSILON(CD_ONE)*MAX(CD_ONE, depth, ABS(z_eval)) - IF (PRESENT(exp_m2kd)) THEN - DO i = 1, nb - ch(i) = EXP(k_comp(i)*z_eval) - sh(i) = exp_m2kd(i) - END DO - ELSE - DO i = 1, nb - ch(i) = EXP(k_comp(i)*z_eval) - sh(i) = EXP(-2.0_wp*(k_comp(i)*depth)) - END DO - END IF - IF (at_bed) THEN - DO i = 1, nb - denom = CD_ONE - sh(i) - ch(i) = (ch(i) + ch(i))/denom - sh(i) = CD_ZERO - END DO - ELSE - ! an underflowed exponential takes profile_ratios' stable form; those components - ! (rare) are redone one at a time below, the rest stay branch-free here - n_small = COUNT(ch(1:nb) <= TINY(CD_ONE) .OR. sh(1:nb) <= TINY(CD_ONE)) - DO i = 1, nb - e_neg = sh(i)/MAX(ch(i), TINY(CD_ONE)) - denom = CD_ONE - sh(i) - sh(i) = (ch(i) - e_neg)/denom - ch(i) = (ch(i) + e_neg)/denom + use_tail = .FALSE. + IF (PRESENT(tail_sums)) use_tail = z_eval <= CD_ZERO .AND. z_eval >= -depth + mag = CD_ZERO + DO i0 = 1, n, NBLK + nk = MIN(n - i0 + 1, NBLK) + IF (i0 <= nb) THEN + bc(1:nk) = cth(i0:i0 + nk - 1) + ELSE + DO j = 1, nk + bc(j) = COS(k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1)) + END DO + END IF + ! the sine in its own loop: a compiler fuses COS and SIN of one argument into a sincos + ! call, which in the MinGW runtime costs several times a cos plus a sin + DO j = 1, nk + bs(j) = SIN(k_comp(i0 + j - 1)*x_along - omega_comp(i0 + j - 1)*t + phase(i0 + j - 1)) END DO - IF (n_small > 0) THEN - DO i = 1, nb - kd = k_comp(i)*depth - kz = k_comp(i)*z_eval - e_kz = EXP(kz) - e_neg2kd = EXP(-2.0_wp*kd) - IF (e_kz <= TINY(e_kz) .OR. e_neg2kd <= TINY(e_neg2kd)) & - CALL profile_ratios(k_comp(i), depth, z_eval, ch(i), sh(i)) + IF (PRESENT(exp_m2kd)) THEN + DO j = 1, nk + ch(j) = EXP(k_comp(i0 + j - 1)*z_eval) + sh(j) = exp_m2kd(i0 + j - 1) + END DO + ELSE + DO j = 1, nk + ch(j) = EXP(k_comp(i0 + j - 1)*z_eval) + sh(j) = EXP(-2.0_wp*(k_comp(i0 + j - 1)*depth)) END DO END IF - END IF - DO i = 1, nb - amp = (scl*amplitude(i))*omega_comp(i) - velocity(1) = velocity(1) + amp*ch(i)*cth(i)*cb - velocity(2) = velocity(2) + amp*ch(i)*cth(i)*sb - velocity(3) = velocity(3) + amp*sh(i)*sth(i) - amp = (scl*amplitude(i))*omega_comp(i)*omega_comp(i) - acceleration(1) = acceleration(1) + amp*ch(i)*sth(i)*cb - acceleration(2) = acceleration(2) + amp*ch(i)*sth(i)*sb - acceleration(3) = acceleration(3) - amp*sh(i)*cth(i) - END DO - IF (PRESENT(pdyn)) THEN - DO i = 1, nb - pdyn = pdyn + (scl*amplitude(i))*omega_comp(i)*omega_comp(i)/k_comp(i)*ch(i)*cth(i) + IF (at_bed) THEN + DO j = 1, nk + denom = CD_ONE - sh(j) + ch(j) = (ch(j) + ch(j))/denom + sh(j) = CD_ZERO + END DO + ELSE + ! an underflowed exponential (exp(-2kd) of a short component in deep water) takes + ! profile_ratios' stable form; those components are redone one at a time below, the + ! rest stay branch-free here + small(1:nk) = ch(1:nk) <= TINY(CD_ONE) .OR. sh(1:nk) <= TINY(CD_ONE) + n_small = COUNT(small(1:nk)) + DO j = 1, nk + e_neg = sh(j)/MAX(ch(j), TINY(CD_ONE)) + denom = CD_ONE - sh(j) + sh(j) = (ch(j) - e_neg)/denom + ch(j) = (ch(j) + e_neg)/denom + END DO + IF (n_small > 0) THEN + DO j = 1, nk + IF (small(j)) CALL profile_ratios(k_comp(i0 + j - 1), depth, z_eval, ch(j), sh(j)) + END DO + END IF + END IF + DO j = 1, nk + i = i0 + j - 1 + amp = (scl*amplitude(i))*omega_comp(i) + velocity(1) = velocity(1) + amp*ch(j)*bc(j)*cb + velocity(2) = velocity(2) + amp*ch(j)*bc(j)*sb + velocity(3) = velocity(3) + amp*sh(j)*bs(j) + amp = (scl*amplitude(i))*omega_comp(i)*omega_comp(i) + acceleration(1) = acceleration(1) + amp*ch(j)*bs(j)*cb + acceleration(2) = acceleration(2) + amp*ch(j)*bs(j)*sb + acceleration(3) = acceleration(3) - amp*sh(j)*bc(j) END DO - END IF - DO i = nb + 1, n - omega = omega_comp(i) - k = k_comp(i) - theta = k*x_along - omega*t + phase(i) - c_i = COS(theta) - s_i = SIN(theta) - CALL profile_ratios(k, depth, z_eval, cosh_ratio, sinh_ratio) - amp = (scl*amplitude(i))*omega - velocity(1) = velocity(1) + amp*cosh_ratio*c_i*cb - velocity(2) = velocity(2) + amp*cosh_ratio*c_i*sb - velocity(3) = velocity(3) + amp*sinh_ratio*s_i - amp = (scl*amplitude(i))*omega*omega - acceleration(1) = acceleration(1) + amp*cosh_ratio*s_i*cb - acceleration(2) = acceleration(2) + amp*cosh_ratio*s_i*sb - acceleration(3) = acceleration(3) - amp*sinh_ratio*c_i - IF (PRESENT(pdyn)) pdyn = pdyn + amp/k*cosh_ratio*c_i + IF (PRESENT(pdyn)) THEN + DO j = 1, nk + i = i0 + j - 1 + pdyn = pdyn + (scl*amplitude(i))*omega_comp(i)*omega_comp(i)/k_comp(i)*ch(j)*bc(j) + END DO + END IF + IF (use_tail) THEN + DO j = 1, nk + i = i0 + j - 1 + mag(1) = mag(1) + amplitude(i)*omega_comp(i)*ch(j) + mag(2) = mag(2) + amplitude(i)*omega_comp(i)*omega_comp(i)*ch(j) + mag(3) = mag(3) + amplitude(i)*omega_comp(i)*omega_comp(i)/k_comp(i)*ch(j) + END DO + IF (i0 + nk <= n) THEN + rest = ch(nk)*tail_sums(:, i0 + nk) + IF (rest(1) <= HALF_ULP*mag(1) .AND. rest(2) <= HALF_ULP*mag(2) .AND. & + (.NOT. PRESENT(pdyn) .OR. rest(3) <= HALF_ULP*mag(3))) EXIT + END IF + END IF END DO END SUBROUTINE CD_Component_Wave_Kinematics diff --git a/tests/test_hermite_irregular_waves.f90 b/tests/test_hermite_irregular_waves.f90 index 4d5d7165..b6283d46 100644 --- a/tests/test_hermite_irregular_waves.f90 +++ b/tests/test_hermite_irregular_waves.f90 @@ -26,6 +26,10 @@ PROGRAM test_hermite_irregular_waves !! all-zero amplitudes, bad period/phase/depth/gravity, missing hydro config). !! 7. IRREGULAR SMOKE: a 12-component JONSWAP-like table on a hanging cable runs !! bounded with every step converged (waves break the at-rest fixed point). + !! 8. TAIL SUMS: on a 1500-component table of a 600 s record (the components of a WaterKin + !! elevation file), the kernel with tail_sums gives the same elevation bit for bit and + !! velocity, acceleration and dynamic pressure within round-off of the full sums, from + !! the surface to the seabed; above still water (stretching off) it sums every component. USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_VALUE, IEEE_QUIET_NAN USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64 USE CableDyn_Precision, ONLY: wp @@ -50,6 +54,7 @@ PROGRAM test_hermite_irregular_waves CALL model_displacement() CALL fail_closed_battery() CALL irregular_smoke() + CALL kernel_tail_sums() IF (nfail > 0) THEN WRITE (*, '(A,I0,A)') 'FAIL: ', nfail, ' assertion(s) failed' @@ -151,6 +156,67 @@ SUBROUTINE kernel_profile_underflow() CALL require(ABS(a(3)) <= TINY(1.0_wp), 'profile underflow: seabed sinh ratio remains zero') END SUBROUTINE kernel_profile_underflow + SUBROUTINE kernel_tail_sums() + INTEGER, PARAMETER :: N = 1500, NZ = 7 + ! (z, stretch): near the surface, mid-depth, deep, near and at the seabed; above still water + REAL(wp), PARAMETER :: ZS(NZ) = [-0.5_wp, -5.0_wp, -20.0_wp, -45.0_wp, -59.999_wp, -60.0_wp, 0.3_wp] + LOGICAL, PARAMETER :: STRETCH(NZ) = [.TRUE., .TRUE., .TRUE., .FALSE., .TRUE., .FALSE., .FALSE.] + REAL(wp) :: om(N), k(N), amp(N), ph(N), tail(3, N), e2kd(N), w(3) + REAL(wp) :: eta0, u0(3), a0(3), p0, eta1, u1(3), a1(3), p1, mag(3), ratio, ze + INTEGER :: i, iz, es + CHARACTER(200) :: em + ! omega_i = i 2 pi/600 s up to 2 Hz: a peaked sea plus the leakage tail of a finite record + DO i = 1, N + om(i) = REAL(i, wp)*2.0_wp*PI/600.0_wp + amp(i) = 0.3_wp*EXP(-0.5_wp*((om(i) - 0.63_wp)/0.12_wp)**2) + 1.0e-3_wp/REAL(i, wp) + ph(i) = MODULO(2.399963_wp*REAL(i, wp)**2, 2.0_wp*PI) + CALL CD_Solve_Dispersion_Wavenumber(om(i), DEPTH, GRAV, k(i), es, em) + CALL require(es == CD_HYDRO_OK, 'tail sums: dispersion solve: '//TRIM(em)) + e2kd(i) = EXP(-2.0_wp*(k(i)*DEPTH)) + END DO + tail(:, N) = amp(N)*[om(N), om(N)**2, om(N)**2/k(N)] + DO i = N - 1, 1, -1 + tail(:, i) = tail(:, i + 1) + amp(i)*[om(i), om(i)**2, om(i)**2/k(i)] + END DO + DO iz = 1, NZ + CALL CD_Component_Wave_Kinematics(12.0_wp, 3.0_wp, ZS(iz), 333.3_wp, DEPTH, 20.0_wp, STRETCH(iz), & + om, k, amp, ph, eta0, u0, a0, es, em, inputs_validated=.TRUE., & + pdyn=p0, exp_m2kd=e2kd) + CALL require(es == CD_HYDRO_OK, 'tail sums: full sum: '//TRIM(em)) + CALL CD_Component_Wave_Kinematics(12.0_wp, 3.0_wp, ZS(iz), 333.3_wp, DEPTH, 20.0_wp, STRETCH(iz), & + om, k, amp, ph, eta1, u1, a1, es, em, inputs_validated=.TRUE., & + pdyn=p1, exp_m2kd=e2kd, tail_sums=tail) + CALL require(es == CD_HYDRO_OK, 'tail sums: bounded sum: '//TRIM(em)) + CALL require(TRANSFER(eta1, 0_INT64) == TRANSFER(eta0, 0_INT64), 'tail sums: the elevation sums every component') + IF (ZS(iz) > 0.0_wp) THEN + CALL require(ALL(TRANSFER([u1, a1, p1], [0_INT64]) == TRANSFER([u0, a0, p0], [0_INT64])), & + 'tail sums: above still water every component is summed') + CYCLE + END IF + ! the magnitudes summed: a omega, a omega^2 and a omega^2/k times the cosh ratio + ze = ZS(iz) + IF (STRETCH(iz)) ze = (ZS(iz) - eta0)*DEPTH/(DEPTH + eta0) + mag = 0.0_wp + DO i = 1, N + ratio = (EXP(k(i)*ze) + EXP(-k(i)*(ze + 2.0_wp*DEPTH)))/(1.0_wp - e2kd(i)) + w = amp(i)*[om(i), om(i)**2, om(i)**2/k(i)] + mag = mag + w*ratio + END DO + CALL require(MAXVAL(ABS(u1 - u0)) <= 4.0_wp*EPSILON(1.0_wp)*mag(1) .AND. & + MAXVAL(ABS(a1 - a0)) <= 4.0_wp*EPSILON(1.0_wp)*mag(2) .AND. & + ABS(p1 - p0) <= 4.0_wp*EPSILON(1.0_wp)*mag(3), & + 'tail sums: velocity, acceleration and pressure within round-off at z = '//fmt_z(ZS(iz))) + END DO + CALL CD_Component_Wave_Kinematics(12.0_wp, 3.0_wp, -5.0_wp, 333.3_wp, DEPTH, 20.0_wp, .TRUE., & + om, k, amp, ph, eta1, u1, a1, es, em, tail_sums=tail(1:2, :)) + CALL require(es /= CD_HYDRO_OK, 'tail sums: a mis-shaped table fails closed') + END SUBROUTINE kernel_tail_sums + + CHARACTER(16) FUNCTION fmt_z(z) + REAL(wp), INTENT(IN) :: z + WRITE (fmt_z, '(F0.3)') z + END FUNCTION fmt_z + SUBROUTINE kernel_total_eta_wheeler() INTEGER, PARAMETER :: N = 4 REAL(wp) :: amp(N), per(N), phd(N), om(N), k(N), ph(N) From 788cbac2b97c3ef2f119dd81e5302a9673804708 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 28 Oct 2026 15:38:31 +0900 Subject: [PATCH 3/4] feat(waves): WvHiCOff cuts an elevation record at 0.5 Hz by default A WaterKin WaveKinMod 1 record kept every Fourier component up to the Nyquist frequency of dtWave: 18,000 for a one-hour record at 0.1 s, each summed at every node for the surface elevation. Measured on a user's 600 s twin case, keeping only the components up to 0.5 Hz changed the curvature fatigue load by 0.02 % and cut the wave time by 8.5 times. The new OPTION WvHiCOff (rad/s, SeaState's name and meaning) drops the components of an elevation record above it, by default pi rad/s, the 0.5 Hz at which MoorDyn-C cuts WaveKin 3; WaveKin 3 now follows the option too (bit for bit at the default). none WvHiCOff keeps every component, as MoorDyn-F and earlier CableDyn did. A record with no component at or below the cut-off (a run shorter than 2 s at the default) is refused by name. The WaveKin 3 components are stored in preallocated arrays instead of growing by one per component. On the 300 s lazy-wave case (1024 elements), records at dtWave 0.25 s and 0.1 s both run in 72 s (103 s and 189 s with none), and every output channel's standard deviation moves by at most 0.002 %. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 7 ++++ doc/driver_format.md | 4 +- doc/file_formats.rst | 14 ++++--- doc/migrating.rst | 4 +- doc/options.rst | 10 +++++ doc/theory.rst | 3 +- examples/cabledyn_options_reference.dat | 1 + python/cabledyn/deck_file.py | 23 +++++++++-- python/tests/test_deck_file.py | 4 ++ src/CableDyn_DeckDriver.f90 | 52 +++++++++++++++++++------ tests/test_deck_driver.f90 | 23 +++++++---- tests/test_wavekin_modes.f90 | 49 +++++++++++++++++++++++ 12 files changed, 164 insertions(+), 30 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index f44cd557..0e53302f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -65,6 +65,13 @@ All notable changes to CableDyn are recorded in this file. The format follows cable over 300 s, a record at `dtWave` 0.25 s (600 components) runs in 103 s instead of 226 s, and one at 0.1 s in 189 s instead of about 660 s, with output identical to the printed digits. A `jonswap` sea changes at round-off. +- An elevation record (WaterKin `WaveKinMod 1`) keeps only its Fourier components up to the new + `WvHiCOff` option, in rad/s as in SeaState, by default 0.5 Hz (MoorDyn-C's fixed cut for + `WaveKin 3`, which now follows the option too); `none WvHiCOff` keeps them up to the Nyquist + frequency of `dtWave`, as MoorDyn-F and earlier CableDyn did. A one-hour record at `dtWave` + 0.1 s drops from 18,000 components to 1,800. On the 300 s lazy-wave case both records then run + in 72 s, and every output channel's standard deviation moves by at most 0.002 %. A record with + no component at or below the cut-off is refused by name. - Under a bend stiffener, `BendMomN` (and the `BendMoment` columns of the static profile, range graphs and element file) report the cable's own moment, the line type's EI times the curvature; lines without stiffeners are unchanged. diff --git a/doc/driver_format.md b/doc/driver_format.md index 82c34340..3e299aa8 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -1182,7 +1182,7 @@ them on `water_grid.txt` and interpolates, so that file is not read. Standalone | Option | File | Meaning | |---|---|---| -| `WaveKin 3` | `wave_elevation.txt` | `time elevation` rows from `t = 0` (no header rows), resampled linearly at `dtWave` to `floor(t_last/dtWave) + 1` samples (the last dropped when the count is odd) and reduced to its Fourier components; components above 0.5 Hz are dropped and the mean is a mean-level offset, as MoorDyn-C does. Waves travel along +x | +| `WaveKin 3` | `wave_elevation.txt` | `time elevation` rows from `t = 0` (no header rows), resampled linearly at `dtWave` to `floor(t_last/dtWave) + 1` samples (the last dropped when the count is odd) and reduced to its Fourier components; components above `WvHiCOff` (default 0.5 Hz, MoorDyn-C's fixed cut) are dropped and the mean is a mean-level offset, as MoorDyn-C does. Waves travel along +x | | `WaveKin 7` | `wave_frequencies.txt` | `omega Re Im [beta]` rows [rad/s, m, m, rad], the first at `omega = 0`: each row is the component `\|c\| sin(omega t - k d + arg c)`, `d = x cos(beta) + y sin(beta)`; the `omega = 0` row is a mean-level offset. All rows must share one `beta` | | `Currents 1` | `current_profile.txt` | `z ux uy uz` rows after its header rows, strictly increasing `z`; linear in `z` and held beyond the end rows | @@ -1208,7 +1208,7 @@ A MoorDyn-F deck may select a WaterKin file (grammar in [Auxiliary file formats] | Mode | Meaning | |---|---| | `WaveKinMod = 0` | no waves | -| `WaveKinMod = 1` | elevation history resampled at `dtWave` over deck `TMax` (host `TMax` for caller-driven decks), truncated or zero-padded, and Fourier-reduced once on one padded DFT time base | +| `WaveKinMod = 1` | elevation history resampled at `dtWave` over deck `TMax` (host `TMax` for caller-driven decks), truncated or zero-padded, and Fourier-reduced once on one padded DFT time base, keeping the components up to `WvHiCOff` (default 0.5 Hz; `none` keeps all, as MoorDyn-F) | | `WaveKinMod = 2` / `SEASTATE` | waves from the coupled host SeaState field | | `CurrentMod = 0` | no current | | `CurrentMod = 1` | N-level WaterKin depth table, interpolated at structural nodes | diff --git a/doc/file_formats.rst b/doc/file_formats.rst index d029174d..ce828700 100644 --- a/doc/file_formats.rst +++ b/doc/file_formats.rst @@ -564,11 +564,15 @@ two columns: * ``TMax / dtWave`` may be at most 10\ :sup:`6` samples; a longer record is rejected (``WaterKin TMax/dtWave needs more than 1000000 wave samples``) because the one-time reduction grows with the square of the sample count. -* The record gives about ``TMax / (2 dtWave)`` components, 600 for a 300 s run at - ``dtWave`` 0.25 s, against the 200 of a ``jonswap`` sea. Every node sums all of them for its - surface elevation. Below the surface, the components too short to reach the node's depth - are dropped once they cannot change its velocity and acceleration beyond round-off - (:ref:`theory-waves`). A coarser ``dtWave`` still shortens the run. +* The components above the ``WvHiCOff`` option (default :math:`\pi` rad/s, 0.5 Hz) are + dropped, as SeaState drops those of an elevation series; ``none WvHiCOff`` keeps them up to + the Nyquist frequency of ``dtWave``, as MoorDyn-F does. A record with no component at or + below the cut-off, for example a run shorter than 2 s, is refused by name. +* The record keeps about ``TMax WvHiCOff / (2 pi)`` components (150 for a 300 s run), or + ``TMax / (2 dtWave)`` with ``none`` (600 at ``dtWave`` 0.25 s), against the 200 of a + ``jonswap`` sea. Every node sums all of them for its surface elevation. Below the surface, + the components too short to reach the node's depth are dropped once they cannot change its + velocity and acceleration beyond round-off (:ref:`theory-waves`). Example ~~~~~~~ diff --git a/doc/migrating.rst b/doc/migrating.rst index 53a743d1..39010cfa 100644 --- a/doc/migrating.rst +++ b/doc/migrating.rst @@ -123,7 +123,9 @@ Keyword map * - ``kBot``, ``cBot``, seabed friction coefficient - ``kBot``, ``cBot``, ``frictionMu`` (alias ``mu``) * - ``WaterKin`` file (``CurrentMod 1``, ``WaveKinMod 1``) - - same file; ``WaveKinMod 2`` and ``SEASTATE`` only when coupled to OpenFAST + - same file; ``WaveKinMod 2`` and ``SEASTATE`` only when coupled to OpenFAST. An + elevation record keeps its components up to ``WvHiCOff`` (default 0.5 Hz); give + ``none WvHiCOff`` to keep all of them, as MoorDyn-F does * - ``FAILURE``, ``CONTROL`` sections - ``FAILURE`` on ``EI = 0`` decks, standalone and in OpenFAST (a deck with a finite-EI cable rejects it); ``CONTROL`` on ``EI = 0`` lines and finite-EI cables in OpenFAST, not diff --git a/doc/options.rst b/doc/options.rst index 0766cedf..5c304764 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -746,6 +746,16 @@ Ambient fluid and prescribed motion - the step at which ``WaveKin 3`` resamples ``wave_elevation.txt`` (MoorDyn-C) - standalone - ``0.1 dtWave`` + * - ``WvHiCOff`` + - positive number [rad/s] or ``none`` + - ``3.14159`` (0.5 Hz) + - the high cut-off frequency of an elevation record (WaterKin ``WaveKinMod 1``, + ``WaveKin 3``): its Fourier components above it are dropped, as SeaState's ``WvHiCOff`` + zeroes the spectrum of an elevation series. ``none`` keeps them up to the Nyquist + frequency of ``dtWave``, as MoorDyn-F's ``WaveKinMod 1`` does. A record with no + component at or below the cut-off is refused + - standalone + - ``6.2832 WvHiCOff`` * - ``Currents`` - ``0`` or ``1`` - ``0`` diff --git a/doc/theory.rst b/doc/theory.rst index 5cc02c5a..98295023 100644 --- a/doc/theory.rst +++ b/doc/theory.rst @@ -902,7 +902,8 @@ ratios :math:`\cosh k(z' + h)/\sinh kh` and :math:`\sinh k(z' + h)/\sinh kh` fal bounds the rest of each sum. The sums stop once those bounds are below half an ulp of the magnitudes already summed. A deep point therefore skips the short components that have decayed to nothing there, and the result changes at round-off only. This matters for an -elevation history, whose :math:`T_{max}/(2\,\Delta t_{wave})` components reach the Nyquist +elevation history, which keeps its components up to the ``WvHiCOff`` cut-off (0.5 Hz by +default) or, with ``none``, all :math:`T_{max}/(2\,\Delta t_{wave})` of them up to the Nyquist frequency of ``dtWave``. **Regular nonlinear waves.** A ``stream`` wave is Dean's stream-function wave diff --git a/examples/cabledyn_options_reference.dat b/examples/cabledyn_options_reference.dat index dabeaebe..85a57e0a 100644 --- a/examples/cabledyn_options_reference.dat +++ b/examples/cabledyn_options_reference.dat @@ -98,6 +98,7 @@ none waves - Wave model and parameters (m, s, deg) {none; airy; -- 0.1 dtOut - MoorDyn output-cadence compatibility only; accepted and ignored -- 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] -- Keyword aliases (equivalent spellings, case-insensitive): -- g = gravity; rhoW = WtrDnsty = water_density; WtrDpth = water_depth; kBot = kb; cBot = cb -- bathymetryFile = bathymetry_file = seafloorFile = seafloor_file; frictionMu = mu = frictionCoefficient diff --git a/python/cabledyn/deck_file.py b/python/cabledyn/deck_file.py index 7ade3115..5eadc030 100644 --- a/python/cabledyn/deck_file.py +++ b/python/cabledyn/deck_file.py @@ -276,6 +276,7 @@ "bodyscheme", "bodysubstep", "dtwave", + "wvhicoff", "bodywetting", "bodyhydro", "rodhydro", @@ -1114,8 +1115,15 @@ def _scalar_option_value_error(keyword: str, value: str) -> str | None: if not value: return "requires a non-empty path" boolean_values = {"true", "t", "yes", "y", "on", "1", "false", "f", "no", "n", "off", "0"} - # native check_option_row_value rule 'positive' (dtWave is the WaveKin 3 resampling step) - positive = key in {"gravity", "water_density", "water_depth", "dtm"} or raw == "dtwave" + if raw == "wvhicoff" and value.lower() == "none": + # native rule: 'none' keeps every component of an elevation record + return None + # native check_option_row_value rule 'positive' (dtWave is the WaveKin 3 resampling step, + # WvHiCOff the high cut-off frequency of an elevation record) + positive = key in {"gravity", "water_density", "water_depth", "dtm"} or raw in { + "dtwave", + "wvhicoff", + } if positive: lower, upper = 0.0, None elif key in {"kbot", "cbot"}: @@ -1161,7 +1169,16 @@ def _scalar_option_value_error(keyword: str, value: str) -> str | None: "max_strain", "range_start", "viv_rms_window", - } or raw in {"dtic", "tmaxic", "cdscaleic", "threshic", "writelog", "dtout", "dtwave"}: + } or raw in { + "dtic", + "tmaxic", + "cdscaleic", + "threshic", + "writelog", + "dtout", + "dtwave", + "wvhicoff", + }: try: numeric = _native_float(value) except ValueError: diff --git a/python/tests/test_deck_file.py b/python/tests/test_deck_file.py index 063253ea..1da6a512 100644 --- a/python/tests/test_deck_file.py +++ b/python/tests/test_deck_file.py @@ -651,6 +651,8 @@ def test_unknown_scalar_option_keyword_fails_closed(tmp_path): ("implicit", "bodyScheme", "monolithic or staggered"), ("fast", "bodySubstep", "none or accuracy"), ("x", "dtWave", "must be numeric"), + ("0", "WvHiCOff", "must be positive"), + ("off", "WvHiCOff", "must be numeric"), ("2", "Currents", "supports only mode 0 or 1"), ("1.5", "Currents", "supports only mode 0 or 1"), ("4", "WaterKin", "numeric mode 0, 3 or 7"), @@ -713,6 +715,8 @@ def test_zero_e_exponent_waterkin_mode_is_accepted(tmp_path): "none bodySubstep", "accuracy bodySubstep", "0.25 dtWave", + "6.283 WvHiCOff", + "none WvHiCOff", "60 TMax", "motion.dat motionFile", "RK4 tScheme", diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 74d7706a..6866301f 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -669,6 +669,10 @@ MODULE CableDyn_DeckDriver INTEGER :: mdc_wave_kin = 0 INTEGER :: mdc_currents = 0 REAL(wp) :: mdc_dt_wave = 0.25_wp + ! WvHiCOff: the components of an elevation record (WaterKin WaveKinMod 1, WaveKin 3) above + ! this frequency are dropped (rad/s, as SeaState's WvHiCOff; default 0.5 Hz, MoorDyn-C's + ! 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. LOGICAL :: waterkin_host_wave = .FALSE. LOGICAL :: waterkin_host_current = .FALSE. @@ -12533,7 +12537,19 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma times = [(REAL(j - 1, wp)*dt, j=1, n)] eta_rows = sample_eta - nc = n/2 + ! the components up to WvHiCOff (all n/2 with 'none') + nc = 0 + DO k = 1, n/2 + IF (opts%wv_hi_cutoff >= CD_ZERO .AND. TWO_PI*REAL(k, wp)/(REAL(n, wp)*dt) > opts%wv_hi_cutoff) EXIT + nc = k + END DO + IF (nc < 1) THEN + CALL fail(ErrStat, ErrMsg, 'WvHiCOff '//TRIM(ADJUSTL(es_to_str(opts%wv_hi_cutoff)))//' rad/s keeps no '// & + 'component of the WaterKin WaveKinFile record, whose lowest frequency is '// & + TRIM(ADJUSTL(es_to_str(TWO_PI/(REAL(n, wp)*dt))))//' rad/s over the '// & + TRIM(ADJUSTL(es_to_str(REAL(n, wp)*dt)))//' s window; lengthen TMax or give none WvHiCOff') + RETURN + END IF IF (ALLOCATED(opts%wave_component_omega)) DEALLOCATE (opts%wave_component_omega) IF (ALLOCATED(opts%wave_component_k)) DEALLOCATE (opts%wave_component_k) IF (ALLOCATED(opts%wave_component_amplitude)) DEALLOCATE (opts%wave_component_amplitude) @@ -12562,7 +12578,7 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma END IF END DO scale = 2.0_wp/REAL(n, wp) - IF (MOD(n, 2) == 0 .AND. k == nc) scale = CD_ONE/REAL(n, wp) + IF (MOD(n, 2) == 0 .AND. k == n/2) scale = CD_ONE/REAL(n, wp) ca = scale*ca sa = scale*sa ! Coefficients and runtime components must share the padded DFT time base. @@ -12691,13 +12707,14 @@ SUBROUTINE read_moordyn_c_kinematics(dir, opts, ErrStat, ErrMsg) frac = MIN(CD_ONE, MAX(CD_ZERO, frac)) eta(j) = tab(2, bracket) + frac*(tab(2, bracket + 1) - tab(2, bracket)) END DO - ! discrete Fourier components on the record's own base (period nt dt); MoorDyn-C zeroes the - ! bins above 0.5 Hz and keeps the mean + ! discrete Fourier components on the record's own base (period nt dt) up to WvHiCOff (by + ! default 0.5 Hz, where MoorDyn-C zeroes the bins); the mean is kept mean_level = SUM(eta)/REAL(nt, wp) - ALLOCATE (comp_w(0), comp_a(0), comp_p(0)) + ALLOCATE (comp_w(nt/2), comp_a(nt/2), comp_p(nt/2)) + nc = 0 DO k = 1, nt/2 angle = TWO_PI*REAL(k, wp)/(REAL(nt, wp)*dt) - IF (angle > 0.5_wp*TWO_PI) EXIT + IF (opts%wv_hi_cutoff >= CD_ZERO .AND. angle > opts%wv_hi_cutoff) EXIT ca = CD_ZERO sa = CD_ZERO DO j = 1, nt @@ -12710,10 +12727,14 @@ SUBROUTINE read_moordyn_c_kinematics(dir, opts, ErrStat, ErrMsg) IF (k == nt/2) scale = CD_ONE/REAL(nt, wp) ca = scale*ca sa = scale*sa - comp_w = [comp_w, angle] - comp_a = [comp_a, SQRT(ca*ca + sa*sa)] - comp_p = [comp_p, ATAN2(sa, ca)] - END DO + nc = k + comp_w(nc) = angle + comp_a(nc) = SQRT(ca*ca + sa*sa) + comp_p(nc) = ATAN2(sa, ca) + END DO + comp_w = comp_w(1:nc) + comp_a = comp_a(1:nc) + comp_p = comp_p(1:nc) CALL install_components() IF (ErrStat /= CD_DECKDRV_OK) RETURN CASE (7) @@ -12789,7 +12810,7 @@ SUBROUTINE install_components() nc = SIZE(comp_w) IF (nc < 1) THEN CALL fail(ErrStat, ErrMsg, 'WaveKin '//TRIM(int_to_str(opts%mdc_wave_kin))//': '//TRIM(fname)// & - ' gives no wave component at or below 0.5 Hz'); RETURN + ' gives no wave component at or below WvHiCOff'); RETURN END IF IF (ALLOCATED(opts%wave_component_omega)) DEALLOCATE (opts%wave_component_omega) IF (ALLOCATED(opts%wave_component_k)) DEALLOCATE (opts%wave_component_k) @@ -14948,6 +14969,12 @@ SUBROUTINE apply_option(line, opts, ErrStat, ErrMsg) CASE ('dtwave') ! MoorDyn-C WaveKin 3: the resampling step of wave_elevation.txt CALL rd(val, opts%mdc_dt_wave, ErrStat, ErrMsg) + CASE ('wvhicoff') + IF (to_lower(TRIM(val)) == 'none') THEN + opts%wv_hi_cutoff = -CD_ONE + ELSE + CALL rd(val, opts%wv_hi_cutoff, ErrStat, ErrMsg) + END IF CASE ('ramptime', 'ramp_time', 'tramp') CALL rd(val, opts%ramp_time, ErrStat, ErrMsg) CASE ('maxstrain', 'max_strain') @@ -15429,6 +15456,9 @@ SUBROUTINE check_option_row_value(kw, val, ErrStat, ErrMsg) CASE ('frictionmu', 'mu', 'frictioncoefficient') IF (to_lower(TRIM(val)) == 'none') RETURN rule = 'non-negative' + CASE ('wvhicoff') + IF (to_lower(TRIM(val)) == 'none') RETURN + rule = 'positive' CASE ('frictionmuaxial', 'frictionmu_axial', 'mu_axial', 'muaxial', 'frictionmulateral', 'frictionmu_lateral', & 'mu_lateral', 'mulateral', 'frictionmunormal', 'frictionmu_normal') rule = 'non-negative' diff --git a/tests/test_deck_driver.f90 b/tests/test_deck_driver.f90 index ff565bac..a7fcf729 100644 --- a/tests/test_deck_driver.f90 +++ b/tests/test_deck_driver.f90 @@ -645,10 +645,16 @@ PROGRAM test_deck_driver wave_file='wk_eta_short.dat', dtwave=0.25_wp) CALL write_waterkin_file('wk_wave_padded.dat', wavekinmod='1', deepest_first=.FALSE., & wave_file='wk_eta_padded.dat', dtwave=0.25_wp) - CALL write_dynamic_connect_deck('deck_wk_wave_short.dat', option_row='wk_wave_short.dat WaterKin', & + ! a 1 s window has no component at or below the default 0.5 Hz WvHiCOff: refused by name + CALL write_dynamic_connect_deck('deck_wk_wave_cut.dat', option_row='wk_wave_short.dat WaterKin', & run_tmax=1.0_wp) + CALL CD_Run_Deck_Driver('deck_wk_wave_cut.dat', 'deck_wk_wave_cut', conv, es, em) + CALL require(es /= CD_DECKDRV_OK .AND. INDEX(em, 'none WvHiCOff') > 0, & + 'a record with nothing below WvHiCOff is refused by name: '//TRIM(em)) + CALL write_dynamic_connect_deck('deck_wk_wave_short.dat', option_row='wk_wave_short.dat WaterKin', & + option_row2='none WvHiCOff', run_tmax=1.0_wp) CALL write_dynamic_connect_deck('deck_wk_wave_padded.dat', option_row='wk_wave_padded.dat WaterKin', & - run_tmax=1.0_wp) + option_row2='none WvHiCOff', run_tmax=1.0_wp) CALL CD_Run_Deck_Driver('deck_wk_wave_short.dat', 'deck_wk_wave_short', conv, es, em) CALL require(es == CD_DECKDRV_OK .AND. conv, 'short WaveKinMod 1 record converged: '//TRIM(em)) CALL CD_Run_Deck_Driver('deck_wk_wave_padded.dat', 'deck_wk_wave_padded', conv, es, em) @@ -666,7 +672,7 @@ PROGRAM test_deck_driver CALL write_waterkin_file('wk_sub/wk_wave_sub.dat', wavekinmod='1', deepest_first=.FALSE., & wave_file='wk_eta_short.dat', dtwave=0.25_wp) CALL write_dynamic_connect_deck('deck_wk_wave_sub.dat', option_row='wk_sub/wk_wave_sub.dat WaterKin', & - run_tmax=1.0_wp) + option_row2='none WvHiCOff', run_tmax=1.0_wp) CALL CD_Run_Deck_Driver('deck_wk_wave_sub.dat', 'deck_wk_wave_sub', conv, es, em) CALL require(es == CD_DECKDRV_OK .AND. conv, 'deck-relative WaveKinFile of a nested WaterKin file: '//TRIM(em)) IF (es == CD_DECKDRV_OK) THEN @@ -753,15 +759,17 @@ PROGRAM test_deck_driver ! WaveKinMod 1: reduce a sampled elevation history to Fourier components. A ! pure Airy history must reproduce the equivalent inline wave/current deck. ! The source record is twice the run TMax and its second half is deliberately - ! contaminated. The FFT window must ignore that tail and match one clean period. + ! contaminated. The FFT window must ignore that tail and match one clean period. The 1 Hz wave + ! lies above the 0.5 Hz default WvHiCOff, so these decks keep every component. CALL write_wave_elevation_file('wk_eta.dat', 1.0_wp, 1.0_wp, 0.0_wp, nperiods=2, tail_bias=0.4_wp) CALL write_waterkin_file('wk_wave.dat', wavekinmod='1', deepest_first=.FALSE., & wave_file='wk_eta.dat', dtwave=0.25_wp) - CALL write_dynamic_connect_deck('deck_wk_wave.dat', option_row='wk_wave.dat WaterKin', run_tmax=1.0_wp) + CALL write_dynamic_connect_deck('deck_wk_wave.dat', option_row='wk_wave.dat WaterKin', & + option_row2='none WvHiCOff', run_tmax=1.0_wp) CALL CD_Run_Deck_Driver('deck_wk_wave.dat', 'deck_wk_wave', conv, es, em) CALL require(es == CD_DECKDRV_OK .AND. conv, 'WaveKinMod 1 elevation-history deck converged: '//TRIM(em)) CALL write_dynamic_connect_deck('deck_wk_wave_host_tmax.dat', option_row='wk_wave.dat WaterKin', & - omit_tmax=.TRUE.) + option_row2='none WvHiCOff', omit_tmax=.TRUE.) BLOCK TYPE(CD_DeckAggregateType) :: wkagg CALL CD_Init_Deck_Aggregate('deck_wk_wave_host_tmax.dat', 0.005_wp, wkagg, es, em, & @@ -812,7 +820,8 @@ PROGRAM test_deck_driver END BLOCK CALL write_waterkin_file('wk_mixed_hybrid.dat', wavekinmod='1', deepest_first=.FALSE., & wave_file='wk_eta.dat', currentmod='2', dtwave=0.25_wp) - CALL write_dynamic_connect_deck('deck_wk_mixed_hybrid.dat', option_row='wk_mixed_hybrid.dat WaterKin') + CALL write_dynamic_connect_deck('deck_wk_mixed_hybrid.dat', option_row='wk_mixed_hybrid.dat WaterKin', & + option_row2='none WvHiCOff') CALL CD_Run_Deck_Driver('deck_wk_mixed_hybrid.dat', 'deck_wk_mixed_hybrid', conv, es, em) CALL require(es /= CD_DECKDRV_OK .AND. INDEX(em, 'cannot separate') > 0, & 'WaveKinMod 1 plus CurrentMod 2 fails closed by mixed-source contract') diff --git a/tests/test_wavekin_modes.f90 b/tests/test_wavekin_modes.f90 index 07f64166..d85f2004 100644 --- a/tests/test_wavekin_modes.f90 +++ b/tests/test_wavekin_modes.f90 @@ -14,6 +14,8 @@ !> equals the record's two harmonics to 1e-10 m), and velocity and acceleration, which !> MoorDyn-C interpolates in the stretched depth on its 0.25 m grid, within 1e-3 of their !> scale; +!> - WvHiCOff: 1 rad/s keeps only the record's 8 s harmonic, exactly; none keeps both, as the +!> 0.5 Hz default does (the record has nothing above it); !> - Currents 1: identical to 1e-12 m/s; !> - the MoorDyn-C modes CableDyn does not support fail closed by name. PROGRAM test_wavekin_modes @@ -27,6 +29,7 @@ PROGRAM test_wavekin_modes CALL check_mode('wavekin_mdc/wavekin3.dat', 'wavekin_mdc/mdc_wavekin3.csv', 'WaveKin 3', 1.0e-6_wp, & 1.0e-3_wp, 1.0e-3_wp) CALL check_record() + CALL check_cutoff() CALL check_mode('wavekin_mdc/currents1.dat', 'wavekin_mdc/mdc_currents1.csv', 'Currents 1', 1.0e-12_wp, & 1.0e-12_wp, 1.0e-12_wp, absolute=.TRUE.) CALL check_rejections() @@ -138,6 +141,52 @@ SUBROUTINE check_record() CALL require(err <= 1.0e-10_wp, 'WaveKin 3 reproduces the recorded elevation') END SUBROUTINE check_record + SUBROUTINE check_cutoff() + !! WvHiCOff drops the record's components above it: at 1 rad/s only 0.8 cos(2 pi t/8) of + !! wave_elevation.txt is left; with none the record is reproduced as with the default. + REAL(wp), PARAMETER :: PI = 3.14159265358979323846_wp + REAL(wp) :: pos(3, 5), t(5), eta(5), vel(3, 5), acc(3, 5), err_cut, err_none + CHARACTER(1024) :: line + INTEGER :: es, i, u_in, u_cut, u_none, ios + CHARACTER(512) :: em + OPEN (NEWUNIT=u_in, FILE='wavekin_mdc/wavekin3.dat', STATUS='OLD', ACTION='READ') + OPEN (NEWUNIT=u_cut, FILE='wavekin_mdc/wavekin3_cut.dat', STATUS='REPLACE', ACTION='WRITE') + OPEN (NEWUNIT=u_none, FILE='wavekin_mdc/wavekin3_none.dat', STATUS='REPLACE', ACTION='WRITE') + DO + READ (u_in, '(A)', IOSTAT=ios) line + IF (ios /= 0) EXIT + WRITE (u_cut, '(A)') TRIM(line) + WRITE (u_none, '(A)') TRIM(line) + IF (INDEX(line, 'dtWave') > 0) THEN + WRITE (u_cut, '(A)') '1.0 WvHiCOff' + WRITE (u_none, '(A)') 'none WvHiCOff' + END IF + END DO + CLOSE (u_in); CLOSE (u_cut); CLOSE (u_none) + pos = 0.0_wp + pos(3, :) = -10.0_wp + t = [0.0_wp, 1.23_wp, 5.55_wp, 13.01_wp, 27.7_wp] + CALL CD_Deck_Fluid_Probe('wavekin_mdc/wavekin3_cut.dat', pos, t, eta, vel, acc, es, em) + CALL require(es == CD_DECKDRV_OK, 'WvHiCOff 1 rad/s evaluated: '//TRIM(em)) + IF (es /= CD_DECKDRV_OK) RETURN + err_cut = 0.0_wp + DO i = 1, SIZE(t) + err_cut = MAX(err_cut, ABS(eta(i) - 0.8_wp*COS(2.0_wp*PI*t(i)/8.0_wp))) + END DO + CALL CD_Deck_Fluid_Probe('wavekin_mdc/wavekin3_none.dat', pos, t, eta, vel, acc, es, em) + CALL require(es == CD_DECKDRV_OK, 'none WvHiCOff evaluated: '//TRIM(em)) + IF (es /= CD_DECKDRV_OK) RETURN + err_none = 0.0_wp + DO i = 1, SIZE(t) + err_none = MAX(err_none, ABS(eta(i) - (0.8_wp*COS(2.0_wp*PI*t(i)/8.0_wp) + & + 0.4_wp*SIN(2.0_wp*PI*t(i)/5.0_wp + 0.3_wp)))) + END DO + WRITE (*, '(A,ES10.3,A,ES10.3,A)') 'WvHiCOff: 1 rad/s vs the 8 s harmonic ', err_cut, ' m; none vs the record ', & + err_none, ' m' + CALL require(err_cut <= 1.0e-10_wp, 'WvHiCOff 1 rad/s keeps only the 8 s harmonic') + CALL require(err_none <= 1.0e-10_wp, 'none WvHiCOff reproduces the record') + END SUBROUTINE check_cutoff + SUBROUTINE write_fail_deck(path, wavekin, currents, extra_option) !! The shared probe deck with the given WaveKin and Currents rows (and an optional extra !! OPTIONS row). From b891e559265cc171846971bff19c86e394e1dd21 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 28 Oct 2026 16:13:14 +0900 Subject: [PATCH 4/4] fix(waves): an elevation record at TMax = 0 reduces over its own length A WaterKin WaveKinMod 1 deck sizes its Fourier window from TMax, as MoorDyn-F does, and refused TMax = 0, the check of a dynamic deck's static start. At TMax = 0 the window is now the record's own length. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 3 +++ src/CableDyn_DeckDriver.f90 | 13 ++++++++----- tests/test_deck_driver.f90 | 7 +++++++ 3 files changed, 18 insertions(+), 5 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 0e53302f..8711f8d5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -87,6 +87,9 @@ All notable changes to CableDyn are recorded in this file. The format follows ### Fixed +- A deck with a WaterKin elevation history (`WaveKinMod 1`) at `TMax = 0`, a check of the static + start, reduces the record over its own length instead of failing for want of a positive + `TMax`. - Reading a WaterKin `WaveKinFile` no longer slows with the square of its length: the rows grow by doubling instead of copying the whole record per row. A 10 s run on a 168,000-row record took 107 s and now takes 3.5 s. diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 6866301f..d6d19fe5 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -12424,7 +12424,7 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma INTEGER :: unit, ios, n, n_window, j, k, nc, nraw, bracket, row_status, lineno CHARACTER(DECK_RECLEN) :: line CHARACTER(1024) :: why - REAL(wp) :: te_row(2), tr, dt, tol, angle, ca, sa, scale, frac + REAL(wp) :: te_row(2), tr, dt, tol, angle, ca, sa, scale, frac, window REAL(wp) :: cos_step, sin_step, cos_j, sin_j, cos_next, trig_norm REAL(wp), ALLOCATABLE :: times(:), eta_rows(:), sample_eta(:), grown(:) LOGICAL :: data_started @@ -12436,8 +12436,8 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma '(double-counting); keep one') RETURN END IF - IF (.NOT. IEEE_IS_FINITE(fft_tmax) .OR. fft_tmax <= CD_ZERO) THEN - CALL fail(ErrStat, ErrMsg, 'WaterKin WaveKinMod 1 requires a finite positive deck or '// & + IF (.NOT. IEEE_IS_FINITE(fft_tmax) .OR. fft_tmax < CD_ZERO) THEN + CALL fail(ErrStat, ErrMsg, 'WaterKin WaveKinMod 1 requires a finite non-negative deck or '// & 'host TMax for its FFT window') RETURN END IF @@ -12506,14 +12506,17 @@ SUBROUTINE read_wave_elevation_components(path, opts, dt_wave, wave_dir, fft_tma ! MoorDyn-F sizes the resampled record from the RUN TMax, not from the input ! file length, then zero-pads to an efficient even FFT size. A longer file is ! truncated to the run window; a shorter file leaves the uncovered tail zero. + ! TMax = 0, a check of the static start, takes the record's own length instead. + window = fft_tmax + IF (.NOT. window > CD_ZERO) window = times(nraw) dt = dt_wave ! Bound the resampled record before sizing it: CEILING of a ratio beyond the ! INTEGER range is undefined, and the one-time DFT setup grows with its square. - IF (.NOT. (fft_tmax/dt <= MAX_WAVE_SAMPLES)) THEN + IF (.NOT. (window/dt <= MAX_WAVE_SAMPLES)) THEN CALL fail(ErrStat, ErrMsg, 'WaterKin TMax/dtWave needs more than '//TRIM(int_to_str(INT(MAX_WAVE_SAMPLES)))// & ' wave samples; increase dtWave or reduce TMax'); RETURN END IF - n_window = CEILING(fft_tmax/dt) + n_window = CEILING(window/dt) n = padded_fft_size(n_window) IF (n > LONG_WAVE_RECORD) WRITE (error_unit, '(A)') ' Note: reducing the WaterKin wave record ('// & TRIM(int_to_str(n))//' samples) to Fourier components; this one-time setup grows with the square '// & diff --git a/tests/test_deck_driver.f90 b/tests/test_deck_driver.f90 index a7fcf729..f7a302f1 100644 --- a/tests/test_deck_driver.f90 +++ b/tests/test_deck_driver.f90 @@ -645,6 +645,13 @@ PROGRAM test_deck_driver wave_file='wk_eta_short.dat', dtwave=0.25_wp) CALL write_waterkin_file('wk_wave_padded.dat', wavekinmod='1', deepest_first=.FALSE., & wave_file='wk_eta_padded.dat', dtwave=0.25_wp) + ! TMax = 0 (a static-start check) reduces the record over its own length: 40 s of a 10 s wave + CALL write_wave_elevation_file('wk_eta_t0.dat', 1.0_wp, 10.0_wp, 0.0_wp, nperiods=4) + CALL write_waterkin_file('wk_wave_t0.dat', wavekinmod='1', deepest_first=.FALSE., & + wave_file='wk_eta_t0.dat', dtwave=0.25_wp) + CALL write_dynamic_connect_deck('deck_wk_wave_t0.dat', option_row='wk_wave_t0.dat WaterKin', run_tmax=0.0_wp) + CALL CD_Run_Deck_Driver('deck_wk_wave_t0.dat', 'deck_wk_wave_t0', conv, es, em) + CALL require(es == CD_DECKDRV_OK .AND. conv, 'WaveKinMod 1 record at TMax = 0 checks the static start: '//TRIM(em)) ! a 1 s window has no component at or below the default 0.5 Hz WvHiCOff: refused by name CALL write_dynamic_connect_deck('deck_wk_wave_cut.dat', option_row='wk_wave_short.dat WaterKin', & run_tmax=1.0_wp)