From 4247124fd71a5021cdb13e613caf202ecaff622b Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Wed, 11 Nov 2026 19:04:48 +0900 Subject: [PATCH 1/2] feat: cabledyn.current_steps, stepped-current VIV studies in one run A stepped-current study holds the current at a sequence of speeds and lets each step start from the state the previous one left, so the response follows its branch up and back down; separate runs would each start from rest. The standalone driver has no restart file, but its MoorDyn-C Currents 2 table (a depth profile in time) carries the whole sweep in one run. current_steps(speeds, hold=, ramp=, direction=) returns a CurrentSteps schedule: each speed held, then ramped linearly to the next. Its write() puts current_profile_dynamic.txt in the deck folder (uniform over two depths), duration is the TMax to give, windows(settle) the analysis window of every hold, and responses() the viv_response of each. The table is resampled at its smallest interval, the ramp, so a hold must be a whole number of ramps (refused otherwise). Checks: the schedule, the file rows and the refusals (python/tests/test_viv.py); end to end, the in-line VIV example under 0.10 -> 0.18 -> 0.10 m/s: the lock-in frequency rises with the current and returns with it. Full pytest, ruff, mypy strict, Sphinx -W. Signed-off-by: Jae Hoon Seo --- CHANGELOG.md | 3 + doc/api_python.rst | 5 + doc/python_postprocessing.rst | 24 +++++ python/cabledyn/__init__.py | 10 +- python/cabledyn/viv.py | 158 +++++++++++++++++++++++++++++++- python/tests/test_end_to_end.py | 27 ++++++ python/tests/test_viv.py | 49 +++++++++- 7 files changed, 273 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4b854b8..1179d05 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -41,6 +41,9 @@ All notable changes to CableDyn are recorded in this file. The format follows (`CurvX`/`CurvY`), `T/A - E r (kappa_x cos theta + kappa_y sin theta)`, counted point by point for the fatigue of biaxial bending; a whirling section, which the two-fibre recovery from the curvature magnitude sees as constant, now accumulates its damage. +- `cabledyn.current_steps`: a stepped-current schedule for a VIV study in one run (each speed + held, then ramped to the next), written as the deck's MoorDyn-C `Currents 2` file, with the + VIV response of every hold. ## [0.4.2] - 2026-11-09 diff --git a/doc/api_python.rst b/doc/api_python.rst index 19b1138..b4e67c9 100644 --- a/doc/api_python.rst +++ b/doc/api_python.rst @@ -346,6 +346,11 @@ the solver's own curvature, tension, and angle channels, where written, are auth .. autoclass:: cabledyn.ModalAmplitudes :members: +.. autofunction:: cabledyn.current_steps + +.. autoclass:: cabledyn.CurrentSteps + :members: + Deck editing and case generation -------------------------------- diff --git a/doc/python_postprocessing.rst b/doc/python_postprocessing.rst index e2358f8..4bd0d4d 100644 --- a/doc/python_postprocessing.rst +++ b/doc/python_postprocessing.rst @@ -495,6 +495,30 @@ is 0.05, a standing wave between the pinned ends. viv.plot_orbit(13) viv.export("results/line1_viv.csv") +A stepped-current study holds the current at a sequence of speeds in one run, so each step +starts from the state the previous one left: the response follows a branch as the current goes +up and comes back down, where separate runs would each start from rest. +:func:`cabledyn.current_steps` builds the schedule (each speed held ``hold`` seconds, ramped +linearly over ``ramp`` seconds to the next, along one direction); its ``write`` puts the deck's +MoorDyn-C ``Currents 2`` file ``current_profile_dynamic.txt`` (:doc:`options`) in the deck +folder, its ``duration`` is the ``TMax`` to give, and its ``responses`` returns the +:func:`~cabledyn.viv_response` of every hold from ``settle`` seconds into it. The file's +smallest time interval is the ramp, the step the current table is resampled to, so a hold must +be a whole number of ramps; the static start takes the first speed. + +.. code-block:: python + + from cabledyn import current_steps + + speeds = [0.10, 0.14, 0.18, 0.22, 0.26, 0.22, 0.18, 0.14, 0.10] + steps = current_steps(speeds, hold=60.0, ramp=5.0, direction=(0.0, 1.0, 0.0)) + steps.write("cases/stepped") # next to the deck, which sets "2 Currents" and TMax + print(steps.duration) + # ... run the deck, then: + for speed, viv in zip(steps.speeds, steps.responses( + result.read_line_positions(1), diameter=0.1, settle=30.0)): + print(speed, viv.amplitude_over_diameter("cross_flow").max(), viv.frequency("cross_flow")) + Parameter grids --------------- diff --git a/python/cabledyn/__init__.py b/python/cabledyn/__init__.py index d23b3cf..d13fdac 100644 --- a/python/cabledyn/__init__.py +++ b/python/cabledyn/__init__.py @@ -150,7 +150,13 @@ ) from cabledyn.sweep import parameter_grid from cabledyn.touchdown import TouchdownHistory, touchdown_history -from cabledyn.viv import ModalAmplitudes, VIVResponse, viv_response +from cabledyn.viv import ( + CurrentSteps, + ModalAmplitudes, + VIVResponse, + current_steps, + viv_response, +) if TYPE_CHECKING: from cabledyn._lib import abi_minor as abi_minor @@ -177,6 +183,7 @@ "CoherenceResult", "ConvergenceError", "CoupledRun", + "CurrentSteps", "DamageProfile", "DeckFile", "DeckFormatError", @@ -243,6 +250,7 @@ "channel_summary", "clearance_matrix", "compare_histories", + "current_steps", "cycle_histogram", "damage_along_arc", "damage_equivalent_range", diff --git a/python/cabledyn/viv.py b/python/cabledyn/viv.py index d24d3ce..28c3513 100644 --- a/python/cabledyn/viv.py +++ b/python/cabledyn/viv.py @@ -41,7 +41,7 @@ from cabledyn.spectra import _sampling from cabledyn.touchdown import _positions -__all__ = ["ModalAmplitudes", "VIVResponse", "viv_response"] +__all__ = ["CurrentSteps", "ModalAmplitudes", "VIVResponse", "current_steps", "viv_response"] _DIRECTIONS = ("cross_flow", "in_line") @@ -596,3 +596,159 @@ def viv_response( whole_line=whole_line, node_numbers=numbers, ) + + +@dataclass(frozen=True) +class CurrentSteps: + """A uniform current held at a sequence of speeds, for a stepped-current VIV study. + + Created by :func:`current_steps`. The current is held at ``speeds[k]`` for + ``hold`` seconds, then ramps linearly over ``ramp`` seconds to the next + speed, so one run continues each step from the state the previous one + left (the response branch an up-and-down sweep follows). :meth:`write` + gives the deck its MoorDyn-C ``Currents 2`` file. + + Attributes + ---------- + speeds : numpy.ndarray + Read-only ``(n_steps,)`` current speeds, m/s. + hold, ramp : float + Hold time of each speed and ramp time between speeds, s. + direction : numpy.ndarray + Read-only ``(3,)`` unit direction of the current. + """ + + speeds: npt.NDArray[Any] + hold: float + ramp: float + direction: npt.NDArray[Any] + + @property + def starts(self) -> npt.NDArray[Any]: + """Read-only ``(n_steps,)`` start time of each hold, s.""" + return _readonly(np.arange(self.speeds.size) * (self.hold + self.ramp)) + + @property + def duration(self) -> float: + """End of the last hold, s: the deck's ``TMax`` (a longer run repeats the record).""" + return float(self.starts[-1] + self.hold) + + def windows(self, settle: float) -> tuple[tuple[float, float], ...]: + """Return the analysis window of every hold, from ``settle`` seconds into it to its end.""" + if not (math.isfinite(float(settle)) and 0.0 <= float(settle) < self.hold): + raise ValueError("settle must be finite, non-negative and shorter than the hold") + return tuple((float(t) + float(settle), float(t) + self.hold) for t in self.starts) + + def write( + self, + folder: str | os.PathLike[str], + *, + depths: tuple[float, float] = (-1.0e4, 0.0), + overwrite: bool = False, + ) -> Path: + """Write ``current_profile_dynamic.txt``, the deck's ``Currents 2`` file, into ``folder``. + + The current is uniform between the two ``depths`` (z, m, increasing) and + held beyond them. The file's smallest time interval is the ramp, the time + step MoorDyn-C and CableDyn resample it to, so the holds stay exact. + + Raises + ------ + FileExistsError + If the file exists and ``overwrite`` is false. + ValueError + If the depths are not two finite, increasing elevations. + """ + low, high = (float(z) for z in depths) + if not (math.isfinite(low) and math.isfinite(high) and low < high): + raise ValueError("depths must be two finite, increasing elevations") + target = Path(folder).expanduser().resolve() / "current_profile_dynamic.txt" + if target.exists() and not overwrite: + raise FileExistsError(f"output already exists: {target}") + rows: list[str] = [] + for k, (start, speed) in enumerate(zip(self.starts, self.speeds, strict=True)): + velocity = float(speed) * self.direction + values = " ".join(f"{number(v)} {number(v)}" for v in velocity) + times = (float(start), float(start) + self.hold) if k else (0.0, self.hold) + rows.extend(f"{number(t)} {values}" for t in times) + lines = [ + "--------------------- MoorDyn dynamic currents File -------------------------", + "a uniform current held at a sequence of speeds (cabledyn.current_steps)", + "line 5 lists the depths (m); each later row is t ux(z1 z2) uy(z1 z2) uz(z1 z2)", + "------------------------------------------------------------------------------", + f"{number(low)} {number(high)}", + "time ux... uy... uz...", + *rows, + ] + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text("\n".join(lines) + "\n", encoding="ascii") + return target + + def responses( + self, + history: TimeHistory, + *, + diameter: float, + settle: float, + line_id: int | None = None, + ) -> tuple[VIVResponse, ...]: + """Return the :func:`viv_response` of every hold, from ``settle`` seconds into it.""" + return tuple( + viv_response( + history, + flow=float(speed) * self.direction, + diameter=diameter, + start=start, + stop=stop, + line_id=line_id, + ) + for speed, (start, stop) in zip(self.speeds, self.windows(settle), strict=True) + ) + + +def current_steps( + speeds: npt.ArrayLike, + *, + hold: float, + ramp: float, + direction: npt.ArrayLike = (0.0, 1.0, 0.0), +) -> CurrentSteps: + """Return a stepped current schedule. + + Parameters + ---------- + speeds : array_like + Positive current speeds, m/s, in the order they are held; an + up-and-down sweep lists them up and back. + hold : float + Hold time of each speed, s; a whole number of ramps. + ramp : float + Positive ramp time between speeds, s. + direction : array_like + ``(3,)`` direction of the current (normalised), default ``+y``. + + Raises + ------ + ValueError + If a speed is not finite and positive, the times are invalid, the hold + is not a whole number of ramps, or the direction is not a finite, + non-zero 3-vector. + """ + values = np.array(speeds, dtype=np.float64).reshape(-1) + if values.size < 1 or not np.all(np.isfinite(values)) or np.any(values <= 0.0): + raise ValueError("speeds must be one or more finite, positive values") + hold_s, ramp_s = float(hold), float(ramp) + if not (math.isfinite(hold_s) and hold_s > 0.0 and math.isfinite(ramp_s) and ramp_s > 0.0): + raise ValueError("hold and ramp must be finite and positive") + ratio = hold_s / ramp_s + if abs(ratio - round(ratio)) > 1.0e-9 * ratio: + raise ValueError("hold must be a whole number of ramps (the file's resampling step)") + unit = np.array(direction, dtype=np.float64) + if unit.shape != (3,) or not np.all(np.isfinite(unit)) or not np.any(unit): + raise ValueError("direction must be a finite, non-zero 3-vector") + return CurrentSteps( + speeds=_readonly(values), + hold=hold_s, + ramp=ramp_s, + direction=_readonly(unit / np.linalg.norm(unit)), + ) diff --git a/python/tests/test_end_to_end.py b/python/tests/test_end_to_end.py index 9abe487..02cd1ef 100644 --- a/python/tests/test_end_to_end.py +++ b/python/tests/test_end_to_end.py @@ -23,6 +23,7 @@ DriverExecutionError, StaticProfile, compare_histories, + current_steps, fft_filter, generate_deck_cases, line_geometry, @@ -305,3 +306,29 @@ def test_viv_response_of_the_inline_example(driver, tmp_path): 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 + + +def test_stepped_current_continues_the_response(driver, tmp_path): + # the in-line VIV example under a current stepped 0.10 -> 0.18 -> 0.10 m/s in one run + steps = current_steps([0.10, 0.18, 0.10], hold=60.0, ramp=5.0) + text = (EXAMPLES / "viv_taut_cable_inline.dat").read_text(encoding="utf-8") + text = text.replace("1 1 2 V", "1 1 2 p") + lines = [] + for line in text.splitlines(): + if line.startswith("uniform 0.0 0.15 0.0 current"): + line = "2 Currents" + elif line.startswith("90.0 TMax"): + line = f"{steps.duration} TMax" + lines.append(line) + deck = tmp_path / "stepped.dat" + deck.write_text("\n".join(lines) + "\n", encoding="utf-8") + steps.write(tmp_path) + result = driver.run(deck, "out/stepped", timeout=600) + first, middle, last = steps.responses(result.read_line_positions(1), diameter=0.1, settle=30.0) + # the lock-in frequency follows the current up and comes back with it + assert middle.frequency("cross_flow") > first.frequency("cross_flow") + 0.03 + assert last.frequency("cross_flow") == pytest.approx(first.frequency("cross_flow"), abs=0.01) + assert ( + middle.amplitude_over_diameter("cross_flow").max() + > first.amplitude_over_diameter("cross_flow").max() + ) diff --git a/python/tests/test_viv.py b/python/tests/test_viv.py index cb8057e..bc3578d 100644 --- a/python/tests/test_viv.py +++ b/python/tests/test_viv.py @@ -10,7 +10,7 @@ import numpy as np import pytest -from cabledyn import LineNodeHistory, VIVResponse, viv_response +from cabledyn import LineNodeHistory, VIVResponse, current_steps, viv_response from cabledyn.results import TimeHistory L = 100.0 @@ -272,3 +272,50 @@ def test_methods_validate_direction_and_node(): response.modal_amplitudes(n_modes=0) with pytest.raises(ValueError, match="shapes must have shape"): response.modal_amplitudes(shapes=np.ones((2, 3))) + + +def test_current_steps_schedule_and_file(tmp_path): + steps = current_steps([0.1, 0.2, 0.1], hold=20.0, ramp=5.0, direction=(0.0, 2.0, 0.0)) + np.testing.assert_allclose(steps.starts, [0.0, 25.0, 50.0]) + assert steps.duration == pytest.approx(70.0) + np.testing.assert_allclose(steps.direction, [0.0, 1.0, 0.0]) + assert steps.windows(15.0) == ((15.0, 20.0), (40.0, 45.0), (65.0, 70.0)) + path = steps.write(tmp_path, depths=(-100.0, 0.0)) + assert path.name == "current_profile_dynamic.txt" + lines = path.read_text(encoding="ascii").splitlines() + assert lines[4].split() == ["-100", "0"] + rows = np.array([[float(v) for v in line.split()] for line in lines[6:]]) + # t ux(z1 z2) uy(z1 z2) uz(z1 z2): held, ramped over 5 s, held + np.testing.assert_allclose(rows[:, 0], [0.0, 20.0, 25.0, 45.0, 50.0, 70.0]) + np.testing.assert_allclose(rows[:, 3], [0.1, 0.1, 0.2, 0.2, 0.1, 0.1]) + assert np.all(rows[:, [1, 2, 5, 6]] == 0.0) and np.all(rows[:, 3] == rows[:, 4]) + with pytest.raises(FileExistsError): + steps.write(tmp_path) + with pytest.raises(ValueError, match="settle"): + steps.windows(20.0) + + +@pytest.mark.parametrize( + ("kwargs", "message"), + [ + ({"speeds": []}, "speeds must be"), + ({"speeds": [0.1, 0.0]}, "speeds must be"), + ({"ramp": 0.0}, "hold and ramp"), + ({"hold": 22.0}, "whole number of ramps"), + ({"direction": (0.0, 0.0, 0.0)}, "direction must be"), + ], +) +def test_current_steps_validation(kwargs, message): + arguments = {"speeds": [0.1, 0.2], "hold": 20.0, "ramp": 5.0, **kwargs} + with pytest.raises(ValueError, match=message): + current_steps(**arguments) + + +def test_current_steps_responses_take_each_hold(): + steps = current_steps([0.5, 0.25], hold=15.0, ramp=5.0) + responses = steps.responses(_history(_standing), diameter=D, settle=5.0) + assert len(responses) == 2 + assert responses[1].time[0] == pytest.approx(25.0) + assert np.allclose(responses[0].normal_speed, 0.5) and np.allclose( + responses[1].normal_speed, 0.25 + ) From 6b7786333e3581f6a80b6640b4142f7b95a32459 Mon Sep 17 00:00:00 2001 From: Jae Hoon Seo Date: Thu, 12 Nov 2026 13:28:06 +0900 Subject: [PATCH 2/2] fix: hold the last current_steps speed past TMax The resampled current table has floor(t_last/dt) + 1 samples and takes its first sample over its last interval (CD_Current_Grid_Velocity, as in MoorDyn-C), so a file that ended at the last hold's end returned to the first speed at TMax. With a rounded resampling step it did so a whole step early: speeds (0.5, 1.0) held 0.3 s with 0.1 s ramps give dt = 0.10000000000000003, the table ends at 0.6 s, and the last 0.1 s of the last hold ran at 0.5 m/s. CurrentSteps.write now ends the file two ramps after duration, still at the last speed. The last sample then lies at least about one ramp past TMax, so neither the wrap nor a dropped step reaches the run. Checks: the written file, evaluated by the native resampling rule, gives the last speed over the whole last hold for the case above, an integer schedule and a single speed; without the guard row the same rule returns the first speed. Full pytest (with the stepped-current end-to-end run), ruff, mypy, Sphinx -W, pre-commit. Signed-off-by: Jae Hoon Seo --- doc/python_postprocessing.rst | 4 +++- python/cabledyn/viv.py | 14 +++++++++++++- python/tests/test_viv.py | 36 ++++++++++++++++++++++++++++++++--- 3 files changed, 49 insertions(+), 5 deletions(-) diff --git a/doc/python_postprocessing.rst b/doc/python_postprocessing.rst index 4bd0d4d..dc2763e 100644 --- a/doc/python_postprocessing.rst +++ b/doc/python_postprocessing.rst @@ -504,7 +504,9 @@ MoorDyn-C ``Currents 2`` file ``current_profile_dynamic.txt`` (:doc:`options`) i folder, its ``duration`` is the ``TMax`` to give, and its ``responses`` returns the :func:`~cabledyn.viv_response` of every hold from ``settle`` seconds into it. The file's smallest time interval is the ramp, the step the current table is resampled to, so a hold must -be a whole number of ramps; the static start takes the first speed. +be a whole number of ramps; the static start takes the first speed. The file holds the last +speed for two ramps past ``duration``, because the resampled table returns to its first sample +over its last interval; the run therefore keeps the last speed up to ``TMax``. .. code-block:: python diff --git a/python/cabledyn/viv.py b/python/cabledyn/viv.py index 28c3513..414d86e 100644 --- a/python/cabledyn/viv.py +++ b/python/cabledyn/viv.py @@ -630,7 +630,11 @@ def starts(self) -> npt.NDArray[Any]: @property def duration(self) -> float: - """End of the last hold, s: the deck's ``TMax`` (a longer run repeats the record).""" + """End of the last hold, s: the deck's ``TMax``. + + The file holds the last speed for two ramps beyond it (:meth:`write`); a + longer run then repeats the record. + """ return float(self.starts[-1] + self.hold) def windows(self, settle: float) -> tuple[tuple[float, float], ...]: @@ -652,6 +656,12 @@ def write( held beyond them. The file's smallest time interval is the ramp, the time step MoorDyn-C and CableDyn resample it to, so the holds stay exact. + The resampled table has ``floor(t_last/dt) + 1`` samples and takes its + first sample over its last interval (where a longer run starts to repeat + it), and a rounded ``dt`` can drop the last sample by one step. The file + therefore ends two ramps after :attr:`duration`, still at the last speed, + so the run up to ``TMax`` never returns to the first speed. + Raises ------ FileExistsError @@ -671,6 +681,8 @@ def write( values = " ".join(f"{number(v)} {number(v)}" for v in velocity) times = (float(start), float(start) + self.hold) if k else (0.0, self.hold) rows.extend(f"{number(t)} {values}" for t in times) + # the guard: the last speed held two ramps past TMax (see above) + rows.append(f"{number(self.duration + 2.0 * self.ramp)} {values}") lines = [ "--------------------- MoorDyn dynamic currents File -------------------------", "a uniform current held at a sequence of speeds (cabledyn.current_steps)", diff --git a/python/tests/test_viv.py b/python/tests/test_viv.py index bc3578d..c7ffa1e 100644 --- a/python/tests/test_viv.py +++ b/python/tests/test_viv.py @@ -285,9 +285,10 @@ def test_current_steps_schedule_and_file(tmp_path): lines = path.read_text(encoding="ascii").splitlines() assert lines[4].split() == ["-100", "0"] rows = np.array([[float(v) for v in line.split()] for line in lines[6:]]) - # t ux(z1 z2) uy(z1 z2) uz(z1 z2): held, ramped over 5 s, held - np.testing.assert_allclose(rows[:, 0], [0.0, 20.0, 25.0, 45.0, 50.0, 70.0]) - np.testing.assert_allclose(rows[:, 3], [0.1, 0.1, 0.2, 0.2, 0.1, 0.1]) + # t ux(z1 z2) uy(z1 z2) uz(z1 z2): held, ramped over 5 s, held, and the last speed two + # ramps past TMax + np.testing.assert_allclose(rows[:, 0], [0.0, 20.0, 25.0, 45.0, 50.0, 70.0, 80.0]) + np.testing.assert_allclose(rows[:, 3], [0.1, 0.1, 0.2, 0.2, 0.1, 0.1, 0.1]) assert np.all(rows[:, [1, 2, 5, 6]] == 0.0) and np.all(rows[:, 3] == rows[:, 4]) with pytest.raises(FileExistsError): steps.write(tmp_path) @@ -311,6 +312,35 @@ def test_current_steps_validation(kwargs, message): current_steps(**arguments) +def _resampled_speed(times, speeds, t): + # the native rule (CD_Current_Grid_Resample, CD_Current_Grid_Velocity): dt the smallest + # interval, floor(t_last/dt) + 1 samples at k dt, the upper index modulo the sample count + # and both indices the first sample over the last interval + dt = np.diff(times).min() + samples = np.interp(np.arange(int(np.floor(times[-1] / dt)) + 1) * dt, times, speeds) + q = t / dt + n = np.floor(q).astype(int) + upper = (n + 1) % samples.size + lower = np.maximum(upper - 1, 0) + return samples[lower] * (1.0 - (q - n)) + samples[upper] * (q - n) + + +@pytest.mark.parametrize( + ("speeds", "hold", "ramp"), + [([0.5, 1.0], 0.3, 0.1), ([0.1, 0.2, 0.3], 20.0, 5.0), ([0.4], 1.2, 0.4)], +) +def test_current_steps_file_holds_the_last_speed_to_tmax(tmp_path, speeds, hold, ramp): + steps = current_steps(speeds, hold=hold, ramp=ramp) + lines = steps.write(tmp_path).read_text(encoding="ascii").splitlines() + rows = np.array([[float(v) for v in line.split()] for line in lines[6:]]) + t = np.linspace(steps.windows(0.0)[-1][0], steps.duration, 401) + np.testing.assert_allclose(_resampled_speed(rows[:, 0], rows[:, 3], t), speeds[-1]) + if speeds[0] != speeds[-1]: + # without the guard row the table would return to the first speed within the last hold + old = _resampled_speed(rows[:-1, 0], rows[:-1, 3], t) + assert old[-1] == pytest.approx(speeds[0]) + + def test_current_steps_responses_take_each_hold(): steps = current_steps([0.5, 0.25], hold=15.0, ramp=5.0) responses = steps.responses(_history(_standing), diameter=D, settle=5.0)