From 56a892252af6fd407f3e9f3a2053c6cce2be0f42 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 20:05:00 +0900 Subject: [PATCH 1/6] feat(capi): step decks in moving water in-process On a deck with finite-EI lines, bodies or rods the C API and Python ran in still water only: a deck current was refused, and no call reached the line nodes. - A steady deck current (current, WaterKin CurrentMod 1, MoorDyn-C Currents 1) is marched in-process, in the static start and in every step, also from host start positions. - A host can supply the ambient fluid at every node instead (ABI 1.4): CableDyn_SetHostFluid before the initialization, then CableDyn_NFluidNodes, CableDyn_GetFluidNodePositions and CableDyn_UpdateFluidFields; in Python set_host_fluid, n_fluid_nodes, fluid_node_positions and update_fluid_fields. A steady deck current then sets the static start only, as a host's current does in OpenFAST. - The field follows the standalone march and OpenFAST: sampled at t + dt at the step-start nodes and held over the step. The first field, at t = 0, sets the start acceleration, on EI = 0 lines too, and a step without a field is refused. Stepped in current and regular waves, a cable matches the standalone driver to the digits of its output (NRMSE 2e-7), with a stiffener and as-laid seabed friction too; SaveState and RestoreState carry the field. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 11 + doc/api_python.rst | 46 +++- doc/capabilities.rst | 3 +- doc/capi.rst | 67 +++++- doc/coupling_boundary.md | 9 +- doc/options.rst | 2 +- doc/python.rst | 29 ++- python/cabledyn/_lib.py | 37 ++- python/cabledyn/model.py | 101 ++++++++ python/tests/test_host_fluid.py | 352 ++++++++++++++++++++++++++++ python/tests/test_host_rotation.py | 2 +- python/tests/test_objects.py | 2 +- src/CableDyn_CAPI.f90 | 192 ++++++++++++++- src/CableDyn_CAPI.h | 34 ++- src/CableDyn_DeckDriver.f90 | 55 ++++- src/CableDyn_OpenFAST_Aggregate.f90 | 26 +- src/cabledyn.def | 4 + src/cabledyn.exp | 4 + src/cabledyn.map | 4 + tests/test_c_api_host_rotation.c | 38 ++- 20 files changed, 977 insertions(+), 41 deletions(-) create mode 100644 python/tests/test_host_fluid.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e55d9c4..cfadb54d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,17 @@ All notable changes to CableDyn are recorded in this file. The format follows ## [Unreleased] +### Added + +- In-process stepping in moving water (ABI 1.4). On decks with finite-EI lines, bodies or rods + the C API and Python march a steady deck current (`current`, WaterKin `CurrentMod 1`, MoorDyn-C + `Currents 1`), in the static start and in every step. A host can instead supply the fluid at + every line node: `CableDyn_SetHostFluid`, `CableDyn_NFluidNodes`, + `CableDyn_GetFluidNodePositions` and `CableDyn_UpdateFluidFields`, in Python `set_host_fluid`, + `n_fluid_nodes`, `fluid_node_positions` and `update_fluid_fields`. The field is sampled and held + as in the standalone march and in OpenFAST; in current and waves a stepped cable matches the + standalone driver to the digits of its output. + ### Fixed - The C API messages of `CableDyn_UpdatePointFluidFields` and `CableDyn_CalcOutputDerivatives` on diff --git a/doc/api_python.rst b/doc/api_python.rst index 20262612..93aeefdc 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -710,6 +710,49 @@ library is located. Array ordering, frames, and units at the coupling boundary f :rtype: numpy.ndarray :raises CableDynError: if the call fails. + .. py:method:: set_host_fluid(enable=True) + + Choose, before a deck initialization, whether the host supplies the ambient fluid. + With ``enable``, the following :meth:`init_deck`, :meth:`init_deck_at` and + :meth:`init_deck_rotating` take the field of :meth:`update_fluid_fields`: deck waves + are refused and a steady deck current sets the static start only. + + :param enable: Whether the host supplies the fluid. + :type enable: bool + :raises CableDynError: if the call fails. + + .. py:attribute:: n_fluid_nodes + + Nodes of the host fluid field; zero without one. + + .. py:method:: fluid_node_positions() + + Committed positions of the fluid nodes, where the host evaluates the field of the + coming step. + + :returns: Global positions (m), shaped ``(3, n_fluid_nodes)``. + :rtype: numpy.ndarray + :raises CableDynError: on a model built without a host fluid field. + + .. py:method:: update_fluid_fields(fluid_velocity, fluid_acceleration, waterline_z, dynamic_pressure=None) + + Prescribe the ambient fluid at every fluid node, held until the next call. Call it + once with the field at ``t = 0`` before the first step, then before each step from + ``t`` to ``t + dt`` with the field at ``t + dt`` at the positions of + :meth:`fluid_node_positions`. The density is the deck's. + + :param fluid_velocity: Whole ambient velocity (m/s), global axes, shaped + ``(3, n_fluid_nodes)`` or flat. + :type fluid_velocity: array_like + :param fluid_acceleration: Fluid acceleration (m/s\ :sup:`2`), with the same shape. + :type fluid_acceleration: array_like + :param waterline_z: Free-surface elevation above each node (m), ``(n_fluid_nodes,)``. + :type waterline_z: array_like + :param dynamic_pressure: Wave dynamic pressure (Pa) for the end caps of rods. + :type dynamic_pressure: array_like, optional + :raises CableDynError: on a model built without a host fluid field, or if the call + fails. + .. py:method:: update_point_fluid_fields(fluid_velocity, fluid_acceleration, waterline_z, fluid_density) Prescribe external fluid kinematics at every system point. @@ -828,7 +871,8 @@ imports without the shared library. .. py:function:: abi_minor() - Return the extension level of ABI 1 of the loaded library: 3 when it also has the + Return the extension level of ABI 1 of the loaded library: 4 when it also has the host + fluid calls behind :meth:`CableDyn.update_fluid_fields`, 3 when it has the host-rotation calls behind :meth:`CableDyn.init_deck_rotating`, :meth:`CableDyn.update_rotations` and :meth:`CableDyn.coupled_moments`, 2 when it has the host-coupling calls behind :meth:`CableDyn.init_deck_at`, :meth:`CableDyn.save_state` and diff --git a/doc/capabilities.rst b/doc/capabilities.rst index cfba7e1d..6bfe8d75 100644 --- a/doc/capabilities.rst +++ b/doc/capabilities.rst @@ -221,7 +221,8 @@ node that takes the platform position only and returns a force with zero moment, rods turn about a fixed End A. A coupled deck (OpenFAST, the C API and Python) carries bodies or rods, not both, a rod fixed to a body counting as a rod; the standalone driver's multibody march takes both, as does MoorDyn (``CompMooring = 3``). The C API and Python -run free, fixed and pinned rods and free bodies in still water. The coupled body/rod routes carry +run free, fixed and pinned rods and free bodies in still water or in a field the host supplies +at the nodes (:doc:`capi`). The coupled body/rod routes carry checkpoint state and SeaState drag, Froude–Krylov, and added mass. ``Rigid6`` also carries the documented hydrostatic restoring terms. Consult :doc:`driver_format` before using an imported object because unsupported fields fail closed. diff --git a/doc/capi.rst b/doc/capi.rst index 5fac1f83..25baf74a 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -29,11 +29,12 @@ A model lives behind an opaque handle. The lifecycle is: .. code-block:: text CableDyn_Create + -> [CableDyn_SetHostFluid] (host fluid field) -> CableDyn_InitDeck | CableDyn_InitDeckAt | CableDyn_InitDeckRotating | CableDyn_InitLine | CableDyn_InitLines (initialize; may repeat) -> CableDyn_GetCoupledMotion (read the initial state) -> loop: [CableDyn_SaveState | CableDyn_RestoreState] (host outer correctors) - [CableDyn_UpdatePointFluidFields] + [CableDyn_UpdatePointFluidFields | CableDyn_UpdateFluidFields] [CableDyn_UpdateRotations] (a host that turns) CableDyn_Step(dt, motion at t+dt) CableDyn_CalcOutput [, CableDyn_GetCoupledMoments] (loads at t+dt) @@ -61,6 +62,9 @@ MoorDyn's C API. - set the coupled-point motion without advancing time * - ``CableDyn_UpdatePointFluidFields`` - set fluid kinematics at the deck points (point hydrodynamics) + * - ``CableDyn_SetHostFluid``, ``CableDyn_NFluidNodes``, ``CableDyn_GetFluidNodePositions``, + ``CableDyn_UpdateFluidFields`` + - supply the ambient fluid at the nodes of every line (`Step 9: moving water`_) * - ``CableDyn_Step`` - advance one implicit step to :math:`t+\Delta t` * - ``CableDyn_CalcOutput`` @@ -685,6 +689,53 @@ The rotations are inputs, like the motion: an end frame turned by more than a qu about its line since the last committed step is refused, and ``CableDyn_SaveState``/``CableDyn_RestoreState`` carry the last rotations with the model. +Step 9: moving water +~~~~~~~~~~~~~~~~~~~~ + +A deck's steady current is marched as in the standalone driver: a ``current`` option, a WaterKin +``CurrentMod 1`` depth table or a MoorDyn-C ``Currents 1`` profile acts in the static start and in +every step, on lines between ``Fixed``, ``Coupled`` and ``Vessel`` points. Nothing else is needed. + +A host that evaluates the water itself, such as a wave field not known in advance, supplies it at +the nodes: + +.. code-block:: c + + CableDyn_SetHostFluid(h, 1, &err); /* before the initialization */ + CableDyn_InitDeckRotating(h, deck, len, q0, n_q0, &err); + n = CableDyn_NFluidNodes(h, &err); + + CableDyn_GetFluidNodePositions(h, xyz, n, &err); /* the field at t = 0 */ + CableDyn_UpdateFluidFields(h, vel, acc, eta, NULL, n, &err); + for (;;) { /* a step from t to t + dt */ + CableDyn_GetFluidNodePositions(h, xyz, n, &err); /* the step-start positions */ + /* evaluate vel, acc, eta at xyz at time t + dt */ + CableDyn_UpdateFluidFields(h, vel, acc, eta, NULL, n, &err); + CableDyn_Step(h, dt, q, v, a, n_dof, &converged, &stalled, &n_iter, &err); + } + +The convention is that of the standalone march and of the OpenFAST module: + +* the field of a step from ``t`` to ``t + dt`` is sampled at ``t + dt`` at the step-start node + positions, and it is held unchanged over the step; +* ``vel`` is the whole ambient velocity, current and waves together, ``acc`` the fluid + acceleration, both as ``x, y, z`` triples in global axes, and ``eta`` the free-surface elevation + above each node, which decides the wetting of its drag, added mass and buoyancy; +* the first call, before the first step, is the field at ``t = 0`` and sets the start acceleration; + a step without any field is refused, because the march would otherwise run in still water; +* ``dynamic_pressure`` may be ``NULL``; rods use it for their end caps; +* the density is the deck's ``rhoW``; +* the nodes are every node of every line, then the deck's bodies, rods and hydrodynamic points. + The field depends on position alone, so the host needs no node numbering; +* ``CableDyn_SaveState`` and ``CableDyn_RestoreState`` carry the held field. + +With the host field, a deck runs on the coupled aggregate whatever its lines, needs ``dtM``, and +needs a seabed if it has ``EI = 0`` lines. Deck waves are refused. A steady deck current sets the +static start only, so the start is the equilibrium in that current, and the host's field is then +the whole water of the march; a deck current that varies in time is refused. + +Seabed friction, ``staticsFriction asLaid`` and ``STIFFENERS`` work on this route. + Call sequence ~~~~~~~~~~~~~ @@ -908,8 +959,10 @@ coupled aggregate as the OpenFAST module, with these differences from the point- the order of `Coupled DOF layout`_ (anchors are not part of the vector); the bodies and rods are integrated internally; * the deck must declare ``dtM``, and every ``CableDyn_Step`` must use that ``dt``; -* the run is in still water: deck waves or currents are rejected, and - ``CableDyn_UpdatePointFluidFields`` and ``CableDyn_CalcOutputDerivatives`` return +* a deck current is marched on lines between ``Fixed``, ``Coupled`` and ``Vessel`` points, + deck waves are rejected, and other moving water comes from the host (`Step 9: moving + water`_); +* ``CableDyn_UpdatePointFluidFields`` and ``CableDyn_CalcOutputDerivatives`` return ``CD_C_BAD_INPUT``; * ``CableDyn_NPoints`` and ``CableDyn_NLines`` report the deck's point and line counts. @@ -940,13 +993,15 @@ The deck is validated under the standalone-deck rules: * - a ``CONTROL`` section (active line control) - the OpenFAST module * - ``WaveKinMod 2`` / ``SEASTATE`` wave kinematics - - the OpenFAST module + - the OpenFAST module; a host that calls ``CableDyn_SetHostFluid`` * - a ``waves`` option (regular or JONSWAP deck waves) - the standalone driver; supply time-varying fluid kinematics through - ``CableDyn_UpdatePointFluidFields`` + ``CableDyn_UpdateFluidFields`` (`Step 9: moving water`_), or at the points of a point + deck through ``CableDyn_UpdatePointFluidFields`` * - a MoorDyn-C ``Currents 2``/``5`` table that varies in time - the standalone driver; supply time-varying fluid kinematics through - ``CableDyn_UpdatePointFluidFields`` + ``CableDyn_UpdateFluidFields`` (`Step 9: moving water`_), or at the points of a point + deck through ``CableDyn_UpdatePointFluidFields`` * - FAST.Farm ``Turbine`` points - the OpenFAST module in FAST.Farm * - ``frictionMu`` in a deck that has ``Free`` or ``Connect`` points diff --git a/doc/coupling_boundary.md b/doc/coupling_boundary.md index 16950b31..2695fba0 100644 --- a/doc/coupling_boundary.md +++ b/doc/coupling_boundary.md @@ -28,9 +28,12 @@ acceleration enters the dynamic residual through the consistent mass. **Fluid fields in.** -- Line nodes take their fluid kinematics from the deck environment (waves and current) in - standalone and C API use, and from the host field in OpenFAST, where SeaState is sampled at the - structural nodes and held over the step. +- Line nodes take their fluid kinematics from the deck environment in standalone use (waves and + current) and in C API use (current), and from a host field in OpenFAST, where SeaState is sampled + at the structural nodes, and in C API use after `CableDyn_SetHostFluid`, where the host passes + velocity, acceleration and surface elevation at every node through + `CableDyn_UpdateFluidFields`. All routes sample the field of a step at `t + dt` at the + step-start node positions and hold it over the step. - Dynamic `Free`/`Connect` points with hydrodynamic properties accept an external point-level field through `CableDyn_UpdatePointFluidFields`: velocity and acceleration (3 × `n_point`), local surface elevation (`n_point`), and one fluid density. A point above its surface diff --git a/doc/options.rst b/doc/options.rst index cc59b65b..ccfa60ba 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -741,7 +741,7 @@ Ambient fluid and prescribed motion filename; ``SEASTATE`` selects the host field. The other MoorDyn-C modes fail closed by name. Mode rules are in :ref:`moordyn-c-wavekin` and :ref:`waterkin-file-modes` - ``3``/``7`` and file ``WaveKinMod 1``: standalone decks only; ``SEASTATE``, - ``WaveKinMod 2``, and ``CurrentMod 2``: OpenFAST only + ``WaveKinMod 2``, and ``CurrentMod 2``: OpenFAST and C API hosts with a host fluid field - ``waterkin.dat WaterKin`` * - ``dtWave`` - positive number [s] diff --git a/doc/python.rst b/doc/python.rst index a5ec813c..8f5e68ca 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -769,9 +769,32 @@ through the C API (:doc:`capi`). A deck with finite-EI lines, ``BODIES`` or ``RODS`` runs on the coupled aggregate and needs ``dtM``; other decks run on the point route. Decks with deck waves, a ``motionFile`` or vessel -motion are rejected in-process (they run in the standalone driver): time-varying fluid -kinematics enter through :meth:`~cabledyn.CableDyn.update_point_fluid_fields`, and motion through -the coupled kinematics of every step. +motion are rejected in-process (they run in the standalone driver): motion enters through the +coupled kinematics of every step. A steady deck current is marched in-process, in the static +start and in every step. Other moving water comes from the host, at the nodes of every line: + +.. code-block:: python + + model = cabledyn.CableDyn() + model.set_host_fluid() # before the initialization + model.init_deck_rotating(deck) + + def field(t): + xyz = model.fluid_node_positions() # (3, n), the committed positions + velocity, acceleration, elevation = my_sea(xyz, t) + model.update_fluid_fields(velocity, acceleration, elevation) + + field(0.0) # the start acceleration + for i in range(1, steps + 1): + t = i * dt + field(t) # held over the step + model.step(dt, q(t), v(t), a(t)) + +``velocity`` is the whole ambient velocity, current and waves together. The field of a step to +``t + dt`` is evaluated at ``t + dt`` at the step-start positions and held over the step, as in +the standalone march and in OpenFAST; :meth:`~cabledyn.CableDyn.save_state` carries it. A steady +deck current then sets the static start only; the rules are in :doc:`capi`. On a deck of the +point route, :meth:`~cabledyn.CableDyn.update_point_fluid_fields` sets the field at the points. A host that moves the ``Coupled`` points from its own body solver starts the model at its positions and rewinds it between the passes of an iterated time step. The save is keyed on the diff --git a/python/cabledyn/_lib.py b/python/cabledyn/_lib.py index 44c49741..910b4e5f 100644 --- a/python/cabledyn/_lib.py +++ b/python/cabledyn/_lib.py @@ -214,8 +214,7 @@ def _bind_host_coupling() -> bool: # the coupled moments. A library built before the extension lacks these symbols # and reports ``abi_minor() < 3``. -#: Minor extension level of ABI 1 this binding uses for the host-rotation calls -#: (the newest extension the binding knows). +#: Minor extension level of ABI 1 this binding uses for the host-rotation calls. HOST_ROTATION_ABI_MINOR = 3 @@ -235,6 +234,40 @@ def _bind_host_rotation() -> bool: _has_host_rotation = _bind_host_rotation() +# Host fluid field (ABI minor 4). A library built before the extension lacks these +# symbols and reports ``abi_minor() < 4``. + +#: Minor extension level of ABI 1 this binding uses for the host fluid field +#: (the newest extension the binding knows). +HOST_FLUID_ABI_MINOR = 4 + + +def _bind_host_fluid() -> bool: + try: + set_fluid = _lib.CableDyn_SetHostFluid + except AttributeError: + return False + set_fluid.argtypes = [c_void_p, c_int, POINTER(c_int)] + set_fluid.restype = None + _lib.CableDyn_NFluidNodes.argtypes = [c_void_p, POINTER(c_int)] + _lib.CableDyn_NFluidNodes.restype = c_int + _lib.CableDyn_GetFluidNodePositions.argtypes = [c_void_p, _DBL, c_int, POINTER(c_int)] + _lib.CableDyn_GetFluidNodePositions.restype = None + _lib.CableDyn_UpdateFluidFields.argtypes = [ + c_void_p, + _DBL, + _DBL, + _DBL, + _DBL, + c_int, + POINTER(c_int), + ] + _lib.CableDyn_UpdateFluidFields.restype = None + return True + + +_has_host_fluid = _bind_host_fluid() + def abi_minor() -> int: """The loaded library's ABI 1 extension level (0 before the object queries).""" diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index 97a81963..4150c4a8 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -86,6 +86,21 @@ def _as_dof_array(x: ArrayInput, n: int, name: str) -> FloatArray: return arr +def _as_field(x: ArrayInput, n: int, name: str) -> FloatArray: + """Return a per-node vector field as flat ``(3 n,)``; accepts ``(3, n)`` or flat.""" + return _as_dof_array(x, 3 * n, name) + + +def _as_node_values(x: ArrayInput, n: int, name: str) -> FloatArray: + """Return one finite value per node as a contiguous ``(n,)`` array.""" + arr = _as_real_array(x, name) + if arr.ndim != 1 or arr.size != n: + raise ValueError(f"{name} must have {n} entries") + if not np.all(np.isfinite(arr)): + raise ValueError(f"{name} must be finite (no NaN or Inf)") + return np.ascontiguousarray(arr) + + def _dbl_ptr(arr: FloatArray) -> Any: return arr.ctypes.data_as(POINTER(c_double)) @@ -310,6 +325,15 @@ def _initialized_from(self, deck: Path) -> None: self._saved_time = None self._deck = deck + @staticmethod + def _require_host_fluid() -> None: + if _lib_module.abi_minor() < _lib_module.HOST_FLUID_ABI_MINOR: + # not a C status: the loaded library lacks the entry points + raise RuntimeError( + "the loaded CableDyn library predates the host fluid calls " + "(ABI 1 minor extension 4); rebuild it from this checkout" + ) + @staticmethod def _require_host_rotation() -> None: if _lib_module.abi_minor() < _lib_module.HOST_ROTATION_ABI_MINOR: @@ -687,6 +711,83 @@ def host_dofs(self) -> npt.NDArray[np.intp]: blocks = [k for k, (_, kind) in enumerate(layout) if kind == "coupled"] return np.array([3 * k + c for k in blocks for c in range(3)], dtype=np.intp) + def set_host_fluid(self, enable: bool = True) -> None: + """Choose, before a deck initialization, whether the host supplies the fluid. + + With ``enable`` the following :meth:`init_deck`, :meth:`init_deck_at` and + :meth:`init_deck_rotating` take the field of :meth:`update_fluid_fields`: + deck waves are refused, and a steady deck current sets the static start + only. The deck needs ``dtM`` and a seabed. + """ + with self._lock: + self._require_host_fluid() + status = c_int() + _lib.CableDyn_SetHostFluid(self._handle, 1 if enable else 0, byref(status)) + self._check("CableDyn_SetHostFluid", status.value) + + @property + def n_fluid_nodes(self) -> int: + """Nodes of the host fluid field; zero without one.""" + with self._lock: + self._require_host_fluid() + status = c_int() + n = _lib.CableDyn_NFluidNodes(self._handle, byref(status)) + self._check("CableDyn_NFluidNodes", status.value) + return int(n) + + def fluid_node_positions(self) -> FloatArray: + """Committed fluid node positions ``(3, n_fluid_nodes)``, global axes [m]. + + Where the host evaluates the field of the coming step. + """ + with self._lock: + n = self.n_fluid_nodes + xyz = np.zeros(3 * n) + status = c_int() + _lib.CableDyn_GetFluidNodePositions( + self._handle, _dbl_ptr(xyz) if n else None, n, byref(status) + ) + self._check("CableDyn_GetFluidNodePositions", status.value) + return xyz.reshape(n, 3).T.copy() + + def update_fluid_fields( + self, + fluid_velocity: ArrayInput, + fluid_acceleration: ArrayInput, + waterline_z: ArrayInput, + dynamic_pressure: ArrayInput | None = None, + ) -> None: + """Prescribe the ambient fluid at every fluid node, held until the next call. + + ``fluid_velocity`` and ``fluid_acceleration`` are ``(3, n_fluid_nodes)`` in + global axes, ``waterline_z`` the free-surface elevation ``(n_fluid_nodes,)``, + ``dynamic_pressure`` the wave pressure ``(n_fluid_nodes,)`` rods use for their + end caps. Call it once with the field at ``t = 0`` before the first step, then + before each step from ``t`` to ``t + dt`` with the field at ``t + dt`` at the + positions of :meth:`fluid_node_positions`. The density is the deck's. + """ + with self._lock: + n = self.n_fluid_nodes + fv = _as_field(fluid_velocity, n, "fluid_velocity") + fa = _as_field(fluid_acceleration, n, "fluid_acceleration") + wl = _as_node_values(waterline_z, n, "waterline_z") + dp = ( + None + if dynamic_pressure is None + else _as_node_values(dynamic_pressure, n, "dynamic_pressure") + ) + status = c_int() + _lib.CableDyn_UpdateFluidFields( + self._handle, + _dbl_ptr(fv) if n else None, + _dbl_ptr(fa) if n else None, + _dbl_ptr(wl) if n else None, + _dbl_ptr(dp) if dp is not None and n else None, + n, + byref(status), + ) + self._check("CableDyn_UpdateFluidFields", status.value) + def update_point_fluid_fields( self, fluid_velocity: ArrayInput, diff --git a/python/tests/test_host_fluid.py b/python/tests/test_host_fluid.py new file mode 100644 index 00000000..0fc9219d --- /dev/null +++ b/python/tests/test_host_fluid.py @@ -0,0 +1,352 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""In-process stepping of a deck in moving water, against the standalone driver. + +The driver reads the deck's current and waves and a motion file. The same deck runs here on the +library with the same motion: its current either from the deck, or with every fluid value computed +in this file and handed over node by node (``update_fluid_fields``). Both routes hold the field at +``t + dt`` at the step-start nodes over a step, so they agree to the digits of the driver's output. +""" + +from __future__ import annotations + +import math +import subprocess +from pathlib import Path + +import numpy as np +import pytest + +try: + from cabledyn import _lib # noqa: F401 +except OSError as exc: + pytest.skip(f"CableDyn shared library not available: {exc}", allow_module_level=True) + +from cabledyn.driver import CableDynDriver +from cabledyn.errors import CableDynError, DriverNotFoundError +from cabledyn.model import CableDyn + +DT, TMAX = 0.02, 6.0 +HEIGHT, PERIOD, DEPTH, GRAVITY = 2.0, 8.0, 60.0, 9.80665 +SPEED = 0.4 +TOP = np.array([0.0, 0.0, -10.0]) +SWAY, MOTION_RATE = 0.6, 2.0 * math.pi / 10.0 +CHANNELS = ["FairTen1", "AnchTen1"] +TOLERANCE = 1.0e-5 + +DECK = """--------------------- CableDyn Input File ------------------------------------ +A cable between a moving top end and an anchor +--------------------- LINE TYPES --------------------------------------------- +TypeName Diam MassDenInAir EA BA EI Cd_n Cd_t Ca_n Ca_t +(-) (m) (kg/m) (N) (-) (N-m2) (-) (-) (-) (-) +cable 0.16 36.7 4.69e8 -1.0 1.99e4 1.2 0.1 1.0 0.0 +--------------------- POINTS ------------------------------------------------ +ID Type X Y Z +(-) (-) (m) (m) (m) +1 Coupled 0.0 0.0 -10.0 +2 Fixed 70.0 0.0 -60.0 +--------------------- LINES ------------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 1 2 - +--------------------- SECTIONS ---------------------------------------------- +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 cable 100.0 40 +{tables}--------------------- OPTIONS ----------------------------------------------- +9.80665 g +1025.0 rhoW +60.0 WtrDpth +1.0e5 kBot +1.0e4 cBot +0.02 dtM +6.0 TMax +{options} +--------------------- OUTPUTS ----------------------------------------------- +"FairTen1" +"AnchTen1" +--------------------- need this line ---------------------------------------- +""" + +EI0_DECK = DECK.replace(" 1.99e4 ", " 0 ") + +WATERKIN = """MoorDyn v2 water kinematics file +a sheared current +--------------------------- WAVES ------------------------------------- +0 WaveKinMod - type of wave input +"" WaveKinFile - file containing wave elevation time series +0.000000E+00 dtWave - time step to use in setting up wave kinematics grid +0 WaveDir - wave heading (deg) +2 - X wave input type +-10, 110, 2 - X wave grid point data +2 - Y wave input type +-10, 10, 2 - Y wave grid point data +2 - Z wave input type +-100, 0, 2 - Z wave grid point data +--------------------------- CURRENT ------------------------------------- +1 CurrentMod - type of current input +z-depth x-current y-current +(m) (m/s) (m/s) +0.0 0.5 0.1 +-30.0 0.3 0.0 +-60.0 0.1 0.0 +--------------------- need this line ------------------ +""" + +# a tapered stiffener at a clamped top end, on a line resting on a seabed with friction +STIFFENER = """--------------------- STIFFENERS -------------------------------------------- +LineID End Length RootOD TipOD InnerD E Density +(-) (-) (m) (m) (m) (m) (Pa) (kg/m^3) +1 A 4.0 0.45 0.18 0.17 5.0e7 1150 +--------------------- END CONNECTIONS --------------------------------------- +LineID End Stiffness EzX EzY EzZ +(-) (-) (N-m/rad) (-) (-) (-) +1 A Rigid 0.3 0.0 -0.9539 +""" + +CURRENT = f"uniform {SPEED} 0 0 current" +WAVE = f"airy {HEIGHT} {PERIOD} 0 waves" + + +def _driver() -> CableDynDriver: + try: + return CableDynDriver() + except DriverNotFoundError as exc: + pytest.skip(f"the standalone driver is not available: {exc}") + + +def _motion(t: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Host motion with zero velocity and acceleration at t = 0.""" + s, c = math.sin(MOTION_RATE * t), math.cos(MOTION_RATE * t) + q = TOP + np.array([SWAY * s**3, 0.0, 0.0]) + v = np.array([3.0 * SWAY * MOTION_RATE * s * s * c, 0.0, 0.0]) + a = np.array([3.0 * SWAY * MOTION_RATE**2 * (2.0 * s * c * c - s**3), 0.0, 0.0]) + return q, v, a + + +def _wave_number() -> tuple[float, float]: + omega = 2.0 * math.pi / PERIOD + k = omega * omega / GRAVITY + for _ in range(50): + th = math.tanh(k * DEPTH) + k -= (GRAVITY * k * th - omega * omega) / ( + GRAVITY * th + GRAVITY * k * DEPTH / math.cosh(k * DEPTH) ** 2 + ) + return omega, k + + +OMEGA, WAVE_NUMBER = _wave_number() + + +def _airy(xyz: np.ndarray, t: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """The deck's Airy wave along +x with Wheeler stretching: velocity, acceleration, elevation.""" + theta = WAVE_NUMBER * xyz[0] - OMEGA * t + eta = 0.5 * HEIGHT * np.cos(theta) + wet = xyz[2] <= eta + level = (xyz[2] - eta) * DEPTH / (DEPTH + eta) + DEPTH + ratio_h = np.cosh(WAVE_NUMBER * level) / math.sinh(WAVE_NUMBER * DEPTH) + ratio_v = np.sinh(WAVE_NUMBER * level) / math.sinh(WAVE_NUMBER * DEPTH) + amp = 0.5 * HEIGHT * OMEGA + velocity = np.zeros_like(xyz) + acceleration = np.zeros_like(xyz) + velocity[0] = np.where(wet, amp * ratio_h * np.cos(theta), 0.0) + velocity[2] = np.where(wet, amp * ratio_v * np.sin(theta), 0.0) + acceleration[0] = np.where(wet, amp * OMEGA * ratio_h * np.sin(theta), 0.0) + acceleration[2] = np.where(wet, -amp * OMEGA * ratio_v * np.cos(theta), 0.0) + return velocity, acceleration, eta + + +def _deck(folder: Path, name: str, options: str, tables: str = "", template: str = DECK) -> Path: + path = folder / f"{name}.dat" + path.write_text(template.format(options=options, tables=tables), encoding="utf-8") + return path + + +def _driver_run(folder: Path, options: str, tables: str = "", template: str = DECK) -> np.ndarray: + """FairTen1 and AnchTen1 of the driver on the deck with the motion as a motionFile.""" + with (folder / "motion.txt").open("w", encoding="ascii") as stream: + for i in range(round(TMAX / DT) + 1): + q, v, a = _motion(i * DT) + row = " ".join(f"{x:.14e}" for x in (*q, *v, *a)) + stream.write(f"{i * DT:.10f} 1 {row}\n") + deck = _deck(folder, "driver", f"{options}\nmotion.txt motionFile", tables, template) + subprocess.run( + [str(_driver().executable), deck.name, "driver"], + cwd=folder, + capture_output=True, + text=True, + check=True, + ) + rows = (folder / "driver.out").read_text(encoding="utf-8").splitlines()[2:] + return np.array([[float(x) for x in row.split()[1:3]] for row in rows]) + + +def _host_field(model: CableDyn, t: float, current: float) -> None: + xyz = model.fluid_node_positions() + velocity, acceleration, eta = _airy(xyz, t) + velocity[0] += current + model.update_fluid_fields(velocity, acceleration, eta) + + +def _march(model: CableDyn, current: float | None) -> np.ndarray: + """The library run: with ``current`` set, the host field of that current and the wave.""" + if current is not None: + _host_field(model, 0.0, current) + model.calc_output() + history = [model.channels(CHANNELS)] + for i in range(1, round(TMAX / DT) + 1): + t = i * DT + if current is not None: + _host_field(model, t, current) + model.step(DT, *_motion(t)) + model.calc_output() + history.append(model.channels(CHANNELS)) + return np.array(history) + + +def _nrmse(reference: np.ndarray, value: np.ndarray) -> float: + assert reference.shape == value.shape + span = np.ptp(reference, axis=0) + return float(np.max(np.sqrt(np.mean((reference - value) ** 2, axis=0)) / span)) + + +def test_deck_current_is_marched_in_process(tmp_path): + reference = _driver_run(tmp_path, CURRENT) + with CableDyn(_deck(tmp_path, "library", CURRENT)) as model: + history = _march(model, None) + assert _nrmse(reference, history) < TOLERANCE + + +def test_waterkin_depth_table_is_marched_in_process(tmp_path): + (tmp_path / "water.dat").write_text(WATERKIN, encoding="utf-8") + reference = _driver_run(tmp_path, "water.dat WaterKin") + still = _driver_run(tmp_path, "") + with CableDyn(_deck(tmp_path, "library", "water.dat WaterKin")) as model: + history = _march(model, None) + assert _nrmse(reference, history) < TOLERANCE + # the table reaches the static start as well as the march + assert abs(history[0, 0] - still[0, 0]) > 1.0 + + +def test_deck_current_starts_at_host_positions(tmp_path): + deck = _deck(tmp_path, "library", CURRENT) + with CableDyn(deck) as model: + start = model.calc_output() + with CableDyn() as model: + model.init_deck_at(deck, TOP) + np.testing.assert_allclose(model.calc_output(), start, rtol=1e-12) + + +def test_host_field_matches_the_driver_in_current_and_waves(tmp_path): + reference = _driver_run(tmp_path, f"{CURRENT}\n{WAVE}") + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", CURRENT)) + assert model.n_fluid_nodes == 41 + assert model.fluid_node_positions().shape == (3, 41) + history = _march(model, SPEED) + assert _nrmse(reference, history) < TOLERANCE + + +def test_host_field_takes_a_stiffener_and_as_laid_friction(tmp_path): + friction = "0.5 frictionMu\nasLaid staticsFriction\n0 layAzimuth" + options = f"{CURRENT}\n{friction}" + reference = _driver_run(tmp_path, f"{options}\n{WAVE}", STIFFENER) + with CableDyn() as model: + model.set_host_fluid() + model.init_deck_rotating(_deck(tmp_path, "library", options, STIFFENER)) + history = _march(model, SPEED) + assert _nrmse(reference, history) < TOLERANCE + + +def test_save_and_restore_carry_the_held_field(tmp_path): + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", CURRENT)) + _host_field(model, 0.0, SPEED) + for i in range(1, 6): + _host_field(model, i * DT, SPEED) + model.step(DT, *_motion(i * DT)) + _host_field(model, 6 * DT, SPEED) + model.save_state() + model.step(DT, *_motion(6 * DT)) + expected = model.calc_output() + # a different field after the save goes with the restore + _host_field(model, 7 * DT, 2.0) + model.restore_state() + model.step(DT, *_motion(6 * DT)) + np.testing.assert_array_equal(model.calc_output(), expected) + + +def test_a_step_needs_a_host_field(tmp_path): + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", "")) + q, v, a = _motion(DT) + with pytest.raises(CableDynError, match="before the first step"): + model.step(DT, q, v, a) + model.save_state() + _host_field(model, 0.0, 0.0) + model.restore_state() + with pytest.raises(CableDynError, match="before the first step"): + model.step(DT, q, v, a) + + +def test_host_field_calls_need_the_switch(tmp_path): + with CableDyn(_deck(tmp_path, "library", "")) as model: + assert model.n_fluid_nodes == 0 + with pytest.raises(CableDynError, match="takes no host fluid field"): + model.fluid_node_positions() + with pytest.raises(CableDynError, match="takes no host fluid field"): + model.update_fluid_fields(np.zeros((3, 0)), np.zeros((3, 0)), np.zeros(0)) + + +def test_host_field_inputs_are_checked(tmp_path): + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", "")) + n = model.n_fluid_nodes + with pytest.raises(ValueError, match="fluid_velocity"): + model.update_fluid_fields(np.zeros((3, n - 1)), np.zeros((3, n)), np.zeros(n)) + with pytest.raises(ValueError, match="waterline_z"): + model.update_fluid_fields(np.zeros((3, n)), np.zeros((3, n)), np.zeros(n - 1)) + bad = np.zeros(n) + bad[0] = math.nan + with pytest.raises(ValueError, match="finite"): + model.update_fluid_fields(np.zeros((3, n)), np.zeros((3, n)), bad) + + +def test_deck_waves_are_refused_with_a_host_field(tmp_path): + with CableDyn() as model: + model.set_host_fluid() + with pytest.raises(CableDynError, match="remove the deck waves"): + model.init_deck(_deck(tmp_path, "library", WAVE)) + + +def test_ei0_lines_of_a_host_field_need_a_seabed(tmp_path): + deck = _deck(tmp_path, "library", "", template=EI0_DECK) + text = deck.read_text(encoding="utf-8").replace("60.0 WtrDpth\n", "") + deck.write_text(text, encoding="utf-8") + with CableDyn() as model: + model.set_host_fluid() + with pytest.raises(CableDynError, match="seabed"): + model.init_deck(deck) + + +def test_ei0_line_takes_the_host_field(tmp_path): + reference = _driver_run(tmp_path, f"{CURRENT}\n{WAVE}", template=EI0_DECK) + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", CURRENT, template=EI0_DECK)) + history = _march(model, SPEED) + print("EI0 NRMSE", _nrmse(reference, history)) + assert _nrmse(reference, history) < TOLERANCE + + +def test_the_switch_can_be_turned_off(tmp_path): + deck = _deck(tmp_path, "library", CURRENT) + with CableDyn() as model: + model.set_host_fluid() + model.set_host_fluid(False) + model.init_deck(deck) + assert model.n_fluid_nodes == 0 diff --git a/python/tests/test_host_rotation.py b/python/tests/test_host_rotation.py index 794d515f..18bc2bff 100644 --- a/python/tests/test_host_rotation.py +++ b/python/tests/test_host_rotation.py @@ -67,7 +67,7 @@ def _roll(phi: float) -> np.ndarray: def test_abi_minor_reports_the_host_rotation_extension(): assert _lib.HOST_ROTATION_ABI_MINOR == 3 - assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR + assert _lib.abi_minor() == cabledyn.abi_minor() >= _lib.HOST_ROTATION_ABI_MINOR def test_torsion_deck_needs_the_rotating_initialization(tmp_path): diff --git a/python/tests/test_objects.py b/python/tests/test_objects.py index bfd122d6..1f728f14 100644 --- a/python/tests/test_objects.py +++ b/python/tests/test_objects.py @@ -450,7 +450,7 @@ def test_unbound_handle_and_raw_lines(monkeypatch, tmp_path): def test_abi_minor_is_reported(): assert _lib.OBJECT_QUERY_ABI_MINOR == 1 - assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR == 3 + assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_FLUID_ABI_MINOR == 4 assert objects_module.OBJ_ROD == 4 diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 50b81519..0db74491 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -20,7 +20,8 @@ MODULE CableDyn_CAPI USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_NMovingPoints, & CD_AGG_UpdateStates_Moving, CD_AGG_Step_Moving, CD_AGG_CalcOutput, & CD_AGG_GetMovingPointMesh, CD_AGG_End, CD_AGG_IsInitialized, CD_AGG_OK, & - CD_AGG_BADINPUT, CD_AGG_NOT_INITIALIZED, CD_AGG_ALLOCFAIL + CD_AGG_BADINPUT, CD_AGG_NOT_INITIALIZED, CD_AGG_ALLOCFAIL, & + CD_AGG_NFluidNodes, CD_AGG_GetFluidNodePositions, CD_AGG_SetFluidFields 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, & @@ -68,6 +69,10 @@ MODULE CableDyn_CAPI PUBLIC :: CableDyn_RestoreState PUBLIC :: CableDyn_GetCoupledLayout PUBLIC :: CableDyn_InitDeckRotating + PUBLIC :: CableDyn_SetHostFluid + PUBLIC :: CableDyn_NFluidNodes + PUBLIC :: CableDyn_GetFluidNodePositions + PUBLIC :: CableDyn_UpdateFluidFields PUBLIC :: CableDyn_UpdateRotations PUBLIC :: CableDyn_GetCoupledMoments @@ -85,8 +90,8 @@ MODULE CableDyn_CAPI !> Minor extension level of ABI 1: 1 adds the in-process object queries, 2 the host-coupling !> calls (initialization at host positions, state save/restore, the coupled layout query), 3 !> the host rotations (initialization for a host that turns its coupled points, their - !> rotations, the coupled moments). - INTEGER(C_INT), PARAMETER :: CD_C_ABI_MINOR = 3_C_INT + !> rotations, the coupled moments), 4 the host fluid field at the nodes of a deck. + INTEGER(C_INT), PARAMETER :: CD_C_ABI_MINOR = 4_C_INT !> Object kinds of CableDyn_NObjects / CableDyn_GetObjectInfo. INTEGER(C_INT), PARAMETER :: CD_C_OBJ_LINE = 1_C_INT, CD_C_OBJ_POINT = 2_C_INT, CD_C_OBJ_BODY = 3_C_INT, & CD_C_OBJ_ROD = 4_C_INT @@ -167,6 +172,11 @@ END FUNCTION cabledyn_blas_threads_once ! velocity and acceleration in global axes; identity and rest at the static start). ! agg_moment: the coupled moments' workspace of CableDyn_GetCoupledMoments. LOGICAL :: host_rot = .FALSE. + ! CableDyn_SetHostFluid: the next deck initialization takes the host's fluid field; agg_host_fluid + ! is what the live model was built with, and fluid_ready that it holds a field (the march + ! refuses a step without one: the deck's declared water would silently be still). + LOGICAL :: host_fluid = .FALSE., agg_host_fluid = .FALSE., fluid_ready = .FALSE. + LOGICAL :: saved_fluid_ready = .FALSE. REAL(wp), ALLOCATABLE :: agg_dcm(:, :, :), agg_om(:, :), agg_al(:, :), agg_moment(:, :) ! Point-route line inventory for the object queries: the deck-line-id -> system-line map ! (pt_obj, 0 = no such line; pt_is_cable all .FALSE.) the shared channel evaluator resolves @@ -391,7 +401,7 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, er ! A deck with finite-EI lines likewise runs on the aggregate (its Hermite cables). CALL CD_Deck_Query_dtM(TRIM(deck_path), dtm, has_dtm, es, em, standalone_scan=.TRUE., n_bodies_rods=n_objects, & n_finite_ei=n_finite) - IF (es == CD_DECKDRV_OK .AND. (n_objects > 0 .OR. n_finite > 0)) THEN + IF (es == CD_DECKDRV_OK .AND. (n_objects > 0 .OR. n_finite > 0 .OR. h%host_fluid)) THEN CALL init_deck_aggregate(h, TRIM(deck_path), has_dtm, dtm, caller, rot, err_stat, positions) RETURN END IF @@ -513,8 +523,11 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, rotating, err RETURN END IF ! An absent positions argument stays absent through the optional coupled_positions. + ! The deck's own current is marched here, unless the host supplies the field: then it sets + ! the static start only. CALL CD_AGG_Init_From_Deck(new_agg, deck_path, dtm, es, em, coupled_positions=positions, & - host_orientation=rotating) + host_orientation=rotating, external_fluid=h%host_fluid, & + deck_current=.NOT. h%host_fluid, static_deck_current=h%host_fluid) IF (es /= CD_AGG_OK) THEN CALL map_agg_status(es, err_stat) CALL store_status(h, err_stat, caller//': '//TRIM(em)) @@ -578,6 +591,8 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, rotating, err CALL MOVE_ALLOC(al, h%agg_al) CALL MOVE_ALLOC(moment, h%agg_moment) h%host_rot = rotating + h%agg_host_fluid = h%host_fluid + h%fluid_ready = .FALSE. CALL move_aggregate(new_agg, h%agg) CALL clear_point_line_map(h) h%use_agg = .TRUE. @@ -645,6 +660,8 @@ SUBROUTINE drop_aggregate(h) IF (ALLOCATED(h%agg_pos)) DEALLOCATE (h%agg_pos, h%agg_vel, h%agg_acc, h%agg_load) IF (ALLOCATED(h%agg_dcm)) DEALLOCATE (h%agg_dcm, h%agg_om, h%agg_al, h%agg_moment) h%host_rot = .FALSE. + h%agg_host_fluid = .FALSE. + h%fluid_ready = .FALSE. END SUBROUTINE drop_aggregate SUBROUTINE map_agg_status(agg_stat, err_stat) @@ -1101,6 +1118,161 @@ SUBROUTINE CableDyn_UpdatePointFluidFields(handle, fluid_velocity_ptr, fluid_acc CALL store_status(h, err_stat, em) END SUBROUTINE CableDyn_UpdatePointFluidFields + SUBROUTINE CableDyn_SetHostFluid(handle, enable, err_stat) BIND(C, NAME='CableDyn_SetHostFluid') + !! Choose, before a deck initialization, whether the host supplies the ambient fluid + !! (nonzero) or the deck does (0, the default). It applies to every following CableDyn_InitDeck, + !! CableDyn_InitDeckAt and CableDyn_InitDeckRotating of the handle. With it, the deck runs on + !! the coupled aggregate whatever its lines; its waves are refused, a steady deck current sets + !! the static start only, and CableDyn_UpdateFluidFields supplies the whole field of the march. + TYPE(C_PTR), VALUE :: handle + INTEGER(C_INT), VALUE :: enable + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + + err_stat = validate_handle(handle, h) + IF (err_stat /= CD_C_OK) RETURN + h%host_fluid = enable /= 0_C_INT + CALL store_status(h, CD_C_OK, '') + END SUBROUTINE CableDyn_SetHostFluid + + FUNCTION CableDyn_NFluidNodes(handle, err_stat) RESULT(n) BIND(C, NAME='CableDyn_NFluidNodes') + !! The number of nodes at which the host supplies the fluid field (every line node, then the + !! bodies, rods and hydrodynamic points of the deck), or zero for a null or uninitialized + !! handle and for a handle without a host fluid field. + TYPE(C_PTR), VALUE :: handle + INTEGER(C_INT), INTENT(OUT) :: err_stat + INTEGER(C_INT) :: n + TYPE(CD_C_Handle), POINTER :: h + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + + n = 0_C_INT + IF (.NOT. query_ready(handle, h, 'CableDyn_NFluidNodes', err_stat)) RETURN + IF (h%agg_host_fluid) THEN + n = INT(CD_AGG_NFluidNodes(h%agg, es, em), C_INT) + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, em) + ELSE + CALL store_status(h, CD_C_OK, '') + END IF + END FUNCTION CableDyn_NFluidNodes + + SUBROUTINE CableDyn_GetFluidNodePositions(handle, xyz_ptr, n_node, err_stat) & + BIND(C, NAME='CableDyn_GetFluidNodePositions') + !! The committed position of every fluid node (x, y, z triples, global axes): where the host + !! evaluates the field of the coming step. + TYPE(C_PTR), VALUE :: handle, xyz_ptr + INTEGER(C_INT), VALUE :: n_node + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + REAL(C_DOUBLE), POINTER :: xyz_c(:) + INTEGER :: es, n, p + CHARACTER(CD_C_MSG_LEN) :: em + + IF (.NOT. host_fluid_call(handle, h, 'CableDyn_GetFluidNodePositions', n_node, n, err_stat)) RETURN + IF (n == 0) THEN + CALL store_status(h, CD_C_OK, '') + RETURN + END IF + IF (.NOT. C_ASSOCIATED(xyz_ptr)) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_GetFluidNodePositions: output pointer is null', err_stat) + RETURN + END IF + CALL ensure_c_fluid_workspace(h, n, err_stat) + IF (err_stat /= CD_C_OK) RETURN + CALL CD_AGG_GetFluidNodePositions(h%agg, h%fluid_velocity_work(:, 1:n), es, em) + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, em) + IF (err_stat /= CD_C_OK) RETURN + CALL C_F_POINTER(xyz_ptr, xyz_c, [3*n]) + DO p = 1, n + xyz_c(3*p - 2:3*p) = REAL(h%fluid_velocity_work(:, p), C_DOUBLE) + END DO + END SUBROUTINE CableDyn_GetFluidNodePositions + + SUBROUTINE CableDyn_UpdateFluidFields(handle, fluid_velocity_ptr, fluid_acceleration_ptr, waterline_z_ptr, & + dynamic_pressure_ptr, n_node, err_stat) & + BIND(C, NAME='CableDyn_UpdateFluidFields') + !! The ambient fluid at every fluid node (CableDyn_GetFluidNodePositions), held until the next + !! call: velocity and acceleration as x, y, z triples in global axes, the free-surface + !! elevation, and the wave dynamic pressure (may be NULL; rods use it for their end caps). + !! The first call, before the first step, is the field at t = 0 and sets the start + !! acceleration; later calls are the field of the coming step, the field at t + dt at the + !! step-start positions. The density is the deck's. + TYPE(C_PTR), VALUE :: handle, fluid_velocity_ptr, fluid_acceleration_ptr, waterline_z_ptr + TYPE(C_PTR), VALUE :: dynamic_pressure_ptr + INTEGER(C_INT), VALUE :: n_node + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + REAL(C_DOUBLE), POINTER :: velocity_c(:), acceleration_c(:), waterline_c(:), pressure_c(:) + INTEGER :: es, n, p + CHARACTER(CD_C_MSG_LEN) :: em + + IF (.NOT. host_fluid_call(handle, h, 'CableDyn_UpdateFluidFields', n_node, n, err_stat)) RETURN + IF (n > 0 .AND. .NOT. (C_ASSOCIATED(fluid_velocity_ptr) .AND. C_ASSOCIATED(fluid_acceleration_ptr) .AND. & + C_ASSOCIATED(waterline_z_ptr))) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateFluidFields: input pointer is null', err_stat) + RETURN + END IF + CALL ensure_c_fluid_workspace(h, n, err_stat) + IF (err_stat /= CD_C_OK) RETURN + IF (n > 0) THEN + CALL C_F_POINTER(fluid_velocity_ptr, velocity_c, [3*n]) + CALL C_F_POINTER(fluid_acceleration_ptr, acceleration_c, [3*n]) + CALL C_F_POINTER(waterline_z_ptr, waterline_c, [n]) + DO p = 1, n + h%fluid_velocity_work(:, p) = REAL(velocity_c(3*p - 2:3*p), wp) + h%fluid_acceleration_work(:, p) = REAL(acceleration_c(3*p - 2:3*p), wp) + END DO + h%waterline_work(1:n) = REAL(waterline_c, wp) + END IF + IF (n > 0 .AND. C_ASSOCIATED(dynamic_pressure_ptr)) THEN + CALL C_F_POINTER(dynamic_pressure_ptr, pressure_c, [n]) + CALL CD_AGG_SetFluidFields(h%agg, h%fluid_velocity_work(:, 1:n), h%fluid_acceleration_work(:, 1:n), & + h%waterline_work(1:n), es, em, dynamic_pressure=REAL(pressure_c, wp), & + initial_condition=.NOT. h%fluid_ready) + ELSE + CALL CD_AGG_SetFluidFields(h%agg, h%fluid_velocity_work(:, 1:n), h%fluid_acceleration_work(:, 1:n), & + h%waterline_work(1:n), es, em, initial_condition=.NOT. h%fluid_ready) + END IF + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, em) + IF (err_stat == CD_C_OK) h%fluid_ready = .TRUE. + END SUBROUTINE CableDyn_UpdateFluidFields + + LOGICAL FUNCTION host_fluid_call(handle, h, caller, n_node, n, err_stat) RESULT(ready) + !! Validate a host fluid call: an initialized model built for a host field, with n_node equal + !! to the fluid node count n. + TYPE(C_PTR), VALUE :: handle + TYPE(CD_C_Handle), POINTER, INTENT(OUT) :: h + CHARACTER(*), INTENT(IN) :: caller + INTEGER(C_INT), INTENT(IN) :: n_node + INTEGER, INTENT(OUT) :: n + INTEGER(C_INT), INTENT(OUT) :: err_stat + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + + ready = .FALSE. + n = 0 + IF (.NOT. query_ready(handle, h, caller, err_stat)) RETURN + IF (.NOT. h%agg_host_fluid) THEN + CALL set_status(h, CD_C_BAD_INPUT, caller//': the model takes no host fluid field: call '// & + 'CableDyn_SetHostFluid before its deck initialization', err_stat) + RETURN + END IF + n = CD_AGG_NFluidNodes(h%agg, es, em) + IF (es /= CD_AGG_OK) THEN + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, em) + RETURN + END IF + IF (INT(n_node) /= n) THEN + CALL set_status(h, CD_C_BAD_INPUT, caller//': node count does not match CableDyn_NFluidNodes', err_stat) + RETURN + END IF + ready = .TRUE. + END FUNCTION host_fluid_call + SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converged, stalled, n_iter, err_stat) & BIND(C, NAME='CableDyn_Step') !! Advance one coupled time step. @@ -1121,6 +1293,11 @@ SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converg CALL coupled_inputs(handle, q_ptr, v_ptr, a_ptr, n_coupled_dof, h, q_c, v_c, a_c, err_stat) IF (err_stat /= CD_C_OK) RETURN IF (h%use_agg) THEN + IF (h%agg_host_fluid .AND. .NOT. h%fluid_ready) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_Step: the model takes a host fluid field: call '// & + 'CableDyn_UpdateFluidFields before the first step', err_stat) + RETURN + END IF IF (n_coupled_dof > 0_C_INT) THEN h%agg_pos = RESHAPE(REAL(q_c, wp), SHAPE(h%agg_pos)) h%agg_vel = RESHAPE(REAL(v_c, wp), SHAPE(h%agg_vel)) @@ -1864,7 +2041,8 @@ SUBROUTINE CableDyn_SaveState(handle, err_stat) BIND(C, NAME='CableDyn_SaveState !! Save the whole model into the handle's single save slot, replacing any earlier save: !! every line, point, body and rod state with its solver history (viscoelastic, Syrope and !! friction states, the last converged step), the point fluid fields, and on the aggregate - !! route the committed time and the host's rotations (CableDyn_UpdateRotations). The slot + !! route the committed time, the host's rotations (CableDyn_UpdateRotations) and the host's + !! fluid field (CableDyn_UpdateFluidFields). The slot !! holds a deep copy of the model object, independent of the step's own rollback buffers, !! so any number of steps may follow before the restore. !! A successful Init* call discards the slot; a failed InitDeck/InitDeckAt keeps it with the @@ -1891,6 +2069,7 @@ SUBROUTINE CableDyn_SaveState(handle, err_stat) BIND(C, NAME='CableDyn_SaveState END IF CALL copy_aggregate(h%agg, h%saved_agg) h%saved_agg_t = h%agg_t + h%saved_fluid_ready = h%fluid_ready ! the host's rotations are the inputs of the saved instant (CableDyn_UpdateRotations) IF (h%host_rot) THEN h%saved_dcm = h%agg_dcm @@ -1922,6 +2101,7 @@ SUBROUTINE CableDyn_RestoreState(handle, err_stat) BIND(C, NAME='CableDyn_Restor IF (h%use_agg) THEN CALL copy_aggregate(h%saved_agg, h%agg) h%agg_t = h%saved_agg_t + h%fluid_ready = h%saved_fluid_ready IF (h%host_rot) THEN h%agg_dcm = h%saved_dcm h%agg_om = h%saved_om diff --git a/src/CableDyn_CAPI.h b/src/CableDyn_CAPI.h index 2ce3bef7..65240c07 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -127,9 +127,9 @@ int CableDyn_NLines(void *handle, int *err_stat); * aggregate (it needs dtM); other decks keep the point route. Check * CableDyn_GetAbiMinor() >= 1 before using these on a library of unknown * vintage. CABLEDYN_CAPI_ABI_MINOR is the extension level this header - * declares (3: the host-coupling and host-rotation calls below are present - * too). */ -#define CABLEDYN_CAPI_ABI_MINOR 3 + * declares (4: the host-coupling, host-rotation and host fluid calls below are + * present too). */ +#define CABLEDYN_CAPI_ABI_MINOR 4 #define CD_C_OBJ_LINE 1 #define CD_C_OBJ_POINT 2 @@ -256,6 +256,34 @@ void CableDyn_UpdateRotations(void *handle, const double *dcm, void CableDyn_GetCoupledMoments(void *handle, double *coupled_moments, int n_coupled_dof, int *err_stat); +/* Host fluid field (ABI minor 4). The host evaluates the ambient fluid and hands + * it over at the nodes of the deck, on any deck with dtM and a seabed. Check + * CableDyn_GetAbiMinor() >= 4 before using these on a library of unknown + * vintage. */ + +/* Before a deck initialization: nonzero makes every following InitDeck, + * InitDeckAt and InitDeckRotating of the handle take the host's field (0, the + * default, keeps the deck's). A steady deck current then sets the static start + * only, and deck waves are refused. */ +void CableDyn_SetHostFluid(void *handle, int enable, int *err_stat); +/* The fluid node count; zero without a host fluid field. */ +int CableDyn_NFluidNodes(void *handle, int *err_stat); +/* The committed node positions, x y z triples in global axes: where the host + * evaluates the field of the coming step. */ +void CableDyn_GetFluidNodePositions(void *handle, double *xyz, int n_node, + int *err_stat); +/* The fluid at every node, held until the next call: velocity and acceleration + * as x y z triples in global axes, the free-surface elevation, and the wave + * dynamic pressure (may be NULL; rods use it for their end caps). Call it once + * with the t = 0 field before the first step, then before each step from t to + * t + dt with the field at t + dt at the positions of + * CableDyn_GetFluidNodePositions. A step before the first call is refused. */ +void CableDyn_UpdateFluidFields(void *handle, const double *fluid_velocity, + const double *fluid_acceleration, + const double *waterline_z, + const double *dynamic_pressure, int n_node, + int *err_stat); + #ifdef __cplusplus } #endif diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index c86ee353..5cc1b50c 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -7375,7 +7375,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi ptfm_init, external_fluid, coupled_positions, & n_turbines, turbine_ref_pos, farm_ptfm_init, forbid_deck_ambient, run_tmax, & range_files, host_orientation, static_current, prescribed_motion, & - static_run, deck_current, deck_turbines) + static_run, deck_current, deck_turbines, static_deck_current) !! Parse a MIXED deck ONCE and partition its lines into {EI=0 mooring} and !! {finite-EI cable}, returning the raw parts the OpenFAST aggregate facade wraps: !! the EI=0 mooring SYSTEM built from the mooring subset (over ALL deck points, the @@ -7475,6 +7475,11 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi ! every node before each step (CD_Deck_Current_Sample_System/_Cables). A coupled host keeps ! supplying its own field and passes no deck_current. LOGICAL, INTENT(IN), OPTIONAL :: deck_current + ! static_deck_current (with external_fluid): the deck's steady current (a current OPTION, a + ! WaterKin CurrentMod 1 table or MoorDyn-C Currents 1) sets the static start only, as a + ! host's static_current does, and the dynamics take the host field alone. A library host + ! that evaluates its own field passes it; a current that varies in time is refused. + LOGICAL, INTENT(IN), OPTIONAL :: static_deck_current ! deck_turbines: the caller is the standalone driver, which runs a TURBINES deck by itself: the ! deck's TURBINES rows place every Turbine point at ref_J + PtfmInit_J(p) as the parse of @@ -7496,6 +7501,10 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi TYPE(DeckOptions) :: opts ! opts plus the host's steady current (static_current): the options of the static builders TYPE(DeckOptions) :: opts_static + ! the deck's steady current of static_deck_current, kept for the static builders + LOGICAL :: keep_static_current, kept_has_current, kept_has_profile + REAL(wp) :: kept_velocity(3) + REAL(wp), ALLOCATABLE :: kept_profile_z(:), kept_profile_velocity(:, :) CHARACTER(NAMELEN), ALLOCATABLE :: channels(:) TYPE(CD_BathymetryType) :: bathymetry TYPE(DeckFailure), ALLOCATABLE :: fails(:) @@ -7633,6 +7642,27 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi END IF own_current = .FALSE. IF (PRESENT(deck_current)) own_current = deck_current + keep_static_current = .FALSE. + IF (PRESENT(static_deck_current)) keep_static_current = static_deck_current + keep_static_current = keep_static_current .AND. (opts%has_current .OR. opts%has_current_profile) + IF (keep_static_current) THEN + IF (opts%has_current_grid) THEN + CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: the deck current varies in time, and a host '// & + 'fluid field replaces it in the dynamics: supply it through the host field and '// & + 'remove it from the deck'); RETURN + END IF + kept_has_current = opts%has_current + kept_has_profile = opts%has_current_profile + kept_velocity = opts%current_velocity + IF (ALLOCATED(opts%current_profile_z)) THEN + kept_profile_z = opts%current_profile_z + kept_profile_velocity = opts%current_profile_velocity + END IF + opts%has_current = .FALSE. + opts%has_current_profile = .FALSE. + opts%mdc_currents = 0 + opts%waterkin_current_mode = -1 + END IF IF (opts%mdc_wave_kin > 0 .AND. own_current) THEN CALL fail(ErrStat, ErrMsg, 'the MoorDyn-C WaveKin '//TRIM(int_to_str(opts%mdc_wave_kin))//' waves are '// & 'not supported for a standalone mixed EI=0/finite-EI deck (it takes a deck current but no '// & @@ -7645,10 +7675,10 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi 'aggregate route (coupled runs take water kinematics from the host)') RETURN END IF - ! The deck's own current (deck_current) is marched by the standalone driver over lines between - ! Fixed/Coupled/Vessel points held or moved by the deck's motion, from the deck pose: no host - ! field, placement or farm, and no body, rod or Connect/Free point (those decks run on the - ! standalone multibody or point-system march, which take the current themselves). + ! The deck's own current (deck_current) is marched by the standalone driver and the C API over + ! lines between Fixed/Coupled/Vessel points: no host field, platform placement or farm, and no + ! body, rod or Connect/Free point (those decks run on the standalone multibody or point-system + ! march, which take the current themselves). IF (own_current .AND. (opts%has_current .OR. opts%has_current_profile)) THEN IF (PRESENT(external_fluid)) THEN IF (external_fluid) THEN @@ -7656,9 +7686,9 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi 'host fluid field (external_fluid) would double-count the current'); RETURN END IF END IF - IF (nturb > 0 .OR. PRESENT(ptfm_init) .OR. PRESENT(coupled_positions) .OR. PRESENT(static_current)) THEN - CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: a deck-owned current (deck_current) is marched '// & - 'from the deck pose of a standalone deck (no host placement, farm or host current)'); RETURN + IF (nturb > 0 .OR. PRESENT(ptfm_init) .OR. PRESENT(static_current)) THEN + CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: a deck-owned current (deck_current) takes no '// & + 'platform placement, farm or host current'); RETURN END IF IF (deck_has_dynamic_points(points) .OR. SIZE(bodies) > 0 .OR. SIZE(rods) > 0) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: a deck-owned current (deck_current) drives lines '// & @@ -8034,6 +8064,15 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi ! The static builders' options: the deck's, plus the host's steady current when the host ! current drives this deck (a WaterKin CurrentMod 1 file keeps its own profile instead). opts_static = opts + IF (keep_static_current) THEN + opts_static%has_current = kept_has_current + opts_static%has_current_profile = kept_has_profile + opts_static%current_velocity = kept_velocity + IF (ALLOCATED(kept_profile_z)) THEN + opts_static%current_profile_z = kept_profile_z + opts_static%current_profile_velocity = kept_profile_velocity + END IF + END IF IF (PRESENT(static_current)) THEN IF (.NOT. opts%external_fluid) THEN CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_Aggregate: static_current needs the host fluid field '// & diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index be68b088..0ee28790 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -63,7 +63,7 @@ MODULE CableDyn_OpenFAST_Aggregate USE CableDyn_HermiteCableDynamic, ONLY: CD_HermiteCable_Dyn_Profile_Enabled, CD_HermiteCableControlSaveType, & CD_HermiteCable_Dyn_Save_Control, CD_HermiteCable_Dyn_Restore_Control, & CD_HCDYN_OK - USE CableDyn_Model, ONLY: CD_ModelControlSaveType + USE CableDyn_Model, ONLY: CD_ModelControlSaveType, CD_Recompute_Model_Acceleration, CD_MODEL_OK USE CableDyn_DeckDriver, ONLY: CD_DeckAggregateType, CD_Init_Deck_Aggregate, CD_End_Deck_Aggregate, & CD_DECKDRV_OK, CD_DECKDRV_BADINPUT, CD_Eval_Aggregate_Channel, & CD_Cable_Deck_Node, & @@ -292,7 +292,7 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi ptfm_init, external_fluid, coupled_positions, & n_turbines, turbine_ref_pos, farm_ptfm_init, forbid_deck_ambient, run_tmax, & range_files, host_orientation, static_current, prescribed_motion, static_run, & - deck_current, deck_turbines) + deck_current, deck_turbines, static_deck_current) !! Build the aggregate from ONE mixed deck: partition its lines into {EI=0 mooring} !! and {finite-EI cable}, wrap the mooring subset into a CD_FMF, and own one CD_HFMF !! per cable. Same signature philosophy as CD_FMF_Init_From_Deck (host environment @@ -343,6 +343,9 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi ! deck_current: the caller marches the deck's own current (the standalone driver; see ! CD_Init_Deck_Aggregate): every step samples it at the nodes, at its t_committed LOGICAL, INTENT(IN), OPTIONAL :: deck_current + ! static_deck_current (with external_fluid): the deck's steady current sets the static start + ! only and the dynamics take the host field alone (see CD_Init_Deck_Aggregate) + LOGICAL, INTENT(IN), OPTIONAL :: static_deck_current ! deck_turbines: the standalone driver runs a TURBINES deck, whose TURBINES rows place the ! Turbine points and whose per-turbine records move them (see CD_Init_Deck_Aggregate) LOGICAL, INTENT(IN), OPTIONAL :: deck_turbines @@ -387,7 +390,7 @@ SUBROUTINE CD_AGG_Init_From_Deck(self, deck_path, dt, ErrStat, ErrMsg, env_gravi range_files=range_files, host_orientation=host_orientation, & static_current=static_current, prescribed_motion=prescribed_motion, & static_run=static_run, deck_current=deck_current, & - deck_turbines=deck_turbines) + deck_turbines=deck_turbines, static_deck_current=static_deck_current) IF (PRESENT(external_fluid)) THEN candidate%built_extfluid = external_fluid END IF @@ -1938,7 +1941,7 @@ SUBROUTINE CD_AGG_GetFluidNodePositions(self, xyz, ErrStat, ErrMsg) END SUBROUTINE CD_AGG_GetFluidNodePositions SUBROUTINE CD_AGG_SetFluidFields(self, fluid_velocity, fluid_acceleration, waterline_z, ErrStat, ErrMsg, & - dynamic_pressure) + dynamic_pressure, initial_condition) !! Prescribe the ambient fluid kinematics at every fluid sampling node for the NEXT !! advance: velocity + acceleration shaped (3, nfluid), the local free-surface !! elevation waterline_z shaped (nfluid) (drives the wetting of drag / FK / added @@ -1947,6 +1950,9 @@ SUBROUTINE CD_AGG_SetFluidFields(self, fluid_velocity, fluid_acceleration, water !! drag configuration, so the model layer alone cannot catch them). !! dynamic_pressure (optional, Pa, shaped (nfluid)): the wave dynamic pressure at the nodes; !! the rod blocks use it for the end-cap pressure (other blocks ignore it). + !! initial_condition (optional): the field at t = 0 of a host that starts its march in it: + !! the EI = 0 lines re-derive their start acceleration, as a cable's first field does and + !! as the standalone routes do at their t = 0 sample. !! Before the first committed step (and before a state mirror is restored) the integrated !! bodies and rods re-solve their start accelerations in the new fields: the accelerations !! solved at Init saw the zero fields of the build, and the first step starts from them. @@ -1955,9 +1961,13 @@ SUBROUTINE CD_AGG_SetFluidFields(self, fluid_velocity, fluid_acceleration, water INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg REAL(wp), INTENT(IN), OPTIONAL :: dynamic_pressure(:) + LOGICAL, INTENT(IN), OPTIONAL :: initial_condition INTEGER :: li, o1, o2, i, es + LOGICAL :: at_start CHARACTER(1024) :: em IF (.NOT. require_initialized(self, ErrStat, ErrMsg)) RETURN + at_start = .FALSE. + IF (PRESENT(initial_condition)) at_start = initial_condition ! Uniform contract for BOTH line families: host fields are only accepted on a ! build that declared them. Cables always carry a drag/added-mass configuration, ! so without this gate a plain cable-only build would silently accept held fields @@ -2013,6 +2023,14 @@ SUBROUTINE CD_AGG_SetFluidFields(self, fluid_velocity, fluid_acceleration, water ErrMsg = 'CableDyn_OpenFAST_Aggregate: fluid-field update: '//TRIM(em) RETURN END IF + IF (at_start) THEN + CALL CD_Recompute_Model_Acceleration(self%sys%fast%system%lines(li), es, em) + IF (es /= CD_MODEL_OK) THEN + ErrStat = CD_AGG_BADINPUT + ErrMsg = 'CableDyn_OpenFAST_Aggregate: start acceleration in the fluid field: '//TRIM(em) + RETURN + END IF + END IF END DO ! finite-EI cables: the held-field mode (frozen over the step; the drag adds the ! nodal velocity, the Froude-Krylov forcing takes the nodal acceleration, the diff --git a/src/cabledyn.def b/src/cabledyn.def index 107e180e..29c03865 100644 --- a/src/cabledyn.def +++ b/src/cabledyn.def @@ -31,6 +31,10 @@ EXPORTS CableDyn_RestoreState CableDyn_SaveState CableDyn_Step + CableDyn_SetHostFluid + CableDyn_NFluidNodes + CableDyn_GetFluidNodePositions + CableDyn_UpdateFluidFields CableDyn_UpdatePointFluidFields CableDyn_UpdateRotations CableDyn_UpdateStates diff --git a/src/cabledyn.exp b/src/cabledyn.exp index 7c6ff0d0..4537d25a 100644 --- a/src/cabledyn.exp +++ b/src/cabledyn.exp @@ -30,6 +30,10 @@ _CableDyn_NPoints _CableDyn_RestoreState _CableDyn_SaveState _CableDyn_Step +_CableDyn_SetHostFluid +_CableDyn_NFluidNodes +_CableDyn_GetFluidNodePositions +_CableDyn_UpdateFluidFields _CableDyn_UpdatePointFluidFields _CableDyn_UpdateRotations _CableDyn_UpdateStates diff --git a/src/cabledyn.map b/src/cabledyn.map index 53952d5c..7e1bec89 100644 --- a/src/cabledyn.map +++ b/src/cabledyn.map @@ -33,6 +33,10 @@ CableDyn_RestoreState; CableDyn_SaveState; CableDyn_Step; + CableDyn_SetHostFluid; + CableDyn_NFluidNodes; + CableDyn_GetFluidNodePositions; + CableDyn_UpdateFluidFields; CableDyn_UpdatePointFluidFields; CableDyn_UpdateRotations; CableDyn_UpdateStates; diff --git a/tests/test_c_api_host_rotation.c b/tests/test_c_api_host_rotation.c index 963e5fb6..f8058cab 100644 --- a/tests/test_c_api_host_rotation.c +++ b/tests/test_c_api_host_rotation.c @@ -25,6 +25,7 @@ * - a handle initialised without rotations refuses CableDyn_UpdateRotations; * the EI = 0 point route (box_points.dat) takes rotations and ignores them, * and its coupled moments are zero. + * - the host fluid calls of extension 4 link and run through the public header. * The decks this test writes are removed on every exit path. */ #include "CableDyn_CAPI.h" @@ -381,6 +382,41 @@ static int check_point_route(void) return failed; } +static int check_host_fluid(void) +{ + enum { MAX_NODES = NSEG + 1 }; + static double xyz[3 * MAX_NODES], vel[3 * MAX_NODES], acc[3 * MAX_NODES], eta[MAX_NODES]; + const double q[3] = {0.0, 0.0, -50.0}, z[3] = {0.0, 0.0, 0.0}; + bool converged = false, stalled = false; + void *h = NULL; + int err = -1, failed = 1, n, n_iter = 0; + CHECK(CableDyn_GetAbiMinor() >= 4, "the library declares ABI minor 4"); + CableDyn_Create(&h, &err); + REQUIRE(err == CD_C_OK, "create"); + CableDyn_SetHostFluid(h, 1, &err); + REQUIRE(err == CD_C_OK, "SetHostFluid"); + CableDyn_InitDeckRotating(h, TORSION_DECK, (int)strlen(TORSION_DECK), NULL, 0, &err); + REQUIRE(err == CD_C_OK, "InitDeckRotating with a host fluid field"); + n = CableDyn_NFluidNodes(h, &err); + REQUIRE(err == CD_C_OK && n == MAX_NODES, "one fluid node per line node"); + CableDyn_GetFluidNodePositions(h, xyz, n, &err); + REQUIRE(err == CD_C_OK && xyz[3 * (n - 1) + 2] < 0.0, "the node positions"); + CableDyn_GetFluidNodePositions(h, xyz, n - 1, &err); + REQUIRE(err == CD_C_BAD_INPUT, "a wrong node count is refused"); + CableDyn_Step(h, DT, q, z, z, 3, &converged, &stalled, &n_iter, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "before the first step"), + "a step before the first field is refused"); + CableDyn_UpdateFluidFields(h, vel, acc, eta, NULL, n, &err); + REQUIRE(err == CD_C_OK, "UpdateFluidFields"); + CableDyn_UpdateFluidFields(h, NULL, acc, eta, NULL, n, &err); + REQUIRE(err == CD_C_BAD_INPUT, "a null field is refused"); + REQUIRE(step_at_deck(h) == 0, "a step in the held field"); + failed = 0; +done: + close_handle(&h); + return failed; +} + int main(int argc, char **argv) { int failed; @@ -396,7 +432,7 @@ int main(int argc, char **argv) return 1; } failed = check_init() || check_feedthrough() || check_march() || check_save_restore() || check_rejections() || - check_point_route(); + check_point_route() || check_host_fluid(); remove_written_decks(); if (failed) return 1; puts("PASS: CableDyn C API host rotations"); From 6d9bb87a3f3fe049ed45e4b8ec30e87ed0be2187 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 20:36:49 +0900 Subject: [PATCH 2/6] docs(python): add a complete example of stepping in host water Signed-off-by: Jae Hoon Seo --- doc/capi.rst | 3 + doc/python.rst | 2 + examples/python/step_in_moving_water.py | 120 ++++++++++++++++++++++++ python/tests/test_host_fluid.py | 23 +++++ 4 files changed, 148 insertions(+) create mode 100644 examples/python/step_in_moving_water.py diff --git a/doc/capi.rst b/doc/capi.rst index 25baf74a..1a463d2a 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -736,6 +736,9 @@ the whole water of the march; a deck current that varies in time is refused. Seabed friction, ``staticsFriction asLaid`` and ``STIFFENERS`` work on this route. +A deck with a current also declares ``TMax``, as under the standalone rules; it does not limit the +host, which owns the clock and may step past it. + Call sequence ~~~~~~~~~~~~~ diff --git a/doc/python.rst b/doc/python.rst index 8f5e68ca..75dc5427 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -790,6 +790,8 @@ start and in every step. Other moving water comes from the host, at the nodes of field(t) # held over the step model.step(dt, q(t), v(t), a(t)) +``examples/python/step_in_moving_water.py`` is a complete script of this loop. + ``velocity`` is the whole ambient velocity, current and waves together. The field of a step to ``t + dt`` is evaluated at ``t + dt`` at the step-start positions and held over the step, as in the standalone march and in OpenFAST; :meth:`~cabledyn.CableDyn.save_state` carries it. A steady diff --git a/examples/python/step_in_moving_water.py b/examples/python/step_in_moving_water.py new file mode 100644 index 00000000..dc7e1157 --- /dev/null +++ b/examples/python/step_in_moving_water.py @@ -0,0 +1,120 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Step a cable in-process while the host supplies the water and moves the top end. + +The host owns the time loop. Before each step it reads the node positions, evaluates its own +current and wave at them, hands the field over, and passes the motion of the top end. Replace +``sea`` and ``top_end`` with your own models. Run it with:: + + python step_in_moving_water.py +""" + +from __future__ import annotations + +import math +import tempfile +from pathlib import Path + +import numpy as np + +import cabledyn + +DT = 0.05 +DEPTH, GRAVITY = 60.0, 9.80665 +AMPLITUDE, PERIOD, CURRENT = 1.0, 8.0, 0.4 +TOP = np.array([0.0, 0.0, -10.0]) + +DECK = """--------------------- CableDyn Input File ------------------------------------ +A cable from a moving top end to an anchor. The steady current of the deck sets the static start. +--------------------- LINE TYPES --------------------------------------------- +TypeName Diam MassDenInAir EA BA EI Cd_n Cd_t Ca_n Ca_t +(-) (m) (kg/m) (N) (-) (N-m2) (-) (-) (-) (-) +cable 0.16 36.7 4.69e8 -1.0 1.99e4 1.2 0.1 1.0 0.0 +--------------------- POINTS ------------------------------------------------ +ID Type X Y Z +(-) (-) (m) (m) (m) +1 Coupled 0.0 0.0 -10.0 +2 Fixed 70.0 0.0 -60.0 +--------------------- LINES ------------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 1 2 - +--------------------- SECTIONS ---------------------------------------------- +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 cable 100.0 50 +--------------------- OPTIONS ----------------------------------------------- +9.80665 g +1025.0 rhoW +60.0 WtrDpth +0.05 dtM +3600.0 TMax - required with a deck current; the host owns the clock and may run past it +uniform 0.4 0 0 current +--------------------- OUTPUTS ----------------------------------------------- +"FairTen1" +--------------------- need this line ---------------------------------------- +""" + + +def wave_number(omega: float) -> float: + k = omega * omega / GRAVITY + for _ in range(50): + k = omega * omega / (GRAVITY * math.tanh(k * DEPTH)) + return k + + +OMEGA = 2.0 * math.pi / PERIOD +K = wave_number(OMEGA) + + +def sea(xyz: np.ndarray, t: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Whole ambient velocity, fluid acceleration and surface elevation at the nodes ``(3, n)``.""" + theta = K * xyz[0] - OMEGA * t + decay = np.exp(K * np.minimum(xyz[2], 0.0)) # deep-water profile, for brevity + velocity = np.zeros_like(xyz) + acceleration = np.zeros_like(xyz) + velocity[0] = CURRENT + AMPLITUDE * OMEGA * decay * np.cos(theta) + velocity[2] = AMPLITUDE * OMEGA * decay * np.sin(theta) + acceleration[0] = AMPLITUDE * OMEGA**2 * decay * np.sin(theta) + acceleration[2] = -AMPLITUDE * OMEGA**2 * decay * np.cos(theta) + return velocity, acceleration, AMPLITUDE * np.cos(theta) + + +def top_end(t: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """Position, velocity and acceleration of the coupled point: a slow surge, from rest.""" + rate = 2.0 * math.pi / 10.0 + s, c = math.sin(rate * t), math.cos(rate * t) + q = TOP + np.array([0.5 * s**3, 0.0, 0.0]) + v = np.array([1.5 * rate * s * s * c, 0.0, 0.0]) + a = np.array([1.5 * rate**2 * (2.0 * s * c * c - s**3), 0.0, 0.0]) + return q, v, a + + +def main(duration: float = 20.0) -> list[float]: + """March for ``duration`` seconds and return the top tension of every step.""" + tensions = [] + with tempfile.TemporaryDirectory() as folder: + deck = Path(folder) / "cable.dat" + deck.write_text(DECK, encoding="utf-8") + with cabledyn.CableDyn() as model: + model.set_host_fluid() # before the initialization + model.init_deck(deck) + + def give_field(t: float) -> None: + # the field of a step: at its end time, at the step-start positions + model.update_fluid_fields(*sea(model.fluid_node_positions(), t)) + + give_field(0.0) # the start acceleration + for i in range(1, round(duration / DT) + 1): + t = i * DT + give_field(t) + model.step(DT, *top_end(t)) + model.calc_output() + tensions.append(float(model.channel("FairTen1"))) + if i % round(1.0 / DT) == 0: + print(f"t = {t:5.1f} s top tension {tensions[-1]:10.1f} N") + return tensions + + +if __name__ == "__main__": + main() diff --git a/python/tests/test_host_fluid.py b/python/tests/test_host_fluid.py index 0fc9219d..c53df234 100644 --- a/python/tests/test_host_fluid.py +++ b/python/tests/test_host_fluid.py @@ -11,6 +11,7 @@ from __future__ import annotations import math +import runpy import subprocess from pathlib import Path @@ -259,6 +260,19 @@ def test_host_field_takes_a_stiffener_and_as_laid_friction(tmp_path): assert _nrmse(reference, history) < TOLERANCE +def test_a_host_marches_past_the_deck_tmax(tmp_path): + deck = _deck(tmp_path, "library", CURRENT) + deck.write_text(deck.read_text(encoding="utf-8").replace("6.0 TMax", "0.1 TMax"), "utf-8") + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(deck) + _host_field(model, 0.0, SPEED) + for i in range(1, 21): + _host_field(model, i * DT, SPEED) + model.step(DT, *_motion(i * DT)) + assert np.all(np.isfinite(model.calc_output())) + + def test_save_and_restore_carry_the_held_field(tmp_path): with CableDyn() as model: model.set_host_fluid() @@ -350,3 +364,12 @@ def test_the_switch_can_be_turned_off(tmp_path): model.set_host_fluid(False) model.init_deck(deck) assert model.n_fluid_nodes == 0 + + +def test_the_stepping_example_runs(): + example = ( + Path(__file__).resolve().parents[2] / "examples" / "python" / "step_in_moving_water.py" + ) + tensions = runpy.run_path(str(example))["main"](duration=2.0) + assert len(tensions) == 40 + assert all(math.isfinite(value) and value > 0.0 for value in tensions) From 51ed760973bc4d7bff6d2325af165a9d2c9f2a4c Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 20:50:30 +0900 Subject: [PATCH 3/6] test(capi): carry the held field with a stiffener and as-laid friction Signed-off-by: Jae Hoon Seo --- python/tests/test_host_fluid.py | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/python/tests/test_host_fluid.py b/python/tests/test_host_fluid.py index c53df234..ca234f56 100644 --- a/python/tests/test_host_fluid.py +++ b/python/tests/test_host_fluid.py @@ -105,6 +105,7 @@ 1 A Rigid 0.3 0.0 -0.9539 """ +FRICTION = "0.5 frictionMu\nasLaid staticsFriction\n0 layAzimuth" CURRENT = f"uniform {SPEED} 0 0 current" WAVE = f"airy {HEIGHT} {PERIOD} 0 waves" @@ -250,8 +251,7 @@ def test_host_field_matches_the_driver_in_current_and_waves(tmp_path): def test_host_field_takes_a_stiffener_and_as_laid_friction(tmp_path): - friction = "0.5 frictionMu\nasLaid staticsFriction\n0 layAzimuth" - options = f"{CURRENT}\n{friction}" + options = f"{CURRENT}\n{FRICTION}" reference = _driver_run(tmp_path, f"{options}\n{WAVE}", STIFFENER) with CableDyn() as model: model.set_host_fluid() @@ -273,10 +273,15 @@ def test_a_host_marches_past_the_deck_tmax(tmp_path): assert np.all(np.isfinite(model.calc_output())) -def test_save_and_restore_carry_the_held_field(tmp_path): +@pytest.mark.parametrize( + "options, tables", + [(CURRENT, ""), (CURRENT + "\n" + FRICTION, STIFFENER)], + ids=["plain", "stiffener-and-as-laid-friction"], +) +def test_save_and_restore_carry_the_held_field(tmp_path, options, tables): with CableDyn() as model: model.set_host_fluid() - model.init_deck(_deck(tmp_path, "library", CURRENT)) + model.init_deck_rotating(_deck(tmp_path, "library", options, tables)) _host_field(model, 0.0, SPEED) for i in range(1, 6): _host_field(model, i * DT, SPEED) From e801cc33af14c105ae7b8d0fcfd84a8d2d1857b3 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 21:13:10 +0900 Subject: [PATCH 4/6] fix(capi): point the point-field refusal to the host fluid calls Signed-off-by: Jae Hoon Seo --- src/CableDyn_CAPI.f90 | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 0db74491..05ce06ce 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -1069,7 +1069,8 @@ SUBROUTINE CableDyn_UpdatePointFluidFields(handle, fluid_velocity_ptr, fluid_acc IF (err_stat /= CD_C_OK) RETURN IF (h%use_agg) THEN CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdatePointFluidFields: a deck with finite-EI lines, BODIES or '// & - 'RODS runs on the coupled aggregate, which takes no point fluid fields', err_stat) + 'RODS runs on the coupled aggregate, which takes no point fluid fields; supply the '// & + 'fluid at its nodes with CableDyn_SetHostFluid and CableDyn_UpdateFluidFields', err_stat) RETURN END IF IF (n_point < 0_C_INT) THEN From b733ee3ce965166b8c26ddb3a98baa05c838ec27 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 21:33:18 +0900 Subject: [PATCH 5/6] chore(release): check the newest Python ABI level Signed-off-by: Jae Hoon Seo --- release/check_release_metadata.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/release/check_release_metadata.py b/release/check_release_metadata.py index ae9172e7..1c4113de 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -140,7 +140,7 @@ def main() -> int: "C header ABI minor level": f"CABLEDYN_CAPI_ABI_MINOR {abi_minor}" in read( "src/CableDyn_CAPI.h" ), - "Python ABI minor level": f"HOST_ROTATION_ABI_MINOR = {abi_minor}" in read( + "Python ABI minor level": f"HOST_FLUID_ABI_MINOR = {abi_minor}" in read( "python/cabledyn/_lib.py" ), "C header ABI version": f"CABLEDYN_CAPI_ABI_VERSION {abi_version}" in read( From 8b30aa2bcf130f6ced2717073284880697a47378 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Sat, 7 Nov 2026 21:39:26 +0900 Subject: [PATCH 6/6] fix(capi): read a host-field deck by the coupled rules Signed-off-by: Jae Hoon Seo --- doc/capi.rst | 6 ++++-- examples/python/step_in_moving_water.py | 1 - python/tests/test_host_fluid.py | 26 +++++++++++++++++++++++++ src/CableDyn_CAPI.f90 | 5 ++++- 4 files changed, 34 insertions(+), 4 deletions(-) diff --git a/doc/capi.rst b/doc/capi.rst index 1a463d2a..8260b57a 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -736,8 +736,10 @@ the whole water of the march; a deck current that varies in time is refused. Seabed friction, ``staticsFriction asLaid`` and ``STIFFENERS`` work on this route. -A deck with a current also declares ``TMax``, as under the standalone rules; it does not limit the -host, which owns the clock and may step past it. +With a host field the deck is read by the coupled rules, as in OpenFAST: it needs no ``TMax``, and a +``SEASTATE`` or ``WaveKinMod 2`` water policy takes the host's field. A deck current marched without +one follows the standalone rules and declares ``TMax``. Neither limits the host, which owns the clock +and may step past it. Call sequence ~~~~~~~~~~~~~ diff --git a/examples/python/step_in_moving_water.py b/examples/python/step_in_moving_water.py index dc7e1157..11423a1f 100644 --- a/examples/python/step_in_moving_water.py +++ b/examples/python/step_in_moving_water.py @@ -48,7 +48,6 @@ 1025.0 rhoW 60.0 WtrDpth 0.05 dtM -3600.0 TMax - required with a deck current; the host owns the clock and may run past it uniform 0.4 0 0 current --------------------- OUTPUTS ----------------------------------------------- "FairTen1" diff --git a/python/tests/test_host_fluid.py b/python/tests/test_host_fluid.py index ca234f56..1af63874 100644 --- a/python/tests/test_host_fluid.py +++ b/python/tests/test_host_fluid.py @@ -273,6 +273,32 @@ def test_a_host_marches_past_the_deck_tmax(tmp_path): assert np.all(np.isfinite(model.calc_output())) +@pytest.mark.parametrize("policy", ["SEASTATE WaterKin", "water.dat WaterKin"]) +def test_host_water_policies_of_a_deck_take_the_host_field(tmp_path, policy): + text = WATERKIN.replace("0 WaveKinMod", "2 WaveKinMod") + text = text.replace("1 CurrentMod", "2 CurrentMod") + (tmp_path / "water.dat").write_text(text, encoding="utf-8") + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(_deck(tmp_path, "library", policy)) + _host_field(model, 0.0, SPEED) + _host_field(model, DT, SPEED) + model.step(DT, *_motion(DT)) + assert np.all(np.isfinite(model.calc_output())) + + +def test_a_host_field_deck_needs_no_tmax(tmp_path): + deck = _deck(tmp_path, "library", CURRENT) + deck.write_text(deck.read_text(encoding="utf-8").replace("6.0 TMax", ""), "utf-8") + with CableDyn() as model: + model.set_host_fluid() + model.init_deck(deck) + _host_field(model, 0.0, SPEED) + _host_field(model, DT, SPEED) + model.step(DT, *_motion(DT)) + assert np.all(np.isfinite(model.calc_output())) + + @pytest.mark.parametrize( "options, tables", [(CURRENT, ""), (CURRENT + "\n" + FRICTION, STIFFENER)], diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 05ce06ce..98a50426 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -399,7 +399,10 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, er ! A deck with BODIES or RODS (standalone rules: a motionFile-free deck with dtM) runs on the ! coupled aggregate; every other deck keeps the point-system route and its diagnostics. ! A deck with finite-EI lines likewise runs on the aggregate (its Hermite cables). - CALL CD_Deck_Query_dtM(TRIM(deck_path), dtm, has_dtm, es, em, standalone_scan=.TRUE., n_bodies_rods=n_objects, & + ! With a host fluid field the deck is read as the aggregate reads it, a caller-driven deck, so + ! the SEASTATE and WaveKinMod 2 water policies of a host reach it. + CALL CD_Deck_Query_dtM(TRIM(deck_path), dtm, has_dtm, es, em, standalone_scan=.NOT. h%host_fluid, & + n_bodies_rods=n_objects, & n_finite_ei=n_finite) IF (es == CD_DECKDRV_OK .AND. (n_objects > 0 .OR. n_finite > 0 .OR. h%host_fluid)) THEN CALL init_deck_aggregate(h, TRIM(deck_path), has_dtm, dtm, caller, rot, err_stat, positions)