From 869bf0865be445215c88ee954f86abecafe71a9e Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 11:16:37 +0000 Subject: [PATCH 1/8] Add contact dynamics that solves growth and contact together Simulation.step(dt, ContactDynamicsParameters) advances cell growth and contact in one convex problem per substep: contact forces are non-negative, gaps stay non-negative, and a cell's elongation responds to the axial load its contacts put on it. Rows that the move opens are added to the same solve, and a substep that fails is retried at half its length. The CPU backend implements the solve; a backend without the feature rejects the step. A box or cylinder container reports one wall contact per face to this solve, so a cell end in a corner is held by every wall that meets there. MechanicsConfig(contact_dynamics=ContactDynamicsConfig(...)) selects the solve in a native controller, and payloads without the entry keep the relaxation passes. --- CMakeLists.txt | 6 + cpp/core/contact_dynamics.cpp | 525 ++++++++++++++++++ cpp/core/contact_solver.hpp | 83 +++ cpp/core/contact_stepper.hpp | 24 + cpp/core/simulation.cpp | 53 +- cpp/cpu/cpu_backend.cpp | 14 +- cpp/cpu/cpu_constraints.cpp | 116 +++- cpp/cpu/cpu_contact_dynamics.cpp | 222 ++++++++ cpp/include/microsimulator/backend.hpp | 6 + cpp/include/microsimulator/constraints.hpp | 10 + .../microsimulator/contact_dynamics.hpp | 165 ++++++ cpp/include/microsimulator/simulation.hpp | 12 + cpp/include/microsimulator/types.hpp | 1 + cpp/python/bindings.cpp | 63 ++- docs/architecture/0002-contact-mechanics.md | 2 + docs/architecture/0014-native-controllers.md | 2 + docs/architecture/0026-contact-dynamics.md | 84 +++ docs/architecture/README.md | 1 + python/src/microsimulator/__init__.py | 12 + python/src/microsimulator/_core.pyi | 60 ++ python/src/microsimulator/controller.py | 200 ++++++- python/tests/test_contact_dynamics.py | 420 ++++++++++++++ tests/cpp/contact_dynamics_test.cpp | 442 +++++++++++++++ 23 files changed, 2494 insertions(+), 29 deletions(-) create mode 100644 cpp/core/contact_dynamics.cpp create mode 100644 cpp/core/contact_solver.hpp create mode 100644 cpp/core/contact_stepper.hpp create mode 100644 cpp/cpu/cpu_contact_dynamics.cpp create mode 100644 cpp/include/microsimulator/contact_dynamics.hpp create mode 100644 docs/architecture/0026-contact-dynamics.md create mode 100644 python/tests/test_contact_dynamics.py create mode 100644 tests/cpp/contact_dynamics_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index f4c3653..0249429 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -22,6 +22,7 @@ add_library(microsimulator_core STATIC cpp/core/channels.cpp cpp/core/checkpoint.cpp cpp/core/checkpoint_file.cpp + cpp/core/contact_dynamics.cpp cpp/core/contact_graph.cpp cpp/core/constraints.cpp cpp/core/coupled_rates.cpp @@ -38,6 +39,7 @@ add_library(microsimulator_core STATIC cpp/cpu/cpu_backend.cpp cpp/cpu/cpu_contacts.cpp cpp/cpu/cpu_constraints.cpp + cpp/cpu/cpu_contact_dynamics.cpp cpp/cpu/cpu_coupled.cpp cpp/cpu/cpu_flow.cpp cpp/cpu/cpu_mechanics.cpp @@ -217,6 +219,10 @@ if(MICROSIMULATOR_BUILD_TESTS) target_link_libraries(microsimulator_mechanics_operator_test PRIVATE microsimulator::core) add_test(NAME mechanics_operator COMMAND microsimulator_mechanics_operator_test) + add_executable(microsimulator_contact_dynamics_test tests/cpp/contact_dynamics_test.cpp) + target_link_libraries(microsimulator_contact_dynamics_test PRIVATE microsimulator::core) + add_test(NAME contact_dynamics COMMAND microsimulator_contact_dynamics_test) + add_executable(microsimulator_mechanics_integration_test tests/cpp/mechanics_integration_test.cpp) target_link_libraries(microsimulator_mechanics_integration_test PRIVATE microsimulator::core) add_test(NAME mechanics_integration COMMAND microsimulator_mechanics_integration_test) diff --git a/cpp/core/contact_dynamics.cpp b/cpp/core/contact_dynamics.cpp new file mode 100644 index 0000000..ec3f189 --- /dev/null +++ b/cpp/core/contact_dynamics.cpp @@ -0,0 +1,525 @@ +#include "microsimulator/contact_dynamics.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/contact_stepper.hpp" +#include "microsimulator/mechanics.hpp" + +namespace microsimulator { +namespace { + +// Cylinder lengths below this have no axis to elongate along. +constexpr float minimum_lever_length = 1.0e-6F; +// The solve converges to this fraction of the overlap tolerance, which leaves +// the rest for the error of moving the cells along a linearized gap. +constexpr float solve_tolerance_fraction = 0.25F; +// Fraction of the load scale of the growth response that an accepted overlap +// may add to a contact force. +constexpr float load_resolution_fraction = 0.1F; +// A rotation this large in one substep is outside the linearization the +// substep's rows rest on. +constexpr float maximum_substep_rotation = 0.5F; + +[[nodiscard]] bool finite(const Vec3& value) { + return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z); +} + +struct Geometry { + std::vector positions; + std::vector directions; + std::vector lengths; + + [[nodiscard]] std::size_t size() const noexcept { + return lengths.size(); + } +}; + +[[nodiscard]] Geometry capture(const WorldState& state) { + const auto view = state.geometry_state(); + Geometry geometry; + geometry.positions.reserve(view.size()); + geometry.directions.reserve(view.size()); + geometry.lengths.assign(view.lengths.begin(), view.lengths.end()); + for (std::size_t slot = 0; slot < view.size(); ++slot) { + geometry.positions.push_back( + {view.position_x[slot], view.position_y[slot], view.position_z[slot]}); + geometry.directions.push_back( + {view.direction_x[slot], view.direction_y[slot], view.direction_z[slot]}); + } + return geometry; +} + +void restore(WorldState& state, const Geometry& geometry) { + for (std::size_t slot = 0; slot < geometry.size(); ++slot) { + state.set_cell_geometry(static_cast(slot), geometry.positions[slot], + geometry.directions[slot], geometry.lengths[slot]); + } +} + +// A contact reduced to what a row needs. `partner` is the second cell's slot +// for a pair and the constraint for a wall. +struct Touch { + Slot first_slot{invalid_slot}; + Slot second_slot{invalid_slot}; + std::uint64_t partner{0}; + Vec3 point{}; + Vec3 normal{}; + float separation{0.0F}; +}; + +using TouchKey = std::tuple; + +[[nodiscard]] TouchKey key_of(const Touch& touch) { + return {touch.first_slot, touch.second_slot == invalid_slot, touch.partner}; +} + +[[nodiscard]] std::vector find_touches(const WorldState& state, + const ConstraintSet& constraints, + ComputeBackend& backend, + ContactParameters contact_parameters, + ConstraintContactParameters constraint_parameters, + float margin) { + contact_parameters.activation_margin = margin; + constraint_parameters.activation_margin = margin; + std::vector touches; + const auto pairs = backend.find_cell_contacts(state, contact_parameters); + touches.reserve(pairs.size()); + for (const auto& contact : pairs.contacts()) { + touches.push_back({ + .first_slot = contact.first_slot, + .second_slot = contact.second_slot, + .partner = contact.second_slot, + .point = contact.point_on_first, + .normal = contact.normal, + .separation = contact.signed_separation, + }); + } + if (!constraints.empty()) { + const auto walls = find_external_contact_faces(state, constraints, constraint_parameters); + for (const auto& contact : walls.contacts()) { + touches.push_back({ + .first_slot = contact.cell_slot, + .partner = contact.constraint_id, + .point = contact.point_on_cell, + .normal = contact.normal, + .separation = contact.signed_separation, + }); + } + } + return touches; +} + +// The fraction of a cell's elongation that closes a contact whose centerline +// point is `centerline_point` and whose normal points out of the cell. The +// cylinder stretches uniformly about its center and the caps ride on its ends. +[[nodiscard]] float length_lever(const Geometry& geometry, Slot slot, Vec3 centerline_point, + Vec3 outward_normal) { + const auto length = geometry.lengths[slot]; + if (length <= minimum_lever_length) { + return 0.0F; + } + const auto& axis = geometry.directions[slot]; + const auto coordinate = dot(axis, centerline_point - geometry.positions[slot]) / length; + return std::max(0.0F, std::clamp(coordinate, -0.5F, 0.5F) * dot(axis, outward_normal)); +} + +// The row of a contact at the given geometry. A contact deeper than the +// recovery limit asks for only that much separation, and is stiffened in +// proportion so that a pair unable to separate still meets the full contact +// force of its overlap. +[[nodiscard]] ContactRow make_row(const Geometry& geometry, std::span radii, + const Touch& touch, float compliance, float recovery) { + ContactRow row; + row.first_slot = touch.first_slot; + row.second_slot = touch.second_slot; + row.offset = std::max(touch.separation, -recovery); + row.compliance = touch.separation < -recovery ? compliance * recovery / -touch.separation + : compliance; + const auto& normal = touch.normal; + const auto first_arm = cross(touch.point - geometry.positions[touch.first_slot], normal); + row.first_jacobian = {-normal.x, -normal.y, -normal.z, + -first_arm.x, -first_arm.y, -first_arm.z}; + const auto first_centerline = touch.point - normal * radii[touch.first_slot]; + row.first_length_lever = length_lever(geometry, touch.first_slot, first_centerline, normal); + if (touch.second_slot != invalid_slot) { + const auto second_arm = cross(touch.point - geometry.positions[touch.second_slot], normal); + row.second_jacobian = {normal.x, normal.y, normal.z, + second_arm.x, second_arm.y, second_arm.z}; + const auto second_centerline = + touch.point + normal * (touch.separation + radii[touch.second_slot]); + row.second_length_lever = + length_lever(geometry, touch.second_slot, second_centerline, normal * -1.0F); + } + return row; +} + +// Mobilities come from the geometry the state holds. Elongation rates come +// from `rate_lengths`, the lengths at the start of the whole step, so that the +// elongation of an unloaded cell does not depend on how the step is divided. +[[nodiscard]] std::vector make_bodies(const WorldState& state, + std::span rate_lengths, + float drag) { + const auto geometry = state.geometry_state(); + const auto attributes = state.cell_attributes(); + std::vector bodies(geometry.size()); + for (std::size_t slot = 0; slot < bodies.size(); ++slot) { + auto& body = bodies[slot]; + body.axis = {geometry.direction_x[slot], geometry.direction_y[slot], + geometry.direction_z[slot]}; + body.length_rate = attributes.growth_rates[slot] * rate_lengths[slot]; + if (attributes.fixed[slot] != 0) { + continue; + } + const auto radius = geometry.radii[slot]; + const auto total_length = geometry.lengths[slot] + 2.0F * radius; + const auto translational = drag * total_length; + const auto axial = 0.5F * translational * radius * radius; + const auto transverse = + translational * ((total_length * total_length) + 3.0F * radius * radius) / 12.0F; + body.translational_mobility = 1.0F / translational; + body.axial_mobility = 1.0F / axial; + body.transverse_mobility = 1.0F / transverse; + } + return bodies; +} + +[[nodiscard]] float predicted_rate(const ContactRow& row, const ContactResponse& response) { + const auto product = [](const std::array& left, const std::array& right) { + auto result = 0.0F; + for (std::size_t index = 0; index < left.size(); ++index) { + result += left[index] * right[index]; + } + return result; + }; + auto rate = product(row.first_jacobian, response.velocities[row.first_slot]) - + row.first_length_lever * response.length_rates[row.first_slot]; + if (row.second_slot != invalid_slot) { + rate += product(row.second_jacobian, response.velocities[row.second_slot]) - + row.second_length_lever * response.length_rates[row.second_slot]; + } + return rate; +} + +// The geometry after moving every cell for `dt` under a response, or nothing +// when the move is not a valid geometry. +[[nodiscard]] std::optional moved(const Geometry& base, const ContactResponse& response, + float dt) { + auto result = base; + for (std::size_t slot = 0; slot < base.size(); ++slot) { + const auto& velocity = response.velocities[slot]; + const Vec3 rotation{velocity[3] * dt, velocity[4] * dt, velocity[5] * dt}; + if (!finite(rotation) || norm(rotation) > maximum_substep_rotation) { + return std::nullopt; + } + result.positions[slot] = + base.positions[slot] + Vec3{velocity[0], velocity[1], velocity[2]} * dt; + result.directions[slot] = + rotate_axis_angle(base.directions[slot], rotation, maximum_substep_rotation); + result.lengths[slot] = base.lengths[slot] + response.length_rates[slot] * dt; + if (!finite(result.positions[slot]) || !finite(result.directions[slot]) || + !std::isfinite(result.lengths[slot]) || result.lengths[slot] < 0.0F) { + return std::nullopt; + } + } + return result; +} + +// The overlap accepted at the end of a substep. An overlap of e that a jammed +// pair cannot recover stays as a contact force of e * stiffness. Where growth +// responds to load, the tolerance is therefore held to the overlap that a +// small fraction of the load scale of that response presses into a contact. +[[nodiscard]] float effective_overlap_tolerance(const ContactDynamicsParameters& parameters) { + auto load_scale = 0.0F; + if (parameters.growth.law == GrowthLoadLaw::linear) { + load_scale = parameters.growth.stall_load - parameters.growth.free_load; + } else if (parameters.growth.law == GrowthLoadLaw::exponential && + parameters.growth.sensitivity > 0.0F) { + load_scale = 1.0F / parameters.growth.sensitivity; + } + if (load_scale <= 0.0F) { + return parameters.overlap_tolerance; + } + return std::min(parameters.overlap_tolerance, + load_resolution_fraction * load_scale / parameters.contact_stiffness); +} + +struct Substep { + Geometry geometry; + std::vector loads; + std::uint32_t refinements{0}; + std::size_t rows{0}; + float max_overlap{0.0F}; +}; + +// One substep from the geometry the state holds. On failure the state holds +// that geometry again. +[[nodiscard]] std::optional advance_substep( + WorldState& state, const Geometry& base, std::span rate_lengths, + const ConstraintSet& constraints, ComputeBackend& backend, float dt, + const ContactDynamicsParameters& parameters, + const ContactParameters& contact_parameters, + const ConstraintContactParameters& constraint_parameters, std::uint64_t& iterations) { + const auto radii = state.geometry_state().radii; + const auto bodies = make_bodies(state, rate_lengths, parameters.drag); + const auto candidates = find_touches(state, constraints, backend, contact_parameters, + constraint_parameters, parameters.candidate_margin); + std::vector rows; + std::vector keys; + rows.reserve(candidates.size()); + keys.reserve(candidates.size()); + auto starting_overlap = 0.0F; + const auto compliance = 1.0F / parameters.contact_stiffness; + for (const auto& touch : candidates) { + starting_overlap = std::max(starting_overlap, -touch.separation); + rows.push_back(make_row(base, radii, touch, compliance, parameters.max_overlap_recovery)); + keys.push_back(key_of(touch)); + } + // Overlap deeper than one substep recovers is accepted for now. + const auto tolerance = effective_overlap_tolerance(parameters); + const auto slack = + tolerance + std::max(0.0F, starting_overlap - parameters.max_overlap_recovery); + const ContactSolveParameters solve_parameters{ + .tolerance = solve_tolerance_fraction * tolerance, + .max_iterations = parameters.max_iterations, + }; + + std::vector multipliers(rows.size(), 0.0F); + for (std::uint32_t refinement = 0; refinement <= parameters.max_refinements; ++refinement) { + const ContactSystem system{ + .rows = rows, + .bodies = bodies, + .dt = dt, + .growth = parameters.growth, + }; + auto solve = backend.solve_contact_forces(system, multipliers, solve_parameters); + iterations += solve.report.iterations; + if (solve.report.status != ContactSolveStatus::converged) { + break; + } + multipliers = std::move(solve.multipliers); + const auto response = evaluate_contact_response(system, multipliers); + const auto trial = moved(base, response, dt); + if (!trial.has_value()) { + break; + } + restore(state, *trial); + + const auto found = + find_touches(state, constraints, backend, contact_parameters, constraint_parameters, 0.0F); + std::map forces; + for (std::size_t index = 0; index < rows.size(); ++index) { + forces[keys[index]] += multipliers[index]; + } + std::vector overlapping; + auto max_overlap = 0.0F; + for (const auto& touch : found) { + max_overlap = std::max(max_overlap, -touch.separation); + const auto force = forces.find(key_of(touch)); + const auto allowed = slack + (force == forces.end() ? 0.0F : force->second * compliance); + if (touch.separation < -allowed) { + overlapping.push_back(touch); + } + } + if (overlapping.empty()) { + return Substep{ + .geometry = *trial, + .loads = response.loads, + .refinements = refinement, + .rows = rows.size(), + .max_overlap = max_overlap, + }; + } + + // Each new row is linearized where it was found. Its offset is set so + // that the multipliers that produced the move predict the gap that the + // move actually left. + for (const auto& touch : overlapping) { + auto row = make_row(*trial, radii, touch, compliance, parameters.max_overlap_recovery); + row.offset -= dt * predicted_rate(row, response); + rows.push_back(row); + keys.push_back(key_of(touch)); + multipliers.push_back(0.0F); + } + } + restore(state, base); + return std::nullopt; +} + +} // namespace + +void validate_growth_load_response(const GrowthLoadResponse& response) { + if (response.law > GrowthLoadLaw::linear) { + throw std::invalid_argument("growth load law is invalid"); + } + if (!std::isfinite(response.sensitivity) || response.sensitivity < 0.0F) { + throw std::invalid_argument("growth load sensitivity must be finite and non-negative"); + } + if (!std::isfinite(response.free_load) || !std::isfinite(response.stall_load) || + response.free_load < 0.0F || response.stall_load <= response.free_load) { + throw std::invalid_argument( + "growth stall load must be finite and exceed a finite, non-negative free load"); + } +} + +float growth_load_factor(const GrowthLoadResponse& response, float load) { + switch (response.law) { + case GrowthLoadLaw::none: + return 1.0F; + case GrowthLoadLaw::exponential: + return std::exp(-response.sensitivity * std::max(0.0F, load)); + case GrowthLoadLaw::linear: + return std::clamp( + 1.0F - (load - response.free_load) / (response.stall_load - response.free_load), 0.0F, + 1.0F); + } + throw std::invalid_argument("growth load law is invalid"); +} + +void validate_contact_dynamics_parameters(const ContactDynamicsParameters& parameters) { + const auto positive = [](float value) { return std::isfinite(value) && value > 0.0F; }; + if (!positive(parameters.drag)) { + throw std::invalid_argument("contact dynamics drag must be finite and positive"); + } + if (!positive(parameters.contact_stiffness)) { + throw std::invalid_argument("contact stiffness must be finite and positive"); + } + if (!positive(parameters.overlap_tolerance)) { + throw std::invalid_argument("contact overlap tolerance must be finite and positive"); + } + if (!std::isfinite(parameters.candidate_margin) || parameters.candidate_margin < 0.0F) { + throw std::invalid_argument("contact candidate margin must be finite and non-negative"); + } + if (!positive(parameters.max_overlap_recovery)) { + throw std::invalid_argument("contact overlap recovery must be finite and positive"); + } + if (!positive(parameters.max_growth_fraction)) { + throw std::invalid_argument("contact growth fraction must be finite and positive"); + } + if (parameters.max_iterations == 0) { + throw std::invalid_argument("contact dynamics iteration limit must be positive"); + } + validate_growth_load_response(parameters.growth); +} + +void validate_contact_system(const ContactSystem& system) { + if (!std::isfinite(system.dt) || system.dt <= 0.0F) { + throw std::invalid_argument("contact system time step must be finite and positive"); + } + validate_growth_load_response(system.growth); + for (const auto& body : system.bodies) { + if (!finite(body.axis) || !std::isfinite(body.translational_mobility) || + !std::isfinite(body.transverse_mobility) || !std::isfinite(body.axial_mobility) || + !std::isfinite(body.length_rate) || body.translational_mobility < 0.0F || + body.transverse_mobility < 0.0F || body.axial_mobility < 0.0F) { + throw std::invalid_argument("contact body is invalid"); + } + } + for (const auto& row : system.rows) { + if (row.first_slot >= system.bodies.size() || + (row.second_slot != invalid_slot && row.second_slot >= system.bodies.size())) { + throw std::invalid_argument("contact row slot is out of range"); + } + auto valid = std::isfinite(row.offset) && std::isfinite(row.compliance) && + row.compliance >= 0.0F && std::isfinite(row.first_length_lever) && + std::isfinite(row.second_length_lever) && row.first_length_lever >= 0.0F && + row.second_length_lever >= 0.0F; + for (std::size_t index = 0; index < row.first_jacobian.size(); ++index) { + valid = valid && std::isfinite(row.first_jacobian[index]) && + std::isfinite(row.second_jacobian[index]); + } + if (!valid) { + throw std::invalid_argument("contact row is invalid"); + } + } +} + +namespace detail { + +ContactDynamicsResult advance_contact_dynamics( + WorldState& state, const ConstraintSet& constraints, ComputeBackend& backend, float dt, + const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, + const ConstraintContactParameters& constraint_parameters) { + if (!std::isfinite(dt) || dt < 0.0F) { + throw std::invalid_argument("time step must be finite and non-negative"); + } + validate_contact_dynamics_parameters(parameters); + validate_contact_parameters(contact_parameters); + validate_constraint_contact_parameters(constraint_parameters); + state.validate(); + + ContactDynamicsResult result; + result.axial_loads.assign(state.size(), 0.0F); + result.length_increments.assign(state.size(), 0.0F); + if (state.empty() || dt == 0.0F) { + return result; + } + + const auto initial = capture(state); + auto base = initial; + try { + // The first substep is as long as the growth bound allows. + const auto view = state.geometry_state(); + const auto rates = state.cell_attributes().growth_rates; + auto growth = 0.0F; + for (std::size_t slot = 0; slot < view.size(); ++slot) { + growth = std::max( + growth, std::abs(rates[slot]) * view.lengths[slot] * 0.5F * dt / view.radii[slot]); + } + const auto pieces = std::max(1.0F, std::ceil(growth / parameters.max_growth_fraction)); + if (!std::isfinite(pieces)) { + throw std::runtime_error("contact dynamics growth per step is not finite"); + } + const auto longest = dt / pieces; + const auto shortest = std::ldexp(longest, -static_cast(parameters.max_step_halvings)); + + auto remaining = static_cast(dt); + auto length = longest; + while (remaining > 0.0) { + // A final piece within rounding of the remainder takes all of it. + if (static_cast(length) >= remaining * (1.0 - 1.0e-6)) { + length = static_cast(remaining); + } + auto substep = + advance_substep(state, base, initial.lengths, constraints, backend, length, parameters, + contact_parameters, constraint_parameters, result.report.iterations); + if (!substep.has_value()) { + length *= 0.5F; + ++result.report.halvings; + if (length < shortest) { + throw std::runtime_error( + "contact dynamics did not resolve the contacts of a substep of " + + std::to_string(length * 2.0F)); + } + continue; + } + remaining -= static_cast(length); + base = std::move(substep->geometry); + result.axial_loads = std::move(substep->loads); + ++result.report.substeps; + result.report.refinements += substep->refinements; + result.report.max_rows = std::max(result.report.max_rows, substep->rows); + result.report.max_overlap = substep->max_overlap; + length = std::min(longest, length * 2.0F); + } + } catch (...) { + restore(state, initial); + throw; + } + for (std::size_t slot = 0; slot < initial.size(); ++slot) { + result.length_increments[slot] = base.lengths[slot] - initial.lengths[slot]; + } + return result; +} + +} // namespace detail +} // namespace microsimulator diff --git a/cpp/core/contact_solver.hpp b/cpp/core/contact_solver.hpp new file mode 100644 index 0000000..64a9bcb --- /dev/null +++ b/cpp/core/contact_solver.hpp @@ -0,0 +1,83 @@ +#pragma once + +#include +#include +#include +#include + +#include "microsimulator/contact_dynamics.hpp" + +namespace microsimulator::detail { + +// What one projected-gradient step reports. `step` is the change in the +// multipliers and `change` the change in their gaps. +struct ContactSolverSums { + double step_dot_step{0.0}; + double step_dot_change{0.0}; + double change_dot_change{0.0}; + float residual{0.0F}; +}; + +// The vector operations of the projected-gradient solve of a contact system. +// A backend supplies them over its own storage for the multipliers and their +// gaps; the iteration, its step lengths, and its convergence test are the +// same for every backend. +struct ContactSolverOperations { + // Loads the initial multipliers and evaluates their gaps. Returns the + // residual. + std::function initialize; + // multipliers = max(multipliers - step_length * gaps, 0), then evaluates + // the gaps of the new multipliers. + std::function step; +}; + +// The residual contribution of one row: a positive multiplier needs a zero +// gap, and a zero multiplier needs a non-negative one. +[[nodiscard]] inline float contact_row_residual(float multiplier, float gap) { + return multiplier > 0.0F ? std::abs(gap) : std::max(0.0F, -gap); +} + +// Barzilai-Borwein projected gradient descent on the convex contact energy, +// whose gradient is the gap. The two Barzilai-Borwein step lengths alternate. +// `first_step_length` must be positive. +[[nodiscard]] inline ContactSolveReport solve_contact_system( + const ContactSolverOperations& operations, float first_step_length, + const ContactSolveParameters& parameters) { + ContactSolveReport report; + report.residual = operations.initialize(); + if (!std::isfinite(report.residual)) { + report.status = ContactSolveStatus::breakdown; + return report; + } + if (report.residual <= parameters.tolerance) { + return report; + } + + report.status = ContactSolveStatus::iteration_limit; + auto step_length = first_step_length; + for (std::uint32_t iteration = 1; iteration <= parameters.max_iterations; ++iteration) { + const auto sums = operations.step(step_length); + report.iterations = iteration; + report.residual = sums.residual; + if (!std::isfinite(sums.residual) || !std::isfinite(sums.step_dot_change)) { + report.status = ContactSolveStatus::breakdown; + return report; + } + if (sums.residual <= parameters.tolerance) { + report.status = ContactSolveStatus::converged; + return report; + } + // The energy is convex, so step . change is non-negative; a vanishing + // product keeps the previous step length. + if (sums.step_dot_change > 0.0 && sums.change_dot_change > 0.0) { + const auto next = (iteration % 2U) == 1U ? sums.step_dot_step / sums.step_dot_change + : sums.step_dot_change / sums.change_dot_change; + if (std::isfinite(next) && next > 0.0) { + step_length = static_cast(next); + } + } + } + return report; +} + +} // namespace microsimulator::detail diff --git a/cpp/core/contact_stepper.hpp b/cpp/core/contact_stepper.hpp new file mode 100644 index 0000000..36f475d --- /dev/null +++ b/cpp/core/contact_stepper.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "microsimulator/backend.hpp" +#include "microsimulator/constraints.hpp" +#include "microsimulator/contact_dynamics.hpp" +#include "microsimulator/contact_graph.hpp" +#include "microsimulator/world_state.hpp" + +namespace microsimulator::detail { + +// Advances cell positions, orientations, and lengths over `dt` with growth and +// contact solved together. Each substep finds the cells and walls within the +// candidate margin, solves for the non-negative contact forces that keep every +// gap open while the cells elongate under their loads, and moves the cells. +// Contacts that the move opens are added to the same solve until the geometry +// is free of overlap, and a substep whose solve fails is retried at half its +// length. The activation margins of the contact and constraint parameters are +// replaced by the candidate margin. The state is unchanged if this throws. +[[nodiscard]] ContactDynamicsResult advance_contact_dynamics( + WorldState& state, const ConstraintSet& constraints, ComputeBackend& backend, float dt, + const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, + const ConstraintContactParameters& constraint_parameters); + +} // namespace microsimulator::detail diff --git a/cpp/core/simulation.cpp b/cpp/core/simulation.cpp index d110152..2d4cceb 100644 --- a/cpp/core/simulation.cpp +++ b/cpp/core/simulation.cpp @@ -6,6 +6,8 @@ #include #include +#include "core/contact_stepper.hpp" + namespace microsimulator { namespace { @@ -311,7 +313,29 @@ std::pair Simulation::divide_equal(CellId parent_id) { return state_.divide_equal(parent_id); } +struct Simulation::ContactDynamicsRequest { + const ContactDynamicsParameters& dynamics; + const ContactParameters& contacts; + const ConstraintContactParameters& constraints; +}; + void Simulation::step(float dt) { + std::ignore = advance(dt, nullptr); +} + +ContactDynamicsResult Simulation::step(float dt, + const ContactDynamicsParameters& dynamics_parameters, + const ContactParameters& contact_parameters, + const ConstraintContactParameters& constraint_parameters) { + if (!backend_->supports(BackendFeature::contact_dynamics)) { + throw std::runtime_error("selected backend does not implement contact dynamics"); + } + const ContactDynamicsRequest request{dynamics_parameters, contact_parameters, + constraint_parameters}; + return advance(dt, &request); +} + +ContactDynamicsResult Simulation::advance(float dt, const ContactDynamicsRequest* dynamics) { if (!std::isfinite(dt) || dt < 0.0F) { throw std::invalid_argument("time step must be finite and non-negative"); } @@ -334,13 +358,33 @@ void Simulation::step(float dt) { signal_grid_->validate_step(dt); } // Growth, species, and coupled updates write only cell lengths and species - // levels, so those two arrays are the whole cell-state rollback record. + // levels. Contact dynamics also moves and turns the cells, so its rollback + // record holds their positions and directions too. const auto species_levels = state_.species_state().levels; const std::vector saved_species(species_levels.begin(), species_levels.end()); const auto saved_levels = signal_grid_.has_value() ? signal_levels() : std::vector{}; const auto saved_report = last_signal_solve_report_; + std::vector saved_positions; + std::vector saved_directions; + if (dynamics != nullptr) { + saved_positions.reserve(geometry.size()); + saved_directions.reserve(geometry.size()); + for (std::size_t slot = 0; slot < geometry.size(); ++slot) { + saved_positions.push_back( + {geometry.position_x[slot], geometry.position_y[slot], geometry.position_z[slot]}); + saved_directions.push_back( + {geometry.direction_x[slot], geometry.direction_y[slot], geometry.direction_z[slot]}); + } + } + ContactDynamicsResult result; try { - backend_->advance_growth(state_, dt); + if (dynamics != nullptr) { + result = + detail::advance_contact_dynamics(state_, constraints_, *backend_, dt, dynamics->dynamics, + dynamics->contacts, dynamics->constraints); + } else { + backend_->advance_growth(state_, dt); + } if (!std::ranges::all_of(state_.geometry_state().lengths, [](float length) { return std::isfinite(length) && length >= 0.0F; })) { @@ -360,12 +404,17 @@ void Simulation::step(float dt) { } } catch (...) { std::ranges::copy(previous_lengths, state_.growth_state().lengths.begin()); + for (std::size_t slot = 0; slot < saved_positions.size(); ++slot) { + state_.set_cell_geometry(static_cast(slot), saved_positions[slot], + saved_directions[slot], previous_lengths[slot]); + } std::ranges::copy(saved_species, state_.species_state().levels.begin()); if (signal_grid_.has_value()) signal_grid_->set_levels(saved_levels); last_signal_solve_report_ = saved_report; throw; } time_ += static_cast(dt); + return result; } ContactGraph Simulation::find_cell_contacts(const ContactParameters& parameters) { diff --git a/cpp/cpu/cpu_backend.cpp b/cpp/cpu/cpu_backend.cpp index cf4247c..fcf51c6 100644 --- a/cpp/cpu/cpu_backend.cpp +++ b/cpp/cpu/cpu_backend.cpp @@ -24,7 +24,7 @@ class CpuBackend final : public ComputeBackend { feature == BackendFeature::external_constraints || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || - feature == BackendFeature::resolved_flow; + feature == BackendFeature::resolved_flow || feature == BackendFeature::contact_dynamics; } void advance_growth(WorldState& state, float dt) override { @@ -64,6 +64,12 @@ class CpuBackend final : public ComputeBackend { return solve_cell_mechanics_cpu(state, contacts, external_contacts, parameters); } + [[nodiscard]] ContactSolveResult solve_contact_forces( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters) override { + return solve_contact_system_cpu(system, initial_multipliers, parameters); + } + [[nodiscard]] DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) override { @@ -79,6 +85,12 @@ class CpuBackend final : public ComputeBackend { } // namespace +ContactSolveResult ComputeBackend::solve_contact_forces(const ContactSystem&, + std::span, + const ContactSolveParameters&) { + throw std::runtime_error("selected backend does not implement contact dynamics"); +} + std::unique_ptr make_cpu_backend(std::uint32_t device_index) { if (device_index != 0) { throw std::out_of_range("CPU backend exposes only device index 0"); diff --git a/cpp/cpu/cpu_constraints.cpp b/cpp/cpu/cpu_constraints.cpp index 4cc3146..daaee0f 100644 --- a/cpp/cpu/cpu_constraints.cpp +++ b/cpp/cpu/cpu_constraints.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -307,6 +308,80 @@ SurfacePoint box_surface(const Vec3& point, const BoxConstraint& box, float dege return {-clearances[nearest_axis], outward}; } +// One row for every face of a box container that an end of the cell is within +// the activation margin of. Each face is its own half-space, so a cell end in +// a corner is held by every wall that meets there. +void append_box_face_contacts(std::vector& contacts, + const CellGeometryView& geometry, std::size_t slot, + const BoxConstraint& box, + const ConstraintContactParameters& parameters) { + const auto radius = geometry.radii[slot]; + const std::array half_extents{box.half_extents.x, box.half_extents.y, + box.half_extents.z}; + for (const auto& endpoint : endpoints(geometry, slot)) { + const auto delta = endpoint.centerline_point - box.center; + const std::array offsets{delta.x, delta.y, delta.z}; + for (std::size_t axis = 0; axis < offsets.size(); ++axis) { + for (const auto sign : {-1.0F, 1.0F}) { + const auto separation = half_extents[axis] - sign * offsets[axis] - radius; + if (separation >= parameters.activation_margin) { + continue; + } + Vec3 normal{}; + (axis == 0 ? normal.x : axis == 1 ? normal.y : normal.z) = sign; + contacts.push_back({ + .cell_id = geometry.ids[slot], + .cell_slot = static_cast(slot), + .constraint_id = box.id, + .constraint_kind = ExternalConstraintKind::box, + .location = endpoint.location, + .point_on_cell = endpoint.centerline_point + normal * radius, + .normal = normal, + .signed_separation = separation, + .weight = box.coefficient, + }); + } + } + } +} + +// The barrel and both caps of a cylinder container, one row each. +void append_cylinder_face_contacts(std::vector& contacts, + const CellGeometryView& geometry, std::size_t slot, + const CylinderConstraint& cylinder, + const ConstraintContactParameters& parameters) { + const auto radius = geometry.radii[slot]; + for (const auto& endpoint : endpoints(geometry, slot)) { + const auto push = [&](Vec3 normal, float separation) { + if (separation >= parameters.activation_margin) { + return; + } + contacts.push_back({ + .cell_id = geometry.ids[slot], + .cell_slot = static_cast(slot), + .constraint_id = cylinder.id, + .constraint_kind = ExternalConstraintKind::cylinder, + .location = endpoint.location, + .point_on_cell = endpoint.centerline_point + normal * radius, + .normal = normal, + .signed_separation = separation, + .weight = cylinder.coefficient, + }); + }; + const Vec3 radial_delta{endpoint.centerline_point.x - cylinder.center.x, + endpoint.centerline_point.y - cylinder.center.y, 0.0F}; + const auto radial_distance = norm(radial_delta); + const auto radial = radial_distance > parameters.degeneracy_epsilon + ? radial_delta * (1.0F / radial_distance) + : Vec3{1.0F, 0.0F, 0.0F}; + push(radial, cylinder.radius - radial_distance - radius); + const auto z_offset = endpoint.centerline_point.z - cylinder.center.z; + for (const auto sign : {-1.0F, 1.0F}) { + push({0.0F, 0.0F, sign}, cylinder.half_height - sign * z_offset - radius); + } + } +} + void append_box_contacts(std::vector& contacts, const CellGeometryView& geometry, std::size_t slot, const BoxConstraint& box, const ConstraintContactParameters& parameters) { @@ -490,14 +565,18 @@ void append_cylinder_contacts(std::vector& contacts, } } -} // namespace +enum class ContainerRows : std::uint8_t { + nearest_face, + every_face, +}; -ExternalContactGraph find_external_contacts_cpu(const WorldState& state, - const ConstraintSet& constraints, - const ConstraintContactParameters& parameters) { +ExternalContactGraph external_contacts(const WorldState& state, const ConstraintSet& constraints, + const ConstraintContactParameters& parameters, + ContainerRows container_rows) { validate_constraint_contact_parameters(parameters); state.validate(); const auto geometry = state.geometry_state(); + const auto every_face = container_rows == ContainerRows::every_face; std::vector contacts; for (std::size_t slot = 0; slot < geometry.size(); ++slot) { for (const auto& plane : constraints.planes()) { @@ -507,18 +586,41 @@ ExternalContactGraph find_external_contacts_cpu(const WorldState& state, append_sphere_contacts(contacts, geometry, slot, sphere, parameters); } for (const auto& box : constraints.boxes()) { - append_box_contacts(contacts, geometry, slot, box, parameters); + if (every_face && box.allowed_region == ConstraintRegion::inside) { + append_box_face_contacts(contacts, geometry, slot, box, parameters); + } else { + append_box_contacts(contacts, geometry, slot, box, parameters); + } } for (const auto& cylinder : constraints.cylinders()) { - append_cylinder_contacts(contacts, geometry, slot, cylinder, parameters); + if (every_face && cylinder.allowed_region == ConstraintRegion::inside) { + append_cylinder_face_contacts(contacts, geometry, slot, cylinder, parameters); + } else { + append_cylinder_contacts(contacts, geometry, slot, cylinder, parameters); + } } } - std::ranges::sort(contacts, {}, [](const ExternalContact& contact) { + // The stable sort keeps the faces of one container in emission order. + std::ranges::stable_sort(contacts, {}, [](const ExternalContact& contact) { return std::tuple{contact.cell_id, contact.constraint_id, contact.location}; }); return ExternalContactGraph(geometry.size(), std::move(contacts)); } +} // namespace + +ExternalContactGraph find_external_contacts_cpu(const WorldState& state, + const ConstraintSet& constraints, + const ConstraintContactParameters& parameters) { + return external_contacts(state, constraints, parameters, ContainerRows::nearest_face); +} + +ExternalContactGraph find_external_contact_faces(const WorldState& state, + const ConstraintSet& constraints, + const ConstraintContactParameters& parameters) { + return external_contacts(state, constraints, parameters, ContainerRows::every_face); +} + void project_cells_out_of_constraints(WorldState& state, const ConstraintSet& constraints, const ConstraintContactParameters& parameters) { if (constraints.empty() || state.empty()) { diff --git a/cpp/cpu/cpu_contact_dynamics.cpp b/cpp/cpu/cpu_contact_dynamics.cpp new file mode 100644 index 0000000..e84c32a --- /dev/null +++ b/cpp/cpu/cpu_contact_dynamics.cpp @@ -0,0 +1,222 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "core/contact_solver.hpp" +#include "microsimulator/contact_dynamics.hpp" + +namespace microsimulator { +namespace { + +using Wrench = std::array; + +[[nodiscard]] float wrench_dot(const Wrench& left, const Wrench& right) { + float result = 0.0F; + for (std::size_t index = 0; index < left.size(); ++index) { + result += left[index] * right[index]; + } + return result; +} + +void add_scaled(Wrench& destination, const Wrench& source, float scale) { + for (std::size_t index = 0; index < destination.size(); ++index) { + destination[index] += scale * source[index]; + } +} + +// Velocity and angular velocity of a body under a force and torque. +[[nodiscard]] Wrench apply_mobility(const ContactBody& body, const Wrench& wrench) { + const Vec3 torque{wrench[3], wrench[4], wrench[5]}; + const auto angular = + torque * body.transverse_mobility + + body.axis * ((body.axial_mobility - body.transverse_mobility) * dot(body.axis, torque)); + return { + wrench[0] * body.translational_mobility, + wrench[1] * body.translational_mobility, + wrench[2] * body.translational_mobility, + angular.x, + angular.y, + angular.z, + }; +} + +[[nodiscard]] float length_rate(const ContactBody& body, const GrowthLoadResponse& growth, + float load) { + return body.length_rate > 0.0F ? body.length_rate * growth_load_factor(growth, load) + : body.length_rate; +} + +// Scratch storage for evaluating a system, reused across solver iterations. +struct Evaluation { + std::vector wrenches; + std::vector velocities; + std::vector loads; + std::vector length_rates; +}; + +void evaluate(const ContactSystem& system, std::span multipliers, + Evaluation& evaluation) { + const auto body_count = system.bodies.size(); + evaluation.wrenches.assign(body_count, Wrench{}); + evaluation.loads.assign(body_count, 0.0F); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + const auto multiplier = multipliers[index]; + if (multiplier == 0.0F) { + continue; + } + add_scaled(evaluation.wrenches[row.first_slot], row.first_jacobian, multiplier); + evaluation.loads[row.first_slot] += row.first_length_lever * multiplier; + if (row.second_slot != invalid_slot) { + add_scaled(evaluation.wrenches[row.second_slot], row.second_jacobian, multiplier); + evaluation.loads[row.second_slot] += row.second_length_lever * multiplier; + } + } + evaluation.velocities.resize(body_count); + evaluation.length_rates.resize(body_count); + for (std::size_t index = 0; index < body_count; ++index) { + evaluation.velocities[index] = apply_mobility(system.bodies[index], evaluation.wrenches[index]); + evaluation.length_rates[index] = + length_rate(system.bodies[index], system.growth, evaluation.loads[index]); + } +} + +void evaluate_gaps(const ContactSystem& system, std::span multipliers, + Evaluation& evaluation, std::vector& gaps) { + evaluate(system, multipliers, evaluation); + gaps.resize(system.rows.size()); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + auto rate = wrench_dot(row.first_jacobian, evaluation.velocities[row.first_slot]) - + row.first_length_lever * evaluation.length_rates[row.first_slot]; + if (row.second_slot != invalid_slot) { + rate += wrench_dot(row.second_jacobian, evaluation.velocities[row.second_slot]) - + row.second_length_lever * evaluation.length_rates[row.second_slot]; + } + gaps[index] = row.offset + system.dt * rate + row.compliance * multipliers[index]; + } +} + +void require_multiplier_count(const ContactSystem& system, std::span multipliers) { + if (multipliers.size() != system.rows.size()) { + throw std::invalid_argument("contact multiplier count does not match the contact rows"); + } + for (const auto multiplier : multipliers) { + if (!std::isfinite(multiplier) || multiplier < 0.0F) { + throw std::invalid_argument("contact multipliers must be finite and non-negative"); + } + } +} + +} // namespace + +ContactResponse evaluate_contact_response(const ContactSystem& system, + std::span multipliers) { + validate_contact_system(system); + require_multiplier_count(system, multipliers); + Evaluation evaluation; + evaluate(system, multipliers, evaluation); + return { + .velocities = std::move(evaluation.velocities), + .loads = std::move(evaluation.loads), + .length_rates = std::move(evaluation.length_rates), + }; +} + +std::vector evaluate_contact_gaps(const ContactSystem& system, + std::span multipliers) { + validate_contact_system(system); + require_multiplier_count(system, multipliers); + Evaluation evaluation; + std::vector gaps; + evaluate_gaps(system, multipliers, evaluation, gaps); + return gaps; +} + +float contact_system_diagonal_bound(const ContactSystem& system) { + const auto diagonal = [](const ContactBody& body, const Wrench& jacobian) { + return wrench_dot(jacobian, apply_mobility(body, jacobian)); + }; + auto bound = 0.0F; + for (const auto& row : system.rows) { + auto entry = diagonal(system.bodies[row.first_slot], row.first_jacobian); + if (row.second_slot != invalid_slot) { + entry += diagonal(system.bodies[row.second_slot], row.second_jacobian); + } + bound = std::max(bound, system.dt * entry + row.compliance); + } + return bound; +} + +ContactSolveResult solve_contact_system_cpu(const ContactSystem& system, + std::span initial_multipliers, + const ContactSolveParameters& parameters) { + validate_contact_system(system); + require_multiplier_count(system, initial_multipliers); + if (!std::isfinite(parameters.tolerance) || parameters.tolerance <= 0.0F) { + throw std::invalid_argument("contact solve tolerance must be finite and positive"); + } + + ContactSolveResult result; + result.multipliers.assign(initial_multipliers.begin(), initial_multipliers.end()); + if (system.rows.empty()) { + return result; + } + const auto bound = contact_system_diagonal_bound(system); + if (!std::isfinite(bound) || bound <= 0.0F) { + throw std::invalid_argument("contact system has no positive diagonal"); + } + + Evaluation evaluation; + std::vector gaps; + std::vector next_multipliers(system.rows.size()); + std::vector next_gaps; + const auto residual_of = [](std::span multipliers, std::span values) { + auto residual = 0.0F; + for (std::size_t index = 0; index < multipliers.size(); ++index) { + residual = + std::max(residual, detail::contact_row_residual(multipliers[index], values[index])); + if (!std::isfinite(values[index])) { + return std::numeric_limits::quiet_NaN(); + } + } + return residual; + }; + const detail::ContactSolverOperations operations{ + .initialize = + [&] { + evaluate_gaps(system, result.multipliers, evaluation, gaps); + return residual_of(result.multipliers, gaps); + }, + .step = + [&](float step_length) { + for (std::size_t index = 0; index < next_multipliers.size(); ++index) { + next_multipliers[index] = + std::max(0.0F, result.multipliers[index] - step_length * gaps[index]); + } + evaluate_gaps(system, next_multipliers, evaluation, next_gaps); + detail::ContactSolverSums sums; + for (std::size_t index = 0; index < next_multipliers.size(); ++index) { + const auto step = + static_cast(next_multipliers[index]) - result.multipliers[index]; + const auto change = static_cast(next_gaps[index]) - gaps[index]; + sums.step_dot_step += step * step; + sums.step_dot_change += step * change; + sums.change_dot_change += change * change; + } + sums.residual = residual_of(next_multipliers, next_gaps); + result.multipliers.swap(next_multipliers); + gaps.swap(next_gaps); + return sums; + }, + }; + result.report = detail::solve_contact_system(operations, 1.0F / bound, parameters); + return result; +} + +} // namespace microsimulator diff --git a/cpp/include/microsimulator/backend.hpp b/cpp/include/microsimulator/backend.hpp index 68ba310..11a9f5c 100644 --- a/cpp/include/microsimulator/backend.hpp +++ b/cpp/include/microsimulator/backend.hpp @@ -6,6 +6,7 @@ #include #include "microsimulator/constraints.hpp" +#include "microsimulator/contact_dynamics.hpp" #include "microsimulator/contact_graph.hpp" #include "microsimulator/coupled_rates.hpp" #include "microsimulator/flow.hpp" @@ -39,6 +40,11 @@ class ComputeBackend { [[nodiscard]] virtual MechanicsSolveResult solve_cell_mechanics( const WorldState& state, const ContactGraph& contacts, const ExternalContactGraph& external_contacts, const MechanicsParameters& parameters) = 0; + // Solves one substep's contact system from the given multipliers. A backend + // without the contact dynamics feature throws. + [[nodiscard]] virtual ContactSolveResult solve_contact_forces( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters); [[nodiscard]] virtual DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) = 0; diff --git a/cpp/include/microsimulator/constraints.hpp b/cpp/include/microsimulator/constraints.hpp index 545f545..ecb8ea3 100644 --- a/cpp/include/microsimulator/constraints.hpp +++ b/cpp/include/microsimulator/constraints.hpp @@ -181,6 +181,16 @@ class ExternalContactGraph { const WorldState& state, const ConstraintSet& constraints, const ConstraintContactParameters& parameters = ConstraintContactParameters{}); +// The contacts of `find_external_contacts_cpu`, except that a box or cylinder +// that cells live inside reports one contact for every face a cell end is +// near rather than for the nearest face alone. Each face of a container is an +// independent half-space, which is what a solve with unilateral rows needs to +// hold a cell in a corner. The contacts come from the host geometry on every +// backend. +[[nodiscard]] ExternalContactGraph find_external_contact_faces( + const WorldState& state, const ConstraintSet& constraints, + const ConstraintContactParameters& parameters = ConstraintContactParameters{}); + // Moves every mobile cell out of the external constraints it penetrates. // The regularized contact solve weighs a wall row against the cells pressing // on it, so a crowded colony leaves a cell part-way through a wall; this makes diff --git a/cpp/include/microsimulator/contact_dynamics.hpp b/cpp/include/microsimulator/contact_dynamics.hpp new file mode 100644 index 0000000..ae5bfc1 --- /dev/null +++ b/cpp/include/microsimulator/contact_dynamics.hpp @@ -0,0 +1,165 @@ +#pragma once + +#include +#include +#include +#include +#include + +#include "microsimulator/types.hpp" + +namespace microsimulator { + +// How a cell's elongation responds to the axial compressive load its contacts +// put on it. +enum class GrowthLoadLaw : std::uint8_t { + // Elongation ignores load. + none, + // Elongation is scaled by exp(-sensitivity * load). + exponential, + // Elongation is unscaled up to `free_load`, falls linearly, and stops at + // `stall_load`. + linear, +}; + +struct GrowthLoadResponse { + GrowthLoadLaw law{GrowthLoadLaw::none}; + float sensitivity{0.0F}; + float free_load{0.0F}; + float stall_load{1.0F}; +}; + +void validate_growth_load_response(const GrowthLoadResponse& response); + +// The factor in [0, 1] that scales a cell's positive elongation under `load`. +[[nodiscard]] float growth_load_factor(const GrowthLoadResponse& response, float load); + +struct ContactDynamicsParameters { + // Drag per unit capsule length. A cell of full length L resists translation + // with drag * L and rotation with the matching rod inertias. + float drag{1.0F}; + // Contact force per unit overlap. Contacts are unilateral springs solved + // implicitly, so a resting contact under force f overlaps by f / stiffness. + float contact_stiffness{1.0e4F}; + // Overlap, beyond what the contact force accounts for, accepted at the end + // of a substep. + float overlap_tolerance{1.0e-3F}; + // Pairs and walls closer than this enter the solve as candidate rows. + float candidate_margin{0.1F}; + // Existing overlap that a pair free to move recovers per substep at most. + // A pair that cannot move is pressed apart with the full contact force of + // its overlap. + float max_overlap_recovery{0.05F}; + // Elongation of one cell end per substep at most, in cell radii. + float max_growth_fraction{0.25F}; + std::uint32_t max_iterations{20000}; + std::uint32_t max_refinements{10}; + std::uint32_t max_step_halvings{12}; + GrowthLoadResponse growth; +}; + +void validate_contact_dynamics_parameters(const ContactDynamicsParameters& parameters); + +// One unilateral contact. The gap rate of the row is +// first_jacobian . (velocity, angular velocity) of the first cell plus the +// same product for the second, minus each cell's length lever times its +// elongation rate. The row yields by `compliance` per unit of its multiplier. +// A row against a constraint has no second cell. +struct ContactRow { + Slot first_slot{invalid_slot}; + Slot second_slot{invalid_slot}; + std::array first_jacobian{}; + std::array second_jacobian{}; + float first_length_lever{0.0F}; + float second_length_lever{0.0F}; + float offset{0.0F}; + float compliance{0.0F}; +}; + +// Mobility and nominal elongation of one cell. A fixed cell has zero +// mobility. +struct ContactBody { + Vec3 axis{1.0F, 0.0F, 0.0F}; + float translational_mobility{0.0F}; + float transverse_mobility{0.0F}; + float axial_mobility{0.0F}; + float length_rate{0.0F}; +}; + +// The convex problem of one substep. With multipliers g >= 0, the predicted +// gap of every row is +// offset + dt * J^T M^-1 J g - dt * L^T (length_rate * factor(L g)) + compliance * g +// and the solution has gap >= 0 with gap_i * g_i = 0. +struct ContactSystem { + std::span rows; + std::span bodies; + float dt{0.0F}; + GrowthLoadResponse growth; +}; + +enum class ContactSolveStatus : std::uint8_t { + converged, + iteration_limit, + breakdown, +}; + +struct ContactSolveReport { + ContactSolveStatus status{ContactSolveStatus::converged}; + std::uint32_t iterations{0}; + // Largest violation of the complementarity conditions, as a length. + float residual{0.0F}; +}; + +struct ContactSolveParameters { + float tolerance{2.5e-4F}; + std::uint32_t max_iterations{20000}; +}; + +struct ContactSolveResult { + std::vector multipliers; + ContactSolveReport report; +}; + +// What a set of multipliers does to the cells. +struct ContactResponse { + // Velocity then angular velocity of every cell. + std::vector> velocities; + std::vector loads; + std::vector length_rates; +}; + +void validate_contact_system(const ContactSystem& system); + +[[nodiscard]] ContactResponse evaluate_contact_response(const ContactSystem& system, + std::span multipliers); + +[[nodiscard]] std::vector evaluate_contact_gaps(const ContactSystem& system, + std::span multipliers); + +// The largest diagonal entry of the linear part of the system, which bounds +// the first solver step. +[[nodiscard]] float contact_system_diagonal_bound(const ContactSystem& system); + +[[nodiscard]] ContactSolveResult solve_contact_system_cpu( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters = ContactSolveParameters{}); + +struct ContactDynamicsReport { + std::uint32_t substeps{0}; + std::uint32_t halvings{0}; + std::uint32_t refinements{0}; + std::uint64_t iterations{0}; + std::size_t max_rows{0}; + // Deepest overlap between cells or with a constraint after the step. + float max_overlap{0.0F}; +}; + +struct ContactDynamicsResult { + ContactDynamicsReport report; + // Axial compressive load on each cell, by slot, over the last substep. + std::vector axial_loads; + // Elongation applied to each cell, by slot, over the whole step. + std::vector length_increments; +}; + +} // namespace microsimulator diff --git a/cpp/include/microsimulator/simulation.hpp b/cpp/include/microsimulator/simulation.hpp index 8a899fc..de717d5 100644 --- a/cpp/include/microsimulator/simulation.hpp +++ b/cpp/include/microsimulator/simulation.hpp @@ -51,6 +51,15 @@ class Simulation { std::pair divide(CellId parent_id, float first_fraction); std::pair divide_equal(CellId parent_id); void step(float dt); + // Advances growth and contact together: cells elongate, push each other + // and the constraints apart, and slow under the load that puts on them. + // Species, coupled, and signal updates then see the elongation that + // happened. The activation margins of the contact parameters are replaced + // by the candidate margin of the dynamics parameters. + ContactDynamicsResult step( + float dt, const ContactDynamicsParameters& dynamics_parameters, + const ContactParameters& contact_parameters = ContactParameters{}, + const ConstraintContactParameters& constraint_parameters = ConstraintContactParameters{}); [[nodiscard]] ContactGraph find_cell_contacts( const ContactParameters& parameters = ContactParameters{}); [[nodiscard]] ExternalContactGraph find_external_contacts( @@ -81,6 +90,9 @@ class Simulation { void validate() const; private: + struct ContactDynamicsRequest; + ContactDynamicsResult advance(float dt, const ContactDynamicsRequest* dynamics); + WorldState state_; ConstraintSet constraints_; std::unique_ptr backend_; diff --git a/cpp/include/microsimulator/types.hpp b/cpp/include/microsimulator/types.hpp index 2cf2f9a..7821252 100644 --- a/cpp/include/microsimulator/types.hpp +++ b/cpp/include/microsimulator/types.hpp @@ -72,6 +72,7 @@ enum class BackendFeature : std::uint8_t { coupled_rates, depth_averaged_flow, resolved_flow, + contact_dynamics, }; struct BackendInfo { diff --git a/cpp/python/bindings.cpp b/cpp/python/bindings.cpp index 11c1f76..b636673 100644 --- a/cpp/python/bindings.cpp +++ b/cpp/python/bindings.cpp @@ -35,7 +35,8 @@ NB_MODULE(_core, module) { .value("SIGNALS", microsimulator::BackendFeature::signals) .value("COUPLED_RATES", microsimulator::BackendFeature::coupled_rates) .value("DEPTH_AVERAGED_FLOW", microsimulator::BackendFeature::depth_averaged_flow) - .value("RESOLVED_FLOW", microsimulator::BackendFeature::resolved_flow); + .value("RESOLVED_FLOW", microsimulator::BackendFeature::resolved_flow) + .value("CONTACT_DYNAMICS", microsimulator::BackendFeature::contact_dynamics); nb::enum_(module, "FlowAxis") .value("X", microsimulator::FlowAxis::x) @@ -100,6 +101,11 @@ NB_MODULE(_core, module) { .value("INTERIOR", microsimulator::RodContactLocation::interior); module.attr("RodEndpoint") = module.attr("RodContactLocation"); + nb::enum_(module, "GrowthLoadLaw") + .value("NONE", microsimulator::GrowthLoadLaw::none) + .value("EXPONENTIAL", microsimulator::GrowthLoadLaw::exponential) + .value("LINEAR", microsimulator::GrowthLoadLaw::linear); + nb::enum_(module, "SolverStatus") .value("CONVERGED", microsimulator::SolverStatus::converged) .value("ITERATION_LIMIT", microsimulator::SolverStatus::iteration_limit) @@ -512,6 +518,45 @@ NB_MODULE(_core, module) { .def_ro("initial_residual_rms", µsimulator::SolverReport::initial_residual_rms) .def_ro("final_residual_rms", µsimulator::SolverReport::final_residual_rms); + nb::class_(module, "GrowthLoadResponse") + .def(nb::init<>()) + .def_rw("law", µsimulator::GrowthLoadResponse::law) + .def_rw("sensitivity", µsimulator::GrowthLoadResponse::sensitivity) + .def_rw("free_load", µsimulator::GrowthLoadResponse::free_load) + .def_rw("stall_load", µsimulator::GrowthLoadResponse::stall_load) + .def("factor", [](const microsimulator::GrowthLoadResponse& response, float load) { + microsimulator::validate_growth_load_response(response); + return microsimulator::growth_load_factor(response, load); + }); + + nb::class_(module, "ContactDynamicsParameters") + .def(nb::init<>()) + .def_rw("drag", µsimulator::ContactDynamicsParameters::drag) + .def_rw("contact_stiffness", µsimulator::ContactDynamicsParameters::contact_stiffness) + .def_rw("overlap_tolerance", µsimulator::ContactDynamicsParameters::overlap_tolerance) + .def_rw("candidate_margin", µsimulator::ContactDynamicsParameters::candidate_margin) + .def_rw("max_overlap_recovery", + µsimulator::ContactDynamicsParameters::max_overlap_recovery) + .def_rw("max_growth_fraction", + µsimulator::ContactDynamicsParameters::max_growth_fraction) + .def_rw("max_iterations", µsimulator::ContactDynamicsParameters::max_iterations) + .def_rw("max_refinements", µsimulator::ContactDynamicsParameters::max_refinements) + .def_rw("max_step_halvings", µsimulator::ContactDynamicsParameters::max_step_halvings) + .def_rw("growth", µsimulator::ContactDynamicsParameters::growth); + + nb::class_(module, "ContactDynamicsReport") + .def_ro("substeps", µsimulator::ContactDynamicsReport::substeps) + .def_ro("halvings", µsimulator::ContactDynamicsReport::halvings) + .def_ro("refinements", µsimulator::ContactDynamicsReport::refinements) + .def_ro("iterations", µsimulator::ContactDynamicsReport::iterations) + .def_ro("max_rows", µsimulator::ContactDynamicsReport::max_rows) + .def_ro("max_overlap", µsimulator::ContactDynamicsReport::max_overlap); + + nb::class_(module, "ContactDynamicsResult") + .def_ro("report", µsimulator::ContactDynamicsResult::report) + .def_ro("axial_loads", µsimulator::ContactDynamicsResult::axial_loads) + .def_ro("length_increments", µsimulator::ContactDynamicsResult::length_increments); + nb::class_(module, "MechanicsSolveResult") .def_ro("corrections", µsimulator::MechanicsSolveResult::corrections) .def_ro("report", µsimulator::MechanicsSolveResult::report); @@ -606,7 +651,21 @@ NB_MODULE(_core, module) { .def("divide_equal", microsimulator::python::exclusive(µsimulator::Simulation::divide_equal), "parent_id"_a) - .def("step", microsimulator::python::released(µsimulator::Simulation::step), "dt"_a) + .def( + "step", + microsimulator::python::released(static_cast( + µsimulator::Simulation::step)), + "dt"_a) + .def("step", + microsimulator::python::released( + static_cast( + µsimulator::Simulation::step)), + "dt"_a, "dynamics_parameters"_a, + "contact_parameters"_a = microsimulator::ContactParameters{}, + "constraint_parameters"_a = microsimulator::ConstraintContactParameters{}) .def("find_cell_contacts", microsimulator::python::released(µsimulator::Simulation::find_cell_contacts), "parameters"_a = microsimulator::ContactParameters{}) diff --git a/docs/architecture/0002-contact-mechanics.md b/docs/architecture/0002-contact-mechanics.md index a640374..c6cdaeb 100644 --- a/docs/architecture/0002-contact-mechanics.md +++ b/docs/architecture/0002-contact-mechanics.md @@ -33,6 +33,8 @@ For a cell with full capsule length `L = l + 2r`, the reference regularizer uses The reference solver starts from zero and uses unpreconditioned conjugate gradient. Residual RMS is `sqrt(dot(r, r) / cell_count)`, and the default iteration limit is `7 * cell_count`. Apparent convergence is checked by recomputing `B^T b - A delta_q`; non-finite residuals, non-finite curvature, and non-positive curvature are reported as typed breakdowns rather than allowed to contaminate the simulation. +The [contact dynamics](0026-contact-dynamics.md) step is the alternative to this relaxation: it solves contact with non-negative forces and growth in one convex problem. + Integration is a separate backend-neutral operation over a solver result. It requires convergence by default, applies translation directly, interprets the rotation vector as axis-angle and caps it at five degrees, and computes the length increment as `max(0, desired_increment + delta_l)`. Mechanics may suppress requested elongation but may not directly shorten a cell. All updates are validated before any world-state array is mutated. `Simulation.step` remains the growth-only primitive; `relax_cell_mechanics` is the explicit contact-relaxation operation. Walls are impenetrable. The regularized solve weighs each wall row against the cells pressing on it, so on its own it leaves a crowded cell part-way through a wall. After integrating a pass, `relax_cell_mechanics` therefore moves every mobile cell that is more than `1e-4` inside a constraint out of it. Each end of the cell's centerline moves back along the normals of the contacts it is inside, to a depth of `5e-5` so the resting contact stays active for the next solve and visible to contact analysis; a mid-span contact moves both ends; and the cell is rebuilt at its own length between the moved ends. A rod tilted against a wall comes to lie along it, and a rod wedged upright between a floor and a ceiling is turned flat. Up to eight sweeps settle the ends against each other. Length is unchanged, fixed cells are not moved, and the overlap this opens between cells is left to the next contact solve. A cell deeper than a wall's mid-plane would resolve toward the far face, so when any correction exceeds its cell's radius the pass is applied in up to sixteen equal parts that each move a cell at most one radius, projecting after each part. The projection uses the host constraint geometry on every backend. A wall thinner than a cell's diameter, or a correction longer than sixteen radii, is outside this guarantee. diff --git a/docs/architecture/0014-native-controllers.md b/docs/architecture/0014-native-controllers.md index 09b8278..fd50ec7 100644 --- a/docs/architecture/0014-native-controllers.md +++ b/docs/architecture/0014-native-controllers.md @@ -33,6 +33,8 @@ A controller-backed model resumes through `resume(context, checkpoint)`. The ope 6. apply flow drift when enabled in the mechanics configuration; and 7. execute exactly `MechanicsConfig.passes` contact/relaxation passes when mechanics is configured and cells remain. Each pass ends by projecting mobile cells out of the external constraints, so cells end the step resting on or clear of the walls. +With `MechanicsConfig.contact_dynamics` set, steps 5 to 7 are instead flow drift when enabled, then `Simulation.step(dt, ...)` with the [contact dynamics](0026-contact-dynamics.md) parameters, which advances growth and contact together before the typed rate plans. `NativeController.last_contact_dynamics` holds that step's report, the axial load on each cell, and the elongation each cell was allowed. + `UniformLengthDivision.jitter_z` controls only the random perturbation added to daughter orientation: `None` disables jitter, `False` adds XY-only jitter, and `True` adds XYZ jitter. Native normalization can change an inherited nonzero Z component even when the added Z perturbation is zero. Division places daughters along the parent's three-dimensional axis; subsequent contact relaxation and flow drift remain three-dimensional. See the [planarity diagnostics and tutorial audit](../tutorials/planarity.md) for reproducible examples and the limits of finite-height confinement. The standard payload records a stable model ID and version, completed-step counter, model JSON state, random stream, and every mechanics parameter. `NativeController.from_checkpoint` validates and restores that payload while the checkpoint's native state retains rate plans, signal grids, geometry, and lineage. The number of mechanics passes is an explicit part of the native-controller contract. diff --git a/docs/architecture/0026-contact-dynamics.md b/docs/architecture/0026-contact-dynamics.md new file mode 100644 index 0000000..c22fe59 --- /dev/null +++ b/docs/architecture/0026-contact-dynamics.md @@ -0,0 +1,84 @@ +# ADR 0026: contact dynamics with growth + +- Status: accepted +- Date: 2026-11-13 + +## Context + +The regularized least-squares relaxation of [ADR 0002](0002-contact-mechanics.md) treats contacts as equalities, minimizes the sum of squared overlaps, and runs after growth is committed. A colony that fills a closed space therefore keeps elongating into itself, pairs pushed past one radius invert and stay inverted, and no value of the length weight suits both a free colony and a jam. + +Growing rod-shaped cells are simulated without those failures by solving contact as a complementarity problem: contact forces are non-negative, gaps stay non-negative, and a force acts only where a gap is closed ([Yan, Zhang, and Shelley 2019](https://arxiv.org/abs/1811.04736); [Yan et al. 2020](https://arxiv.org/abs/1909.06623)). Growth enters the same problem when a cell's elongation responds to the compressive load its contacts put on it ([Weady et al. 2024](https://arxiv.org/abs/2405.10158); [Lerchner](https://home.cit.tum.de/~ler/html-data/bacteria/cell-collectives.pdf)). + +## Decision + +`Simulation.step(dt, ContactDynamicsParameters)` advances growth and contact together. It is selected per controller by `MechanicsConfig(contact_dynamics=ContactDynamicsConfig(...))`; without it the controller grows the cells and runs least-squares relaxation passes. + +### The problem of one substep + +Every candidate contact is a row with a multiplier `g >= 0`, the magnitude of its contact force along the contact normal. For rows `J`, cell mobility `M^-1`, and the current signed gaps `phi`, the predicted gap after a substep of length `h` is + +``` +gap(g) = phi + h J^T M^-1 J g - h L^T (r * f(L g)) + c g +``` + +- `J g` is the force and torque the rows put on each cell, and `J^T` maps cell velocities to gap rates. +- `M` is the drag of each cell on its surroundings: `drag * L` in translation for a capsule of full length `L`, with the finite-radius rod inertias of ADR 0002 in rotation. A fixed cell has no mobility. +- `L g` is the axial load on each cell. A row contributes its multiplier times the cell's length lever, the fraction of the cell's elongation that closes that contact: the cylinder stretches uniformly about its center and the caps ride on its ends, so the lever is one half for a contact on a cap along the axis and zero for a contact on the side. +- `r` is the nominal elongation rate `growth_rate * length`, taken from the lengths at the start of the step, and `f` is the growth load response. `L^T` maps elongation to the gap it closes. +- `c` is the compliance `1 / contact_stiffness`. + +The solution satisfies `g >= 0`, `gap >= 0`, and `g * gap = 0` row by row. Those are the optimality conditions of a convex energy whose gradient is `gap`, because `f` is non-increasing. In a full space the multipliers rise until the loads stop growth. + +The growth load response `f` is one of: + +- `none`: elongation ignores load; +- `exponential`: `f = exp(-sensitivity * load)`; +- `linear`: `f = 1` up to `free_load`, falling linearly to zero at `stall_load`. + +Shrinkage is never scaled. Loads are forces in units of drag times length squared per time, so a stall load is chosen relative to the drag. + +### Compliance + +A contact is a unilateral linear spring solved implicitly: a resting contact under force `g` overlaps by `g / contact_stiffness`, and the solve is stable at any stiffness. Compliance keeps the problem well posed when a space holds more than it can: the forces of an over-full region are finite, where rigid constraints have no solution. It also means an overlap `e` that a jammed pair cannot recover persists as a force `e * contact_stiffness`. Where growth responds to load, the accepted overlap is therefore held to the overlap that a tenth of the load scale of the response presses into a contact. The forces of a rigid jam above the stall load depend on the history of those small overlaps and are not otherwise determined. + +A contact already deeper than `max_overlap_recovery` asks for only that much separation in one substep and is stiffened in proportion, so a pair free to move separates at a bounded rate while a pair that cannot move still meets the full spring force of its overlap. + +### Solve + +The energy is minimized by Barzilai–Borwein projected gradient descent with the two step lengths alternating. The iteration needs only the gap of a multiplier vector, starts from a step length bounded by the largest diagonal entry of the linear part, and stops when the largest violation of the complementarity conditions, a length, falls below a quarter of the accepted overlap. `core/contact_solver.hpp` holds the iteration; a backend supplies the gap evaluation and the reductions over its own storage. + +### Substeps and refinement + +A step is divided so that no cell end elongates by more than `max_growth_fraction` radii in one substep. Each substep: + +1. finds the cell pairs and walls within `candidate_margin` and builds their rows at the current geometry; +2. solves for the multipliers and moves the cells: positions by velocity, directions by the axis-angle rotation, lengths by the loaded elongation; +3. finds the contacts that overlap at the moved geometry by more than the accepted overlap plus what their force accounts for; +4. appends a row for each, linearized where it was found with its offset set so that the multipliers that produced the move predict the gap the move left, and solves again from the current multipliers. + +Rows are never rebuilt once added, which is the recursively generated complementarity scheme of [Palmer, Aktulga, and Gao 2025](https://arxiv.org/abs/2506.14097). A substep that does not converge, or needs more than `max_refinements` rounds, is retried at half its length, and after `max_step_halvings` the step throws. A step that throws leaves the simulation unchanged. + +The stepping carries no state between steps, so a resumed run repeats an uninterrupted one. + +### Walls + +Constraints are rows in the same solve. A box or cylinder that cells live inside contributes one row for every face a cell end is near, from `find_external_contact_faces`: each face is an independent half-space, and a row for the nearest face alone leaves a cell end in a corner free to cross the other wall. These rows come from the host constraint geometry on every backend. The wall projection of ADR 0002 is not applied. + +### Order within a step + +Growth and contact run first, then species, coupled, and signal updates, which see the elongation that happened; uptake tied to volume change is charged for it. With flow drift enabled the controller moves the cells with the flow before the step, so the step ends with every contact resolved. + +## Validation + +- A cell between two walls fills the space, stalls with its axial load within 5% of the stall load, and stops consuming nutrient. +- A closed chamber fills to under one layer of cells and its population and footprint then hold, with overlap at what the contact forces press into the cells. +- An unconfined colony without load response elongates exactly as it does without mechanics, stays planar, and packs to a fraction a little under one. +- That colony's radial load profile follows the continuum solution for an incompressible growing layer dragged on its substrate, `p(r) = zeta g (R^2 - r^2) / 4` with `zeta = drag * packing / diameter`, without fitted constants. + +## Limits + +- Contacts are frictionless and cells are rigid apart from the contact compliance. +- The cost of a step is the number of projected-gradient iterations, which grows with the number of cells that push on each other through the colony; published solvers of this kind report on the order of a thousand iterations per step in dense colonies. +- A perfectly collinear line of cells between two walls is an equilibrium and does not buckle. Division plans perturb daughter directions to break that symmetry. +- The exponential response never stops growth, so a closed space keeps filling slowly as its contact overlaps deepen. +- The cited growth models are two-dimensional and unconfined. Monolayers confined between a floor and a ceiling are covered by the tests here, not by that literature. diff --git a/docs/architecture/README.md b/docs/architecture/README.md index d7e02f5..e5f2161 100644 --- a/docs/architecture/README.md +++ b/docs/architecture/README.md @@ -20,6 +20,7 @@ The [numerical contract](numerical-contract.md) is the best starting point for w ## Cell biology and mechanics - [Typed dynamic contact mechanics](0002-contact-mechanics.md) +- [Contact dynamics with growth](0026-contact-dynamics.md) - [Explicit daughter fractions](0007-division.md) - [Persistent fixed rod cells](0009-fixed-cells.md) - [Biomass, growth, division, and uptake](0024-biomass-accounting.md) diff --git a/python/src/microsimulator/__init__.py b/python/src/microsimulator/__init__.py index 33c01a8..76f9dc6 100644 --- a/python/src/microsimulator/__init__.py +++ b/python/src/microsimulator/__init__.py @@ -20,6 +20,9 @@ CellSnapshot, ConstraintContactParameters, ConstraintRegion, + ContactDynamicsParameters, + ContactDynamicsReport, + ContactDynamicsResult, ContactGraph, ContactParameters, CoupledRatePlan, @@ -34,6 +37,8 @@ GridBoundary, GridBoundaryKind, GridShape, + GrowthLoadLaw, + GrowthLoadResponse, MechanicsIntegrationParameters, MechanicsParameters, MechanicsSolveResult, @@ -75,6 +80,7 @@ ) from .controller import ( CellUpdate, + ContactDynamicsConfig, ControllerPlanError, ControllerStateError, ControllerStep, @@ -162,6 +168,10 @@ "CheckpointSourceBackend", "ConstraintContactParameters", "ConstraintRegion", + "ContactDynamicsConfig", + "ContactDynamicsParameters", + "ContactDynamicsReport", + "ContactDynamicsResult", "ContactGraph", "ContactParameters", "ControllerPlanError", @@ -182,6 +192,8 @@ "GridBoundary", "GridBoundaryKind", "GridShape", + "GrowthLoadLaw", + "GrowthLoadResponse", "MechanicsConfig", "MechanicsIntegrationParameters", "MechanicsParameters", diff --git a/python/src/microsimulator/_core.pyi b/python/src/microsimulator/_core.pyi index 37aafd1..e71cb41 100644 --- a/python/src/microsimulator/_core.pyi +++ b/python/src/microsimulator/_core.pyi @@ -96,6 +96,7 @@ class BackendFeature(Enum): COUPLED_RATES: BackendFeature DEPTH_AVERAGED_FLOW: BackendFeature RESOLVED_FLOW: BackendFeature + CONTACT_DYNAMICS: BackendFeature class FlowAxis(Enum): X: FlowAxis @@ -612,6 +613,56 @@ class MechanicsIntegrationParameters: def __init__(self) -> None: ... +class GrowthLoadLaw(Enum): + NONE: GrowthLoadLaw + EXPONENTIAL: GrowthLoadLaw + LINEAR: GrowthLoadLaw + +class GrowthLoadResponse: + law: GrowthLoadLaw + sensitivity: float + free_load: float + stall_load: float + + def __init__(self) -> None: ... + def factor(self, load: float) -> float: ... + +class ContactDynamicsParameters: + drag: float + contact_stiffness: float + overlap_tolerance: float + candidate_margin: float + max_overlap_recovery: float + max_growth_fraction: float + max_iterations: int + max_refinements: int + max_step_halvings: int + growth: GrowthLoadResponse + + def __init__(self) -> None: ... + +class ContactDynamicsReport: + @property + def substeps(self) -> int: ... + @property + def halvings(self) -> int: ... + @property + def refinements(self) -> int: ... + @property + def iterations(self) -> int: ... + @property + def max_rows(self) -> int: ... + @property + def max_overlap(self) -> float: ... + +class ContactDynamicsResult: + @property + def report(self) -> ContactDynamicsReport: ... + @property + def axial_loads(self) -> list[float]: ... + @property + def length_increments(self) -> list[float]: ... + class SolverReport: @property def status(self) -> SolverStatus: ... @@ -687,7 +738,16 @@ class Simulation: def set_signal_reaction(self, reaction: SignalGridAffineReaction | None) -> None: ... def divide(self, parent_id: int, first_fraction: float) -> tuple[int, int]: ... def divide_equal(self, parent_id: int) -> tuple[int, int]: ... + @overload def step(self, dt: float) -> None: ... + @overload + def step( + self, + dt: float, + dynamics_parameters: ContactDynamicsParameters, + contact_parameters: ContactParameters = ..., + constraint_parameters: ConstraintContactParameters = ..., + ) -> ContactDynamicsResult: ... def find_cell_contacts(self, parameters: ContactParameters = ...) -> ContactGraph: ... def find_external_contacts( self, parameters: ConstraintContactParameters = ... diff --git a/python/src/microsimulator/controller.py b/python/src/microsimulator/controller.py index 3a404f4..0158574 100644 --- a/python/src/microsimulator/controller.py +++ b/python/src/microsimulator/controller.py @@ -12,7 +12,10 @@ from ._core import ( # pyright: ignore[reportMissingModuleSource] CellSnapshot, ConstraintContactParameters, + ContactDynamicsParameters, + ContactDynamicsResult, ContactParameters, + GrowthLoadLaw, MechanicsIntegrationParameters, MechanicsParameters, MechanicsSolveResult, @@ -170,9 +173,135 @@ def _json_object(value: Mapping[str, JSONValue], path: str) -> dict[str, JSONVal return cast(dict[str, JSONValue], decoded) +_GROWTH_LOAD_LAWS = { + "none": GrowthLoadLaw.NONE, + "exponential": GrowthLoadLaw.EXPONENTIAL, + "linear": GrowthLoadLaw.LINEAR, +} + + +@dataclass(frozen=True, slots=True) +class ContactDynamicsConfig: + """Checkpointable parameters for growth and contact solved together. + + Cells push each other and the walls apart with non-negative contact forces + while they elongate, and a cell's elongation responds to the axial load its + contacts put on it. ``growth_law`` selects that response: ``"none"`` ignores + load, ``"exponential"`` scales elongation by ``exp(-growth_sensitivity * + load)``, and ``"linear"`` leaves it unscaled up to ``growth_free_load`` and + stops it at ``growth_stall_load``. Loads are forces in units of ``drag`` times + length squared per time. + """ + + drag: float = 1.0 + contact_stiffness: float = 1.0e4 + overlap_tolerance: float = 1.0e-3 + candidate_margin: float = 0.1 + max_overlap_recovery: float = 0.05 + max_growth_fraction: float = 0.25 + max_iterations: int = 20000 + max_refinements: int = 10 + max_step_halvings: int = 12 + growth_law: str = "none" + growth_sensitivity: float = 0.0 + growth_free_load: float = 0.0 + growth_stall_load: float = 1.0 + + def __post_init__(self) -> None: + for name in ("drag", "contact_stiffness", "overlap_tolerance"): + if _finite_number(getattr(self, name), f"contact_dynamics.{name}") <= 0.0: + raise ControllerStateError(f"contact_dynamics.{name} must be positive") + for name in ("max_overlap_recovery", "max_growth_fraction"): + if _finite_number(getattr(self, name), f"contact_dynamics.{name}") <= 0.0: + raise ControllerStateError(f"contact_dynamics.{name} must be positive") + if _finite_number(self.candidate_margin, "contact_dynamics.candidate_margin") < 0.0: + raise ControllerStateError("contact_dynamics.candidate_margin must be non-negative") + _integer(self.max_iterations, "contact_dynamics.max_iterations", 1, _UINT32_MAX) + _integer(self.max_refinements, "contact_dynamics.max_refinements", 0, _UINT32_MAX) + _integer(self.max_step_halvings, "contact_dynamics.max_step_halvings", 0, 64) + if cast(object, self.growth_law) not in _GROWTH_LOAD_LAWS: + raise ControllerStateError( + "contact_dynamics.growth_law must be one of " + ", ".join(sorted(_GROWTH_LOAD_LAWS)) + ) + sensitivity = _finite_number( + self.growth_sensitivity, "contact_dynamics.growth_sensitivity" + ) + free_load = _finite_number(self.growth_free_load, "contact_dynamics.growth_free_load") + stall_load = _finite_number(self.growth_stall_load, "contact_dynamics.growth_stall_load") + if sensitivity < 0.0 or free_load < 0.0 or stall_load <= free_load: + raise ControllerStateError( + "contact_dynamics growth sensitivity and free load must be non-negative, " + "and the stall load must exceed the free load" + ) + + def native_parameters(self) -> ContactDynamicsParameters: + parameters = ContactDynamicsParameters() + parameters.drag = self.drag + parameters.contact_stiffness = self.contact_stiffness + parameters.overlap_tolerance = self.overlap_tolerance + parameters.candidate_margin = self.candidate_margin + parameters.max_overlap_recovery = self.max_overlap_recovery + parameters.max_growth_fraction = self.max_growth_fraction + parameters.max_iterations = self.max_iterations + parameters.max_refinements = self.max_refinements + parameters.max_step_halvings = self.max_step_halvings + growth = parameters.growth + growth.law = _GROWTH_LOAD_LAWS[self.growth_law] + growth.sensitivity = self.growth_sensitivity + growth.free_load = self.growth_free_load + growth.stall_load = self.growth_stall_load + parameters.growth = growth + return parameters + + def to_json(self) -> dict[str, JSONValue]: + return { + field.name: cast(JSONValue, getattr(self, field.name)) + for field in fields(ContactDynamicsConfig) + } + + @classmethod + def from_json(cls, value: JSONValue) -> ContactDynamicsConfig: + names = {field.name for field in fields(ContactDynamicsConfig)} + if not isinstance(value, dict) or set(value) != names: + raise ControllerStateError("contact dynamics configuration is invalid") + growth_law = value["growth_law"] + if not isinstance(growth_law, str): + raise ControllerStateError("contact_dynamics.growth_law must be a string") + + def number(name: str) -> float: + return _finite_number(value[name], f"contact_dynamics.{name}") + + def count(name: str) -> int: + return _integer(value[name], f"contact_dynamics.{name}", 0, _UINT32_MAX) + + return cls( + drag=number("drag"), + contact_stiffness=number("contact_stiffness"), + overlap_tolerance=number("overlap_tolerance"), + candidate_margin=number("candidate_margin"), + max_overlap_recovery=number("max_overlap_recovery"), + max_growth_fraction=number("max_growth_fraction"), + max_iterations=count("max_iterations"), + max_refinements=count("max_refinements"), + max_step_halvings=count("max_step_halvings"), + growth_law=growth_law, + growth_sensitivity=number("growth_sensitivity"), + growth_free_load=number("growth_free_load"), + growth_stall_load=number("growth_stall_load"), + ) + + @dataclass(frozen=True, slots=True) class MechanicsConfig: - """Checkpointable parameters for exact mechanics passes after each step.""" + """Checkpointable mechanics parameters applied on each controller step. + + Without ``contact_dynamics`` the controller grows the cells and then runs + ``passes`` least-squares relaxation passes. With it, the controller advances + growth and contact together with the contact dynamics solve, and the + relaxation fields ``passes``, ``gamma``, ``residual_rms_tolerance``, + ``max_iterations``, ``max_rotation_radians``, ``require_convergence``, and the + two activation margins are unused. + """ passes: int = 1 mu_a: float = 1.0 @@ -187,6 +316,7 @@ class MechanicsConfig: constraint_activation_margin: float = 0.0 constraint_degeneracy_epsilon: float = 1.0e-6 flow_drift: bool = False + contact_dynamics: ContactDynamicsConfig | None = None def __post_init__(self) -> None: _integer(self.passes, "mechanics.passes", 1, _UINT32_MAX) @@ -225,6 +355,11 @@ def __post_init__(self) -> None: raise ControllerStateError("mechanics.require_convergence must be Boolean") if not isinstance(cast(object, self.flow_drift), bool): raise ControllerStateError("mechanics.flow_drift must be Boolean") + dynamics = cast(object, self.contact_dynamics) + if dynamics is not None and not isinstance(dynamics, ContactDynamicsConfig): + raise ControllerStateError( + "mechanics.contact_dynamics must be a ContactDynamicsConfig or None" + ) def native_parameters( self, @@ -252,17 +387,26 @@ def native_parameters( return mechanics, contacts, integration, constraints def to_json(self) -> dict[str, JSONValue]: - return { + result = { field.name: cast(JSONValue, getattr(self, field.name)) for field in fields(MechanicsConfig) + if field.name != "contact_dynamics" } + result["contact_dynamics"] = ( + None if self.contact_dynamics is None else self.contact_dynamics.to_json() + ) + return result @classmethod def from_json(cls, value: JSONValue) -> MechanicsConfig: - if not isinstance(value, dict) or set(value) != { - field.name for field in fields(MechanicsConfig) - }: + # A payload without a contact dynamics entry selects relaxation passes. + names = {field.name for field in fields(MechanicsConfig)} + if not isinstance(value, dict) or set(value) | {"contact_dynamics"} != names: raise ControllerStateError("controller mechanics configuration is invalid") + dynamics_value = value.get("contact_dynamics") + contact_dynamics = ( + None if dynamics_value is None else ContactDynamicsConfig.from_json(dynamics_value) + ) require_convergence = value["require_convergence"] if not isinstance(require_convergence, bool): raise ControllerStateError("mechanics.require_convergence must be Boolean") @@ -304,6 +448,7 @@ def from_json(cls, value: JSONValue) -> MechanicsConfig: "mechanics.constraint_degeneracy_epsilon", ), flow_drift=flow_drift, + contact_dynamics=contact_dynamics, ) @@ -348,6 +493,7 @@ def __init__( completed_steps, "native controller completed steps", 0, _UINT64_MAX ) self._last_mechanics_reports: tuple[MechanicsSolveResult, ...] = () + self._last_contact_dynamics: ContactDynamicsResult | None = None @property def completed_steps(self) -> int: @@ -361,6 +507,15 @@ def state(self) -> dict[str, JSONValue]: def last_mechanics_reports(self) -> tuple[MechanicsSolveResult, ...]: return self._last_mechanics_reports + @property + def last_contact_dynamics(self) -> ContactDynamicsResult | None: + """The result of the last step's contact dynamics solve, if it ran. + + Its ``axial_loads`` and ``length_increments`` are indexed by cell slot. + """ + + return self._last_contact_dynamics + def _context(self) -> ControllerStep: return ControllerStep( simulation=self.simulation, @@ -471,19 +626,30 @@ def step(self, dt: float) -> None: for removal in plan.removals: self.simulation.remove_cell(removal) - self.simulation.step(dt) reports: list[MechanicsSolveResult] = [] - if ( - self._mechanics is not None - and self._mechanics.flow_drift - and self.simulation.cell_count != 0 - ): - _, _, integration, _ = self._mechanics.native_parameters() - self.simulation.apply_flow_drift(dt, integration) - if self._mechanics is not None and self.simulation.cell_count != 0: - parameters = self._mechanics.native_parameters() - for _ in range(self._mechanics.passes): - reports.append(self.simulation.relax_cell_mechanics(*parameters)) + mechanics = self._mechanics + drifts = ( + mechanics is not None and mechanics.flow_drift and self.simulation.cell_count != 0 + ) + if mechanics is not None and mechanics.contact_dynamics is not None: + # The flow moves the cells first, so the step ends with every + # contact resolved. + _, contacts, integration, constraints = mechanics.native_parameters() + if drifts: + self.simulation.apply_flow_drift(dt, integration) + self._last_contact_dynamics = self.simulation.step( + dt, mechanics.contact_dynamics.native_parameters(), contacts, constraints + ) + else: + self._last_contact_dynamics = None + self.simulation.step(dt) + if mechanics is not None and drifts: + _, _, integration, _ = mechanics.native_parameters() + self.simulation.apply_flow_drift(dt, integration) + if mechanics is not None and self.simulation.cell_count != 0: + parameters = mechanics.native_parameters() + for _ in range(mechanics.passes): + reports.append(self.simulation.relax_cell_mechanics(*parameters)) self._last_mechanics_reports = tuple(reports) self._completed_steps += 1 diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py new file mode 100644 index 0000000..8f829a3 --- /dev/null +++ b/python/tests/test_contact_dynamics.py @@ -0,0 +1,420 @@ +from __future__ import annotations + +import math +import random +from collections.abc import Callable +from pathlib import Path + +import pytest +from microsimulator import ( + BackendFeature, + BackendKind, + BoxConstraintInit, + CellInit, + ConstraintRegion, + ContactDynamicsConfig, + ContactDynamicsParameters, + ControllerStateError, + ControllerStep, + DivisionEvent, + DivisionRequest, + GridShape, + GrowthLoadLaw, + GrowthLoadResponse, + MechanicsConfig, + NativeController, + PlaneConstraintInit, + RatePlanBuilder, + SignalGridSpec, + Simulation, + StepPlan, + Vec3, + backend_available, + load_checkpoint_bundle, + save_checkpoint, +) +from microsimulator.biomass import biomass_volume + +BACKENDS = [pytest.param(backend, id=backend.name.lower()) for backend in BackendKind] + + +def _simulation(backend: BackendKind, **arguments: int) -> Simulation: + if not backend_available(backend): + pytest.skip("native backend is not built") + simulation = Simulation(backend, **arguments) + if not simulation.supports(BackendFeature.CONTACT_DYNAMICS): + pytest.skip("backend does not implement contact dynamics") + return simulation + + +def _between_walls(simulation: Simulation, half_width: float) -> None: + for sign in (-1.0, 1.0): + wall = PlaneConstraintInit() + wall.point = Vec3(sign * half_width, 0.0, 0.0) + wall.inward_normal = Vec3(-sign, 0.0, 0.0) + simulation.add_plane_constraint(wall) + + +def _stalling(stall_load: float) -> ContactDynamicsParameters: + parameters = ContactDynamicsParameters() + growth = parameters.growth + growth.law = GrowthLoadLaw.LINEAR + growth.stall_load = stall_load + parameters.growth = growth + return parameters + + +def _divide_at(length: float) -> Callable[[ControllerStep], StepPlan]: + """Return a regulation callback that divides cells reaching ``length``.""" + + def regulate(step: ControllerStep) -> StepPlan: + return StepPlan( + divisions=tuple( + DivisionRequest(cell.id, 0.5) for cell in step.cells if cell.length >= length + ) + ) + + return regulate + + +def _tilt_daughters(step: ControllerStep, event: DivisionEvent) -> None: + """Turn each daughter by a small angle in the plane so a line of cells can buckle.""" + + for daughter in (event.first, event.second): + angle = step.rng.gauss(0.0, 0.01) + x, y = daughter.direction.x, daughter.direction.y + step.simulation.set_cell_geometry( + daughter.id, + daughter.position, + Vec3( + x * math.cos(angle) - y * math.sin(angle), + x * math.sin(angle) + y * math.cos(angle), + daughter.direction.z, + ), + daughter.length, + ) + + +def _chamber(backend: BackendKind, config: ContactDynamicsConfig) -> NativeController: + simulation = _simulation(backend) + chamber = BoxConstraintInit() + chamber.half_extents = Vec3(2.0, 2.0, 0.6) + chamber.allowed_region = ConstraintRegion.INSIDE + simulation.add_box_constraint(chamber) + founder = CellInit() + founder.length = 1.0 + founder.radius = 0.4 + simulation.add_cell(founder) + return NativeController( + simulation, + model_id="contact-dynamics-chamber-test", + model_version=1, + rng=random.Random(3), + regulate=_divide_at(2.0), + on_division=_tilt_daughters, + mechanics=MechanicsConfig(contact_dynamics=config), + ) + + +def _footprint(simulation: Simulation) -> float: + return sum( + math.pi * cell.radius**2 + 2.0 * cell.radius * cell.length for cell in simulation.cells() + ) + + +def _deepest_overlap(simulation: Simulation) -> float: + contacts = simulation.find_cell_contacts().contacts + walls = simulation.find_external_contacts().contacts + return max([0.0, *(-contact.signed_separation for contact in (*contacts, *walls))]) + + +def test_growth_load_response_factor() -> None: + response = GrowthLoadResponse() + assert response.factor(50.0) == 1.0 + response.law = GrowthLoadLaw.EXPONENTIAL + response.sensitivity = 0.5 + assert math.isclose(response.factor(2.0), math.exp(-1.0), rel_tol=1e-6) + response.law = GrowthLoadLaw.LINEAR + response.free_load, response.stall_load = 1.0, 3.0 + assert response.factor(1.0) == 1.0 + assert math.isclose(response.factor(2.0), 0.5, rel_tol=1e-6) + assert response.factor(9.0) == 0.0 + response.stall_load = 0.5 + with pytest.raises(ValueError, match="stall load"): + response.factor(1.0) + + +def test_contact_dynamics_config_round_trips_and_validates() -> None: + config = ContactDynamicsConfig( + growth_law="linear", growth_free_load=1.0, growth_stall_load=8.0, contact_stiffness=2000.0 + ) + mechanics = MechanicsConfig(flow_drift=True, contact_dynamics=config) + assert MechanicsConfig.from_json(mechanics.to_json()) == mechanics + + parameters = config.native_parameters() + assert parameters.growth.law == GrowthLoadLaw.LINEAR + assert parameters.growth.stall_load == 8.0 + assert parameters.contact_stiffness == 2000.0 + + # A payload written without the entry selects relaxation passes. + legacy = MechanicsConfig(passes=2).to_json() + del legacy["contact_dynamics"] + assert MechanicsConfig.from_json(legacy) == MechanicsConfig(passes=2) + + with pytest.raises(ControllerStateError, match="growth_law"): + ContactDynamicsConfig(growth_law="quadratic") + with pytest.raises(ControllerStateError, match="stall load"): + ContactDynamicsConfig(growth_law="linear", growth_free_load=2.0, growth_stall_load=2.0) + with pytest.raises(ControllerStateError, match="contact_stiffness"): + ContactDynamicsConfig(contact_stiffness=0.0) + invalid = mechanics.to_json() + invalid["contact_dynamics"] = {"drag": 1.0} + with pytest.raises(ControllerStateError, match="contact dynamics configuration"): + MechanicsConfig.from_json(invalid) + with pytest.raises(ControllerStateError, match="ContactDynamicsConfig"): + MechanicsConfig(contact_dynamics=object()) # type: ignore[arg-type] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_unloaded_cells_grow_exactly_as_without_contact(backend: BackendKind) -> None: + simulation = _simulation(backend) + reference = Simulation(backend) + cell = CellInit() + cell.length = 3.0 + cell.growth_rate = 0.8 + for target in (simulation, reference): + target.add_cell(cell) + for dt in (0.0, 0.05, 0.4, 1.0): + result = simulation.step(dt, ContactDynamicsParameters()) + reference.step(dt) + # Substeps add the same elongation in pieces, to rounding. + assert math.isclose(simulation.cell(1).length, reference.cell(1).length, rel_tol=1e-6) + assert simulation.time == reference.time + assert result.report.max_rows == 0 + assert result.axial_loads == [0.0] + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_cell_between_walls_stalls_and_stops_consuming(backend: BackendKind) -> None: + simulation = _simulation(backend, species_count=1) + spec = SignalGridSpec() + shape = GridShape() + shape.x = shape.y = shape.z = 1 + spec.shape = shape + spec.origin = Vec3(-4.0, -4.0, -4.0) + spec.spacing = Vec3(8.0, 8.0, 8.0) + spec.signal_count, spec.diffusion, spec.advection = 1, [0], [Vec3()] + simulation.configure_signal_grid(spec, [10.0]) + rates = RatePlanBuilder() + simulation.set_coupled_rate_plan( + rates.coupled_plan(1, 1, (rates.constant(0),), (-rates.cell_volume_change_rate() / 0.4,)) + ) + _between_walls(simulation, 2.0) + cell = CellInit() + cell.length, cell.radius, cell.species = 2.0, 0.5, [1.0] + cid = simulation.add_cell(cell) + initial = biomass_volume(cell.length, cell.radius) + + parameters = _stalling(4.0) + result = simulation.step(0.0, parameters) + for _ in range(200): + result = simulation.step(0.05, parameters) + current = simulation.cell(cid) + consumed = (10.0 - simulation.signal_levels[0]) * spec.voxel_volume + grown = biomass_volume(current.length, current.radius) - initial + # Uptake is charged for the elongation that happened, not the nominal rate. + assert math.isclose(0.4 * consumed, grown, abs_tol=2e-4) + + # The walls leave room for a cylinder of length 3. + filled = simulation.cell(cid) + assert 3.0 - 2e-3 <= filled.length <= 3.0 + 2e-3 + assert math.isclose(result.axial_loads[0], 4.0, rel_tol=0.05) + assert result.length_increments[0] == 0.0 + level = simulation.signal_levels[0] + for _ in range(20): + simulation.step(0.05, parameters) + assert simulation.signal_levels[0] == level + assert math.isclose(simulation.cell(cid).length, filled.length, abs_tol=1e-5) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_closed_chamber_fills_and_holds(backend: BackendKind) -> None: + controller = _chamber(backend, ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0)) + for _ in range(300): + controller.step(0.05) + simulation = controller.simulation + count, footprint = simulation.cell_count, _footprint(simulation) + for _ in range(300): + controller.step(0.05) + + assert simulation.cell_count == count + assert math.isclose(_footprint(simulation), footprint, abs_tol=0.02) + assert 0.6 < _footprint(simulation) / 16.0 < 1.0 + assert _deepest_overlap(simulation) < 0.01 + result = controller.last_contact_dynamics + assert result is not None + assert max(result.length_increments) < 1e-5 + assert controller.last_mechanics_reports == () + for cell in simulation.cells(): + assert abs(cell.position.x) <= 2.0 and abs(cell.position.y) <= 2.0 + assert abs(cell.position.z) < 1e-3 + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_unconfined_colony_grows_in_full_without_overlap(backend: BackendKind) -> None: + simulation = _simulation(backend, reserved_capacity=512) + founder = CellInit() + founder.length = 2.0 + simulation.add_cell(founder) + controller = NativeController( + simulation, + model_id="contact-dynamics-colony-test", + model_version=1, + rng=random.Random(5), + regulate=_divide_at(4.0), + on_division=_tilt_daughters, + mechanics=MechanicsConfig(contact_dynamics=ContactDynamicsConfig()), + ) + # The same lineage with growth and division alone. + reference = Simulation(BackendKind.CPU, reserved_capacity=512) + reference.add_cell(founder) + worst = 0.0 + for _ in range(130): + for cell in reference.cells(): + if cell.length >= 4.0: + reference.divide(cell.id, 0.5) + reference.step(0.05) + controller.step(0.05) + result = controller.last_contact_dynamics + assert result is not None + worst = max(worst, result.report.max_overlap) + + assert simulation.cell_count == reference.cell_count >= 64 + length = sum(cell.length for cell in simulation.cells()) + assert math.isclose(length, sum(cell.length for cell in reference.cells()), rel_tol=1e-4) + assert worst < 0.01 + assert all(abs(cell.position.z) < 1e-3 for cell in simulation.cells()) + # A colony that buckled is far wider than its cells are long, and no + # longer a single line. + xs = [cell.position.x for cell in simulation.cells()] + ys = [cell.position.y for cell in simulation.cells()] + assert max(ys) - min(ys) > 4.0 + assert max(xs) - min(xs) < 0.5 * length + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_resume_reproduces_the_uninterrupted_trajectory( + backend: BackendKind, tmp_path: Path +) -> None: + config = ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0) + uninterrupted = _chamber(backend, config) + for _ in range(120): + uninterrupted.step(0.05) + + split = _chamber(backend, config) + for _ in range(70): + split.step(0.05) + midpoint = tmp_path / "midpoint.json" + save_checkpoint(split.simulation, midpoint, controller=split.controller_state()) + resumed = NativeController.from_checkpoint( + load_checkpoint_bundle(midpoint, backend=backend), + model_id="contact-dynamics-chamber-test", + model_version=1, + regulate=_divide_at(2.0), + on_division=_tilt_daughters, + ) + for _ in range(50): + resumed.step(0.05) + + assert resumed.controller_state() == uninterrupted.controller_state() + assert resumed.simulation.cell_count == uninterrupted.simulation.cell_count > 4 + for actual, expected in zip( + resumed.simulation.cells(), uninterrupted.simulation.cells(), strict=True + ): + assert actual.id == expected.id + assert actual.length == expected.length + assert (actual.position.x, actual.position.y) == (expected.position.x, expected.position.y) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_free_colony_matches_the_continuum_pressure_profile(backend: BackendKind) -> None: + """A colony growing without load response against its drag on the substrate. + + Treating the colony as an incompressible fluid that grows at the areal + rate g and is dragged at zeta per unit area gives the radial pressure + p(r) = zeta * g * (R^2 - r^2) / 4. Drag per unit cell length becomes + zeta = drag * packing / diameter per unit area, and the axial load on a + cell is the pressure across its diameter. + """ + + simulation = _simulation(backend, reserved_capacity=2048) + founder = CellInit() + founder.length = 2.0 + simulation.add_cell(founder) + rng = random.Random(1) + thresholds: dict[int, float] = {} + parameters = ContactDynamicsParameters() + areas: list[float] = [] + step_length = 0.05 + result = simulation.step(0.0, parameters) + for _ in range(200): + for cell in simulation.cells(): + threshold = thresholds.setdefault(cell.id, 4.0 * (1.0 + 0.2 * (rng.random() - 0.5))) + if cell.length < threshold: + continue + for daughter_id in simulation.divide(cell.id, 0.5): + daughter = simulation.cell(daughter_id) + angle = rng.gauss(0.0, 0.02) + x, y = daughter.direction.x, daughter.direction.y + simulation.set_cell_geometry( + daughter_id, + daughter.position, + Vec3( + x * math.cos(angle) - y * math.sin(angle), + x * math.sin(angle) + y * math.cos(angle), + 0.0, + ), + daughter.length, + ) + result = simulation.step(step_length, parameters) + areas.append(_footprint(simulation)) + + cells = simulation.cells() + assert len(cells) > 800 + center_x = sum(cell.position.x for cell in cells) / len(cells) + center_y = sum(cell.position.y for cell in cells) / len(cells) + radii = [math.hypot(cell.position.x - center_x, cell.position.y - center_y) for cell in cells] + colony_radius = sorted(radii)[int(0.98 * len(radii))] + packing = areas[-1] / (math.pi * colony_radius**2) + areal_rate = math.log(areas[-1] / areas[-21]) / (20 * step_length) + # Rigid cells pack to a little under a full layer. + assert 0.8 < packing < 1.0 + + bin_count = 6 + bins: list[list[float]] = [[] for _ in range(bin_count)] + for radius, cell in zip(radii, cells, strict=True): + bins[min(bin_count - 1, int(radius / colony_radius * bin_count))].append( + result.axial_loads[cell.slot] + ) + means = [sum(loads) / len(loads) for loads in bins] + central = parameters.drag * packing * areal_rate * colony_radius**2 / 4.0 + for index, mean in enumerate(means): + position = (index + 0.5) / bin_count + predicted = central * (1.0 - position**2) + assert math.isclose(mean, predicted, rel_tol=0.35, abs_tol=0.05 * central) + # The few cells of the innermost bin are noisy; the fall toward the edge is not. + assert means[1:] == sorted(means[1:], reverse=True) + assert means[0] > 3.0 * means[-1] + + +def test_backend_without_the_feature_rejects_the_step() -> None: + for backend in BackendKind: + if not backend_available(backend): + continue + simulation = Simulation(backend) + if simulation.supports(BackendFeature.CONTACT_DYNAMICS): + continue + simulation.add_cell(CellInit()) + with pytest.raises(RuntimeError, match="contact dynamics"): + simulation.step(0.1, ContactDynamicsParameters()) + assert simulation.time == 0.0 diff --git a/tests/cpp/contact_dynamics_test.cpp b/tests/cpp/contact_dynamics_test.cpp new file mode 100644 index 0000000..ba329d2 --- /dev/null +++ b/tests/cpp/contact_dynamics_test.cpp @@ -0,0 +1,442 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +#include "microsimulator/contact_dynamics.hpp" +#include "microsimulator/simulation.hpp" + +namespace { + +using microsimulator::BackendKind; +using microsimulator::CellInit; +using microsimulator::ContactDynamicsParameters; +using microsimulator::GrowthLoadLaw; +using microsimulator::Simulation; +using microsimulator::Vec3; + +bool close(float actual, float expected, float tolerance = 1.0e-5F) { + return std::abs(actual - expected) <= tolerance; +} + +// Deterministic angles in (-scale, scale) for perturbing daughter directions. +class Jitter { + public: + float next(float scale) { + state_ = state_ * 6364136223846793005ULL + 1442695040888963407ULL; + const auto unit = static_cast((state_ >> 40U) & 0xFFFFFFU) / 16777216.0F; + return (2.0F * unit - 1.0F) * scale; + } + + private: + std::uint64_t state_{0x9E3779B97F4A7C15ULL}; +}; + +// Divides every cell at least `division_length` long, turning each daughter by +// a small angle in the plane so that a line of cells can buckle. +void divide_long_cells(Simulation& simulation, float division_length, Jitter& jitter) { + for (const auto& cell : simulation.cells()) { + if (cell.length < division_length) { + continue; + } + const auto [first, second] = simulation.divide_equal(cell.id); + for (const auto id : {first, second}) { + const auto daughter = simulation.cell(id); + const auto angle = jitter.next(0.02F); + const Vec3 direction{ + daughter.direction.x * std::cos(angle) - daughter.direction.y * std::sin(angle), + daughter.direction.x * std::sin(angle) + daughter.direction.y * std::cos(angle), + daughter.direction.z, + }; + simulation.set_cell_geometry(id, daughter.position, direction, daughter.length); + } + } +} + +float deepest_overlap(Simulation& simulation) { + auto overlap = 0.0F; + const auto pairs = simulation.find_cell_contacts(); + for (const auto& contact : pairs.contacts()) { + overlap = std::max(overlap, -contact.signed_separation); + } + const auto walls = simulation.find_external_contacts(); + for (const auto& contact : walls.contacts()) { + overlap = std::max(overlap, -contact.signed_separation); + } + return overlap; +} + +float footprint(const Simulation& simulation) { + auto area = 0.0F; + for (const auto& cell : simulation.cells()) { + area += std::numbers::pi_v * cell.radius * cell.radius + + 2.0F * cell.radius * cell.length; + } + return area; +} + +void test_growth_load_factor_follows_each_law() { + microsimulator::GrowthLoadResponse response; + assert(close(microsimulator::growth_load_factor(response, 100.0F), 1.0F)); + + response.law = GrowthLoadLaw::exponential; + response.sensitivity = 0.5F; + assert(close(microsimulator::growth_load_factor(response, 0.0F), 1.0F)); + assert(close(microsimulator::growth_load_factor(response, 2.0F), std::exp(-1.0F))); + + response.law = GrowthLoadLaw::linear; + response.free_load = 1.0F; + response.stall_load = 3.0F; + assert(close(microsimulator::growth_load_factor(response, 0.5F), 1.0F)); + assert(close(microsimulator::growth_load_factor(response, 2.0F), 0.5F)); + assert(close(microsimulator::growth_load_factor(response, 3.0F), 0.0F)); + assert(close(microsimulator::growth_load_factor(response, 30.0F), 0.0F)); + + response.stall_load = 1.0F; + bool rejected = false; + try { + microsimulator::validate_growth_load_response(response); + } catch (const std::invalid_argument&) { + rejected = true; + } + assert(rejected); +} + +void test_separated_cells_grow_without_moving() { + Simulation simulation; + CellInit cell; + cell.length = 2.0F; + const auto first = simulation.add_cell(cell); + cell.position = {0.0F, 5.0F, 0.0F}; + const auto second = simulation.add_cell(cell); + + const auto result = simulation.step(0.1F, ContactDynamicsParameters{}); + assert(result.report.max_rows == 0); + assert(close(simulation.cell(first).position.y, 0.0F)); + assert(close(simulation.cell(second).position.y, 5.0F)); + assert(close(simulation.cell(first).length, 2.2F)); + assert(close(result.length_increments[0], 0.2F)); + assert(close(result.axial_loads[0], 0.0F)); + assert(close(static_cast(simulation.time()), 0.1F)); +} + +void test_end_to_end_cells_push_apart_and_keep_growing() { + Simulation simulation; + CellInit cell; + cell.length = 2.0F; + cell.position = {-1.5F, 0.0F, 0.0F}; + const auto first = simulation.add_cell(cell); + cell.position = {1.5F, 0.0F, 0.0F}; + const auto second = simulation.add_cell(cell); + + ContactDynamicsParameters parameters; + const auto result = simulation.step(0.1F, parameters); + const auto left = simulation.cell(first); + const auto right = simulation.cell(second); + // Without a load response both cells elongate in full, and the drag is the + // same on each, so they move apart symmetrically. + assert(close(left.length, 2.2F)); + assert(close(right.length, 2.2F)); + assert(close(left.position.x, -right.position.x, 1.0e-4F)); + const auto gap = (right.position.x - left.position.x) - 0.5F * (left.length + right.length) - + (left.radius + right.radius); + assert(gap > -parameters.overlap_tolerance); + assert(gap < parameters.overlap_tolerance); + // Each cell carries the contact force on one end. + assert(result.axial_loads[0] > 0.0F); + assert(close(result.axial_loads[0], result.axial_loads[1], 1.0e-3F)); +} + +void test_solution_satisfies_complementarity() { + // Two crossed rods pressed together and a third clear of both. + const std::vector bodies( + 3, microsimulator::ContactBody{ + .axis = {1.0F, 0.0F, 0.0F}, + .translational_mobility = 0.5F, + .transverse_mobility = 1.0F, + .axial_mobility = 8.0F, + .length_rate = 0.5F, + }); + std::vector rows(2); + rows[0].first_slot = 0; + rows[0].second_slot = 1; + rows[0].first_jacobian = {0.0F, -1.0F, 0.0F, 0.0F, 0.0F, -0.3F}; + rows[0].second_jacobian = {0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.1F}; + rows[0].first_length_lever = 0.5F; + rows[0].offset = -0.02F; + rows[0].compliance = 1.0e-4F; + rows[1].first_slot = 1; + rows[1].second_slot = 2; + rows[1].first_jacobian = {-1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}; + rows[1].second_jacobian = {1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.0F}; + rows[1].offset = 0.5F; + rows[1].compliance = 1.0e-4F; + + microsimulator::ContactSystem system{ + .rows = rows, + .bodies = bodies, + .dt = 0.05F, + }; + system.growth.law = GrowthLoadLaw::exponential; + system.growth.sensitivity = 0.2F; + + const std::vector zero(rows.size(), 0.0F); + const microsimulator::ContactSolveParameters parameters{.tolerance = 1.0e-6F}; + const auto solve = microsimulator::solve_contact_system_cpu(system, zero, parameters); + assert(solve.report.status == microsimulator::ContactSolveStatus::converged); + const auto gaps = microsimulator::evaluate_contact_gaps(system, solve.multipliers); + assert(solve.multipliers[0] > 0.0F); + assert(std::abs(gaps[0]) <= 1.0e-5F); + assert(solve.multipliers[1] == 0.0F); + assert(gaps[1] > 0.0F); + + // The pressed cell elongates more slowly than the free one. + const auto response = microsimulator::evaluate_contact_response(system, solve.multipliers); + assert(response.loads[0] > 0.0F); + assert(response.length_rates[0] < 0.5F); + assert(close(response.length_rates[2], 0.5F)); + + // A solve started from its own solution has nothing left to do. + const auto again = + microsimulator::solve_contact_system_cpu(system, solve.multipliers, parameters); + assert(again.report.iterations == 0); +} + +void test_cell_between_walls_stalls_at_the_stall_load() { + Simulation simulation; + microsimulator::PlaneConstraintInit left; + left.point = {-2.0F, 0.0F, 0.0F}; + left.inward_normal = {1.0F, 0.0F, 0.0F}; + simulation.add_plane_constraint(left); + microsimulator::PlaneConstraintInit right; + right.point = {2.0F, 0.0F, 0.0F}; + right.inward_normal = {-1.0F, 0.0F, 0.0F}; + simulation.add_plane_constraint(right); + CellInit cell; + cell.length = 2.0F; + const auto id = simulation.add_cell(cell); + + ContactDynamicsParameters parameters; + parameters.growth.law = GrowthLoadLaw::linear; + parameters.growth.stall_load = 4.0F; + microsimulator::ContactDynamicsResult result; + for (int step = 0; step < 200; ++step) { + result = simulation.step(0.05F, parameters); + } + // The walls leave room for a cylinder of length 3. The cell fills it, to + // within the overlap its stall load presses into the two walls, and stops. + const auto filled = simulation.cell(id); + const auto wall_overlap = parameters.growth.stall_load / parameters.contact_stiffness; + assert(filled.length >= 3.0F - 2.0F * parameters.overlap_tolerance); + assert(filled.length <= 3.0F + 2.0F * (wall_overlap + parameters.overlap_tolerance)); + assert(close(filled.position.x, 0.0F, 1.0e-3F)); + assert(result.axial_loads[0] >= parameters.growth.stall_load * 0.99F); + assert(result.axial_loads[0] <= parameters.growth.stall_load * 1.05F); + const auto held = filled.length; + for (int step = 0; step < 50; ++step) { + std::ignore = simulation.step(0.05F, parameters); + } + assert(close(simulation.cell(id).length, held, 1.0e-4F)); +} + +void test_fixed_cell_holds_its_place() { + Simulation simulation; + CellInit cell; + cell.length = 2.0F; + cell.position = {-1.5F, 0.0F, 0.0F}; + cell.fixed = true; + const auto anchor = simulation.add_cell(cell); + cell.position = {1.5F, 0.0F, 0.0F}; + cell.fixed = false; + const auto free = simulation.add_cell(cell); + + ContactDynamicsParameters parameters; + std::ignore = simulation.step(0.1F, parameters); + const auto held = simulation.cell(anchor); + const auto pushed = simulation.cell(free); + assert(close(held.position.x, -1.5F)); + assert(close(held.length, 2.2F)); + // Each cell's facing end advances by half its elongation, and the free cell + // takes all of the separation. + assert(close(pushed.position.x, 1.5F + 0.2F, 2.0F * parameters.overlap_tolerance)); +} + +void test_container_corner_reports_every_wall() { + microsimulator::WorldState state; + CellInit cell; + cell.length = 1.0F; + cell.radius = 0.4F; + cell.position = {1.1F, 1.55F, 0.0F}; + state.add_cell(cell); + microsimulator::ConstraintSet constraints; + microsimulator::BoxConstraintInit box; + box.half_extents = {2.0F, 2.0F, 0.6F}; + box.allowed_region = microsimulator::ConstraintRegion::inside; + constraints.add_box(box); + + microsimulator::ConstraintContactParameters parameters; + parameters.activation_margin = 0.1F; + // Both ends lie 0.05 clear of the +y wall, and the positive end also touches + // the +x wall. The nearest-face contacts hold each end against one wall only. + const auto nearest = microsimulator::find_external_contacts_cpu(state, constraints, parameters); + const auto faces = microsimulator::find_external_contact_faces(state, constraints, parameters); + assert(nearest.size() == 2); + assert(faces.size() == 3); + bool x_wall = false; + bool y_wall = false; + for (const auto& contact : faces.contacts()) { + if (contact.location != microsimulator::RodContactLocation::positive) { + assert(close(contact.normal.y, 1.0F)); + continue; + } + if (close(contact.normal.x, 1.0F)) { + x_wall = true; + assert(close(contact.signed_separation, 0.0F, 1.0e-5F)); + } + if (close(contact.normal.y, 1.0F)) { + y_wall = true; + assert(close(contact.signed_separation, 0.05F, 1.0e-5F)); + } + } + assert(x_wall && y_wall); +} + +void test_closed_chamber_fills_and_holds() { + Simulation simulation; + microsimulator::BoxConstraintInit chamber; + chamber.half_extents = {2.0F, 2.0F, 0.6F}; + chamber.allowed_region = microsimulator::ConstraintRegion::inside; + simulation.add_box_constraint(chamber); + CellInit founder; + founder.length = 1.0F; + founder.radius = 0.4F; + simulation.add_cell(founder); + + ContactDynamicsParameters parameters; + parameters.growth.law = GrowthLoadLaw::linear; + parameters.growth.stall_load = 2.0F; + Jitter jitter; + const auto run = [&](int steps) { + for (int step = 0; step < steps; ++step) { + divide_long_cells(simulation, 2.0F, jitter); + std::ignore = simulation.step(0.05F, parameters); + } + }; + run(300); + const auto filled_count = simulation.cell_count(); + const auto filled_footprint = footprint(simulation); + run(300); + + // The population and its footprint stop changing once the floor is full. + assert(simulation.cell_count() == filled_count); + assert(close(footprint(simulation), filled_footprint, 0.02F)); + const auto cover = footprint(simulation) / 16.0F; + assert(cover > 0.6F); + assert(cover < 1.0F); + assert(deepest_overlap(simulation) < 0.01F); + for (const auto& cell : simulation.cells()) { + assert(std::abs(cell.position.x) + 0.0F <= 2.0F); + assert(std::abs(cell.position.y) <= 2.0F); + assert(close(cell.position.z, 0.0F, 1.0e-3F)); + } +} + +void test_unconfined_colony_grows_in_full_without_overlap() { + Simulation simulation(BackendKind::cpu, 512); + CellInit founder; + founder.length = 2.0F; + simulation.add_cell(founder); + // The same cells with no mechanics: growth and division alone. + Simulation reference(BackendKind::cpu, 512); + reference.add_cell(founder); + + ContactDynamicsParameters parameters; + Jitter jitter; + Jitter reference_jitter; + auto worst = 0.0F; + for (int step = 0; step < 110; ++step) { + divide_long_cells(simulation, 4.0F, jitter); + divide_long_cells(reference, 4.0F, reference_jitter); + const auto result = simulation.step(0.05F, parameters); + reference.step(0.05F); + worst = std::max(worst, result.report.max_overlap); + } + assert(simulation.cell_count() == reference.cell_count()); + assert(simulation.cell_count() >= 32); + auto length = 0.0F; + auto reference_length = 0.0F; + for (const auto& cell : simulation.cells()) { + length += cell.length; + assert(close(cell.position.z, 0.0F, 1.0e-4F)); + } + for (const auto& cell : reference.cells()) { + reference_length += cell.length; + } + assert(close(length, reference_length, 1.0e-3F * reference_length)); + // Overlap stays at what the contact forces press into the cells. + assert(worst < 0.01F); + assert(deepest_overlap(simulation) < 0.01F); +} + +void test_failed_step_leaves_the_simulation_unchanged() { + Simulation simulation; + CellInit cell; + cell.length = 2.0F; + cell.position = {-1.5F, 0.0F, 0.0F}; + simulation.add_cell(cell); + cell.position = {1.5F, 0.0F, 0.0F}; + simulation.add_cell(cell); + cell.position = {4.5F, 0.0F, 0.0F}; + simulation.add_cell(cell); + const auto before = simulation.cells(); + + ContactDynamicsParameters parameters; + // One iteration cannot resolve two coupled contacts at any substep length. + parameters.max_iterations = 1; + parameters.overlap_tolerance = 1.0e-7F; + parameters.max_step_halvings = 2; + bool failed = false; + try { + std::ignore = simulation.step(0.1F, parameters); + } catch (const std::runtime_error&) { + failed = true; + } + assert(failed); + assert(simulation.time() == 0.0); + const auto after = simulation.cells(); + for (std::size_t index = 0; index < before.size(); ++index) { + assert(after[index].position.x == before[index].position.x); + assert(after[index].length == before[index].length); + assert(after[index].direction.x == before[index].direction.x); + } + + parameters = ContactDynamicsParameters{}; + parameters.contact_stiffness = 0.0F; + bool rejected = false; + try { + std::ignore = simulation.step(0.1F, parameters); + } catch (const std::invalid_argument&) { + rejected = true; + } + assert(rejected); +} + +} // namespace + +int main() { + test_growth_load_factor_follows_each_law(); + test_separated_cells_grow_without_moving(); + test_end_to_end_cells_push_apart_and_keep_growing(); + test_solution_satisfies_complementarity(); + test_cell_between_walls_stalls_at_the_stall_load(); + test_fixed_cell_holds_its_place(); + test_container_corner_reports_every_wall(); + test_closed_chamber_fills_and_holds(); + test_unconfined_colony_grows_in_full_without_overlap(); + test_failed_step_leaves_the_simulation_unchanged(); + return 0; +} From 1a9547da15a2933216bbf965fcc05858c29259a0 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 11:27:22 +0000 Subject: [PATCH 2/8] Solve contact dynamics on the Metal and CUDA backends The projected-gradient iteration is shared: a backend supplies the gap evaluation and the reductions over its own storage. The Metal backend keeps the step length and stopping test on the device and runs a batch of steps per command buffer. The CUDA backend reads the reduced step terms back each step. Simulation.solve_contact_system solves a standalone contact system on the selected backend, and the conformance test holds every backend to the CPU solution of the same systems and to the chamber and free-colony trajectories. --- CMakeLists.txt | 9 + cpp/core/contact_dynamics.cpp | 27 +- cpp/core/contact_solver.hpp | 95 ++++-- cpp/core/device_types.hpp | 4 + cpp/core/simulation.cpp | 9 + cpp/cpu/cpu_contact_dynamics.cpp | 48 +-- cpp/cuda/cuda_backend.cu | 201 ++++++++++- cpp/cuda/kernels/contact_dynamics.cu | 172 ++++++++++ cpp/cuda/kernels/contact_dynamics.cuh | 73 ++++ cpp/include/microsimulator/simulation.hpp | 5 + cpp/metal/kernels/contact_dynamics.metal | 168 ++++++++++ cpp/metal/metal_backend.mm | 313 +++++++++++++++++- cpp/shared/constants.def | 4 + cpp/shared/device_types.h | 44 +++ python/tests/test_contact_dynamics.py | 3 +- .../contact_dynamics_conformance_test.cpp | 305 +++++++++++++++++ 16 files changed, 1416 insertions(+), 64 deletions(-) create mode 100644 cpp/cuda/kernels/contact_dynamics.cu create mode 100644 cpp/cuda/kernels/contact_dynamics.cuh create mode 100644 cpp/metal/kernels/contact_dynamics.metal create mode 100644 tests/conformance/contact_dynamics_conformance_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 0249429..8af4081 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -106,6 +106,7 @@ if(MICROSIMULATOR_ENABLE_METAL) microsimulator_embed_metal_source(species cpp/metal/kernels/species.metal) microsimulator_embed_metal_source(contacts cpp/metal/kernels/contacts.metal) microsimulator_embed_metal_source(mechanics cpp/metal/kernels/mechanics.metal) + microsimulator_embed_metal_source(contact_dynamics cpp/metal/kernels/contact_dynamics.metal) microsimulator_embed_metal_source(signals cpp/metal/kernels/grid_transport.metal cpp/metal/kernels/signals.metal) microsimulator_embed_metal_source(coupled_rates @@ -155,6 +156,7 @@ if(MICROSIMULATOR_ENABLE_CUDA) cpp/cuda/cuda_flow.cu cpp/cuda/cuda_occupancy.cu cpp/cuda/kernels/occupancy.cu + cpp/cuda/kernels/contact_dynamics.cu cpp/cuda/kernels/contacts.cu cpp/cuda/kernels/coupled_rates.cu cpp/cuda/kernels/growth.cu @@ -351,6 +353,13 @@ if(MICROSIMULATOR_BUILD_TESTS) add_test(NAME mechanics_conformance COMMAND microsimulator_mechanics_conformance_test) set_tests_properties(mechanics_conformance PROPERTIES LABELS conformance) + add_executable(microsimulator_contact_dynamics_conformance_test + tests/conformance/contact_dynamics_conformance_test.cpp + ) + target_link_libraries(microsimulator_contact_dynamics_conformance_test PRIVATE microsimulator::core) + add_test(NAME contact_dynamics_conformance COMMAND microsimulator_contact_dynamics_conformance_test) + set_tests_properties(contact_dynamics_conformance PROPERTIES LABELS conformance) + add_executable(microsimulator_constraint_mechanics_conformance_test tests/conformance/constraint_mechanics_conformance_test.cpp ) diff --git a/cpp/core/contact_dynamics.cpp b/cpp/core/contact_dynamics.cpp index ec3f189..5c8937f 100644 --- a/cpp/core/contact_dynamics.cpp +++ b/cpp/core/contact_dynamics.cpp @@ -13,11 +13,18 @@ #include #include "core/contact_stepper.hpp" +#include "core/shared_constants.hpp" #include "microsimulator/mechanics.hpp" namespace microsimulator { namespace { +// The device kernels select the growth load law by these codes. +static_assert(static_cast(GrowthLoadLaw::none) == shared::growth_load_law_none); +static_assert(static_cast(GrowthLoadLaw::exponential) == + shared::growth_load_law_exponential); +static_assert(static_cast(GrowthLoadLaw::linear) == shared::growth_load_law_linear); + // Cylinder lengths below this have no axis to elongate along. constexpr float minimum_lever_length = 1.0e-6F; // The solve converges to this fraction of the overlap tolerance, which leaves @@ -143,18 +150,16 @@ using TouchKey = std::tuple; row.first_slot = touch.first_slot; row.second_slot = touch.second_slot; row.offset = std::max(touch.separation, -recovery); - row.compliance = touch.separation < -recovery ? compliance * recovery / -touch.separation - : compliance; + row.compliance = + touch.separation < -recovery ? compliance * recovery / -touch.separation : compliance; const auto& normal = touch.normal; const auto first_arm = cross(touch.point - geometry.positions[touch.first_slot], normal); - row.first_jacobian = {-normal.x, -normal.y, -normal.z, - -first_arm.x, -first_arm.y, -first_arm.z}; + row.first_jacobian = {-normal.x, -normal.y, -normal.z, -first_arm.x, -first_arm.y, -first_arm.z}; const auto first_centerline = touch.point - normal * radii[touch.first_slot]; row.first_length_lever = length_lever(geometry, touch.first_slot, first_centerline, normal); if (touch.second_slot != invalid_slot) { const auto second_arm = cross(touch.point - geometry.positions[touch.second_slot], normal); - row.second_jacobian = {normal.x, normal.y, normal.z, - second_arm.x, second_arm.y, second_arm.z}; + row.second_jacobian = {normal.x, normal.y, normal.z, second_arm.x, second_arm.y, second_arm.z}; const auto second_centerline = touch.point + normal * (touch.separation + radii[touch.second_slot]); row.second_length_lever = @@ -266,8 +271,7 @@ struct Substep { [[nodiscard]] std::optional advance_substep( WorldState& state, const Geometry& base, std::span rate_lengths, const ConstraintSet& constraints, ComputeBackend& backend, float dt, - const ContactDynamicsParameters& parameters, - const ContactParameters& contact_parameters, + const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, const ConstraintContactParameters& constraint_parameters, std::uint64_t& iterations) { const auto radii = state.geometry_state().radii; const auto bodies = make_bodies(state, rate_lengths, parameters.drag); @@ -286,8 +290,7 @@ struct Substep { } // Overlap deeper than one substep recovers is accepted for now. const auto tolerance = effective_overlap_tolerance(parameters); - const auto slack = - tolerance + std::max(0.0F, starting_overlap - parameters.max_overlap_recovery); + const auto slack = tolerance + std::max(0.0F, starting_overlap - parameters.max_overlap_recovery); const ContactSolveParameters solve_parameters{ .tolerance = solve_tolerance_fraction * tolerance, .max_iterations = parameters.max_iterations, @@ -472,8 +475,8 @@ ContactDynamicsResult advance_contact_dynamics( const auto rates = state.cell_attributes().growth_rates; auto growth = 0.0F; for (std::size_t slot = 0; slot < view.size(); ++slot) { - growth = std::max( - growth, std::abs(rates[slot]) * view.lengths[slot] * 0.5F * dt / view.radii[slot]); + growth = std::max(growth, + std::abs(rates[slot]) * view.lengths[slot] * 0.5F * dt / view.radii[slot]); } const auto pieces = std::max(1.0F, std::ceil(growth / parameters.max_growth_fraction)); if (!std::isfinite(pieces)) { diff --git a/cpp/core/contact_solver.hpp b/cpp/core/contact_solver.hpp index 64a9bcb..406fe98 100644 --- a/cpp/core/contact_solver.hpp +++ b/cpp/core/contact_solver.hpp @@ -18,17 +18,27 @@ struct ContactSolverSums { float residual{0.0F}; }; -// The vector operations of the projected-gradient solve of a contact system. -// A backend supplies them over its own storage for the multipliers and their -// gaps; the iteration, its step lengths, and its convergence test are the -// same for every backend. +// Where a run of iterations ended. +struct ContactSolverProgress { + // Iterations taken in this run. + std::uint32_t iterations{0}; + float residual{0.0F}; +}; + +// The projected-gradient solve of a contact system over a backend's own +// storage for the multipliers and their gaps. struct ContactSolverOperations { - // Loads the initial multipliers and evaluates their gaps. Returns the - // residual. - std::function initialize; - // multipliers = max(multipliers - step_length * gaps, 0), then evaluates - // the gaps of the new multipliers. - std::function step; + // Loads the initial multipliers, evaluates their gaps, and sets the first + // step length. Returns the residual. + std::function initialize; + // Takes up to the given number of steps, stopping after the first whose + // residual is within the tolerance or not finite. Each step is + // multipliers = max(multipliers - step_length * gaps, 0) followed by + // `next_contact_step_length`. + std::function iterate; + // Steps requested per call of `iterate`. A device backend runs a batch + // without returning to the host. + std::uint32_t batch{1}; }; // The residual contribution of one row: a positive multiplier needs a zero @@ -37,14 +47,47 @@ struct ContactSolverOperations { return multiplier > 0.0F ? std::abs(gap) : std::max(0.0F, -gap); } +// The Barzilai-Borwein step length after the step numbered `iteration`, +// counting from one. The two lengths alternate. The contact energy is convex, +// so step . change is non-negative; a vanishing product keeps the current +// length. +[[nodiscard]] inline float next_contact_step_length(float current, const ContactSolverSums& sums, + std::uint32_t iteration) { + if (!(sums.step_dot_change > 0.0) || !(sums.change_dot_change > 0.0)) { + return current; + } + const auto next = (iteration % 2U) == 1U ? sums.step_dot_step / sums.step_dot_change + : sums.step_dot_change / sums.change_dot_change; + return std::isfinite(next) && next > 0.0 ? static_cast(next) : current; +} + +// Runs `iterate`'s contract over a host-driven step: `step(step_length)` +// takes one projected step and returns its sums. +template +[[nodiscard]] ContactSolverProgress iterate_contact_steps(std::uint32_t count, float tolerance, + float& step_length, + std::uint32_t& iteration, Step&& step) { + ContactSolverProgress progress; + for (std::uint32_t index = 0; index < count; ++index) { + const ContactSolverSums sums = step(step_length); + ++iteration; + ++progress.iterations; + progress.residual = sums.residual; + if (!(sums.residual > tolerance) || !std::isfinite(sums.residual)) { + break; + } + step_length = next_contact_step_length(step_length, sums, iteration); + } + return progress; +} + // Barzilai-Borwein projected gradient descent on the convex contact energy, -// whose gradient is the gap. The two Barzilai-Borwein step lengths alternate. -// `first_step_length` must be positive. +// whose gradient is the gap. `first_step_length` must be positive. [[nodiscard]] inline ContactSolveReport solve_contact_system( const ContactSolverOperations& operations, float first_step_length, const ContactSolveParameters& parameters) { ContactSolveReport report; - report.residual = operations.initialize(); + report.residual = operations.initialize(first_step_length); if (!std::isfinite(report.residual)) { report.status = ContactSolveStatus::breakdown; return report; @@ -54,27 +97,23 @@ struct ContactSolverOperations { } report.status = ContactSolveStatus::iteration_limit; - auto step_length = first_step_length; - for (std::uint32_t iteration = 1; iteration <= parameters.max_iterations; ++iteration) { - const auto sums = operations.step(step_length); - report.iterations = iteration; - report.residual = sums.residual; - if (!std::isfinite(sums.residual) || !std::isfinite(sums.step_dot_change)) { + const auto batch = std::max(1, operations.batch); + while (report.iterations < parameters.max_iterations) { + const auto requested = std::min(batch, parameters.max_iterations - report.iterations); + const auto progress = operations.iterate(requested); + report.iterations += progress.iterations; + report.residual = progress.residual; + if (!std::isfinite(progress.residual)) { report.status = ContactSolveStatus::breakdown; return report; } - if (sums.residual <= parameters.tolerance) { + if (progress.residual <= parameters.tolerance) { report.status = ContactSolveStatus::converged; return report; } - // The energy is convex, so step . change is non-negative; a vanishing - // product keeps the previous step length. - if (sums.step_dot_change > 0.0 && sums.change_dot_change > 0.0) { - const auto next = (iteration % 2U) == 1U ? sums.step_dot_step / sums.step_dot_change - : sums.step_dot_change / sums.change_dot_change; - if (std::isfinite(next) && next > 0.0) { - step_length = static_cast(next); - } + if (progress.iterations == 0) { + report.status = ContactSolveStatus::breakdown; + return report; } } return report; diff --git a/cpp/core/device_types.hpp b/cpp/core/device_types.hpp index 11d56de..2900daf 100644 --- a/cpp/core/device_types.hpp +++ b/cpp/core/device_types.hpp @@ -43,6 +43,10 @@ static_assert(sizeof(float4) == 16 && alignof(float4) == 16); static_assert(sizeof(uint4) == 16 && alignof(uint4) == 16); static_assert(sizeof(RateInstruction) == 20); static_assert(sizeof(MechanicsDofs) == 32); +static_assert(sizeof(ContactRowData) == 80 && offsetof(ContactRowData, first_slot) == 64); +static_assert(sizeof(ContactBodyData) == 32); +static_assert(sizeof(ContactSolveData) == 32); +static_assert(sizeof(ContactSolveState) == 16); static_assert(sizeof(ExternalConstraint) == 48 && offsetof(ExternalConstraint, geometry) == 16); static_assert(sizeof(GridShape) == 16); static_assert(sizeof(FlowGridParameters) == 96 && offsetof(FlowGridParameters, flow_axis) == 80); diff --git a/cpp/core/simulation.cpp b/cpp/core/simulation.cpp index 2d4cceb..a50072c 100644 --- a/cpp/core/simulation.cpp +++ b/cpp/core/simulation.cpp @@ -500,6 +500,15 @@ MechanicsSolveResult Simulation::relax_cell_mechanics( return result; } +ContactSolveResult Simulation::solve_contact_system(const ContactSystem& system, + std::span initial_multipliers, + const ContactSolveParameters& parameters) { + if (!backend_->supports(BackendFeature::contact_dynamics)) { + throw std::runtime_error("selected backend does not implement contact dynamics"); + } + return backend_->solve_contact_forces(system, initial_multipliers, parameters); +} + DepthAveragedFlowResult Simulation::solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) { diff --git a/cpp/cpu/cpu_contact_dynamics.cpp b/cpp/cpu/cpu_contact_dynamics.cpp index e84c32a..024144e 100644 --- a/cpp/cpu/cpu_contact_dynamics.cpp +++ b/cpp/cpu/cpu_contact_dynamics.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -187,32 +188,37 @@ ContactSolveResult solve_contact_system_cpu(const ContactSystem& system, } return residual; }; + auto step_length = 0.0F; + std::uint32_t iteration = 0; + const auto step = [&](float length) { + for (std::size_t index = 0; index < next_multipliers.size(); ++index) { + next_multipliers[index] = std::max(0.0F, result.multipliers[index] - length * gaps[index]); + } + evaluate_gaps(system, next_multipliers, evaluation, next_gaps); + detail::ContactSolverSums sums; + for (std::size_t index = 0; index < next_multipliers.size(); ++index) { + const auto moved = static_cast(next_multipliers[index]) - result.multipliers[index]; + const auto change = static_cast(next_gaps[index]) - gaps[index]; + sums.step_dot_step += moved * moved; + sums.step_dot_change += moved * change; + sums.change_dot_change += change * change; + } + sums.residual = residual_of(next_multipliers, next_gaps); + result.multipliers.swap(next_multipliers); + gaps.swap(next_gaps); + return sums; + }; const detail::ContactSolverOperations operations{ .initialize = - [&] { + [&](float first_step_length) { + step_length = first_step_length; evaluate_gaps(system, result.multipliers, evaluation, gaps); return residual_of(result.multipliers, gaps); }, - .step = - [&](float step_length) { - for (std::size_t index = 0; index < next_multipliers.size(); ++index) { - next_multipliers[index] = - std::max(0.0F, result.multipliers[index] - step_length * gaps[index]); - } - evaluate_gaps(system, next_multipliers, evaluation, next_gaps); - detail::ContactSolverSums sums; - for (std::size_t index = 0; index < next_multipliers.size(); ++index) { - const auto step = - static_cast(next_multipliers[index]) - result.multipliers[index]; - const auto change = static_cast(next_gaps[index]) - gaps[index]; - sums.step_dot_step += step * step; - sums.step_dot_change += step * change; - sums.change_dot_change += change * change; - } - sums.residual = residual_of(next_multipliers, next_gaps); - result.multipliers.swap(next_multipliers); - gaps.swap(next_gaps); - return sums; + .iterate = + [&](std::uint32_t count) { + return detail::iterate_contact_steps(count, parameters.tolerance, step_length, + iteration, step); }, }; result.report = detail::solve_contact_system(operations, 1.0F / bound, parameters); diff --git a/cpp/cuda/cuda_backend.cu b/cpp/cuda/cuda_backend.cu index 7408caf..4bd8db9 100644 --- a/cpp/cuda/cuda_backend.cu +++ b/cpp/cuda/cuda_backend.cu @@ -15,9 +15,11 @@ #include #include +#include "core/contact_solver.hpp" #include "core/mechanics_solver.hpp" #include "core/signal_jacobi.hpp" #include "cuda_flow.cuh" +#include "kernels/contact_dynamics.cuh" #include "kernels/contacts.cuh" #include "kernels/coupled_rates.cuh" #include "kernels/growth.cuh" @@ -129,7 +131,7 @@ class CudaBackend final : public ComputeBackend { feature == BackendFeature::cell_mechanics || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || - feature == BackendFeature::resolved_flow; + feature == BackendFeature::resolved_flow || feature == BackendFeature::contact_dynamics; } void advance_growth(WorldState& state, float dt) override { @@ -804,6 +806,84 @@ class CudaBackend final : public ComputeBackend { return result; } + [[nodiscard]] ContactSolveResult solve_contact_forces( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters) override { + activate_device(); + validate_contact_system(system); + if (initial_multipliers.size() != system.rows.size()) { + throw std::invalid_argument("contact multiplier count does not match the contact rows"); + } + for (const auto multiplier : initial_multipliers) { + if (!std::isfinite(multiplier) || multiplier < 0.0F) { + throw std::invalid_argument("contact multipliers must be finite and non-negative"); + } + } + if (!std::isfinite(parameters.tolerance) || parameters.tolerance <= 0.0F) { + throw std::invalid_argument("contact solve tolerance must be finite and positive"); + } + + ContactSolveResult result; + result.multipliers.assign(initial_multipliers.begin(), initial_multipliers.end()); + if (system.rows.empty()) { + return result; + } + const auto bound = contact_system_diagonal_bound(system); + if (!std::isfinite(bound) || bound <= 0.0F) { + throw std::invalid_argument("contact system has no positive diagonal"); + } + // An incidence entry packs a row index with one bit for the row's side. + if (system.bodies.size() >= std::numeric_limits::max() || + system.rows.size() > std::numeric_limits::max() / 2) { + throw std::overflow_error("CUDA contact dynamics exceeds the uint32 index space"); + } + + const cuda::ContactSolveGpu solve{ + .dt = system.dt, + .law = static_cast(system.growth.law), + .sensitivity = system.growth.sensitivity, + .free_load = system.growth.free_load, + .stall_load = system.growth.stall_load, + .row_count = static_cast(system.rows.size()), + .body_count = static_cast(system.bodies.size()), + }; + ensure_contact_dynamics_capacity(solve.body_count, solve.row_count); + upload_contact_system(system, result.multipliers); + + // The multipliers and their gaps live in the buffer pair `current` names; + // each step writes the other pair. + std::size_t current = 0; + auto step_length = 0.0F; + std::uint32_t iteration = 0; + const auto step = [&](float length) { + const auto next = 1 - current; + cuda::launch_contact_project(contact_multipliers_[current].data(), + contact_gaps_[current].data(), contact_multipliers_[next].data(), + length, solve.row_count, stream_); + check_cuda(cudaGetLastError(), "failed to launch the CUDA contact-project kernel"); + const auto sums = evaluate_contact_step(solve, next, current, false); + current = next; + return sums; + }; + const detail::ContactSolverOperations operations{ + .initialize = + [&](float first_step_length) { + step_length = first_step_length; + return evaluate_contact_step(solve, 0, 0, true).residual; + }, + .iterate = + [&](std::uint32_t count) { + return detail::iterate_contact_steps(count, parameters.tolerance, step_length, + iteration, step); + }, + }; + result.report = detail::solve_contact_system(operations, 1.0F / bound, parameters); + copy_to_host(result.multipliers, contact_multipliers_[current], + "failed to download CUDA contact multipliers"); + check_cuda(cudaStreamSynchronize(stream_), "CUDA contact multiplier download failed"); + return result; + } + [[nodiscard]] DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) override { @@ -1467,6 +1547,116 @@ class CudaBackend final : public ComputeBackend { "CUDA mechanics residual recomputation failed"); } + void ensure_contact_dynamics_capacity(std::size_t body_count, std::size_t row_count) { + contact_bodies_.reserve(body_count, "contact bodies"); + contact_response_.reserve(body_count, "contact response"); + contact_incidence_offsets_.reserve(body_count + 1, "contact incidence offsets"); + contact_rows_.reserve(row_count, "contact rows"); + contact_incidence_entries_.reserve(row_count * 2, "contact incidence entries"); + contact_terms_.reserve(row_count, "contact step terms"); + for (std::size_t index = 0; index < 2; ++index) { + contact_multipliers_[index].reserve(row_count, "contact multipliers"); + contact_gaps_[index].reserve(row_count, "contact gaps"); + contact_reduce_[index].reserve(row_count, "contact reduction"); + } + } + + void upload_contact_system(const ContactSystem& system, + const std::vector& initial_multipliers) { + const auto body_count = system.bodies.size(); + std::vector rows(system.rows.size()); + std::vector offsets(body_count + 1, 0U); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + const auto& first = row.first_jacobian; + const auto& second = row.second_jacobian; + rows[index] = { + .first_linear = make_float4(first[0], first[1], first[2], row.first_length_lever), + .first_angular = make_float4(first[3], first[4], first[5], row.offset), + .second_linear = make_float4(second[0], second[1], second[2], row.second_length_lever), + .second_angular = make_float4(second[3], second[4], second[5], row.compliance), + .first_slot = row.first_slot, + .second_slot = row.second_slot, + .padding0 = 0, + .padding1 = 0, + }; + ++offsets[row.first_slot + 1]; + if (row.second_slot != invalid_slot) { + ++offsets[row.second_slot + 1]; + } + } + for (std::size_t body = 0; body < body_count; ++body) { + offsets[body + 1] += offsets[body]; + } + std::vector entries(offsets[body_count]); + std::vector cursors(offsets.begin(), offsets.end() - 1); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + const auto entry = static_cast(index) << 1U; + entries[cursors[row.first_slot]++] = entry; + if (row.second_slot != invalid_slot) { + entries[cursors[row.second_slot]++] = entry | 1U; + } + } + std::vector bodies(body_count); + for (std::size_t body = 0; body < body_count; ++body) { + const auto& source = system.bodies[body]; + bodies[body] = { + .axis_mobility = make_float4(source.axis.x, source.axis.y, source.axis.z, + source.translational_mobility), + .rates = make_float4(source.transverse_mobility, source.axial_mobility, + source.length_rate, 0.0F), + }; + } + copy_to_device(contact_rows_, rows, "failed to upload CUDA contact rows"); + copy_to_device(contact_bodies_, bodies, "failed to upload CUDA contact bodies"); + copy_to_device(contact_incidence_offsets_, offsets, + "failed to upload CUDA contact incidence offsets"); + copy_to_device(contact_incidence_entries_, entries, + "failed to upload CUDA contact incidence entries"); + copy_to_device(contact_multipliers_[0], initial_multipliers, + "failed to upload CUDA contact multipliers"); + check_cuda(cudaStreamSynchronize(stream_), "CUDA contact system upload failed"); + } + + // Evaluates the response to the multipliers in pair `target`, then their + // gaps and step terms against pair `previous`, and reduces the terms. + [[nodiscard]] detail::ContactSolverSums evaluate_contact_step(const cuda::ContactSolveGpu& solve, + std::size_t target, + std::size_t previous, + bool initial) { + cuda::launch_contact_respond( + contact_rows_.data(), contact_bodies_.data(), contact_multipliers_[target].data(), + contact_incidence_offsets_.data(), contact_incidence_entries_.data(), + contact_response_.data(), solve, stream_); + check_cuda(cudaGetLastError(), "failed to launch the CUDA contact-respond kernel"); + cuda::launch_contact_gaps(contact_rows_.data(), contact_response_.data(), + contact_multipliers_[target].data(), contact_gaps_[target].data(), + contact_multipliers_[previous].data(), contact_gaps_[previous].data(), + contact_terms_.data(), solve, initial, stream_); + check_cuda(cudaGetLastError(), "failed to launch the CUDA contact-gaps kernel"); + const float4* input = contact_terms_.data(); + std::size_t output = 0; + auto element_count = solve.row_count; + while (element_count > 1) { + cuda::launch_contact_reduce(input, contact_reduce_[output].data(), element_count, stream_); + check_cuda(cudaGetLastError(), "failed to launch the CUDA contact-reduce kernel"); + input = contact_reduce_[output].data(); + output = 1 - output; + element_count = (element_count + 1) / 2; + } + float4 reduced{}; + check_cuda(cudaMemcpyAsync(&reduced, input, sizeof(reduced), cudaMemcpyDeviceToHost, stream_), + "failed to download a CUDA contact reduction"); + check_cuda(cudaStreamSynchronize(stream_), "CUDA contact step failed"); + return { + .step_dot_step = reduced.x, + .step_dot_change = reduced.y, + .change_dot_change = reduced.z, + .residual = reduced.w, + }; + } + [[nodiscard]] std::vector download_mechanics_solution(std::size_t cell_count) { std::vector values(cell_count); copy_to_host(values, mechanics_solution_, "failed to download CUDA mechanics solution"); @@ -1603,6 +1793,15 @@ class CudaBackend final : public ComputeBackend { CudaBuffer mechanics_dot_terms_; CudaBuffer mechanics_reduce_a_; CudaBuffer mechanics_reduce_b_; + CudaBuffer contact_rows_; + CudaBuffer contact_bodies_; + CudaBuffer contact_response_; + CudaBuffer contact_incidence_offsets_; + CudaBuffer contact_incidence_entries_; + CudaBuffer contact_terms_; + std::array, 2> contact_multipliers_; + std::array, 2> contact_gaps_; + std::array, 2> contact_reduce_; }; } // namespace diff --git a/cpp/cuda/kernels/contact_dynamics.cu b/cpp/cuda/kernels/contact_dynamics.cu new file mode 100644 index 0000000..e9cc872 --- /dev/null +++ b/cpp/cuda/kernels/contact_dynamics.cu @@ -0,0 +1,172 @@ +#include "contact_dynamics.cuh" + +#include + +#include "core/shared_constants.hpp" + +namespace microsimulator::cuda { +namespace { + +using shared::growth_load_law_exponential; +using shared::growth_load_law_linear; + +constexpr std::uint32_t threads_per_block = 256; +constexpr std::uint32_t no_second_slot = 0xffffffffU; + +__device__ float dot3(float4 left, float4 right) { + return left.x * right.x + left.y * right.y + left.z * right.z; +} + +__device__ float contact_growth_factor(const ContactSolveGpu& solve, float load) { + if (solve.law == growth_load_law_exponential) { + return expf(-solve.sensitivity * fmaxf(load, 0.0F)); + } + if (solve.law == growth_load_law_linear) { + const float factor = 1.0F - (load - solve.free_load) / (solve.stall_load - solve.free_load); + return fminf(fmaxf(factor, 0.0F), 1.0F); + } + return 1.0F; +} + +__global__ void contact_project(const float* multipliers, const float* gaps, float* next, + float step_length, std::uint32_t row_count) { + const std::uint32_t row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= row_count) { + return; + } + next[row] = fmaxf(multipliers[row] - step_length * gaps[row], 0.0F); +} + +__global__ void contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, + const float* multipliers, const std::uint32_t* incidence_offsets, + const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, + ContactSolveGpu solve) { + const std::uint32_t body = blockIdx.x * blockDim.x + threadIdx.x; + if (body >= solve.body_count) { + return; + } + float force_x = 0.0F; + float force_y = 0.0F; + float force_z = 0.0F; + float torque_x = 0.0F; + float torque_y = 0.0F; + float torque_z = 0.0F; + float load = 0.0F; + for (std::uint32_t offset = incidence_offsets[body]; offset < incidence_offsets[body + 1]; + ++offset) { + const std::uint32_t entry = incidence_entries[offset]; + const std::uint32_t row = entry >> 1U; + const float multiplier = multipliers[row]; + const bool second = (entry & 1U) != 0U; + const float4 linear = second ? rows[row].second_linear : rows[row].first_linear; + const float4 angular = second ? rows[row].second_angular : rows[row].first_angular; + force_x += linear.x * multiplier; + force_y += linear.y * multiplier; + force_z += linear.z * multiplier; + torque_x += angular.x * multiplier; + torque_y += angular.y * multiplier; + torque_z += angular.z * multiplier; + load += linear.w * multiplier; + } + const float4 axis = bodies[body].axis_mobility; + const float translational = axis.w; + const float transverse = bodies[body].rates.x; + const float axial = bodies[body].rates.y; + const float nominal = bodies[body].rates.z; + const float along = (axial - transverse) * (axis.x * torque_x + axis.y * torque_y + + axis.z * torque_z); + const float rate = nominal > 0.0F ? nominal * contact_growth_factor(solve, load) : nominal; + response[body].linear_length = make_float4(force_x * translational, force_y * translational, + force_z * translational, rate); + response[body].rotation = + make_float4(torque_x * transverse + axis.x * along, torque_y * transverse + axis.y * along, + torque_z * transverse + axis.z * along, load); +} + +__global__ void contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, + const float* multipliers, float* gaps, + const float* previous_multipliers, const float* previous_gaps, + float4* terms, ContactSolveGpu solve, bool initial) { + const std::uint32_t row = blockIdx.x * blockDim.x + threadIdx.x; + if (row >= solve.row_count) { + return; + } + const std::uint32_t first = rows[row].first_slot; + const std::uint32_t second = rows[row].second_slot; + float rate = dot3(rows[row].first_linear, response[first].linear_length) + + dot3(rows[row].first_angular, response[first].rotation) - + rows[row].first_linear.w * response[first].linear_length.w; + if (second != no_second_slot) { + rate += dot3(rows[row].second_linear, response[second].linear_length) + + dot3(rows[row].second_angular, response[second].rotation) - + rows[row].second_linear.w * response[second].linear_length.w; + } + const float multiplier = multipliers[row]; + const float gap = + rows[row].first_angular.w + solve.dt * rate + rows[row].second_angular.w * multiplier; + gaps[row] = gap; + float residual = multiplier > 0.0F ? fabsf(gap) : fmaxf(0.0F, -gap); + if (!isfinite(gap) || !isfinite(multiplier)) { + residual = HUGE_VALF; + } + if (initial) { + terms[row] = make_float4(0.0F, 0.0F, 0.0F, residual); + return; + } + const float step = multiplier - previous_multipliers[row]; + const float change = gap - previous_gaps[row]; + terms[row] = make_float4(step * step, step * change, change * change, residual); +} + +__global__ void contact_reduce(const float4* input, float4* output, std::uint32_t element_count) { + const std::uint32_t index = blockIdx.x * blockDim.x + threadIdx.x; + const std::uint32_t first = index * 2U; + if (first >= element_count) { + return; + } + float4 value = input[first]; + if (first + 1U < element_count) { + const float4 other = input[first + 1U]; + value = make_float4(value.x + other.x, value.y + other.y, value.z + other.z, + fmaxf(value.w, other.w)); + } + output[index] = value; +} + +std::uint32_t block_count(std::uint32_t count) { + return ((count - 1) / threads_per_block) + 1; +} + +} // namespace + +void launch_contact_project(const float* multipliers, const float* gaps, float* next, + float step_length, std::uint32_t row_count, cudaStream_t stream) { + contact_project<<>>( + multipliers, gaps, next, step_length, row_count); +} + +void launch_contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, + const float* multipliers, const std::uint32_t* incidence_offsets, + const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, + ContactSolveGpu solve, cudaStream_t stream) { + contact_respond<<>>( + rows, bodies, multipliers, incidence_offsets, incidence_entries, response, solve); +} + +void launch_contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, + const float* multipliers, float* gaps, const float* previous_multipliers, + const float* previous_gaps, float4* terms, ContactSolveGpu solve, + bool initial, cudaStream_t stream) { + contact_gaps<<>>( + rows, response, multipliers, gaps, previous_multipliers, previous_gaps, terms, solve, + initial); +} + +void launch_contact_reduce(const float4* input, float4* output, std::uint32_t element_count, + cudaStream_t stream) { + const auto output_count = (element_count + 1) / 2; + contact_reduce<<>>(input, output, + element_count); +} + +} // namespace microsimulator::cuda diff --git a/cpp/cuda/kernels/contact_dynamics.cuh b/cpp/cuda/kernels/contact_dynamics.cuh new file mode 100644 index 0000000..379cfbd --- /dev/null +++ b/cpp/cuda/kernels/contact_dynamics.cuh @@ -0,0 +1,73 @@ +#pragma once + +#include + +#include + +#include "mechanics.cuh" + +namespace microsimulator::cuda { + +// One row of the contact dynamics solve. The w components carry the row's +// scalars: the first and second length levers ride on the linear parts, the +// offset on the first angular part, and the compliance on the second. +struct alignas(16) ContactRowGpu { + float4 first_linear; + float4 first_angular; + float4 second_linear; + float4 second_angular; + std::uint32_t first_slot; + std::uint32_t second_slot; + std::uint32_t padding0; + std::uint32_t padding1; +}; + +// Cell axis with the translational mobility in w, then the transverse +// mobility, axial mobility, and nominal elongation rate. +struct alignas(16) ContactBodyGpu { + float4 axis_mobility; + float4 rates; +}; + +struct ContactSolveGpu { + float dt; + std::uint32_t law; + float sensitivity; + float free_load; + float stall_load; + std::uint32_t row_count; + std::uint32_t body_count; +}; + +static_assert(sizeof(ContactRowGpu) == 80); +static_assert(sizeof(ContactBodyGpu) == 32); + +// next = max(multipliers - step_length * gaps, 0). +void launch_contact_project(const float* multipliers, const float* gaps, float* next, + float step_length, std::uint32_t row_count, cudaStream_t stream); + +// The velocity, angular velocity, elongation rate, and axial load of every +// cell under a set of multipliers. An incidence entry is a row index shifted +// left by one, with the low bit set when the cell is the row's second cell. +// The response holds the velocity and elongation rate in `linear_length` and +// the angular velocity and load in `rotation`. +void launch_contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, + const float* multipliers, const std::uint32_t* incidence_offsets, + const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, + ContactSolveGpu solve, cudaStream_t stream); + +// The gap of every row under the multipliers whose response is given, and the +// terms of the step that led to them: step . step, step . change, +// change . change, and the row's residual. The initial evaluation has no +// previous step and writes only the residual. +void launch_contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, + const float* multipliers, float* gaps, const float* previous_multipliers, + const float* previous_gaps, float4* terms, ContactSolveGpu solve, + bool initial, cudaStream_t stream); + +// Sums the first three components of neighboring elements and keeps the larger +// fourth. +void launch_contact_reduce(const float4* input, float4* output, std::uint32_t element_count, + cudaStream_t stream); + +} // namespace microsimulator::cuda diff --git a/cpp/include/microsimulator/simulation.hpp b/cpp/include/microsimulator/simulation.hpp index de717d5..9d5d18f 100644 --- a/cpp/include/microsimulator/simulation.hpp +++ b/cpp/include/microsimulator/simulation.hpp @@ -74,6 +74,11 @@ class Simulation { const MechanicsIntegrationParameters& integration_parameters = MechanicsIntegrationParameters{}, const ConstraintContactParameters& constraint_parameters = ConstraintContactParameters{}); + // Solves a contact system on the selected backend. The system stands on + // its own; it need not describe this simulation's cells. + [[nodiscard]] ContactSolveResult solve_contact_system( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters = ContactSolveParameters{}); [[nodiscard]] DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility = {}, const DepthAveragedFlowParameters& parameters = DepthAveragedFlowParameters{}); diff --git a/cpp/metal/kernels/contact_dynamics.metal b/cpp/metal/kernels/contact_dynamics.metal new file mode 100644 index 0000000..d9e1309 --- /dev/null +++ b/cpp/metal/kernels/contact_dynamics.metal @@ -0,0 +1,168 @@ +float contact_growth_factor(const ContactSolveData solve, float load) { + if (solve.law == growth_load_law_exponential) { + return exp(-solve.sensitivity * max(load, 0.0f)); + } + if (solve.law == growth_load_law_linear) { + return clamp(1.0f - (load - solve.free_load) / (solve.stall_load - solve.free_load), 0.0f, + 1.0f); + } + return 1.0f; +} + +// next = max(multipliers - step_length * gaps, 0). +kernel void contact_project(device const float* multipliers [[buffer(0)]], + device const float* gaps [[buffer(1)]], + device float* next [[buffer(2)]], + device const ContactSolveState* state [[buffer(3)]], + constant ContactSolveData& solve [[buffer(4)]], + uint row [[thread_position_in_grid]]) { + if (row >= solve.row_count || state[0].done != 0u) { + return; + } + next[row] = max(multipliers[row] - state[0].step_length * gaps[row], 0.0f); +} + +// The velocity, angular velocity, elongation rate, and axial load of every +// cell under a set of multipliers. An incidence entry is a row index shifted +// left by one, with the low bit set when the cell is the row's second cell. +// The response holds the velocity and elongation rate in `linear_length` and +// the angular velocity and load in `rotation`. +kernel void contact_respond(device const ContactRowData* rows [[buffer(0)]], + device const ContactBodyData* bodies [[buffer(1)]], + device const float* multipliers [[buffer(2)]], + device const uint* incidence_offsets [[buffer(3)]], + device const uint* incidence_entries [[buffer(4)]], + device MechanicsDofs* response [[buffer(5)]], + device const ContactSolveState* state [[buffer(6)]], + constant ContactSolveData& solve [[buffer(7)]], + constant uint& initial [[buffer(8)]], + uint body [[thread_position_in_grid]]) { + if (body >= solve.body_count || (initial == 0u && state[0].done != 0u)) { + return; + } + float3 force = 0.0f; + float3 torque = 0.0f; + float load = 0.0f; + for (uint offset = incidence_offsets[body]; offset < incidence_offsets[body + 1]; ++offset) { + uint entry = incidence_entries[offset]; + uint row = entry >> 1; + float multiplier = multipliers[row]; + bool second = (entry & 1u) != 0u; + float4 linear = second ? rows[row].second_linear : rows[row].first_linear; + float4 angular = second ? rows[row].second_angular : rows[row].first_angular; + force += linear.xyz * multiplier; + torque += angular.xyz * multiplier; + load += linear.w * multiplier; + } + float3 axis = bodies[body].axis_mobility.xyz; + float transverse = bodies[body].rates.x; + float axial = bodies[body].rates.y; + float nominal = bodies[body].rates.z; + float3 velocity = force * bodies[body].axis_mobility.w; + float3 angular_velocity = + torque * transverse + axis * ((axial - transverse) * dot(axis, torque)); + float rate = nominal > 0.0f ? nominal * contact_growth_factor(solve, load) : nominal; + response[body].linear_length = float4(velocity, rate); + response[body].rotation = float4(angular_velocity, load); +} + +// The gap of every row under the multipliers whose response is given, and the +// terms of the step that led to them: step . step, step . change, +// change . change, and the row's residual. The initial evaluation has no +// previous step and writes only the residual. +kernel void contact_gaps(device const ContactRowData* rows [[buffer(0)]], + device const MechanicsDofs* response [[buffer(1)]], + device const float* multipliers [[buffer(2)]], + device float* gaps [[buffer(3)]], + device const float* previous_multipliers [[buffer(4)]], + device const float* previous_gaps [[buffer(5)]], + device float4* terms [[buffer(6)]], + device const ContactSolveState* state [[buffer(7)]], + constant ContactSolveData& solve [[buffer(8)]], + constant uint& initial [[buffer(9)]], + uint row [[thread_position_in_grid]]) { + if (row >= solve.row_count || (initial == 0u && state[0].done != 0u)) { + return; + } + uint first = rows[row].first_slot; + uint second = rows[row].second_slot; + float rate = dot(rows[row].first_linear.xyz, response[first].linear_length.xyz) + + dot(rows[row].first_angular.xyz, response[first].rotation.xyz) - + rows[row].first_linear.w * response[first].linear_length.w; + if (second != 0xffffffffu) { + rate += dot(rows[row].second_linear.xyz, response[second].linear_length.xyz) + + dot(rows[row].second_angular.xyz, response[second].rotation.xyz) - + rows[row].second_linear.w * response[second].linear_length.w; + } + float multiplier = multipliers[row]; + float gap = rows[row].first_angular.w + solve.dt * rate + rows[row].second_angular.w * multiplier; + gaps[row] = gap; + float residual = multiplier > 0.0f ? fabs(gap) : max(0.0f, -gap); + if (!isfinite(gap) || !isfinite(multiplier)) { + residual = INFINITY; + } + if (initial != 0u) { + terms[row] = float4(0.0f, 0.0f, 0.0f, residual); + return; + } + float step = multiplier - previous_multipliers[row]; + float change = gap - previous_gaps[row]; + terms[row] = float4(step * step, step * change, change * change, residual); +} + +// Sums the first three components of neighboring elements and keeps the larger +// fourth. +kernel void contact_reduce(device const float4* input [[buffer(0)]], + device float4* output [[buffer(1)]], + constant uint& element_count [[buffer(2)]], + uint index [[thread_position_in_grid]]) { + uint first = index * 2; + if (first >= element_count) { + return; + } + float4 value = input[first]; + if (first + 1 < element_count) { + float4 other = input[first + 1]; + value = float4(value.xyz + other.xyz, max(value.w, other.w)); + } + output[index] = value; +} + +// Records the step that the reduced terms describe: counts it, stops the +// iteration when its residual is within the tolerance or not finite, and +// otherwise sets the next Barzilai-Borwein step length. The two lengths +// alternate, and a vanishing step . change keeps the current length. +kernel void contact_advance(device const float4* reduced [[buffer(0)]], + device ContactSolveState* state [[buffer(1)]], + constant ContactSolveData& solve [[buffer(2)]], + constant uint& initial [[buffer(3)]], + constant float& first_step_length [[buffer(4)]], + uint index [[thread_position_in_grid]]) { + if (index != 0u) { + return; + } + float4 sums = reduced[0]; + bool stop = !(sums.w > solve.tolerance) || isinf(sums.w); + if (initial != 0u) { + state[0].step_length = first_step_length; + state[0].residual = sums.w; + state[0].iterations = 0u; + state[0].done = stop ? 1u : 0u; + return; + } + if (state[0].done != 0u) { + return; + } + state[0].iterations += 1u; + state[0].residual = sums.w; + if (stop) { + state[0].done = 1u; + return; + } + if (sums.y > 0.0f && sums.z > 0.0f) { + float next = (state[0].iterations & 1u) != 0u ? sums.x / sums.y : sums.y / sums.z; + if (isfinite(next) && next > 0.0f) { + state[0].step_length = next; + } + } +} diff --git a/cpp/metal/metal_backend.mm b/cpp/metal/metal_backend.mm index ee04908..ef98db4 100644 --- a/cpp/metal/metal_backend.mm +++ b/cpp/metal/metal_backend.mm @@ -16,11 +16,13 @@ #include #include +#include "core/contact_solver.hpp" #include "core/device_types.hpp" #include "core/mechanics_solver.hpp" #include "core/signal_jacobi.hpp" #include "metal_flow.hpp" #include "microsimulator/backend.hpp" +#include "microsimulator/metal/contact_dynamics_source.hpp" #include "microsimulator/metal/contacts_source.hpp" #include "microsimulator/metal/coupled_rates_source.hpp" #include "microsimulator/metal/growth_source.hpp" @@ -36,6 +38,10 @@ using MetalFloat4 = device::float4; using MetalUInt4 = device::uint4; using MetalDofs = device::MechanicsDofs; +using MetalContactRow = device::ContactRowData; +using MetalContactBody = device::ContactBodyData; +using MetalContactSolve = device::ContactSolveData; +using MetalContactState = device::ContactSolveState; using MetalExternalConstraint = device::ExternalConstraint; using MetalRateInstruction = device::RateInstruction; using MetalGridShape = device::GridShape; @@ -219,6 +225,22 @@ explicit MetalBackend(std::uint32_t device_index) : device_index_(device_index) mechanics_reduce_pipeline_ = compile_pipeline(device_, mechanics_library, @"reduce_sum_pairs", "failed to create the Metal mechanics-reduction pipeline"); + const auto contact_dynamics_library = compile_library( + device_, metal::contact_dynamics_source, "failed to compile Metal contact dynamics"); + contact_project_pipeline_ = + compile_pipeline(device_, contact_dynamics_library, @"contact_project", + "failed to create the Metal contact-project pipeline"); + contact_respond_pipeline_ = + compile_pipeline(device_, contact_dynamics_library, @"contact_respond", + "failed to create the Metal contact-respond pipeline"); + contact_gaps_pipeline_ = compile_pipeline(device_, contact_dynamics_library, @"contact_gaps", + "failed to create the Metal contact-gaps pipeline"); + contact_reduce_pipeline_ = + compile_pipeline(device_, contact_dynamics_library, @"contact_reduce", + "failed to create the Metal contact-reduce pipeline"); + contact_advance_pipeline_ = + compile_pipeline(device_, contact_dynamics_library, @"contact_advance", + "failed to create the Metal contact-advance pipeline"); flow_solver_ = std::make_unique(device_index_); } } @@ -242,7 +264,7 @@ explicit MetalBackend(std::uint32_t device_index) : device_index_(device_index) feature == BackendFeature::external_constraints || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || - feature == BackendFeature::resolved_flow; + feature == BackendFeature::resolved_flow || feature == BackendFeature::contact_dynamics; } void advance_growth(WorldState& state, float dt) override { @@ -875,6 +897,74 @@ SignalSolveReport advance_coupled(WorldState& state, SignalGrid& grid, return result; } + [[nodiscard]] ContactSolveResult solve_contact_forces( + const ContactSystem& system, std::span initial_multipliers, + const ContactSolveParameters& parameters) override { + validate_contact_system(system); + if (initial_multipliers.size() != system.rows.size()) { + throw std::invalid_argument("contact multiplier count does not match the contact rows"); + } + for (const auto multiplier : initial_multipliers) { + if (!std::isfinite(multiplier) || multiplier < 0.0F) { + throw std::invalid_argument("contact multipliers must be finite and non-negative"); + } + } + if (!std::isfinite(parameters.tolerance) || parameters.tolerance <= 0.0F) { + throw std::invalid_argument("contact solve tolerance must be finite and positive"); + } + + ContactSolveResult result; + result.multipliers.assign(initial_multipliers.begin(), initial_multipliers.end()); + if (system.rows.empty()) { + return result; + } + const auto bound = contact_system_diagonal_bound(system); + if (!std::isfinite(bound) || bound <= 0.0F) { + throw std::invalid_argument("contact system has no positive diagonal"); + } + // An incidence entry packs a row index with one bit for the row's side. + if (system.bodies.size() >= std::numeric_limits::max() || + system.rows.size() > std::numeric_limits::max() / 2) { + throw std::overflow_error("Metal contact dynamics exceeds the uint32 index space"); + } + + const auto row_count = static_cast(system.rows.size()); + const auto body_count = static_cast(system.bodies.size()); + ensure_contact_dynamics_capacity(body_count, row_count); + upload_contact_system(system, initial_multipliers); + const MetalContactSolve solve{ + .dt = system.dt, + .tolerance = parameters.tolerance, + .law = static_cast(system.growth.law), + .sensitivity = system.growth.sensitivity, + .free_load = system.growth.free_load, + .stall_load = system.growth.stall_load, + .row_count = row_count, + .body_count = body_count, + }; + + // The multipliers and their gaps live in the buffer pair `current` names; + // each step writes the other pair. + std::size_t current = 0; + const detail::ContactSolverOperations operations{ + .initialize = + [&](float first_step_length) { + return initialize_contact_solve(solve, first_step_length); + }, + .iterate = + [&](std::uint32_t count) { + const auto progress = iterate_contact_solve(solve, current, count); + current = (current + progress.iterations) % 2; + return progress; + }, + .batch = contact_solve_batch, + }; + result.report = detail::solve_contact_system(operations, 1.0F / bound, parameters); + const auto* multipliers = static_cast(contact_multipliers_[current].contents); + result.multipliers.assign(multipliers, multipliers + row_count); + return result; + } + [[nodiscard]] DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) override { @@ -2102,6 +2192,210 @@ void update_search_direction(std::uint32_t cell_count, float beta) { } } + // Projected-gradient steps encoded in one command buffer. The device stops + // itself at convergence, so the steps left in a batch do nothing. + static constexpr std::uint32_t contact_solve_batch = 32; + + void ensure_contact_dynamics_capacity(std::size_t body_count, std::size_t row_count) { + if (body_count > contact_body_capacity_) { + const auto capacity = std::bit_ceil(body_count); + contact_bodies_ = + allocate_shared_buffer(device_, capacity * sizeof(MetalContactBody), "contact bodies"); + contact_response_ = + allocate_shared_buffer(device_, capacity * sizeof(MetalDofs), "contact response"); + contact_incidence_offsets_ = allocate_shared_buffer( + device_, (capacity + 1) * sizeof(std::uint32_t), "contact incidence offsets"); + contact_body_capacity_ = capacity; + } + if (row_count > contact_row_capacity_) { + const auto capacity = std::bit_ceil(row_count); + contact_rows_ = + allocate_shared_buffer(device_, capacity * sizeof(MetalContactRow), "contact rows"); + contact_incidence_entries_ = allocate_shared_buffer( + device_, capacity * 2 * sizeof(std::uint32_t), "contact incidence entries"); + for (std::size_t index = 0; index < 2; ++index) { + contact_multipliers_[index] = + allocate_shared_buffer(device_, capacity * sizeof(float), "contact multipliers"); + contact_gaps_[index] = + allocate_shared_buffer(device_, capacity * sizeof(float), "contact gaps"); + contact_reduce_[index] = + allocate_shared_buffer(device_, capacity * sizeof(MetalFloat4), "contact reduction"); + } + contact_terms_ = + allocate_shared_buffer(device_, capacity * sizeof(MetalFloat4), "contact step terms"); + contact_row_capacity_ = capacity; + } + if (contact_state_ == nil) { + contact_state_ = + allocate_shared_buffer(device_, sizeof(MetalContactState), "contact solve state"); + } + } + + void upload_contact_system(const ContactSystem& system, + std::span initial_multipliers) { + auto* rows = static_cast(contact_rows_.contents); + auto* offsets = static_cast(contact_incidence_offsets_.contents); + auto* entries = static_cast(contact_incidence_entries_.contents); + const auto body_count = system.bodies.size(); + std::fill_n(offsets, body_count + 1, 0U); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + const auto& first = row.first_jacobian; + const auto& second = row.second_jacobian; + rows[index] = { + .first_linear = {first[0], first[1], first[2], row.first_length_lever}, + .first_angular = {first[3], first[4], first[5], row.offset}, + .second_linear = {second[0], second[1], second[2], row.second_length_lever}, + .second_angular = {second[3], second[4], second[5], row.compliance}, + .first_slot = row.first_slot, + .second_slot = row.second_slot, + .padding0 = 0, + .padding1 = 0, + }; + ++offsets[row.first_slot + 1]; + if (row.second_slot != invalid_slot) { + ++offsets[row.second_slot + 1]; + } + } + for (std::size_t body = 0; body < body_count; ++body) { + offsets[body + 1] += offsets[body]; + } + std::vector cursors(offsets, offsets + body_count); + for (std::size_t index = 0; index < system.rows.size(); ++index) { + const auto& row = system.rows[index]; + const auto entry = static_cast(index) << 1U; + entries[cursors[row.first_slot]++] = entry; + if (row.second_slot != invalid_slot) { + entries[cursors[row.second_slot]++] = entry | 1U; + } + } + + auto* bodies = static_cast(contact_bodies_.contents); + for (std::size_t body = 0; body < body_count; ++body) { + const auto& source = system.bodies[body]; + bodies[body] = { + .axis_mobility = {source.axis.x, source.axis.y, source.axis.z, + source.translational_mobility}, + .rates = {source.transverse_mobility, source.axial_mobility, source.length_rate, 0.0F}, + }; + } + std::memcpy(contact_multipliers_[0].contents, initial_multipliers.data(), + initial_multipliers.size() * sizeof(float)); + } + + // Encodes the response to the multipliers in pair `target`, then their gaps + // and step terms against pair `previous`, and reduces the terms. Returns the + // buffer whose first element holds the reduced terms. + id encode_contact_evaluation(id encoder, + const MetalContactSolve& solve, std::size_t target, + std::size_t previous, std::uint32_t initial) { + [encoder setComputePipelineState:contact_respond_pipeline_]; + [encoder setBuffer:contact_rows_ offset:0 atIndex:0]; + [encoder setBuffer:contact_bodies_ offset:0 atIndex:1]; + [encoder setBuffer:contact_multipliers_[target] offset:0 atIndex:2]; + [encoder setBuffer:contact_incidence_offsets_ offset:0 atIndex:3]; + [encoder setBuffer:contact_incidence_entries_ offset:0 atIndex:4]; + [encoder setBuffer:contact_response_ offset:0 atIndex:5]; + [encoder setBuffer:contact_state_ offset:0 atIndex:6]; + [encoder setBytes:&solve length:sizeof(solve) atIndex:7]; + [encoder setBytes:&initial length:sizeof(initial) atIndex:8]; + dispatch_1d(encoder, contact_respond_pipeline_, solve.body_count); + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; + + [encoder setComputePipelineState:contact_gaps_pipeline_]; + [encoder setBuffer:contact_rows_ offset:0 atIndex:0]; + [encoder setBuffer:contact_response_ offset:0 atIndex:1]; + [encoder setBuffer:contact_multipliers_[target] offset:0 atIndex:2]; + [encoder setBuffer:contact_gaps_[target] offset:0 atIndex:3]; + [encoder setBuffer:contact_multipliers_[previous] offset:0 atIndex:4]; + [encoder setBuffer:contact_gaps_[previous] offset:0 atIndex:5]; + [encoder setBuffer:contact_terms_ offset:0 atIndex:6]; + [encoder setBuffer:contact_state_ offset:0 atIndex:7]; + [encoder setBytes:&solve length:sizeof(solve) atIndex:8]; + [encoder setBytes:&initial length:sizeof(initial) atIndex:9]; + dispatch_1d(encoder, contact_gaps_pipeline_, solve.row_count); + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; + + id input = contact_terms_; + std::size_t output = 0; + auto element_count = solve.row_count; + while (element_count > 1) { + const auto output_count = (element_count + 1) / 2; + [encoder setComputePipelineState:contact_reduce_pipeline_]; + [encoder setBuffer:input offset:0 atIndex:0]; + [encoder setBuffer:contact_reduce_[output] offset:0 atIndex:1]; + [encoder setBytes:&element_count length:sizeof(element_count) atIndex:2]; + dispatch_1d(encoder, contact_reduce_pipeline_, output_count); + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; + input = contact_reduce_[output]; + output = 1 - output; + element_count = output_count; + } + return input; + } + + void encode_contact_advance(id encoder, id reduced, + const MetalContactSolve& solve, std::uint32_t initial, + float first_step_length) { + [encoder setComputePipelineState:contact_advance_pipeline_]; + [encoder setBuffer:reduced offset:0 atIndex:0]; + [encoder setBuffer:contact_state_ offset:0 atIndex:1]; + [encoder setBytes:&solve length:sizeof(solve) atIndex:2]; + [encoder setBytes:&initial length:sizeof(initial) atIndex:3]; + [encoder setBytes:&first_step_length length:sizeof(first_step_length) atIndex:4]; + dispatch_1d(encoder, contact_advance_pipeline_, 1); + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; + } + + [[nodiscard]] float initialize_contact_solve(const MetalContactSolve& solve, + float first_step_length) { + @autoreleasepool { + id command_buffer = [queue_ commandBuffer]; + id encoder = [command_buffer computeCommandEncoder]; + if (command_buffer == nil || encoder == nil) { + throw std::runtime_error("failed to create a Metal contact initialization command"); + } + const auto reduced = encode_contact_evaluation(encoder, solve, 0, 0, 1); + encode_contact_advance(encoder, reduced, solve, 1, first_step_length); + [encoder endEncoding]; + wait_for_command(command_buffer, "Metal contact solve initialization failed"); + return static_cast(contact_state_.contents)->residual; + } + } + + [[nodiscard]] detail::ContactSolverProgress iterate_contact_solve(const MetalContactSolve& solve, + std::size_t current, + std::uint32_t count) { + @autoreleasepool { + const auto before = + static_cast(contact_state_.contents)->iterations; + id command_buffer = [queue_ commandBuffer]; + id encoder = [command_buffer computeCommandEncoder]; + if (command_buffer == nil || encoder == nil) { + throw std::runtime_error("failed to create a Metal contact iteration command"); + } + for (std::uint32_t index = 0; index < count; ++index) { + const auto next = 1 - current; + [encoder setComputePipelineState:contact_project_pipeline_]; + [encoder setBuffer:contact_multipliers_[current] offset:0 atIndex:0]; + [encoder setBuffer:contact_gaps_[current] offset:0 atIndex:1]; + [encoder setBuffer:contact_multipliers_[next] offset:0 atIndex:2]; + [encoder setBuffer:contact_state_ offset:0 atIndex:3]; + [encoder setBytes:&solve length:sizeof(solve) atIndex:4]; + dispatch_1d(encoder, contact_project_pipeline_, solve.row_count); + [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; + + const auto reduced = encode_contact_evaluation(encoder, solve, next, current, 0); + encode_contact_advance(encoder, reduced, solve, 0, 0.0F); + current = next; + } + [encoder endEncoding]; + wait_for_command(command_buffer, "Metal contact solve iteration failed"); + const auto* state = static_cast(contact_state_.contents); + return {.iterations = state->iterations - before, .residual = state->residual}; + } + } + [[nodiscard]] std::vector download_mechanics_solution( std::size_t cell_count) const { const auto* values = static_cast(mechanics_solution_.contents); @@ -2150,6 +2444,11 @@ void update_search_direction(std::uint32_t cell_count, float beta) { id mechanics_subtract_pipeline_{nil}; id mechanics_dot_pipeline_{nil}; id mechanics_reduce_pipeline_{nil}; + id contact_project_pipeline_{nil}; + id contact_respond_pipeline_{nil}; + id contact_gaps_pipeline_{nil}; + id contact_reduce_pipeline_{nil}; + id contact_advance_pipeline_{nil}; std::unique_ptr flow_solver_; id lengths_{nil}; @@ -2283,6 +2582,18 @@ void update_search_direction(std::uint32_t cell_count, float beta) { id mechanics_reduce_b_{nil}; std::size_t mechanics_cell_capacity_{0}; std::size_t mechanics_contact_capacity_{0}; + id contact_rows_{nil}; + id contact_bodies_{nil}; + id contact_response_{nil}; + id contact_incidence_offsets_{nil}; + id contact_incidence_entries_{nil}; + std::array, 2> contact_multipliers_{}; + std::array, 2> contact_gaps_{}; + std::array, 2> contact_reduce_{}; + id contact_terms_{nil}; + id contact_state_{nil}; + std::size_t contact_body_capacity_{0}; + std::size_t contact_row_capacity_{0}; }; } // namespace diff --git a/cpp/shared/constants.def b/cpp/shared/constants.def index 0137011..c7eb9a3 100644 --- a/cpp/shared/constants.def +++ b/cpp/shared/constants.def @@ -10,5 +10,9 @@ MICROSIMULATOR_SHARED_FLOAT(float_epsilon, 1.1920928955078125e-7) MICROSIMULATOR_SHARED_UINT(segment_minimization_iterations, 40) // Unknowns per cell in the mechanics system: translation, rotation, length. MICROSIMULATOR_SHARED_UINT(mechanics_degrees_of_freedom, 7) +// Growth load laws of the contact dynamics solve, in the order of GrowthLoadLaw. +MICROSIMULATOR_SHARED_UINT(growth_load_law_none, 0) +MICROSIMULATOR_SHARED_UINT(growth_load_law_exponential, 1) +MICROSIMULATOR_SHARED_UINT(growth_load_law_linear, 2) // Elements each device thread group reduces to one partial dot product. MICROSIMULATOR_SHARED_UINT(flow_reduction_width, 64) diff --git a/cpp/shared/device_types.h b/cpp/shared/device_types.h index 84355c6..c6c7787 100644 --- a/cpp/shared/device_types.h +++ b/cpp/shared/device_types.h @@ -19,6 +19,50 @@ struct MechanicsDofs { float4 rotation; }; +// One row of the contact dynamics solve. The w components carry the row's +// scalars. +struct ContactRowData { + // Force on the first cell per unit multiplier; w is its length lever. + float4 first_linear; + // Torque on the first cell per unit multiplier; w is the row offset. + float4 first_angular; + // Force on the second cell per unit multiplier; w is its length lever. + float4 second_linear; + // Torque on the second cell per unit multiplier; w is the row compliance. + float4 second_angular; + uint first_slot; + uint second_slot; + uint padding0; + uint padding1; +}; + +struct ContactBodyData { + // Cell axis; w is the translational mobility. + float4 axis_mobility; + // Transverse mobility, axial mobility, and nominal elongation rate. + float4 rates; +}; + +struct ContactSolveData { + float dt; + float tolerance; + uint law; + float sensitivity; + float free_load; + float stall_load; + uint row_count; + uint body_count; +}; + +// Progress of the projected-gradient iteration, kept on the device so that a +// batch of steps runs without returning to the host. +struct ContactSolveState { + float step_length; + float residual; + uint iterations; + uint done; +}; + struct ExternalConstraint { ulong id; uint kind; diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py index 8f829a3..6490c52 100644 --- a/python/tests/test_contact_dynamics.py +++ b/python/tests/test_contact_dynamics.py @@ -239,7 +239,8 @@ def test_cell_between_walls_stalls_and_stops_consuming(backend: BackendKind) -> @pytest.mark.parametrize("backend", BACKENDS) def test_closed_chamber_fills_and_holds(backend: BackendKind) -> None: - controller = _chamber(backend, ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0)) + config = ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0) + controller = _chamber(backend, config) for _ in range(300): controller.step(0.05) simulation = controller.simulation diff --git a/tests/conformance/contact_dynamics_conformance_test.cpp b/tests/conformance/contact_dynamics_conformance_test.cpp new file mode 100644 index 0000000..340c99b --- /dev/null +++ b/tests/conformance/contact_dynamics_conformance_test.cpp @@ -0,0 +1,305 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "backend_devices.hpp" +#include "microsimulator/simulation.hpp" + +namespace { + +using microsimulator::BackendKind; +using microsimulator::ContactBody; +using microsimulator::ContactRow; +using microsimulator::ContactSolveStatus; +using microsimulator::ContactSystem; +using microsimulator::GrowthLoadLaw; + +void require_close(float actual, float expected, float tolerance, std::string_view scenario, + std::size_t index, std::string_view field) { + if (std::abs(actual - expected) <= tolerance) { + return; + } + std::cerr << scenario << ' ' << field << ' ' << index << ": actual=" << actual + << " expected=" << expected << '\n'; + std::abort(); +} + +// A chain of `count` cells along x, each pressed into the next, with the +// first held against a wall, a fixed cell at the far end, and a cross +// contact that couples rotation. +struct Fixture { + std::vector bodies; + std::vector rows; + + [[nodiscard]] ContactSystem system(GrowthLoadLaw law) const { + ContactSystem result{ + .rows = rows, + .bodies = bodies, + .dt = 0.05F, + }; + result.growth.law = law; + result.growth.sensitivity = 0.3F; + result.growth.free_load = 0.2F; + result.growth.stall_load = 3.0F; + return result; + } +}; + +Fixture make_chain(std::size_t count) { + Fixture fixture; + for (std::size_t index = 0; index < count; ++index) { + const auto angle = 0.1F * static_cast(index % 5); + ContactBody body{ + .axis = {std::cos(angle), std::sin(angle), 0.0F}, + .translational_mobility = 1.0F / (3.0F + 0.1F * static_cast(index % 7)), + .transverse_mobility = 0.9F, + .axial_mobility = 20.0F, + .length_rate = index % 4 == 3 ? -0.2F : 0.8F + 0.05F * static_cast(index % 3), + }; + if (index + 1 == count) { + body.translational_mobility = 0.0F; + body.transverse_mobility = 0.0F; + body.axial_mobility = 0.0F; + } + fixture.bodies.push_back(body); + } + // The wall on the first cell. + ContactRow wall; + wall.first_slot = 0; + wall.first_jacobian = {1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 0.1F}; + wall.first_length_lever = 0.5F; + wall.offset = -0.004F; + wall.compliance = 1.0e-4F; + fixture.rows.push_back(wall); + for (std::size_t index = 0; index + 1 < count; ++index) { + const auto tilt = 0.2F * static_cast(index % 3) - 0.2F; + const auto normal_x = std::cos(tilt); + const auto normal_y = std::sin(tilt); + ContactRow row; + row.first_slot = static_cast(index); + row.second_slot = static_cast(index + 1); + row.first_jacobian = {-normal_x, -normal_y, 0.0F, 0.0F, 0.0F, -1.5F * normal_y}; + row.second_jacobian = {normal_x, normal_y, 0.0F, 0.0F, 0.0F, -1.5F * normal_y}; + row.first_length_lever = 0.5F * normal_x; + row.second_length_lever = 0.5F * normal_x; + row.offset = index % 3 == 0 ? -0.01F : 0.002F * static_cast(index % 4); + row.compliance = index % 6 == 0 ? 2.5e-5F : 1.0e-4F; + fixture.rows.push_back(row); + } + // A row far from closing, which stays inactive. + if (count > 2) { + ContactRow distant; + distant.first_slot = 0; + distant.second_slot = static_cast(count - 2); + distant.first_jacobian = {0.0F, -1.0F, 0.0F, 0.0F, 0.0F, 0.0F}; + distant.second_jacobian = {0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F}; + distant.offset = 5.0F; + distant.compliance = 1.0e-4F; + fixture.rows.push_back(distant); + } + return fixture; +} + +void run_solve_matches_reference(microsimulator::Simulation& backend, std::size_t count, + GrowthLoadLaw law, std::string_view scenario) { + const auto fixture = make_chain(count); + const auto system = fixture.system(law); + const std::vector zero(fixture.rows.size(), 0.0F); + const microsimulator::ContactSolveParameters parameters{.tolerance = 2.0e-6F, + .max_iterations = 200000}; + const auto expected = microsimulator::solve_contact_system_cpu(system, zero, parameters); + const auto actual = backend.solve_contact_system(system, zero, parameters); + assert(expected.report.status == ContactSolveStatus::converged); + assert(actual.report.status == ContactSolveStatus::converged); + assert(actual.report.residual <= parameters.tolerance); + assert(actual.multipliers.size() == expected.multipliers.size()); + + // The solution is unique, so both solves reach the same response. + const auto gaps = microsimulator::evaluate_contact_gaps(system, actual.multipliers); + for (std::size_t index = 0; index < gaps.size(); ++index) { + assert(actual.multipliers[index] >= 0.0F); + assert(gaps[index] >= -2.0F * parameters.tolerance); + if (actual.multipliers[index] > 0.0F) { + assert(std::abs(gaps[index]) <= 2.0F * parameters.tolerance); + } + } + const auto actual_response = + microsimulator::evaluate_contact_response(system, actual.multipliers); + const auto expected_response = + microsimulator::evaluate_contact_response(system, expected.multipliers); + for (std::size_t body = 0; body < fixture.bodies.size(); ++body) { + for (std::size_t component = 0; component < 6; ++component) { + require_close(actual_response.velocities[body][component], + expected_response.velocities[body][component], 2.0e-3F, scenario, body, + "velocity"); + } + require_close(actual_response.length_rates[body], expected_response.length_rates[body], + 2.0e-3F, scenario, body, "length rate"); + require_close(actual_response.loads[body], expected_response.loads[body], + 2.0e-2F * (1.0F + expected_response.loads[body]), scenario, body, "load"); + } + + // A solve from the solution has nothing left to do. + const auto again = backend.solve_contact_system(system, actual.multipliers, parameters); + assert(again.report.status == ContactSolveStatus::converged); + assert(again.report.iterations == 0); + for (std::size_t index = 0; index < again.multipliers.size(); ++index) { + assert(again.multipliers[index] == actual.multipliers[index]); + } +} + +void run_empty_and_limited_solves(microsimulator::Simulation& backend) { + const auto fixture = make_chain(6); + auto system = fixture.system(GrowthLoadLaw::linear); + const std::vector zero(fixture.rows.size(), 0.0F); + + // The iteration limit is reported with the multipliers reached so far. + const microsimulator::ContactSolveParameters limited{.tolerance = 1.0e-7F, .max_iterations = 3}; + const auto stopped = backend.solve_contact_system(system, zero, limited); + assert(stopped.report.status == ContactSolveStatus::iteration_limit); + assert(stopped.report.iterations == 3); + assert(stopped.report.residual > limited.tolerance); + assert(std::ranges::any_of(stopped.multipliers, [](float value) { return value > 0.0F; })); + + system.rows = {}; + const auto empty = backend.solve_contact_system(system, {}, limited); + assert(empty.report.status == ContactSolveStatus::converged); + assert(empty.multipliers.empty()); +} + +float footprint(const microsimulator::Simulation& simulation) { + auto area = 0.0F; + for (const auto& cell : simulation.cells()) { + area += std::numbers::pi_v * cell.radius * cell.radius + + 2.0F * cell.radius * cell.length; + } + return area; +} + +// Divides cells at `division_length`, turning daughters by fixed alternating +// angles so that every backend sees the same plan. +void divide_long_cells(microsimulator::Simulation& simulation, float division_length, + std::uint32_t& counter) { + for (const auto& cell : simulation.cells()) { + if (cell.length < division_length) { + continue; + } + const auto [first, second] = simulation.divide_equal(cell.id); + for (const auto id : {first, second}) { + const auto daughter = simulation.cell(id); + const auto angle = 0.004F * static_cast(counter++ % 7U) - 0.012F; + simulation.set_cell_geometry( + id, daughter.position, + {daughter.direction.x * std::cos(angle) - daughter.direction.y * std::sin(angle), + daughter.direction.x * std::sin(angle) + daughter.direction.y * std::cos(angle), + daughter.direction.z}, + daughter.length); + } + } +} + +void run_closed_chamber(BackendKind backend, std::uint32_t device_index) { + microsimulator::Simulation simulation(backend, 0, 0, device_index); + microsimulator::BoxConstraintInit chamber; + chamber.half_extents = {2.0F, 2.0F, 0.6F}; + chamber.allowed_region = microsimulator::ConstraintRegion::inside; + simulation.add_box_constraint(chamber); + microsimulator::CellInit founder; + founder.length = 1.0F; + founder.radius = 0.4F; + simulation.add_cell(founder); + + microsimulator::ContactDynamicsParameters parameters; + parameters.growth.law = GrowthLoadLaw::linear; + parameters.growth.stall_load = 2.0F; + std::uint32_t counter = 0; + const auto run = [&](int steps) { + for (int step = 0; step < steps; ++step) { + divide_long_cells(simulation, 2.0F, counter); + std::ignore = simulation.step(0.05F, parameters); + } + }; + run(300); + const auto filled_count = simulation.cell_count(); + const auto filled_footprint = footprint(simulation); + run(200); + assert(simulation.cell_count() == filled_count); + assert(std::abs(footprint(simulation) - filled_footprint) < 0.02F); + const auto cover = footprint(simulation) / 16.0F; + assert(cover > 0.6F && cover < 1.0F); + const auto contacts = simulation.find_cell_contacts(); + for (const auto& contact : contacts.contacts()) { + assert(contact.signed_separation > -0.01F); + } + for (const auto& cell : simulation.cells()) { + assert(std::abs(cell.position.x) <= 2.0F && std::abs(cell.position.y) <= 2.0F); + assert(std::abs(cell.position.z) < 1.0e-3F); + } +} + +void run_free_colony(BackendKind backend, std::uint32_t device_index) { + microsimulator::Simulation simulation(backend, 256, 0, device_index); + microsimulator::Simulation reference(BackendKind::cpu, 256); + microsimulator::CellInit founder; + founder.length = 2.0F; + simulation.add_cell(founder); + reference.add_cell(founder); + + const microsimulator::ContactDynamicsParameters parameters; + std::uint32_t counter = 0; + std::uint32_t reference_counter = 0; + auto worst = 0.0F; + for (int step = 0; step < 100; ++step) { + divide_long_cells(simulation, 4.0F, counter); + divide_long_cells(reference, 4.0F, reference_counter); + const auto result = simulation.step(0.05F, parameters); + reference.step(0.05F); + worst = std::max(worst, result.report.max_overlap); + } + // Growth without a load response is the growth of cells that never touch. + assert(simulation.cell_count() == reference.cell_count()); + assert(simulation.cell_count() >= 16); + auto length = 0.0F; + auto reference_length = 0.0F; + for (const auto& cell : simulation.cells()) { + length += cell.length; + assert(std::abs(cell.position.z) < 1.0e-3F); + } + for (const auto& cell : reference.cells()) { + reference_length += cell.length; + } + assert(std::abs(length - reference_length) <= 1.0e-3F * reference_length); + assert(worst < 0.01F); +} + +} // namespace + +int main() { + microsimulator::test::for_each_backend_device( + [](BackendKind backend, std::uint32_t device_index) { + microsimulator::Simulation solver_host(backend, 0, 0, device_index); + if (!solver_host.supports(microsimulator::BackendFeature::contact_dynamics)) { + return; + } + auto* solver = &solver_host; + run_solve_matches_reference(*solver, 2, GrowthLoadLaw::none, "pair"); + run_solve_matches_reference(*solver, 9, GrowthLoadLaw::none, "chain without response"); + run_solve_matches_reference(*solver, 9, GrowthLoadLaw::exponential, "exponential chain"); + run_solve_matches_reference(*solver, 9, GrowthLoadLaw::linear, "linear chain"); + // A larger system after a smaller one grows the device buffers. + run_solve_matches_reference(*solver, 300, GrowthLoadLaw::linear, "long chain"); + run_solve_matches_reference(*solver, 5, GrowthLoadLaw::exponential, "short chain"); + run_empty_and_limited_solves(*solver); + run_closed_chamber(backend, device_index); + run_free_colony(backend, device_index); + }); + return 0; +} From 931d3703ca2e3d3fd0cac7b779ac17418e24d19d Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 11:31:47 +0000 Subject: [PATCH 3/8] Start each substep's contact solve from the previous forces A contact that persists from one substep to the next carries nearly the same force, so the solve of the next substep starts there. A substep is lengthened only after one that settled within two refinement rounds, which stops the step length from alternating between one that fails and one that succeeds. --- cpp/core/contact_dynamics.cpp | 41 +++++++++++++++++++++--- cpp/cuda/kernels/contact_dynamics.cu | 17 +++++----- cpp/metal/kernels/contact_dynamics.metal | 3 +- 3 files changed, 45 insertions(+), 16 deletions(-) diff --git a/cpp/core/contact_dynamics.cpp b/cpp/core/contact_dynamics.cpp index 5c8937f..e4ea0e6 100644 --- a/cpp/core/contact_dynamics.cpp +++ b/cpp/core/contact_dynamics.cpp @@ -33,6 +33,9 @@ constexpr float solve_tolerance_fraction = 0.25F; // Fraction of the load scale of the growth response that an accepted overlap // may add to a contact force. constexpr float load_resolution_fraction = 0.1F; +// Refinement rounds within which a substep counts as short enough to try a +// longer one next. +constexpr std::uint32_t easy_refinements = 2; // A rotation this large in one substep is outside the linearization the // substep's rows rest on. constexpr float maximum_substep_rotation = 0.5F; @@ -258,9 +261,15 @@ using TouchKey = std::tuple; load_resolution_fraction * load_scale / parameters.contact_stiffness); } +// The contact forces of a solved substep by contact, in row order, which +// start the solve of the next substep: a contact that persists carries nearly +// the same force. +using ForceMemory = std::map>; + struct Substep { Geometry geometry; std::vector loads; + ForceMemory forces; std::uint32_t refinements{0}; std::size_t rows{0}; float max_overlap{0.0F}; @@ -272,7 +281,8 @@ struct Substep { WorldState& state, const Geometry& base, std::span rate_lengths, const ConstraintSet& constraints, ComputeBackend& backend, float dt, const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, - const ConstraintContactParameters& constraint_parameters, std::uint64_t& iterations) { + const ConstraintContactParameters& constraint_parameters, const ForceMemory& remembered, + std::uint64_t& iterations) { const auto radii = state.geometry_state().radii; const auto bodies = make_bodies(state, rate_lengths, parameters.drag); const auto candidates = find_touches(state, constraints, backend, contact_parameters, @@ -297,6 +307,17 @@ struct Substep { }; std::vector multipliers(rows.size(), 0.0F); + std::map used; + for (std::size_t index = 0; index < rows.size(); ++index) { + const auto memory = remembered.find(keys[index]); + if (memory == remembered.end()) { + continue; + } + const auto position = used[keys[index]]++; + if (position < memory->second.size()) { + multipliers[index] = memory->second[position]; + } + } for (std::uint32_t refinement = 0; refinement <= parameters.max_refinements; ++refinement) { const ContactSystem system{ .rows = rows, @@ -334,9 +355,14 @@ struct Substep { } } if (overlapping.empty()) { + ForceMemory memory; + for (std::size_t index = 0; index < rows.size(); ++index) { + memory[keys[index]].push_back(multipliers[index]); + } return Substep{ .geometry = *trial, .loads = response.loads, + .forces = std::move(memory), .refinements = refinement, .rows = rows.size(), .max_overlap = max_overlap, @@ -487,14 +513,15 @@ ContactDynamicsResult advance_contact_dynamics( auto remaining = static_cast(dt); auto length = longest; + ForceMemory forces; while (remaining > 0.0) { // A final piece within rounding of the remainder takes all of it. if (static_cast(length) >= remaining * (1.0 - 1.0e-6)) { length = static_cast(remaining); } - auto substep = - advance_substep(state, base, initial.lengths, constraints, backend, length, parameters, - contact_parameters, constraint_parameters, result.report.iterations); + auto substep = advance_substep(state, base, initial.lengths, constraints, backend, length, + parameters, contact_parameters, constraint_parameters, forces, + result.report.iterations); if (!substep.has_value()) { length *= 0.5F; ++result.report.halvings; @@ -512,7 +539,11 @@ ContactDynamicsResult advance_contact_dynamics( result.report.refinements += substep->refinements; result.report.max_rows = std::max(result.report.max_rows, substep->rows); result.report.max_overlap = substep->max_overlap; - length = std::min(longest, length * 2.0F); + forces = std::move(substep->forces); + // A substep that settled in few rounds has room to lengthen. + if (substep->refinements <= easy_refinements) { + length = std::min(longest, length * 2.0F); + } } } catch (...) { restore(state, initial); diff --git a/cpp/cuda/kernels/contact_dynamics.cu b/cpp/cuda/kernels/contact_dynamics.cu index e9cc872..8f17526 100644 --- a/cpp/cuda/kernels/contact_dynamics.cu +++ b/cpp/cuda/kernels/contact_dynamics.cu @@ -1,7 +1,6 @@ -#include "contact_dynamics.cuh" - #include +#include "contact_dynamics.cuh" #include "core/shared_constants.hpp" namespace microsimulator::cuda { @@ -73,11 +72,11 @@ __global__ void contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* const float transverse = bodies[body].rates.x; const float axial = bodies[body].rates.y; const float nominal = bodies[body].rates.z; - const float along = (axial - transverse) * (axis.x * torque_x + axis.y * torque_y + - axis.z * torque_z); + const float along = + (axial - transverse) * (axis.x * torque_x + axis.y * torque_y + axis.z * torque_z); const float rate = nominal > 0.0F ? nominal * contact_growth_factor(solve, load) : nominal; - response[body].linear_length = make_float4(force_x * translational, force_y * translational, - force_z * translational, rate); + response[body].linear_length = + make_float4(force_x * translational, force_y * translational, force_z * translational, rate); response[body].rotation = make_float4(torque_x * transverse + axis.x * along, torque_y * transverse + axis.y * along, torque_z * transverse + axis.z * along, load); @@ -141,8 +140,8 @@ std::uint32_t block_count(std::uint32_t count) { void launch_contact_project(const float* multipliers, const float* gaps, float* next, float step_length, std::uint32_t row_count, cudaStream_t stream) { - contact_project<<>>( - multipliers, gaps, next, step_length, row_count); + contact_project<<>>(multipliers, gaps, next, + step_length, row_count); } void launch_contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, @@ -166,7 +165,7 @@ void launch_contact_reduce(const float4* input, float4* output, std::uint32_t el cudaStream_t stream) { const auto output_count = (element_count + 1) / 2; contact_reduce<<>>(input, output, - element_count); + element_count); } } // namespace microsimulator::cuda diff --git a/cpp/metal/kernels/contact_dynamics.metal b/cpp/metal/kernels/contact_dynamics.metal index d9e1309..c15f62d 100644 --- a/cpp/metal/kernels/contact_dynamics.metal +++ b/cpp/metal/kernels/contact_dynamics.metal @@ -59,8 +59,7 @@ kernel void contact_respond(device const ContactRowData* rows [[buffer(0)]], float axial = bodies[body].rates.y; float nominal = bodies[body].rates.z; float3 velocity = force * bodies[body].axis_mobility.w; - float3 angular_velocity = - torque * transverse + axis * ((axial - transverse) * dot(axis, torque)); + float3 angular_velocity = torque * transverse + axis * ((axial - transverse) * dot(axis, torque)); float rate = nominal > 0.0f ? nominal * contact_growth_factor(solve, load) : nominal; response[body].linear_length = float4(velocity, rate); response[body].rotation = float4(angular_velocity, load); From aeb8024d73e4986acef582272400fb081f4e89d0 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 11:48:24 +0000 Subject: [PATCH 4/8] Carry cells with the flow inside the contact solve With flow drift enabled, the velocity and Jeffery rotation the flow gives each cell enter the contact solve as a known velocity, so contacts resist the flow pressing cells together instead of correcting overlap after a separate drift move. Contacts with constraints use their own stiffness, a hundred times the cell value by default, so cells rest on a wall within a small fraction of the overlap they have with each other. The trap example solves growth and contact together with a linear growth load response in place of its overlap-based growth rule. --- cpp/core/contact_dynamics.cpp | 52 +++++++---- cpp/core/contact_stepper.hpp | 15 +++- cpp/core/device_types.hpp | 2 +- cpp/core/simulation.cpp | 88 ++++++++++++++----- cpp/cpu/cpu_contact_dynamics.cpp | 3 + cpp/cuda/cuda_backend.cu | 2 + cpp/cuda/kernels/contact_dynamics.cu | 12 ++- cpp/cuda/kernels/contact_dynamics.cuh | 9 +- .../microsimulator/contact_dynamics.hpp | 14 ++- cpp/include/microsimulator/simulation.hpp | 8 ++ cpp/metal/kernels/contact_dynamics.metal | 5 +- cpp/metal/metal_backend.mm | 2 + cpp/python/bindings.cpp | 2 + cpp/shared/device_types.h | 3 + docs/architecture/0026-contact-dynamics.md | 12 ++- docs/tutorials/microfluidics.md | 4 +- examples/microfluidic_trap.py | 51 +++++------ python/src/microsimulator/_core.pyi | 2 + python/src/microsimulator/controller.py | 22 ++--- python/tests/test_contact_dynamics.py | 77 +++++++++++++++- python/tests/test_microfluidics.py | 2 +- tests/cpp/contact_dynamics_test.cpp | 5 +- 22 files changed, 292 insertions(+), 100 deletions(-) diff --git a/cpp/core/contact_dynamics.cpp b/cpp/core/contact_dynamics.cpp index e4ea0e6..d9ec624 100644 --- a/cpp/core/contact_dynamics.cpp +++ b/cpp/core/contact_dynamics.cpp @@ -281,10 +281,16 @@ struct Substep { WorldState& state, const Geometry& base, std::span rate_lengths, const ConstraintSet& constraints, ComputeBackend& backend, float dt, const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, - const ConstraintContactParameters& constraint_parameters, const ForceMemory& remembered, - std::uint64_t& iterations) { + const ConstraintContactParameters& constraint_parameters, const detail::ContactDrift& drift, + const ForceMemory& remembered, std::uint64_t& iterations) { const auto radii = state.geometry_state().radii; - const auto bodies = make_bodies(state, rate_lengths, parameters.drag); + auto bodies = make_bodies(state, rate_lengths, parameters.drag); + if (drift.rates) { + const auto rates = drift.rates(dt); + for (std::size_t slot = 0; slot < bodies.size(); ++slot) { + bodies[slot].drift = rates[slot]; + } + } const auto candidates = find_touches(state, constraints, backend, contact_parameters, constraint_parameters, parameters.candidate_margin); std::vector rows; @@ -292,10 +298,15 @@ struct Substep { rows.reserve(candidates.size()); keys.reserve(candidates.size()); auto starting_overlap = 0.0F; - const auto compliance = 1.0F / parameters.contact_stiffness; + // A wall is rigid next to a cell, so a wall contact yields less. + const auto compliance_of = [¶meters](const Touch& touch) { + return 1.0F / (touch.second_slot == invalid_slot ? parameters.wall_stiffness + : parameters.contact_stiffness); + }; for (const auto& touch : candidates) { starting_overlap = std::max(starting_overlap, -touch.separation); - rows.push_back(make_row(base, radii, touch, compliance, parameters.max_overlap_recovery)); + rows.push_back( + make_row(base, radii, touch, compliance_of(touch), parameters.max_overlap_recovery)); keys.push_back(key_of(touch)); } // Overlap deeper than one substep recovers is accepted for now. @@ -349,7 +360,8 @@ struct Substep { for (const auto& touch : found) { max_overlap = std::max(max_overlap, -touch.separation); const auto force = forces.find(key_of(touch)); - const auto allowed = slack + (force == forces.end() ? 0.0F : force->second * compliance); + const auto allowed = + slack + (force == forces.end() ? 0.0F : force->second * compliance_of(touch)); if (touch.separation < -allowed) { overlapping.push_back(touch); } @@ -373,7 +385,8 @@ struct Substep { // that the multipliers that produced the move predict the gap that the // move actually left. for (const auto& touch : overlapping) { - auto row = make_row(*trial, radii, touch, compliance, parameters.max_overlap_recovery); + auto row = + make_row(*trial, radii, touch, compliance_of(touch), parameters.max_overlap_recovery); row.offset -= dt * predicted_rate(row, response); rows.push_back(row); keys.push_back(key_of(touch)); @@ -419,8 +432,8 @@ void validate_contact_dynamics_parameters(const ContactDynamicsParameters& param if (!positive(parameters.drag)) { throw std::invalid_argument("contact dynamics drag must be finite and positive"); } - if (!positive(parameters.contact_stiffness)) { - throw std::invalid_argument("contact stiffness must be finite and positive"); + if (!positive(parameters.contact_stiffness) || !positive(parameters.wall_stiffness)) { + throw std::invalid_argument("contact and wall stiffness must be finite and positive"); } if (!positive(parameters.overlap_tolerance)) { throw std::invalid_argument("contact overlap tolerance must be finite and positive"); @@ -448,8 +461,10 @@ void validate_contact_system(const ContactSystem& system) { for (const auto& body : system.bodies) { if (!finite(body.axis) || !std::isfinite(body.translational_mobility) || !std::isfinite(body.transverse_mobility) || !std::isfinite(body.axial_mobility) || - !std::isfinite(body.length_rate) || body.translational_mobility < 0.0F || - body.transverse_mobility < 0.0F || body.axial_mobility < 0.0F) { + !std::isfinite(body.length_rate) || + !std::ranges::all_of(body.drift, [](float value) { return std::isfinite(value); }) || + body.translational_mobility < 0.0F || body.transverse_mobility < 0.0F || + body.axial_mobility < 0.0F) { throw std::invalid_argument("contact body is invalid"); } } @@ -477,7 +492,7 @@ namespace detail { ContactDynamicsResult advance_contact_dynamics( WorldState& state, const ConstraintSet& constraints, ComputeBackend& backend, float dt, const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, - const ConstraintContactParameters& constraint_parameters) { + const ConstraintContactParameters& constraint_parameters, const ContactDrift& drift) { if (!std::isfinite(dt) || dt < 0.0F) { throw std::invalid_argument("time step must be finite and non-negative"); } @@ -504,7 +519,14 @@ ContactDynamicsResult advance_contact_dynamics( growth = std::max(growth, std::abs(rates[slot]) * view.lengths[slot] * 0.5F * dt / view.radii[slot]); } - const auto pieces = std::max(1.0F, std::ceil(growth / parameters.max_growth_fraction)); + auto pieces = std::max(1.0F, std::ceil(growth / parameters.max_growth_fraction)); + if (drift.rates && drift.travel_limit > 0.0F) { + auto speed = 0.0F; + for (const auto& rate : drift.rates(0.0F)) { + speed = std::max(speed, norm(Vec3{rate[0], rate[1], rate[2]})); + } + pieces = std::max(pieces, std::ceil(speed * dt / drift.travel_limit)); + } if (!std::isfinite(pieces)) { throw std::runtime_error("contact dynamics growth per step is not finite"); } @@ -520,8 +542,8 @@ ContactDynamicsResult advance_contact_dynamics( length = static_cast(remaining); } auto substep = advance_substep(state, base, initial.lengths, constraints, backend, length, - parameters, contact_parameters, constraint_parameters, forces, - result.report.iterations); + parameters, contact_parameters, constraint_parameters, drift, + forces, result.report.iterations); if (!substep.has_value()) { length *= 0.5F; ++result.report.halvings; diff --git a/cpp/core/contact_stepper.hpp b/cpp/core/contact_stepper.hpp index 36f475d..6b1635a 100644 --- a/cpp/core/contact_stepper.hpp +++ b/cpp/core/contact_stepper.hpp @@ -1,5 +1,9 @@ #pragma once +#include +#include +#include + #include "microsimulator/backend.hpp" #include "microsimulator/constraints.hpp" #include "microsimulator/contact_dynamics.hpp" @@ -8,6 +12,15 @@ namespace microsimulator::detail { +// Motion that cells have without contact. `rates` returns the velocity then +// angular velocity of each cell, by slot, for a move of the given length from +// the geometry the state holds. A substep moves no cell further than +// `travel_limit` by drift. +struct ContactDrift { + std::function>(float)> rates; + float travel_limit{0.0F}; +}; + // Advances cell positions, orientations, and lengths over `dt` with growth and // contact solved together. Each substep finds the cells and walls within the // candidate margin, solves for the non-negative contact forces that keep every @@ -19,6 +32,6 @@ namespace microsimulator::detail { [[nodiscard]] ContactDynamicsResult advance_contact_dynamics( WorldState& state, const ConstraintSet& constraints, ComputeBackend& backend, float dt, const ContactDynamicsParameters& parameters, const ContactParameters& contact_parameters, - const ConstraintContactParameters& constraint_parameters); + const ConstraintContactParameters& constraint_parameters, const ContactDrift& drift = {}); } // namespace microsimulator::detail diff --git a/cpp/core/device_types.hpp b/cpp/core/device_types.hpp index 2900daf..4658d4f 100644 --- a/cpp/core/device_types.hpp +++ b/cpp/core/device_types.hpp @@ -44,7 +44,7 @@ static_assert(sizeof(uint4) == 16 && alignof(uint4) == 16); static_assert(sizeof(RateInstruction) == 20); static_assert(sizeof(MechanicsDofs) == 32); static_assert(sizeof(ContactRowData) == 80 && offsetof(ContactRowData, first_slot) == 64); -static_assert(sizeof(ContactBodyData) == 32); +static_assert(sizeof(ContactBodyData) == 64); static_assert(sizeof(ContactSolveData) == 32); static_assert(sizeof(ContactSolveState) == 16); static_assert(sizeof(ExternalConstraint) == 48 && offsetof(ExternalConstraint, geometry) == 16); diff --git a/cpp/core/simulation.cpp b/cpp/core/simulation.cpp index a50072c..99f52b2 100644 --- a/cpp/core/simulation.cpp +++ b/cpp/core/simulation.cpp @@ -124,6 +124,60 @@ void Simulation::remove_cell(CellId id) { state_.remove_cell(id); } +std::pair Simulation::flow_derivative(Vec3 point, Vec3 axis, float lambda, + bool rotates) const { + const auto spacing = signal_grid_->spec().spacing; + const std::array h{spacing.x, spacing.y, spacing.z}; + const std::array dims{ + signal_grid_->spec().shape.x, signal_grid_->spec().shape.y, signal_grid_->spec().shape.z}; + const auto sample = [&](Vec3 position) { + return signal_grid_->sample_velocity(position, GridSampleBound::clamped); + }; + // Central differences of the interpolated fluid velocity. This is an + // equivalent-spheroid Jeffery closure, not cell-resolved hydrodynamics. + std::array gradient{}; + for (std::size_t k = 0; k < 3; ++k) { + if (dims[k] == 1) continue; + Vec3 offset{}; + if (k == 0) offset.x = h[k] * 0.5F; + if (k == 1) offset.y = h[k] * 0.5F; + if (k == 2) offset.z = h[k] * 0.5F; + gradient[k] = (sample(point + offset) - sample(point - offset)) * (1 / h[k]); + } + const Vec3 ap = gradient[0] * axis.x + gradient[1] * axis.y + gradient[2] * axis.z; + const Vec3 atp{dot(gradient[0], axis), dot(gradient[1], axis), dot(gradient[2], axis)}; + const Vec3 strain = (ap + atp) * 0.5F; + const Vec3 spin = (ap - atp) * 0.5F; + const auto orientation = rotates ? spin + (strain - axis * dot(axis, strain)) * lambda : Vec3{}; + return {sample(point), orientation}; +} + +std::vector> Simulation::flow_drift_rates(float dt) const { + const auto geometry = state_.geometry_state(); + const auto attributes = state_.cell_attributes(); + std::vector> rates(geometry.size()); + for (std::size_t slot = 0; slot < geometry.size(); ++slot) { + if (attributes.fixed[slot] != 0) continue; + const Vec3 position{geometry.position_x[slot], geometry.position_y[slot], + geometry.position_z[slot]}; + const Vec3 direction{geometry.direction_x[slot], geometry.direction_y[slot], + geometry.direction_z[slot]}; + const float aspect = + (geometry.lengths[slot] + 2 * geometry.radii[slot]) / (2 * geometry.radii[slot]); + const float lambda = (aspect * aspect - 1) / (aspect * aspect + 1); + // The rates at the midpoint of the free motion over `dt`. + const auto [velocity, orientation] = flow_derivative(position, direction, lambda, true); + const auto midpoint = position + velocity * (dt * 0.5F); + const auto mid_direction = normalized(direction + orientation * (dt * 0.5F)); + const auto [mid_velocity, mid_orientation] = + flow_derivative(midpoint, mid_direction, lambda, true); + // A direction turning at rate d is a rotation at angular velocity p x d. + const auto angular = cross(direction, mid_orientation); + rates[slot] = {mid_velocity.x, mid_velocity.y, mid_velocity.z, angular.x, angular.y, angular.z}; + } + return rates; +} + void Simulation::apply_flow_drift(float dt, const MechanicsIntegrationParameters& parameters) { if (!std::isfinite(dt) || dt < 0.0F) { throw std::invalid_argument("time step must be finite and non-negative"); @@ -158,29 +212,8 @@ void Simulation::apply_flow_drift(float dt, const MechanicsIntegrationParameters const float aspect = (geometry.lengths[slot] + 2 * geometry.radii[slot]) / (2 * geometry.radii[slot]); const float lambda = (aspect * aspect - 1) / (aspect * aspect + 1); - const auto sample = [&](Vec3 point) { - return signal_grid_->sample_velocity(point, GridSampleBound::clamped); - }; const auto derivative = [&](Vec3 point, Vec3 axis) { - // Central differences of the interpolated fluid velocity. This is an - // equivalent-spheroid Jeffery closure, not cell-resolved hydrodynamics. - std::array gradient{}; - for (std::size_t k = 0; k < 3; ++k) { - if (dims[k] == 1) continue; - Vec3 offset{}; - if (k == 0) offset.x = h[k] * 0.5F; - if (k == 1) offset.y = h[k] * 0.5F; - if (k == 2) offset.z = h[k] * 0.5F; - gradient[k] = (sample(point + offset) - sample(point - offset)) * (1 / h[k]); - } - const Vec3 ap = gradient[0] * axis.x + gradient[1] * axis.y + gradient[2] * axis.z; - const Vec3 atp{dot(gradient[0], axis), dot(gradient[1], axis), dot(gradient[2], axis)}; - const Vec3 strain = (ap + atp) * 0.5F; - const Vec3 spin = (ap - atp) * 0.5F; - const auto orientation = parameters.max_rotation_radians == 0 - ? Vec3{} - : spin + (strain - axis * dot(axis, strain)) * lambda; - return std::pair{sample(point), orientation}; + return flow_derivative(point, axis, lambda, parameters.max_rotation_radians != 0); }; double remaining = dt; std::uint32_t steps = 0; @@ -379,9 +412,18 @@ ContactDynamicsResult Simulation::advance(float dt, const ContactDynamicsRequest ContactDynamicsResult result; try { if (dynamics != nullptr) { + detail::ContactDrift drift; + if (dynamics->dynamics.flow_drift) { + if (!signal_grid_.has_value() || !signal_grid_->spec().velocity_field.has_value()) { + throw std::logic_error("flow drift requires a signal grid with a velocity field"); + } + const auto spacing = signal_grid_->spec().spacing; + drift.rates = [this](float length) { return flow_drift_rates(length); }; + drift.travel_limit = 0.25F * std::min({spacing.x, spacing.y, spacing.z}); + } result = detail::advance_contact_dynamics(state_, constraints_, *backend_, dt, dynamics->dynamics, - dynamics->contacts, dynamics->constraints); + dynamics->contacts, dynamics->constraints, drift); } else { backend_->advance_growth(state_, dt); } diff --git a/cpp/cpu/cpu_contact_dynamics.cpp b/cpp/cpu/cpu_contact_dynamics.cpp index 024144e..278829b 100644 --- a/cpp/cpu/cpu_contact_dynamics.cpp +++ b/cpp/cpu/cpu_contact_dynamics.cpp @@ -82,6 +82,9 @@ void evaluate(const ContactSystem& system, std::span multipliers, evaluation.length_rates.resize(body_count); for (std::size_t index = 0; index < body_count; ++index) { evaluation.velocities[index] = apply_mobility(system.bodies[index], evaluation.wrenches[index]); + for (std::size_t component = 0; component < 6; ++component) { + evaluation.velocities[index][component] += system.bodies[index].drift[component]; + } evaluation.length_rates[index] = length_rate(system.bodies[index], system.growth, evaluation.loads[index]); } diff --git a/cpp/cuda/cuda_backend.cu b/cpp/cuda/cuda_backend.cu index 4bd8db9..065b1bd 100644 --- a/cpp/cuda/cuda_backend.cu +++ b/cpp/cuda/cuda_backend.cu @@ -1606,6 +1606,8 @@ class CudaBackend final : public ComputeBackend { source.translational_mobility), .rates = make_float4(source.transverse_mobility, source.axial_mobility, source.length_rate, 0.0F), + .drift_linear = make_float4(source.drift[0], source.drift[1], source.drift[2], 0.0F), + .drift_angular = make_float4(source.drift[3], source.drift[4], source.drift[5], 0.0F), }; } copy_to_device(contact_rows_, rows, "failed to upload CUDA contact rows"); diff --git a/cpp/cuda/kernels/contact_dynamics.cu b/cpp/cuda/kernels/contact_dynamics.cu index 8f17526..ccb525b 100644 --- a/cpp/cuda/kernels/contact_dynamics.cu +++ b/cpp/cuda/kernels/contact_dynamics.cu @@ -75,11 +75,15 @@ __global__ void contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* const float along = (axial - transverse) * (axis.x * torque_x + axis.y * torque_y + axis.z * torque_z); const float rate = nominal > 0.0F ? nominal * contact_growth_factor(solve, load) : nominal; - response[body].linear_length = - make_float4(force_x * translational, force_y * translational, force_z * translational, rate); + const float4 drift_linear = bodies[body].drift_linear; + const float4 drift_angular = bodies[body].drift_angular; + response[body].linear_length = make_float4(drift_linear.x + force_x * translational, + drift_linear.y + force_y * translational, + drift_linear.z + force_z * translational, rate); response[body].rotation = - make_float4(torque_x * transverse + axis.x * along, torque_y * transverse + axis.y * along, - torque_z * transverse + axis.z * along, load); + make_float4(drift_angular.x + torque_x * transverse + axis.x * along, + drift_angular.y + torque_y * transverse + axis.y * along, + drift_angular.z + torque_z * transverse + axis.z * along, load); } __global__ void contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, diff --git a/cpp/cuda/kernels/contact_dynamics.cuh b/cpp/cuda/kernels/contact_dynamics.cuh index 379cfbd..4965108 100644 --- a/cpp/cuda/kernels/contact_dynamics.cuh +++ b/cpp/cuda/kernels/contact_dynamics.cuh @@ -22,11 +22,14 @@ struct alignas(16) ContactRowGpu { std::uint32_t padding1; }; -// Cell axis with the translational mobility in w, then the transverse -// mobility, axial mobility, and nominal elongation rate. +// Cell axis with the translational mobility in w; the transverse mobility, +// axial mobility, and nominal elongation rate; then the velocity and angular +// velocity the cell has without contact. struct alignas(16) ContactBodyGpu { float4 axis_mobility; float4 rates; + float4 drift_linear; + float4 drift_angular; }; struct ContactSolveGpu { @@ -40,7 +43,7 @@ struct ContactSolveGpu { }; static_assert(sizeof(ContactRowGpu) == 80); -static_assert(sizeof(ContactBodyGpu) == 32); +static_assert(sizeof(ContactBodyGpu) == 64); // next = max(multipliers - step_length * gaps, 0). void launch_contact_project(const float* multipliers, const float* gaps, float* next, diff --git a/cpp/include/microsimulator/contact_dynamics.hpp b/cpp/include/microsimulator/contact_dynamics.hpp index ae5bfc1..03528b0 100644 --- a/cpp/include/microsimulator/contact_dynamics.hpp +++ b/cpp/include/microsimulator/contact_dynamics.hpp @@ -41,6 +41,9 @@ struct ContactDynamicsParameters { // Contact force per unit overlap. Contacts are unilateral springs solved // implicitly, so a resting contact under force f overlaps by f / stiffness. float contact_stiffness{1.0e4F}; + // Force per unit overlap of a contact with a constraint. Walls are rigid + // next to cells, so this is the stiffer of the two. + float wall_stiffness{1.0e6F}; // Overlap, beyond what the contact force accounts for, accepted at the end // of a substep. float overlap_tolerance{1.0e-3F}; @@ -55,6 +58,9 @@ struct ContactDynamicsParameters { std::uint32_t max_iterations{20000}; std::uint32_t max_refinements{10}; std::uint32_t max_step_halvings{12}; + // Carries the cells with the signal grid's velocity field inside the solve, + // so that contacts resist the flow pressing cells together. + bool flow_drift{false}; GrowthLoadResponse growth; }; @@ -76,19 +82,21 @@ struct ContactRow { float compliance{0.0F}; }; -// Mobility and nominal elongation of one cell. A fixed cell has zero -// mobility. +// Mobility, nominal elongation, and imposed motion of one cell. A fixed cell +// has zero mobility. `drift` is the velocity then angular velocity the cell +// has without contact, which contact forces add to. struct ContactBody { Vec3 axis{1.0F, 0.0F, 0.0F}; float translational_mobility{0.0F}; float transverse_mobility{0.0F}; float axial_mobility{0.0F}; float length_rate{0.0F}; + std::array drift{}; }; // The convex problem of one substep. With multipliers g >= 0, the predicted // gap of every row is -// offset + dt * J^T M^-1 J g - dt * L^T (length_rate * factor(L g)) + compliance * g +// offset + dt * J^T (drift + M^-1 J g) - dt * L^T (length_rate * factor(L g)) + compliance * g // and the solution has gap >= 0 with gap_i * g_i = 0. struct ContactSystem { std::span rows; diff --git a/cpp/include/microsimulator/simulation.hpp b/cpp/include/microsimulator/simulation.hpp index 9d5d18f..4c402a4 100644 --- a/cpp/include/microsimulator/simulation.hpp +++ b/cpp/include/microsimulator/simulation.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -97,6 +98,13 @@ class Simulation { private: struct ContactDynamicsRequest; ContactDynamicsResult advance(float dt, const ContactDynamicsRequest* dynamics); + // The fluid velocity at a point and the rate at which it turns a rod of + // the given axis and Jeffery shape factor. + [[nodiscard]] std::pair flow_derivative(Vec3 point, Vec3 axis, float lambda, + bool rotates) const; + // The velocity then angular velocity the flow gives each cell over a move + // of length `dt`, by slot. Fixed cells do not drift. + [[nodiscard]] std::vector> flow_drift_rates(float dt) const; WorldState state_; ConstraintSet constraints_; diff --git a/cpp/metal/kernels/contact_dynamics.metal b/cpp/metal/kernels/contact_dynamics.metal index c15f62d..9daf954 100644 --- a/cpp/metal/kernels/contact_dynamics.metal +++ b/cpp/metal/kernels/contact_dynamics.metal @@ -58,8 +58,9 @@ kernel void contact_respond(device const ContactRowData* rows [[buffer(0)]], float transverse = bodies[body].rates.x; float axial = bodies[body].rates.y; float nominal = bodies[body].rates.z; - float3 velocity = force * bodies[body].axis_mobility.w; - float3 angular_velocity = torque * transverse + axis * ((axial - transverse) * dot(axis, torque)); + float3 velocity = bodies[body].drift_linear.xyz + force * bodies[body].axis_mobility.w; + float3 angular_velocity = bodies[body].drift_angular.xyz + torque * transverse + + axis * ((axial - transverse) * dot(axis, torque)); float rate = nominal > 0.0f ? nominal * contact_growth_factor(solve, load) : nominal; response[body].linear_length = float4(velocity, rate); response[body].rotation = float4(angular_velocity, load); diff --git a/cpp/metal/metal_backend.mm b/cpp/metal/metal_backend.mm index ef98db4..f36e4fd 100644 --- a/cpp/metal/metal_backend.mm +++ b/cpp/metal/metal_backend.mm @@ -2277,6 +2277,8 @@ void upload_contact_system(const ContactSystem& system, .axis_mobility = {source.axis.x, source.axis.y, source.axis.z, source.translational_mobility}, .rates = {source.transverse_mobility, source.axial_mobility, source.length_rate, 0.0F}, + .drift_linear = {source.drift[0], source.drift[1], source.drift[2], 0.0F}, + .drift_angular = {source.drift[3], source.drift[4], source.drift[5], 0.0F}, }; } std::memcpy(contact_multipliers_[0].contents, initial_multipliers.data(), diff --git a/cpp/python/bindings.cpp b/cpp/python/bindings.cpp index b636673..0001c9f 100644 --- a/cpp/python/bindings.cpp +++ b/cpp/python/bindings.cpp @@ -533,6 +533,7 @@ NB_MODULE(_core, module) { .def(nb::init<>()) .def_rw("drag", µsimulator::ContactDynamicsParameters::drag) .def_rw("contact_stiffness", µsimulator::ContactDynamicsParameters::contact_stiffness) + .def_rw("wall_stiffness", µsimulator::ContactDynamicsParameters::wall_stiffness) .def_rw("overlap_tolerance", µsimulator::ContactDynamicsParameters::overlap_tolerance) .def_rw("candidate_margin", µsimulator::ContactDynamicsParameters::candidate_margin) .def_rw("max_overlap_recovery", @@ -542,6 +543,7 @@ NB_MODULE(_core, module) { .def_rw("max_iterations", µsimulator::ContactDynamicsParameters::max_iterations) .def_rw("max_refinements", µsimulator::ContactDynamicsParameters::max_refinements) .def_rw("max_step_halvings", µsimulator::ContactDynamicsParameters::max_step_halvings) + .def_rw("flow_drift", µsimulator::ContactDynamicsParameters::flow_drift) .def_rw("growth", µsimulator::ContactDynamicsParameters::growth); nb::class_(module, "ContactDynamicsReport") diff --git a/cpp/shared/device_types.h b/cpp/shared/device_types.h index c6c7787..cf90f77 100644 --- a/cpp/shared/device_types.h +++ b/cpp/shared/device_types.h @@ -41,6 +41,9 @@ struct ContactBodyData { float4 axis_mobility; // Transverse mobility, axial mobility, and nominal elongation rate. float4 rates; + // Velocity and angular velocity the cell has without contact. + float4 drift_linear; + float4 drift_angular; }; struct ContactSolveData { diff --git a/docs/architecture/0026-contact-dynamics.md b/docs/architecture/0026-contact-dynamics.md index c22fe59..93f91e1 100644 --- a/docs/architecture/0026-contact-dynamics.md +++ b/docs/architecture/0026-contact-dynamics.md @@ -25,7 +25,7 @@ gap(g) = phi + h J^T M^-1 J g - h L^T (r * f(L g)) + c g - `M` is the drag of each cell on its surroundings: `drag * L` in translation for a capsule of full length `L`, with the finite-radius rod inertias of ADR 0002 in rotation. A fixed cell has no mobility. - `L g` is the axial load on each cell. A row contributes its multiplier times the cell's length lever, the fraction of the cell's elongation that closes that contact: the cylinder stretches uniformly about its center and the caps ride on its ends, so the lever is one half for a contact on a cap along the axis and zero for a contact on the side. - `r` is the nominal elongation rate `growth_rate * length`, taken from the lengths at the start of the step, and `f` is the growth load response. `L^T` maps elongation to the gap it closes. -- `c` is the compliance `1 / contact_stiffness`. +- `c` is the compliance of the row: `1 / contact_stiffness` between cells and `1 / wall_stiffness` against a constraint. The solution satisfies `g >= 0`, `gap >= 0`, and `g * gap = 0` row by row. Those are the optimality conditions of a convex energy whose gradient is `gap`, because `f` is non-increasing. In a full space the multipliers rise until the loads stop growth. @@ -39,7 +39,7 @@ Shrinkage is never scaled. Loads are forces in units of drag times length square ### Compliance -A contact is a unilateral linear spring solved implicitly: a resting contact under force `g` overlaps by `g / contact_stiffness`, and the solve is stable at any stiffness. Compliance keeps the problem well posed when a space holds more than it can: the forces of an over-full region are finite, where rigid constraints have no solution. It also means an overlap `e` that a jammed pair cannot recover persists as a force `e * contact_stiffness`. Where growth responds to load, the accepted overlap is therefore held to the overlap that a tenth of the load scale of the response presses into a contact. The forces of a rigid jam above the stall load depend on the history of those small overlaps and are not otherwise determined. +A contact is a unilateral linear spring solved implicitly: a resting contact under force `g` overlaps by `g / contact_stiffness`, and the solve is stable at any stiffness. Walls are rigid next to cells, so a contact with a constraint uses the larger `wall_stiffness`, by default a hundred times the cell value; cells then rest on a wall within a small fraction of the overlap they have with each other, at little cost to the solve. Compliance keeps the problem well posed when a space holds more than it can: the forces of an over-full region are finite, where rigid constraints have no solution. It also means an overlap `e` that a jammed pair cannot recover persists as a force `e * contact_stiffness`. Where growth responds to load, the accepted overlap is therefore held to the overlap that a tenth of the load scale of the response presses into a contact. The forces of a rigid jam above the stall load depend on the history of those small overlaps and are not otherwise determined. A contact already deeper than `max_overlap_recovery` asks for only that much separation in one substep and is stiffened in proportion, so a pair free to move separates at a bounded rate while a pair that cannot move still meets the full spring force of its overlap. @@ -66,7 +66,11 @@ Constraints are rows in the same solve. A box or cylinder that cells live inside ### Order within a step -Growth and contact run first, then species, coupled, and signal updates, which see the elongation that happened; uptake tied to volume change is charged for it. With flow drift enabled the controller moves the cells with the flow before the step, so the step ends with every contact resolved. +Growth and contact run first, then species, coupled, and signal updates, which see the elongation that happened; uptake tied to volume change is charged for it. + +### Flow + +With `flow_drift` set, the velocity and Jeffery rotation that the signal grid's velocity field gives each cell ([ADR 0021](0021-flow-drift.md)) enter the solve as a known velocity `u`: the predicted gap gains `h J^T u` and each cell moves at `u` plus what its contact forces add. Contacts therefore resist the flow pressing cells together or into a wall, rather than correcting the overlap after a separate drift move. The rates are evaluated at the midpoint of each cell's free motion over the substep, fixed cells do not drift, and a substep carries no cell further than a quarter of the smallest grid spacing. ## Validation @@ -78,6 +82,8 @@ Growth and contact run first, then species, coupled, and signal updates, which s ## Limits - Contacts are frictionless and cells are rigid apart from the contact compliance. +- Contact stiffness trades overlap against cost: in an unconfined colony of 2,000 cells without load response, ten times the stiffness leaves a fifth of the overlap and takes about eight times the iterations. Loads grow with the size of a colony whose growth ignores them, so the stiffness that keeps overlaps small grows with it. +- A cell squeezed directly between two walls, with no softer contact to yield, has its load resolved only to the accepted overlap times the wall stiffness. - The cost of a step is the number of projected-gradient iterations, which grows with the number of cells that push on each other through the colony; published solvers of this kind report on the order of a thousand iterations per step in dense colonies. - A perfectly collinear line of cells between two walls is an equilibrium and does not buckle. Division plans perturb daughter directions to break that symmetry. - The exponential response never stops growth, so a closed space keeps filling slowly as its contact overlaps deepen. diff --git a/docs/tutorials/microfluidics.md b/docs/tutorials/microfluidics.md index 01dfc8f..d06a13a 100644 --- a/docs/tutorials/microfluidics.md +++ b/docs/tutorials/microfluidics.md @@ -21,7 +21,7 @@ Run any of them live: uv run microsimulator view --model examples/microfluidic_trap.py --seed 42 --dt 0.02 --backend cpu --open ``` -The trap example is sized to one population: a 40 by 20 micrometer trap, 1.5 micrometers deep, beside a 20 micrometer channel. A few hundred cells fill it as a monolayer. Its growth rule multiplies the Monod rate by a compression factor that falls linearly to zero as a cell's deepest overlap with a neighbor reaches a fifth of its diameter, so the packed interior stops elongating while cells at the mouth keep growing, spill into the channel, and wash out. The population settles near 320 cells with continuous turnover. The compression limit is a model choice, not a measured mechanical response. +The trap example is sized to one population: a 40 by 20 micrometer trap, 1.5 micrometers deep, beside a 20 micrometer channel. A few hundred cells fill it as a monolayer. It solves growth and contact together with [contact dynamics](../architecture/0026-contact-dynamics.md): cells push each other toward the mouth with contact forces, and a cell's elongation falls linearly with the axial load on it, stopping at a stall load. The cells at the back carry the load of everything between them and the mouth, so they slow and stall, while cells at the mouth keep growing, spill into the channel, and wash out. The trap holds about 260 cells with continuous turnover. The stall load is a model choice, not a measured mechanical response. ## Walls that cells and chemistry both respect @@ -65,7 +65,7 @@ The constructor's keyword arguments set the trap, channel, and wall dimensions; ## Flow on signals and on cells -The velocity field advects every signal with conservative upwind face fluxes under all three signal integrators. With `MechanicsConfig(flow_drift=True)`, the controller translates each non-fixed cell using the velocity sampled at its center and rotates it with a finite-aspect Jeffery approximation, so escaped cells travel down the channel and rods rotate in shear. Contact relaxation then resolves overlaps with walls or neighbors. The [flow-drift design](../architecture/0021-flow-drift.md) describes this kinematic approximation and its integration limits. +The velocity field advects every signal with conservative upwind face fluxes under all three signal integrators. With `MechanicsConfig(flow_drift=True)`, the controller translates each non-fixed cell using the velocity sampled at its center and rotates it with a finite-aspect Jeffery approximation, so escaped cells travel down the channel and rods rotate in shear. Contact relaxation then resolves overlaps with walls or neighbors; with contact dynamics the flow velocity is part of the contact solve instead, so cells the flow presses together do not overlap. The [flow-drift design](../architecture/0021-flow-drift.md) describes this kinematic approximation and its integration limits. ## Washout diff --git a/examples/microfluidic_trap.py b/examples/microfluidic_trap.py index 0cbecd5..ea416ee 100644 --- a/examples/microfluidic_trap.py +++ b/examples/microfluidic_trap.py @@ -9,10 +9,13 @@ between flow supply, diffusion into the trap, and consumption by the cells already there. -The trap is a monolayer that a few hundred cells fill. A cell pressed into its -neighbors stops elongating, so the packed colony holds its density while the -cells at the trap mouth, which have room, keep growing, spill into the channel, -and are carried to the outlet. The population settles at a steady turnover. +The trap is a monolayer that a few hundred cells fill. Growth and contact are +solved together: cells push each other toward the trap mouth with contact +forces, and a cell elongates more slowly the larger the axial load those forces +put on it. The cells deep in the trap carry the load of everything between them +and the mouth, so they slow and stall, while the cells at the mouth keep +growing, spill into the channel, and are carried to the outlet. The population +settles at a steady turnover. """ from __future__ import annotations @@ -22,6 +25,7 @@ from microsimulator import ( CellInit, CellUpdate, + ContactDynamicsConfig, ControllerStep, CoupledRatePlan, DivisionEvent, @@ -42,7 +46,7 @@ from microsimulator.microfluidics import TrapChannelDevice MODEL_ID = "examples.microfluidic-trap" -MODEL_VERSION = 5 +MODEL_VERSION = 6 DIVISION = UniformLengthDivision(3.2, 3.8, jitter_z=False) FLOW_SPEED = 20.0 @@ -67,12 +71,11 @@ # the actual increase of B = pi*r^2*(length + 2*r), divided by this yield. # The value is illustrative; penetration and growth require refinement checks. NUTRIENT_YIELD = 0.5 -# Growth stops under compression: a cell whose deepest overlap with a neighbor -# reaches this depth does not elongate, and growth falls off linearly up to -# it. Contact relaxation spreads overlap over several steps, so growth that -# ignored it would keep packing cells into a full trap. The value is a model -# choice, a fifth of a cell's diameter, not a measured mechanical response. -COMPRESSION_LIMIT = 0.2 +# Growth slows under load: elongation falls linearly with the axial load on a +# cell and stops at this load. Loads are forces in units of drag times length +# squared per time, and the load on a cell at the back of the full trap is a +# few hundred. The value is a model choice, not a measured mechanical response. +GROWTH_STALL_LOAD = 200.0 WASHOUT_Y = DEVICE.channel_half_length - 10.0 # Resistance feedback uses only fixed (attached) cells, with a physical @@ -129,18 +132,6 @@ def _nutrient_growth(simulation: Simulation, position: Vec3) -> float: return BASE_GROWTH_RATE * nutrient / (NUTRIENT_K + nutrient) -def _compression(simulation: Simulation) -> dict[int, float]: - """Each cell's deepest overlap with a neighbor, for the cells that have one.""" - - deepest: dict[int, float] = {} - for contact in simulation.find_cell_contacts().contacts: - overlap = -contact.signed_separation - if overlap > 0.0: - for cell_id in (contact.first_id, contact.second_id): - deepest[cell_id] = max(deepest.get(cell_id, 0.0), overlap) - return deepest - - def _regulate(step: ControllerStep) -> StepPlan: if step.completed_steps and step.completed_steps % RESOLVE_INTERVAL == 0: mobility = colony_mobility( @@ -159,14 +150,9 @@ def _regulate(step: ControllerStep) -> StepPlan: if washed: DIVISION.forget(step, washed) divisions = tuple(request for request in divisions if request.parent_id not in washed) - compression = _compression(step.simulation) return StepPlan( updates=tuple( - CellUpdate( - cell.id, - growth_rate=_nutrient_growth(step.simulation, cell.position) - * max(0.0, 1.0 - compression.get(cell.id, 0.0) / COMPRESSION_LIMIT), - ) + CellUpdate(cell.id, growth_rate=_nutrient_growth(step.simulation, cell.position)) for cell in step.cells if cell.id not in washed ), @@ -200,7 +186,12 @@ def build(context: ModelContext) -> NativeController: rng=context.rng, regulate=_regulate, on_division=_divided, - mechanics=MechanicsConfig(flow_drift=True), + mechanics=MechanicsConfig( + flow_drift=True, + contact_dynamics=ContactDynamicsConfig( + growth_law="linear", growth_stall_load=GROWTH_STALL_LOAD + ), + ), state=state, ) diff --git a/python/src/microsimulator/_core.pyi b/python/src/microsimulator/_core.pyi index e71cb41..716e26f 100644 --- a/python/src/microsimulator/_core.pyi +++ b/python/src/microsimulator/_core.pyi @@ -630,6 +630,7 @@ class GrowthLoadResponse: class ContactDynamicsParameters: drag: float contact_stiffness: float + wall_stiffness: float overlap_tolerance: float candidate_margin: float max_overlap_recovery: float @@ -637,6 +638,7 @@ class ContactDynamicsParameters: max_iterations: int max_refinements: int max_step_halvings: int + flow_drift: bool growth: GrowthLoadResponse def __init__(self) -> None: ... diff --git a/python/src/microsimulator/controller.py b/python/src/microsimulator/controller.py index 0158574..400f37d 100644 --- a/python/src/microsimulator/controller.py +++ b/python/src/microsimulator/controller.py @@ -190,11 +190,13 @@ class ContactDynamicsConfig: load, ``"exponential"`` scales elongation by ``exp(-growth_sensitivity * load)``, and ``"linear"`` leaves it unscaled up to ``growth_free_load`` and stops it at ``growth_stall_load``. Loads are forces in units of ``drag`` times - length squared per time. + length squared per time. A contact under force ``f`` overlaps by ``f / + contact_stiffness`` between cells and ``f / wall_stiffness`` against a wall. """ drag: float = 1.0 contact_stiffness: float = 1.0e4 + wall_stiffness: float = 1.0e6 overlap_tolerance: float = 1.0e-3 candidate_margin: float = 0.1 max_overlap_recovery: float = 0.05 @@ -208,7 +210,7 @@ class ContactDynamicsConfig: growth_stall_load: float = 1.0 def __post_init__(self) -> None: - for name in ("drag", "contact_stiffness", "overlap_tolerance"): + for name in ("drag", "contact_stiffness", "wall_stiffness", "overlap_tolerance"): if _finite_number(getattr(self, name), f"contact_dynamics.{name}") <= 0.0: raise ControllerStateError(f"contact_dynamics.{name} must be positive") for name in ("max_overlap_recovery", "max_growth_fraction"): @@ -238,6 +240,7 @@ def native_parameters(self) -> ContactDynamicsParameters: parameters = ContactDynamicsParameters() parameters.drag = self.drag parameters.contact_stiffness = self.contact_stiffness + parameters.wall_stiffness = self.wall_stiffness parameters.overlap_tolerance = self.overlap_tolerance parameters.candidate_margin = self.candidate_margin parameters.max_overlap_recovery = self.max_overlap_recovery @@ -277,6 +280,7 @@ def count(name: str) -> int: return cls( drag=number("drag"), contact_stiffness=number("contact_stiffness"), + wall_stiffness=number("wall_stiffness"), overlap_tolerance=number("overlap_tolerance"), candidate_margin=number("candidate_margin"), max_overlap_recovery=number("max_overlap_recovery"), @@ -632,14 +636,12 @@ def step(self, dt: float) -> None: mechanics is not None and mechanics.flow_drift and self.simulation.cell_count != 0 ) if mechanics is not None and mechanics.contact_dynamics is not None: - # The flow moves the cells first, so the step ends with every - # contact resolved. - _, contacts, integration, constraints = mechanics.native_parameters() - if drifts: - self.simulation.apply_flow_drift(dt, integration) - self._last_contact_dynamics = self.simulation.step( - dt, mechanics.contact_dynamics.native_parameters(), contacts, constraints - ) + # The flow carries the cells inside the solve, so contacts resist + # it pressing cells together. + _, contacts, _, constraints = mechanics.native_parameters() + dynamics = mechanics.contact_dynamics.native_parameters() + dynamics.flow_drift = mechanics.flow_drift + self._last_contact_dynamics = self.simulation.step(dt, dynamics, contacts, constraints) else: self._last_contact_dynamics = None self.simulation.step(dt) diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py index 6490c52..1c965b0 100644 --- a/python/tests/test_contact_dynamics.py +++ b/python/tests/test_contact_dynamics.py @@ -18,6 +18,7 @@ ControllerStep, DivisionEvent, DivisionRequest, + GridBoundaryKind, GridShape, GrowthLoadLaw, GrowthLoadResponse, @@ -26,6 +27,7 @@ PlaneConstraintInit, RatePlanBuilder, SignalGridSpec, + SignalGridVelocityField, Simulation, StepPlan, Vec3, @@ -57,6 +59,9 @@ def _between_walls(simulation: Simulation, half_width: float) -> None: def _stalling(stall_load: float) -> ContactDynamicsParameters: parameters = ContactDynamicsParameters() + # Nothing softer than the walls holds a cell squeezed between two of them, + # so the wall stiffness sets how finely its load is resolved. + parameters.wall_stiffness = parameters.contact_stiffness growth = parameters.growth growth.law = GrowthLoadLaw.LINEAR growth.stall_load = stall_load @@ -146,7 +151,11 @@ def test_growth_load_response_factor() -> None: def test_contact_dynamics_config_round_trips_and_validates() -> None: config = ContactDynamicsConfig( - growth_law="linear", growth_free_load=1.0, growth_stall_load=8.0, contact_stiffness=2000.0 + growth_law="linear", + growth_free_load=1.0, + growth_stall_load=8.0, + contact_stiffness=2000.0, + wall_stiffness=5.0e4, ) mechanics = MechanicsConfig(flow_drift=True, contact_dynamics=config) assert MechanicsConfig.from_json(mechanics.to_json()) == mechanics @@ -155,6 +164,7 @@ def test_contact_dynamics_config_round_trips_and_validates() -> None: assert parameters.growth.law == GrowthLoadLaw.LINEAR assert parameters.growth.stall_load == 8.0 assert parameters.contact_stiffness == 2000.0 + assert parameters.wall_stiffness == 5.0e4 # A payload written without the entry selects relaxation passes. legacy = MechanicsConfig(passes=2).to_json() @@ -408,6 +418,71 @@ def test_free_colony_matches_the_continuum_pressure_profile(backend: BackendKind assert means[0] > 3.0 * means[-1] +def _uniform_flow(backend: BackendKind, speed: float) -> Simulation: + simulation = _simulation(backend) + sites = 9 + shape = GridShape() + shape.x, shape.y, shape.z = sites, 1, 1 + grid = SignalGridSpec() + grid.signal_count = 1 + grid.shape = shape + grid.spacing = Vec3(1.0, 1.0, 1.0) + grid.diffusion = [0.0] + grid.advection = [Vec3()] + grid.x_lower.kind = GridBoundaryKind.FIXED + grid.x_lower.values = [0.0] + grid.x_upper.kind = GridBoundaryKind.FIXED + grid.x_upper.values = [0.0] + velocity = SignalGridVelocityField() + velocity.x_faces = [speed] * (sites + 1) + velocity.y_faces = [0.0] * (2 * sites) + velocity.z_faces = [0.0] * (2 * sites) + grid.velocity_field = velocity + simulation.configure_signal_grid(grid) + return simulation + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_flow_carries_cells_inside_the_solve(backend: BackendKind) -> None: + simulation = _uniform_flow(backend, 0.5) + cell = CellInit() + cell.position = Vec3(2.0, 0.0, 0.0) + cell.length, cell.radius, cell.growth_rate = 1.0, 0.25, 0.0 + free = simulation.add_cell(cell) + # A fixed cell downstream, 0.1 clear of the free cell's leading cap. + cell.position = Vec3(3.6, 0.0, 0.0) + cell.fixed = True + simulation.add_cell(cell) + + parameters = ContactDynamicsParameters() + parameters.flow_drift = True + result = simulation.step(0.1, parameters) + # The flow carries the free cell at its own speed while nothing is in the way. + assert math.isclose(simulation.cell(free).position.x, 2.05, abs_tol=1e-5) + for _ in range(9): + result = simulation.step(0.1, parameters) + # The fixed cell stops it at contact, where the flow alone would have + # carried it 0.4 further. + stopped = simulation.cell(free).position.x + assert 2.1 - 2e-3 <= stopped <= 2.1 + 2e-3 + assert result.report.max_overlap < 2e-3 + assert math.isclose(simulation.cell(2).position.x, 3.6, abs_tol=1e-6) + + still = ContactDynamicsParameters() + simulation.step(0.1, still) + assert math.isclose(simulation.cell(free).position.x, stopped, abs_tol=2e-3) + + +def test_flow_drift_requires_a_velocity_field() -> None: + simulation = Simulation() + simulation.add_cell(CellInit()) + parameters = ContactDynamicsParameters() + parameters.flow_drift = True + with pytest.raises(RuntimeError, match="velocity field"): + simulation.step(0.1, parameters) + assert simulation.time == 0.0 + + def test_backend_without_the_feature_rejects_the_step() -> None: for backend in BackendKind: if not backend_available(backend): diff --git a/python/tests/test_microfluidics.py b/python/tests/test_microfluidics.py index 7ac46bb..08535cd 100644 --- a/python/tests/test_microfluidics.py +++ b/python/tests/test_microfluidics.py @@ -208,7 +208,7 @@ def test_trap_example_fills_and_settles_at_a_steady_turnover() -> None: walls = simulation.find_external_contacts().contacts assert walls - # Resting depth of the wall projection, with room for its last sweep. + # What the contact forces press into the walls, which are stiff. assert min(contact.signed_separation for contact in walls) >= -2.0e-3 slack = 2.0e-3 for cell in cells: diff --git a/tests/cpp/contact_dynamics_test.cpp b/tests/cpp/contact_dynamics_test.cpp index ba329d2..678f7cd 100644 --- a/tests/cpp/contact_dynamics_test.cpp +++ b/tests/cpp/contact_dynamics_test.cpp @@ -223,6 +223,9 @@ void test_cell_between_walls_stalls_at_the_stall_load() { ContactDynamicsParameters parameters; parameters.growth.law = GrowthLoadLaw::linear; parameters.growth.stall_load = 4.0F; + // Nothing softer than the walls holds this cell, so the wall stiffness sets + // how finely its load is resolved. + parameters.wall_stiffness = parameters.contact_stiffness; microsimulator::ContactDynamicsResult result; for (int step = 0; step < 200; ++step) { result = simulation.step(0.05F, parameters); @@ -230,7 +233,7 @@ void test_cell_between_walls_stalls_at_the_stall_load() { // The walls leave room for a cylinder of length 3. The cell fills it, to // within the overlap its stall load presses into the two walls, and stops. const auto filled = simulation.cell(id); - const auto wall_overlap = parameters.growth.stall_load / parameters.contact_stiffness; + const auto wall_overlap = parameters.growth.stall_load / parameters.wall_stiffness; assert(filled.length >= 3.0F - 2.0F * parameters.overlap_tolerance); assert(filled.length <= 3.0F + 2.0F * (wall_overlap + parameters.overlap_tolerance)); assert(close(filled.position.x, 0.0F, 1.0e-3F)); From ea9b97e282477509392c2ba8749dceb46038e387 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 11:51:06 +0000 Subject: [PATCH 5/8] Check the trap example's load profile from mouth to back The settled colony's axial load climbs steeply from the trap mouth, levels off where it slows growth, and peaks against the back wall. --- python/tests/test_microfluidics.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/python/tests/test_microfluidics.py b/python/tests/test_microfluidics.py index 08535cd..f9e0050 100644 --- a/python/tests/test_microfluidics.py +++ b/python/tests/test_microfluidics.py @@ -11,6 +11,7 @@ BackendKind, GridShape, ModelContext, + NativeController, SignalGridSpec, SimulationController, Vec3, @@ -184,16 +185,28 @@ def test_trap_example_fills_and_settles_at_a_steady_turnover() -> None: _EXAMPLES / "microfluidic_trap.py", ModelContext(BackendKind.CPU, 0, seed=42), ) - assert isinstance(model, SimulationController) + assert isinstance(model, NativeController) simulation = model.simulation device = _trap_example_device() populations: list[int] = [] + # Axial loads of the settled colony, by depth into the trap from its mouth. + depth_bins = 8 + bin_width = (device.trap_back_x - device.trap_open_x) / depth_bins + loads_by_depth: list[list[float]] = [[] for _ in range(depth_bins)] # Long enough for the colony to fill the trap, press on all three walls, # and shed cells into the channel for several doubling times. for step in range(1, 1501): model.step(0.02) if step % 100 == 0: populations.append(len(simulation.cells())) + if step > 1100 and step % 20 == 0: + result = model.last_contact_dynamics + assert result is not None + for cell in simulation.cells(): + depth = cell.position.x - device.trap_open_x + if depth > 0.0: + index = min(depth_bins - 1, int(depth / bin_width)) + loads_by_depth[index].append(result.axial_loads[cell.slot]) cells = simulation.cells() in_trap = [cell for cell in cells if cell.position.x > device.trap_open_x] @@ -206,6 +219,16 @@ def test_trap_example_fills_and_settles_at_a_steady_turnover() -> None: settled = populations[-5:] assert max(settled) - min(settled) <= 0.15 * max(settled) + # Cells deeper in the trap carry the drag of everything between them and + # the mouth. The load climbs steeply from the mouth, levels off where it + # slows growth, and peaks against the back wall, where cells lie along the + # wall with no open boundary ahead of them. + profile = [sum(loads) / len(loads) for loads in loads_by_depth] + assert profile[:-1] == sorted(profile[:-1]) + assert profile[3] - profile[0] > 2.0 * (profile[6] - profile[3]) + assert profile[-1] > 1.3 * profile[-2] + assert profile[0] < 0.5 * profile[-2] + walls = simulation.find_external_contacts().contacts assert walls # What the contact forces press into the walls, which are stiff. From eada4ff0782a472abdef3e9752468c49075aa057 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 12:02:03 +0000 Subject: [PATCH 6/8] Test buckling and the load-sensitive colony solution A pair of cells spanning a closed chamber turns out of line when its growth ignores load, and a perfectly straight pair with a load response stalls where it is. A colony whose growth falls exponentially with load follows the published continuum pressure profile and expansion speed. --- python/tests/test_contact_dynamics.py | 150 ++++++++++++++++++++++++++ 1 file changed, 150 insertions(+) diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py index 1c965b0..1d041ce 100644 --- a/python/tests/test_contact_dynamics.py +++ b/python/tests/test_contact_dynamics.py @@ -418,6 +418,156 @@ def test_free_colony_matches_the_continuum_pressure_profile(backend: BackendKind assert means[0] > 3.0 * means[-1] +def _divide_and_tilt( + simulation: Simulation, thresholds: dict[int, float], rng: random.Random +) -> None: + """Divide cells at lengths spread around 4, turning daughters slightly in the plane.""" + + for cell in simulation.cells(): + threshold = thresholds.setdefault(cell.id, 4.0 * (1.0 + 0.2 * (rng.random() - 0.5))) + if cell.length < threshold: + continue + for daughter_id in simulation.divide(cell.id, 0.5): + daughter = simulation.cell(daughter_id) + angle = rng.gauss(0.0, 0.02) + x, y = daughter.direction.x, daughter.direction.y + simulation.set_cell_geometry( + daughter_id, + daughter.position, + Vec3( + x * math.cos(angle) - y * math.sin(angle), + x * math.sin(angle) + y * math.cos(angle), + 0.0, + ), + daughter.length, + ) + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_load_sensitive_colony_matches_the_continuum_solution(backend: BackendKind) -> None: + """A colony whose growth falls exponentially with load. + + With areal growth g exp(-s p) and drag zeta per unit area, the radial + pressure of a colony of radius R is + p(r) = (2 zeta g / k) ln(1 / (8 c) - c k r^2), with k = s zeta g and + c = (sqrt(1 + k R^2 / 2) - 1) / (2 k R^2), and its edge advances at + 4 g c R / (1 / (8 c) - c k R^2) (Weady et al. 2024). The axial load on a + cell is the pressure across its diameter, so s is the load sensitivity + times the diameter. + """ + + simulation = _simulation(backend, reserved_capacity=4096) + founder = CellInit() + founder.length = 2.0 + simulation.add_cell(founder) + # The same division rule with nothing to slow it gives the unloaded rate. + unloaded = Simulation(BackendKind.CPU, reserved_capacity=1 << 16) + unloaded.add_cell(founder) + + parameters = ContactDynamicsParameters() + growth = parameters.growth + growth.law = GrowthLoadLaw.EXPONENTIAL + growth.sensitivity = 0.03 + parameters.growth = growth + rng, unloaded_rng = random.Random(1), random.Random(1) + thresholds: dict[int, float] = {} + unloaded_thresholds: dict[int, float] = {} + step_length = 0.05 + edges: list[float] = [] + unloaded_areas: list[float] = [] + result = simulation.step(0.0, parameters) + radii: list[float] = [] + for step in range(280): + _divide_and_tilt(simulation, thresholds, rng) + result = simulation.step(step_length, parameters) + if step < 200: + _divide_and_tilt(unloaded, unloaded_thresholds, unloaded_rng) + unloaded.step(step_length) + unloaded_areas.append(_footprint(unloaded)) + cells = simulation.cells() + center_x = sum(cell.position.x for cell in cells) / len(cells) + center_y = sum(cell.position.y for cell in cells) / len(cells) + radii = [ + math.hypot(cell.position.x - center_x, cell.position.y - center_y) for cell in cells + ] + edges.append(sorted(radii)[int(0.98 * len(radii))]) + + cells = simulation.cells() + assert len(cells) > 800 + colony_radius = edges[-1] + packing = _footprint(simulation) / (math.pi * colony_radius**2) + rate = math.log(unloaded_areas[-1] / unloaded_areas[-21]) / (20 * step_length) + drag_per_area = parameters.drag * packing # per unit diameter, which the load carries + k = growth.sensitivity * drag_per_area * rate + c = (math.sqrt(1.0 + k * colony_radius**2 / 2.0) - 1.0) / (2.0 * k * colony_radius**2) + # The response matters here: the colony is well past the unloaded regime. + assert k * colony_radius**2 > 10.0 + + bin_count = 6 + bins: list[list[float]] = [[] for _ in range(bin_count)] + for radius, cell in zip(radii, cells, strict=True): + bins[min(bin_count - 1, int(radius / colony_radius * bin_count))].append( + result.axial_loads[cell.slot] + ) + for index, loads in enumerate(bins): + position = (index + 0.5) / bin_count * colony_radius + predicted = ( + drag_per_area * rate * (2.0 / k) * math.log(1.0 / (8.0 * c) - c * k * position**2) + ) + unloaded_prediction = drag_per_area * rate * (colony_radius**2 - position**2) / 4.0 + mean = sum(loads) / len(loads) + assert math.isclose(mean, predicted, rel_tol=0.25) + assert mean < 0.6 * unloaded_prediction + + speed = (edges[-1] - edges[-21]) / (20 * step_length) + predicted_speed = ( + rate * 4.0 * c * colony_radius / (1.0 / (8.0 * c) - c * k * colony_radius**2) + ) + assert math.isclose(speed, predicted_speed, rel_tol=0.25) + assert speed < 0.6 * rate * colony_radius / 2.0 + + +def _spanning_pair(backend: BackendKind, tilt: float) -> Simulation: + """Two cells end to end that exactly span a closed 4 by 4 chamber.""" + + simulation = _simulation(backend) + chamber = BoxConstraintInit() + chamber.half_extents = Vec3(2.0, 2.0, 0.6) + chamber.allowed_region = ConstraintRegion.INSIDE + simulation.add_box_constraint(chamber) + cell = CellInit() + cell.length, cell.radius = 1.2, 0.4 + for sign in (-1.0, 1.0): + cell.position = Vec3(sign * 1.0, 0.0, 0.0) + cell.direction = Vec3(math.cos(sign * tilt), math.sin(sign * tilt), 0.0) + simulation.add_cell(cell) + return simulation + + +@pytest.mark.parametrize("backend", BACKENDS) +def test_collinear_cells_spanning_a_chamber_buckle(backend: BackendKind) -> None: + # Growth that ignores load has to go somewhere: the pair turns out of line. + simulation = _spanning_pair(backend, 0.01) + parameters = ContactDynamicsParameters() + for _ in range(12): + result = simulation.step(0.05, parameters) + cells = simulation.cells() + assert all(abs(cell.direction.y) > 0.3 for cell in cells) + assert all(cell.length > 1.2 * 1.6 for cell in cells) + assert result.report.max_overlap < 0.01 + assert all(abs(cell.position.z) < 1e-3 for cell in cells) + + # A perfectly straight pair has no direction to turn in. With a load + # response it stalls where it is. + straight = _spanning_pair(backend, 0.0) + stalling = _stalling(4.0) + for _ in range(40): + straight.step(0.05, stalling) + for cell in straight.cells(): + assert cell.direction.y == 0.0 + assert math.isclose(cell.length, 1.2, abs_tol=5e-3) + + def _uniform_flow(backend: BackendKind, speed: float) -> Simulation: simulation = _simulation(backend) sites = 9 From f1c3cb0cb2906647090527af6ad06c56b45ca0c9 Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 12:02:21 +0000 Subject: [PATCH 7/8] Bind the buckling test's result before its loop --- python/tests/test_contact_dynamics.py | 1 + 1 file changed, 1 insertion(+) diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py index 1d041ce..be5eed5 100644 --- a/python/tests/test_contact_dynamics.py +++ b/python/tests/test_contact_dynamics.py @@ -549,6 +549,7 @@ def test_collinear_cells_spanning_a_chamber_buckle(backend: BackendKind) -> None # Growth that ignores load has to go somewhere: the pair turns out of line. simulation = _spanning_pair(backend, 0.01) parameters = ContactDynamicsParameters() + result = simulation.step(0.0, parameters) for _ in range(12): result = simulation.step(0.05, parameters) cells = simulation.cells() From 3a2d8a5ad32b8a4401187b7063b652eb8918356f Mon Sep 17 00:00:00 2001 From: Mike Arpaia Date: Fri, 13 Nov 2026 12:18:30 +0000 Subject: [PATCH 8/8] Remove the least-squares relaxation Contact dynamics is the only contact solve. The regularized least-squares solve, its conjugate-gradient iteration, the mechanics integration of its corrections, the wall projection, and their Metal and CUDA kernels are gone, with the backend feature, bindings, and tests that served them. No compatibility with the removed solve is kept. MechanicsConfig holds the contact dynamics parameters directly, and a controller configured with it solves growth and contact together on every step. Every example and tutorial model uses it. The planarity diagnostic observes the contact step in place of relaxation passes. FlowDriftParameters replaces the integration parameters as the argument of the standalone flow drift. --- CMakeLists.txt | 25 - cpp/core/device_types.hpp | 2 +- cpp/core/mechanics_integration.cpp | 71 +-- cpp/core/mechanics_solver.hpp | 123 ----- cpp/core/simulation.cpp | 75 +-- cpp/cpu/cpu_backend.cpp | 15 +- cpp/cpu/cpu_constraints.cpp | 75 --- cpp/cpu/cpu_mechanics.cpp | 382 -------------- cpp/cuda/cuda_backend.cu | 306 +----------- cpp/cuda/kernels/contact_dynamics.cu | 10 +- cpp/cuda/kernels/contact_dynamics.cuh | 15 +- cpp/cuda/kernels/mechanics.cu | 342 ------------- cpp/cuda/kernels/mechanics.cuh | 68 --- cpp/cuda/kernels/signals.cu | 21 + cpp/cuda/kernels/signals.cuh | 4 + cpp/include/microsimulator/backend.hpp | 8 +- cpp/include/microsimulator/constraints.hpp | 16 - cpp/include/microsimulator/mechanics.hpp | 85 +--- cpp/include/microsimulator/simulation.hpp | 13 +- cpp/include/microsimulator/types.hpp | 1 - cpp/metal/kernels/contact_dynamics.metal | 4 +- cpp/metal/kernels/mechanics.metal | 213 -------- cpp/metal/metal_backend.mm | 469 +----------------- cpp/python/bindings.cpp | 57 +-- cpp/shared/constants.def | 2 - cpp/shared/device_types.h | 4 +- docs/architecture/0002-contact-mechanics.md | 31 +- docs/architecture/0009-fixed-cells.md | 8 +- docs/architecture/0014-native-controllers.md | 10 +- docs/architecture/0024-biomass-accounting.md | 2 +- docs/architecture/0026-contact-dynamics.md | 8 +- docs/development/validation.md | 4 +- docs/microfluidics.md | 4 +- docs/tutorials/biophysics-and-growth.md | 6 +- docs/tutorials/discrete-state-and-contacts.md | 4 +- docs/tutorials/microfluidics.md | 6 +- docs/tutorials/planarity.md | 18 +- examples/microfluidic_trap.py | 6 +- examples/tutorials/biophysics.py | 2 +- examples/tutorials/biopixel_trap.py | 2 +- examples/tutorials/conjugation.py | 2 +- examples/tutorials/plasmid_segregation.py | 5 +- examples/tutorials/simbol_circuits.py | 2 +- python/src/microsimulator/__init__.py | 18 +- python/src/microsimulator/_core.pyi | 66 +-- python/src/microsimulator/controller.py | 306 +++--------- python/tests/test_contact_dynamics.py | 66 +-- python/tests/test_controller.py | 8 +- python/tests/test_coupling_foundations.py | 4 +- python/tests/test_planarity.py | 24 +- python/tests/test_simulation.py | 76 +-- scripts/diagnose_planarity.py | 59 ++- tests/conformance/README.md | 10 +- .../backend_contract_conformance_test.cpp | 2 +- .../constraint_mechanics_conformance_test.cpp | 256 ---------- .../mechanics_conformance_test.cpp | 215 -------- .../trajectory_conformance_test.cpp | 20 +- tests/cpp/constraint_geometry_test.cpp | 86 ---- tests/cpp/mechanics_integration_test.cpp | 209 -------- tests/cpp/mechanics_operator_test.cpp | 321 ------------ tests/cpp/signal_grid_test.cpp | 4 +- 61 files changed, 318 insertions(+), 3958 deletions(-) delete mode 100644 cpp/core/mechanics_solver.hpp delete mode 100644 cpp/cpu/cpu_mechanics.cpp delete mode 100644 cpp/cuda/kernels/mechanics.cu delete mode 100644 cpp/cuda/kernels/mechanics.cuh delete mode 100644 cpp/metal/kernels/mechanics.metal delete mode 100644 tests/conformance/constraint_mechanics_conformance_test.cpp delete mode 100644 tests/conformance/mechanics_conformance_test.cpp delete mode 100644 tests/cpp/mechanics_integration_test.cpp delete mode 100644 tests/cpp/mechanics_operator_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8af4081..8fcf7d7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -42,7 +42,6 @@ add_library(microsimulator_core STATIC cpp/cpu/cpu_contact_dynamics.cpp cpp/cpu/cpu_coupled.cpp cpp/cpu/cpu_flow.cpp - cpp/cpu/cpu_mechanics.cpp cpp/cpu/cpu_species.cpp ) add_library(microsimulator::core ALIAS microsimulator_core) @@ -105,7 +104,6 @@ if(MICROSIMULATOR_ENABLE_METAL) microsimulator_embed_metal_source(growth cpp/metal/kernels/growth.metal) microsimulator_embed_metal_source(species cpp/metal/kernels/species.metal) microsimulator_embed_metal_source(contacts cpp/metal/kernels/contacts.metal) - microsimulator_embed_metal_source(mechanics cpp/metal/kernels/mechanics.metal) microsimulator_embed_metal_source(contact_dynamics cpp/metal/kernels/contact_dynamics.metal) microsimulator_embed_metal_source(signals cpp/metal/kernels/grid_transport.metal cpp/metal/kernels/signals.metal) @@ -161,7 +159,6 @@ if(MICROSIMULATOR_ENABLE_CUDA) cpp/cuda/kernels/coupled_rates.cu cpp/cuda/kernels/growth.cu cpp/cuda/kernels/flow.cu - cpp/cuda/kernels/mechanics.cu cpp/cuda/kernels/signals.cu cpp/cuda/kernels/species.cu ) @@ -217,18 +214,10 @@ if(MICROSIMULATOR_BUILD_TESTS) target_link_libraries(microsimulator_constraint_geometry_test PRIVATE microsimulator::core) add_test(NAME constraint_geometry COMMAND microsimulator_constraint_geometry_test) - add_executable(microsimulator_mechanics_operator_test tests/cpp/mechanics_operator_test.cpp) - target_link_libraries(microsimulator_mechanics_operator_test PRIVATE microsimulator::core) - add_test(NAME mechanics_operator COMMAND microsimulator_mechanics_operator_test) - add_executable(microsimulator_contact_dynamics_test tests/cpp/contact_dynamics_test.cpp) target_link_libraries(microsimulator_contact_dynamics_test PRIVATE microsimulator::core) add_test(NAME contact_dynamics COMMAND microsimulator_contact_dynamics_test) - add_executable(microsimulator_mechanics_integration_test tests/cpp/mechanics_integration_test.cpp) - target_link_libraries(microsimulator_mechanics_integration_test PRIVATE microsimulator::core) - add_test(NAME mechanics_integration COMMAND microsimulator_mechanics_integration_test) - add_executable(microsimulator_species_test tests/cpp/species_test.cpp) target_link_libraries(microsimulator_species_test PRIVATE microsimulator::core) add_test(NAME species COMMAND microsimulator_species_test) @@ -346,13 +335,6 @@ if(MICROSIMULATOR_BUILD_TESTS) add_test(NAME constraint_conformance COMMAND microsimulator_constraint_conformance_test) set_tests_properties(constraint_conformance PROPERTIES LABELS conformance) - add_executable(microsimulator_mechanics_conformance_test - tests/conformance/mechanics_conformance_test.cpp - ) - target_link_libraries(microsimulator_mechanics_conformance_test PRIVATE microsimulator::core) - add_test(NAME mechanics_conformance COMMAND microsimulator_mechanics_conformance_test) - set_tests_properties(mechanics_conformance PROPERTIES LABELS conformance) - add_executable(microsimulator_contact_dynamics_conformance_test tests/conformance/contact_dynamics_conformance_test.cpp ) @@ -360,13 +342,6 @@ if(MICROSIMULATOR_BUILD_TESTS) add_test(NAME contact_dynamics_conformance COMMAND microsimulator_contact_dynamics_conformance_test) set_tests_properties(contact_dynamics_conformance PROPERTIES LABELS conformance) - add_executable(microsimulator_constraint_mechanics_conformance_test - tests/conformance/constraint_mechanics_conformance_test.cpp - ) - target_link_libraries(microsimulator_constraint_mechanics_conformance_test PRIVATE microsimulator::core) - add_test(NAME constraint_mechanics_conformance COMMAND microsimulator_constraint_mechanics_conformance_test) - set_tests_properties(constraint_mechanics_conformance PROPERTIES LABELS conformance) - if(MICROSIMULATOR_ENABLE_CUDA) add_executable(microsimulator_cuda_runtime_gate_test tests/conformance/cuda_runtime_gate_test.cpp diff --git a/cpp/core/device_types.hpp b/cpp/core/device_types.hpp index 4658d4f..c291a82 100644 --- a/cpp/core/device_types.hpp +++ b/cpp/core/device_types.hpp @@ -42,7 +42,7 @@ static_assert(sizeof(uint2) == 8 && alignof(uint2) == 4); static_assert(sizeof(float4) == 16 && alignof(float4) == 16); static_assert(sizeof(uint4) == 16 && alignof(uint4) == 16); static_assert(sizeof(RateInstruction) == 20); -static_assert(sizeof(MechanicsDofs) == 32); +static_assert(sizeof(ContactResponse) == 32); static_assert(sizeof(ContactRowData) == 80 && offsetof(ContactRowData, first_slot) == 64); static_assert(sizeof(ContactBodyData) == 64); static_assert(sizeof(ContactSolveData) == 32); diff --git a/cpp/core/mechanics_integration.cpp b/cpp/core/mechanics_integration.cpp index 5cea414..18b84e9 100644 --- a/cpp/core/mechanics_integration.cpp +++ b/cpp/core/mechanics_integration.cpp @@ -1,26 +1,10 @@ #include #include -#include #include -#include #include "microsimulator/mechanics.hpp" namespace microsimulator { -namespace { - -struct GeometryUpdate { - Slot slot; - Vec3 position; - Vec3 direction; - float length; -}; - -bool finite(const Vec3& value) { - return std::isfinite(value.x) && std::isfinite(value.y) && std::isfinite(value.z); -} - -} // namespace Vec3 rotate_axis_angle(Vec3 direction, Vec3 rotation, float max_rotation) { const auto magnitude = norm(rotation); @@ -35,60 +19,9 @@ Vec3 rotate_axis_angle(Vec3 direction, Vec3 rotation, float max_rotation) { axis * (dot(axis, direction) * (1.0F - cosine))); } -void validate_mechanics_integration_parameters(const MechanicsIntegrationParameters& parameters) { +void validate_flow_drift_parameters(const FlowDriftParameters& parameters) { if (!std::isfinite(parameters.max_rotation_radians) || parameters.max_rotation_radians < 0.0F) { - throw std::invalid_argument("mechanics rotation limit must be finite and non-negative"); - } -} - -void integrate_mechanics_result(WorldState& state, const MechanicsSolveResult& result, - const MechanicsIntegrationParameters& parameters, - std::span desired_length_increments) { - validate_mechanics_integration_parameters(parameters); - state.validate(); - if (result.corrections.size() != state.size()) { - throw std::invalid_argument("mechanics correction count does not match the world state"); - } - if (!desired_length_increments.empty() && desired_length_increments.size() != state.size()) { - throw std::invalid_argument("desired length increment count does not match the world state"); - } - if (parameters.require_convergence && result.report.status != SolverStatus::converged) { - throw std::runtime_error("mechanics corrections require a converged solver result"); - } - - const auto cells = state.cells(); - std::vector updates; - updates.reserve(cells.size()); - for (std::size_t index = 0; index < cells.size(); ++index) { - const auto& cell = cells[index]; - const auto& correction = result.corrections[index]; - if (!finite(correction.translation) || !finite(correction.rotation) || - !std::isfinite(correction.length)) { - throw std::invalid_argument("mechanics correction must be finite"); - } - const auto desired_increment = - desired_length_increments.empty() ? 0.0F : desired_length_increments[index]; - if (!std::isfinite(desired_increment) || desired_increment < 0.0F) { - throw std::invalid_argument("desired length increments must be finite and non-negative"); - } - const auto applied_length_increment = - desired_length_increments.empty() - ? 0.0F - : (cell.fixed ? desired_increment - : std::max(0.0F, desired_increment + correction.length)); - const auto new_position = cell.fixed ? cell.position : cell.position + correction.translation; - const auto new_direction = cell.fixed ? cell.direction - : rotate_axis_angle(cell.direction, correction.rotation, - parameters.max_rotation_radians); - const auto new_length = cell.length + applied_length_increment; - if (!finite(new_position) || !finite(new_direction) || !std::isfinite(new_length)) { - throw std::overflow_error("mechanics integration produced non-finite geometry"); - } - updates.push_back({cell.slot, new_position, new_direction, new_length}); - } - - for (const auto& update : updates) { - state.set_cell_geometry(update.slot, update.position, update.direction, update.length); + throw std::invalid_argument("flow drift rotation limit must be finite and non-negative"); } } diff --git a/cpp/core/mechanics_solver.hpp b/cpp/core/mechanics_solver.hpp deleted file mode 100644 index a515751..0000000 --- a/cpp/core/mechanics_solver.hpp +++ /dev/null @@ -1,123 +0,0 @@ -#pragma once - -#include -#include -#include -#include -#include -#include - -#include "core/shared_constants.hpp" -#include "microsimulator/mechanics.hpp" - -namespace microsimulator::detail { - -// The vector operations of the conjugate-gradient solve of the regularized -// contact system. A backend supplies them over its own storage for the -// solution, residual, and search direction; the iteration, its convergence -// test, and its breakdown reporting are the same for every backend. -struct MechanicsSolverOperations { - // solution = 0, residual = right-hand side, direction = residual. Returns - // residual . residual. - std::function initialize; - // Applies the system operator to the direction and returns the curvature - // direction . (A direction). - std::function apply_direction; - // solution += alpha direction and residual -= alpha (A direction). Returns - // residual . residual. - std::function update; - // Recomputes residual = right-hand side - A solution from the solution - // itself. Returns residual . residual. - std::function recompute_residual; - // direction = residual + beta direction. - std::function update_direction; -}; - -// Iteration limit of the mechanics solve: the caller's limit, or the number of -// unknowns when the caller leaves it at zero. -[[nodiscard]] inline std::uint32_t mechanics_iteration_limit(const MechanicsParameters& parameters, - std::size_t cell_count) { - if (parameters.max_iterations != 0) { - return parameters.max_iterations; - } - constexpr std::size_t degrees_of_freedom = shared::mechanics_degrees_of_freedom; - if (cell_count > std::numeric_limits::max() / degrees_of_freedom) { - throw std::overflow_error("default mechanics iteration limit exceeds uint32"); - } - return static_cast(cell_count * degrees_of_freedom); -} - -// Solves the system and reports how the iteration ended. A residual that -// reaches the tolerance by recurrence is recomputed from the solution before -// it is accepted; if the recomputed residual misses the tolerance the search -// restarts from it. `cell_count` must be positive. -[[nodiscard]] inline SolverReport solve_mechanics_system( - const MechanicsSolverOperations& operations, std::size_t cell_count, - const MechanicsParameters& parameters) { - const auto count = static_cast(cell_count); - const auto breakdown = [](SolverReport& report, SolverBreakdown reason) { - report.status = SolverStatus::breakdown; - report.breakdown = reason; - }; - - SolverReport report; - auto residual_squared = operations.initialize(); - report.initial_residual_rms = std::sqrt(residual_squared / count); - report.final_residual_rms = report.initial_residual_rms; - if (!std::isfinite(report.initial_residual_rms)) { - breakdown(report, SolverBreakdown::non_finite_residual); - return report; - } - if (report.initial_residual_rms <= parameters.residual_rms_tolerance) { - return report; - } - - report.status = SolverStatus::iteration_limit; - const auto maximum_iterations = mechanics_iteration_limit(parameters, cell_count); - for (std::uint32_t iteration = 0; iteration < maximum_iterations; ++iteration) { - const auto curvature = operations.apply_direction(); - if (!std::isfinite(curvature)) { - breakdown(report, SolverBreakdown::non_finite_curvature); - break; - } - if (curvature <= 0.0F) { - breakdown(report, SolverBreakdown::non_positive_curvature); - break; - } - - const auto alpha = residual_squared / curvature; - const auto next_residual_squared = operations.update(alpha); - report.iterations = iteration + 1; - const auto recurrence_rms = std::sqrt(next_residual_squared / count); - if (!std::isfinite(recurrence_rms)) { - breakdown(report, SolverBreakdown::non_finite_residual); - break; - } - - if (recurrence_rms <= parameters.residual_rms_tolerance) { - residual_squared = operations.recompute_residual(); - const auto recomputed_rms = std::sqrt(residual_squared / count); - if (!std::isfinite(recomputed_rms)) { - breakdown(report, SolverBreakdown::non_finite_residual); - break; - } - if (recomputed_rms <= parameters.residual_rms_tolerance) { - report.status = SolverStatus::converged; - break; - } - operations.update_direction(0.0F); - continue; - } - - operations.update_direction(next_residual_squared / residual_squared); - residual_squared = next_residual_squared; - } - - report.final_residual_rms = std::sqrt(operations.recompute_residual() / count); - if (!std::isfinite(report.final_residual_rms) && report.status != SolverStatus::breakdown) { - breakdown(report, SolverBreakdown::non_finite_residual); - } - return report; -} - -} // namespace microsimulator::detail diff --git a/cpp/core/simulation.cpp b/cpp/core/simulation.cpp index 99f52b2..cdb8ede 100644 --- a/cpp/core/simulation.cpp +++ b/cpp/core/simulation.cpp @@ -178,11 +178,11 @@ std::vector> Simulation::flow_drift_rates(float dt) const { return rates; } -void Simulation::apply_flow_drift(float dt, const MechanicsIntegrationParameters& parameters) { +void Simulation::apply_flow_drift(float dt, const FlowDriftParameters& parameters) { if (!std::isfinite(dt) || dt < 0.0F) { throw std::invalid_argument("time step must be finite and non-negative"); } - validate_mechanics_integration_parameters(parameters); + validate_flow_drift_parameters(parameters); if (!signal_grid_.has_value() || !signal_grid_->spec().velocity_field.has_value()) { throw std::logic_error("flow drift requires a signal grid with a velocity field"); } @@ -471,77 +471,6 @@ ExternalContactGraph Simulation::find_external_contacts( return backend_->find_external_contacts(state_, constraints_, parameters); } -MechanicsSolveResult Simulation::solve_cell_mechanics( - const MechanicsParameters& mechanics_parameters, const ContactParameters& contact_parameters, - const ConstraintContactParameters& constraint_parameters) { - if (!backend_->supports(BackendFeature::cell_mechanics)) { - throw std::runtime_error("selected backend does not implement cell mechanics"); - } - validate_constraint_contact_parameters(constraint_parameters); - if (!constraints_.empty() && !backend_->supports(BackendFeature::external_constraints)) { - throw std::runtime_error("selected backend does not implement external constraints"); - } - const auto contacts = backend_->find_cell_contacts(state_, contact_parameters); - ExternalContactGraph external_contacts(state_.size(), {}); - if (!constraints_.empty()) { - external_contacts = - backend_->find_external_contacts(state_, constraints_, constraint_parameters); - } - return backend_->solve_cell_mechanics(state_, contacts, external_contacts, mechanics_parameters); -} - -MechanicsSolveResult Simulation::relax_cell_mechanics( - const MechanicsParameters& mechanics_parameters, const ContactParameters& contact_parameters, - const MechanicsIntegrationParameters& integration_parameters, - const ConstraintContactParameters& constraint_parameters) { - auto result = - solve_cell_mechanics(mechanics_parameters, contact_parameters, constraint_parameters); - if (constraints_.empty()) { - integrate_mechanics_result(state_, result, integration_parameters); - return result; - } - - // Projection resolves a cell toward the nearest face of the wall it is in, - // which is the face it entered through only while it is less than halfway - // across. The corrections are therefore applied in equal parts that each - // move a cell at most its own radius, projecting after every part, so a - // large correction from a crowded colony cannot carry a cell through a wall. - constexpr std::uint32_t maximum_parts = 16; - std::uint32_t parts = 1; - const auto geometry = state_.geometry_state(); - const auto fixed = state_.cell_attributes().fixed; - for (std::size_t slot = 0; slot < result.corrections.size() && slot < geometry.size(); ++slot) { - const auto travel = norm(result.corrections[slot].translation); - if (fixed[slot] != 0 || !std::isfinite(travel) || geometry.radii[slot] <= 0.0F) { - continue; - } - const auto needed = std::ceil(travel / geometry.radii[slot]); - parts = std::max( - parts, static_cast(std::min(needed, static_cast(maximum_parts)))); - } - if (parts == 1) { - integrate_mechanics_result(state_, result, integration_parameters); - project_cells_out_of_constraints(state_, constraints_, constraint_parameters); - return result; - } - - auto part = result; - for (auto& correction : part.corrections) { - correction.translation = correction.translation * (1.0F / static_cast(parts)); - correction.rotation = {}; - } - for (std::uint32_t index = 0; index < parts; ++index) { - if (index + 1 == parts) { - for (std::size_t slot = 0; slot < part.corrections.size(); ++slot) { - part.corrections[slot].rotation = result.corrections[slot].rotation; - } - } - integrate_mechanics_result(state_, part, integration_parameters); - project_cells_out_of_constraints(state_, constraints_, constraint_parameters); - } - return result; -} - ContactSolveResult Simulation::solve_contact_system(const ContactSystem& system, std::span initial_multipliers, const ContactSolveParameters& parameters) { diff --git a/cpp/cpu/cpu_backend.cpp b/cpp/cpu/cpu_backend.cpp index fcf51c6..66cf157 100644 --- a/cpp/cpu/cpu_backend.cpp +++ b/cpp/cpu/cpu_backend.cpp @@ -20,7 +20,7 @@ class CpuBackend final : public ComputeBackend { [[nodiscard]] bool supports(BackendFeature feature) const noexcept override { return feature == BackendFeature::growth || feature == BackendFeature::species || - feature == BackendFeature::cell_contacts || feature == BackendFeature::cell_mechanics || + feature == BackendFeature::cell_contacts || feature == BackendFeature::external_constraints || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || @@ -57,13 +57,6 @@ class CpuBackend final : public ComputeBackend { return find_external_contacts_cpu(state, constraints, parameters); } - [[nodiscard]] MechanicsSolveResult solve_cell_mechanics( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) override { - return solve_cell_mechanics_cpu(state, contacts, external_contacts, parameters); - } - [[nodiscard]] ContactSolveResult solve_contact_forces( const ContactSystem& system, std::span initial_multipliers, const ContactSolveParameters& parameters) override { @@ -85,12 +78,6 @@ class CpuBackend final : public ComputeBackend { } // namespace -ContactSolveResult ComputeBackend::solve_contact_forces(const ContactSystem&, - std::span, - const ContactSolveParameters&) { - throw std::runtime_error("selected backend does not implement contact dynamics"); -} - std::unique_ptr make_cpu_backend(std::uint32_t device_index) { if (device_index != 0) { throw std::out_of_range("CPU backend exposes only device index 0"); diff --git a/cpp/cpu/cpu_constraints.cpp b/cpp/cpu/cpu_constraints.cpp index daaee0f..53d42ae 100644 --- a/cpp/cpu/cpu_constraints.cpp +++ b/cpp/cpu/cpu_constraints.cpp @@ -16,16 +16,6 @@ namespace { using shared::inverse_sqrt_two; constexpr std::size_t segment_minimization_iterations = shared::segment_minimization_iterations; -// Penetration beyond which a cell is projected, and the depth it is left at. -// A cell resting on a surface stays just inside it, so the contact remains -// active for the next solve and visible to contact analysis; the gap between -// the two depths keeps single-precision rounding from projecting it again. -constexpr float projection_tolerance = 1.0e-4F; -constexpr float resting_penetration = 0.5F * projection_tolerance; -// Sweeps of one move per cell. A cell in a corner needs one per wall meeting -// there. -constexpr std::size_t projection_sweeps = 8; - struct EndpointGeometry { RodContactLocation location; Vec3 centerline_point; @@ -621,69 +611,4 @@ ExternalContactGraph find_external_contact_faces(const WorldState& state, return external_contacts(state, constraints, parameters, ContainerRows::every_face); } -void project_cells_out_of_constraints(WorldState& state, const ConstraintSet& constraints, - const ConstraintContactParameters& parameters) { - if (constraints.empty() || state.empty()) { - return; - } - struct Move { - Slot slot; - Vec3 position; - Vec3 direction; - float length; - }; - // Displacement of each centerline endpoint, negative end first. - std::vector> displacements(state.size()); - std::vector penetrating(state.size()); - std::vector moves; - for (std::size_t sweep = 0; sweep < projection_sweeps; ++sweep) { - const auto graph = find_external_contacts_cpu(state, constraints, parameters); - std::ranges::fill(displacements, std::array{}); - std::ranges::fill(penetrating, false); - for (const auto& contact : graph.contacts()) { - if (contact.signed_separation >= -projection_tolerance) { - continue; - } - const auto slot = static_cast(contact.cell_slot); - const auto displacement = contact.normal * (contact.signed_separation + resting_penetration); - penetrating[slot] = true; - if (contact.location != RodContactLocation::positive) { - displacements[slot][0] = displacements[slot][0] + displacement; - } - if (contact.location != RodContactLocation::negative) { - displacements[slot][1] = displacements[slot][1] + displacement; - } - } - - const auto geometry = state.geometry_state(); - const auto fixed = state.cell_attributes().fixed; - moves.clear(); - for (std::size_t slot = 0; slot < penetrating.size(); ++slot) { - if (!penetrating[slot] || fixed[slot] != 0) { - continue; - } - const auto cell_endpoints = endpoints(geometry, slot); - const auto negative = cell_endpoints[0].centerline_point + displacements[slot][0]; - const auto positive = cell_endpoints[1].centerline_point + displacements[slot][1]; - const auto span = positive - negative; - const auto span_length = norm(span); - moves.push_back({ - static_cast(slot), - (negative + positive) * 0.5F, - span_length > parameters.degeneracy_epsilon - ? span * (1.0F / span_length) - : Vec3{geometry.direction_x[slot], geometry.direction_y[slot], - geometry.direction_z[slot]}, - geometry.lengths[slot], - }); - } - if (moves.empty()) { - return; - } - for (const auto& move : moves) { - state.set_cell_geometry(move.slot, move.position, move.direction, move.length); - } - } -} - } // namespace microsimulator diff --git a/cpp/cpu/cpu_mechanics.cpp b/cpp/cpu/cpu_mechanics.cpp deleted file mode 100644 index 9f0cc10..0000000 --- a/cpp/cpu/cpu_mechanics.cpp +++ /dev/null @@ -1,382 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include -#include - -#include "core/mechanics_solver.hpp" -#include "core/shared_constants.hpp" -#include "microsimulator/mechanics.hpp" - -namespace microsimulator { -namespace { - -constexpr std::size_t degrees_of_freedom = shared::mechanics_degrees_of_freedom; -using Dofs = std::array; -using DofVector = std::vector; - -struct ContactRow { - Slot first_slot; - Slot second_slot{invalid_slot}; - Dofs first; - Dofs second{}; - float right_hand_side; -}; - -[[nodiscard]] bool finite(const Dofs& value) { - for (const auto component : value) { - if (!std::isfinite(component)) { - return false; - } - } - return true; -} - -[[nodiscard]] float dof_dot(const Dofs& left, const Dofs& right) { - float result = 0.0F; - for (std::size_t index = 0; index < degrees_of_freedom; ++index) { - result += left[index] * right[index]; - } - return result; -} - -[[nodiscard]] float vector_dot(const DofVector& left, const DofVector& right) { - float result = 0.0F; - for (std::size_t index = 0; index < left.size(); ++index) { - result += dof_dot(left[index], right[index]); - } - return result; -} - -void add_scaled(Dofs& destination, const Dofs& source, float scale) { - for (std::size_t index = 0; index < degrees_of_freedom; ++index) { - destination[index] += scale * source[index]; - } -} - -void add_scaled(DofVector& destination, const DofVector& source, float scale) { - for (std::size_t index = 0; index < destination.size(); ++index) { - add_scaled(destination[index], source[index], scale); - } -} - -[[nodiscard]] Dofs make_jacobian(const Vec3& normal, const Vec3& arm, const Vec3& axis, - float total_length, float weight) { - const auto angular = cross(arm, normal); - const auto length = dot(axis, arm) * dot(axis, normal) / total_length; - return { - weight * normal.x, weight * normal.y, weight * normal.z, weight * angular.x, - weight * angular.y, weight * angular.z, weight * length, - }; -} - -[[nodiscard]] Dofs flatten(const CellCorrection& correction) { - return { - correction.translation.x, correction.translation.y, correction.translation.z, - correction.rotation.x, correction.rotation.y, correction.rotation.z, - correction.length, - }; -} - -[[nodiscard]] CellCorrection unflatten(const Dofs& value) { - return { - .translation = {value[0], value[1], value[2]}, - .rotation = {value[3], value[4], value[5]}, - .length = value[6], - }; -} - -[[nodiscard]] DofVector flatten(std::span values) { - DofVector result; - result.reserve(values.size()); - for (const auto& value : values) { - const auto flattened = flatten(value); - if (!finite(flattened)) { - throw std::invalid_argument("mechanics input correction must be finite"); - } - result.push_back(flattened); - } - return result; -} - -[[nodiscard]] std::vector unflatten(const DofVector& values) { - std::vector result; - result.reserve(values.size()); - for (const auto& value : values) { - result.push_back(unflatten(value)); - } - return result; -} - -class CpuMechanicsSystem { - public: - CpuMechanicsSystem(const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) - : geometry_(state.geometry_state()), parameters_(parameters) { - fixed_ = state.cell_attributes().fixed; - state.validate(); - validate_mechanics_parameters(parameters_); - if (contacts.cell_count() != geometry_.size()) { - throw std::invalid_argument("contact graph and world state cell counts disagree"); - } - if (external_contacts.cell_count() != geometry_.size()) { - throw std::invalid_argument("external contact graph and world state cell counts disagree"); - } - if (external_contacts.size() > std::numeric_limits::max() - contacts.size()) { - throw std::overflow_error("mechanics contact row count overflow"); - } - - rows_.reserve(contacts.size() + external_contacts.size()); - for (const auto& contact : contacts.contacts()) { - const auto first = static_cast(contact.first_slot); - const auto second = static_cast(contact.second_slot); - if (geometry_.ids[first] != contact.first_id || geometry_.ids[second] != contact.second_id) { - throw std::invalid_argument("contact graph identifiers do not match current state slots"); - } - - const Vec3 first_center{geometry_.position_x[first], geometry_.position_y[first], - geometry_.position_z[first]}; - const Vec3 second_center{geometry_.position_x[second], geometry_.position_y[second], - geometry_.position_z[second]}; - const Vec3 first_axis{geometry_.direction_x[first], geometry_.direction_y[first], - geometry_.direction_z[first]}; - const Vec3 second_axis{geometry_.direction_x[second], geometry_.direction_y[second], - geometry_.direction_z[second]}; - const auto first_total_length = geometry_.lengths[first] + 2.0F * geometry_.radii[first]; - const auto second_total_length = geometry_.lengths[second] + 2.0F * geometry_.radii[second]; - - rows_.push_back({ - .first_slot = contact.first_slot, - .second_slot = contact.second_slot, - .first = make_jacobian(contact.normal, contact.point_on_first - first_center, first_axis, - first_total_length, contact.weight), - .second = make_jacobian(contact.normal, contact.point_on_first - second_center, - second_axis, second_total_length, contact.weight), - .right_hand_side = contact.weight * contact.signed_separation, - }); - } - - for (const auto& contact : external_contacts.contacts()) { - const auto cell = static_cast(contact.cell_slot); - if (geometry_.ids[cell] != contact.cell_id) { - throw std::invalid_argument( - "external contact graph identifiers do not match current state slots"); - } - - const Vec3 center{geometry_.position_x[cell], geometry_.position_y[cell], - geometry_.position_z[cell]}; - const Vec3 axis{geometry_.direction_x[cell], geometry_.direction_y[cell], - geometry_.direction_z[cell]}; - const auto total_length = geometry_.lengths[cell] + 2.0F * geometry_.radii[cell]; - rows_.push_back({ - .first_slot = contact.cell_slot, - .first = make_jacobian(contact.normal, contact.point_on_cell - center, axis, total_length, - contact.weight), - .right_hand_side = contact.weight * contact.signed_separation, - }); - } - } - - [[nodiscard]] std::size_t cell_count() const noexcept { - return geometry_.size(); - } - - void apply(const DofVector& input, DofVector& output) const { - auto projected = input; - for (std::size_t index = 0; index < cell_count(); ++index) { - if (fixed_[index] != 0) { - projected[index] = {}; - } - } - output.assign(cell_count(), Dofs{}); - for (const auto& row : rows_) { - const auto first = static_cast(row.first_slot); - auto row_value = dof_dot(row.first, projected[first]); - if (row.second_slot != invalid_slot) { - row_value -= dof_dot(row.second, projected[static_cast(row.second_slot)]); - } - add_scaled(output[first], row.first, row_value); - if (row.second_slot != invalid_slot) { - add_scaled(output[static_cast(row.second_slot)], row.second, -row_value); - } - } - - const auto regularization = 1.0F / parameters_.gamma; - for (std::size_t index = 0; index < cell_count(); ++index) { - if (fixed_[index] != 0) { - output[index] = input[index]; - continue; - } - const Vec3 axis{geometry_.direction_x[index], geometry_.direction_y[index], - geometry_.direction_z[index]}; - const Vec3 rotation{input[index][3], input[index][4], input[index][5]}; - const auto total_length = geometry_.lengths[index] + 2.0F * geometry_.radii[index]; - const auto mass = parameters_.mu_a * total_length; - const auto radius = geometry_.radii[index]; - const auto axial_inertia = 0.5F * mass * radius * radius; - const auto transverse_inertia = - mass * ((total_length * total_length) + 3.0F * radius * radius) / 12.0F; - const auto inertia_rotation = - rotation * transverse_inertia + - axis * ((axial_inertia - transverse_inertia) * dot(axis, rotation)); - - output[index][0] += regularization * mass * input[index][0]; - output[index][1] += regularization * mass * input[index][1]; - output[index][2] += regularization * mass * input[index][2]; - output[index][3] += regularization * inertia_rotation.x; - output[index][4] += regularization * inertia_rotation.y; - output[index][5] += regularization * inertia_rotation.z; - output[index][6] += input[index][6]; - } - } - - [[nodiscard]] DofVector right_hand_side() const { - DofVector result(cell_count()); - for (const auto& row : rows_) { - const auto first = static_cast(row.first_slot); - add_scaled(result[first], row.first, row.right_hand_side); - if (row.second_slot != invalid_slot) { - add_scaled(result[static_cast(row.second_slot)], row.second, - -row.right_hand_side); - } - } - for (std::size_t index = 0; index < cell_count(); ++index) { - if (fixed_[index] != 0) { - result[index] = {}; - } - } - return result; - } - - private: - CellGeometryView geometry_; - std::span fixed_; - MechanicsParameters parameters_; - std::vector rows_; -}; - -[[nodiscard]] DofVector exact_residual(const CpuMechanicsSystem& system, - const DofVector& right_hand_side, - const DofVector& solution) { - DofVector applied; - system.apply(solution, applied); - auto residual = right_hand_side; - add_scaled(residual, applied, -1.0F); - return residual; -} - -} // namespace - -void validate_mechanics_parameters(const MechanicsParameters& parameters) { - if (!std::isfinite(parameters.mu_a) || parameters.mu_a <= 0.0F) { - throw std::invalid_argument("mechanics mu_a must be finite and positive"); - } - if (!std::isfinite(parameters.gamma) || parameters.gamma <= 0.0F) { - throw std::invalid_argument("mechanics gamma must be finite and positive"); - } - if (!std::isfinite(parameters.residual_rms_tolerance) || - parameters.residual_rms_tolerance < 0.0F) { - throw std::invalid_argument("mechanics residual tolerance must be finite and non-negative"); - } -} - -std::vector apply_mechanics_operator_cpu( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, std::span input, - const MechanicsParameters& parameters) { - const CpuMechanicsSystem system(state, contacts, external_contacts, parameters); - if (input.size() != system.cell_count()) { - throw std::invalid_argument("mechanics input size does not match the world state"); - } - const auto flat_input = flatten(input); - DofVector output; - system.apply(flat_input, output); - return unflatten(output); -} - -std::vector apply_mechanics_operator_cpu(const WorldState& state, - const ContactGraph& contacts, - std::span input, - const MechanicsParameters& parameters) { - return apply_mechanics_operator_cpu(state, contacts, ExternalContactGraph(state.size(), {}), - input, parameters); -} - -std::vector build_mechanics_rhs_cpu(const WorldState& state, - const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) { - const CpuMechanicsSystem system(state, contacts, external_contacts, parameters); - return unflatten(system.right_hand_side()); -} - -std::vector build_mechanics_rhs_cpu(const WorldState& state, - const ContactGraph& contacts, - const MechanicsParameters& parameters) { - return build_mechanics_rhs_cpu(state, contacts, ExternalContactGraph(state.size(), {}), - parameters); -} - -MechanicsSolveResult solve_cell_mechanics_cpu(const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) { - const CpuMechanicsSystem system(state, contacts, external_contacts, parameters); - const auto right_hand_side = system.right_hand_side(); - DofVector solution(system.cell_count()); - auto residual = right_hand_side; - auto search_direction = residual; - DofVector applied; - - MechanicsSolveResult result; - result.corrections.resize(system.cell_count()); - if (system.cell_count() == 0) { - return result; - } - const detail::MechanicsSolverOperations operations{ - .initialize = [&] { return vector_dot(residual, residual); }, - .apply_direction = - [&] { - system.apply(search_direction, applied); - return vector_dot(search_direction, applied); - }, - .update = - [&](float alpha) { - add_scaled(solution, search_direction, alpha); - add_scaled(residual, applied, -alpha); - return vector_dot(residual, residual); - }, - .recompute_residual = - [&] { - residual = exact_residual(system, right_hand_side, solution); - return vector_dot(residual, residual); - }, - .update_direction = - [&](float beta) { - if (beta == 0.0F) { - search_direction = residual; - return; - } - for (std::size_t index = 0; index < search_direction.size(); ++index) { - for (std::size_t component = 0; component < degrees_of_freedom; ++component) { - search_direction[index][component] = - residual[index][component] + beta * search_direction[index][component]; - } - } - }, - }; - result.report = detail::solve_mechanics_system(operations, system.cell_count(), parameters); - result.corrections = unflatten(solution); - return result; -} - -MechanicsSolveResult solve_cell_mechanics_cpu(const WorldState& state, const ContactGraph& contacts, - const MechanicsParameters& parameters) { - return solve_cell_mechanics_cpu(state, contacts, ExternalContactGraph(state.size(), {}), - parameters); -} - -} // namespace microsimulator diff --git a/cpp/cuda/cuda_backend.cu b/cpp/cuda/cuda_backend.cu index 065b1bd..9ae4756 100644 --- a/cpp/cuda/cuda_backend.cu +++ b/cpp/cuda/cuda_backend.cu @@ -16,14 +16,12 @@ #include #include "core/contact_solver.hpp" -#include "core/mechanics_solver.hpp" #include "core/signal_jacobi.hpp" #include "cuda_flow.cuh" #include "kernels/contact_dynamics.cuh" #include "kernels/contacts.cuh" #include "kernels/coupled_rates.cuh" #include "kernels/growth.cuh" -#include "kernels/mechanics.cuh" #include "kernels/signals.cuh" #include "kernels/species.cuh" #include "microsimulator/backend.hpp" @@ -127,8 +125,7 @@ class CudaBackend final : public ComputeBackend { [[nodiscard]] bool supports(BackendFeature feature) const noexcept override { return feature == BackendFeature::growth || feature == BackendFeature::species || feature == BackendFeature::cell_contacts || - feature == BackendFeature::external_constraints || - feature == BackendFeature::cell_mechanics || feature == BackendFeature::signals || + feature == BackendFeature::external_constraints || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || feature == BackendFeature::resolved_flow || feature == BackendFeature::contact_dynamics; @@ -751,61 +748,6 @@ class CudaBackend final : public ComputeBackend { return download_external_contacts(geometry.size(), contact_count); } - [[nodiscard]] MechanicsSolveResult solve_cell_mechanics( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) override { - activate_device(); - validate_mechanics_parameters(parameters); - state.validate(); - const auto geometry = state.geometry_state(); - if (contacts.cell_count() != geometry.size()) { - throw std::invalid_argument("contact graph and world state cell counts disagree"); - } - if (external_contacts.cell_count() != geometry.size()) { - throw std::invalid_argument("external contact graph and world state cell counts disagree"); - } - if (external_contacts.size() > std::numeric_limits::max() - contacts.size()) { - throw std::overflow_error("CUDA mechanics row count overflow"); - } - const auto row_count = contacts.size() + external_contacts.size(); - if (geometry.size() > std::numeric_limits::max() || - row_count > std::numeric_limits::max() / 2) { - throw std::overflow_error("CUDA mechanics exceeds the uint32 index space"); - } - - MechanicsSolveResult result; - result.corrections.resize(geometry.size()); - if (geometry.size() == 0 || row_count == 0) { - return result; - } - - validate_mechanics_contacts(geometry, contacts); - validate_external_mechanics_contacts(geometry, external_contacts); - ensure_contact_cell_capacity(geometry.size()); - ensure_contact_output_capacity(row_count); - ensure_mechanics_capacity(geometry.size(), row_count); - upload_contact_cells(geometry); - upload_mechanics_fixed(state.cell_attributes().fixed); - upload_mechanics_contacts(contacts, external_contacts); - upload_mechanics_incidence(contacts, external_contacts); - - const auto cell_count = static_cast(geometry.size()); - const auto contact_count = static_cast(row_count); - const detail::MechanicsSolverOperations operations{ - .initialize = [&] { return initialize_mechanics(cell_count, contact_count); }, - .apply_direction = - [&] { return apply_search_direction(cell_count, contact_count, parameters); }, - .update = [&](float alpha) { return update_solution_residual(cell_count, alpha); }, - .recompute_residual = - [&] { return recompute_residual(cell_count, contact_count, parameters); }, - .update_direction = [&](float beta) { update_search_direction(cell_count, beta); }, - }; - result.report = detail::solve_mechanics_system(operations, geometry.size(), parameters); - result.corrections = download_mechanics_solution(geometry.size()); - return result; - } - [[nodiscard]] ContactSolveResult solve_contact_forces( const ContactSystem& system, std::span initial_multipliers, const ContactSolveParameters& parameters) override { @@ -1227,140 +1169,6 @@ class CudaBackend final : public ComputeBackend { return ExternalContactGraph(cell_count, std::move(contacts)); } - static void validate_mechanics_contacts(const CellGeometryView& geometry, - const ContactGraph& contacts) { - for (const auto& contact : contacts.contacts()) { - const auto first = static_cast(contact.first_slot); - const auto second = static_cast(contact.second_slot); - if (geometry.ids[first] != contact.first_id || geometry.ids[second] != contact.second_id) { - throw std::invalid_argument("contact graph identifiers do not match current state slots"); - } - } - } - - static void validate_external_mechanics_contacts(const CellGeometryView& geometry, - const ExternalContactGraph& contacts) { - for (const auto& contact : contacts.contacts()) { - const auto cell = static_cast(contact.cell_slot); - if (geometry.ids[cell] != contact.cell_id) { - throw std::invalid_argument( - "external contact graph identifiers do not match current state slots"); - } - } - } - - void ensure_mechanics_capacity(std::size_t cell_count, std::size_t contact_count) { - mechanics_incidence_offsets_.reserve(cell_count + 1, "mechanics incidence offsets"); - mechanics_fixed_.reserve(cell_count, "mechanics fixed flags"); - mechanics_solution_.reserve(cell_count, "mechanics solution"); - mechanics_rhs_.reserve(cell_count, "mechanics right-hand side"); - mechanics_residual_.reserve(cell_count, "mechanics residual"); - mechanics_search_.reserve(cell_count, "mechanics search direction"); - mechanics_applied_.reserve(cell_count, "mechanics applied vector"); - mechanics_dot_terms_.reserve(cell_count, "mechanics dot terms"); - mechanics_reduce_a_.reserve(cell_count, "mechanics reduction A"); - mechanics_reduce_b_.reserve(cell_count, "mechanics reduction B"); - mechanics_first_rows_.reserve(contact_count, "mechanics first Jacobian rows"); - mechanics_second_rows_.reserve(contact_count, "mechanics second Jacobian rows"); - mechanics_row_values_.reserve(contact_count, "mechanics row values"); - mechanics_row_rhs_.reserve(contact_count, "mechanics row right-hand side"); - mechanics_incidence_indices_.reserve(contact_count * 2, "mechanics incidence indices"); - } - - void upload_mechanics_fixed(std::span fixed) { - check_cuda(cudaMemcpyAsync(mechanics_fixed_.data(), fixed.data(), fixed.size_bytes(), - cudaMemcpyHostToDevice, stream_), - "failed to upload CUDA mechanics fixed flags"); - } - - void upload_mechanics_contacts(const ContactGraph& contacts, - const ExternalContactGraph& external_contacts) { - const auto row_count = contacts.size() + external_contacts.size(); - std::vector first_slots(row_count); - std::vector second_slots(row_count); - std::vector points(row_count); - std::vector normals(row_count); - std::vector separations(row_count); - std::vector weights(row_count); - for (std::size_t index = 0; index < contacts.size(); ++index) { - const auto& contact = contacts.contacts()[index]; - first_slots[index] = contact.first_slot; - second_slots[index] = contact.second_slot; - points[index] = make_float4(contact.point_on_first.x, contact.point_on_first.y, - contact.point_on_first.z, 0.0F); - normals[index] = make_float4(contact.normal.x, contact.normal.y, contact.normal.z, 0.0F); - separations[index] = contact.signed_separation; - weights[index] = contact.weight; - } - for (std::size_t index = 0; index < external_contacts.size(); ++index) { - const auto output_index = contacts.size() + index; - const auto& contact = external_contacts.contacts()[index]; - first_slots[output_index] = contact.cell_slot; - second_slots[output_index] = invalid_slot; - points[output_index] = make_float4(contact.point_on_cell.x, contact.point_on_cell.y, - contact.point_on_cell.z, 0.0F); - normals[output_index] = - make_float4(contact.normal.x, contact.normal.y, contact.normal.z, 0.0F); - separations[output_index] = contact.signed_separation; - weights[output_index] = contact.weight; - } - copy_to_device(contact_first_slots_, first_slots, - "failed to upload CUDA mechanics first slots"); - copy_to_device(contact_second_slots_, second_slots, - "failed to upload CUDA mechanics second slots"); - copy_to_device(contact_points_, points, "failed to upload CUDA mechanics contact points"); - copy_to_device(contact_normals_, normals, "failed to upload CUDA mechanics contact normals"); - copy_to_device(contact_separations_, separations, - "failed to upload CUDA mechanics contact separations"); - copy_to_device(contact_weights_, weights, "failed to upload CUDA mechanics contact weights"); - check_cuda(cudaStreamSynchronize(stream_), "CUDA mechanics contact upload failed"); - } - - void upload_mechanics_incidence(const ContactGraph& contacts, - const ExternalContactGraph& external_contacts) { - std::vector offsets(contacts.cell_count() + 1); - std::vector indices(contacts.size() * 2 + external_contacts.size()); - std::uint32_t cursor = 0; - for (std::size_t slot = 0; slot < contacts.cell_count(); ++slot) { - offsets[slot] = cursor; - for (const auto contact_index : contacts.incident_contact_indices(static_cast(slot))) { - indices[cursor++] = static_cast(contact_index); - } - for (const auto contact_index : - external_contacts.incident_contact_indices(static_cast(slot))) { - indices[cursor++] = static_cast(contacts.size() + contact_index); - } - } - offsets[contacts.cell_count()] = cursor; - if (cursor != contacts.size() * 2 + external_contacts.size()) { - throw std::logic_error("contact incidence size is inconsistent"); - } - copy_to_device(mechanics_incidence_offsets_, offsets, - "failed to upload CUDA mechanics incidence offsets"); - copy_to_device(mechanics_incidence_indices_, indices, - "failed to upload CUDA mechanics incidence indices"); - check_cuda(cudaStreamSynchronize(stream_), "CUDA mechanics incidence upload failed"); - } - - void apply_mechanics_operator(const cuda::MechanicsDofsGpu* input, cuda::MechanicsDofsGpu* output, - std::uint32_t cell_count, std::uint32_t contact_count, - const MechanicsParameters& parameters) { - cuda::launch_apply_mechanics_b(mechanics_first_rows_.data(), mechanics_second_rows_.data(), - contact_first_slots_.data(), contact_second_slots_.data(), input, - mechanics_fixed_.data(), mechanics_row_values_.data(), - contact_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-B kernel"); - cuda::launch_apply_mechanics_transpose( - mechanics_first_rows_.data(), mechanics_second_rows_.data(), mechanics_row_values_.data(), - mechanics_incidence_offsets_.data(), mechanics_incidence_indices_.data(), - contact_first_slots_.data(), output, cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-transpose kernel"); - cuda::launch_add_mechanics_regularizer(contact_axes_.data(), contact_geometry_.data(), input, - output, mechanics_fixed_.data(), parameters.mu_a, - parameters.gamma, cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-regularizer kernel"); - } - void ensure_signal_solve_capacity(std::uint32_t level_count) { signal_cn_a_.reserve(level_count, "signal Jacobi field A"); signal_cn_b_.reserve(level_count, "signal Jacobi field B"); @@ -1468,85 +1276,6 @@ class CudaBackend final : public ComputeBackend { return {current, report}; } - [[nodiscard]] float reduce_mechanics_dot(const cuda::MechanicsDofsGpu* left, - const cuda::MechanicsDofsGpu* right, - std::uint32_t cell_count, const char* operation) { - cuda::launch_mechanics_dot_terms(left, right, mechanics_dot_terms_.data(), cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-dot kernel"); - const float* input = mechanics_dot_terms_.data(); - float* output = mechanics_reduce_a_.data(); - auto element_count = cell_count; - while (element_count > 1) { - cuda::launch_reduce_sum_pairs(input, output, element_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-reduction kernel"); - input = output; - output = output == mechanics_reduce_a_.data() ? mechanics_reduce_b_.data() - : mechanics_reduce_a_.data(); - element_count = (element_count + 1) / 2; - } - float result = 0.0F; - check_cuda(cudaMemcpyAsync(&result, input, sizeof(result), cudaMemcpyDeviceToHost, stream_), - "failed to download a CUDA mechanics reduction"); - check_cuda(cudaStreamSynchronize(stream_), operation); - return result; - } - - [[nodiscard]] float initialize_mechanics(std::uint32_t cell_count, std::uint32_t contact_count) { - cuda::launch_build_mechanics_rows( - contact_centers_.data(), contact_axes_.data(), contact_geometry_.data(), - contact_first_slots_.data(), contact_second_slots_.data(), contact_points_.data(), - contact_normals_.data(), contact_separations_.data(), contact_weights_.data(), - mechanics_first_rows_.data(), mechanics_second_rows_.data(), mechanics_row_rhs_.data(), - contact_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-row kernel"); - cuda::launch_apply_mechanics_transpose( - mechanics_first_rows_.data(), mechanics_second_rows_.data(), mechanics_row_rhs_.data(), - mechanics_incidence_offsets_.data(), mechanics_incidence_indices_.data(), - contact_first_slots_.data(), mechanics_rhs_.data(), cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-RHS kernel"); - cuda::launch_initialize_mechanics_vectors(mechanics_rhs_.data(), mechanics_solution_.data(), - mechanics_residual_.data(), mechanics_search_.data(), - mechanics_fixed_.data(), cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-initialize kernel"); - return reduce_mechanics_dot(mechanics_residual_.data(), mechanics_residual_.data(), cell_count, - "CUDA mechanics initialization failed"); - } - - [[nodiscard]] float apply_search_direction(std::uint32_t cell_count, std::uint32_t contact_count, - const MechanicsParameters& parameters) { - apply_mechanics_operator(mechanics_search_.data(), mechanics_applied_.data(), cell_count, - contact_count, parameters); - return reduce_mechanics_dot(mechanics_search_.data(), mechanics_applied_.data(), cell_count, - "CUDA mechanics operator application failed"); - } - - [[nodiscard]] float update_solution_residual(std::uint32_t cell_count, float alpha) { - cuda::launch_update_mechanics_solution_residual( - mechanics_solution_.data(), mechanics_residual_.data(), mechanics_search_.data(), - mechanics_applied_.data(), alpha, cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-update kernel"); - return reduce_mechanics_dot(mechanics_residual_.data(), mechanics_residual_.data(), cell_count, - "CUDA mechanics update failed"); - } - - void update_search_direction(std::uint32_t cell_count, float beta) { - cuda::launch_update_mechanics_search_direction( - mechanics_residual_.data(), mechanics_search_.data(), beta, cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-search kernel"); - check_cuda(cudaStreamSynchronize(stream_), "CUDA mechanics search update failed"); - } - - [[nodiscard]] float recompute_residual(std::uint32_t cell_count, std::uint32_t contact_count, - const MechanicsParameters& parameters) { - apply_mechanics_operator(mechanics_solution_.data(), mechanics_applied_.data(), cell_count, - contact_count, parameters); - cuda::launch_subtract_mechanics_vectors(mechanics_rhs_.data(), mechanics_applied_.data(), - mechanics_residual_.data(), cell_count, stream_); - check_cuda(cudaGetLastError(), "failed to launch the CUDA mechanics-residual kernel"); - return reduce_mechanics_dot(mechanics_residual_.data(), mechanics_residual_.data(), cell_count, - "CUDA mechanics residual recomputation failed"); - } - void ensure_contact_dynamics_capacity(std::size_t body_count, std::size_t row_count) { contact_bodies_.reserve(body_count, "contact bodies"); contact_response_.reserve(body_count, "contact response"); @@ -1659,22 +1388,6 @@ class CudaBackend final : public ComputeBackend { }; } - [[nodiscard]] std::vector download_mechanics_solution(std::size_t cell_count) { - std::vector values(cell_count); - copy_to_host(values, mechanics_solution_, "failed to download CUDA mechanics solution"); - check_cuda(cudaStreamSynchronize(stream_), "CUDA mechanics solution download failed"); - std::vector result; - result.reserve(cell_count); - for (const auto& value : values) { - result.push_back({ - .translation = {value.linear_length.x, value.linear_length.y, value.linear_length.z}, - .rotation = {value.rotation.x, value.rotation.y, value.rotation.z}, - .length = value.linear_length.w, - }); - } - return result; - } - template void copy_to_device(CudaBuffer& destination, const std::vector& source, const char* operation) { @@ -1780,24 +1493,9 @@ class CudaBackend final : public ComputeBackend { CudaBuffer contact_separations_; CudaBuffer contact_weights_; - CudaBuffer mechanics_first_rows_; - CudaBuffer mechanics_second_rows_; - CudaBuffer mechanics_row_values_; - CudaBuffer mechanics_row_rhs_; - CudaBuffer mechanics_incidence_offsets_; - CudaBuffer mechanics_incidence_indices_; - CudaBuffer mechanics_fixed_; - CudaBuffer mechanics_solution_; - CudaBuffer mechanics_rhs_; - CudaBuffer mechanics_residual_; - CudaBuffer mechanics_search_; - CudaBuffer mechanics_applied_; - CudaBuffer mechanics_dot_terms_; - CudaBuffer mechanics_reduce_a_; - CudaBuffer mechanics_reduce_b_; CudaBuffer contact_rows_; CudaBuffer contact_bodies_; - CudaBuffer contact_response_; + CudaBuffer contact_response_; CudaBuffer contact_incidence_offsets_; CudaBuffer contact_incidence_entries_; CudaBuffer contact_terms_; diff --git a/cpp/cuda/kernels/contact_dynamics.cu b/cpp/cuda/kernels/contact_dynamics.cu index ccb525b..600c417 100644 --- a/cpp/cuda/kernels/contact_dynamics.cu +++ b/cpp/cuda/kernels/contact_dynamics.cu @@ -38,8 +38,8 @@ __global__ void contact_project(const float* multipliers, const float* gaps, flo __global__ void contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, const float* multipliers, const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, - ContactSolveGpu solve) { + const std::uint32_t* incidence_entries, + ContactResponseGpu* response, ContactSolveGpu solve) { const std::uint32_t body = blockIdx.x * blockDim.x + threadIdx.x; if (body >= solve.body_count) { return; @@ -86,7 +86,7 @@ __global__ void contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* drift_angular.z + torque_z * transverse + axis.z * along, load); } -__global__ void contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, +__global__ void contact_gaps(const ContactRowGpu* rows, const ContactResponseGpu* response, const float* multipliers, float* gaps, const float* previous_multipliers, const float* previous_gaps, float4* terms, ContactSolveGpu solve, bool initial) { @@ -150,13 +150,13 @@ void launch_contact_project(const float* multipliers, const float* gaps, float* void launch_contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, const float* multipliers, const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, + const std::uint32_t* incidence_entries, ContactResponseGpu* response, ContactSolveGpu solve, cudaStream_t stream) { contact_respond<<>>( rows, bodies, multipliers, incidence_offsets, incidence_entries, response, solve); } -void launch_contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, +void launch_contact_gaps(const ContactRowGpu* rows, const ContactResponseGpu* response, const float* multipliers, float* gaps, const float* previous_multipliers, const float* previous_gaps, float4* terms, ContactSolveGpu solve, bool initial, cudaStream_t stream) { diff --git a/cpp/cuda/kernels/contact_dynamics.cuh b/cpp/cuda/kernels/contact_dynamics.cuh index 4965108..af4f5e5 100644 --- a/cpp/cuda/kernels/contact_dynamics.cuh +++ b/cpp/cuda/kernels/contact_dynamics.cuh @@ -4,10 +4,17 @@ #include -#include "mechanics.cuh" - namespace microsimulator::cuda { +// What a set of contact multipliers does to one cell: its velocity with the +// elongation rate in w, and its angular velocity with the axial load in w. +struct alignas(16) ContactResponseGpu { + float4 linear_length; + float4 rotation; +}; + +static_assert(sizeof(ContactResponseGpu) == 32); + // One row of the contact dynamics solve. The w components carry the row's // scalars: the first and second length levers ride on the linear parts, the // offset on the first angular part, and the compliance on the second. @@ -56,14 +63,14 @@ void launch_contact_project(const float* multipliers, const float* gaps, float* // the angular velocity and load in `rotation`. void launch_contact_respond(const ContactRowGpu* rows, const ContactBodyGpu* bodies, const float* multipliers, const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_entries, MechanicsDofsGpu* response, + const std::uint32_t* incidence_entries, ContactResponseGpu* response, ContactSolveGpu solve, cudaStream_t stream); // The gap of every row under the multipliers whose response is given, and the // terms of the step that led to them: step . step, step . change, // change . change, and the row's residual. The initial evaluation has no // previous step and writes only the residual. -void launch_contact_gaps(const ContactRowGpu* rows, const MechanicsDofsGpu* response, +void launch_contact_gaps(const ContactRowGpu* rows, const ContactResponseGpu* response, const float* multipliers, float* gaps, const float* previous_multipliers, const float* previous_gaps, float4* terms, ContactSolveGpu solve, bool initial, cudaStream_t stream); diff --git a/cpp/cuda/kernels/mechanics.cu b/cpp/cuda/kernels/mechanics.cu deleted file mode 100644 index 6d14c3c..0000000 --- a/cpp/cuda/kernels/mechanics.cu +++ /dev/null @@ -1,342 +0,0 @@ -#include "mechanics.cuh" - -namespace microsimulator::cuda { -namespace { - -constexpr std::uint32_t threads_per_block = 256; - -__device__ float3 add(float3 left, float3 right) { - return make_float3(left.x + right.x, left.y + right.y, left.z + right.z); -} - -__device__ float3 subtract(float3 left, float3 right) { - return make_float3(left.x - right.x, left.y - right.y, left.z - right.z); -} - -__device__ float3 multiply(float3 value, float scale) { - return make_float3(value.x * scale, value.y * scale, value.z * scale); -} - -__device__ float dot_product(float3 left, float3 right) { - return left.x * right.x + left.y * right.y + left.z * right.z; -} - -__device__ float3 cross_product(float3 left, float3 right) { - return make_float3(left.y * right.z - left.z * right.y, left.z * right.x - left.x * right.z, - left.x * right.y - left.y * right.x); -} - -__device__ MechanicsDofsGpu zero_dofs() { - return { - make_float4(0.0F, 0.0F, 0.0F, 0.0F), - make_float4(0.0F, 0.0F, 0.0F, 0.0F), - }; -} - -__device__ float dof_dot(const MechanicsDofsGpu& left, const MechanicsDofsGpu& right) { - return left.linear_length.x * right.linear_length.x + - left.linear_length.y * right.linear_length.y + - left.linear_length.z * right.linear_length.z + - left.linear_length.w * right.linear_length.w + left.rotation.x * right.rotation.x + - left.rotation.y * right.rotation.y + left.rotation.z * right.rotation.z; -} - -__device__ MechanicsDofsGpu scaled(const MechanicsDofsGpu& value, float scale) { - return { - make_float4(value.linear_length.x * scale, value.linear_length.y * scale, - value.linear_length.z * scale, value.linear_length.w * scale), - make_float4(value.rotation.x * scale, value.rotation.y * scale, value.rotation.z * scale, - 0.0F), - }; -} - -__device__ MechanicsDofsGpu added(const MechanicsDofsGpu& left, const MechanicsDofsGpu& right) { - return { - make_float4(left.linear_length.x + right.linear_length.x, - left.linear_length.y + right.linear_length.y, - left.linear_length.z + right.linear_length.z, - left.linear_length.w + right.linear_length.w), - make_float4(left.rotation.x + right.rotation.x, left.rotation.y + right.rotation.y, - left.rotation.z + right.rotation.z, 0.0F), - }; -} - -__device__ MechanicsDofsGpu contact_jacobian(float3 normal, float3 arm, float3 axis, - float total_length, float weight) { - const auto angular = cross_product(arm, normal); - return { - make_float4(weight * normal.x, weight * normal.y, weight * normal.z, - weight * dot_product(axis, arm) * dot_product(axis, normal) / total_length), - make_float4(weight * angular.x, weight * angular.y, weight * angular.z, 0.0F), - }; -} - -__global__ void build_mechanics_rows(const float4* centers, const float4* axes, - const float4* geometry, const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const float4* points, - const float4* normals, const float* separations, - const float* weights, MechanicsDofsGpu* first_rows, - MechanicsDofsGpu* second_rows, float* right_hand_side, - std::uint32_t contact_count) { - const auto index = blockIdx.x * blockDim.x + threadIdx.x; - if (index >= contact_count) { - return; - } - const auto first = first_slots[index]; - const auto second = second_slots[index]; - const auto point = make_float3(points[index].x, points[index].y, points[index].z); - const auto normal = make_float3(normals[index].x, normals[index].y, normals[index].z); - const auto first_center = make_float3(centers[first].x, centers[first].y, centers[first].z); - const auto first_axis = make_float3(axes[first].x, axes[first].y, axes[first].z); - const auto weight = weights[index]; - first_rows[index] = contact_jacobian(normal, subtract(point, first_center), first_axis, - geometry[first].x + 2.0F * geometry[first].y, weight); - if (second == 0xffffffffU) { - second_rows[index] = zero_dofs(); - } else { - const auto second_center = make_float3(centers[second].x, centers[second].y, centers[second].z); - const auto second_axis = make_float3(axes[second].x, axes[second].y, axes[second].z); - second_rows[index] = contact_jacobian(normal, subtract(point, second_center), second_axis, - geometry[second].x + 2.0F * geometry[second].y, weight); - } - right_hand_side[index] = weight * separations[index]; -} - -__global__ void apply_mechanics_b(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, - const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const MechanicsDofsGpu* input, - const std::uint8_t* fixed, float* row_values, - std::uint32_t contact_count) { - const auto index = blockIdx.x * blockDim.x + threadIdx.x; - if (index >= contact_count) { - return; - } - const auto first = first_slots[index]; - const auto second = second_slots[index]; - const auto first_input = fixed[first] == 0 ? input[first] : zero_dofs(); - row_values[index] = dof_dot(first_rows[index], first_input); - if (second != 0xffffffffU) { - const auto second_input = fixed[second] == 0 ? input[second] : zero_dofs(); - row_values[index] -= dof_dot(second_rows[index], second_input); - } -} - -__global__ void apply_mechanics_transpose(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, - const float* row_values, - const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_indices, - const std::uint32_t* first_slots, - MechanicsDofsGpu* output, std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - auto result = zero_dofs(); - for (auto offset = incidence_offsets[cell]; offset < incidence_offsets[cell + 1]; ++offset) { - const auto row = incidence_indices[offset]; - const auto is_first = first_slots[row] == cell; - const auto jacobian = is_first ? first_rows[row] : second_rows[row]; - result = added(result, scaled(jacobian, (is_first ? 1.0F : -1.0F) * row_values[row])); - } - output[cell] = result; -} - -__global__ void add_mechanics_regularizer(const float4* axes, const float4* geometry, - const MechanicsDofsGpu* input, MechanicsDofsGpu* output, - const std::uint8_t* fixed, float mu_a, float gamma, - std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - if (fixed[cell] != 0) { - output[cell] = input[cell]; - return; - } - const auto total_length = geometry[cell].x + 2.0F * geometry[cell].y; - const auto radius = geometry[cell].y; - const auto mass = mu_a * total_length; - const auto axial_inertia = 0.5F * mass * radius * radius; - const auto transverse_inertia = - mass * (total_length * total_length + 3.0F * radius * radius) / 12.0F; - const auto axis = make_float3(axes[cell].x, axes[cell].y, axes[cell].z); - const auto rotation = - make_float3(input[cell].rotation.x, input[cell].rotation.y, input[cell].rotation.z); - const auto inertia_rotation = - add(multiply(rotation, transverse_inertia), - multiply(axis, (axial_inertia - transverse_inertia) * dot_product(axis, rotation))); - const auto regularization = 1.0F / gamma; - - output[cell].linear_length.x += regularization * mass * input[cell].linear_length.x; - output[cell].linear_length.y += regularization * mass * input[cell].linear_length.y; - output[cell].linear_length.z += regularization * mass * input[cell].linear_length.z; - output[cell].linear_length.w += input[cell].linear_length.w; - output[cell].rotation.x += regularization * inertia_rotation.x; - output[cell].rotation.y += regularization * inertia_rotation.y; - output[cell].rotation.z += regularization * inertia_rotation.z; -} - -__global__ void initialize_mechanics_vectors(MechanicsDofsGpu* right_hand_side, - MechanicsDofsGpu* solution, MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, - const std::uint8_t* fixed, std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - solution[cell] = zero_dofs(); - const auto projected_rhs = fixed[cell] == 0 ? right_hand_side[cell] : zero_dofs(); - right_hand_side[cell] = projected_rhs; - residual[cell] = projected_rhs; - search_direction[cell] = projected_rhs; -} - -__global__ void update_mechanics_solution_residual(MechanicsDofsGpu* solution, - MechanicsDofsGpu* residual, - const MechanicsDofsGpu* search_direction, - const MechanicsDofsGpu* applied, float alpha, - std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - solution[cell] = added(solution[cell], scaled(search_direction[cell], alpha)); - residual[cell] = added(residual[cell], scaled(applied[cell], -alpha)); -} - -__global__ void update_mechanics_search_direction(const MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, float beta, - std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - search_direction[cell] = added(residual[cell], scaled(search_direction[cell], beta)); -} - -__global__ void subtract_mechanics_vectors(const MechanicsDofsGpu* left, - const MechanicsDofsGpu* right, MechanicsDofsGpu* output, - std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - output[cell] = added(left[cell], scaled(right[cell], -1.0F)); -} - -__global__ void mechanics_dot_terms(const MechanicsDofsGpu* left, const MechanicsDofsGpu* right, - float* terms, std::uint32_t cell_count) { - const auto cell = blockIdx.x * blockDim.x + threadIdx.x; - if (cell >= cell_count) { - return; - } - terms[cell] = dof_dot(left[cell], right[cell]); -} - -__global__ void reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count) { - const auto index = blockIdx.x * blockDim.x + threadIdx.x; - const auto first = index * 2; - if (first >= element_count) { - return; - } - auto value = input[first]; - if (first + 1 < element_count) { - value += input[first + 1]; - } - output[index] = value; -} - -std::uint32_t block_count(std::uint32_t count) { - return ((count - 1) / threads_per_block) + 1; -} - -} // namespace - -void launch_build_mechanics_rows(const float4* centers, const float4* axes, const float4* geometry, - const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const float4* points, - const float4* normals, const float* separations, - const float* weights, MechanicsDofsGpu* first_rows, - MechanicsDofsGpu* second_rows, float* right_hand_side, - std::uint32_t contact_count, cudaStream_t stream) { - build_mechanics_rows<<>>( - centers, axes, geometry, first_slots, second_slots, points, normals, separations, weights, - first_rows, second_rows, right_hand_side, contact_count); -} - -void launch_apply_mechanics_b(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const MechanicsDofsGpu* input, - const std::uint8_t* fixed, float* row_values, - std::uint32_t contact_count, cudaStream_t stream) { - apply_mechanics_b<<>>( - first_rows, second_rows, first_slots, second_slots, input, fixed, row_values, contact_count); -} - -void launch_apply_mechanics_transpose(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, const float* row_values, - const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_indices, - const std::uint32_t* first_slots, MechanicsDofsGpu* output, - std::uint32_t cell_count, cudaStream_t stream) { - apply_mechanics_transpose<<>>( - first_rows, second_rows, row_values, incidence_offsets, incidence_indices, first_slots, - output, cell_count); -} - -void launch_add_mechanics_regularizer(const float4* axes, const float4* geometry, - const MechanicsDofsGpu* input, MechanicsDofsGpu* output, - const std::uint8_t* fixed, float mu_a, float gamma, - std::uint32_t cell_count, cudaStream_t stream) { - add_mechanics_regularizer<<>>( - axes, geometry, input, output, fixed, mu_a, gamma, cell_count); -} - -void launch_initialize_mechanics_vectors(MechanicsDofsGpu* right_hand_side, - MechanicsDofsGpu* solution, MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, - const std::uint8_t* fixed, std::uint32_t cell_count, - cudaStream_t stream) { - initialize_mechanics_vectors<<>>( - right_hand_side, solution, residual, search_direction, fixed, cell_count); -} - -void launch_update_mechanics_solution_residual(MechanicsDofsGpu* solution, - MechanicsDofsGpu* residual, - const MechanicsDofsGpu* search_direction, - const MechanicsDofsGpu* applied, float alpha, - std::uint32_t cell_count, cudaStream_t stream) { - update_mechanics_solution_residual<<>>( - solution, residual, search_direction, applied, alpha, cell_count); -} - -void launch_update_mechanics_search_direction(const MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, float beta, - std::uint32_t cell_count, cudaStream_t stream) { - update_mechanics_search_direction<<>>( - residual, search_direction, beta, cell_count); -} - -void launch_subtract_mechanics_vectors(const MechanicsDofsGpu* left, const MechanicsDofsGpu* right, - MechanicsDofsGpu* output, std::uint32_t cell_count, - cudaStream_t stream) { - subtract_mechanics_vectors<<>>( - left, right, output, cell_count); -} - -void launch_mechanics_dot_terms(const MechanicsDofsGpu* left, const MechanicsDofsGpu* right, - float* terms, std::uint32_t cell_count, cudaStream_t stream) { - mechanics_dot_terms<<>>(left, right, terms, - cell_count); -} - -void launch_reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count, - cudaStream_t stream) { - const auto output_count = (element_count + 1) / 2; - reduce_sum_pairs<<>>(input, output, - element_count); -} - -} // namespace microsimulator::cuda diff --git a/cpp/cuda/kernels/mechanics.cuh b/cpp/cuda/kernels/mechanics.cuh deleted file mode 100644 index 340e2c2..0000000 --- a/cpp/cuda/kernels/mechanics.cuh +++ /dev/null @@ -1,68 +0,0 @@ -#pragma once - -#include - -#include - -namespace microsimulator::cuda { - -struct alignas(16) MechanicsDofsGpu { - float4 linear_length; - float4 rotation; -}; - -static_assert(sizeof(MechanicsDofsGpu) == 32); - -void launch_build_mechanics_rows(const float4* centers, const float4* axes, const float4* geometry, - const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const float4* points, - const float4* normals, const float* separations, - const float* weights, MechanicsDofsGpu* first_rows, - MechanicsDofsGpu* second_rows, float* right_hand_side, - std::uint32_t contact_count, cudaStream_t stream); - -void launch_apply_mechanics_b(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, const std::uint32_t* first_slots, - const std::uint32_t* second_slots, const MechanicsDofsGpu* input, - const std::uint8_t* fixed, float* row_values, - std::uint32_t contact_count, cudaStream_t stream); - -void launch_apply_mechanics_transpose(const MechanicsDofsGpu* first_rows, - const MechanicsDofsGpu* second_rows, const float* row_values, - const std::uint32_t* incidence_offsets, - const std::uint32_t* incidence_indices, - const std::uint32_t* first_slots, MechanicsDofsGpu* output, - std::uint32_t cell_count, cudaStream_t stream); - -void launch_add_mechanics_regularizer(const float4* axes, const float4* geometry, - const MechanicsDofsGpu* input, MechanicsDofsGpu* output, - const std::uint8_t* fixed, float mu_a, float gamma, - std::uint32_t cell_count, cudaStream_t stream); - -void launch_initialize_mechanics_vectors(MechanicsDofsGpu* right_hand_side, - MechanicsDofsGpu* solution, MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, - const std::uint8_t* fixed, std::uint32_t cell_count, - cudaStream_t stream); - -void launch_update_mechanics_solution_residual(MechanicsDofsGpu* solution, - MechanicsDofsGpu* residual, - const MechanicsDofsGpu* search_direction, - const MechanicsDofsGpu* applied, float alpha, - std::uint32_t cell_count, cudaStream_t stream); - -void launch_update_mechanics_search_direction(const MechanicsDofsGpu* residual, - MechanicsDofsGpu* search_direction, float beta, - std::uint32_t cell_count, cudaStream_t stream); - -void launch_subtract_mechanics_vectors(const MechanicsDofsGpu* left, const MechanicsDofsGpu* right, - MechanicsDofsGpu* output, std::uint32_t cell_count, - cudaStream_t stream); - -void launch_mechanics_dot_terms(const MechanicsDofsGpu* left, const MechanicsDofsGpu* right, - float* terms, std::uint32_t cell_count, cudaStream_t stream); - -void launch_reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count, - cudaStream_t stream); - -} // namespace microsimulator::cuda diff --git a/cpp/cuda/kernels/signals.cu b/cpp/cuda/kernels/signals.cu index 72d0dab..5dd9823 100644 --- a/cpp/cuda/kernels/signals.cu +++ b/cpp/cuda/kernels/signals.cu @@ -180,6 +180,19 @@ __global__ void signal_crank_nicolson_residual_terms( terms[index] = residual * residual; } +__global__ void reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count) { + const auto index = blockIdx.x * blockDim.x + threadIdx.x; + const auto first = index * 2; + if (first >= element_count) { + return; + } + auto value = input[first]; + if (first + 1 < element_count) { + value += input[first + 1]; + } + output[index] = value; +} + } // namespace void launch_advance_signal_grid( @@ -235,4 +248,12 @@ void launch_signal_crank_nicolson_residual_terms( spacing, half_dt, signal_count, level_count); } +void launch_reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count, + cudaStream_t stream) { + constexpr std::uint32_t threads_per_block = 256; + const auto output_count = (element_count + 1) / 2; + const auto block_count = ((output_count - 1) / threads_per_block) + 1; + reduce_sum_pairs<<>>(input, output, element_count); +} + } // namespace microsimulator::cuda diff --git a/cpp/cuda/kernels/signals.cuh b/cpp/cuda/kernels/signals.cuh index 315b383..57f49f4 100644 --- a/cpp/cuda/kernels/signals.cuh +++ b/cpp/cuda/kernels/signals.cuh @@ -133,4 +133,8 @@ void launch_signal_crank_nicolson_residual_terms( SignalGridBoundariesGpu boundaries, SignalGridShapeGpu shape, float4 spacing, float half_dt, std::uint32_t signal_count, std::uint32_t level_count, cudaStream_t stream); +// Sums neighboring elements of `input` into `output`, halving the count. +void launch_reduce_sum_pairs(const float* input, float* output, std::uint32_t element_count, + cudaStream_t stream); + } // namespace microsimulator::cuda diff --git a/cpp/include/microsimulator/backend.hpp b/cpp/include/microsimulator/backend.hpp index 11a9f5c..9792352 100644 --- a/cpp/include/microsimulator/backend.hpp +++ b/cpp/include/microsimulator/backend.hpp @@ -37,14 +37,10 @@ class ComputeBackend { [[nodiscard]] virtual ExternalContactGraph find_external_contacts( const WorldState& state, const ConstraintSet& constraints, const ConstraintContactParameters& parameters) = 0; - [[nodiscard]] virtual MechanicsSolveResult solve_cell_mechanics( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, const MechanicsParameters& parameters) = 0; - // Solves one substep's contact system from the given multipliers. A backend - // without the contact dynamics feature throws. + // Solves one substep's contact system from the given multipliers. [[nodiscard]] virtual ContactSolveResult solve_contact_forces( const ContactSystem& system, std::span initial_multipliers, - const ContactSolveParameters& parameters); + const ContactSolveParameters& parameters) = 0; [[nodiscard]] virtual DepthAveragedFlowResult solve_depth_averaged_flow( const SignalGridSpec& spec, std::span mobility, const DepthAveragedFlowParameters& parameters) = 0; diff --git a/cpp/include/microsimulator/constraints.hpp b/cpp/include/microsimulator/constraints.hpp index ecb8ea3..783982a 100644 --- a/cpp/include/microsimulator/constraints.hpp +++ b/cpp/include/microsimulator/constraints.hpp @@ -191,20 +191,4 @@ class ExternalContactGraph { const WorldState& state, const ConstraintSet& constraints, const ConstraintContactParameters& parameters = ConstraintContactParameters{}); -// Moves every mobile cell out of the external constraints it penetrates. -// The regularized contact solve weighs a wall row against the cells pressing -// on it, so a crowded colony leaves a cell part-way through a wall; this makes -// walls impenetrable. Each end of a cell's centerline moves back along the -// normals of the contacts it is inside until it rests in contact with those -// surfaces, a mid-span contact moves both ends, and the cell is rebuilt at its -// own length between the moved ends. A rod tilted against a wall therefore -// comes to lie along it, and one wedged upright between a floor and a ceiling -// is turned flat. Repeated sweeps settle the ends against each other. Fixed -// cells stay put, and overlap the move opens between cells is left to the -// next contact solve. The contacts come from the host geometry on every -// backend. -void project_cells_out_of_constraints( - WorldState& state, const ConstraintSet& constraints, - const ConstraintContactParameters& parameters = ConstraintContactParameters{}); - } // namespace microsimulator diff --git a/cpp/include/microsimulator/mechanics.hpp b/cpp/include/microsimulator/mechanics.hpp index d56f95d..c12f878 100644 --- a/cpp/include/microsimulator/mechanics.hpp +++ b/cpp/include/microsimulator/mechanics.hpp @@ -1,97 +1,18 @@ #pragma once -#include -#include -#include - -#include "microsimulator/constraints.hpp" -#include "microsimulator/contact_graph.hpp" #include "microsimulator/types.hpp" -#include "microsimulator/world_state.hpp" namespace microsimulator { -struct CellCorrection { - Vec3 translation{}; - Vec3 rotation{}; - float length{0.0F}; -}; - -struct MechanicsParameters { - float mu_a{1.0F}; - float gamma{10.0F}; - float residual_rms_tolerance{5.0e-3F}; - std::uint32_t max_iterations{0}; -}; - -enum class SolverStatus : std::uint8_t { - converged, - iteration_limit, - breakdown, -}; - -enum class SolverBreakdown : std::uint8_t { - none, - non_finite_residual, - non_finite_curvature, - non_positive_curvature, -}; - -struct SolverReport { - SolverStatus status{SolverStatus::converged}; - SolverBreakdown breakdown{SolverBreakdown::none}; - std::uint32_t iterations{0}; - float initial_residual_rms{0.0F}; - float final_residual_rms{0.0F}; -}; - -struct MechanicsSolveResult { - std::vector corrections; - SolverReport report; -}; - -struct MechanicsIntegrationParameters { +struct FlowDriftParameters { + // Largest turn of a cell's direction in one substep of the drift. float max_rotation_radians{0.0872664626F}; - bool require_convergence{true}; }; -void validate_mechanics_parameters(const MechanicsParameters& parameters); -void validate_mechanics_integration_parameters(const MechanicsIntegrationParameters& parameters); +void validate_flow_drift_parameters(const FlowDriftParameters& parameters); // The axis-angle rotation of a unit direction by a rotation vector, with the // angle capped at ``max_rotation``. [[nodiscard]] Vec3 rotate_axis_angle(Vec3 direction, Vec3 rotation, float max_rotation); -void integrate_mechanics_result( - WorldState& state, const MechanicsSolveResult& result, - const MechanicsIntegrationParameters& parameters = MechanicsIntegrationParameters{}, - std::span desired_length_increments = {}); - -[[nodiscard]] std::vector apply_mechanics_operator_cpu( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, std::span input, - const MechanicsParameters& parameters = MechanicsParameters{}); - -[[nodiscard]] std::vector apply_mechanics_operator_cpu( - const WorldState& state, const ContactGraph& contacts, std::span input, - const MechanicsParameters& parameters = MechanicsParameters{}); - -[[nodiscard]] std::vector build_mechanics_rhs_cpu( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters = MechanicsParameters{}); - -[[nodiscard]] std::vector build_mechanics_rhs_cpu( - const WorldState& state, const ContactGraph& contacts, - const MechanicsParameters& parameters = MechanicsParameters{}); - -[[nodiscard]] MechanicsSolveResult solve_cell_mechanics_cpu( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters = MechanicsParameters{}); - -[[nodiscard]] MechanicsSolveResult solve_cell_mechanics_cpu( - const WorldState& state, const ContactGraph& contacts, - const MechanicsParameters& parameters = MechanicsParameters{}); - } // namespace microsimulator diff --git a/cpp/include/microsimulator/simulation.hpp b/cpp/include/microsimulator/simulation.hpp index 4c402a4..2fc2f6b 100644 --- a/cpp/include/microsimulator/simulation.hpp +++ b/cpp/include/microsimulator/simulation.hpp @@ -32,8 +32,7 @@ class Simulation { CellId add_cell(const CellInit& cell); void remove_cell(CellId id); - void apply_flow_drift(float dt, const MechanicsIntegrationParameters& parameters = - MechanicsIntegrationParameters{}); + void apply_flow_drift(float dt, const FlowDriftParameters& parameters = FlowDriftParameters{}); ConstraintId add_plane_constraint(const PlaneConstraintInit& plane); ConstraintId add_sphere_constraint(const SphereConstraintInit& sphere); ConstraintId add_box_constraint(const BoxConstraintInit& box); @@ -65,16 +64,6 @@ class Simulation { const ContactParameters& parameters = ContactParameters{}); [[nodiscard]] ExternalContactGraph find_external_contacts( const ConstraintContactParameters& parameters = ConstraintContactParameters{}); - [[nodiscard]] MechanicsSolveResult solve_cell_mechanics( - const MechanicsParameters& mechanics_parameters = MechanicsParameters{}, - const ContactParameters& contact_parameters = ContactParameters{}, - const ConstraintContactParameters& constraint_parameters = ConstraintContactParameters{}); - [[nodiscard]] MechanicsSolveResult relax_cell_mechanics( - const MechanicsParameters& mechanics_parameters = MechanicsParameters{}, - const ContactParameters& contact_parameters = ContactParameters{}, - const MechanicsIntegrationParameters& integration_parameters = - MechanicsIntegrationParameters{}, - const ConstraintContactParameters& constraint_parameters = ConstraintContactParameters{}); // Solves a contact system on the selected backend. The system stands on // its own; it need not describe this simulation's cells. [[nodiscard]] ContactSolveResult solve_contact_system( diff --git a/cpp/include/microsimulator/types.hpp b/cpp/include/microsimulator/types.hpp index 7821252..1fe024e 100644 --- a/cpp/include/microsimulator/types.hpp +++ b/cpp/include/microsimulator/types.hpp @@ -66,7 +66,6 @@ enum class BackendFeature : std::uint8_t { growth, species, cell_contacts, - cell_mechanics, external_constraints, signals, coupled_rates, diff --git a/cpp/metal/kernels/contact_dynamics.metal b/cpp/metal/kernels/contact_dynamics.metal index 9daf954..28516f9 100644 --- a/cpp/metal/kernels/contact_dynamics.metal +++ b/cpp/metal/kernels/contact_dynamics.metal @@ -32,7 +32,7 @@ kernel void contact_respond(device const ContactRowData* rows [[buffer(0)]], device const float* multipliers [[buffer(2)]], device const uint* incidence_offsets [[buffer(3)]], device const uint* incidence_entries [[buffer(4)]], - device MechanicsDofs* response [[buffer(5)]], + device ContactResponse* response [[buffer(5)]], device const ContactSolveState* state [[buffer(6)]], constant ContactSolveData& solve [[buffer(7)]], constant uint& initial [[buffer(8)]], @@ -71,7 +71,7 @@ kernel void contact_respond(device const ContactRowData* rows [[buffer(0)]], // change . change, and the row's residual. The initial evaluation has no // previous step and writes only the residual. kernel void contact_gaps(device const ContactRowData* rows [[buffer(0)]], - device const MechanicsDofs* response [[buffer(1)]], + device const ContactResponse* response [[buffer(1)]], device const float* multipliers [[buffer(2)]], device float* gaps [[buffer(3)]], device const float* previous_multipliers [[buffer(4)]], diff --git a/cpp/metal/kernels/mechanics.metal b/cpp/metal/kernels/mechanics.metal deleted file mode 100644 index c334b01..0000000 --- a/cpp/metal/kernels/mechanics.metal +++ /dev/null @@ -1,213 +0,0 @@ -MechanicsDofs zero_dofs() { - MechanicsDofs result; - result.linear_length = 0.0f; - result.rotation = 0.0f; - return result; -} - -float dof_dot(const MechanicsDofs left, const MechanicsDofs right) { - return dot(left.linear_length, right.linear_length) + dot(left.rotation, right.rotation); -} - -MechanicsDofs scaled(const MechanicsDofs value, float scale) { - MechanicsDofs result; - result.linear_length = value.linear_length * scale; - result.rotation = value.rotation * scale; - return result; -} - -MechanicsDofs added(const MechanicsDofs left, const MechanicsDofs right) { - MechanicsDofs result; - result.linear_length = left.linear_length + right.linear_length; - result.rotation = left.rotation + right.rotation; - return result; -} - -MechanicsDofs contact_jacobian(float3 normal, float3 arm, float3 axis, float total_length, - float weight) { - MechanicsDofs result; - result.linear_length = - float4(weight * normal, weight * dot(axis, arm) * dot(axis, normal) / total_length); - result.rotation = float4(weight * cross(arm, normal), 0.0f); - return result; -} - -kernel void build_mechanics_rows( - device const float4* centers [[buffer(0)]], device const float4* axes [[buffer(1)]], - device const float4* geometry [[buffer(2)]], device const uint* first_slots [[buffer(3)]], - device const uint* second_slots [[buffer(4)]], device const float4* points [[buffer(5)]], - device const float4* normals [[buffer(6)]], device const float* separations [[buffer(7)]], - device const float* weights [[buffer(8)]], device MechanicsDofs* first_rows [[buffer(9)]], - device MechanicsDofs* second_rows [[buffer(10)]], device float* right_hand_side [[buffer(11)]], - constant uint& contact_count [[buffer(12)]], uint index [[thread_position_in_grid]]) { - if (index >= contact_count) { - return; - } - uint first = first_slots[index]; - uint second = second_slots[index]; - float weight = weights[index]; - float3 normal = normals[index].xyz; - float3 point = points[index].xyz; - first_rows[index] = contact_jacobian(normal, point - centers[first].xyz, axes[first].xyz, - geometry[first].x + 2.0f * geometry[first].y, weight); - second_rows[index] = - second == 0xffffffffu - ? zero_dofs() - : contact_jacobian(normal, point - centers[second].xyz, axes[second].xyz, - geometry[second].x + 2.0f * geometry[second].y, weight); - right_hand_side[index] = weight * separations[index]; -} - -kernel void apply_mechanics_b(device const MechanicsDofs* first_rows [[buffer(0)]], - device const MechanicsDofs* second_rows [[buffer(1)]], - device const uint* first_slots [[buffer(2)]], - device const uint* second_slots [[buffer(3)]], - device const MechanicsDofs* input [[buffer(4)]], - device float* row_values [[buffer(5)]], - constant uint& contact_count [[buffer(6)]], - device const uchar* fixed [[buffer(7)]], - uint index [[thread_position_in_grid]]) { - if (index >= contact_count) { - return; - } - uint first = first_slots[index]; - uint second = second_slots[index]; - MechanicsDofs first_input = fixed[first] == 0 ? input[first] : zero_dofs(); - row_values[index] = dof_dot(first_rows[index], first_input); - if (second != 0xffffffffu) { - MechanicsDofs second_input = fixed[second] == 0 ? input[second] : zero_dofs(); - row_values[index] -= dof_dot(second_rows[index], second_input); - } -} - -kernel void apply_mechanics_transpose(device const MechanicsDofs* first_rows [[buffer(0)]], - device const MechanicsDofs* second_rows [[buffer(1)]], - device const float* row_values [[buffer(2)]], - device const uint* incidence_offsets [[buffer(3)]], - device const uint* incidence_indices [[buffer(4)]], - device const uint* first_slots [[buffer(5)]], - device MechanicsDofs* output [[buffer(6)]], - constant uint& cell_count [[buffer(7)]], - uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - MechanicsDofs result = zero_dofs(); - for (uint offset = incidence_offsets[cell]; offset < incidence_offsets[cell + 1]; ++offset) { - uint row = incidence_indices[offset]; - bool is_first = first_slots[row] == cell; - MechanicsDofs jacobian = is_first ? first_rows[row] : second_rows[row]; - float sign = is_first ? 1.0f : -1.0f; - result = added(result, scaled(jacobian, sign * row_values[row])); - } - output[cell] = result; -} - -kernel void add_mechanics_regularizer( - device const float4* axes [[buffer(0)]], device const float4* geometry [[buffer(1)]], - device const MechanicsDofs* input [[buffer(2)]], device MechanicsDofs* output [[buffer(3)]], - constant float4& parameters [[buffer(4)]], constant uint& cell_count [[buffer(5)]], - device const uchar* fixed [[buffer(6)]], uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - if (fixed[cell] != 0) { - output[cell] = input[cell]; - return; - } - float mu_a = parameters.x; - float gamma = parameters.y; - float total_length = geometry[cell].x + 2.0f * geometry[cell].y; - float radius = geometry[cell].y; - float mass = mu_a * total_length; - float axial_inertia = 0.5f * mass * radius * radius; - float transverse_inertia = mass * (total_length * total_length + 3.0f * radius * radius) / 12.0f; - float3 axis = axes[cell].xyz; - float3 rotation = input[cell].rotation.xyz; - float3 inertia_rotation = rotation * transverse_inertia + - axis * ((axial_inertia - transverse_inertia) * dot(axis, rotation)); - float regularization = 1.0f / gamma; - - MechanicsDofs result = output[cell]; - result.linear_length.xyz += regularization * mass * input[cell].linear_length.xyz; - result.linear_length.w += input[cell].linear_length.w; - result.rotation.xyz += regularization * inertia_rotation; - output[cell] = result; -} - -kernel void initialize_mechanics_vectors(device MechanicsDofs* right_hand_side [[buffer(0)]], - device MechanicsDofs* solution [[buffer(1)]], - device MechanicsDofs* residual [[buffer(2)]], - device MechanicsDofs* search_direction [[buffer(3)]], - constant uint& cell_count [[buffer(4)]], - device const uchar* fixed [[buffer(5)]], - uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - solution[cell] = zero_dofs(); - MechanicsDofs projected_rhs = fixed[cell] == 0 ? right_hand_side[cell] : zero_dofs(); - right_hand_side[cell] = projected_rhs; - residual[cell] = projected_rhs; - search_direction[cell] = projected_rhs; -} - -kernel void update_mechanics_solution_residual( - device MechanicsDofs* solution [[buffer(0)]], device MechanicsDofs* residual [[buffer(1)]], - device const MechanicsDofs* search_direction [[buffer(2)]], - device const MechanicsDofs* applied [[buffer(3)]], constant float& alpha [[buffer(4)]], - constant uint& cell_count [[buffer(5)]], uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - solution[cell] = added(solution[cell], scaled(search_direction[cell], alpha)); - residual[cell] = added(residual[cell], scaled(applied[cell], -alpha)); -} - -kernel void update_mechanics_search_direction(device const MechanicsDofs* residual [[buffer(0)]], - device MechanicsDofs* search_direction [[buffer(1)]], - constant float& beta [[buffer(2)]], - constant uint& cell_count [[buffer(3)]], - uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - search_direction[cell] = added(residual[cell], scaled(search_direction[cell], beta)); -} - -kernel void subtract_mechanics_vectors(device const MechanicsDofs* left [[buffer(0)]], - device const MechanicsDofs* right [[buffer(1)]], - device MechanicsDofs* output [[buffer(2)]], - constant uint& cell_count [[buffer(3)]], - uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - output[cell] = added(left[cell], scaled(right[cell], -1.0f)); -} - -kernel void mechanics_dot_terms(device const MechanicsDofs* left [[buffer(0)]], - device const MechanicsDofs* right [[buffer(1)]], - device float* terms [[buffer(2)]], - constant uint& cell_count [[buffer(3)]], - uint cell [[thread_position_in_grid]]) { - if (cell >= cell_count) { - return; - } - terms[cell] = dof_dot(left[cell], right[cell]); -} - -kernel void reduce_sum_pairs(device const float* input [[buffer(0)]], - device float* output [[buffer(1)]], - constant uint& element_count [[buffer(2)]], - uint index [[thread_position_in_grid]]) { - uint first = index * 2; - if (first >= element_count) { - return; - } - float value = input[first]; - if (first + 1 < element_count) { - value += input[first + 1]; - } - output[index] = value; -} diff --git a/cpp/metal/metal_backend.mm b/cpp/metal/metal_backend.mm index f36e4fd..39d8490 100644 --- a/cpp/metal/metal_backend.mm +++ b/cpp/metal/metal_backend.mm @@ -18,7 +18,6 @@ #include "core/contact_solver.hpp" #include "core/device_types.hpp" -#include "core/mechanics_solver.hpp" #include "core/signal_jacobi.hpp" #include "metal_flow.hpp" #include "microsimulator/backend.hpp" @@ -26,7 +25,6 @@ #include "microsimulator/metal/contacts_source.hpp" #include "microsimulator/metal/coupled_rates_source.hpp" #include "microsimulator/metal/growth_source.hpp" -#include "microsimulator/metal/mechanics_source.hpp" #include "microsimulator/metal/signals_source.hpp" #include "microsimulator/metal/species_source.hpp" @@ -37,7 +35,7 @@ using MetalUInt2 = device::uint2; using MetalFloat4 = device::float4; using MetalUInt4 = device::uint4; -using MetalDofs = device::MechanicsDofs; +using MetalContactResponse = device::ContactResponse; using MetalContactRow = device::ContactRowData; using MetalContactBody = device::ContactBodyData; using MetalContactSolve = device::ContactSolveData; @@ -194,37 +192,6 @@ explicit MetalBackend(std::uint32_t device_index) : device_index_(device_index) compile_pipeline(device_, contacts_library, @"fill_external_contacts", "failed to create the Metal external-contact-fill pipeline"); - const auto mechanics_library = - compile_library(device_, metal::mechanics_source, "failed to compile Metal mechanics"); - mechanics_rows_pipeline_ = - compile_pipeline(device_, mechanics_library, @"build_mechanics_rows", - "failed to create the Metal mechanics-row pipeline"); - mechanics_b_pipeline_ = compile_pipeline(device_, mechanics_library, @"apply_mechanics_b", - "failed to create the Metal mechanics-B pipeline"); - mechanics_transpose_pipeline_ = - compile_pipeline(device_, mechanics_library, @"apply_mechanics_transpose", - "failed to create the Metal mechanics-transpose pipeline"); - mechanics_regularizer_pipeline_ = - compile_pipeline(device_, mechanics_library, @"add_mechanics_regularizer", - "failed to create the Metal mechanics-regularizer pipeline"); - mechanics_initialize_pipeline_ = - compile_pipeline(device_, mechanics_library, @"initialize_mechanics_vectors", - "failed to create the Metal mechanics-initialize pipeline"); - mechanics_update_solution_pipeline_ = - compile_pipeline(device_, mechanics_library, @"update_mechanics_solution_residual", - "failed to create the Metal mechanics-update pipeline"); - mechanics_update_search_pipeline_ = - compile_pipeline(device_, mechanics_library, @"update_mechanics_search_direction", - "failed to create the Metal mechanics-search pipeline"); - mechanics_subtract_pipeline_ = - compile_pipeline(device_, mechanics_library, @"subtract_mechanics_vectors", - "failed to create the Metal mechanics-subtract pipeline"); - mechanics_dot_pipeline_ = - compile_pipeline(device_, mechanics_library, @"mechanics_dot_terms", - "failed to create the Metal mechanics-dot pipeline"); - mechanics_reduce_pipeline_ = - compile_pipeline(device_, mechanics_library, @"reduce_sum_pairs", - "failed to create the Metal mechanics-reduction pipeline"); const auto contact_dynamics_library = compile_library( device_, metal::contact_dynamics_source, "failed to compile Metal contact dynamics"); contact_project_pipeline_ = @@ -260,7 +227,7 @@ explicit MetalBackend(std::uint32_t device_index) : device_index_(device_index) [[nodiscard]] bool supports(BackendFeature feature) const noexcept override { return feature == BackendFeature::growth || feature == BackendFeature::species || - feature == BackendFeature::cell_contacts || feature == BackendFeature::cell_mechanics || + feature == BackendFeature::cell_contacts || feature == BackendFeature::external_constraints || feature == BackendFeature::signals || feature == BackendFeature::coupled_rates || feature == BackendFeature::depth_averaged_flow || @@ -843,60 +810,6 @@ SignalSolveReport advance_coupled(WorldState& state, SignalGrid& grid, return download_external_contacts(geometry.size(), contact_count); } - [[nodiscard]] MechanicsSolveResult solve_cell_mechanics( - const WorldState& state, const ContactGraph& contacts, - const ExternalContactGraph& external_contacts, - const MechanicsParameters& parameters) override { - validate_mechanics_parameters(parameters); - state.validate(); - const auto geometry = state.geometry_state(); - if (contacts.cell_count() != geometry.size()) { - throw std::invalid_argument("contact graph and world state cell counts disagree"); - } - if (external_contacts.cell_count() != geometry.size()) { - throw std::invalid_argument("external contact graph and world state cell counts disagree"); - } - if (external_contacts.size() > std::numeric_limits::max() - contacts.size()) { - throw std::overflow_error("Metal mechanics row count overflow"); - } - const auto row_count = contacts.size() + external_contacts.size(); - if (geometry.size() > std::numeric_limits::max() || - row_count > std::numeric_limits::max() / 2) { - throw std::overflow_error("Metal mechanics exceeds the uint32 index space"); - } - - MechanicsSolveResult result; - result.corrections.resize(geometry.size()); - if (geometry.size() == 0 || row_count == 0) { - return result; - } - - validate_mechanics_contacts(geometry, contacts); - validate_external_mechanics_contacts(geometry, external_contacts); - ensure_contact_cell_capacity(geometry.size()); - ensure_contact_output_capacity(row_count); - ensure_mechanics_capacity(geometry.size(), row_count); - upload_contact_cells(geometry); - upload_mechanics_fixed(state.cell_attributes().fixed); - upload_mechanics_contacts(contacts, external_contacts); - upload_mechanics_incidence(contacts, external_contacts); - - const auto cell_count = static_cast(geometry.size()); - const auto contact_count = static_cast(row_count); - const detail::MechanicsSolverOperations operations{ - .initialize = [&] { return initialize_mechanics(cell_count, contact_count); }, - .apply_direction = - [&] { return apply_search_direction(cell_count, contact_count, parameters); }, - .update = [&](float alpha) { return update_solution_residual(cell_count, alpha); }, - .recompute_residual = - [&] { return recompute_residual(cell_count, contact_count, parameters); }, - .update_direction = [&](float beta) { update_search_direction(cell_count, beta); }, - }; - result.report = detail::solve_mechanics_system(operations, geometry.size(), parameters); - result.corrections = download_mechanics_solution(geometry.size()); - return result; - } - [[nodiscard]] ContactSolveResult solve_contact_forces( const ContactSystem& system, std::span initial_multipliers, const ContactSolveParameters& parameters) override { @@ -1862,336 +1775,6 @@ void fill_external_contacts(std::uint32_t cell_count, std::uint32_t constraint_c return ExternalContactGraph(cell_count, std::move(contacts)); } - static void validate_mechanics_contacts(const CellGeometryView& geometry, - const ContactGraph& contacts) { - for (const auto& contact : contacts.contacts()) { - const auto first = static_cast(contact.first_slot); - const auto second = static_cast(contact.second_slot); - if (geometry.ids[first] != contact.first_id || geometry.ids[second] != contact.second_id) { - throw std::invalid_argument("contact graph identifiers do not match current state slots"); - } - } - } - - static void validate_external_mechanics_contacts(const CellGeometryView& geometry, - const ExternalContactGraph& contacts) { - for (const auto& contact : contacts.contacts()) { - const auto cell = static_cast(contact.cell_slot); - if (geometry.ids[cell] != contact.cell_id) { - throw std::invalid_argument( - "external contact graph identifiers do not match current state slots"); - } - } - } - - void ensure_mechanics_capacity(std::size_t cell_count, std::size_t contact_count) { - if (cell_count > mechanics_cell_capacity_) { - const auto mechanics_cell_capacity = std::bit_ceil(cell_count); - const auto dof_bytes = mechanics_cell_capacity * sizeof(MetalDofs); - const auto scalar_bytes = mechanics_cell_capacity * sizeof(float); - mechanics_incidence_offsets_ = - allocate_shared_buffer(device_, (mechanics_cell_capacity + 1) * sizeof(std::uint32_t), - "mechanics incidence offsets"); - mechanics_fixed_ = - allocate_shared_buffer(device_, mechanics_cell_capacity, "mechanics fixed flags"); - mechanics_solution_ = allocate_shared_buffer(device_, dof_bytes, "mechanics solution"); - mechanics_rhs_ = allocate_shared_buffer(device_, dof_bytes, "mechanics right-hand side"); - mechanics_residual_ = allocate_shared_buffer(device_, dof_bytes, "mechanics residual"); - mechanics_search_ = allocate_shared_buffer(device_, dof_bytes, "mechanics search direction"); - mechanics_applied_ = allocate_shared_buffer(device_, dof_bytes, "mechanics applied vector"); - mechanics_dot_terms_ = allocate_shared_buffer(device_, scalar_bytes, "mechanics dot terms"); - mechanics_reduce_a_ = allocate_shared_buffer(device_, scalar_bytes, "mechanics reduction A"); - mechanics_reduce_b_ = allocate_shared_buffer(device_, scalar_bytes, "mechanics reduction B"); - mechanics_cell_capacity_ = mechanics_cell_capacity; - } - if (contact_count > mechanics_contact_capacity_) { - const auto mechanics_contact_capacity = std::bit_ceil(contact_count); - const auto dof_bytes = mechanics_contact_capacity * sizeof(MetalDofs); - mechanics_first_rows_ = - allocate_shared_buffer(device_, dof_bytes, "mechanics first Jacobian rows"); - mechanics_second_rows_ = - allocate_shared_buffer(device_, dof_bytes, "mechanics second Jacobian rows"); - mechanics_row_values_ = allocate_shared_buffer( - device_, mechanics_contact_capacity * sizeof(float), "mechanics row values"); - mechanics_row_rhs_ = allocate_shared_buffer( - device_, mechanics_contact_capacity * sizeof(float), "mechanics row right-hand side"); - mechanics_incidence_indices_ = - allocate_shared_buffer(device_, mechanics_contact_capacity * 2 * sizeof(std::uint32_t), - "mechanics incidence indices"); - mechanics_contact_capacity_ = mechanics_contact_capacity; - } - } - - void upload_mechanics_fixed(std::span fixed) { - std::memcpy(mechanics_fixed_.contents, fixed.data(), fixed.size_bytes()); - } - - void upload_mechanics_contacts(const ContactGraph& contacts, - const ExternalContactGraph& external_contacts) { - auto* first_slots = static_cast(contact_first_slots_.contents); - auto* second_slots = static_cast(contact_second_slots_.contents); - auto* points = static_cast(contact_points_.contents); - auto* normals = static_cast(contact_normals_.contents); - auto* separations = static_cast(contact_separations_.contents); - auto* weights = static_cast(contact_weights_.contents); - for (std::size_t index = 0; index < contacts.size(); ++index) { - const auto& contact = contacts.contacts()[index]; - first_slots[index] = contact.first_slot; - second_slots[index] = contact.second_slot; - points[index] = {contact.point_on_first.x, contact.point_on_first.y, contact.point_on_first.z, - 0.0F}; - normals[index] = {contact.normal.x, contact.normal.y, contact.normal.z, 0.0F}; - separations[index] = contact.signed_separation; - weights[index] = contact.weight; - } - for (std::size_t index = 0; index < external_contacts.size(); ++index) { - const auto output_index = contacts.size() + index; - const auto& contact = external_contacts.contacts()[index]; - first_slots[output_index] = contact.cell_slot; - second_slots[output_index] = invalid_slot; - points[output_index] = {contact.point_on_cell.x, contact.point_on_cell.y, - contact.point_on_cell.z, 0.0F}; - normals[output_index] = {contact.normal.x, contact.normal.y, contact.normal.z, 0.0F}; - separations[output_index] = contact.signed_separation; - weights[output_index] = contact.weight; - } - } - - void upload_mechanics_incidence(const ContactGraph& contacts, - const ExternalContactGraph& external_contacts) { - auto* offsets = static_cast(mechanics_incidence_offsets_.contents); - auto* indices = static_cast(mechanics_incidence_indices_.contents); - std::uint32_t cursor = 0; - for (std::size_t slot = 0; slot < contacts.cell_count(); ++slot) { - offsets[slot] = cursor; - for (const auto contact_index : contacts.incident_contact_indices(static_cast(slot))) { - indices[cursor++] = static_cast(contact_index); - } - for (const auto contact_index : - external_contacts.incident_contact_indices(static_cast(slot))) { - indices[cursor++] = static_cast(contacts.size() + contact_index); - } - } - offsets[contacts.cell_count()] = cursor; - if (cursor != contacts.size() * 2 + external_contacts.size()) { - throw std::logic_error("contact incidence size is inconsistent"); - } - } - - void encode_build_mechanics_rows(id encoder, - std::uint32_t contact_count) { - [encoder setComputePipelineState:mechanics_rows_pipeline_]; - [encoder setBuffer:contact_centers_ offset:0 atIndex:0]; - [encoder setBuffer:contact_axes_ offset:0 atIndex:1]; - [encoder setBuffer:contact_geometry_ offset:0 atIndex:2]; - [encoder setBuffer:contact_first_slots_ offset:0 atIndex:3]; - [encoder setBuffer:contact_second_slots_ offset:0 atIndex:4]; - [encoder setBuffer:contact_points_ offset:0 atIndex:5]; - [encoder setBuffer:contact_normals_ offset:0 atIndex:6]; - [encoder setBuffer:contact_separations_ offset:0 atIndex:7]; - [encoder setBuffer:contact_weights_ offset:0 atIndex:8]; - [encoder setBuffer:mechanics_first_rows_ offset:0 atIndex:9]; - [encoder setBuffer:mechanics_second_rows_ offset:0 atIndex:10]; - [encoder setBuffer:mechanics_row_rhs_ offset:0 atIndex:11]; - [encoder setBytes:&contact_count length:sizeof(contact_count) atIndex:12]; - dispatch_1d(encoder, mechanics_rows_pipeline_, contact_count); - } - - void encode_mechanics_transpose(id encoder, id row_values, - id output, std::uint32_t cell_count) { - [encoder setComputePipelineState:mechanics_transpose_pipeline_]; - [encoder setBuffer:mechanics_first_rows_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_second_rows_ offset:0 atIndex:1]; - [encoder setBuffer:row_values offset:0 atIndex:2]; - [encoder setBuffer:mechanics_incidence_offsets_ offset:0 atIndex:3]; - [encoder setBuffer:mechanics_incidence_indices_ offset:0 atIndex:4]; - [encoder setBuffer:contact_first_slots_ offset:0 atIndex:5]; - [encoder setBuffer:output offset:0 atIndex:6]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:7]; - dispatch_1d(encoder, mechanics_transpose_pipeline_, cell_count); - } - - void encode_mechanics_operator(id encoder, id input, - id output, std::uint32_t cell_count, - std::uint32_t contact_count, - const MechanicsParameters& parameters) { - [encoder setComputePipelineState:mechanics_b_pipeline_]; - [encoder setBuffer:mechanics_first_rows_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_second_rows_ offset:0 atIndex:1]; - [encoder setBuffer:contact_first_slots_ offset:0 atIndex:2]; - [encoder setBuffer:contact_second_slots_ offset:0 atIndex:3]; - [encoder setBuffer:input offset:0 atIndex:4]; - [encoder setBuffer:mechanics_row_values_ offset:0 atIndex:5]; - [encoder setBytes:&contact_count length:sizeof(contact_count) atIndex:6]; - [encoder setBuffer:mechanics_fixed_ offset:0 atIndex:7]; - dispatch_1d(encoder, mechanics_b_pipeline_, contact_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - encode_mechanics_transpose(encoder, mechanics_row_values_, output, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - const MetalFloat4 gpu_parameters{parameters.mu_a, parameters.gamma, 0.0F, 0.0F}; - [encoder setComputePipelineState:mechanics_regularizer_pipeline_]; - [encoder setBuffer:contact_axes_ offset:0 atIndex:0]; - [encoder setBuffer:contact_geometry_ offset:0 atIndex:1]; - [encoder setBuffer:input offset:0 atIndex:2]; - [encoder setBuffer:output offset:0 atIndex:3]; - [encoder setBytes:&gpu_parameters length:sizeof(gpu_parameters) atIndex:4]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:5]; - [encoder setBuffer:mechanics_fixed_ offset:0 atIndex:6]; - dispatch_1d(encoder, mechanics_regularizer_pipeline_, cell_count); - } - - id encode_mechanics_dot(id encoder, id left, - id right, std::uint32_t cell_count) { - [encoder setComputePipelineState:mechanics_dot_pipeline_]; - [encoder setBuffer:left offset:0 atIndex:0]; - [encoder setBuffer:right offset:0 atIndex:1]; - [encoder setBuffer:mechanics_dot_terms_ offset:0 atIndex:2]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:3]; - dispatch_1d(encoder, mechanics_dot_pipeline_, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - id input = mechanics_dot_terms_; - id output = mechanics_reduce_a_; - auto element_count = cell_count; - while (element_count > 1) { - const auto output_count = (element_count + 1) / 2; - [encoder setComputePipelineState:mechanics_reduce_pipeline_]; - [encoder setBuffer:input offset:0 atIndex:0]; - [encoder setBuffer:output offset:0 atIndex:1]; - [encoder setBytes:&element_count length:sizeof(element_count) atIndex:2]; - dispatch_1d(encoder, mechanics_reduce_pipeline_, output_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - input = output; - output = output == mechanics_reduce_a_ ? mechanics_reduce_b_ : mechanics_reduce_a_; - element_count = output_count; - } - return input; - } - - static float read_reduction(id reduction) { - return *static_cast(reduction.contents); - } - - [[nodiscard]] float initialize_mechanics(std::uint32_t cell_count, std::uint32_t contact_count) { - @autoreleasepool { - id command_buffer = [queue_ commandBuffer]; - id encoder = [command_buffer computeCommandEncoder]; - if (command_buffer == nil || encoder == nil) { - throw std::runtime_error("failed to create a Metal mechanics initialization command"); - } - encode_build_mechanics_rows(encoder, contact_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - encode_mechanics_transpose(encoder, mechanics_row_rhs_, mechanics_rhs_, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - [encoder setComputePipelineState:mechanics_initialize_pipeline_]; - [encoder setBuffer:mechanics_rhs_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_solution_ offset:0 atIndex:1]; - [encoder setBuffer:mechanics_residual_ offset:0 atIndex:2]; - [encoder setBuffer:mechanics_search_ offset:0 atIndex:3]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:4]; - [encoder setBuffer:mechanics_fixed_ offset:0 atIndex:5]; - dispatch_1d(encoder, mechanics_initialize_pipeline_, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - const auto reduction = - encode_mechanics_dot(encoder, mechanics_residual_, mechanics_residual_, cell_count); - [encoder endEncoding]; - wait_for_command(command_buffer, "Metal mechanics initialization failed"); - return read_reduction(reduction); - } - } - - [[nodiscard]] float apply_search_direction(std::uint32_t cell_count, std::uint32_t contact_count, - const MechanicsParameters& parameters) { - @autoreleasepool { - id command_buffer = [queue_ commandBuffer]; - id encoder = [command_buffer computeCommandEncoder]; - if (command_buffer == nil || encoder == nil) { - throw std::runtime_error("failed to create a Metal mechanics operator command"); - } - encode_mechanics_operator(encoder, mechanics_search_, mechanics_applied_, cell_count, - contact_count, parameters); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - const auto reduction = - encode_mechanics_dot(encoder, mechanics_search_, mechanics_applied_, cell_count); - [encoder endEncoding]; - wait_for_command(command_buffer, "Metal mechanics operator application failed"); - return read_reduction(reduction); - } - } - - [[nodiscard]] float update_solution_residual(std::uint32_t cell_count, float alpha) { - @autoreleasepool { - id command_buffer = [queue_ commandBuffer]; - id encoder = [command_buffer computeCommandEncoder]; - if (command_buffer == nil || encoder == nil) { - throw std::runtime_error("failed to create a Metal mechanics update command"); - } - [encoder setComputePipelineState:mechanics_update_solution_pipeline_]; - [encoder setBuffer:mechanics_solution_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_residual_ offset:0 atIndex:1]; - [encoder setBuffer:mechanics_search_ offset:0 atIndex:2]; - [encoder setBuffer:mechanics_applied_ offset:0 atIndex:3]; - [encoder setBytes:&alpha length:sizeof(alpha) atIndex:4]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:5]; - dispatch_1d(encoder, mechanics_update_solution_pipeline_, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - const auto reduction = - encode_mechanics_dot(encoder, mechanics_residual_, mechanics_residual_, cell_count); - [encoder endEncoding]; - wait_for_command(command_buffer, "Metal mechanics update failed"); - return read_reduction(reduction); - } - } - - void update_search_direction(std::uint32_t cell_count, float beta) { - @autoreleasepool { - id command_buffer = [queue_ commandBuffer]; - id encoder = [command_buffer computeCommandEncoder]; - if (command_buffer == nil || encoder == nil) { - throw std::runtime_error("failed to create a Metal mechanics search command"); - } - [encoder setComputePipelineState:mechanics_update_search_pipeline_]; - [encoder setBuffer:mechanics_residual_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_search_ offset:0 atIndex:1]; - [encoder setBytes:&beta length:sizeof(beta) atIndex:2]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:3]; - dispatch_1d(encoder, mechanics_update_search_pipeline_, cell_count); - [encoder endEncoding]; - wait_for_command(command_buffer, "Metal mechanics search update failed"); - } - } - - [[nodiscard]] float recompute_residual(std::uint32_t cell_count, std::uint32_t contact_count, - const MechanicsParameters& parameters) { - @autoreleasepool { - id command_buffer = [queue_ commandBuffer]; - id encoder = [command_buffer computeCommandEncoder]; - if (command_buffer == nil || encoder == nil) { - throw std::runtime_error("failed to create a Metal mechanics residual command"); - } - encode_mechanics_operator(encoder, mechanics_solution_, mechanics_applied_, cell_count, - contact_count, parameters); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - - [encoder setComputePipelineState:mechanics_subtract_pipeline_]; - [encoder setBuffer:mechanics_rhs_ offset:0 atIndex:0]; - [encoder setBuffer:mechanics_applied_ offset:0 atIndex:1]; - [encoder setBuffer:mechanics_residual_ offset:0 atIndex:2]; - [encoder setBytes:&cell_count length:sizeof(cell_count) atIndex:3]; - dispatch_1d(encoder, mechanics_subtract_pipeline_, cell_count); - [encoder memoryBarrierWithScope:MTLBarrierScopeBuffers]; - const auto reduction = - encode_mechanics_dot(encoder, mechanics_residual_, mechanics_residual_, cell_count); - [encoder endEncoding]; - wait_for_command(command_buffer, "Metal mechanics residual recomputation failed"); - return read_reduction(reduction); - } - } - // Projected-gradient steps encoded in one command buffer. The device stops // itself at convergence, so the steps left in a batch do nothing. static constexpr std::uint32_t contact_solve_batch = 32; @@ -2201,8 +1784,8 @@ void ensure_contact_dynamics_capacity(std::size_t body_count, std::size_t row_co const auto capacity = std::bit_ceil(body_count); contact_bodies_ = allocate_shared_buffer(device_, capacity * sizeof(MetalContactBody), "contact bodies"); - contact_response_ = - allocate_shared_buffer(device_, capacity * sizeof(MetalDofs), "contact response"); + contact_response_ = allocate_shared_buffer(device_, capacity * sizeof(MetalContactResponse), + "contact response"); contact_incidence_offsets_ = allocate_shared_buffer( device_, (capacity + 1) * sizeof(std::uint32_t), "contact incidence offsets"); contact_body_capacity_ = capacity; @@ -2398,23 +1981,6 @@ void encode_contact_advance(id encoder, id } } - [[nodiscard]] std::vector download_mechanics_solution( - std::size_t cell_count) const { - const auto* values = static_cast(mechanics_solution_.contents); - std::vector result; - result.reserve(cell_count); - for (std::size_t index = 0; index < cell_count; ++index) { - result.push_back({ - .translation = {values[index].linear_length.x, values[index].linear_length.y, - values[index].linear_length.z}, - .rotation = {values[index].rotation.x, values[index].rotation.y, - values[index].rotation.z}, - .length = values[index].linear_length.w, - }); - } - return result; - } - std::uint32_t device_index_{0}; id device_{nil}; id queue_{nil}; @@ -2436,16 +2002,6 @@ void encode_contact_advance(id encoder, id id contact_fill_pipeline_{nil}; id external_contact_count_pipeline_{nil}; id external_contact_fill_pipeline_{nil}; - id mechanics_rows_pipeline_{nil}; - id mechanics_b_pipeline_{nil}; - id mechanics_transpose_pipeline_{nil}; - id mechanics_regularizer_pipeline_{nil}; - id mechanics_initialize_pipeline_{nil}; - id mechanics_update_solution_pipeline_{nil}; - id mechanics_update_search_pipeline_{nil}; - id mechanics_subtract_pipeline_{nil}; - id mechanics_dot_pipeline_{nil}; - id mechanics_reduce_pipeline_{nil}; id contact_project_pipeline_{nil}; id contact_respond_pipeline_{nil}; id contact_gaps_pipeline_{nil}; @@ -2567,23 +2123,6 @@ void encode_contact_advance(id encoder, id id contact_weights_{nil}; std::size_t contact_output_capacity_{0}; - id mechanics_first_rows_{nil}; - id mechanics_second_rows_{nil}; - id mechanics_row_values_{nil}; - id mechanics_row_rhs_{nil}; - id mechanics_incidence_offsets_{nil}; - id mechanics_incidence_indices_{nil}; - id mechanics_fixed_{nil}; - id mechanics_solution_{nil}; - id mechanics_rhs_{nil}; - id mechanics_residual_{nil}; - id mechanics_search_{nil}; - id mechanics_applied_{nil}; - id mechanics_dot_terms_{nil}; - id mechanics_reduce_a_{nil}; - id mechanics_reduce_b_{nil}; - std::size_t mechanics_cell_capacity_{0}; - std::size_t mechanics_contact_capacity_{0}; id contact_rows_{nil}; id contact_bodies_{nil}; id contact_response_{nil}; diff --git a/cpp/python/bindings.cpp b/cpp/python/bindings.cpp index 0001c9f..a6b246a 100644 --- a/cpp/python/bindings.cpp +++ b/cpp/python/bindings.cpp @@ -30,7 +30,6 @@ NB_MODULE(_core, module) { .value("GROWTH", microsimulator::BackendFeature::growth) .value("SPECIES", microsimulator::BackendFeature::species) .value("CELL_CONTACTS", microsimulator::BackendFeature::cell_contacts) - .value("CELL_MECHANICS", microsimulator::BackendFeature::cell_mechanics) .value("EXTERNAL_CONSTRAINTS", microsimulator::BackendFeature::external_constraints) .value("SIGNALS", microsimulator::BackendFeature::signals) .value("COUPLED_RATES", microsimulator::BackendFeature::coupled_rates) @@ -106,17 +105,6 @@ NB_MODULE(_core, module) { .value("EXPONENTIAL", microsimulator::GrowthLoadLaw::exponential) .value("LINEAR", microsimulator::GrowthLoadLaw::linear); - nb::enum_(module, "SolverStatus") - .value("CONVERGED", microsimulator::SolverStatus::converged) - .value("ITERATION_LIMIT", microsimulator::SolverStatus::iteration_limit) - .value("BREAKDOWN", microsimulator::SolverStatus::breakdown); - - nb::enum_(module, "SolverBreakdown") - .value("NONE", microsimulator::SolverBreakdown::none) - .value("NON_FINITE_RESIDUAL", microsimulator::SolverBreakdown::non_finite_residual) - .value("NON_FINITE_CURVATURE", microsimulator::SolverBreakdown::non_finite_curvature) - .value("NON_POSITIVE_CURVATURE", microsimulator::SolverBreakdown::non_positive_curvature); - nb::class_(module, "Vec3") .def(nb::init(), "x"_a = 0.0F, "y"_a = 0.0F, "z"_a = 0.0F) .def_rw("x", µsimulator::Vec3::x) @@ -490,33 +478,9 @@ NB_MODULE(_core, module) { }, "slot"_a); - nb::class_(module, "CellCorrection") - .def_ro("translation", µsimulator::CellCorrection::translation) - .def_ro("rotation", µsimulator::CellCorrection::rotation) - .def_ro("length", µsimulator::CellCorrection::length); - - nb::class_(module, "MechanicsParameters") + nb::class_(module, "FlowDriftParameters") .def(nb::init<>()) - .def_rw("mu_a", µsimulator::MechanicsParameters::mu_a) - .def_rw("gamma", µsimulator::MechanicsParameters::gamma) - .def_rw("residual_rms_tolerance", - µsimulator::MechanicsParameters::residual_rms_tolerance) - .def_rw("max_iterations", µsimulator::MechanicsParameters::max_iterations); - - nb::class_(module, - "MechanicsIntegrationParameters") - .def(nb::init<>()) - .def_rw("max_rotation_radians", - µsimulator::MechanicsIntegrationParameters::max_rotation_radians) - .def_rw("require_convergence", - µsimulator::MechanicsIntegrationParameters::require_convergence); - - nb::class_(module, "SolverReport") - .def_ro("status", µsimulator::SolverReport::status) - .def_ro("breakdown", µsimulator::SolverReport::breakdown) - .def_ro("iterations", µsimulator::SolverReport::iterations) - .def_ro("initial_residual_rms", µsimulator::SolverReport::initial_residual_rms) - .def_ro("final_residual_rms", µsimulator::SolverReport::final_residual_rms); + .def_rw("max_rotation_radians", µsimulator::FlowDriftParameters::max_rotation_radians); nb::class_(module, "GrowthLoadResponse") .def(nb::init<>()) @@ -559,10 +523,6 @@ NB_MODULE(_core, module) { .def_ro("axial_loads", µsimulator::ContactDynamicsResult::axial_loads) .def_ro("length_increments", µsimulator::ContactDynamicsResult::length_increments); - nb::class_(module, "MechanicsSolveResult") - .def_ro("corrections", µsimulator::MechanicsSolveResult::corrections) - .def_ro("report", µsimulator::MechanicsSolveResult::report); - nb::class_(module, "Simulation") .def(nb::init(), "backend"_a = microsimulator::BackendKind::cpu, "reserved_capacity"_a = 0, @@ -594,7 +554,7 @@ NB_MODULE(_core, module) { microsimulator::python::exclusive(µsimulator::Simulation::remove_cell), "id"_a) .def("apply_flow_drift", microsimulator::python::released(µsimulator::Simulation::apply_flow_drift), "dt"_a, - "integration"_a = microsimulator::MechanicsIntegrationParameters{}) + "parameters"_a = microsimulator::FlowDriftParameters{}) .def("add_plane_constraint", microsimulator::python::exclusive(µsimulator::Simulation::add_plane_constraint), "plane"_a) @@ -674,17 +634,6 @@ NB_MODULE(_core, module) { .def("find_external_contacts", microsimulator::python::released(µsimulator::Simulation::find_external_contacts), "parameters"_a = microsimulator::ConstraintContactParameters{}) - .def("solve_cell_mechanics", - microsimulator::python::released(µsimulator::Simulation::solve_cell_mechanics), - "mechanics_parameters"_a = microsimulator::MechanicsParameters{}, - "contact_parameters"_a = microsimulator::ContactParameters{}, - "constraint_parameters"_a = microsimulator::ConstraintContactParameters{}) - .def("relax_cell_mechanics", - microsimulator::python::released(µsimulator::Simulation::relax_cell_mechanics), - "mechanics_parameters"_a = microsimulator::MechanicsParameters{}, - "contact_parameters"_a = microsimulator::ContactParameters{}, - "integration_parameters"_a = microsimulator::MechanicsIntegrationParameters{}, - "constraint_parameters"_a = microsimulator::ConstraintContactParameters{}) .def( "solve_depth_averaged_flow", [](microsimulator::Simulation& simulation, const microsimulator::SignalGridSpec& spec, diff --git a/cpp/shared/constants.def b/cpp/shared/constants.def index c7eb9a3..7ae4fcc 100644 --- a/cpp/shared/constants.def +++ b/cpp/shared/constants.def @@ -8,8 +8,6 @@ MICROSIMULATOR_SHARED_FLOAT(inverse_sqrt_two, 0.7071067811865475) MICROSIMULATOR_SHARED_FLOAT(float_epsilon, 1.1920928955078125e-7) // Golden-section iterations used to minimize distance along a capsule segment. MICROSIMULATOR_SHARED_UINT(segment_minimization_iterations, 40) -// Unknowns per cell in the mechanics system: translation, rotation, length. -MICROSIMULATOR_SHARED_UINT(mechanics_degrees_of_freedom, 7) // Growth load laws of the contact dynamics solve, in the order of GrowthLoadLaw. MICROSIMULATOR_SHARED_UINT(growth_load_law_none, 0) MICROSIMULATOR_SHARED_UINT(growth_load_law_exponential, 1) diff --git a/cpp/shared/device_types.h b/cpp/shared/device_types.h index cf90f77..427ba33 100644 --- a/cpp/shared/device_types.h +++ b/cpp/shared/device_types.h @@ -14,7 +14,9 @@ struct RateInstruction { float value; }; -struct MechanicsDofs { +// What a set of contact multipliers does to one cell: its velocity with the +// elongation rate in w, and its angular velocity with the axial load in w. +struct ContactResponse { float4 linear_length; float4 rotation; }; diff --git a/docs/architecture/0002-contact-mechanics.md b/docs/architecture/0002-contact-mechanics.md index c6cdaeb..e87a65a 100644 --- a/docs/architecture/0002-contact-mechanics.md +++ b/docs/architecture/0002-contact-mechanics.md @@ -5,7 +5,7 @@ ## Context -Rod contact and mechanical relaxation require irregular GPU work, dynamic topology, reductions, and iterative solves. A fixed-stride contact table is unsafe at high density and mixes cell pairs, planes, and spheres through integer conventions. A generic portable GPU abstraction would also prevent Metal and CUDA from using their native scan, sort, reduction, and synchronization facilities. +Rod contact and its mechanics require irregular GPU work, dynamic topology, reductions, and iterative solves. A fixed-stride contact table is unsafe at high density and mixes cell pairs, planes, and spheres through integer conventions. A generic portable GPU abstraction would also prevent Metal and CUDA from using their native scan, sort, reduction, and synchronization facilities. ## Decision @@ -27,29 +27,19 @@ There is no scientific contact cap. Allocation failure is explicit. In determini The narrow phase distinguishes one-row from two-row contacts and weights each row of a two-row contact by `1/sqrt(2)`. Degenerate normals are resolved deterministically by projecting center displacement perpendicular to the rod axis; if that also vanishes, the least-aligned Cartesian basis axis defines a perpendicular. Every emitted normal must be finite and unit length. -The solver exposes a matrix-free operator rather than a materialized sparse matrix. The operator is a regularized seven-DOF system. The public result includes convergence status, iteration count, initial and final residuals, and a breakdown reason. A backend may use native reductions and preconditioning, but it must apply the same declared operator and convergence criterion. - -For a cell with full capsule length `L = l + 2r`, the reference regularizer uses mass `m = mu_a L`, axial inertia `m r^2 / 2`, transverse inertia `m (L^2 + 3r^2) / 12`, and length weight `gamma`. The operator adds `gamma^-1 M`. A slender-rod tensor gives axial rotation zero energy; this finite-radius tensor does not, which makes the declared seven-DOF operator positive definite for valid cells. - -The reference solver starts from zero and uses unpreconditioned conjugate gradient. Residual RMS is `sqrt(dot(r, r) / cell_count)`, and the default iteration limit is `7 * cell_count`. Apparent convergence is checked by recomputing `B^T b - A delta_q`; non-finite residuals, non-finite curvature, and non-positive curvature are reported as typed breakdowns rather than allowed to contaminate the simulation. - -The [contact dynamics](0026-contact-dynamics.md) step is the alternative to this relaxation: it solves contact with non-negative forces and growth in one convex problem. - -Integration is a separate backend-neutral operation over a solver result. It requires convergence by default, applies translation directly, interprets the rotation vector as axis-angle and caps it at five degrees, and computes the length increment as `max(0, desired_increment + delta_l)`. Mechanics may suppress requested elongation but may not directly shorten a cell. All updates are validated before any world-state array is mutated. `Simulation.step` remains the growth-only primitive; `relax_cell_mechanics` is the explicit contact-relaxation operation. - -Walls are impenetrable. The regularized solve weighs each wall row against the cells pressing on it, so on its own it leaves a crowded cell part-way through a wall. After integrating a pass, `relax_cell_mechanics` therefore moves every mobile cell that is more than `1e-4` inside a constraint out of it. Each end of the cell's centerline moves back along the normals of the contacts it is inside, to a depth of `5e-5` so the resting contact stays active for the next solve and visible to contact analysis; a mid-span contact moves both ends; and the cell is rebuilt at its own length between the moved ends. A rod tilted against a wall comes to lie along it, and a rod wedged upright between a floor and a ceiling is turned flat. Up to eight sweeps settle the ends against each other. Length is unchanged, fixed cells are not moved, and the overlap this opens between cells is left to the next contact solve. A cell deeper than a wall's mid-plane would resolve toward the far face, so when any correction exceeds its cell's radius the pass is applied in up to sixteen equal parts that each move a cell at most one radius, projecting after each part. The projection uses the host constraint geometry on every backend. A wall thinner than a cell's diameter, or a correction longer than sixteen radii, is outside this guarantee. +Contacts are the input to the [contact dynamics](0026-contact-dynamics.md) solve, which turns each one into a row with a non-negative force and solves contact together with growth. That record defines the cell drag, the solve, and how cells and walls are kept apart. Planes, spheres, boxes, and cylinders are stored in a simulation-owned constraint set with stable IDs shared across constraint kinds. A plane declares a point and a normalized inward normal; its permitted half-space lies in the inward direction. Each finite constraint explicitly declares whether cells are permitted inside or outside. Negative separation means penetration in every case. Plane half-spaces and inside regions of convex finite constraints are endpoint-extremal, so their contact generation examines both capsule centerline endpoints. Outside regions of finite convex constraints instead minimize the obstacle signed-distance function over the complete centerline and subtract the capsule radius. Sphere minimization uses exact projection onto the segment. Box and cylinder minimization use a deterministic 40-iteration ternary bracket over their convex signed-distance functions; equal sampled distances retain the middle third, selecting a stable central representative on a flat minimum. Cylinder evaluation also includes the analytic radial-axis and axial-center projections, avoiding iterative location error in the barrel and cap cases. Expanded axis-aligned obstacle bounds provide a conservative early rejection for boxes and cylinders. -When a finite outside constraint is closest at the rod mid-span, contact generation emits one row tagged `interior` at that centerline location. When the minimum lies at an endpoint, every endpoint within the activation margin emits its own row: a rod lying against a flat face at a slight angle has both ends inside the surface, and a single row at the deeper end lets the solve answer with a rotation that drives the other end further in. Two endpoint rows each have weight `coefficient / sqrt(2)`; a single row has the full coefficient. An external contact normal points from the permitted region toward the constraint boundary. `point_on_cell` is the capsule surface point reached from the selected centerline location along that normal. Sphere-center, box-face-tie, and cylinder-axis degeneracies use documented deterministic directions before applying the inside/outside orientation. External rows use the same seven-DOF cell Jacobian as pair contacts, but have no second cell term. They therefore enter the declared system as `B_external^T B_external` and `B_external^T b_external` alongside the pair rows. A simulation with constraints must execute both geometry and mechanics on a backend that advertises external-constraint support; unsupported native backends fail explicitly instead of dropping the boundary rows. +When a finite outside constraint is closest at the rod mid-span, contact generation emits one row tagged `interior` at that centerline location. When the minimum lies at an endpoint, every endpoint within the activation margin emits its own row: a rod lying against a flat face at a slight angle has both ends inside the surface, and a single row at the deeper end lets the solve answer with a rotation that drives the other end further in. Two endpoint rows each have weight `coefficient / sqrt(2)`; a single row has the full coefficient. An external contact normal points from the permitted region toward the constraint boundary. `point_on_cell` is the capsule surface point reached from the selected centerline location along that normal. Sphere-center, box-face-tie, and cylinder-axis degeneracies use documented deterministic directions before applying the inside/outside orientation. A contact with a constraint has no second cell. A simulation with constraints must find those contacts on a backend that advertises external-constraint support; unsupported native backends fail explicitly instead of dropping the boundary contacts. The public location type is `RodContactLocation`, and `ExternalContact.location` distinguishes `negative`, `positive`, and `interior`. `RodEndpoint` remains a C++ and Python type alias, and the Python `ExternalContact.endpoint` accessor remains a compatibility alias for existing plane and sphere consumers. The C++ record field is intentionally named `location` because not every contact lies at an endpoint. -The Metal and CUDA implementations upload stable-ID-sorted tagged constraints and run native count/scan/fill pipelines over cell-constraint pairs. Each pair emits zero, one, or two location-tagged rows into dynamic storage. Pair and external rows are then combined in the native solver buffers; a reserved invalid second slot marks the one-sided row inside each private operator without reintroducing a sentinel into the public contact model. +The Metal and CUDA implementations upload stable-ID-sorted tagged constraints and run native count/scan/fill pipelines over cell-constraint pairs. Each pair emits zero, one, or two location-tagged rows into dynamic storage. -CPU, Metal, and CUDA own separate implementations of the contact geometry and the system operator. They share the conjugate-gradient iteration in `cpp/core/mechanics_solver.hpp`, contact fixtures, operator probes, tolerances, and exact location-tag invariants. Metal uses Metal compute pipelines and MSL; CUDA uses CUDA C++ and the CUDA Runtime API. +CPU, Metal, and CUDA own separate implementations of the contact geometry. They share contact fixtures, tolerances, and exact location-tag invariants. Metal uses Metal compute pipelines and MSL; CUDA uses CUDA C++ and the CUDA Runtime API. ### Neighbor reporting @@ -61,13 +51,10 @@ CPU, Metal, and CUDA own separate implementations of the contact geometry and th 2. Shared contact fixtures and a dynamic contact-graph API. 3. Deterministic sweep-and-prune candidate staging. 4. Native Metal and CUDA count/scan/fill pipelines. -5. CPU matrix-free operator and diagnosed conjugate-gradient solver. -6. Native Metal and CUDA operator, reductions, and solver loops. -7. Typed plane, sphere, box, and cylinder constraint geometry. -8. Full-centerline finite-obstacle contact fixtures, including clear endpoints with penetrating mid-spans. -9. CPU external-constraint mechanics rows. -10. Native Metal external-constraint conformance. -11. Native CUDA external-constraint conformance. +5. Typed plane, sphere, box, and cylinder constraint geometry. +6. Full-centerline finite-obstacle contact fixtures, including clear endpoints with penetrating mid-spans. +7. Native Metal external-constraint conformance. +8. Native CUDA external-constraint conformance. This sequence isolates geometry disagreements before solver behavior can hide them. Backend support requires the corresponding shared scenario to pass on real hardware. diff --git a/docs/architecture/0009-fixed-cells.md b/docs/architecture/0009-fixed-cells.md index fabb309..dfc6a97 100644 --- a/docs/architecture/0009-fixed-cells.md +++ b/docs/architecture/0009-fixed-cells.md @@ -13,13 +13,7 @@ MicroSimulator needs the useful behavior without introducing a second, incompati Fixedness is a persistent Boolean cell attribute. A fixed cell remains a rod: growth, species rates, signal sampling and secretion, and division continue to use the ordinary cell lifecycle. Daughters inherit the parent's fixedness. Callers may change the attribute by stable cell identifier. -Mechanics constrains all seven correction degrees of freedom for fixed cells. With `P` denoting the diagonal projection that zeros fixed-cell degrees of freedom, the constrained system is - -```text -(P A P + I - P) x = P b. -``` - -This preserves a symmetric positive-definite operator for conjugate gradient, makes the fixed solution entries exactly zero, and lets movable cells react to contacts with immovable cells. Mechanics integration independently ignores fixed-cell translation, rotation, and contact-induced length correction. An explicit desired growth increment still increases rod length. +A fixed cell has no mobility in the [contact dynamics](0026-contact-dynamics.md) solve: contact forces do not move or turn it, and the flow does not carry it. Movable cells react to contacts with it as they do with a wall. It still elongates, at its growth rate scaled by the growth load response to the axial load its contacts put on it, and that elongation closes the gaps of its contacts. Checkpoints record `fixed` for every active cell. diff --git a/docs/architecture/0014-native-controllers.md b/docs/architecture/0014-native-controllers.md index fd50ec7..a8a7754 100644 --- a/docs/architecture/0014-native-controllers.md +++ b/docs/architecture/0014-native-controllers.md @@ -29,15 +29,13 @@ A controller-backed model resumes through `resume(context, checkpoint)`. The ope 2. apply cell attributes, species, and fixed-state updates; 3. apply division requests and division callbacks; 4. apply requested cell removals; -5. execute `Simulation.step(dt)` for growth and typed rate plans; -6. apply flow drift when enabled in the mechanics configuration; and -7. execute exactly `MechanicsConfig.passes` contact/relaxation passes when mechanics is configured and cells remain. Each pass ends by projecting mobile cells out of the external constraints, so cells end the step resting on or clear of the walls. +5. execute `Simulation.step(dt, ...)` with the mechanics configuration, which advances growth and contact together with the [contact dynamics](0026-contact-dynamics.md) solve, carrying the cells with the flow when flow drift is enabled, and then advances the typed rate plans. Without a mechanics configuration the step is `Simulation.step(dt)`: growth and rate plans alone. -With `MechanicsConfig.contact_dynamics` set, steps 5 to 7 are instead flow drift when enabled, then `Simulation.step(dt, ...)` with the [contact dynamics](0026-contact-dynamics.md) parameters, which advances growth and contact together before the typed rate plans. `NativeController.last_contact_dynamics` holds that step's report, the axial load on each cell, and the elongation each cell was allowed. +`NativeController.last_contact_dynamics` holds that step's report, the axial load on each cell, and the elongation each cell was allowed. -`UniformLengthDivision.jitter_z` controls only the random perturbation added to daughter orientation: `None` disables jitter, `False` adds XY-only jitter, and `True` adds XYZ jitter. Native normalization can change an inherited nonzero Z component even when the added Z perturbation is zero. Division places daughters along the parent's three-dimensional axis; subsequent contact relaxation and flow drift remain three-dimensional. See the [planarity diagnostics and tutorial audit](../tutorials/planarity.md) for reproducible examples and the limits of finite-height confinement. +`UniformLengthDivision.jitter_z` controls only the random perturbation added to daughter orientation: `None` disables jitter, `False` adds XY-only jitter, and `True` adds XYZ jitter. Native normalization can change an inherited nonzero Z component even when the added Z perturbation is zero. Division places daughters along the parent's three-dimensional axis; the contact solve and flow drift remain three-dimensional. See the [planarity diagnostics and tutorial audit](../tutorials/planarity.md) for reproducible examples and the limits of finite-height confinement. -The standard payload records a stable model ID and version, completed-step counter, model JSON state, random stream, and every mechanics parameter. `NativeController.from_checkpoint` validates and restores that payload while the checkpoint's native state retains rate plans, signal grids, geometry, and lineage. The number of mechanics passes is an explicit part of the native-controller contract. +The standard payload records a stable model ID and version, completed-step counter, model JSON state, random stream, and every mechanics parameter. `NativeController.from_checkpoint` validates and restores that payload while the checkpoint's native state retains rate plans, signal grids, geometry, and lineage. Every mechanics parameter is an explicit part of the native-controller contract. ## Consequences diff --git a/docs/architecture/0024-biomass-accounting.md b/docs/architecture/0024-biomass-accounting.md index e0adddf..ef980c7 100644 --- a/docs/architecture/0024-biomass-accounting.md +++ b/docs/architecture/0024-biomass-accounting.md @@ -6,6 +6,6 @@ Native division preserves the parent's outer endpoints and satisfies l1 + l2 = l Growth retains the elongation law dl/dt = g l. Consequently dB/dt = pi r² g l, not g B. `RatePlanBuilder.cell_volume_change_rate()` returns the realized change (B_after - B_before)/dt during the current growth step, with zero at dt=0. A nutrient sink `-rates.cell_volume_change_rate()/yield` therefore consumes exactly the biomass increment divided by yield, up to floating-point error. `rates.cell_volume()` and `microsimulator.biomass.biomass_volume` expose B. A negative concentration is a rejected step, never an invitation to clip away a mass-balance error. -Contact relaxation without explicitly prescribed length increments preserves each rod's length. Numerical overlap corrections therefore cannot manufacture biomass after the biological update. Direct geometry edits and explicitly prescribed mechanical length increments are externally imposed changes; callers must account for their biomass and intracellular amounts. +The contact solve changes a rod's length only by the elongation its growth load response allows, which is the growth step that uptake is charged for. Resolving overlap moves and turns cells without changing their lengths, so it cannot manufacture biomass. Direct geometry edits are externally imposed changes; callers must account for their biomass and intracellular amounts. Colony resistance uses a calibrated biomass-density closure derived from B. Its density must be deposited conservatively over a physical averaging scale independent of voxel size. It is not an exact solid-occupancy reconstruction of individual capsules. diff --git a/docs/architecture/0026-contact-dynamics.md b/docs/architecture/0026-contact-dynamics.md index 93f91e1..2e697a3 100644 --- a/docs/architecture/0026-contact-dynamics.md +++ b/docs/architecture/0026-contact-dynamics.md @@ -5,13 +5,13 @@ ## Context -The regularized least-squares relaxation of [ADR 0002](0002-contact-mechanics.md) treats contacts as equalities, minimizes the sum of squared overlaps, and runs after growth is committed. A colony that fills a closed space therefore keeps elongating into itself, pairs pushed past one radius invert and stay inverted, and no value of the length weight suits both a free colony and a jam. +A contact scheme for growing cells has to keep cells apart in a full space and let a full space stop growing. A regularized least-squares relaxation of the contacts found in [ADR 0002](0002-contact-mechanics.md), applied after growth is committed, does neither: it treats contacts as equalities and minimizes the sum of squared overlaps, so a colony that fills a closed space keeps elongating into itself, pairs pushed past one radius invert and stay inverted, and no weighting suits both a free colony and a jam. Growing rod-shaped cells are simulated without those failures by solving contact as a complementarity problem: contact forces are non-negative, gaps stay non-negative, and a force acts only where a gap is closed ([Yan, Zhang, and Shelley 2019](https://arxiv.org/abs/1811.04736); [Yan et al. 2020](https://arxiv.org/abs/1909.06623)). Growth enters the same problem when a cell's elongation responds to the compressive load its contacts put on it ([Weady et al. 2024](https://arxiv.org/abs/2405.10158); [Lerchner](https://home.cit.tum.de/~ler/html-data/bacteria/cell-collectives.pdf)). ## Decision -`Simulation.step(dt, ContactDynamicsParameters)` advances growth and contact together. It is selected per controller by `MechanicsConfig(contact_dynamics=ContactDynamicsConfig(...))`; without it the controller grows the cells and runs least-squares relaxation passes. +`Simulation.step(dt, ContactDynamicsParameters)` advances growth and contact together. A controller configured with `MechanicsConfig` takes every step this way; `Simulation.step(dt)` alone grows cells without contact. ### The problem of one substep @@ -22,7 +22,7 @@ gap(g) = phi + h J^T M^-1 J g - h L^T (r * f(L g)) + c g ``` - `J g` is the force and torque the rows put on each cell, and `J^T` maps cell velocities to gap rates. -- `M` is the drag of each cell on its surroundings: `drag * L` in translation for a capsule of full length `L`, with the finite-radius rod inertias of ADR 0002 in rotation. A fixed cell has no mobility. +- `M` is the drag of each cell on its surroundings. For a capsule of full length `L = l + 2r` it is `m = drag * L` in translation, `m r^2 / 2` about the axis, and `m (L^2 + 3 r^2) / 12` across it; the finite radius keeps rotation about the axis from being free. A fixed cell has no mobility. - `L g` is the axial load on each cell. A row contributes its multiplier times the cell's length lever, the fraction of the cell's elongation that closes that contact: the cylinder stretches uniformly about its center and the caps ride on its ends, so the lever is one half for a contact on a cap along the axis and zero for a contact on the side. - `r` is the nominal elongation rate `growth_rate * length`, taken from the lengths at the start of the step, and `f` is the growth load response. `L^T` maps elongation to the gap it closes. - `c` is the compliance of the row: `1 / contact_stiffness` between cells and `1 / wall_stiffness` against a constraint. @@ -62,7 +62,7 @@ The stepping carries no state between steps, so a resumed run repeats an uninter ### Walls -Constraints are rows in the same solve. A box or cylinder that cells live inside contributes one row for every face a cell end is near, from `find_external_contact_faces`: each face is an independent half-space, and a row for the nearest face alone leaves a cell end in a corner free to cross the other wall. These rows come from the host constraint geometry on every backend. The wall projection of ADR 0002 is not applied. +Constraints are rows in the same solve. A box or cylinder that cells live inside contributes one row for every face a cell end is near, from `find_external_contact_faces`: each face is an independent half-space, and a row for the nearest face alone leaves a cell end in a corner free to cross the other wall. These rows come from the host constraint geometry on every backend. ### Order within a step diff --git a/docs/development/validation.md b/docs/development/validation.md index ef39fde..6bf36ba 100644 --- a/docs/development/validation.md +++ b/docs/development/validation.md @@ -46,7 +46,7 @@ The native gate performs a fresh Metal-enabled build, constructs every enumerate Together, these gates cover: - growth, equal and asymmetric division, stable identity, and lineage; -- cell contacts, plane, sphere, box, and cylinder constraints, full-capsule finite-obstacle contact, fixed cells, and mechanics relaxation; +- cell contacts, plane, sphere, box, and cylinder constraints, full-capsule finite-obstacle contact, fixed cells, and contact dynamics; - species, signal transport, Forward Euler, Crank-Nicolson, backward Euler, and coupled rates; - depth-averaged Hele-Shaw/Darcy flow and resolved MAC Stokes-Brinkman flow; - checkpoint round trips, exact controller resume, and deterministic runtime random state; @@ -82,7 +82,7 @@ The Python and C++ suites exercise more than numerical parity: - SBML fixtures cover supported Level 3 Version 2 Core symbols and operators, ordered metadata, local and global parameters, stoichiometry, and explicit rejection of unsupported semantics. - Signal fixtures cover mass conservation, fixed reservoirs, periodic upwind advection, reduced dimensions, 3D interpolation, nonuniform affine sources and losses, stability rejection, checkpoint round trips, and diagnosed solver convergence. - Coupled fixtures cover old-field sampling, post-growth intracellular rates, amount-to-voxel conversion, repeated scatter destinations, empty colonies, and failure atomicity. -- Contact and mechanics fixtures cover sparse and dense candidate staging, coincident cells, stable ordering after slot reuse, operator properties, convergence and breakdown diagnostics, buffer growth, fixed-cell projection, and integrated geometry. +- Contact and contact dynamics fixtures cover sparse and dense candidate staging, coincident cells, stable ordering after slot reuse, complementarity of the solved contact forces, agreement with the CPU solution, iteration limits, buffer growth, fixed cells, and the chamber and colony trajectories. - Checkpoint fixtures compare every persisted field before continuing execution and reject corrupt, malformed, non-finite, duplicate, unknown, or unsupported data. - Batch and manifest fixtures cover seed reproducibility, model digests, periodic output names, stopping rules, path resolution, collision preflight, and import-before-authentication hazards. - Scene and viewer fixtures cover strict cross-language decoding, RFC 8785 digests, browser-safe identities, coloring, signal slicing, token and origin checks, WebSocket messages, reset, and checkpointing. diff --git a/docs/microfluidics.md b/docs/microfluidics.md index 901936f..cd6df49 100644 --- a/docs/microfluidics.md +++ b/docs/microfluidics.md @@ -7,7 +7,7 @@ MicroSimulator connects the physical environment of a microfluidic device to the 1. **Describe the device.** Define the channels, cavities, and obstacles that shape the experiment. Device helpers produce mechanical constraints, solid transport masks, and inlet and outlet boundaries from one description. The [device tutorial](tutorials/microfluidics.md) covers traps and channels; the [pillar example](tutorials/flow-solvers.md) shows curved obstacles. 2. **Solve the flow.** Choose a shallow or resolved steady-flow model, set the mean inlet speed, and obtain the face velocities used by solute transport. Refresh the field when the model's stationary resistance changes. 3. **Add biology.** Define founders, growth and division rules, intracellular rates, and exchange with extracellular nutrients or signals. Growth, dilution, division, and uptake share an explicit [biochemical biomass convention](architecture/0024-biomass-accounting.md). -4. **Define attachment and exit rules.** Fixed cells represent an attached population. Free cells drift and rotate in the velocity field before contact relaxation. Model rules determine attachment, daughter release, and washout, while stable identifiers retain lineage history. +4. **Define attachment and exit rules.** Fixed cells represent an attached population. Free cells drift and rotate in the velocity field, with their contacts solved in the same step. Model rules determine attachment, daughter release, and washout, while stable identifiers retain lineage history. 5. **Run and measure.** Use the [live viewer](../viewer/README.md) to inspect the model, [batch runs](formats/run-manifest-v1.md) to compare parameters and seeds, and [analysis datasets](analysis/recipes.md) to measure the resulting populations and fields. Checkpoints preserve the state needed to resume an experiment. The [microfluidic trap](../examples/microfluidic_trap.py) is a compact starting model. The [Danino clock](../examples/tutorials/danino_clock.py) adds a quorum-sensing circuit; the [biopixel tutorial](tutorials/microfluidics.md#a-source-backed-prindle-biopixel-example) combines a single-trap model with published cavity dimensions and a supplied CAD layout whose provenance is documented. @@ -29,7 +29,7 @@ Solutes move through the device by conservative advection and diffusion with rea Attached biomass can change flow resistance through a conservatively smoothed density field. This provides an empirical feedback between a stationary population and its nutrient supply. The resistance coefficient, smoothing radius, and flow-refresh interval are explicit model choices. Freely moving cells are excluded from the stationary resistance used by the tutorials. -Free-cell motion uses the local velocity and a finite-aspect Jeffery orientation approximation, followed by contact relaxation. This kinematic coupling approximates rods as equivalent spheroids for rotation. Cell-scale hydrodynamic forces, lubrication, and predictive adhesion or detachment are outside its scope. The [flow-drift design](architecture/0021-flow-drift.md) specifies the approximation and integration limits. +Free-cell motion uses the local velocity and a finite-aspect Jeffery orientation approximation as the known velocity of the contact solve. This kinematic coupling approximates rods as equivalent spheroids for rotation. Cell-scale hydrodynamic forces, lubrication, and predictive adhesion or detachment are outside its scope. The [flow-drift design](architecture/0021-flow-drift.md) specifies the approximation and integration limits. ## Cell-occupied extracellular volume diff --git a/docs/tutorials/biophysics-and-growth.md b/docs/tutorials/biophysics-and-growth.md index 55b4647..df520d9 100644 --- a/docs/tutorials/biophysics-and-growth.md +++ b/docs/tutorials/biophysics-and-growth.md @@ -113,11 +113,11 @@ uv run microsimulator view \ --open ``` -Five `PlaneConstraintInit` values define a floor and four walls. Each plane has a point, an inward unit normal, and a positive row coefficient. The permitted half-space lies in the inward direction. The founder begins at `z = 0.5`, so its radius-0.5 capsule initially touches rather than penetrates the floor. +Five `PlaneConstraintInit` values define a floor and four walls. Each plane has a point and an inward unit normal. The permitted half-space lies in the inward direction. The founder begins at `z = 0.5`, so its radius-0.5 capsule initially touches rather than penetrates the floor. -The tutorial sets `MechanicsConfig(gamma=20)`. Here, `gamma` is the positive length regularizer in the seven-degree-of-freedom mechanics operator. It affects how strongly changes in cell length are penalized during relaxation. +The tutorial uses the default `MechanicsConfig()`. Each step solves growth and contact together: cells and walls push with non-negative contact forces while the cells elongate, as the [contact dynamics design](../architecture/0026-contact-dynamics.md) describes. The box is open at the top, so growth that ignores load always has somewhere to go; a closed space needs a growth load response such as `growth_law="linear"` with a stall load. -After each biological step the controller runs a mechanics pass. Pair and constraint contacts are re-derived dynamically; there is no `max_planes`, `max_contacts`, or fixed contact-table capacity to tune. +Pair and constraint contacts are re-derived dynamically; there is no `max_planes`, `max_contacts`, or fixed contact-table capacity to tune. ## Experiments diff --git a/docs/tutorials/discrete-state-and-contacts.md b/docs/tutorials/discrete-state-and-contacts.md index 27c9282..2de1422 100644 --- a/docs/tutorials/discrete-state-and-contacts.md +++ b/docs/tutorials/discrete-state-and-contacts.md @@ -2,7 +2,7 @@ This tutorial uses plasmid segregation and conjugation to show how discrete biological state, stochastic events, and contact-dependent behavior fit into a MicroSimulator model. -Both models start with centers at Z=0 and axes in XY, and division adds no orientation jitter. Neither has mechanical Z confinement: daughters inherit the parent axis and contact relaxation remains three-dimensional. See [division jitter and out-of-plane motion](planarity.md). +Both models start with centers at Z=0 and axes in XY, and division adds no orientation jitter. Neither has mechanical Z confinement: daughters inherit the parent axis and the contact solve remains three-dimensional. See [division jitter and out-of-plane motion](planarity.md). For backend selection, PowerShell syntax, quoted JSON parameters, and paths with spaces, see [tutorial commands by backend and shell](commands.md#choose-a-shell). Multiline commands on this page use POSIX shell backslashes; the guide provides the PowerShell equivalents and [explicit CPU, Metal, and CUDA trap launches](commands.md#run-the-same-trap-on-cpu-metal-or-cuda). @@ -65,7 +65,7 @@ for cell in simulation.cells(): neighbors = graph.neighbor_ids(cell.slot) ``` -Stable IDs identify cells across compaction and checkpoints. Slots are dense, temporary indices used to query one graph. Recompute the graph after growth, division, or mechanical relaxation; neighbor lists are not persistent cell state. +Stable IDs identify cells across compaction and checkpoints. Slots are dense, temporary indices used to query one graph. Recompute the graph after a step or a division; neighbor lists are not persistent cell state. Parallel rods can produce two geometric contact rows. `neighbor_ids(slot)` returns ascending unique stable IDs, so a pair is one biological neighbor even when the mechanics operator needs two rows. Constraint contacts are a separate typed graph and never appear as cell neighbors. diff --git a/docs/tutorials/microfluidics.md b/docs/tutorials/microfluidics.md index d06a13a..ab191aa 100644 --- a/docs/tutorials/microfluidics.md +++ b/docs/tutorials/microfluidics.md @@ -2,7 +2,7 @@ This tutorial connects device geometry, flowing media, and cell biology in runnable MicroSimulator models. The [modeling guide](../microfluidics.md) introduces the workflow and the choice of flow solver. Four examples cover the range: -These models use XY-only division jitter and finite-height 3D confinement. A thin cavity can encourage a monolayer, but it does not force a common center Z or eliminate tilt; walls are impenetrable, so every relaxation pass leaves each cell resting on or clear of them, while overlap between cells remains a soft residual that depends on relaxation tolerance and passes. The [dimensionality audit](planarity.md) lists each device and reproduces these distinctions. +These models use XY-only division jitter and finite-height 3D confinement. A thin cavity can encourage a monolayer, but it does not force a common center Z or eliminate tilt; walls and neighbors are held apart by contact forces, and a contact overlaps by its force divided by its stiffness, with walls a hundred times stiffer than cells by default. The [dimensionality audit](planarity.md) lists each device and reproduces these distinctions. For backend selection, PowerShell syntax, quoted JSON parameters, and paths with spaces, see [tutorial commands by backend and shell](commands.md#choose-a-shell). Multiline commands on this page use POSIX shell backslashes; the guide provides the PowerShell equivalents and [explicit CPU, Metal, and CUDA trap launches](commands.md#run-the-same-trap-on-cpu-metal-or-cuda). @@ -65,7 +65,7 @@ The constructor's keyword arguments set the trap, channel, and wall dimensions; ## Flow on signals and on cells -The velocity field advects every signal with conservative upwind face fluxes under all three signal integrators. With `MechanicsConfig(flow_drift=True)`, the controller translates each non-fixed cell using the velocity sampled at its center and rotates it with a finite-aspect Jeffery approximation, so escaped cells travel down the channel and rods rotate in shear. Contact relaxation then resolves overlaps with walls or neighbors; with contact dynamics the flow velocity is part of the contact solve instead, so cells the flow presses together do not overlap. The [flow-drift design](../architecture/0021-flow-drift.md) describes this kinematic approximation and its integration limits. +The velocity field advects every signal with conservative upwind face fluxes under all three signal integrators. With `MechanicsConfig(flow_drift=True)`, the controller translates each non-fixed cell using the velocity sampled at its center and rotates it with a finite-aspect Jeffery approximation, so escaped cells travel down the channel and rods rotate in shear. That velocity is part of the contact solve, so cells the flow presses together or into a wall do not overlap. The [flow-drift design](../architecture/0021-flow-drift.md) describes this kinematic approximation and its integration limits. ## Washout @@ -174,7 +174,7 @@ The model also does not reproduce an experimentally established separation betwe - Let the lattice of site centers cover every position a cell can reach, with about a voxel of margin past each wall: sampling outside the lattice is an error. - Keep the mechanics walls enclosing the solid mask. The device helpers mark a site solid - when its center lies inside a wall, and relaxation keeps every cell center at least a + when its center lies inside a wall, and the contact solve keeps every cell center about a cell radius clear of each wall, so a cell against a wall always has a fluid site to sample. A hand-built mask needs the same rule; the [pillar channel](flow-solvers.md) shows it for curved walls. diff --git a/docs/tutorials/planarity.md b/docs/tutorials/planarity.md index ed04ee7..91ab5fc 100644 --- a/docs/tutorials/planarity.md +++ b/docs/tutorials/planarity.md @@ -2,7 +2,7 @@ MicroSimulator's native cell mechanics is three-dimensional. An initially planar colony and XY-only division jitter can remain planar in a particular run, but neither imposes a planar constraint. A shallow flow calculation or a one-layer signal grid does not change the mechanical degrees of freedom. -`UniformLengthDivision(jitter_z=False)` draws the usual three random perturbations and replaces the new Z perturbation with zero. It adds the resulting vector to each daughter's inherited direction, then the engine normalizes that direction. An inherited nonzero Z component therefore survives, and its normalized value can change when X or Y changes. Daughter centers are placed along the parent's three-dimensional axis before jitter is applied. `jitter_z=None` disables orientation jitter entirely; `jitter_z=True` includes the new Z perturbation. All three settings leave subsequent contact relaxation and flow drift three-dimensional. +`UniformLengthDivision(jitter_z=False)` draws the usual three random perturbations and replaces the new Z perturbation with zero. It adds the resulting vector to each daughter's inherited direction, then the engine normalizes that direction. An inherited nonzero Z component therefore survives, and its normalized value can change when X or Y changes. Daughter centers are placed along the parent's three-dimensional axis before jitter is applied. `jitter_z=None` disables orientation jitter entirely; `jitter_z=True` includes the new Z perturbation. All three settings leave the contact solve and flow drift three-dimensional. ## Tutorial audit @@ -24,7 +24,7 @@ The following contracts describe the checked-in models after the founder-initial | `biopixel_trap.py` | Centers Z=0.825, directions in XY; XY-only jitter | Trap floor Z=0 and roof Z=1.65; the channel is taller. The thin trap encourages a monolayer but does not force identical center Z or zero tilt. | | `examples/culture_dish.py` | Centers Z=0, directions in XY; XY-only jitter | Inside cylinder with caps at Z=±1. Finite-height confinement permits nonzero Z and tilt. | -“Monolayer” in the device tutorials describes a physical modeling intention supported by a thin cavity. Walls are impenetrable: each relaxation pass leaves every mobile cell resting on or clear of them. Overlap between cells remains a soft residual that depends on the contact solver tolerance and number of relaxation passes, and walls do not eliminate out-of-plane degrees of freedom. +“Monolayer” in the device tutorials describes a physical modeling intention supported by a thin cavity. Walls and neighbors are held apart by contact forces: a contact overlaps by its force divided by its stiffness, and walls are a hundred times stiffer than cells by default. Walls do not eliminate out-of-plane degrees of freedom. ## Reproduce and locate a departure @@ -42,7 +42,7 @@ Use `--plane-z 0.5` for the box scenario. Other model parameters accept JSON, fo The JSON records the backend, seed, timestep, model path and supplied parameters, model/controller state, source provenance, mechanics settings, initial and final geometry, and constraints. Every stage records maximum absolute center Z, displacement from the selected reference plane, absolute direction Z, and the change in each Z component for surviving cell IDs. The first event exceeding `1e-6` includes before/after geometry. This is a diagnostic detection tolerance, not a global engine guarantee. For an initially tilted cell, the first event is initialization; later stages still report their changes. -The probe wraps native Python entry points for the selected simulation in a dedicated process and restores them in `finally`. It observes division, geometry edits, removal, growth/chemistry, flow drift, and contact/constraint relaxation without duplicating the controller or drawing random numbers. Contact and wall relaxation use the same native entry point: the isolated contact-only and wall-only fixtures distinguish their causes. Arbitrary native work performed internally by a custom extension is outside these Python stage boundaries. Use this as a headless diagnostic, not inside a multithreaded application. +The probe wraps native Python entry points for the selected simulation in a dedicated process and restores them in `finally`. It observes division, geometry edits, removal, standalone flow drift, and the step that solves growth and contact and advances the chemistry, without duplicating the controller or drawing random numbers. Cell contacts and wall contacts are resolved by the same step: the isolated contact-only and wall-only fixtures distinguish their causes. Arbitrary native work performed internally by a custom extension is outside these Python stage boundaries. Use this as a headless diagnostic, not inside a multithreaded application. ## Findings and classification @@ -50,12 +50,12 @@ The seven fixtures in `scripts/diagnose_planarity.py` and their shared-backend a | Fixture | Observation | Classification | | --- | --- | --- | -| Separated planar rods | Two nonoverlapping X-oriented rods retain center Z=0 and direction Z=0 through relaxation. | Planar control case; no departure. | -| Crossing rods | Two rods at the same center, directions X and Y, centerline length 4 and radius 0.5, produce a Z-directed normal. One relaxation moves their centers to approximately ±0.4. | Expected 3D contact response. Crossing rods at zero centerline separation are an overlapping initialization if intended as a nonoverlapping planar colony. | -| Coincident parallel rods | Two identical X-oriented rods at one center use the deterministic degenerate-contact fallback; the normal points in Z and relaxation separates centers to approximately ±0.4. | Expected 3D degeneracy handling, also an overlapping initialization. | +| Separated planar rods | Two nonoverlapping X-oriented rods retain center Z=0 and direction Z=0 through the contact step. | Planar control case; no departure. | +| Crossing rods | Two rods at the same center, directions X and Y, centerline length 4 and radius 0.5, produce a Z-directed normal. The rods separate in Z by at most the overlap recovery limit per step and come to rest a diameter apart, with centers at approximately ±0.5. | Expected 3D contact response. Crossing rods at zero centerline separation are an overlapping initialization if intended as a nonoverlapping planar colony. | +| Coincident parallel rods | Two identical X-oriented rods at one center use the deterministic degenerate-contact fallback; the normal points in Z and the rods separate to centers at approximately ±0.5. | Expected 3D degeneracy handling, also an overlapping initialization. | | Planar division | An intentionally oversized planar parent divides with XY-only jitter without creating a Z component. | Planar division control; no departure. The fixture intentionally bypasses tutorial founder capping. | | Inherited tilt | A parent initialized with direction `(1, 0, 0.2)` has normalized Z≈0.196116. Division places daughters at Z≈±0.245145. Both geometry-edit calls request exactly zero added Z, although native normalization changes the daughters' direction Z. | Expected inherited geometry and normalization; an initially tilted setup cannot test preservation of a planar state. | -| Finite-height walls | A horizontal radius-0.5 rod at Z=0.8 intersects the ceiling at Z=1. One relaxation leaves it resting on the ceiling with its center at approximately 0.50005, the `5e-5` resting depth of the wall projection. Repeated default solves keep it there; tightening the residual tolerance to `1e-8` reduces penetration below `1e-6`. The center remains near Z=0.5. | Expected wall projection within a finite-height 3D space. Physical confinement bounds the cell by the walls but does not imply the plane Z=0. | +| Finite-height walls | A horizontal radius-0.5 rod at Z=0.8 intersects the ceiling at Z=1. The contact with the ceiling moves it down by at most the overlap recovery limit per step until it rests on the ceiling with its center at approximately Z=0.5. | Expected wall contact within a finite-height 3D space. Physical confinement bounds the cell by the walls but does not imply the plane Z=0. | | Vertical flow | Prescribed Z velocity 0.2 over dt=0.02 moves a center from Z=1 to approximately 1.004, with no division. | Expected 3D advection. XY-only jitter does not filter flow. | For zero closest-point separation, the CPU, Metal, and CUDA contact implementations first try the cross product of rod axes, then transverse center separation, then a deterministic perpendicular fallback. Two crossing XY axes have a Z-directed cross product; coincident X axes use a fallback that can also point in Z. Choosing these directions is consistent with the existing 3D contact contract. Suppressing them globally would change three-dimensional mechanics. @@ -66,13 +66,13 @@ Representative tutorial runs used seed 17, dt=0.02, a maximum of 1000 steps, and | --- | ---: | ---: | --- | | Biophysics: basics | 0 | 312 / 128 | None above diagnostic tolerance | | Biophysics: two_types | 0 | 149 / 128 | None above diagnostic tolerance | -| Biophysics: competition | 0 | 351 / 130 | None above diagnostic tolerance | +| Biophysics: competition | 0 | 354 / 128 | None above diagnostic tolerance | | Biophysics: short_cells | 0 | 325 / 128 | Division geometry edit at time≈0.02: direction Z≈0.000531725 | | Biophysics: box | 0.5 | 327 / 128 | Division geometry edit at time≈0.02: direction Z≈0.000531725 | | Gene expression: constitutive | 0 | 327 / 128 | None above diagnostic tolerance | | Signaling: single_gene | 0 | 179 / 128 | None above diagnostic tolerance | | Pillar channel | 0 | 394 / 131 | None above diagnostic tolerance | -| Biopixel trap | 0.825 | 478 / 128 | None above diagnostic tolerance | +| Biopixel trap | 0.825 | 479 / 128 | None above diagnostic tolerance | The two departures in this matrix are the tutorials' intentional XYZ jitter. The source audit covers additional scenarios without claiming that they all received these trajectory runs. The unchanged plane in the other runs provides reproducibility evidence for those particular initial states and durations, not proof of planar invariance. diff --git a/examples/microfluidic_trap.py b/examples/microfluidic_trap.py index ea416ee..5825677 100644 --- a/examples/microfluidic_trap.py +++ b/examples/microfluidic_trap.py @@ -25,7 +25,6 @@ from microsimulator import ( CellInit, CellUpdate, - ContactDynamicsConfig, ControllerStep, CoupledRatePlan, DivisionEvent, @@ -187,10 +186,7 @@ def build(context: ModelContext) -> NativeController: regulate=_regulate, on_division=_divided, mechanics=MechanicsConfig( - flow_drift=True, - contact_dynamics=ContactDynamicsConfig( - growth_law="linear", growth_stall_load=GROWTH_STALL_LOAD - ), + flow_drift=True, growth_law="linear", growth_stall_load=GROWTH_STALL_LOAD ), state=state, ) diff --git a/examples/tutorials/biophysics.py b/examples/tutorials/biophysics.py index 0548e99..c0ec95f 100644 --- a/examples/tutorials/biophysics.py +++ b/examples/tutorials/biophysics.py @@ -163,7 +163,7 @@ def build(context: ModelContext) -> NativeController: targets[str(founder_id)] = target regulate, divided = _callbacks(scenario) - mechanics = MechanicsConfig(gamma=20.0 if scenario == "box" else 10.0) + mechanics = MechanicsConfig() return NativeController( simulation, model_id=MODEL_ID, diff --git a/examples/tutorials/biopixel_trap.py b/examples/tutorials/biopixel_trap.py index 1b6f5f1..cbac92a 100644 --- a/examples/tutorials/biopixel_trap.py +++ b/examples/tutorials/biopixel_trap.py @@ -190,7 +190,7 @@ def build(context: ModelContext) -> NativeController: rng=context.rng, regulate=_regulate, on_division=_divided, - mechanics=MechanicsConfig(flow_drift=True, passes=2), + mechanics=MechanicsConfig(flow_drift=True), state=state, ) diff --git a/examples/tutorials/conjugation.py b/examples/tutorials/conjugation.py index 83e6167..f4ad5c7 100644 --- a/examples/tutorials/conjugation.py +++ b/examples/tutorials/conjugation.py @@ -106,7 +106,7 @@ def build(context: ModelContext) -> NativeController: rng=context.rng, regulate=regulate, on_division=divided, - mechanics=MechanicsConfig(gamma=10.0), + mechanics=MechanicsConfig(), state={ "transfer_probability": transfer_probability, "division_targets": targets, diff --git a/examples/tutorials/plasmid_segregation.py b/examples/tutorials/plasmid_segregation.py index cc48ad2..19e4061 100644 --- a/examples/tutorials/plasmid_segregation.py +++ b/examples/tutorials/plasmid_segregation.py @@ -9,6 +9,7 @@ from microsimulator import ( CellInit, + ContactDynamicsParameters, ModelContext, Simulation, capped_founder_length, @@ -136,9 +137,7 @@ def step(self, dt: float) -> None: if first_counts[1] + second_counts[1] != 2 * b_count: raise AssertionError("plasmid B copies were not conserved") - self.simulation.step(dt) - if self.simulation.cell_count: - self.simulation.relax_cell_mechanics() + self.simulation.step(dt, ContactDynamicsParameters()) self._present_state() self._completed_steps += 1 self._validate() diff --git a/examples/tutorials/simbol_circuits.py b/examples/tutorials/simbol_circuits.py index 921e933..cc6eb5a 100644 --- a/examples/tutorials/simbol_circuits.py +++ b/examples/tutorials/simbol_circuits.py @@ -217,7 +217,7 @@ def build(context: ModelContext) -> NativeController: rng=context.rng, regulate=_regulate, on_division=DIVISION.on_division, - mechanics=MechanicsConfig(gamma=100.0), + mechanics=MechanicsConfig(), state=state, ) diff --git a/python/src/microsimulator/__init__.py b/python/src/microsimulator/__init__.py index 76f9dc6..6acb715 100644 --- a/python/src/microsimulator/__init__.py +++ b/python/src/microsimulator/__init__.py @@ -15,7 +15,6 @@ BackendKind, BoxConstraintInit, CellContact, - CellCorrection, CellInit, CellSnapshot, ConstraintContactParameters, @@ -34,14 +33,12 @@ ExternalContact, ExternalContactGraph, FlowAxis, + FlowDriftParameters, GridBoundary, GridBoundaryKind, GridShape, GrowthLoadLaw, GrowthLoadResponse, - MechanicsIntegrationParameters, - MechanicsParameters, - MechanicsSolveResult, PlaneConstraintInit, RateInstruction, RateOp, @@ -57,9 +54,6 @@ SignalSolveParameters, SignalSolveReport, Simulation, - SolverBreakdown, - SolverReport, - SolverStatus, SpeciesRatePlan, SphereConstraintInit, SphereRegion, @@ -80,7 +74,6 @@ ) from .controller import ( CellUpdate, - ContactDynamicsConfig, ControllerPlanError, ControllerStateError, ControllerStep, @@ -157,7 +150,6 @@ "BatchError", "BoxConstraintInit", "CellContact", - "CellCorrection", "CellInit", "CellSnapshot", "CellUpdate", @@ -168,7 +160,6 @@ "CheckpointSourceBackend", "ConstraintContactParameters", "ConstraintRegion", - "ContactDynamicsConfig", "ContactDynamicsParameters", "ContactDynamicsReport", "ContactDynamicsResult", @@ -189,15 +180,13 @@ "ExternalContact", "ExternalContactGraph", "FlowAxis", + "FlowDriftParameters", "GridBoundary", "GridBoundaryKind", "GridShape", "GrowthLoadLaw", "GrowthLoadResponse", "MechanicsConfig", - "MechanicsIntegrationParameters", - "MechanicsParameters", - "MechanicsSolveResult", "ModelContext", "NativeController", "PlaneConstraintInit", @@ -240,9 +229,6 @@ "SignalSolveReport", "Simulation", "SimulationController", - "SolverBreakdown", - "SolverReport", - "SolverStatus", "SpeciesRatePlan", "SphereConstraintInit", "SphereRegion", diff --git a/python/src/microsimulator/_core.pyi b/python/src/microsimulator/_core.pyi index 716e26f..2f71f73 100644 --- a/python/src/microsimulator/_core.pyi +++ b/python/src/microsimulator/_core.pyi @@ -90,7 +90,6 @@ class BackendFeature(Enum): GROWTH: BackendFeature SPECIES: BackendFeature CELL_CONTACTS: BackendFeature - CELL_MECHANICS: BackendFeature EXTERNAL_CONSTRAINTS: BackendFeature SIGNALS: BackendFeature COUPLED_RATES: BackendFeature @@ -163,17 +162,6 @@ class RodContactLocation(Enum): RodEndpoint = RodContactLocation -class SolverStatus(Enum): - CONVERGED: SolverStatus - ITERATION_LIMIT: SolverStatus - BREAKDOWN: SolverStatus - -class SolverBreakdown(Enum): - NONE: SolverBreakdown - NON_FINITE_RESIDUAL: SolverBreakdown - NON_FINITE_CURVATURE: SolverBreakdown - NON_POSITIVE_CURVATURE: SolverBreakdown - def backend_available(backend: BackendKind, device_index: int = 0) -> bool: ... def backend_device_count(backend: BackendKind) -> int: ... @@ -591,25 +579,8 @@ class ExternalContactGraph: def __len__(self) -> int: ... def incident_contact_indices(self, slot: int) -> list[int]: ... -class CellCorrection: - @property - def translation(self) -> Vec3: ... - @property - def rotation(self) -> Vec3: ... - @property - def length(self) -> float: ... - -class MechanicsParameters: - mu_a: float - gamma: float - residual_rms_tolerance: float - max_iterations: int - - def __init__(self) -> None: ... - -class MechanicsIntegrationParameters: +class FlowDriftParameters: max_rotation_radians: float - require_convergence: bool def __init__(self) -> None: ... @@ -665,24 +636,6 @@ class ContactDynamicsResult: @property def length_increments(self) -> list[float]: ... -class SolverReport: - @property - def status(self) -> SolverStatus: ... - @property - def breakdown(self) -> SolverBreakdown: ... - @property - def iterations(self) -> int: ... - @property - def initial_residual_rms(self) -> float: ... - @property - def final_residual_rms(self) -> float: ... - -class MechanicsSolveResult: - @property - def corrections(self) -> list[CellCorrection]: ... - @property - def report(self) -> SolverReport: ... - class Simulation: @overload def __init__( @@ -718,9 +671,7 @@ class Simulation: def has_coupled_rate_plan(self) -> bool: ... def add_cell(self, cell: CellInit) -> int: ... def remove_cell(self, id: int) -> None: ... - def apply_flow_drift( - self, dt: float, integration: MechanicsIntegrationParameters = ... - ) -> None: ... + def apply_flow_drift(self, dt: float, parameters: FlowDriftParameters = ...) -> None: ... def add_plane_constraint(self, plane: PlaneConstraintInit) -> int: ... def add_sphere_constraint(self, sphere: SphereConstraintInit) -> int: ... def add_box_constraint(self, box: BoxConstraintInit) -> int: ... @@ -754,19 +705,6 @@ class Simulation: def find_external_contacts( self, parameters: ConstraintContactParameters = ... ) -> ExternalContactGraph: ... - def solve_cell_mechanics( - self, - mechanics_parameters: MechanicsParameters = ..., - contact_parameters: ContactParameters = ..., - constraint_parameters: ConstraintContactParameters = ..., - ) -> MechanicsSolveResult: ... - def relax_cell_mechanics( - self, - mechanics_parameters: MechanicsParameters = ..., - contact_parameters: ContactParameters = ..., - integration_parameters: MechanicsIntegrationParameters = ..., - constraint_parameters: ConstraintContactParameters = ..., - ) -> MechanicsSolveResult: ... def solve_depth_averaged_flow( self, spec: SignalGridSpec, diff --git a/python/src/microsimulator/controller.py b/python/src/microsimulator/controller.py index 400f37d..84f97f7 100644 --- a/python/src/microsimulator/controller.py +++ b/python/src/microsimulator/controller.py @@ -16,9 +16,6 @@ ContactDynamicsResult, ContactParameters, GrowthLoadLaw, - MechanicsIntegrationParameters, - MechanicsParameters, - MechanicsSolveResult, Simulation, ) from .channels import UNNAMED_CHANNELS, ChannelMetadata @@ -178,10 +175,21 @@ def _json_object(value: Mapping[str, JSONValue], path: str) -> dict[str, JSONVal "exponential": GrowthLoadLaw.EXPONENTIAL, "linear": GrowthLoadLaw.LINEAR, } +_MECHANICS_INTEGERS = ("max_iterations", "max_refinements", "max_step_halvings") +_MECHANICS_POSITIVE = ( + "drag", + "contact_stiffness", + "wall_stiffness", + "overlap_tolerance", + "max_overlap_recovery", + "max_growth_fraction", + "contact_degeneracy_epsilon", + "constraint_degeneracy_epsilon", +) @dataclass(frozen=True, slots=True) -class ContactDynamicsConfig: +class MechanicsConfig: """Checkpointable parameters for growth and contact solved together. Cells push each other and the walls apart with non-negative contact forces @@ -192,6 +200,8 @@ class ContactDynamicsConfig: stops it at ``growth_stall_load``. Loads are forces in units of ``drag`` times length squared per time. A contact under force ``f`` overlaps by ``f / contact_stiffness`` between cells and ``f / wall_stiffness`` against a wall. + With ``flow_drift`` the signal grid's velocity field carries the cells inside + the same solve. """ drag: float = 1.0 @@ -208,74 +218,91 @@ class ContactDynamicsConfig: growth_sensitivity: float = 0.0 growth_free_load: float = 0.0 growth_stall_load: float = 1.0 + contact_parallel_sine_threshold: float = 0.1 + contact_degeneracy_epsilon: float = 1.0e-6 + constraint_degeneracy_epsilon: float = 1.0e-6 + flow_drift: bool = False def __post_init__(self) -> None: - for name in ("drag", "contact_stiffness", "wall_stiffness", "overlap_tolerance"): - if _finite_number(getattr(self, name), f"contact_dynamics.{name}") <= 0.0: - raise ControllerStateError(f"contact_dynamics.{name} must be positive") - for name in ("max_overlap_recovery", "max_growth_fraction"): - if _finite_number(getattr(self, name), f"contact_dynamics.{name}") <= 0.0: - raise ControllerStateError(f"contact_dynamics.{name} must be positive") - if _finite_number(self.candidate_margin, "contact_dynamics.candidate_margin") < 0.0: - raise ControllerStateError("contact_dynamics.candidate_margin must be non-negative") - _integer(self.max_iterations, "contact_dynamics.max_iterations", 1, _UINT32_MAX) - _integer(self.max_refinements, "contact_dynamics.max_refinements", 0, _UINT32_MAX) - _integer(self.max_step_halvings, "contact_dynamics.max_step_halvings", 0, 64) + for name in _MECHANICS_POSITIVE: + if _finite_number(getattr(self, name), f"mechanics.{name}") <= 0.0: + raise ControllerStateError(f"mechanics.{name} must be positive") + if _finite_number(self.candidate_margin, "mechanics.candidate_margin") < 0.0: + raise ControllerStateError("mechanics.candidate_margin must be non-negative") + _integer(self.max_iterations, "mechanics.max_iterations", 1, _UINT32_MAX) + _integer(self.max_refinements, "mechanics.max_refinements", 0, _UINT32_MAX) + _integer(self.max_step_halvings, "mechanics.max_step_halvings", 0, 64) if cast(object, self.growth_law) not in _GROWTH_LOAD_LAWS: raise ControllerStateError( - "contact_dynamics.growth_law must be one of " + ", ".join(sorted(_GROWTH_LOAD_LAWS)) + "mechanics.growth_law must be one of " + ", ".join(sorted(_GROWTH_LOAD_LAWS)) ) - sensitivity = _finite_number( - self.growth_sensitivity, "contact_dynamics.growth_sensitivity" - ) - free_load = _finite_number(self.growth_free_load, "contact_dynamics.growth_free_load") - stall_load = _finite_number(self.growth_stall_load, "contact_dynamics.growth_stall_load") + sensitivity = _finite_number(self.growth_sensitivity, "mechanics.growth_sensitivity") + free_load = _finite_number(self.growth_free_load, "mechanics.growth_free_load") + stall_load = _finite_number(self.growth_stall_load, "mechanics.growth_stall_load") if sensitivity < 0.0 or free_load < 0.0 or stall_load <= free_load: raise ControllerStateError( - "contact_dynamics growth sensitivity and free load must be non-negative, " + "mechanics growth sensitivity and free load must be non-negative, " "and the stall load must exceed the free load" ) + parallel_threshold = _finite_number( + self.contact_parallel_sine_threshold, "mechanics.contact_parallel_sine_threshold" + ) + if parallel_threshold < 0.0 or parallel_threshold > 1.0: + raise ControllerStateError("mechanics contact parallel threshold is invalid") + if not isinstance(cast(object, self.flow_drift), bool): + raise ControllerStateError("mechanics.flow_drift must be Boolean") - def native_parameters(self) -> ContactDynamicsParameters: - parameters = ContactDynamicsParameters() - parameters.drag = self.drag - parameters.contact_stiffness = self.contact_stiffness - parameters.wall_stiffness = self.wall_stiffness - parameters.overlap_tolerance = self.overlap_tolerance - parameters.candidate_margin = self.candidate_margin - parameters.max_overlap_recovery = self.max_overlap_recovery - parameters.max_growth_fraction = self.max_growth_fraction - parameters.max_iterations = self.max_iterations - parameters.max_refinements = self.max_refinements - parameters.max_step_halvings = self.max_step_halvings - growth = parameters.growth + def native_parameters( + self, + ) -> tuple[ContactDynamicsParameters, ContactParameters, ConstraintContactParameters]: + dynamics = ContactDynamicsParameters() + dynamics.drag = self.drag + dynamics.contact_stiffness = self.contact_stiffness + dynamics.wall_stiffness = self.wall_stiffness + dynamics.overlap_tolerance = self.overlap_tolerance + dynamics.candidate_margin = self.candidate_margin + dynamics.max_overlap_recovery = self.max_overlap_recovery + dynamics.max_growth_fraction = self.max_growth_fraction + dynamics.max_iterations = self.max_iterations + dynamics.max_refinements = self.max_refinements + dynamics.max_step_halvings = self.max_step_halvings + dynamics.flow_drift = self.flow_drift + growth = dynamics.growth growth.law = _GROWTH_LOAD_LAWS[self.growth_law] growth.sensitivity = self.growth_sensitivity growth.free_load = self.growth_free_load growth.stall_load = self.growth_stall_load - parameters.growth = growth - return parameters + dynamics.growth = growth + contacts = ContactParameters() + contacts.parallel_sine_threshold = self.contact_parallel_sine_threshold + contacts.degeneracy_epsilon = self.contact_degeneracy_epsilon + constraints = ConstraintContactParameters() + constraints.degeneracy_epsilon = self.constraint_degeneracy_epsilon + return dynamics, contacts, constraints def to_json(self) -> dict[str, JSONValue]: return { field.name: cast(JSONValue, getattr(self, field.name)) - for field in fields(ContactDynamicsConfig) + for field in fields(MechanicsConfig) } @classmethod - def from_json(cls, value: JSONValue) -> ContactDynamicsConfig: - names = {field.name for field in fields(ContactDynamicsConfig)} + def from_json(cls, value: JSONValue) -> MechanicsConfig: + names = {field.name for field in fields(MechanicsConfig)} if not isinstance(value, dict) or set(value) != names: - raise ControllerStateError("contact dynamics configuration is invalid") + raise ControllerStateError("controller mechanics configuration is invalid") growth_law = value["growth_law"] if not isinstance(growth_law, str): - raise ControllerStateError("contact_dynamics.growth_law must be a string") + raise ControllerStateError("mechanics.growth_law must be a string") + flow_drift = value["flow_drift"] + if not isinstance(flow_drift, bool): + raise ControllerStateError("mechanics.flow_drift must be Boolean") def number(name: str) -> float: - return _finite_number(value[name], f"contact_dynamics.{name}") + return _finite_number(value[name], f"mechanics.{name}") def count(name: str) -> int: - return _integer(value[name], f"contact_dynamics.{name}", 0, _UINT32_MAX) + return _integer(value[name], f"mechanics.{name}", 0, _UINT32_MAX) return cls( drag=number("drag"), @@ -292,167 +319,10 @@ def count(name: str) -> int: growth_sensitivity=number("growth_sensitivity"), growth_free_load=number("growth_free_load"), growth_stall_load=number("growth_stall_load"), - ) - - -@dataclass(frozen=True, slots=True) -class MechanicsConfig: - """Checkpointable mechanics parameters applied on each controller step. - - Without ``contact_dynamics`` the controller grows the cells and then runs - ``passes`` least-squares relaxation passes. With it, the controller advances - growth and contact together with the contact dynamics solve, and the - relaxation fields ``passes``, ``gamma``, ``residual_rms_tolerance``, - ``max_iterations``, ``max_rotation_radians``, ``require_convergence``, and the - two activation margins are unused. - """ - - passes: int = 1 - mu_a: float = 1.0 - gamma: float = 10.0 - residual_rms_tolerance: float = 5.0e-3 - max_iterations: int = 0 - contact_activation_margin: float = 0.01 - contact_parallel_sine_threshold: float = 0.1 - contact_degeneracy_epsilon: float = 1.0e-6 - max_rotation_radians: float = 0.0872664626 - require_convergence: bool = True - constraint_activation_margin: float = 0.0 - constraint_degeneracy_epsilon: float = 1.0e-6 - flow_drift: bool = False - contact_dynamics: ContactDynamicsConfig | None = None - - def __post_init__(self) -> None: - _integer(self.passes, "mechanics.passes", 1, _UINT32_MAX) - _integer(self.max_iterations, "mechanics.max_iterations", 0, _UINT32_MAX) - mu_a = _finite_number(self.mu_a, "mechanics.mu_a") - gamma = _finite_number(self.gamma, "mechanics.gamma") - tolerance = _finite_number(self.residual_rms_tolerance, "mechanics.residual_rms_tolerance") - contact_margin = _finite_number( - self.contact_activation_margin, "mechanics.contact_activation_margin" - ) - parallel_threshold = _finite_number( - self.contact_parallel_sine_threshold, - "mechanics.contact_parallel_sine_threshold", - ) - contact_epsilon = _finite_number( - self.contact_degeneracy_epsilon, "mechanics.contact_degeneracy_epsilon" - ) - rotation = _finite_number(self.max_rotation_radians, "mechanics.max_rotation_radians") - constraint_margin = _finite_number( - self.constraint_activation_margin, - "mechanics.constraint_activation_margin", - ) - constraint_epsilon = _finite_number( - self.constraint_degeneracy_epsilon, - "mechanics.constraint_degeneracy_epsilon", - ) - if mu_a <= 0.0 or gamma <= 0.0: - raise ControllerStateError("mechanics mu_a and gamma must be positive") - if tolerance < 0.0 or contact_margin < 0.0 or rotation < 0.0: - raise ControllerStateError("mechanics tolerances, margins, and limits are invalid") - if parallel_threshold < 0.0 or parallel_threshold > 1.0: - raise ControllerStateError("mechanics contact parallel threshold is invalid") - if contact_epsilon <= 0.0 or constraint_epsilon <= 0.0 or constraint_margin < 0.0: - raise ControllerStateError("mechanics constraint/contact parameters are invalid") - if not isinstance(cast(object, self.require_convergence), bool): - raise ControllerStateError("mechanics.require_convergence must be Boolean") - if not isinstance(cast(object, self.flow_drift), bool): - raise ControllerStateError("mechanics.flow_drift must be Boolean") - dynamics = cast(object, self.contact_dynamics) - if dynamics is not None and not isinstance(dynamics, ContactDynamicsConfig): - raise ControllerStateError( - "mechanics.contact_dynamics must be a ContactDynamicsConfig or None" - ) - - def native_parameters( - self, - ) -> tuple[ - MechanicsParameters, - ContactParameters, - MechanicsIntegrationParameters, - ConstraintContactParameters, - ]: - mechanics = MechanicsParameters() - mechanics.mu_a = self.mu_a - mechanics.gamma = self.gamma - mechanics.residual_rms_tolerance = self.residual_rms_tolerance - mechanics.max_iterations = self.max_iterations - contacts = ContactParameters() - contacts.activation_margin = self.contact_activation_margin - contacts.parallel_sine_threshold = self.contact_parallel_sine_threshold - contacts.degeneracy_epsilon = self.contact_degeneracy_epsilon - integration = MechanicsIntegrationParameters() - integration.max_rotation_radians = self.max_rotation_radians - integration.require_convergence = self.require_convergence - constraints = ConstraintContactParameters() - constraints.activation_margin = self.constraint_activation_margin - constraints.degeneracy_epsilon = self.constraint_degeneracy_epsilon - return mechanics, contacts, integration, constraints - - def to_json(self) -> dict[str, JSONValue]: - result = { - field.name: cast(JSONValue, getattr(self, field.name)) - for field in fields(MechanicsConfig) - if field.name != "contact_dynamics" - } - result["contact_dynamics"] = ( - None if self.contact_dynamics is None else self.contact_dynamics.to_json() - ) - return result - - @classmethod - def from_json(cls, value: JSONValue) -> MechanicsConfig: - # A payload without a contact dynamics entry selects relaxation passes. - names = {field.name for field in fields(MechanicsConfig)} - if not isinstance(value, dict) or set(value) | {"contact_dynamics"} != names: - raise ControllerStateError("controller mechanics configuration is invalid") - dynamics_value = value.get("contact_dynamics") - contact_dynamics = ( - None if dynamics_value is None else ContactDynamicsConfig.from_json(dynamics_value) - ) - require_convergence = value["require_convergence"] - if not isinstance(require_convergence, bool): - raise ControllerStateError("mechanics.require_convergence must be Boolean") - flow_drift = value["flow_drift"] - if not isinstance(flow_drift, bool): - raise ControllerStateError("mechanics.flow_drift must be Boolean") - return cls( - passes=_integer(value["passes"], "mechanics.passes", 1, _UINT32_MAX), - mu_a=_finite_number(value["mu_a"], "mechanics.mu_a"), - gamma=_finite_number(value["gamma"], "mechanics.gamma"), - residual_rms_tolerance=_finite_number( - value["residual_rms_tolerance"], "mechanics.residual_rms_tolerance" - ), - max_iterations=_integer( - value["max_iterations"], "mechanics.max_iterations", 0, _UINT32_MAX - ), - contact_activation_margin=_finite_number( - value["contact_activation_margin"], - "mechanics.contact_activation_margin", - ), - contact_parallel_sine_threshold=_finite_number( - value["contact_parallel_sine_threshold"], - "mechanics.contact_parallel_sine_threshold", - ), - contact_degeneracy_epsilon=_finite_number( - value["contact_degeneracy_epsilon"], - "mechanics.contact_degeneracy_epsilon", - ), - max_rotation_radians=_finite_number( - value["max_rotation_radians"], "mechanics.max_rotation_radians" - ), - require_convergence=require_convergence, - constraint_activation_margin=_finite_number( - value["constraint_activation_margin"], - "mechanics.constraint_activation_margin", - ), - constraint_degeneracy_epsilon=_finite_number( - value["constraint_degeneracy_epsilon"], - "mechanics.constraint_degeneracy_epsilon", - ), + contact_parallel_sine_threshold=number("contact_parallel_sine_threshold"), + contact_degeneracy_epsilon=number("contact_degeneracy_epsilon"), + constraint_degeneracy_epsilon=number("constraint_degeneracy_epsilon"), flow_drift=flow_drift, - contact_dynamics=contact_dynamics, ) @@ -496,7 +366,6 @@ def __init__( self._completed_steps = _integer( completed_steps, "native controller completed steps", 0, _UINT64_MAX ) - self._last_mechanics_reports: tuple[MechanicsSolveResult, ...] = () self._last_contact_dynamics: ContactDynamicsResult | None = None @property @@ -507,10 +376,6 @@ def completed_steps(self) -> int: def state(self) -> dict[str, JSONValue]: return self._state - @property - def last_mechanics_reports(self) -> tuple[MechanicsSolveResult, ...]: - return self._last_mechanics_reports - @property def last_contact_dynamics(self) -> ContactDynamicsResult | None: """The result of the last step's contact dynamics solve, if it ran. @@ -630,29 +495,12 @@ def step(self, dt: float) -> None: for removal in plan.removals: self.simulation.remove_cell(removal) - reports: list[MechanicsSolveResult] = [] mechanics = self._mechanics - drifts = ( - mechanics is not None and mechanics.flow_drift and self.simulation.cell_count != 0 - ) - if mechanics is not None and mechanics.contact_dynamics is not None: - # The flow carries the cells inside the solve, so contacts resist - # it pressing cells together. - _, contacts, _, constraints = mechanics.native_parameters() - dynamics = mechanics.contact_dynamics.native_parameters() - dynamics.flow_drift = mechanics.flow_drift - self._last_contact_dynamics = self.simulation.step(dt, dynamics, contacts, constraints) - else: + if mechanics is None: self._last_contact_dynamics = None self.simulation.step(dt) - if mechanics is not None and drifts: - _, _, integration, _ = mechanics.native_parameters() - self.simulation.apply_flow_drift(dt, integration) - if mechanics is not None and self.simulation.cell_count != 0: - parameters = mechanics.native_parameters() - for _ in range(mechanics.passes): - reports.append(self.simulation.relax_cell_mechanics(*parameters)) - self._last_mechanics_reports = tuple(reports) + else: + self._last_contact_dynamics = self.simulation.step(dt, *mechanics.native_parameters()) self._completed_steps += 1 def controller_state(self) -> dict[str, JSONValue]: diff --git a/python/tests/test_contact_dynamics.py b/python/tests/test_contact_dynamics.py index be5eed5..c9ecc1d 100644 --- a/python/tests/test_contact_dynamics.py +++ b/python/tests/test_contact_dynamics.py @@ -12,7 +12,6 @@ BoxConstraintInit, CellInit, ConstraintRegion, - ContactDynamicsConfig, ContactDynamicsParameters, ControllerStateError, ControllerStep, @@ -100,7 +99,7 @@ def _tilt_daughters(step: ControllerStep, event: DivisionEvent) -> None: ) -def _chamber(backend: BackendKind, config: ContactDynamicsConfig) -> NativeController: +def _chamber(backend: BackendKind, config: MechanicsConfig) -> NativeController: simulation = _simulation(backend) chamber = BoxConstraintInit() chamber.half_extents = Vec3(2.0, 2.0, 0.6) @@ -117,7 +116,7 @@ def _chamber(backend: BackendKind, config: ContactDynamicsConfig) -> NativeContr rng=random.Random(3), regulate=_divide_at(2.0), on_division=_tilt_daughters, - mechanics=MechanicsConfig(contact_dynamics=config), + mechanics=config, ) @@ -149,40 +148,46 @@ def test_growth_load_response_factor() -> None: response.factor(1.0) -def test_contact_dynamics_config_round_trips_and_validates() -> None: - config = ContactDynamicsConfig( +def test_mechanics_config_round_trips_and_validates() -> None: + config = MechanicsConfig( growth_law="linear", growth_free_load=1.0, growth_stall_load=8.0, contact_stiffness=2000.0, wall_stiffness=5.0e4, + flow_drift=True, + ) + assert MechanicsConfig.from_json(config.to_json()) == config + + dynamics, contacts, constraints = config.native_parameters() + assert dynamics.growth.law == GrowthLoadLaw.LINEAR + assert dynamics.growth.stall_load == 8.0 + assert dynamics.contact_stiffness == 2000.0 + assert dynamics.wall_stiffness == 5.0e4 + assert dynamics.flow_drift + assert math.isclose( + contacts.parallel_sine_threshold, config.contact_parallel_sine_threshold, rel_tol=1e-6 + ) + assert math.isclose( + constraints.degeneracy_epsilon, config.constraint_degeneracy_epsilon, rel_tol=1e-6 ) - mechanics = MechanicsConfig(flow_drift=True, contact_dynamics=config) - assert MechanicsConfig.from_json(mechanics.to_json()) == mechanics - - parameters = config.native_parameters() - assert parameters.growth.law == GrowthLoadLaw.LINEAR - assert parameters.growth.stall_load == 8.0 - assert parameters.contact_stiffness == 2000.0 - assert parameters.wall_stiffness == 5.0e4 - - # A payload written without the entry selects relaxation passes. - legacy = MechanicsConfig(passes=2).to_json() - del legacy["contact_dynamics"] - assert MechanicsConfig.from_json(legacy) == MechanicsConfig(passes=2) with pytest.raises(ControllerStateError, match="growth_law"): - ContactDynamicsConfig(growth_law="quadratic") + MechanicsConfig(growth_law="quadratic") with pytest.raises(ControllerStateError, match="stall load"): - ContactDynamicsConfig(growth_law="linear", growth_free_load=2.0, growth_stall_load=2.0) + MechanicsConfig(growth_law="linear", growth_free_load=2.0, growth_stall_load=2.0) with pytest.raises(ControllerStateError, match="contact_stiffness"): - ContactDynamicsConfig(contact_stiffness=0.0) - invalid = mechanics.to_json() - invalid["contact_dynamics"] = {"drag": 1.0} - with pytest.raises(ControllerStateError, match="contact dynamics configuration"): - MechanicsConfig.from_json(invalid) - with pytest.raises(ControllerStateError, match="ContactDynamicsConfig"): - MechanicsConfig(contact_dynamics=object()) # type: ignore[arg-type] + MechanicsConfig(contact_stiffness=0.0) + with pytest.raises(ControllerStateError, match="flow_drift must be Boolean"): + MechanicsConfig(flow_drift=1) # type: ignore[arg-type] + incomplete = config.to_json() + del incomplete["wall_stiffness"] + with pytest.raises(ControllerStateError, match="mechanics configuration is invalid"): + MechanicsConfig.from_json(incomplete) + unknown = config.to_json() + unknown["gamma"] = 10.0 + with pytest.raises(ControllerStateError, match="mechanics configuration is invalid"): + MechanicsConfig.from_json(unknown) @pytest.mark.parametrize("backend", BACKENDS) @@ -249,7 +254,7 @@ def test_cell_between_walls_stalls_and_stops_consuming(backend: BackendKind) -> @pytest.mark.parametrize("backend", BACKENDS) def test_closed_chamber_fills_and_holds(backend: BackendKind) -> None: - config = ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0) + config = MechanicsConfig(growth_law="linear", growth_stall_load=2.0) controller = _chamber(backend, config) for _ in range(300): controller.step(0.05) @@ -265,7 +270,6 @@ def test_closed_chamber_fills_and_holds(backend: BackendKind) -> None: result = controller.last_contact_dynamics assert result is not None assert max(result.length_increments) < 1e-5 - assert controller.last_mechanics_reports == () for cell in simulation.cells(): assert abs(cell.position.x) <= 2.0 and abs(cell.position.y) <= 2.0 assert abs(cell.position.z) < 1e-3 @@ -284,7 +288,7 @@ def test_unconfined_colony_grows_in_full_without_overlap(backend: BackendKind) - rng=random.Random(5), regulate=_divide_at(4.0), on_division=_tilt_daughters, - mechanics=MechanicsConfig(contact_dynamics=ContactDynamicsConfig()), + mechanics=MechanicsConfig(), ) # The same lineage with growth and division alone. reference = Simulation(BackendKind.CPU, reserved_capacity=512) @@ -317,7 +321,7 @@ def test_unconfined_colony_grows_in_full_without_overlap(backend: BackendKind) - def test_resume_reproduces_the_uninterrupted_trajectory( backend: BackendKind, tmp_path: Path ) -> None: - config = ContactDynamicsConfig(growth_law="linear", growth_stall_load=2.0) + config = MechanicsConfig(growth_law="linear", growth_stall_load=2.0) uninterrupted = _chamber(backend, config) for _ in range(120): uninterrupted.step(0.05) diff --git a/python/tests/test_controller.py b/python/tests/test_controller.py index 2eb5f27..d8643ce 100644 --- a/python/tests/test_controller.py +++ b/python/tests/test_controller.py @@ -130,7 +130,7 @@ def invalidate_gaussian(value: dict[str, Any]) -> None: def test_mechanics_config_round_trip_preserves_flow_drift() -> None: - configuration = MechanicsConfig(passes=2, flow_drift=True) + configuration = MechanicsConfig(max_refinements=4, flow_drift=True) assert MechanicsConfig.from_json(configuration.to_json()) == configuration @@ -219,7 +219,7 @@ def divided(step: ControllerStep, event: DivisionEvent) -> None: rng=random.Random(17), regulate=regulate, on_division=divided, - mechanics=MechanicsConfig(passes=2), + mechanics=MechanicsConfig(), ) assert isinstance(controller, SimulationController) @@ -229,7 +229,7 @@ def divided(step: ControllerStep, event: DivisionEvent) -> None: assert controller.state["regulated"] is True daughter_ids = cast(list[JSONValue], controller.state["daughter_ids"]) assert len(daughter_ids) == 2 - assert len(controller.last_mechanics_reports) == 2 + assert controller.last_contact_dynamics is not None for daughter_id in daughter_ids: assert isinstance(daughter_id, int) daughter = simulation.cell(daughter_id) @@ -261,7 +261,7 @@ def build() -> NativeController: model_version=3, rng=random.Random(99), regulate=regulate, - mechanics=MechanicsConfig(passes=1), + mechanics=MechanicsConfig(), state={"draws": 0}, ) diff --git a/python/tests/test_coupling_foundations.py b/python/tests/test_coupling_foundations.py index 42857b1..2c43ef6 100644 --- a/python/tests/test_coupling_foundations.py +++ b/python/tests/test_coupling_foundations.py @@ -7,9 +7,9 @@ from microsimulator import ( BackendKind, CellInit, + FlowDriftParameters, GridBoundaryKind, GridShape, - MechanicsIntegrationParameters, RatePlanBuilder, SignalGridAffineReaction, SignalGridSpec, @@ -71,7 +71,7 @@ def test_rigid_rotation_has_second_order_drift_convergence() -> None: cell = CellInit() cell.position, cell.direction = Vec3(1, 0, 0), Vec3(1, 0, 0) cid = sim.add_cell(cell) - parameters = MechanicsIntegrationParameters() + parameters = FlowDriftParameters() parameters.max_rotation_radians = 0.5 for _ in range(n): sim.apply_flow_drift(0.8 / n, parameters) diff --git a/python/tests/test_planarity.py b/python/tests/test_planarity.py index 1a99098..4830c84 100644 --- a/python/tests/test_planarity.py +++ b/python/tests/test_planarity.py @@ -36,10 +36,15 @@ def test_three_dimensional_diagnostic_fixtures(backend: BackendKind) -> None: for name in ("crossing", "coincident_parallel"): result = results[name] assert any(abs(normal[2]) > 0.99 for normal in result["contact_normals"]) - assert result["first_out_of_plane"]["stage"] == "contact_and_constraint_relaxation" + assert result["first_out_of_plane"]["stage"] == "growth_contact_and_chemistry" + overlaps = result["overlap_by_step"] + assert math.isclose(overlaps[0], 1.0, abs_tol=1e-6) + assert all(after < before for before, after in pairwise(overlaps)) + assert overlaps[-1] <= 2e-3 + # The rods end a diameter apart in Z, each having moved half of it. negative, positive = sorted(cell["center"][2] for cell in result["final_geometry"]) - assert math.isclose(negative, -0.4, abs_tol=1e-6) - assert math.isclose(positive, 0.4, abs_tol=1e-6) + assert math.isclose(negative, -0.5, abs_tol=2e-3) + assert math.isclose(positive, 0.5, abs_tol=2e-3) inherited = results["inherited_tilt"] assert inherited["first_out_of_plane"]["stage"] == "initialization" assert any( @@ -52,15 +57,13 @@ def test_three_dimensional_diagnostic_fixtures(backend: BackendKind) -> None: assert all(stage["requested_direction_delta_z"] == 0 for stage in jitter) assert any(stage["max_stage_direction_change_z"] > 1e-6 for stage in jitter) confined = results["finite_height_constraints"] - default = confined["default_wall_penetration_by_pass"] - tight = confined["tight_wall_penetration_by_pass"] - assert math.isclose(default[0], 0.3, abs_tol=1e-6) - assert 1e-6 < default[-1] < 0.005 - assert tight[-1] < 1e-6 - assert all(after <= before + 1e-7 for before, after in pairwise(tight)) + penetrations = confined["wall_penetration_by_step"] + assert math.isclose(penetrations[0], 0.3, abs_tol=1e-6) + assert all(after < before for before, after in pairwise(penetrations)) + assert penetrations[-1] <= 2e-3 final = confined["final_geometry"][0] axial_z_extent = abs(final["direction"][2]) * final["length"] / 2 + final["radius"] - assert final["center"][2] + axial_z_extent <= 1 + 1e-6 + assert final["center"][2] + axial_z_extent <= 1 + 2e-3 assert final["center"][2] > 0.49 # walls permit nonzero Z; they do not impose z=0 flow = results["vertical_flow"] assert flow["first_out_of_plane"]["stage"] == "flow_drift" @@ -86,7 +89,6 @@ def test_diagnostics_preserve_rng_and_restore_native_methods_on_failure() -> Non "remove_cell", "step", "apply_flow_drift", - "relax_cell_mechanics", "set_cell_geometry", ) } diff --git a/python/tests/test_simulation.py b/python/tests/test_simulation.py index 8dd1519..fbdfd5e 100644 --- a/python/tests/test_simulation.py +++ b/python/tests/test_simulation.py @@ -10,12 +10,12 @@ CellInit, ConstraintContactParameters, ConstraintRegion, + ContactDynamicsParameters, ContactParameters, ExternalConstraintKind, + FlowDriftParameters, GridBoundaryKind, GridShape, - MechanicsIntegrationParameters, - MechanicsParameters, PlaneConstraintInit, RateInstruction, RateOp, @@ -24,8 +24,6 @@ SignalGridSpec, SignalGridVelocityField, Simulation, - SolverBreakdown, - SolverStatus, SpeciesRatePlan, Vec3, backend_available, @@ -273,27 +271,32 @@ def test_contact_graph_is_available_through_the_public_api(backend: BackendKind) ) -def test_cpu_mechanics_reports_convergence() -> None: +def test_contact_step_pushes_overlapping_cells_apart() -> None: simulation = Simulation() first = CellInit() first.length = 4.0 + first.growth_rate = 0.0 second = CellInit() second.position = Vec3(0.0, 0.8, 0.0) second.length = 4.0 - simulation.add_cell(first) - simulation.add_cell(second) + second.growth_rate = 0.0 + first_id = simulation.add_cell(first) + second_id = simulation.add_cell(second) - parameters = MechanicsParameters() - parameters.residual_rms_tolerance = 1.0e-6 - result = simulation.solve_cell_mechanics(parameters) + parameters = ContactDynamicsParameters() + result = simulation.step(0.05, parameters) - assert simulation.supports(BackendFeature.CELL_MECHANICS) - assert result.report.status == SolverStatus.CONVERGED - assert result.report.breakdown == SolverBreakdown.NONE - assert result.report.final_residual_rms <= parameters.residual_rms_tolerance - assert len(result.corrections) == 2 - assert result.corrections[0].translation.y < 0.0 - assert result.corrections[1].translation.y > 0.0 + assert simulation.supports(BackendFeature.CONTACT_DYNAMICS) + # One step recovers the overlap limit, shared equally by cells of equal drag. + assert result.report.max_rows >= 1 + below, above = simulation.cell(first_id), simulation.cell(second_id) + assert math.isclose(below.position.y, -0.025, abs_tol=2.0e-3) + assert math.isclose(above.position.y, 0.825, abs_tol=2.0e-3) + assert math.isclose(below.length, 4.0) + for _ in range(8): + result = simulation.step(0.05, parameters) + assert result.report.max_overlap <= 2.0e-3 + assert simulation.cell(second_id).position.y - simulation.cell(first_id).position.y >= 0.998 def test_cell_attributes_can_be_updated_by_stable_id() -> None: @@ -361,7 +364,7 @@ def test_plane_constraint_graph_is_typed_and_incident(backend: BackendKind) -> N @pytest.mark.parametrize("backend", list(BackendKind)) -def test_constraints_participate_in_mechanical_relaxation(backend: BackendKind) -> None: +def test_constraints_participate_in_the_contact_solve(backend: BackendKind) -> None: if not backend_available(backend): pytest.skip("native backend is not built") simulation = Simulation(backend) @@ -377,15 +380,13 @@ def test_constraints_participate_in_mechanical_relaxation(backend: BackendKind) plane.inward_normal = Vec3(0.0, 1.0, 0.0) simulation.add_plane_constraint(plane) - result = simulation.relax_cell_mechanics() + simulation.step(0.05, ContactDynamicsParameters()) - assert result.report.status == SolverStatus.CONVERGED - assert result.corrections[0].translation.y > 0.0 assert simulation.cell(cell_id).position.y > 0.4 @pytest.mark.parametrize("backend", list(BackendKind)) -def test_box_constraints_participate_in_mechanical_relaxation(backend: BackendKind) -> None: +def test_box_constraints_participate_in_the_contact_solve(backend: BackendKind) -> None: if not backend_available(backend): pytest.skip("native backend is not built") simulation = Simulation(backend) @@ -412,10 +413,8 @@ def test_box_constraints_participate_in_mechanical_relaxation(backend: BackendKi for contact in graph.contacts ) - result = simulation.relax_cell_mechanics() + simulation.step(0.05, ContactDynamicsParameters()) - assert result.report.status == SolverStatus.CONVERGED - assert result.corrections[0].translation.x > 0.0 assert simulation.cell(cell_id).position.x > 1.4 @@ -448,31 +447,10 @@ def test_finite_wall_detects_midspan_capsule_contact(backend: BackendKind) -> No assert math.isclose(contact.normal.y, -1.0, abs_tol=2.0e-5) assert math.isclose(contact.signed_separation, -0.75, abs_tol=2.0e-5) - result = simulation.relax_cell_mechanics() - assert result.report.status == SolverStatus.CONVERGED - assert result.corrections[0].translation.y > 0.0 + simulation.step(0.05, ContactDynamicsParameters()) assert simulation.cell(cell_id).position.y > 0.75 -def test_cpu_mechanics_relaxation_updates_geometry() -> None: - simulation = Simulation() - first = CellInit() - first.length = 4.0 - second = CellInit() - second.position = Vec3(0.0, 0.8, 0.0) - second.length = 4.0 - first_id = simulation.add_cell(first) - second_id = simulation.add_cell(second) - - integration = MechanicsIntegrationParameters() - result = simulation.relax_cell_mechanics(integration_parameters=integration) - - assert result.report.status == SolverStatus.CONVERGED - assert simulation.cell(first_id).position.y < 0.0 - assert simulation.cell(second_id).position.y > 0.8 - assert math.isclose(simulation.cell(first_id).length, 4.0) - - @pytest.mark.parametrize("backend", [BackendKind.METAL, BackendKind.CUDA]) def test_native_growth_matches_cpu(backend: BackendKind) -> None: if not backend_available(backend): @@ -575,13 +553,13 @@ def test_flow_drift_substeps_instead_of_clipping_the_total_rotation() -> None: capped.configure_signal_grid(grid) capped_id = capped.add_cell(cell) capped.apply_flow_drift(1.0) - limit = MechanicsIntegrationParameters().max_rotation_radians + limit = FlowDriftParameters().max_rotation_radians assert capped.cell(capped_id).direction.x > 3 * math.sin(limit) frozen = Simulation() frozen.configure_signal_grid(grid) frozen_id = frozen.add_cell(cell) - integration = MechanicsIntegrationParameters() + integration = FlowDriftParameters() integration.max_rotation_radians = 0.0 frozen.apply_flow_drift(1.0, integration) assert math.isclose(frozen.cell(frozen_id).direction.x, 0.0, abs_tol=1.0e-6) diff --git a/scripts/diagnose_planarity.py b/scripts/diagnose_planarity.py index 7aad6b9..84f6187 100644 --- a/scripts/diagnose_planarity.py +++ b/scripts/diagnose_planarity.py @@ -102,9 +102,8 @@ def instrument(self): "divide": "division", "divide_equal": "division", "remove_cell": "removal", - "step": "growth_and_chemistry", + "step": "growth_contact_and_chemistry", "apply_flow_drift": "flow_drift", - "relax_cell_mechanics": "contact_and_constraint_relaxation", "set_cell_geometry": "geometry_edit", } originals = {} @@ -156,6 +155,27 @@ def add(simulation, position=(0, 0, 0), direction=(1, 0, 0), length=4.0, radius= return simulation.add_cell(cell) +def deepest_overlap(simulation): + contacts = simulation.find_cell_contacts().contacts + walls = simulation.find_external_contacts().contacts + return max([0.0, *(-contact.signed_separation for contact in (*contacts, *walls))]) + + +def resolve(simulation, dt, tolerance=2e-3, max_steps=60): + """Step the contact solve until no overlap deeper than the tolerance remains. + + Returns the deepest overlap before each step and after the last. The cells + of these fixtures do not grow, so each step only moves them apart, by at + most the recovery limit. + """ + + overlaps = [deepest_overlap(simulation)] + while overlaps[-1] > tolerance and len(overlaps) <= max_steps: + simulation.step(dt, *MechanicsConfig().native_parameters()) + overlaps.append(deepest_overlap(simulation)) + return overlaps + + def fixtures(backend, seed, dt): results = {} for name in ("separated_planar", "crossing", "coincident_parallel"): @@ -171,11 +191,12 @@ def fixtures(backend, seed, dt): ] trace = Trace(simulation) with trace.instrument(): - simulation.relax_cell_mechanics(*MechanicsConfig().native_parameters()) + overlaps = resolve(simulation, dt) results[name] = dict( classification="expected 3D contact behavior", mechanics=MechanicsConfig().to_json(), contact_normals=normals, + overlap_by_step=overlaps, **trace.report(), ) for name, direction in (("planar_division", (1, 0, 0)), ("inherited_tilt", (1, 0, 0.2))): @@ -213,36 +234,12 @@ def fixtures(backend, seed, dt): simulation.add_plane_constraint(plane) trace = Trace(simulation, plane_z=0.8) - def relax_to_tolerance(config): - residuals = [] - for _ in range(20): - residuals.append( - max( - ( - max(0.0, -contact.signed_separation) - for contact in simulation.find_external_contacts().contacts - ), - default=0.0, - ) - ) - if residuals[-1] <= 1e-6 or (len(residuals) > 1 and residuals[-1] == residuals[-2]): - break - simulation.relax_cell_mechanics(*config.native_parameters()) - return residuals - - default_config = MechanicsConfig() - tight_config = MechanicsConfig(residual_rms_tolerance=1e-8) with trace.instrument(): - default_residuals = relax_to_tolerance(default_config) - default_geometry = cells(simulation) - tight_residuals = relax_to_tolerance(tight_config) + penetrations = resolve(simulation, dt) results["finite_height_constraints"] = dict( - classification="expected 3D wall relaxation; finite height is not strict 2D", - default_mechanics=default_config.to_json(), - tight_mechanics=tight_config.to_json(), - default_wall_penetration_by_pass=default_residuals, - tight_wall_penetration_by_pass=tight_residuals, - default_final_geometry=default_geometry, + classification="expected 3D wall contact; finite height is not strict 2D", + mechanics=MechanicsConfig().to_json(), + wall_penetration_by_step=penetrations, **trace.report(), ) simulation = Simulation(backend) diff --git a/tests/conformance/README.md b/tests/conformance/README.md index d65e8ae..c7c552b 100644 --- a/tests/conformance/README.md +++ b/tests/conformance/README.md @@ -34,7 +34,7 @@ The lifecycle scenario interleaves growth with two generations of deterministic ## Composed trajectory -The trajectory scenario composes coupled intracellular/extracellular rates, growth, cell and plane contacts, fixed-cell projection, mechanics relaxation, and equal division over three heterogeneous time steps. It compares every intermediate cell and signal state with a fresh CPU trajectory, requires each mechanics solve to converge, checks exact lineage identities, and confirms the final contact count. Geometry uses a `2e-3` absolute and relative tolerance, species use `2e-4`, and signal levels use `5e-4`; the wider bounds account for native solver differences feeding subsequent trajectory stages. +The trajectory scenario composes coupled intracellular/extracellular rates, growth and contact solved together with cell and plane contacts and a fixed cell, and equal division over three heterogeneous time steps. It compares every intermediate cell and signal state with a fresh CPU trajectory, checks exact lineage identities, and confirms the final contact count. Geometry uses a `2e-3` absolute and relative tolerance, species use `2e-4`, and signal levels use `5e-4`; the wider bounds account for native solver differences feeding subsequent trajectory stages. ## Signal grid @@ -60,10 +60,6 @@ The contact scenario compares each contact-capable backend with the CPU geometry The external-constraint scenario compares every typed field and per-cell incidence index with the CPU oracle for mixed planes, spheres, boxes, and cylinders; inside and outside regions; empty inputs; stable IDs across constraint kinds; deterministic degeneracies; rods tilted against a box face and a pillar barrel with both ends or one end inside the surface; and finite obstacles intersected only by a capsule mid-span. Geometry fields use absolute and relative tolerances of `2e-5`; identities, kinds, centerline-location tags, graph sizes, and incidence are exact. -## Mechanics +## Contact dynamics -The CPU mechanics fixtures probe the declared regularizer, operator symmetry and positive definiteness, solver convergence, exact residual recomputation, iteration-limit reporting, and non-finite-curvature breakdown. The shared mechanics scenario then compares native correction vectors and diagnostics with the CPU reference for a mixed colony, a one-iteration limit, empty systems, and buffer growth. It also applies a converged mixed-colony result and compares the resulting position, direction, and length state. Corrections, geometry, and initial residuals use absolute and relative tolerances of `3e-4`; convergence status and breakdown type are exact. - -## Constraint mechanics - -The external-constraint mechanics scenario compares correction vectors and integrated cell geometry with the CPU reference for plane, sphere, box, and cylinder boundaries, including outside finite obstacles whose only contact lies at the rod mid-span. It uses the mechanics tolerances above and requires an available backend without external-constraint support to reject a nonempty constraint set explicitly. The same executable is the native Metal and CUDA hardware acceptance gate. +The contact dynamics scenario solves the same contact systems on each backend and on the CPU reference: a pair, and chains of cells pressed together against a wall with a fixed cell at the far end, an inactive row, mixed compliances, and each growth load law. Both solves must converge, the backend's multipliers must satisfy the complementarity conditions to twice the solve tolerance, and the velocities, elongation rates, and loads they produce must match the reference, whose solution is unique. A solve restarted from its own solution takes no iterations, an iteration limit is reported with the multipliers reached, and an empty system is accepted. The scenario then runs a closed chamber until it fills and holds, and an unconfined colony that must elongate exactly as the same lineage does without contact. The same executable is the native Metal and CUDA hardware acceptance gate. diff --git a/tests/conformance/backend_contract_conformance_test.cpp b/tests/conformance/backend_contract_conformance_test.cpp index a2de3be..3b9937b 100644 --- a/tests/conformance/backend_contract_conformance_test.cpp +++ b/tests/conformance/backend_contract_conformance_test.cpp @@ -11,7 +11,7 @@ constexpr std::array required_features{ microsimulator::BackendFeature::growth, microsimulator::BackendFeature::species, microsimulator::BackendFeature::cell_contacts, - microsimulator::BackendFeature::cell_mechanics, + microsimulator::BackendFeature::contact_dynamics, microsimulator::BackendFeature::external_constraints, microsimulator::BackendFeature::signals, microsimulator::BackendFeature::coupled_rates, diff --git a/tests/conformance/constraint_mechanics_conformance_test.cpp b/tests/conformance/constraint_mechanics_conformance_test.cpp deleted file mode 100644 index c712d7b..0000000 --- a/tests/conformance/constraint_mechanics_conformance_test.cpp +++ /dev/null @@ -1,256 +0,0 @@ -#include -#include -#include -#include -#include - -#include "backend_devices.hpp" -#include "microsimulator/simulation.hpp" - -namespace { - -constexpr float absolute_tolerance = 3.0e-4F; -constexpr float relative_tolerance = 3.0e-4F; - -bool close(float actual, float expected) { - const auto tolerance = absolute_tolerance + relative_tolerance * std::abs(expected); - return std::abs(actual - expected) <= tolerance; -} - -using Fixture = void (*)(microsimulator::Simulation&); - -void populate_plane(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {0.0F, 0.4F, 0.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 2.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::PlaneConstraintInit plane; - plane.inward_normal = {0.0F, 1.0F, 0.0F}; - plane.coefficient = 1.25F; - simulation.add_plane_constraint(plane); -} - -void populate_fixed_plane(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {0.0F, 0.4F, 0.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 2.0F; - cell.radius = 0.5F; - cell.fixed = true; - simulation.add_cell(cell); - - microsimulator::PlaneConstraintInit plane; - plane.inward_normal = {0.0F, 1.0F, 0.0F}; - plane.coefficient = 1.25F; - simulation.add_plane_constraint(plane); -} - -void populate_outside_sphere(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {1.2F, 0.0F, 0.0F}; - cell.length = 0.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::SphereConstraintInit sphere; - sphere.radius = 1.0F; - sphere.coefficient = 0.75F; - simulation.add_sphere_constraint(sphere); -} - -void populate_inside_sphere(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {4.8F, 0.0F, 0.0F}; - cell.length = 0.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::SphereConstraintInit sphere; - sphere.radius = 5.0F; - sphere.allowed_region = microsimulator::SphereRegion::inside; - simulation.add_sphere_constraint(sphere); -} - -void populate_outside_box(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {1.4F, 0.0F, 0.0F}; - cell.direction = {0.0F, 1.0F, 0.0F}; - cell.length = 2.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::BoxConstraintInit box; - box.coefficient = 1.25F; - simulation.add_box_constraint(box); -} - -void populate_inside_box(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {4.8F, 0.0F, 0.0F}; - cell.length = 0.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::BoxConstraintInit box; - box.half_extents = {5.0F, 5.0F, 5.0F}; - box.allowed_region = microsimulator::ConstraintRegion::inside; - simulation.add_box_constraint(box); -} - -void populate_outside_cylinder(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {1.4F, 0.0F, 0.0F}; - cell.direction = {0.0F, 0.0F, 1.0F}; - cell.length = 2.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::CylinderConstraintInit cylinder; - cylinder.coefficient = 1.25F; - simulation.add_cylinder_constraint(cylinder); -} - -void populate_inside_cylinder(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {4.8F, 0.0F, 0.0F}; - cell.length = 0.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::CylinderConstraintInit cylinder; - cylinder.radius = 5.0F; - cylinder.half_height = 5.0F; - cylinder.allowed_region = microsimulator::ConstraintRegion::inside; - simulation.add_cylinder_constraint(cylinder); -} - -void populate_midspan_sphere(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {0.0F, 0.75F, 0.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 3.5F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::SphereConstraintInit sphere; - simulation.add_sphere_constraint(sphere); -} - -void populate_midspan_box(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {0.0F, 0.75F, 0.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 3.5F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::BoxConstraintInit box; - box.half_extents = {1.0F, 1.0F, 5.0F}; - simulation.add_box_constraint(box); -} - -void populate_midspan_cylinder(microsimulator::Simulation& simulation) { - microsimulator::CellInit cell; - cell.position = {0.0F, 0.75F, 0.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 3.5F; - cell.radius = 0.5F; - simulation.add_cell(cell); - - microsimulator::CylinderConstraintInit cylinder; - cylinder.center = {0.4F, 0.0F, 0.0F}; - cylinder.half_height = 5.0F; - simulation.add_cylinder_constraint(cylinder); -} - -void compare_results(const microsimulator::MechanicsSolveResult& actual, - const microsimulator::MechanicsSolveResult& expected) { - assert(actual.report.status == expected.report.status); - assert(actual.report.breakdown == expected.report.breakdown); - assert(close(actual.report.initial_residual_rms, expected.report.initial_residual_rms)); - assert(actual.corrections.size() == expected.corrections.size()); - for (std::size_t index = 0; index < expected.corrections.size(); ++index) { - const auto& left = actual.corrections[index]; - const auto& right = expected.corrections[index]; - assert(close(left.translation.x, right.translation.x)); - assert(close(left.translation.y, right.translation.y)); - assert(close(left.translation.z, right.translation.z)); - assert(close(left.rotation.x, right.rotation.x)); - assert(close(left.rotation.y, right.rotation.y)); - assert(close(left.rotation.z, right.rotation.z)); - assert(close(left.length, right.length)); - } -} - -void compare_cells(const microsimulator::Simulation& actual, - const microsimulator::Simulation& expected) { - const auto actual_cells = actual.cells(); - const auto expected_cells = expected.cells(); - assert(actual_cells.size() == expected_cells.size()); - for (std::size_t index = 0; index < expected_cells.size(); ++index) { - const auto& left = actual_cells[index]; - const auto& right = expected_cells[index]; - assert(left.id == right.id); - assert(close(left.position.x, right.position.x)); - assert(close(left.position.y, right.position.y)); - assert(close(left.position.z, right.position.z)); - assert(close(left.direction.x, right.direction.x)); - assert(close(left.direction.y, right.direction.y)); - assert(close(left.direction.z, right.direction.z)); - assert(close(left.length, right.length)); - } -} - -void run_fixture(microsimulator::BackendKind backend, std::uint32_t device_index, Fixture fixture) { - microsimulator::Simulation reference(microsimulator::BackendKind::cpu); - microsimulator::Simulation candidate(backend, 0, 0, device_index); - fixture(reference); - fixture(candidate); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 2.0e-5F; - const auto expected = reference.relax_cell_mechanics(parameters); - const auto actual = candidate.relax_cell_mechanics(parameters); - compare_results(actual, expected); - compare_cells(candidate, reference); -} - -void reject_unsupported_backend(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation simulation(backend, 0, 0, device_index); - populate_plane(simulation); - bool rejected = false; - try { - static_cast(simulation.solve_cell_mechanics()); - } catch (const std::runtime_error&) { - rejected = true; - } - assert(rejected); -} - -} // namespace - -int main() { - microsimulator::test::for_each_backend_device( - [](microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation capability_probe(backend, 0, 0, device_index); - if (!capability_probe.supports(microsimulator::BackendFeature::external_constraints)) { - reject_unsupported_backend(backend, device_index); - return; - } - run_fixture(backend, device_index, populate_plane); - run_fixture(backend, device_index, populate_fixed_plane); - run_fixture(backend, device_index, populate_outside_sphere); - run_fixture(backend, device_index, populate_inside_sphere); - run_fixture(backend, device_index, populate_outside_box); - run_fixture(backend, device_index, populate_inside_box); - run_fixture(backend, device_index, populate_outside_cylinder); - run_fixture(backend, device_index, populate_inside_cylinder); - run_fixture(backend, device_index, populate_midspan_sphere); - run_fixture(backend, device_index, populate_midspan_box); - run_fixture(backend, device_index, populate_midspan_cylinder); - }); - return 0; -} diff --git a/tests/conformance/mechanics_conformance_test.cpp b/tests/conformance/mechanics_conformance_test.cpp deleted file mode 100644 index 049f736..0000000 --- a/tests/conformance/mechanics_conformance_test.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include -#include -#include -#include -#include -#include -#include - -#include "backend_devices.hpp" -#include "microsimulator/simulation.hpp" - -namespace { - -constexpr float absolute_tolerance = 3.0e-4F; -constexpr float relative_tolerance = 3.0e-4F; - -bool close(float actual, float expected) { - const auto tolerance = absolute_tolerance + relative_tolerance * std::abs(expected); - return std::abs(actual - expected) <= tolerance; -} - -microsimulator::CellId add_capsule(microsimulator::Simulation& simulation, - microsimulator::Vec3 center, microsimulator::Vec3 axis, - float length = 4.0F, float radius = 0.5F) { - microsimulator::CellInit cell; - cell.position = center; - cell.direction = axis; - cell.length = length; - cell.radius = radius; - return simulation.add_cell(cell); -} - -void populate_mixed_colony(microsimulator::Simulation& simulation) { - add_capsule(simulation, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - add_capsule(simulation, {0.2F, 0.8F, 0.0F}, {1.0F, 0.2F, 0.0F}); - add_capsule(simulation, {-0.3F, 0.1F, 0.7F}, {0.0F, 1.0F, 0.3F}); - add_capsule(simulation, {4.8F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); -} - -void require_close(float actual, float expected, std::string_view scenario, std::size_t index, - std::string_view field) { - if (close(actual, expected)) { - return; - } - std::cerr << scenario << " correction " << index << ' ' << field << ": actual=" << actual - << " expected=" << expected << '\n'; - std::abort(); -} - -void compare_corrections(const microsimulator::MechanicsSolveResult& actual, - const microsimulator::MechanicsSolveResult& expected, - std::string_view scenario) { - assert(actual.report.status == expected.report.status); - assert(actual.report.breakdown == expected.report.breakdown); - require_close(actual.report.initial_residual_rms, expected.report.initial_residual_rms, scenario, - 0, "initial_residual_rms"); - assert(actual.corrections.size() == expected.corrections.size()); - for (std::size_t index = 0; index < expected.corrections.size(); ++index) { - const auto& left = actual.corrections[index]; - const auto& right = expected.corrections[index]; - require_close(left.translation.x, right.translation.x, scenario, index, "translation.x"); - require_close(left.translation.y, right.translation.y, scenario, index, "translation.y"); - require_close(left.translation.z, right.translation.z, scenario, index, "translation.z"); - require_close(left.rotation.x, right.rotation.x, scenario, index, "rotation.x"); - require_close(left.rotation.y, right.rotation.y, scenario, index, "rotation.y"); - require_close(left.rotation.z, right.rotation.z, scenario, index, "rotation.z"); - require_close(left.length, right.length, scenario, index, "length"); - } -} - -void run_converged_colony(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation reference(microsimulator::BackendKind::cpu); - microsimulator::Simulation candidate(backend, 0, 0, device_index); - populate_mixed_colony(reference); - populate_mixed_colony(candidate); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 2.0e-5F; - const auto expected = reference.solve_cell_mechanics(parameters); - const auto actual = candidate.solve_cell_mechanics(parameters); - assert(expected.report.status == microsimulator::SolverStatus::converged); - assert(actual.report.final_residual_rms <= parameters.residual_rms_tolerance); - compare_corrections(actual, expected, "converged colony"); -} - -void run_iteration_limit(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation reference(microsimulator::BackendKind::cpu); - microsimulator::Simulation candidate(backend, 0, 0, device_index); - populate_mixed_colony(reference); - populate_mixed_colony(candidate); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 0.0F; - parameters.max_iterations = 1; - const auto expected = reference.solve_cell_mechanics(parameters); - const auto actual = candidate.solve_cell_mechanics(parameters); - assert(expected.report.status == microsimulator::SolverStatus::iteration_limit); - assert(actual.report.iterations == 1); - compare_corrections(actual, expected, "iteration limit"); -} - -void run_empty_systems(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation empty(backend, 0, 0, device_index); - const auto empty_result = empty.solve_cell_mechanics(); - assert(empty_result.report.status == microsimulator::SolverStatus::converged); - assert(empty_result.corrections.empty()); - - microsimulator::Simulation separated(backend, 0, 0, device_index); - add_capsule(separated, {}, {1.0F, 0.0F, 0.0F}); - add_capsule(separated, {10.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto separated_result = separated.solve_cell_mechanics(); - assert(separated_result.report.status == microsimulator::SolverStatus::converged); - assert(separated_result.report.iterations == 0); - for (const auto& correction : separated_result.corrections) { - assert(correction.translation.x == 0.0F); - assert(correction.translation.y == 0.0F); - assert(correction.translation.z == 0.0F); - } -} - -void run_buffer_growth(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation simulation(backend, 0, 0, device_index); - add_capsule(simulation, {}, {1.0F, 0.0F, 0.0F}); - add_capsule(simulation, {0.0F, 0.8F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto first = simulation.solve_cell_mechanics(); - assert(first.report.status == microsimulator::SolverStatus::converged); - - for (std::size_t index = 0; index < 7; ++index) { - add_capsule(simulation, {0.1F * static_cast(index), 0.2F, 0.1F}, {1.0F, 0.1F, 0.0F}); - } - const auto grown = simulation.solve_cell_mechanics(); - assert(grown.report.status == microsimulator::SolverStatus::converged); - assert(grown.corrections.size() == 9); -} - -void run_integrated_relaxation(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation reference(microsimulator::BackendKind::cpu); - microsimulator::Simulation candidate(backend, 0, 0, device_index); - populate_mixed_colony(reference); - populate_mixed_colony(candidate); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 2.0e-5F; - const auto expected = reference.relax_cell_mechanics(parameters); - const auto actual = candidate.relax_cell_mechanics(parameters); - compare_corrections(actual, expected, "integrated relaxation"); - const auto expected_cells = reference.cells(); - const auto actual_cells = candidate.cells(); - assert(actual_cells.size() == expected_cells.size()); - for (std::size_t index = 0; index < expected_cells.size(); ++index) { - assert(actual_cells[index].id == expected_cells[index].id); - assert(close(actual_cells[index].position.x, expected_cells[index].position.x)); - assert(close(actual_cells[index].position.y, expected_cells[index].position.y)); - assert(close(actual_cells[index].position.z, expected_cells[index].position.z)); - assert(close(actual_cells[index].direction.x, expected_cells[index].direction.x)); - assert(close(actual_cells[index].direction.y, expected_cells[index].direction.y)); - assert(close(actual_cells[index].direction.z, expected_cells[index].direction.z)); - assert(close(actual_cells[index].length, expected_cells[index].length)); - } -} - -void run_fixed_cell_relaxation(microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation reference(microsimulator::BackendKind::cpu); - microsimulator::Simulation candidate(backend, 0, 0, device_index); - const auto reference_fixed = add_capsule(reference, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto candidate_fixed = add_capsule(candidate, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto reference_free = add_capsule(reference, {0.0F, 0.8F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto candidate_free = add_capsule(candidate, {0.0F, 0.8F, 0.0F}, {1.0F, 0.0F, 0.0F}); - reference.set_cell_fixed(reference_fixed, true); - candidate.set_cell_fixed(candidate_fixed, true); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 2.0e-5F; - const auto expected = reference.solve_cell_mechanics(parameters); - const auto actual = candidate.solve_cell_mechanics(parameters); - compare_corrections(actual, expected, "fixed-cell solve"); - assert(actual.report.status == microsimulator::SolverStatus::converged); - assert(actual.corrections[0].translation.x == 0.0F); - assert(actual.corrections[0].translation.y == 0.0F); - assert(actual.corrections[0].translation.z == 0.0F); - assert(actual.corrections[0].rotation.x == 0.0F); - assert(actual.corrections[0].rotation.y == 0.0F); - assert(actual.corrections[0].rotation.z == 0.0F); - assert(actual.corrections[0].length == 0.0F); - assert(actual.corrections[1].translation.y > 0.0F); - - const auto expected_relaxation = reference.relax_cell_mechanics(parameters); - const auto actual_relaxation = candidate.relax_cell_mechanics(parameters); - compare_corrections(actual_relaxation, expected_relaxation, "fixed-cell relaxation"); - assert(candidate.cell(candidate_fixed).position.x == 0.0F); - assert(candidate.cell(candidate_fixed).position.y == 0.0F); - assert(candidate.cell(candidate_fixed).position.z == 0.0F); - assert(candidate.cell(candidate_free).position.y > 0.8F); - assert( - close(candidate.cell(candidate_free).position.y, reference.cell(reference_free).position.y)); -} - -} // namespace - -int main() { - microsimulator::test::for_each_backend_device( - [](microsimulator::BackendKind backend, std::uint32_t device_index) { - microsimulator::Simulation capability_probe(backend, 0, 0, device_index); - if (!capability_probe.supports(microsimulator::BackendFeature::cell_mechanics)) { - return; - } - run_empty_systems(backend, device_index); - run_converged_colony(backend, device_index); - run_iteration_limit(backend, device_index); - run_buffer_growth(backend, device_index); - run_integrated_relaxation(backend, device_index); - run_fixed_cell_relaxation(backend, device_index); - }); - return 0; -} diff --git a/tests/conformance/trajectory_conformance_test.cpp b/tests/conformance/trajectory_conformance_test.cpp index ee6da8e..a9abe91 100644 --- a/tests/conformance/trajectory_conformance_test.cpp +++ b/tests/conformance/trajectory_conformance_test.cpp @@ -141,22 +141,18 @@ void compare_state(const microsimulator::Simulation& actual, void run_trajectory(microsimulator::BackendKind backend, std::uint32_t device_index) { auto reference = make_simulation(microsimulator::BackendKind::cpu, 0); auto candidate = make_simulation(backend, device_index); - microsimulator::MechanicsParameters mechanics; - mechanics.residual_rms_tolerance = 2.0e-5F; - mechanics.max_iterations = 256; + // A tight overlap tolerance holds both backends to the same contact + // solution, which is unique. + microsimulator::ContactDynamicsParameters dynamics; + dynamics.overlap_tolerance = 2.0e-4F; for (std::size_t step = 0; step < time_steps.size(); ++step) { - reference.step(time_steps[step]); - candidate.step(time_steps[step]); - compare_state(candidate, reference); + const auto expected_solve = reference.step(time_steps[step], dynamics); + const auto actual_solve = candidate.step(time_steps[step], dynamics); assert(reference.last_signal_solve_report()->converged); assert(candidate.last_signal_solve_report()->converged); - - const auto expected_solve = reference.relax_cell_mechanics(mechanics); - const auto actual_solve = candidate.relax_cell_mechanics(mechanics); - assert(expected_solve.report.status == microsimulator::SolverStatus::converged); - assert(actual_solve.report.status == microsimulator::SolverStatus::converged); - assert(actual_solve.report.final_residual_rms <= mechanics.residual_rms_tolerance); + assert(close(actual_solve.report.max_overlap, expected_solve.report.max_overlap, + geometry_tolerance)); compare_state(candidate, reference); if (step == 0) { diff --git a/tests/cpp/constraint_geometry_test.cpp b/tests/cpp/constraint_geometry_test.cpp index 2a447b9..9a2b8e0 100644 --- a/tests/cpp/constraint_geometry_test.cpp +++ b/tests/cpp/constraint_geometry_test.cpp @@ -385,89 +385,6 @@ void test_outside_box_clear_endpoint_emits_no_row() { assert(close(contact.weight, 1.0F)); } -float deepest_penetration(const microsimulator::WorldState& state, - const microsimulator::ConstraintSet& constraints) { - auto deepest = 0.0F; - const auto graph = microsimulator::find_external_contacts_cpu(state, constraints); - for (const auto& contact : graph.contacts()) { - deepest = std::min(deepest, contact.signed_separation); - } - return deepest; -} - -void test_projection_lays_a_tilted_cell_along_a_wall() { - microsimulator::WorldState state; - const auto id = add_capsule(state, {1.3F, 0.25F, 0.0F}, {0.1F, 1.0F, 0.0F}, 1.0F); - microsimulator::ConstraintSet constraints; - microsimulator::BoxConstraintInit box; - box.half_extents = {1.0F, 2.0F, 3.0F}; - constraints.add_box(box); - - microsimulator::project_cells_out_of_constraints(state, constraints); - - // Each end moves out by its own depth, so the rod ends up parallel to the - // face, in contact with the wall without being inside it. - const auto after = state.cell(id); - assert(close(after.position.x, 1.5F, 1.0e-4F)); - assert(close(after.position.y, 0.25F, 1.0e-4F)); - assert(close(after.direction.x, 0.0F, 1.0e-4F)); - assert(close(after.direction.y, 1.0F, 1.0e-4F)); - assert(close(after.length, 1.0F)); - const auto resting = deepest_penetration(state, constraints); - assert(resting < 0.0F); - assert(resting >= -1.0e-4F); -} - -void test_projection_turns_a_wedged_cell_flat() { - microsimulator::WorldState state; - // A rod standing almost upright in a slot too low for it. - const auto id = add_capsule(state, {0.0F, 0.0F, 0.8F}, {0.3F, 0.0F, 1.0F}, 1.5F); - microsimulator::ConstraintSet constraints; - microsimulator::PlaneConstraintInit floor; - floor.inward_normal = {0.0F, 0.0F, 1.0F}; - constraints.add_plane(floor); - microsimulator::PlaneConstraintInit ceiling; - ceiling.point = {0.0F, 0.0F, 1.6F}; - ceiling.inward_normal = {0.0F, 0.0F, -1.0F}; - constraints.add_plane(ceiling); - const auto before = deepest_penetration(state, constraints); - assert(before < -0.4F); - - for (int pass = 0; pass < 4; ++pass) { - microsimulator::project_cells_out_of_constraints(state, constraints); - } - - const auto after = state.cell(id); - assert(deepest_penetration(state, constraints) >= -1.0e-3F); - assert(std::abs(after.direction.z) * after.length <= 0.6F + 2.0e-3F); - assert(close(after.length, 1.5F)); -} - -void test_projection_resolves_a_corner_and_leaves_fixed_cells() { - microsimulator::WorldState state; - const auto mobile = add_capsule(state, {0.2F, 0.3F, 0.0F}, {0.0F, 0.0F, 1.0F}, 0.0F); - microsimulator::CellInit pinned; - pinned.position = {4.0F, 0.1F, 0.0F}; - pinned.direction = {0.0F, 0.0F, 1.0F}; - pinned.length = 0.0F; - pinned.radius = 0.5F; - pinned.fixed = true; - const auto fixed = state.add_cell(pinned); - microsimulator::ConstraintSet constraints; - microsimulator::PlaneConstraintInit floor; - floor.inward_normal = {0.0F, 1.0F, 0.0F}; - constraints.add_plane(floor); - microsimulator::PlaneConstraintInit side; - side.inward_normal = {1.0F, 0.0F, 0.0F}; - constraints.add_plane(side); - - microsimulator::project_cells_out_of_constraints(state, constraints); - - assert(close(state.cell(mobile).position.x, 0.5F, 1.0e-4F)); - assert(close(state.cell(mobile).position.y, 0.5F, 1.0e-4F)); - assert(state.cell(fixed).position.y == 0.1F); -} - void test_cylinder_ids_validation_and_checkpoint() { microsimulator::ConstraintSet constraints; microsimulator::CylinderConstraintInit cylinder; @@ -650,9 +567,6 @@ int main() { test_outside_box_detects_centered_wall_crossing(); test_outside_box_tilted_face_contact_keeps_both_endpoints(); test_outside_box_clear_endpoint_emits_no_row(); - test_projection_lays_a_tilted_cell_along_a_wall(); - test_projection_turns_a_wedged_cell_flat(); - test_projection_resolves_a_corner_and_leaves_fixed_cells(); test_cylinder_ids_validation_and_checkpoint(); test_outside_cylinder_barrel_contact_uses_two_weighted_endpoints(); test_outside_cylinder_rim_contact_has_blended_normal(); diff --git a/tests/cpp/mechanics_integration_test.cpp b/tests/cpp/mechanics_integration_test.cpp deleted file mode 100644 index 6b1a142..0000000 --- a/tests/cpp/mechanics_integration_test.cpp +++ /dev/null @@ -1,209 +0,0 @@ -#include -#include -#include -#include -#include - -#include "microsimulator/mechanics.hpp" -#include "microsimulator/simulation.hpp" - -namespace { - -bool close(float actual, float expected, float tolerance = 1.0e-5F) { - return std::abs(actual - expected) <= tolerance; -} - -void test_integration_applies_declared_geometry_semantics() { - microsimulator::WorldState state; - microsimulator::CellInit first; - first.length = 4.0F; - const auto first_id = state.add_cell(first); - microsimulator::CellInit second = first; - second.position = {2.0F, 0.0F, 0.0F}; - const auto second_id = state.add_cell(second); - - microsimulator::MechanicsSolveResult result; - result.corrections = { - microsimulator::CellCorrection{{1.0F, 2.0F, 3.0F}, {0.0F, 0.0F, 0.2F}, -1.0F}, - microsimulator::CellCorrection{{-1.0F, 0.0F, 0.0F}, {0.0F, 0.0F, 0.0F}, 0.25F}, - }; - microsimulator::MechanicsIntegrationParameters parameters; - parameters.max_rotation_radians = 0.1F; - const float desired_increments[] = {0.5F, 0.5F}; - microsimulator::integrate_mechanics_result(state, result, parameters, desired_increments); - - const auto integrated_first = state.cell(first_id); - assert(close(integrated_first.position.x, 1.0F)); - assert(close(integrated_first.position.y, 2.0F)); - assert(close(integrated_first.position.z, 3.0F)); - assert(close(integrated_first.direction.x, std::cos(0.1F))); - assert(close(integrated_first.direction.y, std::sin(0.1F))); - assert(close(integrated_first.length, 4.0F)); - - const auto integrated_second = state.cell(second_id); - assert(close(integrated_second.position.x, 1.0F)); - assert(close(integrated_second.length, 4.75F)); - state.validate(); -} - -void test_validation_is_atomic_and_requires_convergence() { - microsimulator::WorldState state; - microsimulator::CellInit cell; - const auto id = state.add_cell(cell); - - microsimulator::MechanicsSolveResult invalid; - invalid.corrections = {microsimulator::CellCorrection{}}; - invalid.corrections[0].translation.x = std::numeric_limits::quiet_NaN(); - bool rejected = false; - try { - microsimulator::integrate_mechanics_result(state, invalid); - } catch (const std::invalid_argument&) { - rejected = true; - } - assert(rejected); - assert(close(state.cell(id).position.x, 0.0F)); - - microsimulator::MechanicsSolveResult unconverged; - unconverged.corrections = {microsimulator::CellCorrection{}}; - unconverged.report.status = microsimulator::SolverStatus::iteration_limit; - rejected = false; - try { - microsimulator::integrate_mechanics_result(state, unconverged); - } catch (const std::runtime_error&) { - rejected = true; - } - assert(rejected); - assert(close(state.cell(id).position.x, 0.0F)); -} - -void test_relaxation_cannot_create_biomass() { - microsimulator::WorldState state; - const auto id = state.add_cell(microsimulator::CellInit{}); - const auto before = state.cell(id).length; - microsimulator::MechanicsSolveResult result; - result.corrections = {microsimulator::CellCorrection{{}, {}, 0.5F}}; - microsimulator::integrate_mechanics_result(state, result); - assert(state.cell(id).length == before); -} - -void test_fixed_cell_integration_only_applies_declared_growth() { - microsimulator::WorldState state; - microsimulator::CellInit cell; - cell.position = {1.0F, 2.0F, 3.0F}; - cell.direction = {1.0F, 0.0F, 0.0F}; - cell.length = 4.0F; - cell.fixed = true; - const auto id = state.add_cell(cell); - - microsimulator::MechanicsSolveResult result; - result.corrections = {microsimulator::CellCorrection{ - .translation = {8.0F, 7.0F, 6.0F}, - .rotation = {0.0F, 0.0F, 1.0F}, - .length = -2.0F, - }}; - const float desired_increments[] = {0.5F}; - microsimulator::integrate_mechanics_result(state, result, {}, desired_increments); - - const auto integrated = state.cell(id); - assert(close(integrated.position.x, 1.0F)); - assert(close(integrated.position.y, 2.0F)); - assert(close(integrated.position.z, 3.0F)); - assert(close(integrated.direction.x, 1.0F)); - assert(close(integrated.direction.y, 0.0F)); - assert(close(integrated.direction.z, 0.0F)); - assert(close(integrated.length, 4.5F)); -} - -void test_simulation_relaxation_reduces_penetration() { - microsimulator::Simulation simulation; - microsimulator::CellInit first; - first.length = 4.0F; - microsimulator::CellInit second = first; - second.position.y = 0.8F; - const auto first_id = simulation.add_cell(first); - const auto second_id = simulation.add_cell(second); - const auto before = simulation.find_cell_contacts(); - assert(before.size() == 2); - - const auto result = simulation.relax_cell_mechanics(); - assert(result.report.status == microsimulator::SolverStatus::converged); - const auto after = simulation.find_cell_contacts(); - assert(after.size() == 2); - assert(after.contacts()[0].signed_separation > before.contacts()[0].signed_separation); - assert(simulation.cell(first_id).position.y < 0.0F); - assert(simulation.cell(second_id).position.y > 0.8F); - assert(close(simulation.cell(first_id).length, 4.0F)); - assert(close(simulation.cell(second_id).length, 4.0F)); - simulation.validate(); -} - -float deepest_wall_penetration(microsimulator::Simulation& simulation) { - auto deepest = 0.0F; - const auto graph = simulation.find_external_contacts(); - for (const auto& contact : graph.contacts()) { - deepest = std::min(deepest, contact.signed_separation); - } - return deepest; -} - -void test_simulation_relaxation_leaves_no_cell_inside_a_wall() { - microsimulator::Simulation simulation; - microsimulator::CellInit cell; - cell.position = {1.3F, 0.0F, 0.0F}; - cell.direction = {0.1F, 1.0F, 0.0F}; - cell.length = 1.0F; - cell.radius = 0.5F; - simulation.add_cell(cell); - microsimulator::BoxConstraintInit wall; - wall.half_extents = {1.0F, 2.0F, 3.0F}; - simulation.add_box_constraint(wall); - assert(deepest_wall_penetration(simulation) < -0.2F); - - const auto result = simulation.relax_cell_mechanics(); - assert(result.report.status == microsimulator::SolverStatus::converged); - assert(deepest_wall_penetration(simulation) >= -1.0e-4F); - simulation.validate(); -} - -void test_simulation_relaxation_cannot_carry_a_cell_through_a_thin_wall() { - microsimulator::Simulation simulation; - // A wall barely wider than the cell's radius, with a fixed neighbor that - // overlaps the cell almost completely from the side away from the wall. - microsimulator::BoxConstraintInit wall; - wall.center = {0.3F, 0.0F, 0.0F}; - wall.half_extents = {0.3F, 5.0F, 5.0F}; - simulation.add_box_constraint(wall); - microsimulator::CellInit cell; - cell.position = {-0.55F, 0.0F, 0.0F}; - cell.direction = {0.0F, 1.0F, 0.0F}; - cell.length = 1.0F; - cell.radius = 0.5F; - const auto cell_id = simulation.add_cell(cell); - microsimulator::CellInit neighbor = cell; - neighbor.position = {-0.6F, 0.0F, 0.0F}; - neighbor.fixed = true; - simulation.add_cell(neighbor); - - microsimulator::MechanicsParameters parameters; - parameters.gamma = 1.0e4F; - const auto result = simulation.relax_cell_mechanics(parameters); - assert(result.report.status == microsimulator::SolverStatus::converged); - // The correction alone would put the centerline past the wall's mid-plane, - // where the nearest face is the far one. - assert(result.corrections[0].translation.x > 0.85F); - assert(simulation.cell(cell_id).position.x < -0.49F); - assert(deepest_wall_penetration(simulation) >= -1.0e-4F); -} - -} // namespace - -int main() { - test_relaxation_cannot_create_biomass(); - test_integration_applies_declared_geometry_semantics(); - test_validation_is_atomic_and_requires_convergence(); - test_fixed_cell_integration_only_applies_declared_growth(); - test_simulation_relaxation_reduces_penetration(); - test_simulation_relaxation_leaves_no_cell_inside_a_wall(); - test_simulation_relaxation_cannot_carry_a_cell_through_a_thin_wall(); - return 0; -} diff --git a/tests/cpp/mechanics_operator_test.cpp b/tests/cpp/mechanics_operator_test.cpp deleted file mode 100644 index 64553b8..0000000 --- a/tests/cpp/mechanics_operator_test.cpp +++ /dev/null @@ -1,321 +0,0 @@ -#include -#include -#include -#include -#include -#include - -#include "microsimulator/mechanics.hpp" -#include "microsimulator/simulation.hpp" - -namespace { - -bool close(float actual, float expected, float tolerance = 1.0e-5F) { - return std::abs(actual - expected) <= tolerance; -} - -microsimulator::CellId add_capsule(microsimulator::WorldState& state, microsimulator::Vec3 center, - microsimulator::Vec3 axis, float length = 4.0F, - float radius = 0.5F) { - microsimulator::CellInit cell; - cell.position = center; - cell.direction = axis; - cell.length = length; - cell.radius = radius; - return state.add_cell(cell); -} - -float correction_dot(const std::vector& left, - const std::vector& right) { - float result = 0.0F; - for (std::size_t index = 0; index < left.size(); ++index) { - result += microsimulator::dot(left[index].translation, right[index].translation); - result += microsimulator::dot(left[index].rotation, right[index].rotation); - result += left[index].length * right[index].length; - } - return result; -} - -std::vector subtract( - const std::vector& left, - const std::vector& right) { - auto result = left; - for (std::size_t index = 0; index < result.size(); ++index) { - result[index].translation = left[index].translation - right[index].translation; - result[index].rotation = left[index].rotation - right[index].rotation; - result[index].length = left[index].length - right[index].length; - } - return result; -} - -float residual_rms(const std::vector& residual) { - if (residual.empty()) { - return 0.0F; - } - return std::sqrt(correction_dot(residual, residual) / static_cast(residual.size())); -} - -void assert_correction_close(const microsimulator::CellCorrection& actual, - const microsimulator::CellCorrection& expected) { - assert(close(actual.translation.x, expected.translation.x)); - assert(close(actual.translation.y, expected.translation.y)); - assert(close(actual.translation.z, expected.translation.z)); - assert(close(actual.rotation.x, expected.rotation.x)); - assert(close(actual.rotation.y, expected.rotation.y)); - assert(close(actual.rotation.z, expected.rotation.z)); - assert(close(actual.length, expected.length)); -} - -void test_contact_free_operator_is_declared_regularizer() { - microsimulator::WorldState state; - add_capsule(state, {}, {1.0F, 0.0F, 0.0F}); - const microsimulator::ContactGraph contacts(1, {}); - microsimulator::MechanicsParameters parameters; - parameters.mu_a = 2.0F; - parameters.gamma = 4.0F; - const std::vector input{microsimulator::CellCorrection{ - .translation = {1.0F, 2.0F, 3.0F}, - .rotation = {1.0F, 2.0F, 3.0F}, - .length = 4.0F, - }}; - - const auto output = - microsimulator::apply_mechanics_operator_cpu(state, contacts, input, parameters); - const auto mass = 10.0F; - const auto axial_inertia = 0.5F * mass * 0.5F * 0.5F; - const auto transverse_inertia = mass * (25.0F + 3.0F * 0.25F) / 12.0F; - assert(close(output[0].translation.x, 0.25F * mass)); - assert(close(output[0].translation.y, 0.25F * mass * 2.0F)); - assert(close(output[0].translation.z, 0.25F * mass * 3.0F)); - assert(close(output[0].rotation.x, 0.25F * axial_inertia)); - assert(close(output[0].rotation.y, 0.25F * transverse_inertia * 2.0F)); - assert(close(output[0].rotation.z, 0.25F * transverse_inertia * 3.0F)); - assert(close(output[0].length, 4.0F)); -} - -void test_operator_is_symmetric_and_positive_definite() { - microsimulator::WorldState state; - add_capsule(state, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - add_capsule(state, {0.2F, 0.8F, 0.0F}, {1.0F, 0.2F, 0.0F}); - add_capsule(state, {-0.3F, 0.1F, 0.7F}, {0.0F, 1.0F, 0.3F}); - const auto contacts = microsimulator::find_cell_contacts_cpu(state); - assert(!contacts.empty()); - - const std::vector first{ - microsimulator::CellCorrection{{0.2F, -0.4F, 0.3F}, {0.1F, 0.2F, -0.2F}, 0.05F}, - microsimulator::CellCorrection{{-0.1F, 0.7F, -0.2F}, {0.4F, -0.3F, 0.1F}, -0.02F}, - microsimulator::CellCorrection{{0.5F, 0.1F, -0.6F}, {-0.2F, 0.1F, 0.3F}, 0.08F}, - }; - const std::vector second{ - microsimulator::CellCorrection{{-0.3F, 0.2F, 0.1F}, {0.5F, -0.1F, 0.2F}, -0.04F}, - microsimulator::CellCorrection{{0.6F, -0.2F, 0.4F}, {-0.3F, 0.4F, 0.2F}, 0.03F}, - microsimulator::CellCorrection{{-0.2F, 0.8F, 0.1F}, {0.2F, 0.3F, -0.4F}, 0.06F}, - }; - - const auto applied_first = microsimulator::apply_mechanics_operator_cpu(state, contacts, first); - const auto applied_second = microsimulator::apply_mechanics_operator_cpu(state, contacts, second); - const auto left = correction_dot(first, applied_second); - const auto right = correction_dot(applied_first, second); - assert(close(left, right, 2.0e-5F)); - assert(correction_dot(first, applied_first) > 0.0F); -} - -void test_solver_converges_and_reports_recomputed_residual() { - microsimulator::WorldState state; - add_capsule(state, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - add_capsule(state, {0.0F, 0.8F, 0.0F}, {1.0F, 0.0F, 0.0F}); - const auto contacts = microsimulator::find_cell_contacts_cpu(state); - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 1.0e-6F; - - const auto solution = microsimulator::solve_cell_mechanics_cpu(state, contacts, parameters); - assert(solution.report.status == microsimulator::SolverStatus::converged); - assert(solution.report.breakdown == microsimulator::SolverBreakdown::none); - assert(solution.report.iterations > 0); - assert(solution.corrections[0].translation.y < 0.0F); - assert(solution.corrections[1].translation.y > 0.0F); - - const auto applied = microsimulator::apply_mechanics_operator_cpu( - state, contacts, solution.corrections, parameters); - const auto rhs = microsimulator::build_mechanics_rhs_cpu(state, contacts, parameters); - const auto recomputed = residual_rms(subtract(rhs, applied)); - assert(close(solution.report.final_residual_rms, recomputed, 1.0e-7F)); - assert(recomputed <= parameters.residual_rms_tolerance); -} - -void test_external_rows_contribute_to_operator_rhs_and_solve() { - microsimulator::WorldState state; - add_capsule(state, {0.0F, 0.4F, 0.0F}, {1.0F, 0.0F, 0.0F}, 2.0F); - const microsimulator::ContactGraph contacts(1, {}); - microsimulator::ConstraintSet constraints; - microsimulator::PlaneConstraintInit plane; - plane.inward_normal = {0.0F, 1.0F, 0.0F}; - constraints.add_plane(plane); - const auto external_contacts = microsimulator::find_external_contacts_cpu(state, constraints); - assert(external_contacts.size() == 2); - - const std::vector input{microsimulator::CellCorrection{ - .translation = {0.0F, 1.0F, 0.0F}, - }}; - const auto applied = - microsimulator::apply_mechanics_operator_cpu(state, contacts, external_contacts, input); - assert(close(applied[0].translation.y, 1.3F)); - assert(close(applied[0].rotation.z, 0.0F)); - assert(close(applied[0].length, 0.0F)); - - const auto rhs = microsimulator::build_mechanics_rhs_cpu(state, contacts, external_contacts); - assert(close(rhs[0].translation.y, 0.1F)); - assert(close(rhs[0].rotation.z, 0.0F)); - assert(close(rhs[0].length, 0.0F)); - - microsimulator::MechanicsParameters parameters; - parameters.residual_rms_tolerance = 1.0e-6F; - const auto solution = - microsimulator::solve_cell_mechanics_cpu(state, contacts, external_contacts, parameters); - assert(solution.report.status == microsimulator::SolverStatus::converged); - assert(solution.corrections[0].translation.y > 0.0F); -} - -void test_sphere_rows_drive_cells_toward_the_allowed_region() { - microsimulator::Simulation outside; - microsimulator::CellInit outside_cell; - outside_cell.position = {1.2F, 0.0F, 0.0F}; - outside_cell.length = 0.0F; - outside_cell.radius = 0.5F; - outside.add_cell(outside_cell); - microsimulator::SphereConstraintInit outside_sphere; - outside_sphere.radius = 1.0F; - outside.add_sphere_constraint(outside_sphere); - const auto outside_result = outside.solve_cell_mechanics(); - assert(outside_result.report.status == microsimulator::SolverStatus::converged); - assert(outside_result.corrections[0].translation.x > 0.0F); - - microsimulator::Simulation inside; - microsimulator::CellInit inside_cell; - inside_cell.position = {4.8F, 0.0F, 0.0F}; - inside_cell.length = 0.0F; - inside_cell.radius = 0.5F; - inside.add_cell(inside_cell); - microsimulator::SphereConstraintInit inside_sphere; - inside_sphere.radius = 5.0F; - inside_sphere.allowed_region = microsimulator::SphereRegion::inside; - inside.add_sphere_constraint(inside_sphere); - const auto inside_result = inside.solve_cell_mechanics(); - assert(inside_result.report.status == microsimulator::SolverStatus::converged); - assert(inside_result.corrections[0].translation.x < 0.0F); -} - -void test_iteration_limit_and_breakdown_are_diagnosed() { - microsimulator::WorldState limited_state; - add_capsule(limited_state, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - add_capsule(limited_state, {0.2F, 0.8F, 0.0F}, {1.0F, 0.2F, 0.0F}); - add_capsule(limited_state, {-0.3F, 0.1F, 0.7F}, {0.0F, 1.0F, 0.3F}); - const auto limited_contacts = microsimulator::find_cell_contacts_cpu(limited_state); - microsimulator::MechanicsParameters limited_parameters; - limited_parameters.residual_rms_tolerance = 0.0F; - limited_parameters.max_iterations = 1; - const auto limited = - microsimulator::solve_cell_mechanics_cpu(limited_state, limited_contacts, limited_parameters); - assert(limited.report.status == microsimulator::SolverStatus::iteration_limit); - assert(limited.report.breakdown == microsimulator::SolverBreakdown::none); - assert(limited.report.iterations == 1); - - microsimulator::WorldState overflow_state; - const auto first = add_capsule(overflow_state, {}, {1.0F, 0.0F, 0.0F}, 1.0e20F, 1.0e20F); - const auto second = - add_capsule(overflow_state, {0.0F, 1.0F, 0.0F}, {1.0F, 0.0F, 0.0F}, 1.0e20F, 1.0e20F); - microsimulator::CellContact contact{ - .first_id = first, - .second_id = second, - .first_slot = 0, - .second_slot = 1, - .point_on_first = {}, - .normal = {0.0F, 1.0F, 0.0F}, - .signed_separation = -1.0F, - .weight = 1.0F, - }; - const microsimulator::ContactGraph overflow_contacts(2, {contact}); - const auto broken = microsimulator::solve_cell_mechanics_cpu(overflow_state, overflow_contacts); - assert(broken.report.status == microsimulator::SolverStatus::breakdown); - assert(broken.report.breakdown == microsimulator::SolverBreakdown::non_finite_curvature); -} - -void test_invalid_inputs_are_rejected() { - microsimulator::WorldState state; - add_capsule(state, {}, {1.0F, 0.0F, 0.0F}); - microsimulator::MechanicsParameters parameters; - parameters.gamma = 0.0F; - bool rejected = false; - try { - static_cast(microsimulator::solve_cell_mechanics_cpu( - state, microsimulator::ContactGraph(1, {}), parameters)); - } catch (const std::invalid_argument&) { - rejected = true; - } - assert(rejected); -} - -void test_fixed_cells_are_projected_out_of_cpu_mechanics() { - microsimulator::WorldState state; - const auto fixed_id = - add_capsule(state, {0.0F, 0.0F, 0.0F}, {1.0F, 0.0F, 0.0F}); - add_capsule(state, {0.0F, 0.8F, 0.0F}, {1.0F, 0.0F, 0.0F}); - state.set_cell_fixed(fixed_id, true); - const auto contacts = microsimulator::find_cell_contacts_cpu(state); - assert(!contacts.empty()); - - const microsimulator::CellCorrection fixed_input{ - .translation = {0.4F, -0.3F, 0.2F}, - .rotation = {-0.1F, 0.5F, 0.7F}, - .length = 0.25F, - }; - const microsimulator::CellCorrection free_input{ - .translation = {-0.2F, 0.6F, 0.3F}, - .rotation = {0.8F, -0.4F, 0.1F}, - .length = -0.15F, - }; - const std::vector with_fixed_input{fixed_input, free_input}; - const std::vector with_zero_fixed{microsimulator::CellCorrection{}, free_input}; - const auto applied = - microsimulator::apply_mechanics_operator_cpu(state, contacts, with_fixed_input); - const auto applied_zero = - microsimulator::apply_mechanics_operator_cpu(state, contacts, with_zero_fixed); - assert_correction_close(applied[0], fixed_input); - assert_correction_close(applied[1], applied_zero[1]); - - const auto rhs = microsimulator::build_mechanics_rhs_cpu(state, contacts); - assert_correction_close(rhs[0], microsimulator::CellCorrection{}); - const auto solution = microsimulator::solve_cell_mechanics_cpu(state, contacts); - assert(solution.report.status == microsimulator::SolverStatus::converged); - assert_correction_close(solution.corrections[0], microsimulator::CellCorrection{}); - assert(solution.corrections[1].translation.y > 0.0F); -} - -void test_simulation_exposes_cpu_mechanics_capability() { - microsimulator::Simulation simulation; - microsimulator::CellInit first; - first.length = 4.0F; - microsimulator::CellInit second = first; - second.position.y = 0.8F; - simulation.add_cell(first); - simulation.add_cell(second); - assert(simulation.supports(microsimulator::BackendFeature::cell_mechanics)); - const auto result = simulation.solve_cell_mechanics(); - assert(result.report.status == microsimulator::SolverStatus::converged); - assert(result.corrections.size() == 2); -} - -} // namespace - -int main() { - test_contact_free_operator_is_declared_regularizer(); - test_operator_is_symmetric_and_positive_definite(); - test_solver_converges_and_reports_recomputed_residual(); - test_external_rows_contribute_to_operator_rhs_and_solve(); - test_sphere_rows_drive_cells_toward_the_allowed_region(); - test_iteration_limit_and_breakdown_are_diagnosed(); - test_invalid_inputs_are_rejected(); - test_fixed_cells_are_projected_out_of_cpu_mechanics(); - test_simulation_exposes_cpu_mechanics_capability(); - return 0; -} diff --git a/tests/cpp/signal_grid_test.cpp b/tests/cpp/signal_grid_test.cpp index 9b5d7c2..4b0a060 100644 --- a/tests/cpp/signal_grid_test.cpp +++ b/tests/cpp/signal_grid_test.cpp @@ -565,7 +565,7 @@ int main() { capped.configure_signal_grid(spec); const auto capped_id = capped.add_cell(rod); capped.apply_flow_drift(1.0F); - const auto limit = microsimulator::MechanicsIntegrationParameters{}.max_rotation_radians; + const auto limit = microsimulator::FlowDriftParameters{}.max_rotation_radians; assert(capped.cell(capped_id).direction.x > 3 * std::sin(limit)); assert_close(microsimulator::norm(capped.cell(capped_id).direction), 1.0F); @@ -573,7 +573,7 @@ int main() { frozen.configure_signal_grid(spec); const auto frozen_id = frozen.add_cell(rod); frozen.apply_flow_drift( - 1.0F, microsimulator::MechanicsIntegrationParameters{.max_rotation_radians = 0.0F}); + 1.0F, microsimulator::FlowDriftParameters{.max_rotation_radians = 0.0F}); assert_close(frozen.cell(frozen_id).direction.x, 0.0F); assert_close(frozen.cell(frozen_id).direction.y, 1.0F); }