diff --git a/doc/api_python.rst b/doc/api_python.rst index 93aeefdc..e5df1d65 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -494,6 +494,66 @@ library is located. Array ordering, frames, and units at the coupling boundary f Release the native handle. Calling it again is harmless. + .. py:method:: init_line(q0, v0, elem_conn, l0, ea, rho_a, fixed_dofs, tension_only, rho_inf) + + Initialise from one line meshed by the caller (``CableDyn_InitLine``). The model is + structural only: two-node ``EI = 0`` axial elements with a consistent mass matrix, without + gravity, buoyancy, seabed, hydrodynamics or structural damping, and without a static solve. + The handle has no deck and no points; the views of :attr:`lines` run from the last node of + ``q0`` to its first. + + :param q0: Initial node positions (m), flat ``(3 * n_nodes,)`` or column-per-point + ``(3, n_nodes)``; a ``(3, 3)`` array is rejected as ambiguous. + :type q0: array_like + :param v0: Initial node velocities (m/s), shaped as ``q0``. + :type v0: array_like + :param elem_conn: **1-based** node pair of each element, flat ``(2 * n_elem,)`` or + ``(n_elem, 2)``. An integer array. + :type elem_conn: array_like + :param l0: Unstretched length of each element (m), ``(n_elem,)``. + :type l0: array_like + :param ea: Axial stiffness of each element (N), ``(n_elem,)``. + :type ea: array_like + :param rho_a: Mass per unit unstretched length of each element (kg/m), ``(n_elem,)``. + :type rho_a: array_like + :param fixed_dofs: **1-based** DOFs the caller prescribes, in the order of the coupled + vector; node ``k`` owns DOFs ``3k-2``, ``3k-1`` and ``3k``. May be empty. + :type fixed_dofs: array_like + :param tension_only: If true an element goes slack instead of carrying compression. + :type tension_only: bool + :param rho_inf: Generalised-α spectral radius, in ``[0, 1]``. + :type rho_inf: float + :raises ValueError: on a wrong shape, a non-finite value, or ``rho_inf`` outside + ``[0, 1]``, before the library is called. + :raises TypeError: on a non-real array, a non-integer index array, or a non-numeric + scalar, before the library is called. + :raises CableDynError: if the library rejects the values (an index out of range, a repeated + fixed DOF, a non-positive ``l0``, ``ea`` or ``rho_a``) or the initial acceleration solve + fails. The handle must then be initialised again and a saved state is lost, unless it + held a model on the coupled aggregate, which stays live with its save. + + .. py:method:: init_lines(n_nodes, n_elem, n_fixed, q0, v0, elem_conn, l0, ea, rho_a, fixed_dofs, tension_only, rho_inf, coupled_map=None) + + Initialise from several lines meshed by the caller (``CableDyn_InitLines``), each as in + :meth:`init_line`, in one system. Every array is the concatenation, in line order, of that + line's :meth:`init_line` array; ``elem_conn`` and ``fixed_dofs`` stay local to each line. + + :param n_nodes: Node count of each line, at least 2. + :type n_nodes: array_like + :param n_elem: Element count of each line, at least 1. + :type n_elem: array_like + :param n_fixed: Prescribed DOF count of each line, at least 0. + :type n_fixed: array_like + :param coupled_map: Connects lines at shared points. Every line has exactly six fixed DOFs, + and entry ``6 * i + j`` (0-based ``i``, ``j``) is the **1-based** system DOF of line + ``i``'s ``j``-th fixed DOF. The entries use every index from 1 to their maximum, which is + the coupled DOF count; loads and Jacobian entries of a shared DOF are summed. ``None`` + keeps the lines independent, their ``fixed_dofs`` in turn forming the coupled vector. + :type coupled_map: array_like | None + :raises ValueError: as :meth:`init_line`, and if the counts do not match the arrays. + :raises TypeError: as :meth:`init_line`. + :raises CableDynError: as :meth:`init_line`, and on a ``coupled_map`` with a gap. + .. py:method:: last_error() Return the library's most recent diagnostic message for this instance. @@ -753,6 +813,33 @@ library is located. Array ordering, frames, and units at the coupling boundary f :raises CableDynError: on a model built without a host fluid field, or if the call fails. + .. py:method:: calc_output_derivatives(q, v, a) + + Return the coupled loads at an operating point and their analytic Jacobians + (``CableDyn_CalcOutputDerivatives``). Each line's interior DOFs are condensed out: interior + positions and velocities are held and interior accelerations eliminated through the mass + matrix, so ``dload_da`` is :math:`-(M_{cc} - M_{cf} M_{ff}^{-1} M_{fc})`, and the blocks are + those of :meth:`update_states` followed by :meth:`calc_output`. + + This call **sets the model state**, as :meth:`update_states` does, also when a later stage + of it fails; the previous state is not restored and :attr:`time` does not change. The + library's unused ``eps_fd`` argument is not exposed. + + :param q: Operating-point positions (m). + :type q: array_like + :param v: Operating-point velocities (m/s). + :type v: array_like + :param a: Operating-point accelerations (m/s\ :sup:`2`). + :type a: array_like + :returns: ``(loads, dload_dq, dload_dv, dload_da, added_mass)``. ``loads`` is flat, + ``(n_coupled_dof,)`` (N). The others are ``(n_coupled_dof, n_coupled_dof)`` with + ``J[i, j]`` the derivative of load ``i`` with respect to coupled DOF ``j``: N/m, N·s/m, + kg and kg; ``added_mass`` is ``-dload_da``. + :rtype: tuple[numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray, numpy.ndarray] + :raises ValueError: if an array has the wrong shape or a non-finite value. + :raises CableDynError: if the library rejects the call, as on a model on the coupled + aggregate (finite-EI lines, bodies or rods), which has no load derivatives. + .. py:method:: update_point_fluid_fields(fluid_velocity, fluid_acceleration, waterline_z, fluid_density) Prescribe external fluid kinematics at every system point. diff --git a/doc/capi.rst b/doc/capi.rst index 5b647bb3..5f592f87 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -348,8 +348,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 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 + ``CableDyn_InitLines`` build the point model in place: a failure during the build leaves the + handle to be initialised again, an input rejected before it leaves the previous model live + (``CableDyn_IsInitialized`` tells which), and either way 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 diff --git a/doc/python.rst b/doc/python.rst index 75dc5427..9e123114 100644 --- a/doc/python.rst +++ b/doc/python.rst @@ -762,10 +762,8 @@ environment variable ``CABLEDYN_BLAS_THREADS`` changes that (:doc:`capi`). Array ordering is defined in :ref:`capi:Calling conventions`; frames, fluid fields, and lifecycle rules are defined in :doc:`coupling_boundary`. Use this API only when the Python process owns time integration; use ``CompMooring = 5`` for OpenFAST (:doc:`openfast`). The Python -class covers deck initialisation and the coupled step/output cycle; raw-array initialisation -(``CableDyn_InitLine`` and -``CableDyn_InitLines``) and output Jacobians (``CableDyn_CalcOutputDerivatives``) are available -through the C API (:doc:`capi`). +class covers deck initialisation, raw-array lines, the coupled step/output cycle and the load +Jacobians (see `Raw-array lines and load Jacobians`_). A deck with finite-EI lines, ``BODIES`` or ``RODS`` runs on the coupled aggregate and needs ``dtM``; other decks run on the point route. Decks with deck waves, a ``motionFile`` or vessel @@ -831,6 +829,63 @@ start time of the pass, so a pass retried with a smaller ``dt`` restores as well self.model.step(dt, self.q, self.v, self.a) return self.model.calc_output()[self.host].reshape(3, -1, order="F") +Raw-array lines and load Jacobians +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +:meth:`~cabledyn.CableDyn.init_line` and :meth:`~cabledyn.CableDyn.init_lines` build a model from +lines the caller has meshed, without a deck. These lines are **structural only**: two-node +``EI = 0`` axial elements with a consistent mass matrix, without gravity, buoyancy, seabed, +hydrodynamics or structural damping, and without a static solve, so the state starts at ``q0``, +``v0`` exactly. Use a deck for anything else. As in the C API, ``elem_conn``, ``fixed_dofs`` and +``coupled_map`` are **1-based**, and the order of ``fixed_dofs`` is the order of the coupled +vector: + +.. code-block:: python + + import numpy as np + from cabledyn import CableDyn + + n_elem = 10 + nodes = np.linspace(0.0, 1.0, n_elem + 1)[:, None] * [100.5, 0.0, 0.0] + first = np.arange(1, n_elem + 1) + + with CableDyn() as model: + model.init_line( + q0=nodes.reshape(-1), + v0=np.zeros(nodes.size), + elem_conn=np.column_stack([first, first + 1]), # 1-based node pairs + l0=np.full(n_elem, 10.0), # m + ea=np.full(n_elem, 1.0e7), # N + rho_a=np.full(n_elem, 50.0), # kg/m + fixed_dofs=[1, 2, 3, 31, 32, 33], # both end nodes, 1-based + tension_only=True, + rho_inf=0.8, + ) + q, v, a = model.get_coupled_motion() + loads, dload_dq, dload_dv, dload_da, added_mass = model.calc_output_derivatives(q, v, a) + +:meth:`~cabledyn.CableDyn.init_lines` takes the counts of each line, then the same arrays +concatenated in line order, with connectivity and ``fixed_dofs`` local to each line. Its optional +``coupled_map`` connects lines at shared points; see ``CableDyn_InitLines`` in :doc:`capi`. +Shapes, non-finite values and non-integer indices raise ``ValueError`` or ``TypeError`` before the +library is called, which changes nothing. The library judges the values (an index out of range, a +repeated fixed DOF, a non-positive length) and raises :class:`cabledyn.CableDynError`; the handle +must then be initialised again, unless it held a model on the coupled aggregate, which stays live. + +:meth:`~cabledyn.CableDyn.calc_output_derivatives` returns the loads at an operating point and +their analytic Jacobians, ``J[i, j]`` being the derivative of load ``i`` with respect to coupled +DOF ``j``, and works on raw lines and on decks of the point route. A model on the coupled aggregate +has no load derivatives and raises :class:`cabledyn.CableDynError`. Each line's interior DOFs are +condensed out: interior positions and velocities are held and interior accelerations eliminated +through the mass matrix, so the blocks are those of ``update_states`` followed by ``calc_output``, +the instantaneous response of the end loads to the end motion. ``added_mass`` is ``-dload_da``. + +.. warning:: + + ``calc_output_derivatives`` **sets the model state**: on return the model is at the operating + point, as after ``update_states``, and the previous state is not restored. Call + ``update_states`` with the previous kinematics to return to them. + Objects and output channels ~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/python/cabledyn/_lib.py b/python/cabledyn/_lib.py index 910b4e5f..8db7444e 100644 --- a/python/cabledyn/_lib.py +++ b/python/cabledyn/_lib.py @@ -87,6 +87,46 @@ def library_path() -> str: _lib.CableDyn_GetLastError.restype = None _DBL = POINTER(c_double) +_INT = POINTER(c_int) + +_lib.CableDyn_InitLine.argtypes = [ + c_void_p, + c_int, + c_int, + _DBL, + _DBL, + _INT, + _DBL, + _DBL, + _DBL, + _INT, + c_int, + c_int, + c_double, + _INT, +] +_lib.CableDyn_InitLine.restype = None + +_lib.CableDyn_InitLines.argtypes = [ + c_void_p, + c_int, + _INT, + _INT, + _INT, + _DBL, + _DBL, + _INT, + _DBL, + _DBL, + _DBL, + _INT, + _INT, + c_int, + c_int, + c_double, + _INT, +] +_lib.CableDyn_InitLines.restype = None _lib.CableDyn_UpdateStates.argtypes = [c_void_p, _DBL, _DBL, _DBL, c_int, POINTER(c_int)] _lib.CableDyn_UpdateStates.restype = None @@ -108,6 +148,22 @@ def library_path() -> str: _lib.CableDyn_CalcOutput.argtypes = [c_void_p, _DBL, c_int, POINTER(c_int)] _lib.CableDyn_CalcOutput.restype = None +_lib.CableDyn_CalcOutputDerivatives.argtypes = [ + c_void_p, + _DBL, + _DBL, + _DBL, + c_int, + c_double, + _DBL, + _DBL, + _DBL, + _DBL, + _DBL, + _INT, +] +_lib.CableDyn_CalcOutputDerivatives.restype = None + _lib.CableDyn_GetCoupledMotion.argtypes = [c_void_p, _DBL, _DBL, _DBL, c_int, POINTER(c_int)] _lib.CableDyn_GetCoupledMotion.restype = None diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index 4150c4a8..014dda9b 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -35,6 +35,7 @@ __all__ = ["Body", "CableDyn", "CableDynError", "ConvergenceError", "Line", "Point", "Rod"] FloatArray = npt.NDArray[np.float64] +IntArray = npt.NDArray[np.intc] ArrayInput = npt.ArrayLike # The C library retains up to 4096 characters per handle; +1 for the NUL. @@ -105,23 +106,104 @@ def _dbl_ptr(arr: FloatArray) -> Any: return arr.ctypes.data_as(POINTER(c_double)) -def _host_positions(q0: ArrayInput) -> FloatArray: +def _int_ptr(arr: IntArray) -> Any: + return arr.ctypes.data_as(POINTER(c_int)) + + +def _as_index_array(x: ArrayInput, name: str) -> IntArray: + """Return ``x`` as a contiguous C ``int`` array, rejecting non-integer input. + + Connectivity, DOF and count arrays stay exact: a float array is not rounded to one. + """ + src = np.asarray(x) + if src.size == 0: + return np.zeros(src.shape, dtype=np.intc) + if src.dtype.kind not in "iu": + raise TypeError(f"{name} must be an integer array; got dtype {src.dtype}") + limits = np.iinfo(np.intc) + if int(src.min()) < limits.min or int(src.max()) > limits.max: + raise ValueError(f"{name} holds a value outside the range of a C int") + return np.ascontiguousarray(src, dtype=np.intc) + + +def _as_flag(value: object, name: str) -> int: + """Return a true-or-false argument as the C ``int`` 1 or 0.""" + if not isinstance(value, (bool, np.bool_, numbers.Integral)): + raise TypeError(f"{name} must be a boolean; got {type(value).__name__}") + return 1 if value else 0 + + +def _as_spectral_radius(value: object) -> float: + """Return ``rho_inf``, a finite real number in ``[0, 1]``.""" + result = _as_real_scalar(value, "rho_inf", positive=False) + if result > 1.0: + raise ValueError(f"rho_inf must lie in [0, 1]; got {result}") + return result + + +def _as_element_array(x: ArrayInput, n_elem: int, name: str) -> FloatArray: + """Return a per-element array: flat, ``n_elem`` finite values.""" + arr = _as_real_array(x, name) + if arr.ndim != 1 or arr.size != n_elem: + raise ValueError(f"{name} must be flat ({n_elem},); got shape {np.shape(x)}") + if not np.all(np.isfinite(arr)): + raise ValueError(f"{name} must be finite (no NaN or Inf)") + return arr + + +def _raw_line_arrays( + q0: ArrayInput, + v0: ArrayInput, + elem_conn: ArrayInput, + l0: ArrayInput, + ea: ArrayInput, + rho_a: ArrayInput, + fixed_dofs: ArrayInput, +) -> tuple[FloatArray, FloatArray, IntArray, FloatArray, FloatArray, FloatArray, IntArray]: + """The arrays of :meth:`CableDyn.init_line` and :meth:`CableDyn.init_lines`, checked for shape. + + Returns them in that order, each flat. The values are the library's to judge. + """ + q = _host_positions(q0) + v = _host_positions(v0, "v0") + if v.size != q.size: + raise ValueError(f"v0 must hold as many values as q0 ({q.size}); got {v.size}") + length = _as_real_array(l0, "l0") + if length.ndim != 1: + raise ValueError(f"l0 must be flat (n_elem,); got shape {np.shape(l0)}") + n_elem = int(length.size) + length = _as_element_array(length, n_elem, "l0") + stiffness = _as_element_array(ea, n_elem, "ea") + mass = _as_element_array(rho_a, n_elem, "rho_a") + conn = _as_index_array(elem_conn, "elem_conn") + if conn.shape not in {(2 * n_elem,), (n_elem, 2)}: + raise ValueError( + f"elem_conn must be flat ({2 * n_elem},) or one row per element ({n_elem}, 2); " + f"got shape {conn.shape}" + ) + fixed = _as_index_array(fixed_dofs, "fixed_dofs") + if fixed.ndim != 1: + raise ValueError(f"fixed_dofs must be flat; got shape {fixed.shape}") + return q, v, conn.reshape(-1), length, stiffness, mass, fixed + + +def _host_positions(q0: ArrayInput, name: str = "q0") -> FloatArray: """``q0`` of :meth:`CableDyn.init_deck_at`: flat ``(3 n,)`` or column-per-point ``(3, n)``.""" - q = _as_real_array(q0, "q0") + q = _as_real_array(q0, name) 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); " + f"{name} 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)}" + f"{name} 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)") + raise ValueError(f"{name} must be finite (no NaN or Inf)") return q @@ -151,7 +233,8 @@ class CableDyn: A MoorDyn-style sectioned ``.dat`` deck (the deck format in the documentation, https://cabledyn.readthedocs.io). When given, the static initial condition is solved immediately. - ``None`` creates an unbound handle for a later :meth:`init_deck`. + ``None`` creates an unbound handle for a later :meth:`init_deck`, or for + :meth:`init_line` or :meth:`init_lines` with lines meshed by the caller. The coupled exchange follows the coupling boundary described in the documentation (https://cabledyn.readthedocs.io): kinematics in @@ -317,8 +400,184 @@ def init_deck_rotating( 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).""" + def init_line( + self, + q0: ArrayInput, + v0: ArrayInput, + elem_conn: ArrayInput, + l0: ArrayInput, + ea: ArrayInput, + rho_a: ArrayInput, + fixed_dofs: ArrayInput, + tension_only: bool, + rho_inf: float, + ) -> None: + """Initialize from one line meshed by the caller (``CableDyn_InitLine``). + + The model is structural only: two-node ``EI = 0`` axial elements with a + consistent mass matrix, without gravity, buoyancy, seabed, hydrodynamics or + structural damping, and without a static solve: the state starts at ``q0``, + ``v0`` exactly. ``q0`` and ``v0`` are the node positions [m] and velocities + [m/s], flat ``(3 * n_nodes,)`` or column-per-point ``(3, n_nodes)`` (a + ``(3, 3)`` array is rejected as ambiguous). ``elem_conn`` is the **1-based** + node pair of each element, flat ``(2 * n_elem,)`` or ``(n_elem, 2)``. + ``l0``, ``ea`` and ``rho_a`` are the unstretched length [m], axial stiffness + [N] and mass per unit length [kg/m] of each element, ``(n_elem,)``. + ``fixed_dofs`` lists the **1-based** DOFs the caller prescribes; node ``k`` + owns DOFs ``3k-2, 3k-1, 3k``, and their order is the order of the coupled + vector. A true ``tension_only`` lets an element go slack instead of carrying + compression. ``rho_inf`` is the generalised-alpha spectral radius in + ``[0, 1]``. + + The handle then has no deck and no points: :attr:`deck` is ``None`` and every + coupled DOF is prescribed by the caller. The views of :attr:`lines` run from + the last node of ``q0`` to its first, as they run from End A on a deck line, + whose model holds End B first. + + A wrong shape, a non-finite value or a non-integer index raises + :class:`ValueError` or :class:`TypeError` before the library is called, and + changes nothing. The library judges the values and raises + :class:`CableDynError`. After that error the handle must be initialized + again, and a saved state is lost, unless it held a model on the coupled + aggregate (finite-EI lines, bodies or rods), which stays live with its save. + """ + q, v, conn, length, stiffness, mass, fixed = _raw_line_arrays( + q0, v0, elem_conn, l0, ea, rho_a, fixed_dofs + ) + slack = _as_flag(tension_only, "tension_only") + radius = _as_spectral_radius(rho_inf) + if q.size < 6 or length.size < 1: + raise ValueError( + f"a line needs at least 2 nodes and 1 element; got {q.size // 3} and {length.size}" + ) + with self._lock: + status = c_int() + _lib.CableDyn_InitLine( + self._handle, + q.size // 3, + length.size, + _dbl_ptr(q), + _dbl_ptr(v), + _int_ptr(conn), + _dbl_ptr(length), + _dbl_ptr(stiffness), + _dbl_ptr(mass), + _int_ptr(fixed) if fixed.size else None, + fixed.size, + slack, + radius, + byref(status), + ) + self._finish_raw_init("CableDyn_InitLine", status.value) + + def init_lines( + self, + n_nodes: ArrayInput, + n_elem: ArrayInput, + n_fixed: ArrayInput, + q0: ArrayInput, + v0: ArrayInput, + elem_conn: ArrayInput, + l0: ArrayInput, + ea: ArrayInput, + rho_a: ArrayInput, + fixed_dofs: ArrayInput, + tension_only: bool, + rho_inf: float, + coupled_map: ArrayInput | None = None, + ) -> None: + """Initialize from several lines meshed by the caller (``CableDyn_InitLines``). + + The lines are those of :meth:`init_line`, in one system. ``n_nodes``, + ``n_elem`` and ``n_fixed`` hold the counts of each line; every other array is + the concatenation, in line order, of that line's :meth:`init_line` array. + ``elem_conn`` and ``fixed_dofs`` stay local to each line: node 1 is the first + node of that line. ``tension_only`` and ``rho_inf`` apply to every line. + + Without ``coupled_map`` the lines are independent, and the coupled vector is + their ``fixed_dofs`` in turn. ``coupled_map`` connects lines at shared points: + every line has exactly six fixed DOFs, and entry ``6 * i + j`` (0-based ``i``, + ``j``) is the **1-based** system DOF of line ``i``'s ``j``-th fixed DOF. The + entries use every index from 1 to their maximum, which is the coupled DOF + count; loads and Jacobian entries of a shared DOF are summed. + + Errors are those of :meth:`init_line`. + """ + q, v, conn, length, stiffness, mass, fixed = _raw_line_arrays( + q0, v0, elem_conn, l0, ea, rho_a, fixed_dofs + ) + slack = _as_flag(tension_only, "tension_only") + radius = _as_spectral_radius(rho_inf) + nodes = _as_index_array(n_nodes, "n_nodes") + elements = _as_index_array(n_elem, "n_elem") + fixed_counts = _as_index_array(n_fixed, "n_fixed") + n_lines = nodes.size + if nodes.ndim != 1 or n_lines < 1: + raise ValueError(f"n_nodes must be flat with an entry per line; got {nodes.shape}") + for name, counts in (("n_elem", elements), ("n_fixed", fixed_counts)): + if counts.shape != nodes.shape: + raise ValueError(f"{name} must have {n_lines} entries; got shape {counts.shape}") + if np.any(nodes < 2) or np.any(elements < 1) or np.any(fixed_counts < 0): + raise ValueError( + "every line needs at least 2 nodes, 1 element and 0 fixed DOFs; got " + f"n_nodes {nodes.tolist()}, n_elem {elements.tolist()}, " + f"n_fixed {fixed_counts.tolist()}" + ) + totals = ( + ("q0", q.size, 3 * int(nodes.sum(dtype=np.int64))), + ("l0", length.size, int(elements.sum(dtype=np.int64))), + ("fixed_dofs", fixed.size, int(fixed_counts.sum(dtype=np.int64))), + ) + for name, size, expected in totals: + if size != expected: + raise ValueError(f"{name} must hold {expected} values in all; got {size}") + shared = _as_index_array((), "coupled_map") + if coupled_map is not None: + shared = _as_index_array(coupled_map, "coupled_map") + if shared.size: + if shared.shape != (6 * n_lines,): + raise ValueError( + f"coupled_map must be flat ({6 * n_lines},); got shape {shared.shape}" + ) + if np.any(fixed_counts != 6): + raise ValueError("coupled_map needs exactly six fixed DOFs on every line") + with self._lock: + status = c_int() + _lib.CableDyn_InitLines( + self._handle, + n_lines, + _int_ptr(nodes), + _int_ptr(elements), + _int_ptr(fixed_counts), + _dbl_ptr(q), + _dbl_ptr(v), + _int_ptr(conn), + _dbl_ptr(length), + _dbl_ptr(stiffness), + _dbl_ptr(mass), + _int_ptr(fixed) if fixed.size else None, + _int_ptr(shared) if shared.size else None, + shared.size, + slack, + radius, + byref(status), + ) + self._finish_raw_init("CableDyn_InitLines", status.value) + + def _finish_raw_init(self, call: str, status: int) -> None: + """Book-keeping after InitLine or InitLines (the caller holds the lock). + + A failed call can leave the earlier model live, whose time and views then stand. + """ + if status != 0: + message = self._last_error() + if not _lib.CableDyn_IsInitialized(self._handle): + self._initialized_from(None) + raise CableDynError(call, status, message) + self._initialized_from(None) + + def _initialized_from(self, deck: Path | None) -> None: + """Book-keeping after a successful initialization (the caller holds the lock).""" self._generation += 1 self._views_valid = False self._time = 0.0 @@ -574,6 +833,60 @@ def calc_output(self) -> FloatArray: self._check("CableDyn_CalcOutput", status.value) return loads + def calc_output_derivatives( + self, q: ArrayInput, v: ArrayInput, a: ArrayInput + ) -> tuple[FloatArray, FloatArray, FloatArray, FloatArray, FloatArray]: + """The coupled loads and their analytic Jacobians at an operating point. + + ``q``, ``v`` and ``a`` are the operating point, as in :meth:`update_states`. + Returns ``(loads, dload_dq, dload_dv, dload_da, added_mass)``: ``loads`` is + ``(n_dof,)`` [N], and the others are ``(n_dof, n_dof)`` with ``J[i, j]`` the + derivative of load ``i`` with respect to coupled DOF ``j``, in N/m, N s/m and + kg; ``added_mass`` is ``-dload_da``. + + Each line's interior DOFs are condensed out at the operating point: interior + positions and velocities are held, and interior accelerations are eliminated + through the mass matrix, so ``dload_da`` is + ``-(M_cc - M_cf inv(M_ff) M_fc)``. The Jacobians are therefore those of + :meth:`update_states` followed by :meth:`calc_output`, the instantaneous + response of the end loads to the end motion. + + This call **sets the model state**, as :meth:`update_states` does, also when + a later stage of it fails; :attr:`time` stays. Call :meth:`update_states` with + the previous kinematics to return to them. A model on the coupled aggregate + (finite-EI lines, bodies or rods) has no load derivatives and raises + :class:`CableDynError`. + """ + with self._lock: + n = self.n_coupled_dof + qa = _as_dof_array(q, n, "q") + va = _as_dof_array(v, n, "v") + aa = _as_dof_array(a, n, "a") + loads = np.zeros(n) + # The library writes J[i + j*n]: column-major, so J[i, j] reads as it should. + dload_dq = np.zeros((n, n), order="F") + dload_dv = np.zeros((n, n), order="F") + dload_da = np.zeros((n, n), order="F") + added_mass = np.zeros((n, n), order="F") + status = c_int() + # The library's eps_fd argument is unused: the blocks are analytic. + _lib.CableDyn_CalcOutputDerivatives( + self._handle, + _dbl_ptr(qa) if n else None, + _dbl_ptr(va) if n else None, + _dbl_ptr(aa) if n else None, + n, + 0.0, + _dbl_ptr(loads) if n else None, + _dbl_ptr(dload_dq) if n else None, + _dbl_ptr(dload_dv) if n else None, + _dbl_ptr(dload_da) if n else None, + _dbl_ptr(added_mass) if n else None, + byref(status), + ) + self._check("CableDyn_CalcOutputDerivatives", status.value) + return loads, dload_dq, dload_dv, dload_da, added_mass + # -- host coupling: outer correctors and the coupled layout ------------------- def save_state(self) -> None: diff --git a/python/tests/test_raw_lines.py b/python/tests/test_raw_lines.py new file mode 100644 index 00000000..3e6f256d --- /dev/null +++ b/python/tests/test_raw_lines.py @@ -0,0 +1,593 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Raw-array lines and load Jacobians through the binding, against the C behaviour. + +A raw line carries no gravity, seabed or hydrodynamics, so the decks that it must reproduce set +a negligible ``g`` and ``rhoW`` (both must be positive) and no drag or added mass. Skipped when the +library cannot be loaded (set ``CABLEDYN_LIBRARY``). +""" + +from __future__ import annotations + +from pathlib import Path + +import numpy as np +import pytest + +try: + from cabledyn import model as model_module # 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 CableDyn +from cabledyn.errors import CableDynError + +REPO = Path(__file__).resolve().parents[2] +VOLTURNUS = REPO / "examples" / "iea15mw_volturnus_mooring.dat" +BAR = "-" * 21 +BAD_INPUT = 3 + +LENGTH, N_ELEM, EA, MASS, RHO_INF = 100.0, 10, 1.0e7, 50.0, 0.4 +SPAN = 100.5 +TENSION = EA * (SPAN / LENGTH - 1.0) + + +def line_deck( + tmp_path: Path, rows: tuple[str, ...] = ("1 1 2 -",), rho_inf: float = RHO_INF +) -> Path: + """Taut lines from the Coupled point 1 to the Fixed points 2 and 3, in deck form.""" + sections = "\n".join(f"{row.split()[0]} cab {LENGTH} {N_ELEM}" for row in rows) + deck = tmp_path / "taut.dat" + deck.write_text( + f"""{BAR} CableDyn Input File {BAR} +taut lines without weight +{BAR} LINE TYPES {BAR} +Name Diam Mass EA BA EI Cdn Cdt Can Cat +cab 0.1 {MASS} {EA} 0.0 0.0 0.0 0.0 0.0 0.0 +{BAR} POINTS {BAR} +ID Type X Y Z +1 Coupled 0.0 0.0 -10.0 +2 Fixed {SPAN} 0.0 -10.0 +3 Fixed 0.0 {SPAN} -10.0 +{BAR} LINES {BAR} +ID NodeA NodeB Outputs +{chr(10).join(rows)} +{BAR} SECTIONS {BAR} +LineID LineType Length NumSegs +{sections} +{BAR} OPTIONS {BAR} +1.0e-9 g +1.0e-9 rhoW +500.0 WtrDpth +{rho_inf} rhoInf +{BAR} OUTPUTS {BAR} +FairTen1 +{BAR} need this line {BAR} +""", + encoding="utf-8", + ) + return deck + + +def straight(end: tuple[float, float, float], n_elem: int = N_ELEM) -> np.ndarray: + """Flat node positions of a straight line from (0, 0, -10) to ``end``.""" + start = np.array([0.0, 0.0, -10.0]) + weights = np.linspace(0.0, 1.0, n_elem + 1)[:, None] + return (start + weights * (np.array(end) - start)).reshape(-1) + + +def chain_conn(n_elem: int = N_ELEM) -> np.ndarray: + """The 1-based node pairs of a chain of elements, one row per element.""" + first = np.arange(1, n_elem + 1) + return np.column_stack([first, first + 1]) + + +def end_dofs(n_elem: int = N_ELEM) -> list[int]: + """The 1-based DOFs of the two end nodes.""" + last = 3 * n_elem + return [1, 2, 3, last + 1, last + 2, last + 3] + + +def element_values(value: float, n_elem: int = N_ELEM) -> np.ndarray: + return np.full(n_elem, value) + + +def init_taut( + model: CableDyn, + end: tuple[float, float, float] = (SPAN, 0.0, -10.0), + *, + tension_only: bool = True, + fixed: list[int] | None = None, + rho_inf: float = RHO_INF, +) -> np.ndarray: + q0 = straight(end) + model.init_line( + q0, + np.zeros_like(q0), + chain_conn(), + element_values(LENGTH / N_ELEM), + element_values(EA), + element_values(MASS), + end_dofs() if fixed is None else fixed, + tension_only, + rho_inf, + ) + return q0 + + +def fairlead_motion(q: np.ndarray, time: float) -> tuple[np.ndarray, np.ndarray, np.ndarray]: + """A smooth motion of the first coupled block away from ``q``, in x and in y.""" + omega = 2.0 * np.pi / 2.0 + position, velocity, acceleration = q.copy(), np.zeros_like(q), np.zeros_like(q) + for axis, amplitude in ((0, 0.2), (1, 0.5)): + position[axis] += amplitude * (1.0 - np.cos(omega * time)) + velocity[axis] = amplitude * omega * np.sin(omega * time) + acceleration[axis] = amplitude * omega**2 * np.cos(omega * time) + return position, velocity, acceleration + + +@pytest.mark.parametrize("rho_inf", [0.0, 0.4, 0.8]) +def test_a_raw_line_matches_the_same_line_from_a_deck(tmp_path, rho_inf): + with CableDyn(line_deck(tmp_path, rho_inf=rho_inf)) as deck, CableDyn() as raw: + init_taut(raw, rho_inf=rho_inf) + assert raw.initialized and raw.n_coupled_dof == 6 and raw.n_lines == 1 + assert raw.deck is None and raw.n_points == 0 + + q_deck, _, _ = deck.get_coupled_motion() + q_raw, v_raw, a_raw = raw.get_coupled_motion() + assert q_raw == pytest.approx(q_deck, abs=1e-9) + assert not np.any(v_raw) and not np.any(a_raw) + assert raw.calc_output() == pytest.approx(deck.calc_output(), abs=1e-4) + assert raw.calc_output()[0] == pytest.approx(TENSION, rel=1e-12) + + dt = 0.01 + for step in range(1, 201): + motion = fairlead_motion(q_raw, step * dt) + deck.step(dt, *motion) + raw.step(dt, *motion) + loads = deck.calc_output() + assert np.max(np.abs(loads - TENSION * np.array([1, 0, 0, -1, 0, 0]))) > 100.0 + assert raw.calc_output() == pytest.approx(loads, rel=1e-8, abs=1e-3) + # The views run from the last node of the arrays, the End A of a deck model's arrays. + assert raw.lines[0].node_positions()[::-1] == pytest.approx( + deck.lines[0].node_positions(), abs=1e-8 + ) + assert raw.time == pytest.approx(deck.time) + + +def shared_arrays() -> dict[str, np.ndarray]: + """Two lines of the shared-point system, as ``init_lines`` takes them.""" + q0 = np.concatenate([straight((SPAN, 0.0, -10.0)), straight((0.0, SPAN, -10.0))]) + fixed = end_dofs() + end_dofs() + return { + "n_nodes": np.array([N_ELEM + 1] * 2), + "n_elem": np.array([N_ELEM] * 2), + "n_fixed": np.array([6, 6]), + "q0": q0, + "v0": np.zeros_like(q0), + "elem_conn": np.concatenate([chain_conn(), chain_conn()]), + "l0": element_values(LENGTH / N_ELEM, 2 * N_ELEM), + "ea": element_values(EA, 2 * N_ELEM), + "rho_a": element_values(MASS, 2 * N_ELEM), + "fixed_dofs": np.array(fixed), + } + + +def test_shared_points_of_raw_lines_match_a_deck(tmp_path): + deck_file = line_deck(tmp_path, ("1 1 2 -", "2 1 3 -")) + with CableDyn(deck_file) as deck, CableDyn() as raw: + raw.init_lines( + **shared_arrays(), + tension_only=True, + rho_inf=RHO_INF, + coupled_map=[1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8, 9], + ) + assert raw.n_lines == 2 and raw.n_coupled_dof == 9 == deck.n_coupled_dof + q, _, _ = raw.get_coupled_motion() + assert q == pytest.approx(deck.get_coupled_motion()[0], abs=1e-9) + # The shared point takes the pull of both lines. + loads = raw.calc_output() + assert loads[:3] == pytest.approx([TENSION, TENSION, 0.0], rel=1e-12) + assert loads == pytest.approx(deck.calc_output(), abs=1e-4) + dt = 0.01 + for step in range(1, 101): + motion = fairlead_motion(q, step * dt) + deck.step(dt, *motion) + raw.step(dt, *motion) + assert raw.calc_output() == pytest.approx(deck.calc_output(), rel=1e-8, abs=1e-3) + + +def test_independent_raw_lines_equal_separate_handles(): + arrays = shared_arrays() + with CableDyn() as both, CableDyn() as first, CableDyn() as second: + both.init_lines(**arrays, tension_only=True, rho_inf=RHO_INF) + init_taut(first) + init_taut(second, (0.0, SPAN, -10.0)) + assert both.n_lines == 2 and both.n_coupled_dof == 12 + q, v, a = both.get_coupled_motion() + assert q[:6] == pytest.approx(first.get_coupled_motion()[0]) + assert q[6:] == pytest.approx(second.get_coupled_motion()[0]) + moved = q.copy() + moved[1] += 0.3 + both.step(0.01, moved, v, a) + first.step(0.01, moved[:6], v[:6], a[:6]) + second.step(0.01, moved[6:], v[6:], a[6:]) + expected = np.concatenate([first.calc_output(), second.calc_output()]) + assert both.calc_output() == pytest.approx(expected, rel=1e-13) + + +def central_difference(model, q, v, a, block: int, column: int, step: float) -> np.ndarray: + """d(calc_output)/d(the coupled DOF ``column`` of q, v or a), held as update_states holds it.""" + columns = [] + for sign in (1.0, -1.0): + state = [q.copy(), v.copy(), a.copy()] + state[block][column] += sign * step + model.update_states(*state) + columns.append(model.calc_output()) + return (columns[0] - columns[1]) / (2.0 * step) + + +def check_jacobians(model, q, v, a, steps: tuple[float, float, float]) -> list[np.ndarray]: + loads, dq, dv, da, added = model.calc_output_derivatives(q, v, a) + n = model.n_coupled_dof + assert loads.shape == (n,) + for block in (dq, dv, da, added): + assert block.shape == (n, n) + assert added == pytest.approx(-da, abs=0.0) + model.update_states(q, v, a) + assert loads == pytest.approx(model.calc_output(), rel=1e-12) + for index, (jacobian, step) in enumerate(zip((dq, dv, da), steps, strict=True)): + scale = max(float(np.max(np.abs(jacobian))), 1.0) + for column in range(n): + numeric = central_difference(model, q, v, a, index, column, step) + assert np.max(np.abs(jacobian[:, column] - numeric)) < 2e-6 * scale, (index, column) + return [dq, dv, da] + + +@pytest.mark.parametrize( + ("end", "tension_only"), + [ + ((SPAN, 0.0, -10.0), True), # taut along x + ((70.0, 60.0, 40.0), True), # sloped, past its length + ((70.0, 60.0, 30.0), False), # sloped, nearly at its length + ((60.0, 50.0, 10.0), False), # in compression + ], +) +def test_the_jacobians_of_a_raw_line_match_finite_differences(end, tension_only): + with CableDyn() as model: + # The fixed DOFs out of order, the line moving and accelerating. + init_taut(model, end, tension_only=tension_only, fixed=[33, 1, 2, 31, 3, 32]) + q, _, _ = model.get_coupled_motion() + rng = np.random.default_rng(7) + v = rng.uniform(-0.5, 0.5, 6) + a = rng.uniform(-0.5, 0.5, 6) + dq, dv, da = check_jacobians( + model, q + rng.uniform(-0.05, 0.05, 6), v, a, (1e-5, 1e-3, 1e-3) + ) + assert np.any(dq) + assert not np.any(dv) # a raw line has no damping + # The condensed mass is positive definite. + assert np.linalg.eigvalsh(-0.5 * (da + da.T)).min() > 0.0 + + +def test_the_jacobians_of_a_shared_point_sum_its_lines(): + with CableDyn() as model: + model.init_lines( + **shared_arrays(), + tension_only=True, + rho_inf=RHO_INF, + coupled_map=[1, 2, 3, 4, 5, 6, 1, 2, 3, 7, 8, 9], + ) + q, _, _ = model.get_coupled_motion() + rng = np.random.default_rng(3) + v = rng.uniform(-0.5, 0.5, 9) + a = rng.uniform(-0.5, 0.5, 9) + dq, _, da = check_jacobians(model, q, v, a, (1e-5, 1e-3, 1e-3)) + # The far ends of the two lines do not act on each other. + assert not np.any(dq[3:6, 6:9]) and not np.any(da[3:6, 6:9]) + with CableDyn() as first, CableDyn() as second: + init_taut(first) + init_taut(second, (0.0, SPAN, -10.0)) + one = first.calc_output_derivatives(q[:6], v[:6], a[:6])[1] + two = second.calc_output_derivatives( + q[[0, 1, 2, 6, 7, 8]], v[[0, 1, 2, 6, 7, 8]], a[[0, 1, 2, 6, 7, 8]] + )[1] + assert dq[:3, :3] == pytest.approx(one[:3, :3] + two[:3, :3], rel=1e-12) + + +def test_the_jacobians_are_read_column_major(monkeypatch): + """J[i + j*n] of the library is J[i, j] here. The stiffness blocks are nearly symmetric, so + finite differences could not tell a transposed block; a stand-in writes the flat index.""" + + def write_blocks(_handle, _q, _v, _a, n, _eps, loads, *rest): + *blocks, status = rest + for number, block in enumerate(blocks, start=1): + for j in range(n): + for i in range(n): + block[i + j * n] = 1000.0 * number + 10.0 * i + j + loads[0] = 7.0 + status._obj.value = 0 + + with CableDyn() as model: + init_taut(model) + q, v, a = model.get_coupled_motion() + monkeypatch.setattr(model_module._lib, "CableDyn_CalcOutputDerivatives", write_blocks) + loads, *blocks = model.calc_output_derivatives(q, v, a) + assert loads[0] == 7.0 + for number, block in enumerate(blocks, start=1): + assert block[1, 4] == 1000.0 * number + 14.0 + assert block[4, 1] == 1000.0 * number + 41.0 + + +def test_the_jacobians_of_a_deck_with_hydrodynamics_match_finite_differences(): + with CableDyn(VOLTURNUS) as model: + q, v, a = model.get_coupled_motion() + rng = np.random.default_rng(11) + _, dv, da = check_jacobians( + model, + q + rng.uniform(-0.02, 0.02, q.size), + v + rng.uniform(0.2, 0.6, q.size), + a + rng.uniform(-0.2, 0.2, q.size), + (1e-5, 1e-5, 1e-3), + ) + assert np.any(dv) and np.any(da) + + +def test_calc_output_derivatives_sets_the_state_and_keeps_the_time(): + with CableDyn() as model: + init_taut(model) + q, v, a = model.get_coupled_motion() + model.step(0.01, q, v, a) + moved = q.copy() + moved[1] += 0.1 + velocity = np.full(6, 0.2) + acceleration = np.full(6, -0.1) + model.calc_output_derivatives(moved, velocity, acceleration) + assert model.time == pytest.approx(0.01) + q_now, v_now, a_now = model.get_coupled_motion() + assert q_now == pytest.approx(moved) and v_now == pytest.approx(velocity) + assert a_now == pytest.approx(acceleration) + + +def test_the_jacobians_are_refused_on_the_coupled_aggregate(tmp_path): + deck = aggregate_deck(tmp_path) + with CableDyn(deck) as model: + q, v, a = model.get_coupled_motion() + with pytest.raises(CableDynError, match="no load derivatives"): + model.calc_output_derivatives(q, v, a) + + +def aggregate_deck(tmp_path: Path) -> Path: + """A finite-EI line, which runs on the coupled aggregate.""" + text = line_deck(tmp_path).read_text(encoding="utf-8") + finite = text.replace( + f"Name Diam Mass EA BA EI Cdn Cdt Can Cat\ncab 0.1 {MASS} {EA} 0.0 0.0 0.0 0.0 0.0 0.0", + "Name Diam Mass EA BA EI GAs GJ Irt Irn Cdn Cdt Can Cat\n" + f"cab 0.1 {MASS} {EA} 0.0 100.0 1.0e8 80.0 1.0 0.04 0.0 0.0 0.0 0.0", + ).replace("1.0e-9 g\n1.0e-9 rhoW", "9.8 g\n1025.0 rhoW\n0.01 dtM\n1.0 TMax") + deck = tmp_path / "finite.dat" + deck.write_text(finite, encoding="utf-8") + return deck + + +def test_flat_and_column_per_point_positions_build_the_same_line(): + q0 = straight((SPAN, 0.0, -10.0)) + with CableDyn() as flat, CableDyn() as columns: + init_taut(flat) + columns.init_line( + q0.reshape(-1, 3).T, + np.zeros((3, N_ELEM + 1)), + chain_conn().reshape(-1), + element_values(LENGTH / N_ELEM), + element_values(EA), + element_values(MASS), + end_dofs(), + True, + RHO_INF, + ) + assert columns.calc_output() == pytest.approx(flat.calc_output(), abs=0.0) + + +def test_a_line_without_prescribed_dofs_has_an_empty_coupled_vector(): + q0 = straight((SPAN, 0.0, -10.0)) + with CableDyn() as model: + model.init_line( + q0, + np.zeros_like(q0), + chain_conn(), + element_values(LENGTH / N_ELEM), + element_values(EA), + element_values(MASS), + [], + True, + RHO_INF, + ) + assert model.n_coupled_dof == 0 and model.calc_output().shape == (0,) + loads, dq, dv, da, added = model.calc_output_derivatives([], [], []) + assert loads.shape == (0,) + assert dq.shape == dv.shape == da.shape == added.shape == (0, 0) + + +def test_tension_only_lets_a_line_go_slack(): + span = (LENGTH * 0.9, 0.0, -10.0) + with CableDyn() as slack, CableDyn() as linear: + init_taut(slack, span, tension_only=True) + init_taut(linear, span, tension_only=False) + assert not np.any(slack.calc_output()) + assert linear.calc_output()[0] == pytest.approx(-0.1 * EA, rel=1e-12) + + +def raw_arguments() -> dict: + q0 = straight((SPAN, 0.0, -10.0)) + return { + "q0": q0, + "v0": np.zeros_like(q0), + "elem_conn": chain_conn(), + "l0": element_values(LENGTH / N_ELEM), + "ea": element_values(EA), + "rho_a": element_values(MASS), + "fixed_dofs": end_dofs(), + "tension_only": True, + "rho_inf": RHO_INF, + } + + +@pytest.mark.parametrize( + ("name", "value", "error", "match"), + [ + ("q0", np.zeros(32), ValueError, "q0 must be flat"), + ("q0", np.zeros((3, 3)), ValueError, "ambiguous"), + ("q0", np.full(33, np.nan), ValueError, "q0 must be finite"), + ("q0", np.zeros(33, dtype=complex), TypeError, "real-valued"), + ("v0", np.zeros(30), ValueError, "v0 must hold as many"), + ("v0", np.full(33, np.inf), ValueError, "v0 must be finite"), + ("elem_conn", np.ones((N_ELEM, 3), dtype=int), ValueError, "elem_conn must be"), + ("elem_conn", np.ones((N_ELEM, 2)), TypeError, "elem_conn must be an integer"), + ("elem_conn", np.full((N_ELEM, 2), 2**33), ValueError, "range of a C int"), + ("l0", np.ones((N_ELEM, 1)), ValueError, "l0 must be flat"), + ("l0", np.zeros(0), ValueError, "ea must be flat"), + ("l0", np.full(N_ELEM, np.nan), ValueError, "l0 must be finite"), + ("ea", np.ones(N_ELEM + 1), ValueError, "ea must be flat"), + ("ea", np.full(N_ELEM, np.inf), ValueError, "ea must be finite"), + ("rho_a", np.ones(N_ELEM - 1), ValueError, "rho_a must be flat"), + ("rho_a", np.full(N_ELEM, np.nan), ValueError, "rho_a must be finite"), + ("fixed_dofs", np.ones((2, 3), dtype=int), ValueError, "fixed_dofs must be flat"), + ("fixed_dofs", [1.0, 2.0], TypeError, "fixed_dofs must be an integer"), + ("tension_only", "yes", TypeError, "tension_only must be a boolean"), + ("rho_inf", float("nan"), ValueError, "rho_inf must be finite"), + ("rho_inf", -0.1, ValueError, "rho_inf must be non-negative"), + ("rho_inf", 1.5, ValueError, r"rho_inf must lie in \[0, 1\]"), + ("rho_inf", "0.4", TypeError, "rho_inf must be a real number"), + ], +) +def test_a_bad_array_is_refused_before_the_library(name, value, error, match): + with CableDyn(VOLTURNUS) as model: + n_lines = model.n_lines + arguments = raw_arguments() + arguments[name] = value + with pytest.raises(error, match=match): + model.init_line(**arguments) + assert model.deck == VOLTURNUS.resolve() and model.n_lines == n_lines + + +def test_a_line_needs_two_nodes_and_an_element(): + arguments = raw_arguments() + with CableDyn() as model: + short = {**arguments, "q0": np.zeros(3), "v0": np.zeros(3)} + with pytest.raises(ValueError, match="at least 2 nodes"): + model.init_line(**short) + empty = {**arguments, "elem_conn": [], "l0": [], "ea": [], "rho_a": []} + with pytest.raises(ValueError, match="at least 2 nodes and 1 element"): + model.init_line(**empty) + + +@pytest.mark.parametrize( + ("name", "value", "match"), + [ + ("elem_conn", chain_conn() - 1, "elem_conn|connectivity|node"), + ("fixed_dofs", [0, 1, 2], "fixed"), + ("fixed_dofs", [1, 1, 2], "fixed|duplicate"), + ("fixed_dofs", [34], "fixed"), + ("l0", -element_values(1.0), "l0|length|positive"), + ("ea", 0.0 * element_values(1.0), "ea|EA|positive"), + ("rho_a", -element_values(1.0), "rho_a|mass|positive"), + ], +) +def test_a_bad_value_is_the_library_s_to_refuse(name, value, match): + arguments = raw_arguments() + arguments[name] = value + with CableDyn() as model: + with pytest.raises(CableDynError, match=match) as raised: + model.init_line(**arguments) + assert raised.value.status == BAD_INPUT + assert not model.initialized + + +@pytest.mark.parametrize( + ("change", "error", "match"), + [ + ({"n_nodes": [11]}, ValueError, "n_elem must have 1 entries"), + ({"n_nodes": []}, ValueError, "n_nodes must be flat"), + ({"n_nodes": [11, 1]}, ValueError, "at least 2 nodes"), + ({"n_elem": [10, 0]}, ValueError, "at least 2 nodes"), + ({"n_fixed": [6, -6]}, ValueError, "at least 2 nodes"), + ({"n_nodes": [11, 10]}, ValueError, "q0 must hold 63"), + ({"n_elem": [10, 9]}, ValueError, "l0 must hold 19"), + ({"n_fixed": [6, 5]}, ValueError, "fixed_dofs must hold 11"), + ({"n_nodes": [11.0, 11.0]}, TypeError, "n_nodes must be an integer"), + ({"coupled_map": [1, 2, 3]}, ValueError, r"coupled_map must be flat \(12,\)"), + ({"coupled_map": [1.0] * 12}, TypeError, "coupled_map must be an integer"), + ], +) +def test_a_bad_count_is_refused_before_the_library(change, error, match): + arguments = shared_arrays() + arguments.update(change) + with CableDyn() as model, pytest.raises(error, match=match): + model.init_lines(**arguments, tension_only=True, rho_inf=RHO_INF) + + +def test_a_coupled_map_needs_six_fixed_dofs_on_every_line(): + arguments = shared_arrays() + arguments["n_fixed"] = np.array([3, 3]) + arguments["fixed_dofs"] = np.array([1, 2, 3, 1, 2, 3]) + with CableDyn() as model, pytest.raises(ValueError, match="six fixed DOFs"): + model.init_lines( + **arguments, tension_only=True, rho_inf=RHO_INF, coupled_map=list(range(1, 13)) + ) + + +def test_a_coupled_map_with_a_gap_is_the_library_s_to_refuse(): + with CableDyn() as model: + with pytest.raises(CableDynError) as raised: + model.init_lines( + **shared_arrays(), + tension_only=True, + rho_inf=RHO_INF, + coupled_map=[1, 2, 3, 4, 5, 6, 1, 2, 3, 8, 9, 10], + ) + assert raised.value.status == BAD_INPUT + assert not model.initialized + + +def test_a_raw_line_replaces_a_deck_model_and_its_book_keeping(tmp_path): + with CableDyn(line_deck(tmp_path)) as model: + q, v, a = model.get_coupled_motion() + model.step(0.01, q, v, a) + model.save_state() + old_line = model.lines[0] + init_taut(model) + assert model.deck is None and model.time == 0.0 + with pytest.raises(CableDynError): + model.restore_state() # the library drops the save + with pytest.raises(RuntimeError): + old_line.node_positions() + assert model.lines[0].n_nodes == N_ELEM + 1 + + +def test_a_failed_raw_line_keeps_a_live_aggregate_with_its_save(tmp_path): + deck = aggregate_deck(tmp_path) + with CableDyn(deck) as model: + q, v, a = model.get_coupled_motion() + model.step(0.01, q, v, a) + model.save_state() + view = model.lines[0] + arguments = raw_arguments() + arguments["l0"] = -element_values(1.0) + with pytest.raises(CableDynError): + model.init_line(**arguments) + assert model.initialized and model.deck == deck.resolve() + assert model.time == pytest.approx(0.01) + assert view.n_nodes > 0 + model.step(0.01, q, v, a) + model.restore_state() + assert model.time == pytest.approx(0.01) + + +def test_a_failed_raw_line_loses_the_save_of_a_point_model(tmp_path): + with CableDyn(line_deck(tmp_path)) as model: + model.save_state() + arguments = raw_arguments() + arguments["ea"] = -element_values(1.0) + with pytest.raises(CableDynError): + model.init_line(**arguments) + with pytest.raises(CableDynError): + model.restore_state()