diff --git a/CHANGELOG.md b/CHANGELOG.md index 7bc9d957..99f92999 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -321,6 +321,29 @@ All notable changes to CableDyn are recorded in this file. The format follows `vreg F/(mu N)`) where it slid back and forth at a few mm/s. This changes the results of decks with rods or bodies on a frictional seabed; none of the shipped examples or existing tests has one. +- Node output channels of a finite-EI line whose mesh the static solve refined read the wrong + node, silently. `TenN`, `CurvN`, `BendMomN`, `LNp/v/a{x,y,z}`, + `LNDec`/`Azi`, `TorqN` and `TwistN` name a deck node (1 + the total + `NumSegs` of the line's sections) and are checked against that count, but after an automatic + refinement (adaptive, stability or curvature refinement) they reported node `J` of the refined + mesh. On the lazy-wave cable of `tests/data/lazy_wave_touchdown_planar_coarse.dat` with its top + section cut from 20 to 4 elements (refined from 71 to 1136 elements), `Ten4N34`, the deck node + at the 220 m touchdown, reported 5488 N, the tension at 41 m from End A, against 1544 N, and + `BendMom4N54`, on the seabed at 420 m, 1214 N·m against 0. Each refined line now maps its deck + nodes onto the final mesh by their unstretched arc length from End A (an exact match, which + does not assume a uniform refinement; a deck node not on the mesh fails closed), and the node + channels read deck nodes on every route: standalone static and dynamic cubic-Hermite, mixed + `EI = 0` + finite-EI, multibody, OpenFAST and the C API `CableDyn_EvalChannel`. `.static.out`, + the range graphs, the per-line files and `CableDyn_GetLineValues` still list every node of the + refined mesh; `.static.out` then carries a `DeckNode` column naming the deck node of each row + (0 for a node the refinement added), `.Line.p.out` a `# DeckNode` comment line (also on the + multibody march, which writes no `.static.out`), and the new C API quantity + `CD_C_LINE_DECK_NODE` (10) of `CableDyn_GetLineValues`, Python `Line.deck_nodes`, gives the + same numbering in process. The Python `StaticProfile.deck_node_arc_lengths`, + `LineNodeHistory.deck_nodes`, `node_range_graph`, `profile_at`/`profiles_at` and + `line_range_graph` place main-output node channels at their deck node, from a static profile, + a per-line position file or `LinePositions` read from one. `EI = 0` lines are never refined, and every output of a deck whose meshes are + not refined is unchanged. See the manual's output reference (Node channels on a refined line). - Tension spikes of tension-only (`EI = 0`) lines that go slack. The generalised-α step evaluated the axial force and the dynamic loads at the blended configuration diff --git a/CMakeLists.txt b/CMakeLists.txt index fd3bdce1..b57cb64e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1503,6 +1503,30 @@ if(Python3_Interpreter_FOUND) message(STATUS "anchor_uplift_channels: skipped (numpy not importable in ${Python3_EXECUTABLE})") endif() + # Node channels on a refined finite-EI line name deck nodes: the static profile's DeckNode + # column, the standalone static and dynamic cubic-Hermite routes, the mixed route (the OpenFAST + # aggregate evaluator) and the C API on the coarse lazy-wave deck the static solve refines + # (needs numpy). + if(_range_tdp_numpy_rc EQUAL 0) + if(WIN32 AND CABLEDYN_RUNTIME_DLLS) + set(_node_channels_library "${CMAKE_BINARY_DIR}/runtime/$") + else() + set(_node_channels_library "$") + endif() + add_test(NAME node_channels_refined_line + COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/test_node_channels_refined.py + --exe $ + --deck ${CMAKE_CURRENT_SOURCE_DIR}/tests/data/lazy_wave_touchdown_planar_coarse.dat + --output ${CMAKE_BINARY_DIR}/node_channels_refined_line + --library ${_node_channels_library}) + set_tests_properties(node_channels_refined_line PROPERTIES + LABELS "python;integration;static;dynamic;capi" + TIMEOUT 600 + ENVIRONMENT "${_cabledyn_python_test_environment}") + else() + message(STATUS "node_channels_refined_line: skipped (numpy not importable in ${Python3_EXECUTABLE})") + endif() + # The arbiter imports numpy + scipy at load time; only register the test when they are # importable, so an image with python3 but without those packages does not fail the # validation suite with ModuleNotFoundError before any CableDyn gate runs. diff --git a/doc/capi.rst b/doc/capi.rst index 8cd3272a..19c90a50 100644 --- a/doc/capi.rst +++ b/doc/capi.rst @@ -1760,16 +1760,21 @@ handle numbers its lines 1..n). * - ``CableDyn_NObjects`` - number of objects of ``kind`` * - ``CableDyn_GetObjectInfo`` - - ``id``; ``n_nodes`` (lines: node count; rods: ``NumSegs + 1``; points and bodies: 1); + - ``id``; ``n_nodes`` (lines: node count of the final mesh; rods: ``NumSegs + 1``; points and + bodies: 1); ``subtype`` (lines: 1 finite-EI, 0 EI = 0; points: 1 Fixed, 2 Coupled, 3 Free, 4 Connect) * - ``CableDyn_GetLineValues`` - - one quantity along the line, End A first: ``CD_C_LINE_POSITION`` (1), + - one quantity at every node of the line's final mesh, End A first: + ``CD_C_LINE_POSITION`` (1), ``_VELOCITY`` (2), ``_ACCELERATION`` (4), 3 values per node, xyz interleaved; ``_TENSION`` (3, the ``TenN`` node tension), ``_CURVATURE`` (5), ``_BEND_MOMENT`` (6, zero on an EI = 0 line), ``_DECLINATION`` (7), ``_AZIMUTH`` (8), - one value per node; ``_SEGMENT_TENSION`` (9), one value per segment. ``n_out`` must - equal the value count. + one value per node; ``_SEGMENT_TENSION`` (9), one value per segment; + ``_DECK_NODE`` (10), one value per node: the deck node ``J`` of the node (the ```` + of the node channels), 0 for a node a mesh refinement added, ``1 … n_nodes`` on a line + meshed as the deck. ``n_out`` must equal the value count. A library without code 10 + rejects it with ``CD_C_BAD_INPUT``. * - ``CableDyn_GetPointState`` - position, velocity and the resultant force of the attached lines (``Point

F``), 3 doubles each @@ -1782,7 +1787,14 @@ handle numbers its lines 1..n). of End A with the axis roll and pitch from vertical; velocity and wrench about End A * - ``CableDyn_EvalChannel`` - the value of one ``OUTPUTS`` token (:doc:`outputs`), for example ``FairTen1``, - ``L2N5px``, ``Curv1N3``, ``Point4Fz``, ``Body1Pz`` or ``Rod2TenA`` + ``L2N5px``, ``Curv1N3``, ``Point4Fz``, ``Body1Pz`` or ``Rod2TenA``; a line-node token + names a deck node + +On a finite-EI line whose mesh the static solve refined, ``n_nodes`` and the +``CableDyn_GetLineValues`` arrays cover every node of the refined mesh, while a node token of +``CableDyn_EvalChannel`` (``Ten1N5``, ``L1N5px``) names deck node 5 at its node of that mesh +(:ref:`outputs-refined-nodes`); ``CD_C_LINE_DECK_NODE`` locates it: the array row whose value is +5. A ``NULL`` output pointer skips that output, except for the ``out`` array of ``CableDyn_GetLineValues`` and the ``value`` of ``CableDyn_EvalChannel``; the latter is not diff --git a/doc/options.rst b/doc/options.rst index ca95a4af..d573b6e4 100644 --- a/doc/options.rst +++ b/doc/options.rst @@ -376,7 +376,8 @@ Finite-EI cable controls keeps the declared ``NumSegs`` authoritative but does not disable the folded-element safety check, nor the automatic refinement of a deck mesh that cannot resolve the curvature of the equilibrium (reported). When ``True``, reaching the refinement cap while - the mesh remains fragile is reported + the mesh remains fragile is reported. Node output channels keep naming the deck nodes + on a refined mesh (:ref:`outputs-refined-nodes`) - both (finite-EI lines) - ``True adaptive_mesh`` * - ``alpha_force_blend`` / ``alphaforceblend`` diff --git a/doc/outputs.rst b/doc/outputs.rst index e5a02415..eedcd047 100644 --- a/doc/outputs.rst +++ b/doc/outputs.rst @@ -183,7 +183,9 @@ Example (static route):: ---------------------------------------------- The along-arc static configuration, one row per node of every line (a *range graph* of the static -state). It is independent of the ``OUTPUTS`` selection. On a dynamic cubic-Hermite or mixed +state): every node of the line's final mesh, so a finite-EI line whose mesh the static solve +refined has more rows than deck nodes (see :ref:`outputs-refined-nodes`). It is independent of +the ``OUTPUTS`` selection. On a dynamic cubic-Hermite or mixed run it records the converged initial state that the march starts from. Layout: title line, header row, **units row**, then data. The title reads @@ -191,7 +193,8 @@ Layout: title line, header row, **units row**, then data. The title reads (static route), ``CableDyn standalone static configuration (deformed arc; public node order End A -> End B)`` (cubic-Hermite route) or ``CableDyn coupled static configuration (deformed arc; public node order End A -> End B)`` (mixed route and OpenFAST). The columns are identical -on every route: +on every route; the ``DeckNode`` column follows only when the static solve refined the mesh of a +finite-EI line of the run: .. list-table:: :header-rows: 1 @@ -231,6 +234,12 @@ on every route: * - ``Azimuth`` - ``(deg)`` - axial-tangent azimuth from +X toward +Y, in [0, 360) + * - ``DeckNode`` + - ``(-)`` + - the deck node of the row, the ```` of the node channels (1 = End A … 1 + the total + ``NumSegs`` of the line's sections = End B); 0 for a node the refinement added. An + ``EI = 0`` line, never refined, numbers its rows as the deck. Written only when a line's + mesh was refined Plot ``Curvature`` or ``Tension`` against ``ArcLength`` for a fatigue or strength check. @@ -335,9 +344,13 @@ channels instead) and accept ``r``. moment, declination and seabed clearance (and torque and twist on a line with torsion), one row per node (see below) -```` is the deck line id. Each file starts with a ``#`` comment line (e.g. +```` is the deck line id. The files list every node and segment of the line's final mesh, +also on a finite-EI line whose mesh the static solve refined (:ref:`outputs-refined-nodes`). +Each file starts with a ``#`` comment line (e.g. ``# CableDyn static line node positions; public node order EndA -> EndB``) and a header row; -there is no units row — units are in the column names. +there is no units row — units are in the column names. On a refined line the ``.p.out`` file +has a second comment line, ``# DeckNode`` followed by one tab-separated integer per node: the +deck node of that node, 0 for a node the refinement added. .. list-table:: :header-rows: 1 @@ -381,7 +394,8 @@ End A -> End B)``. - Meaning * - ``Node`` - ``(-)`` - - node number, 1 = End A … N = End B + - node number of the line's final mesh, 1 = End A … N = End B (the ``Node`` of + ``.static.out``) * - ``ArcLength`` - ``(m)`` - cumulative deformed chord length from End A at the first sample (``t = 0``, the static @@ -463,6 +477,28 @@ numeric id written with leading zeros (``Ten1N02`` = ``Ten1N2``), or an alias sp ``LINES`` and ``POINTS`` ids (not array positions); ```` is a node number on line ````, 1 = End A to ``N`` = End B, where ``N`` = 1 + the total ``NumSegs`` of the line's sections. +.. _outputs-refined-nodes: + +Node channels on a refined line +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +```` is always a node of the **deck** mesh. The static solve of a finite-EI line can refine +its mesh (``OPTIONS adaptive_mesh``, or the automatic refinement after a failed stability test +or an unresolved curvature, which a note of the initialization report names). A refinement splits +deck elements, so each deck node is a node of the refined mesh at the same unstretched arc length +from End A, and ``TenN``, ``CurvN``, ``BendMomN``, ``LN…``, +``TorqN`` and ``TwistN`` report deck node ``J`` there, on every route (standalone, +mixed, multibody, OpenFAST and the C API ``CableDyn_EvalChannel``). ``.static.out``, the range +graphs, the per-line files and the C API ``CableDyn_GetLineValues`` list every node of the +refined mesh instead, and ``.elements.out`` every element. To find deck node ``J`` among them, +take the ``.static.out`` row whose ``DeckNode`` is ``J``: its ``Node`` is the node number in the +range graph and the per-line files (and the array row + 1 of ``CableDyn_GetLineValues``), its +``ArcLength`` the node's deformed arc length. The ``# DeckNode`` line of ``.Line.p.out`` gives +the same numbering on routes that write no ``.static.out`` (the multibody march), and the C API +quantity ``CD_C_LINE_DECK_NODE`` (Python ``Line.deck_nodes``) in process. The deck node also lies +where the ``ReferenceArcStart`` of ``.elements.out`` equals its unstretched arc length from End A +(``ReferenceArcEnd`` of the last element for End B). ``EI = 0`` lines are never refined. + Line-end channels ~~~~~~~~~~~~~~~~~ diff --git a/doc/python_postprocessing.rst b/doc/python_postprocessing.rst index 5f041ba0..b756e574 100644 --- a/doc/python_postprocessing.rst +++ b/doc/python_postprocessing.rst @@ -329,7 +329,9 @@ moment along a line, with ``plot()`` and ``export()``: functions below rebuild envelopes from other files. * :func:`cabledyn.node_range_graph` builds it from the ``TenN``, ``CurvN``, or ``BendMomN`` channels of a main output over a time window. Node positions come from a - static profile of the run, a ``{node: arc}`` mapping, or the node numbers. + static profile of the run, a ``{node: arc}`` mapping, or the node numbers. The channels name + deck nodes; on a line whose mesh the static solve refined, the profile's ``DeckNode`` column + places them (:ref:`outputs-refined-nodes`). * :func:`cabledyn.static_range_graph` builds it from a ``.static.out`` profile. * :func:`cabledyn.element_range_graph` builds it from a cubic-Hermite ``.elements.out`` table: the peak curvature or bend moment of each element, where it occurs between the nodes, or the diff --git a/python/cabledyn/model.py b/python/cabledyn/model.py index e05e8b24..8cf17336 100644 --- a/python/cabledyn/model.py +++ b/python/cabledyn/model.py @@ -394,7 +394,9 @@ def channel(self, token: str) -> float: ``token`` uses the deck OUTPUTS vocabulary (``FairTen1``, ``L2N5px``, ``Curv1N3``, ``Point4Fz``, ``Body1Pz``, ``Rod2TenA``, ...) and returns the - value the standalone driver writes for that channel at the same state. + value the standalone driver writes for that channel at the same state. A + node channel names a deck node, also on a finite-EI line whose mesh the + static solve refined. """ with self._lock: self._object_views() diff --git a/python/cabledyn/objects.py b/python/cabledyn/objects.py index d93bb601..c8078548 100644 --- a/python/cabledyn/objects.py +++ b/python/cabledyn/objects.py @@ -67,6 +67,9 @@ "segment_tension": (9, 1), } +#: C ABI code of the deck node of each mesh node (``CD_C_LINE_DECK_NODE``). +_LINE_DECK_NODE = 10 + PointKind = Literal["fixed", "coupled", "free", "connect"] _POINT_KINDS: dict[int, PointKind] = {1: "fixed", 2: "coupled", 3: "free", 4: "connect"} @@ -147,9 +150,12 @@ def _check(self, call: str, status: int) -> None: class Line(_View): """One line (mooring line or cable) of an in-process model. - Nodes run from End A (index 0) to End B, the order of the ``LN`` output - channels (node ``k`` is array row ``k - 1``) and of the ``.Line.p.out`` - files. Segments run in the same order. + Nodes run from End A (index 0) to End B, the order of the ``.Line.p.out`` + files; segments run in the same order. The arrays hold every node of the + line's final mesh. The output channels (:meth:`~cabledyn.CableDyn.channel`, + ``TenN``, ``LNpx``, ...) name deck nodes: on the deck mesh deck + node ``J`` is array row ``J - 1``; on a finite-EI line whose mesh the static + solve refined, :attr:`deck_nodes` locates them among the mesh nodes. """ _kind = OBJ_LINE @@ -165,6 +171,30 @@ def n_segments(self) -> int: """Segment (element) count, ``n_nodes - 1``.""" return self._info.n_nodes - 1 + @property + def deck_nodes(self) -> npt.NDArray[np.int64]: + """Deck node of each node of the final mesh ``(n_nodes,)``. + + Entry ``k`` is the deck node ``J`` (the ```` of the node output + channels) at array row ``k``, or 0 for a node a mesh refinement added. + On the deck mesh it is ``1 .. n_nodes``. Rows of the line arrays at deck + node ``J`` are ``numpy.flatnonzero(line.deck_nodes == J)``. + + Raises + ------ + CableDynError + If the library predates this query (``CD_C_LINE_DECK_NODE``). + """ + buf = _buffer(None, (self.n_nodes,)) + with self._model._lock: + handle = self._handle() + status = c_int() + self._model._lib.CableDyn_GetLineValues( + handle, self.index, _LINE_DECK_NODE, _dbl(buf), buf.size, byref(status) + ) + self._check("CableDyn_GetLineValues", status.value) + return np.rint(buf).astype(np.int64) + @property def finite_ei(self) -> bool: """Whether the line carries bending stiffness (the cubic-Hermite element).""" diff --git a/python/cabledyn/profiles.py b/python/cabledyn/profiles.py index 39578e75..0455f930 100644 --- a/python/cabledyn/profiles.py +++ b/python/cabledyn/profiles.py @@ -30,6 +30,19 @@ Arc length is the deformed arc length from End A: the ``ArcLength`` column of a static profile, otherwise the cumulative straight node-to-node distance at the requested time. + +The node channels of a main output number deck nodes (1 at End A to 1 + the +total ``NumSegs`` of the line's sections at End B); a static profile and the +per-line files list every node of the line's final mesh. The two differ on a +finite-EI line whose mesh the static solve refined: a static profile then +places main-output node channels at the rows its ``DeckNode`` column names, +and a per-line position file ``.Line.p.out`` (also as the ``source`` +of :class:`~cabledyn.LinePositions`) at the nodes its ``# DeckNode`` line names. Plain +position arrays carry no such map: they are taken as numbered by deck node, so +pass the in-process mesh positions of a refined line +(:meth:`cabledyn.objects.Line.values`) together with +:attr:`cabledyn.objects.Line.deck_nodes`, for example as a ``{node: arc}`` +mapping. """ from __future__ import annotations @@ -54,6 +67,8 @@ OutputTable, StaticProfile, TimeHistory, + _deck_node_comment, + read_output, ) __all__ = [ @@ -202,6 +217,9 @@ class LinePositions: CableDyn, ``0`` for End A of a MoorDyn line). source : pathlib.Path | None Result file the positions were read from, if any. + line_id : int | None + Line of a multi-line ``source`` (a static profile) the positions were + taken from, if any; it selects that line's deck-node map. Raises ------ @@ -214,6 +232,7 @@ class LinePositions: positions: npt.NDArray[Any] node_ids: npt.NDArray[Any] source: Path | None = None + line_id: int | None = None def __post_init__(self) -> None: positions = _readonly(self.positions) @@ -308,7 +327,9 @@ def period(self, start: float | None = None, stop: float | None = None) -> LineP if self.time is None or (start is None and stop is None): return self mask = _window(self.time, start, stop) - return LinePositions(self.time[mask], self.positions[mask], self.node_ids, self.source) + return LinePositions( + self.time[mask], self.positions[mask], self.node_ids, self.source, self.line_id + ) def _at( @@ -352,6 +373,12 @@ class LineField: ``(n_samples, n_locations)`` values. source : pathlib.Path | None Result file the field was read from, if any. + deck_nodes : bool + True when :attr:`ids` are deck node numbers, as the node channels of a + main output name them (1 at End A to 1 + the total ``NumSegs`` of the + line's sections at End B); false when they number the nodes of the + source's own mesh, as a static profile and the per-line files do. The + two differ on a finite-EI line whose mesh the static solve refined. Raises ------ @@ -367,6 +394,7 @@ class LineField: time: npt.NDArray[Any] | None values: npt.NDArray[Any] source: Path | None = None + deck_nodes: bool = False def __post_init__(self) -> None: if self.location_kind not in {"Node", "Segment"}: @@ -437,6 +465,7 @@ def period(self, start: float | None = None, stop: float | None = None) -> LineF self.time[mask], self.values[mask], self.source, + self.deck_nodes, ) @@ -649,7 +678,12 @@ def _unit(table: OutputTable, channel: str, default: str | None) -> str | None: def _history_field( - history: TimeHistory, quantity: str, kind: str, channels: Mapping[int, str], default: str | None + history: TimeHistory, + quantity: str, + kind: str, + channels: Mapping[int, str], + default: str | None, + deck_nodes: bool = False, ) -> LineField: names = list(channels.values()) return LineField( @@ -660,6 +694,7 @@ def _history_field( time=history.time, values=np.column_stack([history.column(name) for name in names]), source=history.path, + deck_nodes=deck_nodes, ) @@ -691,7 +726,7 @@ def build(axis: int = axis, name: str = name) -> LineField: elif isinstance(source, StaticProfile): line = _static_line(source, identifier) for column in line.channels: - if column in {"LineID", "Node", "ArcLength"}: + if column in {"LineID", "Node", "ArcLength", "DeckNode"}: continue def static_build(column: str = column) -> LineField: @@ -730,7 +765,8 @@ def moordyn_build(name: str = name, kind: str = kind, ids: Any = ids) -> LineFie def main_build( name: str = name, channels: Any = channels, unit: str = default ) -> LineField: - return _history_field(source, name, "Node", channels, unit) + # main-output node channels number deck nodes + return _history_field(source, name, "Node", channels, unit, deck_nodes=True) catalog[name] = main_build elif isinstance(source, OutputTable) and _is_static_node_table(source): @@ -879,7 +915,9 @@ def line_positions( if isinstance(source, StaticProfile): line = _static_line(source, identifier) xyz = np.column_stack([line.column(axis) for axis in "XYZ"]) - return LinePositions(None, xyz[None], line.column("Node").astype(np.int64), line.path) + return LinePositions( + None, xyz[None], line.column("Node").astype(np.int64), line.path, line.line_ids[0] + ) data: npt.NDArray[Any] if isinstance(source, LineNodeHistory): _no_line_id(identifier, source) @@ -941,10 +979,20 @@ def _node_arc( time: float | None, interpolation: Interpolation, line_id: int | None, + deck_nodes: bool = False, ) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]: - """Return node ids and their arc lengths from End A at ``time``.""" + """Return node ids and their arc lengths from End A at ``time``. + + ``deck_nodes`` asks for deck node numbers (main-output node channels): a + static profile then gives the rows its ``DeckNode`` column names on a line + whose mesh the static solve refined. + """ if isinstance(locate, StaticProfile): line = _static_line(locate, line_id) + if deck_nodes: + lookup = line.deck_node_arc_lengths(line.line_ids[0]) + ids = np.asarray(sorted(lookup), dtype=np.int64) + return ids, np.asarray([lookup[int(node)] for node in ids], dtype=np.float64) return line.column("Node").astype(np.int64), np.asarray(line.column("ArcLength")) if isinstance(locate, Mapping): ids = np.asarray(sorted(int(node) for node in locate), dtype=np.int64) @@ -955,9 +1003,94 @@ def _node_arc( line_id=line_id if isinstance(locate, TimeHistory) and not _per_line(locate) else None, ) xyz = positions.at(None if positions.static else time, interpolation=interpolation) + if deck_nodes: + return _deck_node_positions(locate, positions.node_ids, _cumulative_arc(xyz)) return positions.node_ids, _cumulative_arc(xyz) +def _deck_node_positions( + locate: LocationSource, node_ids: npt.NDArray[Any], arc: npt.NDArray[Any] +) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]: + """Deck node ids and arc lengths of the nodes of a position source. + + A per-line file ``.Line.p.out`` and a static profile list every + node of the line's final mesh. On a line whose mesh the static solve + refined, the file's ``# DeckNode`` line (or the ``DeckNode`` column of the + static profile ``.static.out`` beside it) names the deck nodes among + them; without either the file's nodes are the deck nodes. Position arrays + carry no such map and are taken as numbered by deck node. + """ + mesh_node = _deck_node_rows(locate) + if mesh_node is None: + return node_ids, arc + position = dict(zip(node_ids.tolist(), arc.tolist(), strict=True)) + deck = [j for j in sorted(mesh_node) if mesh_node[j] in position] + return ( + np.asarray(deck, dtype=np.int64), + np.asarray([position[mesh_node[j]] for j in deck], dtype=np.float64), + ) + + +def _deck_node_rows(locate: LocationSource) -> dict[int, int] | None: + """Deck node -> node id of a position source's file; ``None`` when they coincide.""" + path: Path | None + deck: npt.NDArray[Any] | None = None + if isinstance(locate, LineNodeHistory): + path, deck = locate.path, locate.deck_nodes + elif isinstance(locate, OutputTable) and _is_static_node_table(locate): + path, deck = locate.path, _deck_node_comment(locate.title, locate.path) + elif isinstance(locate, LinePositions) and locate.source is not None: + path = locate.source + if path.name.lower().endswith(".static.out"): + return _static_profile_rows(path, locate.line_id) + if path.is_file(): + deck = _deck_node_comment(_comment_head(path), path) + else: + return None + if deck is not None: + return {int(j): k + 1 for k, j in enumerate(deck.tolist()) if j > 0} + match = _FILE_LINE.search(path.name) + if match is None: + return None + static = path.with_name(path.name[: match.start()] + ".static.out") + if not static.is_file(): + return None + return _static_profile_rows(static, int(match.group(1))) + + +def _static_profile_rows(path: Path, line_id: int | None) -> dict[int, int] | None: + """Deck node -> ``Node`` of one line of a static profile with a ``DeckNode`` column.""" + profile = read_output(path) + if not isinstance(profile, StaticProfile) or "DeckNode" not in profile.channels: + return None + if line_id is None: + if len(profile.line_ids) != 1: + raise ValueError( + f"{path.name} lists several lines with a refined mesh; place deck-node " + "channels with the StaticProfile itself" + ) + line_id = profile.line_ids[0] + if line_id not in profile.line_ids: + return None + rows = profile.line(line_id) + return { + int(deck): int(node) + for deck, node in zip(rows.column("DeckNode"), rows.column("Node"), strict=True) + if deck > 0.0 + } + + +def _comment_head(path: Path) -> str: + """The leading ``#`` comment lines of a result file.""" + lines: list[str] = [] + with path.open(encoding="utf-8") as handle: + for line in handle: + if not line.startswith("#"): + break + lines.append(line.rstrip("\n")) + return "\n".join(lines) + + def _cumulative_arc(xyz: npt.NDArray[Any]) -> npt.NDArray[Any]: """Cumulative chord length from the first of ``(n_nodes, 3)`` points.""" return np.concatenate(([0.0], np.cumsum(np.linalg.norm(np.diff(xyz, axis=0), axis=1)))) @@ -991,7 +1124,7 @@ def _place( """Return the location kind and location of each field value.""" if locate is None: return field.location_kind, field.ids.astype(np.float64) - node_ids, arc = _node_arc(locate, time, interpolation, line_id) + node_ids, arc = _node_arc(locate, time, interpolation, line_id, field.deck_nodes) return "ArcLength", _assign(field, isinstance(locate, Mapping), node_ids, arc) @@ -1016,15 +1149,23 @@ def _assign( def _mean_node_arc( - locate: LocationSource, line_id: int | None, start: float | None, stop: float | None + locate: LocationSource, + line_id: int | None, + start: float | None, + stop: float | None, + deck_nodes: bool = False, ) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]: """Node ids and their arc length, time-averaged over a window for a history.""" if isinstance(locate, (StaticProfile, Mapping)): - return _node_arc(locate, None, "linear", line_id) + return _node_arc(locate, None, "linear", line_id, deck_nodes) positions = line_positions( locate, # type: ignore[arg-type] line_id=line_id if isinstance(locate, TimeHistory) and not _per_line(locate) else None, ).period(start, stop) + if deck_nodes: + return _deck_node_positions( + locate, positions.node_ids, np.mean(positions.arc_length, axis=0) + ) return positions.node_ids, np.mean(positions.arc_length, axis=0) @@ -1085,7 +1226,7 @@ def line_range_graph( raise ValueError("a segment range graph needs node positions to place the segments") kind, location = "Node", field.ids.astype(np.float64) else: - node_ids, arc = _mean_node_arc(locate, line_id, start, stop) + node_ids, arc = _mean_node_arc(locate, line_id, start, stop, field.deck_nodes) kind, location = "ArcLength", _assign(field, isinstance(locate, Mapping), node_ids, arc) order = np.argsort(location, kind="stable") values = field.values[:, order] diff --git a/python/cabledyn/ranges.py b/python/cabledyn/ranges.py index 6cbee0eb..f823c8eb 100644 --- a/python/cabledyn/ranges.py +++ b/python/cabledyn/ranges.py @@ -17,10 +17,13 @@ cubic-Hermite element table (``.elements.out``). Node channels are written only for the nodes named in the deck ``OUTPUTS`` -section. Their positions along the line come from ``arc_length``: a static -profile of the same run (the node's static deformed arc length), an explicit -mapping from node number to arc length, or nothing, in which case the graph is -plotted against node number. +section and number deck nodes (1 at End A to 1 + the total ``NumSegs`` of the +line's sections at End B). Their positions along the line come from +``arc_length``: a static profile of the same run (the node's static deformed arc +length; on a line whose mesh the static solve refined, the deck node's row of +the profile, see :meth:`~cabledyn.StaticProfile.deck_node_arc_lengths`), an +explicit mapping from node number to arc length, or nothing, in which case the +graph is plotted against node number. """ from __future__ import annotations @@ -130,14 +133,8 @@ def node_locations( if arc_length is None: return "Node", np.asarray(node_ids, dtype=np.float64) if isinstance(arc_length, StaticProfile): - line = arc_length.line(line_id) - lookup = dict( - zip( - (int(node) for node in line.column("Node")), - (float(arc) for arc in line.column("ArcLength")), - strict=True, - ) - ) + # node channels number deck nodes; a refined line's profile locates them (DeckNode) + lookup = arc_length.deck_node_arc_lengths(line_id) elif isinstance(arc_length, Mapping): lookup = {int(node): float(arc) for node, arc in arc_length.items()} else: diff --git a/python/cabledyn/results.py b/python/cabledyn/results.py index 6366013a..b9cf14b7 100644 --- a/python/cabledyn/results.py +++ b/python/cabledyn/results.py @@ -865,11 +865,16 @@ class LineNodeHistory(TimeHistory): are those of :class:`cabledyn.OutputTable`, with ``values`` of shape ``(n_samples, 1 + 3 * n_nodes)``; positions are in metres. + The file lists every node of the line's final mesh. On a finite-EI line + whose mesh the static solve refined, a ``# DeckNode`` comment line names + the deck node of each (:attr:`deck_nodes`). + Raises ------ OutputFormatError If the node channels are malformed, not contiguous from ``Node1``, or - not in metres, or time does not strictly increase. + not in metres, time does not strictly increase, or a ``# DeckNode`` + line does not number the deck nodes of the file's nodes. """ def __post_init__(self) -> None: @@ -888,6 +893,31 @@ def __post_init__(self) -> None: units = {match.group(3) for match in parsed if match is not None} if units != {"m"}: raise OutputFormatError(f"{self.path}: line-node position channels must use metres") + deck = self.deck_nodes + if deck is not None: + named = deck[deck > 0] + if ( + deck.size != node_count + or np.any(deck < 0) + or deck[0] != 1 + or deck[-1] <= 0 + or not np.array_equal(named, np.arange(1, named.size + 1)) + ): + raise OutputFormatError( + f"{self.path}: the DeckNode line does not number the deck nodes of the " + f"{node_count} nodes 1, 2, ... from End A to End B" + ) + + @property + def deck_nodes(self) -> npt.NDArray[np.int64] | None: + """Deck node of each node of the file, or ``None`` for the deck mesh. + + ``(n_nodes,)`` deck node numbers (the ```` of the node channels of + a main output) from the file's ``# DeckNode`` line, 0 for a node a mesh + refinement added; ``None`` when the file has no such line (the line was + not refined, so its nodes are the deck nodes). + """ + return _deck_node_comment(self.title, self.path) @property def node_ids(self) -> tuple[int, ...]: @@ -1180,12 +1210,21 @@ class StaticProfile(OutputTable): :class:`cabledyn.OutputTable`, with ``values`` of shape ``(n_rows, n_channels)``. + A finite-EI line whose mesh the static solve refined lists every node of + its final mesh. The file then has a ``DeckNode`` column: the deck node of + each row (deck nodes run from 1 at End A to 1 + the total ``NumSegs`` of the + line's sections at End B), or 0 for a node the refinement added. The node + channels of a main output (``TenN``, ``LNpx``, ...) number deck + nodes; :meth:`deck_node_arc_lengths` places them. + Raises ------ OutputFormatError If a required column is missing, ``LineID`` or ``Node`` values are not - positive integers, a line's rows are not contiguous, or a line's arc - length or node order is not increasing. + positive integers, a line's rows are not contiguous, a line's arc + length or node order is not increasing, or a ``DeckNode`` column does + not number the deck nodes of a line in increasing order from 1 at its + first row to its last row. """ def __post_init__(self) -> None: @@ -1225,6 +1264,24 @@ def __post_init__(self) -> None: raise OutputFormatError( f"{self.path}: LineID {line_id} node order is not increasing" ) + if "DeckNode" in self.channels: + deck = self.column("DeckNode") + if np.any(deck < 0.0) or np.any(deck != np.floor(deck)): + raise OutputFormatError( + f"{self.path}: DeckNode values must be non-negative integers" + ) + for line_id in self.line_ids: + numbered = deck[self.column("LineID") == line_id] + named = numbered[numbered > 0.0] + if ( + numbered[0] != 1.0 + or numbered[-1] <= 0.0 + or np.any(named != np.arange(1, named.size + 1)) + ): + raise OutputFormatError( + f"{self.path}: LineID {line_id} DeckNode does not number the deck nodes " + "1, 2, ... from End A to End B" + ) @property def line_ids(self) -> tuple[int, ...]: @@ -1258,6 +1315,40 @@ def line(self, line_id: int) -> StaticProfile: self.path, self.title, self.channels, self.units, self.values[mask].copy() ) + def deck_node_arc_lengths(self, line_id: int) -> dict[int, float]: + """Return the static arc length of each deck node of one line. + + The node channels of a main output number deck nodes, from 1 at End A + to 1 + the total ``NumSegs`` of the line's sections at End B. On a line + whose mesh the static solve refined, the profile lists every node of the + final mesh and its ``DeckNode`` column locates the deck nodes among + them; otherwise the profile nodes are the deck nodes. + + Parameters + ---------- + line_id : int + One-based line identifier, as in the ``LineID`` column. + + Returns + ------- + dict[int, float] + Deck node number to its deformed arc length from End A, in metres. + + Raises + ------ + KeyError + If the profile has no rows for ``line_id``. + """ + line = self.line(line_id) + arc = line.column("ArcLength") + if "DeckNode" not in line.channels: + nodes = line.column("Node") + return {int(node): float(value) for node, value in zip(nodes, arc, strict=True)} + deck = line.column("DeckNode") + return { + int(node): float(value) for node, value in zip(deck, arc, strict=True) if node > 0.0 + } + def summary(self, line_id: int) -> StaticLineSummary: """Return core geometry and demand extrema for one line. @@ -1487,6 +1578,18 @@ def _check_not_device(table_path: Path) -> None: ) +def _deck_node_comment(title: str, path: Path | None = None) -> npt.NDArray[np.int64] | None: + """Deck node numbers of a ``# DeckNode`` comment line of a result title, if any.""" + for line in title.splitlines(): + tokens = line.split() + if len(tokens) >= 2 and tokens[0] == "#" and tokens[1] == "DeckNode": + try: + return np.asarray([int(token) for token in tokens[2:]], dtype=np.int64) + except ValueError as exc: + raise OutputFormatError(f"{path}: malformed DeckNode line") from exc + return None + + def _read_lines(table_path: Path) -> list[str]: """Return the lines of a UTF-8 text output file, failing with OutputFormatError.""" _check_not_device(table_path) diff --git a/python/tests/test_profiles.py b/python/tests/test_profiles.py index 479c07b3..53081156 100644 --- a/python/tests/test_profiles.py +++ b/python/tests/test_profiles.py @@ -10,7 +10,7 @@ import pytest from _design_data import TIME, write_main, write_static -from cabledyn import read_moordyn_line, read_output +from cabledyn import node_range_graph, read_moordyn_line, read_output from cabledyn.profiles import ( ArcProfile, LineField, @@ -463,6 +463,76 @@ def test_line_range_graph_of_main_output_and_static_profile(tmp_path): np.testing.assert_array_equal(moment.minimum, moment.maximum) +def _write_refined_static(path): + """Line 1 refined twice: deck nodes 1, 2, 3 are mesh nodes 1, 3, 5 (25 m apart).""" + lines = [ + "CableDyn standalone static configuration (deformed arc; public node order End A -> End B)", + "LineID\tNode\tArcLength\tX\tY\tZ\tTension\tCurvature\tBendMoment\tDeckNode", + "(-)\t(-)\t(m)\t(m)\t(m)\t(m)\t(N)\t(1/m)\t(N.m)\t(-)", + ] + for node in range(1, 6): + deck = (node + 1) // 2 if node % 2 else 0 + lines.append(f"1\t{node}\t{25.0 * (node - 1)}\t0\t0\t-50\t{1.0e5 * node}\t0\t0\t{deck}") + path.write_text("\n".join(lines) + "\n", encoding="ascii") + return read_output(path) + + +def test_main_output_node_channels_are_deck_nodes_on_a_refined_line(tmp_path): + # Ten1N3 names deck node 3 (End B), mesh node 5 of the refined line + main = _write_main_output(tmp_path / "run.out") + refined = _write_refined_static(tmp_path / "run.static.out") + assert "deck_node" not in available_quantities(refined, line_id=1) + by_static = profile_at(main, "tension", 10.0, line_id=1, positions=refined) + np.testing.assert_allclose(by_static.location, [0.0, 100.0]) + graph = line_range_graph(main, "tension", line_id=1, positions=refined) + np.testing.assert_allclose(graph.location, [0.0, 100.0]) + by_channels = node_range_graph(main, 1, "tension", arc_length=refined) + np.testing.assert_allclose(by_channels.location, [0.0, 100.0]) + # the static profile's own fields stay on its mesh nodes + own = profile_at(refined, "tension", line_id=1) + np.testing.assert_allclose(own.location, 25.0 * np.arange(5)) + # a per-line position file lists the refined mesh: the profile beside it locates the deck nodes + nodes = _write_nodes(tmp_path / "run.Line1.p.out") + by_file = profile_at(main, "tension", 1.0, line_id=1, positions=nodes) + np.testing.assert_allclose(by_file.location, [0.0, 4.0 * _chord(1.0)]) + by_file_graph = line_range_graph(main, "tension", line_id=1, positions=nodes) + mean_arc = np.mean([4.0 * _chord(t) for t in TIMES]) + np.testing.assert_allclose(by_file_graph.location, [0.0, mean_arc]) + alone = tmp_path / "alone" + alone.mkdir() + unrefined = _write_nodes(alone / "run.Line1.p.out") + by_alone = profile_at(main, "tension", 1.0, line_id=1, positions=unrefined) + np.testing.assert_allclose(by_alone.location, [0.0, 2.0 * _chord(1.0)]) + + +def test_line_positions_of_a_multi_line_refined_profile_keep_their_line(tmp_path): + # line 2 is meshed as the deck; line 1 is refined (deck nodes 1, 2, 3 are mesh nodes 1, 3, 5) + path = tmp_path / "run.static.out" + rows = [ + "CableDyn standalone static configuration (deformed arc; public node order End A -> End B)", + "LineID\tNode\tArcLength\tX\tY\tZ\tTension\tCurvature\tBendMoment\tDeckNode", + "(-)\t(-)\t(m)\t(m)\t(m)\t(m)\t(N)\t(1/m)\t(N.m)\t(-)", + ] + for node in range(1, 6): + deck = (node + 1) // 2 if node % 2 else 0 + arc = 25.0 * (node - 1) + rows.append(f"1\t{node}\t{arc}\t{arc}\t0\t-50\t{1.0e5 * node}\t0\t0\t{deck}") + for node in range(1, 4): + arc = 50.0 * (node - 1) + rows.append(f"2\t{node}\t{arc}\t{arc}\t10\t-50\t1e5\t0\t0\t{node}") + path.write_text("\n".join(rows) + "\n", encoding="ascii") + profile = read_output(path) + main = _write_main_output(tmp_path / "run.out") + positions = line_positions(profile, line_id=1) + assert positions.line_id == 1 + placed = profile_at(main, "tension", 10.0, line_id=1, positions=positions) + np.testing.assert_allclose(placed.location, [0.0, 100.0]) + # without the selected line the multi-line profile cannot name one map + ambiguous = LinePositions(None, positions.positions, positions.node_ids, positions.source) + with pytest.raises(ValueError, match="several lines"): + profile_at(main, "tension", 10.0, line_id=1, positions=ambiguous) + + def test_per_line_range_graph_takes_its_line_id_from_the_file_name(tmp_path): nodes = _write_nodes(tmp_path / "run.Line3.p.out") assert line_range_graph(nodes, "z").line_id == 3 diff --git a/python/tests/test_results.py b/python/tests/test_results.py index f213c8ca..22a9bdb0 100644 --- a/python/tests/test_results.py +++ b/python/tests/test_results.py @@ -729,6 +729,21 @@ def test_static_summary_without_curvature_and_with_zero_curvature(tmp_path): [[1, 1, 0.0], [2, 1, 0.0], [1, 2, 1.0]], "LineID 1 rows are not contiguous", ), + ( + ("LineID", "Node", "ArcLength", "DeckNode"), + [[1, 1, 0.0, 1], [1, 2, 1.0, 0.5]], + "DeckNode values must be non-negative integers", + ), + ( + ("LineID", "Node", "ArcLength", "DeckNode"), + [[1, 1, 0.0, 1], [1, 2, 1.0, 0], [1, 3, 2.0, 3]], + "LineID 1 DeckNode does not number the deck nodes", + ), + ( + ("LineID", "Node", "ArcLength", "DeckNode"), + [[1, 1, 0.0, 1], [1, 2, 1.0, 2], [1, 3, 2.0, 0]], + "LineID 1 DeckNode does not number the deck nodes", + ), ], ) def test_static_profile_validation(tmp_path, channels, rows, message): @@ -736,6 +751,22 @@ def test_static_profile_validation(tmp_path, channels, rows, message): StaticProfile(tmp_path / "s.out", "", channels, None, np.asarray(rows, dtype=float)) +def test_static_profile_deck_node_arc_lengths(tmp_path): + # line 1 refined twice: deck nodes 1, 2, 3 are mesh nodes 1, 3, 5; line 2 is the deck mesh + channels = ("LineID", "Node", "ArcLength", "DeckNode") + rows = [[1, n, 10.0 * (n - 1), (n + 1) // 2 if n % 2 else 0] for n in range(1, 6)] + rows += [[2, 1, 0.0, 1], [2, 2, 4.0, 2]] + profile = StaticProfile(tmp_path / "s.out", "", channels, None, np.asarray(rows, dtype=float)) + assert profile.deck_node_arc_lengths(1) == {1: 0.0, 2: 20.0, 3: 40.0} + assert profile.deck_node_arc_lengths(2) == {1: 0.0, 2: 4.0} + plain = StaticProfile( + tmp_path / "p.out", "", channels[:3], None, np.asarray([[1, 1, 0.0], [1, 2, 3.0]]) + ) + assert plain.deck_node_arc_lengths(1) == {1: 0.0, 2: 3.0} + with pytest.raises(KeyError, match="LineID 3"): + profile.deck_node_arc_lengths(3) + + # ---------------------------------------------------------------------------- plots and data frames diff --git a/src/CableDyn_CAPI.f90 b/src/CableDyn_CAPI.f90 index 7f50c96f..b2455028 100644 --- a/src/CableDyn_CAPI.f90 +++ b/src/CableDyn_CAPI.f90 @@ -16,7 +16,7 @@ MODULE CableDyn_CAPI USE CableDyn_DeckDriver, ONLY: CD_Init_Deck_System, CD_DECKDRV_OK, CD_DECKDRV_BADINPUT, CD_DECKDRV_SOLVEFAIL, & CD_Deck_Query_dtM, CD_DECK_NAMELEN, CD_Eval_Aggregate_Channel, & CD_Eval_Aggregate_Segment_Tensions, CD_Rigid6_Inventory, CD_Rod_Inventory, & - CD_Channel_Token_Parses + CD_Channel_Token_Parses, CD_Cable_Deck_Node USE CableDyn_OpenFAST_Aggregate, ONLY: CD_AGG_ModuleType, CD_AGG_Init_From_Deck, CD_AGG_NMovingPoints, & CD_AGG_UpdateStates_Moving, CD_AGG_Step_Moving, CD_AGG_CalcOutput, & CD_AGG_GetMovingPointMesh, CD_AGG_End, CD_AGG_IsInitialized, CD_AGG_OK, & @@ -90,7 +90,7 @@ MODULE CableDyn_CAPI CD_C_LINE_TENSION = 3_C_INT, CD_C_LINE_ACCELERATION = 4_C_INT, & CD_C_LINE_CURVATURE = 5_C_INT, CD_C_LINE_BEND_MOMENT = 6_C_INT, & CD_C_LINE_DECLINATION = 7_C_INT, CD_C_LINE_AZIMUTH = 8_C_INT, & - CD_C_LINE_SEGMENT_TENSION = 9_C_INT + CD_C_LINE_SEGMENT_TENSION = 9_C_INT, CD_C_LINE_DECK_NODE = 10_C_INT !> Capacity of the per-handle diagnostic retained for CableDyn_GetLastError. INTEGER, PARAMETER :: CD_C_MSG_LEN = 1024 @@ -1463,7 +1463,9 @@ SUBROUTINE CableDyn_GetLineValues(handle, index, quantity, out_ptr, n_out, err_s !! One quantity along line `index` (0-based) in public node order End A -> End B. !! quantity: CD_C_LINE_POSITION / VELOCITY / ACCELERATION (3 per node, xyz interleaved), !! TENSION / CURVATURE / BEND_MOMENT / DECLINATION / AZIMUTH (1 per node), or - !! SEGMENT_TENSION (1 per segment). n_out must equal the value count exactly. + !! SEGMENT_TENSION (1 per segment), or DECK_NODE (1 per node: the deck node of each node of the + !! line's final mesh, the J of the node channels; 0 for a node a refinement added). Every quantity + !! covers every node of the final mesh. n_out must equal the value count exactly. TYPE(C_PTR), VALUE :: handle, out_ptr INTEGER(C_INT), VALUE :: index, quantity, n_out INTEGER(C_INT), INTENT(OUT) :: err_stat @@ -1493,7 +1495,7 @@ SUBROUTINE CableDyn_GetLineValues(handle, index, quantity, out_ptr, n_out, err_s IF (quantity == CD_C_LINE_VELOCITY) field = 'v' IF (quantity == CD_C_LINE_ACCELERATION) field = 'a' CASE (CD_C_LINE_TENSION, CD_C_LINE_CURVATURE, CD_C_LINE_BEND_MOMENT, CD_C_LINE_DECLINATION, & - CD_C_LINE_AZIMUTH) + CD_C_LINE_AZIMUTH, CD_C_LINE_DECK_NODE) nvals = nnode CASE (CD_C_LINE_SEGMENT_TENSION) nvals = nnode - 1 @@ -1508,6 +1510,20 @@ SUBROUTINE CableDyn_GetLineValues(handle, index, quantity, out_ptr, n_out, err_s END IF CALL C_F_POINTER(out_ptr, out_c, [nvals]) + IF (quantity == CD_C_LINE_DECK_NODE) THEN + ! deck node of each mesh node: a refined finite-EI cable maps them; any other line is meshed + ! as the deck + DO node = 1, nnode + out_c(node) = REAL(node, C_DOUBLE) + IF (h%use_agg) THEN + IF (h%agg%line_is_cable(line_id)) out_c(node) = & + REAL(CD_Cable_Deck_Node(h%agg%cables(h%agg%line_obj_index(line_id)), node), C_DOUBLE) + END IF + END DO + CALL store_status(h, CD_C_OK, '') + RETURN + END IF + IF (quantity == CD_C_LINE_SEGMENT_TENSION) THEN BLOCK REAL(wp) :: ten(nvals) @@ -1534,7 +1550,7 @@ SUBROUTINE CableDyn_GetLineValues(handle, index, quantity, out_ptr, n_out, err_s SELECT CASE (quantity) CASE (CD_C_LINE_POSITION, CD_C_LINE_VELOCITY, CD_C_LINE_ACCELERATION) DO c = 1, 3 - CALL eval_token(h, 'L'//TRIM(stem)//field//xyz(c), val, err_stat) + CALL eval_token(h, 'L'//TRIM(stem)//field//xyz(c), val, err_stat, mesh_node=.TRUE.) IF (err_stat /= CD_C_OK) RETURN out_c(3*(node - 1) + c) = REAL(val, C_DOUBLE) END DO @@ -1550,7 +1566,7 @@ SUBROUTINE CableDyn_GetLineValues(handle, index, quantity, out_ptr, n_out, err_s CASE DEFAULT token = 'L'//TRIM(stem)//'Azi' END SELECT - CALL eval_token(h, token, val, err_stat) + CALL eval_token(h, token, val, err_stat, mesh_node=.TRUE.) IF (err_stat /= CD_C_OK) RETURN out_c(node) = REAL(val, C_DOUBLE) END DO @@ -2027,12 +2043,15 @@ SUBROUTINE collect_points(system) END SUBROUTINE collect_points END SUBROUTINE object_inventory - SUBROUTINE eval_token(h, token, val, err_stat) - !! Evaluate one channel token on the handle's model (aggregate or point route). + SUBROUTINE eval_token(h, token, val, err_stat, mesh_node) + !! Evaluate one channel token on the handle's model (aggregate or point route). A node token + !! names a deck node; mesh_node = .TRUE. reads it as a node of the line's final mesh instead + !! (CableDyn_GetLineValues lists every mesh node of a refined finite-EI line). TYPE(CD_C_Handle), POINTER, INTENT(INOUT) :: h CHARACTER(*), INTENT(IN) :: token REAL(wp), INTENT(OUT) :: val INTEGER(C_INT), INTENT(OUT) :: err_stat + LOGICAL, INTENT(IN), OPTIONAL :: mesh_node INTEGER :: es CHARACTER(CD_C_MSG_LEN) :: em @@ -2041,15 +2060,18 @@ SUBROUTINE eval_token(h, token, val, err_stat) IF (h%agg%has_rigid6) THEN CALL CD_Eval_Aggregate_Channel(token, h%agg%has_sys, h%agg%sys%fast%system, h%agg%cables, & h%agg%line_is_cable, h%agg%line_obj_index, val, es, em, & - cable_points=h%agg%cable_points, rigid_rt=h%agg%rigid6, ranges=h%agg%ranges) + cable_points=h%agg%cable_points, rigid_rt=h%agg%rigid6, ranges=h%agg%ranges, & + mesh_node=mesh_node) ELSE IF (h%agg%has_rod) THEN CALL CD_Eval_Aggregate_Channel(token, h%agg%has_sys, h%agg%sys%fast%system, h%agg%cables, & h%agg%line_is_cable, h%agg%line_obj_index, val, es, em, & - cable_points=h%agg%cable_points, rod_rt=h%agg%rod, ranges=h%agg%ranges) + cable_points=h%agg%cable_points, rod_rt=h%agg%rod, ranges=h%agg%ranges, & + mesh_node=mesh_node) ELSE CALL CD_Eval_Aggregate_Channel(token, h%agg%has_sys, h%agg%sys%fast%system, h%agg%cables, & h%agg%line_is_cable, h%agg%line_obj_index, val, es, em, & - cable_points=h%agg%cable_points, ranges=h%agg%ranges) + cable_points=h%agg%cable_points, ranges=h%agg%ranges, & + mesh_node=mesh_node) END IF ELSE IF (.NOT. (ALLOCATED(h%pt_obj) .AND. ALLOCATED(h%pt_is_cable))) THEN diff --git a/src/CableDyn_CAPI.h b/src/CableDyn_CAPI.h index 31253a3a..ed888f9f 100644 --- a/src/CableDyn_CAPI.h +++ b/src/CableDyn_CAPI.h @@ -135,16 +135,21 @@ int CableDyn_NLines(void *handle, int *err_stat); #define CD_C_OBJ_BODY 3 #define CD_C_OBJ_ROD 4 -/* Line quantities (the codes of the line-node output channels). */ +/* Line quantities (the codes of the line-node output channels). Every quantity covers every + * node of the line's final mesh; the node channels of CableDyn_EvalChannel (TenN, ...) + * name deck nodes, which CD_C_LINE_DECK_NODE locates on a refined finite-EI line. */ #define CD_C_LINE_POSITION 1 /* 3 per node, xyz interleaved [m] */ #define CD_C_LINE_VELOCITY 2 /* 3 per node [m/s] */ -#define CD_C_LINE_TENSION 3 /* 1 per node, TenN [N] */ +#define CD_C_LINE_TENSION 3 /* 1 per mesh node, as TenN [N] */ #define CD_C_LINE_ACCELERATION 4 /* 3 per node [m/s^2] */ #define CD_C_LINE_CURVATURE 5 /* 1 per node [1/m] */ #define CD_C_LINE_BEND_MOMENT 6 /* 1 per node [N.m], 0 when EI=0 */ #define CD_C_LINE_DECLINATION 7 /* 1 per node [deg] */ #define CD_C_LINE_AZIMUTH 8 /* 1 per node [deg] */ #define CD_C_LINE_SEGMENT_TENSION 9 /* 1 per segment, .t.out order [N] */ +#define CD_C_LINE_DECK_NODE 10 /* 1 per mesh node: its deck node J, 0 if added by a + * refinement (an earlier library rejects the + * code with CD_C_BAD_INPUT) */ int CableDyn_GetAbiMinor(void); int CableDyn_NObjects(void *handle, int kind, int *err_stat); @@ -152,7 +157,8 @@ int CableDyn_NObjects(void *handle, int kind, int *err_stat); * 2 Coupled, 3 Free, 4 Connect. Bodies: n_nodes 1. Rods: n_nodes = NumSegs+1. */ void CableDyn_GetObjectInfo(void *handle, int kind, int index, int *id, int *n_nodes, int *subtype, int *err_stat); -/* Nodes run End A -> End B; n_out must equal the value count exactly. */ +/* Every node of the line's final mesh, End A -> End B (node channels name deck nodes; see + * CD_C_LINE_DECK_NODE); n_out must equal the value count exactly. */ void CableDyn_GetLineValues(void *handle, int index, int quantity, double *out, int n_out, int *err_stat); /* pos, vel, force: 3 doubles each (NULL skips). force is the resultant of diff --git a/src/CableDyn_DeckDriver.f90 b/src/CableDyn_DeckDriver.f90 index 73328fbe..8596e50f 100644 --- a/src/CableDyn_DeckDriver.f90 +++ b/src/CableDyn_DeckDriver.f90 @@ -208,6 +208,8 @@ MODULE CableDyn_DeckDriver ! Both reuse the same private evaluators the standalone .out writers use, so a coupled run ! and the standalone driver report identical channel values on a shared configuration. PUBLIC :: CD_Eval_Aggregate_Channel, CD_Channel_Unit + ! The deck node of a node of a finite-EI cable's final mesh (the static-profile DeckNode column). + PUBLIC :: CD_Cable_Deck_Node ! In-process object queries of the C API (CableDyn_CAPI): segment tensions in the .t.out ! convention, and the body/rod inventories the Body/Rod channels resolve on. PUBLIC :: CD_Eval_Aggregate_Segment_Tensions, CD_Rigid6_Inventory, CD_Rod_Inventory, CD_Channel_Token_Parses @@ -1627,6 +1629,8 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, REAL(wp), ALLOCATABLE :: l0_am(:), ea_am(:), ei_am(:), w_am(:) INTEGER, ALLOCATABLE :: fixed_am(:) TYPE(CD_HermiteResolutionType) :: diag + ! Deck node -> final-mesh node map of the node output channels (deck_node_mesh_map). + INTEGER, ALLOCATABLE :: deck_map(:) ! ATTACHMENTS: the deck-mesh bare submerged weight and mesh (the static solve runs on the ! smeared equivalent first), and the attachment nodes on the final mesh. LOGICAL :: has_att @@ -2781,6 +2785,9 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, CALL remap_elem_by_reference_arc(cat, l0, l0_am) CALL remap_elem_by_reference_arc(ba_raw, l0, l0_am) END IF + ! The node output channels read deck nodes: map each onto the final mesh (set on the cable + ! once it is built below). + CALL deck_node_mesh_map(l0, l0_am, deck_map) CALL MOVE_ALLOC(l0_am, l0) CALL MOVE_ALLOC(ea_am, ea) CALL MOVE_ALLOC(ei_am, ei) @@ -2864,6 +2871,7 @@ RECURSIVE SUBROUTINE build_one_hermite_cable(ln, sections, types, points, opts, IF (es /= CD_HFMF_OK) THEN CALL fail(ErrStat, ErrMsg, 'finite-EI cable coupled-shell init failed: '//TRIM(em)); RETURN END IF + IF (ALLOCATED(deck_map)) CALL MOVE_ALLOC(deck_map, cable%deck_node) IF (ANY(ba > CD_ZERO)) THEN CALL CD_HFMF_Set_Axial_Damping(cable, ba, es, em) IF (es /= CD_HFMF_OK) THEN @@ -8442,6 +8450,42 @@ SUBROUTINE remap_elem_by_reference_arc(a, l0_parent, l0_child) CALL MOVE_ALLOC(b, a) END SUBROUTINE remap_elem_by_reference_arc + SUBROUTINE deck_node_mesh_map(l0_deck, l0_mesh, map) + !! The public node (End A = 1) of a finite-EI line's final mesh at each deck node, matched on + !! the reference arc from End A: map(J) = k when mesh node k lies within 1e-9 of the line length + !! of deck node J, else 0. l0_deck and l0_mesh are the element lengths of the deck mesh and of + !! the final mesh in internal order (End B first). The match uses the arc positions alone, so + !! any refinement that keeps the deck nodes, uniform or local, maps exactly. The map is left + !! unallocated when the final mesh is the deck mesh. + REAL(wp), INTENT(IN) :: l0_deck(:), l0_mesh(:) + INTEGER, ALLOCATABLE, INTENT(OUT) :: map(:) + REAL(wp) :: s_mesh(SIZE(l0_mesh) + 1), s_deck, tol + INTEGER :: nd, nm, j, k + + nd = SIZE(l0_deck) + nm = SIZE(l0_mesh) + IF (nd == nm) THEN + IF (.NOT. (MAXVAL(ABS(l0_deck - l0_mesh)) > CD_ZERO)) RETURN + END IF + s_mesh(1) = CD_ZERO + DO k = 1, nm + s_mesh(k + 1) = s_mesh(k) + l0_mesh(nm - k + 1) + END DO + tol = 1.0e-9_wp*MAX(SUM(l0_deck), s_mesh(nm + 1)) + ALLOCATE (map(nd + 1)) + map = 0 + k = 1 + s_deck = CD_ZERO + DO j = 1, nd + 1 + ! public deck element j - 1 is internal element nd - j + 2 + IF (j > 1) s_deck = s_deck + l0_deck(nd - j + 2) + DO WHILE (k < nm + 1 .AND. s_mesh(k) < s_deck - tol) + k = k + 1 + END DO + IF (ABS(s_mesh(k) - s_deck) <= tol) map(j) = k + END DO + END SUBROUTINE deck_node_mesh_map + SUBROUTINE finite_section_closure(ea, ei, mpl, diam, gas_in, gj_in, i_rt_in, i_rn_in, & gas, gj, rho_a, i_rt, i_rn, ErrStat, ErrMsg) !! Close deck-format finite-EI properties for the Cosserat dynamic model. @@ -25990,6 +26034,7 @@ SUBROUTINE write_hermite_static_profile(out_root, lines, cables, ErrStat, ErrMsg CHARACTER(*), INTENT(OUT) :: ErrMsg INTEGER :: unit, ios, li, node, nn + LOGICAL :: refined REAL(wp) :: s, xyz(3), xyz_prev(3), tension, curvature, bend_moment, declination, azimuth CHARACTER(NAMELEN) :: channel CHARACTER(LEN(out_root) + 16) :: path @@ -26005,11 +26050,19 @@ SUBROUTINE write_hermite_static_profile(out_root, lines, cables, ErrStat, ErrMsg CALL fail(ErrStat, ErrMsg, 'cannot open Hermite static profile: '//TRIM(path)); RETURN END IF tab = CHAR(9) + ! A line whose mesh the static solve refined lists every node of its final mesh; the DeckNode + ! column then names the deck node of each row (0: a node the refinement added). + refined = .FALSE. + DO li = 1, SIZE(cables) + refined = refined .OR. ALLOCATED(cables(li)%deck_node) + END DO WRITE (unit, '(A)') 'CableDyn standalone static configuration (deformed arc; public node order End A -> End B)' WRITE (unit, '(A)') 'LineID'//tab//'Node'//tab//'ArcLength'//tab//'X'//tab//'Y'//tab//'Z'//tab// & - 'Tension'//tab//'Curvature'//tab//'BendMoment'//tab//'Declination'//tab//'Inclination'//tab//'Azimuth' + 'Tension'//tab//'Curvature'//tab//'BendMoment'//tab//'Declination'//tab//'Inclination'//tab//'Azimuth'// & + TRIM(MERGE(tab//'DeckNode', REPEAT(' ', 9), refined)) WRITE (unit, '(A)') '(-)'//tab//'(-)'//tab//'(m)'//tab//'(m)'//tab//'(m)'//tab//'(m)'//tab// & - '(N)'//tab//'(1/m)'//tab//'(N.m)'//tab//'(deg)'//tab//'(deg)'//tab//'(deg)' + '(N)'//tab//'(1/m)'//tab//'(N.m)'//tab//'(deg)'//tab//'(deg)'//tab//'(deg)'// & + TRIM(MERGE(tab//'(-)', REPEAT(' ', 4), refined)) DO li = 1, SIZE(lines) nn = CD_HFMF_NNodes(cables(li)) @@ -26028,9 +26081,15 @@ SUBROUTINE write_hermite_static_profile(out_root, lines, cables, ErrStat, ErrMsg CALL eval_node('Dec', declination); IF (ErrStat /= CD_DECKDRV_OK) RETURN CALL eval_node('Azi', azimuth); IF (ErrStat /= CD_DECKDRV_OK) RETURN IF (node > 1) s = s + NORM2(xyz - xyz_prev) - WRITE (unit, '(I0,A,I0,10(A,ES15.7E3))') lines(li)%id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & - tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & - tab, declination - 90.0_wp, tab, azimuth + IF (refined) THEN + WRITE (unit, '(I0,A,I0,10(A,ES15.7E3),A,I0)') lines(li)%id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & + tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & + tab, declination - 90.0_wp, tab, azimuth, tab, CD_Cable_Deck_Node(cables(li), node) + ELSE + WRITE (unit, '(I0,A,I0,10(A,ES15.7E3))') lines(li)%id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & + tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & + tab, declination - 90.0_wp, tab, azimuth + END IF xyz_prev = xyz END DO END DO @@ -26047,7 +26106,7 @@ SUBROUTINE eval_node(kind, value) ELSE WRITE (channel, '(A,I0,A,I0)') TRIM(kind), lines(li)%id, 'N', node END IF - CALL eval_cable_channel(cables(li), TRIM(channel), value, ErrStat, eval_msg) + CALL eval_cable_channel(cables(li), TRIM(channel), value, ErrStat, eval_msg, mesh_node=.TRUE.) IF (ErrStat /= CD_DECKDRV_OK) THEN CLOSE (unit, STATUS='DELETE') ErrMsg = 'CableDyn_DeckDriver: Hermite static-profile channel '//TRIM(channel)//' failed: '//TRIM(eval_msg) @@ -26338,6 +26397,15 @@ SUBROUTINE open_dynamic_hermite_line_outputs(out_root, lines, cables, pos_units, CALL fail(ErrStat, ErrMsg, 'cannot open Hermite line position output: '//TRIM(path)); RETURN END IF WRITE (pos_units(i), '(A)') '# CableDyn finite-EI Hermite line node positions; public node order EndA -> EndB' + IF (ALLOCATED(cables(i)%deck_node)) THEN + ! A line whose mesh the static solve refined lists every node of its final mesh: name the + ! deck node of each (0: a node the refinement added), as the static-profile DeckNode column + WRITE (pos_units(i), '(A)', ADVANCE='NO') '# DeckNode' + DO node = 1, cables(i)%line%nn + WRITE (pos_units(i), '(A,I0)', ADVANCE='NO') char_tab(), CD_Cable_Deck_Node(cables(i), node) + END DO + WRITE (pos_units(i), '(A)') '' + END IF WRITE (pos_units(i), '(A)', ADVANCE='NO') 'Time(s)' DO node = 1, cables(i)%line%nn WRITE (pos_units(i), '(A,A,I0,A)', ADVANCE='NO') char_tab(), 'Node', node, 'X(m)' @@ -31737,7 +31805,7 @@ END SUBROUTINE aggregate_tdp_value ! -------------------------------------------------------------------------- ! SUBROUTINE CD_Eval_Aggregate_Channel(ch, has_sys, system, cables, line_is_cable, line_obj_index, val, ErrStat, & - ErrMsg, cable_points, rigid_rt, rod_rt, ranges) + ErrMsg, cable_points, rigid_rt, rod_rt, ranges, mesh_node) !! Evaluate ONE deck OUTPUTS channel token against a built aggregate. The token's deck line !! id is resolved through the map to either an EI=0 system line (eval_system_line_channel) or !! a finite-EI cable (eval_cable_channel); Point

