From 97224109ce3e55143484bc5c8a939982737e5d60 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:52:18 +0000 Subject: [PATCH 01/12] Test the radiation convolution against a direct sum of its quadrature. RadiationRirfConvolution had no unit test. test_radiation_rirf_convolution checks it on synthetic kernels against a term-by-term evaluation of F_i = sum_j sum_k K_ij(tau_k) w_k v_j(t - tau_k): time steps equal to, an integer fraction of and not commensurate with the lag spacing, a variable step, a non-uniform lag grid, start-up, two bodies, a truncated kernel and rejected inputs. test_radiation_component checks RadiationComponent on the bundled sphere and RM3 kernels, as stored, smoothed, truncated and with a yawed body. --- tests/unit/CMakeLists.txt | 13 + tests/unit/test_radiation_component.cpp | 191 +++++++++ .../unit/test_radiation_rirf_convolution.cpp | 390 ++++++++++++++++++ 3 files changed, 594 insertions(+) create mode 100644 tests/unit/test_radiation_component.cpp create mode 100644 tests/unit/test_radiation_rirf_convolution.cpp diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 69859d0..3bdf035 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -119,6 +119,14 @@ if(TARGET seastack_hydro_io) "SEASTACK_TEST_RM3_H5_FILE=\"${_seastack_test_rm3_h5}\"" "SEASTACK_TEST_SPHERE_H5_FILE=\"${CMAKE_SOURCE_DIR}/data/demos/run_seastack/iea_sphere/assets/hydroData/sphere.h5\"") set_tests_properties(test_radiation_ss_reporting PROPERTIES LABELS "unit;chrono-free") + + # RadiationComponent on the bundled sphere and RM3 kernels against a direct sum + build_unit_test(test_radiation_component) + target_link_libraries(test_radiation_component PRIVATE SEAStack::HydroIO) + target_compile_definitions(test_radiation_component PRIVATE + "SEASTACK_TEST_RM3_H5_FILE=\"${_seastack_test_rm3_h5}\"" + "SEASTACK_TEST_SPHERE_H5_FILE=\"${CMAKE_SOURCE_DIR}/data/demos/run_seastack/iea_sphere/assets/hydroData/sphere.h5\"") + set_tests_properties(test_radiation_component PROPERTIES LABELS "unit;chrono-free") else() message(STATUS "Skipping test_directional_waves (requires SEASTACK_ENABLE_HYDRO_IO)") endif() @@ -479,6 +487,11 @@ build_unit_test(test_ramp_and_rirf_truncation) target_link_libraries(test_ramp_and_rirf_truncation PRIVATE SEAStack::Hydro) set_tests_properties(test_ramp_and_rirf_truncation PROPERTIES LABELS "unit;chrono-free") +# Radiation convolution against a direct evaluation of its quadrature (Chrono-free, HDF5-free) +build_unit_test(test_radiation_rirf_convolution) +target_link_libraries(test_radiation_rirf_convolution PRIVATE SEAStack::Hydro) +set_tests_properties(test_radiation_rirf_convolution PROPERTIES LABELS "unit;chrono-free") + # Runtime wave amplitude envelope (live wave height) and FD excitation scaling (Chrono-free) build_unit_test(test_amplitude_envelope) target_link_libraries(test_amplitude_envelope PRIVATE SEAStack::Hydro) diff --git a/tests/unit/test_radiation_component.cpp b/tests/unit/test_radiation_component.cpp new file mode 100644 index 0000000..9734747 --- /dev/null +++ b/tests/unit/test_radiation_component.cpp @@ -0,0 +1,191 @@ +/********************************************************************* + * @file test_radiation_component.cpp + * @brief RadiationComponent on the bundled BEM data against a direct sum. + * + * RadiationComponent::Compute() subtracts from the body forces + * + * F_i(t) = sum_j sum_k K_ij(tau_k) w_k v_j(t - tau_k) + * + * with K the retardation kernel of the BEM file in dimensional units + * (HydroData::GetRIRFVal, i.e. rho times the stored value), optionally + * smoothed and tapered (ProcessRirfKernels), w_k the trapezoid weights of the + * lag grid and v the body velocities in each body's heading frame. + * + * The time step is the lag spacing of the file, so every lagged velocity is + * a stored sample and the reference sum needs no interpolation. Cases: + * - sphere (1 body), kernel as stored; + * - RM3 (2 bodies with body-to-body coupling), kernel as stored; + * - RM3, kernel smoothed and tapered; + * - RM3, kernel truncated at 8 s; + * - RM3 with the float yawed: velocities and forces rotate with the heading. + * + * Needs the bundled sphere.h5 and rm3.h5 (HydroIO); no Chrono. + *********************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +/// World-frame velocity of body `body`, component `dof` (0-2 linear, 3-5 angular). +double WorldVelocity(int body, int dof, double t) { + const double amplitude = (dof < 3) ? 0.4 : 0.05; + return amplitude * (std::sin((0.6 + 0.07 * dof + 0.04 * body) * t + 0.5 * dof) + + 0.3 * std::sin((1.7 + 0.05 * dof) * t + 1.1 * body)); +} + +struct CaseSetup { + std::string label; + std::string h5_file; + int num_bodies = 1; + RadiationKernelProcessing processing; // default: kernel as stored + double truncation_time = 0.0; // [s], 0 = full kernel + double yaw_body1 = 0.0; // [rad] +}; + +/// Largest difference between the component and the direct sum over the +/// checked steps, relative to the largest force component. +double RunCase(const CaseSetup& setup) { + const HydroData data = seastack::hydro_io::H5FileInfo(setup.h5_file, setup.num_bodies).ReadH5Data(); + const int n = kDofPerBody * setup.num_bodies; + + // Lag grid and weights, as HydroModelBuilder prepares them. + const Eigen::VectorXd tau = TruncateRirfTimeVector(data.GetRIRFTimeVector(), setup.truncation_time); + const Eigen::VectorXd width = ComputeRirfWidthVector(tau); + const int steps = static_cast(tau.size()); + const double dt = tau[1] - tau[0]; + + // Reference kernel K(row, col, step) [dimensional]. + std::vector> kernel; + auto stored = [&data](int body, int row_dof, int col, int step) { + return data.GetRIRFVal(body, row_dof, col, step); + }; + if (setup.processing.RequiresProcessing()) { + kernel = ProcessRirfKernels(setup.num_bodies, steps, tau, stored, setup.processing); + } else { + kernel.assign(setup.num_bodies, Eigen::Tensor(kDofPerBody, n, steps)); + for (int b = 0; b < setup.num_bodies; ++b) + for (int row_dof = 0; row_dof < kDofPerBody; ++row_dof) + for (int col = 0; col < n; ++col) + for (int s = 0; s < steps; ++s) kernel[b](row_dof, col, s) = stored(b, row_dof, col, s); + } + + RadiationComponent component(data, setup.num_bodies, steps, tau, width, setup.processing, ""); + + SystemState state; + state.bodies.resize(setup.num_bodies); + state.bodies[0].orientation_rpy[2] = setup.yaw_body1; + + // heading_velocity[step][dof]: what the component should have recorded. + std::vector> heading_velocity; + const int total_steps = steps + 12; + double worst = 0.0; + for (int step = 0; step < total_steps; ++step) { + const double t = step * dt; + std::vector recorded(n); + for (int b = 0; b < setup.num_bodies; ++b) { + BodyState& body = state.bodies[b]; + for (int d = 0; d < 3; ++d) { + body.linear_velocity[d] = WorldVelocity(b, d, t); + body.angular_velocity[d] = WorldVelocity(b, d + 3, t); + } + const Eigen::Matrix3d world_to_heading = HeadingToWorld(body).transpose(); + const Eigen::Vector3d linear = world_to_heading * body.linear_velocity; + const Eigen::Vector3d angular = world_to_heading * body.angular_velocity; + for (int d = 0; d < 3; ++d) { + recorded[kDofPerBody * b + d] = linear[d]; + recorded[kDofPerBody * b + 3 + d] = angular[d]; + } + } + heading_velocity.push_back(recorded); + + BodyForces forces(setup.num_bodies); + component.Compute(state, t, forces); + + // Check once the record covers the kernel (steady state). + if (step < steps + 1 || (step != steps + 1 && step != total_steps - 1)) continue; + Eigen::VectorXd expected = Eigen::VectorXd::Zero(n); + for (int k = 0; k < steps; ++k) { + const std::vector& v = heading_velocity[step - k]; + for (int col = 0; col < n; ++col) { + for (int row = 0; row < n; ++row) { + expected[row] += kernel[row / kDofPerBody](row % kDofPerBody, col, k) * width[k] * v[col]; + } + } + } + // The component subtracts the radiation force, rotated to the world frame. + double scale = 0.0; + double difference = 0.0; + for (int b = 0; b < setup.num_bodies; ++b) { + const Eigen::Matrix3d heading_to_world = HeadingToWorld(state.bodies[b]); + const Eigen::Vector3d force = -(heading_to_world * expected.segment<3>(kDofPerBody * b)); + const Eigen::Vector3d moment = -(heading_to_world * expected.segment<3>(kDofPerBody * b + 3)); + scale = std::max({scale, force.cwiseAbs().maxCoeff(), moment.cwiseAbs().maxCoeff()}); + difference = std::max({difference, (forces[b].force - force).cwiseAbs().maxCoeff(), + (forces[b].moment - moment).cwiseAbs().maxCoeff()}); + } + Check(scale > 1.0, setup.label + ": reference force is non-zero"); + worst = std::max(worst, difference / scale); + } + return worst; +} + +} // namespace + +int main() { + constexpr double kTolerance = 1.0e-11; // relative; differences are rounding only + + CaseSetup sphere{"sphere, stored kernel", SEASTACK_TEST_SPHERE_H5_FILE, 1}; + Check(RunCase(sphere) < kTolerance, sphere.label); + + CaseSetup rm3{"rm3, stored kernel", SEASTACK_TEST_RM3_H5_FILE, 2}; + Check(RunCase(rm3) < kTolerance, rm3.label); + + CaseSetup smoothed = rm3; + smoothed.label = "rm3, smoothed and tapered kernel"; + smoothed.processing = RadiationKernelProcessing::DefaultSmoothing(); + Check(RunCase(smoothed) < kTolerance, smoothed.label); + + CaseSetup truncated = rm3; + truncated.label = "rm3, kernel truncated at 8 s"; + truncated.truncation_time = 8.0; + Check(RunCase(truncated) < kTolerance, truncated.label); + + CaseSetup yawed = rm3; + yawed.label = "rm3, float yawed 0.4 rad"; + yawed.yaw_body1 = 0.4; + Check(RunCase(yawed) < kTolerance, yawed.label); + + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} diff --git a/tests/unit/test_radiation_rirf_convolution.cpp b/tests/unit/test_radiation_rirf_convolution.cpp new file mode 100644 index 0000000..2eb3d63 --- /dev/null +++ b/tests/unit/test_radiation_rirf_convolution.cpp @@ -0,0 +1,390 @@ +/********************************************************************* + * @file test_radiation_rirf_convolution.cpp + * @brief Radiation convolution against a direct evaluation of its quadrature. + * + * RadiationRirfConvolution evaluates, for force degree of freedom i, + * + * F_i(t) = sum_j sum_k K_ij(tau_k) w_k v_j(t - tau_k) + * + * with K the retardation kernel on the lag grid tau_k, w_k the trapezoid + * weights of that grid, and v_j the recorded velocity of degree of freedom + * j, interpolated linearly between samples. A lag is left out while the + * record does not reach back to t - tau_k (start-up). + * + * Each test builds a small kernel, records a velocity history and compares + * the result with DirectSum() below, which evaluates the formula term by + * term. Cases: + * - step equal to the lag spacing, an integer fraction of it, a + * non-integer fraction of it, and a variable step; + * - a non-uniform lag grid; + * - start-up, before the record covers the kernel; + * - two bodies with body-to-body coupling; + * - a kernel shortened by a truncation time; + * - motion in one degree of freedom, and no motion; + * - a constant velocity, where the force is the trapezoid integral of K; + * - the same result from the kernel-tensor and the callback interfaces; + * - rejected inputs. + * + * Self-contained: no data files, HDF5 or Chrono. + *********************************************************************/ + +#include +#include +#include + +#include +#include + +#include +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +/// Kernel for all bodies: one (6, 6N, S) tensor per body, as RadiationComponent holds it. +using KernelTensors = std::vector>; + +/// A smooth, decaying, oscillating kernel that differs for every (row, column). +KernelTensors MakeKernel(int num_bodies, const Eigen::VectorXd& tau) { + const int n = kDofPerBody * num_bodies; + const int steps = static_cast(tau.size()); + KernelTensors kernel(num_bodies, Eigen::Tensor(kDofPerBody, n, steps)); + for (int row = 0; row < n; ++row) { + for (int col = 0; col < n; ++col) { + const double amplitude = 1.0e4 * (1.0 + 0.3 * row - 0.2 * col); + const double decay = 0.4 + 0.05 * ((row + 2 * col) % 5); + const double frequency = 1.0 + 0.25 * ((3 * row + col) % 7); + for (int s = 0; s < steps; ++s) { + kernel[row / kDofPerBody](row % kDofPerBody, col, s) = + amplitude * std::exp(-decay * tau[s]) * std::cos(frequency * tau[s]); + } + } + } + return kernel; +} + +double KernelValue(const KernelTensors& kernel, int row, int col, int step) { + return kernel[row / kDofPerBody](row % kDofPerBody, col, step); +} + +/// Velocity of degree of freedom `dof` at time t [m/s or rad/s]; zero at t = 0. +double Velocity(int dof, double t) { + return (0.2 + 0.03 * dof) * std::sin((0.7 + 0.11 * dof) * t) + 0.05 * std::sin((1.9 + 0.07 * dof) * t); +} + +/// Recorded history, oldest first: times[n] and velocities[n][dof]. +struct Record { + std::vector times; + std::vector> velocities; +}; + +/// v_dof(time) by linear interpolation in the record. `found` is false when +/// the record does not reach back to `time`. +double InterpolateRecord(const Record& record, int dof, double time, bool& found) { + const int count = static_cast(record.times.size()); + found = false; + for (int n = count - 1; n >= 0; --n) { + if (record.times[n] <= time) { + found = true; + if (n == count - 1 || record.times[n] == time) return record.velocities[n][dof]; + const double span = record.times[n + 1] - record.times[n]; + const double weight_newer = (time - record.times[n]) / span; + return (1.0 - weight_newer) * record.velocities[n][dof] + weight_newer * record.velocities[n + 1][dof]; + } + } + return 0.0; +} + +/// The quadrature evaluated term by term at the newest recorded time. +std::vector DirectSum(const KernelTensors& kernel, const Eigen::VectorXd& tau, const Record& record) { + const int n = kDofPerBody * static_cast(kernel.size()); + const Eigen::VectorXd width = ComputeRirfWidthVector(tau); + const double now = record.times.back(); + std::vector force(n, 0.0); + if (record.times.size() < 2) return force; // one sample: nothing to convolve with + for (int step = 0; step < tau.size(); ++step) { + for (int col = 0; col < n; ++col) { + bool found = false; + const double v = InterpolateRecord(record, col, now - tau[step], found); + if (!found) continue; + for (int row = 0; row < n; ++row) { + force[row] += KernelValue(kernel, row, col, step) * width[step] * v; + } + } + } + return force; +} + +/// Largest difference between two force vectors, relative to the largest reference value. +double RelativeDifference(const std::vector& actual, const std::vector& reference) { + double scale = 0.0; + double difference = 0.0; + for (size_t i = 0; i < reference.size(); ++i) { + scale = std::max(scale, std::abs(reference[i])); + difference = std::max(difference, std::abs(actual[i] - reference[i])); + } + return scale > 0.0 ? difference / scale : difference; +} + +std::vector> PerBody(const std::vector& flat, int num_bodies) { + std::vector> out(num_bodies, std::vector(kDofPerBody)); + for (int b = 0; b < num_bodies; ++b) { + for (int d = 0; d < kDofPerBody; ++d) out[b][d] = flat[kDofPerBody * b + d]; + } + return out; +} + +/// Convolution under test plus the record of what it has been given. +struct Harness { + int num_bodies; + Eigen::VectorXd tau; + KernelTensors kernel; + RadiationRirfConvolution convolution; + Record record; + + Harness(int bodies, const Eigen::VectorXd& lag_grid, int kernel_steps_stored = -1) + : num_bodies(bodies), + tau(lag_grid), + kernel(MakeKernel(bodies, kernel_steps_stored > 0 + ? Eigen::VectorXd::LinSpaced(kernel_steps_stored, 0.0, + lag_grid[1] * (kernel_steps_stored - 1)) + : lag_grid)), + convolution(bodies, static_cast(lag_grid.size()), lag_grid, ComputeRirfWidthVector(lag_grid)) {} + + /// Record the velocities at `time` and return the radiation force vector. + std::vector Step(double time, const std::vector& velocity) { + record.times.push_back(time); + record.velocities.push_back(velocity); + convolution.RecordVelocities(time, PerBody(velocity, num_bodies)); + return convolution.ComputeForces([](int, int, int) { return 0.0; }, &kernel); + } + + std::vector StepWithSignal(double time) { + std::vector v(kDofPerBody * num_bodies); + for (int dof = 0; dof < static_cast(v.size()); ++dof) v[dof] = Velocity(dof, time); + return Step(time, v); + } +}; + +/// Run `num_steps` steps of size dt and return the largest difference from +/// DirectSum() over the steps listed in `check_steps`. +double LargestDifference(Harness& harness, double dt, int num_steps, const std::vector& check_steps) { + double worst = 0.0; + for (int n = 0; n <= num_steps; ++n) { + const std::vector force = harness.StepWithSignal(n * dt); + if (std::find(check_steps.begin(), check_steps.end(), n) != check_steps.end()) { + worst = std::max(worst, RelativeDifference(force, DirectSum(harness.kernel, harness.tau, harness.record))); + } + } + return worst; +} + +constexpr double kTolerance = 1.0e-12; // relative; the two evaluations differ only by rounding + +Eigen::VectorXd UniformLags(int steps, double spacing) { + return Eigen::VectorXd::LinSpaced(steps, 0.0, spacing * (steps - 1)); +} + +void TestStepEqualToLagSpacing() { + Harness h(1, UniformLags(41, 0.05)); + Check(LargestDifference(h, 0.05, 130, {60, 61, 97, 130}) < kTolerance, "step = lag spacing"); +} + +void TestStepIntegerFractionOfLagSpacing() { + Harness h(1, UniformLags(41, 0.05)); + Check(LargestDifference(h, 0.0125, 400, {200, 201, 202, 203, 333, 400}) < kTolerance, + "step = lag spacing / 4"); +} + +void TestStepNotCommensurateWithLagSpacing() { + Harness h(1, UniformLags(41, 0.05)); + Check(LargestDifference(h, 0.035, 160, {80, 81, 119, 160}) < kTolerance, "step = 0.7 x lag spacing"); + Harness coarse(1, UniformLags(41, 0.05)); + Check(LargestDifference(coarse, 0.13, 60, {30, 31, 47, 60}) < kTolerance, "step = 2.6 x lag spacing"); +} + +void TestVariableStep() { + Harness h(1, UniformLags(41, 0.05)); + double time = 0.0; + double worst = 0.0; + for (int n = 0; n < 220; ++n) { + const std::vector force = h.StepWithSignal(time); + if (n > 120 && n % 9 == 0) { + worst = std::max(worst, RelativeDifference(force, DirectSum(h.kernel, h.tau, h.record))); + } + time += 0.02 + 0.015 * std::sin(0.37 * n); // steps between 0.005 and 0.035 s + } + Check(worst < kTolerance, "variable step"); + + // A constant step, then a different constant step. + Harness switched(1, UniformLags(41, 0.05)); + time = 0.0; + worst = 0.0; + for (int n = 0; n < 200; ++n) { + const std::vector force = switched.StepWithSignal(time); + if (n >= 60) worst = std::max(worst, RelativeDifference(force, DirectSum(switched.kernel, switched.tau, switched.record))); + time += (n < 80) ? 0.05 : 0.025; + } + Check(worst < kTolerance, "step halved during the run"); +} + +void TestNonUniformLagGrid() { + Eigen::VectorXd tau(12); + tau << 0.0, 0.02, 0.05, 0.1, 0.18, 0.3, 0.45, 0.7, 1.0, 1.4, 1.9, 2.5; + Harness h(1, tau); + Check(LargestDifference(h, 0.03, 150, {100, 101, 137, 150}) < kTolerance, "non-uniform lag grid"); +} + +void TestStartUp() { + // The record is shorter than the kernel (2 s) for the first 40 steps. + Harness h(1, UniformLags(41, 0.05)); + Check(LargestDifference(h, 0.05, 45, {1, 2, 3, 7, 20, 39, 40, 41, 45}) < kTolerance, "start-up, step = lag spacing"); + Harness fine(1, UniformLags(41, 0.05)); + Check(LargestDifference(fine, 0.02, 110, {1, 2, 5, 33, 99, 100, 101, 110}) < kTolerance, + "start-up, step = 0.4 x lag spacing"); + + Harness first(1, UniformLags(41, 0.05)); + const std::vector force = first.Step(0.0, std::vector(kDofPerBody, 1.0)); + Check(std::all_of(force.begin(), force.end(), [](double f) { return f == 0.0; }), + "one recorded sample gives zero force"); +} + +void TestTwoBodies() { + Harness h(2, UniformLags(31, 0.04)); + Check(LargestDifference(h, 0.04, 80, {40, 41, 66, 80}) < kTolerance, "two bodies, step = lag spacing"); + Harness interpolated(2, UniformLags(31, 0.04)); + Check(LargestDifference(interpolated, 0.03, 100, {50, 51, 77, 100}) < kTolerance, + "two bodies, step = 0.75 x lag spacing"); + + // Motion of body 2 only: the force on body 1 comes from the body-to-body kernels. + Harness coupled(2, UniformLags(31, 0.04)); + std::vector force; + for (int n = 0; n <= 60; ++n) { + std::vector v(12, 0.0); + for (int dof = 6; dof < 12; ++dof) v[dof] = Velocity(dof, n * 0.04); + force = coupled.Step(n * 0.04, v); + } + Check(RelativeDifference(force, DirectSum(coupled.kernel, coupled.tau, coupled.record)) < kTolerance, + "motion of body 2 only"); + Check(std::abs(force[2]) > 1.0, "body 2 motion loads body 1"); +} + +void TestTruncatedKernel() { + // The stored kernel has 41 lags; the convolution is given the first 21 (truncation at 1 s). + Harness h(1, UniformLags(21, 0.05), 41); + Check(h.kernel[0].dimension(2) == 41, "stored kernel is longer than the lag grid"); + Check(LargestDifference(h, 0.05, 70, {30, 31, 52, 70}) < kTolerance, "kernel truncated to the lag grid"); +} + +void TestSingleDegreeOfFreedomAndRest() { + Harness heave(1, UniformLags(41, 0.05)); + std::vector force; + for (int n = 0; n <= 70; ++n) { + std::vector v(kDofPerBody, 0.0); + v[2] = Velocity(2, n * 0.05); + force = heave.Step(n * 0.05, v); + } + Check(RelativeDifference(force, DirectSum(heave.kernel, heave.tau, heave.record)) < kTolerance, "heave motion only"); + + Harness rest(1, UniformLags(41, 0.05)); + bool all_zero = true; + for (int n = 0; n <= 50; ++n) { + for (double f : rest.Step(n * 0.05, std::vector(kDofPerBody, 0.0))) all_zero = all_zero && f == 0.0; + } + Check(all_zero, "no motion gives exactly zero force"); +} + +void TestConstantVelocity() { + // After the record covers the kernel, a unit velocity in degree of freedom j + // gives F_i = sum_k K_ij(tau_k) w_k, the trapezoid integral of the kernel. + Harness h(1, UniformLags(41, 0.05)); + std::vector force; + std::vector v(kDofPerBody, 0.0); + v[4] = 1.0; + for (int n = 0; n <= 60; ++n) force = h.Step(n * 0.05, v); + const Eigen::VectorXd width = ComputeRirfWidthVector(h.tau); + std::vector integral(kDofPerBody, 0.0); + for (int row = 0; row < kDofPerBody; ++row) { + for (int s = 0; s < h.tau.size(); ++s) integral[row] += KernelValue(h.kernel, row, 4, s) * width[s]; + } + Check(RelativeDifference(force, integral) < kTolerance, "constant velocity gives the kernel integral"); +} + +void TestCallbackInterface() { + // The callback form of ComputeForces() returns the same forces as the kernel-tensor form. + Harness tensor(1, UniformLags(41, 0.05)); + Harness callback(1, UniformLags(41, 0.05)); + double worst = 0.0; + for (int n = 0; n <= 70; ++n) { + const double time = n * 0.035; + std::vector v(kDofPerBody); + for (int dof = 0; dof < kDofPerBody; ++dof) v[dof] = Velocity(dof, time); + const std::vector from_tensor = tensor.Step(time, v); + callback.convolution.RecordVelocities(time, PerBody(v, 1)); + const std::vector from_callback = callback.convolution.ComputeForces( + [&callback](int row, int col, int step) { return KernelValue(callback.kernel, row, col, step); }); + worst = std::max(worst, RelativeDifference(from_callback, from_tensor)); + } + Check(worst < kTolerance, "callback and kernel-tensor interfaces agree"); +} + +template +bool Throws(Callable&& callable) { + try { + callable(); + } catch (const std::exception&) { + return true; + } + return false; +} + +void TestRejectedInputs() { + const Eigen::VectorXd tau = UniformLags(11, 0.1); + const Eigen::VectorXd width = ComputeRirfWidthVector(tau); + Check(Throws([&] { RadiationRirfConvolution(0, 11, tau, width); }), "zero bodies rejected"); + Check(Throws([&] { RadiationRirfConvolution(1, 0, tau, width); }), "zero lags rejected"); + Check(Throws([&] { RadiationRirfConvolution(1, 11, Eigen::VectorXd(), width); }), "empty lag grid rejected"); + Check(Throws([&] { RadiationRirfConvolution(1, 11, tau, Eigen::VectorXd()); }), "empty weights rejected"); + + Harness h(1, tau); + h.Step(0.0, std::vector(kDofPerBody, 0.0)); + h.Step(0.1, std::vector(kDofPerBody, 0.1)); + Check(Throws([&] { h.convolution.RecordVelocities(0.1, PerBody(std::vector(kDofPerBody, 0.2), 1)); }), + "two records at the same time rejected"); +} + +} // namespace + +int main() { + TestStepEqualToLagSpacing(); + TestStepIntegerFractionOfLagSpacing(); + TestStepNotCommensurateWithLagSpacing(); + TestVariableStep(); + TestNonUniformLagGrid(); + TestStartUp(); + TestTwoBodies(); + TestTruncatedKernel(); + TestSingleDegreeOfFreedomAndRest(); + TestConstantVelocity(); + TestCallbackInterface(); + TestRejectedInputs(); + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} From 0ee3514dee48a2b55cfd3e5151db17e935cff8ed Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:52:18 +0000 Subject: [PATCH 02/12] Add bench_hydro_kernels: force-component timing without Chrono. Builds a HydroModel from each demo BEM file with HydroModelBuilder and times radiation, excitation and hydrostatics / nonlinear Froude-Krylov through HydroForces' profiling counters, with a prescribed body motion. Prints microseconds per evaluation as CSV. Run by hand; not a CTest test. --- tests/benchmark/CMakeLists.txt | 16 ++ .../benchmark/kernels/bench_hydro_kernels.cpp | 241 ++++++++++++++++++ 2 files changed, 257 insertions(+) create mode 100644 tests/benchmark/kernels/bench_hydro_kernels.cpp diff --git a/tests/benchmark/CMakeLists.txt b/tests/benchmark/CMakeLists.txt index b382a03..3e183ff 100644 --- a/tests/benchmark/CMakeLists.txt +++ b/tests/benchmark/CMakeLists.txt @@ -158,6 +158,22 @@ if(SEASTACK_ENABLE_MOORING) target_include_directories(test_bench_5sa_spreading PRIVATE ${CMAKE_SOURCE_DIR}/demos/5sa) endif() +# ═══════════════════════════════════════════════════════════════════════════════ +# Force-component timing without Chrono +# +# bench_hydro_kernels times the hydrodynamic force components (radiation, +# excitation, hydrostatics / nonlinear Froude-Krylov) on the demo BEM data with +# a prescribed body motion. It prints a CSV table and is run by hand; it is not +# a CTest test and takes no part in the benchmark report below. +# ═══════════════════════════════════════════════════════════════════════════════ +if(TARGET seastack_hydro_io) + add_executable(bench_hydro_kernels kernels/bench_hydro_kernels.cpp) + target_link_libraries(bench_hydro_kernels PRIVATE SEAStack::HydroIO) + target_compile_features(bench_hydro_kernels PRIVATE ${SEASTACK_CXX_STANDARD}) + target_compile_definitions(bench_hydro_kernels PRIVATE "SEASTACK_SOURCE_DIR=\"${CMAKE_SOURCE_DIR}\"") + seastack_apply_compile_settings(bench_hydro_kernels) +endif() + # ═══════════════════════════════════════════════════════════════════════════════ # Benchmark Report Generation # diff --git a/tests/benchmark/kernels/bench_hydro_kernels.cpp b/tests/benchmark/kernels/bench_hydro_kernels.cpp new file mode 100644 index 0000000..7b63612 --- /dev/null +++ b/tests/benchmark/kernels/bench_hydro_kernels.cpp @@ -0,0 +1,241 @@ +/** + * Timing of the hydrodynamic force components on the demo BEM data, without + * Chrono. + * + * Each case builds a HydroModel from a demo .h5 file with HydroModelBuilder, + * as an application would, and calls HydroForces::Evaluate() with a + * prescribed body motion. The time spent in each component type comes from + * HydroForces' own profiling counters, so the figures are those of the + * production components and nothing else. + * + * bench_hydro_kernels [] [] + * + * is data/demos/run_seastack (default: from the source tree). + * Output: one CSV row per case on standard output, + * + * case,bodies,step_s,steps,hydrostatics_us,radiation_us,excitation_us + * + * in microseconds per Evaluate() call. Nonlinear Froude-Krylov is counted + * under hydrostatics, as in the application's profile. Each case is timed in + * several blocks after a warm-up that fills the radiation history; the + * fastest block is reported, being the one least disturbed by other + * processes. + * + * The prescribed motion is a sum of sinusoids in all six degrees of freedom + * of every body. It is not a solution of the equations of motion; the cost + * of these components does not depend on that. + */ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#ifndef SEASTACK_SOURCE_DIR +#define SEASTACK_SOURCE_DIR "." +#endif + +using namespace seastack::hydro; + +namespace { + +enum class Sea { kStill, kRegular, kIrregular, kSpreading }; + +struct Case { + std::string name; + std::string h5_file; ///< relative to the demo root + int num_bodies; + double step; ///< time step of the calls [s] + Sea sea; + bool smooth_kernel; ///< Savitzky-Golay smoothing and taper of the radiation kernel + double start_time; ///< time of the first call [s] + std::string mesh_file; ///< closed mesh for nonlinear Froude-Krylov (body 1); empty = linear +}; + +constexpr double kRampDuration = 60.0; // [s], as in the irregular-wave demos + +/// The cases mirror the demo models. "steady" cases start long after the +/// excitation ramp; "ramp" cases start at t = 0 inside it. +std::vector Cases() { + const std::string sphere = "iea_sphere/assets/hydroData/sphere.h5"; + const std::string rm3 = "rm3/assets/hydroData/rm3.h5"; + const std::string oswec = "oswec/assets/hydroData/oswec.h5"; + const std::string f3of = "f3of/assets/hydroData/f3of.h5"; + const std::string trimaran = "trimaran/assets/hydroData/trimaran.h5"; + const std::string five_sa = "5sa/assets/hydroData/5sa.h5"; + const std::string five_sa_dir = "5sa/assets/hydroData/5sa_directional.h5"; + const std::string wigley = "wigley/assets/hydroData/wigley_directional.h5"; + const std::string sphere_mesh = "iea_sphere/assets/geometry/sphere.obj"; + return { + {"sphere_still", sphere, 1, 0.01, Sea::kStill, false, 0.0, ""}, + {"sphere_regular", sphere, 1, 0.01, Sea::kRegular, false, 1000.0, ""}, + {"sphere_irregular_steady", sphere, 1, 0.015, Sea::kIrregular, false, 1000.0, ""}, + {"sphere_nlfk_regular", sphere, 1, 0.01, Sea::kRegular, false, 1000.0, sphere_mesh}, + {"sphere_nlfk_irregular", sphere, 1, 0.01, Sea::kIrregular, false, 1000.0, sphere_mesh}, + {"rm3_still", rm3, 2, 0.01, Sea::kStill, false, 0.0, ""}, + {"rm3_regular", rm3, 2, 0.01, Sea::kRegular, true, 1000.0, ""}, + {"rm3_irregular_ramp", rm3, 2, 0.01, Sea::kIrregular, true, 0.0, ""}, + {"rm3_irregular_steady", rm3, 2, 0.01, Sea::kIrregular, true, 1000.0, ""}, + {"oswec_still", oswec, 2, 0.03, Sea::kStill, false, 0.0, ""}, + {"oswec_irregular_ramp", oswec, 2, 0.03, Sea::kIrregular, true, 0.0, ""}, + {"oswec_irregular_steady", oswec, 2, 0.03, Sea::kIrregular, true, 1000.0, ""}, + {"f3of_still", f3of, 3, 0.02, Sea::kStill, false, 0.0, ""}, + {"f3of_irregular_ramp", f3of, 3, 0.02, Sea::kIrregular, true, 0.0, ""}, + {"f3of_irregular_steady", f3of, 3, 0.02, Sea::kIrregular, true, 1000.0, ""}, + {"trimaran_spreading", trimaran, 3, 0.02, Sea::kSpreading, true, 1000.0, ""}, + {"5sa_regular", five_sa, 5, 0.01, Sea::kRegular, true, 1000.0, ""}, + {"5sa_irregular_steady", five_sa, 5, 0.01, Sea::kIrregular, true, 1000.0, ""}, + {"5sa_spreading", five_sa_dir, 5, 0.01, Sea::kSpreading, true, 1000.0, ""}, + {"wigley_spreading", wigley, 1, 0.01, Sea::kSpreading, true, 1000.0, ""}, + }; +} + +SeaStateDefinition MakeSeaState(Sea sea, double depth) { + SeaStateDefinition def; + def.depth = std::isfinite(depth) ? depth : 0.0; + if (sea == Sea::kRegular) { + def.type = "regular"; + def.amplitude = 1.0; // [m] + def.omega = 2.0 * 3.14159265358979323846 / 8.0; // T = 8 s + return def; + } + def.type = "irregular"; + SeaStatePartition partition; + partition.spectrum.type = "jonswap"; + partition.spectrum.Hs = 2.0; // [m] + partition.spectrum.Tp = 8.0; // [s] + if (sea == Sea::kSpreading) { + partition.spreading.type = "cos2s"; + partition.spreading.s = 12.0; + def.n_theta = 21; + } + def.partitions.push_back(partition); + def.n_omega = 512; + return def; +} + +/// Prescribed motion of degree of freedom `dof` of body `body`: displacement +/// from the body's reference pose [m or rad] and its rate. +void Motion(int body, int dof, double t, double& displacement, double& velocity) { + const double amplitude = (dof < 3) ? 0.3 : 0.03; + const double w1 = 0.6 + 0.05 * dof + 0.03 * body; + const double w2 = 1.3 + 0.07 * dof + 0.02 * body; + const double phase = 0.4 * dof + 0.9 * body; + displacement = amplitude * (std::sin(w1 * t + phase) + 0.4 * std::sin(w2 * t + 2.0 * phase)); + velocity = amplitude * (w1 * std::cos(w1 * t + phase) + 0.4 * w2 * std::cos(w2 * t + 2.0 * phase)); +} + +void FillState(const std::vector& reference_positions, double t, SystemState& state) { + for (size_t b = 0; b < reference_positions.size(); ++b) { + BodyState& body = state.bodies[b]; + for (int dof = 0; dof < 3; ++dof) { + double displacement = 0.0; + double velocity = 0.0; + Motion(static_cast(b), dof, t, displacement, velocity); + body.position[dof] = reference_positions[b][dof] + displacement; + body.linear_velocity[dof] = velocity; + Motion(static_cast(b), dof + 3, t, displacement, velocity); + body.orientation_rpy[dof] = displacement; + body.angular_velocity[dof] = velocity; + } + } +} + +struct Timing { + double hydrostatics_us = 0.0; + double radiation_us = 0.0; + double excitation_us = 0.0; + int steps = 0; +}; + +Timing RunCase(const Case& c, const std::string& demo_root) { + HydroData data = seastack::hydro_io::H5FileInfo(demo_root + "/" + c.h5_file, c.num_bodies).ReadH5Data(); + const double kernel_length = data.GetRIRFTimeVector()[data.GetRIRFTimeVector().size() - 1]; + std::vector reference_positions; + for (int b = 0; b < c.num_bodies; ++b) reference_positions.push_back(data.GetCGVector(b).head<3>()); + + HydroModelBuilder builder; + const double depth = data.GetSimulationInfo().water_depth; + builder.FromHydroData(std::move(data)).EnableRadiation(); + if (c.smooth_kernel) builder.WithRadiationOptions(RadiationKernelProcessing::DefaultSmoothing()); + if (c.sea != Sea::kStill) { + builder.WithSeaState(MakeSeaState(c.sea, depth)).WithRampDuration(kRampDuration).EnableExcitation(); + } + if (c.mesh_file.empty()) { + builder.EnableHydrostatics(); + } else { + std::vector configs(c.num_bodies); + configs[0].model = HydrostaticsModel::kNonlinear; + configs[0].froude_krylov = FroudeKrylovModel::kNonlinear; + configs[0].mesh_file = demo_root + "/" + c.mesh_file; + builder.WithBodyHydrostatics(configs); + } + HydroModel model = builder.Build(); + HydroForces& forces = model.GetForces(); + + SystemState state; + state.bodies.resize(c.num_bodies); + long long step = 0; + auto advance = [&](int count) { + for (int i = 0; i < count; ++i, ++step) { + const double t = c.start_time + static_cast(step) * c.step; + FillState(reference_positions, t, state); + forces.Evaluate(state, t); + } + }; + + // Warm-up: until the velocity history covers the radiation kernel. + advance(static_cast(std::ceil(kernel_length / c.step)) + 20); + + const int block_steps = 400; + const int num_blocks = 5; + Timing best; + best.hydrostatics_us = best.radiation_us = best.excitation_us = std::numeric_limits::max(); + forces.SetProfilingEnabled(true); + for (int block = 0; block < num_blocks; ++block) { + forces.ResetProfileStats(); + advance(block_steps); + const HydroForcesProfileStats stats = forces.GetProfileStats(); + best.hydrostatics_us = std::min(best.hydrostatics_us, 1e6 * stats.hydrostatics_seconds / block_steps); + best.radiation_us = std::min(best.radiation_us, 1e6 * stats.radiation_seconds / block_steps); + best.excitation_us = std::min(best.excitation_us, 1e6 * stats.excitation_seconds / block_steps); + } + best.steps = block_steps * num_blocks; + return best; +} + +} // namespace + +int main(int argc, char* argv[]) { + const std::string demo_root = + (argc > 1) ? argv[1] : std::string(SEASTACK_SOURCE_DIR) + "/data/demos/run_seastack"; + const std::string filter = (argc > 2) ? argv[2] : ""; + std::printf("case,bodies,step_s,steps,hydrostatics_us,radiation_us,excitation_us\n"); + int failures = 0; + for (const Case& c : Cases()) { + if (!filter.empty() && c.name.find(filter) == std::string::npos) continue; + try { + const Timing t = RunCase(c, demo_root); + std::printf("%s,%d,%g,%d,%.3f,%.3f,%.3f\n", c.name.c_str(), c.num_bodies, c.step, t.steps, + t.hydrostatics_us, t.radiation_us, t.excitation_us); + std::fflush(stdout); + } catch (const std::exception& e) { + std::cerr << "ERROR in case " << c.name << ": " << e.what() << "\n"; + ++failures; + } + } + return failures == 0 ? 0 : 1; +} From 49f93429b6999c319ac6d2680d40d2693add6dee Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:52:18 +0000 Subject: [PATCH 03/12] Report mooring and damping time separately in run_seastack --profile. The 'Chrono Solver' line was the loop time minus hydrostatics, radiation and excitation, so it also held MoorDyn and the damping and external components. HydroForces now times damping and external components as well, the profile lists 'Mooring' and 'Damping + External' when present, and 'Chrono Solver' excludes them. --- apps/seastack/single_run.cpp | 11 ++++++++++- libs/hydro/include/seastack/hydro/hydro_forces.h | 7 ++++++- libs/hydro/src/core/hydro_forces.cpp | 2 ++ 3 files changed, 18 insertions(+), 2 deletions(-) diff --git a/apps/seastack/single_run.cpp b/apps/seastack/single_run.cpp index 5cc61a1..b019af9 100644 --- a/apps/seastack/single_run.cpp +++ b/apps/seastack/single_run.cpp @@ -1864,7 +1864,10 @@ SingleRunResult RunSingleCase(const SingleRunConfig& config) { if (hydro_forces) { auto hp = hydro_forces->GetProfileStats(); - double hydro_total = hp.hydrostatics_seconds + hp.radiation_seconds + hp.excitation_seconds; + // Everything in the loop that is not a hydrodynamic force component: the Chrono + // step itself, PTO and controller callbacks, and progress output. + double hydro_total = hp.hydrostatics_seconds + hp.radiation_seconds + hp.excitation_seconds + + hp.mooring_seconds + hp.other_seconds; double chrono_solver = std::max(0.0, prof_loop_seconds - hydro_total); auto loop_pct = [&](double s){ return seastack::infra::FormatNumber(100.0 * (s / std::max(1e-12, prof_loop_seconds)), 1) + "%"; }; @@ -1872,6 +1875,12 @@ SingleRunResult RunSingleCase(const SingleRunConfig& config) { prof_lines.push_back(seastack::infra::cli::CreateAlignedLine(" ⚓", "Hydrostatics", seastack::infra::FormatNumber(hp.hydrostatics_seconds, 4) + " s (" + loop_pct(hp.hydrostatics_seconds) + ") [" + std::to_string(hp.hydrostatics_calls) + " calls]")); prof_lines.push_back(seastack::infra::cli::CreateAlignedLine(" 💧", "Radiation Damping", seastack::infra::FormatNumber(hp.radiation_seconds, 4) + " s (" + loop_pct(hp.radiation_seconds) + ") [" + std::to_string(hp.radiation_calls) + " calls]")); prof_lines.push_back(seastack::infra::cli::CreateAlignedLine(" 🌊", "Wave Forces", seastack::infra::FormatNumber(hp.excitation_seconds, 4) + " s (" + loop_pct(hp.excitation_seconds) + ") [" + std::to_string(hp.excitation_calls) + " calls]")); + if (hp.mooring_calls > 0) { + prof_lines.push_back(seastack::infra::cli::CreateAlignedLine(" 🔗", "Mooring", seastack::infra::FormatNumber(hp.mooring_seconds, 4) + " s (" + loop_pct(hp.mooring_seconds) + ") [" + std::to_string(hp.mooring_calls) + " calls]")); + } + if (hp.other_calls > 0) { + prof_lines.push_back(seastack::infra::cli::CreateAlignedLine(" ➕", "Damping + External", seastack::infra::FormatNumber(hp.other_seconds, 4) + " s (" + loop_pct(hp.other_seconds) + ") [" + std::to_string(hp.other_calls) + " calls]")); + } } if (exporter) { diff --git a/libs/hydro/include/seastack/hydro/hydro_forces.h b/libs/hydro/include/seastack/hydro/hydro_forces.h index 4e9d4a9..f592e22 100644 --- a/libs/hydro/include/seastack/hydro/hydro_forces.h +++ b/libs/hydro/include/seastack/hydro/hydro_forces.h @@ -34,11 +34,16 @@ struct HydroForcesProfileStats { int radiation_calls = 0; int excitation_calls = 0; int mooring_calls = 0; - + /// Linear / quadratic damping and external force components. + double other_seconds = 0.0; + int other_calls = 0; + /// Reset all counters to zero void Reset() { hydrostatics_seconds = radiation_seconds = excitation_seconds = mooring_seconds = 0.0; hydrostatics_calls = radiation_calls = excitation_calls = mooring_calls = 0; + other_seconds = 0.0; + other_calls = 0; } }; diff --git a/libs/hydro/src/core/hydro_forces.cpp b/libs/hydro/src/core/hydro_forces.cpp index 44ed255..ff3d06f 100644 --- a/libs/hydro/src/core/hydro_forces.cpp +++ b/libs/hydro/src/core/hydro_forces.cpp @@ -117,6 +117,8 @@ BodyForces HydroForces::Evaluate(const SystemState& state, double time, break; case HydroComponentType::kDamping: case HydroComponentType::kExternal: + profile_stats_.other_seconds += elapsed; + profile_stats_.other_calls++; break; } } else { From 3328a3aac4c51b42601f1b19072286f6aa37aacf Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 00:52:18 +0000 Subject: [PATCH 04/12] Stop Chrono rebuilding spring visuals in headless runs. Chrono regenerates the geometry of every point-to-point visual shape on a link at each time step, drawn or not; a SPRING coil is rebuilt point by point with heap allocation. With --nogui this took 10% of the loop for RM3 (one PTO spring) and 22% for 5SA regular waves (16 ram springs). RemoveLinkVisualShapes() clears the link shapes; run_seastack calls it for headless runs once the replay scene is written, and the 5SA demos and benchmark call it when no viewer is requested. VizExtractor reads a link's shape once and afterwards uses only its end points, so replay data is unchanged. Results are bit-identical. --- .../seastack/adapters/chrono/viz_extractor.h | 14 +++++++ adapters/chrono/src/viz_extractor.cpp | 11 +++++ apps/seastack/single_run.cpp | 9 ++++ demos/5sa/demo_5sa_bimodal.cpp | 7 ++++ demos/5sa/demo_5sa_spreading.cpp | 7 ++++ .../5sa/test_bench_5sa_spreading.cpp | 5 +++ tests/unit/test_viz_extractor.cpp | 41 +++++++++++++++++++ 7 files changed, 94 insertions(+) diff --git a/adapters/chrono/include/seastack/adapters/chrono/viz_extractor.h b/adapters/chrono/include/seastack/adapters/chrono/viz_extractor.h index b0a3832..55bafbe 100644 --- a/adapters/chrono/include/seastack/adapters/chrono/viz_extractor.h +++ b/adapters/chrono/include/seastack/adapters/chrono/viz_extractor.h @@ -96,4 +96,18 @@ bool IsWaterSurfaceBody(const ::chrono::ChBody& body); /// entry is a short description for the user; empty = everything is drawable. std::vector FindUndrawableItems(const ::chrono::ChSystem& system); +/// Remove the visual shapes of every link in `system`. Returns the number of +/// links that had shapes. +/// +/// For runs in which nothing draws the Chrono system (headless runs). Chrono +/// rebuilds the geometry of every point-to-point shape on a link at each time +/// step, whether or not it is drawn; a SPRING coil is rebuilt point by point. +/// Removing the shapes stops that work and does not change the simulation. +/// +/// Call it after every VizExtractor that should describe these links has been +/// constructed: an extractor reads a link's SEGMENT or SPRING shape once, to +/// describe the scene, and afterwards captures only the link's end points and +/// force. Body shapes are kept; Chrono does not rebuild them. +int RemoveLinkVisualShapes(::chrono::ChSystem& system); + } // namespace seastack::chrono diff --git a/adapters/chrono/src/viz_extractor.cpp b/adapters/chrono/src/viz_extractor.cpp index 0240cd8..9122396 100644 --- a/adapters/chrono/src/viz_extractor.cpp +++ b/adapters/chrono/src/viz_extractor.cpp @@ -271,6 +271,17 @@ std::vector FindUndrawableItems(const ::chrono::ChSystem& system) { return items; } +int RemoveLinkVisualShapes(::chrono::ChSystem& system) { + int links_changed = 0; + for (const auto& link : system.GetLinks()) { + if (link && HasVisualShapes(*link)) { + link->GetVisualModel()->Clear(); + ++links_changed; + } + } + return links_changed; +} + VizExtractor::VizExtractor(::chrono::ChSystem* system, viz::MooringVizProvider mooring) : system_(system), mooring_(std::move(mooring)) { if (system_) { diff --git a/apps/seastack/single_run.cpp b/apps/seastack/single_run.cpp index b019af9..c5013da 100644 --- a/apps/seastack/single_run.cpp +++ b/apps/seastack/single_run.cpp @@ -1435,6 +1435,15 @@ SingleRunResult RunSingleCase(const SingleRunConfig& config) { double active_wall_s = 0.0; if (nogui) { + // Nothing draws the Chrono system in a headless run, and the replay + // scene above already holds the description of every spring and + // cable. Without this, Chrono rebuilds each spring coil every step. + const int links_without_shapes = seastack::chrono::RemoveLinkVisualShapes(*system); + if (links_without_shapes > 0) { + seastack::infra::debug::LogDebug("Headless run: removed the visual shapes of " + + std::to_string(links_without_shapes) + " link(s)"); + } + const double end_time_bound = timing.HeadlessEndTime(); if (!timing.end_time_explicit) { seastack::infra::cli::LogInfo("simulation.end_time is not set in " + config.simulation_file + diff --git a/demos/5sa/demo_5sa_bimodal.cpp b/demos/5sa/demo_5sa_bimodal.cpp index 57cc480..446f7c0 100644 --- a/demos/5sa/demo_5sa_bimodal.cpp +++ b/demos/5sa/demo_5sa_bimodal.cpp @@ -22,6 +22,8 @@ #include #include +#include + #include "five_sa_model_setup.h" using namespace chrono; @@ -109,6 +111,11 @@ int main(int argc, char* argv[]) { }); #endif + // Without a viewer nothing draws the ram springs; stop Chrono rebuilding their coils every step. + if (!visualizationOn) { + seastack::chrono::RemoveLinkVisualShapes(system); + } + std::vector time_vector; std::vector body3_heave; std::vector body3_sway; diff --git a/demos/5sa/demo_5sa_spreading.cpp b/demos/5sa/demo_5sa_spreading.cpp index 2bc21c7..c3a114f 100644 --- a/demos/5sa/demo_5sa_spreading.cpp +++ b/demos/5sa/demo_5sa_spreading.cpp @@ -22,6 +22,8 @@ #include #include +#include + #include "five_sa_model_setup.h" using namespace chrono; @@ -97,6 +99,11 @@ int main(int argc, char* argv[]) { }); #endif + // Without a viewer nothing draws the ram springs; stop Chrono rebuilding their coils every step. + if (!visualizationOn) { + seastack::chrono::RemoveLinkVisualShapes(system); + } + std::vector time_vector; std::vector body3_heave; diff --git a/tests/benchmark/5sa/test_bench_5sa_spreading.cpp b/tests/benchmark/5sa/test_bench_5sa_spreading.cpp index 059b2df..50233b9 100644 --- a/tests/benchmark/5sa/test_bench_5sa_spreading.cpp +++ b/tests/benchmark/5sa/test_bench_5sa_spreading.cpp @@ -23,6 +23,8 @@ #include #include +#include + #include "five_sa_model_setup.h" using namespace chrono; @@ -106,6 +108,9 @@ int main(int argc, char* argv[]) { hydro.AddWaves(waves); hydro.SetProfilingEnabled(true); + // Headless: nothing draws the ram springs, so do not let Chrono rebuild their coils every step. + seastack::chrono::RemoveLinkVisualShapes(system); + result.setup_wall_s = timer.StopSeconds(); timer.Start(); diff --git a/tests/unit/test_viz_extractor.cpp b/tests/unit/test_viz_extractor.cpp index bed501d..5015ae0 100644 --- a/tests/unit/test_viz_extractor.cpp +++ b/tests/unit/test_viz_extractor.cpp @@ -231,6 +231,47 @@ int main() { TEST_ASSERT(seastack::chrono::FindUndrawableItems(dist_sys).empty(), "distance SEGMENT is drawable"); } + // Headless runs remove link visual shapes after the scene is described: + // the extractor keeps the spring's description and still tracks its ends. + { + ::chrono::ChSystemNSC spring_sys; + auto a = chrono_types::make_shared<::chrono::ChBody>(); + a->SetPos({0.0, 0.0, 5.0}); + a->SetFixed(true); + a->AddVisualShape(chrono_types::make_shared<::chrono::ChVisualShapeSphere>(0.5)); + spring_sys.AddBody(a); + auto b = chrono_types::make_shared<::chrono::ChBody>(); + b->SetFixed(true); + spring_sys.AddBody(b); + + auto pto = chrono_types::make_shared<::chrono::ChLinkTSDA>(); + pto->Initialize(a, b, false, {0.0, 0.0, 5.0}, {0.0, 0.0, 0.0}); + pto->AddVisualShape(chrono_types::make_shared<::chrono::ChVisualShapeSpring>(0.3, 80, 15.0)); + spring_sys.AddLink(pto); + auto bare = chrono_types::make_shared<::chrono::ChLinkTSDA>(); + bare->Initialize(a, b, false, {1.0, 0.0, 5.0}, {1.0, 0.0, 5.0}); + spring_sys.AddLink(bare); + + VizExtractor spring_ex(&spring_sys); + TEST_ASSERT(spring_ex.Scene().cable_lines.size() == 1 && + spring_ex.Scene().cable_lines[0].kind == CableKind::kSpring, + "SPRING glyph described before removal"); + + TEST_ASSERT(seastack::chrono::RemoveLinkVisualShapes(spring_sys) == 1, "one link had visual shapes"); + TEST_ASSERT(pto->GetVisualModel() && pto->GetVisualModel()->GetNumShapes() == 0, "link shapes removed"); + TEST_ASSERT(a->GetVisualModel() && a->GetVisualModel()->GetNumShapes() == 1, "body shapes kept"); + TEST_ASSERT(seastack::chrono::RemoveLinkVisualShapes(spring_sys) == 0, "nothing left to remove"); + + TEST_ASSERT(spring_ex.Scene().cable_lines.size() == 1 && + spring_ex.Scene().cable_lines[0].kind == CableKind::kSpring && + spring_ex.Scene().cable_lines[0].spring_turns == 15.0, + "scene keeps the spring description"); + pto->Initialize(a, b, false, {0.0, 0.0, 5.0}, {0.0, 0.0, -1.0}); + const VizFrame spring_frame = spring_ex.Capture(1); + TEST_ASSERT(IsConsistent(spring_ex.Scene(), spring_frame), "frame matches scene after removal"); + TEST_NEAR(spring_frame.cable_lines[0].point2[2], -1.0, 1e-12, "spring end still tracked after removal"); + } + // Undrawable content is reported so the GUI can fall back to the Chrono viewer. TEST_ASSERT(seastack::chrono::FindUndrawableItems(system).empty(), "box, sphere and mesh are drawable"); { From 8eb33ff0b80db91b2cea8e7e9031522ec37fe4f6 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:23:28 +0000 Subject: [PATCH 05/12] Evaluate the radiation convolution as dot products over a contiguous velocity record. The convolution term of the Cummins equation is now computed with one dot product per non-zero kernel K_ij against the lagged velocity of degree of freedom j. Trapezoid weights are folded into the stored kernel, identically zero kernels and degrees of freedom that have not moved are skipped, and the velocity record (new class VelocityHistory) is a contiguous array in time order. When the recorded samples coincide with the lag grid the lagged velocities are read directly from the record; otherwise they are interpolated linearly as before. The quadrature is unchanged; results differ from the previous implementation by rounding only. The kernel runs on one thread and gives the same result for any OMP_NUM_THREADS. Interface: RadiationRirfConvolution::ComputeForces(callback, kernel) is replaced by SetKernel() and ComputeForces(). The lag grid must be non-negative and strictly increasing. A time earlier than the newest sample (a repeated integrator step) discards the samples at or after it, with a warning reported once; an equal time still throws. --- libs/hydro/CMakeLists.txt | 1 + .../force_components/radiation_component.h | 20 +- .../radiation/radiation_rirf_convolution.h | 193 ++++--- .../hydro/radiation/velocity_history.h | 91 ++++ .../force_components/radiation_component.cpp | 65 ++- .../radiation/radiation_rirf_convolution.cpp | 491 ++++++++++-------- libs/hydro/src/radiation/velocity_history.cpp | 96 ++++ .../unit/test_radiation_rirf_convolution.cpp | 128 ++++- 8 files changed, 729 insertions(+), 356 deletions(-) create mode 100644 libs/hydro/include/seastack/hydro/radiation/velocity_history.h create mode 100644 libs/hydro/src/radiation/velocity_history.cpp diff --git a/libs/hydro/CMakeLists.txt b/libs/hydro/CMakeLists.txt index a8fa660..ad9a9d2 100644 --- a/libs/hydro/CMakeLists.txt +++ b/libs/hydro/CMakeLists.txt @@ -15,6 +15,7 @@ add_library(seastack_hydro STATIC src/waves/wave_utilities.cpp src/radiation/radiation_rirf_processing.cpp src/radiation/radiation_rirf_convolution.cpp + src/radiation/velocity_history.cpp src/radiation/radiation_ss_model.cpp src/radiation/radiation_ss_fitter.cpp src/radiation/bem_frequency_match.cpp diff --git a/libs/hydro/include/seastack/hydro/force_components/radiation_component.h b/libs/hydro/include/seastack/hydro/force_components/radiation_component.h index 17ab593..606b092 100644 --- a/libs/hydro/include/seastack/hydro/force_components/radiation_component.h +++ b/libs/hydro/include/seastack/hydro/force_components/radiation_component.h @@ -25,6 +25,12 @@ class HydroData; * Computes radiation damping forces via convolution of RIRF kernels * with body velocity history. Supports optional kernel processing * (smoothing and/or tapering) via RadiationKernelProcessing. + * + * The kernel is taken from the HydroData in dimensional units, processed if + * requested, and handed to RadiationRirfConvolution once, on the first call + * to Compute(). Each call then records the body velocities in each body's + * heading frame (heading_frame.h), evaluates the convolution and subtracts + * the result, rotated back to the world frame, from the body forces. */ class RadiationComponent : public IHydroForceComponent { public: @@ -63,15 +69,15 @@ class RadiationComponent : public IHydroForceComponent { std::unique_ptr convolution_; Eigen::VectorXd rirf_time_vector_; Eigen::VectorXd rirf_width_vector_; - - bool rirf_processed_ready_ = false; - std::vector> rirf_processed_; - + + bool kernel_ready_ = false; + // Reusable buffer for body velocities to avoid per-timestep allocation std::vector> body_velocities_buffer_; - - void EnsureProcessedRIRF(); - double GetRIRFval(int row, int col, int st); + + /// Build the kernel (processed if requested) and give it to the + /// convolution. Done once, on the first Compute(). + void EnsureKernel(); }; } // namespace seastack::hydro diff --git a/libs/hydro/include/seastack/hydro/radiation/radiation_rirf_convolution.h b/libs/hydro/include/seastack/hydro/radiation/radiation_rirf_convolution.h index 9cac0bd..56b8015 100644 --- a/libs/hydro/include/seastack/hydro/radiation/radiation_rirf_convolution.h +++ b/libs/hydro/include/seastack/hydro/radiation/radiation_rirf_convolution.h @@ -1,98 +1,159 @@ /********************************************************************* * @file radiation_rirf_convolution.h - * @brief RIRF-based radiation damping via velocity history convolution. + * @brief Radiation force by convolution of the retardation kernel with + * the velocity history. *********************************************************************/ #ifndef SEASTACK_HYDRO_RADIATION_RIRF_CONVOLUTION_H #define SEASTACK_HYDRO_RADIATION_RIRF_CONVOLUTION_H -#include -#include -#include #include #include #include +#include + namespace seastack::hydro { /** - * @brief RIRF-based radiation damping convolution. - * - * Manages velocity history buffers and performs convolution of RIRF kernels - * with body velocity history to compute radiation damping forces. + * @brief Convolution integral of the Cummins equation. + * + * With N bodies there are 6N degrees of freedom (surge, sway, heave, roll, + * pitch, yaw of each body). The radiation force in degree of freedom i is + * + * F_i(t) = sum_j integral_0^T K_ij(tau) v_j(t - tau) dtau + * + * where K_ij is the retardation kernel (radiation impulse response + * function) from the BEM data and v_j the velocity of degree of freedom j. + * The kernel is given on a grid of lags tau_k, k = 0 .. S-1, and the + * integral is evaluated with the trapezoid rule on that grid: + * + * F_i(t) = sum_j sum_k K_ij(tau_k) w_k v_j(t - tau_k) + * + * with w_k the trapezoid weights. The number of terms per call is therefore + * (6N)^2 S whatever the time step of the simulation. + * + * Velocities are recorded once per time step. v_j(t - tau_k) is the + * recorded sample at that time when there is one, and is interpolated + * linearly between the two neighbouring samples otherwise. A lag reaching + * back before the first recorded sample is left out (start of a run). + * + * How it is evaluated. For each pair (i, j) the products K_ij(tau_k) w_k + * are stored once as one array, ordered from the largest lag to lag zero. + * The lagged velocities of j are an array in the same order, i.e. in time + * order. The sum over k is then one dot product of two arrays: + * + * kernel array of (i, j) : K w at tau_{S-1} ... K w at tau_1 K w at tau_0 + * velocities of j : v_j(t - tau_{S-1}) ... v_j(t - tau_1) v_j(t) + * + * When the time step is constant and the lag spacing is a whole multiple of + * it (commonly equal to it), the lagged velocities are recorded samples and + * no interpolation is done. + * + * The result does not depend on the number of threads: the evaluation is + * serial. + * + * Reference: Cummins, W.E. (1962) "The Impulse Response Function and Ship + * Motions", Schiffstechnik, 9, 101-109. */ class RadiationRirfConvolution { -public: + public: /** - * @brief Constructor. - * - * @param num_bodies Number of bodies in the system - * @param rirf_steps Number of time steps in RIRF - * @param rirf_time_vector Time vector for RIRF - * @param rirf_width_vector Width vector for RIRF (for trapezoidal integration) + * @param num_bodies Number of bodies N (> 0). + * @param rirf_steps Number of lags S (> 0). + * @param rirf_time_vector Lags tau_k [s], S values, non-negative and increasing. + * @param rirf_width_vector Trapezoid weights w_k [s], S values + * (ComputeRirfWidthVector() in hydro_setup_helpers.h). */ - RadiationRirfConvolution( - int num_bodies, - int rirf_steps, - const Eigen::VectorXd& rirf_time_vector, - const Eigen::VectorXd& rirf_width_vector); + RadiationRirfConvolution(int num_bodies, + int rirf_steps, + const Eigen::VectorXd& rirf_time_vector, + const Eigen::VectorXd& rirf_width_vector); /** - * @brief Record current velocities and update history buffers. - * - * @param simulation_time Current simulation time - * @param body_velocities Velocities for all bodies [body][dof] where dof is 6-DOF + * @brief Set the retardation kernel. Call once before ComputeForces(). + * + * @param kernel_per_body One tensor per body, holding that body's six rows + * of K: kernel_per_body[b](i, j, k) = K at row 6b + i, column j, + * lag tau_k, in dimensional units [kg/s, kg.m/s or kg.m^2/s]. Each + * tensor is 6 x 6N x (S or more); lags beyond S are not used. */ - void RecordVelocities(double simulation_time, - const std::vector>& body_velocities); + void SetKernel(const std::vector>& kernel_per_body); + + /// True once SetKernel() has been called. + bool HasKernel() const { return has_kernel_; } /** - * @brief Compute radiation damping forces via RIRF convolution. - * - * @param get_rirf_val Function to get RIRF value: (row, col, step) -> value - * For Baseline mode: raw RIRF from H5 - * For TaperedDirect mode: processed RIRF tensor - * @param processed_rirf Optional processed RIRF tensors (for TaperedDirect mode) - * If provided, get_rirf_val is ignored and processed_rirf is used - * - * @return Radiation damping force vector [6N] for N bodies + * @brief Record the velocities at a new time. + * + * @param simulation_time Time of the sample [s]. If it is earlier than + * the last recorded time (the integrator repeated a step), the + * samples at or after it are discarded first. + * @param body_velocities [body][6] linear then angular velocity of each + * body [m/s, rad/s], in the frame the kernel is defined in. + * @throws std::runtime_error if simulation_time equals the last recorded time. */ - std::vector ComputeForces( - std::function get_rirf_val, - const std::vector>* processed_rirf = nullptr); + void RecordVelocities(double simulation_time, const std::vector>& body_velocities); + + /** + * @brief Radiation force at the time of the last RecordVelocities(). + * + * @return 6N values F_i [N or N.m], ordered by body, then surge .. yaw. + * The reference stays valid until the next call. All zeros while + * fewer than two samples are recorded. + */ + const std::vector& ComputeForces(); + + private: + /// One retained kernel: force degree of freedom `row`, velocity degree of freedom `column`. + struct KernelPair { + int row; + int column; + }; + + /// Fill lagged_velocity_ for every moving degree of freedom and return the + /// number of lags L that the record reaches back to (lags 0 .. L-1). + int PrepareLaggedVelocities(); + + /// If the recorded samples fall on the lags, the number of samples per lag + /// spacing (>= 1) and the number of lags covered; 0 if they do not. + int SamplesPerLagSpacing(int& lags_covered) const; + + /// Lagged velocities by linear interpolation in the record. Returns the + /// number of lags covered. + int InterpolateLaggedVelocities(); -private: int num_bodies_; - int rirf_steps_; - int total_dofs_; - Eigen::VectorXd rirf_time_vector_; - Eigen::VectorXd rirf_width_vector_; - - // Velocity history buffers (multibody: one per body) - // Using deque for O(1) push_front/pop_back operations - std::vector>> velocity_history_; - std::deque time_history_; - - // Reusable buffer for force output to avoid per-timestep allocation - std::vector force_radiation_damping_buffer_; - - // Helper functions - void PruneHistory(double history_min_time); - static void InterpolateVelocity6D( - const std::deque>& velocity_history_body, - size_t newer_index, - double query_time, - double older_time, - double newer_time, - std::array& out_velocity); - static bool AdvanceToBracket( - const std::deque& time_history, - size_t& index, - double query_time); + int num_lags_; ///< S + int total_dofs_; ///< 6N + Eigen::VectorXd lag_times_; ///< tau_k [s] + Eigen::VectorXd lag_weights_; ///< w_k [s] + + bool has_kernel_ = false; + /// Retained kernels (those not identically zero), ordered by column. + std::vector kernel_pairs_; + /// weighted_kernel_(q, p) = K_ij(tau_k) w_k for pair p = (i, j), with + /// q = S - 1 - k: each column runs from the largest lag to lag zero. + Eigen::MatrixXd weighted_kernel_; + + VelocityHistory history_; + std::vector newest_sample_; ///< Scratch for RecordVelocities(), 6N values. + bool warned_time_reversal_ = false; + + /// Where the lagged velocities of each degree of freedom are for the + /// current call (L values in time order): in the record itself, in + /// lagged_buffer_, or nullptr for a degree of freedom at rest. + std::vector lagged_velocity_; + Eigen::MatrixXd lagged_buffer_; ///< S x 6N + /// Interpolation data per lag: index in the record of the sample at or + /// before t - tau_k, and the weight of that sample (1 = that sample alone). + std::vector older_sample_; + std::vector older_weight_; + + std::vector force_; ///< Result, 6N values. }; } // namespace seastack::hydro #endif // SEASTACK_HYDRO_RADIATION_RIRF_CONVOLUTION_H - diff --git a/libs/hydro/include/seastack/hydro/radiation/velocity_history.h b/libs/hydro/include/seastack/hydro/radiation/velocity_history.h new file mode 100644 index 0000000..e5b75c9 --- /dev/null +++ b/libs/hydro/include/seastack/hydro/radiation/velocity_history.h @@ -0,0 +1,91 @@ +/********************************************************************* + * @file velocity_history.h + * @brief Recorded body velocities for the radiation convolution. + *********************************************************************/ + +#ifndef SEASTACK_HYDRO_RADIATION_VELOCITY_HISTORY_H +#define SEASTACK_HYDRO_RADIATION_VELOCITY_HISTORY_H + +#include +#include + +namespace seastack::hydro { + +/** + * @brief Velocity samples of every degree of freedom, in time order. + * + * The radiation convolution needs the velocity of each degree of freedom + * over the length of the retardation kernel. This class keeps those + * samples so that the convolution can read them as plain arrays: + * + * Times() : t[0] t[1] ... t[Size()-1] oldest first + * Column(j) : v_j[0] v_j[1] ... v_j[Size()-1] same order + * + * Each column is one degree of freedom (6 per body: surge, sway, heave, + * roll, pitch, yaw) and is stored contiguously, so a sum over past samples + * of one degree of freedom runs through memory in order. + * + * New samples are appended at the end. Samples older than the kernel are + * dropped from the front with DropOlderThan(). The arrays are moved back to + * the start of their storage only when the storage is full, so appending + * and dropping cost a fixed amount per sample on average. + */ +class VelocityHistory { + public: + /// @param num_columns Number of degrees of freedom (6 per body), > 0. + explicit VelocityHistory(int num_columns); + + /// Number of degrees of freedom. + int NumColumns() const { return num_columns_; } + + /// Number of samples held. + int Size() const { return size_; } + + /// Add a sample at the end. + /// @param time Sample time [s]; must be later than NewestTime(). + /// @param velocities NumColumns() values [m/s or rad/s]. + void Append(double time, const double* velocities); + + /// Drop the oldest samples that are no longer needed to evaluate the + /// velocity at `time` or later. The last sample taken before `time` is + /// kept, so that `time` stays between two held samples. + void DropOlderThan(double time); + + /// Drop every sample taken at `time` or later. Used when the integrator + /// repeats a step and time goes backwards. + void DropFrom(double time); + + /// Sample times [s], Size() values, oldest first. + const double* Times() const { return times_.data() + first_; } + + /// Samples of one degree of freedom, Size() values, oldest first. + const double* Column(int column) const { return values_.data() + Offset(column) + first_; } + + /// Time of the newest sample [s]. Size() must be > 0. + double NewestTime() const { return times_[first_ + size_ - 1]; } + + /// True if every held sample of this degree of freedom is exactly zero. + bool ColumnIsZero(int column) const { return nonzero_samples_[column] == 0; } + + private: + /// Start of a column's storage in values_. + std::size_t Offset(int column) const { + return static_cast(column) * static_cast(capacity_); + } + void DropOldest(); + /// Make room for one more sample: move the held samples to the start of + /// the storage, enlarging it when it is more than half full. + void MakeRoom(); + + int num_columns_; + int capacity_ = 0; ///< Samples each array can hold. + int first_ = 0; ///< Position of the oldest held sample in each array. + int size_ = 0; ///< Number of held samples. + std::vector times_; ///< capacity_ values. + std::vector values_; ///< num_columns_ arrays of capacity_ values, one after another. + std::vector nonzero_samples_; ///< Per column: held samples that are not exactly zero. +}; + +} // namespace seastack::hydro + +#endif // SEASTACK_HYDRO_RADIATION_VELOCITY_HISTORY_H diff --git a/libs/hydro/src/force_components/radiation_component.cpp b/libs/hydro/src/force_components/radiation_component.cpp index ab4d6c7..723f000 100644 --- a/libs/hydro/src/force_components/radiation_component.cpp +++ b/libs/hydro/src/force_components/radiation_component.cpp @@ -29,8 +29,7 @@ RadiationComponent::RadiationComponent( convolution_(std::make_unique( num_bodies, rirf_steps, rirf_time_vector, rirf_width_vector)), rirf_time_vector_(rirf_time_vector), - rirf_width_vector_(rirf_width_vector), - rirf_processed_ready_(false) { + rirf_width_vector_(rirf_width_vector) { // Require at least one body for radiation damping computation. if (num_bodies_ <= 0) { throw std::invalid_argument( @@ -63,39 +62,43 @@ RadiationComponent::RadiationComponent( } } -void RadiationComponent::EnsureProcessedRIRF() { - if (rirf_processed_ready_) { +void RadiationComponent::EnsureKernel() { + if (kernel_ready_) { return; } const int steps = static_cast(rirf_time_vector_.size()); + const int total_dofs = kDofPerBody * num_bodies_; + if (file_info_.GetRIRFDims(2) < steps) { + throw std::out_of_range("RadiationComponent: the RIRF in the hydro data has " + + std::to_string(file_info_.GetRIRFDims(2)) + " time samples, fewer than the " + + std::to_string(steps) + " requested"); + } - auto get_rirf_val = [this](int body, int row_dof, int col, int step) -> double { + // Kernel in dimensional units (HydroData applies rho). + auto stored_kernel = [this](int body, int row_dof, int col, int step) -> double { return file_info_.GetRIRFVal(body, row_dof, col, step); }; - rirf_processed_ = ProcessRirfKernels( - num_bodies_, steps, rirf_time_vector_, get_rirf_val, kernel_processing_, diagnostics_output_dir_); - - rirf_processed_ready_ = true; -} - -double RadiationComponent::GetRIRFval(int row, int col, int st) { - if (row < 0 || row >= kDofPerBody * num_bodies_ || col < 0 || col >= kDofPerBody * num_bodies_ || st < 0 || - st >= file_info_.GetRIRFDims(2)) { - throw std::out_of_range("rirfval index out of range in RadiationComponent"); - } - - int body_index = row / kDofPerBody; - int row_dof = row % kDofPerBody; - + std::vector> kernel; if (kernel_processing_.RequiresProcessing()) { - EnsureProcessedRIRF(); - const auto& tensor = rirf_processed_[body_index]; - return tensor(row_dof, col, st); + kernel = ProcessRirfKernels(num_bodies_, steps, rirf_time_vector_, stored_kernel, kernel_processing_, + diagnostics_output_dir_); + } else { + kernel.assign(num_bodies_, Eigen::Tensor(kDofPerBody, total_dofs, steps)); + for (int body = 0; body < num_bodies_; ++body) { + for (int step = 0; step < steps; ++step) { + for (int col = 0; col < total_dofs; ++col) { + for (int row_dof = 0; row_dof < kDofPerBody; ++row_dof) { + kernel[body](row_dof, col, step) = stored_kernel(body, row_dof, col, step); + } + } + } + } } - return file_info_.GetRIRFVal(body_index, row_dof, col, st); + convolution_->SetKernel(kernel); + kernel_ready_ = true; } void RadiationComponent::Compute(const SystemState& state, @@ -113,9 +116,7 @@ void RadiationComponent::Compute(const SystemState& state, std::to_string(num_bodies_) + ", got " + std::to_string(inout_forces.size()) + ")"); } - if (kernel_processing_.RequiresProcessing()) { - EnsureProcessedRIRF(); - } + EnsureKernel(); // Prepare body velocities for recording (use member buffer), in each // body's heading frame (heading_frame.h). @@ -133,15 +134,7 @@ void RadiationComponent::Compute(const SystemState& state, // Record velocities in the convolution module convolution_->RecordVelocities(time, body_velocities_buffer_); - auto get_rirf_val = [this](int row, int col, int step) -> double { - return GetRIRFval(row, col, step); - }; - - const std::vector>* processed_rirf = - (kernel_processing_.RequiresProcessing() && rirf_processed_ready_) - ? &rirf_processed_ : nullptr; - - std::vector force_flat = convolution_->ComputeForces(get_rirf_val, processed_rirf); + const std::vector& force_flat = convolution_->ComputeForces(); // Map flat vector to per-body forces and add to inout_forces. // Radiation damping opposes motion, so we SUBTRACT (add with negative sign). diff --git a/libs/hydro/src/radiation/radiation_rirf_convolution.cpp b/libs/hydro/src/radiation/radiation_rirf_convolution.cpp index 56b870a..7ec9bb6 100644 --- a/libs/hydro/src/radiation/radiation_rirf_convolution.cpp +++ b/libs/hydro/src/radiation/radiation_rirf_convolution.cpp @@ -1,291 +1,324 @@ /********************************************************************* * @file radiation_rirf_convolution.cpp - * @brief RIRF-based radiation damping convolution implementation. + * @brief Radiation force by convolution of the retardation kernel with + * the velocity history. * - * Implements the Cummins equation radiation force term: - * F_rad(t) = -A_inf * x_ddot(t) - integral_0^t K(t-tau) * x_dot(tau) dtau - * where K is the retardation (impulse response) function. - * See: Cummins, W.E. (1962) "The Impulse Response Function and Ship Motions", - * Schiffstechnik, 9, 101-109. + * Evaluates the convolution term of the Cummins equation, + * F_i(t) = sum_j sum_k K_ij(tau_k) w_k v_j(t - tau_k), + * as described in radiation_rirf_convolution.h. *********************************************************************/ #include + #include +#include #include -#include +#include #include +#include + +namespace seastack::hydro { -#include -#include +namespace { -#ifdef _OPENMP -#include -#endif +/// A recorded sample stands for the velocity at t - tau_k without +/// interpolation when its time differs from t - tau_k by less than this +/// fraction of the time step. Sample times that come from adding a constant +/// step differ from the lag times by rounding only, far below this. +constexpr double kSampleTimeTolerance = 1.0e-6; -namespace seastack::hydro { +} // namespace -RadiationRirfConvolution::RadiationRirfConvolution( - int num_bodies, - int rirf_steps, - const Eigen::VectorXd& rirf_time_vector, - const Eigen::VectorXd& rirf_width_vector) +RadiationRirfConvolution::RadiationRirfConvolution(int num_bodies, + int rirf_steps, + const Eigen::VectorXd& rirf_time_vector, + const Eigen::VectorXd& rirf_width_vector) : num_bodies_(num_bodies), - rirf_steps_(rirf_steps), - total_dofs_(kDofPerBody * num_bodies_), - rirf_time_vector_(rirf_time_vector), - rirf_width_vector_(rirf_width_vector) { - // Validate configuration parameters. + num_lags_(rirf_steps), + total_dofs_(kDofPerBody * std::max(num_bodies, 1)), + lag_times_(rirf_time_vector), + lag_weights_(rirf_width_vector), + history_(total_dofs_) { if (num_bodies_ <= 0) { - throw std::invalid_argument( - "RadiationRirfConvolution: num_bodies must be > 0 (got " + - std::to_string(num_bodies_) + ")"); + throw std::invalid_argument("RadiationRirfConvolution: num_bodies must be > 0 (got " + + std::to_string(num_bodies_) + ")"); } - if (rirf_steps_ <= 0) { - throw std::invalid_argument( - "RadiationRirfConvolution: rirf_steps must be > 0 (got " + - std::to_string(rirf_steps_) + ")"); + if (num_lags_ <= 0) { + throw std::invalid_argument("RadiationRirfConvolution: rirf_steps must be > 0 (got " + + std::to_string(num_lags_) + ")"); } - if (rirf_time_vector_.size() == 0) { - throw std::invalid_argument( - "RadiationRirfConvolution: rirf_time_vector is empty"); + if (lag_times_.size() != num_lags_) { + throw std::invalid_argument("RadiationRirfConvolution: rirf_time_vector has " + + std::to_string(lag_times_.size()) + " values, expected rirf_steps = " + + std::to_string(num_lags_)); } - if (rirf_width_vector_.size() == 0) { - throw std::invalid_argument( - "RadiationRirfConvolution: rirf_width_vector is empty"); + if (lag_weights_.size() != num_lags_) { + throw std::invalid_argument("RadiationRirfConvolution: rirf_width_vector has " + + std::to_string(lag_weights_.size()) + " values, expected rirf_steps = " + + std::to_string(num_lags_)); + } + if (lag_times_[0] < 0.0) { + throw std::invalid_argument("RadiationRirfConvolution: the first lag is negative (" + + std::to_string(lag_times_[0]) + " s)"); + } + for (int k = 1; k < num_lags_; ++k) { + if (!(lag_times_[k] > lag_times_[k - 1])) { + throw std::invalid_argument("RadiationRirfConvolution: rirf_time_vector must increase (lag " + + std::to_string(k) + " is " + std::to_string(lag_times_[k]) + " s after " + + std::to_string(lag_times_[k - 1]) + " s)"); + } } - velocity_history_.resize(num_bodies_); - - // Pre-allocate force output buffer - force_radiation_damping_buffer_.resize(total_dofs_); + newest_sample_.resize(total_dofs_); + lagged_velocity_.assign(total_dofs_, nullptr); + lagged_buffer_.setZero(num_lags_, total_dofs_); + older_sample_.resize(num_lags_); + older_weight_.resize(num_lags_); + force_.assign(total_dofs_, 0.0); } -void RadiationRirfConvolution::RecordVelocities( - double simulation_time, - const std::vector>& body_velocities) { - - // Prevent duplicate computation within same step - if (!time_history_.empty() && simulation_time == time_history_.front()) { - throw std::runtime_error("Tried to compute the radiation damping convolution twice within the same time step!"); +void RadiationRirfConvolution::SetKernel(const std::vector>& kernel_per_body) { + if (static_cast(kernel_per_body.size()) != num_bodies_) { + throw std::invalid_argument("RadiationRirfConvolution::SetKernel: got kernels for " + + std::to_string(kernel_per_body.size()) + " bodies, expected " + + std::to_string(num_bodies_)); } - - // Record current time at the front (most recent first) - O(1) with deque - time_history_.push_front(simulation_time); - - // Record current velocities per body at the front (matching time_history_ ordering) - O(1) with deque for (int b = 0; b < num_bodies_; ++b) { - auto& velocity_history_body = velocity_history_[b]; - velocity_history_body.push_front(body_velocities[b]); + const auto& k = kernel_per_body[b]; + if (k.dimension(0) != kDofPerBody || k.dimension(1) != total_dofs_ || k.dimension(2) < num_lags_) { + throw std::invalid_argument( + "RadiationRirfConvolution::SetKernel: kernel of body " + std::to_string(b + 1) + " is " + + std::to_string(k.dimension(0)) + " x " + std::to_string(k.dimension(1)) + " x " + + std::to_string(k.dimension(2)) + ", expected 6 x " + std::to_string(total_dofs_) + " x " + + std::to_string(num_lags_) + " (or more lags)"); + } } - - // Prune history older than the max RIRF time span - const int rirf_last_index = static_cast(rirf_time_vector_.size()) - 1; - const double history_min_time = simulation_time - (rirf_last_index >= 0 ? rirf_time_vector_[rirf_last_index] : 0.0); - PruneHistory(history_min_time); -} - -void RadiationRirfConvolution::PruneHistory(double history_min_time) { - while (time_history_.size() > 1 && time_history_[time_history_.size() - 2] < history_min_time) { - time_history_.pop_back(); - for (int b = 0; b < num_bodies_; ++b) { - auto& velocity_history_body = velocity_history_[b]; - if (!velocity_history_body.empty()) { - velocity_history_body.pop_back(); + auto kernel_value = [&kernel_per_body](int row, int column, int lag) { + return kernel_per_body[row / kDofPerBody](row % kDofPerBody, column, lag); + }; + + // Keep the kernels that are not identically zero. Ordering them by column + // means consecutive dot products use the same velocity array. + kernel_pairs_.clear(); + for (int column = 0; column < total_dofs_; ++column) { + for (int row = 0; row < total_dofs_; ++row) { + bool any_nonzero = false; + for (int lag = 0; lag < num_lags_ && !any_nonzero; ++lag) { + any_nonzero = kernel_value(row, column, lag) != 0.0; } + if (any_nonzero) { + kernel_pairs_.push_back({row, column}); + } + } + } + + // Fold the trapezoid weight into the kernel and store each pair from the + // largest lag to lag zero, the order of the velocity history. + weighted_kernel_.resize(num_lags_, static_cast(kernel_pairs_.size())); + for (std::size_t p = 0; p < kernel_pairs_.size(); ++p) { + const KernelPair& pair = kernel_pairs_[p]; + for (int lag = 0; lag < num_lags_; ++lag) { + weighted_kernel_(num_lags_ - 1 - lag, static_cast(p)) = + kernel_value(pair.row, pair.column, lag) * lag_weights_[lag]; } } + has_kernel_ = true; } -void RadiationRirfConvolution::InterpolateVelocity6D( - const std::deque>& velocity_history_body, - size_t newer_index, - double query_time, - double older_time, - double newer_time, - std::array& out_velocity) { - - if (query_time == older_time) { - const auto& older_velocity = velocity_history_body[newer_index + 1]; - for (int dof = 0; dof < kDofPerBody; ++dof) out_velocity[dof] = older_velocity[dof]; - return; +void RadiationRirfConvolution::RecordVelocities(double simulation_time, + const std::vector>& body_velocities) { + if (static_cast(body_velocities.size()) != num_bodies_) { + throw std::invalid_argument("RadiationRirfConvolution::RecordVelocities: got velocities for " + + std::to_string(body_velocities.size()) + " bodies, expected " + + std::to_string(num_bodies_)); } - if (query_time == newer_time) { - const auto& newer_velocity = velocity_history_body[newer_index]; - for (int dof = 0; dof < kDofPerBody; ++dof) out_velocity[dof] = newer_velocity[dof]; - return; + if (history_.Size() > 0) { + if (simulation_time == history_.NewestTime()) { + throw std::runtime_error( + "Tried to compute the radiation damping convolution twice within the same time step!"); + } + if (simulation_time < history_.NewestTime()) { + // The integrator went back in time (a repeated step). The samples + // recorded at or after the new time belong to the discarded attempt. + if (!warned_time_reversal_) { + warned_time_reversal_ = true; + LOG_WARNING("Radiation convolution: time went back from " << history_.NewestTime() << " s to " + << simulation_time << " s (repeated step). Velocity samples at or after the new time " + "are discarded. Reported once."); + } + history_.DropFrom(simulation_time); + } } - if (query_time > older_time && query_time < newer_time) { - const double time_delta = (newer_time - older_time); - const double weight_older = (time_delta != 0.0) ? ((newer_time - query_time) / time_delta) : 0.0; - const double weight_newer = 1.0 - weight_older; - const auto& older_velocity = velocity_history_body[newer_index + 1]; - const auto& newer_velocity = velocity_history_body[newer_index]; + + for (int b = 0; b < num_bodies_; ++b) { for (int dof = 0; dof < kDofPerBody; ++dof) { - out_velocity[dof] = weight_older * older_velocity[dof] + weight_newer * newer_velocity[dof]; + newest_sample_[kDofPerBody * b + dof] = body_velocities[b][dof]; } - return; } - throw std::runtime_error("Radiation convolution: interpolation error; query_time not bracketed by history."); -} + history_.Append(simulation_time, newest_sample_.data()); -bool RadiationRirfConvolution::AdvanceToBracket( - const std::deque& time_history, - size_t& index, - double query_time) { - while ((index + 1) < time_history.size() && time_history[index + 1] > query_time) { - ++index; - } - return ((index + 1) < time_history.size()); + // Samples older than the longest lag are no longer needed. + history_.DropOlderThan(simulation_time - lag_times_[num_lags_ - 1]); } -std::vector RadiationRirfConvolution::ComputeForces( - std::function get_rirf_val, - const std::vector>* processed_rirf) { - - // Use member buffer instead of allocating every timestep - std::fill(force_radiation_damping_buffer_.begin(), force_radiation_damping_buffer_.end(), 0.0); +const std::vector& RadiationRirfConvolution::ComputeForces() { + if (!has_kernel_) { + throw std::logic_error("RadiationRirfConvolution::ComputeForces: SetKernel() has not been called"); + } + std::fill(force_.begin(), force_.end(), 0.0); - // Nothing to convolve with if we don't yet have at least 2 time points - if (time_history_.size() <= 1) { - return force_radiation_damping_buffer_; + // One sample: there is no interval to integrate over yet. + if (history_.Size() < 2) { + return force_; } - const double simulation_time = time_history_.front(); - size_t history_index = 0; // index into descending time_history_ (front is most recent) + const int lags_covered = PrepareLaggedVelocities(); + if (lags_covered == 0) { + return force_; + } -#ifdef _OPENMP - const int num_threads = omp_get_max_threads(); - std::vector> thread_locals(num_threads, std::vector(total_dofs_, 0.0)); + // F_i += sum_k [K_ij(tau_k) w_k] v_j(t - tau_k), one dot product per kernel. + // Both arrays hold the covered lags in time order (largest lag first), so + // the kernel array is read from row S - L. + const Eigen::Index first_row = num_lags_ - lags_covered; + for (std::size_t p = 0; p < kernel_pairs_.size(); ++p) { + const KernelPair& pair = kernel_pairs_[p]; + const double* velocity = lagged_velocity_[pair.column]; + if (velocity == nullptr) { + continue; // this degree of freedom has not moved + } + const Eigen::Map kernel( + weighted_kernel_.col(static_cast(p)).data() + first_row, lags_covered); + const Eigen::Map lagged(velocity, lags_covered); + force_[pair.row] += kernel.dot(lagged); + } + return force_; +} - #pragma omp parallel - { - const int tid = omp_get_thread_num(); - auto& local_out = thread_locals[tid]; +int RadiationRirfConvolution::PrepareLaggedVelocities() { + const int count = history_.Size(); + int lags_covered = 0; + const int stride = SamplesPerLagSpacing(lags_covered); - size_t history_index_local = history_index; - #pragma omp for schedule(static) - for (int step = 0; step < rirf_steps_; ++step) { - const double rirf_query_time = simulation_time - rirf_time_vector_[step]; + if (stride == 0) { + return InterpolateLaggedVelocities(); + } - size_t time_index = history_index_local; - if (!AdvanceToBracket(time_history_, time_index, rirf_query_time)) { - continue; // not enough older history to interpolate + for (int column = 0; column < total_dofs_; ++column) { + if (history_.ColumnIsZero(column)) { + lagged_velocity_[column] = nullptr; + continue; + } + const double* samples = history_.Column(column); + if (stride == 1) { + // One sample per lag: the lagged velocities are the newest + // samples themselves, already in time order. + lagged_velocity_[column] = samples + (count - lags_covered); + } else { + // Every stride-th sample, counted back from the newest. + double* lagged = lagged_buffer_.col(column).data(); + const int oldest = count - 1 - (lags_covered - 1) * stride; + for (int q = 0; q < lags_covered; ++q) { + lagged[q] = samples[oldest + q * stride]; } - history_index_local = time_index; - - const double newer_time = time_history_[history_index_local]; - const double older_time = time_history_[history_index_local + 1]; + lagged_velocity_[column] = lagged; + } + } + return lags_covered; +} - // Multibody loop: process each body's velocity history - for (int body_index = 0; body_index < num_bodies_; ++body_index) { - const auto& velocity_history_body = velocity_history_[body_index]; - // InterpolateVelocity6D accesses [history_index_local] and [history_index_local + 1] - // so we need at least history_index_local + 2 elements - if (velocity_history_body.size() < history_index_local + 2) { - continue; // not enough history entries for interpolation - } +int RadiationRirfConvolution::SamplesPerLagSpacing(int& lags_covered) const { + const int count = history_.Size(); + const double* times = history_.Times(); + const double now = times[count - 1]; - std::array interpolated_velocity_dof{}; - InterpolateVelocity6D(velocity_history_body, history_index_local, rirf_query_time, - older_time, newer_time, interpolated_velocity_dof); + if (lag_times_[0] != 0.0) { + return 0; + } + if (num_lags_ == 1) { + lags_covered = 1; // lag zero only: the newest sample + return 1; + } - const double step_width = rirf_width_vector_[step]; - if (step_width == 0.0) { - continue; - } - const int body_col_offset = body_index * kDofPerBody; - // Per-DOF loop: accumulate force contribution for each DOF - for (int dof = 0; dof < kDofPerBody; ++dof) { - const int col = body_col_offset + dof; - const double contribution_scale = interpolated_velocity_dof[dof] * step_width; - if (contribution_scale == 0.0) { - continue; - } - for (int row = 0; row < total_dofs_; ++row) { - double rirf_val; - if (processed_rirf) { - // Use processed RIRF tensor (TaperedDirect mode) - int body_idx = row / kDofPerBody; - int row_dof = row % kDofPerBody; - rirf_val = (*processed_rirf)[body_idx](row_dof, col, step); - } else { - // Use raw RIRF via function (Baseline mode) - rirf_val = get_rirf_val(row, col, step); - } - local_out[row] += rirf_val * contribution_scale; - } - } - } + // Candidate: the lag spacing as a whole number of the latest time step. + const double step = now - times[count - 2]; + const double ratio = (lag_times_[1] - lag_times_[0]) / step; + const double rounded = std::round(ratio); + if (!(rounded >= 1.0 && rounded <= 1.0e6) || std::abs(ratio - rounded) > kSampleTimeTolerance) { + return 0; + } + const int stride = static_cast(rounded); + + // Counting back `stride` samples per lag, the record holds lags 0 .. lags - 1. + const int lags = std::min(num_lags_, (count - 1) / stride + 1); + + // Confirm it lag by lag: sample (count - 1 - k * stride) must have been + // taken at t - tau_k. This fails after a change of time step and for a + // lag grid that is not evenly spaced. + const double tolerance = kSampleTimeTolerance * step; + for (int k = 0; k < lags; ++k) { + if (std::abs(times[count - 1 - k * stride] - (now - lag_times_[k])) > tolerance) { + return 0; } } + // The next lag must lie before the first sample. Otherwise the record + // reaches it between samples (older samples taken with another step). + if (lags < num_lags_ && !(now - lag_times_[lags] < times[0])) { + return 0; + } + lags_covered = lags; + return stride; +} - // Deterministic combine of thread-local accumulators - for (int t = 0; t < num_threads; ++t) { - const auto& local = thread_locals[t]; - for (int row = 0; row < total_dofs_; ++row) { - force_radiation_damping_buffer_[row] += local[row]; +int RadiationRirfConvolution::InterpolateLaggedVelocities() { + const int count = history_.Size(); + const double* times = history_.Times(); + const double now = times[count - 1]; + + // For each lag, find the two samples around t - tau_k. The lags increase, + // so the search moves back through the record once. + int lags_covered = 0; + int newer = count - 1; // sample at or after the time looked for + for (int k = 0; k < num_lags_; ++k) { + const double query = now - lag_times_[k]; + while (newer >= 1 && times[newer - 1] > query) { + --newer; + } + if (newer < 1) { + break; // the record does not reach back to this lag + } + const int older = newer - 1; + double weight_older; + if (query == times[older]) { + weight_older = 1.0; + } else if (query == times[newer]) { + weight_older = 0.0; + } else { + const double span = times[newer] - times[older]; + weight_older = (span != 0.0) ? (times[newer] - query) / span : 0.0; } + older_sample_[k] = older; + older_weight_[k] = weight_older; + lags_covered = k + 1; } -#else - for (int step = 0; step < rirf_steps_; ++step) { - const double rirf_query_time = simulation_time - rirf_time_vector_[step]; - size_t time_index = history_index; - if (!AdvanceToBracket(time_history_, time_index, rirf_query_time)) { - break; // not enough older history to interpolate + for (int column = 0; column < total_dofs_; ++column) { + if (history_.ColumnIsZero(column)) { + lagged_velocity_[column] = nullptr; + continue; } - history_index = time_index; - - const double newer_time = time_history_[history_index]; - const double older_time = time_history_[history_index + 1]; - - // Multibody loop: process each body's velocity history - for (int body_index = 0; body_index < num_bodies_; ++body_index) { - const auto& velocity_history_body = velocity_history_[body_index]; - // InterpolateVelocity6D accesses [history_index] and [history_index + 1] - // so we need at least history_index + 2 elements - if (velocity_history_body.size() < history_index + 2) { - continue; // not enough history entries for interpolation - } - - std::array interpolated_velocity_dof{}; - InterpolateVelocity6D(velocity_history_body, history_index, rirf_query_time, - older_time, newer_time, interpolated_velocity_dof); - - const double step_width = rirf_width_vector_[step]; - if (step_width == 0.0) { - continue; - } - const int body_col_offset = body_index * kDofPerBody; - // Per-DOF loop: accumulate force contribution for each DOF - for (int dof = 0; dof < kDofPerBody; ++dof) { - const int col = body_col_offset + dof; - const double contribution_scale = interpolated_velocity_dof[dof] * step_width; - if (contribution_scale == 0.0) { - continue; - } - for (int row = 0; row < total_dofs_; ++row) { - double rirf_val; - if (processed_rirf) { - // Use processed RIRF tensor (TaperedDirect mode) - int body_idx = row / kDofPerBody; - int row_dof = row % kDofPerBody; - rirf_val = (*processed_rirf)[body_idx](row_dof, col, step); - } else { - // Use raw RIRF via function (Baseline mode) - rirf_val = get_rirf_val(row, col, step); - } - force_radiation_damping_buffer_[row] += rirf_val * contribution_scale; - } - } + const double* samples = history_.Column(column); + double* lagged = lagged_buffer_.col(column).data(); + for (int k = 0; k < lags_covered; ++k) { + const int older = older_sample_[k]; + const double weight_older = older_weight_[k]; + // Lag k is entry L - 1 - k of the time-ordered array. + lagged[lags_covered - 1 - k] = weight_older * samples[older] + (1.0 - weight_older) * samples[older + 1]; } + lagged_velocity_[column] = lagged; } -#endif - - // Return a copy to avoid exposing the member buffer (caller may hold reference) - return force_radiation_damping_buffer_; + return lags_covered; } } // namespace seastack::hydro - diff --git a/libs/hydro/src/radiation/velocity_history.cpp b/libs/hydro/src/radiation/velocity_history.cpp new file mode 100644 index 0000000..e86cdad --- /dev/null +++ b/libs/hydro/src/radiation/velocity_history.cpp @@ -0,0 +1,96 @@ +/********************************************************************* + * @file velocity_history.cpp + * @brief Recorded body velocities for the radiation convolution. + *********************************************************************/ + +#include + +#include +#include +#include + +namespace seastack::hydro { + +VelocityHistory::VelocityHistory(int num_columns) : num_columns_(num_columns) { + if (num_columns_ <= 0) { + throw std::invalid_argument("VelocityHistory: num_columns must be > 0 (got " + + std::to_string(num_columns_) + ")"); + } + nonzero_samples_.assign(num_columns_, 0); +} + +void VelocityHistory::Append(double time, const double* velocities) { + if (size_ > 0 && !(time > NewestTime())) { + throw std::invalid_argument("VelocityHistory::Append: time " + std::to_string(time) + + " s is not later than the newest sample (" + std::to_string(NewestTime()) + + " s)"); + } + if (first_ + size_ == capacity_) { + MakeRoom(); + } + const int position = first_ + size_; + times_[position] = time; + for (int column = 0; column < num_columns_; ++column) { + values_[Offset(column) + position] = velocities[column]; + if (velocities[column] != 0.0) { + ++nonzero_samples_[column]; + } + } + ++size_; +} + +void VelocityHistory::DropOlderThan(double time) { + // The oldest sample can go while the next one is still before `time`. + while (size_ > 1 && times_[first_ + 1] < time) { + DropOldest(); + } +} + +void VelocityHistory::DropFrom(double time) { + while (size_ > 0 && NewestTime() >= time) { + const int position = first_ + size_ - 1; + for (int column = 0; column < num_columns_; ++column) { + if (values_[Offset(column) + position] != 0.0) { + --nonzero_samples_[column]; + } + } + --size_; + } +} + +void VelocityHistory::DropOldest() { + for (int column = 0; column < num_columns_; ++column) { + if (values_[Offset(column) + first_] != 0.0) { + --nonzero_samples_[column]; + } + } + ++first_; + --size_; +} + +void VelocityHistory::MakeRoom() { + // Enlarge when the held samples fill more than half of the storage, so + // that the samples are moved at most once per `size_` appended samples. + const int new_capacity = (2 * size_ >= capacity_) ? std::max(64, 2 * capacity_) : capacity_; + if (new_capacity != capacity_) { + std::vector new_times(new_capacity); + std::vector new_values(static_cast(num_columns_) * new_capacity); + std::copy_n(times_.begin() + first_, size_, new_times.begin()); + for (int column = 0; column < num_columns_; ++column) { + std::copy_n(values_.begin() + Offset(column) + first_, size_, + new_values.begin() + static_cast(column) * new_capacity); + } + times_.swap(new_times); + values_.swap(new_values); + capacity_ = new_capacity; + } else { + std::copy_n(times_.begin() + first_, size_, times_.begin()); + for (int column = 0; column < num_columns_; ++column) { + const auto column_begin = values_.begin() + Offset(column); + std::copy_n(column_begin + first_, size_, column_begin); + } + } + first_ = 0; +} + +} // namespace seastack::hydro diff --git a/tests/unit/test_radiation_rirf_convolution.cpp b/tests/unit/test_radiation_rirf_convolution.cpp index 2eb3d63..8a71b43 100644 --- a/tests/unit/test_radiation_rirf_convolution.cpp +++ b/tests/unit/test_radiation_rirf_convolution.cpp @@ -22,8 +22,10 @@ * - a kernel shortened by a truncation time; * - motion in one degree of freedom, and no motion; * - a constant velocity, where the force is the trapezoid integral of K; - * - the same result from the kernel-tensor and the callback interfaces; + * - a kernel with couplings that are identically zero; + * - a repeated step (time goes back); * - rejected inputs. + * VelocityHistory, which holds the record, is tested on its own at the end. * * Self-contained: no data files, HDF5 or Chrono. *********************************************************************/ @@ -31,6 +33,7 @@ #include #include #include +#include #include #include @@ -166,14 +169,16 @@ struct Harness { ? Eigen::VectorXd::LinSpaced(kernel_steps_stored, 0.0, lag_grid[1] * (kernel_steps_stored - 1)) : lag_grid)), - convolution(bodies, static_cast(lag_grid.size()), lag_grid, ComputeRirfWidthVector(lag_grid)) {} + convolution(bodies, static_cast(lag_grid.size()), lag_grid, ComputeRirfWidthVector(lag_grid)) { + convolution.SetKernel(kernel); + } /// Record the velocities at `time` and return the radiation force vector. std::vector Step(double time, const std::vector& velocity) { record.times.push_back(time); record.velocities.push_back(velocity); convolution.RecordVelocities(time, PerBody(velocity, num_bodies)); - return convolution.ComputeForces([](int, int, int) { return 0.0; }, &kernel); + return convolution.ComputeForces(); } std::vector StepWithSignal(double time) { @@ -327,22 +332,43 @@ void TestConstantVelocity() { Check(RelativeDifference(force, integral) < kTolerance, "constant velocity gives the kernel integral"); } -void TestCallbackInterface() { - // The callback form of ComputeForces() returns the same forces as the kernel-tensor form. - Harness tensor(1, UniformLags(41, 0.05)); - Harness callback(1, UniformLags(41, 0.05)); +void TestZeroCouplings() { + // Only heave-heave, surge-pitch and pitch-surge are non-zero, as for a + // body with two planes of symmetry. Kernels that are identically zero + // are not stored; the result must be that of the full sum. + Harness h(1, UniformLags(41, 0.05)); + for (int row = 0; row < kDofPerBody; ++row) { + for (int col = 0; col < kDofPerBody; ++col) { + const bool keep = (row == 2 && col == 2) || (row == 0 && col == 4) || (row == 4 && col == 0); + if (keep) continue; + for (int s = 0; s < h.tau.size(); ++s) h.kernel[0](row, col, s) = 0.0; + } + } + h.convolution.SetKernel(h.kernel); + std::vector force; + for (int n = 0; n <= 70; ++n) force = h.StepWithSignal(n * 0.05); + Check(RelativeDifference(force, DirectSum(h.kernel, h.tau, h.record)) < kTolerance, "kernel with zero couplings"); + Check(force[1] == 0.0 && force[3] == 0.0 && force[5] == 0.0, "rows without a kernel get exactly zero force"); + Check(std::abs(force[0]) > 1.0 && std::abs(force[2]) > 1.0, "rows with a kernel are loaded"); +} + +void TestRepeatedStep() { + // The integrator tries a step to t = 1.0 s, rejects it and steps to 0.975 s + // instead. The sample of the rejected attempt must not be used. + Harness h(1, UniformLags(41, 0.05)); + for (int n = 0; n <= 19; ++n) h.StepWithSignal(n * 0.05); // up to t = 0.95 s + h.StepWithSignal(1.0); // rejected attempt + h.record.times.pop_back(); + h.record.velocities.pop_back(); + const std::vector retried = h.StepWithSignal(0.975); + Check(RelativeDifference(retried, DirectSum(h.kernel, h.tau, h.record)) < kTolerance, + "repeated step: the rejected sample is discarded"); double worst = 0.0; - for (int n = 0; n <= 70; ++n) { - const double time = n * 0.035; - std::vector v(kDofPerBody); - for (int dof = 0; dof < kDofPerBody; ++dof) v[dof] = Velocity(dof, time); - const std::vector from_tensor = tensor.Step(time, v); - callback.convolution.RecordVelocities(time, PerBody(v, 1)); - const std::vector from_callback = callback.convolution.ComputeForces( - [&callback](int row, int col, int step) { return KernelValue(callback.kernel, row, col, step); }); - worst = std::max(worst, RelativeDifference(from_callback, from_tensor)); + for (int n = 1; n <= 60; ++n) { + const std::vector force = h.StepWithSignal(0.975 + n * 0.05); + worst = std::max(worst, RelativeDifference(force, DirectSum(h.kernel, h.tau, h.record))); } - Check(worst < kTolerance, "callback and kernel-tensor interfaces agree"); + Check(worst < kTolerance, "steps after a repeated step"); } template @@ -363,11 +389,75 @@ void TestRejectedInputs() { Check(Throws([&] { RadiationRirfConvolution(1, 11, Eigen::VectorXd(), width); }), "empty lag grid rejected"); Check(Throws([&] { RadiationRirfConvolution(1, 11, tau, Eigen::VectorXd()); }), "empty weights rejected"); + Eigen::VectorXd not_increasing = tau; + not_increasing[5] = not_increasing[4]; + Check(Throws([&] { RadiationRirfConvolution(1, 11, not_increasing, width); }), "repeated lag rejected"); + Eigen::VectorXd negative = tau.array() - 0.05; + Check(Throws([&] { RadiationRirfConvolution(1, 11, negative, width); }), "negative lag rejected"); + Check(Throws([&] { RadiationRirfConvolution(1, 10, tau, width); }), "lag count different from rirf_steps rejected"); + Harness h(1, tau); h.Step(0.0, std::vector(kDofPerBody, 0.0)); h.Step(0.1, std::vector(kDofPerBody, 0.1)); Check(Throws([&] { h.convolution.RecordVelocities(0.1, PerBody(std::vector(kDofPerBody, 0.2), 1)); }), "two records at the same time rejected"); + Check(Throws([&] { h.convolution.RecordVelocities(0.2, PerBody(std::vector(12, 0.2), 2)); }), + "velocities for the wrong number of bodies rejected"); + + RadiationRirfConvolution no_kernel(1, 11, tau, width); + Check(!no_kernel.HasKernel(), "no kernel before SetKernel()"); + Check(Throws([&] { no_kernel.ComputeForces(); }), "ComputeForces() before SetKernel() rejected"); + Check(Throws([&] { no_kernel.SetKernel(MakeKernel(2, tau)); }), "kernel for the wrong number of bodies rejected"); + Check(Throws([&] { no_kernel.SetKernel(MakeKernel(1, UniformLags(6, 0.1))); }), + "kernel with fewer lags than the lag grid rejected"); + KernelTensors wrong_columns(1, Eigen::Tensor(kDofPerBody, 12, 11)); + Check(Throws([&] { no_kernel.SetKernel(wrong_columns); }), "kernel with the wrong number of columns rejected"); +} + +void TestVelocityHistory() { + VelocityHistory history(2); + Check(history.Size() == 0 && history.NumColumns() == 2, "new history is empty"); + Check(history.ColumnIsZero(0) && history.ColumnIsZero(1), "empty columns count as zero"); + + // Column 0 holds the sample number, column 1 is zero except at sample 3. + for (int n = 0; n < 10; ++n) { + const double sample[2] = {static_cast(n), n == 3 ? 7.0 : 0.0}; + history.Append(0.1 * n, sample); + } + Check(history.Size() == 10, "ten samples appended"); + Check(history.Times()[0] == 0.0 && history.NewestTime() == 0.1 * 9, "times in order"); + Check(history.Column(0)[4] == 4.0 && history.Column(1)[3] == 7.0, "values in order"); + Check(!history.ColumnIsZero(1), "column with one non-zero sample is not zero"); + + // Keeps the last sample before the given time, so that the time stays bracketed. + history.DropOlderThan(0.35); + Check(history.Size() == 7 && history.Times()[0] == 0.1 * 3, "DropOlderThan keeps the last sample before the time"); + history.DropOlderThan(0.1 * 5); + Check(history.Size() == 6 && history.Times()[0] == 0.1 * 4, + "DropOlderThan keeps one sample before a time that has a sample"); + Check(history.ColumnIsZero(1), "column is zero once its non-zero sample is dropped"); + Check(history.Column(0)[0] == 4.0, "columns follow the times"); + + history.DropFrom(0.1 * 8); + Check(history.Size() == 4 && history.NewestTime() == 0.1 * 7, "DropFrom removes the samples from that time on"); + Check(Throws([&] { + const double sample[2] = {0.0, 0.0}; + history.Append(0.1 * 7, sample); + }), "sample not later than the newest rejected"); + + // A long run with a sliding window: the storage is reused and the window stays correct. + VelocityHistory sliding(1); + bool window_correct = true; + for (int n = 0; n < 5000; ++n) { + const double sample[1] = {static_cast(n)}; + sliding.Append(n, sample); + sliding.DropOlderThan(n - 100.0); + const int size = sliding.Size(); + window_correct = window_correct && size <= 102 && sliding.Column(0)[size - 1] == n && + sliding.Column(0)[0] == sliding.Times()[0] && sliding.Times()[0] == std::max(0, n - 101); + } + Check(window_correct, "sliding window over 5000 samples"); + Check(Throws([] { VelocityHistory invalid(0); }), "zero columns rejected"); } } // namespace @@ -383,8 +473,10 @@ int main() { TestTruncatedKernel(); TestSingleDegreeOfFreedomAndRest(); TestConstantVelocity(); - TestCallbackInterface(); + TestZeroCouplings(); + TestRepeatedStep(); TestRejectedInputs(); + TestVelocityHistory(); std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; return g_fail == 0 ? 0 : 1; } From 050e5ea08c6241b728ff85aa63c239b0d40f7b2a Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:51:10 +0000 Subject: [PATCH 06/12] Evaluate the excitation convolution in closed form for component waves. For a wave made of components the sum over the kernel lags is carried out once, giving per-component coefficients C_i and S_i, so that F(t) = sum_i A_i [C_i cos(theta_i) - S_i sin(theta_i)] with theta_i = phi_i - omega_i t. The lags still inside the start-up ramp are corrected with a direct sum over those lags only. This is the same quadrature in another order; results differ from the direct sum by rounding. The direct sum is kept for eta-table waves, while every lag is inside the ramp, while a change of wave height is inside the kernel window, and for live period or direction changes. AmplitudeEnvelope::IsConstantOver() identifies the intervals on which the wave-height factor is constant, so a schedule that leaves the wave height unchanged stays bit-identical to a run without one. --- .../excitation_irf_component.h | 55 +++++ .../seastack/hydro/waves/amplitude_envelope.h | 5 + .../excitation_irf_component.cpp | 92 ++++++++ libs/hydro/src/waves/amplitude_envelope.cpp | 12 + tests/unit/CMakeLists.txt | 8 + tests/unit/test_amplitude_envelope.cpp | 19 ++ .../unit/test_excitation_irf_closed_form.cpp | 217 ++++++++++++++++++ 7 files changed, 408 insertions(+) create mode 100644 tests/unit/test_excitation_irf_closed_form.cpp diff --git a/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h b/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h index ef7c827..cfd2e20 100644 --- a/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h +++ b/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h @@ -17,6 +17,41 @@ * interpolated between BEM headings (see SelectKernelForHeading). * Seas with several directions are rejected: use the frequency-domain * ExcitationComponent instead. + * + * Evaluation. With trapezoid weights w_j on the lag grid tau_j and the + * start-up ramp r, the force in one degree of freedom is + * + * F(t) = sum_j K(tau_j) w_j r(t - tau_j) eta(t - tau_j) (1) + * + * For a wave made of components, eta(t) = sum_i A_i cos(phi_i - omega_i t). + * Putting this into (1) and summing over the lags first gives, wherever the + * ramp is 1, + * + * F(t) = sum_i A_i [ C_i cos(theta_i) - S_i sin(theta_i) ], (2) + * theta_i = phi_i - omega_i t, + * C_i = sum_j K(tau_j) w_j cos(omega_i tau_j), + * S_i = sum_j K(tau_j) w_j sin(omega_i tau_j). + * + * C_i and S_i do not depend on time and are computed once. (2) is the same + * sum as (1) in a different order, not another excitation model, and costs + * a few operations per component instead of one per component and lag. + * + * The lags with t - tau_j < T_r are still inside the ramp. For those, (2) + * counts the full elevation where (1) has r times it, so their excess is + * subtracted: + * + * F(t) = (2) - sum_{j: t - tau_j < T_r} K(tau_j) w_j [1 - r(t - tau_j)] eta(t - tau_j). + * + * The number of such lags falls to zero at t = T_r + (largest lag). While + * every lag is inside the ramp, (1) is evaluated directly. + * + * A live change of wave height multiplies eta(t - tau_j) by the envelope + * e(t - tau_j). Where e has one value over all the lags, the result above is + * multiplied by it. While the change is inside the kernel window, each lag + * has its own factor and (1) is evaluated directly. + * + * (1) is also evaluated directly for waves without components (eta table) + * and for live period or direction changes. *********************************************************************/ #ifndef SEASTACK_HYDRO_FORCE_COMPONENTS_EXCITATION_IRF_COMPONENT_H @@ -104,6 +139,26 @@ class ExcitationIrfComponent : public IHydroForceComponent { // Reusable buffer for eta_at_tau to avoid per-timestep allocation Eigen::VectorXd eta_at_tau_buffer_; + // Closed form (2) of the file comment, for component waves. Per body: + // closed_form_cos_[b](dof, i) = C_i and closed_form_sin_[b](dof, i) = S_i + // of degree of freedom `dof` [N/m], 6 x N_comp. + bool has_closed_form_ = false; + std::vector closed_form_cos_; + std::vector closed_form_sin_; + // Per step: A_i cos(theta_i), A_i sin(theta_i), and the elevation excess + // [1 - r(t - tau_j)] eta(t - tau_j) at the lags still inside the ramp. + Eigen::ArrayXd phase_buffer_; // theta_i + Eigen::VectorXd amplitude_cos_buffer_, amplitude_sin_buffer_; + Eigen::VectorXd ramp_excess_buffer_; + + /// Compute C_i and S_i. Requires the fast-path tables and an increasing lag grid. + void BuildClosedForm(); + /// Add the excitation at `time` from the closed form, multiplied by the + /// wave-height factor e [-] that holds at every lag. Returns false, adding + /// nothing, when every lag is still inside the ramp. + bool ComputeClosedForm(const SystemState& state, double time, double wave_height_factor, + BodyForces& inout_forces); + void TryBuildFastPath(); void ComputeFastPath(double time, Eigen::VectorXd& eta_at_tau) const; void ComputeSlowPath(double time, Eigen::VectorXd& eta_at_tau) const; diff --git a/libs/hydro/include/seastack/hydro/waves/amplitude_envelope.h b/libs/hydro/include/seastack/hydro/waves/amplitude_envelope.h index 5385947..75a7e07 100644 --- a/libs/hydro/include/seastack/hydro/waves/amplitude_envelope.h +++ b/libs/hydro/include/seastack/hydro/waves/amplitude_envelope.h @@ -38,6 +38,11 @@ class AmplitudeEnvelope { /// True once any change was made (callers may skip work while false). bool HasChanges() const { return !segments_.empty(); } + /// True when e has one value at every time in [begin, end]; `value` + /// receives it. May return false for an interval that only touches a + /// change at one of its ends (callers then take their general path). + bool IsConstantOver(double begin, double end, double& value) const; + /// Ramp from the current value e(start_time) to `target` [-] over /// `duration` [s] (0 = step). Later segments replace any segment still in /// progress from start_time on. Returns the time at which e reaches target. diff --git a/libs/hydro/src/force_components/excitation_irf_component.cpp b/libs/hydro/src/force_components/excitation_irf_component.cpp index d4b5457..aab7f62 100644 --- a/libs/hydro/src/force_components/excitation_irf_component.cpp +++ b/libs/hydro/src/force_components/excitation_irf_component.cpp @@ -16,6 +16,7 @@ #include #include +#include #include #include #include @@ -187,6 +188,7 @@ ExcitationIrfComponent::ExcitationIrfComponent( eta_at_tau_buffer_.resize(max_n_steps); TryBuildFastPath(); + BuildClosedForm(); } void ExcitationIrfComponent::TryBuildFastPath() { @@ -223,6 +225,79 @@ void ExcitationIrfComponent::TryBuildFastPath() { has_fast_path_ = true; } +void ExcitationIrfComponent::BuildClosedForm() { + has_closed_form_ = false; + if (!has_fast_path_) return; + + // The lags inside the ramp must be the last ones of the grid. + const Eigen::VectorXd& tau = body_irfs_[0].time_vec; + for (Eigen::Index j = 1; j < tau.size(); ++j) { + if (!(tau[j] > tau[j - 1])) return; + } + + for (const auto& birf : body_irfs_) { + if (birf.kernel.rows() != kDofPerBody || birf.kernel.cols() != tau.size()) return; + } + + closed_form_cos_.resize(body_irfs_.size()); + closed_form_sin_.resize(body_irfs_.size()); + for (std::size_t b = 0; b < body_irfs_.size(); ++b) { + // K(dof, tau_j) w_j, then summed over the lags against cos / sin(omega_i tau_j). + const Eigen::MatrixXd weighted_kernel = body_irfs_[b].kernel * body_irfs_[b].width_vec.asDiagonal(); + closed_form_cos_[b] = weighted_kernel * irf_cos_wt_; + closed_form_sin_[b] = weighted_kernel * irf_sin_wt_; + } + has_closed_form_ = true; +} + +bool ExcitationIrfComponent::ComputeClosedForm(const SystemState& state, double time, double wave_height_factor, + BodyForces& inout_forces) { + const Eigen::VectorXd& tau = body_irfs_[0].time_vec; + const Eigen::Index n_lags = tau.size(); + + // Lags still inside the ramp: t - tau_j < T_r, i.e. tau_j > t - T_r. + // The lag grid increases, so they are the lags from `first_in_ramp` on. + Eigen::Index first_in_ramp = n_lags; + if (ramp_duration_ > 0.0) { + const double* begin = tau.data(); + first_in_ramp = std::upper_bound(begin, begin + n_lags, time - ramp_duration_) - begin; + if (first_in_ramp == 0) { + return false; // every lag is inside the ramp: the direct sum costs less + } + } + const Eigen::Index n_in_ramp = n_lags - first_in_ramp; + + // A_i cos(theta_i) and A_i sin(theta_i), theta_i = phi_i - omega_i t. + phase_buffer_ = comp_phases_.array() - comp_omegas_.array() * time; + amplitude_cos_buffer_ = (comp_amplitudes_.array() * phase_buffer_.cos()).matrix(); + amplitude_sin_buffer_ = (comp_amplitudes_.array() * phase_buffer_.sin()).matrix(); + + // Elevation excess at the lags inside the ramp: [1 - r(t - tau_j)] eta(t - tau_j). + if (n_in_ramp > 0) { + ramp_excess_buffer_.noalias() = irf_cos_wt_.bottomRows(n_in_ramp) * amplitude_cos_buffer_; + ramp_excess_buffer_.noalias() -= irf_sin_wt_.bottomRows(n_in_ramp) * amplitude_sin_buffer_; + for (Eigen::Index s = 0; s < n_in_ramp; ++s) { + ramp_excess_buffer_[s] *= 1.0 - RampFactor(time - tau[first_in_ramp + s]); + } + } + + // Excitation in each body's heading frame, rotated to world (heading_frame.h). + for (int b = 0; b < num_bodies_; ++b) { + const auto& birf = body_irfs_[b]; + Eigen::Matrix f_heading = + closed_form_cos_[b] * amplitude_cos_buffer_ - closed_form_sin_[b] * amplitude_sin_buffer_; + for (Eigen::Index s = 0; s < n_in_ramp; ++s) { + const Eigen::Index lag = first_in_ramp + s; + f_heading -= birf.kernel.col(lag) * (birf.width_vec[lag] * ramp_excess_buffer_[s]); + } + f_heading *= wave_height_factor; + const Eigen::Matrix3d heading_to_world = HeadingToWorld(state.bodies[b]); + inout_forces[b].force += heading_to_world * f_heading.head<3>(); + inout_forces[b].moment += heading_to_world * f_heading.tail<3>(); + } + return true; +} + void ExcitationIrfComponent::ComputeFastPath( double time, Eigen::VectorXd& eta_at_tau) const { // theta_i = phi_i - omega_i * t @@ -276,6 +351,21 @@ void ExcitationIrfComponent::Compute( return; } + // Component wave: the lag sum is known in closed form (see the header) + // when the wave-height envelope has one value over the kernel window, + // i.e. at the times t - tau_j of all lags. While a change of wave height + // is inside the window, each lag has its own factor and the direct sum + // below is used. + if (has_closed_form_) { + double wave_height_factor = 1.0; + const double window_begin = time - birf0.time_vec[n_steps - 1]; + const double window_end = time - birf0.time_vec[0]; + if (waves_->GetAmplitudeEnvelope()->IsConstantOver(window_begin, window_end, wave_height_factor) && + ComputeClosedForm(state, time, wave_height_factor, inout_forces)) { + return; + } + } + // Use member buffer instead of allocating every timestep // Resize to exact size needed (buffer is pre-allocated to max size, so this is cheap) eta_at_tau_buffer_.resize(n_steps); @@ -398,6 +488,8 @@ void ExcitationIrfComponent::ReleaseFinishedLayers(double time) { } void ExcitationIrfComponent::ComputeLayered(const SystemState& state, double time, BodyForces& inout_forces) { + // The component tables change from here on; the closed-form coefficients no longer match them. + has_closed_form_ = false; AddNewWaveComponents(); ReleaseFinishedLayers(time); const auto& layers = waves_->GetWaveLayers(); diff --git a/libs/hydro/src/waves/amplitude_envelope.cpp b/libs/hydro/src/waves/amplitude_envelope.cpp index f7b9982..f31bd54 100644 --- a/libs/hydro/src/waves/amplitude_envelope.cpp +++ b/libs/hydro/src/waves/amplitude_envelope.cpp @@ -41,6 +41,18 @@ double AmplitudeEnvelope::Value(double time) const { return s.v0 + (s.v1 - s.v0) * 0.5 * (1.0 - std::cos(kPi * u)); } +bool AmplitudeEnvelope::IsConstantOver(double begin, double end, double& value) const { + value = Value(begin); + // A change from v0 to v1 takes place over [t0, t1]. e keeps one value + // over [begin, end] when no such change overlaps the interval. + for (const Segment& s : segments_) { + if (s.v0 != s.v1 && s.t0 <= end && s.t1 > begin) { + return false; + } + } + return true; +} + double AmplitudeEnvelope::RampTo(double start_time, double target, double duration) { if (!std::isfinite(start_time) || !std::isfinite(target) || !std::isfinite(duration)) { throw std::invalid_argument("AmplitudeEnvelope::RampTo: arguments must be finite"); diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 3bdf035..b802eaf 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -127,6 +127,14 @@ if(TARGET seastack_hydro_io) "SEASTACK_TEST_RM3_H5_FILE=\"${_seastack_test_rm3_h5}\"" "SEASTACK_TEST_SPHERE_H5_FILE=\"${CMAKE_SOURCE_DIR}/data/demos/run_seastack/iea_sphere/assets/hydroData/sphere.h5\"") set_tests_properties(test_radiation_component PROPERTIES LABELS "unit;chrono-free") + + # ExcitationIrfComponent (closed form and ramp correction) against a direct sum, RM3 and OSWEC data + build_unit_test(test_excitation_irf_closed_form) + target_link_libraries(test_excitation_irf_closed_form PRIVATE SEAStack::HydroIO) + target_compile_definitions(test_excitation_irf_closed_form PRIVATE + "SEASTACK_TEST_RM3_H5_FILE=\"${_seastack_test_rm3_h5}\"" + "SEASTACK_TEST_OSWEC_H5_FILE=\"${CMAKE_SOURCE_DIR}/data/demos/run_seastack/oswec/assets/hydroData/oswec.h5\"") + set_tests_properties(test_excitation_irf_closed_form PROPERTIES LABELS "unit;chrono-free") else() message(STATUS "Skipping test_directional_waves (requires SEASTACK_ENABLE_HYDRO_IO)") endif() diff --git a/tests/unit/test_amplitude_envelope.cpp b/tests/unit/test_amplitude_envelope.cpp index de30895..bc74cd6 100644 --- a/tests/unit/test_amplitude_envelope.cpp +++ b/tests/unit/test_amplitude_envelope.cpp @@ -106,6 +106,25 @@ int main() { TEST_ASSERT(e.Value(20.0) == 3.0 && e.Value(19.999) == 2.0, "same-time change replaces the previous one"); } + // ---- E1b. Intervals over which e is constant ---- + { + AmplitudeEnvelope e; + double value = 0.0; + TEST_ASSERT(e.IsConstantOver(-1e3, 1e3, value) && value == 1.0, "no change: constant 1 everywhere"); + e.RampTo(5.0, 1.0, 2.0); + TEST_ASSERT(e.IsConstantOver(0.0, 100.0, value) && value == 1.0, "change to the same value: still constant 1"); + e.RampTo(10.0, 0.5, 4.0); + TEST_ASSERT(e.IsConstantOver(0.0, 9.0, value) && value == 1.0, "interval before the change"); + TEST_ASSERT(!e.IsConstantOver(0.0, 11.0, value), "interval reaching into the change"); + TEST_ASSERT(!e.IsConstantOver(11.0, 12.0, value), "interval inside the change"); + TEST_ASSERT(!e.IsConstantOver(13.0, 50.0, value), "interval starting inside the change"); + TEST_ASSERT(e.IsConstantOver(14.0, 50.0, value) && value == 0.5, "interval after the change"); + e.RampTo(20.0, 2.0, 0.0); + TEST_ASSERT(!e.IsConstantOver(19.0, 20.0, value), "interval ending on a step change"); + TEST_ASSERT(e.IsConstantOver(20.0, 30.0, value) && value == 2.0, "interval starting on a step change"); + TEST_ASSERT(e.IsConstantOver(14.0, 19.9, value) && value == 0.5, "interval between two changes"); + } + // ---- E2. Rejected changes ---- { AmplitudeEnvelope e; diff --git a/tests/unit/test_excitation_irf_closed_form.cpp b/tests/unit/test_excitation_irf_closed_form.cpp new file mode 100644 index 0000000..0958fbb --- /dev/null +++ b/tests/unit/test_excitation_irf_closed_form.cpp @@ -0,0 +1,217 @@ +/********************************************************************* + * @file test_excitation_irf_closed_form.cpp + * @brief Excitation IRF convolution against a direct sum of its quadrature. + * + * ExcitationIrfComponent computes, per body and degree of freedom, + * + * F(t) = sum_j K(tau_j) w_j r(t - tau_j) e(t - tau_j) eta(t - tau_j) + * + * with K the excitation impulse response for the wave direction, w_j the + * trapezoid weights of the lag grid, r the start-up ramp, e the wave-height + * envelope and eta the undisturbed elevation at the origin. For a wave made + * of components the component evaluates the lag sum in closed form once the + * ramp is over, with a correction for the lags still inside the ramp (see + * excitation_irf_component.h). This test checks every branch against the + * sum above evaluated term by term: + * - no ramp (closed form from the start); + * - linear and cosine ramps: early (correction over most lags), late + * (few lags) and after the ramp window (closed form only); + * - a ramp longer than the kernel reaches forward, so that every lag is + * inside it at first (direct sum), then the transition to the closed form; + * - a truncated kernel; + * - a change of wave height: before it enters the kernel window (closed + * form), while it is inside (direct sum with the envelope) and after it + * has left (closed form times the new factor); + * - two bodies (RM3) and a file with several wave headings (OSWEC). + * + * Needs the bundled rm3.h5 and oswec.h5 (HydroIO); no Chrono. + *********************************************************************/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +struct CaseSetup { + std::string label; + std::string h5_file; + int num_bodies = 1; + double ramp_duration = 0.0; // [s] + RampShape ramp_shape = RampShape::kLinear; + double truncation_time = 0.0; // [s], 0 = full kernel + double wave_height_change_time = -1.0; // [s], < 0 = none; the change takes 20 s + std::vector times; // [s] at which the force is checked +}; + +std::shared_ptr MakeWave() { + SeaStateDefinition sea; + sea.type = "irregular"; + SeaStatePartition partition; + partition.spectrum.type = "jonswap"; + partition.spectrum.Hs = 2.0; + partition.spectrum.Tp = 8.0; + sea.partitions.push_back(partition); + sea.n_omega = 96; + sea.seed = 7; + return std::make_shared(ComponentSampler::Build(sea), 0.0); +} + +/// Trapezoid weights of a grid with at least two points. +Eigen::VectorXd TrapezoidWeights(const Eigen::VectorXd& t) { + const Eigen::Index n = t.size(); + Eigen::VectorXd w(n); + w[0] = 0.5 * (t[1] - t[0]); + for (Eigen::Index i = 1; i < n - 1; ++i) w[i] = 0.5 * (t[i + 1] - t[i - 1]); + w[n - 1] = 0.5 * (t[n - 1] - t[n - 2]); + return w; +} + +/// Largest difference between component and direct sum over the case's +/// times, relative to the largest unramped force component. +double RunCase(const CaseSetup& setup) { + const HydroData data = seastack::hydro_io::H5FileInfo(setup.h5_file, setup.num_bodies).ReadH5Data(); + auto wave = MakeWave(); + const std::vector& components = *wave->GetWaveComponents(); + const double direction = components[0].direction; + + ExcitationIrfComponent excitation(data, wave, setup.num_bodies, setup.truncation_time, setup.ramp_duration, + setup.ramp_shape); + if (setup.wave_height_change_time >= 0.0) { + wave->GetAmplitudeEnvelope()->RampTo(setup.wave_height_change_time, 0.5, 20.0); + } + const AmplitudeEnvelope& envelope = *wave->GetAmplitudeEnvelope(); + + auto elevation = [&components](double t) { + double eta = 0.0; + for (const WaveComponent& c : components) eta += c.amplitude * std::cos(c.phase - c.omega * t); + return eta; + }; + + // Kernels and lag grid as the component uses them. + const Eigen::VectorXd& bem_headings = data.GetSimulationInfo().wave_directions; + std::vector kernels; + Eigen::VectorXd tau; + for (int b = 0; b < setup.num_bodies; ++b) { + const auto& irreg = data.GetIrregularWaveInfos()[b]; + Eigen::MatrixXd kernel = + SelectKernelForHeading(irreg.excitation_irf_by_heading, bem_headings, direction, irreg.excitation_irf_matrix); + tau = irreg.excitation_irf_time; + if (setup.truncation_time > 0.0) { + Eigen::Index keep = tau.size(); + for (Eigen::Index i = 0; i < tau.size(); ++i) { + if (tau[i] > setup.truncation_time) { + keep = i; + break; + } + } + tau = tau.head(keep).eval(); + kernel = kernel.leftCols(keep).eval(); + } + kernels.push_back(kernel); + } + const Eigen::VectorXd weights = TrapezoidWeights(tau); + + SystemState state; + state.bodies.resize(setup.num_bodies); + double scale = 0.0; + double worst = 0.0; + std::vector> expected(setup.num_bodies); + for (int pass = 0; pass < 2; ++pass) { + for (double t : setup.times) { + for (int b = 0; b < setup.num_bodies; ++b) expected[b].setZero(); + for (Eigen::Index s = 0; s < tau.size(); ++s) { + const double t_sample = t - tau[s]; + // Pass 0 finds the size of the unramped force (the scale); pass 1 is the check. + const double factor = (pass == 0) ? 1.0 + : RampFactor(setup.ramp_shape, t_sample, setup.ramp_duration) * + envelope.Value(t_sample); + const double eta = factor * elevation(t_sample) * weights[s]; + for (int b = 0; b < setup.num_bodies; ++b) expected[b] += kernels[b].col(s) * eta; + } + if (pass == 0) { + for (int b = 0; b < setup.num_bodies; ++b) scale = std::max(scale, expected[b].cwiseAbs().maxCoeff()); + continue; + } + BodyForces forces(setup.num_bodies); + for (auto& f : forces) { + f.force.setZero(); + f.moment.setZero(); + } + excitation.Compute(state, t, forces); + for (int b = 0; b < setup.num_bodies; ++b) { + worst = std::max({worst, (forces[b].force - expected[b].head<3>()).cwiseAbs().maxCoeff(), + (forces[b].moment - expected[b].tail<3>()).cwiseAbs().maxCoeff()}); + } + } + } + Check(scale > 1.0, setup.label + ": reference force is non-zero"); + return worst / scale; +} + +} // namespace + +int main() { + constexpr double kTolerance = 1.0e-11; // relative; differences are rounding only + const std::string rm3 = SEASTACK_TEST_RM3_H5_FILE; // lags in [-157, 157] s, 2 bodies + const std::string oswec = SEASTACK_TEST_OSWEC_H5_FILE; // lags in [-30, 30] s, 10 headings + + std::vector cases; + cases.push_back({"rm3, no ramp", rm3, 2, 0.0, RampShape::kLinear, 0.0, -1.0, {0.0, 3.7, 50.0, 300.0}}); + // 60 s ramp: lags leave it between t = -97 s and t = 217 s. + cases.push_back({"rm3, linear ramp", rm3, 2, 60.0, RampShape::kLinear, 0.0, -1.0, + {0.0, 0.01, 12.3, 59.99, 60.0, 61.0, 150.0, 216.9, 217.1, 400.0}}); + cases.push_back({"rm3, cosine ramp", rm3, 2, 60.0, RampShape::kCosine, 0.0, -1.0, {0.0, 30.0, 100.0, 216.0, 250.0}}); + // 300 s ramp: every lag is inside it until t = 143 s, none after 457 s. + cases.push_back({"rm3, ramp longer than the kernel", rm3, 2, 300.0, RampShape::kLinear, 0.0, -1.0, + {0.0, 100.0, 142.9, 143.1, 144.0, 300.0, 456.9, 457.1, 600.0}}); + cases.push_back({"rm3, kernel truncated at 40 s", rm3, 2, 60.0, RampShape::kLinear, 40.0, -1.0, + {0.0, 50.0, 99.9, 100.1, 200.0}}); + // Change over [120, 140] s: inside the window t -+ 157 s until t = 297 s. + cases.push_back({"rm3, wave height changed at 120 s", rm3, 2, 60.0, RampShape::kLinear, 0.0, 120.0, + {10.0, 100.0, 130.0, 250.0, 296.9, 297.1, 400.0}}); + // Change over [150, 170] s: inside the window t -+ 30 s from t = 120 s to 200 s. + cases.push_back({"oswec, wave height changed at 150 s", oswec, 2, 60.0, RampShape::kLinear, 0.0, 150.0, + {10.0, 100.0, 119.9, 120.1, 160.0, 199.9, 200.1, 300.0}}); + cases.push_back({"oswec, linear ramp", oswec, 2, 60.0, RampShape::kLinear, 0.0, -1.0, + {0.0, 29.9, 30.1, 45.0, 89.9, 90.1, 200.0}}); + cases.push_back({"oswec, no ramp", oswec, 2, 0.0, RampShape::kLinear, 0.0, -1.0, {0.0, 17.0, 400.0}}); + + for (const CaseSetup& c : cases) { + const double difference = RunCase(c); + Check(difference < kTolerance, c.label + " (relative difference " + std::to_string(difference) + ")"); + } + + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} From cd3ceb1f271cfebee77c9e22bd8938d65f749b3b Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 01:57:15 +0000 Subject: [PATCH 07/12] Sum the frequency-domain excitation per distinct wave frequency. Components of equal frequency are added together when the component is built, giving F(t) = sum_m [P_m cos(omega_m t) + Q_m sin(omega_m t)] over the distinct frequencies. A sea with directional spreading has n_omega x n_theta components but n_omega frequencies, so each time step needs n_theta times fewer cosines and sines. The terms are those of the sum over components in another order; results differ by rounding. The sum over components is kept during and after a live change of wave period or direction. --- .../force_components/excitation_component.h | 39 +++++ .../force_components/excitation_component.cpp | 71 ++++++++ tests/unit/CMakeLists.txt | 5 + tests/unit/test_excitation_frequency_sums.cpp | 163 ++++++++++++++++++ 4 files changed, 278 insertions(+) create mode 100644 tests/unit/test_excitation_frequency_sums.cpp diff --git a/libs/hydro/include/seastack/hydro/force_components/excitation_component.h b/libs/hydro/include/seastack/hydro/force_components/excitation_component.h index cb43a6e..98ca781 100644 --- a/libs/hydro/include/seastack/hydro/force_components/excitation_component.h +++ b/libs/hydro/include/seastack/hydro/force_components/excitation_component.h @@ -8,6 +8,30 @@ * * This component owns the interpolated excitation transfer function data, * separating excitation force responsibility from the wave kinematic model. + * + * Evaluation. With Re_i and Im_i the columns of the transfer function data + * and theta_i = phi_i - omega_i t, the force in a body's heading frame is + * + * F(t) = sum_i A_i [ Re_i cos(theta_i) - Im_i sin(theta_i) ] (1) + * + * Components with the same frequency are added together once, when the + * component is built. Using + * + * cos(theta_i) = cos(phi_i) cos(omega_i t) + sin(phi_i) sin(omega_i t) + * sin(theta_i) = sin(phi_i) cos(omega_i t) - cos(phi_i) sin(omega_i t) + * + * (1) becomes a sum over the distinct frequencies omega_m: + * + * F(t) = sum_m [ P_m cos(omega_m t) + Q_m sin(omega_m t) ] (2) + * P_m = sum_{i: omega_i = omega_m} A_i [ Re_i cos(phi_i) - Im_i sin(phi_i) ] + * Q_m = sum_{i: omega_i = omega_m} A_i [ Re_i sin(phi_i) + Im_i cos(phi_i) ] + * + * (2) is (1) with its terms in another order. A sea with directional + * spreading has n_omega x n_theta components but only n_omega frequencies, + * so (2) needs n_theta times fewer cosines and sines per time step. + * + * (1) is evaluated term by term during and after a live change of wave + * period or direction, when each component has its own time-varying weight. *********************************************************************/ #ifndef SEASTACK_HYDRO_FORCE_COMPONENTS_EXCITATION_COMPONENT_H @@ -88,6 +112,21 @@ class ExcitationComponent : public IHydroForceComponent { TransferFunction transfer_; Eigen::VectorXd weights_; ///< Layer weight of each component [-] (work buffer) + // Sum over distinct frequencies, (2) of the file comment. Per body: + // frequency_cos_[b] holds P_m and frequency_sin_[b] holds Q_m as columns + // (6 x M) [N or N m]. + bool has_frequency_sums_ = false; + Eigen::ArrayXd distinct_omegas_; ///< omega_m [rad/s] + std::vector frequency_cos_; + std::vector frequency_sin_; + Eigen::ArrayXd omega_t_; ///< omega_m t [rad] (work buffer) + Eigen::VectorXd cos_omega_t_, sin_omega_t_; ///< work buffers + + /// Group the components by frequency and compute P_m and Q_m. + void BuildFrequencySums(); + /// Add the excitation at `time` from (2). + void ComputeFromFrequencySums(const SystemState& state, double time, BodyForces& inout_forces); + /// Append TF data for components the wave gained since the last call. void AddNewWaveComponents(); diff --git a/libs/hydro/src/force_components/excitation_component.cpp b/libs/hydro/src/force_components/excitation_component.cpp index 3168e14..5c41056 100644 --- a/libs/hydro/src/force_components/excitation_component.cpp +++ b/libs/hydro/src/force_components/excitation_component.cpp @@ -4,9 +4,11 @@ *********************************************************************/ #include +#include #include #include +#include #include #include @@ -43,6 +45,69 @@ ExcitationComponent::ExcitationComponent( throw std::invalid_argument( "ExcitationComponent: excitation_re size mismatch"); } + BuildFrequencySums(); +} + +void ExcitationComponent::BuildFrequencySums() { + has_frequency_sums_ = false; + const Eigen::Index n_comp = wave_data_.amplitudes.size(); + if (n_comp == 0 || wave_data_.omegas.size() != n_comp || wave_data_.phases.size() != n_comp || + static_cast(excitation_im_.size()) != num_bodies_) { + return; + } + for (int b = 0; b < num_bodies_; ++b) { + if (excitation_re_[b].rows() != kDofPerBody || excitation_re_[b].cols() != n_comp || + excitation_im_[b].rows() != kDofPerBody || excitation_im_[b].cols() != n_comp) { + return; + } + } + + // Components with exactly the same frequency share one group, numbered in + // order of first appearance. + std::map group_of_omega; + std::vector group(static_cast(n_comp)); + for (Eigen::Index i = 0; i < n_comp; ++i) { + const auto next_group = static_cast(group_of_omega.size()); + group[static_cast(i)] = group_of_omega.try_emplace(wave_data_.omegas[i], next_group).first->second; + } + const auto n_groups = static_cast(group_of_omega.size()); + distinct_omegas_.resize(n_groups); + for (const auto& [omega, m] : group_of_omega) { + distinct_omegas_[m] = omega; + } + + frequency_cos_.assign(static_cast(num_bodies_), Eigen::MatrixXd::Zero(kDofPerBody, n_groups)); + frequency_sin_.assign(static_cast(num_bodies_), Eigen::MatrixXd::Zero(kDofPerBody, n_groups)); + for (Eigen::Index i = 0; i < n_comp; ++i) { + const Eigen::Index m = group[static_cast(i)]; + const double a_cos_phi = wave_data_.amplitudes[i] * std::cos(wave_data_.phases[i]); + const double a_sin_phi = wave_data_.amplitudes[i] * std::sin(wave_data_.phases[i]); + for (int b = 0; b < num_bodies_; ++b) { + frequency_cos_[b].col(m) += excitation_re_[b].col(i) * a_cos_phi - excitation_im_[b].col(i) * a_sin_phi; + frequency_sin_[b].col(m) += excitation_re_[b].col(i) * a_sin_phi + excitation_im_[b].col(i) * a_cos_phi; + } + } + has_frequency_sums_ = true; +} + +void ExcitationComponent::ComputeFromFrequencySums(const SystemState& state, double time, BodyForces& inout_forces) { + omega_t_ = distinct_omegas_ * time; + cos_omega_t_ = omega_t_.cos().matrix(); + sin_omega_t_ = omega_t_.sin().matrix(); + + // The ramp and the wave-height envelope scale the excitation only. + double ramp = RampFactor(ramp_shape_, time, ramp_duration_); + if (envelope_ && envelope_->HasChanges()) { + ramp *= envelope_->Value(time); + } + + for (int b = 0; b < num_bodies_; ++b) { + const Eigen::Matrix f_heading = + (frequency_cos_[b] * cos_omega_t_ + frequency_sin_[b] * sin_omega_t_) * ramp; + const Eigen::Matrix3d heading_to_world = HeadingToWorld(state.bodies[b]); + inout_forces[b].force += heading_to_world * f_heading.head<3>(); + inout_forces[b].moment += heading_to_world * f_heading.tail<3>(); + } } void ExcitationComponent::Compute(const SystemState& state, @@ -98,7 +163,13 @@ void ExcitationComponent::ComputeFromTFData(const SystemState& state, double tim BodyForces& inout_forces) { // Live period or direction change: the wave holds several weighted sets. const bool layered = wave_ && !wave_->GetWaveLayers().empty(); + if (has_frequency_sums_ && !layered) { + ComputeFromFrequencySums(state, time, inout_forces); + return; + } if (layered) { + // The component set changes from here on; the frequency sums no longer match it. + has_frequency_sums_ = false; AddNewWaveComponents(); } const Eigen::Index n_comp = wave_data_.amplitudes.size(); diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index b802eaf..93f39a5 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -505,6 +505,11 @@ build_unit_test(test_amplitude_envelope) target_link_libraries(test_amplitude_envelope PRIVATE SEAStack::Hydro) set_tests_properties(test_amplitude_envelope PROPERTIES LABELS "unit;chrono-free") +# Frequency-domain excitation summed per distinct frequency against a term-by-term sum (Chrono-free) +build_unit_test(test_excitation_frequency_sums) +target_link_libraries(test_excitation_frequency_sums PRIVATE SEAStack::Hydro) +set_tests_properties(test_excitation_frequency_sums PROPERTIES LABELS "unit;chrono-free") + # Live wave period / direction: guardrails, crossfade, FD excitation (Chrono-free) build_unit_test(test_sea_state_change) target_link_libraries(test_sea_state_change PRIVATE SEAStack::Hydro) diff --git a/tests/unit/test_excitation_frequency_sums.cpp b/tests/unit/test_excitation_frequency_sums.cpp new file mode 100644 index 0000000..085e459 --- /dev/null +++ b/tests/unit/test_excitation_frequency_sums.cpp @@ -0,0 +1,163 @@ +/********************************************************************* + * @file test_excitation_frequency_sums.cpp + * @brief Frequency-domain excitation against a term-by-term sum. + * + * ExcitationComponent computes, per body in its heading frame, + * + * F(t) = r(t) e(t) sum_i A_i [ Re_i cos(theta_i) - Im_i sin(theta_i) ], + * theta_i = phi_i - omega_i t, + * + * with r the start-up ramp and e the wave-height envelope. The component + * adds the components of equal frequency together when it is built and + * evaluates one cosine and one sine per distinct frequency (see + * excitation_component.h). This test compares it with the sum above taken + * term by term, for: + * - a sea with several directions per frequency (shared frequencies); + * - a sea whose frequencies are all different; + * - no ramp, cosine ramp and linear ramp; + * - a change of wave height during the run; + * - two bodies with different transfer functions. + * + * Synthetic transfer-function values; no BEM data, no Chrono. + *********************************************************************/ + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +constexpr int kNumBodies = 2; + +struct Sea { + ExcitationComponent::WaveComponentData wave; + std::vector re, im; // per body, 6 x n_components +}; + +/// `n_frequencies` frequencies with `n_directions` components each. Every +/// component has its own amplitude, phase and transfer-function column, as +/// the components of one frequency and different directions do. +Sea MakeSea(int n_frequencies, int n_directions) { + const int n = n_frequencies * n_directions; + Sea sea; + sea.wave.amplitudes.resize(n); + sea.wave.omegas.resize(n); + sea.wave.phases.resize(n); + sea.re.assign(kNumBodies, Eigen::MatrixXd(6, n)); + sea.im.assign(kNumBodies, Eigen::MatrixXd(6, n)); + for (int f = 0; f < n_frequencies; ++f) { + for (int d = 0; d < n_directions; ++d) { + const int i = f * n_directions + d; + sea.wave.omegas[i] = 0.35 + 0.11 * f; // [rad/s] + sea.wave.amplitudes[i] = 0.05 + 0.02 * ((7 * i) % 11); // [m] + sea.wave.phases[i] = 6.2 * std::sin(1.7 * i + 0.3); // [rad] + for (int b = 0; b < kNumBodies; ++b) { + for (int dof = 0; dof < 6; ++dof) { + sea.re[b](dof, i) = 1.0e5 * std::cos(0.9 * i + 1.3 * dof + 2.1 * b); + sea.im[b](dof, i) = 8.0e4 * std::sin(0.6 * i - 0.8 * dof + 1.1 * b); + } + } + } + } + return sea; +} + +/// Largest difference between the component and the term-by-term sum over +/// `times`, relative to the largest term-by-term force without ramp. +double WorstDifference(const Sea& sea, double ramp_duration, RampShape ramp_shape, + const std::shared_ptr& envelope, const std::vector& times) { + ExcitationComponent excitation(sea.wave, sea.re, sea.im, kNumBodies, ramp_duration, envelope, nullptr, nullptr, + ramp_shape); + SystemState state; + state.bodies.resize(kNumBodies); + + double scale = 0.0; + double worst = 0.0; + for (double t : times) { + BodyForces forces(kNumBodies); + for (auto& f : forces) { + f.force.setZero(); + f.moment.setZero(); + } + excitation.Compute(state, t, forces); + + const double factor = RampFactor(ramp_shape, t, ramp_duration) * (envelope ? envelope->Value(t) : 1.0); + for (int b = 0; b < kNumBodies; ++b) { + Eigen::Matrix unramped = Eigen::Matrix::Zero(); + for (Eigen::Index i = 0; i < sea.wave.amplitudes.size(); ++i) { + const double theta = sea.wave.phases[i] - sea.wave.omegas[i] * t; + unramped += sea.wave.amplitudes[i] * (sea.re[b].col(i) * std::cos(theta) - sea.im[b].col(i) * std::sin(theta)); + } + scale = std::max(scale, unramped.cwiseAbs().maxCoeff()); + const Eigen::Matrix expected = unramped * factor; + worst = std::max({worst, (forces[b].force - expected.head<3>()).cwiseAbs().maxCoeff(), + (forces[b].moment - expected.tail<3>()).cwiseAbs().maxCoeff()}); + } + } + return scale > 0.0 ? worst / scale : 1.0; +} + +} // namespace + +int main() { + constexpr double kTolerance = 1.0e-12; // relative; differences are rounding only + const std::vector times = {0.0, 0.37, 2.5, 4.99, 5.0, 7.3, 31.1, 1234.5}; + + const Sea spreading = MakeSea(9, 7); // 63 components, 9 frequencies + const Sea long_crested = MakeSea(40, 1); // all frequencies different + const Sea regular = MakeSea(1, 1); + + struct Case { + std::string label; + const Sea* sea; + double ramp_duration; + RampShape ramp_shape; + bool change_wave_height; + }; + const std::vector cases = { + {"spreading sea, no ramp", &spreading, 0.0, RampShape::kCosine, false}, + {"spreading sea, cosine ramp", &spreading, 5.0, RampShape::kCosine, false}, + {"spreading sea, linear ramp", &spreading, 5.0, RampShape::kLinear, false}, + {"spreading sea, wave height changed at 3 s", &spreading, 5.0, RampShape::kCosine, true}, + {"long-crested sea, cosine ramp", &long_crested, 5.0, RampShape::kCosine, false}, + {"long-crested sea, wave height changed at 3 s", &long_crested, 0.0, RampShape::kCosine, true}, + {"regular wave, cosine ramp", ®ular, 5.0, RampShape::kCosine, false}, + }; + for (const Case& c : cases) { + std::shared_ptr envelope; + if (c.change_wave_height) { + envelope = std::make_shared(); + envelope->RampTo(3.0, 0.5, 4.0); + } + const double difference = WorstDifference(*c.sea, c.ramp_duration, c.ramp_shape, envelope, times); + Check(difference < kTolerance, c.label + " (relative difference " + std::to_string(difference) + ")"); + } + + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} From 1843cc41706b71614eb4aa3b3ce38a5e31e0a002 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:33:46 +0000 Subject: [PATCH 08/12] Make the closed-form excitation coefficients independent of the thread count. The coefficients were formed with one matrix-matrix product, which Eigen splits between the OpenMP threads; the rounding then depended on the number of threads (differences of 1e-11 in the excitation force). They are now formed with one matrix-vector product per wave component, which runs on one thread. Results are bit-identical for any OMP_NUM_THREADS. --- .../force_components/excitation_irf_component.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/libs/hydro/src/force_components/excitation_irf_component.cpp b/libs/hydro/src/force_components/excitation_irf_component.cpp index aab7f62..1c6ba67 100644 --- a/libs/hydro/src/force_components/excitation_irf_component.cpp +++ b/libs/hydro/src/force_components/excitation_irf_component.cpp @@ -244,8 +244,16 @@ void ExcitationIrfComponent::BuildClosedForm() { for (std::size_t b = 0; b < body_irfs_.size(); ++b) { // K(dof, tau_j) w_j, then summed over the lags against cos / sin(omega_i tau_j). const Eigen::MatrixXd weighted_kernel = body_irfs_[b].kernel * body_irfs_[b].width_vec.asDiagonal(); - closed_form_cos_[b] = weighted_kernel * irf_cos_wt_; - closed_form_sin_[b] = weighted_kernel * irf_sin_wt_; + // One matrix-vector product per component. Eigen runs these on one + // thread; a single matrix-matrix product would be split between the + // OpenMP threads and round differently for each thread count. + const Eigen::Index n_comp = irf_cos_wt_.cols(); + closed_form_cos_[b].resize(kDofPerBody, n_comp); + closed_form_sin_[b].resize(kDofPerBody, n_comp); + for (Eigen::Index i = 0; i < n_comp; ++i) { + closed_form_cos_[b].col(i).noalias() = weighted_kernel * irf_cos_wt_.col(i); + closed_form_sin_[b].col(i).noalias() = weighted_kernel * irf_sin_wt_.col(i); + } } has_closed_form_ = true; } From e2f0936a1aebdcbe1884d67acbf68d1a01075f87 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 02:33:46 +0000 Subject: [PATCH 09/12] Speed up the set-up of eta-file wave components and the incident elevation series. BuildFromEtaFile: every angle of the transform at the Fourier frequencies is a multiple of 2 pi / N, so the cosines and sines are taken from a table of N values in place of two library calls per term, and the frequencies are summed in parallel (one thread per frequency, so the result does not depend on the thread count). Component amplitudes and phases differ from the previous values by rounding. ComputeElevationTimeSeries is now virtual. LinearDirectionalWaveField adds the components of equal frequency into one cosine before the time loop: a sea with directional spreading needs one cosine per frequency and time instead of one per component. For a long-crested sea the series is identical to the previous one. --- .../waves/linear_directional_wave_field.h | 8 + .../include/seastack/hydro/waves/wave_base.h | 5 +- libs/hydro/src/waves/component_sampler.cpp | 60 ++++++- .../waves/linear_directional_wave_field.cpp | 54 +++++++ tests/unit/CMakeLists.txt | 10 ++ tests/unit/test_elevation_time_series.cpp | 119 ++++++++++++++ tests/unit/test_eta_file_components.cpp | 153 ++++++++++++++++++ 7 files changed, 400 insertions(+), 9 deletions(-) create mode 100644 tests/unit/test_elevation_time_series.cpp create mode 100644 tests/unit/test_eta_file_components.cpp diff --git a/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h b/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h index 5057b7d..b8a318a 100644 --- a/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h +++ b/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h @@ -54,6 +54,14 @@ class LinearDirectionalWaveField : public WaveBase { /// Surface slope (d_eta/dx, d_eta/dy) at a given position and time. Eigen::Vector2d GetElevationGradientXY(const Eigen::Vector3d& position, double time) const override; + /// Elevation at the origin over a uniform time grid (see WaveBase). + /// Components of the same frequency are added into one cosine first, so + /// a sea with directional spreading costs one cosine per frequency and + /// time. For a sea whose frequencies all differ the values are those of + /// GetElevation() at the origin. + std::pair, std::vector> + ComputeElevationTimeSeries(double t_start, double t_end, double dt) const override; + /// Elevation using only the max_components largest-amplitude components (for faster visualization). double GetElevationForVisualization(const Eigen::Vector3d& position, double time, int max_components) const; diff --git a/libs/hydro/include/seastack/hydro/waves/wave_base.h b/libs/hydro/include/seastack/hydro/waves/wave_base.h index 954bfe2..58913ba 100644 --- a/libs/hydro/include/seastack/hydro/waves/wave_base.h +++ b/libs/hydro/include/seastack/hydro/waves/wave_base.h @@ -126,8 +126,9 @@ class WaveBase { /// models with components give their directions in GetWaveComponents(). virtual std::optional GetEtaRecordDirection() const { return std::nullopt; } - /// Compute elevation at the origin over a uniform time grid. - std::pair, std::vector> + /// Compute elevation at the origin over a uniform time grid: + /// (times, elevations) at t_start, t_start + dt, ... up to t_end. + virtual std::pair, std::vector> ComputeElevationTimeSeries(double t_start, double t_end, double dt) const; void SetNumBodies(unsigned int n) { num_bodies_ = n; } diff --git a/libs/hydro/src/waves/component_sampler.cpp b/libs/hydro/src/waves/component_sampler.cpp index 1a62e52..b70777d 100644 --- a/libs/hydro/src/waves/component_sampler.cpp +++ b/libs/hydro/src/waves/component_sampler.cpp @@ -26,6 +26,12 @@ constexpr double kDegToRad = M_PI / 180.0; constexpr double kDefaultOmegaMinFactor = 0.25; constexpr double kDefaultOmegaMaxFactor = 4.0; +/// Cosine and sine of one angle. +struct CosSin { + double cos; + double sin; +}; + std::pair FindPeakOmegaRange( const std::vector& partitions) { double omega_p_min = std::numeric_limits::max(); @@ -348,11 +354,13 @@ std::vector ComponentSampler::BuildFromEtaFile( } Eigen::VectorXd freqs_hz(0); + std::vector bins; // Fourier bin k of each frequency, f = k / (N dt) { std::vector freq_vec; freq_vec.reserve(static_cast(nf_full / stride + 1)); for (int k = k_min; k <= k_max; k += stride) { freq_vec.push_back(static_cast(k) * df_natural); + bins.push_back(k); } freqs_hz.resize(static_cast(freq_vec.size())); for (Eigen::Index i = 0; i < freqs_hz.size(); ++i) { @@ -364,18 +372,56 @@ std::vector ComponentSampler::BuildFromEtaFile( Eigen::VectorXd omegas = 2.0 * M_PI * freqs_hz; Eigen::VectorXd wavenumbers = ComputeWaveNumbers(omegas, depth, g); - // 3. DFT at the (orthogonal) Fourier frequencies. + // 3. DFT at the (orthogonal) Fourier frequencies: + // re_k = sum_j eta_j cos(omega_k (t0 + j dt)), im_k = sum_j eta_j sin(omega_k (t0 + j dt)). + // + // With omega_k = 2 pi k / (N dt) the angle is omega_k t0 + 2 pi k j / N, + // and 2 pi k j / N differs from 2 pi ((k j) mod N) / N by whole turns. + // Every cosine and sine needed is therefore one of the N values + // cos(2 pi m / N), sin(2 pi m / N), which are tabulated once: + // C_k = sum_j eta_j cos(2 pi m_j / N), S_k = sum_j eta_j sin(2 pi m_j / N), m_j = (k j) mod N, + // followed by a rotation through the angle omega_k t0: + // re_k = C_k cos(omega_k t0) - S_k sin(omega_k t0) + // im_k = S_k cos(omega_k t0) + C_k sin(omega_k t0) + std::vector table(N); + for (size_t m = 0; m < N; ++m) { + const double angle = 2.0 * M_PI * static_cast(m) / static_cast(N); + table[m] = {std::cos(angle), std::sin(angle)}; + } + + std::vector re_part(static_cast(nf_actual)); + std::vector im_part(static_cast(nf_actual)); +#ifdef _OPENMP + // One thread sums one frequency, so the result does not depend on the + // number of threads. Below this many terms threading costs more than it saves. + constexpr double kMinParallelTerms = 1.0e7; + const bool parallel = static_cast(N) * static_cast(nf_actual) >= kMinParallelTerms; + #pragma omp parallel for schedule(static) if (parallel) +#endif + for (int i = 0; i < nf_actual; ++i) { + const size_t step = static_cast(bins[static_cast(i)]) % N; + size_t m = 0; // (k j) mod N + double sum_cos = 0.0, sum_sin = 0.0; + for (size_t j = 0; j < N; ++j) { + sum_cos += etas[j] * table[m].cos; + sum_sin += etas[j] * table[m].sin; + m += step; + if (m >= N) m -= N; + } + const double start_angle = omegas[i] * t0; + const double cos_start = std::cos(start_angle); + const double sin_start = std::sin(start_angle); + re_part[static_cast(i)] = sum_cos * cos_start - sum_sin * sin_start; + im_part[static_cast(i)] = sum_sin * cos_start + sum_cos * sin_start; + } + std::vector components; components.reserve(static_cast(nf_actual)); for (int i = 0; i < nf_actual; ++i) { const double omega = omegas[i]; - double re = 0.0, im = 0.0; - for (size_t j = 0; j < N; ++j) { - const double angle = omega * (t0 + static_cast(j) * dt); - re += etas[j] * std::cos(angle); - im += etas[j] * std::sin(angle); - } + const double re = re_part[static_cast(i)]; + const double im = im_part[static_cast(i)]; const double amplitude = 2.0 * std::sqrt(re * re + im * im) / static_cast(N); const double phase = std::atan2(im, re); diff --git a/libs/hydro/src/waves/linear_directional_wave_field.cpp b/libs/hydro/src/waves/linear_directional_wave_field.cpp index 2f32f13..2c0d4fc 100644 --- a/libs/hydro/src/waves/linear_directional_wave_field.cpp +++ b/libs/hydro/src/waves/linear_directional_wave_field.cpp @@ -11,6 +11,7 @@ #include #include +#include #include #include @@ -207,6 +208,59 @@ double LinearDirectionalWaveField::GetElevation(const Eigen::Vector3d& position, return (amplitudes.array() * phase_args.cos()).sum(); } +std::pair, std::vector> +LinearDirectionalWaveField::ComputeElevationTimeSeries(double t_start, double t_end, double dt) const { + if (!layers_.empty()) { + return WaveBase::ComputeElevationTimeSeries(t_start, t_end, dt); + } + + // At the origin, eta(t) = sum_i A_i cos(phi_i - omega_i t). The components + // of one frequency omega_m add up to a single cosine: + // sum_{i: omega_i = omega_m} A_i cos(phi_i - omega_m t) = R_m cos(psi_m - omega_m t) + // R_m cos(psi_m) = sum A_i cos(phi_i), R_m sin(psi_m) = sum A_i sin(phi_i) + // A frequency with one component keeps its A_i and phi_i. + const Eigen::Index n_comp = amplitudes_.size(); + std::map group_of_omega; // numbered in order of first appearance + std::vector group(static_cast(n_comp)); + for (Eigen::Index i = 0; i < n_comp; ++i) { + const auto next_group = static_cast(group_of_omega.size()); + group[static_cast(i)] = group_of_omega.try_emplace(omegas_[i], next_group).first->second; + } + const auto n_groups = static_cast(group_of_omega.size()); + + Eigen::ArrayXd group_omega(n_groups), group_amplitude(n_groups), group_phase(n_groups); + Eigen::ArrayXd sum_cos = Eigen::ArrayXd::Zero(n_groups); + Eigen::ArrayXd sum_sin = Eigen::ArrayXd::Zero(n_groups); + std::vector group_size(static_cast(n_groups), 0); + for (Eigen::Index i = 0; i < n_comp; ++i) { + const Eigen::Index m = group[static_cast(i)]; + group_omega[m] = omegas_[i]; + group_amplitude[m] = amplitudes_[i]; + group_phase[m] = phases_[i]; + sum_cos[m] += amplitudes_[i] * std::cos(phases_[i]); + sum_sin[m] += amplitudes_[i] * std::sin(phases_[i]); + ++group_size[static_cast(m)]; + } + for (Eigen::Index m = 0; m < n_groups; ++m) { + if (group_size[static_cast(m)] > 1) { + group_amplitude[m] = std::hypot(sum_cos[m], sum_sin[m]); + group_phase[m] = std::atan2(sum_sin[m], sum_cos[m]); + } + } + + const int n = static_cast(std::ceil((t_end - t_start) / dt)) + 1; + std::vector times(n); + std::vector elevations(n); + Eigen::ArrayXd phase_args(n_groups); + for (int i = 0; i < n; ++i) { + const double t = t_start + i * dt; + times[i] = t; + phase_args = group_phase - group_omega * t; + elevations[i] = (group_amplitude * phase_args.cos()).sum(); + } + return {times, elevations}; +} + Eigen::Vector2d LinearDirectionalWaveField::GetElevationGradientXY( const Eigen::Vector3d& position, double time) const { const double x = position.x(); diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 93f39a5..5b3ac59 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -510,6 +510,16 @@ build_unit_test(test_excitation_frequency_sums) target_link_libraries(test_excitation_frequency_sums PRIVATE SEAStack::Hydro) set_tests_properties(test_excitation_frequency_sums PROPERTIES LABELS "unit;chrono-free") +# Wave components from an elevation record against a direct Fourier transform (Chrono-free) +build_unit_test(test_eta_file_components) +target_link_libraries(test_eta_file_components PRIVATE SEAStack::Hydro) +set_tests_properties(test_eta_file_components PROPERTIES LABELS "unit;chrono-free") + +# Incident elevation series at the origin against the sum over wave components (Chrono-free) +build_unit_test(test_elevation_time_series) +target_link_libraries(test_elevation_time_series PRIVATE SEAStack::Hydro) +set_tests_properties(test_elevation_time_series PROPERTIES LABELS "unit;chrono-free") + # Live wave period / direction: guardrails, crossfade, FD excitation (Chrono-free) build_unit_test(test_sea_state_change) target_link_libraries(test_sea_state_change PRIVATE SEAStack::Hydro) diff --git a/tests/unit/test_elevation_time_series.cpp b/tests/unit/test_elevation_time_series.cpp new file mode 100644 index 0000000..08c9f55 --- /dev/null +++ b/tests/unit/test_elevation_time_series.cpp @@ -0,0 +1,119 @@ +/********************************************************************* + * @file test_elevation_time_series.cpp + * @brief Incident elevation series at the origin against the sum over + * wave components. + * + * LinearDirectionalWaveField::ComputeElevationTimeSeries returns + * + * eta(t) = sum_i A_i cos(phi_i - omega_i t) + * + * on a uniform time grid. It adds the components of equal frequency into + * one cosine before the time loop (linear_directional_wave_field.cpp). + * Checked here: + * - a sea with directional spreading (21 directions per frequency) + * against the sum over all components, term by term; + * - a long-crested sea, where no components share a frequency: the + * series must equal GetElevation() at the origin exactly; + * - the time grid. + * + * No BEM data, no Chrono. + *********************************************************************/ + +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +std::vector SampleSea(bool spreading) { + SeaStateDefinition sea; + sea.type = "irregular"; + SeaStatePartition partition; + partition.spectrum.type = "jonswap"; + partition.spectrum.Hs = 2.5; + partition.spectrum.Tp = 9.0; + if (spreading) { + partition.spreading.type = "cos2s"; + partition.spreading.s = 12.0; + partition.spreading.mean_direction_deg = 20.0; + sea.n_theta = 21; + } + sea.partitions.push_back(partition); + sea.n_omega = 64; + sea.seed = 3; + return ComponentSampler::Build(sea); +} + +} // namespace + +int main() { + constexpr double kStart = -5.0; // [s] + constexpr double kEnd = 120.0; // [s] + constexpr double kStep = 0.25; // [s] + const Eigen::Vector3d origin = Eigen::Vector3d::Zero(); + + // ---- Directional spreading: several components per frequency ---- + { + const std::vector components = SampleSea(true); + const LinearDirectionalWaveField wave(components, 0.0); + const auto [times, elevations] = wave.ComputeElevationTimeSeries(kStart, kEnd, kStep); + + Check(components.size() > 64, "spreading sea has several components per frequency (" + + std::to_string(components.size()) + " components)"); + Check(times.size() == 501 && elevations.size() == 501, "grid has (end - start) / step + 1 points"); + Check(times.front() == kStart && std::abs(times.back() - kEnd) < 1e-12, "grid runs from start to end"); + + double largest = 0.0; + double worst = 0.0; + for (std::size_t n = 0; n < times.size(); ++n) { + double eta = 0.0; + for (const WaveComponent& c : components) eta += c.amplitude * std::cos(c.phase - c.omega * times[n]); + largest = std::max(largest, std::abs(eta)); + worst = std::max(worst, std::abs(elevations[n] - eta)); + } + char text[64]; + std::snprintf(text, sizeof(text), "%.2e", worst / largest); + Check(largest > 0.1, "spreading sea: reference elevation is non-zero"); + Check(worst < 1.0e-12 * largest, std::string("spreading sea: series equals the sum over components (relative " + "difference ") + text + ")"); + } + + // ---- Long-crested: every frequency has one component ---- + { + const std::vector components = SampleSea(false); + const LinearDirectionalWaveField wave(components, 0.0); + const auto [times, elevations] = wave.ComputeElevationTimeSeries(kStart, kEnd, kStep); + + bool identical = times.size() == 501; + for (std::size_t n = 0; n < times.size(); ++n) { + identical = identical && elevations[n] == wave.GetElevation(origin, times[n]); + } + Check(identical, "long-crested sea: series is identical to GetElevation() at the origin"); + } + + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} diff --git a/tests/unit/test_eta_file_components.cpp b/tests/unit/test_eta_file_components.cpp new file mode 100644 index 0000000..27400ac --- /dev/null +++ b/tests/unit/test_eta_file_components.cpp @@ -0,0 +1,153 @@ +/********************************************************************* + * @file test_eta_file_components.cpp + * @brief Wave components from an elevation record against a direct + * discrete Fourier transform. + * + * ComponentSampler::BuildFromEtaFile returns, for the Fourier frequencies + * omega_k = 2 pi k / (N dt) of a record eta_j at times t0 + j dt, + * + * re_k = sum_j eta_j cos(omega_k (t0 + j dt)), + * im_k = sum_j eta_j sin(omega_k (t0 + j dt)), + * amplitude = 2 sqrt(re_k^2 + im_k^2) / N, phase = atan2(im_k, re_k). + * + * The sampler takes its cosines and sines from a table of N values (see + * component_sampler.cpp). This test evaluates the sums above with one + * std::cos and std::sin per term and compares every returned component, for + * - a record that starts at t = 0 and one that starts later; + * - record lengths that are prime, a power of two and neither; + * - a frequency cap that keeps every second or third Fourier bin. + * + * No BEM data, no Chrono. + *********************************************************************/ + +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace seastack::hydro; + +namespace { + +constexpr double kPi = 3.14159265358979323846; + +int g_pass = 0; +int g_fail = 0; + +void Check(bool condition, const std::string& label) { + if (condition) { + ++g_pass; + } else { + ++g_fail; + std::cerr << "FAIL: " << label << "\n"; + } +} + +struct Record { + std::vector times; // [s] + std::vector elevations; // [m] +}; + +/// Three sinusoids on Fourier frequencies of the record plus a small, +/// repeatable broadband part, so that every bin holds some signal. +Record MakeRecord(int n_samples, double dt, double t0) { + Record record; + const double window = n_samples * dt; + unsigned int state = 12345u; + for (int j = 0; j < n_samples; ++j) { + const double t = t0 + j * dt; + state = state * 1664525u + 1013904223u; // linear congruential generator + const double broadband = 0.02 * (static_cast(state >> 8) / 16777216.0 - 0.5); + const double eta = 0.8 * std::cos(2.0 * kPi * 11.0 / window * t - 0.4) + + 0.5 * std::cos(2.0 * kPi * 23.0 / window * t + 1.9) + + 0.2 * std::cos(2.0 * kPi * 40.0 / window * t + 0.7) + broadband; + record.times.push_back(t); + record.elevations.push_back(eta); + } + return record; +} + +/// Write "time : elevation" lines with enough digits to read back the same values. +void WriteRecord(const Record& record, const std::filesystem::path& path) { + std::ofstream file(path); + file << std::setprecision(17); + for (std::size_t j = 0; j < record.times.size(); ++j) { + file << record.times[j] << " : " << record.elevations[j] << "\n"; + } +} + +/// Largest difference between the sampler's components and the direct +/// transform, as |A e^(i phase) - A_ref e^(i phase_ref)| / (largest amplitude). +/// Returns the number of components through `count`. +double WorstDifference(int n_samples, double dt, double t0, int max_frequencies, std::size_t& count) { + const Record record = MakeRecord(n_samples, dt, t0); + const std::filesystem::path path = + std::filesystem::temp_directory_path() / ("seastack_test_eta_" + std::to_string(n_samples) + ".txt"); + WriteRecord(record, path); + const std::vector components = + ComponentSampler::BuildFromEtaFile(path.string(), 0.0, 9.81, max_frequencies, 0.02, 1.0); + std::filesystem::remove(path); + count = components.size(); + + const double n = static_cast(n_samples); + const double step = (record.times.back() - record.times.front()) / (n - 1.0); + double largest = 0.0; + double worst = 0.0; + for (const WaveComponent& c : components) { + double re = 0.0; + double im = 0.0; + for (int j = 0; j < n_samples; ++j) { + const double angle = c.omega * (record.times.front() + j * step); + re += record.elevations[j] * std::cos(angle); + im += record.elevations[j] * std::sin(angle); + } + const std::complex reference = std::complex(re, im) * (2.0 / n); + const std::complex sampled = std::polar(c.amplitude, c.phase); + largest = std::max(largest, std::abs(reference)); + worst = std::max(worst, std::abs(sampled - reference)); + } + return largest > 0.0 ? worst / largest : 1.0; +} + +} // namespace + +int main() { + // The direct transform rounds each angle omega (t0 + j dt), which is up to + // a few thousand radians here; the differences are of that size. + constexpr double kTolerance = 1.0e-10; + + struct Case { + std::string label; + int n_samples; + double dt; // [s] + double t0; // [s] + int max_frequencies; + }; + const std::vector cases = { + {"3001 samples (prime), record from t = 0", 3001, 0.1, 0.0, 1000}, + {"3001 samples (prime), record from t = 12.5 s", 3001, 0.1, 12.5, 1000}, + {"4096 samples (power of two), record from t = -3 s", 4096, 0.05, -3.0, 1000}, + {"6000 samples, every third Fourier bin", 6000, 0.05, 0.0, 100}, + {"6000 samples, every second Fourier bin, record from t = 7 s", 6000, 0.05, 7.0, 150}, + }; + for (const Case& c : cases) { + std::size_t count = 0; + const double difference = WorstDifference(c.n_samples, c.dt, c.t0, c.max_frequencies, count); + Check(count >= 3, c.label + ": components returned (" + std::to_string(count) + ")"); + char text[64]; + std::snprintf(text, sizeof(text), "%.2e", difference); + Check(difference < kTolerance, c.label + " (relative difference " + text + ")"); + } + + std::cout << "Results: " << g_pass << " passed, " << g_fail << " failed\n"; + return g_fail == 0 ? 0 : 1; +} From 7408ab0e9783fb693c89219edcc431952d183437 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 03:05:17 +0000 Subject: [PATCH 10/12] Speed up the mesh loops of nonlinear hydrostatics and nonlinear Froude-Krylov. The submerged-volume and pressure integrals and the vertex transform now work on plain doubles (internal type Vec3). The same formulas written with Eigen::Vector3d took about ten times as long per mesh face in the Windows release build. The per-face heap allocations of the waterline clipping are gone. Results differ from the previous ones by rounding. LinearDirectionalWaveField::GetElevationAndPressureHead works through the points one component at a time for a regular wave or up to 8 components, so each cosine and exponential is one array operation over all mesh vertices. Seas with more components keep the point-by-point loop. TriangleMesh gains TransformVertices(). --- .../seastack/hydro/geometry/triangle_mesh.h | 5 ++ .../waves/linear_directional_wave_field.h | 18 +++- libs/hydro/src/geometry/submerged_volume.cpp | 83 ++++++++--------- libs/hydro/src/geometry/triangle_mesh.cpp | 20 +++++ libs/hydro/src/geometry/vec3.h | 69 +++++++++++++++ .../src/geometry/wetted_surface_pressure.cpp | 49 +++++++---- .../waves/linear_directional_wave_field.cpp | 88 +++++++++++++++++++ tests/unit/test_wave_pressure.cpp | 27 ++++-- 8 files changed, 289 insertions(+), 70 deletions(-) create mode 100644 libs/hydro/src/geometry/vec3.h diff --git a/libs/hydro/include/seastack/hydro/geometry/triangle_mesh.h b/libs/hydro/include/seastack/hydro/geometry/triangle_mesh.h index bc89c8b..a3717d1 100644 --- a/libs/hydro/include/seastack/hydro/geometry/triangle_mesh.h +++ b/libs/hydro/include/seastack/hydro/geometry/triangle_mesh.h @@ -30,6 +30,11 @@ struct TriangleMesh { Eigen::AlignedBox3d bounding_box() const; + /// Vertex positions in the world frame, one per column: R v + t for each + /// vertex v, with R and t the linear part and translation of + /// body_to_world. `world` is resized if needed. + void TransformVertices(const Eigen::Affine3d& body_to_world, Eigen::Matrix3Xd& world) const; + /** * @brief Mesh topology diagnostics. */ diff --git a/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h b/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h index b8a318a..be57733 100644 --- a/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h +++ b/libs/hydro/include/seastack/hydro/waves/linear_directional_wave_field.h @@ -42,9 +42,11 @@ class LinearDirectionalWaveField : public WaveBase { double GetDynamicPressureHead(const Eigen::Vector3d& position, double time, double elevation) const override; /// Batched elevation and pressure head (see WaveBase). Each component's - /// cosine is evaluated once per point and shared by both outputs; points - /// are processed in parallel with OpenMP when the workload is large. - /// Results do not depend on the thread count. + /// cosine is evaluated once per point and shared by both outputs. A + /// regular wave or a few components are worked through one component at + /// a time, with one array operation over all points; otherwise the points + /// are taken one at a time, in parallel with OpenMP when the workload is + /// large. Results do not depend on the thread count. void GetElevationAndPressureHead(const Eigen::Matrix3Xd& points, double time, double elevation_scale, @@ -169,6 +171,16 @@ class LinearDirectionalWaveField : public WaveBase { /// all components when there are no layers. std::pair ActiveComponents(double time) const; + /// GetElevationAndPressureHead for components [first, first + count), + /// one component at a time with array operations over the points. + void ElevationAndPressureHeadByComponent(const Eigen::Matrix3Xd& points, + double time, + double elevation_scale, + Eigen::Index first, + Eigen::Index count, + Eigen::VectorXd& elevation, + Eigen::VectorXd* pressure_head) const; + /// Cosine excitation ramp: 0.5*(1 - cos(pi*t/T_ramp)); 1 if no ramp or t >= T_ramp. double ExcitationRampFactor(double time) const; }; diff --git a/libs/hydro/src/geometry/submerged_volume.cpp b/libs/hydro/src/geometry/submerged_volume.cpp index 18c475f..49d266b 100644 --- a/libs/hydro/src/geometry/submerged_volume.cpp +++ b/libs/hydro/src/geometry/submerged_volume.cpp @@ -17,6 +17,9 @@ #include +#include "vec3.h" + +#include #include #include #include @@ -52,30 +55,24 @@ namespace { constexpr double kVolumeEpsilon = 1.0e-15; +// Points are Vec3 (plain doubles, see vec3.h) in the loop over the faces. + // Signed volume of the tetrahedron formed by triangle (a,b,c) and the origin. -inline double SignedTetVolume(const Eigen::Vector3d& a, - const Eigen::Vector3d& b, - const Eigen::Vector3d& c) { - return a.dot(b.cross(c)) / 6.0; +inline double SignedTetVolume(const Vec3& a, const Vec3& b, const Vec3& c) { + return Dot(a, Cross(b, c)) / 6.0; } // Accumulate a triangle's contribution to volume and first moment. -inline void AccumulateTriangle(const Eigen::Vector3d& a, - const Eigen::Vector3d& b, - const Eigen::Vector3d& c, - double& volume, - Eigen::Vector3d& moment) { - double v = SignedTetVolume(a, b, c); +inline void AccumulateTriangle(const Vec3& a, const Vec3& b, const Vec3& c, double& volume, Vec3& moment) { + const double v = SignedTetVolume(a, b, c); volume += v; // Centroid of the tetrahedron (origin, a, b, c) is (a+b+c)/4 moment += v * (a + b + c) / 4.0; } // Linearly interpolate between two points at a given z-level. -inline Eigen::Vector3d LerpAtZ(const Eigen::Vector3d& below, - const Eigen::Vector3d& above, - double z) { - double t = (z - below.z()) / (above.z() - below.z()); +inline Vec3 LerpAtZ(const Vec3& below, const Vec3& above, double z) { + const double t = (z - below.z) / (above.z - below.z); return below + t * (above - below); } @@ -89,30 +86,27 @@ SubmergedVolumeResult MeshSubmergedVolume::Compute( const Eigen::Affine3d& body_to_world, double waterplane_z) const { - const int nv = mesh_.num_vertices(); const int nf = mesh_.num_faces(); - // Transform all vertices to world frame - Eigen::MatrixXd world_verts(nv, 3); - for (int i = 0; i < nv; ++i) { - Eigen::Vector3d v = mesh_.vertices.row(i).transpose(); - world_verts.row(i) = (body_to_world * v).transpose(); - } + // Transform all vertices to world frame, one vertex per column + Eigen::Matrix3Xd world_verts; + mesh_.TransformVertices(body_to_world, world_verts); double total_volume = 0.0; - Eigen::Vector3d total_moment = Eigen::Vector3d::Zero(); + Vec3 total_moment; // Collect waterplane intersection edges for cap polygon - std::vector> cap_edges; + std::vector> cap_edges; + cap_edges.reserve(256); for (int f = 0; f < nf; ++f) { - const Eigen::Vector3d v0 = world_verts.row(mesh_.faces(f, 0)); - const Eigen::Vector3d v1 = world_verts.row(mesh_.faces(f, 1)); - const Eigen::Vector3d v2 = world_verts.row(mesh_.faces(f, 2)); + const Vec3 v0 = Column(world_verts, mesh_.faces(f, 0)); + const Vec3 v1 = Column(world_verts, mesh_.faces(f, 1)); + const Vec3 v2 = Column(world_verts, mesh_.faces(f, 2)); - const bool b0 = v0.z() <= waterplane_z; - const bool b1 = v1.z() <= waterplane_z; - const bool b2 = v2.z() <= waterplane_z; + const bool b0 = v0.z <= waterplane_z; + const bool b1 = v1.z <= waterplane_z; + const bool b2 = v2.z <= waterplane_z; const int below_count = static_cast(b0) + static_cast(b1) + static_cast(b2); @@ -132,33 +126,34 @@ SubmergedVolumeResult MeshSubmergedVolume::Compute( // We iterate the three edges; when an edge crosses the waterplane, // we compute the intersection point. - const Eigen::Vector3d* verts[3] = {&v0, &v1, &v2}; + const Vec3* verts[3] = {&v0, &v1, &v2}; const bool below[3] = {b0, b1, b2}; - std::vector submerged_poly; + std::array submerged_poly; // a clipped triangle has at most 4 submerged points + int poly_size = 0; // Waterline segment of this face, taken in the face's own winding // order: it runs from the point where the boundary leaves the water // (below -> above) to the point where it re-enters (above -> below). // The order must not depend on which vertex happens to be first. - Eigen::Vector3d clip_exit, clip_entry; + Vec3 clip_exit, clip_entry; bool has_exit = false; bool has_entry = false; for (int e = 0; e < 3; ++e) { int next = (e + 1) % 3; - const Eigen::Vector3d& va = *verts[e]; - const Eigen::Vector3d& vb = *verts[next]; + const Vec3& va = *verts[e]; + const Vec3& vb = *verts[next]; if (below[e]) { - submerged_poly.push_back(va); + submerged_poly[poly_size++] = va; } // Check if edge crosses waterplane if (below[e] != below[next]) { - const Eigen::Vector3d& lo = below[e] ? va : vb; - const Eigen::Vector3d& hi = below[e] ? vb : va; - Eigen::Vector3d ip = LerpAtZ(lo, hi, waterplane_z); - submerged_poly.push_back(ip); + const Vec3& lo = below[e] ? va : vb; + const Vec3& hi = below[e] ? vb : va; + const Vec3 ip = LerpAtZ(lo, hi, waterplane_z); + submerged_poly[poly_size++] = ip; if (below[e]) { clip_exit = ip; @@ -171,7 +166,7 @@ SubmergedVolumeResult MeshSubmergedVolume::Compute( } // Fan-triangulate the submerged polygon and accumulate - for (size_t i = 1; i + 1 < submerged_poly.size(); ++i) { + for (int i = 1; i + 1 < poly_size; ++i) { AccumulateTriangle(submerged_poly[0], submerged_poly[i], submerged_poly[i + 1], total_volume, total_moment); @@ -187,14 +182,14 @@ SubmergedVolumeResult MeshSubmergedVolume::Compute( // The cap is a planar polygon at z = waterplane_z formed by the clipping // edges. We fan-triangulate from the centroid of all clipping points. if (!cap_edges.empty()) { - Eigen::Vector3d cap_centroid = Eigen::Vector3d::Zero(); + Vec3 cap_centroid; int cap_point_count = 0; for (const auto& [a, b] : cap_edges) { cap_centroid += a + b; cap_point_count += 2; } - cap_centroid /= static_cast(cap_point_count); - cap_centroid.z() = waterplane_z; + cap_centroid = cap_centroid / static_cast(cap_point_count); + cap_centroid.z = waterplane_z; // Each clipping edge forms a cap triangle with the centroid. // Winding: cap normal should point upward (+z) to close the volume @@ -212,7 +207,7 @@ SubmergedVolumeResult MeshSubmergedVolume::Compute( result.centroid = Eigen::Vector3d::Zero(); } else { result.volume = total_volume; - result.centroid = total_moment / total_volume; + result.centroid = ToEigen(total_moment / total_volume); } return result; diff --git a/libs/hydro/src/geometry/triangle_mesh.cpp b/libs/hydro/src/geometry/triangle_mesh.cpp index c82474f..f464e90 100644 --- a/libs/hydro/src/geometry/triangle_mesh.cpp +++ b/libs/hydro/src/geometry/triangle_mesh.cpp @@ -19,6 +19,26 @@ Eigen::AlignedBox3d TriangleMesh::bounding_box() const { return box; } +void TriangleMesh::TransformVertices(const Eigen::Affine3d& body_to_world, Eigen::Matrix3Xd& world) const { + const int nv = num_vertices(); + world.resize(3, nv); + // world = R v + t, written out per coordinate on plain doubles (see + // vec3.h for the reason). + const Eigen::Matrix3d linear = body_to_world.linear(); + const Eigen::Vector3d translation = body_to_world.translation(); + const double r00 = linear(0, 0), r01 = linear(0, 1), r02 = linear(0, 2), tx = translation.x(); + const double r10 = linear(1, 0), r11 = linear(1, 1), r12 = linear(1, 2), ty = translation.y(); + const double r20 = linear(2, 0), r21 = linear(2, 1), r22 = linear(2, 2), tz = translation.z(); + for (int i = 0; i < nv; ++i) { + const double x = vertices(i, 0); + const double y = vertices(i, 1); + const double z = vertices(i, 2); + world(0, i) = r00 * x + r01 * y + r02 * z + tx; + world(1, i) = r10 * x + r11 * y + r12 * z + ty; + world(2, i) = r20 * x + r21 * y + r22 * z + tz; + } +} + TriangleMesh::TopologyInfo TriangleMesh::AnalyzeTopology() const { TopologyInfo info{}; info.is_closed = false; diff --git a/libs/hydro/src/geometry/vec3.h b/libs/hydro/src/geometry/vec3.h new file mode 100644 index 0000000..80fe827 --- /dev/null +++ b/libs/hydro/src/geometry/vec3.h @@ -0,0 +1,69 @@ +/********************************************************************* + * @file vec3.h + * @brief Three-component vector of plain doubles for the loops over mesh + * faces. + * + * The submerged-volume and pressure integrals apply a few vector + * operations to every triangle of a hull mesh at every time step. With + * Eigen::Vector3d these loops were measured to run an order of magnitude + * slower than the same formulas on plain doubles (MSVC with AVX2, Eigen 5). + * They therefore use the type below, which the compiler turns into ordinary + * scalar arithmetic. + * + * Internal to the geometry sources; the public interfaces keep Eigen types. + *********************************************************************/ + +#ifndef SEASTACK_HYDRO_GEOMETRY_VEC3_H +#define SEASTACK_HYDRO_GEOMETRY_VEC3_H + +#include + +#include + +namespace seastack::hydro::geometry { + +struct Vec3 { + double x = 0.0; + double y = 0.0; + double z = 0.0; +}; + +inline Vec3 operator+(const Vec3& a, const Vec3& b) { return {a.x + b.x, a.y + b.y, a.z + b.z}; } +inline Vec3 operator-(const Vec3& a, const Vec3& b) { return {a.x - b.x, a.y - b.y, a.z - b.z}; } +inline Vec3 operator*(double s, const Vec3& a) { return {s * a.x, s * a.y, s * a.z}; } +inline Vec3 operator*(const Vec3& a, double s) { return {a.x * s, a.y * s, a.z * s}; } +inline Vec3 operator/(const Vec3& a, double s) { return {a.x / s, a.y / s, a.z / s}; } + +inline Vec3& operator+=(Vec3& a, const Vec3& b) { + a.x += b.x; + a.y += b.y; + a.z += b.z; + return a; +} + +inline Vec3& operator-=(Vec3& a, const Vec3& b) { + a.x -= b.x; + a.y -= b.y; + a.z -= b.z; + return a; +} + +inline double Dot(const Vec3& a, const Vec3& b) { return a.x * b.x + a.y * b.y + a.z * b.z; } + +inline Vec3 Cross(const Vec3& a, const Vec3& b) { + return {a.y * b.z - a.z * b.y, a.z * b.x - a.x * b.z, a.x * b.y - a.y * b.x}; +} + +inline double Norm(const Vec3& a) { return std::sqrt(Dot(a, a)); } + +/// Column j of a 3 x N matrix (one point per column). +inline Vec3 Column(const Eigen::Matrix3Xd& points, Eigen::Index j) { + return {points(0, j), points(1, j), points(2, j)}; +} + +inline Vec3 FromEigen(const Eigen::Vector3d& a) { return {a.x(), a.y(), a.z()}; } +inline Eigen::Vector3d ToEigen(const Vec3& a) { return Eigen::Vector3d(a.x, a.y, a.z); } + +} // namespace seastack::hydro::geometry + +#endif // SEASTACK_HYDRO_GEOMETRY_VEC3_H diff --git a/libs/hydro/src/geometry/wetted_surface_pressure.cpp b/libs/hydro/src/geometry/wetted_surface_pressure.cpp index 9735add..71f4737 100644 --- a/libs/hydro/src/geometry/wetted_surface_pressure.cpp +++ b/libs/hydro/src/geometry/wetted_surface_pressure.cpp @@ -10,6 +10,8 @@ #include +#include "vec3.h" + #include #include #include @@ -39,29 +41,32 @@ Eigen::Matrix3Xd WettedSurfacePressureIntegrator::TransformVertices( void WettedSurfacePressureIntegrator::TransformVertices(const Eigen::Affine3d& body_to_world, Eigen::Matrix3Xd& world) const { - const int nv = mesh_.num_vertices(); - world.resize(3, nv); - for (int i = 0; i < nv; ++i) { - world.col(i) = body_to_world * Eigen::Vector3d(mesh_.vertices.row(i).transpose()); - } + mesh_.TransformVertices(body_to_world, world); } namespace { +// Points are Vec3 (plain doubles, see vec3.h) in the loop over the faces. struct PolygonPoint { - Eigen::Vector3d r; // position relative to the moment reference point [m] - double p; // pressure [Pa] + Vec3 r; // position relative to the moment reference point [m] + double p; // pressure [Pa] +}; + +/// Running totals of the loop over the faces. +struct Totals { + Vec3 force; // -int p n dS [N] + Vec3 moment; // -int p (r - r_ref) x n dS [N m] + double wetted_area = 0.0; // [m^2] }; /// Force, moment and area of one triangle with linear pressure (positions relative to r_ref). -void AccumulateTriangle(const PolygonPoint& a, const PolygonPoint& b, const PolygonPoint& c, - PressureIntegral& out) { - const Eigen::Vector3d area_vector = 0.5 * (b.r - a.r).cross(c.r - a.r); // A n +inline void AccumulateTriangle(const PolygonPoint& a, const PolygonPoint& b, const PolygonPoint& c, Totals& out) { + const Vec3 area_vector = 0.5 * Cross(b.r - a.r, c.r - a.r); // A n const double p_sum = a.p + b.p + c.p; out.force -= area_vector * (p_sum / 3.0); - const Eigen::Vector3d first_moment = (a.r * (a.p + p_sum) + b.r * (b.p + p_sum) + c.r * (c.p + p_sum)) / 12.0; - out.moment -= first_moment.cross(area_vector); - out.wetted_area += area_vector.norm(); + const Vec3 first_moment = (a.r * (a.p + p_sum) + b.r * (b.p + p_sum) + c.r * (c.p + p_sum)) / 12.0; + out.moment -= Cross(first_moment, area_vector); + out.wetted_area += Norm(area_vector); } } // namespace @@ -79,7 +84,8 @@ PressureIntegral WettedSurfacePressureIntegrator::Integrate( std::to_string(nv) + " entries"); } - PressureIntegral result; + Totals totals; + const Vec3 reference = FromEigen(reference_point); std::array poly; // a clipped triangle has at most 4 wet points for (int f = 0; f < mesh_.num_faces(); ++f) { @@ -95,23 +101,30 @@ PressureIntegral WettedSurfacePressureIntegrator::Integrate( const int i = idx[e]; const int j = idx[(e + 1) % 3]; if (wet[e]) { - poly[n++] = {world_vertices.col(i) - reference_point, vertex_pressure[i]}; + poly[n++] = {Column(world_vertices, i) - reference, vertex_pressure[i]}; } if (wet[e] != wet[(e + 1) % 3]) { // Point on edge i-j where d = 0, measured from the wet end. const int lo = wet[e] ? i : j; const int hi = wet[e] ? j : i; const double t = height_above_surface[lo] / (height_above_surface[lo] - height_above_surface[hi]); - const Eigen::Vector3d r = world_vertices.col(lo) + t * (world_vertices.col(hi) - world_vertices.col(lo)); + const Vec3 r_lo = Column(world_vertices, lo); + const Vec3 r_hi = Column(world_vertices, hi); + const Vec3 r = r_lo + t * (r_hi - r_lo); const double p = surface_pressure[lo] + t * (surface_pressure[hi] - surface_pressure[lo]); - poly[n++] = {r - reference_point, p}; + poly[n++] = {r - reference, p}; } } for (int k = 1; k + 1 < n; ++k) { - AccumulateTriangle(poly[0], poly[k], poly[k + 1], result); + AccumulateTriangle(poly[0], poly[k], poly[k + 1], totals); } } + + PressureIntegral result; + result.force = ToEigen(totals.force); + result.moment = ToEigen(totals.moment); + result.wetted_area = totals.wetted_area; return result; } diff --git a/libs/hydro/src/waves/linear_directional_wave_field.cpp b/libs/hydro/src/waves/linear_directional_wave_field.cpp index 2c0d4fc..3b9b3ba 100644 --- a/libs/hydro/src/waves/linear_directional_wave_field.cpp +++ b/libs/hydro/src/waves/linear_directional_wave_field.cpp @@ -472,6 +472,16 @@ void LinearDirectionalWaveField::GetElevationAndPressureHead(const Eigen::Matrix const std::pair active = ActiveComponents(time); const Eigen::Index c0 = active.first; const Eigen::Index n_comp = active.second; + + // A regular wave, or a few components: the loop below would handle arrays + // of one or a few entries at every point. Working through the points one + // component at a time gives arrays as long as the number of points. + constexpr Eigen::Index kFewComponents = 8; + if (n_comp >= 1 && n_comp <= kFewComponents) { + ElevationAndPressureHeadByComponent(points, time, elevation_scale, c0, n_comp, elevation, pressure_head); + return; + } + const auto kx = kx_.segment(c0, n_comp).array(); const auto ky = ky_.segment(c0, n_comp).array(); const auto wavenumbers = wavenumbers_.segment(c0, n_comp); @@ -529,6 +539,84 @@ void LinearDirectionalWaveField::GetElevationAndPressureHead(const Eigen::Matrix } } +void LinearDirectionalWaveField::ElevationAndPressureHeadByComponent(const Eigen::Matrix3Xd& points, + double time, + double elevation_scale, + Eigen::Index first, + Eigen::Index count, + Eigen::VectorXd& elevation, + Eigen::VectorXd* pressure_head) const { + const Eigen::Index n_points = points.cols(); + + // Coordinates as arrays over the points (a row of `points` is not contiguous in memory). + const Eigen::ArrayXd x = points.row(0).transpose(); + const Eigen::ArrayXd y = points.row(1).transpose(); + const Eigen::ArrayXd z = points.row(2).transpose(); + + Eigen::VectorXd scratch; + const Eigen::VectorXd& amplitudes = AmplitudesAt(time, scratch); + + // cos_phase(j, i) = cos(kx_i x_j + ky_i y_j + phi_i - omega_i t), kept for the pressure head. + // eta_j = scale * sum_i A_i cos_phase(j, i) + Eigen::ArrayXXd cos_phase(n_points, count); + Eigen::ArrayXd eta(n_points); + for (Eigen::Index i = 0; i < count; ++i) { + const Eigen::Index c = first + i; + const double theta = phases_[c] - omegas_[c] * time; + cos_phase.col(i) = (kx_[c] * x + ky_[c] * y + theta).cos(); + if (i == 0) { + eta = amplitudes[c] * cos_phase.col(i); + } else { + eta += amplitudes[c] * cos_phase.col(i); + } + } + eta *= elevation_scale; + elevation = eta.matrix(); + if (!pressure_head) return; + + // Points above the surface carry no pressure. + const Eigen::Array dry = (z - mwl_ - eta) > 0.0; + + // Wheeler-stretched depth below the surface, as in GetDynamicPressureHead + // (0 at dry points, where it is not used). + const bool infinite_depth = water_depth_ <= 0.0 || std::isinf(water_depth_); + Eigen::ArrayXd z_s(n_points); + if (infinite_depth) { + z_s = dry.select(0.0, (z - mwl_) - eta); + } else { + for (Eigen::Index j = 0; j < n_points; ++j) { + z_s[j] = dry[j] ? 0.0 + : GetWheelerStretchedPosition(Eigen::Vector3d(x[j], y[j], z[j]), eta[j], water_depth_, mwl_) + .z() - mwl_; + } + } + + bool all_deep = true; + for (Eigen::Index i = 0; i < count; ++i) { + all_deep = all_deep && is_in_deep_water(std::abs(wavenumbers_[first + i]), water_depth_); + } + + // head_j = sum_i A_i (depth factor of component i at z_s,j) cos_phase(j, i) + Eigen::ArrayXd head(n_points); + Eigen::ArrayXd depth_factor(n_points); + for (Eigen::Index i = 0; i < count; ++i) { + const Eigen::Index c = first + i; + if (all_deep) { + depth_factor = (std::abs(wavenumbers_[c]) * z_s).exp(); + } else { + for (Eigen::Index j = 0; j < n_points; ++j) { + depth_factor[j] = dry[j] ? 0.0 : AiryPressureDepthFactor(wavenumbers_[c], z_s[j], water_depth_); + } + } + if (i == 0) { + head = amplitudes[c] * depth_factor * cos_phase.col(i); + } else { + head += amplitudes[c] * depth_factor * cos_phase.col(i); + } + } + *pressure_head = dry.select(0.0, head).matrix(); +} + // ───────────────────────────────────────────────────────────────────────────── // Environment update // ───────────────────────────────────────────────────────────────────────────── diff --git a/tests/unit/test_wave_pressure.cpp b/tests/unit/test_wave_pressure.cpp index 77c81b3..4e947fd 100644 --- a/tests/unit/test_wave_pressure.cpp +++ b/tests/unit/test_wave_pressure.cpp @@ -84,6 +84,17 @@ std::vector MakeDirectionalSea(double depth) { MakeComponent(0.1, 2.5, depth, 3.0, 1.0)}; } +/// The first `count` components of a 16-component sea whose first four are +/// those of MakeDirectionalSea. +std::vector MakeSeaWithComponents(double depth, int count) { + std::vector comps = MakeDirectionalSea(depth); + for (int i = 0; i < 12; ++i) { + comps.push_back(MakeComponent(0.05 + 0.01 * i, 0.5 + 0.13 * i, depth, 0.4 * i - 2.0, 0.9 * i)); + } + comps.resize(static_cast(count)); + return comps; +} + } // namespace int main() { @@ -138,10 +149,13 @@ int main() { } // Batched GetElevationAndPressureHead matches the per-point functions, for - // points above and below the surface. 81 x 81 x 4 points with 4 components - // exceed the OpenMP threshold, so the threaded path is exercised. + // points above and below the surface. A regular wave (1 component) and + // the 4-component sea take the path that works through the points one + // component at a time; 16 components take the point-by-point path, and + // 81 x 81 x 4 points exceed its OpenMP threshold, so it runs threaded. + for (int n_components : {1, 4, 16}) { for (double depth : {0.0, 30.0, 6.0, 500.0}) { - const auto comps = MakeDirectionalSea(depth); + const auto comps = MakeSeaWithComponents(depth, n_components); LinearDirectionalWaveField field(comps, depth); double sum_a = 0.0; for (const auto& c : comps) sum_a += c.amplitude; @@ -178,7 +192,8 @@ int main() { std::abs(head[j] - field.GetDynamicPressureHead(p, t, eta_ref))); } } - const std::string tag = ", depth " + std::to_string(depth) + ", scale " + std::to_string(scale); + const std::string tag = ", " + std::to_string(n_components) + " component(s), depth " + + std::to_string(depth) + ", scale " + std::to_string(scale); TEST_NEAR(max_eta_err, 0.0, 1e-12 * sum_a, "batched eta matches GetElevation" + tag); TEST_NEAR(max_head_err, 0.0, 1e-12 * sum_a, "batched head matches GetDynamicPressureHead" + tag); TEST_ASSERT(zero_above, "batched head is zero above the surface" + tag); @@ -195,9 +210,11 @@ int main() { field.GetElevationAndPressureHead(cloud, 3.1, 1.0, eta_n, &head_n); omp_set_num_threads(max_threads); TEST_ASSERT(eta_1 == eta_n && head_1 == head_n, - "batched results identical for 1 and N threads, depth " + std::to_string(depth)); + "batched results identical for 1 and N threads, " + std::to_string(n_components) + + " component(s), depth " + std::to_string(depth)); #endif } + } // Default WaveBase implementation (eta table: elevation only, no pressure field). { From 28cd6241b68a4e3df596ce229a1a01c0d54e3656 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 12:37:37 +0000 Subject: [PATCH 11/12] Update the nonlinear Froude-Krylov cost figures in the example workflows. A regular wave now costs about 0.1 ms per time step for the 8064-face sphere mesh, and the wave evaluation runs in parallel only for more than 8 wave components. --- docs/usage/EXAMPLE_WORKFLOWS.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/docs/usage/EXAMPLE_WORKFLOWS.md b/docs/usage/EXAMPLE_WORKFLOWS.md index daf4ad8..641aca3 100644 --- a/docs/usage/EXAMPLE_WORKFLOWS.md +++ b/docs/usage/EXAMPLE_WORKFLOWS.md @@ -199,12 +199,12 @@ Limits: incident wave is not disturbed by the body. Slamming, breaking and green water are not modelled. - Cost scales with mesh vertices times wave components. For the 8064-face - IEA sphere mesh: about 0.4 ms per time step in a regular wave - (`test_benchmark_sphere_reg_nlfk`), and about 1.6 ms in an irregular sea + IEA sphere mesh: about 0.1 ms per time step in a regular wave + (`test_benchmark_sphere_reg_nlfk`), and about 1.5 ms in an irregular sea with 512 components (`test_benchmark_sphere_irreg_nlfk`; 16-core desktop, - 12 ms on one thread). The wave evaluation runs in parallel with OpenMP; set - `OMP_NUM_THREADS` to limit it. Use the coarsest mesh that resolves the - waterline. + 11 ms on one thread). With more than 8 wave components the wave evaluation + runs in parallel with OpenMP; set `OMP_NUM_THREADS` to limit it. Use the + coarsest mesh that resolves the waterline. ## Regular waves: constant-coefficient radiation From 5434c88f13fabe0a0c3e547bdbf08e418b6505c9 Mon Sep 17 00:00:00 2001 From: David Ogden <12831266+dav-og@users.noreply.github.com> Date: Tue, 1 Dec 2026 10:59:57 +0000 Subject: [PATCH 12/12] Evaluate the start-up of the excitation convolution from partial sums over the lags. While some lags still look back into the start-up ramp, the excitation convolution was corrected with a direct sum over all of those lags at every step. The ramp factor r(t - tau) of the linear and cosine ramps is a sum of a few products of a function of t and a function of tau, so the contribution of the ramping lags is a combination of sums over ranges of lags. These are now taken from partial sums stored at every 16th lag (or a larger spacing, to keep the tables below 64 MB); only the lags between a range end and the nearest stored sum are summed directly. The result is the same sum in another order and differs by rounding. After the ramp window the evaluation is unchanged. The case in which every lag is still inside the ramp, which used the direct sum, is evaluated in the same way. --- .../excitation_irf_component.h | 67 +++++- .../excitation_irf_component.cpp | 202 ++++++++++++++++-- .../unit/test_excitation_irf_closed_form.cpp | 40 +++- 3 files changed, 268 insertions(+), 41 deletions(-) diff --git a/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h b/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h index cfd2e20..b8f0e79 100644 --- a/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h +++ b/libs/hydro/include/seastack/hydro/force_components/excitation_irf_component.h @@ -36,14 +36,36 @@ * sum as (1) in a different order, not another excitation model, and costs * a few operations per component instead of one per component and lag. * - * The lags with t - tau_j < T_r are still inside the ramp. For those, (2) - * counts the full elevation where (1) has r times it, so their excess is - * subtracted: + * Start-up. Until t = T_r + (largest lag) some lags look back into the ramp. + * At time t the lags fall into three groups (the lag grid increases): * - * F(t) = (2) - sum_{j: t - tau_j < T_r} K(tau_j) w_j [1 - r(t - tau_j)] eta(t - tau_j). + * t - tau_j >= T_r r = 1 fully ramped: the first lags + * 0 < t - tau_j < T_r 0 < r < 1 ramping + * t - tau_j <= 0 r = 0 no contribution: the last lags * - * The number of such lags falls to zero at t = T_r + (largest lag). While - * every lag is inside the ramp, (1) is evaluated directly. + * The fully ramped lags are a sum like (2) over the first lags only. For the + * ramping lags, r(t - tau) is a sum of a few products of a function of t and + * a function of tau, + * + * linear ramp: r = (t / T_r) 1 - (1 / T_r) tau + * cosine ramp: r = 0.5 - 0.5 cos(pi t / T_r) cos(pi tau / T_r) + * - 0.5 sin(pi t / T_r) sin(pi tau / T_r) + * + * i.e. r(t - tau) = sum_m h_m(t) g_m(tau), so their contribution is + * + * sum_m h_m(t) sum_i A_i [ C_i,m cos(theta_i) - S_i,m sin(theta_i) ], + * C_i,m = sum_{j ramping} K(tau_j) w_j g_m(tau_j) cos(omega_i tau_j) (S_i,m with sin). + * + * Both are sums over a range of lags. They are taken from partial sums + * + * sum_{j < p} K(tau_j) w_j g_m(tau_j) cos(omega_i tau_j) (and sin) + * + * stored once at every B-th lag p (B = 16, or larger for large data). A sum + * over a range is the difference of two stored partial sums; the fewer than + * 2 B lags between the ends of a range and the nearest stored p are summed + * directly, as in (1). The result is (1) in another order. Each step then + * costs a few operations per component, plus those few lags, in place of one + * operation per component and lag. * * A live change of wave height multiplies eta(t - tau_j) by the envelope * e(t - tau_j). Where e has one value over all the lags, the result above is @@ -145,19 +167,44 @@ class ExcitationIrfComponent : public IHydroForceComponent { bool has_closed_form_ = false; std::vector closed_form_cos_; std::vector closed_form_sin_; - // Per step: A_i cos(theta_i), A_i sin(theta_i), and the elevation excess - // [1 - r(t - tau_j)] eta(t - tau_j) at the lags still inside the ramp. + // Per step: A_i cos(theta_i), A_i sin(theta_i), the force of each body in + // its heading frame, and the ramped elevation r(t - tau_j) eta(t - tau_j) + // at the lags that are summed directly. Eigen::ArrayXd phase_buffer_; // theta_i Eigen::VectorXd amplitude_cos_buffer_, amplitude_sin_buffer_; - Eigen::VectorXd ramp_excess_buffer_; + std::vector> heading_force_buffer_; + Eigen::VectorXd ramped_elevation_buffer_; + + // Start-up (see the file comment): partial sums over the first lags, + // stored at every ramp_block_-th lag. Checkpoint c stands at lag + // p_c = min(c ramp_block_, number of lags), c = 0 .. ramp_last_checkpoint_. + // For body b, ramp function m and checkpoint c, the N_comp x 6 matrices + // RampCosTable(b, m, c)(i, dof) = sum_{j < p_c} K(dof, tau_j) w_j g_m(tau_j) cos(omega_i tau_j) + // RampSinTable(b, m, c)(i, dof) = the same with sin(omega_i tau_j). + bool has_ramp_tables_ = false; + Eigen::Index ramp_block_ = 0; + Eigen::Index ramp_last_checkpoint_ = 0; + int ramp_terms_ = 0; ///< Number of functions g_m: 2 (linear ramp) or 3 (cosine ramp) + std::vector ramp_cos_tables_; + std::vector ramp_sin_tables_; /// Compute C_i and S_i. Requires the fast-path tables and an increasing lag grid. void BuildClosedForm(); + /// Compute the partial sums for the start-up. Requires the closed form. + void BuildRampTables(); + /// Position of the table of (body, ramp function, checkpoint) in ramp_cos_tables_ and ramp_sin_tables_. + std::size_t RampTableIndex(int body, int term, Eigen::Index checkpoint) const; /// Add the excitation at `time` from the closed form, multiplied by the /// wave-height factor e [-] that holds at every lag. Returns false, adding - /// nothing, when every lag is still inside the ramp. + /// nothing, when it cannot be used at this time (a ramp shape without + /// partial sums, during the start-up). bool ComputeClosedForm(const SystemState& state, double time, double wave_height_factor, BodyForces& inout_forces); + /// Start-up: fill heading_force_buffer_ for lags [0, first_zero), of which + /// those from first_ramping on are still ramping. + void ComputeRampWindow(double time, Eigen::Index first_ramping, Eigen::Index first_zero); + /// Add lags [begin, end) to heading_force_buffer_ by the direct sum (1). + void AddLagsDirectly(double time, Eigen::Index begin, Eigen::Index end); void TryBuildFastPath(); void ComputeFastPath(double time, Eigen::VectorXd& eta_at_tau) const; diff --git a/libs/hydro/src/force_components/excitation_irf_component.cpp b/libs/hydro/src/force_components/excitation_irf_component.cpp index 1c6ba67..c773781 100644 --- a/libs/hydro/src/force_components/excitation_irf_component.cpp +++ b/libs/hydro/src/force_components/excitation_irf_component.cpp @@ -17,6 +17,7 @@ #include #include +#include #include #include #include @@ -189,6 +190,7 @@ ExcitationIrfComponent::ExcitationIrfComponent( TryBuildFastPath(); BuildClosedForm(); + BuildRampTables(); } void ExcitationIrfComponent::TryBuildFastPath() { @@ -258,45 +260,203 @@ void ExcitationIrfComponent::BuildClosedForm() { has_closed_form_ = true; } +std::size_t ExcitationIrfComponent::RampTableIndex(int body, int term, Eigen::Index checkpoint) const { + const std::size_t per_term = static_cast(ramp_last_checkpoint_) + 1; + return (static_cast(body) * static_cast(ramp_terms_) + static_cast(term)) * + per_term + static_cast(checkpoint); +} + +void ExcitationIrfComponent::BuildRampTables() { + has_ramp_tables_ = false; + if (!has_closed_form_ || ramp_duration_ <= 0.0) return; + + const Eigen::VectorXd& tau = body_irfs_[0].time_vec; + const Eigen::Index n_lags = tau.size(); + const Eigen::Index n_comp = irf_cos_wt_.cols(); + + // g_m(tau_j), one column per function (see the header). + Eigen::MatrixXd lag_functions; + if (ramp_shape_ == RampShape::kLinear) { + lag_functions.resize(n_lags, 2); + lag_functions.col(0).setOnes(); + lag_functions.col(1) = tau; + } else if (ramp_shape_ == RampShape::kCosine) { + lag_functions.resize(n_lags, 3); + lag_functions.col(0).setOnes(); + lag_functions.col(1) = (tau.array() * (kPi / ramp_duration_)).cos(); + lag_functions.col(2) = (tau.array() * (kPi / ramp_duration_)).sin(); + } else { + return; // a ramp shape without this form: Compute() uses the direct sum during the start-up + } + ramp_terms_ = static_cast(lag_functions.cols()); + + // Lags between stored partial sums: 16, doubled while the tables would + // need more than kMaxTableBytes. + constexpr double kMaxTableBytes = 64.0e6; + auto last_checkpoint = [n_lags](Eigen::Index block) { return (n_lags + block - 1) / block; }; + auto table_bytes = [&](Eigen::Index block) { + return 2.0 * num_bodies_ * ramp_terms_ * static_cast(last_checkpoint(block) + 1) * kDofPerBody * + static_cast(n_comp) * sizeof(double); + }; + ramp_block_ = 16; + while (table_bytes(ramp_block_) > kMaxTableBytes && ramp_block_ < n_lags) { + ramp_block_ *= 2; + } + ramp_last_checkpoint_ = last_checkpoint(ramp_block_); + + const std::size_t n_tables = RampTableIndex(num_bodies_, 0, 0); + ramp_cos_tables_.assign(n_tables, Eigen::MatrixXd::Zero(n_comp, kDofPerBody)); + ramp_sin_tables_.assign(n_tables, Eigen::MatrixXd::Zero(n_comp, kDofPerBody)); + + for (int b = 0; b < num_bodies_; ++b) { + const auto& birf = body_irfs_[b]; + for (int m = 0; m < ramp_terms_; ++m) { + // K(dof, tau_j) w_j g_m(tau_j), 6 x lags. + const Eigen::MatrixXd scaled_kernel = + birf.kernel * (birf.width_vec.array() * lag_functions.col(m).array()).matrix().asDiagonal(); + // One wave component at a time: running sums over the lags, written + // out at each checkpoint. Plain doubles and one thread, so the + // tables do not depend on the number of threads. + for (Eigen::Index i = 0; i < n_comp; ++i) { + const double* cos_i = irf_cos_wt_.col(i).data(); + const double* sin_i = irf_sin_wt_.col(i).data(); + std::array sum_cos{}; + std::array sum_sin{}; + for (Eigen::Index c = 1; c <= ramp_last_checkpoint_; ++c) { + const Eigen::Index block_end = std::min(c * ramp_block_, n_lags); + for (Eigen::Index j = (c - 1) * ramp_block_; j < block_end; ++j) { + const double* k = scaled_kernel.col(j).data(); + for (int dof = 0; dof < kDofPerBody; ++dof) { + sum_cos[dof] += k[dof] * cos_i[j]; + sum_sin[dof] += k[dof] * sin_i[j]; + } + } + Eigen::MatrixXd& cos_table = ramp_cos_tables_[RampTableIndex(b, m, c)]; + Eigen::MatrixXd& sin_table = ramp_sin_tables_[RampTableIndex(b, m, c)]; + for (int dof = 0; dof < kDofPerBody; ++dof) { + cos_table(i, dof) = sum_cos[dof]; + sin_table(i, dof) = sum_sin[dof]; + } + } + } + } + } + heading_force_buffer_.resize(static_cast(num_bodies_)); + ramped_elevation_buffer_.resize(n_lags); + has_ramp_tables_ = true; +} + +void ExcitationIrfComponent::AddLagsDirectly(double time, Eigen::Index begin, Eigen::Index end) { + const Eigen::Index count = end - begin; + if (count <= 0) return; + const Eigen::VectorXd& tau = body_irfs_[0].time_vec; + + // r(t - tau_j) eta(t - tau_j) at these lags, as in ComputeFastPath(). + auto ramped_elevation = ramped_elevation_buffer_.head(count); + ramped_elevation.noalias() = irf_cos_wt_.middleRows(begin, count) * amplitude_cos_buffer_; + ramped_elevation.noalias() -= irf_sin_wt_.middleRows(begin, count) * amplitude_sin_buffer_; + for (Eigen::Index s = 0; s < count; ++s) { + ramped_elevation[s] *= RampFactor(time - tau[begin + s]); + } + for (int b = 0; b < num_bodies_; ++b) { + const auto& birf = body_irfs_[b]; + Eigen::Matrix& f_heading = heading_force_buffer_[static_cast(b)]; + for (Eigen::Index s = 0; s < count; ++s) { + const Eigen::Index lag = begin + s; + f_heading += birf.kernel.col(lag) * (birf.width_vec[lag] * ramped_elevation[s]); + } + } +} + +void ExcitationIrfComponent::ComputeRampWindow(double time, Eigen::Index first_ramping, Eigen::Index first_zero) { + const Eigen::Index n_lags = body_irfs_[0].time_vec.size(); + auto lag_of = [this, n_lags](Eigen::Index checkpoint) { return std::min(checkpoint * ramp_block_, n_lags); }; + + // Checkpoints around the two ends of the ramping lags [first_ramping, first_zero): + // full the last one at or before first_ramping: every lag before it is fully ramped + // begin the first one at or after first_ramping + // end the last one at or before first_zero + const Eigen::Index full = first_ramping / ramp_block_; + const Eigen::Index begin = std::min((first_ramping + ramp_block_ - 1) / ramp_block_, ramp_last_checkpoint_); + const Eigen::Index end = (first_zero == n_lags) ? ramp_last_checkpoint_ : first_zero / ramp_block_; + const bool has_table_range = begin < end; // ramping lags [lag_of(begin), lag_of(end)) come from the tables + + // r(t - tau) = sum_m h_m(t) g_m(tau) for the ramping lags (see the header). + std::array h{}; + if (ramp_shape_ == RampShape::kLinear) { + h[0] = time / ramp_duration_; + h[1] = -1.0 / ramp_duration_; + } else { + const double angle = kPi * time / ramp_duration_; + h[0] = 0.5; + h[1] = -0.5 * std::cos(angle); + h[2] = -0.5 * std::sin(angle); + } + + // sum_i A_i [ (partial sum with cos)_i cos(theta_i) - (partial sum with sin)_i sin(theta_i) ] for one table. + auto table_force = [this](int body, int term, Eigen::Index checkpoint) -> Eigen::Matrix { + const std::size_t index = RampTableIndex(body, term, checkpoint); + return ramp_cos_tables_[index].transpose() * amplitude_cos_buffer_ - + ramp_sin_tables_[index].transpose() * amplitude_sin_buffer_; + }; + + for (int b = 0; b < num_bodies_; ++b) { + Eigen::Matrix f_heading = table_force(b, 0, full); // fully ramped lags before `full` + if (has_table_range) { + for (int m = 0; m < ramp_terms_; ++m) { + f_heading += h[static_cast(m)] * (table_force(b, m, end) - table_force(b, m, begin)); + } + } + heading_force_buffer_[static_cast(b)] = f_heading; + } + + // The lags between the checkpoints and the ends of the ranges. + if (has_table_range) { + AddLagsDirectly(time, lag_of(full), lag_of(begin)); + AddLagsDirectly(time, lag_of(end), first_zero); + } else { + AddLagsDirectly(time, lag_of(full), first_zero); + } +} + bool ExcitationIrfComponent::ComputeClosedForm(const SystemState& state, double time, double wave_height_factor, BodyForces& inout_forces) { const Eigen::VectorXd& tau = body_irfs_[0].time_vec; const Eigen::Index n_lags = tau.size(); - // Lags still inside the ramp: t - tau_j < T_r, i.e. tau_j > t - T_r. - // The lag grid increases, so they are the lags from `first_in_ramp` on. - Eigen::Index first_in_ramp = n_lags; + // Lags by the value of the ramp at their sample time t - tau_j. The lag + // grid increases, so: + // j < first_ramping t - tau_j >= T_r, r = 1 + // first_ramping <= j < first_zero 0 < r < 1 + // j >= first_zero t - tau_j <= 0, r = 0 + Eigen::Index first_ramping = n_lags; + Eigen::Index first_zero = n_lags; if (ramp_duration_ > 0.0) { const double* begin = tau.data(); - first_in_ramp = std::upper_bound(begin, begin + n_lags, time - ramp_duration_) - begin; - if (first_in_ramp == 0) { - return false; // every lag is inside the ramp: the direct sum costs less - } + first_ramping = std::upper_bound(begin, begin + n_lags, time - ramp_duration_) - begin; + first_zero = std::lower_bound(begin, begin + n_lags, time) - begin; + } + const bool ramp_over = first_ramping == n_lags; + if (!ramp_over && !has_ramp_tables_) { + return false; } - const Eigen::Index n_in_ramp = n_lags - first_in_ramp; // A_i cos(theta_i) and A_i sin(theta_i), theta_i = phi_i - omega_i t. phase_buffer_ = comp_phases_.array() - comp_omegas_.array() * time; amplitude_cos_buffer_ = (comp_amplitudes_.array() * phase_buffer_.cos()).matrix(); amplitude_sin_buffer_ = (comp_amplitudes_.array() * phase_buffer_.sin()).matrix(); - // Elevation excess at the lags inside the ramp: [1 - r(t - tau_j)] eta(t - tau_j). - if (n_in_ramp > 0) { - ramp_excess_buffer_.noalias() = irf_cos_wt_.bottomRows(n_in_ramp) * amplitude_cos_buffer_; - ramp_excess_buffer_.noalias() -= irf_sin_wt_.bottomRows(n_in_ramp) * amplitude_sin_buffer_; - for (Eigen::Index s = 0; s < n_in_ramp; ++s) { - ramp_excess_buffer_[s] *= 1.0 - RampFactor(time - tau[first_in_ramp + s]); - } + if (!ramp_over) { + ComputeRampWindow(time, first_ramping, first_zero); } // Excitation in each body's heading frame, rotated to world (heading_frame.h). for (int b = 0; b < num_bodies_; ++b) { - const auto& birf = body_irfs_[b]; - Eigen::Matrix f_heading = - closed_form_cos_[b] * amplitude_cos_buffer_ - closed_form_sin_[b] * amplitude_sin_buffer_; - for (Eigen::Index s = 0; s < n_in_ramp; ++s) { - const Eigen::Index lag = first_in_ramp + s; - f_heading -= birf.kernel.col(lag) * (birf.width_vec[lag] * ramp_excess_buffer_[s]); + Eigen::Matrix f_heading; + if (ramp_over) { + f_heading = closed_form_cos_[b] * amplitude_cos_buffer_ - closed_form_sin_[b] * amplitude_sin_buffer_; + } else { + f_heading = heading_force_buffer_[static_cast(b)]; } f_heading *= wave_height_factor; const Eigen::Matrix3d heading_to_world = HeadingToWorld(state.bodies[b]); diff --git a/tests/unit/test_excitation_irf_closed_form.cpp b/tests/unit/test_excitation_irf_closed_form.cpp index 0958fbb..a493003 100644 --- a/tests/unit/test_excitation_irf_closed_form.cpp +++ b/tests/unit/test_excitation_irf_closed_form.cpp @@ -10,14 +10,17 @@ * trapezoid weights of the lag grid, r the start-up ramp, e the wave-height * envelope and eta the undisturbed elevation at the origin. For a wave made * of components the component evaluates the lag sum in closed form once the - * ramp is over, with a correction for the lags still inside the ramp (see - * excitation_irf_component.h). This test checks every branch against the - * sum above evaluated term by term: + * ramp is over, and from stored partial sums over the lags while some lags + * still look back into the ramp (see excitation_irf_component.h). This test + * checks every branch against the sum above evaluated term by term: * - no ramp (closed form from the start); - * - linear and cosine ramps: early (correction over most lags), late - * (few lags) and after the ramp window (closed form only); + * - linear and cosine ramps: early (most lags ramping or before the + * start), late (few lags) and after the ramp window (closed form only); + * - times at which the first ramping lag, or the first lag before the + * start, moves one lag at a time through 70 consecutive lags, so that + * each falls on a stored partial sum and on every position between two; * - a ramp longer than the kernel reaches forward, so that every lag is - * inside it at first (direct sum), then the transition to the closed form; + * ramping or before the start at first; * - a truncated kernel; * - a change of wave height: before it enters the kernel window (closed * form), while it is inside (direct sum with the envelope) and after it @@ -72,6 +75,7 @@ struct CaseSetup { double truncation_time = 0.0; // [s], 0 = full kernel double wave_height_change_time = -1.0; // [s], < 0 = none; the change takes 20 s std::vector times; // [s] at which the force is checked + bool sweep_lags = false; // also check at times that step through consecutive lags (see the file comment) }; std::shared_ptr MakeWave() { @@ -142,13 +146,26 @@ double RunCase(const CaseSetup& setup) { } const Eigen::VectorXd weights = TrapezoidWeights(tau); + std::vector times = setup.times; + if (setup.sweep_lags) { + // t = tau_k puts the first lag before the start at k; t = T_r + tau_k + // puts the first ramping lag at k or k + 1. + constexpr Eigen::Index kSweep = 70; + const Eigen::Index first = (tau.array() < 2.0).count(); // first lag at or after 2 s + for (Eigen::Index k = first; k < std::min(first + kSweep, tau.size()); ++k) times.push_back(tau[k]); + const Eigen::Index start = (tau.array() < 2.0 - setup.ramp_duration).count(); + for (Eigen::Index k = start; k < std::min(start + kSweep, tau.size()); ++k) { + times.push_back(setup.ramp_duration + tau[k]); + } + } + SystemState state; state.bodies.resize(setup.num_bodies); double scale = 0.0; double worst = 0.0; std::vector> expected(setup.num_bodies); for (int pass = 0; pass < 2; ++pass) { - for (double t : setup.times) { + for (double t : times) { for (int b = 0; b < setup.num_bodies; ++b) expected[b].setZero(); for (Eigen::Index s = 0; s < tau.size(); ++s) { const double t_sample = t - tau[s]; @@ -190,8 +207,9 @@ int main() { cases.push_back({"rm3, no ramp", rm3, 2, 0.0, RampShape::kLinear, 0.0, -1.0, {0.0, 3.7, 50.0, 300.0}}); // 60 s ramp: lags leave it between t = -97 s and t = 217 s. cases.push_back({"rm3, linear ramp", rm3, 2, 60.0, RampShape::kLinear, 0.0, -1.0, - {0.0, 0.01, 12.3, 59.99, 60.0, 61.0, 150.0, 216.9, 217.1, 400.0}}); - cases.push_back({"rm3, cosine ramp", rm3, 2, 60.0, RampShape::kCosine, 0.0, -1.0, {0.0, 30.0, 100.0, 216.0, 250.0}}); + {0.0, 0.01, 12.3, 59.99, 60.0, 61.0, 150.0, 216.9, 217.1, 400.0}, true}); + cases.push_back({"rm3, cosine ramp", rm3, 2, 60.0, RampShape::kCosine, 0.0, -1.0, {0.0, 30.0, 100.0, 216.0, 250.0}, + true}); // 300 s ramp: every lag is inside it until t = 143 s, none after 457 s. cases.push_back({"rm3, ramp longer than the kernel", rm3, 2, 300.0, RampShape::kLinear, 0.0, -1.0, {0.0, 100.0, 142.9, 143.1, 144.0, 300.0, 456.9, 457.1, 600.0}}); @@ -204,7 +222,9 @@ int main() { cases.push_back({"oswec, wave height changed at 150 s", oswec, 2, 60.0, RampShape::kLinear, 0.0, 150.0, {10.0, 100.0, 119.9, 120.1, 160.0, 199.9, 200.1, 300.0}}); cases.push_back({"oswec, linear ramp", oswec, 2, 60.0, RampShape::kLinear, 0.0, -1.0, - {0.0, 29.9, 30.1, 45.0, 89.9, 90.1, 200.0}}); + {0.0, 29.9, 30.1, 45.0, 89.9, 90.1, 200.0}, true}); + cases.push_back({"oswec, cosine ramp of 7.3 s", oswec, 2, 7.3, RampShape::kCosine, 0.0, -1.0, + {0.0, 3.0, 7.2, 7.4, 20.0, 37.2, 37.4, 100.0}, true}); cases.push_back({"oswec, no ramp", oswec, 2, 0.0, RampShape::kLinear, 0.0, -1.0, {0.0, 17.0, 400.0}}); for (const CaseSetup& c : cases) {