diff --git a/CHANGELOG.md b/CHANGELOG.md index 412b296..51d7bb9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -31,6 +31,11 @@ All notable changes to CableDyn are recorded in this file. The format follows standalone and coupled. Their work closes a cable's energy balance to 0.04 % in free decays and VIV runs, and on the locked-in line of `examples/viv_taut_cable_inline.dat` their means balance within 0.5 % of the VIV power. +- `cabledyn.viv_response`: the VIV response of a line from its node positions, in the local flow + frame of every node: cross-flow and in-line amplitude along the span, the response + frequencies and `f D/U_n`, modal weights (taut-line sines or given shapes), the complex shape + and its travelling-wave index (Feeny 2008), orbits and the in-line/cross-flow phase + difference, with a CSV export and plots. ## [0.4.2] - 2026-11-09 diff --git a/doc/api_python.rst b/doc/api_python.rst index ec38d94..4ea3393 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -336,6 +336,14 @@ the solver's own curvature, tension, and angle channels, where written, are auth .. autoclass:: cabledyn.TouchdownHistory :members: +.. autofunction:: cabledyn.viv_response + +.. autoclass:: cabledyn.VIVResponse + :members: + +.. autoclass:: cabledyn.ModalAmplitudes + :members: + Deck editing and case generation -------------------------------- diff --git a/doc/python_postprocessing.rst b/doc/python_postprocessing.rst index 862b731..4548a78 100644 --- a/doc/python_postprocessing.rst +++ b/doc/python_postprocessing.rst @@ -7,7 +7,7 @@ The ``cabledyn`` package reads the output of the tools a CableDyn study is usual against, and applies the same typed tables, statistics, fatigue, spectra, plots, and exports to them (:doc:`python`). This page covers the readers, run-to-run comparison, resampling and filtering, extreme-value statistics, line geometry, fatigue damage, range graphs, design checks, -touchdown histories, and parameter grids. All of them need NumPy only; plots need matplotlib. +touchdown histories, VIV responses, and parameter grids. All of them need NumPy only; plots need matplotlib. Reading OpenFAST, MoorDyn, and coupled runs ------------------------------------------- @@ -421,6 +421,62 @@ that node, for the anchor uplift check. tdp.plot("arc_length") tdp.export("results/line1_tdp.csv") +VIV response +------------ + +:func:`cabledyn.viv_response` resolves the motion of a line's nodes about their mean positions +over a window into the local flow frame of each node, from a CableDyn ``.Line.p.out`` file, a +MoorDyn-F line file with node positions, or the ``LNpx``/``py``/``pz`` channels of a main +output. The frame follows the mean shape: the tangent ``t`` from End A towards End B, the in-line +axis along the part of the given flow velocity normal to the tangent, and the cross-flow axis +``t x`` in-line, so that (in-line, cross-flow, ``t``) is right-handed. A node whose tangent lies +along the flow has no frame and reports ``nan``. The :class:`~cabledyn.VIVResponse` holds the +in-line and cross-flow displacement of every node at every sample and gives: + +* ``rms_over_diameter`` and ``amplitude_over_diameter`` (half the peak-to-peak displacement) along + the line, for either direction; +* ``frequencies`` (each node's) and ``frequency`` (the line's), the peak of the Hann-windowed + periodogram refined by a parabola through its neighbours, and ``nondimensional_frequency`` + ``f D/U_n`` with ``U_n`` the flow speed normal to the tangent, the quantity the synchronisation + band ``cF +/- dF`` of :ref:`theory-viv` bounds (its reciprocal is the reduced velocity); +* ``modal_amplitudes``, the least-squares weights at every sample of the shapes + ``sin(n pi s/S)`` of a taut line with fixed ends (``s`` the mean chord length from End A, ``S`` + the line's), or of shapes you give (for example a component of the run's mode shapes, + :doc:`outputs`), with their RMS, the dominant mode and the share of the motion they leave + unexplained. The sines need the whole line, so they take a per-line file; on the nodes a main + output holds, give the shapes; +* ``complex_shape``, the node Fourier coefficients at one frequency, and from it + ``travelling_wave_index``, the ratio of the smaller to the larger singular value of its real and + imaginary parts (the travelling index of the complex orthogonal decomposition of + :ref:`Feeny 2008 `): 0 for a standing wave, 1 for a wave of constant amplitude + travelling over whole wavelengths; +* ``orbit`` (a node's in-line and cross-flow displacement) and ``phase_difference``, the in-line + phase at twice the cross-flow frequency less twice the cross-flow phase, which sets the shape + and direction of a figure-of-eight orbit. + +A node is named by its CableDyn number (1 = End A; ``node_numbers``): the ``J`` of the +``LNp`` channels of a main output, which may hold only some nodes, and ``1 .. N`` for a +per-line file. The CSV export writes the same numbers. + +The frequency measures need uniform sampling. On the in-line VIV example +``viv_taut_cable_inline.dat``, run with the line output flag ``p``, over 60-90 s the mid-span cross-flow amplitude is A/D 0.82 at +0.295 Hz (``f D/U_n`` 0.20), the quarter-span in-line amplitude 0.19 at 0.57 Hz, the cross-flow +response is mode 1 and the in-line mode 2, and the travelling-wave index of the cross-flow motion +is 0.05, a standing wave between the pinned ends. + +.. code-block:: python + + from cabledyn import viv_response + + viv = viv_response(result.read_line_positions(1), flow=(0.0, 0.15, 0.0), diameter=0.1, + start=60.0) + print(viv.frequency("cross_flow"), viv.nondimensional_frequency()[25]) + print(viv.modal_amplitudes("cross_flow").dominant_mode) + print(viv.travelling_wave_index("cross_flow")) + viv.plot_envelope() + viv.plot_orbit(13) + viv.export("results/line1_viv.csv") + Parameter grids --------------- diff --git a/doc/references.rst b/doc/references.rst index a4a4db4..9e68e89 100644 --- a/doc/references.rst +++ b/doc/references.rst @@ -95,6 +95,11 @@ Hydrodynamics and ocean environment simulation of riser VIV in current and irregular waves. *Marine Structures* **60**, 241–260. https://doi.org/10.1016/j.marstruc.2018.04.001 +.. _ref-feeny2008: + +- **Feeny, B. F. (2008).** A complex orthogonal decomposition for wave motion analysis. + *Journal of Sound and Vibration* **310**, 77–90. https://doi.org/10.1016/j.jsv.2007.07.047 + .. _ref-morison1950: - **Morison, J. R., O'Brien, M. P., Johnson, J. W. & Schaaf, S. A. (1950).** The force diff --git a/python/cabledyn/__init__.py b/python/cabledyn/__init__.py index 90ecc52..d238085 100644 --- a/python/cabledyn/__init__.py +++ b/python/cabledyn/__init__.py @@ -149,6 +149,7 @@ ) from cabledyn.sweep import parameter_grid from cabledyn.touchdown import TouchdownHistory, touchdown_history +from cabledyn.viv import ModalAmplitudes, VIVResponse, viv_response if TYPE_CHECKING: from cabledyn._lib import abi_minor as abi_minor @@ -198,6 +199,7 @@ "LinePositions", "LineSegmentHistory", "LineSummary", + "ModalAmplitudes", "ModeShapes", "MoorDynLineHistory", "NaturalModes", @@ -226,6 +228,7 @@ "TimeHistory", "Touchdown", "TouchdownHistory", + "VIVResponse", "WaterSurface", "WeibullFit", "animate", @@ -284,6 +287,7 @@ "tension_check", "touchdown_history", "upcrossing_maxima", + "viv_response", ] __version__ = "0.4.2" diff --git a/python/cabledyn/viv.py b/python/cabledyn/viv.py new file mode 100644 index 0000000..d24d3ce --- /dev/null +++ b/python/cabledyn/viv.py @@ -0,0 +1,598 @@ +# SPDX-License-Identifier: Apache-2.0 +"""Vortex-induced vibration (VIV) response of a line from its node positions. + +:func:`viv_response` resolves the motion of every node of a line about its mean +position into the local flow frame of the node and reports the quantities a VIV +study describes a response by: the cross-flow and in-line amplitude along the +span, the response frequencies and the non-dimensional frequency they give +against the flow, the modal content, how far the response is a travelling wave, +and the in-line/cross-flow orbits. + +The local frame of a node follows the mean shape over the analysed window: the +tangent ``t`` from End A towards End B (central differences of the mean node +positions), the in-line direction ``e_x`` along the part of the flow velocity +normal to the tangent, and the cross-flow direction ``e_y = t x e_x``, so that +``(e_x, e_y, t)`` is right-handed. A node whose tangent is parallel to the flow +has no normal flow and no frame; its values are ``nan``. + +The positions come from a CableDyn per-line position file +(``.Line.p.out``, a :class:`~cabledyn.LineNodeHistory`), a MoorDyn +per-line file with node positions (a :class:`~cabledyn.MoorDynLineHistory`), or +the ``LNpx``/``py``/``pz`` channels of a main output for the nodes the +deck lists. The frequency analysis needs uniform sampling. +""" + +from __future__ import annotations + +import math +import os +from dataclasses import dataclass +from pathlib import Path +from typing import Any + +import numpy as np +import numpy.typing as npt + +from cabledyn._csv import number, write_csv +from cabledyn._optional import pyplot +from cabledyn.formats import MoorDynLineHistory +from cabledyn.ranges import node_position_channels +from cabledyn.results import LineNodeHistory, TimeHistory +from cabledyn.spectra import _sampling +from cabledyn.touchdown import _positions + +__all__ = ["ModalAmplitudes", "VIVResponse", "viv_response"] + +_DIRECTIONS = ("cross_flow", "in_line") + + +def _readonly(values: npt.ArrayLike, dtype: npt.DTypeLike = np.float64) -> npt.NDArray[Any]: + array = np.array(values, dtype=dtype, copy=True) + array.setflags(write=False) + return array + + +def _direction(direction: str) -> str: + if direction not in _DIRECTIONS: + raise ValueError(f"direction must be one of {_DIRECTIONS}, not {direction!r}") + return direction + + +def _peak_frequency(frequency: npt.NDArray[Any], power: npt.NDArray[Any]) -> float: + """Frequency of the largest power above zero, refined by a parabola through its neighbours.""" + if power.size < 3 or not np.any(power[1:] > 0.0): + return math.nan + k = int(np.argmax(power[1:])) + 1 + if 1 <= k < power.size - 1: + left, middle, right = power[k - 1], power[k], power[k + 1] + curvature = left - 2.0 * middle + right + if curvature < 0.0: + shift = 0.5 * (left - right) / curvature + return float(frequency[k] + shift * (frequency[1] - frequency[0])) + return float(frequency[k]) + + +@dataclass(frozen=True) +class ModalAmplitudes: + """The modal content of one direction of a VIV response. + + Attributes + ---------- + direction : str + ``"cross_flow"`` or ``"in_line"``. + mode_numbers : tuple[int, ...] + One-based numbers of the shapes fitted. + coefficients : numpy.ndarray + Read-only ``(n_samples, n_modes)`` least-squares weights of the shapes + in the displacement at every sample, in metres per unit shape. + rms_over_diameter : numpy.ndarray + Read-only ``(n_modes,)`` RMS of each weight over the window, divided by + the diameter. + residual : float + RMS of the displacement the shapes leave unexplained, over the RMS of + the displacement (0 when the shapes reproduce it). + """ + + direction: str + mode_numbers: tuple[int, ...] + coefficients: npt.NDArray[Any] + rms_over_diameter: npt.NDArray[Any] + residual: float + + @property + def dominant_mode(self) -> int: + """Number of the shape with the largest RMS weight.""" + return self.mode_numbers[int(np.argmax(self.rms_over_diameter))] + + +@dataclass(frozen=True) +class VIVResponse: + """The VIV response of one line over an analysis window. + + Created by :func:`viv_response`. Nodes are in End-A-to-End-B order of the + source; node arrays have one entry per node, time arrays one per sample. + + Attributes + ---------- + time : numpy.ndarray + Read-only ``(n_samples,)`` sample times of the window, in seconds. + arc_length : numpy.ndarray + Read-only ``(n_nodes,)`` chord length of the mean shape from End A, m. + mean_position : numpy.ndarray + Read-only ``(n_nodes, 3)`` mean node positions over the window, m. + tangent, in_line_axis, cross_flow_axis : numpy.ndarray + Read-only ``(n_nodes, 3)`` unit vectors of each node's local frame + (``nan`` rows where the flow is along the tangent). + normal_speed : numpy.ndarray + Read-only ``(n_nodes,)`` speed of the flow normal to the mean tangent, + m/s. + in_line, cross_flow : numpy.ndarray + Read-only ``(n_samples, n_nodes)`` displacement about the mean position + along the node's in-line and cross-flow axes, m. + diameter : float + Diameter the amplitudes are divided by, m. + flow : numpy.ndarray + Read-only ``(3,)`` flow velocity the frame is taken against, m/s. + whole_line : bool + Whether the nodes are the whole line, End A to End B (a per-line + file), so that ``arc_length`` spans it; a main output may hold only + some of its nodes. + node_numbers : tuple of int + The CableDyn number of each node (1 = End A): ``1 .. n_nodes`` for a + per-line file (MoorDyn's node ``J`` is ``J + 1``), the ``J`` of the + ``LNp`` channels for a main output. The methods that take a + node take this number. Empty means ``1 .. n_nodes``. + """ + + time: npt.NDArray[Any] + arc_length: npt.NDArray[Any] + mean_position: npt.NDArray[Any] + tangent: npt.NDArray[Any] + in_line_axis: npt.NDArray[Any] + cross_flow_axis: npt.NDArray[Any] + normal_speed: npt.NDArray[Any] + in_line: npt.NDArray[Any] + cross_flow: npt.NDArray[Any] + diameter: float + flow: npt.NDArray[Any] + whole_line: bool = True + node_numbers: tuple[int, ...] = () + + @property + def node_count(self) -> int: + """Number of nodes.""" + return int(self.arc_length.size) + + @property + def sampling_interval(self) -> float: + """Uniform sampling interval of the window, s.""" + return float(self.time[1] - self.time[0]) + + def displacement(self, direction: str) -> npt.NDArray[Any]: + """Return the ``(n_samples, n_nodes)`` displacement of ``"cross_flow"`` or ``"in_line"``.""" + return self.cross_flow if _direction(direction) == "cross_flow" else self.in_line + + def rms_over_diameter(self, direction: str = "cross_flow") -> npt.NDArray[Any]: + """Return the ``(n_nodes,)`` RMS displacement over the diameter. + + For a harmonic response the amplitude is ``sqrt(2)`` times the RMS. + """ + values = self.displacement(direction) + return _readonly(np.sqrt(np.mean(values * values, axis=0)) / self.diameter) + + def amplitude_over_diameter(self, direction: str = "cross_flow") -> npt.NDArray[Any]: + """Return the ``(n_nodes,)`` half peak-to-peak displacement over the diameter.""" + values = self.displacement(direction) + return _readonly(0.5 * (values.max(axis=0) - values.min(axis=0)) / self.diameter) + + def _moving_displacement(self, direction: str) -> npt.NDArray[Any]: + """The displacement of a direction with still nodes set to exactly zero. + + A node whose displacement stays within round-off of its coordinates (a range below + 1e-12 of its distance from the origin plus the diameter) is still: its round-off + offset from the mean, windowed or transformed, would otherwise read as motion at + every frequency, with an arbitrary phase. + """ + values = np.array(self.displacement(direction), dtype=np.float64) + scale = np.linalg.norm(self.mean_position, axis=1) + self.diameter + with np.errstate(invalid="ignore"): + still = (values.max(axis=0) - values.min(axis=0)) <= 1.0e-12 * scale + values[:, still] = 0.0 + return values + + def _power(self, direction: str) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]: + """Frequencies and the ``(n_freq, n_nodes)`` Hann-windowed periodogram of a direction. + + Still nodes (:meth:`_moving_displacement`) have no power. + """ + values = self._moving_displacement(direction) + window = np.hanning(self.time.size) + spectrum = np.fft.rfft(values * window[:, None], axis=0) + frequency = np.fft.rfftfreq(self.time.size, self.sampling_interval) + return frequency, np.abs(spectrum) ** 2 + + def frequencies(self, direction: str = "cross_flow") -> npt.NDArray[Any]: + """Return the ``(n_nodes,)`` dominant response frequency of each node, Hz. + + The peak of the node's Hann-windowed periodogram above zero frequency, + refined by a parabola through the bins beside it; ``nan`` for a node + without a frame or without motion. + """ + frequency, power = self._power(direction) + result = np.full(self.node_count, math.nan) + for node in range(self.node_count): + if np.all(np.isfinite(power[:, node])): + result[node] = _peak_frequency(frequency, power[:, node]) + return _readonly(result) + + def frequency(self, direction: str = "cross_flow") -> float: + """Return the dominant response frequency of the line, Hz. + + The peak of the sum of the nodes' periodograms (``nan`` without motion). + """ + frequency, power = self._power(direction) + finite = np.all(np.isfinite(power), axis=0) + if not np.any(finite): + return math.nan + return _peak_frequency(frequency, power[:, finite].sum(axis=1)) + + def nondimensional_frequency(self, direction: str = "cross_flow") -> npt.NDArray[Any]: + """Return ``f D / U_n`` at every node, with ``f`` the line's dominant frequency. + + For the cross-flow response this is the quantity a synchronisation + model's band ``cF +/- dF`` bounds, and its reciprocal the reduced + velocity ``U_n/(f D)``. + """ + with np.errstate(divide="ignore", invalid="ignore"): + result = self.frequency(direction) * self.diameter / self.normal_speed + return _readonly(np.where(self.normal_speed > 0.0, result, math.nan)) + + def modal_amplitudes( + self, + direction: str = "cross_flow", + *, + n_modes: int = 10, + shapes: npt.ArrayLike | None = None, + ) -> ModalAmplitudes: + """Fit mode shapes to the displacement of a direction at every sample. + + Parameters + ---------- + direction : str + ``"cross_flow"`` or ``"in_line"``. + n_modes : int + Number of the default shapes ``sin(n pi s / S)``, ``n = 1 .. + n_modes``, of arc length ``s`` from End A over the mean chord + length ``S`` (the modes of a taut string with fixed ends). Ignored + when ``shapes`` is given. + shapes : array_like, optional + ``(n_modes, n_nodes)`` scalar shapes of the direction at the nodes + to fit instead, for example a component of the run's mode shapes. + + Returns + ------- + ModalAmplitudes + The weights of the shapes at every sample (least squares over the + nodes with a frame), their RMS over the diameter and the share of + the displacement they leave unexplained. + + Raises + ------ + ValueError + If the shapes are not finite, have the wrong number of nodes, or + fewer nodes with a frame than shapes remain; if the shapes are not + independent at those nodes (a sine that vanishes at every node, or + two that alias each other on a coarse output); or if the default + shapes are asked of a response that does not hold the whole line. + """ + values = self.displacement(direction) + if shapes is None: + if isinstance(n_modes, bool) or int(n_modes) != n_modes or n_modes < 1: + raise ValueError("n_modes must be a positive integer") + if not self.whole_line: + # the sines vanish at the line's ends, which the nodes of a main output may + # not include: fitted over the span of the nodes it holds, they would be wrong + raise ValueError( + "the default shapes need the whole line, End A to End B: analyse the " + "per-line .p.out file, or give shapes at the nodes held" + ) + span = float(self.arc_length[-1]) + if not span > 0.0: + raise ValueError("the mean shape has no length") + numbers = np.arange(1, int(n_modes) + 1) + basis = np.sin(np.pi * numbers[:, None] * self.arc_length[None, :] / span) + else: + basis = np.array(shapes, dtype=np.float64) + if basis.ndim != 2 or basis.shape[1] != self.node_count or basis.shape[0] < 1: + raise ValueError(f"shapes must have shape (n_modes, {self.node_count})") + if not np.all(np.isfinite(basis)): + raise ValueError("shapes must be finite") + numbers = np.arange(1, basis.shape[0] + 1) + framed = np.all(np.isfinite(values), axis=0) + if int(np.count_nonzero(framed)) < basis.shape[0]: + raise ValueError("fewer nodes with a flow frame than shapes to fit") + design = basis[:, framed].T + target = values[:, framed].T + coefficients, _, rank, _ = np.linalg.lstsq(design, target, rcond=None) + if int(rank) < basis.shape[0]: + # dependent shapes at the nodes held (a mode that vanishes at every node, or two + # that alias each other): their weights are not determined by the motion + raise ValueError( + f"the {basis.shape[0]} shapes are not independent at the nodes with a flow frame " + f"(rank {int(rank)}): fit fewer modes, or use a finer output" + ) + left = target - design @ coefficients + total = float(np.sqrt(np.mean(target * target))) + residual = float(np.sqrt(np.mean(left * left))) / total if total > 0.0 else 0.0 + rms = np.sqrt(np.mean(coefficients * coefficients, axis=1)) / self.diameter + return ModalAmplitudes( + direction=_direction(direction), + mode_numbers=tuple(int(n) for n in numbers), + coefficients=_readonly(coefficients.T), + rms_over_diameter=_readonly(rms), + residual=residual, + ) + + def complex_shape( + self, direction: str = "cross_flow", frequency: float | None = None + ) -> npt.NDArray[Any]: + """Return the ``(n_nodes,)`` complex Fourier shape of a direction at one frequency. + + ``c_j = (2/W) sum_k w_k u_j(t_k) exp(-2 pi i f t_k)`` with the Hann + window ``w`` of sum ``W``, so that a node moving as ``a cos(2 pi f t + + phase)`` has ``c_j = a exp(i phase)``; ``frequency`` defaults to the + line's dominant frequency of the direction. A still node has ``c_j = 0``. + """ + f = self.frequency(direction) if frequency is None else float(frequency) + if not (math.isfinite(f) and f >= 0.0): + raise ValueError("the frequency must be finite and non-negative") + window = np.hanning(self.time.size) + phasor = window * np.exp(-2j * np.pi * f * self.time) + shape: npt.NDArray[Any] = np.asarray( + 2.0 * (phasor @ self._moving_displacement(direction)) / window.sum(), + dtype=np.complex128, + ) + shape.setflags(write=False) + return shape + + def travelling_wave_index( + self, direction: str = "cross_flow", frequency: float | None = None + ) -> float: + """Return how far the response of a direction is a travelling wave, from 0 to 1. + + The ratio of the smaller to the larger singular value of the real and + imaginary parts of :meth:`complex_shape` (the travelling index of the + complex orthogonal decomposition, Feeny 2008): 0 for a standing wave, + whose nodes move in or out of phase, and 1 for a wave of constant + amplitude travelling over whole wavelengths. ``nan`` without motion. + """ + if frequency is None and not math.isfinite(self.frequency(direction)): + return math.nan # no motion, or no node with a flow frame + shape = self.complex_shape(direction, frequency) + framed = np.isfinite(shape) + parts = np.vstack((shape[framed].real, shape[framed].imag)) + if parts.shape[1] < 2: + return math.nan + singular = np.linalg.svd(parts, compute_uv=False) + return float(singular[1] / singular[0]) if singular[0] > 0.0 else math.nan + + def orbit(self, node: int) -> tuple[npt.NDArray[Any], npt.NDArray[Any]]: + """Return the in-line and cross-flow displacement of a node over the window. + + ``node`` is the node's number (:attr:`node_numbers`). + """ + index = self._node_index(node) + return self.in_line[:, index], self.cross_flow[:, index] + + def phase_difference(self, node: int, frequency: float | None = None) -> float: + """Return the in-line phase less twice the cross-flow phase at a node, in degrees. + + ``theta = arg(c_x(2 f)) - 2 arg(c_y(f))`` in ``[0, 360)``, with ``c`` + the node's complex Fourier coefficients (:meth:`complex_shape`) and + ``f`` the cross-flow frequency (default: the line's dominant one): the + phase that sets the shape and direction of a figure-of-eight orbit. + ``nan`` for a node without a frame or without motion at those + frequencies. + """ + index = self._node_index(node) + f = self.frequency("cross_flow") if frequency is None else float(frequency) + if not math.isfinite(f): + return math.nan + cy = self.complex_shape("cross_flow", f)[index] + cx = self.complex_shape("in_line", 2.0 * f)[index] + if not (np.isfinite(cx) and np.isfinite(cy)) or abs(cx) == 0.0 or abs(cy) == 0.0: + return math.nan + return float(np.degrees(np.angle(cx) - 2.0 * np.angle(cy)) % 360.0) + + def _numbers(self) -> tuple[int, ...]: + """The node numbers, ``1 .. n_nodes`` when none were recorded.""" + return self.node_numbers or tuple(range(1, self.node_count + 1)) + + def _node_index(self, node: int) -> int: + numbers = self._numbers() + if isinstance(node, bool) or int(node) != node or int(node) not in numbers: + if numbers == tuple(range(1, self.node_count + 1)): + raise ValueError(f"node must be an integer from 1 to {self.node_count}") + raise ValueError(f"node must be one of the nodes held, {list(numbers)}") + return numbers.index(int(node)) + + def export(self, path: str | os.PathLike[str], *, overwrite: bool = False) -> Path: + """Atomically write the node values as a unit-labelled CSV, one row per node. + + Columns: node number (:attr:`node_numbers`), arc length, normal flow speed, + cross-flow and in-line RMS + and half peak-to-peak displacement over the diameter, the nodes' + dominant frequencies and the non-dimensional cross-flow frequency. + Fields of a node without a frame are empty. + + Raises + ------ + FileExistsError + If ``path`` exists and ``overwrite`` is false. + """ + columns = ( + self.arc_length, + self.normal_speed, + self.rms_over_diameter("cross_flow"), + self.rms_over_diameter("in_line"), + self.amplitude_over_diameter("cross_flow"), + self.amplitude_over_diameter("in_line"), + self.frequencies("cross_flow"), + self.frequencies("in_line"), + self.nondimensional_frequency("cross_flow"), + ) + + numbers = self._numbers() + + def row(index: int) -> tuple[str, ...]: + fields = tuple( + number(column[index]) if math.isfinite(float(column[index])) else "" + for column in columns + ) + return (str(numbers[index]), *fields) + + return write_csv( + path, + ( + "Node", + "ArcLength_[m]", + "NormalSpeed_[m/s]", + "CrossFlowRMSOverD_[-]", + "InLineRMSOverD_[-]", + "CrossFlowAmplitudeOverD_[-]", + "InLineAmplitudeOverD_[-]", + "CrossFlowFrequency_[Hz]", + "InLineFrequency_[Hz]", + "CrossFlowNondimensionalFrequency_[-]", + ), + (row(index) for index in range(self.node_count)), + overwrite=overwrite, + ) + + def plot_envelope(self, *, ax: Any = None) -> Any: + """Plot the cross-flow and in-line RMS displacement over the diameter along the line.""" + plt = pyplot() + if ax is None: + _, ax = plt.subplots() + ax.plot(self.arc_length, self.rms_over_diameter("cross_flow"), label="cross-flow") + ax.plot(self.arc_length, self.rms_over_diameter("in_line"), label="in-line") + ax.set_xlabel("Arc length from End A (m)") + ax.set_ylabel("RMS displacement / D (-)") + ax.legend() + return ax + + def plot_orbit(self, node: int, *, ax: Any = None) -> Any: + """Plot a node's cross-flow displacement against its in-line displacement, over D.""" + plt = pyplot() + if ax is None: + _, ax = plt.subplots() + x, y = self.orbit(node) + ax.plot(x / self.diameter, y / self.diameter) + ax.set_xlabel("In-line displacement / D (-)") + ax.set_ylabel("Cross-flow displacement / D (-)") + ax.set_aspect("equal", adjustable="datalim") + return ax + + +def viv_response( + history: TimeHistory, + *, + flow: npt.ArrayLike, + diameter: float, + start: float | None = None, + stop: float | None = None, + line_id: int | None = None, + uniform_rtol: float = 1.0e-6, +) -> VIVResponse: + """Resolve a line's node motion into its VIV response. + + Parameters + ---------- + history : TimeHistory + A :class:`~cabledyn.LineNodeHistory`, a :class:`~cabledyn.MoorDynLineHistory` + with node positions, or a main output with the line's + ``LNp{x,y,z}`` channels. + flow : array_like + ``(3,)`` flow velocity the local frames are taken against, m/s: the + current at the line (a uniform one, or a representative velocity of a + sheared one). + diameter : float + Diameter the amplitudes are divided by, m. + start, stop : float, optional + The window to analyse, s (default: the whole record); a lock-in study + leaves out the build-up. + line_id : int, optional + The line of a main output (required there, refused for a per-line file). + uniform_rtol : float + Relative tolerance of the uniform-sampling check. + + Returns + ------- + VIVResponse + The displacement in the local flow frames and the response measures. + + Raises + ------ + ValueError + If the flow is not a finite non-zero 3-vector, the diameter is not + positive, the window holds fewer than eight samples, the sampling is + not uniform, or the mean shape has coincident nodes. + """ + velocity = np.array(flow, dtype=np.float64) + if velocity.shape != (3,) or not np.all(np.isfinite(velocity)) or not np.any(velocity): + raise ValueError("flow must be a finite, non-zero 3-vector") + if not (math.isfinite(float(diameter)) and float(diameter) > 0.0): + raise ValueError("diameter must be finite and positive") + time, positions = _positions(history, line_id) + whole_line = isinstance(history, (LineNodeHistory, MoorDynLineHistory)) + if whole_line or line_id is None: + numbers = tuple(range(1, positions.shape[1] + 1)) + else: + # the LNp nodes _positions took, in the same (ascending) order + numbers = tuple(node_position_channels(history, line_id)) + keep = np.ones(time.size, dtype=bool) + if start is not None: + keep &= time >= float(start) + if stop is not None: + keep &= time <= float(stop) + time = time[keep] + positions = positions[keep] + if time.size < 8: + raise ValueError("the window must hold at least eight samples") + _sampling(time, rtol=float(uniform_rtol), atol=0.0) + if positions.shape[1] < 2: + raise ValueError("the line must have at least two nodes") + mean = positions.mean(axis=0) + chords = np.diff(mean, axis=0) + lengths = np.linalg.norm(chords, axis=1) + if np.any(lengths <= 0.0): + raise ValueError("the mean shape has coincident nodes") + tangent = np.empty_like(mean) + tangent[0] = chords[0] + tangent[-1] = chords[-1] + tangent[1:-1] = mean[2:] - mean[:-2] + tangent /= np.linalg.norm(tangent, axis=1)[:, None] + normal = velocity[None, :] - (tangent @ velocity)[:, None] * tangent + speed = np.linalg.norm(normal, axis=1) + framed = speed > 1.0e-9 * float(np.linalg.norm(velocity)) + in_axis = np.full_like(mean, math.nan) + in_axis[framed] = normal[framed] / speed[framed, None] + cross_axis = np.cross(tangent, in_axis) + motion = positions - mean[None, :, :] + in_line = np.einsum("tnk,nk->tn", motion, in_axis) + cross_flow = np.einsum("tnk,nk->tn", motion, cross_axis) + return VIVResponse( + time=_readonly(time), + arc_length=_readonly(np.concatenate(([0.0], np.cumsum(lengths)))), + mean_position=_readonly(mean), + tangent=_readonly(tangent), + in_line_axis=_readonly(in_axis), + cross_flow_axis=_readonly(cross_axis), + normal_speed=_readonly(np.where(framed, speed, 0.0)), + in_line=_readonly(in_line), + cross_flow=_readonly(cross_flow), + diameter=float(diameter), + flow=_readonly(velocity), + whole_line=whole_line, + node_numbers=numbers, + ) diff --git a/python/tests/test_end_to_end.py b/python/tests/test_end_to_end.py index ac271af..9abe487 100644 --- a/python/tests/test_end_to_end.py +++ b/python/tests/test_end_to_end.py @@ -29,6 +29,7 @@ parameter_grid, resample, run_study, + viv_response, ) from cabledyn import cli as run_cli from cabledyn.post_cli import main as post_main @@ -279,3 +280,28 @@ def test_deck_validator_agrees_with_the_native_reader( assert exc.returncode == 1, exc.stderr # a deck error, not a solve failure native_accepts = False assert python_accepts == native_accepts == accepted + + +def test_viv_response_of_the_inline_example(driver, tmp_path): + # the line positions of examples/viv_taut_cable_inline.dat (Outputs p for its V flag) + text = (EXAMPLES / "viv_taut_cable_inline.dat").read_text(encoding="utf-8") + deck = tmp_path / "viv_inline.dat" + deck.write_text( + text.replace("1 1 2 V", "1 1 2 p"), encoding="utf-8" + ) + result = driver.run(deck, "out/viv", timeout=600) + history = result.read_line_positions(1) + response = viv_response(history, flow=(0.0, 0.15, 0.0), diameter=0.1, start=60.0) + mid, quarter = 25, 12 + # the deck's own statement: mid-span cross-flow A/D 0.82 at 0.29 Hz, quarter-span in-line + # A/D 0.19 at twice the frequency + assert response.amplitude_over_diameter("cross_flow")[mid] == pytest.approx(0.82, abs=0.02) + assert response.amplitude_over_diameter("in_line")[quarter] == pytest.approx(0.19, abs=0.02) + f_cf = response.frequency("cross_flow") + assert f_cf == pytest.approx(0.29, abs=0.01) + assert response.frequency("in_line") / f_cf == pytest.approx(2.0, abs=0.15) + # inside the synchronisation band cF +/- dF = 0.18 +/- 0.08 + assert 0.10 < response.nondimensional_frequency()[mid] < 0.26 + assert response.modal_amplitudes("cross_flow").dominant_mode == 1 + assert response.modal_amplitudes("in_line").dominant_mode == 2 + assert response.travelling_wave_index("cross_flow") < 0.2 diff --git a/python/tests/test_viv.py b/python/tests/test_viv.py new file mode 100644 index 0000000..cb8057e --- /dev/null +++ b/python/tests/test_viv.py @@ -0,0 +1,274 @@ +# SPDX-License-Identifier: Apache-2.0 +"""VIV response diagnostics (cabledyn.viv) on synthetic line motions with known answers.""" + +from __future__ import annotations + +import csv +import math +from pathlib import Path + +import numpy as np +import pytest + +from cabledyn import LineNodeHistory, VIVResponse, viv_response +from cabledyn.results import TimeHistory + +L = 100.0 +D = 0.1 +N_NODES = 41 +F = 0.5 # cross-flow frequency [Hz] +DT = 0.01 +T = 40.0 # 20 cross-flow periods +FLOW = (0.0, 0.5, 0.0) + + +def _history(displacement, *, time=None, depth=-50.0, lateral=0.0) -> LineNodeHistory: + """A straight line along +x at y = lateral, z = depth with displacement(t, s) -> (dy, dz).""" + t = np.arange(0.0, T, DT) if time is None else time + s = np.linspace(0.0, L, N_NODES) + dy, dz = displacement(t[:, None], s[None, :]) + x = np.broadcast_to(s, dy.shape) + xyz = np.stack((x, lateral + dy, depth + dz), axis=2).reshape(t.size, -1) + channels = ["Time(s)"] + [f"Node{n}{a}(m)" for n in range(1, N_NODES + 1) for a in "XYZ"] + return LineNodeHistory( + Path("synthetic.Line1.p.out"), "", tuple(channels), None, np.column_stack((t, xyz)) + ) + + +def _standing(t, s, a_cf=0.08, a_il=0.02, phase_cf=0.3, phase_il=1.0): + """Cross-flow (z) mode 1 at F, in-line (y) mode 2 at 2 F.""" + dz = a_cf * np.sin(np.pi * s / L) * np.cos(2.0 * np.pi * F * t + phase_cf) + dy = a_il * np.sin(2.0 * np.pi * s / L) * np.cos(4.0 * np.pi * F * t + phase_il) + return dy, dz + + +def test_local_frame_follows_the_tangent_and_the_flow(): + response = viv_response(_history(_standing), flow=FLOW, diameter=D) + assert isinstance(response, VIVResponse) + assert np.allclose(response.tangent, [1.0, 0.0, 0.0]) + assert np.allclose(response.in_line_axis, [0.0, 1.0, 0.0]) + # (e_x, e_y, t) right-handed: cross-flow = t x in-line = +z + assert np.allclose(response.cross_flow_axis, [0.0, 0.0, 1.0]) + assert np.allclose(response.normal_speed, 0.5) + assert response.arc_length[-1] == pytest.approx(L) + + +def test_amplitudes_frequencies_and_the_nondimensional_frequency(): + response = viv_response(_history(_standing), flow=FLOW, diameter=D) + mid, quarter = N_NODES // 2, N_NODES // 4 + assert response.rms_over_diameter("cross_flow")[mid] == pytest.approx(0.08 / math.sqrt(2) / D) + assert response.amplitude_over_diameter("cross_flow")[mid] == pytest.approx(0.8, rel=1e-3) + assert response.amplitude_over_diameter("in_line")[quarter] == pytest.approx(0.2, rel=1e-3) + assert response.frequency("cross_flow") == pytest.approx(F, abs=1e-3) + assert response.frequency("in_line") == pytest.approx(2.0 * F, abs=1e-3) + assert response.frequencies("cross_flow")[mid] == pytest.approx(F, abs=1e-3) + # the pinned end nodes do not move + assert math.isnan(response.frequencies("cross_flow")[0]) + assert np.allclose(response.nondimensional_frequency(), F * D / 0.5, rtol=1e-3) + + +def test_modal_amplitudes_find_the_modes(): + response = viv_response(_history(_standing), flow=FLOW, diameter=D) + cross = response.modal_amplitudes("cross_flow", n_modes=6) + assert cross.dominant_mode == 1 + assert cross.rms_over_diameter[0] == pytest.approx(0.08 / math.sqrt(2) / D, rel=1e-9) + assert np.all(cross.rms_over_diameter[1:] < 1e-9) + assert cross.residual < 1e-9 + assert cross.coefficients.shape == (response.time.size, 6) + inline = response.modal_amplitudes("in_line") + assert inline.dominant_mode == 2 + s = response.arc_length + custom = response.modal_amplitudes("cross_flow", shapes=[np.sin(2 * np.pi * s / L)]) + assert custom.mode_numbers == (1,) and custom.residual == pytest.approx(1.0, rel=1e-6) + + +def _main_output(displacement, nodes) -> TimeHistory: + """The L1Np[xyz] channels of some nodes of the _history line, as a main output.""" + whole = _history(displacement) + channels = ["Time(s)"] + columns = [whole.time] + for node in nodes: + for axis in "XYZ": + channels.append(f"L1N{node}p{axis.lower()}") + columns.append(whole.column(f"Node{node}{axis}(m)")) + return TimeHistory(Path("run.out"), "", tuple(channels), None, np.column_stack(columns)) + + +def test_default_shapes_need_the_whole_line(): + interior = viv_response(_main_output(_standing, range(5, 38)), flow=FLOW, diameter=D, line_id=1) + assert not interior.whole_line + # the sines would vanish at nodes 5 and 37 instead of the line's ends: refused + with pytest.raises(ValueError, match="the default shapes need the whole line"): + interior.modal_amplitudes("cross_flow") + # shapes at the nodes held are fitted as given + s = np.linspace(0.0, L, N_NODES)[4:37] + fit = interior.modal_amplitudes("cross_flow", shapes=[np.sin(np.pi * s / L)]) + assert fit.rms_over_diameter[0] == pytest.approx(0.08 / math.sqrt(2) / D, rel=1e-9) + assert fit.residual < 1e-9 + assert viv_response(_history(_standing), flow=FLOW, diameter=D).whole_line + + +def test_dependent_shapes_are_refused(): + # ten uniform nodes: sin(9 pi s/S) vanishes at every node, sin(10 pi s/S) = -sin(8 pi s/S) + n = 10 + t = np.arange(0.0, T, DT) + s = np.linspace(0.0, L, n) + dz = 0.05 * np.sin(8.0 * np.pi * s / L)[None, :] * np.cos(2.0 * np.pi * F * t)[:, None] + xyz = np.stack((np.broadcast_to(s, dz.shape), 0.0 * dz, -50.0 + dz), axis=2) + channels = ["Time(s)"] + [f"Node{k}{a}(m)" for k in range(1, n + 1) for a in "XYZ"] + history = LineNodeHistory( + Path("coarse.Line1.p.out"), + "", + tuple(channels), + None, + np.column_stack((t, xyz.reshape(t.size, -1))), + ) + response = viv_response(history, flow=FLOW, diameter=D) + with pytest.raises(ValueError, match=r"10 shapes are not independent .*\(rank 8\)"): + response.modal_amplitudes("cross_flow", n_modes=10) + eight = response.modal_amplitudes("cross_flow", n_modes=8) + assert eight.dominant_mode == 8 + assert eight.rms_over_diameter[7] == pytest.approx(0.05 / math.sqrt(2) / D, rel=1e-9) + assert eight.residual < 1e-9 + + +def test_travelling_wave_index_is_nan_without_motion(): + still = viv_response(_history(lambda t, s: (0.0 * t * s, 0.0 * t * s)), flow=FLOW, diameter=D) + assert math.isnan(still.frequency("cross_flow")) + assert math.isnan(still.travelling_wave_index("cross_flow")) + assert math.isnan(still.travelling_wave_index("in_line")) + along = viv_response(_history(_standing), flow=(1.0, 0.0, 0.0), diameter=D) + assert math.isnan(along.travelling_wave_index("cross_flow")) + # still nodes at coordinates with no exact binary form keep a round-off offset from their + # mean: they have no frequency, on a still line and at the pinned ends of a moving one + for depth in (-50.1, -0.3, -1234.567): + calm = viv_response( + _history(lambda t, s: (0.0 * t * s, 0.0 * t * s), depth=depth), + flow=FLOW, + diameter=D, + ) + assert math.isnan(calm.frequency("cross_flow")) + assert np.all(np.isnan(calm.frequencies("cross_flow"))) + assert math.isnan(calm.travelling_wave_index("cross_flow")) + moving = viv_response(_history(_standing, depth=depth), flow=FLOW, diameter=D) + ends = moving.frequencies("cross_flow")[[0, -1]] + assert np.all(np.isnan(ends)) + assert moving.frequency("cross_flow") == pytest.approx(F, abs=1e-3) + # cross-flow motion only, at a lateral coordinate with no exact binary form: no in-line + # motion, so no orbit phase + flat = viv_response( + _history( + lambda t, s: ( + 0.0 * t * s, + 0.08 * np.sin(np.pi * s / L) * np.cos(2 * np.pi * F * t), + ), + depth=depth, + lateral=-0.3, + ), + flow=FLOW, + diameter=D, + ) + assert math.isnan(flat.phase_difference(N_NODES // 2 + 1)) + assert np.all(flat.complex_shape("in_line", 2.0 * F) == 0.0) + + +def test_main_output_nodes_keep_their_numbers(tmp_path): + whole = viv_response(_history(_standing), flow=FLOW, diameter=D) + held = (5, 10, 21, 37) + some = viv_response(_main_output(_standing, held), flow=FLOW, diameter=D, line_id=1) + assert some.node_numbers == held + assert whole.node_numbers == tuple(range(1, N_NODES + 1)) + # a node is taken by its number: node 21 is the mid-span node of the whole line + for a, b in zip(some.orbit(21), whole.orbit(21), strict=True): + assert np.array_equal(a, b) + assert some.phase_difference(10) == pytest.approx(whole.phase_difference(10), abs=1e-9) + with pytest.raises(ValueError, match=r"one of the nodes held, \[5, 10, 21, 37\]"): + some.orbit(1) + with pytest.raises(ValueError, match="from 1 to 41"): + whole.orbit(42) + with (some.export(tmp_path / "some.csv")).open(encoding="utf-8") as stream: + rows = list(csv.reader(stream)) + assert [row[0] for row in rows[1:]] == [str(node) for node in held] + + +def test_travelling_wave_index_separates_standing_and_travelling_waves(): + standing = viv_response(_history(_standing), flow=FLOW, diameter=D) + assert standing.travelling_wave_index("cross_flow") < 1e-6 + + def travelling(t, s): + dz = 0.05 * np.cos(2.0 * np.pi * F * t - 2.0 * np.pi * 4.0 * s / L) + return np.zeros_like(dz), dz + + wave = viv_response(_history(travelling), flow=FLOW, diameter=D) + assert wave.travelling_wave_index("cross_flow") > 0.95 + + +def test_complex_shape_and_phase_difference(): + response = viv_response(_history(_standing), flow=FLOW, diameter=D) + mid, quarter = N_NODES // 2, N_NODES // 4 + shape = response.complex_shape("cross_flow") + assert abs(shape[mid]) == pytest.approx(0.08, rel=1e-3) + assert np.angle(shape[mid]) == pytest.approx(0.3, abs=1e-3) + # theta = phi_x - 2 phi_y = 1.0 - 0.6 rad + assert response.phase_difference(quarter + 1) == pytest.approx(math.degrees(0.4), abs=0.1) + x, y = response.orbit(quarter + 1) + assert x.shape == y.shape == response.time.shape + assert math.isnan(response.phase_difference(1)) + + +def test_flow_along_the_line_leaves_no_frame(): + response = viv_response(_history(_standing), flow=(0.4, 0.0, 0.0), diameter=D) + assert np.all(np.isnan(response.in_line_axis)) and np.all(response.normal_speed == 0.0) + assert np.all(np.isnan(response.frequencies("cross_flow"))) + assert math.isnan(response.frequency("cross_flow")) + assert np.all(np.isnan(response.nondimensional_frequency())) + with pytest.raises(ValueError, match="fewer nodes with a flow frame"): + response.modal_amplitudes() + + +def test_window_and_export(tmp_path): + response = viv_response(_history(_standing), flow=FLOW, diameter=D, start=10.0, stop=30.0) + assert response.time[0] == pytest.approx(10.0) and response.time[-1] <= 30.0 + target = response.export(tmp_path / "viv.csv") + with target.open(encoding="utf-8") as stream: + rows = list(csv.reader(stream)) + assert rows[0][:3] == ["Node", "ArcLength_[m]", "NormalSpeed_[m/s]"] + assert len(rows) == N_NODES + 1 + assert rows[1][7] == "" # the pinned End A node has no frequency + with pytest.raises(FileExistsError): + response.export(target) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"flow": (0.0, 0.0)}, "finite, non-zero 3-vector"), + ({"flow": (0.0, 0.0, 0.0)}, "finite, non-zero 3-vector"), + ({"diameter": 0.0}, "diameter must be finite and positive"), + ({"start": 39.97}, "at least eight samples"), + ({"line_id": 1}, "line_id does not apply"), + ], +) +def test_arguments_are_validated(kwargs, message): + arguments = {"flow": FLOW, "diameter": D, **kwargs} + with pytest.raises(ValueError, match=message): + viv_response(_history(_standing), **arguments) + + +def test_non_uniform_sampling_is_refused(): + time = np.cumsum(np.full(100, DT)) + time[50:] += 0.003 + with pytest.raises(ValueError, match="uniform sampling"): + viv_response(_history(_standing, time=time), flow=FLOW, diameter=D) + + +def test_methods_validate_direction_and_node(): + response = viv_response(_history(_standing), flow=FLOW, diameter=D) + with pytest.raises(ValueError, match="direction must be one of"): + response.rms_over_diameter("axial") + with pytest.raises(ValueError, match="node must be an integer from 1 to 41"): + response.orbit(0) + with pytest.raises(ValueError, match="n_modes must be a positive integer"): + response.modal_amplitudes(n_modes=0) + with pytest.raises(ValueError, match="shapes must have shape"): + response.modal_amplitudes(shapes=np.ones((2, 3)))