From 96b93f8adc64786fabc455495c02efe0dc98add4 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 30 Oct 2026 14:52:34 +0900 Subject: [PATCH 1/2] feat(capi): host rotations, torsion through the C API The C API moved line ends by translation only, so it refused every deck with a line restrained in torsion and held a Rigid end connection on its deck direction. C ABI 1 minor extension 3 adds a host that turns its coupled points: - CableDyn_InitDeckRotating: InitDeckAt whose handle passes the host's rotations with every update and step on the aggregate route, as the coupled OpenFAST shell does; it accepts torsion decks. - CableDyn_UpdateRotations: per coupled block the global-to-body DCM and the angular velocity and acceleration, kept until the next call and carried by SaveState/RestoreState; all or nothing. - CableDyn_GetCoupledMoments: the moment each block applies to the host. Python: CableDyn.init_deck_rotating, update_rotations, coupled_moments. New gate c_api_host_rotation (and python test_host_rotation): on a straight torsion line a 60 deg/s roll gives Twist1 = -phi and the quasi-static torque GJ phi / L as the coupled moment (3e-6 N m), a 20 deg feedthrough roll twists the end element alone, a restore steps bit-identically, rejected rotations leave the handle unchanged. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 9 + CMakeLists.txt | 11 + doc/api_python.rst | 55 +++- doc/capabilities.rst | 8 +- doc/capi.rst | 132 +++++++++- doc/driver_format.md | 7 +- doc/openfast.rst | 7 +- doc/troubleshooting.rst | 8 +- python/cabledyn/_lib.py | 30 ++- python/cabledyn/deck_file.py | 3 +- python/cabledyn/model.py | 137 ++++++++-- python/tests/test_host_coupling.py | 2 +- python/tests/test_host_rotation.py | 127 +++++++++ python/tests/test_objects.py | 2 +- release/check_release_metadata.py | 2 +- src/CableDyn_CAPI.f90 | 285 ++++++++++++++++++-- src/CableDyn_CAPI.h | 42 ++- src/CableDyn_DeckDriver.f90 | 3 +- src/cabledyn.def | 3 + src/cabledyn.exp | 3 + src/cabledyn.map | 3 + tests/test_c_api_host_coupling.c | 4 +- tests/test_c_api_host_rotation.c | 404 +++++++++++++++++++++++++++++ 23 files changed, 1216 insertions(+), 71 deletions(-) create mode 100644 python/tests/test_host_rotation.py create mode 100644 tests/test_c_api_host_rotation.c diff --git a/CHANGELOG.md b/CHANGELOG.md index 57797afa..ed89f606 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,15 @@ All notable changes to CableDyn are recorded in this file. The format follows ### Added +- C API host rotations (ABI 1.3): `CableDyn_InitDeckRotating` initialises a handle whose host + passes each coupled point's rotation (`CableDyn_UpdateRotations`: the global-to-body DCM and + the angular velocity and acceleration) with every update and step, so a line restrained in + torsion and a `Rigid` end connection turn with the host, as on the coupled OpenFAST route; a + torsion deck, refused by `CableDyn_InitDeck`/`InitDeckAt`, runs there. + `CableDyn_GetCoupledMoments` returns the moments the lines apply to the host. On a straight + line rolled at 60 deg/s the coupled torque is the quasi-static `GJ phi / L` to 3e-6 N m, and + `SaveState`/`RestoreState` carry the rotations. Python: `CableDyn.init_deck_rotating`, + `update_rotations`, `coupled_moments`. - OpenFAST linearisation with the line dynamics, as MoorDyn-F's: the continuous states are the interior-node positions of every `EI = 0` line (MoorDyn's names and order) and the free degrees of freedom of every finite-EI cable (node positions and tangents), then their diff --git a/CMakeLists.txt b/CMakeLists.txt index ad31d2c0..86650b99 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1240,6 +1240,17 @@ add_test(NAME c_api_host_coupling ${CMAKE_CURRENT_SOURCE_DIR}/examples/clump_weight_free_point.dat) set_tests_properties(c_api_host_coupling PROPERTIES LABELS "c;unit;capi;shared;dynamic") +add_executable(test_c_api_host_rotation tests/test_c_api_host_rotation.c) +target_include_directories(test_c_api_host_rotation PRIVATE "${CMAKE_CURRENT_SOURCE_DIR}/src") +target_link_libraries(test_c_api_host_rotation PRIVATE cabledyn_shared) +if(NOT WIN32) + target_link_libraries(test_c_api_host_rotation PRIVATE m) +endif() +add_test(NAME c_api_host_rotation + COMMAND test_c_api_host_rotation ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/foam_esflowc_box_points.dat + WORKING_DIRECTORY ${CMAKE_BINARY_DIR}) +set_tests_properties(c_api_host_rotation PROPERTIES LABELS "c;unit;capi;shared;dynamic;torsion") + find_package(Threads QUIET) if(Threads_FOUND AND CMAKE_USE_PTHREADS_INIT) add_executable(test_c_api_concurrency tests/test_c_api_concurrency.c) diff --git a/doc/api_python.rst b/doc/api_python.rst index 671d10b6..cfae771e 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -540,6 +540,57 @@ library is located. Array ordering, frames, and units at the coupling boundary f multiple of 3; or if ``q0`` is not finite. :raises RuntimeError: if the loaded library predates ABI 1 minor extension 2. + .. py:method:: init_deck_rotating(deck, q0=None) + + Initialise from a deck for a host that turns the bodies its coupled points are fixed to + (``CableDyn_InitDeckRotating``): :meth:`init_deck_at`, or :meth:`init_deck` with + ``q0=None``, whose model takes each coupled block's rotation from + :meth:`update_rotations` and passes it with every :meth:`update_states` and :meth:`step`. + A line restrained in torsion (``END CONNECTIONS`` ``TorsStiffness``) and a ``Rigid`` bending + end connection then turn with the host at their host-driven end, as on the coupled + OpenFAST route; the other initialisations refuse a deck with a line restrained in torsion. + The rotations start at identity (the deck's axes at the static start) and rest. + + :param deck: Path of the ``.dat`` deck, as for :meth:`init_deck`. + :type deck: str | os.PathLike + :param q0: The host positions of :meth:`init_deck_at`, or ``None`` for the deck positions. + :type q0: array_like | None + :raises CableDynError: as :meth:`init_deck_at`. + :raises ValueError: as :meth:`init_deck_at`. + :raises RuntimeError: if the loaded library predates ABI 1 minor extension 3. + + .. py:method:: update_rotations(dcm, omega, alpha) + + Set the host's rotation of every coupled block for the following :meth:`update_states` + and :meth:`step` calls (``CableDyn_UpdateRotations``); it is kept until the next call and + saved and restored with :meth:`save_state` and :meth:`restore_state`. Only a finite-EI + line's host-driven end uses its block. + + :param dcm: ``(n_block, 3, 3)``: block ``k``'s global-to-body direction cosine matrix, its + rows the body axes in global axes (the OpenFAST mesh orientation); identity is the body + at its static-start attitude. + :type dcm: array_like + :param omega: ``(n_block, 3)``: the body's angular velocity in global axes (rad/s). + :type omega: array_like + :param alpha: ``(n_block, 3)``: the body's angular acceleration in global axes (rad/s²). + :type alpha: array_like + :raises ValueError: if an array has the wrong shape. + :raises CableDynError: on a model not initialised by :meth:`init_deck_rotating`, or a + matrix that is not proper orthogonal to 1e-8 or a non-finite value (the rotations are + then unchanged). + :raises RuntimeError: if the loaded library predates ABI 1 minor extension 3. + + .. py:method:: coupled_moments() + + Return the moments the lines apply to the host at the coupled points + (``CableDyn_GetCoupledMoments``), at the state :meth:`calc_output` reports: block ``k`` + (entries ``3k .. 3k+2``, N m, global axes) is a finite-EI line's torsional and bending + reaction about the coupled point at its host-driven end, zero for the other blocks and for + ``EI = 0`` lines. + + :rtype: numpy.ndarray + :raises RuntimeError: if the loaded library predates ABI 1 minor extension 3. + .. py:method:: save_state() restore_state() @@ -776,7 +827,9 @@ imports without the shared library. .. py:function:: abi_minor() - Return the extension level of ABI 1 of the loaded library: 2 when it also has the + Return the extension level of ABI 1 of the loaded library: 3 when it also has the + host-rotation calls behind :meth:`CableDyn.init_deck_rotating`, + :meth:`CableDyn.update_rotations` and :meth:`CableDyn.coupled_moments`, 2 when it has the host-coupling calls behind :meth:`CableDyn.init_deck_at`, :meth:`CableDyn.save_state` and :meth:`CableDyn.coupled_layout`, 1 when it has the object queries behind :attr:`CableDyn.lines` and :meth:`CableDyn.channel`, 0 for an older library. diff --git a/doc/capabilities.rst b/doc/capabilities.rst index 0568936b..06cb61a7 100644 --- a/doc/capabilities.rst +++ b/doc/capabilities.rst @@ -91,9 +91,11 @@ Line and constitutive capability with turning Rigid6 bodies, ``vesselMotion``/``vesselRAO`` and the ``motionFile`` roll column standalone, and with the platform orientation in coupled OpenFAST and FAST.Farm runs (torque returned to the platform, ``PtfmInit``, checkpoints; see - :doc:`openfast`); ``Torq``/``Twist`` channels and standalone range graphs. Stopped by - name: the standalone mixed ``EI = 0`` + finite-EI aggregate and the C API (which move the - line ends by translation only), OpenFAST linearisation of a line restrained in torsion, + :doc:`openfast`) and through the C API with the host's rotations + (``CableDyn_InitDeckRotating``, :doc:`capi`); ``Torq``/``Twist`` channels and standalone + range graphs. Stopped by name: the standalone mixed ``EI = 0`` + finite-EI aggregate and + ``CableDyn_InitDeck``/``InitDeckAt`` (which move the line ends by translation only), + OpenFAST linearisation of a line restrained in torsion, rod ends, bodies other than Rigid6, lines with ``ATTACHMENTS``, modal analysis, and ``False alpha_force_blend``. Not modelled: seabed friction against twist, anisotropic sections, self-contact of a loop (see :ref:`theory-torsion`) diff --git a/doc/capi.rst b/doc/capi.rst index 77ea8dc7..872978d8 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -29,13 +29,14 @@ A model lives behind an opaque handle. The lifecycle is: .. code-block:: text CableDyn_Create - -> CableDyn_InitDeck | CableDyn_InitDeckAt (initialize; may repeat) - | CableDyn_InitLine | CableDyn_InitLines + -> CableDyn_InitDeck | CableDyn_InitDeckAt | CableDyn_InitDeckRotating + | CableDyn_InitLine | CableDyn_InitLines (initialize; may repeat) -> CableDyn_GetCoupledMotion (read the initial state) -> loop: [CableDyn_SaveState | CableDyn_RestoreState] (host outer correctors) [CableDyn_UpdatePointFluidFields] + [CableDyn_UpdateRotations] (a host that turns) CableDyn_Step(dt, motion at t+dt) - CableDyn_CalcOutput (loads at t+dt) + CableDyn_CalcOutput [, CableDyn_GetCoupledMoments] (loads at t+dt) -> CableDyn_Close A host solver that drives the ``Coupled`` points of a deck, a CFD code in particular, should @@ -83,6 +84,11 @@ MoorDyn's C API. - 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`_) + * - ``CableDyn_InitDeckRotating``, ``CableDyn_UpdateRotations``, + ``CableDyn_GetCoupledMoments`` + - host rotations (ABI 1.3): a host that turns the bodies its coupled points are fixed to, + for lines restrained in torsion and Rigid end connections, and the moments the lines + apply (`Host rotation calls`_) Building and linking -------------------- @@ -237,9 +243,9 @@ ABI and versioning - 1 - the C ABI revision the header describes * - ``CABLEDYN_CAPI_ABI_MINOR`` / ``CableDyn_GetAbiMinor()`` - - 2 + - 3 - additive extensions of ABI 1: 1 adds the `Object queries`_, 2 the - `Host coupling calls`_ + `Host coupling calls`_, 3 the `Host rotation calls`_ * - ``CableDyn_GetVersion(&major, &minor, &patch, &abi)`` - runtime - the same four numbers, reported by the loaded library @@ -270,8 +276,9 @@ 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 the object queries, and -``CableDyn_GetAbiMinor() >= 2`` before calling the host-coupling functions. +``CableDyn_GetAbiMinor() >= 1`` before calling the object queries, +``CableDyn_GetAbiMinor() >= 2`` before calling the host-coupling functions, and +``CableDyn_GetAbiMinor() >= 3`` before calling the host-rotation functions. Calling conventions ------------------- @@ -650,6 +657,33 @@ SI units in the global right-handed frame with z up and still water at :math:`z (:doc:`conventions`), as in MoorDyn. A host in another frame or unit system converts the motion it passes and the loads it receives. +Step 8: a host that turns: torsion and rigid end connections +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The coupled vector carries translations only, which is all an ``EI = 0`` line or a pinned +finite-EI end takes. A finite-EI line restrained in torsion (``END CONNECTIONS`` +``TorsStiffness``) twists with the body's roll about the line, and a ``Rigid`` bending end +connection holds the line's end tangent on a direction fixed to the body: both need the body's +rotation. ``CableDyn_InitDeck`` and ``CableDyn_InitDeckAt`` move the ends by translation only and +refuse a deck with a line restrained in torsion; a ``Rigid`` end connection there keeps its deck +direction. + +*CableDyn.* Initialise with ``CableDyn_InitDeckRotating`` (``CableDyn_InitDeckAt`` that takes +rotations; ``n_q0 = 0`` for the deck positions) and, before every ``CableDyn_UpdateStates`` and +``CableDyn_Step``, pass the body's rotation at the same instant with +``CableDyn_UpdateRotations``: for each block of the coupled vector, the global-to-body +direction cosine matrix (row-major: its rows are the body axes in global axes, the OpenFAST +mesh orientation) and the body's angular velocity and acceleration in global axes. The body's +axes are the deck's at the static start, so the rotation starts at identity; a host whose body +starts rotated passes its rotation relative to that start. ``CableDyn_GetCoupledMoments`` then +returns the moment each line applies to the body about its fairlead, in global axes, beside the +force of ``CableDyn_CalcOutput``; add :math:`\sum_k m_k` to the moment of Step 5. *MoorDyn* has +no line torsion; its coupled bodies and rods take 6 values per object. + +The rotations are inputs, like the motion: an end frame turned by more than a quarter turn +about its line since the last committed step is refused, and ``CableDyn_SaveState``/``CableDyn_RestoreState`` carry the +last rotations with the model. + Call sequence ~~~~~~~~~~~~~ @@ -684,9 +718,12 @@ the deck's ``POINTS`` order of the ``Coupled`` points) the host computes from th } ++j; } + /* a host that turns (CableDyn_InitDeckRotating): the body's rotation at t first */ + /* CableDyn_UpdateRotations(h, dcm, omega, alpha, n / 3, &err); */ 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 */ + /* (+ the moments of CableDyn_GetCoupledMoments over the same blocks, Step 8) */ /* End of the run. */ CableDyn_Close(&h, &err); @@ -1953,6 +1990,87 @@ line-bound points of every type in ``POINTS`` order; on the aggregate route they 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``. +Host rotation calls +~~~~~~~~~~~~~~~~~~~ + +ABI 1 minor extension 3: check ``CableDyn_GetAbiMinor() >= 3`` before calling these. +`Step 8: a host that turns: torsion and rigid end connections`_ shows how they fit together. + +.. code-block:: c + + void CableDyn_InitDeckRotating(void *handle, const char *deck_path, + int deck_path_len, const double *q0, int n_q0, + int *err_stat); + void CableDyn_UpdateRotations(void *handle, const double *dcm, + const double *omega, const double *alpha, + int n_block, int *err_stat); + void CableDyn_GetCoupledMoments(void *handle, double *coupled_moments, + int n_coupled_dof, int *err_stat); + +**CableDyn_InitDeckRotating.** ``CableDyn_InitDeckAt`` for a host that turns its coupled points: +the arguments, routes, rejections, serialisation and transactions are those of +``CableDyn_InitDeckAt``, and ``n_q0 = 0`` (``q0`` may be ``NULL``) solves the statics at the deck +positions, as ``CableDyn_InitDeck``. The handle takes each coupled block's rotation from +``CableDyn_UpdateRotations`` and passes it with every ``CableDyn_UpdateStates`` and +``CableDyn_Step``, so a line restrained in torsion and a ``Rigid`` bending end connection turn +with the host at their host-driven end, as on the coupled OpenFAST route. It accepts a deck +with a line restrained in torsion, which the other ``Init*`` calls refuse. The rotations start +at identity and rest. Another ``Init*`` call makes the handle one that takes no rotations. + +**CableDyn_UpdateRotations.** The rotation of each 3-DOF block of the coupled vector for the +following ``CableDyn_UpdateStates`` and ``CableDyn_Step`` calls; it is kept until the next call. + +.. list-table:: + :header-rows: 1 + :widths: 18 8 12 12 12 38 + + * - Argument + - Dir + - C type + - Length + - NULL + - Meaning + * - ``dcm`` + - in + - ``const double *`` + - ``9 * n_block`` + - only if ``n_block == 0`` + - ``dcm[9k + 3i + j]`` is :math:`R_{ij}` of block ``k``'s global-to-body direction cosine + matrix, row-major: row ``i`` is body axis ``i`` in global axes (the OpenFAST mesh + orientation). Identity is the body at its static-start attitude. + * - ``omega``, ``alpha`` + - in + - ``const double *`` + - ``3 * n_block`` each + - only if ``n_block == 0`` + - the body's angular velocity [rad/s] and acceleration [rad/s²] in global axes + * - ``n_block`` + - in + - ``int`` + - -- + - -- + - must equal ``CableDyn_NCoupledDOF / 3`` + +Only a finite-EI line's host-driven end uses its block; the other blocks (``EI = 0`` lines, +the point route, bodies and rods) are checked and not used. The call is all or nothing: a +handle not initialised by ``CableDyn_InitDeckRotating``, a wrong ``n_block``, a ``NULL`` +pointer, a non-finite entry, and a matrix that is not proper orthogonal to :math:`10^{-8}` +(:math:`\max |R R^T - I|` and :math:`|\det R - 1|`) return ``CD_C_BAD_INPUT`` and leave the +rotations unchanged. The rotations are checked against the lines at the next update or step: +an end frame turned by more than a quarter turn about its line since the last committed state is +refused there. +``CableDyn_SaveState`` saves the rotations with the model and ``CableDyn_RestoreState`` restores +them. + +**CableDyn_GetCoupledMoments.** The moment [N m] each block of the coupled vector applies to the +host, about the coupled point in global axes, at the state ``CableDyn_CalcOutput`` reports +(after an update without a step, against the frozen interior as there). It is a finite-EI +line's torsional and bending reaction at its host-driven end, and zero for the other blocks and +on the point route. ``coupled_moments`` holds ``n_coupled_dof`` values (``NULL`` only if +``n_coupled_dof == 0``), which must equal ``CableDyn_NCoupledDOF``; it is set to zero before the +evaluation and stays zero if the call fails. It is available on any initialised handle, so a +host without rotations can read the moment of a ``Rigid`` end connection at its deck direction. + Examples -------- diff --git a/doc/driver_format.md b/doc/driver_format.md index 905f9d4e..4b26a61a 100644 --- a/doc/driver_format.md +++ b/doc/driver_format.md @@ -865,9 +865,10 @@ Scope. A torsionally restrained line needs a finite-EI line with a `Fixed` End B torsion on an `EI = 0` line, on a rod end or on a `Point3` body, a line with `ATTACHMENTS`, modal analysis (`nModes`), a dynamic or coupled run with `False alpha_force_blend`, any restrained end (one end included) in a standalone deck mixing `EI = 0` and finite-EI lines -without a body or through the C API, which move the line ends by translation only (`a line -restrained in torsion needs a host that turns its fairlead frame ...`; with a body such a deck -runs on the multibody route, which supports torsion), OpenFAST linearisation of a line +without a body or through the C API's `CableDyn_InitDeck`/`InitDeckAt`, which move the line +ends by translation only (`a line restrained in torsion needs a host that turns its fairlead +frame ...`; with a body such a deck runs on the multibody route, which supports torsion, and a C +API host passes its rotations after `CableDyn_InitDeckRotating`), OpenFAST linearisation of a line restrained in torsion, and a `Torq`/`Twist` channel on a line that is not restrained at both ends. Seabed friction does not resist twist (the laid part of a line twists freely), and there is no torque–tension coupling. diff --git a/doc/openfast.rst b/doc/openfast.rst index abfe73cc..767dd668 100644 --- a/doc/openfast.rst +++ b/doc/openfast.rst @@ -345,9 +345,10 @@ substeps; an output probe moves the frame without a step, is limited to 90° fro committed twist, and stops by name beyond it (a restart first restores the checkpoint's twist, so it is not limited this way). Formal linearisation of a line restrained in torsion fails during initialisation: the torque's -rotational stiffness has no column in the translation-only quasi-static reduction. The C API -and the standalone deck that mixes ``EI = 0`` and finite-EI lines without a body move the line -ends by translation only and refuse torsion columns. +rotational stiffness has no column in the translation-only quasi-static reduction. The C API's +``CableDyn_InitDeck``/``InitDeckAt`` and the standalone deck that mixes ``EI = 0`` and finite-EI +lines without a body move the line ends by translation only and refuse torsion columns; a C API +host that initialises with ``CableDyn_InitDeckRotating`` passes its rotations (:doc:`capi`). Lifecycle features ------------------ diff --git a/doc/troubleshooting.rst b/doc/troubleshooting.rst index 5125a222..c9179535 100644 --- a/doc/troubleshooting.rst +++ b/doc/troubleshooting.rst @@ -399,9 +399,11 @@ Torsion buoyancy section. * - ``a line restrained in torsion needs a host that turns its fairlead frame`` - the standalone deck that mixes ``EI = 0`` and finite-EI lines without a body, and the C - API, move the line ends by translation only. Run the line in a coupled OpenFAST or - FAST.Farm run, add a body (such a deck runs on the multibody route, which supports - torsion), or set ``TorsStiffness Free`` in every ``END CONNECTIONS`` row. + API's ``CableDyn_InitDeck``/``InitDeckAt``, move the line ends by translation only. Run the + line in a coupled OpenFAST or FAST.Farm run, initialise a C API handle with + ``CableDyn_InitDeckRotating`` and pass the host's rotations, add a body (such a deck runs + on the multibody route, which supports torsion), or set ``TorsStiffness Free`` in every + ``END CONNECTIONS`` row. * - ``formal OpenFAST linearization of a line restrained in torsion is not supported`` - linearise the model with ``TorsStiffness Free``; the twist and the torque carry no linearisation state. diff --git a/python/cabledyn/_lib.py b/python/cabledyn/_lib.py index 5495a4b8..44c49741 100644 --- a/python/cabledyn/_lib.py +++ b/python/cabledyn/_lib.py @@ -180,8 +180,7 @@ def _bind_object_queries() -> bool: # 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). +#: Minor extension level of ABI 1 this binding uses for the host-coupling calls. HOST_COUPLING_ABI_MINOR = 2 @@ -210,6 +209,33 @@ def _bind_host_coupling() -> bool: _has_host_coupling = _bind_host_coupling() +# --- ABI 1, minor extension 3: host rotations -------------------------------- +# Initialization for a host that turns its coupled points, their rotations, and +# the coupled moments. A library built before the extension lacks these symbols +# and reports ``abi_minor() < 3``. + +#: Minor extension level of ABI 1 this binding uses for the host-rotation calls +#: (the newest extension the binding knows). +HOST_ROTATION_ABI_MINOR = 3 + + +def _bind_host_rotation() -> bool: + try: + init_rot = _lib.CableDyn_InitDeckRotating + except AttributeError: + return False + init_rot.argtypes = [c_void_p, c_char_p, c_int, _DBL, c_int, POINTER(c_int)] + init_rot.restype = None + _lib.CableDyn_UpdateRotations.argtypes = [c_void_p, _DBL, _DBL, _DBL, c_int, POINTER(c_int)] + _lib.CableDyn_UpdateRotations.restype = None + _lib.CableDyn_GetCoupledMoments.argtypes = [c_void_p, _DBL, c_int, POINTER(c_int)] + _lib.CableDyn_GetCoupledMoments.restype = None + return True + + +_has_host_rotation = _bind_host_rotation() + + 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/deck_file.py b/python/cabledyn/deck_file.py index c72dd9db..19745538 100644 --- a/python/cabledyn/deck_file.py +++ b/python/cabledyn/deck_file.py @@ -4282,7 +4282,8 @@ def _check_torsion_lines( if has_torsion_column and aggregate_route and not self.caller_driven: raise DeckFormatError( f"{self._label}: a line restrained in torsion needs a host that turns its fairlead " - "frame: coupled OpenFAST and FAST.Farm runs do, while the C API and a standalone " + "frame: coupled OpenFAST and FAST.Farm runs do, and a C API host initialised with " + "CableDyn_InitDeckRotating, while CableDyn_InitDeck/InitDeckAt and a standalone " "deck that mixes EI = 0 and finite-EI lines without a BODY move the line ends by " "translation only (with a BODY such a deck runs on the multibody route, which " "supports torsion); set TorsStiffness Free in every END CONNECTIONS row" diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index bc55aea1..7b2a776d 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -90,6 +90,26 @@ def _dbl_ptr(arr: FloatArray) -> Any: return arr.ctypes.data_as(POINTER(c_double)) +def _host_positions(q0: ArrayInput) -> FloatArray: + """``q0`` of :meth:`CableDyn.init_deck_at`: flat ``(3 n,)`` or column-per-point ``(3, n)``.""" + 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: + 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)") + return q + + def _encode_path(deck: str | os.PathLike[str]) -> bytes: """Encode a deck path for the Fortran runtime's narrow-character ``OPEN``.""" text = os.fspath(deck) @@ -239,21 +259,7 @@ def init_deck_at(self, deck: str | os.PathLike[str], q0: ArrayInput) -> None: _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: - 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)") + q = _host_positions(q0) with self._lock: self._require_host_coupling() status = c_int() @@ -263,6 +269,39 @@ def init_deck_at(self, deck: str | os.PathLike[str], q0: ArrayInput) -> None: self._check("CableDyn_InitDeckAt", status.value) self._initialized_from(resolved) + def init_deck_rotating( + self, deck: str | os.PathLike[str], q0: ArrayInput | None = None + ) -> None: + """Initialize from a deck for a host that turns the bodies its coupled points are on. + + :meth:`init_deck_at` (or :meth:`init_deck` with ``q0=None``) whose model + takes each coupled block's rotation from :meth:`update_rotations` and + passes it with every :meth:`update_states` and :meth:`step`, so a line + restrained in torsion (``END CONNECTIONS`` ``TorsStiffness``) and a + ``Rigid`` bending end connection turn with the host at their host-driven + end; the other initializations refuse a deck with a line restrained in + torsion. The rotations start at identity (the deck's axes at the static + start) and rest. :meth:`coupled_moments` returns the moments the lines + apply to the host. + """ + _encode_path(deck) # rejects a NUL before any file-system call + resolved = Path(deck).expanduser().resolve() + path = _encode_path(resolved) + q = np.zeros(0) if q0 is None else _host_positions(q0) + with self._lock: + self._require_host_rotation() + status = c_int() + _lib.CableDyn_InitDeckRotating( + self._handle, + path, + len(path), + _dbl_ptr(q) if q.size else None, + int(q.size), + byref(status), + ) + self._check("CableDyn_InitDeckRotating", 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 @@ -271,6 +310,15 @@ def _initialized_from(self, deck: Path) -> None: self._saved_time = None self._deck = deck + @staticmethod + def _require_host_rotation() -> None: + if _lib_module.abi_minor() < _lib_module.HOST_ROTATION_ABI_MINOR: + # not a C status: the loaded library lacks the entry points + raise RuntimeError( + "the loaded CableDyn library predates the host-rotation calls " + "(ABI 1 minor extension 3); rebuild it from this checkout" + ) + @staticmethod def _require_host_coupling() -> None: if _lib_module.abi_minor() < _lib_module.HOST_COUPLING_ABI_MINOR: @@ -540,6 +588,65 @@ def restore_state(self) -> None: if self._saved_time is not None: self._time = self._saved_time + # -- host rotations ------------------------------------------------------- + + def update_rotations(self, dcm: ArrayInput, omega: ArrayInput, alpha: ArrayInput) -> None: + """Set the host's rotation of every coupled block for the next updates and steps. + + ``dcm`` is ``(n_block, 3, 3)``: ``dcm[k]`` is block ``k``'s global-to-body + direction cosine matrix (its rows are the body axes in global axes, the + OpenFAST mesh orientation; identity is the body at its static-start + attitude). ``omega`` and ``alpha`` are ``(n_block, 3)``: the body's + angular velocity [rad/s] and acceleration [rad/s^2] in global axes. Only a + finite-EI line's host-driven end uses its block. The rotations are kept + until the next call and saved with :meth:`save_state`. Requires + :meth:`init_deck_rotating`; a rejected input (a matrix that is not proper + orthogonal to 1e-8, a non-finite value) leaves the rotations unchanged. + """ + with self._lock: + self._require_host_rotation() + nb = self.n_coupled_dof // 3 + r = _as_real_array(dcm, "dcm") + w = _as_real_array(omega, "omega") + al = _as_real_array(alpha, "alpha") + if r.shape != (nb, 3, 3): + raise ValueError(f"dcm must be shaped ({nb}, 3, 3); got {r.shape}") + for name, x in (("omega", w), ("alpha", al)): + if x.shape != (nb, 3): + raise ValueError(f"{name} must be shaped ({nb}, 3); got {x.shape}") + r = np.ascontiguousarray(r.reshape(-1)) + w = np.ascontiguousarray(w.reshape(-1)) + al = np.ascontiguousarray(al.reshape(-1)) + status = c_int() + _lib.CableDyn_UpdateRotations( + self._handle, + _dbl_ptr(r) if nb else None, + _dbl_ptr(w) if nb else None, + _dbl_ptr(al) if nb else None, + nb, + byref(status), + ) + self._check("CableDyn_UpdateRotations", status.value) + + def coupled_moments(self) -> FloatArray: + """The moments the lines apply to the host at the coupled points, ``(n_dof,)`` N m. + + Block ``k`` (entries ``3k .. 3k+2``, global axes) is a finite-EI line's + torsional and bending reaction about the coupled point at its host-driven + end, at the state :meth:`calc_output` reports; zero for the other blocks + and for ``EI = 0`` lines. + """ + with self._lock: + self._require_host_rotation() + n = self.n_coupled_dof + moments = np.zeros(n) + status = c_int() + _lib.CableDyn_GetCoupledMoments( + self._handle, _dbl_ptr(moments) if n else None, n, byref(status) + ) + self._check("CableDyn_GetCoupledMoments", status.value) + return moments + def coupled_layout(self) -> tuple[tuple[int, PointKind], ...]: """The owner of each 3-DOF block of the coupled vector, as ``(point_id, kind)``. diff --git a/python/tests/test_host_coupling.py b/python/tests/test_host_coupling.py index 1c104f57..78012600 100644 --- a/python/tests/test_host_coupling.py +++ b/python/tests/test_host_coupling.py @@ -49,7 +49,7 @@ def _motion(model: CableDyn, q0: np.ndarray, amp: float, t: float): 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 + assert _lib.abi_minor() == cabledyn.abi_minor() >= _lib.HOST_COUPLING_ABI_MINOR def test_point_route_layout(): diff --git a/python/tests/test_host_rotation.py b/python/tests/test_host_rotation.py new file mode 100644 index 00000000..f741d289 --- /dev/null +++ b/python/tests/test_host_rotation.py @@ -0,0 +1,127 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Host rotations (C ABI 1 minor extension 3): a host that turns its coupled points. + +The deck is the straight neutral torsion line of test_coupled_torsion: GJ 5e4 N m^2, +100 m along +x from the Coupled fairlead (0, 0, -50) to a Fixed anchor, both ends +clamped and restrained in torsion, a negligible polar inertia (the quasi-static +torsion). Rolling the fairlead by phi about the line axis twists the line by -phi, +and the line returns the torque GJ phi / L to the host about that axis. +""" + +from __future__ import annotations + +import math +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) + +from cabledyn import _lib +from cabledyn.errors import CableDynError +from cabledyn.model import CableDyn + +GJ = 5.0e4 +LENGTH = 100.0 +DT = 0.05 +BOX = Path(__file__).resolve().parents[2] / "tests" / "data" / "foam_esflowc_box_points.dat" + + +def _deck(tmp_path: Path, tors: str = "Rigid") -> Path: + mass = 1025.0 * 0.25 * math.pi * 0.04 + outputs = "Torq1N1\nTorq1N41\nTwist1\n" if tors != "Free" else "FairTen1\n" + text = ( + "host rotation gate\n--- LINE TYPES ---\n" + "Name Diam Mass EA BA EI GAs GJ Irt Irn Cdn Cdt Can Cat\n" + "(-) (m) (kg/m) (N) (-) (Nm2) (N) (Nm2) (kgm) (kgm) (-) (-) (-) (-)\n" + f"cab 0.2 {mass:.16e} 1.0e7 0.0 1.0e6 1.0e8 5.0e4 1.0 1.0e-9 0.0 0.0 0.0 0.0\n" + "--- POINTS ---\nID Type X Y Z Mass Vol CdA Ca\n(-) (-) (m) (m) (m) (kg) (m3) (m2) (-)\n" + "1 Coupled 0.0 0.0 -50.0 0 0 0 0\n2 Fixed 100.0 0.0 -50.0 0 0 0 0\n" + "--- LINES ---\nID NodeA NodeB Outputs\n(-) (-) (-) (-)\n1 1 2 -\n" + "--- SECTIONS ---\nLineID LineType Length NumSegs\n(-) (-) (m) (-)\n1 cab 100.0 40\n" + "--- END CONNECTIONS ---\n" + "LineID End Stiffness EzX EzY EzZ TorsStiffness NxX NxY NxZ Pretwist\n" + "(-) (-) (N-m/rad) (-) (-) (-) (N-m/rad) (-) (-) (-) (deg)\n" + f"1 A Rigid 1 0 0 {tors} 0 0 1 0\n1 B Rigid 1 0 0 {tors} 0 0 1 0\n" + "--- OPTIONS ---\n9.80665 g\n1025.0 rhoW\n0.05 dtM\n0.0 TMax\n" + f"--- OUTPUTS ---\n{outputs}--- END ---\n" + ) + path = tmp_path / f"rotation_{tors.lower()}.dat" + path.write_text(text, encoding="utf-8") + return path + + +def _roll(phi: float) -> np.ndarray: + """OpenFAST mesh orientation (global to local) of a roll phi about +x, (1, 3, 3).""" + c, s = math.cos(phi), math.sin(phi) + return np.array([[[1.0, 0.0, 0.0], [0.0, c, s], [0.0, -s, c]]]) + + +def test_abi_minor_reports_the_host_rotation_extension(): + assert _lib.HOST_ROTATION_ABI_MINOR == 3 + assert _lib.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR + + +def test_torsion_deck_needs_the_rotating_initialization(tmp_path): + deck = _deck(tmp_path) + with CableDyn() as model: + with pytest.raises(CableDynError, match="CableDyn_InitDeckRotating"): + model.init_deck(deck) + model.init_deck_rotating(deck) + assert model.n_coupled_dof == 3 + assert np.all(np.abs(model.coupled_moments()) <= 1.0e-6) + + +def test_rolling_host_gets_the_quasi_static_torque(tmp_path): + rate = math.radians(60.0) + with CableDyn() as model: + model.init_deck_rotating(_deck(tmp_path)) + q, v, a = model.get_coupled_motion() + for k in range(1, 11): + phi = rate * DT * k + model.update_rotations(_roll(phi), [[rate, 0.0, 0.0]], np.zeros((1, 3))) + model.step(DT, q, v, a) + m = model.coupled_moments() + assert m[0] == pytest.approx(-GJ * phi / LENGTH, abs=1.0e-6 * GJ) + assert abs(m[1]) <= 1.0e-6 * GJ and abs(m[2]) <= 1.0e-6 * GJ + assert model.channel("Twist1") == pytest.approx(-math.degrees(phi), abs=1.0e-6) + + +def test_save_restore_carries_the_rotations(tmp_path): + rate = math.radians(60.0) + with CableDyn() as model: + model.init_deck_rotating(_deck(tmp_path)) + q, v, a = model.get_coupled_motion() + model.update_rotations(_roll(rate * DT), [[rate, 0.0, 0.0]], np.zeros((1, 3))) + model.save_state() + model.step(DT, q, v, a) + first = model.coupled_moments() + model.update_rotations(_roll(0.5), [[0.0, 0.0, 0.0]], np.zeros((1, 3))) + model.restore_state() + model.step(DT, q, v, a) + assert np.array_equal(model.coupled_moments(), first) + + +def test_rotation_input_is_checked(tmp_path): + with CableDyn() as model: + model.init_deck_rotating(_deck(tmp_path)) + with pytest.raises(ValueError, match="dcm must be shaped"): + model.update_rotations(np.eye(3), np.zeros((1, 3)), np.zeros((1, 3))) + with pytest.raises(CableDynError, match="proper orthogonal"): + model.update_rotations(1.01 * _roll(0.1), np.zeros((1, 3)), np.zeros((1, 3))) + with CableDyn() as model: + model.init_deck(_deck(tmp_path, "Free")) + with pytest.raises(CableDynError, match="CableDyn_InitDeckRotating"): + model.update_rotations(_roll(0.1), np.zeros((1, 3)), np.zeros((1, 3))) + + +def test_point_route_takes_rotations_and_returns_no_moment(): + with CableDyn() as model: + model.init_deck_rotating(BOX) + nb = model.n_coupled_dof // 3 + model.update_rotations(np.repeat(_roll(0.3), nb, axis=0), np.zeros((nb, 3)), np.zeros((nb, 3))) + assert np.array_equal(model.coupled_moments(), np.zeros(3 * nb)) diff --git a/python/tests/test_objects.py b/python/tests/test_objects.py index e360af3d..e4f99a45 100644 --- a/python/tests/test_objects.py +++ b/python/tests/test_objects.py @@ -450,7 +450,7 @@ def test_unbound_handle_and_raw_lines(monkeypatch, tmp_path): def test_abi_minor_is_reported(): assert _lib.OBJECT_QUERY_ABI_MINOR == 1 - assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_COUPLING_ABI_MINOR == 2 + assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR == 3 assert objects_module.OBJ_ROD == 4 diff --git a/release/check_release_metadata.py b/release/check_release_metadata.py index d1dfcefc..21c3bbbd 100644 --- a/release/check_release_metadata.py +++ b/release/check_release_metadata.py @@ -140,7 +140,7 @@ def main() -> int: "C header ABI minor level": f"CABLEDYN_CAPI_ABI_MINOR {abi_minor}" in read( "src/CableDyn_CAPI.h" ), - "Python ABI minor level": f"HOST_COUPLING_ABI_MINOR = {abi_minor}" in read( + "Python ABI minor level": f"HOST_ROTATION_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 f44140e5..1cf5a9e8 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -31,7 +31,7 @@ MODULE CableDyn_CAPI CD_FAST_NCoupledDOF, CD_FAST_NPoints, CD_FAST_NLines, CD_FAST_OK, CD_FAST_BADINPUT, & 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_Precision, ONLY: wp, CD_ZERO, CD_ONE USE CableDyn_System, ONLY: CD_SystemType, CD_System_Line_NDOF, CD_Get_System_PointBlocks, CD_SYSTEM_OK, & CD_POINT_COUPLED IMPLICIT NONE @@ -67,6 +67,9 @@ MODULE CableDyn_CAPI PUBLIC :: CableDyn_SaveState PUBLIC :: CableDyn_RestoreState PUBLIC :: CableDyn_GetCoupledLayout + PUBLIC :: CableDyn_InitDeckRotating + PUBLIC :: CableDyn_UpdateRotations + PUBLIC :: CableDyn_GetCoupledMoments INTEGER(C_INT), PARAMETER :: CD_C_OK = 0_C_INT INTEGER(C_INT), PARAMETER :: CD_C_BAD_HANDLE = 1_C_INT @@ -80,8 +83,10 @@ MODULE CableDyn_CAPI INTEGER(C_INT), PARAMETER :: CD_C_ABI_VERSION = 1_C_INT CHARACTER(*), PARAMETER :: CD_C_VERSION_STRING = 'CableDyn 0.3.0 C-ABI 1' !> 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 + !> calls (initialization at host positions, state save/restore, the coupled layout query), 3 + !> the host rotations (initialization for a host that turns its coupled points, their + !> rotations, the coupled moments). + INTEGER(C_INT), PARAMETER :: CD_C_ABI_MINOR = 3_C_INT !> 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 +161,13 @@ END FUNCTION cabledyn_blas_threads_once TYPE(CD_AGG_ModuleType) :: agg REAL(wp) :: agg_dt = CD_ZERO, agg_t = CD_ZERO REAL(wp), ALLOCATABLE :: agg_pos(:, :), agg_vel(:, :), agg_acc(:, :), agg_load(:, :) + ! A handle initialised by CableDyn_InitDeckRotating (host_rot): the host's rotation of each + ! coupled block, set by CableDyn_UpdateRotations and passed with every update and step on the + ! aggregate route (agg_dcm: OpenFAST's global-to-body DCM; agg_om, agg_al: the angular + ! velocity and acceleration in global axes; identity and rest at the static start). + ! agg_moment: the coupled moments' workspace of CableDyn_GetCoupledMoments. + LOGICAL :: host_rot = .FALSE. + REAL(wp), ALLOCATABLE :: agg_dcm(:, :, :), agg_om(:, :), agg_al(:, :), agg_moment(:, :) ! Point-route line inventory for the object queries: the deck-line-id -> system-line map ! (pt_obj, 0 = no such line; pt_is_cable all .FALSE.) the shared channel evaluator resolves ! through, and an empty cable store to pass it. Raw-line handles number their lines 1..n. @@ -171,6 +183,7 @@ END FUNCTION cabledyn_blas_threads_once TYPE(CD_FAST_ModuleType) :: saved_fast TYPE(CD_AGG_ModuleType), ALLOCATABLE :: saved_agg REAL(wp) :: saved_agg_t = CD_ZERO + REAL(wp), ALLOCATABLE :: saved_dcm(:, :, :), saved_om(:, :), saved_al(:, :) CHARACTER(CD_C_MSG_LEN) :: last_error = '' END TYPE CD_C_Handle @@ -257,49 +270,86 @@ SUBROUTINE CableDyn_InitDeckAt(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q 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 + + CALL init_deck_at(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q0, 'CableDyn_InitDeckAt', .FALSE., err_stat) + END SUBROUTINE CableDyn_InitDeckAt + + SUBROUTINE CableDyn_InitDeckRotating(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q0, err_stat) & + BIND(C, NAME='CableDyn_InitDeckRotating') + !! CableDyn_InitDeckAt for a host that turns its coupled points: the handle takes each + !! coupled block's rotation from CableDyn_UpdateRotations and passes it with every update and + !! step, so a line restrained in torsion (END CONNECTIONS TorsStiffness) and a Rigid bending + !! END CONNECTION turn with the host at their coupled end, as on the coupled OpenFAST route. + !! The rotations start at identity (the deck's axes at the static start) and rest. n_q0 = 0 + !! solves the statics at the deck positions, as CableDyn_InitDeck. 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 + + CALL init_deck_at(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q0, 'CableDyn_InitDeckRotating', .TRUE., & + err_stat) + END SUBROUTINE CableDyn_InitDeckRotating + + SUBROUTINE init_deck_at(handle, deck_path_ptr, deck_path_len, q0_ptr, n_q0, caller, rotating, err_stat) + !! CableDyn_InitDeckAt / CableDyn_InitDeckRotating body: the host positions q0 (n_q0 = 0: + !! none, the deck positions) and, with rotating, a handle that takes the host's rotations. + TYPE(C_PTR), VALUE :: handle, deck_path_ptr, q0_ptr + INTEGER(C_INT), VALUE :: deck_path_len, n_q0 + CHARACTER(*), INTENT(IN) :: caller + LOGICAL, INTENT(IN) :: rotating + 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 + IF (.NOT. blas_runtime_ready(handle, caller, 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) + CALL set_status(h, CD_C_BAD_INPUT, caller//': 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) + CALL set_status(h, CD_C_BAD_INPUT, caller//': q0 pointer is null', err_stat) + RETURN + END IF + IF (rotating .AND. n_q0 == 0_C_INT) THEN + ! no host positions: the statics at the deck positions, as CableDyn_InitDeck + CALL cabledyn_input_lock() + CALL init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, err_stat, rotating=rotating) + CALL cabledyn_input_unlock() 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) + CALL set_status(h, CD_C_ALLOC_FAIL, caller//': 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) + CALL set_status(h, CD_C_BAD_INPUT, caller//': 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 init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, err_stat, positions, rotating) CALL cabledyn_input_unlock() - END SUBROUTINE CableDyn_InitDeckAt + END SUBROUTINE init_deck_at - 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. + SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, err_stat, positions, rotating) + !! CableDyn_InitDeck / CableDyn_InitDeckAt / CableDyn_InitDeckRotating body; the caller holds + !! the process-wide input lock. positions (3, n): the host positions of CableDyn_InitDeckAt; + !! rotating: the handle takes the host's rotations (CableDyn_InitDeckRotating). 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(:, :) + LOGICAL, INTENT(IN), OPTIONAL :: rotating TYPE(CD_C_Handle), POINTER :: h TYPE(CD_FAST_ModuleType) :: new_fast @@ -308,9 +358,11 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, er INTEGER :: i, es, end_es, stat, n_objects, n_finite INTEGER, ALLOCATABLE :: line_ids(:) REAL(wp) :: dtm, gravity, rho_water - LOGICAL :: has_dtm + LOGICAL :: has_dtm, rot CHARACTER(CD_C_MSG_LEN) :: em, end_em + rot = .FALSE. + IF (PRESENT(rotating)) rot = rotating 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 @@ -340,7 +392,7 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, er 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, caller, err_stat, positions) + CALL init_deck_aggregate(h, TRIM(deck_path), has_dtm, dtm, caller, rot, err_stat, positions) RETURN END IF ! An absent positions argument stays absent through the optional coupled_positions. @@ -366,6 +418,9 @@ SUBROUTINE init_deck_serialised(handle, deck_path_ptr, deck_path_len, caller, er CALL drop_aggregate(h) CALL drop_saved_state(h) CALL set_point_line_map(h, line_ids) + ! the point route's EI = 0 lines take no rotation (CableDyn_UpdateRotations checks and + ! ignores it) + h%host_rot = rot CALL store_status(h, CD_C_OK, '') err_stat = CD_C_OK END SUBROUTINE init_deck_serialised @@ -424,23 +479,27 @@ PURE LOGICAL FUNCTION same_position(x, y) RESULT(same) 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) + SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, rotating, 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. positions (3, n_moving): the host - !! positions of CableDyn_InitDeckAt, in the aggregate's coupled order. + !! positions of CableDyn_InitDeckAt, in the aggregate's coupled order. rotating: the host + !! passes the coupled points' rotations (CableDyn_InitDeckRotating), which a line restrained + !! in torsion needs; without it such a deck is refused. 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 + LOGICAL, INTENT(IN) :: rotating 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, k REAL(wp), ALLOCATABLE :: pos(:, :), vel(:, :), acc(:, :), load(:, :) + REAL(wp), ALLOCATABLE :: dcm(:, :, :), om(:, :), al(:, :), moment(:, :) CHARACTER(CD_C_MSG_LEN) :: em IF (.NOT. (has_dtm .AND. dtm > CD_ZERO)) THEN @@ -454,7 +513,8 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, err_stat, pos RETURN END IF ! 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) + CALL CD_AGG_Init_From_Deck(new_agg, deck_path, dtm, es, em, coupled_positions=positions, & + host_orientation=rotating) IF (es /= CD_AGG_OK) THEN CALL map_agg_status(es, err_stat) CALL store_status(h, err_stat, caller//': '//TRIM(em)) @@ -464,7 +524,8 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, err_stat, pos nm = CD_AGG_NMovingPoints(new_agg, es, em) ! Allocate the new route's workspace before releasing the old route, so an ! allocation failure leaves the handle's previous model in place. - ALLOCATE (pos(3, nm), vel(3, nm), acc(3, nm), load(3, nm), STAT=stat) + ALLOCATE (pos(3, nm), vel(3, nm), acc(3, nm), load(3, nm), dcm(3, 3, nm), om(3, nm), al(3, nm), & + moment(3, nm), STAT=stat) IF (stat /= 0) THEN CALL CD_AGG_End(new_agg, es, em) CALL set_status(h, CD_C_ALLOC_FAIL, caller//': aggregate workspace allocation failed', err_stat) @@ -503,6 +564,20 @@ SUBROUTINE init_deck_aggregate(h, deck_path, has_dtm, dtm, caller, err_stat, pos CALL MOVE_ALLOC(vel, h%agg_vel) CALL MOVE_ALLOC(acc, h%agg_acc) CALL MOVE_ALLOC(load, h%agg_load) + dcm = CD_ZERO + DO k = 1, nm + dcm(1, 1, k) = CD_ONE + dcm(2, 2, k) = CD_ONE + dcm(3, 3, k) = CD_ONE + END DO + om = CD_ZERO + al = CD_ZERO + moment = CD_ZERO + CALL MOVE_ALLOC(dcm, h%agg_dcm) + CALL MOVE_ALLOC(om, h%agg_om) + CALL MOVE_ALLOC(al, h%agg_al) + CALL MOVE_ALLOC(moment, h%agg_moment) + h%host_rot = rotating CALL move_aggregate(new_agg, h%agg) CALL clear_point_line_map(h) h%use_agg = .TRUE. @@ -554,6 +629,7 @@ SUBROUTINE drop_saved_state(h) END IF CALL CD_FAST_End(h%saved_fast, es, em) h%saved_agg_t = CD_ZERO + IF (ALLOCATED(h%saved_dcm)) DEALLOCATE (h%saved_dcm, h%saved_om, h%saved_al) h%has_saved = .FALSE. END SUBROUTINE drop_saved_state @@ -567,6 +643,8 @@ SUBROUTINE drop_aggregate(h) h%agg_dt = CD_ZERO h%agg_t = CD_ZERO IF (ALLOCATED(h%agg_pos)) DEALLOCATE (h%agg_pos, h%agg_vel, h%agg_acc, h%agg_load) + IF (ALLOCATED(h%agg_dcm)) DEALLOCATE (h%agg_dcm, h%agg_om, h%agg_al, h%agg_moment) + h%host_rot = .FALSE. END SUBROUTINE drop_aggregate SUBROUTINE map_agg_status(agg_stat, err_stat) @@ -933,7 +1011,12 @@ SUBROUTINE CableDyn_UpdateStates(handle, q_ptr, v_ptr, a_ptr, n_coupled_dof, err h%agg_vel = RESHAPE(REAL(v_c, wp), SHAPE(h%agg_vel)) h%agg_acc = RESHAPE(REAL(a_c, wp), SHAPE(h%agg_acc)) END IF - CALL CD_AGG_UpdateStates_Moving(h%agg, h%agg_pos, h%agg_vel, h%agg_acc, es, em) + IF (h%host_rot) THEN + CALL CD_AGG_UpdateStates_Moving(h%agg, h%agg_pos, h%agg_vel, h%agg_acc, es, em, orientation=h%agg_dcm, & + angular_velocity=h%agg_om, angular_acceleration=h%agg_al) + ELSE + CALL CD_AGG_UpdateStates_Moving(h%agg, h%agg_pos, h%agg_vel, h%agg_acc, es, em) + END IF CALL map_agg_status(es, err_stat) CALL store_status(h, err_stat, em) RETURN @@ -1043,8 +1126,14 @@ SUBROUTINE CableDyn_Step(handle, dt, q_ptr, v_ptr, a_ptr, n_coupled_dof, converg h%agg_vel = RESHAPE(REAL(v_c, wp), SHAPE(h%agg_vel)) h%agg_acc = RESHAPE(REAL(a_c, wp), SHAPE(h%agg_acc)) END IF - CALL CD_AGG_Step_Moving(h%agg, REAL(dt, wp), h%agg_pos, h%agg_vel, h%agg_acc, conv_f, stall_f, nit, es, em, & - t_committed=h%agg_t + REAL(dt, wp)) + IF (h%host_rot) THEN + CALL CD_AGG_Step_Moving(h%agg, REAL(dt, wp), h%agg_pos, h%agg_vel, h%agg_acc, conv_f, stall_f, nit, es, & + em, t_committed=h%agg_t + REAL(dt, wp), orientation=h%agg_dcm, & + angular_velocity=h%agg_om, angular_acceleration=h%agg_al) + ELSE + CALL CD_AGG_Step_Moving(h%agg, REAL(dt, wp), h%agg_pos, h%agg_vel, h%agg_acc, conv_f, stall_f, nit, es, & + em, t_committed=h%agg_t + REAL(dt, wp)) + END IF IF (es == CD_AGG_OK) h%agg_t = h%agg_t + REAL(dt, wp) converged = LOGICAL(conv_f, C_BOOL) stalled = LOGICAL(stall_f, C_BOOL) @@ -1769,8 +1858,9 @@ 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. + !! route the committed time and the host's rotations (CableDyn_UpdateRotations). The slot + !! holds a deep copy of the model object, independent of the step's own rollback buffers, + !! so any number of steps may follow before the restore. !! A successful Init* call discards the slot; a failed InitDeck/InitDeckAt keeps it with the !! 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 @@ -1795,6 +1885,12 @@ SUBROUTINE CableDyn_SaveState(handle, err_stat) BIND(C, NAME='CableDyn_SaveState END IF CALL copy_aggregate(h%agg, h%saved_agg) h%saved_agg_t = h%agg_t + ! the host's rotations are the inputs of the saved instant (CableDyn_UpdateRotations) + IF (h%host_rot) THEN + h%saved_dcm = h%agg_dcm + h%saved_om = h%agg_om + h%saved_al = h%agg_al + END IF ELSE CALL copy_point_system(h%fast, h%saved_fast) END IF @@ -1820,6 +1916,11 @@ SUBROUTINE CableDyn_RestoreState(handle, err_stat) BIND(C, NAME='CableDyn_Restor IF (h%use_agg) THEN CALL copy_aggregate(h%saved_agg, h%agg) h%agg_t = h%saved_agg_t + IF (h%host_rot) THEN + h%agg_dcm = h%saved_dcm + h%agg_om = h%saved_om + h%agg_al = h%saved_al + END IF ELSE CALL copy_point_system(h%saved_fast, h%fast) END IF @@ -1861,6 +1962,140 @@ SUBROUTINE CableDyn_GetCoupledLayout(handle, point_id_ptr, point_type_ptr, n_blo CALL store_status(h, CD_C_OK, '') END SUBROUTINE CableDyn_GetCoupledLayout + ! --------------------------------------------------------------------------------------- + ! Host rotations (C ABI 1, minor extension 3): CableDyn_InitDeckRotating (above, with + ! InitDeckAt), the rotation of each coupled block, and the coupled moments. + ! --------------------------------------------------------------------------------------- + + SUBROUTINE CableDyn_UpdateRotations(handle, dcm_ptr, omega_ptr, alpha_ptr, n_block, err_stat) & + BIND(C, NAME='CableDyn_UpdateRotations') + !! The host's rotation of each 3-DOF block k of the coupled vector, for the following + !! CableDyn_UpdateStates and CableDyn_Step calls (kept until the next call): dcm[9k + 3i + j] + !! = R_ij of the global-to-body DCM (row-major; rows are the body axes in global axes, the + !! OpenFAST mesh orientation), omega[3k + i] and alpha[3k + i] the body's angular velocity + !! and acceleration in global axes. The body is the host part the coupled point is fixed to, + !! with its axes on the deck's axes at the static start (identity). A finite-EI line's + !! host-driven end turns with it; the other blocks take no rotation (their entries are + !! checked and not used). n_block must equal CableDyn_NCoupledDOF / 3. Only a handle + !! initialised by CableDyn_InitDeckRotating takes rotations. The call is all or nothing: a + !! rejected input (a DCM that is not finite and proper orthogonal to 1e-8, non-finite rates) + !! leaves the rotations unchanged. + TYPE(C_PTR), VALUE :: handle, dcm_ptr, omega_ptr, alpha_ptr + INTEGER(C_INT), VALUE :: n_block + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + REAL(C_DOUBLE), POINTER :: dcm_c(:), om_c(:), al_c(:) + REAL(wp) :: r(3, 3), gram(3, 3), det + INTEGER :: n, k, i, j + + IF (.NOT. query_ready(handle, h, 'CableDyn_UpdateRotations', err_stat)) RETURN + IF (.NOT. h%host_rot) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: the handle takes no rotations (initialise it '// & + 'with CableDyn_InitDeckRotating)', err_stat) + RETURN + END IF + IF (n_block < 0_C_INT .OR. n_block > HUGE(n_block)/9_C_INT) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: n_block does not match '// & + 'CableDyn_NCoupledDOF / 3', err_stat) + RETURN + END IF + IF (.NOT. valid_coupled_dof_count(h, 3_C_INT*n_block, err_stat)) THEN + IF (err_stat == CD_C_BAD_INPUT) CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: n_block '// & + 'does not match CableDyn_NCoupledDOF / 3', err_stat) + RETURN + END IF + n = INT(n_block) + IF (n == 0) THEN + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + RETURN + END IF + IF (.NOT. (C_ASSOCIATED(dcm_ptr) .AND. C_ASSOCIATED(omega_ptr) .AND. C_ASSOCIATED(alpha_ptr))) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: input pointer is null', err_stat) + RETURN + END IF + CALL C_F_POINTER(dcm_ptr, dcm_c, [9*n]) + CALL C_F_POINTER(omega_ptr, om_c, [3*n]) + CALL C_F_POINTER(alpha_ptr, al_c, [3*n]) + IF (.NOT. (ALL(IEEE_IS_FINITE(dcm_c)) .AND. ALL(IEEE_IS_FINITE(om_c)) .AND. ALL(IEEE_IS_FINITE(al_c)))) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: rotations must be finite', err_stat) + RETURN + END IF + ! every block is checked before any is stored (the aggregate's own test of its orientations) + DO k = 1, n + DO i = 1, 3 + DO j = 1, 3 + r(i, j) = REAL(dcm_c(9*(k - 1) + 3*(i - 1) + j), wp) + END DO + END DO + gram = MATMUL(r, TRANSPOSE(r)) + DO i = 1, 3 + gram(i, i) = gram(i, i) - CD_ONE + END DO + det = r(1, 1)*(r(2, 2)*r(3, 3) - r(2, 3)*r(3, 2)) - r(1, 2)*(r(2, 1)*r(3, 3) - r(2, 3)*r(3, 1)) + & + r(1, 3)*(r(2, 1)*r(3, 2) - r(2, 2)*r(3, 1)) + IF (MAXVAL(ABS(gram)) > 1.0e-8_wp .OR. ABS(det - CD_ONE) > 1.0e-8_wp) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_UpdateRotations: the DCM of block '//TRIM(int_text(k - 1))// & + ' is not proper orthogonal', err_stat) + RETURN + END IF + END DO + IF (h%use_agg) THEN + DO k = 1, n + DO i = 1, 3 + DO j = 1, 3 + h%agg_dcm(i, j, k) = REAL(dcm_c(9*(k - 1) + 3*(i - 1) + j), wp) + END DO + END DO + h%agg_om(:, k) = REAL(om_c(3*k - 2:3*k), wp) + h%agg_al(:, k) = REAL(al_c(3*k - 2:3*k), wp) + END DO + END IF + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + END SUBROUTINE CableDyn_UpdateRotations + + SUBROUTINE CableDyn_GetCoupledMoments(handle, moments_ptr, n_coupled_dof, err_stat) & + BIND(C, NAME='CableDyn_GetCoupledMoments') + !! The moment each 3-DOF block of the coupled vector applies to the host, about the coupled + !! point in global axes, at the state CableDyn_CalcOutput reports: a finite-EI line's + !! torsional and bending reaction at its host-driven end (a line restrained in torsion, a + !! Rigid or spring bending END CONNECTION), zero for the other blocks and on the point + !! route. n_coupled_dof must equal CableDyn_NCoupledDOF. + TYPE(C_PTR), VALUE :: handle, moments_ptr + INTEGER(C_INT), VALUE :: n_coupled_dof + INTEGER(C_INT), INTENT(OUT) :: err_stat + TYPE(CD_C_Handle), POINTER :: h + REAL(C_DOUBLE), POINTER :: moments_c(:) + INTEGER :: es + CHARACTER(CD_C_MSG_LEN) :: em + + IF (.NOT. query_ready(handle, h, 'CableDyn_GetCoupledMoments', err_stat)) RETURN + IF (.NOT. valid_coupled_dof_count(h, n_coupled_dof, err_stat)) RETURN + IF (n_coupled_dof == 0_C_INT) THEN + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + RETURN + END IF + IF (.NOT. C_ASSOCIATED(moments_ptr)) THEN + CALL set_status(h, CD_C_BAD_INPUT, 'CableDyn_GetCoupledMoments: moments pointer is null', err_stat) + RETURN + END IF + CALL C_F_POINTER(moments_ptr, moments_c, [INT(n_coupled_dof)]) + moments_c = 0.0_C_DOUBLE + IF (.NOT. h%use_agg) THEN + CALL store_status(h, CD_C_OK, '') + err_stat = CD_C_OK + RETURN + END IF + CALL CD_AGG_CalcOutput(h%agg, es, em) + IF (es == CD_AGG_OK) CALL CD_AGG_GetMovingPointMesh(h%agg, h%agg_pos, h%agg_vel, h%agg_acc, h%agg_load, es, em, & + moment=h%agg_moment) + IF (es == CD_AGG_OK) moments_c = REAL(RESHAPE(h%agg_moment, [INT(n_coupled_dof)]), C_DOUBLE) + CALL map_agg_status(es, err_stat) + CALL store_status(h, err_stat, em) + END SUBROUTINE CableDyn_GetCoupledMoments + 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 diff --git a/src/CableDyn_CAPI.h b/src/CableDyn_CAPI.h index d9067dd5..484be890 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -127,8 +127,9 @@ int CableDyn_NLines(void *handle, int *err_stat); * aggregate (it needs dtM); other decks keep the point route. Check * CableDyn_GetAbiMinor() >= 1 before using these on a library of unknown * vintage. CABLEDYN_CAPI_ABI_MINOR is the extension level this header - * declares (2: the host-coupling calls below are present too). */ -#define CABLEDYN_CAPI_ABI_MINOR 2 + * declares (3: the host-coupling and host-rotation calls below are present + * too). */ +#define CABLEDYN_CAPI_ABI_MINOR 3 #define CD_C_OBJ_LINE 1 #define CD_C_OBJ_POINT 2 @@ -218,6 +219,43 @@ 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); +/* ---- ABI 1, minor extension 3: host rotations ------------------------------ + * + * For a host that turns the bodies its Coupled points are fixed to: a line + * restrained in torsion (END CONNECTIONS TorsStiffness) and a Rigid bending END + * CONNECTION turn with the host at their coupled end, as on the coupled + * OpenFAST route. Check CableDyn_GetAbiMinor() >= 3 before using these on a + * library of unknown vintage. */ + +/* CableDyn_InitDeckAt for a host that passes rotations: the handle takes each + * coupled block's rotation from CableDyn_UpdateRotations and passes it with + * every CableDyn_UpdateStates and CableDyn_Step. The rotations start at + * identity (the deck's axes at the static start) and rest. n_q0 = 0 (q0 may be + * NULL) solves the statics at the deck positions, as CableDyn_InitDeck. A deck + * with a line restrained in torsion needs this initialization. */ +void CableDyn_InitDeckRotating(void *handle, const char *deck_path, + int deck_path_len, const double *q0, int n_q0, + int *err_stat); +/* The rotation of each 3-DOF block k of the coupled vector for the following + * UpdateStates and Step calls (kept until the next call; SaveState/RestoreState + * carry it): dcm[9k + 3i + j] = R_ij of the global-to-body DCM (row-major; the + * rows are the body axes in global axes), omega[3k + i] and alpha[3k + i] the + * body's angular velocity and acceleration in global axes. Only a finite-EI + * line's host-driven end uses its block; the other blocks are checked and not + * used. n_block = CableDyn_NCoupledDOF / 3. All or nothing: a DCM that is not + * finite and proper orthogonal (to 1e-8) or a non-finite rate leaves the + * rotations unchanged. */ +void CableDyn_UpdateRotations(void *handle, const double *dcm, + const double *omega, const double *alpha, + int n_block, int *err_stat); +/* The moment each block of the coupled vector applies to the host, about the + * coupled point in global axes, at the state CableDyn_CalcOutput reports: a + * finite-EI line's torsional and bending reaction at its host-driven end, zero + * for the other blocks and on the point route. Available on any initialized + * handle. */ +void CableDyn_GetCoupledMoments(void *handle, double *coupled_moments, + int n_coupled_dof, int *err_stat); + #ifdef __cplusplus } #endif diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 035060bf..6c7fdd97 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -283,7 +283,8 @@ MODULE CableDyn_DeckDriver CHARACTER(*), PARAMETER :: INSPECTION_NOTE = ' Output contains only committed states and is for inspection only.' ! a line restrained in torsion on an entry whose caller does not turn the fairlead frame CHARACTER(*), PARAMETER :: TORSION_NEEDS_ORIENTATION = 'a line restrained in torsion needs a host that '// & - 'turns its fairlead frame: coupled OpenFAST and FAST.Farm runs do, while the C API '// & + 'turns its fairlead frame: coupled OpenFAST and FAST.Farm runs do, and a C API host '// & + 'initialised with CableDyn_InitDeckRotating, while CableDyn_InitDeck/InitDeckAt '// & 'and a standalone deck that mixes EI = 0 and finite-EI lines without a BODY move '// & 'the line ends by translation only (with a BODY such a deck runs on the multibody '// & 'route, which supports torsion); set TorsStiffness Free in every END CONNECTIONS row' diff --git a/src/cabledyn.def b/src/cabledyn.def index 9d2679d4..107e180e 100644 --- a/src/cabledyn.def +++ b/src/cabledyn.def @@ -9,6 +9,7 @@ EXPORTS CableDyn_GetAbiMinor CableDyn_GetBodyState CableDyn_GetCoupledLayout + CableDyn_GetCoupledMoments CableDyn_GetCoupledMotion CableDyn_GetLastError CableDyn_GetLineValues @@ -19,6 +20,7 @@ EXPORTS CableDyn_GetVersionString CableDyn_InitDeck CableDyn_InitDeckAt + CableDyn_InitDeckRotating CableDyn_InitLine CableDyn_InitLines CableDyn_IsInitialized @@ -30,4 +32,5 @@ EXPORTS CableDyn_SaveState CableDyn_Step CableDyn_UpdatePointFluidFields + CableDyn_UpdateRotations CableDyn_UpdateStates diff --git a/src/cabledyn.exp b/src/cabledyn.exp index 945fcb2f..7c6ff0d0 100644 --- a/src/cabledyn.exp +++ b/src/cabledyn.exp @@ -8,6 +8,7 @@ _CableDyn_EvalChannel _CableDyn_GetAbiMinor _CableDyn_GetBodyState _CableDyn_GetCoupledLayout +_CableDyn_GetCoupledMoments _CableDyn_GetCoupledMotion _CableDyn_GetLastError _CableDyn_GetLineValues @@ -18,6 +19,7 @@ _CableDyn_GetVersion _CableDyn_GetVersionString _CableDyn_InitDeck _CableDyn_InitDeckAt +_CableDyn_InitDeckRotating _CableDyn_InitLine _CableDyn_InitLines _CableDyn_IsInitialized @@ -29,4 +31,5 @@ _CableDyn_RestoreState _CableDyn_SaveState _CableDyn_Step _CableDyn_UpdatePointFluidFields +_CableDyn_UpdateRotations _CableDyn_UpdateStates diff --git a/src/cabledyn.map b/src/cabledyn.map index 125f69b0..53952d5c 100644 --- a/src/cabledyn.map +++ b/src/cabledyn.map @@ -11,6 +11,7 @@ CableDyn_GetAbiMinor; CableDyn_GetBodyState; CableDyn_GetCoupledLayout; + CableDyn_GetCoupledMoments; CableDyn_GetCoupledMotion; CableDyn_GetLastError; CableDyn_GetLineValues; @@ -21,6 +22,7 @@ CableDyn_GetVersionString; CableDyn_InitDeck; CableDyn_InitDeckAt; + CableDyn_InitDeckRotating; CableDyn_InitLine; CableDyn_InitLines; CableDyn_IsInitialized; @@ -32,6 +34,7 @@ CableDyn_SaveState; CableDyn_Step; CableDyn_UpdatePointFluidFields; + CableDyn_UpdateRotations; CableDyn_UpdateStates; local: *; diff --git a/tests/test_c_api_host_coupling.c b/tests/test_c_api_host_coupling.c index d85fbec6..c3b65c30 100644 --- a/tests/test_c_api_host_coupling.c +++ b/tests/test_c_api_host_coupling.c @@ -206,8 +206,8 @@ static int edit_deck(const char *in_path, const char *out_path, const char *old_ static int check_version(void) { - CHECK(CABLEDYN_CAPI_ABI_MINOR == 2 && CableDyn_GetAbiMinor() == CABLEDYN_CAPI_ABI_MINOR, - "ABI minor level 2"); + CHECK(CABLEDYN_CAPI_ABI_MINOR >= 2 && CableDyn_GetAbiMinor() == CABLEDYN_CAPI_ABI_MINOR, + "ABI minor level 2 or later"); return 0; } diff --git a/tests/test_c_api_host_rotation.c b/tests/test_c_api_host_rotation.c new file mode 100644 index 00000000..963e5fb6 --- /dev/null +++ b/tests/test_c_api_host_rotation.c @@ -0,0 +1,404 @@ +/* File: tests/test_c_api_host_rotation.c + * SPDX-License-Identifier: Apache-2.0 + * Host-rotation gate of C ABI 1 minor extension 3, through the public header + * and the shared library. + * + * Usage: test_c_api_host_rotation + * + * The test writes the straight neutral torsion line of test_coupled_torsion + * (GJ 5e4 N m^2, 100 m along +x from the Coupled fairlead (0, 0, -50) to a + * Fixed anchor, 40 elements, both ends clamped and restrained in torsion, a + * negligible polar inertia: the quasi-static torsion) and checks: + * - CableDyn_InitDeck refuses the deck and names CableDyn_InitDeckRotating, + * which accepts it (statics at the deck positions, rotations at rest); + * - feedthrough: CableDyn_UpdateRotations with a 20 deg roll about the line + * axis, then CableDyn_UpdateStates, twists the end element alone (Twist1 = + * -20 deg); CableDyn_GetCoupledMoments returns its torque GJ phi / l_e about + * the line axis, resisting the roll, and no bending moment; + * - march: a roll at 60 deg/s gives Twist1 = -phi(t) and the quasi-static + * torque GJ phi / L at both ends and as the coupled moment, at every step; + * - SaveState/RestoreState carry the rotations: a restore after other + * rotations were set steps bit-identically to the step from the save; + * - the rejections are all or nothing: a wrong block count, a null pointer, a + * DCM that is not proper orthogonal and a non-finite rate leave the handle + * stepping bit-identically to one that never saw them; + * - a handle initialised without rotations refuses CableDyn_UpdateRotations; + * the EI = 0 point route (box_points.dat) takes rotations and ignores them, + * and its coupled moments are zero. + * The decks this test writes are removed on every exit path. + */ +#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) + +/* 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 PI 3.14159265358979323846 +#define DEG (PI / 180.0) +#define GJ 5.0e4 +#define LEN 100.0 +#define NSEG 40 +#define DT 0.05 + +static const char *g_box; + +#define TORSION_DECK "capi_rot_torsion.dat" +#define FREE_DECK "capi_rot_free.dat" +static const char *const g_written[] = {TORSION_DECK, FREE_DECK}; + +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) +{ + char msg[1025]; + CableDyn_GetLastError(h, msg, (int)sizeof msg); + fprintf(stderr, "FAIL: %s (status %d): %s\n", where, err, msg); +} + +static int last_error_has(void *h, const char *text) +{ + char msg[4097]; + CableDyn_GetLastError(h, msg, (int)sizeof msg); + return strstr(msg, text) != NULL; +} + +/* The straight neutral torsion line; tors = "Rigid" (restrained) or "Free". */ +static int write_deck(const char *path, const char *tors) +{ + FILE *f = fopen(path, "w"); + if (!f) return 1; + fputs("host rotation gate\n--- LINE TYPES ---\n", f); + fputs("Name Diam Mass EA BA EI GAs GJ Irt Irn Cdn Cdt Can Cat\n", f); + fputs("(-) (m) (kg/m) (N) (-) (Nm2) (N) (Nm2) (kgm) (kgm) (-) (-) (-) (-)\n", f); + fprintf(f, "cab 0.2 %.16e 1.0e7 0.0 1.0e6 1.0e8 5.0e4 1.0 1.0e-9 0.0 0.0 0.0 0.0\n", 1025.0 * 0.25 * PI * 0.04); + fputs("--- POINTS ---\nID Type X Y Z Mass Vol CdA Ca\n(-) (-) (m) (m) (m) (kg) (m3) (m2) (-)\n", f); + fputs("1 Coupled 0.0 0.0 -50.0 0 0 0 0\n2 Fixed 100.0 0.0 -50.0 0 0 0 0\n", f); + fputs("--- LINES ---\nID NodeA NodeB Outputs\n(-) (-) (-) (-)\n1 1 2 -\n", f); + fputs("--- SECTIONS ---\nLineID LineType Length NumSegs\n(-) (-) (m) (-)\n1 cab 100.0 40\n", f); + fputs("--- END CONNECTIONS ---\nLineID End Stiffness EzX EzY EzZ TorsStiffness NxX NxY NxZ Pretwist\n", f); + fputs("(-) (-) (N-m/rad) (-) (-) (-) (N-m/rad) (-) (-) (-) (deg)\n", f); + fprintf(f, "1 A Rigid 1 0 0 %s 0 0 1 0\n1 B Rigid 1 0 0 %s 0 0 1 0\n", tors, tors); + fputs("--- OPTIONS ---\n9.80665 g\n1025.0 rhoW\n0.05 dtM\n0.0 TMax\n", f); + fputs(strcmp(tors, "Free") == 0 ? "--- OUTPUTS ---\nFairTen1\n--- END ---\n" + : "--- OUTPUTS ---\nTorq1N1\nTorq1N41\nTwist1\n--- END ---\n", + f); + return fclose(f) != 0; +} + +/* OpenFAST mesh orientation (global to local) of a roll phi about +x, row-major. */ +static void roll_dcm(double phi, double *r) +{ + const double c = cos(phi), s = sin(phi); + const double m[9] = {1.0, 0.0, 0.0, 0.0, c, s, 0.0, -s, c}; + memcpy(r, m, sizeof m); +} + +static int channel(void *h, const char *token, double *value) +{ + int err = -1; + CableDyn_EvalChannel(h, token, (int)strlen(token), value, &err); + if (err != CD_C_OK) { + report(h, token, err); + return 1; + } + return 0; +} + +static int rotate(void *h, double phi, double rate) +{ + double r[9]; + const double om[3] = {rate, 0.0, 0.0}, al[3] = {0.0, 0.0, 0.0}; + int err = -1; + roll_dcm(phi, r); + CableDyn_UpdateRotations(h, r, om, al, 1, &err); + if (err != CD_C_OK) { + report(h, "UpdateRotations", err); + return 1; + } + return 0; +} + +static int step_at_deck(void *h) +{ + const double q[3] = {0.0, 0.0, -50.0}, z[3] = {0.0, 0.0, 0.0}; + bool converged = false, stalled = false; + int n_iter = 0, err = -1; + CableDyn_Step(h, DT, q, z, z, 3, &converged, &stalled, &n_iter, &err); + if (err != CD_C_OK || !converged) { + report(h, "Step", err); + return 1; + } + return 0; +} + +static int moments(void *h, double *m) +{ + int err = -1; + CableDyn_GetCoupledMoments(h, m, 3, &err); + if (err != CD_C_OK) { + report(h, "GetCoupledMoments", err); + return 1; + } + return 0; +} + +static int init_rotating(void **h, const char *deck) +{ + int err = -1; + CableDyn_Create(h, &err); + CHECK(err == CD_C_OK, "create"); + CableDyn_InitDeckRotating(*h, deck, (int)strlen(deck), NULL, 0, &err); + if (err != CD_C_OK) { + report(*h, "InitDeckRotating", err); + return 1; + } + return 0; +} + +static void close_handle(void **h) +{ + int err; + if (*h) CableDyn_Close(h, &err); + *h = NULL; +} + +static int check_init(void) +{ + void *h = NULL; + int err = -1, failed = 1; + CHECK(CableDyn_GetAbiMinor() >= 3, "the library declares ABI minor 3"); + CableDyn_Create(&h, &err); + REQUIRE(err == CD_C_OK, "create"); + CableDyn_InitDeck(h, TORSION_DECK, (int)strlen(TORSION_DECK), &err); + if (err != CD_C_BAD_INPUT || !last_error_has(h, "CableDyn_InitDeckRotating")) { + report(h, "InitDeck refuses a line restrained in torsion, naming CableDyn_InitDeckRotating", err); + goto done; + } + close_handle(&h); + if (init_rotating(&h, TORSION_DECK)) goto done; + REQUIRE(CableDyn_NCoupledDOF(h, &err) == 3 && err == CD_C_OK, "one coupled point"); + { + double ta, tw, m[3]; + if (channel(h, "Torq1N1", &ta) || channel(h, "Twist1", &tw) || moments(h, m)) goto done; + REQUIRE(fabs(ta) <= 1.0e-6 && fabs(tw) <= 1.0e-9, "no pretwist, no torque at rest"); + REQUIRE(fabs(m[0]) <= 1.0e-6, "no coupled torque at rest"); + } + /* a handle without rotations refuses them */ + close_handle(&h); + CableDyn_Create(&h, &err); + REQUIRE(err == CD_C_OK, "create"); + CableDyn_InitDeck(h, FREE_DECK, (int)strlen(FREE_DECK), &err); + if (err != CD_C_OK) { + report(h, "InitDeck (torsion free)", err); + goto done; + } + { + double r[9]; + const double z[3] = {0.0, 0.0, 0.0}; + roll_dcm(0.1, r); + CableDyn_UpdateRotations(h, r, z, z, 1, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(h, "CableDyn_InitDeckRotating"), + "a handle initialised by CableDyn_InitDeck refuses rotations"); + } + puts("init: InitDeck refuses the torsion deck, InitDeckRotating takes it at rest"); + failed = 0; +done: + close_handle(&h); + return failed; +} + +static int check_feedthrough(void) +{ + void *h = NULL; + int err = -1, failed = 1; + const double phi = 20.0 * DEG, le = LEN / NSEG, m_ref = GJ * phi / le; + const double q[3] = {0.0, 0.0, -50.0}, z[3] = {0.0, 0.0, 0.0}; + double ta, tb, tw, m[3]; + if (init_rotating(&h, TORSION_DECK)) goto done; + if (rotate(h, phi, 0.0)) goto done; + CableDyn_UpdateStates(h, q, z, z, 3, &err); + if (err != CD_C_OK) { + report(h, "UpdateStates", err); + goto done; + } + if (channel(h, "Torq1N1", &ta) || channel(h, "Torq1N41", &tb) || channel(h, "Twist1", &tw) || moments(h, m)) + goto done; + printf("feedthrough: Twist1 %.9f deg, Torq1N1 %.6e (ref %.6e), coupled moment %.6e %.3e %.3e\n", tw, ta, + -m_ref, m[0], m[1], m[2]); + REQUIRE(fabs(tw + 20.0) <= 1.0e-6, "feedthrough: Twist1 = -roll"); + REQUIRE(fabs(ta + m_ref) <= 1.0e-6 * m_ref && fabs(tb) <= 1.0e-9 * m_ref, + "feedthrough: the end element alone takes the twist"); + REQUIRE(fabs(fabs(m[0]) - m_ref) <= 1.0e-6 * m_ref, "feedthrough: the coupled moment is the torque"); + REQUIRE(m[0] * phi < 0.0, "feedthrough: the moment on the host resists its roll"); + REQUIRE(fmax(fabs(m[1]), fabs(m[2])) <= 1.0e-6 * m_ref, "feedthrough: a straight line has no bending moment"); + failed = 0; +done: + close_handle(&h); + return failed; +} + +static int check_march(void) +{ + void *h = NULL; + int failed = 1; + const double rate = 60.0 * DEG; + double werr = 0.0, terr = 0.0, merr = 0.0; + if (init_rotating(&h, TORSION_DECK)) goto done; + for (int k = 1; k <= 10; ++k) { + const double phi = rate * DT * k; + double ta, tb, tw, m[3]; + if (rotate(h, phi, rate) || step_at_deck(h)) goto done; + if (channel(h, "Torq1N1", &ta) || channel(h, "Torq1N41", &tb) || channel(h, "Twist1", &tw) || moments(h, m)) + goto done; + werr = fmax(werr, fabs(tw + phi / DEG)); + terr = fmax(terr, fmax(fabs(ta + GJ * phi / LEN), fabs(tb - ta))); + merr = fmax(merr, fmax(fabs(m[0] + GJ * phi / LEN), fmax(fabs(m[1]), fabs(m[2])))); + } + printf("march: Twist1 error %.3e deg, torque error %.3e N m, coupled moment error %.3e N m\n", werr, terr, merr); + REQUIRE(werr <= 1.0e-6, "march: Twist1 = -roll(t) at every step"); + REQUIRE(terr <= 1.0e-6 * GJ, "march: Torq = GJ Twist / L at both ends at every step"); + REQUIRE(merr <= 1.0e-6 * GJ, "march: the coupled moment is the restoring torque at every step"); + failed = 0; +done: + close_handle(&h); + return failed; +} + +static int check_save_restore(void) +{ + void *h = NULL; + int err = -1, failed = 1; + const double rate = 60.0 * DEG; + double m1[3], m2[3], tw1, tw2; + if (init_rotating(&h, TORSION_DECK)) goto done; + for (int k = 1; k <= 4; ++k) + if (rotate(h, rate * DT * k, rate) || step_at_deck(h)) goto done; + if (rotate(h, rate * DT * 5, rate)) goto done; + CableDyn_SaveState(h, &err); + REQUIRE(err == CD_C_OK, "SaveState"); + if (step_at_deck(h) || moments(h, m1) || channel(h, "Twist1", &tw1)) goto done; + /* other rotations set and stepped before the restore */ + if (rotate(h, rate * DT * 9, 3.0 * rate) || step_at_deck(h)) goto done; + CableDyn_RestoreState(h, &err); + REQUIRE(err == CD_C_OK, "RestoreState"); + if (step_at_deck(h) || moments(h, m2) || channel(h, "Twist1", &tw2)) goto done; + printf("save/restore: coupled torque %.9e and %.9e\n", m1[0], m2[0]); + REQUIRE(memcmp(m1, m2, sizeof m1) == 0 && tw1 == tw2, + "a restore brings back the saved rotations and steps bit-identically"); + failed = 0; +done: + close_handle(&h); + return failed; +} + +static int check_rejections(void) +{ + void *a = NULL, *b = NULL; + int err = -1, failed = 1; + const double rate = 60.0 * DEG; + double r[9], ma[3], mb[3]; + const double z[3] = {0.0, 0.0, 0.0}; + if (init_rotating(&a, TORSION_DECK) || init_rotating(&b, TORSION_DECK)) goto done; + for (int k = 1; k <= 3; ++k) { + const double phi = rate * DT * k; + if (rotate(a, phi, rate) || rotate(b, phi, rate)) goto done; + /* rejected updates on a only */ + roll_dcm(phi + 0.5, r); + CableDyn_UpdateRotations(a, r, z, z, 2, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(a, "n_block"), "a wrong block count is refused"); + CableDyn_UpdateRotations(a, r, NULL, z, 1, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(a, "null"), "a null pointer is refused"); + for (int i = 0; i < 9; ++i) r[i] *= 1.01; + CableDyn_UpdateRotations(a, r, z, z, 1, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(a, "proper orthogonal"), + "a DCM that is not proper orthogonal is refused"); + roll_dcm(phi + 0.5, r); + { + const double nan_rate[3] = {NAN, 0.0, 0.0}; + CableDyn_UpdateRotations(a, r, nan_rate, z, 1, &err); + REQUIRE(err == CD_C_BAD_INPUT && last_error_has(a, "finite"), "a non-finite rate is refused"); + } + if (step_at_deck(a) || step_at_deck(b)) goto done; + } + if (moments(a, ma) || moments(b, mb)) goto done; + REQUIRE(memcmp(ma, mb, sizeof ma) == 0, "rejected rotations leave the handle unchanged"); + puts("rejections: block count, null pointer, DCM, rate refused; the handle steps unchanged"); + failed = 0; +done: + close_handle(&a); + close_handle(&b); + return failed; +} + +static int check_point_route(void) +{ + void *h = NULL; + int err = -1, failed = 1, n, nb; + double *dcm = NULL, *om = NULL, *m = NULL; + if (init_rotating(&h, g_box)) goto done; + n = CableDyn_NCoupledDOF(h, &err); + REQUIRE(err == CD_C_OK && n > 0 && n % 3 == 0, "the box has coupled blocks"); + nb = n / 3; + dcm = calloc((size_t)(9 * nb), sizeof *dcm); + om = calloc((size_t)(3 * nb), sizeof *om); + m = malloc((size_t)n * sizeof *m); + REQUIRE(dcm && om && m, "allocation"); + for (int k = 0; k < nb; ++k) roll_dcm(0.3, dcm + 9 * k); + CableDyn_UpdateRotations(h, dcm, om, om, nb, &err); + REQUIRE(err == CD_C_OK, "the point route takes rotations"); + for (int i = 0; i < n; ++i) m[i] = 1.0; + CableDyn_GetCoupledMoments(h, m, n, &err); + REQUIRE(err == CD_C_OK, "GetCoupledMoments on the point route"); + for (int i = 0; i < n; ++i) REQUIRE(m[i] == 0.0, "EI = 0 lines apply no moment"); + puts("point route: rotations taken and unused, moments zero"); + failed = 0; +done: + free(dcm); + free(om); + free(m); + close_handle(&h); + return failed; +} + +int main(int argc, char **argv) +{ + int failed; + if (argc != 2) { + fputs("usage: test_c_api_host_rotation \n", stderr); + return 2; + } + g_box = argv[1]; + remove_written_decks(); + if (write_deck(TORSION_DECK, "Rigid") || write_deck(FREE_DECK, "Free")) { + fputs("FAIL: writing the decks\n", stderr); + remove_written_decks(); + return 1; + } + failed = check_init() || check_feedthrough() || check_march() || check_save_restore() || check_rejections() || + check_point_route(); + remove_written_decks(); + if (failed) return 1; + puts("PASS: CableDyn C API host rotations"); + return 0; +} From 0c458f217ae6e6d0e8fcae3e73825c1c5c60d921 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Fri, 30 Oct 2026 15:59:56 +0900 Subject: [PATCH 2/2] style(python): the host-rotation test passes ruff Use the cabledyn import and wrap a long line in test_host_rotation. Signed-off-by: Jae Hoon Seo --- python/tests/test_host_rotation.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/python/tests/test_host_rotation.py b/python/tests/test_host_rotation.py index f741d289..6e2aaffe 100644 --- a/python/tests/test_host_rotation.py +++ b/python/tests/test_host_rotation.py @@ -21,6 +21,7 @@ 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 @@ -63,7 +64,7 @@ def _roll(phi: float) -> np.ndarray: def test_abi_minor_reports_the_host_rotation_extension(): assert _lib.HOST_ROTATION_ABI_MINOR == 3 - assert _lib.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR + assert _lib.abi_minor() == cabledyn.abi_minor() == _lib.HOST_ROTATION_ABI_MINOR def test_torsion_deck_needs_the_rotating_initialization(tmp_path): @@ -123,5 +124,6 @@ def test_point_route_takes_rotations_and_returns_no_moment(): with CableDyn() as model: model.init_deck_rotating(BOX) nb = model.n_coupled_dof // 3 - model.update_rotations(np.repeat(_roll(0.3), nb, axis=0), np.zeros((nb, 3)), np.zeros((nb, 3))) + dcm = np.repeat(_roll(0.3), nb, axis=0) + model.update_rotations(dcm, np.zeros((nb, 3)), np.zeros((nb, 3))) assert np.array_equal(model.coupled_moments(), np.zeros(3 * nb))