diff --git a/doc/capi.rst b/doc/capi.rst index a4d00fd6..b28eabd3 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -1024,7 +1024,10 @@ The deck is validated under the standalone-deck rules: The C ABI has no simulation clock and no per-node fluid input. A deck's current is applied as a steady field. A deck with a ``waves`` option, or a MoorDyn-C ``Currents 2``/``5`` table that varies in time, is rejected with ``CD_C_BAD_INPUT``, because it could not be evaluated - in time; such a table constant in time is applied as the steady field. Time-varying fluid kinematics reach the ``Free`` + in time; such a table constant in time is applied as the steady field. On a deck of + ``EI = 0`` lines the field is sampled at every node of the static state and again at the + step-start nodes before every ``CableDyn_Step``, as the standalone driver samples it, so a + depth profile or grid follows the line. Time-varying fluid kinematics reach the ``Free`` and ``Connect`` points through ``CableDyn_UpdatePointFluidFields``. Parse and validation failures, including a file that cannot be opened, return diff --git a/doc/driver_format.md b/doc/driver_format.md index eb2d0104..743375ab 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -1357,7 +1357,9 @@ every node's position and time as MoorDyn-C interpolates them. Standalone decks - a grid holds at most 2e6 resampled points in space and time (every static solve holds a copy, 48 MB at the limit); - the C API and the OpenFAST point-system shells have no simulation clock: they apply a current - constant in time as a steady field, as `Currents 1`, and refuse one that varies in time; + constant in time as a steady field, as `Currents 1`, sampled at the nodes of the static state + and, through the C API, at the step-start nodes before every step, and refuse one that varies + in time; - `current_profile_4d.txt` is read as MoorDyn-C documents it, which MoorDyn-C v2.7.1 does not quite do: it reads its rows from line 7, so a row on line 6 leaves that grid point at zero, and it matches a row to the grid by the text of its coordinates, so a row writing `-0` for `0` or diff --git a/python/tests/test_point_current_profile.py b/python/tests/test_point_current_profile.py new file mode 100644 index 00000000..a0ab636d --- /dev/null +++ b/python/tests/test_point_current_profile.py @@ -0,0 +1,142 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""A deck of ``EI = 0`` lines in a depth-profile current, stepped in-process. + +The current falls from 1.3 m/s at the surface to 0.23 m/s at the seabed. The line takes it at +its own nodes, at the static state and before every step: held at rest the model stays at +rest, and its start is the standalone driver's static state. +""" + +from __future__ import annotations + +import os +import subprocess +from ctypes import POINTER, byref, c_bool, c_double, c_int +from pathlib import Path + +import numpy as np +import pytest + +try: + from cabledyn._lib import _lib +except OSError as exc: + pytest.skip(f"CableDyn shared library not available: {exc}", allow_module_level=True) + +from cabledyn.model import CableDyn + +CHANNELS = ["FairTen1", "AnchTen1", "Point1Fx", "Point1Fy", "Point1Fz"] + +DECK = """--------------------- CableDyn Input File ------------------------------------ +A chain catenary in a depth-profile current +--------------------- LINE TYPES --------------------------------------- +TypeName Diam Mass EA BA EI Cd_n Cd_t Ca_n Ca_t +(-) (m) (kg/m) (N) (N-s) (N-m2) (-) (-) (-) (-) +chain 0.1754 189.03 8.112e8 -0.5 0.0 2.4 1.15 1.0 0.5 +--------------------- POINTS ------------------------------------------- +ID Type X Y Z +(-) (-) (m) (m) (m) +1 Coupled -2.667 6.615 -9.621 +2 Fixed -189.019 -269.414 -137.53 +--------------------- LINES -------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 1 2 - +--------------------- SECTIONS ----------------------------------------- +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 chain 430.23 25 +--------------------- OPTIONS ------------------------------------------ +137.53 WtrDpth +1.0e5 kBot +profile 0.0 0.5435 1.1875 0.0 -137.53 0.0946 0.2066 0.0 current +0.02 dtM +0.0 TMax +--------------------- OUTPUTS ------------------------------------------ +FairTen1 +AnchTen1 +Point1Fx +Point1Fy +Point1Fz +--------------------- need this line ----------------------------------- +""" + + +@pytest.fixture +def deck(tmp_path: Path) -> Path: + path = tmp_path / "profile_chain.dat" + path.write_text(DECK, encoding="utf-8", newline="\n") + return path + + +def test_held_line_stays_at_rest(deck: Path) -> None: + with CableDyn(deck) as model: + start = model.channels(CHANNELS) + for _ in range(100): + model.step_held(0.02) + end = model.channels(CHANNELS) + scale = abs(start[0]) + assert np.max(np.abs(end - start)) < 1.0e-6 * scale, (start, end) + + +def test_a_refused_step_leaves_the_loads(deck: Path) -> None: + # After the fairlead has moved, the field the next step samples differs from the held one. + # A step the library refuses (dt <= 0, or a non-finite motion: both bypass the binding's own + # checks here) commits nothing, so the loads after it are those before it, bit for bit. + with CableDyn(deck) as model: + q0, _, _ = model.get_coupled_motion() + dt, n = 0.02, 20 + for k in range(1, n + 1): + s = k / n + shape = s * s * (3.0 - 2.0 * s) # smooth 2 m surge, at rest at both ends + rate = 6.0 * s * (1.0 - s) / (n * dt) + accel = 6.0 * (1.0 - 2.0 * s) / (n * dt) ** 2 + q = q0.copy() + q[0] += 2.0 * shape + v = np.zeros_like(q0) + v[0] = 2.0 * rate + a = np.zeros_like(q0) + a[0] = 2.0 * accel + model.step(dt, q, v, a) + before = model.calc_output() + channels = model.channels(CHANNELS) + nan_q = q.copy() + nan_q[0] = float("nan") + for step_dt, motion in ((-1.0, q), (dt, nan_q)): + qa = np.ascontiguousarray(motion, dtype=np.float64) + va = np.zeros_like(qa) + aa = np.zeros_like(qa) + conv, stall, nit, status = c_bool(), c_bool(), c_int(), c_int() + _lib.CableDyn_Step( + model._handle, + step_dt, + qa.ctypes.data_as(POINTER(c_double)), + va.ctypes.data_as(POINTER(c_double)), + aa.ctypes.data_as(POINTER(c_double)), + qa.size, + byref(conv), + byref(stall), + byref(nit), + byref(status), + ) + assert status.value != 0 + assert np.array_equal(model.calc_output(), before) + assert np.array_equal(model.channels(CHANNELS), channels) + + +@pytest.mark.skipif( + not os.environ.get("CABLEDYN_DRIVER", "").strip(), + reason="set CABLEDYN_DRIVER to compare with the standalone driver", +) +def test_start_is_the_driver_static_state(deck: Path, tmp_path: Path) -> None: + root = tmp_path / "profile_chain" + proc = subprocess.run( + [os.environ["CABLEDYN_DRIVER"].strip(), str(deck), str(root)], + capture_output=True, + text=True, + ) + assert proc.returncode == 0, proc.stdout + proc.stderr + rows = Path(str(root) + ".out").read_text(encoding="utf-8").splitlines() + driver = np.array([float(v) for v in rows[2].split()[1:]]) + with CableDyn(deck) as model: + start = model.channels(CHANNELS) + assert np.max(np.abs(start - driver)) < 2.0e-7 * abs(driver[0]), (start, driver) diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 61655166..d76c3ff7 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -14,6 +14,7 @@ MODULE CableDyn_CAPI USE, INTRINSIC :: ISO_FORTRAN_ENV, ONLY: INT64, COMPILER_VERSION USE, INTRINSIC :: IEEE_ARITHMETIC, ONLY: IEEE_IS_FINITE USE CableDyn_DeckDriver, ONLY: CD_Init_Deck_System, CD_DECKDRV_OK, CD_DECKDRV_BADINPUT, CD_DECKDRV_SOLVEFAIL, & + CD_DeckCurrentRuntimeType, CD_Deck_Current_Active, CD_Deck_Current_Sample_System, & CD_Deck_Query_dtM, CD_DECK_NAMELEN, CD_Eval_Aggregate_Channel, & CD_Eval_Aggregate_Segment_Tensions, CD_Eval_Aggregate_Line_Values, & CD_Rigid6_Inventory, CD_Rod_Inventory, CD_Channel_Token_Parses, CD_Cable_Deck_Node, & @@ -27,7 +28,7 @@ MODULE CableDyn_CAPI USE CableDyn_Dynamic, ONLY: GenAlphaConfig USE CableDyn_Linalg, ONLY: CD_Blas_Runtime_Check, CD_LINALG_OK USE CableDyn_Model, ONLY: CD_ModelType, CD_Init_Model, CD_End_Model, CD_MODEL_OK, CD_MODEL_BADINPUT, & - CD_MODEL_SOLVEFAIL, CD_MODEL_ALLOCFAIL + CD_MODEL_SOLVEFAIL, CD_MODEL_ALLOCFAIL, CD_Update_Model_Hydro_Fields USE CableDyn_OpenFAST, ONLY: CD_FAST_ModuleType, CD_FAST_End, CD_FAST_Init_From_Models, & CD_FAST_UpdateStates, CD_FAST_Step, CD_FAST_CalcOutput, & CD_FAST_CalcOutputDerivatives, CD_FAST_GetCoupledMotion, CD_FAST_IsInitialized, & @@ -170,6 +171,9 @@ END FUNCTION cabledyn_blas_threads_once ! coupled DOFs, its step is the deck dtM (agg_dt), and agg_t is its committed time. LOGICAL :: use_agg = .FALSE. TYPE(CD_AGG_ModuleType) :: agg + ! The point route's deck current (a steady field), sampled at the step-start node positions + ! before every step, as the standalone point-system march samples it. + TYPE(CD_DeckCurrentRuntimeType) :: pt_current REAL(wp) :: agg_dt = CD_ZERO, agg_t = CD_ZERO REAL(wp), ALLOCATABLE :: agg_pos(:, :), agg_vel(:, :), agg_acc(:, :), agg_load(:, :) ! A handle initialised by CableDyn_InitDeckRotating (host_rot): the host's rotation of each @@ -391,6 +395,7 @@ SUBROUTINE init_deck_build(handle, deck_path_ptr, deck_path_len, caller, err_sta TYPE(CD_C_Handle), POINTER :: h TYPE(CD_FAST_ModuleType) :: new_fast + TYPE(CD_DeckCurrentRuntimeType) :: new_current CHARACTER(KIND=C_CHAR), POINTER :: path_c(:) CHARACTER(:), ALLOCATABLE :: deck_path INTEGER :: i, es, end_es, stat, n_objects, n_finite @@ -438,7 +443,7 @@ SUBROUTINE init_deck_build(handle, deck_path_ptr, deck_path_len, caller, err_sta END IF ! An absent positions argument stays absent through the optional coupled_positions. CALL CD_Init_Deck_System(TRIM(deck_path), new_fast%system, dtm, gravity, rho_water, es, em, line_ids=line_ids, & - coupled_positions=positions) + coupled_positions=positions, deck_current=new_current) IF (es /= CD_DECKDRV_OK) THEN CALL map_deck_status(es, err_stat) CALL store_status(h, err_stat, caller//': '//TRIM(em)) @@ -455,6 +460,7 @@ SUBROUTINE init_deck_build(handle, deck_path_ptr, deck_path_len, caller, err_sta END IF CALL CD_FAST_End(h%fast, end_es, end_em) h%fast = new_fast + h%pt_current = new_current CALL CD_FAST_End(new_fast, end_es, end_em) CALL drop_aggregate(h) CALL drop_saved_state(h) @@ -602,6 +608,7 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, rotating, err END IF CALL add_aggregate_notes(new_agg) CALL CD_FAST_End(h%fast, es, em) + CALL drop_point_current(h) CALL drop_aggregate(h) CALL drop_saved_state(h) CALL clear_c_workspace(h) @@ -699,6 +706,14 @@ SUBROUTINE drop_saved_state(h) h%has_saved = .FALSE. END SUBROUTINE drop_saved_state + SUBROUTINE drop_point_current(h) + !! Forget the point route's deck current (a model built from raw lines or on the aggregate + !! has none of its own). + TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h + TYPE(CD_DeckCurrentRuntimeType) :: none + h%pt_current = none + END SUBROUTINE drop_point_current + SUBROUTINE drop_aggregate(h) !! Release the aggregate route of a handle (another initialization replaces it). TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h @@ -850,6 +865,7 @@ SUBROUTINE init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_co CALL CD_End_Model(model, es, em) RETURN END IF + CALL drop_point_current(h) CALL CD_FAST_Init_From_Models(h%fast, [model], es, fast_em) CALL CD_End_Model(model, end_es, em) CALL map_fast_status(es, err_stat) @@ -1045,6 +1061,7 @@ SUBROUTINE init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fix elem_off = elem_stop fixed_off = fixed_stop END DO + CALL drop_point_current(h) IF (ALLOCATED(coupled_map)) THEN CALL CD_FAST_Init_From_Models(h%fast, models, es, em, coupled_dof_map=coupled_map) ELSE @@ -1337,9 +1354,15 @@ SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converg INTEGER(C_INT), INTENT(OUT) :: n_iter, err_stat TYPE(CD_C_Handle), POINTER :: h REAL(C_DOUBLE), POINTER :: q_c(:), v_c(:), a_c(:) - LOGICAL :: conv_f, stall_f + LOGICAL :: conv_f, stall_f, sampled INTEGER :: es, nit CHARACTER(CD_C_MSG_LEN) :: em + ! the point route's drag fields before the step's current sample, put back by a step that + ! does not commit + TYPE :: held_fluid + REAL(wp), ALLOCATABLE :: velocity(:, :), waterline(:) + END TYPE held_fluid + TYPE(held_fluid), ALLOCATABLE :: held(:) converged = .FALSE._C_BOOL stalled = .FALSE._C_BOOL @@ -1381,8 +1404,22 @@ SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converg h%v_work(1:INT(n_coupled_dof)) = REAL(v_c, wp) h%a_work(1:INT(n_coupled_dof)) = REAL(a_c, wp) END IF + ! the deck's steady current at the step-start node positions, held over the step; a step + ! that does not commit (refused input or a hard failure) puts back the fields it replaced, + ! so the model's loads are those before the call + sampled = CD_Deck_Current_Active(h%pt_current) + IF (sampled) THEN + CALL hold_point_fluid() + CALL CD_Deck_Current_Sample_System(h%pt_current, h%fast%system, CD_ZERO, es, em) + IF (es /= CD_DECKDRV_OK) THEN + CALL restore_point_fluid() + CALL set_status(h, CD_C_SOLVE_FAIL, 'CableDyn_Step: '//TRIM(em), err_stat) + RETURN + END IF + END IF CALL CD_FAST_Step(h%fast, REAL(dt, wp), h%q_work(1:INT(n_coupled_dof)), h%v_work(1:INT(n_coupled_dof)), & h%a_work(1:INT(n_coupled_dof)), conv_f, stall_f, nit, es, em) + IF (sampled .AND. es /= CD_FAST_OK) CALL restore_point_fluid() converged = LOGICAL(conv_f, C_BOOL) stalled = LOGICAL(stall_f, C_BOOL) n_iter = INT(nit, C_INT) @@ -1392,6 +1429,34 @@ SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converg CONTAINS + SUBROUTINE hold_point_fluid() + !! Keep each line's drag fluid velocity and waterline. + INTEGER :: il + ALLOCATE (held(SIZE(h%fast%system%lines))) + DO il = 1, SIZE(held) + IF (ALLOCATED(h%fast%system%lines(il)%fluid_velocity)) & + held(il)%velocity = h%fast%system%lines(il)%fluid_velocity + IF (ALLOCATED(h%fast%system%lines(il)%drag_waterline_z)) & + held(il)%waterline = h%fast%system%lines(il)%drag_waterline_z + END DO + END SUBROUTINE hold_point_fluid + + SUBROUTINE restore_point_fluid() + !! Put back the fields hold_point_fluid kept (the values the model held, so they pass the + !! setter's checks). + INTEGER :: il, es_r + CHARACTER(CD_C_MSG_LEN) :: em_r + IF (.NOT. ALLOCATED(held)) RETURN + DO il = 1, SIZE(held) + IF (ALLOCATED(held(il)%velocity) .AND. ALLOCATED(held(il)%waterline)) THEN + CALL CD_Update_Model_Hydro_Fields(h%fast%system%lines(il), es_r, em_r, fluid_velocity=held(il)%velocity, & + drag_waterline_z=held(il)%waterline) + ELSE IF (ALLOCATED(held(il)%velocity)) THEN + CALL CD_Update_Model_Hydro_Fields(h%fast%system%lines(il), es_r, em_r, fluid_velocity=held(il)%velocity) + END IF + END DO + END SUBROUTINE restore_point_fluid + SUBROUTINE clear_failed_step_flags() !! A step that did not commit reports converged = stalled = false and n_iter = 0 on !! every route (the documented hard-failure contract). diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 4a765731..8a028c16 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -1359,7 +1359,7 @@ SUBROUTINE CD_Init_Deck_Models(deck_path, models, ErrStat, ErrMsg) END SUBROUTINE CD_Init_Deck_Models SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrStat, ErrMsg, caller_driven, & - env_gravity, env_rho_water, env_wtrdpth, line_ids, coupled_positions) + env_gravity, env_rho_water, env_wtrdpth, line_ids, coupled_positions, deck_current) !! Parse a supported EI=0 deck and initialize one persistent multi-line !! CableDyn system with product-facing points and endpoint bindings. !! caller_driven (default .FALSE.): the host marches the system, so the deck's @@ -1381,6 +1381,9 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt REAL(wp), INTENT(IN), OPTIONAL :: env_gravity, env_rho_water, env_wtrdpth INTEGER, ALLOCATABLE, INTENT(OUT), OPTIONAL :: line_ids(:) REAL(wp), INTENT(IN), OPTIONAL :: coupled_positions(:, :) + ! The deck's steady current, for the caller to sample at the node positions before every + ! step (CD_Deck_Current_Sample_System); inactive without a deck current. + TYPE(CD_DeckCurrentRuntimeType), INTENT(OUT), OPTIONAL :: deck_current TYPE(DeckLineType), ALLOCATABLE :: types(:) TYPE(DeckBody), ALLOCATABLE :: bodies(:) @@ -1392,6 +1395,7 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt TYPE(DeckOptions) :: opts CHARACTER(NAMELEN), ALLOCATABLE :: channels(:) TYPE(CD_BathymetryType) :: bathymetry + TYPE(HydroUpdateWorkspace) :: current_work LOGICAL :: ext_march INTEGER :: i ErrStat = CD_DECKDRV_OK @@ -1471,6 +1475,18 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt ELSE CALL init_deck_system_from_parsed(types, points, lines, sections, opts, system, ErrStat, ErrMsg) END IF + ! A line model takes its drag's fluid velocity at the nodes of its straight seed; the static + ! solve samples a depth profile or grid at its own node positions. The field is sampled + ! again at the static nodes (the t = 0 state), as the standalone march does before its first + ! step, so the end loads at the start are those of the static state and a caller stepping + ! the system at rest stays at rest. A uniform current is the same at every node. + IF (ErrStat == CD_DECKDRV_OK .AND. opts%has_current) THEN + CALL update_system_line_hydro(system, opts, CD_ZERO, current_work, ErrStat, ErrMsg, initial_condition=.TRUE.) + IF (ErrStat == CD_DECKDRV_OK .AND. PRESENT(deck_current)) THEN + deck_current%active = .TRUE. + deck_current%opts = opts + END IF + END IF IF (PRESENT(line_ids) .AND. ErrStat == CD_DECKDRV_OK) THEN ALLOCATE (line_ids(SIZE(lines))) line_ids = lines(:)%id