channels read the EI=0 system point state. @@ -31762,6 +31830,9 @@ SUBROUTINE CD_Eval_Aggregate_Channel(ch, has_sys, system, cables, line_is_cable, TYPE(CD_RodRuntimeType), INTENT(IN), OPTIONAL :: rod_rt ! TDP channels: the touchdown references fixed at initialization TYPE(CD_RangeSet), INTENT(IN), OPTIONAL :: ranges + ! A node channel names a deck node; mesh_node = .TRUE. reads it as a node of the line's final + ! mesh instead (eval_cable_channel), as the static profile and the C API line arrays do + LOGICAL, INTENT(IN), OPTIONAL :: mesh_node CHARACTER(NAMELEN) :: lo LOGICAL :: found @@ -31914,7 +31985,7 @@ SUBROUTINE CD_Eval_Aggregate_Channel(ch, has_sys, system, cables, line_is_cable, IF (line_obj_index(line_id) > SIZE(cables)) THEN CALL fail(ErrStat, ErrMsg, 'OUTPUT "'//TRIM(ch)//'": cable index out of range'); RETURN END IF - CALL eval_cable_channel(cables(line_obj_index(line_id)), ch, val, ErrStat, ErrMsg) + CALL eval_cable_channel(cables(line_obj_index(line_id)), ch, val, ErrStat, ErrMsg, mesh_node=mesh_node) ELSE IF (.NOT. has_sys) THEN CALL fail(ErrStat, ErrMsg, 'OUTPUT "'//TRIM(ch)//'": line maps to the EI=0 system but no system '// & @@ -32215,22 +32286,28 @@ SUBROUTINE sys_solvefail(ch, em, ErrStat, ErrMsg) ErrMsg = 'CableDyn_DeckDriver: OUTPUT "'//TRIM(ch)//'": '//TRIM(em) END SUBROUTINE sys_solvefail - SUBROUTINE eval_cable_channel(cable, ch, val, ErrStat, ErrMsg) + SUBROUTINE eval_cable_channel(cable, ch, val, ErrStat, ErrMsg, mesh_node) !! Evaluate one channel for a finite-EI Hermite power cable (CD_HFMF). Mirrors the driver's !! finite_model_channel_value but reads the cable's committed state directly from the CD_HFMF !! line (stride-6 DOFs: r at 6*(n-1)+1..3, tangent m at +4..6) and recovers the !! complete elastic plus Kelvin-Voigt axial resultant. Node ordering runs anchor (node 1, held) !! -> fairlead (node nn, the coupled endpoint), so deck End A = internal node nn. Bend moment is !! EI(node) * |kvec_current - kvec_reference|; the built cable's reference is straight - !! (kvec_reference = 0), so it reduces to EI * geometric curvature magnitude. + !! (kvec_reference = 0), so it reduces to EI * geometric curvature magnitude. A node channel + !! names a deck node (1 + the total NumSegs of the line's sections, End A first), read at its + !! node of the final mesh on a refined line (cable%deck_node); mesh_node = .TRUE. reads the + !! token's node as a node of the final mesh instead (the static profile and the C API line + !! arrays list every mesh node). TYPE(CD_HFMF_ModuleType), INTENT(INOUT) :: cable CHARACTER(*), INTENT(IN) :: ch REAL(wp), INTENT(OUT) :: val INTEGER, INTENT(OUT) :: ErrStat CHARACTER(*), INTENT(OUT) :: ErrMsg + LOGICAL, INTENT(IN), OPTIONAL :: mesh_node CHARACTER(NAMELEN) :: lo INTEGER :: line_id, node, kind, comp, nnode, nelem, inode, es + LOGICAL :: deck_numbering REAL(wp) :: sec_ten, sec_curv, sec_bend CHARACTER(200) :: em @@ -32272,6 +32349,19 @@ SUBROUTINE eval_cable_channel(cable, ch, val, ErrStat, ErrMsg) RETURN END IF CALL parse_line_node_channel(ch, line_id, node, kind, comp) + deck_numbering = ALLOCATED(cable%deck_node) + IF (PRESENT(mesh_node)) deck_numbering = deck_numbering .AND. .NOT. mesh_node + IF (deck_numbering) THEN + ! a refined line: the deck node's node of the final mesh + IF (node < 1 .OR. node > SIZE(cable%deck_node)) THEN + CALL fail(ErrStat, ErrMsg, 'OUTPUT "'//TRIM(ch)//'": node index out of range'); RETURN + END IF + IF (cable%deck_node(node) < 1) THEN + CALL fail_solve(ErrStat, ErrMsg, 'OUTPUT "'//TRIM(ch)//'": deck node '//TRIM(int_to_str(node))// & + ' is not a node of the refined mesh of the line'); RETURN + END IF + node = cable%deck_node(node) + END IF IF (node < 1 .OR. node > nnode) THEN CALL fail(ErrStat, ErrMsg, 'OUTPUT "'//TRIM(ch)//'": node index out of range'); RETURN END IF @@ -32357,6 +32447,24 @@ PURE FUNCTION cable_frame_is_identity(cable) RESULT(is_id) is_id = .NOT. (ABS(cable%frame_s) > CD_ZERO .OR. ABS(cable%frame_c - CD_ONE) > CD_ZERO) END FUNCTION cable_frame_is_identity + PURE INTEGER FUNCTION CD_Cable_Deck_Node(cable, node) RESULT(deck_node) + !! The deck node at public node `node` (End A = 1) of a finite-EI cable's final mesh: the + !! node itself when the mesh is the deck mesh, 0 for a node the refinement added (the + !! DeckNode column of the static profile). + TYPE(CD_HFMF_ModuleType), INTENT(IN) :: cable + INTEGER, INTENT(IN) :: node + INTEGER :: j + deck_node = node + IF (.NOT. ALLOCATED(cable%deck_node)) RETURN + deck_node = 0 + DO j = 1, SIZE(cable%deck_node) + IF (cable%deck_node(j) == node) THEN + deck_node = j + RETURN + END IF + END DO + END FUNCTION CD_Cable_Deck_Node + PURE FUNCTION cable_global_component(cable, v_local, comp) RESULT(val) !! One component of a cable-local vector expressed in the deck's global frame (the !! transpose of the cable's frame rotation about +z). Identity heading reads the diff --git a/src/CableDyn_OpenFAST_Aggregate.f90 b/src/CableDyn_OpenFAST_Aggregate.f90 index 991c352e..73f98480 100644 --- a/src/CableDyn_OpenFAST_Aggregate.f90 +++ b/src/CableDyn_OpenFAST_Aggregate.f90 @@ -56,6 +56,7 @@ MODULE CableDyn_OpenFAST_Aggregate USE CableDyn_HermiteCableDynamic, ONLY: CD_HermiteCable_Dyn_Profile_Enabled USE CableDyn_DeckDriver, ONLY: CD_DeckAggregateType, CD_Init_Deck_Aggregate, CD_End_Deck_Aggregate, & CD_DECKDRV_OK, CD_DECKDRV_BADINPUT, CD_Eval_Aggregate_Channel, & + CD_Cable_Deck_Node, & CD_Channel_Unit, CD_DECK_NAMELEN, CD_LineInitSummary, & DeckFailure, DeckLine, DeckPoint, CD_Fire_Deck_Failures, & CD_Replay_Deck_Failures, CD_Check_System_Plausibility, & @@ -2055,6 +2056,7 @@ SUBROUTINE CD_AGG_WriteStaticProfile(self, path, ErrStat, ErrMsg) CHARACTER(*), INTENT(OUT) :: ErrMsg INTEGER :: unit, ios, line_id, object_index, nnode, node, ndof, es + LOGICAL :: refined REAL(wp) :: s, xyz(3), xyz_prev(3), tension, curvature, bend_moment, declination, azimuth CHARACTER(CD_DECK_NAMELEN) :: ch CHARACTER(512) :: em @@ -2076,11 +2078,21 @@ SUBROUTINE CD_AGG_WriteStaticProfile(self, path, ErrStat, ErrMsg) END IF tab = CHAR(9) + ! A cable whose mesh the static solve refined lists every node of its final mesh; the DeckNode + ! column then names the deck node of each row (0: a node the refinement added). + refined = .FALSE. + IF (ALLOCATED(self%cables)) THEN + DO object_index = 1, SIZE(self%cables) + refined = refined .OR. ALLOCATED(self%cables(object_index)%deck_node) + END DO + END IF WRITE (unit, '(A)') 'CableDyn coupled static configuration (deformed arc; public node order End A -> End B)' WRITE (unit, '(A)') 'LineID'//tab//'Node'//tab//'ArcLength'//tab//'X'//tab//'Y'//tab//'Z'//tab// & - 'Tension'//tab//'Curvature'//tab//'BendMoment'//tab//'Declination'//tab//'Inclination'//tab//'Azimuth' + 'Tension'//tab//'Curvature'//tab//'BendMoment'//tab//'Declination'//tab//'Inclination'//tab//'Azimuth'// & + TRIM(MERGE(tab//'DeckNode', REPEAT(' ', 9), refined)) WRITE (unit, '(A)') '(-)'//tab//'(-)'//tab//'(m)'//tab//'(m)'//tab//'(m)'//tab//'(m)'//tab// & - '(N)'//tab//'(1/m)'//tab//'(N.m)'//tab//'(deg)'//tab//'(deg)'//tab//'(deg)' + '(N)'//tab//'(1/m)'//tab//'(N.m)'//tab//'(deg)'//tab//'(deg)'//tab//'(deg)'// & + TRIM(MERGE(tab//'(-)', REPEAT(' ', 4), refined)) DO line_id = 1, SIZE(self%line_obj_index) object_index = self%line_obj_index(line_id) @@ -2120,9 +2132,15 @@ SUBROUTINE CD_AGG_WriteStaticProfile(self, path, ErrStat, ErrMsg) CALL eval_node('Dec', declination); IF (ErrStat /= CD_AGG_OK) RETURN CALL eval_node('Azi', azimuth); IF (ErrStat /= CD_AGG_OK) RETURN IF (node > 1) s = s + NORM2(xyz - xyz_prev) - WRITE (unit, '(I0,A,I0,10(A,ES15.7E3))') line_id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & - tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & - tab, declination - 90.0_wp, tab, azimuth + IF (refined) THEN + WRITE (unit, '(I0,A,I0,10(A,ES15.7E3),A,I0)') line_id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & + tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & + tab, declination - 90.0_wp, tab, azimuth, tab, profile_deck_node() + ELSE + WRITE (unit, '(I0,A,I0,10(A,ES15.7E3))') line_id, tab, node, tab, s, tab, xyz(1), tab, xyz(2), & + tab, xyz(3), tab, tension, tab, curvature, tab, bend_moment, tab, declination, & + tab, declination - 90.0_wp, tab, azimuth + END IF xyz_prev = xyz END DO END DO @@ -2138,11 +2156,18 @@ SUBROUTINE eval_node(kind, value) ELSE WRITE (ch, '(A,I0,A,I0)') TRIM(kind), line_id, 'N', node END IF + ! every node of the line's final mesh, also on a refined cable CALL CD_Eval_Aggregate_Channel(TRIM(ch), self%has_sys, self%sys%fast%system, self%cables, & - self%line_is_cable, self%line_obj_index, value, es, em) + self%line_is_cable, self%line_obj_index, value, es, em, mesh_node=.TRUE.) IF (es /= CD_DECKDRV_OK) CALL profile_fail('channel '//TRIM(ch)//' failed: '//TRIM(em)) END SUBROUTINE eval_node + INTEGER FUNCTION profile_deck_node() RESULT(deck_node) + !! The deck node of the current row (an EI = 0 line is meshed as the deck). + deck_node = node + IF (self%line_is_cable(line_id)) deck_node = CD_Cable_Deck_Node(self%cables(object_index), node) + END FUNCTION profile_deck_node + SUBROUTINE profile_fail(message) CHARACTER(*), INTENT(IN) :: message ErrStat = CD_AGG_BADINPUT diff --git a/src/CableDyn_OpenFAST_HermiteFMF.f90 b/src/CableDyn_OpenFAST_HermiteFMF.f90 index a9dbec8e..66f14b96 100644 --- a/src/CableDyn_OpenFAST_HermiteFMF.f90 +++ b/src/CableDyn_OpenFAST_HermiteFMF.f90 @@ -133,6 +133,11 @@ MODULE CableDyn_OpenFAST_HermiteFMF LOGICAL :: tors_parent = .FALSE. INTEGER :: tors_index = 0 REAL(wp) :: tors_frame_parent(3, 2) = CD_ZERO + ! Deck node -> model node map of a line whose mesh the static solve refined: deck_node(J) is + ! the public node (End A = 1) of the final mesh at the reference arc of deck node J (1 + the + ! total NumSegs of the deck sections, End A first), 0 if no mesh node lies there. Unallocated + ! when the mesh is the deck mesh. The node output channels (TenN, ...) read deck nodes. + INTEGER, ALLOCATABLE :: deck_node(:) LOGICAL :: initialized = .FALSE. END TYPE CD_HFMF_ModuleType @@ -1723,6 +1728,7 @@ SUBROUTINE CD_HFMF_End(self) self%tors_parent = .FALSE. self%tors_index = 0 self%tors_frame_parent = CD_ZERO + IF (ALLOCATED(self%deck_node)) DEALLOCATE (self%deck_node) self%initialized = .FALSE. END SUBROUTINE CD_HFMF_End diff --git a/tests/test_anchor_uplift.py b/tests/test_anchor_uplift.py index b6be0c29..66fd076b 100644 --- a/tests/test_anchor_uplift.py +++ b/tests/test_anchor_uplift.py @@ -141,16 +141,18 @@ def check_anchor_point(label: str, root: Path, line_id: int, point_id: int) -> N def line_lengths(path: Path) -> np.ndarray: """Deformed chord length of a line at every row of a dynamic .Line.p.out file.""" - lines = path.read_text(encoding="utf-8").splitlines() - data = np.array([[float(v) for v in row.split()] for row in lines[2:] if row.strip()]) + # skip the comment lines (a refined line adds "# DeckNode") and the header row + lines = [row for row in path.read_text(encoding="utf-8").splitlines() if not row.startswith("#")] + data = np.array([[float(v) for v in row.split()] for row in lines[1:] if row.strip()]) xyz = data[:, 1:].reshape(data.shape[0], -1, 3) return np.linalg.norm(np.diff(xyz, axis=1), axis=2).sum(axis=1) def static_line_length(path: Path) -> float: """Deformed chord length of a line from a static .Line.p.out table (Node X Y Z).""" - lines = path.read_text(encoding="utf-8").splitlines() - data = np.array([[float(v) for v in row.split()] for row in lines[2:] if row.strip()]) + # skip the comment lines (a refined line adds "# DeckNode") and the header row + lines = [row for row in path.read_text(encoding="utf-8").splitlines() if not row.startswith("#")] + data = np.array([[float(v) for v in row.split()] for row in lines[1:] if row.strip()]) return float(np.linalg.norm(np.diff(data[:, 1:4], axis=0), axis=1).sum()) diff --git a/tests/test_c_api_shared.c b/tests/test_c_api_shared.c index ecd17d8a..1142f223 100644 --- a/tests/test_c_api_shared.c +++ b/tests/test_c_api_shared.c @@ -169,6 +169,9 @@ static int check_deck_step(const char *deck) CHECK(err == CD_C_BAD_INPUT, "mis-sized line buffer accepted"); CableDyn_GetLineValues(m, 0, CD_C_LINE_SEGMENT_TENSION, seg, nn - 1, &err); CHECK(err == CD_C_OK && seg[0] > 0.0, "segment tensions"); + /* an EI = 0 line is meshed as the deck: mesh node k is deck node k */ + CableDyn_GetLineValues(m, 0, CD_C_LINE_DECK_NODE, xyz, nn, &err); + CHECK(err == CD_C_OK && xyz[0] == 1.0 && xyz[nn - 1] == (double)nn, "deck nodes of a line"); CableDyn_GetLineValues(m, 0, CD_C_LINE_TENSION, xyz, nn, &err); ten0 = xyz[0]; CableDyn_EvalChannel(m, token, (int)strlen(token), &fair, &err); diff --git a/tests/test_node_channels_refined.py b/tests/test_node_channels_refined.py new file mode 100644 index 00000000..c9b44ea4 --- /dev/null +++ b/tests/test_node_channels_refined.py @@ -0,0 +1,358 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: Apache-2.0 +# Copyright (c) 2026 Jae Hoon Seo, SMI Lab, Inha University +"""Node output channels name deck nodes on a finite-EI line whose mesh the static solve refined. + +The deck is ``tests/data/lazy_wave_touchdown_planar_coarse.dat`` with its top bare section cut +from 20 to 4 elements: the deck mesh (71 elements, 72 deck nodes) cannot resolve the curvature +of the equilibrium and the static solve refines it. ``TenN``, ``CurvN``, +``BendMomN`` and ``LN{px,py,pz,vx,..,Dec,Azi}`` must report deck node ``J`` (1 + +the total ``NumSegs`` of the sections, End A first), at its node of the refined mesh. Gates: + +* static, cubic-Hermite route: the refined profile ``.static.out`` lists every mesh node and + its ``DeckNode`` column names the deck nodes in order, each at the deck node's reference arc + (``.elements.out`` ``ReferenceArcStart``); every node channel equals the profile row of its + deck node, and that row is not row ``J`` (hang-off + 1, sag bend, mid-arch, touchdown, + three-quarter, End B); +* dynamic, cubic-Hermite route: at every output time ``LNp{x,y,z}`` equals the + ``.Line.p.out`` position of the deck node's mesh node, and the end nodes report the + ``FairTen``/``AnchTen`` end forces; +* mixed ``EI = 0`` + finite-EI route (the OpenFAST aggregate's channel evaluator and static + profile): the node channels of the cable at ``t = 0`` equal its profile rows of the deck + nodes, and the ``EI = 0`` line, never refined, numbers its rows as the deck; +* C API: ``CableDyn_EvalChannel`` reads deck nodes and ``CableDyn_GetLineValues`` every mesh + node of the same state; a node past the deck count is rejected; +* Python: ``StaticProfile.deck_node_arc_lengths``, ``node_range_graph`` and ``profile_at`` + place the deck-node channels at their deck node's arc length. + +usage: test_node_channels_refined.py --exe --deck --output

+ [--library ] +""" + +from __future__ import annotations + +import argparse +import os +import re +import shutil +import subprocess +import sys +from pathlib import Path + +import numpy as np + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "python")) +from cabledyn import line_positions, node_range_graph, profile_at, read_output # noqa: E402 + +FAILURES: list[str] = [] +LINE = 4 +# (length, NumSegs) of the deck sections after the cut, End A first +SECTIONS = [(80.0, 4), (100.0, 25), (420.0, 42)] +# hang-off + 1, the buoyancy-section start (sag bend), mid-arch, touchdown, three-quarter, End B +NODES = [1, 2, 5, 18, 34, 54, 72] +STATIC_COLUMN = { + "Ten": "Tension", + "Curv": "Curvature", + "BendMom": "BendMoment", + "px": "X", + "py": "Y", + "pz": "Z", + "Dec": "Declination", + "Azi": "Azimuth", +} + + +def check(ok: bool, message: str) -> None: + print(("PASS: " if ok else "FAIL: ") + message) + if not ok: + FAILURES.append(message) + + +def deck_arcs() -> list[float]: + arcs = [0.0] + for length, nsegs in SECTIONS: + for _ in range(nsegs): + arcs.append(arcs[-1] + length / nsegs) + return arcs + + +def channel_names(dynamic: bool) -> list[str]: + names = [f"FairTen{LINE}", f"AnchTen{LINE}"] + kinematic = ["px", "py", "pz", "Dec", "Azi"] + (["vx", "vz", "ax", "az"] if dynamic else []) + for j in NODES: + names += [f"Ten{LINE}N{j}", f"Curv{LINE}N{j}", f"BendMom{LINE}N{j}"] + names += [f"L{LINE}N{j}{k}" for k in kinematic] + return names + + +def write_deck(source: Path, path: Path, *, outputs: str, tmax: float, mixed: bool = False) -> None: + text = source.read_text() + replaced = { + f"{LINE} bare 80.0 20": f"{LINE} bare 80.0 4", + f"{LINE} 7 8 -": f"{LINE} 7 8 {outputs}", + "0.0 TMax": f"{tmax} TMax", + f"FairTen{LINE}\n": "\n".join(channel_names(tmax > 0.0)) + "\n", + } + for old, new in replaced.items(): + if text.count(old) != 1: + raise SystemExit(f"{source.name}: expected one {old!r}") + text = text.replace(old, new) + if mixed: + # an EI = 0 chain from a second coupled point: the mixed EI = 0 + finite-EI route + extra = { + "buoy 0.29 59.53": "chain 0.10 150.0 8.0e8 0.0 0.0 0 0 0 0 1.2 0.4 1.0 0.5\nbuoy 0.29 59.53", + "8 Fixed 500.0 0.0 -200.0": "8 Fixed 500.0 0.0 -200.0\n9 Coupled -30.0 0.0 -20.0\n" + "10 Fixed -480.0 0.0 -200.0", + f"{LINE} 7 8 {outputs}": f"{LINE} 7 8 {outputs}\n5 9 10 -", + f"{LINE} bare 420.0 42": f"{LINE} bare 420.0 42\n5 chain 520.0 26", + f"FairTen{LINE}\n": f"FairTen{LINE}\nFairTen5\nTen5N2\nL5N14pz\n", + } + for old, new in extra.items(): + line = text.split(old, 1) + if len(line) != 2: + raise SystemExit(f"{source.name}: expected {old!r}") + text = new.join(line) + path.write_text(text) + + +def run(exe: Path, deck: Path, root: Path) -> None: + proc = subprocess.run( + [str(exe), deck.name, root.name], + cwd=deck.parent, + capture_output=True, + text=True, + timeout=600, + env={**os.environ, "OMP_NUM_THREADS": "1"}, + ) + if proc.returncode != 0: + print(proc.stdout[-4000:]) + print(proc.stderr[-4000:]) + raise SystemExit(f"{deck.name}: driver exit {proc.returncode}") + + +def mesh_rows(profile, line_id: int) -> dict[int, int]: + """Deck node -> 0-based row of the line in the static profile (its DeckNode column).""" + line = profile.line(line_id) + deck = line.column("DeckNode") + return {int(j): int(i) for i, j in enumerate(deck) if j > 0} + + +def reference_arcs(elements: Path, line_id: int) -> np.ndarray: + table = read_output(elements) + mask = table.column("LineID") == line_id + start = table.column("ReferenceArcStart")[mask] + end = table.column("ReferenceArcEnd")[mask] + return np.concatenate((start, end[-1:])) + + +def node_channel(name: str) -> tuple[int, str] | None: + match = re.fullmatch(rf"(Ten|Curv|BendMom){LINE}N(\d+)", name) + if match: + return int(match.group(2)), match.group(1) + match = re.fullmatch(rf"L{LINE}N(\d+)(\w+)", name) + if match: + return int(match.group(1)), match.group(2) + return None + + +def static_gates(exe: Path, source: Path, out: Path) -> dict[int, int]: + deck = out / "static.dat" + write_deck(source, deck, outputs="pt", tmax=0.0) + run(exe, deck, out / "static") + profile = read_output(out / "static.static.out") + line = profile.line(LINE) + nrows = line.values.shape[0] + check("DeckNode" in profile.channels, "a refined line's static profile carries the DeckNode column") + check(nrows > 72, f"the deck mesh is refined ({nrows - 1} elements from 71)") + rows = mesh_rows(profile, LINE) + check(sorted(rows) == list(range(1, 73)), "DeckNode names deck nodes 1 .. 72, End A first") + arcs = deck_arcs() + sref = reference_arcs(out / "static.elements.out", LINE) + check(sref.size == nrows, "the element table and the profile list the same mesh") + offset = max(abs(sref[rows[j]] - arcs[j - 1]) for j in rows) + check(offset < 1.0e-6, f"each DeckNode row lies at its deck node's reference arc (max {offset:.1e} m)") + check(all(rows[j] != j - 1 for j in NODES if j > 1), "the deck nodes are not the profile rows J") + check(rows[72] == nrows - 1, "End B is the last mesh node") + history = read_output(out / "static.out") + worst = 0.0 + for name in history.channels[1:]: + parsed = node_channel(name) + if parsed is None: + continue + j, kind = parsed + value = float(history.column(name)[0]) + expected = float(line.column(STATIC_COLUMN[kind])[rows[j]]) + worst = max(worst, abs(value - expected) / max(1.0, abs(expected))) + check(worst == 0.0, f"every static node channel is its deck node's profile row (max rel {worst:.1e})") + touchdown = float(history.column(f"Ten{LINE}N34")[0]) + print(f" Ten{LINE}N34 = {touchdown:.1f} N at mesh node {rows[34] + 1} (s = {arcs[33]:.0f} m)") + check( + float(history.column(f"Ten{LINE}N1")[0]) == float(history.column(f"FairTen{LINE}")[0]) + and float(history.column(f"Ten{LINE}N72")[0]) == float(history.column(f"AnchTen{LINE}")[0]), + "the end deck nodes report the FairTen/AnchTen end forces", + ) + # Python: deck-node channels placed at their deck node's static arc length + lookup = profile.deck_node_arc_lengths(LINE) + arc_column = line.column("ArcLength") + check( + all(lookup[j] == float(arc_column[rows[j]]) for j in rows) and len(lookup) == 72, + "StaticProfile.deck_node_arc_lengths gives each deck node's row", + ) + graph = node_range_graph(history, LINE, "tension", arc_length=profile) + expected = np.asarray([arc_column[rows[j]] for j in NODES]) + check(np.array_equal(graph.location, expected), "node_range_graph places deck nodes at their arc") + return rows + + +def dynamic_gates(exe: Path, source: Path, out: Path, rows: dict[int, int]) -> None: + deck = out / "dynamic.dat" + write_deck(source, deck, outputs="p", tmax=0.1) + run(exe, deck, out / "dynamic") + history = read_output(out / "dynamic.out") + positions = read_output(out / f"dynamic.Line{LINE}.p.out") + check(history.time.size == 5 and positions.time.size == 5, "the march writes t = 0 .. 0.1 s") + worst = 0.0 + for j in NODES: + for axis in "xyz": + value = history.column(f"L{LINE}N{j}p{axis}") + mesh = positions.column(f"Node{rows[j] + 1}{axis.upper()}(m)") + worst = max(worst, float(np.max(np.abs(value - mesh)))) + check(worst == 0.0, f"LNp equals the .p.out position of the deck node's mesh node ({worst:.1e} m)") + check( + np.array_equal(history.column(f"Ten{LINE}N1"), history.column(f"FairTen{LINE}")) + and np.array_equal(history.column(f"Ten{LINE}N72"), history.column(f"AnchTen{LINE}")), + "the end deck nodes report the end forces at every output time", + ) + static = read_output(out / "dynamic.static.out").line(LINE) + first = max( + abs(float(history.column(f"Ten{LINE}N{j}")[0]) - float(static.column("Tension")[rows[j]])) + for j in NODES + ) + check(first == 0.0, "the t = 0 node tensions are the static profile rows of the deck nodes") + # Python: a per-line position file places deck-node channels through the profile beside it + placed = profile_at(history, "tension", 0.1, line_id=LINE, positions=positions) + xyz = np.stack([positions.column(f"Node{k}{a}(m)")[-1] for k in range(1, rows[72] + 2) for a in "XYZ"]) + xyz = xyz.reshape(-1, 3) + chord = np.concatenate(([0.0], np.cumsum(np.linalg.norm(np.diff(xyz, axis=0), axis=1)))) + expected = np.asarray([chord[rows[j]] for j in NODES]) + check( + np.allclose(placed.location, expected, rtol=0.0, atol=1.0e-9), + "profile_at places deck-node channels with a per-line position file at their mesh nodes", + ) + # the per-line file names its deck nodes itself, so it places them without the profile + deck = positions.deck_nodes + check( + deck is not None + and deck.size == rows[72] + 1 + and all(int(deck[rows[j]]) == j for j in rows) + and int(np.count_nonzero(deck)) == 72, + "the .p.out DeckNode line names the deck node of every mesh node", + ) + alone = out / "alone" + alone.mkdir() + shutil.copy(out / f"dynamic.Line{LINE}.p.out", alone / f"dynamic.Line{LINE}.p.out") + lone = read_output(alone / f"dynamic.Line{LINE}.p.out") + by_file = profile_at(history, "tension", 0.1, line_id=LINE, positions=lone) + by_positions = profile_at(history, "tension", 0.1, line_id=LINE, positions=line_positions(lone)) + check( + np.allclose(by_file.location, expected, rtol=0.0, atol=1.0e-9) + and np.allclose(by_positions.location, expected, rtol=0.0, atol=1.0e-9), + "a per-line position file (or LinePositions read from it) places deck nodes on its own", + ) + + +def mixed_gates(exe: Path, source: Path, out: Path, rows: dict[int, int]) -> None: + deck = out / "mixed.dat" + write_deck(source, deck, outputs="-", tmax=0.05, mixed=True) + run(exe, deck, out / "mixed") + history = read_output(out / "mixed.out") + check(history.title.startswith("# CableDyn driver output (mixed aggregate"), "the deck runs on the mixed route") + profile = read_output(out / "mixed.static.out") + check("DeckNode" in profile.channels, "the mixed static profile carries the DeckNode column") + mixed_rows = mesh_rows(profile, LINE) + check(mixed_rows == rows, "the mixed route refines the cable to the same mesh") + chain = profile.line(5) + check( + np.array_equal(chain.column("DeckNode"), chain.column("Node")) and chain.values.shape[0] == 27, + "the EI = 0 line is not refined and numbers its rows as the deck", + ) + line = profile.line(LINE) + worst = 0.0 + for name in history.channels[1:]: + parsed = node_channel(name) + if parsed is None or parsed[1] not in STATIC_COLUMN: + continue + j, kind = parsed + expected = float(line.column(STATIC_COLUMN[kind])[rows[j]]) + worst = max(worst, abs(float(history.column(name)[0]) - expected) / max(1.0, abs(expected))) + check(worst == 0.0, f"mixed-route node channels at t = 0 are the deck nodes' profile rows ({worst:.1e})") + check( + float(history.column("Ten5N2")[0]) == float(chain.column("Tension")[1]) + and float(history.column("L5N14pz")[0]) == float(chain.column("Z")[13]), + "the EI = 0 line's node channels read its deck nodes", + ) + + +def capi_gates(library: Path, source: Path, out: Path, rows: dict[int, int]) -> None: + os.environ["CABLEDYN_LIBRARY"] = str(library) + from cabledyn import CableDyn, CableDynError + + deck = out / "capi.dat" + write_deck(source, deck, outputs="-", tmax=0.0) + with CableDyn(deck) as model: + line = model.line(LINE) + check(line.n_nodes == rows[72] + 1, "GetObjectInfo reports the refined mesh's node count") + tension = line.values("tension") + position = line.values("position") + same = all( + model.channel(f"Ten{LINE}N{j}") == float(tension[rows[j]]) + and model.channel(f"L{LINE}N{j}pz") == float(position[rows[j], 2]) + for j in NODES + ) + check(same, "EvalChannel reads the deck node, GetLineValues the mesh nodes of the same state") + try: + model.channel(f"Ten{LINE}N73") + rejected = False + except CableDynError: + rejected = True + check(rejected, "a node past the deck node count is rejected") + deck = line.deck_nodes + check( + deck.size == line.n_nodes + and all(int(deck[rows[j]]) == j for j in rows) + and int(np.count_nonzero(deck)) == 72, + "Line.deck_nodes (CD_C_LINE_DECK_NODE) locates the deck nodes among the mesh nodes", + ) + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--exe", required=True, type=Path) + parser.add_argument("--deck", required=True, type=Path) + parser.add_argument("--output", required=True, type=Path) + parser.add_argument("--library", type=Path) + args = parser.parse_args() + out = args.output.resolve() + if out.exists(): + shutil.rmtree(out) + out.mkdir(parents=True) + exe = args.exe.resolve() + source = args.deck.resolve() + rows = static_gates(exe, source, out) + dynamic_gates(exe, source, out, rows) + mixed_gates(exe, source, out, rows) + if args.library is None: + print("SKIP: C API gates (no --library)") + elif args.library.is_file(): + capi_gates(args.library.resolve(), source, out, rows) + else: + check(False, f"--library {args.library} is not a file") + if FAILURES: + print(f"{len(FAILURES)} gate(s) failed") + return 1 + print("all gates passed") + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tests/test_seabed_friction_aniso.f90 b/tests/test_seabed_friction_aniso.f90 index 79a9dd94..af966384 100644 --- a/tests/test_seabed_friction_aniso.f90 +++ b/tests/test_seabed_friction_aniso.f90 @@ -446,7 +446,7 @@ SUBROUTINE write_touchdown_deck(path, fric_rows, current, motion, long_run) END IF WRITE (u, '(A)') '--- OUTPUTS ---' IF (long) THEN - WRITE (u, '(A)') 'FairTen1 AnchTen1 L1N5px L1N5py L1N5pz L1N30px L1N30py L1N30pz L1N34py L1N38py L1N42py' + WRITE (u, '(A)') 'FairTen1 AnchTen1 L1N5px L1N5py L1N5pz L1N30px L1N30py L1N30pz L1N17py L1N20py L1N21py' ELSE WRITE (u, '(A)') 'FairTen1 AnchTen1 L1N5px L1N5py L1N5pz' END IF @@ -523,8 +523,8 @@ SUBROUTINE case_hermite_pull() CALL read_out('franiso_pull_highlat.out', db, nb) CALL require(na == nb .AND. na > 10, 'hermite-pull:rows') IF (na /= nb .OR. na <= 10) RETURN - ! grounded nodes 38 and 42 (of 45, node 0 at the fairlead) - WRITE (*, '(A,4ES14.6)') 'hermite sideways pull: grounded-node sway N38, N42 at low / high lateral mu (m): ', & + ! grounded deck nodes 20 and 21 (of 46, node 1 at the fairlead), 38 and 40 m along the line + WRITE (*, '(A,4ES14.6)') 'hermite sideways pull: grounded-node sway N20, N21 at low / high lateral mu (m): ', & da(11, na), da(12, na), db(11, nb), db(12, nb) CALL require(da(11, na) > 1.1_wp*db(11, nb) .AND. da(12, na) > 1.1_wp*db(12, nb) .AND. db(12, nb) > 0.0_wp, & 'hermite-pull:low-lateral-friction-lets-the-grounded-run-sway-more') diff --git a/validation/PAPER_REPRODUCTION.md b/validation/PAPER_REPRODUCTION.md index 77b36cc4..26c3f148 100644 --- a/validation/PAPER_REPRODUCTION.md +++ b/validation/PAPER_REPRODUCTION.md @@ -6,26 +6,29 @@ This record is for readers of the CableDyn journal article (Seo et al., *Ocean E 368 (Part 2), 128332, 2026) who want to know whether the current release reproduces its numbers. The article records the formulation as published. CableDyn keeps developing, and its defaults follow the most accurate and robust methods available. The article's methods stay selectable. The table -lists every quantitative result in the article that CableDyn computes, re-run with the v0.1.0 -release in two modes. +lists every quantitative result in the article that CableDyn computes, re-run in two modes, first +with the v0.1.0 release and again with the development source at revision 71158d5; the table +gives the 71158d5 values. | Mode | Settings | | --- | --- | -| Paper mode | `False alpha_force_blend`: forces evaluated at the generalised-α blended configuration, as in the article. `sequenced cable_statics`: the mesh-sequenced static route runs first. End tensions are the end element's axial tension. | +| Paper mode | `False alpha_force_blend`: forces evaluated at the generalised-α blended configuration, as in the article. `sequenced cable_statics`: the mesh-sequenced static route runs first. `element OutputRecovery`: node tensions are element-mean axial forces and curvatures the geometric Hermite curvature, as in the article. End tensions are the end element's axial tension. | | Defaults | Force-blended generalised-α (`True alpha_force_blend`). Static route starts from a catenary with continuation of the bending stiffness (`continuation cable_statics`). `FairTen`/`AnchTen` report the end force: the end element's force including axial damping, plus the end node's share of weight, seabed contact and drag at the actual velocity, without the end node's inertia. | -The two options apply to finite-EI cables only. Tension-only (EI = 0) lines use the same -solver in both modes, so for moorings the two columns differ only in the reported end -tension. Reference values from OrcaFlex, MoorDyn and closed-form solutions are the fixed values -used in the article; they were not re-run. The source revision recorded in the article's -provenance files, built with the same toolchain, regenerates the article's data files exactly, -so any difference in the paper-mode column comes from a change in CableDyn itself. +`alpha_force_blend` also selects the generalised-α scheme of tension-only (EI = 0) lines, so +moorings differ between the modes as well; `False alpha_force_blend` gives the article's EI = 0 +scheme. In paper mode every EI = 0 and finite-EI result at 71158d5 equals the v0.1.0 one in every +printed digit, except the two-point axial rule row. Reference values from OrcaFlex, MoorDyn and +closed-form solutions are the fixed values used in the article; they were not re-run. The +source revision recorded in the article's provenance files, built with the same toolchain, +regenerates the article's data files exactly, so any difference in the paper-mode column comes +from a change in CableDyn itself. **Outcome.** Of the 58 results, paper mode reproduces 53 within the article's printed precision. Three differ because of later robustness fixes, one of them only in the last printed digit. Two cannot be reproduced from the recorded inputs, even with the article's own source: the 800 m pretension and the count of -subdivided mooring motions. With the defaults, 16 results change because of a changed +subdivided mooring motions. With the defaults, 20 results change because of a changed default. One robustness result is worse with the defaults; see [Known difference](#known-difference). For moorings, the defaults column also shows the end-force channel where the article reported the end element's tension. For the dynamic @@ -37,7 +40,7 @@ Status codes in the notes: **R** reproduced; **D** changed by an intentional def mode reproduces); **F** changed by a robustness fix; **X** not reproducible from the recorded inputs; **W** worse agreement or robustness with the defaults. -| Quantity | Paper | Release, paper mode | Release, defaults | Reference | Note | +| Quantity | Paper | 71158d5, paper mode | 71158d5, defaults | Reference | Note | | --- | --- | --- | --- | --- | --- | | Axial patch force error | 1.10e-13 | 1.10e-13 | 1.10e-13 | closed form | R | | Circular-arc energy convergence order | 4.00 | 4.00 | 4.00 | 4 | R | @@ -55,8 +58,8 @@ inputs; **W** worse agreement or robustness with the defaults. | 200 m pretension; four-way band | 1206.2 kN; 1.1 % | 1206.2 kN; 1.1 % | 1206.2 kN; example-deck `FairTen` 1205.4 kN | design 1205, OrcaFlex 1199.2, MoorDyn-F 1212.0 kN | R | | 800 m pretension; three-solver spread; above design | 1868.8 kN; 0.7 %; ≈ 10 % | 1875.6 kN; 0.3 %; 10.1 % | `FairTen` 1881.5 kN; 0.3 %; 10.4 % | OrcaFlex 1881.5, MoorDyn-F 1875.9, design 1704 kN | X: the article's value came from an earlier, unrecorded mesh; the article's own source gives 1875.6 kN on the published deck; the conclusion is unchanged | | Mooring equilibrium profiles (Fig. 9) | — | identical geometry and element tensions | end node reports the end force | — | R | -| One-hour VolturnUS-S mean / SD / min / max | 1.41 / 0.26 / 1.81 / 1.04 % | 1.41 / 0.26 / 1.81 / 1.04 % | same; end force 0.28 / 0.25 / 0.15 / 0.43 % | OrcaFlex 2439.39 / 206.08 / 2057.86 / 2850.91 kN | R | -| One-hour Fourier amplitude, 90 s / 12 s | 0.83 / 2.10 % | 0.83 / 2.10 % | same; end force 0.27 / 1.13 % | OrcaFlex 228.57 / 178.80 kN | R | +| One-hour VolturnUS-S mean / SD / min / max | 1.41 / 0.26 / 1.81 / 1.04 % | 1.41 / 0.26 / 1.81 / 1.04 % | 1.41 / 0.27 / 1.46 / 1.05 %; end force 0.27 / 0.26 / 0.50 / 0.43 % | OrcaFlex 2439.39 / 206.08 / 2057.86 / 2850.91 kN | D: force-blended EI = 0 step; the mean is unchanged | +| One-hour Fourier amplitude, 90 s / 12 s | 0.83 / 2.10 % | 0.83 / 2.10 % | same; end force 0.27 / 1.14 % | OrcaFlex 228.57 / 178.80 kN | R | | Series-Kelvin cases | 12 recover stiffness; derivatives within 5e-6 | pass | pass | analytical, central differences | R | | Series-Kelvin 0.30 MBL ramp differences | 0.121 / 0.053 / 0.026 / 0.009 / < 0.001 % | same | same | MoorDyn | R | | Syrope residual, 14 cases | 0.70–1.16e-9 N | 0.70–1.16e-9 N | 0.70–1.16e-9 N | independent NumPy implementation | R | @@ -69,7 +72,7 @@ inputs; **W** worse agreement or robustness with the defaults. | 800 m cable solved directly on the final mesh | folded equilibria | mesh sequencing reaches the branch | continuation on the final mesh reaches the same branch | — | D: continuation-first static route | | Equal-order quadrature curvature change | ≤ 0.0020 % | 0.0020 % | 0.0020 % | six-point rule | R | | Three-point axial rule, negative minimum 80 / 800 m | 56.15 / 5.81 kN | 56.15 / 5.81 kN | 56.15 / 5.81 kN | — | R | -| Two-point axial rule | 937 / 820 kN; 800 m fails | 937 / 820 kN; 800 m converges (−280.5 kN) | same | — | F: the continuation route, also the fallback in paper mode, establishes the 800 m equilibrium | +| Two-point axial rule | 937 / 820 kN; 800 m fails | −922.7 / −810.3 kN; 800 m converges (−264.4 kN) | same | — | F: the continuation route, also the fallback in paper mode, establishes the 800 m equilibrium; the values moved with the seabed anchor-end weight-moment fix (v0.1.0: −937 / −820 / −280.5 kN). The large spurious compression under under-integration stands | | Converged dynamic meshes, 80/200/800 m | 240 / 480 / 960 | 240 / 480 / 960 | 480 / 480 / 960 | tensile | D: with the force blend the 240-element 80 m mesh reaches −0.15 kN | | Dynamic continuous axial minima | 0.037 / 0.562 / 1.76 kN | 0.037 / 0.563 / 1.76 kN | 0.94 / 0.54 / 1.24 kN | tensile | F at 200 m (same fix as the 200 m subdivision row); D with the defaults | | Dynamic peak curvature | 0.10254 / 0.08844 / 0.03899 /m | 0.10254 / 0.08844 / 0.03899 /m | 0.10247 / 0.08844 / 0.03899 /m | OrcaFlex 0.10279 / 0.08823 / 0.03881 /m | D (80 m) | @@ -92,11 +95,16 @@ inputs; **W** worse agreement or robustness with the defaults. | Regular-wave chain, mean / swing | 0.30 / 8.41 % | 0.30 / 8.41 % | same; `FairTen` 1.20 / 10.6 % | OrcaFlex effective tension | R | | Irregular-wave cable peak curvature | 0.215 % | 0.215 % | 0.215 % | OrcaFlex | R | | Irregular-wave hang-off tension mean/min/max | 0.192 / 0.186 / 0.108 % | 0.192 / 0.186 / 0.108 % | 0.214 / 0.198 / 0.158 % | OrcaFlex | D | -| Slack-to-taut Δt_CFL; peaks at 0.5–20 ms | 3.155 ms; 10.2248 … 10.5068 MN | same | same | 0.5 ms solution | R | -| Slack-to-taut changes; apparent order; 20 ms | 0.0048–2.7576 %; 2.69; 6.34 Δt_CFL | same | same | 0.5 ms solution | R | +| Slack-to-taut Δt_CFL; peaks at 0.5–20 ms | 3.155 ms; 10.2248 … 10.5068 MN | same | 3.155 ms; 10.2246 … 10.3821 MN | 0.5 ms solution | D: force-blended EI = 0 step | +| Slack-to-taut changes; apparent order; 20 ms | 0.0048–2.7576 %; 2.69; 6.34 Δt_CFL | same | 0.0010–1.5410 %; not defined; 6.34 Δt_CFL | 0.5 ms solution | D: see below the table | | 800 m curvature at 50 ms | 0.03899 /m | 0.03899 /m | 0.03899 /m | OrcaFlex 0.03881 /m | R | | Cable motion envelope at 0.05 s, 30 gated cases | all complete | 30 of 30 complete | 28 of 30 with plain steps; 30 of 30 with subdivision | — | W: see [Known difference](#known-difference) | -| Mooring motion envelope at 0.1 s | subdivision only for the two most severe semitaut motions | subdivision for three semitaut motions (6 m/12 s, 10 m/14 s, 5 m/7 s) | same | — | X: the article's source gives the same three; all-chain needs none | +| Mooring motion envelope at 0.1 s | subdivision only for the two most severe semitaut motions | subdivision for three semitaut motions (6 m/12 s, 10 m/14 s, 5 m/7 s) | a different set; severe-motion peaks changed | — | X: the article's source gives the same three; all-chain needs none. D with the defaults: see [Known difference](#known-difference) | + +With the default force blend the slack-to-taut peaks lie within 1.55 % of the 0.5 ms solution at +every step from 0.5 to 20 ms (within 0.05 % up to 5 ms), without a monotone trend; both blends +converge to the same 0.25 ms peak (10.2246 MN); the article's convergence order (2.69) refers to +the configuration blend (paper mode). The table covers every result the article prints from a CableDyn calculation. Values derived only from reference codes are not listed: the MoorDyn-F native-mesh difference, its refinement @@ -124,6 +132,22 @@ six margin probes complete in both modes. The defaults subdivide 6 intervals in paper mode 4 intervals in 4 cases. The solver is not broken, but under the article's single-step protocol the default scheme has less convergence margin. +**Mooring motion envelope with the default force blend.** With the defaults, a different set of +mooring motions needs step subdivision at the article's 0.1 s envelope step, and the peaks of the +severe motions changed. Against converged 0.5 / 0.25 ms references (configuration blend = paper +mode, force blend = defaults, both at 0.1 s): + +| Case | Reference | Configuration blend | Force blend | +| --- | --- | --- | --- | +| 200 m semitaut surge 10 m/14 s, anchor max | 2950–2975 kN | 8084 kN (+173 %) | 3584 kN (+21 %) | +| 200 m semitaut surge 5 m/7 s, anchor max | 4208–4277 kN | 9042 kN (+113 %) | 5799 kN (+36 %) | +| 80 m all-chain heave 5 m/7 s, fairlead max | 1724–1787 kN | 1723 kN (−2 %) | 1538 kN (−13 %) | +| 80 m all-chain heave 5 m/7 s, anchor max | 1494–1585 kN | 1468 kN (−4 %) | 1246 kN (−19 %) | + +The snap is not resolved at 0.1 s, which the run notes. The force blend removes the spurious +semitaut spikes but underestimates the all-chain heave peaks at that step. Confirm peak tensions +with a smaller `dtM`. + **Hang-off curvature near an unresolved boundary layer.** This is not an article result. At the 800 m hang-off node, where the article reports η_b = 1.63 and omits the bend moment, the maximum dynamic curvature is 1.6e-3 /m with the defaults and 1.3e-4 /m in paper mode. The @@ -185,6 +209,18 @@ dynamic test programs use the default force blend. For paper mode, add `test_l4_lazywave_coupled`, `test_l1_hermite_beam_vibration` and `test_l1_hermite_energy_stability`. +The tension-only (EI = 0) test programs use the default force blend as well. For paper mode, set +`force_blend = .FALSE.` in the `GenAlphaConfig` passed to the EI = 0 step (for example +`dcfg%force_blend = .FALSE.`, or `cfg%force_blend = .FALSE.`) before the march. This applies to +`test_snap_load`, `test_l3_orcaflex_wave_dynamic`, `test_l3_longduration_mooring`, +`test_l2_2_dynamic_parity`, `test_viscoelastic`, `test_syrope`, `test_l1_string` and +`test_l1_energy_stability`. Deck runs (`test_l2_lozon80_mooring`, `test_l2_lozon200_semitaut` +and the driver) take `False alpha_force_blend` from `OPTIONS`. + +**Toolchain.** Built with gfortran, the development source gives the same paper-mode values as +v0.1.0 built with gfortran. One count depends on the toolchain: with gfortran the 800 m paper-mode +run subdivides 0 of 1200 intervals (v0.1.0 as well), where the table records 1 of 1200. + **Deck runs.** The static cable profiles use the example decks, which carry the article's refined meshes (1024, 952 and 1024 elements): @@ -201,9 +237,15 @@ For paper mode, add these rows to `OPTIONS`: ```text sequenced cable_statics False alpha_force_blend +element OutputRecovery ``` -`alpha_force_blend` matters only for dynamic runs. For the quadrature and refinement study, use +`alpha_force_blend` matters only for dynamic runs. The finite-EI node tension, curvature and +bend moment of the deck channels, `.static.out` and the range graphs are recovered from nodal +equilibrium by default; the article reported the element-mean axial force and the geometric +Hermite curvature, which `element OutputRecovery` restores. The test programs of this record +read the geometric curvature (`CD_HermiteCable_Dyn_Curvature_Exact`), so their numbers do not +depend on this option. For the quadrature and refinement study, use the article's starting meshes: | Cable | Segments per section | Multiples run | diff --git a/validation/scripts/orcaflex_discrete_modules_reference.py b/validation/scripts/orcaflex_discrete_modules_reference.py index 78628fc5..b3f03839 100644 --- a/validation/scripts/orcaflex_discrete_modules_reference.py +++ b/validation/scripts/orcaflex_discrete_modules_reference.py @@ -135,16 +135,27 @@ def cabledyn_profile( subprocess.run( [str(exe), "modules.dat", "modules"], cwd=work, check=True, capture_output=True ) + # columns by header name: a refined line adds a DeckNode column + header: list[str] = [] rows = [] for line in (work / "modules.static.out").read_text(encoding="utf-8").splitlines(): + fields = line.split() + if fields[:1] == ["LineID"]: + header = fields + continue try: - values = [float(v) for v in line.split()] + values = [float(v) for v in fields] except ValueError: continue - if len(values) == 12: - rows.append(values) - rows.sort(key=lambda r: r[1]) - return [r[3] for r in rows], [r[5] for r in rows], [r[7] for r in rows], rows[0][6] + if header and len(values) == len(header): + rows.append(dict(zip(header, values, strict=True))) + rows.sort(key=lambda r: r["Node"]) + return ( + [r["X"] for r in rows], + [r["Z"] for r in rows], + [r["Curvature"] for r in rows], + rows[0]["Tension"], + ) def compare(