From 8786479644db4f952938cdbfa8c6e24cec4c1c07 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 15 Oct 2026 13:42:35 +0900 Subject: [PATCH 1/3] feat(capi): host-coupling calls for CFD hosts (ABI 1.2) A host that drives the Coupled points of a deck, such as a CFD solver with a rigid-body solver, had three gaps compared with MoorDyn's C API: - CableDyn_InitDeck solved the statics at the deck coordinates, while MoorDyn_Init(X, XD) moves the coupled points to the host's positions first. A body that starts elsewhere gave the lines a start-up transient. For foamMooring's EsfLOWC box, whose fairleads start 15 mm below the deck, the fairlead load of line 4 moved by up to 0.38 N of its 0.52 N static value and was still 0.04 N off after 1 s. - There was no way to rewind the model between the outer correctors of a host time step (MoorDyn_Serialize/Deserialize). - The layout of the coupled vector differs from MoorDyn's (on the point route it includes the Fixed anchors) and could only be derived from the deck. New entry points, C ABI 1 minor extension 2; no existing function changes: - CableDyn_InitDeckAt solves the statics with every line-bound Coupled/Vessel point at its entry of q0, on the point route (new optional coupled_positions of CD_Init_Deck_System) and the aggregate route (CD_AGG_Init_From_Deck). q0 is either the host blocks alone, MoorDyn's X layout, or the full coupled vector. A post-check confirms that every host block starts at q0. For the box the held fairleads then keep their load to 2e-16 N, and line 4's load (0.3026, -0.0761, -0.4114) N is bit-identical to the deck moved to the host positions. - CableDyn_SaveState and CableDyn_RestoreState keep one in-memory deep copy of the whole model (and the aggregate's committed time). It is independent of the step's own rollback buffers, so any number of steps, including the dtM sub-steps of a host step, may lie between save and restore. Restore then step is bit-identical to stepping from the saved state on both routes. - CableDyn_GetCoupledLayout returns the deck point id and type of every block of the coupled vector. Python gains init_deck_at, save_state, restore_state, coupled_layout and host_dofs. The C API manual has a new section, Coupling a host (CFD) solver, that compares the call sequence with MoorDyn's step by step: initialisation, vector layout, end-of-step motion, outer correctors, load summation, the fixed step of the aggregate route and units. Tests: c_api_host_coupling (the box deck, a chain-and-cable aggregate deck), save/restore in test_c_api and the 1 MiB stack gate, and python/tests/test_host_coupling.py. Signed-off-by: Jae Hoon Seo --- ARCHITECTURE.md | 7 +- CHANGELOG.md | 17 + CMakeLists.txt | 22 +- doc/api_python.rst | 65 ++- doc/capi.rst | 390 +++++++++++++++++- doc/coupling_boundary.md | 5 +- doc/python.rst | 17 + python/cabledyn/_lib.py | 35 ++ python/cabledyn/model.py | 146 ++++++- python/tests/test_host_coupling.py | 160 ++++++++ python/tests/test_objects.py | 3 +- release/check_release_metadata.py | 2 +- src/CableDyn_CAPI.f90 | 400 ++++++++++++++++-- src/CableDyn_CAPI.h | 56 ++- src/CableDyn_DeckDriver.f90 | 78 +++- src/cabledyn.def | 4 + src/cabledyn.exp | 4 + src/cabledyn.map | 4 + tests/data/foam_esflowc_box_points.dat | 41 ++ tests/data/host_coupling_chain_cable.dat | 35 ++ tests/test_c_api.f90 | 21 +- tests/test_c_api_host_coupling.c | 497 +++++++++++++++++++++++ tests/test_c_api_shared.c | 3 +- tests/test_c_api_stack.c | 25 +- 24 files changed, 1959 insertions(+), 78 deletions(-) create mode 100644 python/tests/test_host_coupling.py create mode 100644 tests/data/foam_esflowc_box_points.dat create mode 100644 tests/data/host_coupling_chain_cable.dat create mode 100644 tests/test_c_api_host_coupling.c diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 71582bd4..e7e2c77a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -500,8 +500,11 @@ import only Windows system DLLs. minor extension 1 (`CableDyn_GetAbiMinor() ≥ 1`) adds in-process object queries (object counts and ids, line node and segment values, point, body, and rod states, and any output channel through `CableDyn_EvalChannel`), which return - what the matching output channel reports for the same state (see - [doc/capi.rst](doc/capi.rst)). + what the matching output channel reports for the same state. Minor extension 2 + (`≥ 2`) adds the host-coupling calls: `CableDyn_InitDeckAt` (the statics solved + at the host's coupled-point positions), `CableDyn_SaveState` / + `CableDyn_RestoreState` (a one-slot deep copy of the model object for outer + correctors) and `CableDyn_GetCoupledLayout` (see [doc/capi.rst](doc/capi.rst)). - **Python** (`python/cabledyn`): runs the driver, reads and post-processes outputs, edits decks, runs studies, and binds the C interface through ctypes with a pinned ABI version. With its object views and snapshots it is designed diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fd83771..0d160eb7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -76,6 +76,23 @@ All notable changes to CableDyn are recorded in this file. The format follows body, which move the line ends by translation only, still refuse torsion columns by name, and so does OpenFAST linearisation of a line restrained in torsion. See the manual's OpenFAST page (Line torsion). +- C ABI 1 minor extension 2 (`CableDyn_GetAbiMinor() == 2`) for hosts that drive the + `Coupled` points of a deck, such as CFD solvers. Every existing function is unchanged. + `CableDyn_InitDeckAt` solves the statics with the `Coupled`/`Vessel` points at the host's + positions, the counterpart of `MoorDyn_Init(X, XD)` (the statics start at rest), so a body + that starts away from the deck coordinates starts without a transient: for foamMooring's + `EsfLOWC` box, whose fairleads start 15 mm below the deck, the fairlead load of + `CableDyn_InitDeck` followed by held fairleads deviates by up to 0.38 N of 0.52 N, and stays + constant to round-off after `CableDyn_InitDeckAt`. `CableDyn_SaveState` and + `CableDyn_RestoreState` keep one in-memory copy of the whole model for outer correctors + (PIMPLE); a restore followed by a step is bit-identical to stepping from the saved state, on + both routes and across any number of steps. `CableDyn_GetCoupledLayout` returns the deck point + id and type of every block of the coupled vector, which on the point route includes the + `Fixed` anchors. The Python `CableDyn` class gains `init_deck_at`, `save_state`, + `restore_state`, `coupled_layout` and `host_dofs`. The manual's C API page has a new section, + Coupling a host (CFD) solver, that compares the call sequence step by step with MoorDyn's C + API: initialisation, vector layout, end-of-step motion, outer correctors, load summation, + the fixed step of the aggregate route, and units. ### Changed diff --git a/CMakeLists.txt b/CMakeLists.txt index f3fbb945..c04ed5c6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1081,6 +1081,20 @@ add_test(NAME c_api_shared ${CMAKE_CURRENT_SOURCE_DIR}/examples/dynamic_chain_waves.dat) set_tests_properties(c_api_shared PROPERTIES LABELS "c;unit;capi;shared") +# The host-coupling calls of ABI 1.2 through the public header and the shared library: +# initialization at the host's positions (the foamMooring EsfLOWC box, whose fairleads start +# below their deck coordinates), state save/restore on both routes, and the layout query. +add_executable(test_c_api_host_coupling tests/test_c_api_host_coupling.c) +target_include_directories(test_c_api_host_coupling PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(test_c_api_host_coupling PRIVATE cabledyn_shared) +if(NOT WIN32) + target_link_libraries(test_c_api_host_coupling PRIVATE m) +endif() +add_test(NAME c_api_host_coupling + COMMAND test_c_api_host_coupling ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/foam_esflowc_box_points.dat + ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/host_coupling_chain_cable.dat) +set_tests_properties(c_api_host_coupling PROPERTIES LABELS "c;unit;capi;shared;dynamic") + find_package(Threads QUIET) if(Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) add_executable(test_c_api_concurrency tests/test_c_api_concurrency.c) @@ -1094,10 +1108,10 @@ else() endif() # Portable (Win32 or POSIX threads) stack bound of the shared library: each deck is -# initialised, stepped, and evaluated on a thread with a 1 MiB stack (a host program, not -# CableDyn, chooses the stack of the threads that call the library). The decks are a -# 2048-element finite-EI cable (12294 DOFs), an EI=0 + finite-EI aggregate, and an EI=0 -# mooring; a stack need that grew with the model would overflow here. +# initialised, stepped, saved and restored, and evaluated on a thread with a 1 MiB stack (a +# host program, not CableDyn, chooses the stack of the threads that call the library). The +# decks are a 2048-element finite-EI cable (12294 DOFs), an EI=0 + finite-EI aggregate, and an +# EI=0 mooring; a stack need that grew with the model would overflow here. add_executable(test_c_api_stack tests/test_c_api_stack.c) target_include_directories(test_c_api_stack PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") target_link_libraries(test_c_api_stack PRIVATE $) diff --git a/doc/api_python.rst b/doc/api_python.rst index bc98e41d..4502dc4a 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -513,6 +513,62 @@ library is located. Array ordering, frames, and units at the coupling boundary f :raises ValueError: if the path contains a NUL character or, on Windows, cannot be represented in the active ANSI code page. + .. py:method:: init_deck_at(deck, q0) + + Initialise from a deck file with the static initial condition solved at the host's + positions of the coupled points (``CableDyn_InitDeckAt``). Every line-bound + ``Coupled``/``Vessel`` point starts at its entry of ``q0`` instead of its deck coordinates; + the lines, ``Free``/``Connect`` points, bodies and rods are solved in equilibrium with those + points held there, at rest. A host whose body starts away from the deck coordinates then + starts without a transient (:ref:`capi-host-coupling`). + + :param deck: Path of the ``.dat`` deck, as for :meth:`init_deck`. + :type deck: str | os.PathLike + :param q0: Either the full coupled vector of the deck (``n_coupled_dof`` values, the layout + :meth:`step` uses; the ``Fixed``, ``Free`` and ``Connect`` blocks are not read), or the + ``Coupled``/``Vessel`` blocks alone, in coupled-vector order (the ``MoorDyn_Init`` + layout of a points-only deck). Flat or column-per-point ``(3, n)``; positions in m. + :type q0: array_like + :raises CableDynError: if the deck fails to initialise, or ``q0`` does not match its + coupled points. A failed initialisation keeps any previously initialised model. + :raises ValueError: if ``q0`` is not finite or its length is not a multiple of 3. + :raises RuntimeError: if the loaded library predates ABI 1 minor extension 2. + + .. py:method:: save_state() + restore_state() + + Save the whole model, and :attr:`time`, into the instance's single save slot; return to + it (``CableDyn_SaveState``, ``CableDyn_RestoreState``). The slot is a copy of every line, + point, body and rod state with its solver history. A restore keeps the slot, so one save + serves every outer corrector of a host time step, and a restore followed by a step is + bit-identical to taking that step from the saved state directly. A new initialisation + discards the slot. + + :raises CableDynError: on an uninitialised model, or from :meth:`restore_state` when + nothing was saved since the model was initialised. + :raises RuntimeError: if the loaded library predates ABI 1 minor extension 2. + + .. py:method:: coupled_layout() + + Return the owner of each 3-DOF block of the coupled vector (``CableDyn_GetCoupledLayout``): + a tuple of ``(point_id, kind)`` pairs, block ``k`` holding the degrees of freedom + ``3k .. 3k+2``. ``kind`` is ``"fixed"``, ``"coupled"`` (``Coupled`` or ``Vessel``), + ``"free"`` or ``"connect"``. On a point-system deck every line-bound point has a block, in + deck ``POINTS`` order; on the coupled aggregate (finite-EI lines, bodies or rods) only the + ``Coupled`` points do. + + :rtype: tuple[tuple[int, str], ...] + :raises CableDynError: on an uninitialised model or one built from raw arrays. + + .. py:method:: host_dofs() + + Return the indices of the coupled degrees of freedom the host drives, those of the + ``"coupled"`` blocks of :meth:`coupled_layout`, as an integer array. With ``x`` the + ``(3, n)`` host positions of those points in layout order, + ``q[model.host_dofs()] = x.reshape(-1, order="F")`` fills them in a full coupled vector. + + :rtype: numpy.ndarray + .. py:property:: initialized :type: bool @@ -666,7 +722,8 @@ library is located. Array ordering, frames, and units at the coupling boundary f .. py:property:: time :type: float - Simulation time (s): 0 after initialisation, advanced by every completed step. + Simulation time (s): 0 after initialisation, advanced by every completed step, and set back + by :meth:`restore_state`. .. py:property:: deck :type: pathlib.Path | None @@ -711,8 +768,10 @@ imports without the shared library. .. py:function:: abi_minor() - Return the extension level of ABI 1 of the loaded library: 1 when it has the object queries - behind :attr:`CableDyn.lines` and :meth:`CableDyn.channel`, 0 for an older library. + Return the extension level of ABI 1 of the loaded library: 2 when it also has the + host-coupling calls behind :meth:`CableDyn.init_deck_at`, :meth:`CableDyn.save_state` and + :meth:`CableDyn.coupled_layout`, 1 when it has the object queries behind + :attr:`CableDyn.lines` and :meth:`CableDyn.channel`, 0 for an older library. :rtype: int diff --git a/doc/capi.rst b/doc/capi.rst index 2c6bf44c..ff05fcb5 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -29,13 +29,19 @@ A model lives behind an opaque handle. The lifecycle is: .. code-block:: text CableDyn_Create - -> CableDyn_InitDeck | CableDyn_InitLine | CableDyn_InitLines (initialize; may repeat) + -> CableDyn_InitDeck | CableDyn_InitDeckAt (initialize; may repeat) + | CableDyn_InitLine | CableDyn_InitLines -> CableDyn_GetCoupledMotion (read the initial state) - -> loop: [CableDyn_UpdatePointFluidFields] + -> loop: [CableDyn_SaveState | CableDyn_RestoreState] (host outer correctors) + [CableDyn_UpdatePointFluidFields] CableDyn_Step(dt, motion at t+dt) CableDyn_CalcOutput (loads at t+dt) -> CableDyn_Close +A host solver that drives the ``Coupled`` points of a deck, a CFD code in particular, should +read `Coupling a host (CFD) solver`_ first: it gives the call sequence and how it differs from +MoorDyn's C API. + .. list-table:: Function summary :header-rows: 1 :widths: 38 62 @@ -72,6 +78,11 @@ A model lives behind an opaque handle. The lifecycle is: ``CableDyn_GetRodState``, ``CableDyn_EvalChannel`` - object queries (ABI 1.1): the objects of the model, their committed state, and any ``OUTPUTS`` channel (`Object queries`_) + * - ``CableDyn_InitDeckAt``, ``CableDyn_SaveState``, ``CableDyn_RestoreState``, + ``CableDyn_GetCoupledLayout`` + - host coupling (ABI 1.2): initialization with the statics at the host's positions, a + one-slot state save and restore for outer correctors, and the owner of each block of + the coupled vector (`Host coupling calls`_) Building and linking -------------------- @@ -125,7 +136,7 @@ a work buffer of about 128 MB at once (about 4 GB on a 32-CPU machine). The Wind therefore does not import ``openblas.dll``: the first ``CableDyn_Create`` (or, in an executable, the first solve) loads the ``openblas.dll`` next to the CableDyn library or executable with a one-thread pool, falling back to the standard DLL search order. If it cannot be loaded, -``InitDeck``, ``InitLine`` and ``InitLines`` return ``CD_C_ALLOC_FAIL`` and +``InitDeck``, ``InitDeckAt``, ``InitLine`` and ``InitLines`` return ``CD_C_ALLOC_FAIL`` and ``CableDyn_GetLastError`` names the library, each location tried and the Windows load error; the standalone driver prints the same diagnostic and exits with status 2. Other builds that link OpenBLAS call ``openblas_set_num_threads(1)`` at the first ``Create``; the Intel @@ -226,8 +237,9 @@ ABI and versioning - 1 - the C ABI revision the header describes * - ``CABLEDYN_CAPI_ABI_MINOR`` / ``CableDyn_GetAbiMinor()`` - - 1 - - additive extensions of ABI 1: 1 adds the `Object queries`_ + - 2 + - additive extensions of ABI 1: 1 adds the `Object queries`_, 2 the + `Host coupling calls`_ * - ``CableDyn_GetVersion(&major, &minor, &patch, &abi)`` - runtime - the same four numbers, reported by the loaded library @@ -258,7 +270,8 @@ The Python package does this check at import and rejects a library that speaks a A minor extension only adds functions: every ABI 1 prototype and its semantics are unchanged, so a caller built against an older header keeps working. A caller that uses the additions checks -``CableDyn_GetAbiMinor() >= 1`` before calling them. +``CableDyn_GetAbiMinor() >= 1`` before calling the object queries, and +``CableDyn_GetAbiMinor() >= 2`` before calling the host-coupling functions. Calling conventions ------------------- @@ -301,10 +314,10 @@ These rules apply to every entry point. The Python package uses the same array o water at :math:`z = 0` (:doc:`conventions`). See `State, units, and load sign`_. * **Threads.** ``Create`` and ``Close`` are thread-safe; a process-wide mutex guards the handle registry, independently of OpenMP. Separate handles may run concurrently on separate threads. - ``InitDeck``, ``InitLine``, and ``InitLines`` are serialised by a second process-wide lock: - they open and parse files through the Fortran runtime, which cannot open one file on two units - at once (two threads reading the same deck, or decks sharing a Syrope OWC table) and whose - formatted I/O is not safe to run concurrently. Concurrent initialisations therefore succeed but + ``InitDeck``, ``InitDeckAt``, ``InitLine``, and ``InitLines`` are serialised by a second + process-wide lock: they open and parse files through the Fortran runtime, which cannot open + one file on two units at once (two threads reading the same deck, or decks sharing a Syrope + OWC table) and whose formatted I/O is not safe to run concurrently. Concurrent initialisations therefore succeed but run one after another; a thread blocks while another thread initialises. ``Step``, ``UpdateStates``, ``CalcOutput``, and the other per-handle calls do no file or formatted I/O when they succeed and run concurrently on separate handles. A single handle must not be used @@ -322,7 +335,8 @@ These rules apply to every entry point. The Python package uses the same array o the new handle. * **Re-initialisation is atomic.** Calling any ``Init*`` function on an initialised handle replaces the model only on success. If the new initialisation fails, the previous model is - kept unchanged. + kept unchanged, and so is the state saved by ``CableDyn_SaveState``; a successful one + discards that save. * **Time.** The library keeps no clock. Only ``dt`` enters ``CableDyn_Step``, and the host owns the time line. @@ -378,13 +392,20 @@ Coupled DOF layout so do the rows and columns of every Jacobian. The layout is fixed when the handle is initialised. -``CableDyn_InitDeck`` +``CableDyn_InitDeck`` or ``CableDyn_InitDeckAt``, point route (``EI = 0`` lines only) One ``x, y, z`` block for every deck point that is attached to at least one line end, in ``POINTS`` table order. This includes points of every type: ``Fixed`` anchors, ``Coupled``/``Vessel`` points, and ``Free``/``Connect`` points. ``n_coupled_dof`` is three times the number of attached points. A point referenced by no line gets no block, but it is still counted by ``CableDyn_NPoints``. +``CableDyn_InitDeck`` or ``CableDyn_InitDeckAt``, aggregate route (finite-EI lines, bodies, rods) + One ``x, y, z`` block for every host-driven point and nothing else: first the + ``Coupled``/``Vessel`` points attached to an ``EI = 0`` line, in ``POINTS`` table order, + then the fairlead (End A, which must be ``Coupled``/``Vessel``) of each finite-EI line, in + ``LINES`` table order. ``Fixed`` anchors, ``Free``/``Connect`` points, bodies and rods have + no block. + ``CableDyn_InitLine`` ``n_fixed`` entries. Entry ``k`` is the DOF ``fixed_dofs[k]``, in the order the caller listed them. @@ -404,6 +425,11 @@ anchor blocks of a deck. Fill the vectors once from ``CableDyn_GetCoupledMotion` overwrite only the blocks the host drives. Deck ``Free`` and ``Connect`` points are the exception, described under ``CableDyn_Step``. +On a deck model, ``CableDyn_GetCoupledLayout`` (ABI 1.2) returns the deck point id and type +of every block, so a host does not have to derive the layout from the deck: the host drives +the blocks of type ``CD_C_POINT_COUPLED``. `Coupling a host (CFD) solver`_ works through an +example. + State, units, and load sign --------------------------- @@ -448,6 +474,206 @@ their loads at that point are summed. **Jacobians.** For the tight Newton loop of a monolithic host, the linear load model is :math:`L(q+\delta q, v+\delta v, a+\delta a) \approx L + J_q\,\delta q + J_v\,\delta v - M_a\,\delta a`. +.. _capi-host-coupling: + +Coupling a host (CFD) solver +---------------------------- + +This section is for a host that moves a body with its own equations of motion, typically a CFD +solver with a rigid-body solver, and drives the deck's ``Coupled`` points as fairleads on that +body. It goes through the coupling step by step and compares each step with MoorDyn's C API +(``MoorDyn_Create``, ``MoorDyn_Init``, ``MoorDyn_Step``, ``MoorDyn_Serialize``), because a host +written for MoorDyn needs the differences below, not only renamed calls. The functions are +those of ABI 1.2: check ``CableDyn_GetAbiMinor() >= 2``. + +The example is the floating box of foamMooring's ``EsfLOWC`` tutorial, +``tests/data/foam_esflowc_box_points.dat``: four slack ``EI = 0`` lines from ``Fixed`` anchors +1 to 4 to ``Coupled`` fairleads 5 to 8. The deck places the fairleads at +:math:`z = -0.062` m; the CFD box starts with them at :math:`z = -0.077` m. + +Step 1: initialise at the host's positions +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*MoorDyn.* ``MoorDyn_Create`` parses the input file; ``MoorDyn_Init(X, XD)`` then moves the +coupled points to the host's ``X`` and computes the initial condition there. + +*CableDyn.* ``CableDyn_InitDeckAt(h, deck, deck_len, q0, n_q0, &err)`` does both in one call: it +parses the deck and solves the statics with every line-bound ``Coupled``/``Vessel`` point held at +its entry of ``q0``. ``CableDyn_InitDeck`` solves them at the deck coordinates instead, and a +host whose body starts elsewhere then gives the lines a start-up transient on its first steps. +For the box, the deck statics followed by fairleads held 15 mm lower move line 4's fairlead load +by up to 0.38 N, 74 % of its 0.52 N static value, and it is still 0.04 N off after 1 s +(:math:`\Delta t = 10^{-3}` s). After ``CableDyn_InitDeckAt`` the held fairleads keep their +load to round-off (:math:`2 \times 10^{-16}` N over the same second), and line 4's fairlead load +is the standalone value of the deck moved to the CFD positions, (0.3026, -0.0761, -0.4114) N +(MoorDyn: (0.3034, -0.0763, -0.4136) N). + +``q0`` is one of two vectors; its length selects which: + +* the ``Coupled``/``Vessel`` blocks alone, in coupled-vector order: 3 values per host point. + This is the layout of MoorDyn's ``X`` for a deck whose coupled objects are points, and the + one a host that knows only its fairleads can build before any handle exists; +* the full coupled vector, ``CableDyn_NCoupledDOF`` values. Its ``Fixed``, ``Free`` and + ``Connect`` blocks are not read. + +The statics start at rest: there is no counterpart of MoorDyn's ``XD``. A host whose body is +already moving imposes the velocities on the coupled blocks with ``CableDyn_UpdateStates`` +after the initialisation; the line interiors stay at rest. + +Step 2: build the coupled vector from the layout +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*MoorDyn.* The coupled vector holds the coupled objects and nothing else: 3 values per coupled +point, 6 per coupled body or rod. + +*CableDyn.* On the point route (decks of ``EI = 0`` lines) the vector has a block for every +line-bound point, ``Fixed`` anchors included, in ``POINTS`` order. On the aggregate route +(finite-EI lines, bodies or rods) only the host-driven points have blocks (`Coupled DOF +layout`_). Ask the handle rather than deriving the layout from the deck: + +.. code-block:: c + + int n = CableDyn_NCoupledDOF(h, &err); /* 24 for the box */ + int ids[8], types[8]; /* n / 3 blocks */ + CableDyn_GetCoupledLayout(h, ids, types, n / 3, &err); + +.. list-table:: Coupled vector of the box (point route) + :header-rows: 1 + :widths: 14 18 18 50 + + * - Block ``k`` + - DOFs + - ``point_id[k]`` + - ``point_type[k]`` + * - 0 to 3 + - 0 to 11 + - 1 to 4 + - ``CD_C_POINT_FIXED``: the anchors + * - 4 to 7 + - 12 to 23 + - 5 to 8 + - ``CD_C_POINT_COUPLED``: the fairleads, driven by the host + +Seed ``q``, ``v`` and ``a`` once from ``CableDyn_GetCoupledMotion`` after the initialisation, +and before each step overwrite only the ``CD_C_POINT_COUPLED`` blocks. Every block is +prescribed on every step, so the anchor blocks must keep the values ``GetCoupledMotion`` +returned: zeros there would move the anchors to the origin. ``CableDyn_CalcOutput`` returns a +load for every block, and the anchor blocks carry the anchor reactions, which are not loads on +the host. + +Step 3: step with the motion at the end of the step +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*MoorDyn.* ``MoorDyn_Step(X, XD, F, &t, &dt)`` takes the coupled state at the start of the +step, :math:`t`, extrapolates it over the step with ``XD``, and returns the forces at +:math:`t + \Delta t`. + +*CableDyn.* ``CableDyn_Step(h, dt, q, v, a, ...)`` takes the prescribed position, velocity and +acceleration at the end of the step, :math:`t + \Delta t`, and ``CableDyn_CalcOutput`` then +returns the loads at :math:`t + \Delta t`. Pass the host's motion for the new time level (in a +CFD time step, the body's current iterate for it) with a consistent acceleration: the +integrator uses ``v`` and ``a``, not only ``q``. A host without body accelerations can use the +backward difference :math:`a = (v(t + \Delta t) - v(t)) / \Delta t`. + +Step 4: outer correctors save and restore +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +A host that iterates its time step (PIMPLE outer correctors, predictor-corrector schemes) +advances the mooring once per pass and must rewind it between passes, or the mooring advances +by several steps per host step. + +*MoorDyn.* The host serialises the system at the start of the time step +(``MoorDyn_Serialize``) and deserialises it before every repeated pass. + +*CableDyn.* ``CableDyn_SaveState`` copies the whole model into the handle's single save slot +(every line, point, body and rod state with its solver history); ``CableDyn_RestoreState`` +returns to it. A restore keeps the slot, so one save at the first pass of a time step serves +every later pass. A restore followed by a step is bit-identical to taking that step from the +saved state directly, and any number of steps may lie between the save and the restore (the +sub-steps of Step 6). A successful ``Init*`` call discards the save. + +The names differ from MoorDyn's file calls: ``MoorDyn_SaveState`` writes the state to a file, +``CableDyn_SaveState`` keeps it in memory. Serialising the state to a caller buffer or a +restart file (``MoorDyn_Serialize``, ``MoorDyn_Save``/``MoorDyn_Load``) is not supported. A +restarted host re-initialises with ``CableDyn_InitDeckAt`` at its restart positions, which +gives the statics there rather than the dynamic state. + +Step 5: sum the loads into a rigid-body force and moment +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The sign convention is MoorDyn's: each block of ``coupled_loads`` is the force the lines exert +on that point, in newtons, in global axes (`State, units, and load sign`_). For a rigid body +with reference point :math:`r`, sum the ``CD_C_POINT_COUPLED`` blocks only: + +.. math:: + + F = \sum_k f_k, \qquad M_r = \sum_k (x_k - r) \times f_k + +where :math:`x_k` is the fairlead position the step was taken with. A host that applies the +moment about the global origin (foamMooring's ``moorDynR2`` in point mode accumulates +:math:`x_k \times f_k`) uses :math:`r = 0`. Do not add the anchor blocks. + +Step 6: fixed step on the aggregate route +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +On the point route each ``CableDyn_Step`` takes any :math:`\Delta t > 0`. On the aggregate route +every step must use the deck's ``dtM``: a host step of :math:`m` times ``dtM`` is taken as +:math:`m` calls of ``CableDyn_Step``, with the host-driven motion interpolated linearly between +the start and the end of the host step. One ``CableDyn_SaveState`` before the first sub-step +and one ``CableDyn_RestoreState`` undo all of them. MoorDyn sub-steps internally with its own +``dtM``. + +Step 7: units and frame +~~~~~~~~~~~~~~~~~~~~~~~ + +SI units in the global right-handed frame with z up and still water at :math:`z = 0` +(:doc:`conventions`), as in MoorDyn. A host in another frame or unit system converts the +motion it passes and the loads it receives. + +Call sequence +~~~~~~~~~~~~~ + +The calls a restraint of a CFD rigid-body solver makes, with ``n_fair`` fairleads on one body +whose positions ``x_fair`` (``3 * n_fair`` values in coupled-vector order: on the point route +the deck's ``POINTS`` order of the ``Coupled`` points) the host computes from the body pose: + +.. code-block:: c + + /* First call, the body at its initial pose. */ + CableDyn_Create(&h, &err); + CableDyn_InitDeckAt(h, deck, (int)strlen(deck), x_fair, 3 * n_fair, &err); + n = CableDyn_NCoupledDOF(h, &err); + CableDyn_GetCoupledLayout(h, ids, types, n / 3, &err); /* host blocks: CD_C_POINT_COUPLED */ + CableDyn_GetCoupledMotion(h, q, v, a, n, &err); /* seed every block */ + t_saved = -HUGE_VAL; /* nothing saved yet */ + + /* Every call: time t = t_prev + dt of the current pass of the host time step. */ + if (t != t_saved) { /* first pass: the model is at t_prev */ + CableDyn_SaveState(h, &err); + t_saved = t; + } else { /* a later pass of the same step */ + CableDyn_RestoreState(h, &err); + } + /* the fairlead motion at t (the END of the step) into the host blocks, in layout order */ + for (j = 0, k = 0; k < n / 3; ++k) { + if (types[k] != CD_C_POINT_COUPLED) continue; + for (c = 0; c < 3; ++c) { + q[3 * k + c] = x_fair[3 * j + c]; + v[3 * k + c] = v_fair[3 * j + c]; + a[3 * k + c] = a_fair[3 * j + c]; + } + ++j; + } + CableDyn_Step(h, dt, q, v, a, n, &converged, &stalled, &n_iter, &err); + CableDyn_CalcOutput(h, f, n, &err); + /* F = sum of f over the host blocks; M = sum of (x - r) x f over the same blocks */ + + /* End of the run. */ + CableDyn_Close(&h, &err); + +Check ``err`` after every call. On the aggregate route, replace the single ``CableDyn_Step`` +by the sub-steps of Step 6. + Function reference ------------------ @@ -620,8 +846,9 @@ but the C ABI writes no output files. rods, with their lines) runs on the same coupled aggregate as the OpenFAST module, with these differences from the point-system decks: -* the coupled DOFs are the ``x, y, z`` of the deck's ``Coupled``/``Vessel`` points only, in deck - order (anchors are not part of the vector); the bodies and rods are integrated internally; +* the coupled DOFs are the ``x, y, z`` of the deck's ``Coupled``/``Vessel`` points only, in + 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 @@ -1393,6 +1620,7 @@ them all zero. Copies the current coupled motion. Right after ``CableDyn_InitDeck`` this is the static solution: the deck coordinates of every attached point, with zero velocity and acceleration. +After ``CableDyn_InitDeckAt`` the host-driven blocks hold their entries of ``q0`` instead. Use it to seed the host's coupled vectors before the first step. The buffers are set to zero before the copy and stay zero if the call fails. The model is not changed. @@ -1546,6 +1774,140 @@ capacity of a larger buffer, as for the other string arguments. ``token_len`` mu and a token longer than 64 characters (the longest channel name) is rejected with ``CD_C_BAD_INPUT``. +Host coupling calls +~~~~~~~~~~~~~~~~~~~ + +ABI 1 minor extension 2: check ``CableDyn_GetAbiMinor() >= 2`` before calling these. +`Coupling a host (CFD) solver`_ shows how they fit together. + +.. code-block:: c + + #define CD_C_POINT_FIXED 1 + #define CD_C_POINT_COUPLED 2 /* Coupled or Vessel */ + #define CD_C_POINT_FREE 3 + #define CD_C_POINT_CONNECT 4 + + void CableDyn_InitDeckAt(void *handle, const char *deck_path, int deck_path_len, + const double *q0, int n_q0, int *err_stat); + void CableDyn_SaveState(void *handle, int *err_stat); + void CableDyn_RestoreState(void *handle, int *err_stat); + void CableDyn_GetCoupledLayout(void *handle, int *point_id, int *point_type, + int n_block, int *err_stat); + +The ``CD_C_POINT_*`` codes are also the point ``subtype`` of ``CableDyn_GetObjectInfo``. + +**CableDyn_InitDeckAt.** ``CableDyn_InitDeck`` with the static solve at the host's positions of +the coupled points. ``handle``, ``deck_path`` and ``deck_path_len`` are as for +``CableDyn_InitDeck``, and the call takes the same routes, rejects the same decks, and is +serialised and transactional in the same way. + +.. list-table:: + :header-rows: 1 + :widths: 18 8 12 12 12 38 + + * - Argument + - Dir + - C type + - Length + - NULL + - Meaning + * - ``q0`` + - in + - ``const double *`` + - ``n_q0`` + - only if ``n_q0 == 0`` + - host positions [m], interleaved ``x, y, z``: either the ``Coupled``/``Vessel`` blocks + alone, in coupled-vector order, or the full coupled vector (whose ``Fixed``, ``Free`` and + ``Connect`` blocks are not read) + * - ``n_q0`` + - in + - ``int`` + - -- + - -- + - 3 times the number of line-bound ``Coupled``/``Vessel`` points, or + ``CableDyn_NCoupledDOF`` of the new model; 0 for a deck without line-bound + ``Coupled``/``Vessel`` points + +Every line-bound ``Coupled``/``Vessel`` point is placed at its entry of ``q0`` before the static +solve, and the lines, ``Free``/``Connect`` points, bodies and rods are solved in equilibrium with +those points held there. The result equals ``CableDyn_InitDeck`` of the deck with those points +moved to ``q0``. The statics start at rest: every coupled velocity and acceleration is zero, +and ``CableDyn_GetCoupledMotion`` returns ``q0`` in the host-driven blocks. A +``Coupled``/``Vessel`` point referenced by no line has no block and keeps its deck coordinates. +On the aggregate route the two forms of ``q0`` coincide; a point that has two blocks there (a +fairlead shared by an ``EI = 0`` and a finite-EI line) needs the same position in both. + +An ``n_q0`` that is negative, not a multiple of 3, or fits neither form, a ``NULL`` or +non-finite ``q0``, a line's End A moved below its ``Fixed`` End B anchor (on a deck without +``Free`` or ``Connect`` points), and the deck rejections of ``CableDyn_InitDeck`` return +``CD_C_BAD_INPUT``; the diagnostics of a ``q0`` that does not fit the deck call it +``coupled_positions``. A static-solve failure returns ``CD_C_SOLVE_FAIL``. + +**CableDyn_SaveState, CableDyn_RestoreState.** One save slot per handle, for a host's outer +correctors. + +.. list-table:: + :header-rows: 1 + :widths: 26 74 + + * - Function + - Effect + * - ``CableDyn_SaveState`` + - copies the whole model into the slot, replacing any earlier save: every line, point, + body and rod state with its solver history (viscoelastic, Syrope and seabed-friction + states), the point fluid fields of ``CableDyn_UpdatePointFluidFields``, and the + aggregate route's step time + * - ``CableDyn_RestoreState`` + - returns the model to the slot and keeps the slot, so one save serves any number of + restores + +A restore followed by a step is bit-identical to taking that step from the saved state +directly, whatever ran between the save and the restore: the slot is a copy of the model +object, independent of the rollback buffers the steps use internally. A successful ``Init*`` +call discards the slot; a failed one keeps it with the model. Both calls return +``CD_C_NOT_INITIALIZED`` before an initialisation, and ``RestoreState`` returns +``CD_C_BAD_INPUT`` when nothing has been saved since the model was initialised. Each call copies +the model, so it allocates memory of the size of the model and costs about as much as copying +it; it does no file I/O and follows the threading rules of the other per-handle calls. There is +no serialisation of the state to a caller buffer. + +**CableDyn_GetCoupledLayout.** The owner of each 3-DOF block of the coupled vector. + +.. list-table:: + :header-rows: 1 + :widths: 18 8 12 12 12 38 + + * - Argument + - Dir + - C type + - Length + - NULL + - Meaning + * - ``point_id`` + - out + - ``int *`` + - ``n_block`` + - yes: skipped + - deck point id of block ``k`` (DOFs ``3k`` to ``3k+2``, 0-based) + * - ``point_type`` + - out + - ``int *`` + - ``n_block`` + - yes: skipped + - ``CD_C_POINT_FIXED``, ``_COUPLED``, ``_FREE`` or ``_CONNECT`` + * - ``n_block`` + - in + - ``int`` + - -- + - -- + - must equal ``CableDyn_NCoupledDOF / 3`` + +The host drives the ``CD_C_POINT_COUPLED`` blocks. On the point route the blocks are the +line-bound points of every type in ``POINTS`` order; on the aggregate route they are the +``Coupled``/``Vessel`` points only (`Coupled DOF layout`_). A handle initialised from raw arrays +has no deck points, and the call returns ``CD_C_BAD_INPUT``: its coupled vector is the caller's +own ``fixed_dofs`` list. A wrong ``n_block`` returns ``CD_C_BAD_INPUT``. + Examples -------- diff --git a/doc/coupling_boundary.md b/doc/coupling_boundary.md index 2132e632..9d2af723 100644 --- a/doc/coupling_boundary.md +++ b/doc/coupling_boundary.md @@ -75,7 +75,9 @@ on `t + dt` and the host time grid is unchanged. In OpenFAST the module may adva The public header declares the complete interface of C ABI version 1, including the object queries of its minor extension 1 (ABI 1.1; check `CableDyn_GetAbiMinor() >= 1` before calling -them). Signatures and examples are in the [C API guide](capi.rst). +them) and the host-coupling calls of its minor extension 2 (ABI 1.2; check +`CableDyn_GetAbiMinor() >= 2`). Signatures and examples are in the [C API guide](capi.rst), +whose section "Coupling a host (CFD) solver" gives the call sequence of a CFD host. | Group | Functions | | --- | --- | @@ -86,6 +88,7 @@ them). Signatures and examples are in the [C API guide](capi.rst). | Output | `CableDyn_CalcOutput`, `CableDyn_CalcOutputDerivatives`, `CableDyn_GetCoupledMotion` | | Queries | `CableDyn_NCoupledDOF`, `CableDyn_NPoints`, `CableDyn_NLines`, `CableDyn_GetLastError` | | Object queries (ABI 1.1) | `CableDyn_GetAbiMinor`, `CableDyn_NObjects`, `CableDyn_GetObjectInfo`, `CableDyn_GetLineValues`, `CableDyn_GetPointState`, `CableDyn_GetBodyState`, `CableDyn_GetRodState`, `CableDyn_EvalChannel`: the model's lines, points, bodies and rods, their committed state, and any `OUTPUTS` channel | +| Host coupling (ABI 1.2) | `CableDyn_InitDeckAt` (`CableDyn_InitDeck` with the statics solved at the host's positions of the `Coupled` points), `CableDyn_SaveState`, `CableDyn_RestoreState` (a one-slot in-memory save of the whole model for outer correctors), `CableDyn_GetCoupledLayout` (the deck point id and type of every block of the coupled vector) | Rules shared by every entry point: diff --git a/doc/python.rst b/doc/python.rst index 403d56cc..42e0342d 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -772,6 +772,23 @@ motion are rejected in-process (they run in the standalone driver): time-varying kinematics enter through :meth:`~cabledyn.CableDyn.update_point_fluid_fields`, and motion through the coupled kinematics of every step. +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 (:ref:`capi-host-coupling` +explains each call and how it differs from MoorDyn): + +.. code-block:: python + + with CableDyn() as model: + model.init_deck_at("mooring.dat", fairleads) # (3, n): the Coupled points, layout order + q, v, a = model.get_coupled_motion() + host = model.host_dofs() # the "coupled" blocks of model.coupled_layout() + model.save_state() # at the first pass of a host time step + for corrector in range(3): + model.restore_state() # every pass restarts from the saved state + q[host], v[host], a[host] = x_end, v_end, a_end # flat host motion at t + dt + model.step(dt, q, v, a) + loads = model.calc_output()[host].reshape(3, -1, order="F") + Objects and output channels ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/python/cabledyn/_lib.py b/python/cabledyn/_lib.py index 72a159b8..5495a4b8 100644 --- a/python/cabledyn/_lib.py +++ b/python/cabledyn/_lib.py @@ -175,6 +175,41 @@ def _bind_object_queries() -> bool: _has_object_queries = _bind_object_queries() +# --- ABI 1, minor extension 2: host coupling --------------------------------- +# Initialization at the host's coupled positions, the one-slot state save and +# restore of outer correctors, and the coupled layout query. A library built +# before the extension lacks these symbols and reports ``abi_minor() < 2``. + +#: Minor extension level of ABI 1 this binding uses for the host-coupling calls +#: (the newest extension the binding knows). +HOST_COUPLING_ABI_MINOR = 2 + + +def _bind_host_coupling() -> bool: + try: + init_at = _lib.CableDyn_InitDeckAt + except AttributeError: + return False + init_at.argtypes = [c_void_p, c_char_p, c_int, _DBL, c_int, POINTER(c_int)] + init_at.restype = None + _lib.CableDyn_SaveState.argtypes = [c_void_p, POINTER(c_int)] + _lib.CableDyn_SaveState.restype = None + _lib.CableDyn_RestoreState.argtypes = [c_void_p, POINTER(c_int)] + _lib.CableDyn_RestoreState.restype = None + _lib.CableDyn_GetCoupledLayout.argtypes = [ + c_void_p, + POINTER(c_int), + POINTER(c_int), + c_int, + POINTER(c_int), + ] + _lib.CableDyn_GetCoupledLayout.restype = None + return True + + +_has_host_coupling = _bind_host_coupling() + + def abi_minor() -> int: """The loaded library's ABI 1 extension level (0 before the object queries).""" if not _has_object_queries: diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index b9a1ee1b..24556785 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -21,7 +21,16 @@ from cabledyn import _lib as _lib_module from cabledyn._lib import _lib from cabledyn.errors import CableDynError, ConvergenceError -from cabledyn.objects import Body, Line, Point, Rod, build_views, eval_channel +from cabledyn.objects import ( + _POINT_KINDS, + Body, + Line, + Point, + PointKind, + Rod, + build_views, + eval_channel, +) __all__ = ["Body", "CableDyn", "CableDynError", "ConvergenceError", "Line", "Point", "Rod"] @@ -138,6 +147,8 @@ def __init__(self, deck: str | os.PathLike[str] | None = None) -> None: self._views = ((), (), (), ()) self._views_valid = False self._time = 0.0 + # the time of the state in the save slot (None: nothing saved since the initialization) + self._saved_time: float | None = None self._deck: Path | None = None status = c_int() _lib.CableDyn_Create(byref(self._handle), byref(status)) @@ -206,10 +217,59 @@ def init_deck(self, deck: str | os.PathLike[str]) -> None: status = c_int() _lib.CableDyn_InitDeck(self._handle, path, len(path), byref(status)) self._check("CableDyn_InitDeck", status.value) - self._generation += 1 - self._views_valid = False - self._time = 0.0 - self._deck = resolved + self._initialized_from(resolved) + + def init_deck_at(self, deck: str | os.PathLike[str], q0: ArrayInput) -> None: + """Initialize from a deck with the statics solved at the host's coupled positions. + + Every line-bound Coupled/Vessel point starts at its entry of ``q0`` instead + of its deck coordinates, and the static equilibrium (lines, Free/Connect + points, bodies, rods) is solved with those points held there, at rest; a + host whose body starts away from the deck coordinates then starts without + a transient. ``q0`` is either the full coupled vector of the deck + (``n_coupled_dof`` values, the layout of :meth:`step`; the Fixed, Free and + Connect blocks are not read) or the Coupled/Vessel blocks alone, in + coupled-vector order (the ``MoorDyn_Init`` layout of a points-only deck), + flat or column-per-point ``(3, n)``. See :meth:`coupled_layout`. A failed + initialization keeps any previously initialized model. + """ + _encode_path(deck) # rejects a NUL before any file-system call + resolved = Path(deck).expanduser().resolve() + path = _encode_path(resolved) + q = _as_real_array(q0, "q0") + if q.ndim == 2 and q.shape[0] == 3: + q = np.ascontiguousarray(q.reshape(-1, order="F")) + if q.ndim != 1 or q.size % 3 != 0: + raise ValueError( + f"q0 must be flat (3 * n,) or column-per-point (3, n); got shape {np.shape(q0)}" + ) + if not np.all(np.isfinite(q)): + raise ValueError("q0 must be finite (no NaN or Inf)") + with self._lock: + self._require_host_coupling() + status = c_int() + _lib.CableDyn_InitDeckAt( + self._handle, path, len(path), _dbl_ptr(q), int(q.size), byref(status) + ) + self._check("CableDyn_InitDeckAt", status.value) + self._initialized_from(resolved) + + def _initialized_from(self, deck: Path) -> None: + """Book-keeping after a successful deck initialization (the caller holds the lock).""" + self._generation += 1 + self._views_valid = False + self._time = 0.0 + self._saved_time = None + self._deck = deck + + @staticmethod + def _require_host_coupling() -> None: + if _lib_module.abi_minor() < _lib_module.HOST_COUPLING_ABI_MINOR: + # not a C status: the loaded library lacks the entry points + raise RuntimeError( + "the loaded CableDyn library predates the host-coupling calls " + "(ABI 1 minor extension 2); rebuild it from this checkout" + ) @property def initialized(self) -> bool: @@ -249,7 +309,10 @@ def deck(self) -> Path | None: @property def time(self) -> float: - """Simulation time [s]: 0 after initialization, advanced by every completed step.""" + """Simulation time [s]: 0 after initialization, advanced by every completed step. + + :meth:`restore_state` sets it back to the time of the saved state. + """ with self._lock: return self._time @@ -428,6 +491,77 @@ def calc_output(self) -> FloatArray: self._check("CableDyn_CalcOutput", status.value) return loads + # -- host coupling: outer correctors and the coupled layout ------------------- + + def save_state(self) -> None: + """Save the whole model and :attr:`time` into the handle's single save slot. + + The slot is a deep copy of the model (every line, point, body and rod + state with its solver history), replacing any earlier save. It stays valid + until the next initialization, so one save serves every outer corrector of + a host time step (see :meth:`restore_state`). + """ + with self._lock: + self._require_host_coupling() + status = c_int() + _lib.CableDyn_SaveState(self._handle, byref(status)) + self._check("CableDyn_SaveState", status.value) + self._saved_time = self._time + + def restore_state(self) -> None: + """Return the model and :attr:`time` to the last :meth:`save_state`. + + The save is kept, so the call can be repeated. A restore followed by a + step is bit-identical to taking that step from the saved state directly. + Raises :class:`CableDynError` when nothing was saved since the model was + initialized. + """ + with self._lock: + self._require_host_coupling() + status = c_int() + _lib.CableDyn_RestoreState(self._handle, byref(status)) + self._check("CableDyn_RestoreState", status.value) + if self._saved_time is not None: + self._time = self._saved_time + + def coupled_layout(self) -> tuple[tuple[int, PointKind], ...]: + """The owner of each 3-DOF block of the coupled vector, as ``(point_id, kind)``. + + Block ``k`` holds DOFs ``3k .. 3k+2`` of the vectors :meth:`step`, + :meth:`get_coupled_motion` and :meth:`calc_output` use; ``kind`` is + ``"fixed"``, ``"coupled"`` (Coupled or Vessel), ``"free"`` or + ``"connect"``. On a point-system deck every line-bound point has a block, + in deck POINTS order; on the coupled aggregate (finite-EI lines, bodies or + rods) only the Coupled points do. The host drives the ``"coupled"`` + blocks (:meth:`host_dofs`). + """ + with self._lock: + self._require_host_coupling() + nb = self.n_coupled_dof // 3 + ids = np.zeros(max(nb, 1), dtype=np.intc) + kinds = np.zeros(max(nb, 1), dtype=np.intc) + status = c_int() + _lib.CableDyn_GetCoupledLayout( + self._handle, + ids.ctypes.data_as(POINTER(c_int)), + kinds.ctypes.data_as(POINTER(c_int)), + nb, + byref(status), + ) + self._check("CableDyn_GetCoupledLayout", status.value) + return tuple((int(ids[k]), _POINT_KINDS.get(int(kinds[k]), "fixed")) for k in range(nb)) + + def host_dofs(self) -> npt.NDArray[np.intp]: + """Indices of the coupled DOFs the host drives (the ``"coupled"`` blocks). + + With ``x`` the ``(3, n)`` host positions of those points in layout order, + ``q[model.host_dofs()] = x.reshape(-1, order="F")`` fills them in a full + coupled vector ``q`` taken from :meth:`get_coupled_motion`. + """ + layout = self.coupled_layout() + 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 update_point_fluid_fields( self, fluid_velocity: ArrayInput, diff --git a/python/tests/test_host_coupling.py b/python/tests/test_host_coupling.py new file mode 100644 index 00000000..5fadf22e --- /dev/null +++ b/python/tests/test_host_coupling.py @@ -0,0 +1,160 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host coupling (C ABI 1 minor extension 2): init at host positions, save/restore, layout. + +The point-route deck is the foamMooring EsfLOWC box (four slack EI=0 lines), whose +fairleads sit at z = -0.062 m in the deck while the CFD box starts with them at +z = -0.077 m. The aggregate-route deck is an EI=0 chain plus a finite-EI cable. +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest + +try: + import cabledyn._lib # loads the shared library +except (ImportError, OSError) as exc: # a missing library raises OSError + pytest.skip(f"CableDyn shared library not available: {exc}", allow_module_level=True) + +import cabledyn +from cabledyn import _lib +from cabledyn.errors import CableDynError +from cabledyn.model import CableDyn + +DATA = Path(__file__).resolve().parents[2] / "tests" / "data" +BOX = DATA / "foam_esflowc_box_points.dat" +MIXED = DATA / "host_coupling_chain_cable.dat" + +#: The box fairleads (points 5-8) at the CFD start height, column per point. +BOX_FAIRLEADS = np.array( + [[-0.1, 0.1, -0.077], [-0.1, -0.1, -0.077], [0.1, 0.1, -0.077], [0.1, -0.1, -0.077]] +).T + + +def _motion(model: CableDyn, q0: np.ndarray, amp: float, t: float): + """A smooth surge/heave of the host-driven blocks about q0 at time t.""" + w = 2.0 * np.pi + q, v, a = q0.copy(), np.zeros_like(q0), np.zeros_like(q0) + dofs = model.host_dofs().reshape(-1, 3) + q[dofs[:, 0]] += amp * np.sin(w * t) + v[dofs[:, 0]] = amp * w * np.cos(w * t) + a[dofs[:, 0]] = -amp * w * w * np.sin(w * t) + q[dofs[:, 2]] += 0.5 * amp * (1.0 - np.cos(w * t)) + v[dofs[:, 2]] = 0.5 * amp * w * np.sin(w * t) + a[dofs[:, 2]] = 0.5 * amp * w * w * np.cos(w * t) + return q, v, a + + +def test_abi_minor_reports_the_host_coupling_extension(): + assert _lib.HOST_COUPLING_ABI_MINOR == 2 + assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_COUPLING_ABI_MINOR + + +def test_point_route_layout(): + with CableDyn(BOX) as model: + layout = model.coupled_layout() + assert layout == tuple((p, "fixed") for p in (1, 2, 3, 4)) + tuple( + (p, "coupled") for p in (5, 6, 7, 8) + ) + assert model.host_dofs().tolist() == list(range(12, 24)) + + +def test_init_deck_at_host_positions_has_no_transient(): + with CableDyn() as model: + model.init_deck_at(BOX, BOX_FAIRLEADS) + assert model.n_coupled_dof == 24 + q, v, a = model.get_coupled_motion() + assert np.array_equal(q[model.host_dofs()], BOX_FAIRLEADS.reshape(-1, order="F")) + assert not v.any() and not a.any() + f0 = model.calc_output() + # line 4's fairlead: the standalone statics of the deck moved to z = -0.077 + np.testing.assert_allclose(f0[21:24], [0.3026, -0.0761, -0.4114], atol=1.0e-4) + for _ in range(200): + model.step(1.0e-3, q, v, a) + assert np.max(np.abs(model.calc_output() - f0)) < 1.0e-9 + assert model.time == pytest.approx(0.2) + + # the same statics from the full coupled vector (the Fixed blocks are not read) + full = q.copy() + full[:12] = 1.0e3 + with CableDyn() as other: + other.init_deck_at(BOX, full) + assert np.array_equal(other.calc_output(), f0) + + # InitDeck at the deck positions rings when the host holds the fairleads lower + with CableDyn(BOX) as plain: + peak = 0.0 + for _ in range(200): + plain.step(1.0e-3, q, v, a) + peak = max(peak, float(np.max(np.abs(plain.calc_output() - f0)))) + assert peak > 1.0e-2 + + +def test_init_deck_at_rejections_keep_the_model(): + with CableDyn(BOX) as model: + before = model.calc_output() + with pytest.raises(CableDynError, match="coupled_positions"): + model.init_deck_at(BOX, BOX_FAIRLEADS[:, :3]) + with pytest.raises(ValueError, match="finite"): + model.init_deck_at(BOX, np.full(12, np.nan)) + with pytest.raises(ValueError, match="3 \\* n"): + model.init_deck_at(BOX, np.zeros(13)) + assert np.array_equal(model.calc_output(), before) + + +@pytest.mark.parametrize( + ("deck", "q_host", "dt", "amp"), + [(BOX, BOX_FAIRLEADS, 1.0e-3, 0.005), (MIXED, None, 0.01, 0.2)], + ids=["point-route", "aggregate-route"], +) +def test_save_restore_is_bit_identical(deck, q_host, dt, amp): + with CableDyn(deck) as model, CableDyn(deck) as ref: + if q_host is not None: + model.init_deck_at(deck, q_host) + ref.init_deck_at(deck, q_host) + q0, _, _ = model.get_coupled_motion() + with pytest.raises(CableDynError, match="no state has been saved"): + model.restore_state() + model.save_state() + for corrector in (1, 2): # two outer correctors that try other motions + for s in range(1, 6): + model.step(dt, *_motion(model, q0, 2.0 * corrector * amp, s * dt)) + model.restore_state() + assert model.time == 0.0 + for s in range(1, 8): + motion = _motion(model, q0, amp, s * dt) + model.step(dt, *motion) + ref.step(dt, *motion) + assert np.array_equal(model.calc_output(), ref.calc_output()) + for x, y in zip(model.get_coupled_motion(), ref.get_coupled_motion(), strict=True): + assert np.array_equal(x, y) + for line, line_ref in zip(model.lines, ref.lines, strict=True): + assert np.array_equal(line.node_positions(), line_ref.node_positions()) + assert model.time == pytest.approx(ref.time) + # a new initialization discards the save + model.init_deck(deck) + with pytest.raises(CableDynError, match="no state has been saved"): + model.restore_state() + + +def test_aggregate_layout_holds_only_the_coupled_points(): + with CableDyn(MIXED) as model: + assert model.coupled_layout() == ((2, "coupled"), (4, "coupled")) + assert model.host_dofs().tolist() == list(range(6)) + + +def test_an_uninitialized_handle_has_nothing_to_save(): + with CableDyn() as model: + with pytest.raises(CableDynError, match="NOT_INITIALIZED"): + model.save_state() + + +def test_an_old_library_fails_clearly(monkeypatch): + monkeypatch.setattr(_lib, "abi_minor", lambda: 1) + with CableDyn(BOX) as model: + with pytest.raises(RuntimeError, match="predates the host-coupling calls"): + model.save_state() + with pytest.raises(RuntimeError, match="predates the host-coupling calls"): + model.init_deck_at(BOX, BOX_FAIRLEADS) diff --git a/python/tests/test_objects.py b/python/tests/test_objects.py index acb791b0..1eadb457 100644 --- a/python/tests/test_objects.py +++ b/python/tests/test_objects.py @@ -431,7 +431,8 @@ def test_unbound_handle_and_raw_lines(monkeypatch, tmp_path): def test_abi_minor_is_reported(): - assert _lib.abi_minor() == _lib.OBJECT_QUERY_ABI_MINOR == cabledyn.abi_minor() == 1 + assert _lib.OBJECT_QUERY_ABI_MINOR == 1 + assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_COUPLING_ABI_MINOR == 2 assert objects_module.OBJ_ROD == 4 diff --git a/release/check_release_metadata.py b/release/check_release_metadata.py index 208ebfe0..919255ce 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -139,7 +139,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"OBJECT_QUERY_ABI_MINOR = {abi_minor}" in read( + "Python ABI minor level": f"HOST_COUPLING_ABI_MINOR = {abi_minor}" in read( "python/cabledyn/_lib.py" ), "C header ABI version": f"CABLEDYN_CAPI_ABI_VERSION {abi_version}" in read( diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 2bdec470..ceb68053 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -32,7 +32,8 @@ MODULE CableDyn_CAPI CD_FAST_NOT_INITIALIZED, CD_FAST_ALLOCFAIL, CD_FAST_UpdatePointFluidFields USE CableDyn_OpenFAST_HermiteFMF, ONLY: CD_HFMF_ModuleType USE CableDyn_Precision, ONLY: wp, CD_ZERO - USE CableDyn_System, ONLY: CD_SystemType, CD_System_Line_NDOF + USE CableDyn_System, ONLY: CD_SystemType, CD_System_Line_NDOF, CD_Get_System_PointBlocks, CD_SYSTEM_OK, & + CD_POINT_COUPLED IMPLICIT NONE PRIVATE @@ -62,6 +63,10 @@ MODULE CableDyn_CAPI PUBLIC :: CableDyn_GetBodyState PUBLIC :: CableDyn_GetRodState PUBLIC :: CableDyn_EvalChannel + PUBLIC :: CableDyn_InitDeckAt + PUBLIC :: CableDyn_SaveState + PUBLIC :: CableDyn_RestoreState + PUBLIC :: CableDyn_GetCoupledLayout INTEGER(C_INT), PARAMETER :: CD_C_OK = 0_C_INT INTEGER(C_INT), PARAMETER :: CD_C_BAD_HANDLE = 1_C_INT @@ -74,8 +79,9 @@ MODULE CableDyn_CAPI INTEGER(C_INT), PARAMETER :: CD_C_VERSION_PATCH = 1_C_INT INTEGER(C_INT), PARAMETER :: CD_C_ABI_VERSION = 1_C_INT CHARACTER(*), PARAMETER :: CD_C_VERSION_STRING = 'CableDyn 0.1.1 C-ABI 1' - !> Minor extension level of ABI 1: 1 adds the in-process object queries. - INTEGER(C_INT), PARAMETER :: CD_C_ABI_MINOR = 1_C_INT + !> 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). + INTEGER(C_INT), PARAMETER :: CD_C_ABI_MINOR = 2_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 @@ -156,6 +162,13 @@ END FUNCTION cabledyn_blas_threads_once LOGICAL, ALLOCATABLE :: pt_is_cable(:) INTEGER, ALLOCATABLE :: pt_obj(:) TYPE(CD_HFMF_ModuleType), ALLOCATABLE :: no_cables(:) + ! The single save slot of CableDyn_SaveState/RestoreState: a deep copy of the route's model + ! object (the point system, or the aggregate on the heap) and the aggregate's committed time, + ! valid (has_saved) from a SaveState until the next successful initialization. + LOGICAL :: has_saved = .FALSE. + TYPE(CD_FAST_ModuleType) :: saved_fast + TYPE(CD_AGG_ModuleType), ALLOCATABLE :: saved_agg + REAL(wp) :: saved_agg_t = CD_ZERO CHARACTER(CD_C_MSG_LEN) :: last_error = '' END TYPE CD_C_Handle @@ -225,15 +238,66 @@ SUBROUTINE CableDyn_InitDeck(handle, deck_path_ptr, deck_path_len, err_stat) BIN IF (.NOT. blas_runtime_ready(handle, 'CableDyn_InitDeck', err_stat)) RETURN CALL cabledyn_input_lock() - CALL init_deck_serialised(handle, deck_path_ptr, deck_path_len, err_stat) + CALL init_deck_serialised(handle, deck_path_ptr, deck_path_len, 'CableDyn_InitDeck', err_stat) CALL cabledyn_input_unlock() END SUBROUTINE CableDyn_InitDeck - SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, err_stat) - !! CableDyn_InitDeck body; the caller holds the process-wide input lock. + SUBROUTINE CableDyn_InitDeckAt(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q0, err_stat) & + BIND(C, NAME='CableDyn_InitDeckAt') + !! CableDyn_InitDeck with the static solve at the host's positions of the coupled points: + !! every line-bound Coupled/Vessel point starts at its entry of q0 instead of its deck + !! coordinates, and the statics (lines, Free/Connect points, bodies and rods) are solved + !! with those points held there, at rest. q0 is either the full coupled vector of the + !! deck's route (n_q0 = CableDyn_NCoupledDOF after the call; the Fixed, Free and Connect + !! blocks are not read) or the Coupled/Vessel blocks alone, in coupled-vector order. A + !! deck without line-bound Coupled/Vessel points takes n_q0 = 0 (q0 may then be null). + !! Serialised process-wide and transactional like CableDyn_InitDeck. + TYPE(C_PTR), VALUE :: handle, deck_path_ptr, q0_ptr + INTEGER(C_INT), VALUE :: deck_path_len, n_q0 + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + REAL(C_DOUBLE), POINTER :: q0_c(:) + REAL(wp), ALLOCATABLE :: positions(:, :) + INTEGER :: stat + + IF (.NOT. blas_runtime_ready(handle, 'CableDyn_InitDeckAt', err_stat)) RETURN + err_stat = validate_handle(handle, h) + IF (err_stat /= CD_C_OK) RETURN + IF (n_q0 < 0_C_INT .OR. MOD(n_q0, 3_C_INT) /= 0_C_INT) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeckAt: n_q0 must be a non-negative multiple of 3', & + err_stat) + RETURN + END IF + IF (n_q0 > 0_C_INT .AND. .NOT. C_ASSOCIATED(q0_ptr)) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeckAt: q0 pointer is null', err_stat) + RETURN + END IF + ALLOCATE (positions(3, INT(n_q0)/3), STAT=stat) + IF (stat /= 0) THEN + CALL set_status(h, CD_C_ALLOC_FAIL, 'CableDyn_InitDeckAt: q0 allocation failed', err_stat) + RETURN + END IF + IF (n_q0 > 0_C_INT) THEN + CALL C_F_POINTER(q0_ptr, q0_c, [INT(n_q0)]) + IF (.NOT. ALL(IEEE_IS_FINITE(q0_c))) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeckAt: q0 must be finite', err_stat) + RETURN + END IF + positions = RESHAPE(REAL(q0_c, wp), SHAPE(positions)) + END IF + CALL cabledyn_input_lock() + CALL init_deck_serialised(handle, deck_path_ptr, deck_path_len, 'CableDyn_InitDeckAt', err_stat, positions) + CALL cabledyn_input_unlock() + END SUBROUTINE CableDyn_InitDeckAt + + SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, err_stat, positions) + !! CableDyn_InitDeck / CableDyn_InitDeckAt body; the caller holds the process-wide input + !! lock. positions (3, n): the host positions of CableDyn_InitDeckAt. TYPE(C_PTR), VALUE :: handle, deck_path_ptr INTEGER(C_INT), VALUE :: deck_path_len + CHARACTER(*), INTENT(IN) :: caller INTEGER(C_INT), INTENT(OUT) :: err_stat + REAL(wp), INTENT(IN), OPTIONAL :: positions(:, :) TYPE(CD_C_Handle), POINTER :: h TYPE(CD_FAST_ModuleType) :: new_fast @@ -248,20 +312,19 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, err_stat) err_stat = validate_handle(handle, h) IF (err_stat /= CD_C_OK) RETURN IF (deck_path_len < 1_C_INT .OR. .NOT. C_ASSOCIATED(deck_path_ptr)) THEN - CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeck: deck path pointer is null or length is non-positive', & - err_stat) + CALL set_status(h, CD_C_BAD_INPUT, caller//': deck path pointer is null or length is non-positive', err_stat) RETURN END IF CALL C_F_POINTER(deck_path_ptr, path_c, [INT(deck_path_len)]) ALLOCATE (CHARACTER(LEN=INT(deck_path_len)) :: deck_path, STAT=stat) IF (stat /= 0) THEN - CALL set_status(h, CD_C_ALLOC_FAIL, 'CableDyn_InitDeck: deck path allocation failed', err_stat) + CALL set_status(h, CD_C_ALLOC_FAIL, caller//': deck path allocation failed', err_stat) RETURN END IF DO i = 1, INT(deck_path_len) IF (path_c(i) == C_NULL_CHAR) THEN IF (i == 1) THEN - CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeck: deck path is empty', err_stat) + CALL set_status(h, CD_C_BAD_INPUT, caller//': deck path is empty', err_stat) RETURN END IF deck_path = deck_path(:i - 1) @@ -275,55 +338,124 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, err_stat) 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 - CALL init_deck_aggregate(h, TRIM(deck_path), has_dtm, dtm, err_stat) + CALL init_deck_aggregate(h, TRIM(deck_path), has_dtm, dtm, caller, err_stat, positions) RETURN END IF - CALL CD_Init_Deck_System(TRIM(deck_path), new_fast%system, dtm, gravity, rho_water, es, em, line_ids=line_ids) + ! 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) IF (es /= CD_DECKDRV_OK) THEN CALL map_deck_status(es, err_stat) - CALL store_status(h, err_stat, 'CableDyn_InitDeck: '//TRIM(em)) + CALL store_status(h, err_stat, caller//': '//TRIM(em)) CALL CD_FAST_End(new_fast, end_es, end_em) RETURN END IF + IF (PRESENT(positions)) THEN + CALL check_point_start(new_fast, positions, em) + IF (LEN_TRIM(em) > 0) THEN + CALL set_status(h, CD_C_BAD_INPUT, caller//': '//TRIM(em), err_stat) + CALL CD_FAST_End(new_fast, end_es, end_em) + RETURN + END IF + END IF CALL CD_FAST_End(h%fast, end_es, end_em) h%fast = new_fast CALL CD_FAST_End(new_fast, end_es, end_em) CALL drop_aggregate(h) + CALL drop_saved_state(h) CALL set_point_line_map(h, line_ids) CALL store_status(h, CD_C_OK, '') err_stat = CD_C_OK END SUBROUTINE init_deck_serialised - SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, err_stat) + SUBROUTINE check_point_start(fast, positions, msg) + !! Post-condition of CableDyn_InitDeckAt on the point route: every Coupled block of the new + !! system starts at its host position (msg is blank when it does). positions holds either + !! one column per coupled block or one per Coupled block (apply_point_system_positions). + TYPE(CD_FAST_ModuleType), INTENT(IN) :: fast + REAL(wp), INTENT(IN) :: positions(:, :) + CHARACTER(*), INTENT(OUT) :: msg + INTEGER, ALLOCATABLE :: blocks(:) + REAL(wp), ALLOCATABLE :: q(:), v(:), a(:) + INTEGER :: k, col, n, es, stat + LOGICAL :: full + CHARACTER(CD_C_MSG_LEN) :: em + + msg = '' + n = CD_FAST_NCoupledDOF(fast, es, em) + IF (es /= CD_FAST_OK) THEN + msg = 'the coupled vector of the new model is unavailable: '//TRIM(em) + RETURN + END IF + CALL CD_Get_System_PointBlocks(fast%system, blocks, es, em) + IF (es /= CD_SYSTEM_OK .OR. .NOT. ALLOCATED(blocks)) THEN + msg = 'the coupled layout of the new model is unavailable' + RETURN + END IF + ALLOCATE (q(n), v(n), a(n), STAT=stat) + IF (stat /= 0) THEN + msg = 'workspace allocation failed' + RETURN + END IF + CALL CD_FAST_GetCoupledMotion(fast, q, v, a, es, em) + IF (es /= CD_FAST_OK) THEN + msg = 'the coupled motion of the new model is unavailable: '//TRIM(em) + RETURN + END IF + full = SIZE(positions, 2) == SIZE(blocks) + col = 0 + DO k = 1, SIZE(blocks) + IF (full) col = col + 1 + IF (fast%system%points(blocks(k))%point_type /= CD_POINT_COUPLED) CYCLE + IF (.NOT. full) col = col + 1 + IF (.NOT. same_position(q(3*k - 2:3*k), positions(:, col))) THEN + msg = 'coupled point '//TRIM(int_text(fast%system%points(blocks(k))%id))//' did not start at its '// & + 'position in q0' + RETURN + END IF + END DO + END SUBROUTINE check_point_start + + PURE LOGICAL FUNCTION same_position(x, y) RESULT(same) + !! Two coupled-point positions agree to 1e-9 relative (1e-9 m below 1 m). + REAL(wp), INTENT(IN) :: x(3), y(3) + same = ALL(ABS(x - y) <= 1.0e-9_wp*MAX(1.0_wp, ABS(y))) + END FUNCTION same_position + + SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, err_stat, positions) !! Build a BODIES/RODS deck on the coupled aggregate (transactional: the handle keeps its !! previous model on failure). Coupled/Vessel rods and bodies are 6-DOF host nodes, which the !! translational C ABI cannot drive; the standalone deck rules already reject them without a - !! motionFile, and the aggregate rejects a motionFile. + !! motionFile, and the aggregate rejects a motionFile. positions (3, n_moving): the host + !! positions of CableDyn_InitDeckAt, in the aggregate's coupled order. TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h CHARACTER(*), INTENT(IN) :: deck_path LOGICAL, INTENT(IN) :: has_dtm REAL(wp), INTENT(IN) :: dtm + CHARACTER(*), INTENT(IN) :: caller INTEGER(C_INT), INTENT(OUT) :: err_stat + REAL(wp), INTENT(IN), OPTIONAL :: positions(:, :) ! On the heap: InitDeck runs on the host's thread, whose stack size the host chooses. TYPE(CD_AGG_ModuleType), ALLOCATABLE :: new_agg - INTEGER :: es, nm, stat + INTEGER :: es, nm, stat, k REAL(wp), ALLOCATABLE :: pos(:, :), vel(:, :), acc(:, :), load(:, :) CHARACTER(CD_C_MSG_LEN) :: em IF (.NOT. (has_dtm .AND. dtm > CD_ZERO)) THEN - CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_InitDeck: a deck with finite-EI lines, BODIES or RODS '// & + CALL set_status(h, CD_C_BAD_INPUT, caller//': a deck with finite-EI lines, BODIES or RODS '// & 'needs dtM, the fixed step of CableDyn_Step', err_stat) RETURN END IF ALLOCATE (new_agg, STAT=stat) IF (stat /= 0) THEN - CALL set_status(h, CD_C_ALLOC_FAIL, 'CableDyn_InitDeck: aggregate allocation failed', err_stat) + CALL set_status(h, CD_C_ALLOC_FAIL, caller//': aggregate allocation failed', err_stat) RETURN END IF - CALL CD_AGG_Init_From_Deck(new_agg, deck_path, dtm, es, em) + ! An absent positions argument stays absent through the optional coupled_positions. + CALL CD_AGG_Init_From_Deck(new_agg, deck_path, dtm, es, em, coupled_positions=positions) IF (es /= CD_AGG_OK) THEN CALL map_agg_status(es, err_stat) - CALL store_status(h, err_stat, 'CableDyn_InitDeck: '//TRIM(em)) + CALL store_status(h, err_stat, caller//': '//TRIM(em)) CALL CD_AGG_End(new_agg, es, em) RETURN END IF @@ -333,11 +465,37 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, err_stat) ALLOCATE (pos(3, nm), vel(3, nm), acc(3, nm), load(3, nm), STAT=stat) IF (stat /= 0) THEN CALL CD_AGG_End(new_agg, es, em) - CALL set_status(h, CD_C_ALLOC_FAIL, 'CableDyn_InitDeck: aggregate workspace allocation failed', err_stat) + CALL set_status(h, CD_C_ALLOC_FAIL, caller//': aggregate workspace allocation failed', err_stat) RETURN END IF + IF (PRESENT(positions)) THEN + ! Post-condition: every moving point starts at its host position. A point that appears + ! in two blocks (a fairlead shared by an EI=0 line and a finite-EI line) takes the + ! position of its last block, so two different entries for it are rejected here. + CALL CD_AGG_GetMovingPointMesh(new_agg, pos, vel, acc, load, es, em) + IF (es == CD_AGG_OK .AND. SIZE(positions, 2) == nm) THEN + DO k = 1, nm + IF (.NOT. same_position(pos(:, k), positions(:, k))) THEN + es = CD_AGG_BADINPUT + em = 'coupled block '//TRIM(int_text(k - 1))//' did not start at its position in q0 (a point '// & + 'listed in two blocks needs the same position in both)' + EXIT + END IF + END DO + ELSE IF (es == CD_AGG_OK) THEN + es = CD_AGG_BADINPUT + em = 'q0 does not match the coupled vector of the new model' + END IF + IF (es /= CD_AGG_OK) THEN + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, caller//': '//TRIM(em)) + CALL CD_AGG_End(new_agg, es, em) + RETURN + END IF + END IF CALL CD_FAST_End(h%fast, es, em) CALL drop_aggregate(h) + CALL drop_saved_state(h) CALL clear_c_workspace(h) CALL MOVE_ALLOC(pos, h%agg_pos) CALL MOVE_ALLOC(vel, h%agg_vel) @@ -357,11 +515,46 @@ SUBROUTINE move_aggregate(src, dst) TYPE(CD_AGG_ModuleType), INTENT(INOUT) :: src, dst INTEGER :: es CHARACTER(CD_C_MSG_LEN) :: em - CALL CD_AGG_End(dst, es, em) - dst = src + CALL copy_aggregate(src, dst) CALL CD_AGG_End(src, es, em) END SUBROUTINE move_aggregate + SUBROUTINE copy_aggregate(src, dst) + !! Replace dst by a deep copy of src: every allocatable component (each sub-model's state, + !! histories, snapshot buffers and solver workspace) is copied, so the copy evolves + !! exactly as src would. Dummy arguments, so the assignment needs no temporary. + TYPE(CD_AGG_ModuleType), INTENT(IN) :: src + TYPE(CD_AGG_ModuleType), INTENT(INOUT) :: dst + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + CALL CD_AGG_End(dst, es, em) + dst = src + END SUBROUTINE copy_aggregate + + SUBROUTINE copy_point_system(src, dst) + !! The point-route twin of copy_aggregate. + TYPE(CD_FAST_ModuleType), INTENT(IN) :: src + TYPE(CD_FAST_ModuleType), INTENT(INOUT) :: dst + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + CALL CD_FAST_End(dst, es, em) + dst = src + END SUBROUTINE copy_point_system + + SUBROUTINE drop_saved_state(h) + !! Discard the save slot (a new initialization replaces the model it belongs to). + TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + IF (ALLOCATED(h%saved_agg)) THEN + CALL CD_AGG_End(h%saved_agg, es, em) + DEALLOCATE (h%saved_agg) + END IF + CALL CD_FAST_End(h%saved_fast, es, em) + h%saved_agg_t = CD_ZERO + h%has_saved = .FALSE. + END SUBROUTINE drop_saved_state + SUBROUTINE drop_aggregate(h) !! Release the aggregate route of a handle (another initialization replaces it). TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h @@ -497,6 +690,7 @@ SUBROUTINE init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_co CALL map_fast_status(es, err_stat) IF (err_stat == CD_C_OK) THEN CALL drop_aggregate(h) + CALL drop_saved_state(h) CALL set_point_line_map(h, [1]) CALL store_status(h, err_stat, '') ELSE @@ -692,6 +886,7 @@ SUBROUTINE init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fix CALL map_fast_status(es, err_stat) IF (err_stat == CD_C_OK) THEN CALL drop_aggregate(h) + CALL drop_saved_state(h) CALL set_point_line_map(h, [(i, i=1, INT(n_lines))]) CALL store_status(h, err_stat, '') ELSE @@ -1092,6 +1287,7 @@ SUBROUTINE CableDyn_Close(handle, err_stat) BIND(C, NAME='CableDyn_Close') h%magic = 0_INT64 CALL CD_FAST_End(h%fast, es, em) CALL drop_aggregate(h) + CALL drop_saved_state(h) CALL clear_c_workspace(h) DEALLOCATE (h) handle = C_NULL_PTR @@ -1527,6 +1723,164 @@ SUBROUTINE CableDyn_EvalChannel(handle, token_ptr, token_len, value, err_stat) B CALL store_status(h, CD_C_OK, '') END SUBROUTINE CableDyn_EvalChannel + ! --------------------------------------------------------------------------------------- + ! Host coupling (C ABI 1, minor extension 2): CableDyn_InitDeckAt (above, with InitDeck), + ! the one-slot state save/restore a host's outer correctors (PIMPLE, predictor-corrector) + ! rewind with, and the owner of each block of the coupled vector. + ! --------------------------------------------------------------------------------------- + + 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. 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. + !! It stays valid until the next successful Init* call. + TYPE(C_PTR), VALUE :: handle + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + INTEGER :: stat + + IF (.NOT. query_ready(handle, h, 'CableDyn_SaveState', err_stat)) RETURN + IF (h%use_agg) THEN + IF (.NOT. ALLOCATED(h%saved_agg)) THEN + ! On the heap, as the live aggregate: the host chooses this thread's stack size. + ALLOCATE (h%saved_agg, STAT=stat) + IF (stat /= 0) THEN + CALL set_status(h, CD_C_ALLOC_FAIL, 'CableDyn_SaveState: save slot allocation failed', err_stat) + RETURN + END IF + END IF + CALL copy_aggregate(h%agg, h%saved_agg) + h%saved_agg_t = h%agg_t + ELSE + CALL copy_point_system(h%fast, h%saved_fast) + END IF + h%has_saved = .TRUE. + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + END SUBROUTINE CableDyn_SaveState + + SUBROUTINE CableDyn_RestoreState(handle, err_stat) BIND(C, NAME='CableDyn_RestoreState') + !! Return the model to the last CableDyn_SaveState. The slot is kept, so one save serves any + !! number of restores (one per outer corrector). A restore followed by a step is + !! bit-identical to taking that step from the saved state without the intervening steps. + TYPE(C_PTR), VALUE :: handle + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + + IF (.NOT. query_ready(handle, h, 'CableDyn_RestoreState', err_stat)) RETURN + IF (.NOT. h%has_saved) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_RestoreState: no state has been saved since the model was '// & + 'initialized', err_stat) + RETURN + END IF + IF (h%use_agg) THEN + CALL copy_aggregate(h%saved_agg, h%agg) + h%agg_t = h%saved_agg_t + ELSE + CALL copy_point_system(h%saved_fast, h%fast) + END IF + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + END SUBROUTINE CableDyn_RestoreState + + SUBROUTINE CableDyn_GetCoupledLayout(handle, point_id_ptr, point_type_ptr, n_block, err_stat) & + BIND(C, NAME='CableDyn_GetCoupledLayout') + !! The owner of each 3-DOF block of the coupled vector: block k (0-based, DOFs 3k .. 3k+2) + !! moves deck point point_id[k], of type point_type[k] (1 Fixed, 2 Coupled/Vessel, 3 Free, + !! 4 Connect). The host drives the type-2 blocks; the others take the values last returned + !! by CableDyn_GetCoupledMotion. n_block must equal CableDyn_NCoupledDOF / 3; a null pointer + !! skips that output. A raw-array handle has no deck points (its coupled vector is the + !! caller's own fixed-DOF list) and is rejected with CD_C_BAD_INPUT. + TYPE(C_PTR), VALUE :: handle, point_id_ptr, point_type_ptr + INTEGER(C_INT), VALUE :: n_block + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + INTEGER(C_INT), POINTER :: out_c(:) + INTEGER, ALLOCATABLE :: ids(:), types(:) + + IF (.NOT. query_ready(handle, h, 'CableDyn_GetCoupledLayout', err_stat)) RETURN + CALL coupled_layout(h, ids, types, err_stat) + IF (err_stat /= CD_C_OK) RETURN + IF (INT(n_block) /= SIZE(ids)) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_GetCoupledLayout: n_block does not match '// & + 'CableDyn_NCoupledDOF / 3', err_stat) + RETURN + END IF + IF (SIZE(ids) > 0 .AND. C_ASSOCIATED(point_id_ptr)) THEN + CALL C_F_POINTER(point_id_ptr, out_c, [SIZE(ids)]) + out_c = INT(ids, C_INT) + END IF + IF (SIZE(ids) > 0 .AND. C_ASSOCIATED(point_type_ptr)) THEN + CALL C_F_POINTER(point_type_ptr, out_c, [SIZE(types)]) + out_c = INT(types, C_INT) + END IF + CALL store_status(h, CD_C_OK, '') + END SUBROUTINE CableDyn_GetCoupledLayout + + SUBROUTINE coupled_layout(h, ids, types, err_stat) + !! Deck point id and point type (the CD_POINT_* codes) of each coupled block. Point route: + !! the line-bound points of every type in deck POINT order. Aggregate route: the moving + !! points, i.e. the EI=0-bound Coupled/Vessel points in deck POINT order, then the fairlead + !! (End A, which the coupled cable builder requires to be Coupled/Vessel) of each finite-EI + !! line in deck LINE order. + TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h + INTEGER, ALLOCATABLE, INTENT(OUT) :: ids(:), types(:) + INTEGER(C_INT), INTENT(OUT) :: err_stat + INTEGER, ALLOCATABLE :: blocks(:) + INTEGER :: es, i, k, nm, nsys + CHARACTER(CD_C_MSG_LEN) :: em + + err_stat = CD_C_OK + IF (.NOT. h%use_agg) THEN + CALL CD_Get_System_PointBlocks(h%fast%system, blocks, es, em) + IF (es /= CD_SYSTEM_OK) THEN + CALL set_status(h, CD_C_SOLVE_FAIL, 'CableDyn_GetCoupledLayout: '//TRIM(em), err_stat) + RETURN + END IF + IF (.NOT. ALLOCATED(blocks)) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_GetCoupledLayout: a handle initialized from raw arrays '// & + 'has no deck points; its coupled vector is the caller''s fixed-DOF list', err_stat) + RETURN + END IF + IF (ANY(blocks < 1)) THEN + CALL set_status(h, CD_C_SOLVE_FAIL, 'CableDyn_GetCoupledLayout: a coupled block has no owning point', & + err_stat) + RETURN + END IF + ALLOCATE (ids(SIZE(blocks)), types(SIZE(blocks))) + ids = h%fast%system%points(blocks)%id + types = h%fast%system%points(blocks)%point_type + RETURN + END IF + nm = CD_AGG_NMovingPoints(h%agg, es, em) + nsys = 0 + IF (h%agg%has_sys) nsys = h%agg%ncp_sys + IF (es /= CD_AGG_OK .OR. nm /= nsys + h%agg%ncable) THEN + CALL set_status(h, CD_C_SOLVE_FAIL, 'CableDyn_GetCoupledLayout: the moving points of the model are not '// & + 'its Coupled points and cable fairleads', err_stat) + RETURN + END IF + ALLOCATE (ids(nm), types(nm)) + IF (nsys > 0) THEN + CALL CD_Get_System_PointBlocks(h%agg%sys%fast%system, blocks, es, em) + IF (es /= CD_SYSTEM_OK .OR. .NOT. ALLOCATED(blocks)) THEN + CALL set_status(h, CD_C_SOLVE_FAIL, 'CableDyn_GetCoupledLayout: the system layout is unavailable', err_stat) + RETURN + END IF + DO i = 1, nsys + k = blocks(h%agg%sys%moving_blocks(i)) + ids(i) = h%agg%sys%fast%system%points(k)%id + types(i) = h%agg%sys%fast%system%points(k)%point_type + END DO + END IF + DO i = 1, h%agg%ncable + ids(nsys + i) = h%agg%cable_points(1, i) + types(nsys + i) = CD_POINT_COUPLED + END DO + END SUBROUTINE coupled_layout + LOGICAL FUNCTION query_ready(handle, h, caller, err_stat) RESULT(ready) !! Validate the handle of an object query and require an initialized model. TYPE(C_PTR), VALUE :: handle diff --git a/src/CableDyn_CAPI.h b/src/CableDyn_CAPI.h index bc504883..b8f57bd3 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -18,17 +18,18 @@ * J[i + j*n] = d(load_i)/d(q_j). * - Diagnostics are retained per handle (up to 1024 characters) and copied by * CableDyn_GetLastError, truncated to message_len - 1 and NUL-terminated. - * - Create and Close are thread-safe. InitDeck, InitLine, and InitLines are - * serialised process-wide (they parse files through the Fortran runtime), so - * concurrent initialisations of distinct handles succeed one after another. - * The remaining per-handle calls run concurrently on distinct handles. A - * handle must not be used by two threads at once, and must not be used while - * another thread closes it. + * - Create and Close are thread-safe. InitDeck, InitDeckAt, InitLine, and + * InitLines are serialised process-wide (they parse files through the Fortran + * runtime), so concurrent initialisations of distinct handles succeed one + * after another. The remaining per-handle calls run concurrently on distinct + * handles. A handle must not be used by two threads at once, and must not be + * used while another thread closes it. * - The first Create applies the BLAS thread policy (one OpenBLAS thread unless * the environment variable CABLEDYN_BLAS_THREADS says otherwise) and, in the * Windows GNU build, loads openblas.dll. When that runtime cannot be loaded, - * InitDeck, InitLine and InitLines return CD_C_ALLOC_FAIL and GetLastError names - * the library, the locations tried and the Windows load error. + * InitDeck, InitDeckAt, InitLine and InitLines return CD_C_ALLOC_FAIL and + * GetLastError names the library, the locations tried and the Windows load + * error. */ #ifndef CABLEDYN_CAPI_H #define CABLEDYN_CAPI_H @@ -125,8 +126,9 @@ int CableDyn_NLines(void *handle, int *err_stat); * output. A deck with finite-EI lines, BODIES or RODS runs on the coupled * aggregate (it needs dtM); other decks keep the point route. Check * CableDyn_GetAbiMinor() >= 1 before using these on a library of unknown - * vintage. */ -#define CABLEDYN_CAPI_ABI_MINOR 1 + * vintage. CABLEDYN_CAPI_ABI_MINOR is the extension level this header + * declares (2: the host-coupling calls below are present too). */ +#define CABLEDYN_CAPI_ABI_MINOR 2 #define CD_C_OBJ_LINE 1 #define CD_C_OBJ_POINT 2 @@ -173,6 +175,40 @@ void CableDyn_GetRodState(void *handle, int index, double *nodes, int n_nodes, void CableDyn_EvalChannel(void *handle, const char *token, int token_len, double *value, int *err_stat); +/* ---- ABI 1, minor extension 2: host coupling -------------------------------- + * + * For a host (a CFD solver) that drives the Coupled points of a deck. Check + * CableDyn_GetAbiMinor() >= 2 before using these on a library of unknown + * vintage. doc/capi.rst, "Coupling a host (CFD) solver", gives the call + * sequence. */ + +/* Point types of CableDyn_GetCoupledLayout (and of the point subtype of + * CableDyn_GetObjectInfo). The host drives the CD_C_POINT_COUPLED blocks. */ +#define CD_C_POINT_FIXED 1 +#define CD_C_POINT_COUPLED 2 /* Coupled or Vessel */ +#define CD_C_POINT_FREE 3 +#define CD_C_POINT_CONNECT 4 + +/* CableDyn_InitDeck with the static solve at the host's positions: every + * line-bound Coupled/Vessel point starts at its entry of q0 (statics at rest). + * q0 is either the full coupled vector of the deck's route (n_q0 = + * CableDyn_NCoupledDOF after the call; Fixed, Free and Connect blocks are not + * read) or the Coupled/Vessel blocks alone, in coupled-vector order. n_q0 = 0 + * (q0 may be NULL) for a deck without line-bound Coupled/Vessel points. */ +void CableDyn_InitDeckAt(void *handle, const char *deck_path, int deck_path_len, + const double *q0, int n_q0, int *err_stat); +/* One save slot per handle: SaveState copies the whole model (replacing an + * earlier save); RestoreState returns to it and keeps it, so one save serves + * every outer corrector of a host time step. A restore followed by a step is + * bit-identical to stepping from the saved state. Valid until the next Init*. */ +void CableDyn_SaveState(void *handle, int *err_stat); +void CableDyn_RestoreState(void *handle, int *err_stat); +/* Owner of each 3-DOF block k of the coupled vector (DOFs 3k..3k+2): deck + * point id and CD_C_POINT_* type. n_block = CableDyn_NCoupledDOF / 3; NULL + * skips an output. Not available on a raw-array (InitLine/InitLines) handle. */ +void CableDyn_GetCoupledLayout(void *handle, int *point_id, int *point_type, + int n_block, int *err_stat); + #ifdef __cplusplus } #endif diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index dbc3a5a1..ce5edfed 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -1073,7 +1073,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) + env_gravity, env_rho_water, env_wtrdpth, line_ids, coupled_positions) !! 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 @@ -1084,6 +1084,8 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt !! host values override deck-declared ones); a deck-declared bathymetryFile !! keeps its structured seabed over the host's flat depth. !! line_ids: the deck id of each system line (system line order = deck order). + !! coupled_positions (3, n): the host's positions of the line-bound Coupled/Vessel + !! points, placed before the static solve (layout: apply_point_system_positions). CHARACTER(*), INTENT(IN) :: deck_path TYPE(CD_SystemType), INTENT(INOUT) :: system REAL(wp), INTENT(OUT) :: dtM, gravity, rho_water @@ -1092,6 +1094,7 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt LOGICAL, INTENT(IN), OPTIONAL :: caller_driven 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(:, :) TYPE(DeckLineType), ALLOCATABLE :: types(:) TYPE(DeckBody), ALLOCATABLE :: bodies(:) @@ -1150,6 +1153,12 @@ SUBROUTINE CD_Init_Deck_System(deck_path, system, dtM, gravity, rho_water, ErrSt CALL fail(ErrStat, ErrMsg, 'CD_Init_Deck_System does not support motionFile point-system initialization') RETURN END IF + IF (PRESENT(coupled_positions)) THEN + CALL apply_point_system_positions(points, lines, coupled_positions, ErrStat, ErrMsg) + IF (ErrStat /= CD_DECKDRV_OK) RETURN + CALL revalidate_ptfm_points(points, lines, ErrStat, ErrMsg, origin='coupled_positions') + IF (ErrStat /= CD_DECKDRV_OK) RETURN + END IF IF (opts%has_bathymetry_file) THEN CALL load_bathymetry_file(path_join(deck_dir(deck_path), opts%bathymetry_file), bathymetry, ErrStat, ErrMsg, & points=points) @@ -6429,7 +6438,7 @@ SUBROUTINE CD_Init_Deck_Aggregate(deck_path, dt, agg, ErrStat, ErrMsg, env_gravi IF (PRESENT(coupled_positions)) THEN CALL apply_coupled_positions(points, lines, is_fin, coupled_positions, ptfm_init, ErrStat, ErrMsg) IF (ErrStat /= CD_DECKDRV_OK) RETURN - CALL revalidate_ptfm_points(points, lines, ErrStat, ErrMsg) + CALL revalidate_ptfm_points(points, lines, ErrStat, ErrMsg, origin='coupled_positions') IF (ErrStat /= CD_DECKDRV_OK) RETURN END IF @@ -31840,23 +31849,80 @@ SUBROUTINE apply_coupled_positions(points, lines, is_fin, coupled_positions, ptf END IF END SUBROUTINE apply_coupled_positions - SUBROUTINE revalidate_ptfm_points(points, lines, ErrStat, ErrMsg) + SUBROUTINE apply_point_system_positions(points, lines, coupled_positions, ErrStat, ErrMsg) + !! Place the host-driven points of a point-system deck at the host's positions before + !! the static solve. The columns follow the point-system coupled vector, whose blocks are + !! the line-bound points of every type in deck POINT order. coupled_positions holds either + !! one column per line-bound point (the full coupled vector; only the Coupled/Vessel + !! columns are read, the Fixed, Free and Connect columns are not) or one column per + !! line-bound Coupled/Vessel point (those columns only, in the same order). The column + !! count selects the form; when every line-bound point is Coupled/Vessel the two agree. + !! Fails closed on a shape or count mismatch and on non-finite input. + TYPE(DeckPoint), INTENT(INOUT) :: points(:) + TYPE(DeckLine), INTENT(IN) :: lines(:) + REAL(wp), INTENT(IN) :: coupled_positions(:, :) + INTEGER, INTENT(OUT) :: ErrStat + CHARACTER(*), INTENT(OUT) :: ErrMsg + + INTEGER :: i, icol, n_bound, n_host + LOGICAL :: full + LOGICAL, ALLOCATABLE :: bound(:), host(:) + CHARACTER(12) :: t1, t2, t3 + + ErrStat = CD_DECKDRV_OK + ErrMsg = '' + IF (SIZE(coupled_positions, 1) /= 3) THEN + CALL fail(ErrStat, ErrMsg, 'coupled_positions must be shaped (3, n)'); RETURN + END IF + IF (.NOT. ALL(IEEE_IS_FINITE(coupled_positions))) THEN + CALL fail(ErrStat, ErrMsg, 'coupled_positions must be finite'); RETURN + END IF + ALLOCATE (bound(SIZE(points)), host(SIZE(points))) + DO i = 1, SIZE(points) + bound(i) = ANY(lines(:)%nodeA == points(i)%id) .OR. ANY(lines(:)%nodeB == points(i)%id) + host(i) = bound(i) .AND. (TRIM(points(i)%ptype) == 'coupled' .OR. TRIM(points(i)%ptype) == 'vessel') + END DO + n_bound = COUNT(bound) + n_host = COUNT(host) + full = SIZE(coupled_positions, 2) == n_bound + IF (.NOT. full .AND. SIZE(coupled_positions, 2) /= n_host) THEN + WRITE (t1, '(I0)') SIZE(coupled_positions, 2) + WRITE (t2, '(I0)') n_bound + WRITE (t3, '(I0)') n_host + CALL fail(ErrStat, ErrMsg, 'coupled_positions has '//TRIM(t1)//' points; the deck has '//TRIM(t2)// & + ' line-bound points (the coupled vector), '//TRIM(t3)//' of them Coupled/Vessel'); RETURN + END IF + icol = 0 + DO i = 1, SIZE(points) + IF (full .AND. bound(i)) icol = icol + 1 + IF (.NOT. host(i)) CYCLE + IF (.NOT. full) icol = icol + 1 + points(i)%pos = coupled_positions(:, icol) + END DO + END SUBROUTINE apply_point_system_positions + + SUBROUTINE revalidate_ptfm_points(points, lines, ErrStat, ErrMsg, origin) !! Re-establish the parse's position-dependent contracts on ptfm_init-displaced !! geometry (the transform runs after finalize_and_validate, so without this a !! displaced deck could hand the static builders geometry the undisplaced deck !! would have failed closed on): every point position stays finite, and on a !! static deck no LINE's fairlead-side End A ends up below its Fixed End B anchor - !! (the ordering contract the catenary seeding relies on). + !! (the ordering contract the catenary seeding relies on). origin names the input + !! that moved the points in the diagnostics (default 'ptfm_init'). TYPE(DeckPoint), INTENT(IN) :: points(:) TYPE(DeckLine), INTENT(IN) :: lines(:) INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg + CHARACTER(*), INTENT(IN), OPTIONAL :: origin INTEGER :: i, ia, ib + CHARACTER(32) :: what ErrStat = CD_DECKDRV_OK ErrMsg = '' + what = 'ptfm_init' + IF (PRESENT(origin)) what = origin DO i = 1, SIZE(points) IF (.NOT. ALL(IEEE_IS_FINITE(points(i)%pos))) THEN - CALL fail(ErrStat, ErrMsg, 'ptfm_init produced a non-finite point position'); RETURN + CALL fail(ErrStat, ErrMsg, TRIM(what)//' produced a non-finite point position'); RETURN END IF END DO IF (deck_has_dynamic_points(points)) RETURN @@ -31866,7 +31932,7 @@ SUBROUTINE revalidate_ptfm_points(points, lines, ErrStat, ErrMsg) IF (ia == 0 .OR. ib == 0) CYCLE ! endpoint resolution already validated by the parse IF (TRIM(points(ib)%ptype) == 'fixed') THEN IF (points(ia)%pos(3) < points(ib)%pos(3)) THEN - CALL fail(ErrStat, ErrMsg, 'ptfm_init displaces a LINE End A fairlead (NodeA) below its '// & + CALL fail(ErrStat, ErrMsg, TRIM(what)//' displaces a LINE End A fairlead (NodeA) below its '// & 'Fixed End B anchor (NodeB)'); RETURN END IF END IF diff --git a/src/cabledyn.def b/src/cabledyn.def index 34764f5a..9d2679d4 100644 --- a/src/cabledyn.def +++ b/src/cabledyn.def @@ -8,6 +8,7 @@ EXPORTS CableDyn_EvalChannel CableDyn_GetAbiMinor CableDyn_GetBodyState + CableDyn_GetCoupledLayout CableDyn_GetCoupledMotion CableDyn_GetLastError CableDyn_GetLineValues @@ -17,6 +18,7 @@ EXPORTS CableDyn_GetVersion CableDyn_GetVersionString CableDyn_InitDeck + CableDyn_InitDeckAt CableDyn_InitLine CableDyn_InitLines CableDyn_IsInitialized @@ -24,6 +26,8 @@ EXPORTS CableDyn_NLines CableDyn_NObjects CableDyn_NPoints + CableDyn_RestoreState + CableDyn_SaveState CableDyn_Step CableDyn_UpdatePointFluidFields CableDyn_UpdateStates diff --git a/src/cabledyn.exp b/src/cabledyn.exp index 275e4c6e..945fcb2f 100644 --- a/src/cabledyn.exp +++ b/src/cabledyn.exp @@ -7,6 +7,7 @@ _CableDyn_Create _CableDyn_EvalChannel _CableDyn_GetAbiMinor _CableDyn_GetBodyState +_CableDyn_GetCoupledLayout _CableDyn_GetCoupledMotion _CableDyn_GetLastError _CableDyn_GetLineValues @@ -16,6 +17,7 @@ _CableDyn_GetRodState _CableDyn_GetVersion _CableDyn_GetVersionString _CableDyn_InitDeck +_CableDyn_InitDeckAt _CableDyn_InitLine _CableDyn_InitLines _CableDyn_IsInitialized @@ -23,6 +25,8 @@ _CableDyn_NCoupledDOF _CableDyn_NLines _CableDyn_NObjects _CableDyn_NPoints +_CableDyn_RestoreState +_CableDyn_SaveState _CableDyn_Step _CableDyn_UpdatePointFluidFields _CableDyn_UpdateStates diff --git a/src/cabledyn.map b/src/cabledyn.map index 08a9fe06..125f69b0 100644 --- a/src/cabledyn.map +++ b/src/cabledyn.map @@ -10,6 +10,7 @@ CableDyn_EvalChannel; CableDyn_GetAbiMinor; CableDyn_GetBodyState; + CableDyn_GetCoupledLayout; CableDyn_GetCoupledMotion; CableDyn_GetLastError; CableDyn_GetLineValues; @@ -19,6 +20,7 @@ CableDyn_GetVersion; CableDyn_GetVersionString; CableDyn_InitDeck; + CableDyn_InitDeckAt; CableDyn_InitLine; CableDyn_InitLines; CableDyn_IsInitialized; @@ -26,6 +28,8 @@ CableDyn_NLines; CableDyn_NObjects; CableDyn_NPoints; + CableDyn_RestoreState; + CableDyn_SaveState; CableDyn_Step; CableDyn_UpdatePointFluidFields; CableDyn_UpdateStates; diff --git a/tests/data/foam_esflowc_box_points.dat b/tests/data/foam_esflowc_box_points.dat new file mode 100644 index 00000000..d671462c --- /dev/null +++ b/tests/data/foam_esflowc_box_points.dat @@ -0,0 +1,41 @@ +--------------------- CableDyn Input File ------------------------------------ +foamMooring EsfLOWC floating box (Wu et al., 2018): four slack EI=0 lines, 4 Fixed anchors, 4 Coupled fairleads +Source: the MoorDyn v2 input lines_v2.txt of foamMooring's EsfLOWC tutorial, with the points renumbered +sequentially (anchors 1-4, fairleads 5-8). The fairleads sit at the deck z = -0.062 m; the tutorial's box +starts with them at z = -0.077 m (the C API host-coupling test, tests/test_c_api_host_coupling.c). +--------------------- LINE TYPES --------------------------------------------- +TypeName Diam MassDenInAir EA BA/-zeta EI Cd Ca CdAx CaAx +(name) (m) (kg/m) (N) (N-s/-) (N-m^2) (-) (-) (-) (-) +main 0.003656 0.0607 29 -0.8 0 1.6 1.0 0.05 0.0 +--------------------- POINTS ------------------------------------------------- +ID Type X Y Z Mass Vol CdA Ca +(#) (-) (m) (m) (m) (kg) (m3) (m2) (-) +1 Fixed -1.385 0.423 -0.5 0 0 0 0 +2 Fixed -1.385 -0.423 -0.5 0 0 0 0 +3 Fixed 1.385 0.423 -0.5 0 0 0 0 +4 Fixed 1.385 -0.423 -0.5 0 0 0 0 +5 Coupled -0.1 0.1 -0.062 0 0 0 0 +6 Coupled -0.1 -0.1 -0.062 0 0 0 0 +7 Coupled 0.1 0.1 -0.062 0 0 0 0 +8 Coupled 0.1 -0.1 -0.062 0 0 0 0 +--------------------- LINES -------------------------------------------------- +ID LineType AttachA AttachB UnstrLen NumSegs Outputs +(#) (name) (#) (#) (m) (-) (-) +1 main 1 5 1.455 40 - +2 main 2 6 1.455 40 - +3 main 3 7 1.455 40 - +4 main 4 8 1.455 40 - +--------------------- OPTIONS ------------------------------------------------ +9.81 g +1025.0 rhoW +0.5 WtrDpth +3.0e6 kBot +3.0e5 cBot +--------------------- OUTPUTS ------------------------------------------------ +FairTen4 +AnchTen4 +Point8Fx +Point8Fy +Point8Fz +TDP4s +--------------------- need this line ----------------------------------------- diff --git a/tests/data/host_coupling_chain_cable.dat b/tests/data/host_coupling_chain_cable.dat new file mode 100644 index 00000000..be53a5b8 --- /dev/null +++ b/tests/data/host_coupling_chain_cable.dat @@ -0,0 +1,35 @@ +--------------------- CableDyn Input File ------------------------------------ +C API host-coupling test deck: one EI=0 chain and one finite-EI cable, each from its own +Coupled fairlead to a Fixed anchor on a 50 m flat seabed. The finite-EI line puts the deck on +the coupled aggregate (fixed step dtM); the two sub-objects make every step a staged step. +--------------------------- LINE TYPES ---------------------------------------- +Name Diam Mass EA BA EI Cdn Cdt Can Cat +(-) (m) (kg/m) (N) (-) (Nm2) (-) (-) (-) (-) +chain 0.10 50.0 5.0e8 -1.0 0.0 2.0 0.4 0.82 0.27 +cable 0.16 36.7 4.69e8 0.0 1.99e4 1.2 0.1 1.0 0.0 +--------------------------- POINTS -------------------------------------------- +ID Type X Y Z +(-) (-) (m) (m) (m) +1 Fixed -110.0 0.0 -50.0 +2 Coupled -5.0 0.0 -5.0 +3 Fixed 95.0 0.0 -50.0 +4 Coupled 5.0 0.0 -5.0 +--------------------------- LINES --------------------------------------------- +ID NodeA NodeB Outputs +(-) (-) (-) (-) +1 2 1 - +2 4 3 - +--------------------------- SECTIONS ------------------------------------------ +LineID LineType Length NumSegs +(-) (-) (m) (-) +1 chain 120.0 20 +2 cable 110.0 22 +--------------------------- OPTIONS ------------------------------------------- +9.80665 g +1025.0 rhoW +3.0e6 kBot +3.0e5 cBot +50.0 WtrDpth +0.01 dtM +0.0 TMax +--------------------------- need this line ------------------------------------ diff --git a/tests/test_c_api.f90 b/tests/test_c_api.f90 index dd090160..ea8aa269 100644 --- a/tests/test_c_api.f90 +++ b/tests/test_c_api.f90 @@ -12,7 +12,8 @@ PROGRAM test_c_api CableDyn_UpdatePointFluidFields, CableDyn_Step, CableDyn_CalcOutput, & CableDyn_CalcOutputDerivatives, CableDyn_GetCoupledMotion, CableDyn_GetLastError, & CableDyn_GetVersion, & - CableDyn_GetVersionString, CableDyn_NCoupledDOF, CableDyn_NPoints, CableDyn_NLines + CableDyn_GetVersionString, CableDyn_NCoupledDOF, CableDyn_NPoints, CableDyn_NLines, & + CableDyn_SaveState, CableDyn_RestoreState USE CableDyn_Precision, ONLY: wp USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_Step_Moving, & CD_AGG_CalcOutput, CD_AGG_GetMovingPointMesh, CD_AGG_End, CD_AGG_OK @@ -539,7 +540,8 @@ END SUBROUTINE case_stale_double_close_copied_handle SUBROUTINE case_deck_bodies_rods() !! A deck with a free rod (and one with a free Rigid6 body) initializes through the aggregate: !! the coupled DOFs are its Coupled points, the step is the deck dtM, and 20 driven steps - !! reproduce CD_AGG driven directly bit-for-bit (loads and coupled motion). A mismatched dt, + !! reproduce CD_AGG driven directly bit-for-bit (loads and coupled motion), also across a + !! SaveState / three trial steps / RestoreState rewind half way. A mismatched dt, !! load derivatives and point fluid fields fail closed by name; a Coupled rod (a 6-DOF host !! node) is rejected by the standalone deck rules. CHARACTER(*), PARAMETER :: ROD_DECK = 'capi_rod_deck.dat', BODY_DECK = 'capi_body_deck.dat', & @@ -590,6 +592,21 @@ SUBROUTINE case_deck_bodies_rods() a = 0.0_C_DOUBLE maxdiff = 0.0_wp DO s = 1, 20 + IF (s == 11) THEN + ! An outer-corrector rewind half way: save, take three trial steps with another motion, + ! restore. The march must go on bit for bit with the directly driven aggregate. + CALL CableDyn_SaveState(handle, es) + CALL require(es == 0_C_INT, 'c-api-objects:save') + DO i = 1, 3 + q(1) = qo(1) - 0.1_C_DOUBLE*REAL(i, C_DOUBLE) + v(1) = -0.2_C_DOUBLE + CALL CableDyn_Step(handle, 0.005_C_DOUBLE, C_LOC(q), C_LOC(v), C_LOC(a), 3_C_INT, converged, & + stalled, n_iter, es) + CALL require(es == 0_C_INT, 'c-api-objects:trial-step') + END DO + CALL CableDyn_RestoreState(handle, es) + CALL require(es == 0_C_INT, 'c-api-objects:restore') + END IF q(1) = qo(1) + 0.05_C_DOUBLE*SIN(0.5_C_DOUBLE*REAL(s, C_DOUBLE)) v(1) = 0.025_C_DOUBLE*COS(0.5_C_DOUBLE*REAL(s, C_DOUBLE)) CALL CableDyn_Step(handle, 0.005_C_DOUBLE, C_LOC(q), C_LOC(v), C_LOC(a), 3_C_INT, converged, stalled, & diff --git a/tests/test_c_api_host_coupling.c b/tests/test_c_api_host_coupling.c new file mode 100644 index 00000000..2cbfb050 --- /dev/null +++ b/tests/test_c_api_host_coupling.c @@ -0,0 +1,497 @@ +/* File: tests/test_c_api_host_coupling.c + * SPDX-License-Identifier: Apache-2.0 + * Host-coupling gate of C ABI 1 minor extension 2, through the public header + * and the shared library. + * + * Usage: test_c_api_host_coupling + * + * box_points.dat is the foamMooring EsfLOWC box (four slack EI=0 lines, point + * route) whose fairleads sit at z = -0.062 m in the deck while the CFD box + * starts with them at z = -0.077 m. mixed_chain_cable.dat is an EI=0 chain + * plus a finite-EI cable (aggregate route, staged steps). The test checks: + * - CableDyn_InitDeckAt solves the statics at the host positions: on both + * routes the result equals CableDyn_InitDeck of the deck moved there bit for + * bit; for the box, line 4's fairlead load is the standalone value and held + * fairleads stay at rest, while InitDeck at the deck positions followed by + * steps at the host positions rings; + * - CableDyn_SaveState/RestoreState: a restore followed by steps reproduces a + * fresh model taking the same steps bit for bit, on both routes, also after + * several steps between save and restore and after repeated restores; + * - CableDyn_GetCoupledLayout reports anchors and fairleads on the point route + * and only the Coupled points on the aggregate route; + * - the fail-closed rejections of the new calls. + */ +#include "CableDyn_CAPI.h" + +#include +#include +#include +#include + +#define CHECK(condition, message) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "FAIL: %s\n", (message)); \ + return 1; \ + } \ + } while (0) + +#define BOX_NDOF 24 /* 8 line-bound points: 4 Fixed anchors, 4 Coupled fairleads */ +#define BOX_NHOST 12 /* the 4 Coupled fairleads */ +#define BOX_DT 1.0e-3 +#define BOX_NSTEP 1000 /* 1 s */ +#define DECK_Z (-0.062) +#define HOST_Z (-0.077) + +#define MIX_NDOF 6 /* the chain and the cable fairleads; the anchors are not coupled */ +#define MIX_DT 0.01 + +static const char *g_box; +static const char *g_mixed; + +static void report(void *h, const char *where, int err) +{ + char msg[1025]; + CableDyn_GetLastError(h, msg, (int)sizeof msg); + fprintf(stderr, "FAIL: %s (status %d): %s\n", where, err, msg); +} + +static int init_deck(void **h, const char *deck) +{ + int err = -1; + CableDyn_Create(h, &err); + CHECK(err == CD_C_OK, "create"); + CableDyn_InitDeck(*h, deck, (int)strlen(deck), &err); + if (err != CD_C_OK) { + report(*h, "InitDeck", err); + return 1; + } + return 0; +} + +static int init_deck_at(void **h, const char *deck, const double *q0, int n_q0) +{ + int err = -1; + CableDyn_Create(h, &err); + CHECK(err == CD_C_OK, "create"); + CableDyn_InitDeckAt(*h, deck, (int)strlen(deck), q0, n_q0, &err); + if (err != CD_C_OK) { + report(*h, "InitDeckAt", err); + return 1; + } + return 0; +} + +static int step(void *h, double dt, const double *q, const double *v, const double *a, int n) +{ + bool converged = false, stalled = true; + int n_iter = 0, err = -1; + CableDyn_Step(h, dt, q, v, a, n, &converged, &stalled, &n_iter, &err); + if (err != CD_C_OK || !converged) { + report(h, "Step", err); + return 1; + } + return 0; +} + +static int loads(void *h, double *f, int n) +{ + int err = -1; + CableDyn_CalcOutput(h, f, n, &err); + if (err != CD_C_OK) { + report(h, "CalcOutput", err); + return 1; + } + return 0; +} + +/* The box fairlead positions (deck x, y) at height z, as the 4 Coupled blocks. */ +static void box_fairleads(double z, double *q_host) +{ + static const double xy[4][2] = {{-0.1, 0.1}, {-0.1, -0.1}, {0.1, 0.1}, {0.1, -0.1}}; + for (int p = 0; p < 4; ++p) { + q_host[3 * p + 0] = xy[p][0]; + q_host[3 * p + 1] = xy[p][1]; + q_host[3 * p + 2] = z; + } +} + +/* Copy a deck with the Coupled points moved (the standalone reference of InitDeckAt): on every + * line naming a Coupled point, the text old_text is replaced by new_text of the same length; + * n_moved such lines must be found. */ +static int write_moved_deck(const char *in_path, const char *out_path, const char *old_text, + const char *new_text, int n_moved) +{ + FILE *in = fopen(in_path, "r"), *out = NULL; + char line[512]; + int moved = 0; + CHECK(in != NULL && strlen(old_text) == strlen(new_text), "open the deck to move"); + out = fopen(out_path, "w"); + if (out == NULL) { + fclose(in); + CHECK(0, "write the moved deck"); + } + while (fgets(line, (int)sizeof line, in) != NULL) { + char *at = strstr(line, old_text); + if (at != NULL && strstr(line, "Coupled") != NULL) { + memcpy(at, new_text, strlen(new_text)); + ++moved; + } + fputs(line, out); + } + fclose(in); + fclose(out); + CHECK(moved == n_moved, "the deck names its Coupled points as expected"); + return 0; +} + +static int check_version(void) +{ + CHECK(CABLEDYN_CAPI_ABI_MINOR == 2 && CableDyn_GetAbiMinor() == CABLEDYN_CAPI_ABI_MINOR, + "ABI minor level 2"); + return 0; +} + +static int check_point_layout(void) +{ + void *h = NULL; + int err = -1, ids[8], types[8], n; + if (init_deck(&h, g_box)) return 1; + n = CableDyn_NCoupledDOF(h, &err); + CHECK(err == CD_C_OK && n == BOX_NDOF, "the box coupled vector has 8 blocks"); + CableDyn_GetCoupledLayout(h, ids, types, n / 3, &err); + CHECK(err == CD_C_OK, "layout query"); + for (int k = 0; k < 8; ++k) { + CHECK(ids[k] == k + 1, "point-route blocks follow the POINTS table"); + CHECK(types[k] == (k < 4 ? CD_C_POINT_FIXED : CD_C_POINT_COUPLED), + "point-route blocks: 4 Fixed anchors, then 4 Coupled fairleads"); + } + CableDyn_GetCoupledLayout(h, NULL, types, n / 3, &err); + CHECK(err == CD_C_OK && types[7] == CD_C_POINT_COUPLED, "a NULL output is skipped"); + CableDyn_GetCoupledLayout(h, ids, types, n / 3 - 1, &err); + CHECK(err == CD_C_BAD_INPUT, "a wrong block count is rejected"); + CableDyn_Close(&h, &err); + return 0; +} + +static int check_raw_layout(void) +{ + void *h = NULL; + int err = -1, ids[2], types[2], bogus = 0; + const double q0[6] = {0.0, 0.0, 0.0, 10.0, 0.0, 0.0}, v0[6] = {0.0}; + const int elem_conn[2] = {1, 2}, fixed[6] = {1, 2, 3, 4, 5, 6}; + const double l0[1] = {10.0}, ea[1] = {1.0e6}, rho_a[1] = {10.0}; + char msg[256]; + + CableDyn_Create(&h, &err); + CableDyn_GetCoupledLayout(h, ids, types, 2, &err); + CHECK(err == CD_C_NOT_INITIALIZED, "layout of an uninitialized handle"); + CableDyn_SaveState(h, &err); + CHECK(err == CD_C_NOT_INITIALIZED, "save on an uninitialized handle"); + CableDyn_RestoreState(h, &err); + CHECK(err == CD_C_NOT_INITIALIZED, "restore on an uninitialized handle"); + CableDyn_InitLine(h, 2, 1, q0, v0, elem_conn, l0, ea, rho_a, fixed, 6, 1, 0.8, &err); + CHECK(err == CD_C_OK, "raw line init"); + CableDyn_GetCoupledLayout(h, ids, types, 2, &err); + CableDyn_GetLastError(h, msg, (int)sizeof msg); + CHECK(err == CD_C_BAD_INPUT && strstr(msg, "raw arrays") != NULL, "a raw-array handle has no layout"); + CableDyn_GetCoupledLayout((void *)&bogus, ids, types, 2, &err); + CHECK(err == CD_C_BAD_HANDLE, "foreign handle"); + CableDyn_Close(&h, &err); + return 0; +} + +static int check_init_at(void) +{ + void *at = NULL, *full = NULL, *moved = NULL, *plain = NULL; + double q_host[BOX_NHOST], q_full[BOX_NDOF], q[BOX_NDOF], v[BOX_NDOF] = {0.0}, a[BOX_NDOF] = {0.0}; + double f_at[BOX_NDOF], f_full[BOX_NDOF], f_moved[BOX_NDOF], f[BOX_NDOF], f_plain0[BOX_NDOF]; + double drift = 0.0, ring = 0.0, ring_end = 0.0; + int err = -1, n, ids[8], types[8]; + const char *moved_deck = "capi_host_box_moved.dat"; + /* standalone CableDyn with the deck moved to z = -0.077 (MoorDyn: 0.3034, -0.0763, -0.4136) */ + const double f4_ref[3] = {0.3026, -0.0761, -0.4114}; + char msg[1025]; + + box_fairleads(HOST_Z, q_host); + if (init_deck_at(&at, g_box, q_host, BOX_NHOST)) return 1; + n = CableDyn_NCoupledDOF(at, &err); + CHECK(err == CD_C_OK && n == BOX_NDOF, "InitDeckAt keeps the route's coupled vector"); + CableDyn_GetCoupledLayout(at, ids, types, 8, &err); + CHECK(err == CD_C_OK && ids[7] == 8 && types[7] == CD_C_POINT_COUPLED, "layout after InitDeckAt"); + CableDyn_GetCoupledMotion(at, q, v, a, n, &err); + CHECK(err == CD_C_OK, "coupled motion after InitDeckAt"); + for (int p = 0; p < 4; ++p) { + CHECK(q[3 * p + 2] == -0.5, "the anchors stay at the deck coordinates"); + CHECK(memcmp(&q[12 + 3 * p], &q_host[3 * p], 3 * sizeof(double)) == 0, + "the fairleads start exactly at q0"); + } + for (int i = 0; i < n; ++i) CHECK(v[i] == 0.0 && a[i] == 0.0, "the statics start at rest"); + if (loads(at, f_at, n)) return 1; + printf("InitDeckAt z=%.3f: line 4 fairlead load (%.4f, %.4f, %.4f) N\n", HOST_Z, f_at[21], f_at[22], + f_at[23]); + for (int c = 0; c < 3; ++c) + CHECK(fabs(f_at[21 + c] - f4_ref[c]) < 1.0e-4, "line 4 fairlead load matches the standalone statics"); + + /* The full-vector form: the Fixed blocks are not read. */ + memcpy(q_full, q, sizeof q_full); + for (int i = 0; i < 12; ++i) q_full[i] = 1.0e3; + if (init_deck_at(&full, g_box, q_full, BOX_NDOF)) return 1; + if (loads(full, f_full, n)) return 1; + CHECK(memcmp(f_full, f_at, sizeof f_at) == 0, "full and Coupled-only q0 give the same statics"); + CableDyn_GetCoupledMotion(full, q_full, v, a, n, &err); + CHECK(err == CD_C_OK && memcmp(q_full, q, sizeof q) == 0, "the full form ignores the Fixed blocks"); + + /* Bit for bit the statics of the deck moved to the host positions. */ + if (write_moved_deck(g_box, moved_deck, "-0.062", "-0.077", 4)) return 1; + if (init_deck(&moved, moved_deck)) return 1; + if (loads(moved, f_moved, n)) return 1; + CHECK(memcmp(f_moved, f_at, sizeof f_at) == 0, "InitDeckAt equals InitDeck of the moved deck"); + remove(moved_deck); + + /* Held at the host positions, the InitDeckAt model stays at equilibrium for 1 s. */ + memset(v, 0, sizeof v); + memset(a, 0, sizeof a); + for (int s = 1; s <= BOX_NSTEP; ++s) { + if (step(at, BOX_DT, q, v, a, n) || loads(at, f, n)) return 1; + for (int i = 12; i < n; ++i) drift = fmax(drift, fabs(f[i] - f_at[i])); + } + printf("InitDeckAt, fairleads held 1 s: max fairlead load change %.3e N\n", drift); + CHECK(drift < 1.0e-6, "no start-up transient after InitDeckAt"); + + /* InitDeck at the deck positions, then held at the host positions: the start-up transient. */ + if (init_deck(&plain, g_box)) return 1; + if (loads(plain, f_plain0, n)) return 1; + for (int s = 1; s <= BOX_NSTEP; ++s) { + if (step(plain, BOX_DT, q, v, a, n) || loads(plain, f, n)) return 1; + for (int i = 12; i < n; ++i) { + ring = fmax(ring, fabs(f[i] - f_at[i])); + if (s == BOX_NSTEP) ring_end = fmax(ring_end, fabs(f[i] - f_at[i])); + } + } + printf("InitDeck z=%.3f: line 4 fairlead load (%.4f, %.4f, %.4f) N\n", DECK_Z, f_plain0[21], f_plain0[22], + f_plain0[23]); + printf("InitDeck, then held at z=%.3f for 1 s: max deviation from the equilibrium %.3e N " + "(%.3e N at 1 s)\n", + HOST_Z, ring, ring_end); + CHECK(ring > 1.0e4 * drift && ring > 1.0e-2, "the plain start rings"); + + /* Rejections keep the previous model. */ + CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, 9, &err); + CableDyn_GetLastError(at, msg, (int)sizeof msg); + CHECK(err == CD_C_BAD_INPUT && strstr(msg, "coupled_positions") != NULL, "a wrong q0 length is rejected"); + CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, 13, &err); + CHECK(err == CD_C_BAD_INPUT, "a q0 length that is not a multiple of 3 is rejected"); + CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), NULL, BOX_NHOST, &err); + CHECK(err == CD_C_BAD_INPUT, "a NULL q0 is rejected"); + q_host[5] = NAN; + CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, BOX_NHOST, &err); + CHECK(err == CD_C_BAD_INPUT, "a non-finite q0 is rejected"); + CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), NULL, 0, &err); + CHECK(err == CD_C_BAD_INPUT, "an empty q0 is rejected for a deck with Coupled points"); + CHECK(CableDyn_IsInitialized(at) && CableDyn_NCoupledDOF(at, &err) == BOX_NDOF, + "a rejected InitDeckAt keeps the model"); + + CableDyn_Close(&at, &err); + CableDyn_Close(&full, &err); + CableDyn_Close(&moved, &err); + CableDyn_Close(&plain, &err); + return 0; +} + +/* A smooth host motion of the Coupled blocks: amplitude amp, sample time t. */ +static void host_motion(const int *types, int nb, const double *q0, double amp, double t, double *q, double *v, + double *a) +{ + const double w = 2.0 * acos(-1.0); + for (int k = 0; k < nb; ++k) { + for (int c = 0; c < 3; ++c) { + q[3 * k + c] = q0[3 * k + c]; + v[3 * k + c] = 0.0; + a[3 * k + c] = 0.0; + } + if (types[k] != CD_C_POINT_COUPLED) continue; + q[3 * k + 0] += amp * sin(w * t); + v[3 * k + 0] = amp * w * cos(w * t); + a[3 * k + 0] = -amp * w * w * sin(w * t); + q[3 * k + 2] += 0.5 * amp * (1.0 - cos(w * t)); + v[3 * k + 2] = 0.5 * amp * w * sin(w * t); + a[3 * k + 2] = 0.5 * amp * w * w * cos(w * t); + } +} + +/* Save, take n_trial trial steps, restore (n_restore times) and take n_steps steps; the result must + * equal a fresh model taking the same n_steps steps, bit for bit. */ +static int check_save_restore(const char *deck, const double *q_host, int n_host, double dt, double amp, + int n_trial, int n_steps, const char *route) +{ + void *h = NULL, *ref = NULL; + double *q0, *q, *v, *a, *f, *f_ref, *mq, *mv, *ma, *rq, *rv, *ra; + int err = -1, n, *ids, *types, status = 1, n_lines; + char label[160]; + + if (init_deck_at(&h, deck, q_host, n_host) || init_deck_at(&ref, deck, q_host, n_host)) return 1; + n = CableDyn_NCoupledDOF(h, &err); + n_lines = CableDyn_NLines(h, &err); + q0 = calloc((size_t)n, sizeof *q0); + q = calloc((size_t)n, sizeof *q); + v = calloc((size_t)n, sizeof *v); + a = calloc((size_t)n, sizeof *a); + f = calloc((size_t)n, sizeof *f); + f_ref = calloc((size_t)n, sizeof *f_ref); + mq = calloc((size_t)n, sizeof *mq); + mv = calloc((size_t)n, sizeof *mv); + ma = calloc((size_t)n, sizeof *ma); + rq = calloc((size_t)n, sizeof *rq); + rv = calloc((size_t)n, sizeof *rv); + ra = calloc((size_t)n, sizeof *ra); + ids = calloc((size_t)(n / 3), sizeof *ids); + types = calloc((size_t)(n / 3), sizeof *types); + CHECK(q0 && q && v && a && f && f_ref && mq && mv && ma && rq && rv && ra && ids && types, "allocation"); + CableDyn_GetCoupledMotion(h, q0, v, a, n, &err); + CableDyn_GetCoupledLayout(h, ids, types, n / 3, &err); + CHECK(err == CD_C_OK, "layout"); + + CableDyn_RestoreState(h, &err); + CHECK(err == CD_C_BAD_INPUT, "restore without a save is rejected"); + CableDyn_SaveState(h, &err); + CHECK(err == CD_C_OK, "save"); + /* Two outer correctors that take other (larger) trial motions before the final pass. */ + for (int corrector = 0; corrector < 2; ++corrector) { + for (int s = 1; s <= n_trial; ++s) { + host_motion(types, n / 3, q0, 2.0 * amp * (corrector + 1), s * dt, q, v, a); + if (step(h, dt, q, v, a, n)) goto done; + } + CableDyn_RestoreState(h, &err); + CHECK(err == CD_C_OK, "restore"); + } + for (int s = 1; s <= n_steps; ++s) { + host_motion(types, n / 3, q0, amp, s * dt, q, v, a); + if (step(h, dt, q, v, a, n) || step(ref, dt, q, v, a, n)) goto done; + if (loads(h, f, n) || loads(ref, f_ref, n)) goto done; + CableDyn_GetCoupledMotion(h, mq, mv, ma, n, &err); + CableDyn_GetCoupledMotion(ref, rq, rv, ra, n, &err); + snprintf(label, sizeof label, "%s: restore + step %d equals the fresh model bit for bit", route, s); + CHECK(memcmp(f, f_ref, (size_t)n * sizeof *f) == 0, label); + CHECK(memcmp(mq, rq, (size_t)n * sizeof *mq) == 0 && memcmp(mv, rv, (size_t)n * sizeof *mv) == 0 && + memcmp(ma, ra, (size_t)n * sizeof *ma) == 0, + label); + } + /* Every line node agrees too. */ + for (int l = 0; l < n_lines; ++l) { + int id = 0, nn = 0, sub = 0; + double *xh, *xr; + CableDyn_GetObjectInfo(h, CD_C_OBJ_LINE, l, &id, &nn, &sub, &err); + xh = calloc((size_t)(3 * nn), sizeof *xh); + xr = calloc((size_t)(3 * nn), sizeof *xr); + CHECK(xh && xr, "allocation"); + CableDyn_GetLineValues(h, l, CD_C_LINE_POSITION, xh, 3 * nn, &err); + CableDyn_GetLineValues(ref, l, CD_C_LINE_POSITION, xr, 3 * nn, &err); + snprintf(label, sizeof label, "%s: line %d nodes after the restore equal the fresh model", route, id); + CHECK(err == CD_C_OK && memcmp(xh, xr, (size_t)(3 * nn) * sizeof *xh) == 0, label); + free(xh); + free(xr); + } + printf("%s: %d trial steps x 2 correctors, restore, %d steps: bit-identical to the fresh model\n", route, + n_trial, n_steps); + + /* A new initialization discards the save. */ + CableDyn_InitDeckAt(h, deck, (int)strlen(deck), q_host, n_host, &err); + CHECK(err == CD_C_OK, "re-initialization"); + CableDyn_RestoreState(h, &err); + CHECK(err == CD_C_BAD_INPUT, "a re-initialization discards the save"); + status = 0; + +done: + free(q0); + free(q); + free(v); + free(a); + free(f); + free(f_ref); + free(mq); + free(mv); + free(ma); + free(rq); + free(rv); + free(ra); + free(ids); + free(types); + CableDyn_Close(&h, &err); + CableDyn_Close(&ref, &err); + return status; +} + +static int check_aggregate(void) +{ + void *h = NULL, *moved = NULL; + int err = -1, n, ids[2], types[2]; + double q[MIX_NDOF], v[MIX_NDOF], a[MIX_NDOF], q_host[MIX_NDOF], f[MIX_NDOF], f_moved[MIX_NDOF]; + const char *half_moved = "capi_host_mixed_half.dat", *moved_deck = "capi_host_mixed_moved.dat"; + char msg[1025]; + + if (init_deck(&h, g_mixed)) return 1; + n = CableDyn_NCoupledDOF(h, &err); + CHECK(err == CD_C_OK && n == MIX_NDOF, "the aggregate coupled vector holds the two fairleads only"); + CableDyn_GetCoupledLayout(h, ids, types, 2, &err); + CHECK(err == CD_C_OK && ids[0] == 2 && ids[1] == 4, "aggregate blocks: the chain, then the cable fairlead"); + CHECK(types[0] == CD_C_POINT_COUPLED && types[1] == CD_C_POINT_COUPLED, "aggregate blocks are Coupled"); + CableDyn_GetCoupledMotion(h, q, v, a, n, &err); + CHECK(err == CD_C_OK, "aggregate coupled motion"); + + /* InitDeckAt on the aggregate: the fairleads 1 m outward and 0.5 m down. */ + memcpy(q_host, q, sizeof q); + q_host[0] -= 1.0; + q_host[2] -= 0.5; + q_host[3] += 1.0; + q_host[5] -= 0.5; + CableDyn_InitDeckAt(h, g_mixed, (int)strlen(g_mixed), q_host, MIX_NDOF, &err); + if (err != CD_C_OK) { + report(h, "aggregate InitDeckAt", err); + return 1; + } + CableDyn_GetCoupledMotion(h, q, v, a, n, &err); + CHECK(err == CD_C_OK && memcmp(q, q_host, sizeof q) == 0, "aggregate fairleads start exactly at q0"); + if (loads(h, f, n)) return 1; + printf("aggregate InitDeckAt: fairlead loads (%.1f, %.1f, %.1f) N and (%.1f, %.1f, %.1f) N\n", f[0], f[1], + f[2], f[3], f[4], f[5]); + + /* Bit for bit the statics of the deck with both fairleads moved to q0. */ + CHECK(q_host[0] == -6.0 && q_host[2] == -5.5 && q_host[3] == 6.0 && q_host[5] == -5.5, + "the mixed deck fairleads start at (-5, 0, -5) and (5, 0, -5)"); + if (write_moved_deck(g_mixed, half_moved, "-5.0 0.0 -5.0", "-6.0 0.0 -5.5", 1) || + write_moved_deck(half_moved, moved_deck, " 5.0 0.0 -5.0", " 6.0 0.0 -5.5", 1) || + init_deck(&moved, moved_deck) || loads(moved, f_moved, n)) + return 1; + CHECK(memcmp(f_moved, f, sizeof f) == 0, "aggregate InitDeckAt equals InitDeck of the moved deck"); + remove(half_moved); + remove(moved_deck); + CableDyn_Close(&moved, &err); + + CableDyn_InitDeckAt(h, g_mixed, (int)strlen(g_mixed), q_host, 3, &err); + CableDyn_GetLastError(h, msg, (int)sizeof msg); + CHECK(err == CD_C_BAD_INPUT && strstr(msg, "coupled_positions") != NULL, + "a wrong aggregate q0 length is rejected"); + CableDyn_Close(&h, &err); + + return check_save_restore(g_mixed, q_host, MIX_NDOF, MIX_DT, 0.2, 5, 10, "aggregate route"); +} + +int main(int argc, char **argv) +{ + double q_host[BOX_NHOST]; + + if (argc != 3) { + fputs("usage: test_c_api_host_coupling \n", stderr); + return 2; + } + g_box = argv[1]; + g_mixed = argv[2]; + box_fairleads(HOST_Z, q_host); + if (check_version() || check_point_layout() || check_raw_layout() || check_init_at() || + check_save_restore(g_box, q_host, BOX_NHOST, BOX_DT, 0.005, 7, 20, "point route") || check_aggregate()) { + return 1; + } + puts("PASS: CableDyn C API host coupling"); + return 0; +} diff --git a/tests/test_c_api_shared.c b/tests/test_c_api_shared.c index 8ea81bef..ecd17d8a 100644 --- a/tests/test_c_api_shared.c +++ b/tests/test_c_api_shared.c @@ -148,7 +148,8 @@ static int check_deck_step(const char *deck) double *xyz = NULL, *seg = NULL, pos[3], force[3], fair = 0.0, ten0 = 0.0; const char *token = "FairTen1"; - CHECK(CableDyn_GetAbiMinor() >= 1 && CABLEDYN_CAPI_ABI_MINOR == 1, "ABI minor level"); + CHECK(CableDyn_GetAbiMinor() >= 1 && CableDyn_GetAbiMinor() == CABLEDYN_CAPI_ABI_MINOR, + "ABI minor level"); nl = CableDyn_NObjects(m, CD_C_OBJ_LINE, &err); CHECK(err == CD_C_OK && nl == CableDyn_NLines(m, &err), "line inventory"); np = CableDyn_NObjects(m, CD_C_OBJ_POINT, &err); diff --git a/tests/test_c_api_stack.c b/tests/test_c_api_stack.c index 65184a16..585ce850 100644 --- a/tests/test_c_api_stack.c +++ b/tests/test_c_api_stack.c @@ -11,10 +11,12 @@ * MSVC-linked program is 1 MB), so the library must not rely on the stack reserve of * a CableDyn executable. For every deck this program starts one thread whose stack * is KiB and, on that thread, creates a handle, initialises the deck, - * steps it with the coupled points held (coupling step
s), evaluates the coupled - * loads, and closes the handle. A stack overflow ends the process (SIGSEGV on POSIX - * systems, STATUS_STACK_OVERFLOW on Windows), which fails the test. On Windows the - * deepest stack page the thread touched is also reported. + * steps it with the coupled points held (coupling step
s), saves the state, takes + * one more step and restores it (the whole-model copies of CableDyn_SaveState and + * CableDyn_RestoreState), evaluates the coupled loads, and closes the handle. A stack + * overflow ends the process (SIGSEGV on POSIX systems, STATUS_STACK_OVERFLOW on + * Windows), which fails the test. On Windows the deepest stack page the thread touched + * is also reported. */ #include "CableDyn_CAPI.h" @@ -115,6 +117,21 @@ static void run_deck(struct deck_task *t) goto done; } } + CableDyn_SaveState(m, &err); + if (err != CD_C_OK) { + fail(t, m, "state save failed"); + goto done; + } + CableDyn_Step(m, t->dt, q, v, a, ndof, &converged, &stalled, &n_iter, &err); + if (err != CD_C_OK || !converged || stalled) { + fail(t, m, "held-point step after the save did not converge"); + goto done; + } + CableDyn_RestoreState(m, &err); + if (err != CD_C_OK) { + fail(t, m, "state restore failed"); + goto done; + } CableDyn_CalcOutput(m, loads, ndof, &err); if (err != CD_C_OK) { fail(t, m, "output failed"); From 3fb1c002bc1ed56945b87b56b0546be32a50aeb3 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 16 Oct 2026 13:13:17 +0900 Subject: [PATCH 2/3] fix(capi): save slot on failures; unambiguous q0; ordering test - CableDyn_SaveState marks the slot invalid while it overwrites it, so an allocation failure inside the copy cannot leave a half-written slot marked valid. - InitLine and InitLines build the point system in place, so a failed call loses the previous model; it now discards the saved state as well, and the manual limits the atomic re-initialisation guarantee to InitDeck and InitDeckAt. - Python init_deck_at rejects a (3, 3) q0 as ambiguous (column- or row-per-point) and asks for the flat form. - A test with the Coupled rows listed before the Fixed ones checks that the coupled blocks, the host DOFs and the loads follow the POINTS table order. Signed-off-by: Jae Hoon Seo --- doc/capi.rst | 10 ++++++---- python/cabledyn/model.py | 9 ++++++++- python/tests/test_host_coupling.py | 26 ++++++++++++++++++++++++++ src/CableDyn_CAPI.f90 | 9 +++++++++ 4 files changed, 49 insertions(+), 5 deletions(-) diff --git a/doc/capi.rst b/doc/capi.rst index ff05fcb5..226c2646 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -333,10 +333,12 @@ These rules apply to every entry point. The Python package uses the same array o ``CD_C_BAD_HANDLE`` and is never dereferenced. One limitation is inherent to a pointer ABI: if a stale copy's address has been reused by a new ``Create``, the copy cannot be told apart from the new handle. -* **Re-initialisation is atomic.** Calling any ``Init*`` function on an initialised handle - replaces the model only on success. If the new initialisation fails, the previous model is - kept unchanged, and so is the state saved by ``CableDyn_SaveState``; a successful one - discards that save. +* **Re-initialisation is atomic for decks.** Calling ``CableDyn_InitDeck`` or + ``CableDyn_InitDeckAt`` on an initialised handle replaces the model only on success. If the + new initialisation fails, the previous model is kept unchanged, and so is the state saved by + ``CableDyn_SaveState``; a successful one discards that save. ``CableDyn_InitLine`` and + ``CableDyn_InitLines`` build the model in place: after a failure the handle must be + initialised again, and the saved state is discarded. * **Time.** The library keeps no clock. Only ``dt`` enters ``CableDyn_Step``, and the host owns the time line. diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index 24556785..1181cfb4 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -230,13 +230,20 @@ def init_deck_at(self, deck: str | os.PathLike[str], q0: ArrayInput) -> None: (``n_coupled_dof`` values, the layout of :meth:`step`; the Fixed, Free and Connect blocks are not read) or the Coupled/Vessel blocks alone, in coupled-vector order (the ``MoorDyn_Init`` layout of a points-only deck), - flat or column-per-point ``(3, n)``. See :meth:`coupled_layout`. A failed + flat or column-per-point ``(3, n)`` (a ``(3, 3)`` array is rejected as + ambiguous: pass three points flat). See :meth:`coupled_layout`. A failed initialization keeps any previously initialized model. """ _encode_path(deck) # rejects a NUL before any file-system call resolved = Path(deck).expanduser().resolve() path = _encode_path(resolved) q = _as_real_array(q0, "q0") + if q.ndim == 2 and q.shape == (3, 3): + # three points: column-per-point and row-per-point look alike + raise ValueError( + "q0 of shape (3, 3) is ambiguous (column-per-point or row-per-point); " + "pass it flat, x1 y1 z1 x2 y2 z2 ..." + ) if q.ndim == 2 and q.shape[0] == 3: q = np.ascontiguousarray(q.reshape(-1, order="F")) if q.ndim != 1 or q.size % 3 != 0: diff --git a/python/tests/test_host_coupling.py b/python/tests/test_host_coupling.py index 5fadf22e..de29d58c 100644 --- a/python/tests/test_host_coupling.py +++ b/python/tests/test_host_coupling.py @@ -92,10 +92,36 @@ def test_init_deck_at_host_positions_has_no_transient(): assert peak > 1.0e-2 +def test_point_route_order_follows_the_points_table(tmp_path): + """Coupled rows listed before the Fixed ones: the blocks follow the POINTS table order.""" + lines = BOX.read_text(encoding="utf-8").splitlines() + rows = [i for i, ln in enumerate(lines) if ln.split()[:2] in (["1", "Fixed"], ["5", "Coupled"])] + fixed_at, coupled_at = rows[0], rows[1] + reordered = ( + lines[:fixed_at] + + lines[coupled_at : coupled_at + 4] + + lines[fixed_at : fixed_at + 4] + + lines[coupled_at + 4 :] + ) + deck = tmp_path / "box_reordered.dat" + deck.write_text("\n".join(reordered) + "\n", encoding="utf-8") + with CableDyn() as model: + model.init_deck_at(deck, BOX_FAIRLEADS) + assert model.coupled_layout() == tuple((p, "coupled") for p in (5, 6, 7, 8)) + tuple( + (p, "fixed") for p in (1, 2, 3, 4) + ) + assert model.host_dofs().tolist() == list(range(12)) + f = model.calc_output() + # line 4's fairlead (point 8) is block 3 now + np.testing.assert_allclose(f[9:12], [0.3026, -0.0761, -0.4114], atol=1.0e-4) + + def test_init_deck_at_rejections_keep_the_model(): with CableDyn(BOX) as model: before = model.calc_output() with pytest.raises(CableDynError, match="coupled_positions"): + model.init_deck_at(BOX, BOX_FAIRLEADS[:, :3].reshape(-1, order="F")) + with pytest.raises(ValueError, match="ambiguous"): model.init_deck_at(BOX, BOX_FAIRLEADS[:, :3]) with pytest.raises(ValueError, match="finite"): model.init_deck_at(BOX, np.full(12, np.nan)) diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index ceb68053..75a7df33 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -694,6 +694,9 @@ SUBROUTINE init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_co CALL set_point_line_map(h, [1]) CALL store_status(h, err_stat, '') ELSE + ! the raw-array route builds the point system in place: after a failure the previous + ! model is gone, and with it the state saved for it + CALL drop_saved_state(h) CALL store_status(h, err_stat, 'CableDyn_InitLine: '//TRIM(fast_em)) END IF END SUBROUTINE init_line_serialised @@ -890,6 +893,9 @@ SUBROUTINE init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fix CALL set_point_line_map(h, [(i, i=1, INT(n_lines))]) CALL store_status(h, err_stat, '') ELSE + ! the raw-array route builds the point system in place: after a failure the previous + ! model is gone, and with it the state saved for it + CALL drop_saved_state(h) CALL store_status(h, err_stat, 'CableDyn_InitLines: '//TRIM(em)) END IF END SUBROUTINE init_lines_serialised @@ -1742,6 +1748,9 @@ SUBROUTINE CableDyn_SaveState(handle, err_stat) BIND(C, NAME='CableDyn_SaveState INTEGER :: stat IF (.NOT. query_ready(handle, h, 'CableDyn_SaveState', err_stat)) RETURN + ! the slot is invalid while it is overwritten (an allocation failure inside the copy + ! must not leave a half-written slot marked valid) + h%has_saved = .FALSE. IF (h%use_agg) THEN IF (.NOT. ALLOCATED(h%saved_agg)) THEN ! On the heap, as the live aggregate: the host chooses this thread's stack size. From 5e177cc3a888187281f08cc2495d76428b8126bc Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 16 Oct 2026 15:27:33 +0900 Subject: [PATCH 3/3] fix(capi): save-slot lifetime, outer-corrector keying, docs and tests - The save follows the live model: a successful Init* discards it, a failed InitDeck/InitDeckAt keeps it with the model, and a failed InitLine/InitLines discards it unless an aggregate model stays live; the handle comment, header, manual, coupling boundary note and Python docs now say the same. - The host call sequence keys the save on the start-of-step time (t_prev - t_saved >= 1e-3 dt), so a pass retried with a smaller dt restores instead of saving an already advanced model, as foamMooring's sixDoFMooringRestraints does. - MoorDyn comparisons: 6 values per coupled body or cantilevered rod and 3 per pinned rod or point; the Coupled-only q0 equals MoorDyn's X when every Coupled point is attached to a line; the moment conventions of the two foamMooring restraints are named. Only the aggregate slot allocation returns CD_C_ALLOC_FAIL; an out-of-memory copy aborts. - Tests: the save across failed inits on both routes, save/restore on a raw InitLine handle, bit-identity with viscoelastic + friction, Syrope and a Free point with UpdatePointFluidFields between save and restore, InitDeckAt rejections (a shared fairlead given two positions, End A below its anchor) and the full form on a Free-point deck, InitDeckAt on the 1 MiB stack, and test decks removed on every exit. Signed-off-by: Jae Hoon Seo --- CMakeLists.txt | 14 +- doc/api_python.rst | 18 +- doc/capi.rst | 58 ++- doc/coupling_boundary.md | 10 +- doc/python.rst | 40 +- python/cabledyn/model.py | 21 +- python/tests/test_host_coupling.py | 24 ++ src/CableDyn_CAPI.f90 | 59 ++- src/CableDyn_CAPI.h | 5 +- tests/test_c_api_host_coupling.c | 599 +++++++++++++++++++++++------ tests/test_c_api_stack.c | 21 +- 11 files changed, 681 insertions(+), 188 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c04ed5c6..e0006d2e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1083,7 +1083,9 @@ set_tests_properties(c_api_shared PROPERTIES LABELS "c;unit;capi;shared") # The host-coupling calls of ABI 1.2 through the public header and the shared library: # initialization at the host's positions (the foamMooring EsfLOWC box, whose fairleads start -# below their deck coordinates), state save/restore on both routes, and the layout query. +# below their deck coordinates), state save/restore on both routes, on a raw-array handle and +# with viscoelastic, Syrope, seabed-friction and point fluid-field state, the save-slot +# lifetime across failed initializations, and the layout query. add_executable(test_c_api_host_coupling tests/test_c_api_host_coupling.c) target_include_directories(test_c_api_host_coupling PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") target_link_libraries(test_c_api_host_coupling PRIVATE cabledyn_shared) @@ -1092,7 +1094,10 @@ if(NOT WIN32) endif() add_test(NAME c_api_host_coupling COMMAND test_c_api_host_coupling ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/foam_esflowc_box_points.dat - ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/host_coupling_chain_cable.dat) + ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/host_coupling_chain_cable.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/ve_polyester_catenary_mooring.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/syrope_polyester_mooring.dat + ${CMAKE_CURRENT_SOURCE_DIR}/examples/clump_weight_free_point.dat) set_tests_properties(c_api_host_coupling PROPERTIES LABELS "c;unit;capi;shared;dynamic") find_package(Threads QUIET) @@ -1108,8 +1113,9 @@ else() endif() # Portable (Win32 or POSIX threads) stack bound of the shared library: each deck is -# initialised, stepped, saved and restored, and evaluated on a thread with a 1 MiB stack (a -# host program, not CableDyn, chooses the stack of the threads that call the library). The +# initialised, stepped, saved and restored, evaluated, and initialised again at its coupled +# positions (CableDyn_InitDeckAt) on a thread with a 1 MiB stack (a host program, not +# CableDyn, chooses the stack of the threads that call the library). The # decks are a 2048-element finite-EI cable (12294 DOFs), an EI=0 + finite-EI aggregate, and an # EI=0 mooring; a stack need that grew with the model would overflow here. add_executable(test_c_api_stack tests/test_c_api_stack.c) diff --git a/doc/api_python.rst b/doc/api_python.rst index 4502dc4a..671d10b6 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -527,11 +527,17 @@ library is located. Array ordering, frames, and units at the coupling boundary f :param q0: Either the full coupled vector of the deck (``n_coupled_dof`` values, the layout :meth:`step` uses; the ``Fixed``, ``Free`` and ``Connect`` blocks are not read), or the ``Coupled``/``Vessel`` blocks alone, in coupled-vector order (the ``MoorDyn_Init`` - layout of a points-only deck). Flat or column-per-point ``(3, n)``; positions in m. + layout of a deck whose coupled objects are points that are all attached to lines: a + ``Coupled`` point attached to no line has no block here). Flat, or column-per-point + ``(3, n)`` with ``n`` ≠ 3; positions in m. :type q0: array_like :raises CableDynError: if the deck fails to initialise, or ``q0`` does not match its - coupled points. A failed initialisation keeps any previously initialised model. - :raises ValueError: if ``q0`` is not finite or its length is not a multiple of 3. + coupled points. A failed initialisation keeps any previously initialised model and its + saved state. + :raises ValueError: if the path is rejected as by :meth:`init_deck`; if ``q0`` is a ``(3, 3)`` + array, which is ambiguous (column-per-point or row-per-point: pass three points flat); + if ``q0`` has any other shape than flat or ``(3, n)``, or a length that is not a + multiple of 3; or if ``q0`` is not finite. :raises RuntimeError: if the loaded library predates ABI 1 minor extension 2. .. py:method:: save_state() @@ -541,8 +547,10 @@ library is located. Array ordering, frames, and units at the coupling boundary f it (``CableDyn_SaveState``, ``CableDyn_RestoreState``). The slot is a copy of every line, point, body and rod state with its solver history. A restore keeps the slot, so one save serves every outer corrector of a host time step, and a restore followed by a step is - bit-identical to taking that step from the saved state directly. A new initialisation - discards the slot. + bit-identical to taking that step from the saved state directly. Save when a host time + step starts after the previous one was accepted, and restore on every repeated pass from + the same start time, whatever its ``dt`` (:ref:`capi-host-coupling`). A successful + initialisation discards the slot; a failed one keeps it with the model. :raises CableDynError: on an uninitialised model, or from :meth:`restore_state` when nothing was saved since the model was initialised. diff --git a/doc/capi.rst b/doc/capi.rst index 226c2646..3bdcab8d 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -337,8 +337,10 @@ These rules apply to every entry point. The Python package uses the same array o ``CableDyn_InitDeckAt`` on an initialised handle replaces the model only on success. If the new initialisation fails, the previous model is kept unchanged, and so is the state saved by ``CableDyn_SaveState``; a successful one discards that save. ``CableDyn_InitLine`` and - ``CableDyn_InitLines`` build the model in place: after a failure the handle must be - initialised again, and the saved state is discarded. + ``CableDyn_InitLines`` build the point model in place: after a failure the handle must be + initialised again, and the saved state is discarded. The one exception is a handle whose + deck model runs on the coupled aggregate (finite-EI lines, bodies or rods): a failed + ``InitLine``/``InitLines`` leaves that model live, and its saved state with it. * **Time.** The library keeps no clock. Only ``dt`` enters ``CableDyn_Step``, and the host owns the time line. @@ -513,8 +515,10 @@ is the standalone value of the deck moved to the CFD positions, (0.3026, -0.0761 ``q0`` is one of two vectors; its length selects which: * the ``Coupled``/``Vessel`` blocks alone, in coupled-vector order: 3 values per host point. - This is the layout of MoorDyn's ``X`` for a deck whose coupled objects are points, and the - one a host that knows only its fairleads can build before any handle exists; + This is the layout of MoorDyn's ``X`` for a deck whose coupled objects are points that are + all attached to lines (MoorDyn's ``X`` also holds a ``Coupled`` point attached to no line, + which has no block here), and the one a host that knows only its fairleads can build before + any handle exists; * the full coupled vector, ``CableDyn_NCoupledDOF`` values. Its ``Fixed``, ``Free`` and ``Connect`` blocks are not read. @@ -525,8 +529,8 @@ after the initialisation; the line interiors stay at rest. Step 2: build the coupled vector from the layout ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -*MoorDyn.* The coupled vector holds the coupled objects and nothing else: 3 values per coupled -point, 6 per coupled body or rod. +*MoorDyn.* The coupled vector holds the coupled objects and nothing else: 6 values per coupled +body or cantilevered rod, 3 per pinned rod or coupled point. *CableDyn.* On the point route (decks of ``EI = 0`` lines) the vector has a block for every line-bound point, ``Fixed`` anchors included, in ``POINTS`` order. On the aggregate route @@ -594,6 +598,17 @@ every later pass. A restore followed by a step is bit-identical to taking that s saved state directly, and any number of steps may lie between the save and the restore (the sub-steps of Step 6). A successful ``Init*`` call discards the save. +Key the save on the start time of the pass, :math:`t_{prev} = t - \Delta t`, not on its end +time :math:`t`. Save when a pass starts later than the saved state, which happens once the +previous step has been accepted and the model stands at :math:`t_{prev}`; restore before +every other pass, which starts from the same :math:`t_{prev}` whatever its :math:`\Delta t`. +A host that rejects a step and retries it with a smaller :math:`\Delta t` thus restores: keyed +on :math:`t`, the retry would look like a new step and save a model that the rejected pass has +already advanced. Compare the start times with a tolerance, as foamMooring's +``sixDoFMooringRestraints`` ``moorDynR2`` does (a new step when +:math:`t_{prev} - t_{saved} \ge 10^{-3}\,\Delta t`), since :math:`t - \Delta t` is subject to +round-off. + The names differ from MoorDyn's file calls: ``MoorDyn_SaveState`` writes the state to a file, ``CableDyn_SaveState`` keeps it in memory. Serialising the state to a caller buffer or a restart file (``MoorDyn_Serialize``, ``MoorDyn_Save``/``MoorDyn_Load``) is not supported. A @@ -611,9 +626,12 @@ with reference point :math:`r`, sum the ``CD_C_POINT_COUPLED`` blocks only: F = \sum_k f_k, \qquad M_r = \sum_k (x_k - r) \times f_k -where :math:`x_k` is the fairlead position the step was taken with. A host that applies the -moment about the global origin (foamMooring's ``moorDynR2`` in point mode accumulates -:math:`x_k \times f_k`) uses :math:`r = 0`. Do not add the anchor blocks. +where :math:`x_k` is the fairlead position the step was taken with. The reference point +depends on the host's restraint: foamMooring's ``moorDynR2`` of ``rigidBodyMooringRestraints`` +in point mode accumulates :math:`x_k \times f_k`, the moment about the global origin +(:math:`r = 0`), while its ``moorDynR2`` of ``sixDoFMooringRestraints`` accumulates +:math:`(x_k - x_{CoR}) \times f_k` about the body's centre of rotation +(:math:`r = x_{CoR}`). Do not add the anchor blocks. Step 6: fixed step on the aggregate route ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ @@ -649,11 +667,11 @@ the deck's ``POINTS`` order of the ``Coupled`` points) the host computes from th CableDyn_GetCoupledMotion(h, q, v, a, n, &err); /* seed every block */ t_saved = -HUGE_VAL; /* nothing saved yet */ - /* Every call: time t = t_prev + dt of the current pass of the host time step. */ - if (t != t_saved) { /* first pass: the model is at t_prev */ + /* Every call: a pass of the host time step from t_prev = t - dt to t. */ + if (t_prev - t_saved >= 1.0e-3 * dt) { /* a new step: the model is at t_prev */ CableDyn_SaveState(h, &err); - t_saved = t; - } else { /* a later pass of the same step */ + t_saved = t_prev; + } else { /* a repeated pass from t_saved, any dt */ CableDyn_RestoreState(h, &err); } /* the fairlead motion at t (the END of the step) into the host blocks, in layout order */ @@ -1865,13 +1883,19 @@ correctors. A restore followed by a step is bit-identical to taking that step from the saved state directly, whatever ran between the save and the restore: the slot is a copy of the model -object, independent of the rollback buffers the steps use internally. A successful ``Init*`` -call discards the slot; a failed one keeps it with the model. Both calls return +object, independent of the rollback buffers the steps use internally. The slot follows the +model it was taken from: a successful ``Init*`` call discards it; a failed ``CableDyn_InitDeck`` +or ``CableDyn_InitDeckAt`` keeps it with the model; a failed ``CableDyn_InitLine`` or +``CableDyn_InitLines`` discards it, except on a handle whose model runs on the coupled +aggregate, which stays live with its save (`Calling conventions`_). Both calls return ``CD_C_NOT_INITIALIZED`` before an initialisation, and ``RestoreState`` returns ``CD_C_BAD_INPUT`` when nothing has been saved since the model was initialised. Each call copies the model, so it allocates memory of the size of the model and costs about as much as copying -it; it does no file I/O and follows the threading rules of the other per-handle calls. There is -no serialisation of the state to a caller buffer. +it; it does no file I/O and follows the threading rules of the other per-handle calls. On the +aggregate route ``SaveState`` returns ``CD_C_ALLOC_FAIL`` when the slot itself cannot be +allocated, and the handle then holds no save; running out of memory during the copy of the +model, on either route and in either call, aborts the process, as any Fortran assignment of +allocatable data does. There is no serialisation of the state to a caller buffer. **CableDyn_GetCoupledLayout.** The owner of each 3-DOF block of the coupled vector. diff --git a/doc/coupling_boundary.md b/doc/coupling_boundary.md index 9d2af723..15205cb8 100644 --- a/doc/coupling_boundary.md +++ b/doc/coupling_boundary.md @@ -99,12 +99,16 @@ Rules shared by every entry point: (up to 1024 characters) and copied by `CableDyn_GetLastError`. - `CableDyn_NPoints` returns the column count expected by `CableDyn_UpdatePointFluidFields`; it can exceed `NCoupledDOF/3` when a deck has output-only fixed or coupled points. -- Initialisation is transactional: a failed call leaves the handle as it was (uninitialised, - or holding its previous model). +- Deck initialisation is transactional: a failed `CableDyn_InitDeck` or `CableDyn_InitDeckAt` + leaves the handle as it was (uninitialised, or holding its previous model and the state + saved for it by `CableDyn_SaveState`). `CableDyn_InitLine` and `CableDyn_InitLines` build the + point model in place: after a failure the handle must be initialised again and its saved + state is discarded, except on a handle whose deck model runs on the coupled aggregate, which + stays live with its saved state. A successful initialisation discards the saved state. The interface ships as the versioned shared library `libcabledyn` (`cabledyn.dll` in an Intel Fortran and MSVC build; CMake target `cabledyn_shared`) with the installed header; it reports -CableDyn 0.1.1 and C ABI version 1, minor extension 1. The Python package uses the same library. +CableDyn 0.1.1 and C ABI version 1, minor extension 2. The Python package uses the same library. ### Concurrency diff --git a/doc/python.rst b/doc/python.rst index 42e0342d..c6def699 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -773,21 +773,37 @@ kinematics enter through :meth:`~cabledyn.CableDyn.update_point_fluid_fields`, a the coupled kinematics of every step. 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 (:ref:`capi-host-coupling` -explains each call and how it differs from MoorDyn): +positions and rewinds it between the passes of an iterated time step. The save is keyed on the +start time of the pass, so a pass retried with a smaller ``dt`` restores as well +(:ref:`capi-host-coupling` explains each call and how it differs from MoorDyn): .. code-block:: python - with CableDyn() as model: - model.init_deck_at("mooring.dat", fairleads) # (3, n): the Coupled points, layout order - q, v, a = model.get_coupled_motion() - host = model.host_dofs() # the "coupled" blocks of model.coupled_layout() - model.save_state() # at the first pass of a host time step - for corrector in range(3): - model.restore_state() # every pass restarts from the saved state - q[host], v[host], a[host] = x_end, v_end, a_end # flat host motion at t + dt - model.step(dt, q, v, a) - loads = model.calc_output()[host].reshape(3, -1, order="F") + import math + + from cabledyn import CableDyn + + + class Mooring: + def __init__(self, deck, fairleads): + # fairleads: the Coupled points in layout order, flat or (3, n) with n != 3 + self.model = CableDyn() + self.model.init_deck_at(deck, fairleads) + self.q, self.v, self.a = self.model.get_coupled_motion() + self.host = self.model.host_dofs() # the "coupled" blocks of coupled_layout() + self.t_saved = -math.inf # nothing saved yet + + def solve(self, t, dt, x_end, v_end, a_end): + """One pass of the host time step from t - dt to t (flat host motion at t).""" + t_prev = t - dt + if t_prev - self.t_saved >= 1e-3 * dt: # a new step: the model is at t_prev + self.model.save_state() + self.t_saved = t_prev + else: # a repeated pass from the same start time, whatever its dt + self.model.restore_state() + self.q[self.host], self.v[self.host], self.a[self.host] = x_end, v_end, a_end + self.model.step(dt, self.q, self.v, self.a) + return self.model.calc_output()[self.host].reshape(3, -1, order="F") Objects and output channels ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index 1181cfb4..e05e8b24 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -229,10 +229,12 @@ def init_deck_at(self, deck: str | os.PathLike[str], q0: ArrayInput) -> None: a transient. ``q0`` is either the full coupled vector of the deck (``n_coupled_dof`` values, the layout of :meth:`step`; the Fixed, Free and Connect blocks are not read) or the Coupled/Vessel blocks alone, in - coupled-vector order (the ``MoorDyn_Init`` layout of a points-only deck), - flat or column-per-point ``(3, n)`` (a ``(3, 3)`` array is rejected as - ambiguous: pass three points flat). See :meth:`coupled_layout`. A failed - initialization keeps any previously initialized model. + coupled-vector order (the ``MoorDyn_Init`` layout of a deck whose coupled + objects are points that are all attached to lines: a Coupled point attached + to no line has no block here), flat or column-per-point ``(3, n)`` with + ``n != 3`` (a ``(3, 3)`` array is rejected as ambiguous: pass three points + flat). See :meth:`coupled_layout`. A failed initialization keeps any + previously initialized model and its saved state. """ _encode_path(deck) # rejects a NUL before any file-system call resolved = Path(deck).expanduser().resolve() @@ -504,14 +506,19 @@ def save_state(self) -> None: """Save the whole model and :attr:`time` into the handle's single save slot. The slot is a deep copy of the model (every line, point, body and rod - state with its solver history), replacing any earlier save. It stays valid - until the next initialization, so one save serves every outer corrector of - a host time step (see :meth:`restore_state`). + state with its solver history), replacing any earlier save. A successful + initialization discards it and a failed one keeps it with the model, so one + save serves every outer corrector of a host time step (see + :meth:`restore_state`). Save when a host time step starts after the + previous one was accepted, and restore on every repeated pass from the + same start time, whatever its ``dt``. """ with self._lock: self._require_host_coupling() status = c_int() _lib.CableDyn_SaveState(self._handle, byref(status)) + if status.value != 0: + self._saved_time = None # a failed save leaves no save in the slot self._check("CableDyn_SaveState", status.value) self._saved_time = self._time diff --git a/python/tests/test_host_coupling.py b/python/tests/test_host_coupling.py index de29d58c..1c104f57 100644 --- a/python/tests/test_host_coupling.py +++ b/python/tests/test_host_coupling.py @@ -165,6 +165,30 @@ def test_save_restore_is_bit_identical(deck, q_host, dt, amp): model.restore_state() +def test_a_failed_initialization_keeps_the_save(tmp_path): + """A failed init_deck/init_deck_at keeps the model and its save; restore still works.""" + dt = 1.0e-3 + with CableDyn() as model, CableDyn() as ref: + model.init_deck_at(BOX, BOX_FAIRLEADS) + ref.init_deck_at(BOX, BOX_FAIRLEADS) + q0, _, _ = model.get_coupled_motion() + model.save_state() + model.step(dt, *_motion(model, q0, 0.02, dt)) + with pytest.raises(CableDynError): + model.init_deck(tmp_path / "missing.dat") + with pytest.raises(CableDynError, match="coupled_positions"): + model.init_deck_at(BOX, BOX_FAIRLEADS[:, :2]) + with pytest.raises(ValueError, match="column-per-point"): + model.init_deck_at(BOX, BOX_FAIRLEADS.T) # (4, 3): row per point + model.restore_state() + assert model.time == 0.0 + for s in range(1, 4): + motion = _motion(model, q0, 0.005, s * dt) + model.step(dt, *motion) + ref.step(dt, *motion) + assert np.array_equal(model.calc_output(), ref.calc_output()) + + def test_aggregate_layout_holds_only_the_coupled_points(): with CableDyn(MIXED) as model: assert model.coupled_layout() == ((2, "coupled"), (4, "coupled")) diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 75a7df33..7f50c96f 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -164,7 +164,9 @@ END FUNCTION cabledyn_blas_threads_once TYPE(CD_HFMF_ModuleType), ALLOCATABLE :: no_cables(:) ! The single save slot of CableDyn_SaveState/RestoreState: a deep copy of the route's model ! object (the point system, or the aggregate on the heap) and the aggregate's committed time, - ! valid (has_saved) from a SaveState until the next successful initialization. + ! valid (has_saved) from a SaveState until a successful initialization or a failed + ! InitLine/InitLines on a handle whose live model is a point system (drop_point_save_on_failure); + ! a failed InitDeck/InitDeckAt, or a failed InitLine/InitLines on an aggregate handle, keeps it. LOGICAL :: has_saved = .FALSE. TYPE(CD_FAST_ModuleType) :: saved_fast TYPE(CD_AGG_ModuleType), ALLOCATABLE :: saved_agg @@ -595,13 +597,29 @@ SUBROUTINE CableDyn_InitLine(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_conn_ REAL(C_DOUBLE), VALUE :: rho_inf INTEGER(C_INT), INTENT(OUT) :: err_stat - IF (.NOT. blas_runtime_ready(handle, 'CableDyn_InitLine', err_stat)) RETURN - CALL cabledyn_input_lock() - CALL init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_conn_ptr, l0_ptr, ea_ptr, rho_a_ptr, & - fixed_dofs_ptr, n_fixed, tension_only, rho_inf, err_stat) - CALL cabledyn_input_unlock() + IF (blas_runtime_ready(handle, 'CableDyn_InitLine', err_stat)) THEN + CALL cabledyn_input_lock() + CALL init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_conn_ptr, l0_ptr, ea_ptr, rho_a_ptr, & + fixed_dofs_ptr, n_fixed, tension_only, rho_inf, err_stat) + CALL cabledyn_input_unlock() + END IF + CALL drop_point_save_on_failure(handle, err_stat) END SUBROUTINE CableDyn_InitLine + SUBROUTINE drop_point_save_on_failure(handle, err_stat) + !! After a failed CableDyn_InitLine/InitLines the save slot follows the live model. These + !! calls rebuild the point system in place, so a handle whose live model is that point + !! system must be initialized again and loses the state saved for it. On a handle whose live + !! model is an aggregate (a deck with finite-EI lines, bodies or rods), the failure leaves + !! the aggregate live (use_agg is cleared only on success) and the save with it. + TYPE(C_PTR), VALUE :: handle + INTEGER(C_INT), INTENT(IN) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + IF (err_stat == CD_C_OK) RETURN + IF (validate_handle(handle, h) /= CD_C_OK) RETURN + IF (.NOT. h%use_agg) CALL drop_saved_state(h) + END SUBROUTINE drop_point_save_on_failure + SUBROUTINE init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_conn_ptr, l0_ptr, ea_ptr, & rho_a_ptr, fixed_dofs_ptr, n_fixed, tension_only, rho_inf, err_stat) !! CableDyn_InitLine body; the caller holds the process-wide input lock. @@ -694,9 +712,6 @@ SUBROUTINE init_line_serialised(handle, n_nodes, n_elem, q0_ptr, v0_ptr, elem_co CALL set_point_line_map(h, [1]) CALL store_status(h, err_stat, '') ELSE - ! the raw-array route builds the point system in place: after a failure the previous - ! model is gone, and with it the state saved for it - CALL drop_saved_state(h) CALL store_status(h, err_stat, 'CableDyn_InitLine: '//TRIM(fast_em)) END IF END SUBROUTINE init_line_serialised @@ -716,12 +731,14 @@ SUBROUTINE CableDyn_InitLines(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fixed_ REAL(C_DOUBLE), VALUE :: rho_inf INTEGER(C_INT), INTENT(OUT) :: err_stat - IF (.NOT. blas_runtime_ready(handle, 'CableDyn_InitLines', err_stat)) RETURN - CALL cabledyn_input_lock() - CALL init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fixed_ptr, q0_ptr, v0_ptr, & - elem_conn_ptr, l0_ptr, ea_ptr, rho_a_ptr, fixed_dofs_ptr, & - coupled_map_ptr, n_coupled_map, tension_only, rho_inf, err_stat) - CALL cabledyn_input_unlock() + IF (blas_runtime_ready(handle, 'CableDyn_InitLines', err_stat)) THEN + CALL cabledyn_input_lock() + CALL init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fixed_ptr, q0_ptr, v0_ptr, & + elem_conn_ptr, l0_ptr, ea_ptr, rho_a_ptr, fixed_dofs_ptr, & + coupled_map_ptr, n_coupled_map, tension_only, rho_inf, err_stat) + CALL cabledyn_input_unlock() + END IF + CALL drop_point_save_on_failure(handle, err_stat) END SUBROUTINE CableDyn_InitLines SUBROUTINE init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fixed_ptr, q0_ptr, v0_ptr, & @@ -893,9 +910,6 @@ SUBROUTINE init_lines_serialised(handle, n_lines, n_nodes_ptr, n_elem_ptr, n_fix CALL set_point_line_map(h, [(i, i=1, INT(n_lines))]) CALL store_status(h, err_stat, '') ELSE - ! the raw-array route builds the point system in place: after a failure the previous - ! model is gone, and with it the state saved for it - CALL drop_saved_state(h) CALL store_status(h, err_stat, 'CableDyn_InitLines: '//TRIM(em)) END IF END SUBROUTINE init_lines_serialised @@ -1741,15 +1755,18 @@ SUBROUTINE CableDyn_SaveState(handle, err_stat) BIND(C, NAME='CableDyn_SaveState !! friction states, the last converged step), the point fluid fields, and on the aggregate !! route the committed time. 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. - !! It stays valid until the next successful Init* call. + !! A successful Init* call discards the slot; a failed InitDeck/InitDeckAt keeps it with the + !! model, and a failed InitLine/InitLines discards it unless the handle's live model is an + !! aggregate (drop_point_save_on_failure). Only the allocation of the aggregate slot itself + !! returns CD_C_ALLOC_FAIL (the handle then holds no save); running out of memory inside + !! the copy, an intrinsic assignment of allocatable components, aborts the process. TYPE(C_PTR), VALUE :: handle INTEGER(C_INT), INTENT(OUT) :: err_stat TYPE(CD_C_Handle), POINTER :: h INTEGER :: stat IF (.NOT. query_ready(handle, h, 'CableDyn_SaveState', err_stat)) RETURN - ! the slot is invalid while it is overwritten (an allocation failure inside the copy - ! must not leave a half-written slot marked valid) + ! the slot is invalid while it is overwritten, and stays so if its allocation fails h%has_saved = .FALSE. IF (h%use_agg) THEN IF (.NOT. ALLOCATED(h%saved_agg)) THEN diff --git a/src/CableDyn_CAPI.h b/src/CableDyn_CAPI.h index b8f57bd3..31253a3a 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -200,7 +200,10 @@ void CableDyn_InitDeckAt(void *handle, const char *deck_path, int deck_path_len, /* One save slot per handle: SaveState copies the whole model (replacing an * earlier save); RestoreState returns to it and keeps it, so one save serves * every outer corrector of a host time step. A restore followed by a step is - * bit-identical to stepping from the saved state. Valid until the next Init*. */ + * bit-identical to stepping from the saved state. A successful Init* call + * discards the save; a failed InitDeck/InitDeckAt keeps it with the model; a + * failed InitLine/InitLines discards it, except on a handle whose deck model + * runs on the coupled aggregate, which stays live with its save. */ void CableDyn_SaveState(void *handle, int *err_stat); void CableDyn_RestoreState(void *handle, int *err_stat); /* Owner of each 3-DOF block k of the coupled vector (DOFs 3k..3k+2): deck diff --git a/tests/test_c_api_host_coupling.c b/tests/test_c_api_host_coupling.c index 2cbfb050..d85fbec6 100644 --- a/tests/test_c_api_host_coupling.c +++ b/tests/test_c_api_host_coupling.c @@ -4,22 +4,35 @@ * and the shared library. * * Usage: test_c_api_host_coupling + * * * box_points.dat is the foamMooring EsfLOWC box (four slack EI=0 lines, point * route) whose fairleads sit at z = -0.062 m in the deck while the CFD box * starts with them at z = -0.077 m. mixed_chain_cable.dat is an EI=0 chain - * plus a finite-EI cable (aggregate route, staged steps). The test checks: + * plus a finite-EI cable (aggregate route, staged steps). viscoelastic.dat is a + * grounded viscoelastic (ElasticMod 2) catenary, run with seabed friction + * switched on in a copy; syrope.dat is a taut Syrope line; free_point.dat is a + * chain with a Free clump weight. The test checks: * - CableDyn_InitDeckAt solves the statics at the host positions: on both * routes the result equals CableDyn_InitDeck of the deck moved there bit for * bit; for the box, line 4's fairlead load is the standalone value and held * fairleads stay at rest, while InitDeck at the deck positions followed by - * steps at the host positions rings; + * steps at the host positions rings; the full-vector form ignores the Fixed + * and Free blocks; * - CableDyn_SaveState/RestoreState: a restore followed by steps reproduces a - * fresh model taking the same steps bit for bit, on both routes, also after - * several steps between save and restore and after repeated restores; + * fresh model taking the same steps bit for bit, on both routes, on a raw-array + * (InitLine) handle, with viscoelastic, Syrope and seabed-friction states, and + * with point fluid fields changed between the save and the restore; also + * after several steps between save and restore and after repeated restores; + * - the save slot follows the live model: a failed InitDeck/InitDeckAt keeps + * it, a failed InitLine/InitLines drops it on a point-route handle and keeps + * it on an aggregate handle, and a successful initialization drops it; * - CableDyn_GetCoupledLayout reports anchors and fairleads on the point route * and only the Coupled points on the aggregate route; - * - the fail-closed rejections of the new calls. + * - the fail-closed rejections of the new calls, including a point shared by an + * EI=0 and a finite-EI line given two positions and a line End A moved below + * its Fixed anchor. + * The decks this test writes are removed on every exit path. */ #include "CableDyn_CAPI.h" @@ -36,6 +49,15 @@ } \ } while (0) +/* CHECK for functions that release resources at their label done. */ +#define REQUIRE(condition, message) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "FAIL: %s\n", (message)); \ + goto done; \ + } \ + } while (0) + #define BOX_NDOF 24 /* 8 line-bound points: 4 Fixed anchors, 4 Coupled fairleads */ #define BOX_NHOST 12 /* the 4 Coupled fairleads */ #define BOX_DT 1.0e-3 @@ -46,8 +68,29 @@ #define MIX_NDOF 6 /* the chain and the cable fairleads; the anchors are not coupled */ #define MIX_DT 0.01 +#define RAW_NODES 6 +#define RAW_ELEM 5 + static const char *g_box; static const char *g_mixed; +static const char *g_visco; +static const char *g_syrope; +static const char *g_free; + +/* Every deck the test writes (into the working directory); removed on every exit path. */ +#define BOX_MOVED "capi_host_box_moved.dat" +#define MIXED_HALF "capi_host_mixed_half.dat" +#define MIXED_MOVED "capi_host_mixed_moved.dat" +#define MIXED_SHARED_HALF "capi_host_mixed_shared_half.dat" +#define MIXED_SHARED "capi_host_mixed_shared.dat" +#define VISCO_FRICTION "capi_host_visco_friction.dat" +static const char *const g_written[] = {BOX_MOVED, MIXED_HALF, MIXED_MOVED, + MIXED_SHARED_HALF, MIXED_SHARED, VISCO_FRICTION}; + +static void remove_written_decks(void) +{ + for (size_t i = 0; i < sizeof g_written / sizeof g_written[0]; ++i) remove(g_written[i]); +} static void report(void *h, const char *where, int err) { @@ -105,6 +148,13 @@ static int loads(void *h, double *f, int n) return 0; } +static int last_error_has(void *h, const char *text) +{ + char msg[1025]; + CableDyn_GetLastError(h, msg, (int)sizeof msg); + return strstr(msg, text) != NULL; +} + /* The box fairlead positions (deck x, y) at height z, as the 4 Coupled blocks. */ static void box_fairleads(double z, double *q_host) { @@ -116,32 +166,41 @@ static void box_fairleads(double z, double *q_host) } } -/* Copy a deck with the Coupled points moved (the standalone reference of InitDeckAt): on every - * line naming a Coupled point, the text old_text is replaced by new_text of the same length; - * n_moved such lines must be found. */ -static int write_moved_deck(const char *in_path, const char *out_path, const char *old_text, - const char *new_text, int n_moved) +/* Copy a deck with one text replaced: on every line that contains old_text (and row_key, unless + * row_key is NULL), the first old_text becomes new_text; n_expected such lines must be found. */ +static int edit_deck(const char *in_path, const char *out_path, const char *old_text, const char *new_text, + const char *row_key, int n_expected) { FILE *in = fopen(in_path, "r"), *out = NULL; - char line[512]; - int moved = 0; - CHECK(in != NULL && strlen(old_text) == strlen(new_text), "open the deck to move"); + char line[512], edited[1024]; + int n = 0; + + if (in == NULL) { + fprintf(stderr, "FAIL: open the deck %s\n", in_path); + return 1; + } out = fopen(out_path, "w"); if (out == NULL) { fclose(in); - CHECK(0, "write the moved deck"); + fprintf(stderr, "FAIL: write the deck %s\n", out_path); + return 1; } while (fgets(line, (int)sizeof line, in) != NULL) { char *at = strstr(line, old_text); - if (at != NULL && strstr(line, "Coupled") != NULL) { - memcpy(at, new_text, strlen(new_text)); - ++moved; + if (at != NULL && (row_key == NULL || strstr(line, row_key) != NULL)) { + snprintf(edited, sizeof edited, "%.*s%s%s", (int)(at - line), line, new_text, at + strlen(old_text)); + fputs(edited, out); + ++n; + } else { + fputs(line, out); } - fputs(line, out); } fclose(in); fclose(out); - CHECK(moved == n_moved, "the deck names its Coupled points as expected"); + if (n != n_expected) { + fprintf(stderr, "FAIL: %s: %d lines with \"%s\", expected %d\n", in_path, n, old_text, n_expected); + return 1; + } return 0; } @@ -174,6 +233,32 @@ static int check_point_layout(void) return 0; } +/* A taut raw-array line: RAW_NODES nodes 2 m apart on the x axis, 1 % pretension, both end + * nodes fixed (the coupled vector: node 1, then node RAW_NODES). */ +static void init_raw_line(void *h, double l0_each, double rho_inf, int *err) +{ + double q0[3 * RAW_NODES] = {0.0}, v0[3 * RAW_NODES] = {0.0}, l0[RAW_ELEM], ea[RAW_ELEM], rho_a[RAW_ELEM]; + int elem_conn[2 * RAW_ELEM]; + const int fixed[6] = {1, 2, 3, 3 * RAW_NODES - 2, 3 * RAW_NODES - 1, 3 * RAW_NODES}; + for (int i = 0; i < RAW_NODES; ++i) q0[3 * i] = 2.0 * i; + for (int e = 0; e < RAW_ELEM; ++e) { + elem_conn[2 * e] = e + 1; + elem_conn[2 * e + 1] = e + 2; + l0[e] = l0_each; + ea[e] = 1.0e6; + rho_a[e] = 10.0; + } + CableDyn_InitLine(h, RAW_NODES, RAW_ELEM, q0, v0, elem_conn, l0, ea, rho_a, fixed, 6, 1, rho_inf, err); +} + +/* CableDyn_InitLines rejected before it reads any array (no line). */ +static void init_no_lines(void *h, int *err) +{ + const int counts[1] = {0}; + CableDyn_InitLines(h, 0, counts, counts, counts, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, 0, 1, 0.8, + err); +} + static int check_raw_layout(void) { void *h = NULL; @@ -181,7 +266,6 @@ static int check_raw_layout(void) const double q0[6] = {0.0, 0.0, 0.0, 10.0, 0.0, 0.0}, v0[6] = {0.0}; const int elem_conn[2] = {1, 2}, fixed[6] = {1, 2, 3, 4, 5, 6}; const double l0[1] = {10.0}, ea[1] = {1.0e6}, rho_a[1] = {10.0}; - char msg[256]; CableDyn_Create(&h, &err); CableDyn_GetCoupledLayout(h, ids, types, 2, &err); @@ -193,77 +277,201 @@ static int check_raw_layout(void) CableDyn_InitLine(h, 2, 1, q0, v0, elem_conn, l0, ea, rho_a, fixed, 6, 1, 0.8, &err); CHECK(err == CD_C_OK, "raw line init"); CableDyn_GetCoupledLayout(h, ids, types, 2, &err); - CableDyn_GetLastError(h, msg, (int)sizeof msg); - CHECK(err == CD_C_BAD_INPUT && strstr(msg, "raw arrays") != NULL, "a raw-array handle has no layout"); + CHECK(err == CD_C_BAD_INPUT && last_error_has(h, "raw arrays"), "a raw-array handle has no layout"); CableDyn_GetCoupledLayout((void *)&bogus, ids, types, 2, &err); CHECK(err == CD_C_BAD_HANDLE, "foreign handle"); CableDyn_Close(&h, &err); return 0; } +/* The raw line's far end swinging sideways: amplitude amp, sample time t. */ +static void raw_motion(const double *q0, double amp, double t, double *q, double *v, double *a) +{ + const double w = 2.0 * acos(-1.0); + memcpy(q, q0, 6 * sizeof *q); + memset(v, 0, 6 * sizeof *v); + memset(a, 0, 6 * sizeof *a); + q[4] += amp * sin(w * t); + v[4] = amp * w * cos(w * t); + a[4] = -amp * w * w * sin(w * t); +} + +/* Save/restore on a raw-array (InitLine) handle: two trial correctors, restore, steps; bit for + * bit a fresh line taking the same steps. A successful InitLine drops the save. */ +static int check_raw_save_restore(void) +{ + void *h = NULL, *ref = NULL; + double q0[6], q[6], v[6], a[6], f[6], f_ref[6], mq[6], mv[6], ma[6], rq[6], rv[6], ra[6]; + int err = -1, status = 1, n; + const double dt = 1.0e-3; + + CableDyn_Create(&h, &err); + REQUIRE(err == CD_C_OK, "create"); + CableDyn_Create(&ref, &err); + REQUIRE(err == CD_C_OK, "create"); + init_raw_line(h, 1.98, 0.8, &err); + REQUIRE(err == CD_C_OK, "raw line init"); + init_raw_line(ref, 1.98, 0.8, &err); + REQUIRE(err == CD_C_OK, "raw line init"); + n = CableDyn_NCoupledDOF(h, &err); + REQUIRE(err == CD_C_OK && n == 6, "the raw coupled vector is the fixed-DOF list"); + CableDyn_GetCoupledMotion(h, q0, v, a, n, &err); + REQUIRE(err == CD_C_OK, "raw coupled motion"); + CableDyn_SaveState(h, &err); + REQUIRE(err == CD_C_OK, "raw save"); + for (int corrector = 1; corrector <= 2; ++corrector) { + for (int s = 1; s <= 6; ++s) { + raw_motion(q0, 0.1 * corrector, s * dt, q, v, a); + if (step(h, dt, q, v, a, n)) goto done; + } + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_OK, "raw restore"); + } + for (int s = 1; s <= 20; ++s) { + raw_motion(q0, 0.05, s * dt, q, v, a); + if (step(h, dt, q, v, a, n) || step(ref, dt, q, v, a, n)) goto done; + if (loads(h, f, n) || loads(ref, f_ref, n)) goto done; + CableDyn_GetCoupledMotion(h, mq, mv, ma, n, &err); + CableDyn_GetCoupledMotion(ref, rq, rv, ra, n, &err); + REQUIRE(memcmp(f, f_ref, sizeof f) == 0 && memcmp(mq, rq, sizeof mq) == 0 && + memcmp(mv, rv, sizeof mv) == 0 && memcmp(ma, ra, sizeof ma) == 0, + "raw-array route: restore + steps equal the fresh line bit for bit"); + } + REQUIRE(fabs(f[4]) > 1.0e-3, "the swinging end loads the raw line sideways"); + printf("raw-array route: 6 trial steps x 2 correctors, restore, 20 steps: bit-identical to the fresh " + "line\n"); + init_raw_line(h, 1.98, 0.8, &err); + REQUIRE(err == CD_C_OK, "raw line re-initialization"); + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_BAD_INPUT, "a successful InitLine drops the save"); + status = 0; + +done: + CableDyn_Close(&h, &err); + CableDyn_Close(&ref, &err); + return status; +} + +/* The save follows the live model: a failed InitLine/InitLines drops it on a point-route handle + * (whose point model those calls rebuild in place) and keeps it on an aggregate handle, whose + * model stays live; the aggregate then goes on bit for bit from the restored state. */ +static int check_save_after_failed_raw_init(void) +{ + void *h = NULL, *ref = NULL; + double q0[MIX_NDOF], q[MIX_NDOF], v[MIX_NDOF] = {0.0}, a[MIX_NDOF] = {0.0}, f[MIX_NDOF], f_ref[MIX_NDOF]; + int err = -1, status = 1; + + /* point route */ + if (init_deck(&h, g_box)) goto done; + CableDyn_SaveState(h, &err); + REQUIRE(err == CD_C_OK, "point-route save"); + init_raw_line(h, 1.98, 2.0, &err); /* rho_inf out of range */ + REQUIRE(err == CD_C_BAD_INPUT, "a failed InitLine"); + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "no state has been saved"), + "a failed InitLine drops the save of a point-route handle"); + CableDyn_SaveState(h, &err); + REQUIRE(err == CD_C_OK, "point-route save"); + init_no_lines(h, &err); + REQUIRE(err == CD_C_BAD_INPUT, "a failed InitLines"); + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "no state has been saved"), + "a failed InitLines drops the save of a point-route handle"); + CableDyn_Close(&h, &err); + + /* aggregate route */ + if (init_deck(&h, g_mixed) || init_deck(&ref, g_mixed)) goto done; + CableDyn_GetCoupledMotion(h, q0, v, a, MIX_NDOF, &err); + REQUIRE(err == CD_C_OK, "aggregate coupled motion"); + CableDyn_SaveState(h, &err); + REQUIRE(err == CD_C_OK, "aggregate save"); + memcpy(q, q0, sizeof q); + q[0] -= 0.3; + q[3] += 0.3; + if (step(h, MIX_DT, q, v, a, MIX_NDOF)) goto done; + init_raw_line(h, 1.98, 2.0, &err); /* rejected by the argument checks */ + REQUIRE(err == CD_C_BAD_INPUT, "a failed InitLine on the aggregate handle"); + init_raw_line(h, 0.0, 0.8, &err); /* rejected by the line model */ + REQUIRE(err != CD_C_OK, "a failed InitLine (zero length) on the aggregate handle"); + init_no_lines(h, &err); + REQUIRE(err == CD_C_BAD_INPUT, "a failed InitLines on the aggregate handle"); + REQUIRE(CableDyn_IsInitialized(h) && CableDyn_NCoupledDOF(h, &err) == MIX_NDOF, + "the aggregate model stays live"); + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_OK, "a failed InitLine/InitLines keeps the save of an aggregate handle"); + memcpy(q, q0, sizeof q); + q[0] -= 0.05; + if (step(h, MIX_DT, q, v, a, MIX_NDOF) || step(ref, MIX_DT, q, v, a, MIX_NDOF)) goto done; + if (loads(h, f, MIX_NDOF) || loads(ref, f_ref, MIX_NDOF)) goto done; + REQUIRE(memcmp(f, f_ref, sizeof f) == 0, "the restored aggregate steps as the fresh model"); + status = 0; + +done: + CableDyn_Close(&h, &err); + CableDyn_Close(&ref, &err); + return status; +} + static int check_init_at(void) { void *at = NULL, *full = NULL, *moved = NULL, *plain = NULL; double q_host[BOX_NHOST], q_full[BOX_NDOF], q[BOX_NDOF], v[BOX_NDOF] = {0.0}, a[BOX_NDOF] = {0.0}; double f_at[BOX_NDOF], f_full[BOX_NDOF], f_moved[BOX_NDOF], f[BOX_NDOF], f_plain0[BOX_NDOF]; double drift = 0.0, ring = 0.0, ring_end = 0.0; - int err = -1, n, ids[8], types[8]; - const char *moved_deck = "capi_host_box_moved.dat"; + int err = -1, n = BOX_NDOF, ids[8], types[8], status = 1; /* standalone CableDyn with the deck moved to z = -0.077 (MoorDyn: 0.3034, -0.0763, -0.4136) */ const double f4_ref[3] = {0.3026, -0.0761, -0.4114}; - char msg[1025]; box_fairleads(HOST_Z, q_host); - if (init_deck_at(&at, g_box, q_host, BOX_NHOST)) return 1; + if (init_deck_at(&at, g_box, q_host, BOX_NHOST)) goto done; n = CableDyn_NCoupledDOF(at, &err); - CHECK(err == CD_C_OK && n == BOX_NDOF, "InitDeckAt keeps the route's coupled vector"); + REQUIRE(err == CD_C_OK && n == BOX_NDOF, "InitDeckAt keeps the route's coupled vector"); CableDyn_GetCoupledLayout(at, ids, types, 8, &err); - CHECK(err == CD_C_OK && ids[7] == 8 && types[7] == CD_C_POINT_COUPLED, "layout after InitDeckAt"); + REQUIRE(err == CD_C_OK && ids[7] == 8 && types[7] == CD_C_POINT_COUPLED, "layout after InitDeckAt"); CableDyn_GetCoupledMotion(at, q, v, a, n, &err); - CHECK(err == CD_C_OK, "coupled motion after InitDeckAt"); + REQUIRE(err == CD_C_OK, "coupled motion after InitDeckAt"); for (int p = 0; p < 4; ++p) { - CHECK(q[3 * p + 2] == -0.5, "the anchors stay at the deck coordinates"); - CHECK(memcmp(&q[12 + 3 * p], &q_host[3 * p], 3 * sizeof(double)) == 0, - "the fairleads start exactly at q0"); + REQUIRE(q[3 * p + 2] == -0.5, "the anchors stay at the deck coordinates"); + REQUIRE(memcmp(&q[12 + 3 * p], &q_host[3 * p], 3 * sizeof(double)) == 0, + "the fairleads start exactly at q0"); } - for (int i = 0; i < n; ++i) CHECK(v[i] == 0.0 && a[i] == 0.0, "the statics start at rest"); - if (loads(at, f_at, n)) return 1; + for (int i = 0; i < n; ++i) REQUIRE(v[i] == 0.0 && a[i] == 0.0, "the statics start at rest"); + if (loads(at, f_at, n)) goto done; printf("InitDeckAt z=%.3f: line 4 fairlead load (%.4f, %.4f, %.4f) N\n", HOST_Z, f_at[21], f_at[22], f_at[23]); for (int c = 0; c < 3; ++c) - CHECK(fabs(f_at[21 + c] - f4_ref[c]) < 1.0e-4, "line 4 fairlead load matches the standalone statics"); + REQUIRE(fabs(f_at[21 + c] - f4_ref[c]) < 1.0e-4, "line 4 fairlead load matches the standalone statics"); /* The full-vector form: the Fixed blocks are not read. */ memcpy(q_full, q, sizeof q_full); for (int i = 0; i < 12; ++i) q_full[i] = 1.0e3; - if (init_deck_at(&full, g_box, q_full, BOX_NDOF)) return 1; - if (loads(full, f_full, n)) return 1; - CHECK(memcmp(f_full, f_at, sizeof f_at) == 0, "full and Coupled-only q0 give the same statics"); + if (init_deck_at(&full, g_box, q_full, BOX_NDOF)) goto done; + if (loads(full, f_full, n)) goto done; + REQUIRE(memcmp(f_full, f_at, sizeof f_at) == 0, "full and Coupled-only q0 give the same statics"); CableDyn_GetCoupledMotion(full, q_full, v, a, n, &err); - CHECK(err == CD_C_OK && memcmp(q_full, q, sizeof q) == 0, "the full form ignores the Fixed blocks"); + REQUIRE(err == CD_C_OK && memcmp(q_full, q, sizeof q) == 0, "the full form ignores the Fixed blocks"); /* Bit for bit the statics of the deck moved to the host positions. */ - if (write_moved_deck(g_box, moved_deck, "-0.062", "-0.077", 4)) return 1; - if (init_deck(&moved, moved_deck)) return 1; - if (loads(moved, f_moved, n)) return 1; - CHECK(memcmp(f_moved, f_at, sizeof f_at) == 0, "InitDeckAt equals InitDeck of the moved deck"); - remove(moved_deck); + if (edit_deck(g_box, BOX_MOVED, "-0.062", "-0.077", "Coupled", 4)) goto done; + if (init_deck(&moved, BOX_MOVED)) goto done; + if (loads(moved, f_moved, n)) goto done; + REQUIRE(memcmp(f_moved, f_at, sizeof f_at) == 0, "InitDeckAt equals InitDeck of the moved deck"); /* Held at the host positions, the InitDeckAt model stays at equilibrium for 1 s. */ memset(v, 0, sizeof v); memset(a, 0, sizeof a); for (int s = 1; s <= BOX_NSTEP; ++s) { - if (step(at, BOX_DT, q, v, a, n) || loads(at, f, n)) return 1; + if (step(at, BOX_DT, q, v, a, n) || loads(at, f, n)) goto done; for (int i = 12; i < n; ++i) drift = fmax(drift, fabs(f[i] - f_at[i])); } printf("InitDeckAt, fairleads held 1 s: max fairlead load change %.3e N\n", drift); - CHECK(drift < 1.0e-6, "no start-up transient after InitDeckAt"); + REQUIRE(drift < 1.0e-6, "no start-up transient after InitDeckAt"); /* InitDeck at the deck positions, then held at the host positions: the start-up transient. */ - if (init_deck(&plain, g_box)) return 1; - if (loads(plain, f_plain0, n)) return 1; + if (init_deck(&plain, g_box)) goto done; + if (loads(plain, f_plain0, n)) goto done; for (int s = 1; s <= BOX_NSTEP; ++s) { - if (step(plain, BOX_DT, q, v, a, n) || loads(plain, f, n)) return 1; + if (step(plain, BOX_DT, q, v, a, n) || loads(plain, f, n)) goto done; for (int i = 12; i < n; ++i) { ring = fmax(ring, fabs(f[i] - f_at[i])); if (s == BOX_NSTEP) ring_end = fmax(ring_end, fabs(f[i] - f_at[i])); @@ -274,29 +482,121 @@ static int check_init_at(void) printf("InitDeck, then held at z=%.3f for 1 s: max deviation from the equilibrium %.3e N " "(%.3e N at 1 s)\n", HOST_Z, ring, ring_end); - CHECK(ring > 1.0e4 * drift && ring > 1.0e-2, "the plain start rings"); + REQUIRE(ring > 1.0e4 * drift && ring > 1.0e-2, "the plain start rings"); /* Rejections keep the previous model. */ CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, 9, &err); - CableDyn_GetLastError(at, msg, (int)sizeof msg); - CHECK(err == CD_C_BAD_INPUT && strstr(msg, "coupled_positions") != NULL, "a wrong q0 length is rejected"); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(at, "coupled_positions"), "a wrong q0 length is rejected"); CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, 13, &err); - CHECK(err == CD_C_BAD_INPUT, "a q0 length that is not a multiple of 3 is rejected"); + REQUIRE(err == CD_C_BAD_INPUT, "a q0 length that is not a multiple of 3 is rejected"); CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), NULL, BOX_NHOST, &err); - CHECK(err == CD_C_BAD_INPUT, "a NULL q0 is rejected"); + REQUIRE(err == CD_C_BAD_INPUT, "a NULL q0 is rejected"); q_host[5] = NAN; CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), q_host, BOX_NHOST, &err); - CHECK(err == CD_C_BAD_INPUT, "a non-finite q0 is rejected"); + REQUIRE(err == CD_C_BAD_INPUT, "a non-finite q0 is rejected"); CableDyn_InitDeckAt(at, g_box, (int)strlen(g_box), NULL, 0, &err); - CHECK(err == CD_C_BAD_INPUT, "an empty q0 is rejected for a deck with Coupled points"); - CHECK(CableDyn_IsInitialized(at) && CableDyn_NCoupledDOF(at, &err) == BOX_NDOF, - "a rejected InitDeckAt keeps the model"); + REQUIRE(err == CD_C_BAD_INPUT, "an empty q0 is rejected for a deck with Coupled points"); + REQUIRE(CableDyn_IsInitialized(at) && CableDyn_NCoupledDOF(at, &err) == BOX_NDOF, + "a rejected InitDeckAt keeps the model"); + status = 0; +done: CableDyn_Close(&at, &err); CableDyn_Close(&full, &err); CableDyn_Close(&moved, &err); CableDyn_Close(&plain, &err); - return 0; + return status; +} + +/* The full-vector form on a deck with a Free point: the Free block is not read, and the Free + * point is solved to its static balance. */ +static int check_free_point_full_form(void) +{ + void *only = NULL, *full = NULL; + const double q_host[3] = {0.5, 0.0, -0.5}; + double q[6], v[6], a[6], q_full[6], f[6], f_full[6]; + int err = -1, ids[2], types[2], status = 1; + + if (init_deck_at(&only, g_free, q_host, 3)) goto done; + REQUIRE(CableDyn_NCoupledDOF(only, &err) == 6, "the Coupled and the Free point have a block each"); + CableDyn_GetCoupledLayout(only, ids, types, 2, &err); + REQUIRE(err == CD_C_OK && ids[0] == 1 && types[0] == CD_C_POINT_COUPLED && ids[1] == 2 && + types[1] == CD_C_POINT_FREE, + "free-point deck layout: the Coupled point, then the Free point"); + CableDyn_GetCoupledMotion(only, q, v, a, 6, &err); + REQUIRE(err == CD_C_OK && memcmp(q, q_host, sizeof q_host) == 0, "the Coupled point starts at q0"); + if (loads(only, f, 6)) goto done; + memcpy(q_full, q, sizeof q); + q_full[3] = q_full[4] = q_full[5] = 1.0e3; + if (init_deck_at(&full, g_free, q_full, 6)) goto done; + if (loads(full, f_full, 6)) goto done; + CableDyn_GetCoupledMotion(full, q_full, v, a, 6, &err); + REQUIRE(err == CD_C_OK && memcmp(q_full, q, sizeof q) == 0 && memcmp(f_full, f, sizeof f) == 0, + "the full form ignores the Free block and equals the Coupled-only form"); + status = 0; + +done: + CableDyn_Close(&only, &err); + CableDyn_Close(&full, &err); + return status; +} + +/* A point shared by an EI=0 and a finite-EI line has two blocks on the aggregate route; q0 must + * give both the same position. The mixed deck is edited so that the cable hangs from the chain + * fairlead 2 (its anchor moved so that the cable keeps its geometry). */ +static int check_shared_point(void) +{ + void *h = NULL; + double q[MIX_NDOF], v[MIX_NDOF], a[MIX_NDOF]; + int err = -1, n, ids[2], types[2], status = 1; + + if (edit_deck(g_mixed, MIXED_SHARED_HALF, "2 4 3", "2 2 3", NULL, 1) || + edit_deck(MIXED_SHARED_HALF, MIXED_SHARED, "3 Fixed 95.0", "3 Fixed 85.0", NULL, 1) || + init_deck(&h, MIXED_SHARED)) + goto done; + n = CableDyn_NCoupledDOF(h, &err); + REQUIRE(err == CD_C_OK && n == MIX_NDOF, "the shared fairlead has a block on each route"); + CableDyn_GetCoupledLayout(h, ids, types, 2, &err); + REQUIRE(err == CD_C_OK && ids[0] == 2 && ids[1] == 2, "both blocks belong to point 2"); + CableDyn_GetCoupledMotion(h, q, v, a, n, &err); + REQUIRE(err == CD_C_OK && memcmp(q, q + 3, 3 * sizeof *q) == 0, "the two blocks start together"); + q[0] -= 0.5; + q[3] -= 0.5; + CableDyn_InitDeckAt(h, MIXED_SHARED, (int)strlen(MIXED_SHARED), q, n, &err); + if (err != CD_C_OK) report(h, "InitDeckAt with one position in both blocks", err); + REQUIRE(err == CD_C_OK, "one position in both blocks of the shared point is accepted"); + q[3] -= 0.5; + CableDyn_InitDeckAt(h, MIXED_SHARED, (int)strlen(MIXED_SHARED), q, n, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "same position in both"), + "two positions for the shared point are rejected"); + REQUIRE(CableDyn_IsInitialized(h) && CableDyn_NCoupledDOF(h, &err) == MIX_NDOF, + "the rejection keeps the model"); + status = 0; + +done: + CableDyn_Close(&h, &err); + return status; +} + +/* On a deck without Free or Connect points, q0 may not move a line's End A below its Fixed + * End B anchor (the Syrope line runs from the Vessel fairlead 2 to the anchor 1, both at z = 0). */ +static int check_end_a_below_anchor(void) +{ + void *h = NULL; + double q_host[3] = {20.5, 0.0, 0.0}; + int err = -1, status = 1; + + if (init_deck_at(&h, g_syrope, q_host, 3)) goto done; + q_host[2] = -1.0; + CableDyn_InitDeckAt(h, g_syrope, (int)strlen(g_syrope), q_host, 3, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "coupled_positions displaces a LINE End A"), + "an End A moved below its Fixed anchor is rejected"); + REQUIRE(CableDyn_IsInitialized(h) && CableDyn_NCoupledDOF(h, &err) == 6, "the rejection keeps the model"); + status = 0; + +done: + CableDyn_Close(&h, &err); + return status; } /* A smooth host motion of the Coupled blocks: amplitude amp, sample time t. */ @@ -320,17 +620,41 @@ static void host_motion(const int *types, int nb, const double *q0, double amp, } } +/* A uniform current at every deck point (the point fluid fields), or still water. */ +static int set_fluid(void *h, double u) +{ + int err = -1, np = CableDyn_NPoints(h, &err); + double *vel = calloc((size_t)(3 * np), sizeof *vel), *acc = calloc((size_t)(3 * np), sizeof *acc); + double *zw = calloc((size_t)np, sizeof *zw); + if (vel != NULL && acc != NULL && zw != NULL) { + for (int p = 0; p < np; ++p) vel[3 * p] = u; + CableDyn_UpdatePointFluidFields(h, vel, acc, zw, np, 1025.0, &err); + } + free(vel); + free(acc); + free(zw); + if (err != CD_C_OK) { + report(h, "UpdatePointFluidFields", err); + return 1; + } + return 0; +} + /* Save, take n_trial trial steps, restore (n_restore times) and take n_steps steps; the result must - * equal a fresh model taking the same n_steps steps, bit for bit. */ + * equal a fresh model taking the same n_steps steps, bit for bit. Between the save and the second + * restore, a failed InitDeck and a failed InitDeckAt must keep the save. With fluid set, the trial + * passes run in a current (CableDyn_UpdatePointFluidFields) the reference model never sees. */ static int check_save_restore(const char *deck, const double *q_host, int n_host, double dt, double amp, - int n_trial, int n_steps, const char *route) + int n_trial, int n_steps, int fluid, const char *route) { void *h = NULL, *ref = NULL; - double *q0, *q, *v, *a, *f, *f_ref, *mq, *mv, *ma, *rq, *rv, *ra; - int err = -1, n, *ids, *types, status = 1, n_lines; + double *q0 = NULL, *q = NULL, *v = NULL, *a = NULL, *f = NULL, *f_ref = NULL, *mq = NULL, *mv = NULL; + double *ma = NULL, *rq = NULL, *rv = NULL, *ra = NULL, *xh = NULL, *xr = NULL; + int err = -1, n, *ids = NULL, *types = NULL, status = 1, n_lines; + const char *missing = "capi_host_missing.dat"; char label[160]; - if (init_deck_at(&h, deck, q_host, n_host) || init_deck_at(&ref, deck, q_host, n_host)) return 1; + if (init_deck_at(&h, deck, q_host, n_host) || init_deck_at(&ref, deck, q_host, n_host)) goto done; n = CableDyn_NCoupledDOF(h, &err); n_lines = CableDyn_NLines(h, &err); q0 = calloc((size_t)n, sizeof *q0); @@ -347,23 +671,32 @@ static int check_save_restore(const char *deck, const double *q_host, int n_host ra = calloc((size_t)n, sizeof *ra); ids = calloc((size_t)(n / 3), sizeof *ids); types = calloc((size_t)(n / 3), sizeof *types); - CHECK(q0 && q && v && a && f && f_ref && mq && mv && ma && rq && rv && ra && ids && types, "allocation"); + REQUIRE(q0 && q && v && a && f && f_ref && mq && mv && ma && rq && rv && ra && ids && types, "allocation"); CableDyn_GetCoupledMotion(h, q0, v, a, n, &err); CableDyn_GetCoupledLayout(h, ids, types, n / 3, &err); - CHECK(err == CD_C_OK, "layout"); + REQUIRE(err == CD_C_OK, "layout"); CableDyn_RestoreState(h, &err); - CHECK(err == CD_C_BAD_INPUT, "restore without a save is rejected"); + REQUIRE(err == CD_C_BAD_INPUT, "restore without a save is rejected"); CableDyn_SaveState(h, &err); - CHECK(err == CD_C_OK, "save"); + REQUIRE(err == CD_C_OK, "save"); /* Two outer correctors that take other (larger) trial motions before the final pass. */ for (int corrector = 0; corrector < 2; ++corrector) { + if (fluid && set_fluid(h, 0.5 * (corrector + 1))) goto done; for (int s = 1; s <= n_trial; ++s) { host_motion(types, n / 3, q0, 2.0 * amp * (corrector + 1), s * dt, q, v, a); if (step(h, dt, q, v, a, n)) goto done; } + if (corrector == 1) { + /* Failed re-initializations keep the model and its save. */ + CableDyn_InitDeck(h, missing, (int)strlen(missing), &err); + REQUIRE(err != CD_C_OK, "InitDeck of a missing deck fails"); + CableDyn_InitDeckAt(h, deck, (int)strlen(deck), q_host, n_host - 3, &err); + REQUIRE(err == CD_C_BAD_INPUT, "InitDeckAt with a q0 that fits neither form fails"); + } CableDyn_RestoreState(h, &err); - CHECK(err == CD_C_OK, "restore"); + snprintf(label, sizeof label, "%s: restore (after failed re-initializations on the second)", route); + REQUIRE(err == CD_C_OK, label); } for (int s = 1; s <= n_steps; ++s) { host_motion(types, n / 3, q0, amp, s * dt, q, v, a); @@ -372,34 +705,34 @@ static int check_save_restore(const char *deck, const double *q_host, int n_host CableDyn_GetCoupledMotion(h, mq, mv, ma, n, &err); CableDyn_GetCoupledMotion(ref, rq, rv, ra, n, &err); snprintf(label, sizeof label, "%s: restore + step %d equals the fresh model bit for bit", route, s); - CHECK(memcmp(f, f_ref, (size_t)n * sizeof *f) == 0, label); - CHECK(memcmp(mq, rq, (size_t)n * sizeof *mq) == 0 && memcmp(mv, rv, (size_t)n * sizeof *mv) == 0 && - memcmp(ma, ra, (size_t)n * sizeof *ma) == 0, - label); + REQUIRE(memcmp(f, f_ref, (size_t)n * sizeof *f) == 0, label); + REQUIRE(memcmp(mq, rq, (size_t)n * sizeof *mq) == 0 && memcmp(mv, rv, (size_t)n * sizeof *mv) == 0 && + memcmp(ma, ra, (size_t)n * sizeof *ma) == 0, + label); } /* Every line node agrees too. */ for (int l = 0; l < n_lines; ++l) { int id = 0, nn = 0, sub = 0; - double *xh, *xr; CableDyn_GetObjectInfo(h, CD_C_OBJ_LINE, l, &id, &nn, &sub, &err); xh = calloc((size_t)(3 * nn), sizeof *xh); xr = calloc((size_t)(3 * nn), sizeof *xr); - CHECK(xh && xr, "allocation"); + REQUIRE(xh && xr, "allocation"); CableDyn_GetLineValues(h, l, CD_C_LINE_POSITION, xh, 3 * nn, &err); CableDyn_GetLineValues(ref, l, CD_C_LINE_POSITION, xr, 3 * nn, &err); snprintf(label, sizeof label, "%s: line %d nodes after the restore equal the fresh model", route, id); - CHECK(err == CD_C_OK && memcmp(xh, xr, (size_t)(3 * nn) * sizeof *xh) == 0, label); + REQUIRE(err == CD_C_OK && memcmp(xh, xr, (size_t)(3 * nn) * sizeof *xh) == 0, label); free(xh); free(xr); + xh = xr = NULL; } - printf("%s: %d trial steps x 2 correctors, restore, %d steps: bit-identical to the fresh model\n", route, - n_trial, n_steps); + printf("%s: %d trial steps x 2 correctors%s, restore, %d steps: bit-identical to the fresh model\n", route, + n_trial, fluid ? " in a current" : "", n_steps); - /* A new initialization discards the save. */ + /* A successful initialization discards the save. */ CableDyn_InitDeckAt(h, deck, (int)strlen(deck), q_host, n_host, &err); - CHECK(err == CD_C_OK, "re-initialization"); + REQUIRE(err == CD_C_OK, "re-initialization"); CableDyn_RestoreState(h, &err); - CHECK(err == CD_C_BAD_INPUT, "a re-initialization discards the save"); + REQUIRE(err == CD_C_BAD_INPUT, "a re-initialization discards the save"); status = 0; done: @@ -417,6 +750,8 @@ static int check_save_restore(const char *deck, const double *q_host, int n_host free(ra); free(ids); free(types); + free(xh); + free(xr); CableDyn_Close(&h, &err); CableDyn_Close(&ref, &err); return status; @@ -425,19 +760,17 @@ static int check_save_restore(const char *deck, const double *q_host, int n_host static int check_aggregate(void) { void *h = NULL, *moved = NULL; - int err = -1, n, ids[2], types[2]; + int err = -1, n = MIX_NDOF, ids[2], types[2], status = 1; double q[MIX_NDOF], v[MIX_NDOF], a[MIX_NDOF], q_host[MIX_NDOF], f[MIX_NDOF], f_moved[MIX_NDOF]; - const char *half_moved = "capi_host_mixed_half.dat", *moved_deck = "capi_host_mixed_moved.dat"; - char msg[1025]; - if (init_deck(&h, g_mixed)) return 1; + if (init_deck(&h, g_mixed)) goto done; n = CableDyn_NCoupledDOF(h, &err); - CHECK(err == CD_C_OK && n == MIX_NDOF, "the aggregate coupled vector holds the two fairleads only"); + REQUIRE(err == CD_C_OK && n == MIX_NDOF, "the aggregate coupled vector holds the two fairleads only"); CableDyn_GetCoupledLayout(h, ids, types, 2, &err); - CHECK(err == CD_C_OK && ids[0] == 2 && ids[1] == 4, "aggregate blocks: the chain, then the cable fairlead"); - CHECK(types[0] == CD_C_POINT_COUPLED && types[1] == CD_C_POINT_COUPLED, "aggregate blocks are Coupled"); + REQUIRE(err == CD_C_OK && ids[0] == 2 && ids[1] == 4, "aggregate blocks: the chain, then the cable fairlead"); + REQUIRE(types[0] == CD_C_POINT_COUPLED && types[1] == CD_C_POINT_COUPLED, "aggregate blocks are Coupled"); CableDyn_GetCoupledMotion(h, q, v, a, n, &err); - CHECK(err == CD_C_OK, "aggregate coupled motion"); + REQUIRE(err == CD_C_OK, "aggregate coupled motion"); /* InitDeckAt on the aggregate: the fairleads 1 m outward and 0.5 m down. */ memcpy(q_host, q, sizeof q); @@ -446,52 +779,84 @@ static int check_aggregate(void) q_host[3] += 1.0; q_host[5] -= 0.5; CableDyn_InitDeckAt(h, g_mixed, (int)strlen(g_mixed), q_host, MIX_NDOF, &err); - if (err != CD_C_OK) { - report(h, "aggregate InitDeckAt", err); - return 1; - } + if (err != CD_C_OK) report(h, "aggregate InitDeckAt", err); + REQUIRE(err == CD_C_OK, "aggregate InitDeckAt"); CableDyn_GetCoupledMotion(h, q, v, a, n, &err); - CHECK(err == CD_C_OK && memcmp(q, q_host, sizeof q) == 0, "aggregate fairleads start exactly at q0"); - if (loads(h, f, n)) return 1; + REQUIRE(err == CD_C_OK && memcmp(q, q_host, sizeof q) == 0, "aggregate fairleads start exactly at q0"); + if (loads(h, f, n)) goto done; printf("aggregate InitDeckAt: fairlead loads (%.1f, %.1f, %.1f) N and (%.1f, %.1f, %.1f) N\n", f[0], f[1], f[2], f[3], f[4], f[5]); /* Bit for bit the statics of the deck with both fairleads moved to q0. */ - CHECK(q_host[0] == -6.0 && q_host[2] == -5.5 && q_host[3] == 6.0 && q_host[5] == -5.5, - "the mixed deck fairleads start at (-5, 0, -5) and (5, 0, -5)"); - if (write_moved_deck(g_mixed, half_moved, "-5.0 0.0 -5.0", "-6.0 0.0 -5.5", 1) || - write_moved_deck(half_moved, moved_deck, " 5.0 0.0 -5.0", " 6.0 0.0 -5.5", 1) || - init_deck(&moved, moved_deck) || loads(moved, f_moved, n)) - return 1; - CHECK(memcmp(f_moved, f, sizeof f) == 0, "aggregate InitDeckAt equals InitDeck of the moved deck"); - remove(half_moved); - remove(moved_deck); - CableDyn_Close(&moved, &err); + REQUIRE(q_host[0] == -6.0 && q_host[2] == -5.5 && q_host[3] == 6.0 && q_host[5] == -5.5, + "the mixed deck fairleads start at (-5, 0, -5) and (5, 0, -5)"); + if (edit_deck(g_mixed, MIXED_HALF, "-5.0 0.0 -5.0", "-6.0 0.0 -5.5", "Coupled", 1) || + edit_deck(MIXED_HALF, MIXED_MOVED, " 5.0 0.0 -5.0", " 6.0 0.0 -5.5", "Coupled", 1) || + init_deck(&moved, MIXED_MOVED) || loads(moved, f_moved, n)) + goto done; + REQUIRE(memcmp(f_moved, f, sizeof f) == 0, "aggregate InitDeckAt equals InitDeck of the moved deck"); CableDyn_InitDeckAt(h, g_mixed, (int)strlen(g_mixed), q_host, 3, &err); - CableDyn_GetLastError(h, msg, (int)sizeof msg); - CHECK(err == CD_C_BAD_INPUT && strstr(msg, "coupled_positions") != NULL, - "a wrong aggregate q0 length is rejected"); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "coupled_positions"), + "a wrong aggregate q0 length is rejected"); + CableDyn_Close(&h, &err); + CableDyn_Close(&moved, &err); + + status = check_save_restore(g_mixed, q_host, MIX_NDOF, MIX_DT, 0.2, 5, 10, 0, "aggregate route"); + +done: CableDyn_Close(&h, &err); + CableDyn_Close(&moved, &err); + return status; +} + +/* Viscoelastic, Syrope and seabed-friction states, and point fluid fields, through the save. */ +static int check_state_models(void) +{ + /* the viscoelastic catenary's fairlead (deck: 58, 0, -14) and the Syrope fairlead (deck) */ + const double q_visco[3] = {58.5, 0.0, -14.2}, q_syrope[3] = {20.5, 0.0, 0.0}; + const double q_free[3] = {0.5, 0.0, -0.5}; + + /* seabed friction needs a dynamic deck: dtM and TMax come with it */ + if (edit_deck(g_visco, VISCO_FRICTION, "none frictionMu", + "0.02 dtM\n10.0 TMax\n0.5 frictionMu", NULL, 1)) + return 1; + return check_save_restore(VISCO_FRICTION, q_visco, 3, 0.02, 0.2, 4, 10, 0, + "point route, viscoelastic with seabed friction") || + check_save_restore(g_syrope, q_syrope, 3, 0.01, 0.01, 4, 10, 0, "point route, Syrope") || + check_save_restore(g_free, q_free, 3, 0.01, 0.1, 4, 10, 1, "point route, Free point"); +} - return check_save_restore(g_mixed, q_host, MIX_NDOF, MIX_DT, 0.2, 5, 10, "aggregate route"); +static int run(void) +{ + double q_host[BOX_NHOST]; + box_fairleads(HOST_Z, q_host); + return check_version() || check_point_layout() || check_raw_layout() || check_init_at() || + check_free_point_full_form() || check_shared_point() || check_end_a_below_anchor() || + check_save_restore(g_box, q_host, BOX_NHOST, BOX_DT, 0.005, 7, 20, 0, "point route") || + check_aggregate() || check_raw_save_restore() || check_save_after_failed_raw_init() || + check_state_models(); } int main(int argc, char **argv) { - double q_host[BOX_NHOST]; + int failed; - if (argc != 3) { - fputs("usage: test_c_api_host_coupling \n", stderr); + if (argc != 6) { + fputs("usage: test_c_api_host_coupling " + " \n", + stderr); return 2; } g_box = argv[1]; g_mixed = argv[2]; - box_fairleads(HOST_Z, q_host); - if (check_version() || check_point_layout() || check_raw_layout() || check_init_at() || - check_save_restore(g_box, q_host, BOX_NHOST, BOX_DT, 0.005, 7, 20, "point route") || check_aggregate()) { - return 1; - } + g_visco = argv[3]; + g_syrope = argv[4]; + g_free = argv[5]; + remove_written_decks(); + failed = run(); + remove_written_decks(); + if (failed) return 1; puts("PASS: CableDyn C API host coupling"); return 0; } diff --git a/tests/test_c_api_stack.c b/tests/test_c_api_stack.c index 585ce850..6c12865d 100644 --- a/tests/test_c_api_stack.c +++ b/tests/test_c_api_stack.c @@ -13,7 +13,9 @@ * is KiB and, on that thread, creates a handle, initialises the deck, * steps it with the coupled points held (coupling step
s), saves the state, takes * one more step and restores it (the whole-model copies of CableDyn_SaveState and - * CableDyn_RestoreState), evaluates the coupled loads, and closes the handle. A stack + * CableDyn_RestoreState), evaluates the coupled loads, initialises the deck again with + * the statics at the coupled positions (CableDyn_InitDeckAt with the full coupled + * vector), evaluates the loads again, and closes the handle. A stack * overflow ends the process (SIGSEGV on POSIX systems, STATUS_STACK_OVERFLOW on * Windows), which fails the test. On Windows the deepest stack page the thread touched * is also reported. @@ -143,6 +145,23 @@ static void run_deck(struct deck_task *t) goto done; } } + /* Re-initialise with the statics at the coupled positions (the full-vector q0 form). */ + CableDyn_InitDeckAt(m, t->deck, (int)strlen(t->deck), q, ndof, &err); + if (err != CD_C_OK) { + fail(t, m, "initialisation at the coupled positions failed"); + goto done; + } + CableDyn_CalcOutput(m, loads, ndof, &err); + if (err != CD_C_OK) { + fail(t, m, "output after the initialisation at the coupled positions failed"); + goto done; + } + for (i = 0; i < ndof; ++i) { + if (!isfinite(loads[i])) { + fail(t, NULL, "non-finite coupled load after the initialisation at the coupled positions"); + goto done; + } + } done: free(q);