From 93be4ad7cd785a894b6af472bde371b8bf93fe48 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Wed, 30 Sep 2026 22:55:31 +0200 Subject: [PATCH 01/46] Fix structure-fluid reaction forces --- NEWS.md | 3 + src/schemes/structure/structure.jl | 51 ++++---- test/schemes/schemes.jl | 1 + test/schemes/structure/fluid_interaction.jl | 134 ++++++++++++++++++++ 4 files changed, 166 insertions(+), 23 deletions(-) create mode 100644 test/schemes/structure/fluid_interaction.jl diff --git a/NEWS.md b/NEWS.md index be448787a6..fe9d6e86af 100644 --- a/NEWS.md +++ b/NEWS.md @@ -14,6 +14,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes +- Corrected hydrodynamic reaction forces on TLSPH and rigid-body systems, including + corrected kernel gradients and the approaching-particle condition for artificial + viscosity. - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 01d5917f6b..c7da23ffe5 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -45,10 +45,10 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. - # Note that we use the `neighbor_system` to compute the kernel gradient - # to obtain the same force as in the fluid-structure interaction. - grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, - distance, neighbor) + # Evaluate the actual fluid-side gradient. Corrected gradients need not be odd, + # so negating a gradient evaluated at `pos_diff` would give a different force. + grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, + distance, neighbor) m_b = hydrodynamic_mass(neighbor_system, neighbor) @@ -69,22 +69,22 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, p_a = current_pressure(v_particle_system, particle_system, particle) p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) - # Particle and neighbor (and the corresponding systems and particle quantities) are - # switched in the following two calls. This yields the exact same pair force as in the - # fluid-structure interaction, but with flipped sign because `pos_diff` is reversed. - dv_boundary = pressure_acceleration(neighbor_system, particle_system, - neighbor, particle, - m_b, m_a, p_b, p_a, rho_b, rho_a, - pos_diff, distance, grad_kernel, - system_correction(neighbor_system)) - - dv_particle = add_dv_viscosity(dv_boundary, neighbor_system, particle_system, - v_neighbor_system, v_particle_system, - neighbor, particle, pos_diff, distance, - sound_speed, m_b, m_a, rho_b, rho_a, - v_b, v_a, grad_kernel) - - dv_particle = add_dv_adhesion(dv_particle, surface_tension, + # Evaluate pressure and viscosity with fluid-first ordering, then negate the + # acceleration to obtain the reaction on the structure. This also preserves the + # approaching-particle condition of artificial viscosity. + dv_fluid = pressure_acceleration(neighbor_system, particle_system, + neighbor, particle, + m_b, m_a, p_b, p_a, rho_b, rho_a, + -pos_diff, distance, grad_kernel_fluid, + system_correction(neighbor_system)) + + dv_fluid = add_dv_viscosity(dv_fluid, neighbor_system, particle_system, + v_neighbor_system, v_particle_system, + neighbor, particle, -pos_diff, distance, + sound_speed, m_b, m_a, rho_b, rho_a, + v_b, v_a, grad_kernel_fluid) + + dv_particle = add_dv_adhesion(-dv_fluid, surface_tension, neighbor_system, particle_system, neighbor, particle, pos_diff, distance) @@ -93,7 +93,7 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, drho_particle = add_continuity_equation(zero(rho_a), particle_system, neighbor_system, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b) @inbounds write_drho_particle!(dv, particle_system, drho_particle, particle) end @@ -105,7 +105,7 @@ end particle_system::AbstractStructureSystem, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b) return drho_particle end @@ -114,7 +114,12 @@ end TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b) + # Density evolution uses the structure-side orientation. Only evaluate this + # additional gradient when the boundary model integrates density. + grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, + neighbor) + return add_continuity_equation(drho_particle, density_calculator(neighbor_system), m_b, rho_a, rho_b, v_a, v_b, grad_kernel, particle) diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index bb6e9d5483..dc1941f0b4 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,4 +1,5 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") +include("structure/fluid_interaction.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl new file mode 100644 index 0000000000..877a8f106b --- /dev/null +++ b/test/schemes/structure/fluid_interaction.jl @@ -0,0 +1,134 @@ +@testset verbose=true "Structure-fluid force balance" begin + particle_spacing = 1.0 + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.0 + reference_density = 1000.0 + structure_density = 2000.0 + state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) + viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), + ArtificialViscosityMonaghan(alpha=0.1)) + configurations = ((nothing, AdamiPressureExtrapolation()), + (nothing, ContinuityDensity()), + (KernelCorrection(), SummationDensity()), + (MixedKernelGradientCorrection(), SummationDensity())) + # Zero pressure isolates viscosity for approaching and receding particles. + # Nonzero pressure checks that pressure and viscous reactions accumulate consistently. + fluid_states = ((velocity=(1.0, 0.5), density=reference_density), + (velocity=(-1.0, -0.5), density=reference_density), + (velocity=(1.0, 0.5), density=1005.0)) + + @testset "$viscosity, $correction, $boundary_density" for viscosity in viscosities, + (correction, + boundary_density) in + configurations + + @testset "$structure_kind, $fluid_state" for structure_kind in + (:tlsph, :clamped_tlsph, :rigid), + fluid_state in fluid_states + + # `ContinuityDensity` is currently supported only for rigid structures. + if structure_kind != :rigid && boundary_density isa ContinuityDensity + continue + end + + fluid_velocity = reshape(collect(fluid_state.velocity), 2, 1) + fluid_ic = InitialCondition(; coordinates=reshape([0.0, 0.0], 2, 1), + velocity=fluid_velocity, + mass=[reference_density], + density=[fluid_state.density], particle_spacing) + fluid_system = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, viscosity, + correction, + density_calculator=ContinuityDensity(), + state_equation) + + structure_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), + velocity=zeros(2, 1), mass=[structure_density], + density=[structure_density], particle_spacing) + boundary_model = BoundaryModelDummyParticles([reference_density], + [reference_density], + boundary_density, + smoothing_kernel, smoothing_length; + state_equation, viscosity) + structure_system = if structure_kind == :rigid + RigidBodySystem(structure_ic; boundary_model) + else + clamped_particles = structure_kind == :clamped_tlsph ? (1:1) : (1:0) + TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, + young_modulus=1.0e5, poisson_ratio=0.3, + clamped_particles, boundary_model) + end + + semi = Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + ode = semidiscretize(semi, (0.0, 0.01)) + fluid, structure = ode.p.semi.systems + v_ode, u_ode = ode.u0.x + dv_ode = zero(v_ode) + TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) + dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) + expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] + + if !isnothing(correction) + # Ensure that this fixture exercises a gradient that is not odd. + pos_diff = SVector(1.5, 0.0) + gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, + 1.5, 1) + reverse_gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + -pos_diff, + 1.5, 1) + @test !isapprox(gradient, -reverse_gradient) + end + + if fluid_state.density == reference_density + @test iszero(fluid.pressure[1]) + @test iszero(structure.boundary_model.pressure[1]) + if isnothing(viscosity) || + (viscosity isa ArtificialViscosityMonaghan && + fluid_state.velocity[1] < 0) + @test iszero(expected_force) + else + # The viscous reaction on the structure follows the fluid motion. + @test expected_force[1] * fluid_state.velocity[1] > 0 + end + else + @test !iszero(expected_force) + end + + if boundary_density isa ContinuityDensity + # Independently evaluate d(rho_s)/dt = (rho_s/rho_f) m_f (v_s-v_f) ⋅ ∇_s W. + # Cubic-spline derivative at r/h = 1.5 in 2D, with h = 1. + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -reference_density / fluid_state.density * + fluid.mass[1] * fluid_state.velocity[1] * + kernel_derivative + dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) + @test dv_structure[end, 1] ≈ expected_density_rate + end + + if structure isa RigidBodySystem + @test isapprox(structure.resultant_force[], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + else + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + # Include clamped particles when checking the pair reaction directly. + dv_structure_fluid = zeros(eltype(structure), ndims(structure), + nparticles(structure)) + TrixiParticles.interact!(dv_structure_fluid, v_structure, u_structure, + v_fluid, u_fluid, structure, fluid, semi; + eachparticle=eachparticle(structure)) + @test isapprox(structure.mass[1] * dv_structure_fluid[:, 1], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + + if structure_kind == :tlsph + dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) + @test isapprox(structure.mass[1] * dv_structure[1:2, 1], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + end + end + end + end +end From 81739df123cae7a2e2ae4551b8a97240cb5f0d8e Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Thu, 1 Oct 2026 15:43:42 +0200 Subject: [PATCH 02/46] fix correction logixc as well --- NEWS.md | 2 +- src/schemes/structure/structure.jl | 29 ++++++++++- test/schemes/structure/fluid_interaction.jl | 55 ++++++++++++++------- 3 files changed, 66 insertions(+), 20 deletions(-) diff --git a/NEWS.md b/NEWS.md index fe9d6e86af..927a222534 100644 --- a/NEWS.md +++ b/NEWS.md @@ -16,7 +16,7 @@ used in the Julia ecosystem. Notable changes will be documented in this file for - Corrected hydrodynamic reaction forces on TLSPH and rigid-body systems, including corrected kernel gradients and the approaching-particle condition for artificial - viscosity. + viscosity (#1338). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index c7da23ffe5..d938973c2b 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -17,6 +17,25 @@ end end end +# Match the pressure and viscosity corrections used by the fluid-side RHS. +@inline function structure_fluid_force_correction(system::AbstractFluidSystem, + particle, rho_a, rho_b) + return zero(rho_a), 1, 1 +end + +@inline function structure_fluid_force_correction(system::WeaklyCompressibleSPHSystem, + particle, rho_a, rho_b) + viscosity_correction, pressure_correction, + _ = free_surface_correction(system_correction(system), system, rho_a, rho_b) + + return zero(rho_a), viscosity_correction, pressure_correction +end + +@propagate_inbounds function structure_fluid_force_correction(system::EntropicallyDampedSPHSystem, + particle, rho_a, rho_b) + return average_pressure(system, particle), 1, 1 +end + function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, @@ -69,20 +88,26 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, p_a = current_pressure(v_particle_system, particle_system, particle) p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) + p_avg, viscosity_correction, + pressure_correction = @inbounds structure_fluid_force_correction(neighbor_system, + neighbor, + rho_b, rho_a) + # Evaluate pressure and viscosity with fluid-first ordering, then negate the # acceleration to obtain the reaction on the structure. This also preserves the # approaching-particle condition of artificial viscosity. dv_fluid = pressure_acceleration(neighbor_system, particle_system, neighbor, particle, - m_b, m_a, p_b, p_a, rho_b, rho_a, + m_b, m_a, p_b - p_avg, p_a - p_avg, rho_b, rho_a, -pos_diff, distance, grad_kernel_fluid, system_correction(neighbor_system)) + dv_fluid *= pressure_correction dv_fluid = add_dv_viscosity(dv_fluid, neighbor_system, particle_system, v_neighbor_system, v_particle_system, neighbor, particle, -pos_diff, distance, sound_speed, m_b, m_a, rho_b, rho_a, - v_b, v_a, grad_kernel_fluid) + v_b, v_a, grad_kernel_fluid, viscosity_correction) dv_particle = add_dv_adhesion(-dv_fluid, surface_tension, neighbor_system, particle_system, diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl index 877a8f106b..4d5b728fde 100644 --- a/test/schemes/structure/fluid_interaction.jl +++ b/test/schemes/structure/fluid_interaction.jl @@ -7,20 +7,26 @@ state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), ArtificialViscosityMonaghan(alpha=0.1)) - configurations = ((nothing, AdamiPressureExtrapolation()), - (nothing, ContinuityDensity()), - (KernelCorrection(), SummationDensity()), - (MixedKernelGradientCorrection(), SummationDensity())) + configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), + (:wcsph, nothing, ContinuityDensity()), + (:wcsph, AkinciFreeSurfaceCorrection(reference_density), + AdamiPressureExtrapolation()), + (:wcsph, KernelCorrection(), SummationDensity()), + (:wcsph, MixedKernelGradientCorrection(), SummationDensity()), + (:edac, nothing, AdamiPressureExtrapolation()), + (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) # Zero pressure isolates viscosity for approaching and receding particles. # Nonzero pressure checks that pressure and viscous reactions accumulate consistently. fluid_states = ((velocity=(1.0, 0.5), density=reference_density), (velocity=(-1.0, -0.5), density=reference_density), (velocity=(1.0, 0.5), density=1005.0)) - @testset "$viscosity, $correction, $boundary_density" for viscosity in viscosities, - (correction, - boundary_density) in - configurations + @testset "$fluid_scheme, $viscosity, $correction, $boundary_density" for viscosity in + viscosities, + (fluid_scheme, + correction, + boundary_density) in + configurations @testset "$structure_kind, $fluid_state" for structure_kind in (:tlsph, :clamped_tlsph, :rigid), @@ -35,12 +41,21 @@ fluid_ic = InitialCondition(; coordinates=reshape([0.0, 0.0], 2, 1), velocity=fluid_velocity, mass=[reference_density], - density=[fluid_state.density], particle_spacing) - fluid_system = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, - smoothing_length, viscosity, - correction, - density_calculator=ContinuityDensity(), - state_equation) + density=[fluid_state.density], + pressure=state_equation(fluid_state.density), + particle_spacing) + fluid_system = if fluid_scheme == :wcsph + WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + viscosity, correction, + density_calculator=ContinuityDensity(), + state_equation) + else + EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + sound_speed=10.0, viscosity, correction, + density_calculator=ContinuityDensity(), + average_pressure_reduction=fluid_scheme == + :edac_pressure_reduction) + end structure_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), velocity=zeros(2, 1), mass=[structure_density], @@ -66,10 +81,12 @@ v_ode, u_ode = ode.u0.x dv_ode = zero(v_ode) TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] - if !isnothing(correction) + if correction isa KernelCorrection || + correction isa MixedKernelGradientCorrection # Ensure that this fixture exercises a gradient that is not odd. pos_diff = SVector(1.5, 0.0) gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, @@ -81,7 +98,7 @@ end if fluid_state.density == reference_density - @test iszero(fluid.pressure[1]) + @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, 1)) @test iszero(structure.boundary_model.pressure[1]) if isnothing(viscosity) || (viscosity isa ArtificialViscosityMonaghan && @@ -91,6 +108,11 @@ # The viscous reaction on the structure follows the fluid motion. @test expected_force[1] * fluid_state.velocity[1] > 0 end + elseif fluid_scheme == :edac_pressure_reduction && isnothing(viscosity) + # Uniform nonzero pressure produces no force after pressure reduction. + @test TrixiParticles.current_pressure(v_fluid, fluid, 1) ≈ + structure.boundary_model.pressure[1] + @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) else @test !iszero(expected_force) end @@ -112,7 +134,6 @@ else v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) # Include clamped particles when checking the pair reaction directly. dv_structure_fluid = zeros(eltype(structure), ndims(structure), From 31ba916c5a674625233be130cf5677da5a4fcb3a Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 08:44:28 +0200 Subject: [PATCH 03/46] review round 2 --- NEWS.md | 7 +- .../fluid/entropically_damped_sph/rhs.jl | 2 +- .../fluid/entropically_damped_sph/system.jl | 11 +- .../fluid/weakly_compressible_sph/rhs.jl | 9 +- src/schemes/structure/structure.jl | 195 +++++++----- test/schemes/schemes.jl | 1 + test/schemes/structure/fluid_interaction.jl | 66 ++-- .../structure/fluid_interaction_variants.jl | 295 ++++++++++++++++++ 8 files changed, 469 insertions(+), 117 deletions(-) create mode 100644 test/schemes/structure/fluid_interaction_variants.jl diff --git a/NEWS.md b/NEWS.md index 927a222534..5b79b8cfe8 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,8 +15,11 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Corrected hydrodynamic reaction forces on TLSPH and rigid-body systems, including - corrected kernel gradients and the approaching-particle condition for artificial - viscosity (#1338). + corrected kernel gradients, shifting momentum terms, near-zero-distance handling, + and the approaching-particle condition for artificial viscosity (#1338). +- Fixed EDAC interaction with gradient-based kernel corrections (#1338). +- Fixed pressure mirroring for fluid-structure interaction and boundary-kernel + evaluation in the structure continuity equation (#1338). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index d4c526f175..4f1ad54991 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -46,7 +46,7 @@ function interact!(dv, v_particle_system, u_particle_system, v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) - p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) + p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) # This technique by Basa et al. 2017 (10.1002/fld.1927) aims to reduce numerical # errors due to large pressures by subtracting the average pressure of neighboring diff --git a/src/schemes/fluid/entropically_damped_sph/system.jl b/src/schemes/fluid/entropically_damped_sph/system.jl index 426e79e537..45b5e06d27 100644 --- a/src/schemes/fluid/entropically_damped_sph/system.jl +++ b/src/schemes/fluid/entropically_damped_sph/system.jl @@ -263,6 +263,10 @@ end @inline shifting_technique(system::EntropicallyDampedSPHSystem) = system.shifting_technique +@inline function correction_matrix(system::EntropicallyDampedSPHSystem, particle) + return extract_smatrix(system.cache.correction_matrix, system, particle) +end + @propagate_inbounds function average_pressure(system::EntropicallyDampedSPHSystem, particle) average_pressure(system, system.average_pressure_reduction, particle) end @@ -332,6 +336,7 @@ function update_average_pressure!(system, ::Val{true}, v_ode, u_ode, semi) set_zero!(pressure_average) set_zero!(neighbor_counter) + v = wrap_v(v_ode, system, semi) u = wrap_u(u_ode, system, semi) # Use enabled neighbor systems for the average pressure. @@ -354,8 +359,10 @@ function update_average_pressure!(system, ::Val{true}, v_ode, u_ode, semi) neighbor, pos_diff, distance - pressure_average[particle] += current_pressure(v_neighbor_system, - neighbor_system, neighbor) + p_a = current_pressure(v, system, particle) + pressure_average[particle] += neighbor_pressure(v_neighbor_system, + neighbor_system, neighbor, + p_a) neighbor_counter[particle] += 1 end end diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index f09f56d886..87bef6b56f 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -71,9 +71,8 @@ function interact!(dv, v_particle_system, u_particle_system, # The following call is equivalent to # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # Only when the neighbor system is a `WallBoundarySystem` - # or a `TotalLagrangianSPHSystem` with the boundary model `PressureMirroring`, - # this will return `p_b = p_a`, which is the pressure of the fluid particle. + # For boundaries and structures using `PressureMirroring`, this returns + # `p_b = p_a`, which is the pressure of the fluid particle. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) @@ -155,7 +154,9 @@ end end @inline function neighbor_pressure(v_neighbor_system, - neighbor_system::WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + neighbor_system::Union{WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + RigidBodySystem{<:BoundaryModelDummyParticles{PressureMirroring}}}, neighbor, p_a) return p_a end diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index d938973c2b..3cf5d86592 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -1,20 +1,23 @@ # Shared structure-fluid interaction helpers used by multiple structure schemes. -@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, - particle_system::TotalLagrangianSPHSystem, - particle, m_b) +@propagate_inbounds function write_fluid_force!(dv, + particle_system::TotalLagrangianSPHSystem, + force_particle, particle) material_mass = particle_system.mass[particle] - for dim in eachindex(dv_fs) - dv[dim, particle] += dv_fs[dim] * m_b / material_mass + for i in 1:ndims(particle_system) + dv[i, particle] += force_particle[i] / material_mass end + + return dv end -@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, - particle_system::RigidBodySystem, - particle, m_b) +@propagate_inbounds function write_fluid_force!(dv, particle_system::RigidBodySystem, + force_particle, particle) force_per_particle = particle_system.force_per_particle - for dim in eachindex(dv_fs) - force_per_particle[dim, particle] += dv_fs[dim] * m_b + for i in 1:ndims(particle_system) + force_per_particle[i, particle] += force_particle[i] end + + return dv end # Match the pressure and viscosity corrections used by the fluid-side RHS. @@ -42,85 +45,106 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, neighbor_system::AbstractFluidSystem, semi; eachparticle=each_integrated_particle(particle_system)) sound_speed = system_sound_speed(neighbor_system) + correction = system_correction(neighbor_system) + shifting = shifting_technique(neighbor_system) + surface_tension = surface_tension_model(neighbor_system) + system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) + neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) + backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Match the fluid-side zero-distance check exactly. WCSPH scales this threshold + # with the compact support, while EDAC and IISPH use the smoothing length. + compact_support_ = compact_support(neighbor_system, particle_system) h = initial_smoothing_length(neighbor_system) - almostzero = sqrt(eps(h^2)) - - # Loop over all pairs of particles and neighbors within the kernel cutoff. - foreach_point_neighbor(particle_system, neighbor_system, - system_coords, neighbor_coords, semi; - points=eachparticle) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. - # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(neighbor_system) && distance < almostzero && return - - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. - # Evaluate the actual fluid-side gradient. Corrected gradients need not be odd, - # so negating a gradient evaluated at `pos_diff` would give a different force. - grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, - distance, neighbor) - - m_b = hydrodynamic_mass(neighbor_system, neighbor) - - rho_a = current_density(v_particle_system, particle_system, particle) - rho_b = current_density(v_neighbor_system, neighbor_system, neighbor) - - v_a = current_velocity(v_particle_system, particle_system, particle) - v_b = current_velocity(v_neighbor_system, neighbor_system, neighbor) - - surface_tension = surface_tension_model(neighbor_system) + almostzero = neighbor_system isa WeaklyCompressibleSPHSystem ? + sqrt(eps(compact_support_^2)) : sqrt(eps(h^2)) + @threaded semi for particle in eachparticle # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles # corresponding to the rest density of the fluid and not the material density. - m_a = hydrodynamic_mass(particle_system, particle) - - # In fluid-structure interaction, use the "hydrodynamic pressure" of the structure - # particles corresponding to the chosen boundary model. - p_a = current_pressure(v_particle_system, particle_system, particle) - p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) - - p_avg, viscosity_correction, - pressure_correction = @inbounds structure_fluid_force_correction(neighbor_system, - neighbor, - rho_b, rho_a) - - # Evaluate pressure and viscosity with fluid-first ordering, then negate the - # acceleration to obtain the reaction on the structure. This also preserves the - # approaching-particle condition of artificial viscosity. - dv_fluid = pressure_acceleration(neighbor_system, particle_system, - neighbor, particle, - m_b, m_a, p_b - p_avg, p_a - p_avg, rho_b, rho_a, - -pos_diff, distance, grad_kernel_fluid, - system_correction(neighbor_system)) - dv_fluid *= pressure_correction - - dv_fluid = add_dv_viscosity(dv_fluid, neighbor_system, particle_system, - v_neighbor_system, v_particle_system, - neighbor, particle, -pos_diff, distance, - sound_speed, m_b, m_a, rho_b, rho_a, - v_b, v_a, grad_kernel_fluid, viscosity_correction) - - dv_particle = add_dv_adhesion(-dv_fluid, surface_tension, - neighbor_system, particle_system, - neighbor, particle, pos_diff, distance) - - accumulate_structure_fluid_pair!(dv, dv_particle, particle_system, particle, m_b) - - drho_particle = add_continuity_equation(zero(rho_a), - particle_system, neighbor_system, - particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b) - - @inbounds write_drho_particle!(dv, particle_system, drho_particle, particle) + m_a = @inbounds hydrodynamic_mass(particle_system, particle) + rho_a = @inbounds current_density(v_particle_system, particle_system, particle) + v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) + + # Accumulate force components and density rate in one static vector. + init = zero(SVector{ndims(particle_system) + 1, eltype(particle_system)}) + + # Keep the returned name out of the closure to avoid allocations. + force_drho_particle_ = @inbounds mapreduce_neighbor(+, system_coords, + neighbor_coords, + neighborhood_search, backend, + particle; + init) do particle, + neighbor, + pos_diff, + distance + m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) + rho_b = @inbounds current_density(v_neighbor_system, neighbor_system, neighbor) + v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) + + # Boundary density has its own kernel support and zero-distance check. + drho_particle = @inbounds add_continuity_equation(zero(rho_a), + particle_system, + neighbor_system, + particle, neighbor, pos_diff, + distance, m_b, rho_a, rho_b, + v_a, v_b) + + # Only pressure/momentum contributions use the fluid-side pair cutoffs. + init_pair = vcat(zero(v_a), SVector(drho_particle)) + distance > compact_support_ && return init_pair + skip_zero_distance(neighbor_system) && distance < almostzero && return init_pair + + # Corrected gradients need not be odd; evaluate the fluid-side gradient. + grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, + distance, neighbor) + + # Use the hydrodynamic pressure defined by the structure's boundary model. + p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) + p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, + p_b) + + p_avg, viscosity_correction, + pressure_correction = @inbounds structure_fluid_force_correction(neighbor_system, + neighbor, + rho_b, rho_a) + + # Fluid-first ordering preserves the actual fluid force, including the + # approaching-particle condition of artificial viscosity. + dv_pressure = pressure_acceleration(neighbor_system, particle_system, + neighbor, particle, m_b, m_a, + p_b - p_avg, p_a - p_avg, rho_b, rho_a, + -pos_diff, distance, grad_kernel_fluid, + correction) + dv_fluid = dv_pressure * pressure_correction + + dv_fluid = @inbounds add_dv_viscosity(dv_fluid, neighbor_system, + particle_system, + v_neighbor_system, v_particle_system, + neighbor, particle, -pos_diff, distance, + sound_speed, m_b, m_a, rho_b, rho_a, + v_b, v_a, grad_kernel_fluid, + viscosity_correction) + + dv_fluid = @inbounds add_dv_shifting(dv_fluid, shifting, neighbor_system, + particle_system, v_neighbor_system, + v_particle_system, neighbor, particle, + m_b, m_a, rho_b, rho_a, v_b, v_a, + -pos_diff, distance, grad_kernel_fluid, + correction) + + dv_particle = @inbounds add_dv_adhesion(-dv_fluid, surface_tension, + neighbor_system, particle_system, + neighbor, particle, pos_diff, distance) + + return vcat(m_b * dv_particle, SVector(drho_particle)) + end + + @inbounds write_fluid_force!(dv, particle_system, force_drho_particle_, particle) + @inbounds write_drho_particle!(dv, particle_system, force_drho_particle_[end], + particle) end return dv @@ -140,10 +164,9 @@ end neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, v_a, v_b) - # Density evolution uses the structure-side orientation. Only evaluate this - # additional gradient when the boundary model integrates density. - grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, - neighbor) + # Density evolves with the boundary's own kernel and correction, not with the + # neighboring fluid's corrected gradient evaluated in the opposite direction. + grad_kernel = smoothing_kernel_grad(particle_system, pos_diff, distance, particle) return add_continuity_equation(drho_particle, density_calculator(neighbor_system), diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index dc1941f0b4..bc4043240b 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,5 +1,6 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") include("structure/fluid_interaction.jl") +include("structure/fluid_interaction_variants.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl index 4d5b728fde..d3a7aa7f5c 100644 --- a/test/schemes/structure/fluid_interaction.jl +++ b/test/schemes/structure/fluid_interaction.jl @@ -6,7 +6,9 @@ structure_density = 2000.0 state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), - ArtificialViscosityMonaghan(alpha=0.1)) + ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) + shifting_techniques = (nothing, ConsistentShiftingSun2019(), + TransportVelocityAdami(background_pressure=1000.0)) configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), (:wcsph, nothing, ContinuityDensity()), (:wcsph, AkinciFreeSurfaceCorrection(reference_density), @@ -15,18 +17,20 @@ (:wcsph, MixedKernelGradientCorrection(), SummationDensity()), (:edac, nothing, AdamiPressureExtrapolation()), (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) - # Zero pressure isolates viscosity for approaching and receding particles. - # Nonzero pressure checks that pressure and viscous reactions accumulate consistently. + # Zero pressure isolates viscosity and shifting for approaching and receding particles. + # Nonzero pressure checks that all momentum terms accumulate consistently. fluid_states = ((velocity=(1.0, 0.5), density=reference_density), (velocity=(-1.0, -0.5), density=reference_density), (velocity=(1.0, 0.5), density=1005.0)) - @testset "$fluid_scheme, $viscosity, $correction, $boundary_density" for viscosity in - viscosities, - (fluid_scheme, - correction, - boundary_density) in - configurations + @testset "$fluid_scheme, $viscosity, $correction, $boundary_density, $shifting_technique" for shifting_technique in + shifting_techniques, + viscosity in + viscosities, + (fluid_scheme, + correction, + boundary_density) in + configurations @testset "$structure_kind, $fluid_state" for structure_kind in (:tlsph, :clamped_tlsph, :rigid), @@ -46,12 +50,13 @@ particle_spacing) fluid_system = if fluid_scheme == :wcsph WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - viscosity, correction, + viscosity, correction, shifting_technique, density_calculator=ContinuityDensity(), state_equation) else EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, sound_speed=10.0, viscosity, correction, + shifting_technique, density_calculator=ContinuityDensity(), average_pressure_reduction=fluid_scheme == :edac_pressure_reduction) @@ -82,9 +87,20 @@ dv_ode = zero(v_ode) TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + # Isolate this pair from fluid self-interaction terms, which can be nonzero + # with shifting and corrected kernel gradients. + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, + v_structure, u_structure, fluid, structure, semi) expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] + if !isnothing(shifting_technique) + @test !iszero(TrixiParticles.delta_v(fluid, 1)) + end + if correction isa KernelCorrection || correction isa MixedKernelGradientCorrection # Ensure that this fixture exercises a gradient that is not odd. @@ -100,19 +116,28 @@ if fluid_state.density == reference_density @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, 1)) @test iszero(structure.boundary_model.pressure[1]) - if isnothing(viscosity) || - (viscosity isa ArtificialViscosityMonaghan && - fluid_state.velocity[1] < 0) - @test iszero(expected_force) - else - # The viscous reaction on the structure follows the fluid motion. - @test expected_force[1] * fluid_state.velocity[1] > 0 + if isnothing(shifting_technique) + if isnothing(viscosity) || + (viscosity isa ArtificialViscosityMonaghan && + fluid_state.velocity[1] < 0) + @test iszero(expected_force) + else + # The viscous reaction on the structure follows the fluid motion. + @test expected_force[1] * fluid_state.velocity[1] > 0 + end + elseif isnothing(viscosity) + # A nonzero reaction with no pressure or viscosity exercises shifting. + @test !iszero(expected_force) end elseif fluid_scheme == :edac_pressure_reduction && isnothing(viscosity) # Uniform nonzero pressure produces no force after pressure reduction. @test TrixiParticles.current_pressure(v_fluid, fluid, 1) ≈ structure.boundary_model.pressure[1] - @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) + if isnothing(shifting_technique) + @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) + else + @test !iszero(expected_force) + end else @test !iszero(expected_force) end @@ -132,9 +157,6 @@ @test isapprox(structure.resultant_force[], expected_force; rtol=sqrt(eps()), atol=sqrt(eps())) else - v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) - u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) # Include clamped particles when checking the pair reaction directly. dv_structure_fluid = zeros(eltype(structure), ndims(structure), nparticles(structure)) diff --git a/test/schemes/structure/fluid_interaction_variants.jl b/test/schemes/structure/fluid_interaction_variants.jl new file mode 100644 index 0000000000..5faa5f3297 --- /dev/null +++ b/test/schemes/structure/fluid_interaction_variants.jl @@ -0,0 +1,295 @@ +# Prescribed pair states isolate interaction formulas from density/pressure updates. +function structure_fluid_pair_state(; fluid_scheme=:wcsph, structure_kind=:tlsph, + fluid_options=(;), distance=1.5, dimensions=2, + boundary_density=AdamiPressureExtrapolation(), + boundary_smoothing_length=1.0, + boundary_viscosity=get(fluid_options, :viscosity, + nothing), + fluid_pressure=500.0, monaghan_kajtar=false, + coordinates=reshape([distance; zeros(dimensions - 1)], + dimensions, 1), + parallelization_backend=SerialBackend()) + smoothing_kernel = SchoenbergCubicSplineKernel{dimensions}() + smoothing_length = particle_spacing = 1.0 + state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1000.0, + exponent=1.0, clip_negative_pressure=false) + velocity = reshape([1.0, 0.5, 0.7][1:dimensions], dimensions, 1) + fluid_ic = InitialCondition(; coordinates=zeros(dimensions, 1), velocity, + mass=[1100.0], density=[1005.0], pressure=fluid_pressure, + particle_spacing) + options = (; density_calculator=ContinuityDensity(), reference_particle_spacing=1.0, + fluid_options...) + fluid = if fluid_scheme == :wcsph + WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + state_equation, options...) + else + options = (; average_pressure_reduction=false, options...) + EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + sound_speed=10.0, options...) + end + n = size(coordinates, 2) + structure_velocity = repeat(reshape([0.25, -0.4, 0.2][1:dimensions], dimensions, 1), 1, + n) + structure_ic = InitialCondition(; coordinates, velocity=structure_velocity, + mass=2100.0 .+ 300.0 .* (0:(n - 1)), + density=fill(2000.0, n), particle_spacing) + hydrodynamic_mass = 700.0 .+ 50.0 .* (0:(n - 1)) + boundary_model = monaghan_kajtar ? + BoundaryModelMonaghanKajtar(10.0, 1.0, particle_spacing, + hydrodynamic_mass) : + BoundaryModelDummyParticles(fill(950.0, n), hydrodynamic_mass, + boundary_density, smoothing_kernel, + boundary_smoothing_length; state_equation, + viscosity=boundary_viscosity, + reference_particle_spacing=1.0) + structure = structure_kind == :rigid ? + RigidBodySystem(structure_ic; boundary_model, adhesion_coefficient=0.25) : + TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, + young_modulus=1.0e5, poisson_ratio=0.3, + boundary_model) + semi = Semidiscretization(fluid, structure; parallelization_backend) + ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) + fluid, structure = semi.systems + v_ode, u_ode = ode.u0.x + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + TrixiParticles.current_density(v_fluid, fluid) .= 1005.0 + TrixiParticles.current_pressure(v_fluid, fluid) .= fluid_pressure + if !monaghan_kajtar + structure.boundary_model.pressure .= 230.0 + if !isnothing(boundary_viscosity) + structure.boundary_model.cache.wall_velocity .= 2 .* structure_velocity .- + velocity + end + end + # Nontrivial cache values also exercise non-odd gradients and tensor pressure terms. + for (field, value) in ((:delta_v, [0.4, -0.3, 0.2][1:dimensions]), + (:dw_gamma, [0.1, -0.2, 0.15][1:dimensions]), + (:kernel_correction_coefficient, 1.3), (:pressure_average, 120.0)) + haskey(fluid.cache, field) && (getproperty(fluid.cache, field) .= value) + end + if haskey(fluid.cache, :correction_matrix) + fluid.cache.correction_matrix[:, :, 1] .= Matrix{Float64}(I, dimensions, dimensions) + fluid.cache.correction_matrix[1, 2, 1] = 0.3 + end + if structure isa RigidBodySystem + TrixiParticles.update_final!(structure, v_structure, u_structure, + v_ode, u_ode, semi, 0.0) + end + return (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, u_structure) +end + +function test_structure_fluid_pair_balance(state) + (; fluid, structure, semi, v_fluid, u_fluid, v_structure, u_structure) = state + dv_fluid, dv_structure = zero(v_fluid), zero(v_structure) + TrixiParticles.reset_interaction_caches!(structure) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + TrixiParticles.interact!(dv_structure, v_structure, u_structure, v_fluid, u_fluid, + structure, fluid, semi) + force = -fluid.mass[1] * dv_fluid[1:ndims(fluid), 1] + forces = structure isa RigidBodySystem ? copy(structure.force_per_particle) : + dv_structure[1:ndims(structure), :] .* reshape(structure.mass, 1, :) + @test isapprox(vec(sum(forces; dims=2)), force; rtol=1e-12, atol=1e-12) + @test all(isfinite, dv_fluid) && all(isfinite, dv_structure) + return (; dv_fluid, dv_structure, force, forces) +end + +@testset "Analytical pressure and continuity" begin + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + for density in (SummationDensity(), ContinuityDensity()), + correction in (nothing, KernelCorrection()), + boundary in + (AdamiPressureExtrapolation(), PressureMirroring(), ContinuityDensity()) + + kind == :tlsph && boundary isa ContinuityDensity && continue + options = (; density_calculator=density, pressure_acceleration=nothing, + correction) + scheme == :edac && (options = (; options..., average_pressure_reduction=true)) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + fluid_options=options, + boundary_density=boundary) + grad_s = [-15 / (56pi), 0.0] # Cubic-spline derivative at r/h = 1.5. + grad_f = isnothing(correction) ? -grad_s : + (-grad_s - 5 / (112pi) * [0.1, -0.2]) / 1.3 + p_avg = scheme == :edac ? 120.0 : 0.0 + p_f = 500.0 - p_avg + p_s = (boundary isa PressureMirroring ? 500.0 : 230.0) - p_avg + expected_force = 1100.0 * 700.0 * + (density isa SummationDensity ? + p_f / 1005.0^2 * grad_f - p_s / 950.0^2 * grad_s : + (p_f * grad_f - p_s * grad_s) / (1005.0 * 950.0)) + for direction in (-1, 0, 1) + state.v_fluid[1:2, 1] .= state.v_structure[1:2, 1] + direction * [0.75, 0.9] + result = test_structure_fluid_pair_balance(state) + @test result.forces[:, 1] ≈ expected_force + if density isa ContinuityDensity + @test result.dv_fluid[end, 1] ≈ + 1005.0 / 950.0 * 700.0 * direction * dot([0.75, 0.9], grad_f) + end + if boundary isa ContinuityDensity + rho_factor = density isa ContinuityDensity ? 950.0 / 1005.0 : 1.0 + @test result.dv_structure[end, 1] ≈ + rho_factor * 1100.0 * direction * dot([-0.75, -0.9], grad_s) + end + end + if scheme == :edac && boundary isa PressureMirroring + (; fluid, ode, semi) = state + TrixiParticles.update_average_pressure!(fluid, + fluid.average_pressure_reduction, + ode.u0.x[1], ode.u0.x[2], semi) + @test fluid.cache.pressure_average[1] == 500.0 + end + end + end + # Density uses the boundary kernel even when the fluid skips the pressure pair. + for (h, distance) in ((1.0, 2.0e-8), (2.0, 2.5)) + state = structure_fluid_pair_state(; structure_kind=:rigid, distance, + boundary_density=ContinuityDensity(), + boundary_smoothing_length=h) + result = test_structure_fluid_pair_balance(state) + q = distance / h + derivative = (q < 1 ? -3q + 2.25q^2 : -0.75 * (2 - q)^2) * 10 / (7pi * h^3) + @test iszero(result.force) + @test result.dv_structure[end, 1] ≈ 950.0 / 1005.0 * 1100.0 * (-0.75) * derivative + end +end + +@testset "Additional structure-fluid variants" begin + variants = NamedTuple[(; boundary_viscosity=viscosity, + fluid_options=(; viscosity=ViscosityAdami(nu=0.4))) + for viscosity in (nothing, ViscosityAdamiSGS(nu=0.1), + ViscosityMorrisSGS(nu=0.1), + ViscosityCarreauYasuda(nu0=0.1, nu_inf=0.01, + lambda=1.0, a=2.0, n=0.5))] + append!(variants, + [(; fluid_pressure=-500.0, fluid_options=(; pressure_acceleration)) + for pressure_acceleration in + (TrixiParticles.pressure_acceleration_summation_density, + TrixiParticles.inter_particle_averaged_pressure, + tensile_instability_control)]) + append!(variants, + [(; boundary_density, + fluid_options=(; density_calculator=SummationDensity())) + for boundary_density in (BernoulliPressureExtrapolation(), + PressureMirroring(), PressureZeroing(), + ContinuityDensity())]) + append!(variants, + [(; boundary_density=SummationDensity(), + fluid_options=(; correction, shifting_technique, + density_calculator=SummationDensity(), + pressure_acceleration=TrixiParticles.pressure_acceleration_summation_density)) + for correction in (ShepardKernelCorrection(), GradientCorrection(), + BlendedGradientCorrection(0.5)), + shifting_technique in (ConsistentShiftingSun2019(), + TransportVelocityAdami(background_pressure=1000.0))]) + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + @testset "$variant" for variant in variants + if kind == :tlsph && + get(variant, :boundary_density, nothing) isa ContinuityDensity + @test_throws ArgumentError structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=kind, + variant...) + continue + end + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + variant...) + result = test_structure_fluid_pair_balance(state) + if get(variant, :boundary_density, nothing) isa ContinuityDensity + @test result.dv_structure[end, 1] ≈ + 1100.0 * 0.75 * 0.75 * 0.5^2 * 10 / (7pi) + end + end + end + @testset "$scheme" for scheme in (:wcsph, :edac) + test_structure_fluid_pair_balance(structure_fluid_pair_state(; fluid_scheme=scheme, + monaghan_kajtar=true)) + @testset "$surface_tension" for surface_tension in + (CohesionForceAkinci(), SurfaceTensionAkinci(), + SurfaceTensionMorris(), + SurfaceTensionMomentumMorris()) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=:rigid, + fluid_options=(; surface_tension)) + test_structure_fluid_pair_balance(state) + end + end +end + +@testset "Shifting momentum and distance regressions" begin + shifting_variants = Any[nothing, ParticleShiftingTechniqueSun2017(), + TransportVelocityAdami(background_pressure=1000.0), + TransportVelocityAdami(background_pressure=1000.0, + modify_continuity_equation=true)] + for update_everystage in (false, true), + (modify_continuity_equation, second_continuity_equation_term) in + ((false, nothing), (true, nothing), (true, ContinuityEquationTermSun2019())), + momentum_equation_term in (nothing, MomentumEquationTermSun2019()) + + push!(shifting_variants, + ParticleShiftingTechnique(; update_everystage, + modify_continuity_equation, + second_continuity_equation_term, + momentum_equation_term)) + end + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + @testset "$shifting" for shifting in shifting_variants + options = (; shifting_technique=shifting) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + fluid_options=options, fluid_pressure=0.0) + state.structure.boundary_model.pressure .= 0.0 + result = test_structure_fluid_pair_balance(state) + # Analytical Sun2019/Adami momentum terms for delta_v_structure = 0. + factor = 0.0 + if shifting isa ParticleShiftingTechnique && + !isnothing(shifting.momentum_equation_term) + factor = 2 * 700.0 / 950.0 + elseif shifting isa TransportVelocityAdami + factor = scheme == :wcsph ? -700.0 / 950.0 : + -((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 * + 1005.0 * 950.0 / (1005.0 + 950.0) + end + grad = [0.75 * 0.5^2 * 10 / (7pi), 0.0] + expected = factor * state.v_fluid[1:2, 1] * + dot(TrixiParticles.delta_v(state.fluid, 1), grad) + @test result.dv_fluid[1:2, 1] ≈ expected + end + @testset "$distance" for distance in (0.0, 2.0e-8, 6.0e-8, 2.0, 2.1) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + distance) + result = test_structure_fluid_pair_balance(state) + skipped = distance == 0 || distance >= 2 || + (scheme == :wcsph && distance == 2.0e-8) + @test iszero(result.force) == skipped + end + end +end + +@testset "3D structure-fluid forces and rigid torque" begin + @testset "$scheme, $kind, $backend" for scheme in (:wcsph, :edac), + kind in (:tlsph, :rigid), + backend in + (SerialBackend(), PolyesterBackend()) + + options = (; viscosity=ViscosityAdami(nu=0.1), + shifting_technique=ConsistentShiftingSun2019()) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + dimensions=3, parallelization_backend=backend, + coordinates=[1.2 1.4 1.6; -0.4 0.5 0.1; + 0.2 -0.3 0.6], + fluid_options=options) + result = test_structure_fluid_pair_balance(state) + if kind == :rigid + (; structure, semi) = state + expected_torque = sum(cross(state.u_structure[:, i] - + structure.center_of_mass[], + result.forces[:, i]) + for i in eachparticle(structure)) + TrixiParticles.apply_resultant_force_and_torque!(result.dv_structure, structure, + semi) + @test structure.resultant_force[] ≈ result.force + @test structure.resultant_torque[] ≈ expected_torque + end + end +end From ca579b1e9f0a34dc7df940d8b90218016fbf02ce Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 11:50:41 +0200 Subject: [PATCH 04/46] review --- NEWS.md | 9 +- docs/src/systems/boundary.md | 5 + docs/src/systems/rigid_body.md | 18 + docs/src/systems/total_lagrangian_sph.md | 9 + src/general/abstract_system.jl | 6 + src/general/corrections.jl | 65 +- src/general/neighborhood_search.jl | 14 +- .../boundary/wall_boundary/dummy_particles.jl | 35 + .../boundary/wall_boundary/monaghan_kajtar.jl | 20 +- .../fluid/entropically_damped_sph/rhs.jl | 48 +- .../fluid/entropically_damped_sph/system.jl | 4 - .../fluid/implicit_incompressible_sph/rhs.jl | 32 +- src/schemes/fluid/interaction.jl | 83 ++ src/schemes/fluid/pressure_acceleration.jl | 38 +- src/schemes/fluid/shifting_techniques.jl | 24 +- .../fluid/weakly_compressible_sph/rhs.jl | 76 +- src/schemes/schemes.jl | 1 + src/schemes/structure/structure.jl | 134 ++-- test/Project.toml | 2 + test/schemes/structure/fluid_interaction.jl | 65 +- .../structure/fluid_interaction_variants.jl | 739 +++++++++++------- 21 files changed, 864 insertions(+), 563 deletions(-) create mode 100644 src/schemes/fluid/interaction.jl diff --git a/NEWS.md b/NEWS.md index 5b79b8cfe8..44de0ad68e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,11 +15,10 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Corrected hydrodynamic reaction forces on TLSPH and rigid-body systems, including - corrected kernel gradients, shifting momentum terms, near-zero-distance handling, - and the approaching-particle condition for artificial viscosity (#1338). -- Fixed EDAC interaction with gradient-based kernel corrections (#1338). -- Fixed pressure mirroring for fluid-structure interaction and boundary-kernel - evaluation in the structure continuity equation (#1338). + asymmetric kernel gradients, unequal fluid/boundary supports, and artificial + viscosity. Structural loads now exclude shifting transport corrections. Fixed + pressure mirroring for structures and EDAC walls, hydrodynamic boundary-kernel + evaluation, and double-counted Monaghan-Kajtar repulsion with TVF (#1338). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index bfbe22080f..fdec6ab198 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -86,6 +86,11 @@ We provide six options to compute the boundary density and pressure, determined This option is not recommended due to stability issues. See [`PressureMirroring`](@ref) for more details. +Pressure mirroring also applies to TLSPH and rigid-body boundary models. In EDAC, +the mirrored pressure is used in the momentum equation, the pressure evolution +equation, and the average-pressure reduction. Mirroring makes the pressure +diffusion contribution from a fluid-boundary pair zero. + #### 1. [`AdamiPressureExtrapolation`](@ref) The pressure of the boundary particles is obtained by extrapolating the pressure of the fluid diff --git a/docs/src/systems/rigid_body.md b/docs/src/systems/rigid_body.md index 27928499ce..3bd4aa68f7 100644 --- a/docs/src/systems/rigid_body.md +++ b/docs/src/systems/rigid_body.md @@ -4,6 +4,24 @@ Rigid bodies in TrixiParticles.jl are represented by particles whose motion is e with rigid-body translation and rotation. This allows fluid-structure interaction while keeping the structure kinematics rigid. +## [Fluid loads](@id fluid_structure_loads) + +Fluid loads are assembled from pressure, viscosity, and adhesion using the same +pair operators as the fluid momentum equation. For each fluid particle `f` and +structure particle `s`, the physical fluid acceleration contributes the reaction +force `F_s = -m_f a_f`. Rigid-body resultants and torque are computed from these +particle forces; TLSPH uses the material mass to convert them to acceleration. + +Particle shifting and transport-velocity momentum corrections are applied only to +the fluid RHS. They are not interfacial traction and therefore +are excluded from the structural load. With shifting enabled, action-reaction +balance applies to the physical pair forces rather than the entire fluid RHS. + +The structure-to-fluid search covers both the fluid and boundary-model kernel +supports. Momentum uses the fluid support, while boundary density evolution uses +the boundary model's own kernel, support, and correction. In TLSPH this +hydrodynamic kernel is separate from the elastic self-interaction kernel. + ## API ```@autodocs diff --git a/docs/src/systems/total_lagrangian_sph.md b/docs/src/systems/total_lagrangian_sph.md index 3b391abb37..d435acb588 100644 --- a/docs/src/systems/total_lagrangian_sph.md +++ b/docs/src/systems/total_lagrangian_sph.md @@ -131,6 +131,15 @@ structure, and we recommend using it in combination with penalty force to both prevent hourglass modes and stabilize the fluid close to the fluid-structure interface. +## Fluid loads + +Fluid pressure, viscosity, and adhesion contribute equal-and-opposite physical +pair forces, converted to TLSPH acceleration using the structure's material mass. +The dummy-particle boundary model supplies the hydrodynamic kernel independently +of the elastic kernel. Shifting transport corrections remain in the fluid RHS +and are excluded from structural loads; see [Fluid loads](@ref fluid_structure_loads) in +[Rigid Bodies](@ref rigid_body) for the coupling convention. + ## [Velocity Averaging](@id velocity_averaging) In FSI cases with very stiff structures, the two techniques above might not be diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index f52953d7e8..0cc6ea4f2a 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -162,6 +162,12 @@ end system_correction(system), system, particle) end +# Most systems have a single kernel. Structures can have a separate hydrodynamic +# boundary kernel, which must not be confused with their elastic self-interaction. +@inline function hydrodynamic_kernel_grad(system, pos_diff, distance, particle) + return smoothing_kernel_grad(system, pos_diff, distance, particle) +end + # System updates do nothing by default, but can be dispatched if needed function update_positions!(system, v, u, v_ode, u_ode, semi, t) return system diff --git a/src/general/corrections.jl b/src/general/corrections.jl index d97eeaf341..6ae2fa1d55 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -136,7 +136,7 @@ function compute_correction_values!(system::AbstractBoundarySystem, end function compute_shepard_coeff!(system, system_coords, v_ode, u_ode, semi, - kernel_correction_coefficient) + kernel_correction_coefficient; kernel_system=system) set_zero!(kernel_correction_coefficient) # Use enabled neighbor systems for the correction value. @@ -159,7 +159,7 @@ function compute_shepard_coeff!(system, system_coords, v_ode, u_ode, semi, volume = m_b / rho_b kernel_correction_coefficient[particle] += volume * - smoothing_kernel(system, + smoothing_kernel(kernel_system, distance, particle) end @@ -201,7 +201,8 @@ function compute_correction_values!(system, ::Union{KernelCorrection, MixedKernelGradientCorrection}, system_coords, v_ode, - u_ode, semi, kernel_correction_coefficient, dw_gamma) + u_ode, semi, kernel_correction_coefficient, dw_gamma; + kernel_system=system) set_zero!(kernel_correction_coefficient) set_zero!(dw_gamma) @@ -223,7 +224,7 @@ function compute_correction_values!(system, # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(system) + h = initial_smoothing_length(kernel_system) almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff @@ -234,18 +235,18 @@ function compute_correction_values!(system, volume = m_b / rho_b # Use uncorrected kernel to compute correction coefficients - W = kernel(system_smoothing_kernel(system), distance, - smoothing_length(system, particle)) + W = kernel(system_smoothing_kernel(kernel_system), distance, + smoothing_length(kernel_system, particle)) kernel_correction_coefficient[particle] += volume * W # Only consider particles with a distance > 0. if distance > almostzero - # Now that we know that `distance` is not zero, we can safely call the - # unsafe version of the kernel gradient to avoid redundant zero checks. - grad_W = kernel_grad_unsafe(system_smoothing_kernel(system), pos_diff, - distance, - smoothing_length(system, particle)) + # A structure reaction search can extend beyond the boundary + # kernel, so enforce the kernel's own support here. + grad_W = kernel_grad(system_smoothing_kernel(kernel_system), pos_diff, + distance, + smoothing_length(kernel_system, particle)) tmp = volume * grad_W for i in axes(dw_gamma, 1) dw_gamma[i, particle] += tmp[i] @@ -354,9 +355,23 @@ function compute_gradient_correction_matrix!(corr_matrix, system, coordinates, d return corr_matrix end +@inline function correction_kernel_grad(correction, smoothing_kernel, pos_diff, distance, + smoothing_length_, system, particle) + return smoothing_kernel_grad_unsafe(system, pos_diff, distance, particle) +end + +@inline function correction_kernel_grad(::MixedKernelGradientCorrection, smoothing_kernel, + pos_diff, distance, smoothing_length_, system, + particle) + return corrected_kernel_grad_unsafe(smoothing_kernel, pos_diff, distance, + smoothing_length_, KernelCorrection(), system, + particle) +end + function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, coordinates, v_ode, u_ode, semi, - correction, smoothing_kernel) + correction, smoothing_kernel; + kernel_system=system) set_zero!(corr_matrix) # Loop over all pairs of particles and neighbors within the kernel cutoff @@ -374,33 +389,17 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, foreach_point_neighbor(system, neighbor_system, coordinates, neighbor_coords, semi) do particle, neighbor, pos_diff, distance - function kernel_grad_local(correction, smoothing_kernel, pos_diff, distance, - smoothing_length_, system, particle) - return smoothing_kernel_grad_unsafe(system, pos_diff, distance, - particle) - end - - # Compute gradient of corrected kernel - function kernel_grad_local(correction::MixedKernelGradientCorrection, - smoothing_kernel, pos_diff, distance, - smoothing_length_, system, particle) - return corrected_kernel_grad_unsafe(smoothing_kernel, pos_diff, - distance, - smoothing_length_, - KernelCorrection(), system, - particle) - end - # Skip neighbors with the same position if the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(correction) && distance < almostzero && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. - smoothing_length_ = smoothing_length(system, particle) - grad_kernel = kernel_grad_local(correction, smoothing_kernel, pos_diff, - distance, smoothing_length_, system, - particle) + smoothing_length_ = smoothing_length(kernel_system, particle) + grad_kernel = correction_kernel_grad(correction, smoothing_kernel, pos_diff, + distance, smoothing_length_, + kernel_system, + particle) volume = hydrodynamic_mass(neighbor_system, neighbor) / current_density(v_neighbor_system, neighbor_system, neighbor) diff --git a/src/general/neighborhood_search.jl b/src/general/neighborhood_search.jl index d315e21d0c..9862c5f917 100644 --- a/src/general/neighborhood_search.jl +++ b/src/general/neighborhood_search.jl @@ -149,13 +149,21 @@ end end @inline function compact_support(system, model::BoundaryModelDummyParticles, neighbor) - # TODO: Monaghan-Kajtar BC are using the fluid's compact support for structure-fluid - # interaction. Dummy particle BC use the model's compact support, which is also used - # for density summations. + # Auxiliary boundary passes use the model's compact support. The structure-fluid + # specialization below additionally covers all reaction pairs. (; smoothing_kernel, smoothing_length) = model return compact_support(smoothing_kernel, smoothing_length) end +@inline function compact_support(system::Union{TotalLagrangianSPHSystem, RigidBodySystem}, + model::BoundaryModelDummyParticles, + neighbor::AbstractFluidSystem) + # The reaction must visit every pair seen by the fluid, while boundary density + # and pressure interpolation still need the boundary model's own support. + boundary_support = compact_support(model.smoothing_kernel, model.smoothing_length) + return max(boundary_support, compact_support(neighbor, system)) +end + @inline function compact_support(system::WallBoundarySystem, model::BoundaryModelDummyParticles, neighbor::RigidBodySystem{Nothing}) diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index fcde467f2e..17c2e3cd76 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -113,6 +113,41 @@ end return ndims(boundary_model.smoothing_kernel) end +# A structure's hydrodynamic kernel uses the boundary model as its correction +# context, independently of the structure's elastic kernel and correction matrix. +@inline system_correction(model::BoundaryModelDummyParticles) = model.correction +@inline skip_zero_distance(model::BoundaryModelDummyParticles) = skip_zero_distance(model.correction) + +@propagate_inbounds function kernel_correction_coefficient(model::BoundaryModelDummyParticles, + particle) + return model.cache.kernel_correction_coefficient[particle] +end + +@propagate_inbounds function dw_gamma(model::BoundaryModelDummyParticles, particle) + return extract_svector(model.cache.dw_gamma, Val(ndims(model)), particle) +end + +@propagate_inbounds function correction_matrix(model::BoundaryModelDummyParticles, particle) + return extract_smatrix(model.cache.correction_matrix, Val(ndims(model)), particle) +end + +@inline function correction_kernel_grad(correction, smoothing_kernel, pos_diff, distance, + smoothing_length_, + model::BoundaryModelDummyParticles, + particle) + # Assemble from the raw boundary gradient, never from its uninitialized or + # previous gradient-correction matrix. + return kernel_grad(smoothing_kernel, pos_diff, distance, smoothing_length_) +end + +@inline function correction_kernel_grad(::MixedKernelGradientCorrection, smoothing_kernel, + pos_diff, distance, smoothing_length_, + model::BoundaryModelDummyParticles, particle) + return corrected_kernel_grad_unsafe(smoothing_kernel, pos_diff, distance, + smoothing_length_, KernelCorrection(), model, + particle) +end + @inline function clip_negative_pressure(::BoundaryModelDummyParticles{<:Any, <:Any, CLIP}) where {CLIP} return CLIP end diff --git a/src/schemes/boundary/wall_boundary/monaghan_kajtar.jl b/src/schemes/boundary/wall_boundary/monaghan_kajtar.jl index 2ea6e82cf6..8f37ef9bee 100644 --- a/src/schemes/boundary/wall_boundary/monaghan_kajtar.jl +++ b/src/schemes/boundary/wall_boundary/monaghan_kajtar.jl @@ -71,19 +71,13 @@ end boundary_kernel(distance, smoothing_length(particle_system, particle)) end -# Disambiguation for corrections with asymmetric kernel gradients -@inline function pressure_acceleration(particle_system, - neighbor_system::Union{WallBoundarySystem{<:BoundaryModelMonaghanKajtar}, - TotalLagrangianSPHSystem{<:BoundaryModelMonaghanKajtar}}, - particle, neighbor, m_a, m_b, p_a, p_b, rho_a, rho_b, - pos_diff, distance, grad_kernel, - ::Union{KernelCorrection, - GradientCorrection, - BlendedGradientCorrection, - MixedKernelGradientCorrection}) - return pressure_acceleration(particle_system, neighbor_system, particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, pos_diff, distance, - grad_kernel, nothing) +# Repulsive particles have no hydrodynamic kernel of their own. Transport +# operators use the reversed fluid gradient, not an elastic structure kernel or +# the Monaghan-Kajtar repulsion law. +@inline function neighbor_kernel_gradient(system::Union{WallBoundarySystem{<:BoundaryModelMonaghanKajtar}, + TotalLagrangianSPHSystem{<:BoundaryModelMonaghanKajtar}}, + pos_diff, distance, particle, W_a) + return -W_a end @fastpow @inline function boundary_kernel(r, h) diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index 4f1ad54991..ee9f24bb3c 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -8,17 +8,14 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - surface_tension_a = surface_tension_model(particle_system) - surface_tension_b = surface_tension_model(neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient # and the density diffusion divide by zero. # To account for rounding errors, we check if `distance` is almost zero. # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + compact_support_ = compact_support(particle_system, neighbor_system) + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, @@ -29,7 +26,7 @@ function interact!(dv, v_particle_system, u_particle_system, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_fluid_pair(particle_system, distance, compact_support_, almostzero) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. @@ -48,29 +45,17 @@ function interact!(dv, v_particle_system, u_particle_system, p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) - # This technique by Basa et al. 2017 (10.1002/fld.1927) aims to reduce numerical - # errors due to large pressures by subtracting the average pressure of neighboring - # particles. - # It results in significant improvement for EDAC, especially with TVF, - # but not for WCSPH, according to Ramachandran & Puri (2019), Section 3.2. - # Note that the return value is zero when not using average pressure reduction. - p_avg = @inbounds average_pressure(particle_system, particle) - m_a = @inbounds hydrodynamic_mass(particle_system, particle) m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, - m_a, m_b, p_a - p_avg, p_b - p_avg, rho_a, - rho_b, pos_diff, distance, grad_kernel, - correction) - - dv_particle = @inbounds add_dv_viscosity(dv_pressure, particle_system, - neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, - sound_speed, m_a, m_b, rho_a, rho_b, - v_a, v_b, grad_kernel) + dv_particle = @inbounds fluid_pair_acceleration(particle_system, neighbor_system, + v_particle_system, + v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, + correction) # Extra terms in the momentum equation when using a shifting technique dv_particle = @inbounds add_dv_shifting(dv_particle, @@ -81,17 +66,6 @@ function interact!(dv, v_particle_system, u_particle_system, v_a, v_b, pos_diff, distance, grad_kernel, correction) - dv_particle = @inbounds add_dv_surface_tension(dv_particle, - surface_tension_a, surface_tension_b, - particle_system, neighbor_system, - particle, neighbor, - pos_diff, distance, - rho_a, rho_b, grad_kernel, 1) - - dv_particle = @inbounds add_dv_adhesion(dv_particle, surface_tension_a, - particle_system, neighbor_system, - particle, neighbor, pos_diff, distance) - for i in 1:ndims(particle_system) @inbounds dv[i, particle] += dv_particle[i] end diff --git a/src/schemes/fluid/entropically_damped_sph/system.jl b/src/schemes/fluid/entropically_damped_sph/system.jl index 45b5e06d27..8ae17c4ea0 100644 --- a/src/schemes/fluid/entropically_damped_sph/system.jl +++ b/src/schemes/fluid/entropically_damped_sph/system.jl @@ -263,10 +263,6 @@ end @inline shifting_technique(system::EntropicallyDampedSPHSystem) = system.shifting_technique -@inline function correction_matrix(system::EntropicallyDampedSPHSystem, particle) - return extract_smatrix(system.cache.correction_matrix, system, particle) -end - @propagate_inbounds function average_pressure(system::EntropicallyDampedSPHSystem, particle) average_pressure(system, system.average_pressure_reduction, particle) end diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 6e8b5d18fa..24ac412529 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -16,8 +16,8 @@ function interact!(dv, v_particle_system, u_particle_system, # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + compact_support_ = compact_support(particle_system, neighbor_system) + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -28,7 +28,7 @@ function interact!(dv, v_particle_system, u_particle_system, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_fluid_pair(particle_system, distance, compact_support_, almostzero) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. @@ -50,27 +50,21 @@ function interact!(dv, v_particle_system, u_particle_system, p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) # The following call is equivalent to # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # Only when the neighbor system is a `WallBoundarySystem` - # or a `TotalLagrangianSPHSystem` with the boundary model `PressureMirroring`, - # this will return `p_b = p_a`, which is the pressure of the fluid particle. + # For boundaries and structures using `PressureMirroring`, this returns + # `p_b = p_a`, which is the pressure of the fluid particle. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, pos_diff, - distance, grad_kernel, nothing) - - # Propagate `@inbounds` to the viscosity function, which accesses particle data - dv_viscosity_ = @inbounds add_dv_viscosity(zero(pos_diff), particle_system, - neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, - sound_speed, m_a, m_b, rho_a, rho_b, - v_a, v_b, grad_kernel) + dv_particle = @inbounds fluid_pair_acceleration(particle_system, neighbor_system, + v_particle_system, + v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, nothing) for i in 1:ndims(particle_system) - @inbounds dv[i, particle] += dv_pressure[i] + dv_viscosity_[i] + @inbounds dv[i, particle] += dv_particle[i] end end return dv diff --git a/src/schemes/fluid/interaction.jl b/src/schemes/fluid/interaction.jl new file mode 100644 index 0000000000..d8710d2f13 --- /dev/null +++ b/src/schemes/fluid/interaction.jl @@ -0,0 +1,83 @@ +# Shared fluid-side pair operators. Structure reactions use the same physical +# acceleration, with fluid-first arguments, before converting acceleration to force. +@propagate_inbounds function neighbor_pressure(v_neighbor_system, neighbor_system, + neighbor, p_a) + return current_pressure(v_neighbor_system, neighbor_system, neighbor) +end + +@inline function neighbor_pressure(v_neighbor_system, + neighbor_system::Union{WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + RigidBodySystem{<:BoundaryModelDummyParticles{PressureMirroring}}}, + neighbor, p_a) + return p_a +end + +# EDAC supplies its own average-pressure reduction; other schemes subtract zero. +@inline average_pressure(system, particle) = zero(eltype(system)) + +@inline function interaction_force_correction(system, rho_a, rho_b) + return 1, 1, 1 +end + +@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, + rho_a, rho_b) + return free_surface_correction(system_correction(system), system, rho_a, rho_b) +end + +@inline function interaction_zero_distance(system, neighbor_system) + return sqrt(eps(initial_smoothing_length(system)^2)) +end + +@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, + neighbor_system) + return sqrt(eps(compact_support(system, neighbor_system)^2)) +end + +@inline function skip_fluid_pair(system, distance, support, almostzero) + return distance > support || (skip_zero_distance(system) && distance < almostzero) +end + +@inline function sum_interaction_contributions(a, b) + dv_a, drho_a = a + dv_b, drho_b = b + return dv_a + dv_b, drho_a + drho_b +end + +@propagate_inbounds function fluid_pair_acceleration(particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, correction) + p_avg = average_pressure(particle_system, particle) + viscosity_correction, pressure_correction, + surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) + + dv_pressure = pressure_acceleration(particle_system, neighbor_system, + particle, neighbor, m_a, m_b, + p_a - p_avg, p_b - p_avg, rho_a, rho_b, + pos_diff, distance, grad_kernel, correction) + dv_particle = dv_pressure * pressure_correction + + dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, pos_diff, distance, sound_speed, + m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, + viscosity_correction) + + surface_tension_a = surface_tension_model(particle_system) + surface_tension_b = surface_tension_model(neighbor_system) + dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, + particle_system, neighbor_system, particle, + neighbor, + pos_diff, distance, rho_a, rho_b, grad_kernel, + surface_tension_correction) + dv_particle = add_dv_adhesion(dv_particle, surface_tension_a, + particle_system, neighbor_system, particle, neighbor, + pos_diff, distance) + + # Shifting is a transport correction, not interfacial traction. Apply its + # momentum terms separately in the fluid RHS, not to the structural load. + return dv_particle +end diff --git a/src/schemes/fluid/pressure_acceleration.jl b/src/schemes/fluid/pressure_acceleration.jl index b6114c0bc1..cc9efb76e8 100644 --- a/src/schemes/fluid/pressure_acceleration.jl +++ b/src/schemes/fluid/pressure_acceleration.jl @@ -143,10 +143,24 @@ end @inline pressure_acceleration_formulation(system) = system.pressure_acceleration_formulation -# Formulation using symmetric gradient formulation for corrections not depending on local neighborhood. +# Boundary laws can specialize this wrapper without changing the inter-particle +# operator used by transport-velocity corrections. @inline function pressure_acceleration(particle_system, neighbor_system, particle, neighbor, m_a, m_b, p_a, p_b, rho_a, rho_b, pos_diff, distance, W_a, correction) + return pressure_acceleration_interparticle(particle_system, neighbor_system, + particle, neighbor, m_a, m_b, p_a, p_b, + rho_a, rho_b, pos_diff, distance, W_a, + correction) +end + +# The inter-particle operator is also used for transport-velocity terms. It must +# bypass boundary repulsion laws, which are physical forces rather than tensor +# divergence or background-pressure operators. +@inline function pressure_acceleration_interparticle(particle_system, neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + pos_diff, distance, W_a, correction) # Without correction or with `AkinciFreeSurfaceCorrection`, the kernel gradient is # symmetric, so call the symmetric version of the pressure acceleration formulation. return pressure_acceleration_formulation(particle_system)(m_a, m_b, rho_a, rho_b, @@ -154,17 +168,23 @@ end end # Formulation using asymmetric gradient formulation for corrections depending on local neighborhood. -@inline function pressure_acceleration(particle_system, neighbor_system, particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, pos_diff, - distance, W_a, - correction::Union{KernelCorrection, - GradientCorrection, - BlendedGradientCorrection, - MixedKernelGradientCorrection}) - W_b = smoothing_kernel_grad(neighbor_system, -pos_diff, distance, neighbor) +@inline function pressure_acceleration_interparticle(particle_system, neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + pos_diff, + distance, W_a, + correction::Union{KernelCorrection, + GradientCorrection, + BlendedGradientCorrection, + MixedKernelGradientCorrection}) + W_b = neighbor_kernel_gradient(neighbor_system, -pos_diff, distance, neighbor, W_a) # With correction, the kernel gradient is not necessarily symmetric, so call the # asymmetric version of the pressure acceleration formulation. return pressure_acceleration_formulation(particle_system)(m_a, m_b, rho_a, rho_b, p_a, p_b, W_a, W_b) end + +@inline function neighbor_kernel_gradient(system, pos_diff, distance, particle, W_a) + return hydrodynamic_kernel_grad(system, pos_diff, distance, particle) +end diff --git a/src/schemes/fluid/shifting_techniques.jl b/src/schemes/fluid/shifting_techniques.jl index c746412f89..10a30e6914 100644 --- a/src/schemes/fluid/shifting_techniques.jl +++ b/src/schemes/fluid/shifting_techniques.jl @@ -609,10 +609,12 @@ end # With the most common pressure acceleration formulation, this is # m_b * (A_a + A_b) / (ρ_a * ρ_b) * ∇W_ab. # In order to obtain this, we pass `p_a = A_a` and `p_b = A_b` to the - # `pressure_acceleration` function. - dv_particle += pressure_acceleration(system, neighbor_system, particle, neighbor, - m_a, m_b, A_a, A_b, rho_a, rho_b, - pos_diff, distance, grad_kernel, correction) + # inter-particle pressure operator, bypassing physical boundary repulsion. + dv_particle += pressure_acceleration_interparticle(system, neighbor_system, particle, + neighbor, + m_a, m_b, A_a, A_b, rho_a, rho_b, + pos_diff, distance, grad_kernel, + correction) return dv_particle end @@ -686,7 +688,7 @@ function update_shifting!(system, shifting::TransportVelocityAdami, v, u, v_ode, # m_b * (p_a / ρ_a^2 + p_b / ρ_b^2) * ∇W_ab # is used. They consequently changed the shifting velocity to # δv = -Δt/2 * p_0 * \sum_b[ m_b * (1 / ρ_a^2 + 1 / ρ_b^2) * ∇W_ab ]. - # We therefore use the function `pressure_acceleration` to compute the + # We therefore use the inter-particle pressure operator to compute the # shifting velocity according to the used pressure acceleration formulation. # In most cases, this will be # δv = -Δt/2 * p_0 * \sum_b[ m_b * (1 + 1) / (ρ_a * ρ_b) * ∇W_ab ]. @@ -704,12 +706,14 @@ function update_shifting!(system, shifting::TransportVelocityAdami, v, u, v_ode, # Applying this equation as equality yields the shifting velocity # δv = -p_0 / 8 * h / c * \sum_b[ m_b * (1 + 1) / (ρ_a * ρ_b) * ∇W_ab ]. # The last part is achieved by passing `p_a = 1` and `p_b = 1` to the - # `pressure_acceleration` function. + # inter-particle pressure operator, bypassing physical boundary repulsion. delta_v_ = background_pressure / 8 * h / sound_speed * - pressure_acceleration(system, neighbor_system, particle, neighbor, - m_a, m_b, 1, 1, rho_a, rho_b, pos_diff, - distance, grad_kernel, - system_correction(system)) + pressure_acceleration_interparticle(system, neighbor_system, + particle, neighbor, + m_a, m_b, 1, 1, rho_a, rho_b, + pos_diff, + distance, grad_kernel, + system_correction(system)) # Write into the buffer for i in eachindex(delta_v_) diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index 87bef6b56f..17333da404 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -11,9 +11,6 @@ function interact!(dv, v_particle_system, u_particle_system, sound_speed = system_sound_speed(particle_system) - surface_tension_a = surface_tension_model(particle_system) - surface_tension_b = surface_tension_model(neighbor_system) - system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) @@ -25,7 +22,7 @@ function interact!(dv, v_particle_system, u_particle_system, # the order of `c^2`, so we need to check `distance < sqrt(eps(c^2))`. # Note that `sqrt(eps(c^2)) != eps(c)`. compact_support_ = compact_support(particle_system, neighbor_system) - almostzero = sqrt(eps(compact_support_^2)) + almostzero = interaction_zero_distance(particle_system, neighbor_system) @threaded semi for particle in eachparticle # We are looping over the particles of `particle_system`, so it is guaranteed @@ -38,18 +35,14 @@ function interact!(dv, v_particle_system, u_particle_system, # Accumulate the RHS contributions over all neighbors before writing to `dv`, # to reduce the number of memory writes. - @inline function dv_drho_sum(a, b) - dv_a, drho_a = a - dv_b, drho_b = b - return dv_a + dv_b, drho_a + drho_b - end init = (zero(v_a), zero(rho_a)) # Loop over all neighbors within the kernel cutoff. # Make sure that the returned names `dv_particle_` and `drho_particle_` # are not used inside the closure to avoid allocations. (dv_particle_, - drho_particle_) = @inbounds mapreduce_neighbor(dv_drho_sum, system_coords, + drho_particle_) = @inbounds mapreduce_neighbor(sum_interaction_contributions, + system_coords, neighbor_system_coords, neighborhood_search, backend, particle; @@ -57,7 +50,8 @@ function interact!(dv, v_particle_system, u_particle_system, pos_diff, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return init + skip_fluid_pair(particle_system, distance, compact_support_, almostzero) && + return init # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. @@ -76,29 +70,16 @@ function interact!(dv, v_particle_system, u_particle_system, p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) - # Determine correction factors. - # This can usually be ignored, as these are all 1 when no correction is used. - (viscosity_correction, pressure_correction, - surface_tension_correction) = free_surface_correction(correction, - particle_system, - rho_a, rho_b) - - # For `ContinuityDensity` without correction, this is equivalent to - # dv_pressure = -m_b * (p_a + p_b) / (rho_a * rho_b) * grad_kernel - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, pos_diff, - distance, grad_kernel, correction) - dv_particle = dv_pressure * pressure_correction - - # Propagate `@inbounds` to the viscosity function, which accesses particle data - dv_particle = @inbounds add_dv_viscosity(dv_particle, particle_system, - neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, - sound_speed, m_a, m_b, rho_a, rho_b, - v_a, v_b, grad_kernel, - viscosity_correction) + dv_particle = @inbounds fluid_pair_acceleration(particle_system, + neighbor_system, + v_particle_system, + v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, + rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, + correction) # Extra terms in the momentum equation when using a shifting technique dv_particle = @inbounds add_dv_shifting(dv_particle, @@ -109,20 +90,6 @@ function interact!(dv, v_particle_system, u_particle_system, rho_b, v_a, v_b, pos_diff, distance, grad_kernel, correction) - dv_particle = @inbounds add_dv_surface_tension(dv_particle, - surface_tension_a, - surface_tension_b, - particle_system, - neighbor_system, - particle, neighbor, - pos_diff, distance, - rho_a, rho_b, grad_kernel, - surface_tension_correction) - - dv_particle = @inbounds add_dv_adhesion(dv_particle, surface_tension_a, - particle_system, neighbor_system, - particle, neighbor, pos_diff, distance) - drho_particle = zero(rho_a) # TODO If variable smoothing_length is used, this should use the neighbor smoothing length @@ -147,16 +114,3 @@ function interact!(dv, v_particle_system, u_particle_system, return dv end - -@propagate_inbounds function neighbor_pressure(v_neighbor_system, neighbor_system, - neighbor, p_a) - return current_pressure(v_neighbor_system, neighbor_system, neighbor) -end - -@inline function neighbor_pressure(v_neighbor_system, - neighbor_system::Union{WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, - TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{PressureMirroring}}, - RigidBodySystem{<:BoundaryModelDummyParticles{PressureMirroring}}}, - neighbor, p_a) - return p_a -end diff --git a/src/schemes/schemes.jl b/src/schemes/schemes.jl index 8330312467..4074f505e2 100644 --- a/src/schemes/schemes.jl +++ b/src/schemes/schemes.jl @@ -15,6 +15,7 @@ include("boundary/wall_boundary/monaghan_kajtar.jl") include("fluid/implicit_incompressible_sph/implicit_incompressible_sph.jl") # Include rhs for all schemes +include("fluid/interaction.jl") include("fluid/weakly_compressible_sph/rhs.jl") include("fluid/entropically_damped_sph/rhs.jl") include("fluid/implicit_incompressible_sph/rhs.jl") diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 3cf5d86592..f6ea9c09fc 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -20,23 +20,46 @@ end return dv end -# Match the pressure and viscosity corrections used by the fluid-side RHS. -@inline function structure_fluid_force_correction(system::AbstractFluidSystem, - particle, rho_a, rho_b) - return zero(rho_a), 1, 1 +@inline function hydrodynamic_kernel_grad(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles}, + RigidBodySystem{<:BoundaryModelDummyParticles}}, + pos_diff, distance, particle) + return smoothing_kernel_grad(system.boundary_model, pos_diff, distance, particle) end -@inline function structure_fluid_force_correction(system::WeaklyCompressibleSPHSystem, - particle, rho_a, rho_b) - viscosity_correction, pressure_correction, - _ = free_surface_correction(system_correction(system), system, rho_a, rho_b) +# Populate hydrodynamic correction caches in the boundary-model context. TLSPH's +# elastic correction matrix and smoothing length belong to self-interaction only. +function compute_correction_values!(system::Union{TotalLagrangianSPHSystem, + RigidBodySystem}, + ::ShepardKernelCorrection, u, v_ode, u_ode, semi) + model = system.boundary_model + return compute_shepard_coeff!(system, current_coordinates(u, system), v_ode, u_ode, + semi, model.cache.kernel_correction_coefficient; + kernel_system=model) +end - return zero(rho_a), viscosity_correction, pressure_correction +function compute_correction_values!(system::Union{TotalLagrangianSPHSystem, + RigidBodySystem}, + correction::Union{KernelCorrection, + MixedKernelGradientCorrection}, + u, v_ode, u_ode, semi) + model = system.boundary_model + return compute_correction_values!(system, correction, current_coordinates(u, system), + v_ode, u_ode, semi, + model.cache.kernel_correction_coefficient, + model.cache.dw_gamma; kernel_system=model) end -@propagate_inbounds function structure_fluid_force_correction(system::EntropicallyDampedSPHSystem, - particle, rho_a, rho_b) - return average_pressure(system, particle), 1, 1 +function compute_gradient_correction_matrix!(correction::Union{GradientCorrection, + BlendedGradientCorrection, + MixedKernelGradientCorrection}, + model::BoundaryModelDummyParticles, + system::Union{TotalLagrangianSPHSystem, + RigidBodySystem}, + u, v_ode, u_ode, semi) + return compute_gradient_correction_matrix!(model.cache.correction_matrix, system, + current_coordinates(u, system), + v_ode, u_ode, semi, correction, + model.smoothing_kernel; kernel_system=model) end function interact_structure_fluid!(dv, v_particle_system, u_particle_system, @@ -46,20 +69,15 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, eachparticle=each_integrated_particle(particle_system)) sound_speed = system_sound_speed(neighbor_system) correction = system_correction(neighbor_system) - shifting = shifting_technique(neighbor_system) - surface_tension = surface_tension_model(neighbor_system) system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # Match the fluid-side zero-distance check exactly. WCSPH scales this threshold - # with the compact support, while EDAC and IISPH use the smoothing length. + # Use the same pair cutoffs as the fluid RHS. compact_support_ = compact_support(neighbor_system, particle_system) - h = initial_smoothing_length(neighbor_system) - almostzero = neighbor_system isa WeaklyCompressibleSPHSystem ? - sqrt(eps(compact_support_^2)) : sqrt(eps(h^2)) + almostzero = interaction_zero_distance(neighbor_system, particle_system) @threaded semi for particle in eachparticle # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles @@ -68,18 +86,20 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, rho_a = @inbounds current_density(v_particle_system, particle_system, particle) v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) - # Accumulate force components and density rate in one static vector. - init = zero(SVector{ndims(particle_system) + 1, eltype(particle_system)}) + # Accumulate force and density rate separately, as in the fluid RHS. + init = (zero(v_a), zero(rho_a)) # Keep the returned name out of the closure to avoid allocations. - force_drho_particle_ = @inbounds mapreduce_neighbor(+, system_coords, - neighbor_coords, - neighborhood_search, backend, - particle; - init) do particle, - neighbor, - pos_diff, - distance + (force_particle_, + drho_particle_) = @inbounds mapreduce_neighbor(sum_interaction_contributions, + system_coords, + neighbor_coords, + neighborhood_search, backend, + particle; + init) do particle, + neighbor, + pos_diff, + distance m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) rho_b = @inbounds current_density(v_neighbor_system, neighbor_system, neighbor) v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) @@ -92,10 +112,10 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, distance, m_b, rho_a, rho_b, v_a, v_b) - # Only pressure/momentum contributions use the fluid-side pair cutoffs. - init_pair = vcat(zero(v_a), SVector(drho_particle)) - distance > compact_support_ && return init_pair - skip_zero_distance(neighbor_system) && distance < almostzero && return init_pair + # Apply the fluid-side cutoffs only to physical momentum contributions. + if skip_fluid_pair(neighbor_system, distance, compact_support_, almostzero) + return zero(v_a), drho_particle + end # Corrected gradients need not be odd; evaluate the fluid-side gradient. grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, @@ -106,44 +126,22 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, p_b) - p_avg, viscosity_correction, - pressure_correction = @inbounds structure_fluid_force_correction(neighbor_system, - neighbor, - rho_b, rho_a) - # Fluid-first ordering preserves the actual fluid force, including the # approaching-particle condition of artificial viscosity. - dv_pressure = pressure_acceleration(neighbor_system, particle_system, - neighbor, particle, m_b, m_a, - p_b - p_avg, p_a - p_avg, rho_b, rho_a, - -pos_diff, distance, grad_kernel_fluid, - correction) - dv_fluid = dv_pressure * pressure_correction - - dv_fluid = @inbounds add_dv_viscosity(dv_fluid, neighbor_system, - particle_system, - v_neighbor_system, v_particle_system, - neighbor, particle, -pos_diff, distance, - sound_speed, m_b, m_a, rho_b, rho_a, - v_b, v_a, grad_kernel_fluid, - viscosity_correction) - - dv_fluid = @inbounds add_dv_shifting(dv_fluid, shifting, neighbor_system, - particle_system, v_neighbor_system, - v_particle_system, neighbor, particle, - m_b, m_a, rho_b, rho_a, v_b, v_a, - -pos_diff, distance, grad_kernel_fluid, - correction) - - dv_particle = @inbounds add_dv_adhesion(-dv_fluid, surface_tension, - neighbor_system, particle_system, - neighbor, particle, pos_diff, distance) - - return vcat(m_b * dv_particle, SVector(drho_particle)) + dv_fluid = @inbounds fluid_pair_acceleration(neighbor_system, particle_system, + v_neighbor_system, + v_particle_system, + neighbor, particle, + m_b, m_a, p_b, p_a, rho_b, rho_a, + v_b, v_a, -pos_diff, distance, + sound_speed, grad_kernel_fluid, + correction) + + return -m_b * dv_fluid, drho_particle end - @inbounds write_fluid_force!(dv, particle_system, force_drho_particle_, particle) - @inbounds write_drho_particle!(dv, particle_system, force_drho_particle_[end], + @inbounds write_fluid_force!(dv, particle_system, force_particle_, particle) + @inbounds write_drho_particle!(dv, particle_system, drho_particle_, particle) end @@ -166,7 +164,7 @@ end m_b, rho_a, rho_b, v_a, v_b) # Density evolves with the boundary's own kernel and correction, not with the # neighboring fluid's corrected gradient evaluated in the opposite direction. - grad_kernel = smoothing_kernel_grad(particle_system, pos_diff, distance, particle) + grad_kernel = hydrodynamic_kernel_grad(particle_system, pos_diff, distance, particle) return add_continuity_equation(drho_particle, density_calculator(neighbor_system), diff --git a/test/Project.toml b/test/Project.toml index 28bb94f88b..5d61a162a7 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -7,6 +7,7 @@ GLM = "38e38edf-8417-5370-95a0-9cbb8c7f171a" Glob = "c27321d9-0574-5035-807b-f59d2c89b15c" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" OrdinaryDiffEqLowStorageRK = "b0944070-b475-4768-8dec-fb6eb410534d" OrdinaryDiffEqSymplecticRK = "fa646aed-7ef9-47eb-84c4-9443fc8cbfa8" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" @@ -26,6 +27,7 @@ GLM = "1.9" Glob = "1.3" JSON = "1" LinearAlgebra = "1" +Logging = "1" OrdinaryDiffEqLowStorageRK = "3" OrdinaryDiffEqSymplecticRK = "2" Plots = "1" diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl index d3a7aa7f5c..edd9daf700 100644 --- a/test/schemes/structure/fluid_interaction.jl +++ b/test/schemes/structure/fluid_interaction.jl @@ -1,3 +1,5 @@ +using Logging: NullLogger, with_logger + @testset verbose=true "Structure-fluid force balance" begin particle_spacing = 1.0 smoothing_kernel = SchoenbergCubicSplineKernel{2}() @@ -7,8 +9,6 @@ state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) - shifting_techniques = (nothing, ConsistentShiftingSun2019(), - TransportVelocityAdami(background_pressure=1000.0)) configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), (:wcsph, nothing, ContinuityDensity()), (:wcsph, AkinciFreeSurfaceCorrection(reference_density), @@ -17,20 +17,18 @@ (:wcsph, MixedKernelGradientCorrection(), SummationDensity()), (:edac, nothing, AdamiPressureExtrapolation()), (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) - # Zero pressure isolates viscosity and shifting for approaching and receding particles. - # Nonzero pressure checks that all momentum terms accumulate consistently. + # Zero pressure isolates viscosity for approaching and receding particles. + # Nonzero pressure checks that pressure and viscosity accumulate consistently. fluid_states = ((velocity=(1.0, 0.5), density=reference_density), (velocity=(-1.0, -0.5), density=reference_density), (velocity=(1.0, 0.5), density=1005.0)) - @testset "$fluid_scheme, $viscosity, $correction, $boundary_density, $shifting_technique" for shifting_technique in - shifting_techniques, - viscosity in - viscosities, - (fluid_scheme, - correction, - boundary_density) in - configurations + @testset "$fluid_scheme, $viscosity, $correction, $boundary_density" for viscosity in + viscosities, + (fluid_scheme, + correction, + boundary_density) in + configurations @testset "$structure_kind, $fluid_state" for structure_kind in (:tlsph, :clamped_tlsph, :rigid), @@ -50,13 +48,12 @@ particle_spacing) fluid_system = if fluid_scheme == :wcsph WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - viscosity, correction, shifting_technique, + viscosity, correction, density_calculator=ContinuityDensity(), state_equation) else EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, sound_speed=10.0, viscosity, correction, - shifting_technique, density_calculator=ContinuityDensity(), average_pressure_reduction=fluid_scheme == :edac_pressure_reduction) @@ -79,9 +76,11 @@ clamped_particles, boundary_model) end - semi = Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) - ode = semidiscretize(semi, (0.0, 0.01)) + semi = with_logger(NullLogger()) do + Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end + ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) fluid, structure = ode.p.semi.systems v_ode, u_ode = ode.u0.x dv_ode = zero(v_ode) @@ -90,17 +89,12 @@ u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - # Isolate this pair from fluid self-interaction terms, which can be nonzero - # with shifting and corrected kernel gradients. + # Isolate this pair from corrected fluid self-interaction terms. dv_fluid = zero(v_fluid) TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, fluid, structure, semi) expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] - if !isnothing(shifting_technique) - @test !iszero(TrixiParticles.delta_v(fluid, 1)) - end - if correction isa KernelCorrection || correction isa MixedKernelGradientCorrection # Ensure that this fixture exercises a gradient that is not odd. @@ -116,28 +110,19 @@ if fluid_state.density == reference_density @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, 1)) @test iszero(structure.boundary_model.pressure[1]) - if isnothing(shifting_technique) - if isnothing(viscosity) || - (viscosity isa ArtificialViscosityMonaghan && - fluid_state.velocity[1] < 0) - @test iszero(expected_force) - else - # The viscous reaction on the structure follows the fluid motion. - @test expected_force[1] * fluid_state.velocity[1] > 0 - end - elseif isnothing(viscosity) - # A nonzero reaction with no pressure or viscosity exercises shifting. - @test !iszero(expected_force) + if isnothing(viscosity) || + (viscosity isa ArtificialViscosityMonaghan && + fluid_state.velocity[1] < 0) + @test iszero(expected_force) + else + # The viscous reaction on the structure follows the fluid motion. + @test expected_force[1] * fluid_state.velocity[1] > 0 end elseif fluid_scheme == :edac_pressure_reduction && isnothing(viscosity) # Uniform nonzero pressure produces no force after pressure reduction. @test TrixiParticles.current_pressure(v_fluid, fluid, 1) ≈ structure.boundary_model.pressure[1] - if isnothing(shifting_technique) - @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) - else - @test !iszero(expected_force) - end + @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) else @test !iszero(expected_force) end diff --git a/test/schemes/structure/fluid_interaction_variants.jl b/test/schemes/structure/fluid_interaction_variants.jl index 5faa5f3297..d81d789e06 100644 --- a/test/schemes/structure/fluid_interaction_variants.jl +++ b/test/schemes/structure/fluid_interaction_variants.jl @@ -1,295 +1,512 @@ -# Prescribed pair states isolate interaction formulas from density/pressure updates. -function structure_fluid_pair_state(; fluid_scheme=:wcsph, structure_kind=:tlsph, - fluid_options=(;), distance=1.5, dimensions=2, - boundary_density=AdamiPressureExtrapolation(), - boundary_smoothing_length=1.0, - boundary_viscosity=get(fluid_options, :viscosity, - nothing), - fluid_pressure=500.0, monaghan_kajtar=false, - coordinates=reshape([distance; zeros(dimensions - 1)], - dimensions, 1), - parallelization_backend=SerialBackend()) - smoothing_kernel = SchoenbergCubicSplineKernel{dimensions}() - smoothing_length = particle_spacing = 1.0 - state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1000.0, - exponent=1.0, clip_negative_pressure=false) - velocity = reshape([1.0, 0.5, 0.7][1:dimensions], dimensions, 1) - fluid_ic = InitialCondition(; coordinates=zeros(dimensions, 1), velocity, - mass=[1100.0], density=[1005.0], pressure=fluid_pressure, - particle_spacing) - options = (; density_calculator=ContinuityDensity(), reference_particle_spacing=1.0, - fluid_options...) - fluid = if fluid_scheme == :wcsph - WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - state_equation, options...) - else - options = (; average_pressure_reduction=false, options...) - EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - sound_speed=10.0, options...) - end - n = size(coordinates, 2) - structure_velocity = repeat(reshape([0.25, -0.4, 0.2][1:dimensions], dimensions, 1), 1, - n) - structure_ic = InitialCondition(; coordinates, velocity=structure_velocity, - mass=2100.0 .+ 300.0 .* (0:(n - 1)), - density=fill(2000.0, n), particle_spacing) - hydrodynamic_mass = 700.0 .+ 50.0 .* (0:(n - 1)) - boundary_model = monaghan_kajtar ? - BoundaryModelMonaghanKajtar(10.0, 1.0, particle_spacing, - hydrodynamic_mass) : - BoundaryModelDummyParticles(fill(950.0, n), hydrodynamic_mass, - boundary_density, smoothing_kernel, - boundary_smoothing_length; state_equation, - viscosity=boundary_viscosity, - reference_particle_spacing=1.0) - structure = structure_kind == :rigid ? - RigidBodySystem(structure_ic; boundary_model, adhesion_coefficient=0.25) : - TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, - young_modulus=1.0e5, poisson_ratio=0.3, - boundary_model) - semi = Semidiscretization(fluid, structure; parallelization_backend) - ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) - fluid, structure = semi.systems - v_ode, u_ode = ode.u0.x - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) - v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) - u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - TrixiParticles.current_density(v_fluid, fluid) .= 1005.0 - TrixiParticles.current_pressure(v_fluid, fluid) .= fluid_pressure - if !monaghan_kajtar - structure.boundary_model.pressure .= 230.0 - if !isnothing(boundary_viscosity) - structure.boundary_model.cache.wall_velocity .= 2 .* structure_velocity .- - velocity +using Logging: NullLogger, with_logger + +@testset verbose=true "Structure-fluid interaction variants" begin + # Prescribed pair states isolate interaction formulas from density/pressure updates. + function structure_fluid_pair_state(; fluid_scheme=:wcsph, structure_kind=:tlsph, + fluid_options=(;), distance=1.5, dimensions=2, + boundary_density=AdamiPressureExtrapolation(), + boundary_smoothing_length=1.0, + boundary_correction=nothing, + structure_smoothing_length=1.0, + structure_smoothing_kernel=SchoenbergCubicSplineKernel{dimensions}(), + boundary_viscosity=get(fluid_options, :viscosity, + nothing), + fluid_pressure=500.0, monaghan_kajtar=false, + coordinates=reshape([distance; + zeros(dimensions - 1)], + dimensions, 1), + parallelization_backend=SerialBackend(), + neighborhood_search=GridNeighborhoodSearch{dimensions}(), + neighborhood_search_handler=SharedNHSHandler) + smoothing_kernel = SchoenbergCubicSplineKernel{dimensions}() + smoothing_length = particle_spacing = 1.0 + state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1000.0, + exponent=1.0, clip_negative_pressure=false) + velocity = reshape([1.0, 0.5, 0.7][1:dimensions], dimensions, 1) + fluid_ic = InitialCondition(; coordinates=zeros(dimensions, 1), velocity, + mass=[1100.0], density=[1005.0], + pressure=fluid_pressure, + particle_spacing) + options = (; density_calculator=ContinuityDensity(), reference_particle_spacing=1.0, + fluid_options...) + fluid = if fluid_scheme == :wcsph + WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + state_equation, options...) + elseif fluid_scheme == :edac + options = (; average_pressure_reduction=false, options...) + EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + sound_speed=10.0, options...) + else + ImplicitIncompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + reference_density=1005.0, time_step=0.001, + viscosity=get(fluid_options, :viscosity, + nothing)) end + n = size(coordinates, 2) + structure_velocity = repeat(reshape([0.25, -0.4, 0.2][1:dimensions], dimensions, 1), + 1, + n) + structure_ic = InitialCondition(; coordinates, velocity=structure_velocity, + mass=2100.0 .+ 300.0 .* (0:(n - 1)), + density=fill(2000.0, n), particle_spacing) + hydrodynamic_mass = 700.0 .+ 50.0 .* (0:(n - 1)) + boundary_model = monaghan_kajtar ? + BoundaryModelMonaghanKajtar(10.0, 1.0, particle_spacing, + hydrodynamic_mass) : + BoundaryModelDummyParticles(fill(950.0, n), hydrodynamic_mass, + boundary_density, smoothing_kernel, + boundary_smoothing_length; + state_equation, + viscosity=boundary_viscosity, + correction=boundary_correction, + reference_particle_spacing=1.0) + structure = if structure_kind == :rigid + RigidBodySystem(structure_ic; boundary_model, adhesion_coefficient=0.25) + elseif structure_kind == :wall + WallBoundarySystem(structure_ic, boundary_model) + else + TotalLagrangianSPHSystem(structure_ic; + smoothing_kernel=structure_smoothing_kernel, + smoothing_length=structure_smoothing_length, + young_modulus=1.0e5, poisson_ratio=0.3, + boundary_model) + end + semi = with_logger(NullLogger()) do + Semidiscretization(fluid, structure; + parallelization_backend, neighborhood_search, + neighborhood_search_handler) + end + ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) + fluid, structure = semi.systems + v_ode, u_ode = ode.u0.x + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + TrixiParticles.current_density(v_fluid, fluid) .= 1005.0 + TrixiParticles.current_pressure(v_fluid, fluid) .= fluid_pressure + if !monaghan_kajtar + structure.boundary_model.pressure .= 230.0 + if !isnothing(boundary_viscosity) + structure.boundary_model.cache.wall_velocity .= 2 .* structure_velocity .- + velocity + end + end + # Nontrivial cache values also exercise non-odd gradients and tensor pressure terms. + for (field, value) in ((:delta_v, [0.4, -0.3, 0.2][1:dimensions]), + (:dw_gamma, [0.1, -0.2, 0.15][1:dimensions]), + (:kernel_correction_coefficient, 1.3), (:pressure_average, 120.0)) + haskey(fluid.cache, field) && (getproperty(fluid.cache, field) .= value) + end + if haskey(fluid.cache, :correction_matrix) + fluid.cache.correction_matrix[:, :, + 1] .= Matrix{Float64}(I, dimensions, dimensions) + fluid.cache.correction_matrix[1, 2, 1] = 0.3 + end + if structure isa RigidBodySystem + TrixiParticles.update_final!(structure, v_structure, u_structure, + v_ode, u_ode, semi, 0.0) + end + return (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, u_structure) end - # Nontrivial cache values also exercise non-odd gradients and tensor pressure terms. - for (field, value) in ((:delta_v, [0.4, -0.3, 0.2][1:dimensions]), - (:dw_gamma, [0.1, -0.2, 0.15][1:dimensions]), - (:kernel_correction_coefficient, 1.3), (:pressure_average, 120.0)) - haskey(fluid.cache, field) && (getproperty(fluid.cache, field) .= value) - end - if haskey(fluid.cache, :correction_matrix) - fluid.cache.correction_matrix[:, :, 1] .= Matrix{Float64}(I, dimensions, dimensions) - fluid.cache.correction_matrix[1, 2, 1] = 0.3 - end - if structure isa RigidBodySystem - TrixiParticles.update_final!(structure, v_structure, u_structure, - v_ode, u_ode, semi, 0.0) + + function test_structure_fluid_pair_balance(state) + (; fluid, structure, semi, v_fluid, u_fluid, v_structure, u_structure) = state + dv_fluid, dv_structure = zero(v_fluid), zero(v_structure) + TrixiParticles.reset_interaction_caches!(structure) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + TrixiParticles.interact!(dv_structure, v_structure, u_structure, v_fluid, u_fluid, + structure, fluid, semi) + # Zero shifting velocities isolate physical traction without relying on the + # shared implementation of that operator. Restore the prescribed shifts before + # testing the structural load, which must be independent of transport terms. + dv_physical = dv_fluid + if haskey(fluid.cache, :delta_v) + shifting_velocity = copy(fluid.cache.delta_v) + fluid.cache.delta_v .= 0 + dv_physical = zero(v_fluid) + TrixiParticles.interact!(dv_physical, v_fluid, u_fluid, v_structure, + u_structure, + fluid, structure, semi) + fluid.cache.delta_v .= shifting_velocity + end + force = -fluid.mass[1] * dv_physical[1:ndims(fluid), 1] + forces = structure isa RigidBodySystem ? copy(structure.force_per_particle) : + dv_structure[1:ndims(structure), :] .* reshape(structure.mass, 1, :) + @test isapprox(vec(sum(forces; dims=2)), force; rtol=1e-12, atol=1e-12) + @test all(isfinite, dv_fluid) && all(isfinite, dv_structure) + return (; dv_fluid, dv_structure, force, forces) end - return (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, u_structure) -end -function test_structure_fluid_pair_balance(state) - (; fluid, structure, semi, v_fluid, u_fluid, v_structure, u_structure) = state - dv_fluid, dv_structure = zero(v_fluid), zero(v_structure) - TrixiParticles.reset_interaction_caches!(structure) - TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, - fluid, structure, semi) - TrixiParticles.interact!(dv_structure, v_structure, u_structure, v_fluid, u_fluid, - structure, fluid, semi) - force = -fluid.mass[1] * dv_fluid[1:ndims(fluid), 1] - forces = structure isa RigidBodySystem ? copy(structure.force_per_particle) : - dv_structure[1:ndims(structure), :] .* reshape(structure.mass, 1, :) - @test isapprox(vec(sum(forces; dims=2)), force; rtol=1e-12, atol=1e-12) - @test all(isfinite, dv_fluid) && all(isfinite, dv_structure) - return (; dv_fluid, dv_structure, force, forces) -end + @testset "Analytical pressure and continuity" begin + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + for density in (SummationDensity(), ContinuityDensity()), + correction in (nothing, KernelCorrection()), + boundary in + (AdamiPressureExtrapolation(), PressureMirroring(), ContinuityDensity()) -@testset "Analytical pressure and continuity" begin - @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) - for density in (SummationDensity(), ContinuityDensity()), - correction in (nothing, KernelCorrection()), - boundary in - (AdamiPressureExtrapolation(), PressureMirroring(), ContinuityDensity()) + kind == :tlsph && boundary isa ContinuityDensity && continue + # EDAC correction-cache lifecycle is covered by PR #1218. + scheme == :edac && !isnothing(correction) && continue + options = (; density_calculator=density, pressure_acceleration=nothing, + correction) + scheme == :edac && + (options = (; options..., average_pressure_reduction=true)) + state = structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=kind, + fluid_options=options, + boundary_density=boundary) + grad_s = [-15 / (56pi), 0.0] # Cubic-spline derivative at r/h = 1.5. + grad_f = isnothing(correction) ? -grad_s : + (-grad_s - 5 / (112pi) * [0.1, -0.2]) / 1.3 + p_avg = scheme == :edac ? 120.0 : 0.0 + p_f = 500.0 - p_avg + p_s = (boundary isa PressureMirroring ? 500.0 : 230.0) - p_avg + expected_force = 1100.0 * 700.0 * + (density isa SummationDensity ? + p_f / 1005.0^2 * grad_f - p_s / 950.0^2 * grad_s : + (p_f * grad_f - p_s * grad_s) / (1005.0 * 950.0)) + for direction in (-1, 0, 1) + state.v_fluid[1:2, + 1] .= state.v_structure[1:2, 1] + direction * [0.75, 0.9] + result = test_structure_fluid_pair_balance(state) + @test result.forces[:, 1] ≈ expected_force + if density isa ContinuityDensity + @test result.dv_fluid[end, 1] ≈ + 1005.0 / 950.0 * 700.0 * direction * dot([0.75, 0.9], grad_f) + end + if boundary isa ContinuityDensity + rho_factor = density isa ContinuityDensity ? 950.0 / 1005.0 : 1.0 + @test result.dv_structure[end, 1] ≈ + rho_factor * 1100.0 * direction * dot([-0.75, -0.9], grad_s) + end + end + if scheme == :edac && boundary isa PressureMirroring + (; fluid, ode, semi) = state + TrixiParticles.update_average_pressure!(fluid, + fluid.average_pressure_reduction, + ode.u0.x[1], ode.u0.x[2], semi) + @test fluid.cache.pressure_average[1] == 500.0 + end + end + end + # Density uses the boundary kernel even when the fluid skips the pressure pair. + for (h, distance) in ((1.0, 2.0e-8), (2.0, 2.5)) + state = structure_fluid_pair_state(; structure_kind=:rigid, distance, + boundary_density=ContinuityDensity(), + boundary_smoothing_length=h) + result = test_structure_fluid_pair_balance(state) + q = distance / h + derivative = (q < 1 ? -3q + 2.25q^2 : -0.75 * (2 - q)^2) * 10 / (7pi * h^3) + @test iszero(result.force) + @test result.dv_structure[end, 1] ≈ + 950.0 / 1005.0 * 1100.0 * (-0.75) * derivative + end + end - kind == :tlsph && boundary isa ContinuityDensity && continue - options = (; density_calculator=density, pressure_acceleration=nothing, - correction) - scheme == :edac && (options = (; options..., average_pressure_reduction=true)) - state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - fluid_options=options, - boundary_density=boundary) - grad_s = [-15 / (56pi), 0.0] # Cubic-spline derivative at r/h = 1.5. - grad_f = isnothing(correction) ? -grad_s : - (-grad_s - 5 / (112pi) * [0.1, -0.2]) / 1.3 - p_avg = scheme == :edac ? 120.0 : 0.0 - p_f = 500.0 - p_avg - p_s = (boundary isa PressureMirroring ? 500.0 : 230.0) - p_avg - expected_force = 1100.0 * 700.0 * - (density isa SummationDensity ? - p_f / 1005.0^2 * grad_f - p_s / 950.0^2 * grad_s : - (p_f * grad_f - p_s * grad_s) / (1005.0 * 950.0)) - for direction in (-1, 0, 1) - state.v_fluid[1:2, 1] .= state.v_structure[1:2, 1] + direction * [0.75, 0.9] - result = test_structure_fluid_pair_balance(state) - @test result.forces[:, 1] ≈ expected_force - if density isa ContinuityDensity - @test result.dv_fluid[end, 1] ≈ - 1005.0 / 950.0 * 700.0 * direction * dot([0.75, 0.9], grad_f) + @testset "Additional structure-fluid variants" begin + variants = NamedTuple[(; boundary_viscosity=viscosity, + fluid_options=(; viscosity=ViscosityAdami(nu=0.4))) + for viscosity in (nothing, ViscosityAdamiSGS(nu=0.1), + ViscosityMorrisSGS(nu=0.1), + ViscosityCarreauYasuda(nu0=0.1, nu_inf=0.01, + lambda=1.0, a=2.0, n=0.5))] + append!(variants, + [(; fluid_pressure=-500.0, fluid_options=(; pressure_acceleration)) + for pressure_acceleration in + (TrixiParticles.pressure_acceleration_summation_density, + TrixiParticles.inter_particle_averaged_pressure, + tensile_instability_control)]) + append!(variants, + [(; boundary_density, + fluid_options=(; density_calculator=SummationDensity())) + for boundary_density in (BernoulliPressureExtrapolation(), + PressureMirroring(), PressureZeroing(), + ContinuityDensity())]) + append!(variants, + [(; boundary_density=SummationDensity(), + fluid_options=(; correction, shifting_technique, + density_calculator=SummationDensity(), + pressure_acceleration=TrixiParticles.pressure_acceleration_summation_density)) + for correction in (ShepardKernelCorrection(), GradientCorrection(), + BlendedGradientCorrection(0.5)), + shifting_technique in (ConsistentShiftingSun2019(), + TransportVelocityAdami(background_pressure=1000.0))]) + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + @testset "$variant" for variant in variants + if kind == :tlsph && + get(variant, :boundary_density, nothing) isa ContinuityDensity + @test_throws ArgumentError structure_fluid_pair_state(; + fluid_scheme=scheme, + structure_kind=kind, + variant...) + continue end - if boundary isa ContinuityDensity - rho_factor = density isa ContinuityDensity ? 950.0 / 1005.0 : 1.0 + scheme == :edac && + !isnothing(get(get(variant, :fluid_options, (;)), :correction, nothing)) && + continue + state = structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=kind, + variant...) + result = test_structure_fluid_pair_balance(state) + if get(variant, :boundary_density, nothing) isa ContinuityDensity @test result.dv_structure[end, 1] ≈ - rho_factor * 1100.0 * direction * dot([-0.75, -0.9], grad_s) + 1100.0 * 0.75 * 0.75 * 0.5^2 * 10 / (7pi) end end - if scheme == :edac && boundary isa PressureMirroring - (; fluid, ode, semi) = state - TrixiParticles.update_average_pressure!(fluid, - fluid.average_pressure_reduction, - ode.u0.x[1], ode.u0.x[2], semi) - @test fluid.cache.pressure_average[1] == 500.0 + end + @testset "$scheme" for scheme in (:wcsph, :edac) + test_structure_fluid_pair_balance(structure_fluid_pair_state(; + fluid_scheme=scheme, + monaghan_kajtar=true)) + @testset "$surface_tension" for surface_tension in + (CohesionForceAkinci(), SurfaceTensionAkinci(), + SurfaceTensionMorris(), + SurfaceTensionMomentumMorris()) + state = structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=:rigid, + fluid_options=(; surface_tension)) + test_structure_fluid_pair_balance(state) end end end - # Density uses the boundary kernel even when the fluid skips the pressure pair. - for (h, distance) in ((1.0, 2.0e-8), (2.0, 2.5)) - state = structure_fluid_pair_state(; structure_kind=:rigid, distance, - boundary_density=ContinuityDensity(), - boundary_smoothing_length=h) - result = test_structure_fluid_pair_balance(state) - q = distance / h - derivative = (q < 1 ? -3q + 2.25q^2 : -0.75 * (2 - q)^2) * 10 / (7pi * h^3) - @test iszero(result.force) - @test result.dv_structure[end, 1] ≈ 950.0 / 1005.0 * 1100.0 * (-0.75) * derivative - end -end -@testset "Additional structure-fluid variants" begin - variants = NamedTuple[(; boundary_viscosity=viscosity, - fluid_options=(; viscosity=ViscosityAdami(nu=0.4))) - for viscosity in (nothing, ViscosityAdamiSGS(nu=0.1), - ViscosityMorrisSGS(nu=0.1), - ViscosityCarreauYasuda(nu0=0.1, nu_inf=0.01, - lambda=1.0, a=2.0, n=0.5))] - append!(variants, - [(; fluid_pressure=-500.0, fluid_options=(; pressure_acceleration)) - for pressure_acceleration in - (TrixiParticles.pressure_acceleration_summation_density, - TrixiParticles.inter_particle_averaged_pressure, - tensile_instability_control)]) - append!(variants, - [(; boundary_density, - fluid_options=(; density_calculator=SummationDensity())) - for boundary_density in (BernoulliPressureExtrapolation(), - PressureMirroring(), PressureZeroing(), - ContinuityDensity())]) - append!(variants, - [(; boundary_density=SummationDensity(), - fluid_options=(; correction, shifting_technique, - density_calculator=SummationDensity(), - pressure_acceleration=TrixiParticles.pressure_acceleration_summation_density)) - for correction in (ShepardKernelCorrection(), GradientCorrection(), - BlendedGradientCorrection(0.5)), - shifting_technique in (ConsistentShiftingSun2019(), - TransportVelocityAdami(background_pressure=1000.0))]) - @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) - @testset "$variant" for variant in variants - if kind == :tlsph && - get(variant, :boundary_density, nothing) isa ContinuityDensity - @test_throws ArgumentError structure_fluid_pair_state(; fluid_scheme=scheme, - structure_kind=kind, - variant...) - continue + @testset "Shifting momentum and distance regressions" begin + # Representative momentum operators instead of a Cartesian product of + # callback and continuity options, which do not affect structural traction. + shifting_variants = (nothing, ParticleShiftingTechniqueSun2017(), + ConsistentShiftingSun2019(), + ParticleShiftingTechnique(momentum_equation_term=MomentumEquationTermSun2019()), + TransportVelocityAdami(background_pressure=1000.0), + TransportVelocityAdami(background_pressure=1000.0, + modify_continuity_equation=true)) + @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) + @testset "$shifting" for shifting in shifting_variants + options = (; shifting_technique=shifting) + state = structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=kind, + fluid_options=options, + fluid_pressure=0.0) + state.structure.boundary_model.pressure .= 0.0 + result = test_structure_fluid_pair_balance(state) + # Analytical Sun2019/Adami momentum terms for delta_v_structure = 0. + factor = 0.0 + if shifting isa ParticleShiftingTechnique && + !isnothing(shifting.momentum_equation_term) + factor = 2 * 700.0 / 950.0 + elseif shifting isa TransportVelocityAdami + factor = scheme == :wcsph ? -700.0 / 950.0 : + -((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 * + 1005.0 * 950.0 / (1005.0 + 950.0) + end + grad = [0.75 * 0.5^2 * 10 / (7pi), 0.0] + expected = factor * state.v_fluid[1:2, 1] * + dot(TrixiParticles.delta_v(state.fluid, 1), grad) + @test result.dv_fluid[1:2, 1] ≈ expected + @test iszero(result.force) + @test all(iszero, result.forces) end + @testset "$distance" for distance in (0.0, 2.0e-8, 6.0e-8, 2.0, 2.1) + state = structure_fluid_pair_state(; fluid_scheme=scheme, + structure_kind=kind, + distance) + result = test_structure_fluid_pair_balance(state) + skipped = distance == 0 || distance >= 2 || + (scheme == :wcsph && distance == 2.0e-8) + @test iszero(result.force) == skipped + end + end + end + @testset "3D structure-fluid forces and rigid torque" begin + @testset "$scheme, $kind, $backend" for scheme in (:wcsph, :edac), + kind in (:tlsph, :rigid), + backend in + (SerialBackend(), PolyesterBackend()) + + options = (; viscosity=ViscosityAdami(nu=0.1), + shifting_technique=ConsistentShiftingSun2019()) state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - variant...) + dimensions=3, + parallelization_backend=backend, + coordinates=[1.2 1.4 1.6; -0.4 0.5 0.1; + 0.2 -0.3 0.6], + fluid_options=options) result = test_structure_fluid_pair_balance(state) - if get(variant, :boundary_density, nothing) isa ContinuityDensity - @test result.dv_structure[end, 1] ≈ - 1100.0 * 0.75 * 0.75 * 0.5^2 * 10 / (7pi) + if kind == :rigid + (; structure, semi) = state + expected_torque = sum(cross(state.u_structure[:, i] - + structure.center_of_mass[], + result.forces[:, i]) + for i in eachparticle(structure)) + TrixiParticles.apply_resultant_force_and_torque!(result.dv_structure, + structure, + semi) + @test structure.resultant_force[] ≈ result.force + @test structure.resultant_torque[] ≈ expected_torque end end end - @testset "$scheme" for scheme in (:wcsph, :edac) - test_structure_fluid_pair_balance(structure_fluid_pair_state(; fluid_scheme=scheme, - monaghan_kajtar=true)) - @testset "$surface_tension" for surface_tension in - (CohesionForceAkinci(), SurfaceTensionAkinci(), - SurfaceTensionMorris(), - SurfaceTensionMomentumMorris()) - state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=:rigid, - fluid_options=(; surface_tension)) - test_structure_fluid_pair_balance(state) + + @testset "Unequal fluid and boundary supports" begin + @testset "$kind, $handler, $h" for kind in (:tlsph, :rigid), + handler in (PairsNHSHandler, SharedNHSHandler), + h in (0.5, 1.0, 2.0) + state = structure_fluid_pair_state(; structure_kind=kind, + boundary_smoothing_length=h, + neighborhood_search_handler=handler) + result = test_structure_fluid_pair_balance(state) + @test !iszero(result.force) + @test TrixiParticles.compact_support(state.structure, state.fluid) == + max(2h, 2.0) end + # The enlarged reaction search must not extend the boundary continuity kernel. + state = structure_fluid_pair_state(; structure_kind=:rigid, + boundary_smoothing_length=0.5, + boundary_density=ContinuityDensity()) + result = test_structure_fluid_pair_balance(state) + @test !iszero(result.force) + @test iszero(result.dv_structure[end, 1]) end -end - -@testset "Shifting momentum and distance regressions" begin - shifting_variants = Any[nothing, ParticleShiftingTechniqueSun2017(), - TransportVelocityAdami(background_pressure=1000.0), - TransportVelocityAdami(background_pressure=1000.0, - modify_continuity_equation=true)] - for update_everystage in (false, true), - (modify_continuity_equation, second_continuity_equation_term) in - ((false, nothing), (true, nothing), (true, ContinuityEquationTermSun2019())), - momentum_equation_term in (nothing, MomentumEquationTermSun2019()) - push!(shifting_variants, - ParticleShiftingTechnique(; update_everystage, - modify_continuity_equation, - second_continuity_equation_term, - momentum_equation_term)) + @testset "Hydrodynamic versus elastic TLSPH kernels" begin + for correction in (KernelCorrection(), MixedKernelGradientCorrection()) + options = (; correction, pressure_acceleration=nothing) + state = structure_fluid_pair_state(; fluid_options=options, + structure_smoothing_length=0.4, + structure_smoothing_kernel=WendlandC2Kernel{2}()) + result = test_structure_fluid_pair_balance(state) + grad_s = [-15 / (56pi), 0.0] + grad_f = (-grad_s - 5 / (112pi) * [0.1, -0.2]) / 1.3 + # Mixed correction applies the prescribed, non-diagonal fluid matrix. + correction isa MixedKernelGradientCorrection && + (grad_f = [1.0 0.3; 0.0 1.0] * grad_f) + expected = 1100.0 * 700.0 / (1005.0 * 950.0) * (500.0 * grad_f - 230.0 * grad_s) + @test result.forces[:, 1] ≈ expected + @test iszero(TrixiParticles.smoothing_kernel_grad(state.structure, + SVector(1.5, 0.0), 1.5, 1)) + @test TrixiParticles.hydrodynamic_kernel_grad(state.structure, + SVector(1.5, 0.0), 1.5, 1) ≈ + grad_s + end end - @testset "$scheme, $kind" for scheme in (:wcsph, :edac), kind in (:tlsph, :rigid) - @testset "$shifting" for shifting in shifting_variants - options = (; shifting_technique=shifting) + + @testset "TVF does not duplicate Monaghan-Kajtar repulsion" begin + for (scheme, kind) in ((:wcsph, :tlsph), (:wcsph, :wall), (:edac, :tlsph)) + tvf = TransportVelocityAdami(background_pressure=1000.0) state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - fluid_options=options, fluid_pressure=0.0) - state.structure.boundary_model.pressure .= 0.0 - result = test_structure_fluid_pair_balance(state) - # Analytical Sun2019/Adami momentum terms for delta_v_structure = 0. - factor = 0.0 - if shifting isa ParticleShiftingTechnique && - !isnothing(shifting.momentum_equation_term) - factor = 2 * 700.0 / 950.0 - elseif shifting isa TransportVelocityAdami - factor = scheme == :wcsph ? -700.0 / 950.0 : - -((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 * - 1005.0 * 950.0 / (1005.0 + 950.0) + monaghan_kajtar=true, + fluid_options=(; shifting_technique=tvf)) + (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, + u_structure) = state + fluid.cache.delta_v .= 0 + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + # Independent Monaghan-Kajtar repulsion at q = 1.5, K = 10, beta = 1, + # boundary spacing = 1. Even with zero shifting, the old TVF doubled it. + repulsion = -10.0 / 0.5 * (1.77 / 32) * + (1 + 2.5 * 1.5 + 2 * 1.5^2) * 0.5^5 + @test dv_fluid[1:2, 1] ≈ [repulsion, 0.0] + + TrixiParticles.update_shifting!(fluid, tvf, v_fluid, u_fluid, + ode.u0.x[1], ode.u0.x[2], semi) + grad_f = [15 / (56pi), 0.0] + volume_term = ((1100.0 / 1005.0)^2 + 1.0) / 1100.0 + expected_shift = -1000.0 / (8 * 10.0) * + (scheme == :wcsph ? 2 / 1005.0 : volume_term) * grad_f + @test TrixiParticles.delta_v(fluid, 1) ≈ expected_shift + + # The TVF tensor contribution stays in the fluid and does not change the + # structural repulsion. This also exercises nonzero transport velocities. + if kind == :tlsph + result = test_structure_fluid_pair_balance(state) + @test result.forces[:, 1] ≈ -1100.0 * [repulsion, 0.0] + @test result.dv_fluid[1, 1] != repulsion end - grad = [0.75 * 0.5^2 * 10 / (7pi), 0.0] - expected = factor * state.v_fluid[1:2, 1] * - dot(TrixiParticles.delta_v(state.fluid, 1), grad) - @test result.dv_fluid[1:2, 1] ≈ expected end - @testset "$distance" for distance in (0.0, 2.0e-8, 6.0e-8, 2.0, 2.1) - state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - distance) + end + + @testset "Boundary-model correction context" begin + for kind in (:tlsph, :rigid), + correction in (KernelCorrection(), + GradientCorrection(), + MixedKernelGradientCorrection()) + + state = structure_fluid_pair_state(; structure_kind=kind, + structure_smoothing_length=0.4, + boundary_density=PressureMirroring(), + boundary_correction=correction, + fluid_options=(; + correction=KernelCorrection(), + pressure_acceleration=nothing)) + (; structure, v_structure, u_structure, ode, semi) = state + model = structure.boundary_model + for field in (:dw_gamma, :kernel_correction_coefficient, :correction_matrix) + haskey(model.cache, field) && fill!(getproperty(model.cache, field), NaN) + end + TrixiParticles.update_boundary_interpolation!(structure, v_structure, + u_structure, + ode.u0.x[1], ode.u0.x[2], semi, + 0.0) + for field in (:dw_gamma, :kernel_correction_coefficient, :correction_matrix) + haskey(model.cache, field) && + @test all(isfinite, getproperty(model.cache, field)) + end + + grad_s = [-15 / (56pi), 0.0] + if correction isa KernelCorrection || + correction isa MixedKernelGradientCorrection + # Use the boundary kernel for every visited neighbor. TLSPH's self + # search includes the particle itself; a rigid body without a + # contact model has an empty rigid-to-rigid search. + gamma = 1100.0 / 1005.0 * 5 / (112pi) + kind == :tlsph && (gamma += 700.0 / 950.0 * 10 / (7pi)) + dw_gamma = 1100.0 / 1005.0 * grad_s / gamma + @test model.cache.kernel_correction_coefficient[1] ≈ gamma + @test model.cache.dw_gamma[:, 1] ≈ dw_gamma + grad_s = (grad_s - 5 / (112pi) * dw_gamma) / gamma + end + # A one-neighbor layout is rank deficient, so gradient correction uses I. + grad_f = ([15 / (56pi), 0.0] - 5 / (112pi) * [0.1, -0.2]) / 1.3 + expected = 1100.0 * 700.0 * 500.0 / (1005.0 * 950.0) * (grad_f - grad_s) result = test_structure_fluid_pair_balance(state) - skipped = distance == 0 || distance >= 2 || - (scheme == :wcsph && distance == 2.0e-8) - @test iszero(result.force) == skipped + @test result.forces[:, 1] ≈ expected end end -end -@testset "3D structure-fluid forces and rigid torque" begin - @testset "$scheme, $kind, $backend" for scheme in (:wcsph, :edac), - kind in (:tlsph, :rigid), - backend in - (SerialBackend(), PolyesterBackend()) + @testset "EDAC pressure mirroring at walls" begin + for average_pressure_reduction in (false, true) + state = structure_fluid_pair_state(; fluid_scheme=:edac, structure_kind=:wall, + boundary_density=PressureMirroring(), + fluid_options=(; average_pressure_reduction)) + (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, + u_structure) = state + TrixiParticles.update_average_pressure!(fluid, fluid.average_pressure_reduction, + ode.u0.x[1], ode.u0.x[2], semi) + p_avg = average_pressure_reduction ? 500.0 : 0.0 + @test TrixiParticles.average_pressure(fluid, 1) == p_avg + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + grad_f = [15 / (56pi), 0.0] + volume_term = ((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 + @test dv_fluid[1:2, 1] ≈ -volume_term * (500.0 - p_avg) * grad_f + # Mirroring eliminates pressure diffusion, leaving only the artificial EOS. + @test dv_fluid[3, 1] ≈ 700.0 * 1005.0 / 950.0 * 10.0^2 * dot([1.0, 0.5], grad_f) + end + end - options = (; viscosity=ViscosityAdami(nu=0.1), - shifting_technique=ConsistentShiftingSun2019()) - state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - dimensions=3, parallelization_backend=backend, - coordinates=[1.2 1.4 1.6; -0.4 0.5 0.1; - 0.2 -0.3 0.6], - fluid_options=options) - result = test_structure_fluid_pair_balance(state) - if kind == :rigid - (; structure, semi) = state - expected_torque = sum(cross(state.u_structure[:, i] - - structure.center_of_mass[], - result.forces[:, i]) - for i in eachparticle(structure)) - TrixiParticles.apply_resultant_force_and_torque!(result.dv_structure, structure, - semi) - @test structure.resultant_force[] ≈ result.force - @test structure.resultant_torque[] ≈ expected_torque + @testset "IISPH pair pressure and viscosity" begin + # Test the pair RHS with prescribed pressure. The IISPH pressure solver does + # not yet support structural neighbors, so no coupled kick/solve is attempted. + for kind in (:tlsph, :rigid), boundary in (PressureMirroring(), PressureZeroing()) + state = structure_fluid_pair_state(; fluid_scheme=:iisph, structure_kind=kind, + boundary_density=boundary, + fluid_options=(; + viscosity=ViscosityAdami(nu=0.1))) + result = test_structure_fluid_pair_balance(state) + @test !iszero(result.force) end end -end +end # Structure-fluid interaction variants From 8e15c60fb270076ae19c3ac6d427d6caadb2b146 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 12:14:05 +0200 Subject: [PATCH 05/46] Fix physical structure-fluid reaction forces --- NEWS.md | 7 +- docs/src/systems/rigid_body.md | 8 + src/schemes/structure/structure.jl | 225 +++++++++++++------- test/Project.toml | 2 + test/schemes/schemes.jl | 1 + test/schemes/structure/fluid_interaction.jl | 162 ++++++++++++++ 6 files changed, 324 insertions(+), 81 deletions(-) create mode 100644 test/schemes/structure/fluid_interaction.jl diff --git a/NEWS.md b/NEWS.md index 14c11868bb..8b6bafd589 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,8 +12,11 @@ used in the Julia ecosystem. Notable changes will be documented in this file for `MechanicalWorkCalculator`, which can be passed as a custom quantity to `PostprocessCallback` (#1228). -### Important Bugfixes - +### Important Bugfixes + +- Corrected pressure and viscous reaction forces on TLSPH and rigid-body systems, + including asymmetric fluid gradients, free-surface factors, EDAC pressure + reduction, and the approaching-particle condition for artificial viscosity (#1338). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/docs/src/systems/rigid_body.md b/docs/src/systems/rigid_body.md index 27928499ce..6ad8fcc622 100644 --- a/docs/src/systems/rigid_body.md +++ b/docs/src/systems/rigid_body.md @@ -4,6 +4,14 @@ Rigid bodies in TrixiParticles.jl are represented by particles whose motion is e with rigid-body translation and rotation. This allows fluid-structure interaction while keeping the structure kinematics rigid. +## [Fluid loads](@id fluid_structure_loads) + +Pressure, viscosity, and adhesion use fluid-first pair operators. The physical +fluid acceleration contributes the structural reaction `F_s = -m_f a_f`. +Rigid bodies sum particle forces and torques, while TLSPH converts force to +acceleration with the material mass. Shifting momentum terms remain in the fluid +RHS and are excluded from structural loads because they are transport corrections. + ## API ```@autodocs diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 01d5917f6b..b1dd8583d2 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -1,20 +1,84 @@ # Shared structure-fluid interaction helpers used by multiple structure schemes. -@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, - particle_system::TotalLagrangianSPHSystem, - particle, m_b) +@propagate_inbounds function write_fluid_force!(dv, + particle_system::TotalLagrangianSPHSystem, + force_particle, particle) material_mass = particle_system.mass[particle] - for dim in eachindex(dv_fs) - dv[dim, particle] += dv_fs[dim] * m_b / material_mass + for i in 1:ndims(particle_system) + dv[i, particle] += force_particle[i] / material_mass end + + return dv end -@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, - particle_system::RigidBodySystem, - particle, m_b) +@propagate_inbounds function write_fluid_force!(dv, particle_system::RigidBodySystem, + force_particle, particle) force_per_particle = particle_system.force_per_particle - for dim in eachindex(dv_fs) - force_per_particle[dim, particle] += dv_fs[dim] * m_b + for i in 1:ndims(particle_system) + force_per_particle[i, particle] += force_particle[i] end + + return dv +end + +@inline average_pressure(system, particle) = zero(eltype(system)) + +@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) + +@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, + rho_a, rho_b) + return free_surface_correction(system_correction(system), system, rho_a, rho_b) +end + +@inline function interaction_zero_distance(system, neighbor_system) + return sqrt(eps(initial_smoothing_length(system)^2)) +end + +@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, + neighbor_system) + return sqrt(eps(compact_support(system, neighbor_system)^2)) +end + +@inline function skip_fluid_pair(system, distance, support, almostzero) + return distance > support || (skip_zero_distance(system) && distance < almostzero) +end + +@inline function sum_interaction_contributions(a, b) + dv_a, drho_a = a + dv_b, drho_b = b + return dv_a + dv_b, drho_a + drho_b +end + +# Evaluate physical acceleration in fluid-first order. Shifting transport terms +# are not interfacial traction and do not contribute to the structural load. +@propagate_inbounds function fluid_pair_acceleration(particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, correction) + p_avg = average_pressure(particle_system, particle) + viscosity_correction, pressure_correction, + surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) + dv_pressure = pressure_acceleration(particle_system, neighbor_system, + particle, neighbor, m_a, m_b, + p_a - p_avg, p_b - p_avg, rho_a, rho_b, + pos_diff, distance, grad_kernel, correction) + dv_particle = dv_pressure * pressure_correction + dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, pos_diff, distance, sound_speed, + m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, + viscosity_correction) + surface_tension_a = surface_tension_model(particle_system) + surface_tension_b = surface_tension_model(neighbor_system) + dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, + particle_system, neighbor_system, particle, + neighbor, + pos_diff, distance, rho_a, rho_b, grad_kernel, + surface_tension_correction) + return add_dv_adhesion(dv_particle, surface_tension_a, + particle_system, neighbor_system, particle, neighbor, + pos_diff, distance) end function interact_structure_fluid!(dv, v_particle_system, u_particle_system, @@ -23,79 +87,78 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, neighbor_system::AbstractFluidSystem, semi; eachparticle=each_integrated_particle(particle_system)) sound_speed = system_sound_speed(neighbor_system) + correction = system_correction(neighbor_system) + system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) + neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) + backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(neighbor_system) - almostzero = sqrt(eps(h^2)) - - # Loop over all pairs of particles and neighbors within the kernel cutoff. - foreach_point_neighbor(particle_system, neighbor_system, - system_coords, neighbor_coords, semi; - points=eachparticle) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. - # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(neighbor_system) && distance < almostzero && return - - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. - # Note that we use the `neighbor_system` to compute the kernel gradient - # to obtain the same force as in the fluid-structure interaction. - grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, - distance, neighbor) - - m_b = hydrodynamic_mass(neighbor_system, neighbor) - - rho_a = current_density(v_particle_system, particle_system, particle) - rho_b = current_density(v_neighbor_system, neighbor_system, neighbor) - - v_a = current_velocity(v_particle_system, particle_system, particle) - v_b = current_velocity(v_neighbor_system, neighbor_system, neighbor) - - surface_tension = surface_tension_model(neighbor_system) + # Use the same pair cutoffs as the fluid RHS. + compact_support_ = compact_support(neighbor_system, particle_system) + almostzero = interaction_zero_distance(neighbor_system, particle_system) + @threaded semi for particle in eachparticle # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles # corresponding to the rest density of the fluid and not the material density. - m_a = hydrodynamic_mass(particle_system, particle) - - # In fluid-structure interaction, use the "hydrodynamic pressure" of the structure - # particles corresponding to the chosen boundary model. - p_a = current_pressure(v_particle_system, particle_system, particle) - p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) - - # Particle and neighbor (and the corresponding systems and particle quantities) are - # switched in the following two calls. This yields the exact same pair force as in the - # fluid-structure interaction, but with flipped sign because `pos_diff` is reversed. - dv_boundary = pressure_acceleration(neighbor_system, particle_system, - neighbor, particle, - m_b, m_a, p_b, p_a, rho_b, rho_a, - pos_diff, distance, grad_kernel, - system_correction(neighbor_system)) - - dv_particle = add_dv_viscosity(dv_boundary, neighbor_system, particle_system, - v_neighbor_system, v_particle_system, - neighbor, particle, pos_diff, distance, - sound_speed, m_b, m_a, rho_b, rho_a, - v_b, v_a, grad_kernel) - - dv_particle = add_dv_adhesion(dv_particle, surface_tension, - neighbor_system, particle_system, - neighbor, particle, pos_diff, distance) - - accumulate_structure_fluid_pair!(dv, dv_particle, particle_system, particle, m_b) - - drho_particle = add_continuity_equation(zero(rho_a), - particle_system, neighbor_system, - particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) - - @inbounds write_drho_particle!(dv, particle_system, drho_particle, particle) + m_a = @inbounds hydrodynamic_mass(particle_system, particle) + rho_a = @inbounds current_density(v_particle_system, particle_system, particle) + v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) + + # Accumulate force and density rate separately, as in the fluid RHS. + init = (zero(v_a), zero(rho_a)) + + # Keep the returned name out of the closure to avoid allocations. + (force_particle_, + drho_particle_) = @inbounds mapreduce_neighbor(sum_interaction_contributions, + system_coords, + neighbor_coords, + neighborhood_search, backend, + particle; + init) do particle, + neighbor, + pos_diff, + distance + m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) + rho_b = @inbounds current_density(v_neighbor_system, neighbor_system, neighbor) + v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) + + skip_fluid_pair(neighbor_system, distance, compact_support_, almostzero) && + return init + + drho_particle = @inbounds add_continuity_equation(zero(rho_a), + particle_system, + neighbor_system, + particle, neighbor, pos_diff, + distance, m_b, rho_a, rho_b, + v_a, v_b) + + # Corrected gradients need not be odd; evaluate the fluid-side gradient. + grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, + distance, neighbor) + + # Use the hydrodynamic pressure defined by the structure's boundary model. + p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) + p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, + p_b) + + # Fluid-first ordering preserves the actual fluid force, including the + # approaching-particle condition of artificial viscosity. + dv_fluid = @inbounds fluid_pair_acceleration(neighbor_system, particle_system, + v_neighbor_system, + v_particle_system, + neighbor, particle, + m_b, m_a, p_b, p_a, rho_b, rho_a, + v_b, v_a, -pos_diff, distance, + sound_speed, grad_kernel_fluid, + correction) + + return -m_b * dv_fluid, drho_particle + end + + @inbounds write_fluid_force!(dv, particle_system, force_particle_, particle) + @inbounds write_drho_particle!(dv, particle_system, drho_particle_, + particle) end return dv @@ -105,7 +168,7 @@ end particle_system::AbstractStructureSystem, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b) return drho_particle end @@ -114,7 +177,11 @@ end TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b) + # Boundary density retains its existing structure-first gradient. + grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, + neighbor) + return add_continuity_equation(drho_particle, density_calculator(neighbor_system), m_b, rho_a, rho_b, v_a, v_b, grad_kernel, particle) diff --git a/test/Project.toml b/test/Project.toml index 28bb94f88b..5d61a162a7 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -7,6 +7,7 @@ GLM = "38e38edf-8417-5370-95a0-9cbb8c7f171a" Glob = "c27321d9-0574-5035-807b-f59d2c89b15c" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" +Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" OrdinaryDiffEqLowStorageRK = "b0944070-b475-4768-8dec-fb6eb410534d" OrdinaryDiffEqSymplecticRK = "fa646aed-7ef9-47eb-84c4-9443fc8cbfa8" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" @@ -26,6 +27,7 @@ GLM = "1.9" Glob = "1.3" JSON = "1" LinearAlgebra = "1" +Logging = "1" OrdinaryDiffEqLowStorageRK = "3" OrdinaryDiffEqSymplecticRK = "2" Plots = "1" diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index bb6e9d5483..dc1941f0b4 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,4 +1,5 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") +include("structure/fluid_interaction.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl new file mode 100644 index 0000000000..edd9daf700 --- /dev/null +++ b/test/schemes/structure/fluid_interaction.jl @@ -0,0 +1,162 @@ +using Logging: NullLogger, with_logger + +@testset verbose=true "Structure-fluid force balance" begin + particle_spacing = 1.0 + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.0 + reference_density = 1000.0 + structure_density = 2000.0 + state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) + viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), + ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) + configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), + (:wcsph, nothing, ContinuityDensity()), + (:wcsph, AkinciFreeSurfaceCorrection(reference_density), + AdamiPressureExtrapolation()), + (:wcsph, KernelCorrection(), SummationDensity()), + (:wcsph, MixedKernelGradientCorrection(), SummationDensity()), + (:edac, nothing, AdamiPressureExtrapolation()), + (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) + # Zero pressure isolates viscosity for approaching and receding particles. + # Nonzero pressure checks that pressure and viscosity accumulate consistently. + fluid_states = ((velocity=(1.0, 0.5), density=reference_density), + (velocity=(-1.0, -0.5), density=reference_density), + (velocity=(1.0, 0.5), density=1005.0)) + + @testset "$fluid_scheme, $viscosity, $correction, $boundary_density" for viscosity in + viscosities, + (fluid_scheme, + correction, + boundary_density) in + configurations + + @testset "$structure_kind, $fluid_state" for structure_kind in + (:tlsph, :clamped_tlsph, :rigid), + fluid_state in fluid_states + + # `ContinuityDensity` is currently supported only for rigid structures. + if structure_kind != :rigid && boundary_density isa ContinuityDensity + continue + end + + fluid_velocity = reshape(collect(fluid_state.velocity), 2, 1) + fluid_ic = InitialCondition(; coordinates=reshape([0.0, 0.0], 2, 1), + velocity=fluid_velocity, + mass=[reference_density], + density=[fluid_state.density], + pressure=state_equation(fluid_state.density), + particle_spacing) + fluid_system = if fluid_scheme == :wcsph + WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + viscosity, correction, + density_calculator=ContinuityDensity(), + state_equation) + else + EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + sound_speed=10.0, viscosity, correction, + density_calculator=ContinuityDensity(), + average_pressure_reduction=fluid_scheme == + :edac_pressure_reduction) + end + + structure_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), + velocity=zeros(2, 1), mass=[structure_density], + density=[structure_density], particle_spacing) + boundary_model = BoundaryModelDummyParticles([reference_density], + [reference_density], + boundary_density, + smoothing_kernel, smoothing_length; + state_equation, viscosity) + structure_system = if structure_kind == :rigid + RigidBodySystem(structure_ic; boundary_model) + else + clamped_particles = structure_kind == :clamped_tlsph ? (1:1) : (1:0) + TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, + young_modulus=1.0e5, poisson_ratio=0.3, + clamped_particles, boundary_model) + end + + semi = with_logger(NullLogger()) do + Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end + ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) + fluid, structure = ode.p.semi.systems + v_ode, u_ode = ode.u0.x + dv_ode = zero(v_ode) + TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + # Isolate this pair from corrected fluid self-interaction terms. + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, + v_structure, u_structure, fluid, structure, semi) + expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] + + if correction isa KernelCorrection || + correction isa MixedKernelGradientCorrection + # Ensure that this fixture exercises a gradient that is not odd. + pos_diff = SVector(1.5, 0.0) + gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, + 1.5, 1) + reverse_gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + -pos_diff, + 1.5, 1) + @test !isapprox(gradient, -reverse_gradient) + end + + if fluid_state.density == reference_density + @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, 1)) + @test iszero(structure.boundary_model.pressure[1]) + if isnothing(viscosity) || + (viscosity isa ArtificialViscosityMonaghan && + fluid_state.velocity[1] < 0) + @test iszero(expected_force) + else + # The viscous reaction on the structure follows the fluid motion. + @test expected_force[1] * fluid_state.velocity[1] > 0 + end + elseif fluid_scheme == :edac_pressure_reduction && isnothing(viscosity) + # Uniform nonzero pressure produces no force after pressure reduction. + @test TrixiParticles.current_pressure(v_fluid, fluid, 1) ≈ + structure.boundary_model.pressure[1] + @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) + else + @test !iszero(expected_force) + end + + if boundary_density isa ContinuityDensity + # Independently evaluate d(rho_s)/dt = (rho_s/rho_f) m_f (v_s-v_f) ⋅ ∇_s W. + # Cubic-spline derivative at r/h = 1.5 in 2D, with h = 1. + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -reference_density / fluid_state.density * + fluid.mass[1] * fluid_state.velocity[1] * + kernel_derivative + dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) + @test dv_structure[end, 1] ≈ expected_density_rate + end + + if structure isa RigidBodySystem + @test isapprox(structure.resultant_force[], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + else + # Include clamped particles when checking the pair reaction directly. + dv_structure_fluid = zeros(eltype(structure), ndims(structure), + nparticles(structure)) + TrixiParticles.interact!(dv_structure_fluid, v_structure, u_structure, + v_fluid, u_fluid, structure, fluid, semi; + eachparticle=eachparticle(structure)) + @test isapprox(structure.mass[1] * dv_structure_fluid[:, 1], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + + if structure_kind == :tlsph + dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) + @test isapprox(structure.mass[1] * dv_structure[1:2, 1], expected_force; + rtol=sqrt(eps()), atol=sqrt(eps())) + end + end + end + end +end From 9e0b3f3a3701b75f927f133e22088be6326cb0a3 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 12:21:08 +0200 Subject: [PATCH 06/46] Fix pressure mirroring for structures and EDAC walls --- NEWS.md | 2 + docs/src/systems/boundary.md | 5 ++ .../fluid/entropically_damped_sph/rhs.jl | 2 +- .../fluid/entropically_damped_sph/system.jl | 7 +- .../fluid/implicit_incompressible_sph/rhs.jl | 5 +- .../fluid/weakly_compressible_sph/rhs.jl | 9 +- test/schemes/boundary/pressure_mirroring.jl | 54 ++++++++++++ test/schemes/schemes.jl | 2 + .../structure/fluid_interaction_helpers.jl | 87 +++++++++++++++++++ 9 files changed, 163 insertions(+), 10 deletions(-) create mode 100644 test/schemes/boundary/pressure_mirroring.jl create mode 100644 test/schemes/structure/fluid_interaction_helpers.jl diff --git a/NEWS.md b/NEWS.md index 8b6bafd589..034972c7ad 100644 --- a/NEWS.md +++ b/NEWS.md @@ -14,6 +14,8 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes +- Fixed pressure mirroring for TLSPH and rigid-body neighbors and for EDAC momentum, + pressure diffusion, and average-pressure reduction at walls and structures. - Corrected pressure and viscous reaction forces on TLSPH and rigid-body systems, including asymmetric fluid gradients, free-surface factors, EDAC pressure reduction, and the approaching-particle condition for artificial viscosity (#1338). diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index bfbe22080f..fdec6ab198 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -86,6 +86,11 @@ We provide six options to compute the boundary density and pressure, determined This option is not recommended due to stability issues. See [`PressureMirroring`](@ref) for more details. +Pressure mirroring also applies to TLSPH and rigid-body boundary models. In EDAC, +the mirrored pressure is used in the momentum equation, the pressure evolution +equation, and the average-pressure reduction. Mirroring makes the pressure +diffusion contribution from a fluid-boundary pair zero. + #### 1. [`AdamiPressureExtrapolation`](@ref) The pressure of the boundary particles is obtained by extrapolating the pressure of the fluid diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index d4c526f175..4f1ad54991 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -46,7 +46,7 @@ function interact!(dv, v_particle_system, u_particle_system, v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) - p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) + p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) # This technique by Basa et al. 2017 (10.1002/fld.1927) aims to reduce numerical # errors due to large pressures by subtracting the average pressure of neighboring diff --git a/src/schemes/fluid/entropically_damped_sph/system.jl b/src/schemes/fluid/entropically_damped_sph/system.jl index 426e79e537..8ae17c4ea0 100644 --- a/src/schemes/fluid/entropically_damped_sph/system.jl +++ b/src/schemes/fluid/entropically_damped_sph/system.jl @@ -332,6 +332,7 @@ function update_average_pressure!(system, ::Val{true}, v_ode, u_ode, semi) set_zero!(pressure_average) set_zero!(neighbor_counter) + v = wrap_v(v_ode, system, semi) u = wrap_u(u_ode, system, semi) # Use enabled neighbor systems for the average pressure. @@ -354,8 +355,10 @@ function update_average_pressure!(system, ::Val{true}, v_ode, u_ode, semi) neighbor, pos_diff, distance - pressure_average[particle] += current_pressure(v_neighbor_system, - neighbor_system, neighbor) + p_a = current_pressure(v, system, particle) + pressure_average[particle] += neighbor_pressure(v_neighbor_system, + neighbor_system, neighbor, + p_a) neighbor_counter[particle] += 1 end end diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 6e8b5d18fa..db856ae170 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -50,9 +50,8 @@ function interact!(dv, v_particle_system, u_particle_system, p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) # The following call is equivalent to # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # Only when the neighbor system is a `WallBoundarySystem` - # or a `TotalLagrangianSPHSystem` with the boundary model `PressureMirroring`, - # this will return `p_b = p_a`, which is the pressure of the fluid particle. + # For boundaries and structures using `PressureMirroring`, this returns + # `p_b = p_a`, which is the pressure of the fluid particle. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index f09f56d886..87bef6b56f 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -71,9 +71,8 @@ function interact!(dv, v_particle_system, u_particle_system, # The following call is equivalent to # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # Only when the neighbor system is a `WallBoundarySystem` - # or a `TotalLagrangianSPHSystem` with the boundary model `PressureMirroring`, - # this will return `p_b = p_a`, which is the pressure of the fluid particle. + # For boundaries and structures using `PressureMirroring`, this returns + # `p_b = p_a`, which is the pressure of the fluid particle. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) @@ -155,7 +154,9 @@ end end @inline function neighbor_pressure(v_neighbor_system, - neighbor_system::WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + neighbor_system::Union{WallBoundarySystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{PressureMirroring}}, + RigidBodySystem{<:BoundaryModelDummyParticles{PressureMirroring}}}, neighbor, p_a) return p_a end diff --git a/test/schemes/boundary/pressure_mirroring.jl b/test/schemes/boundary/pressure_mirroring.jl new file mode 100644 index 0000000000..0825efdd58 --- /dev/null +++ b/test/schemes/boundary/pressure_mirroring.jl @@ -0,0 +1,54 @@ +using .FSIPairFixtures: structure_fluid_pair_state + +@testset verbose=true "Pressure mirroring across fluid schemes" begin + for scheme in (:wcsph, :edac, :iisph), kind in (:wall, :tlsph, :rigid) + state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, + boundary_density=PressureMirroring()) + (; fluid, structure, semi, v_fluid, u_fluid, v_structure, u_structure) = state + @test TrixiParticles.neighbor_pressure(v_structure, structure, 1, 500.0) == 500.0 + @test structure.boundary_model.pressure[1] == 230.0 + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + grad_f = [15 / (56pi), 0.0] + coefficient = if scheme == :wcsph + 700.0 * 1000.0 / (1005.0 * 950.0) + elseif scheme == :edac + ((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 * 500.0 + else + 700.0 * (500.0 / 1005.0^2 + 500.0 / 950.0^2) + end + @test dv_fluid[1:2, 1] ≈ -coefficient * grad_f + if kind != :wall + dv_structure = zero(v_structure) + TrixiParticles.reset_interaction_caches!(structure) + TrixiParticles.interact!(dv_structure, v_structure, u_structure, v_fluid, + u_fluid, + structure, fluid, semi) + force = kind == :rigid ? structure.force_per_particle[:, 1] : + structure.mass[1] * dv_structure[1:2, 1] + @test force ≈ -1100.0 * dv_fluid[1:2, 1] + end + end + + @testset "EDAC wall pressure evolution and average" begin + for average_pressure_reduction in (false, true) + state = structure_fluid_pair_state(; fluid_scheme=:edac, structure_kind=:wall, + boundary_density=PressureMirroring(), + fluid_options=(; average_pressure_reduction)) + (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, + u_structure) = state + TrixiParticles.update_average_pressure!(fluid, fluid.average_pressure_reduction, + ode.u0.x[1], ode.u0.x[2], semi) + p_avg = average_pressure_reduction ? 500.0 : 0.0 + @test TrixiParticles.average_pressure(fluid, 1) == p_avg + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, + fluid, structure, semi) + grad_f = [15 / (56pi), 0.0] + volume_term = ((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 + @test dv_fluid[1:2, 1] ≈ -volume_term * (500.0 - p_avg) * grad_f + @test dv_fluid[3, 1] ≈ 700.0 * 1005.0 / 950.0 * 10.0^2 * dot([1.0, 0.5], grad_f) + end + end +end diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index dc1941f0b4..55f9497f7a 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,5 +1,7 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") include("structure/fluid_interaction.jl") +include("structure/fluid_interaction_helpers.jl") +include("boundary/pressure_mirroring.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction_helpers.jl b/test/schemes/structure/fluid_interaction_helpers.jl new file mode 100644 index 0000000000..4c07af98c7 --- /dev/null +++ b/test/schemes/structure/fluid_interaction_helpers.jl @@ -0,0 +1,87 @@ +module FSIPairFixtures +using TrixiParticles +using LinearAlgebra: I +using Logging: NullLogger, with_logger + +export structure_fluid_pair_state + +# Prescribed pair states isolate interaction operators from density/pressure updates. +function structure_fluid_pair_state(; fluid_scheme=:wcsph, structure_kind=:tlsph, + fluid_options=(;), + boundary_density=AdamiPressureExtrapolation(), + distance=1.5, dimensions=2, + coordinates=reshape([distance; zeros(dimensions - 1)], + dimensions, 1), + parallelization_backend=SerialBackend()) + smoothing_kernel = SchoenbergCubicSplineKernel{dimensions}() + smoothing_length = particle_spacing = 1.0 + state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1000.0, + exponent=1.0, clip_negative_pressure=false) + velocity = reshape([1.0, 0.5, 0.7][1:dimensions], dimensions, 1) + fluid_ic = InitialCondition(; coordinates=zeros(dimensions, 1), velocity, + mass=[1100.0], density=[1005.0], pressure=500.0, + particle_spacing) + options = (; density_calculator=ContinuityDensity(), reference_particle_spacing=1.0, + fluid_options...) + fluid = if fluid_scheme == :wcsph + WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + state_equation, options...) + elseif fluid_scheme == :edac + options = (; average_pressure_reduction=false, options...) + EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + sound_speed=10.0, options...) + else + ImplicitIncompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, + reference_density=1005.0, time_step=0.001, + viscosity=get(fluid_options, :viscosity, nothing)) + end + n = size(coordinates, 2) + structure_velocity = repeat(reshape([0.25, -0.4, 0.2][1:dimensions], dimensions, 1), 1, + n) + structure_ic = InitialCondition(; coordinates, velocity=structure_velocity, + mass=2100.0 .+ 300.0 .* (0:(n - 1)), + density=fill(2000.0, n), + particle_spacing) + viscosity = get(fluid_options, :viscosity, nothing) + boundary_model = BoundaryModelDummyParticles(fill(950.0, n), + 700.0 .+ 50.0 .* (0:(n - 1)), + boundary_density, smoothing_kernel, + smoothing_length; + state_equation, viscosity, + reference_particle_spacing=1.0) + structure = if structure_kind == :rigid + RigidBodySystem(structure_ic; boundary_model, adhesion_coefficient=0.25) + elseif structure_kind == :wall + WallBoundarySystem(structure_ic, boundary_model) + else + TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, + young_modulus=1.0e5, poisson_ratio=0.3, boundary_model) + end + semi = with_logger(NullLogger()) do + Semidiscretization(fluid, structure; parallelization_backend) + end + ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) + fluid, structure = semi.systems + v_ode, u_ode = ode.u0.x + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + TrixiParticles.current_density(v_fluid, fluid) .= 1005.0 + TrixiParticles.current_pressure(v_fluid, fluid) .= 500.0 + structure.boundary_model.pressure .= 230.0 + !isnothing(viscosity) && + (structure.boundary_model.cache.wall_velocity .= 2 .* structure_velocity .- + velocity) + for (field, value) in ((:delta_v, [0.4, -0.3, 0.2][1:dimensions]), + (:dw_gamma, [0.1, -0.2, 0.15][1:dimensions]), + (:kernel_correction_coefficient, 1.3), (:pressure_average, 120.0)) + haskey(fluid.cache, field) && (getproperty(fluid.cache, field) .= value) + end + if haskey(fluid.cache, :correction_matrix) + fluid.cache.correction_matrix[:, :, 1] .= Matrix{Float64}(I, dimensions, dimensions) + fluid.cache.correction_matrix[1, 2, 1] = 0.3 + end + return (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, u_structure) +end +end From c7737a8011548197079d1ea1c793c99927003da1 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 12:26:30 +0200 Subject: [PATCH 07/46] Add pressure mirroring PR reference --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 034972c7ad..3ac6604064 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,7 +15,7 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Fixed pressure mirroring for TLSPH and rigid-body neighbors and for EDAC momentum, - pressure diffusion, and average-pressure reduction at walls and structures. + pressure diffusion, and average-pressure reduction at walls and structures (#1341). - Corrected pressure and viscous reaction forces on TLSPH and rigid-body systems, including asymmetric fluid gradients, free-surface factors, EDAC pressure reduction, and the approaching-particle condition for artificial viscosity (#1338). From 51a4fd5798947676a45e2ba1fca08f68c9975497 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 13:22:27 +0200 Subject: [PATCH 08/46] Assert expected FSI setup logs without a Logging dependency --- test/Project.toml | 2 -- test/schemes/structure/fluid_interaction.jl | 14 +++++++++----- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/test/Project.toml b/test/Project.toml index 5d61a162a7..28bb94f88b 100644 --- a/test/Project.toml +++ b/test/Project.toml @@ -7,7 +7,6 @@ GLM = "38e38edf-8417-5370-95a0-9cbb8c7f171a" Glob = "c27321d9-0574-5035-807b-f59d2c89b15c" JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6" LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e" -Logging = "56ddb016-857b-54e1-b83d-db4d58db5568" OrdinaryDiffEqLowStorageRK = "b0944070-b475-4768-8dec-fb6eb410534d" OrdinaryDiffEqSymplecticRK = "fa646aed-7ef9-47eb-84c4-9443fc8cbfa8" Plots = "91a5bcdd-55d7-5caf-9e0b-520d859cae80" @@ -27,7 +26,6 @@ GLM = "1.9" Glob = "1.3" JSON = "1" LinearAlgebra = "1" -Logging = "1" OrdinaryDiffEqLowStorageRK = "3" OrdinaryDiffEqSymplecticRK = "2" Plots = "1" diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl index edd9daf700..c4fb5ef6bd 100644 --- a/test/schemes/structure/fluid_interaction.jl +++ b/test/schemes/structure/fluid_interaction.jl @@ -1,5 +1,3 @@ -using Logging: NullLogger, with_logger - @testset verbose=true "Structure-fluid force balance" begin particle_spacing = 1.0 smoothing_kernel = SchoenbergCubicSplineKernel{2}() @@ -76,9 +74,15 @@ using Logging: NullLogger, with_logger clamped_particles, boundary_model) end - semi = with_logger(NullLogger()) do - Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) + semi = if structure_system isa TotalLagrangianSPHSystem + @test_logs (:info, + r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin + Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end + else + @test_logs Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) end ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) fluid, structure = ode.p.semi.systems From ffca1340bba2a733fbd52b7de7a082f82d4a2252 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 13:45:52 +0200 Subject: [PATCH 09/46] Explain reaction-force regression fixtures and invariants --- test/schemes/structure/fluid_interaction.jl | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl index c4fb5ef6bd..d4be91c49c 100644 --- a/test/schemes/structure/fluid_interaction.jl +++ b/test/schemes/structure/fluid_interaction.jl @@ -1,4 +1,6 @@ @testset verbose=true "Structure-fluid force balance" begin + # One fluid/structure pair isolates cross-system forces from elastic forces. + # At r/h = 1.5 the cubic-spline gradient is nonzero and has a simple exact value. particle_spacing = 1.0 smoothing_kernel = SchoenbergCubicSplineKernel{2}() smoothing_length = 1.0 @@ -7,6 +9,8 @@ state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) + # Exercise fluid-side prefactors as well as the reaction sign: Akinci changes + # viscosity scaling, kernel corrections need not be odd, and EDAC reduces pressure. configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), (:wcsph, nothing, ContinuityDensity()), (:wcsph, AkinciFreeSurfaceCorrection(reference_density), @@ -17,6 +21,8 @@ (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) # Zero pressure isolates viscosity for approaching and receding particles. # Nonzero pressure checks that pressure and viscosity accumulate consistently. + # The structure lies to the right: positive fluid vx approaches it, while + # negative vx must deactivate Monaghan artificial viscosity (but not physical viscosity). fluid_states = ((velocity=(1.0, 0.5), density=reference_density), (velocity=(-1.0, -0.5), density=reference_density), (velocity=(1.0, 0.5), density=1005.0)) @@ -57,6 +63,8 @@ :edac_pressure_reduction) end + # Material mass is twice hydrodynamic mass. Using the wrong mass when + # converting reaction force to TLSPH acceleration cannot pass this check. structure_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), velocity=zeros(2, 1), mass=[structure_density], density=[structure_density], particle_spacing) @@ -74,6 +82,8 @@ clamped_particles, boundary_model) end + # TLS setup reports its deep copy; other setup logs, including warnings, + # are unexpected rather than being hidden by a null logger. semi = if structure_system isa TotalLagrangianSPHSystem @test_logs (:info, r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin @@ -88,6 +98,8 @@ fluid, structure = ode.p.semi.systems v_ode, u_ode = ode.u0.x dv_ode = zero(v_ode) + # Run the normal RHS update sequence to populate boundary pressures, + # ghost velocities, and fluid correction/average-pressure caches. TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) @@ -97,6 +109,8 @@ dv_fluid = zero(v_fluid) TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, fluid, structure, semi) + # Newton's third law uses the fluid particle's mass, regardless of the + # structure's material mass or how it stores its resultant force. expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] if correction isa KernelCorrection || @@ -143,6 +157,7 @@ end if structure isa RigidBodySystem + # kick! must carry the particle reaction through to the body resultant. @test isapprox(structure.resultant_force[], expected_force; rtol=sqrt(eps()), atol=sqrt(eps())) else @@ -156,6 +171,7 @@ rtol=sqrt(eps()), atol=sqrt(eps())) if structure_kind == :tlsph + # An integrated particle must receive the same reaction in the full RHS. dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) @test isapprox(structure.mass[1] * dv_structure[1:2, 1], expected_force; rtol=sqrt(eps()), atol=sqrt(eps())) From 3bf2ff52b45556860af9f64ef4792b0ad7d97480 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 14:30:10 +0200 Subject: [PATCH 10/46] Place fluid pair operators and force writers in their owning schemes --- src/schemes/fluid/interaction.jl | 61 ++++++++++++++ src/schemes/schemes.jl | 3 +- src/schemes/structure/rigid_body/rhs.jl | 11 +++ src/schemes/structure/structure.jl | 82 ------------------- .../structure/total_lagrangian_sph/rhs.jl | 11 +++ 5 files changed, 85 insertions(+), 83 deletions(-) create mode 100644 src/schemes/fluid/interaction.jl diff --git a/src/schemes/fluid/interaction.jl b/src/schemes/fluid/interaction.jl new file mode 100644 index 0000000000..dc629bd4b2 --- /dev/null +++ b/src/schemes/fluid/interaction.jl @@ -0,0 +1,61 @@ +# Physical fluid-side pair operators shared with structure reactions. +@inline average_pressure(system, particle) = zero(eltype(system)) + +@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) + +@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, + rho_a, rho_b) + return free_surface_correction(system_correction(system), system, rho_a, rho_b) +end + +@inline function interaction_zero_distance(system, neighbor_system) + return sqrt(eps(initial_smoothing_length(system)^2)) +end + +@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, + neighbor_system) + return sqrt(eps(compact_support(system, neighbor_system)^2)) +end + +@inline function skip_fluid_pair(system, distance, support, almostzero) + return distance > support || (skip_zero_distance(system) && distance < almostzero) +end + +@inline function sum_interaction_contributions(a, b) + dv_a, drho_a = a + dv_b, drho_b = b + return dv_a + dv_b, drho_a + drho_b +end + +# Evaluate physical acceleration in fluid-first order. Shifting transport terms +# are not interfacial traction and do not contribute to the structural load. +@propagate_inbounds function fluid_pair_acceleration(particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, correction) + p_avg = average_pressure(particle_system, particle) + viscosity_correction, pressure_correction, + surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) + dv_pressure = pressure_acceleration(particle_system, neighbor_system, + particle, neighbor, m_a, m_b, + p_a - p_avg, p_b - p_avg, rho_a, rho_b, + pos_diff, distance, grad_kernel, correction) + dv_particle = dv_pressure * pressure_correction + dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, pos_diff, distance, sound_speed, + m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, + viscosity_correction) + surface_tension_a = surface_tension_model(particle_system) + surface_tension_b = surface_tension_model(neighbor_system) + dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, + particle_system, neighbor_system, particle, + neighbor, + pos_diff, distance, rho_a, rho_b, grad_kernel, + surface_tension_correction) + return add_dv_adhesion(dv_particle, surface_tension_a, + particle_system, neighbor_system, particle, neighbor, + pos_diff, distance) +end diff --git a/src/schemes/schemes.jl b/src/schemes/schemes.jl index 8330312467..38479fbddb 100644 --- a/src/schemes/schemes.jl +++ b/src/schemes/schemes.jl @@ -7,7 +7,6 @@ include("fluid/weakly_compressible_sph/density_diffusion.jl") include("structure/rigid_body/rigid_body.jl") include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") include("structure/discrete_element_method/discrete_element_method.jl") -include("structure/structure.jl") # Monaghan-Kajtar repulsive boundary particles require the `WallBoundarySystem` # and the `TotalLagrangianSPHSystem`. include("boundary/wall_boundary/monaghan_kajtar.jl") @@ -15,10 +14,12 @@ include("boundary/wall_boundary/monaghan_kajtar.jl") include("fluid/implicit_incompressible_sph/implicit_incompressible_sph.jl") # Include rhs for all schemes +include("fluid/interaction.jl") include("fluid/weakly_compressible_sph/rhs.jl") include("fluid/entropically_damped_sph/rhs.jl") include("fluid/implicit_incompressible_sph/rhs.jl") include("boundary/wall_boundary/rhs.jl") +include("structure/structure.jl") include("structure/rigid_body/rhs.jl") include("structure/total_lagrangian_sph/rhs.jl") include("structure/discrete_element_method/rhs.jl") diff --git a/src/schemes/structure/rigid_body/rhs.jl b/src/schemes/structure/rigid_body/rhs.jl index 48fc8d26c8..ceb9500c7c 100644 --- a/src/schemes/structure/rigid_body/rhs.jl +++ b/src/schemes/structure/rigid_body/rhs.jl @@ -33,6 +33,17 @@ function interact!(dv, v_particle_system, u_particle_system, particle_system, neighbor_system, semi) end +# Accumulate pair forces before reducing them to rigid-body resultants. +@propagate_inbounds function write_fluid_force!(dv, particle_system::RigidBodySystem, + force_particle, particle) + force_per_particle = particle_system.force_per_particle + for i in 1:ndims(particle_system) + force_per_particle[i, particle] += force_particle[i] + end + + return dv +end + # Reduce the accumulated fluid forces to rigid-body resultants and apply the corresponding # translational and rotational acceleration to every rigid particle. function apply_resultant_force_and_torque!(dv, particle_system::RigidBodySystem, semi) diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index b1dd8583d2..160cc6ea6d 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -1,86 +1,4 @@ # Shared structure-fluid interaction helpers used by multiple structure schemes. -@propagate_inbounds function write_fluid_force!(dv, - particle_system::TotalLagrangianSPHSystem, - force_particle, particle) - material_mass = particle_system.mass[particle] - for i in 1:ndims(particle_system) - dv[i, particle] += force_particle[i] / material_mass - end - - return dv -end - -@propagate_inbounds function write_fluid_force!(dv, particle_system::RigidBodySystem, - force_particle, particle) - force_per_particle = particle_system.force_per_particle - for i in 1:ndims(particle_system) - force_per_particle[i, particle] += force_particle[i] - end - - return dv -end - -@inline average_pressure(system, particle) = zero(eltype(system)) - -@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) - -@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, - rho_a, rho_b) - return free_surface_correction(system_correction(system), system, rho_a, rho_b) -end - -@inline function interaction_zero_distance(system, neighbor_system) - return sqrt(eps(initial_smoothing_length(system)^2)) -end - -@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, - neighbor_system) - return sqrt(eps(compact_support(system, neighbor_system)^2)) -end - -@inline function skip_fluid_pair(system, distance, support, almostzero) - return distance > support || (skip_zero_distance(system) && distance < almostzero) -end - -@inline function sum_interaction_contributions(a, b) - dv_a, drho_a = a - dv_b, drho_b = b - return dv_a + dv_b, drho_a + drho_b -end - -# Evaluate physical acceleration in fluid-first order. Shifting transport terms -# are not interfacial traction and do not contribute to the structural load. -@propagate_inbounds function fluid_pair_acceleration(particle_system, neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, - v_a, v_b, pos_diff, distance, - sound_speed, grad_kernel, correction) - p_avg = average_pressure(particle_system, particle) - viscosity_correction, pressure_correction, - surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, m_a, m_b, - p_a - p_avg, p_b - p_avg, rho_a, rho_b, - pos_diff, distance, grad_kernel, correction) - dv_particle = dv_pressure * pressure_correction - dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, sound_speed, - m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, - viscosity_correction) - surface_tension_a = surface_tension_model(particle_system) - surface_tension_b = surface_tension_model(neighbor_system) - dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, - particle_system, neighbor_system, particle, - neighbor, - pos_diff, distance, rho_a, rho_b, grad_kernel, - surface_tension_correction) - return add_dv_adhesion(dv_particle, surface_tension_a, - particle_system, neighbor_system, particle, neighbor, - pos_diff, distance) -end - function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index 3fa8b6ea86..be6d063852 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -117,6 +117,17 @@ function interact!(dv, v_particle_system, u_particle_system, particle_system, neighbor_system, semi; eachparticle) end +@propagate_inbounds function write_fluid_force!(dv, + particle_system::TotalLagrangianSPHSystem, + force_particle, particle) + material_mass = particle_system.mass[particle] + for i in 1:ndims(particle_system) + dv[i, particle] += force_particle[i] / material_mass + end + + return dv +end + # Structure-boundary interaction function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, From 4b114432a0544725fbb321266c590924240445ff Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 15:29:34 +0200 Subject: [PATCH 11/46] Keep reaction-only pair calculation in structure-fluid coupling --- src/schemes/fluid/interaction.jl | 61 ------------- src/schemes/schemes.jl | 3 +- .../{structure.jl => fluid_interaction.jl} | 87 +++++++++++++++++-- 3 files changed, 79 insertions(+), 72 deletions(-) delete mode 100644 src/schemes/fluid/interaction.jl rename src/schemes/structure/{structure.jl => fluid_interaction.jl} (56%) diff --git a/src/schemes/fluid/interaction.jl b/src/schemes/fluid/interaction.jl deleted file mode 100644 index dc629bd4b2..0000000000 --- a/src/schemes/fluid/interaction.jl +++ /dev/null @@ -1,61 +0,0 @@ -# Physical fluid-side pair operators shared with structure reactions. -@inline average_pressure(system, particle) = zero(eltype(system)) - -@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) - -@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, - rho_a, rho_b) - return free_surface_correction(system_correction(system), system, rho_a, rho_b) -end - -@inline function interaction_zero_distance(system, neighbor_system) - return sqrt(eps(initial_smoothing_length(system)^2)) -end - -@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, - neighbor_system) - return sqrt(eps(compact_support(system, neighbor_system)^2)) -end - -@inline function skip_fluid_pair(system, distance, support, almostzero) - return distance > support || (skip_zero_distance(system) && distance < almostzero) -end - -@inline function sum_interaction_contributions(a, b) - dv_a, drho_a = a - dv_b, drho_b = b - return dv_a + dv_b, drho_a + drho_b -end - -# Evaluate physical acceleration in fluid-first order. Shifting transport terms -# are not interfacial traction and do not contribute to the structural load. -@propagate_inbounds function fluid_pair_acceleration(particle_system, neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, rho_b, - v_a, v_b, pos_diff, distance, - sound_speed, grad_kernel, correction) - p_avg = average_pressure(particle_system, particle) - viscosity_correction, pressure_correction, - surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, m_a, m_b, - p_a - p_avg, p_b - p_avg, rho_a, rho_b, - pos_diff, distance, grad_kernel, correction) - dv_particle = dv_pressure * pressure_correction - dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, sound_speed, - m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, - viscosity_correction) - surface_tension_a = surface_tension_model(particle_system) - surface_tension_b = surface_tension_model(neighbor_system) - dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, - particle_system, neighbor_system, particle, - neighbor, - pos_diff, distance, rho_a, rho_b, grad_kernel, - surface_tension_correction) - return add_dv_adhesion(dv_particle, surface_tension_a, - particle_system, neighbor_system, particle, neighbor, - pos_diff, distance) -end diff --git a/src/schemes/schemes.jl b/src/schemes/schemes.jl index 38479fbddb..d2b3d1f4fb 100644 --- a/src/schemes/schemes.jl +++ b/src/schemes/schemes.jl @@ -14,12 +14,11 @@ include("boundary/wall_boundary/monaghan_kajtar.jl") include("fluid/implicit_incompressible_sph/implicit_incompressible_sph.jl") # Include rhs for all schemes -include("fluid/interaction.jl") include("fluid/weakly_compressible_sph/rhs.jl") include("fluid/entropically_damped_sph/rhs.jl") include("fluid/implicit_incompressible_sph/rhs.jl") include("boundary/wall_boundary/rhs.jl") -include("structure/structure.jl") +include("structure/fluid_interaction.jl") include("structure/rigid_body/rhs.jl") include("structure/total_lagrangian_sph/rhs.jl") include("structure/discrete_element_method/rhs.jl") diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/fluid_interaction.jl similarity index 56% rename from src/schemes/structure/structure.jl rename to src/schemes/structure/fluid_interaction.jl index 160cc6ea6d..9bbc47955e 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/fluid_interaction.jl @@ -1,4 +1,69 @@ -# Shared structure-fluid interaction helpers used by multiple structure schemes. +# Structure-fluid coupling shared by TLSPH and rigid-body systems. +@inline average_pressure(system, particle) = zero(eltype(system)) + +@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) + +@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, + rho_a, rho_b) + return free_surface_correction(system_correction(system), system, rho_a, rho_b) +end + +@inline function interaction_zero_distance(system, neighbor_system) + return sqrt(eps(initial_smoothing_length(system)^2)) +end + +@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, + neighbor_system) + return sqrt(eps(compact_support(system, neighbor_system)^2)) +end + +@inline function skip_fluid_pair(system, distance, support, almostzero) + return distance > support || (skip_zero_distance(system) && distance < almostzero) +end + +@inline function sum_interaction_contributions(a, b) + dv_a, drho_a = a + dv_b, drho_b = b + return dv_a + dv_b, drho_a + drho_b +end + +# Evaluate the fluid particle's physical acceleration to assemble its structural +# reaction. Shifting transport terms are excluded from the interfacial traction. +@propagate_inbounds function physical_fluid_pair_acceleration(particle_system, + neighbor_system, + v_particle_system, + v_neighbor_system, + particle, neighbor, + m_a, m_b, p_a, p_b, rho_a, + rho_b, + v_a, v_b, pos_diff, distance, + sound_speed, grad_kernel, + correction) + p_avg = average_pressure(particle_system, particle) + viscosity_correction, pressure_correction, + surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) + dv_pressure = pressure_acceleration(particle_system, neighbor_system, + particle, neighbor, m_a, m_b, + p_a - p_avg, p_b - p_avg, rho_a, rho_b, + pos_diff, distance, grad_kernel, correction) + dv_particle = dv_pressure * pressure_correction + dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, + v_particle_system, v_neighbor_system, + particle, neighbor, pos_diff, distance, sound_speed, + m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, + viscosity_correction) + surface_tension_a = surface_tension_model(particle_system) + surface_tension_b = surface_tension_model(neighbor_system) + dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, + particle_system, neighbor_system, particle, + neighbor, + pos_diff, distance, rho_a, rho_b, grad_kernel, + surface_tension_correction) + return add_dv_adhesion(dv_particle, surface_tension_a, + particle_system, neighbor_system, particle, neighbor, + pos_diff, distance) +end + function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, @@ -62,14 +127,18 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # Fluid-first ordering preserves the actual fluid force, including the # approaching-particle condition of artificial viscosity. - dv_fluid = @inbounds fluid_pair_acceleration(neighbor_system, particle_system, - v_neighbor_system, - v_particle_system, - neighbor, particle, - m_b, m_a, p_b, p_a, rho_b, rho_a, - v_b, v_a, -pos_diff, distance, - sound_speed, grad_kernel_fluid, - correction) + dv_fluid = @inbounds physical_fluid_pair_acceleration(neighbor_system, + particle_system, + v_neighbor_system, + v_particle_system, + neighbor, particle, + m_b, m_a, p_b, p_a, rho_b, + rho_a, + v_b, v_a, -pos_diff, + distance, + sound_speed, + grad_kernel_fluid, + correction) return -m_b * dv_fluid, drho_particle end From 0f0fa1474feb595890252934b6b004a4e6781a9d Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 16:17:26 +0200 Subject: [PATCH 12/46] Document structure-fluid pair conventions and reaction assembly --- src/schemes/structure/fluid_interaction.jl | 58 ++++++++++++++++++++-- 1 file changed, 54 insertions(+), 4 deletions(-) diff --git a/src/schemes/structure/fluid_interaction.jl b/src/schemes/structure/fluid_interaction.jl index 9bbc47955e..4ec5aa3bcb 100644 --- a/src/schemes/structure/fluid_interaction.jl +++ b/src/schemes/structure/fluid_interaction.jl @@ -1,6 +1,10 @@ # Structure-fluid coupling shared by TLSPH and rigid-body systems. +# EDAC provides its own particle-local pressure average. Other fluid schemes keep +# their absolute pressures by subtracting zero in the physical pair operator. @inline average_pressure(system, particle) = zero(eltype(system)) +# Match the fluid scheme's force prefactors: EDAC/IISPH use unity, while WCSPH +# delegates to its configured free-surface correction for the two pair densities. @inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) @inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, @@ -8,6 +12,9 @@ return free_surface_correction(system_correction(system), system, rho_a, rho_b) end +# Reproduce the fluid RHS's near-zero tolerance exactly. A different tolerance on +# the reaction side would accept a pair skipped by the fluid, or vice versa. +# EDAC/IISPH scale eps with h^2; WCSPH uses its pair support radius squared. @inline function interaction_zero_distance(system, neighbor_system) return sqrt(eps(initial_smoothing_length(system)^2)) end @@ -18,10 +25,14 @@ end end @inline function skip_fluid_pair(system, distance, support, almostzero) + # Corrected kernels can have a finite, nonzero gradient at coincident particles. + # Honor their skip_zero_distance policy instead of dropping all zero-distance pairs. return distance > support || (skip_zero_distance(system) && distance < almostzero) end @inline function sum_interaction_contributions(a, b) + # Reduce a vector momentum/force contribution and a scalar density rate together + # without packing quantities with different meanings into one static vector. dv_a, drho_a = a dv_b, drho_b = b return dv_a + dv_b, drho_a + drho_b @@ -29,6 +40,9 @@ end # Evaluate the fluid particle's physical acceleration to assemble its structural # reaction. Shifting transport terms are excluded from the interfacial traction. +# In this operator a is the fluid particle and b is its boundary/structure neighbor: +# pos_diff = x_f - x_s and grad_kernel is evaluated at f in that same direction. +# The return value is acceleration of f; the caller applies -m_f to obtain force on s. @propagate_inbounds function physical_fluid_pair_acceleration(particle_system, neighbor_system, v_particle_system, @@ -39,6 +53,8 @@ end v_a, v_b, pos_diff, distance, sound_speed, grad_kernel, correction) + # EDAC subtracts the fluid particle's local mean from both pressures. Using the + # boundary's own mean (or unreduced pressure) would change the fluid's pair force. p_avg = average_pressure(particle_system, particle) viscosity_correction, pressure_correction, surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) @@ -47,11 +63,16 @@ end p_a - p_avg, p_b - p_avg, rho_a, rho_b, pos_diff, distance, grad_kernel, correction) dv_particle = dv_pressure * pressure_correction + # Keep systems, velocities, displacement, and gradient fluid-first as one unit. + # The viscosity helper supplies model-specific ghost velocities where needed; + # artificial viscosity must see the same approaching-particle test as the fluid RHS. dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, v_particle_system, v_neighbor_system, particle, neighbor, pos_diff, distance, sound_speed, m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, viscosity_correction) + # Surface-force dispatch skips inapplicable models. In particular, rigid-body + # adhesion uses the same fluid-frame displacement before the single reaction sign. surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, @@ -64,6 +85,11 @@ end pos_diff, distance) end +# Here the traversal labels are reversed: a=s (structure), b=f (fluid), and the +# neighbor search returns pos_diff=x_s-x_f. Physical operators below are evaluated +# with fluid-first arguments and r_fs=-pos_diff, then F_s=-m_f*a_f^physical. +# The default particle range advances free particles; callers such as mechanical +# work calculation can explicitly include clamped particles to recover their loads. function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, @@ -72,18 +98,25 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, sound_speed = system_sound_speed(neighbor_system) correction = system_correction(neighbor_system) + # Coupling follows the current spatial configuration, unlike TLSPH elastic + # self-interaction, whose neighborhood is built in the initial configuration. system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # Use the same pair cutoffs as the fluid RHS. + # The reverse search may expose a different neighbor set. Limit the reaction + # operator to the same support and near-zero predicate used by the fluid RHS. compact_support_ = compact_support(neighbor_system, particle_system) almostzero = interaction_zero_distance(neighbor_system, particle_system) + # Each task owns one structural particle. Neighbor contributions remain local + # until reduction, so force_per_particle and dv need no per-pair atomic updates. @threaded semi for particle in eachparticle # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles # corresponding to the rest density of the fluid and not the material density. + # This mass/pressure/density is the boundary state used by the forward fluid + # interaction. Material mass enters only when writing TLSPH acceleration. m_a = @inbounds hydrodynamic_mass(particle_system, particle) rho_a = @inbounds current_density(v_particle_system, particle_system, particle) v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) @@ -116,11 +149,16 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, distance, m_b, rho_a, rho_b, v_a, v_b) - # Corrected gradients need not be odd; evaluate the fluid-side gradient. + # Evaluate grad_f W(r_fs) directly at the fluid particle. Neighborhood + # corrections contain particle-local terms, so -grad_f W(r_sf) need not + # equal grad_f W(-r_sf). Negating a structure-oriented corrected gradient + # would therefore give the wrong pressure/viscous reaction. grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, distance, neighbor) - # Use the hydrodynamic pressure defined by the structure's boundary model. + # Read fluid pressure first, then use the same boundary-pressure dispatch + # as the forward interaction. Pair-local mirroring, where supported, + # needs p_f even though the traversal visits the structure particle first. p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, p_b) @@ -140,9 +178,14 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, grad_kernel_fluid, correction) + # m_b is fluid mass in this traversal: Newton's third law transfers the + # opposite physical force, not merely an acceleration with reversed sign. return -m_b * dv_fluid, drho_particle end + # TLS divides the accumulated force by material mass; rigid bodies retain + # particle forces for the later resultant/torque reduction. Boundary density + # is a separate scalar state derivative and is written through its own dispatch. @inbounds write_fluid_force!(dv, particle_system, force_particle_, particle) @inbounds write_drho_particle!(dv, particle_system, drho_particle_, particle) @@ -156,6 +199,8 @@ end neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, v_a, v_b) + # Pressure-extrapolated and summation-density boundaries have no density ODE + # contribution; only the ContinuityDensity specialization below evolves rho_s. return drho_particle end @@ -165,7 +210,9 @@ end neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, v_a, v_b) - # Boundary density retains its existing structure-first gradient. + # Continuity has structure-first orientation: (v_s-v_f) dot grad_s W. This + # reaction-force fix retains the existing density operator, evaluated with the + # neighboring fluid kernel and r_sf here, independently of the force sign above. grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, neighbor) @@ -175,6 +222,7 @@ end end @inline function write_drho_particle!(dv, ::AbstractSystem, drho_particle, particle) + # A boundary model without an integrated density must not modify a velocity row. return dv end @@ -182,6 +230,8 @@ end ::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, drho_particle, particle) + # ContinuityDensity appends hydrodynamic density to v; momentum occupies the + # preceding rows. Add rather than overwrite when several fluid systems contribute. dv[end, particle] += drho_particle return dv From 60504da7b9940217bbf786d00b507861db785e17 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 17:29:48 +0200 Subject: [PATCH 13/46] Centralize and reuse interaction near-zero distance tolerances --- src/general/abstract_system.jl | 14 +++++++++ src/general/corrections.jl | 12 +++----- src/preprocessing/particle_packing/rhs.jl | 10 ++----- src/schemes/boundary/open_boundary/rhs.jl | 10 ++----- src/schemes/boundary/wall_boundary/rhs.jl | 10 ++----- .../fluid/entropically_damped_sph/rhs.jl | 10 ++----- .../fluid/implicit_incompressible_sph/rhs.jl | 10 ++----- .../fluid/weakly_compressible_sph/rhs.jl | 9 ++---- .../fluid/weakly_compressible_sph/system.jl | 7 +++++ .../structure/discrete_element_method/rhs.jl | 9 ++---- src/schemes/structure/fluid_interaction.jl | 12 -------- .../structure/total_lagrangian_sph/rhs.jl | 10 ++----- .../structure/total_lagrangian_sph/system.jl | 10 ++----- test/general/general.jl | 1 + test/general/interaction_zero_distance.jl | 29 +++++++++++++++++++ 15 files changed, 73 insertions(+), 90 deletions(-) create mode 100644 test/general/interaction_zero_distance.jl diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index f52953d7e8..4de0b5d7ee 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -139,6 +139,20 @@ end return skip_zero_distance(system_correction(system)) end +# Distances are compared with roundoff in squared coordinates. For a length scale +# ell, use sqrt(eps(ell^2)), which differs from eps(ell). The scalar overload lets +# operators retain an explicit scale, e.g. DEM radius or correction-search support. +@inline function interaction_zero_distance(length_scale::Real) + return sqrt(eps(length_scale^2)) +end + +# Pair operators normally use the particle system's initial smoothing length. +# Scheme-specific overrides select their own scale, so forward fluid interactions +# and structure reactions share exactly the same near-zero tolerance. +@inline function interaction_zero_distance(system, neighbor_system) + return interaction_zero_distance(initial_smoothing_length(system)) +end + # Robust/safe version of the function below. In performance-critical code, manually check # the kernel support, call `skip_zero_distance` and then `smoothing_kernel_grad_unsafe`. @inline function smoothing_kernel_grad(system, pos_diff, distance, particle) diff --git a/src/general/corrections.jl b/src/general/corrections.jl index d97eeaf341..d092190d09 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -217,14 +217,9 @@ function compute_correction_values!(system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Raw kernel-correction coefficients use the kernel's smoothing-length scale. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + almostzero = interaction_zero_distance(h) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, @@ -370,7 +365,8 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, end neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - almostzero = sqrt(eps(compact_support(system, neighbor_system)^2)) + # Gradient-matrix assembly retains its search-support scale for all systems. + almostzero = interaction_zero_distance(compact_support(system, neighbor_system)) foreach_point_neighbor(system, neighbor_system, coordinates, neighbor_coords, semi) do particle, neighbor, pos_diff, distance diff --git a/src/preprocessing/particle_packing/rhs.jl b/src/preprocessing/particle_packing/rhs.jl index 807fba072f..6f98a2e3a6 100644 --- a/src/preprocessing/particle_packing/rhs.jl +++ b/src/preprocessing/particle_packing/rhs.jl @@ -5,14 +5,8 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + # Packing uses the shared smoothing-length tolerance before its unsafe gradient. + almostzero = interaction_zero_distance(system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 573d0d0914..4bfec64b36 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -10,14 +10,8 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + # The open-boundary gradient uses its own smoothing-length tolerance. + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, diff --git a/src/schemes/boundary/wall_boundary/rhs.jl b/src/schemes/boundary/wall_boundary/rhs.jl index 0edf8642ad..bbd01fd9ee 100644 --- a/src/schemes/boundary/wall_boundary/rhs.jl +++ b/src/schemes/boundary/wall_boundary/rhs.jl @@ -19,14 +19,8 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + # Boundary continuity retains the boundary system's smoothing-length tolerance. + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index d4c526f175..cad353b503 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -11,14 +11,8 @@ function interact!(dv, v_particle_system, u_particle_system, surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + # Use the shared scheme policy before evaluating unsafe pair operators. + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 6e8b5d18fa..d23e9c9b6a 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -10,14 +10,8 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + # Use the shared scheme policy before evaluating unsafe pair operators. + almostzero = interaction_zero_distance(particle_system, neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index f09f56d886..a557cd35e9 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,13 +19,8 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient divides - # by zero. To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the compact support `c`, `distance^2` is in - # the order of `c^2`, so we need to check `distance < sqrt(eps(c^2))`. - # Note that `sqrt(eps(c^2)) != eps(c)`. - compact_support_ = compact_support(particle_system, neighbor_system) - almostzero = sqrt(eps(compact_support_^2)) + # Use the shared scheme policy before evaluating unsafe pair operators. + almostzero = interaction_zero_distance(particle_system, neighbor_system) @threaded semi for particle in eachparticle # We are looping over the particles of `particle_system`, so it is guaranteed diff --git a/src/schemes/fluid/weakly_compressible_sph/system.jl b/src/schemes/fluid/weakly_compressible_sph/system.jl index eea0607d7d..f967776742 100644 --- a/src/schemes/fluid/weakly_compressible_sph/system.jl +++ b/src/schemes/fluid/weakly_compressible_sph/system.jl @@ -284,6 +284,13 @@ end @inline system_sound_speed(system::WeaklyCompressibleSPHSystem) = sound_speed(system.state_equation) +# WCSPH scales the near-zero check with its pair support rather than h. Keep this +# policy with the scheme and reuse it for both its RHS and the structural reaction. +@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, + neighbor_system) + return interaction_zero_distance(compact_support(system, neighbor_system)) +end + @inline shifting_technique(system::WeaklyCompressibleSPHSystem) = system.shifting_technique @inline density_diffusion(system::WeaklyCompressibleSPHSystem) = system.density_diffusion diff --git a/src/schemes/structure/discrete_element_method/rhs.jl b/src/schemes/structure/discrete_element_method/rhs.jl index ee16f2a63d..c663d4f1dd 100644 --- a/src/schemes/structure/discrete_element_method/rhs.jl +++ b/src/schemes/structure/discrete_element_method/rhs.jl @@ -6,14 +6,9 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the radius `r`, `distance^2` is in - # the order of `r^2`, so we need to check `distance < sqrt(eps(r^2))`. - # Note that `sqrt(eps(r^2)) != eps(r)`. + # DEM has no smoothing length: retain the maximum particle radius as its scale. r = maximum(particle_system.radius) - almostzero = sqrt(eps(r^2)) + almostzero = interaction_zero_distance(r) foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; diff --git a/src/schemes/structure/fluid_interaction.jl b/src/schemes/structure/fluid_interaction.jl index 4ec5aa3bcb..0d036d4a41 100644 --- a/src/schemes/structure/fluid_interaction.jl +++ b/src/schemes/structure/fluid_interaction.jl @@ -12,18 +12,6 @@ return free_surface_correction(system_correction(system), system, rho_a, rho_b) end -# Reproduce the fluid RHS's near-zero tolerance exactly. A different tolerance on -# the reaction side would accept a pair skipped by the fluid, or vice versa. -# EDAC/IISPH scale eps with h^2; WCSPH uses its pair support radius squared. -@inline function interaction_zero_distance(system, neighbor_system) - return sqrt(eps(initial_smoothing_length(system)^2)) -end - -@inline function interaction_zero_distance(system::WeaklyCompressibleSPHSystem, - neighbor_system) - return sqrt(eps(compact_support(system, neighbor_system)^2)) -end - @inline function skip_fluid_pair(system, distance, support, almostzero) # Corrected kernels can have a finite, nonzero gradient at coincident particles. # Honor their skip_zero_distance policy instead of dropping all zero-distance pairs. diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index be6d063852..83dc76220f 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -21,14 +21,8 @@ end neighborhood_search = get_neighborhood_search(system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + # Elastic self-interaction uses the TLSPH smoothing-length tolerance. + almostzero = interaction_zero_distance(system, system) @threaded semi for particle in eachparticle # We are looping over the particles of `system`, so it is guaranteed diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index ceca948796..560ceedaa7 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -525,14 +525,8 @@ end @inline function calc_deformation_grad!(deformation_grad, system, semi) (; mass, material_density) = system - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. - h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + # Use the same TLSPH tolerance as elastic self-interaction in the RHS. + almostzero = interaction_zero_distance(system, system) # Loop over all pairs of particles and neighbors within the kernel cutoff initial_coords = initial_coordinates(system) diff --git a/test/general/general.jl b/test/general/general.jl index 28aae03333..add44cc402 100644 --- a/test/general/general.jl +++ b/test/general/general.jl @@ -1,5 +1,6 @@ include("initial_condition.jl") include("smoothing_kernels.jl") +include("interaction_zero_distance.jl") include("density_calculator.jl") include("semidiscretization.jl") include("interpolation.jl") diff --git a/test/general/interaction_zero_distance.jl b/test/general/interaction_zero_distance.jl new file mode 100644 index 0000000000..fd1cb2f9ca --- /dev/null +++ b/test/general/interaction_zero_distance.jl @@ -0,0 +1,29 @@ +@testset verbose=true "Shared near-zero interaction tolerance" begin + for T in (Float32, Float64) + # IEEE spacing at scale 1 gives these exact references. Scaling the length + # by two multiplies the squared-coordinate tolerance's square root by two. + unit_tolerance = T == Float64 ? ldexp(one(T), -26) : ldexp(sqrt(T(2)), -12) + @test TrixiParticles.interaction_zero_distance(one(T)) === unit_tolerance + @test TrixiParticles.interaction_zero_distance(T(2)) === T(2) * unit_tolerance + + # A generic system uses h, independent of the neighbor's smoothing length. + system = (; smoothing_length=one(T)) + neighbor = (; smoothing_length=T(4)) + @test TrixiParticles.interaction_zero_distance(system, neighbor) === unit_tolerance + + # Cubic-spline WCSPH support is 2h. Its override must therefore differ from + # the generic h policy, including for single-precision simulations. + ic = InitialCondition(; coordinates=zeros(T, 2, 1), density=T[1000], + mass=T[1], particle_spacing=one(T)) + eos = StateEquationCole(; sound_speed=T(10), reference_density=T(1000), exponent=1) + fluid = WeaklyCompressibleSPHSystem(ic; + smoothing_kernel=SchoenbergCubicSplineKernel{2}(), + smoothing_length=one(T), state_equation=eos, + density_calculator=ContinuityDensity()) + @test TrixiParticles.interaction_zero_distance(fluid, system) === + T(2) * unit_tolerance + distance = T(1.5) * unit_tolerance + @test distance > TrixiParticles.interaction_zero_distance(system, neighbor) + @test distance < TrixiParticles.interaction_zero_distance(fluid, system) + end +end From 0798ef7702fc6a3711b6f7e820a05553f2e4fb8a Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 20:41:09 +0200 Subject: [PATCH 14/46] Use a uniform relative squared-distance zero criterion --- NEWS.md | 6 ++-- src/general/abstract_system.jl | 4 +-- src/general/corrections.jl | 17 +++++------ src/general/smoothing_kernels.jl | 12 +++----- src/preprocessing/particle_packing/rhs.jl | 11 ++----- src/schemes/boundary/open_boundary/rhs.jl | 11 ++----- src/schemes/boundary/wall_boundary/rhs.jl | 11 ++----- .../fluid/entropically_damped_sph/rhs.jl | 11 ++----- .../fluid/implicit_incompressible_sph/rhs.jl | 11 ++----- src/schemes/fluid/surface_tension.jl | 15 ++++++---- .../density_diffusion.jl | 3 +- .../fluid/weakly_compressible_sph/rhs.jl | 13 ++++---- .../structure/discrete_element_method/rhs.jl | 11 ++----- src/schemes/structure/rigid_body/system.jl | 3 +- .../structure/total_lagrangian_sph/rhs.jl | 11 ++----- .../structure/total_lagrangian_sph/system.jl | 12 +++----- test/general/general.jl | 1 + test/general/near_zero_distance.jl | 30 +++++++++++++++++++ 18 files changed, 92 insertions(+), 101 deletions(-) create mode 100644 test/general/near_zero_distance.jl diff --git a/NEWS.md b/NEWS.md index b8dc88fecd..82b609eebc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -12,8 +12,10 @@ used in the Julia ecosystem. Notable changes will be documented in this file for `MechanicalWorkCalculator`, which can be passed as a custom quantity to `PostprocessCallback` (#1228). -### Important Bugfixes - +### Important Bugfixes + +- Unified near-zero distance checks using the relative squared-distance criterion + `r^2 < eps(typeof(h)) * h^2` across kernels and particle operators. - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index f52953d7e8..539124d803 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -145,9 +145,9 @@ end h = smoothing_length(system, particle) compact_support_ = compact_support(system_smoothing_kernel(system), h) - # Note that `sqrt(eps(h^2)) != eps(h)` + # The same relative squared-distance criterion is used by the pair RHSs. if distance >= compact_support_ || - (skip_zero_distance(system) && distance^2 < eps(h^2)) + (skip_zero_distance(system) && distance^2 < eps(typeof(h)) * h^2) return zero(pos_diff) end diff --git a/src/general/corrections.jl b/src/general/corrections.jl index d97eeaf341..7fe57f71da 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -217,14 +217,9 @@ function compute_correction_values!(system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Coefficient assembly uses the same relative criterion as its kernel. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, @@ -240,7 +235,7 @@ function compute_correction_values!(system, kernel_correction_coefficient[particle] += volume * W # Only consider particles with a distance > 0. - if distance > almostzero + if distance^2 >= zero_distance_squared # Now that we know that `distance` is not zero, we can safely call the # unsafe version of the kernel gradient to avoid redundant zero checks. grad_W = kernel_grad_unsafe(system_smoothing_kernel(system), pos_diff, @@ -370,7 +365,8 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, end neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - almostzero = sqrt(eps(compact_support(system, neighbor_system)^2)) + h = initial_smoothing_length(system) + zero_distance_squared = eps(typeof(h)) * h^2 foreach_point_neighbor(system, neighbor_system, coordinates, neighbor_coords, semi) do particle, neighbor, pos_diff, distance @@ -393,7 +389,8 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, # Skip neighbors with the same position if the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(correction) && distance < almostzero && return + skip_zero_distance(correction) && distance^2 < zero_distance_squared && + return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/general/smoothing_kernels.jl b/src/general/smoothing_kernels.jl index 456d55a13f..6390c2371c 100644 --- a/src/general/smoothing_kernels.jl +++ b/src/general/smoothing_kernels.jl @@ -3,14 +3,10 @@ abstract type AbstractSmoothingKernel{NDIMS} end @inline Base.ndims(::AbstractSmoothingKernel{NDIMS}) where {NDIMS} = NDIMS @inline function kernel_grad(kernel, pos_diff, distance, h) - # For `distance == 0`, the analytical gradient is zero, but the code divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, - # `distance^2` is in the order of `h^2`, hence the comparison `distance^2 < eps(h^2)`. - # Note that this is faster than `distance < sqrt(eps(h^2))`. - # Also note that `sqrt(eps(h^2)) != eps(h)`. + # Use one relative near-zero criterion: (distance/h)^2 < eps(typeof(h)). + # Compare squared lengths directly to avoid a square root in the hot path. compact_support_ = compact_support(kernel, h) - nonzero = distance < compact_support_ && distance^2 > eps(h^2) + nonzero = distance < compact_support_ && distance^2 >= eps(typeof(h)) * h^2 nonzero || return zero(pos_diff) # Now we can use `kernel_grad_unsafe` without worrying about division by zero @@ -37,7 +33,7 @@ end # Zero out result if outside of compact support or if `r` is almost zero # (to avoid division by zero in the unsafe version). compact_support_ = compact_support(kernel, h) - if r < compact_support_ && r^2 > eps(h^2) + if r < compact_support_ && r^2 >= eps(typeof(h)) * h^2 # The unsafe version returns the kernel derivative divided by `r`, # so we multiply it by `r` to get the actual derivative. return kernel_deriv_div_r_unsafe(kernel, r, h) * r diff --git a/src/preprocessing/particle_packing/rhs.jl b/src/preprocessing/particle_packing/rhs.jl index 807fba072f..21f9e7e0b4 100644 --- a/src/preprocessing/particle_packing/rhs.jl +++ b/src/preprocessing/particle_packing/rhs.jl @@ -5,21 +5,16 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Packing uses the same relative kernel-distance criterion. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(system) && distance < almostzero && return + skip_zero_distance(system) && distance^2 < zero_distance_squared && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 573d0d0914..4466e6d1c8 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -10,14 +10,9 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Boundary kernels use the same relative criterion with their own h. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, @@ -28,7 +23,7 @@ function interact!(dv, v_particle_system, u_particle_system, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/boundary/wall_boundary/rhs.jl b/src/schemes/boundary/wall_boundary/rhs.jl index 0edf8642ad..f658662700 100644 --- a/src/schemes/boundary/wall_boundary/rhs.jl +++ b/src/schemes/boundary/wall_boundary/rhs.jl @@ -19,21 +19,16 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Boundary continuity uses the same relative criterion with its own h. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index d4c526f175..70d290e7b6 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -11,14 +11,9 @@ function interact!(dv, v_particle_system, u_particle_system, surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # All kernel interactions use the same relative squared-distance criterion. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, @@ -29,7 +24,7 @@ function interact!(dv, v_particle_system, u_particle_system, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 6e8b5d18fa..c298a178d1 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -10,14 +10,9 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # All kernel interactions use the same relative squared-distance criterion. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -28,7 +23,7 @@ function interact!(dv, v_particle_system, u_particle_system, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/surface_tension.jl b/src/schemes/fluid/surface_tension.jl index 4c86316864..2ba66fbf05 100644 --- a/src/schemes/fluid/surface_tension.jl +++ b/src/schemes/fluid/surface_tension.jl @@ -215,7 +215,8 @@ end (; smoothing_kernel) = particle_system # No cohesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle m_b = hydrodynamic_mass(neighbor_system, neighbor) support_radius = compact_support(smoothing_kernel, @@ -241,7 +242,8 @@ end smoothing_length_ = smoothing_length(particle_system, particle) # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle m_b = hydrodynamic_mass(neighbor_system, neighbor) n_a = surface_normal(particle_system, particle) @@ -267,7 +269,8 @@ end (; surface_tension_coefficient) = surface_tension_a # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle n_a = surface_normal(particle_system, particle) curvature_a = curvature(particle_system, particle) @@ -342,7 +345,8 @@ end (; surface_tension_coefficient) = surface_tension_a # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle S_a = stress_tensor(particle_system, particle) S_b = stress_tensor(neighbor_system, neighbor) @@ -363,7 +367,8 @@ end (; adhesion_coefficient) = neighbor_system # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle # No reason to calculate the adhesion force if adhesion coefficient is near zero abs(adhesion_coefficient) < eps() && return dv_particle diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index e1dd0ce0d3..8eb829fa70 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -219,8 +219,9 @@ end # Density diffusion terms are all zero for distance zero. # If `skip_zero_distance` is `true`, we can assume that this function isn't called # for distance zero because these neighbors have already been skipped. + h = initial_smoothing_length(particle_system) if !skip_zero_distance(particle_system) && - distance^2 < eps(initial_smoothing_length(particle_system)^2) + distance^2 < eps(typeof(h)) * h^2 return drho_particle end diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index f09f56d886..0964a8afe7 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,13 +19,9 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient divides - # by zero. To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the compact support `c`, `distance^2` is in - # the order of `c^2`, so we need to check `distance < sqrt(eps(c^2))`. - # Note that `sqrt(eps(c^2)) != eps(c)`. - compact_support_ = compact_support(particle_system, neighbor_system) - almostzero = sqrt(eps(compact_support_^2)) + # All kernel interactions use the same relative squared-distance criterion. + h = initial_smoothing_length(particle_system) + zero_distance_squared = eps(typeof(h)) * h^2 @threaded semi for particle in eachparticle # We are looping over the particles of `particle_system`, so it is guaranteed @@ -57,7 +53,8 @@ function interact!(dv, v_particle_system, u_particle_system, pos_diff, distance # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return init + skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && + return init # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/structure/discrete_element_method/rhs.jl b/src/schemes/structure/discrete_element_method/rhs.jl index ee16f2a63d..f7849bf190 100644 --- a/src/schemes/structure/discrete_element_method/rhs.jl +++ b/src/schemes/structure/discrete_element_method/rhs.jl @@ -6,14 +6,9 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the radius `r`, `distance^2` is in - # the order of `r^2`, so we need to check `distance < sqrt(eps(r^2))`. - # Note that `sqrt(eps(r^2)) != eps(r)`. + # DEM has no kernel h; apply the same relative criterion to the particle radius. r = maximum(particle_system.radius) - almostzero = sqrt(eps(r^2)) + zero_distance_squared = eps(typeof(r)) * r^2 foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; @@ -21,7 +16,7 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, neighbor, pos_diff, distance - distance < almostzero && return + distance^2 < zero_distance_squared && return # Retrieve particle properties m_a = particle_system.mass[particle] diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index e4b49cea88..c8dd18ac6a 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -293,7 +293,8 @@ end (; adhesion_coefficient) = neighbor_system # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + h = initial_smoothing_length(particle_system) + distance^2 < eps(typeof(h)) * h^2 && return dv_particle abs(adhesion_coefficient) < eps() && return dv_particle diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index 3fa8b6ea86..dd083b6824 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -21,14 +21,9 @@ end neighborhood_search = get_neighborhood_search(system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Elastic interactions use the same relative criterion with the elastic h. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 @threaded semi for particle in eachparticle # We are looping over the particles of `system`, so it is guaranteed @@ -53,7 +48,7 @@ end # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - if skip_zero_distance(system) && initial_distance < almostzero + if skip_zero_distance(system) && initial_distance^2 < zero_distance_squared return zero(initial_pos_diff) end diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index ceca948796..d79a2155a8 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -525,14 +525,9 @@ end @inline function calc_deformation_grad!(deformation_grad, system, semi) (; mass, material_density) = system - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Match the squared-distance criterion used by elastic self-interaction. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff initial_coords = initial_coordinates(system) @@ -556,7 +551,8 @@ end # Skip neighbors with the same position because the kernel gradient is zero. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(system) && initial_distance < almostzero && return zero(L_a) + skip_zero_distance(system) && initial_distance^2 < zero_distance_squared && + return zero(L_a) # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/test/general/general.jl b/test/general/general.jl index 28aae03333..73b6210851 100644 --- a/test/general/general.jl +++ b/test/general/general.jl @@ -1,5 +1,6 @@ include("initial_condition.jl") include("smoothing_kernels.jl") +include("near_zero_distance.jl") include("density_calculator.jl") include("semidiscretization.jl") include("interpolation.jl") diff --git a/test/general/near_zero_distance.jl b/test/general/near_zero_distance.jl new file mode 100644 index 0000000000..00f3a4c736 --- /dev/null +++ b/test/general/near_zero_distance.jl @@ -0,0 +1,30 @@ +@testset verbose=true "Uniform relative near-zero distance" begin + for T in (Float32, Float64), h in T.((0.3, 1.0, 3.5)) + kernel = SchoenbergCubicSplineKernel{2}() + q_tolerance = sqrt(eps(T)) + # These relative distances cover the skipped region and the newly retained + # region between the old support-scaled WCSPH tolerance and the h-based rule. + for factor in T.((0.0, 0.5, 1.5)) + r = factor * q_tolerance * h + pos_diff = SVector(r, zero(T)) + grad = TrixiParticles.kernel_grad(kernel, pos_diff, r, h) + derivative = TrixiParticles.kernel_deriv(kernel, r, h) + if factor < 1 + @test iszero(grad) + @test iszero(derivative) + else + q = r / h + expected = T(10) / (T(7) * T(pi) * h^3) * (-T(3) * q + T(2.25) * q^2) + @test grad[1] ≈ expected + @test derivative ≈ expected + end + end + end + + # The strict '<' rule retains the exact boundary. At h=1 this threshold is + # representable in Float64, exposing inconsistent '<' versus '<=' guards. + kernel = SchoenbergCubicSplineKernel{2}() + r = ldexp(1.0, -26) + @test !iszero(TrixiParticles.kernel_grad(kernel, SVector(r, 0.0), r, 1.0)) + @test !iszero(TrixiParticles.kernel_deriv(kernel, r, 1.0)) +end From fe7d0e394caea1c68f808d57b180befa2e233751 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Fri, 2 Oct 2026 20:44:09 +0200 Subject: [PATCH 15/46] Add uniform near-zero criterion PR reference --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 82b609eebc..e17f3787cf 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,7 +15,7 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Unified near-zero distance checks using the relative squared-distance criterion - `r^2 < eps(typeof(h)) * h^2` across kernels and particle operators. + `r^2 < eps(typeof(h)) * h^2` across kernels and particle operators (#1347). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode From ead055adee679f89663375e2ce098965c50a9057 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Sat, 3 Oct 2026 12:50:44 +0200 Subject: [PATCH 16/46] Trim redundant structure-fluid interaction comments --- src/schemes/structure/fluid_interaction.jl | 71 +++++----------------- 1 file changed, 14 insertions(+), 57 deletions(-) diff --git a/src/schemes/structure/fluid_interaction.jl b/src/schemes/structure/fluid_interaction.jl index f3cd6a0c5c..6f2a1c3db2 100644 --- a/src/schemes/structure/fluid_interaction.jl +++ b/src/schemes/structure/fluid_interaction.jl @@ -1,10 +1,6 @@ # Structure-fluid coupling shared by TLSPH and rigid-body systems. -# EDAC provides its own particle-local pressure average. Other fluid schemes keep -# their absolute pressures by subtracting zero in the physical pair operator. @inline average_pressure(system, particle) = zero(eltype(system)) -# Match the fluid scheme's force prefactors: EDAC/IISPH use unity, while WCSPH -# delegates to its configured free-surface correction for the two pair densities. @inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) @inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, @@ -13,18 +9,13 @@ end @inline function sum_interaction_contributions(a, b) - # Reduce a vector momentum/force contribution and a scalar density rate together - # without packing quantities with different meanings into one static vector. dv_a, drho_a = a dv_b, drho_b = b return dv_a + dv_b, drho_a + drho_b end -# Evaluate the fluid particle's physical acceleration to assemble its structural -# reaction. Shifting transport terms are excluded from the interfacial traction. -# In this operator a is the fluid particle and b is its boundary/structure neighbor: -# pos_diff = x_f - x_s and grad_kernel is evaluated at f in that same direction. -# The return value is acceleration of f; the caller applies -m_f to obtain force on s. +# Fluid-first arguments: a=f, b=s, pos_diff=x_f-x_s, with the gradient evaluated at f. +# Return a_f^physical for the reaction F_s=-m_f*a_f^physical; shifting is excluded. @propagate_inbounds function physical_fluid_pair_acceleration(particle_system, neighbor_system, v_particle_system, @@ -35,8 +26,7 @@ end v_a, v_b, pos_diff, distance, sound_speed, grad_kernel, correction) - # EDAC subtracts the fluid particle's local mean from both pressures. Using the - # boundary's own mean (or unreduced pressure) would change the fluid's pair force. + # EDAC must use the fluid particle's local mean for both pair pressures. p_avg = average_pressure(particle_system, particle) viscosity_correction, pressure_correction, surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) @@ -45,16 +35,12 @@ end p_a - p_avg, p_b - p_avg, rho_a, rho_b, pos_diff, distance, grad_kernel, correction) dv_particle = dv_pressure * pressure_correction - # Keep systems, velocities, displacement, and gradient fluid-first as one unit. - # The viscosity helper supplies model-specific ghost velocities where needed; - # artificial viscosity must see the same approaching-particle test as the fluid RHS. + # Fluid-first kinematics preserve artificial viscosity's approaching-particle test. dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, v_particle_system, v_neighbor_system, particle, neighbor, pos_diff, distance, sound_speed, m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, viscosity_correction) - # Surface-force dispatch skips inapplicable models. In particular, rigid-body - # adhesion uses the same fluid-frame displacement before the single reaction sign. surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, @@ -67,11 +53,8 @@ end pos_diff, distance) end -# Here the traversal labels are reversed: a=s (structure), b=f (fluid), and the -# neighbor search returns pos_diff=x_s-x_f. Physical operators below are evaluated -# with fluid-first arguments and r_fs=-pos_diff, then F_s=-m_f*a_f^physical. -# The default particle range advances free particles; callers such as mechanical -# work calculation can explicitly include clamped particles to recover their loads. +# Traversal labels are a=s, b=f, pos_diff=x_s-x_f; evaluate the fluid force with -pos_diff. +# Mechanical-work calculations override eachparticle to include clamped-particle loads. function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, @@ -80,31 +63,22 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, sound_speed = system_sound_speed(neighbor_system) correction = system_correction(neighbor_system) - # Coupling follows the current spatial configuration, unlike TLSPH elastic - # self-interaction, whose neighborhood is built in the initial configuration. system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # Match the fluid's support and its uniform h-relative squared-distance rule. - # The support factor does not enter the near-zero criterion. compact_support_ = compact_support(neighbor_system, particle_system) h = initial_smoothing_length(neighbor_system) zero_distance_squared = eps(typeof(h)) * h^2 - # Each task owns one structural particle. Neighbor contributions remain local - # until reduction, so force_per_particle and dv need no per-pair atomic updates. @threaded semi for particle in eachparticle - # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles - # corresponding to the rest density of the fluid and not the material density. - # This mass/pressure/density is the boundary state used by the forward fluid - # interaction. Material mass enters only when writing TLSPH acceleration. + # Use the forward fluid interaction's hydrodynamic boundary state. + # TLSPH material mass enters only when converting reaction force to acceleration. m_a = @inbounds hydrodynamic_mass(particle_system, particle) rho_a = @inbounds current_density(v_particle_system, particle_system, particle) v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) - # Accumulate force and density rate separately, as in the fluid RHS. init = (zero(v_a), zero(rho_a)) # Keep the returned name out of the closure to avoid allocations. @@ -123,7 +97,6 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) # Corrected coincident-particle gradients can be finite and nonzero. - # Apply the relative rule only when this correction skips those pairs. if distance > compact_support_ || (skip_zero_distance(neighbor_system) && distance^2 < zero_distance_squared) return init @@ -136,22 +109,16 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, distance, m_b, rho_a, rho_b, v_a, v_b) - # Evaluate grad_f W(r_fs) directly at the fluid particle. Neighborhood - # corrections contain particle-local terms, so -grad_f W(r_sf) need not - # equal grad_f W(-r_sf). Negating a structure-oriented corrected gradient - # would therefore give the wrong pressure/viscous reaction. + # Corrected gradients need not be odd: evaluate grad_f W(x_f-x_s) + # directly instead of negating a gradient computed with x_s-x_f. grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, distance, neighbor) - # Read fluid pressure first, then use the same boundary-pressure dispatch - # as the forward interaction. Pair-local mirroring, where supported, - # needs p_f even though the traversal visits the structure particle first. + # Pair-local pressure mirroring needs p_f although the outer particle is s. p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, p_b) - # Fluid-first ordering preserves the actual fluid force, including the - # approaching-particle condition of artificial viscosity. dv_fluid = @inbounds physical_fluid_pair_acceleration(neighbor_system, particle_system, v_neighbor_system, @@ -165,14 +132,10 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, grad_kernel_fluid, correction) - # m_b is fluid mass in this traversal: Newton's third law transfers the - # opposite physical force, not merely an acceleration with reversed sign. return -m_b * dv_fluid, drho_particle end - # TLS divides the accumulated force by material mass; rigid bodies retain - # particle forces for the later resultant/torque reduction. Boundary density - # is a separate scalar state derivative and is written through its own dispatch. + # TLSPH converts force with material mass; rigid bodies accumulate particle forces. @inbounds write_fluid_force!(dv, particle_system, force_particle_, particle) @inbounds write_drho_particle!(dv, particle_system, drho_particle_, particle) @@ -186,8 +149,6 @@ end neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, v_a, v_b) - # Pressure-extrapolated and summation-density boundaries have no density ODE - # contribution; only the ContinuityDensity specialization below evolves rho_s. return drho_particle end @@ -197,9 +158,8 @@ end neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, v_a, v_b) - # Continuity has structure-first orientation: (v_s-v_f) dot grad_s W. This - # reaction-force fix retains the existing density operator, evaluated with the - # neighboring fluid kernel and r_sf here, independently of the force sign above. + # The legacy density operator uses the fluid kernel with structure-first + # orientation (v_s-v_f) dot grad_s W, independently of the reaction sign. grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, neighbor) @@ -209,7 +169,6 @@ end end @inline function write_drho_particle!(dv, ::AbstractSystem, drho_particle, particle) - # A boundary model without an integrated density must not modify a velocity row. return dv end @@ -217,8 +176,6 @@ end ::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, drho_particle, particle) - # ContinuityDensity appends hydrodynamic density to v; momentum occupies the - # preceding rows. Add rather than overwrite when several fluid systems contribute. dv[end, particle] += drho_particle return dv From a3f06e27f7671857774c0614995ad8595971c5d5 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Sat, 3 Oct 2026 23:58:39 +0200 Subject: [PATCH 17/46] Preserve the inherited hydrodynamic-mass comment --- src/schemes/structure/fluid_interaction.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/schemes/structure/fluid_interaction.jl b/src/schemes/structure/fluid_interaction.jl index 6f2a1c3db2..5cb3d2f145 100644 --- a/src/schemes/structure/fluid_interaction.jl +++ b/src/schemes/structure/fluid_interaction.jl @@ -73,8 +73,8 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, zero_distance_squared = eps(typeof(h)) * h^2 @threaded semi for particle in eachparticle - # Use the forward fluid interaction's hydrodynamic boundary state. - # TLSPH material mass enters only when converting reaction force to acceleration. + # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles + # corresponding to the rest density of the fluid and not the material density. m_a = @inbounds hydrodynamic_mass(particle_system, particle) rho_a = @inbounds current_density(v_particle_system, particle_system, particle) v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) From 367c186497a3526f6e3a595f4f2db61db664255a Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 5 Oct 2026 10:26:39 +0200 Subject: [PATCH 18/46] revert changes --- src/general/abstract_system.jl | 1 + src/general/corrections.jl | 9 ++++++++- src/general/smoothing_kernels.jl | 8 ++++++-- src/preprocessing/particle_packing/rhs.jl | 8 +++++++- src/schemes/boundary/open_boundary/rhs.jl | 8 +++++++- src/schemes/boundary/wall_boundary/rhs.jl | 8 +++++++- src/schemes/fluid/entropically_damped_sph/rhs.jl | 8 +++++++- src/schemes/fluid/implicit_incompressible_sph/rhs.jl | 8 +++++++- src/schemes/fluid/weakly_compressible_sph/rhs.jl | 8 +++++++- src/schemes/structure/discrete_element_method/rhs.jl | 8 +++++++- src/schemes/structure/total_lagrangian_sph/rhs.jl | 9 ++++++++- src/schemes/structure/total_lagrangian_sph/system.jl | 9 ++++++++- 12 files changed, 80 insertions(+), 12 deletions(-) diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index 539124d803..14a968e86b 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -146,6 +146,7 @@ end compact_support_ = compact_support(system_smoothing_kernel(system), h) # The same relative squared-distance criterion is used by the pair RHSs. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. if distance >= compact_support_ || (skip_zero_distance(system) && distance^2 < eps(typeof(h)) * h^2) return zero(pos_diff) diff --git a/src/general/corrections.jl b/src/general/corrections.jl index 7fe57f71da..93549bee95 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -217,7 +217,14 @@ function compute_correction_values!(system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # Coefficient assembly uses the same relative criterion as its kernel. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, + # `distance^2` is in the order of `h^2`, so we use the relative criterion + # `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/general/smoothing_kernels.jl b/src/general/smoothing_kernels.jl index 6390c2371c..334bba3e4f 100644 --- a/src/general/smoothing_kernels.jl +++ b/src/general/smoothing_kernels.jl @@ -3,8 +3,12 @@ abstract type AbstractSmoothingKernel{NDIMS} end @inline Base.ndims(::AbstractSmoothingKernel{NDIMS}) where {NDIMS} = NDIMS @inline function kernel_grad(kernel, pos_diff, distance, h) - # Use one relative near-zero criterion: (distance/h)^2 < eps(typeof(h)). - # Compare squared lengths directly to avoid a square root in the hot path. + # For `distance == 0`, the analytical gradient is zero, but the code divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, + # `distance^2` is in the order of `h^2`, hence `distance^2 < eps(typeof(h)) * h^2`. + # Note that this is faster than `distance < sqrt(eps(typeof(h))) * h`. + # Also note that `sqrt(eps(typeof(h))) * h != eps(h)`. compact_support_ = compact_support(kernel, h) nonzero = distance < compact_support_ && distance^2 >= eps(typeof(h)) * h^2 nonzero || return zero(pos_diff) diff --git a/src/preprocessing/particle_packing/rhs.jl b/src/preprocessing/particle_packing/rhs.jl index 21f9e7e0b4..7609fb6dea 100644 --- a/src/preprocessing/particle_packing/rhs.jl +++ b/src/preprocessing/particle_packing/rhs.jl @@ -5,7 +5,13 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # Packing uses the same relative kernel-distance criterion. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 4466e6d1c8..e412fc835f 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -10,7 +10,13 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # Boundary kernels use the same relative criterion with their own h. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/boundary/wall_boundary/rhs.jl b/src/schemes/boundary/wall_boundary/rhs.jl index f658662700..6687f52ecc 100644 --- a/src/schemes/boundary/wall_boundary/rhs.jl +++ b/src/schemes/boundary/wall_boundary/rhs.jl @@ -19,7 +19,13 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # Boundary continuity uses the same relative criterion with its own h. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index 70d290e7b6..14c5738e9c 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -11,7 +11,13 @@ function interact!(dv, v_particle_system, u_particle_system, surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) - # All kernel interactions use the same relative squared-distance criterion. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index c298a178d1..047b4bbe3a 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -10,7 +10,13 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # All kernel interactions use the same relative squared-distance criterion. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index 0964a8afe7..9d51ce0d49 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,7 +19,13 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # All kernel interactions use the same relative squared-distance criterion. + # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient + # and the density diffusion divide by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in + # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/structure/discrete_element_method/rhs.jl b/src/schemes/structure/discrete_element_method/rhs.jl index f7849bf190..1887539071 100644 --- a/src/schemes/structure/discrete_element_method/rhs.jl +++ b/src/schemes/structure/discrete_element_method/rhs.jl @@ -6,7 +6,13 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # DEM has no kernel h; apply the same relative criterion to the particle radius. + # For `distance == 0`, computing the contact normal divides by zero. + # To account for rounding errors, we check if `distance` is almost zero. + # Since the coordinates are in the order of the radius `r`, `distance^2` is in + # the order of `r^2`, so we check `distance^2 < eps(typeof(r)) * r^2`. + # DEM has no smoothing kernel, so the particle radius is the characteristic length. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(r))) * r != eps(r)`. r = maximum(particle_system.radius) zero_distance_squared = eps(typeof(r)) * r^2 diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index dd083b6824..ca9d40b4fa 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -21,7 +21,14 @@ end neighborhood_search = get_neighborhood_search(system, semi) backend = semi.parallelization_backend - # Elastic interactions use the same relative criterion with the elastic h. + # For `initial_distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `initial_distance` is almost zero. + # Since the initial coordinates are in the order of the smoothing length `h`, + # `initial_distance^2` is in the order of `h^2`, so we use the relative criterion + # `initial_distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) zero_distance_squared = eps(typeof(h)) * h^2 diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index d79a2155a8..7577991af6 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -525,7 +525,14 @@ end @inline function calc_deformation_grad!(deformation_grad, system, semi) (; mass, material_density) = system - # Match the squared-distance criterion used by elastic self-interaction. + # For `initial_distance == 0`, the analytical gradient is zero, but the unsafe gradient + # divides by zero. + # To account for rounding errors, we check if `initial_distance` is almost zero. + # Since the initial coordinates are in the order of the smoothing length `h`, + # `initial_distance^2` is in the order of `h^2`, so we use the relative criterion + # `initial_distance^2 < eps(typeof(h)) * h^2`. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) zero_distance_squared = eps(typeof(h)) * h^2 From 95be7af0c7cedb07ffef4140bc7f55f4ec6d63b0 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 5 Oct 2026 11:31:34 +0200 Subject: [PATCH 19/46] review --- src/general/abstract_system.jl | 1 + src/general/corrections.jl | 24 ++++++------- src/general/smoothing_kernels.jl | 18 ++++++---- src/preprocessing/particle_packing/rhs.jl | 15 ++++---- src/schemes/boundary/open_boundary/rhs.jl | 15 ++++---- src/schemes/boundary/wall_boundary/rhs.jl | 15 ++++---- .../fluid/entropically_damped_sph/rhs.jl | 15 ++++---- .../fluid/implicit_incompressible_sph/rhs.jl | 15 ++++---- src/schemes/fluid/surface_tension.jl | 18 ++++++---- .../density_diffusion.jl | 4 +-- .../fluid/weakly_compressible_sph/rhs.jl | 16 ++++----- .../structure/discrete_element_method/rhs.jl | 27 ++++++++------- src/schemes/structure/rigid_body/system.jl | 3 +- src/schemes/structure/structure.jl | 23 +++++++------ .../structure/total_lagrangian_sph/rhs.jl | 16 ++++----- .../structure/total_lagrangian_sph/system.jl | 16 ++++----- test/general/near_zero_distance.jl | 34 +++++++++++++++++++ test/systems/dem_system.jl | 25 ++++++++++++++ 18 files changed, 185 insertions(+), 115 deletions(-) diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index 14a968e86b..c663541c49 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -146,6 +146,7 @@ end compact_support_ = compact_support(system_smoothing_kernel(system), h) # The same relative squared-distance criterion is used by the pair RHSs. + # Apply this numerical cutoff only when the correction permits skipping coincident pairs. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. if distance >= compact_support_ || (skip_zero_distance(system) && distance^2 < eps(typeof(h)) * h^2) diff --git a/src/general/corrections.jl b/src/general/corrections.jl index 93549bee95..5f3f93eed9 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -217,12 +217,12 @@ function compute_correction_values!(system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, - # `distance^2` is in the order of `h^2`, so we use the relative criterion - # `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident + # particles are treated as numerically zero to avoid division by zero and handle + # rounding errors. This is a numerical convention; not every kernel has a + # zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: + # `distance^2 < eps(typeof(h)) * h^2`, as in the uncorrected kernel gradient. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) @@ -241,10 +241,10 @@ function compute_correction_values!(system, kernel_correction_coefficient[particle] += volume * W - # Only consider particles with a distance > 0. + # Only include gradients outside the numerical zero-distance cutoff. if distance^2 >= zero_distance_squared - # Now that we know that `distance` is not zero, we can safely call the - # unsafe version of the kernel gradient to avoid redundant zero checks. + # The distance check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_W = kernel_grad_unsafe(system_smoothing_kernel(system), pos_diff, distance, smoothing_length(system, particle)) @@ -394,13 +394,13 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, particle) end - # Skip neighbors with the same position if the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(correction) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel + # gradient without repeating its zero-distance check. smoothing_length_ = smoothing_length(system, particle) grad_kernel = kernel_grad_local(correction, smoothing_kernel, pos_diff, distance, smoothing_length_, system, diff --git a/src/general/smoothing_kernels.jl b/src/general/smoothing_kernels.jl index 334bba3e4f..d7cbcd8441 100644 --- a/src/general/smoothing_kernels.jl +++ b/src/general/smoothing_kernels.jl @@ -3,10 +3,12 @@ abstract type AbstractSmoothingKernel{NDIMS} end @inline Base.ndims(::AbstractSmoothingKernel{NDIMS}) where {NDIMS} = NDIMS @inline function kernel_grad(kernel, pos_diff, distance, h) - # For `distance == 0`, the analytical gradient is zero, but the code divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, - # `distance^2` is in the order of `h^2`, hence `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel derivatives divide by `distance`. Treat effectively coincident + # particles as numerically zero to avoid division by zero and handle rounding errors. + # Most kernels have zero gradient at coincidence, but the Spiky gradient is undefined. + # Use the smoothing length `h` to set the relative cutoff + # `distance^2 < eps(typeof(h)) * h^2`, independently of the kernel's compact support. + # This is a numerical convention, not an exact zero-gradient limit for every kernel. # Note that this is faster than `distance < sqrt(eps(typeof(h))) * h`. # Also note that `sqrt(eps(typeof(h))) * h != eps(h)`. compact_support_ = compact_support(kernel, h) @@ -34,8 +36,8 @@ end end @inline function kernel_deriv(kernel, r::Real, h) - # Zero out result if outside of compact support or if `r` is almost zero - # (to avoid division by zero in the unsafe version). + # Return zero outside compact support or for numerically zero separations, + # using the same cutoff convention as `kernel_grad`. compact_support_ = compact_support(kernel, h) if r < compact_support_ && r^2 >= eps(typeof(h)) * h^2 # The unsafe version returns the kernel derivative divided by `r`, @@ -668,6 +670,10 @@ The Spiky kernel is particularly known for its sharp gradients, which can help t sharp features in fluid simulations, especially near solid boundaries. These sharp gradients at the boundary are also the largest disadvantage as they can lead to instability. +At coincident particle positions, the spatial gradient is undefined. The safe kernel +gradient and derivative return zero for effectively coincident particles using the shared +numerical zero-distance cutoff, rather than an analytical zero-gradient limit. + The smoothing length is typically in the range ``[1.5\delta, 3.0\delta]``, where ``\delta`` is the typical particle spacing. diff --git a/src/preprocessing/particle_packing/rhs.jl b/src/preprocessing/particle_packing/rhs.jl index 7609fb6dea..4aec950c7c 100644 --- a/src/preprocessing/particle_packing/rhs.jl +++ b/src/preprocessing/particle_packing/rhs.jl @@ -5,11 +5,10 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(system) @@ -18,12 +17,12 @@ function interact!(dv, v_particle_system, u_particle_system, # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(system, pos_diff, distance, particle) diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index e412fc835f..8ea6d2dec7 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -10,11 +10,10 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) @@ -27,12 +26,12 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) diff --git a/src/schemes/boundary/wall_boundary/rhs.jl b/src/schemes/boundary/wall_boundary/rhs.jl index 6687f52ecc..08a5db03e9 100644 --- a/src/schemes/boundary/wall_boundary/rhs.jl +++ b/src/schemes/boundary/wall_boundary/rhs.jl @@ -19,11 +19,10 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) @@ -32,12 +31,12 @@ function interact!(dv, v_particle_system, u_particle_system, # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index 14c5738e9c..9e924a40a6 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -11,11 +11,10 @@ function interact!(dv, v_particle_system, u_particle_system, surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) @@ -28,12 +27,12 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 047b4bbe3a..2349c3e03c 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -10,11 +10,10 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) @@ -27,12 +26,12 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) diff --git a/src/schemes/fluid/surface_tension.jl b/src/schemes/fluid/surface_tension.jl index 2ba66fbf05..0a30c7a36c 100644 --- a/src/schemes/fluid/surface_tension.jl +++ b/src/schemes/fluid/surface_tension.jl @@ -156,7 +156,8 @@ end (; surface_tension_coefficient) = surface_tension # Eq. 2 - # We only reach this function when `sqrt(eps()) < distance <= support_radius` + # The caller excludes numerically zero separations. At coincidence the force + # direction is undefined, although its magnitude has a nonzero limiting value. if distance > 0.5 * support_radius # Attractive force C = (support_radius - distance)^3 * distance^3 @@ -214,7 +215,8 @@ end surface_tension_correction) (; smoothing_kernel) = particle_system - # No cohesion with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle @@ -241,7 +243,8 @@ end (; surface_tension_coefficient) = surface_tension_a smoothing_length_ = smoothing_length(particle_system, particle) - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle @@ -268,7 +271,8 @@ end surface_tension_correction) (; surface_tension_coefficient) = surface_tension_a - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle @@ -344,7 +348,8 @@ end surface_tension_correction) (; surface_tension_coefficient) = surface_tension_a - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle @@ -366,7 +371,8 @@ end particle, neighbor, pos_diff, distance) (; adhesion_coefficient) = neighbor_system - # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index 8eb829fa70..e2d05f4830 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -216,9 +216,9 @@ end OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, grad_kernel) - # Density diffusion terms are all zero for distance zero. + # Density diffusion divides by separation, so omit numerically zero separations. # If `skip_zero_distance` is `true`, we can assume that this function isn't called - # for distance zero because these neighbors have already been skipped. + # for these separations because the pair RHS has already skipped these neighbors. h = initial_smoothing_length(particle_system) if !skip_zero_distance(particle_system) && distance^2 < eps(typeof(h)) * h^2 diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index 9d51ce0d49..02edf4895f 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,11 +19,11 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we check `distance^2 < eps(typeof(h)) * h^2`. + # Some unsafe kernel gradients and density diffusion terms divide by `distance`. + # Treat effectively coincident particles as numerically zero to avoid division by zero + # and handle rounding errors. This is a numerical convention; not every kernel has a + # zero-gradient limit. + # Scale the cutoff by the smoothing length `h`: `distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(particle_system) @@ -57,13 +57,13 @@ function interact!(dv, v_particle_system, u_particle_system, backend, particle; init) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(particle_system) && distance^2 < zero_distance_squared && return init - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel + # gradient without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) diff --git a/src/schemes/structure/discrete_element_method/rhs.jl b/src/schemes/structure/discrete_element_method/rhs.jl index 1887539071..ec82ec6f2d 100644 --- a/src/schemes/structure/discrete_element_method/rhs.jl +++ b/src/schemes/structure/discrete_element_method/rhs.jl @@ -6,29 +6,30 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, computing the contact normal divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the radius `r`, `distance^2` is in - # the order of `r^2`, so we check `distance^2 < eps(typeof(r)) * r^2`. - # DEM has no smoothing kernel, so the particle radius is the characteristic length. - # Comparing squared distances directly avoids computing a square root. - # Note that `sqrt(eps(typeof(r))) * r != eps(r)`. - r = maximum(particle_system.radius) - zero_distance_squared = eps(typeof(r)) * r^2 - foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; points=each_integrated_particle(particle_system)) do particle, neighbor, pos_diff, distance - distance^2 < zero_distance_squared && return - # Retrieve particle properties - m_a = particle_system.mass[particle] r_a = particle_system.radius[particle] r_b = neighbor_system.radius[neighbor] + # The contact normal is undefined for coincident centers, although the force + # magnitude need not vanish as `distance` approaches zero. + # Treat effectively coincident particles as numerically zero using the relative + # criterion `distance^2 < eps(typeof(r)) * r^2`, with the larger pair radius `r`. + # This symmetric scale gives both directions the same skip decision and is + # independent of unrelated particles in either system. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(r))) * r != eps(r)`. + r = max(r_a, r_b) + zero_distance_squared = eps(typeof(r)) * r^2 + distance^2 < zero_distance_squared && return + + m_a = particle_system.mass[particle] + # Compute the overlap (penetration depth) overlap = r_a + r_b - distance if overlap > 0 diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index c8dd18ac6a..dc5cb245f3 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -292,7 +292,8 @@ end particle, neighbor, pos_diff, distance) (; adhesion_coefficient) = neighbor_system - # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. + # Omit effectively coincident pairs by the numerical convention described in + # `src/general/smoothing_kernels.jl`. h = initial_smoothing_length(particle_system) distance^2 < eps(typeof(h)) * h^2 && return dv_particle diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 01d5917f6b..f73475cd93 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -26,25 +26,26 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. + # Some unsafe kernel gradients divide by `distance`, so effectively coincident particles + # are treated as numerically zero to avoid division by zero and handle rounding errors. + # This is a numerical convention; not every kernel has a zero-gradient limit. + # Use the fluid's smoothing length `h` and the same relative cutoff as its RHS: + # `distance^2 < eps(typeof(h)) * h^2`. Both directions must make the same skip decision. + # Comparing squared distances directly avoids computing a square root. + # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. h = initial_smoothing_length(neighbor_system) - almostzero = sqrt(eps(h^2)) + zero_distance_squared = eps(typeof(h)) * h^2 # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; points=eachparticle) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(neighbor_system) && distance < almostzero && return + skip_zero_distance(neighbor_system) && distance^2 < zero_distance_squared && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel gradient + # without repeating its zero-distance check. # Note that we use the `neighbor_system` to compute the kernel gradient # to obtain the same force as in the fluid-structure interaction. grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index ca9d40b4fa..4643881a5b 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -21,11 +21,11 @@ end neighborhood_search = get_neighborhood_search(system, semi) backend = semi.parallelization_backend - # For `initial_distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `initial_distance` is almost zero. - # Since the initial coordinates are in the order of the smoothing length `h`, - # `initial_distance^2` is in the order of `h^2`, so we use the relative criterion + # Some unsafe kernel gradients divide by `initial_distance`, so effectively coincident + # reference positions are treated as numerically zero to avoid division by zero and + # handle rounding errors. This is a numerical convention; not every kernel has a + # zero-gradient limit. + # Scale the cutoff by the elastic smoothing length `h`: # `initial_distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. @@ -53,14 +53,14 @@ end initial_pos_diff, initial_distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero reference separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. if skip_zero_distance(system) && initial_distance^2 < zero_distance_squared return zero(initial_pos_diff) end - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel + # gradient without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(system, initial_pos_diff, initial_distance, particle) diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 7577991af6..d338395519 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -525,11 +525,11 @@ end @inline function calc_deformation_grad!(deformation_grad, system, semi) (; mass, material_density) = system - # For `initial_distance == 0`, the analytical gradient is zero, but the unsafe gradient - # divides by zero. - # To account for rounding errors, we check if `initial_distance` is almost zero. - # Since the initial coordinates are in the order of the smoothing length `h`, - # `initial_distance^2` is in the order of `h^2`, so we use the relative criterion + # Some unsafe kernel gradients divide by `initial_distance`, so effectively coincident + # reference positions are treated as numerically zero to avoid division by zero and + # handle rounding errors. This is a numerical convention; not every kernel has a + # zero-gradient limit. + # Scale the cutoff by the elastic smoothing length `h`: # `initial_distance^2 < eps(typeof(h)) * h^2`. # Comparing squared distances directly avoids computing a square root. # Note that `sqrt(eps(typeof(h))) * h != eps(h)`. @@ -556,13 +556,13 @@ end initial_pos_diff, initial_distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip numerically zero reference separations only when the correction permits it. # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(system) && initial_distance^2 < zero_distance_squared && return zero(L_a) - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. + # The correction-dependent check makes it safe to call the unsafe kernel + # gradient without repeating its zero-distance check. grad_kernel = smoothing_kernel_grad_unsafe(system, initial_pos_diff, initial_distance, particle) diff --git a/test/general/near_zero_distance.jl b/test/general/near_zero_distance.jl index 00f3a4c736..2d71cea1bf 100644 --- a/test/general/near_zero_distance.jl +++ b/test/general/near_zero_distance.jl @@ -27,4 +27,38 @@ r = ldexp(1.0, -26) @test !iszero(TrixiParticles.kernel_grad(kernel, SVector(r, 0.0), r, 1.0)) @test !iszero(TrixiParticles.kernel_deriv(kernel, r, 1.0)) + + @testset "Fluid-structure force balance" begin + h = 0.3 + kernel = Poly6Kernel{2}() + ic = InitialCondition(; coordinates=zeros(2, 1), mass=[1.0], density=1.0, + particle_spacing=1.0) + state_equation = StateEquationCole(sound_speed=10.0, reference_density=1.0, + exponent=1) + fluid = WeaklyCompressibleSPHSystem(ic; smoothing_kernel=kernel, smoothing_length=h, + density_calculator=SummationDensity(), + state_equation) + boundary_model = BoundaryModelDummyParticles([1.0], [1.0], SummationDensity(), + kernel, h) + structure = RigidBodySystem(ic; boundary_model) + fluid.pressure .= 1.0 + fluid.cache.density .= 1.0 + boundary_model.pressure .= 1.0 + v = zeros(2, 1) + u_fluid, u_structure = ic.coordinates, copy(ic.coordinates) + semi = DummySemidiscretization() + + # At h=0.3, factor 0.9 lies between the old and new cutoffs; 1.5 is retained. + for factor in (0.9, 1.5) + u_structure[1, 1] = factor * sqrt(eps()) * h + dv_fluid = zero(v) + structure.force_per_particle .= 0.0 + TrixiParticles.interact!(dv_fluid, v, u_fluid, v, u_structure, + fluid, structure, semi) + TrixiParticles.interact_structure_fluid!(zero(v), v, u_structure, v, u_fluid, + structure, fluid, semi) + @test dv_fluid ≈ -structure.force_per_particle + @test iszero(dv_fluid) == (factor < 1) + end + end end diff --git a/test/systems/dem_system.jl b/test/systems/dem_system.jl index 746366d095..76da46a9f4 100644 --- a/test/systems/dem_system.jl +++ b/test/systems/dem_system.jl @@ -72,6 +72,31 @@ end # Define ndims for DummySystem so that any call to ndims returns 2 (for 2D systems). Base.ndims(::DummySystem) = 2 +@testset "DEM near-zero pair symmetry" begin + ic = InitialCondition(; coordinates=zeros(Float32, 2, 1), mass=Float32[1], + density=1.0f0, particle_spacing=1.0f0) + model = LinearContactModel(1.0f0) + system_a = DEMSystem(ic; contact_model=model, radius=0.3f0, + damping_coefficient=0.0f0, acceleration=(0.0f0, 0.0f0)) + system_b = DEMSystem(ic; contact_model=model, radius=1.0f0, + damping_coefficient=0.0f0, acceleration=(0.0f0, 0.0f0)) + v = zeros(Float32, 2, 1) + u_a, u_b = ic.coordinates, copy(ic.coordinates) + semi = DummySemidiscretization() + + # The first separation is between the two radius-based cutoffs; the second is retained. + for factor in (0.75f0, 1.5f0) + u_b[1, 1] = factor * sqrt(eps(Float32)) + dv_a, dv_b = zero(v), zero(v) + TrixiParticles.interact!(dv_a, v, u_a, v, u_b, + system_a, system_b, semi) + TrixiParticles.interact!(dv_b, v, u_b, v, u_a, + system_b, system_a, semi) + @test system_a.mass[1] * dv_a ≈ -system_b.mass[1] * dv_b + @test iszero(dv_a) == (factor < 1) + end +end + @testset "ContactModels Physical Behavior" begin # === HertzContactModel Tests === From 4638490e84f2f77df95ff601d7df569bb4934445 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:21:04 +0300 Subject: [PATCH 20/46] Use simpler `almostzero` without computing a `sqrt` --- src/general/abstract_system.jl | 4 ++-- src/general/corrections.jl | 21 ++++++++----------- src/general/smoothing_kernels.jl | 21 +++++++++++++------ src/preprocessing/particle_packing/rhs.jl | 12 +++-------- src/schemes/boundary/open_boundary/rhs.jl | 12 +++-------- src/schemes/boundary/wall_boundary/rhs.jl | 12 +++-------- .../fluid/entropically_damped_sph/rhs.jl | 12 +++-------- .../fluid/implicit_incompressible_sph/rhs.jl | 12 +++-------- .../fluid/weakly_compressible_sph/rhs.jl | 13 +++++------- .../structure/discrete_element_method/rhs.jl | 11 +++------- src/schemes/structure/structure.jl | 12 +++-------- .../structure/total_lagrangian_sph/rhs.jl | 12 +++-------- .../structure/total_lagrangian_sph/system.jl | 14 +++++-------- 13 files changed, 60 insertions(+), 108 deletions(-) diff --git a/src/general/abstract_system.jl b/src/general/abstract_system.jl index f52953d7e8..1871d5779e 100644 --- a/src/general/abstract_system.jl +++ b/src/general/abstract_system.jl @@ -145,9 +145,9 @@ end h = smoothing_length(system, particle) compact_support_ = compact_support(system_smoothing_kernel(system), h) - # Note that `sqrt(eps(h^2)) != eps(h)` + # See `almostzero` for an explanation of the zero distance check if distance >= compact_support_ || - (skip_zero_distance(system) && distance^2 < eps(h^2)) + (skip_zero_distance(system) && distance < almostzero(h)) return zero(pos_diff) end diff --git a/src/general/corrections.jl b/src/general/corrections.jl index d97eeaf341..a24f2c86f0 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -217,14 +217,7 @@ function compute_correction_values!(system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, @@ -239,8 +232,9 @@ function compute_correction_values!(system, kernel_correction_coefficient[particle] += volume * W - # Only consider particles with a distance > 0. - if distance > almostzero + # Only consider particles with a distance > 0 because the kernel gradient + # is zero otherwise, but computing it would divide by zero (see `almostzero`). + if distance > almostzero(h) # Now that we know that `distance` is not zero, we can safely call the # unsafe version of the kernel gradient to avoid redundant zero checks. grad_W = kernel_grad_unsafe(system_smoothing_kernel(system), pos_diff, @@ -370,7 +364,7 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, end neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - almostzero = sqrt(eps(compact_support(system, neighbor_system)^2)) + compact_support_ = compact_support(system, neighbor_system) foreach_point_neighbor(system, neighbor_system, coordinates, neighbor_coords, semi) do particle, neighbor, pos_diff, distance @@ -391,9 +385,12 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, particle) end - # Skip neighbors with the same position if the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(correction) && distance < almostzero && return + if skip_zero_distance(correction) && distance < almostzero(compact_support_) + return + end # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/general/smoothing_kernels.jl b/src/general/smoothing_kernels.jl index 456d55a13f..e7359f375a 100644 --- a/src/general/smoothing_kernels.jl +++ b/src/general/smoothing_kernels.jl @@ -2,15 +2,24 @@ abstract type AbstractSmoothingKernel{NDIMS} end @inline Base.ndims(::AbstractSmoothingKernel{NDIMS}) where {NDIMS} = NDIMS +# Threshold below which a `distance` is considered zero, where `h` is the length scale +# of the coordinates (e.g., the smoothing length or the compact support). +# For `distance == 0`, the analytical kernel gradient is zero, but the code divides by zero. +# To account for rounding errors, we check if `distance` is almost zero. +# Since the coordinates are in the order of `h`, `distance^2` is in the order of `h^2`, +# so the rounding error of `distance^2` is in the order of `eps(h^2) ≈ eps(typeof(h)) * h^2`. +# Hence, we consider `distance` almost zero if `distance^2 < eps(typeof(h)) * h^2`, +# or, equivalently, `distance < sqrt(eps(typeof(h))) * h`. +# Note that `sqrt(eps(h^2)) != eps(h)`. +# Since `sqrt(eps(typeof(h)))` is constant-propagated, this is only a multiplication +# and can be used inside hot loops without precomputing the threshold. +@inline almostzero(h) = sqrt(eps(typeof(h))) * h + @inline function kernel_grad(kernel, pos_diff, distance, h) # For `distance == 0`, the analytical gradient is zero, but the code divides by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, - # `distance^2` is in the order of `h^2`, hence the comparison `distance^2 < eps(h^2)`. - # Note that this is faster than `distance < sqrt(eps(h^2))`. - # Also note that `sqrt(eps(h^2)) != eps(h)`. + # See `almostzero` for an explanation of this check. compact_support_ = compact_support(kernel, h) - nonzero = distance < compact_support_ && distance^2 > eps(h^2) + nonzero = distance < compact_support_ && distance > almostzero(h) nonzero || return zero(pos_diff) # Now we can use `kernel_grad_unsafe` without worrying about division by zero diff --git a/src/preprocessing/particle_packing/rhs.jl b/src/preprocessing/particle_packing/rhs.jl index 807fba072f..208f7e4dcb 100644 --- a/src/preprocessing/particle_packing/rhs.jl +++ b/src/preprocessing/particle_packing/rhs.jl @@ -5,21 +5,15 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(system) && distance < almostzero && return + skip_zero_distance(system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 573d0d0914..1385023c3f 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -10,14 +10,7 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, @@ -26,9 +19,10 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/boundary/wall_boundary/rhs.jl b/src/schemes/boundary/wall_boundary/rhs.jl index 0edf8642ad..17e47c035d 100644 --- a/src/schemes/boundary/wall_boundary/rhs.jl +++ b/src/schemes/boundary/wall_boundary/rhs.jl @@ -19,21 +19,15 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/entropically_damped_sph/rhs.jl b/src/schemes/fluid/entropically_damped_sph/rhs.jl index d4c526f175..9d803c00a7 100644 --- a/src/schemes/fluid/entropically_damped_sph/rhs.jl +++ b/src/schemes/fluid/entropically_damped_sph/rhs.jl @@ -11,14 +11,7 @@ function interact!(dv, v_particle_system, u_particle_system, surface_tension_a = surface_tension_model(particle_system) surface_tension_b = surface_tension_model(neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(particle_system, neighbor_system, @@ -27,9 +20,10 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 6e8b5d18fa..a98762eb4c 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -10,14 +10,7 @@ function interact!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_system_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(particle_system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -26,9 +19,10 @@ function interact!(dv, v_particle_system, u_particle_system, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return + skip_zero_distance(particle_system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index f09f56d886..c9b4347f9e 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,13 +19,7 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient divides - # by zero. To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the compact support `c`, `distance^2` is in - # the order of `c^2`, so we need to check `distance < sqrt(eps(c^2))`. - # Note that `sqrt(eps(c^2)) != eps(c)`. compact_support_ = compact_support(particle_system, neighbor_system) - almostzero = sqrt(eps(compact_support_^2)) @threaded semi for particle in eachparticle # We are looping over the particles of `particle_system`, so it is guaranteed @@ -55,9 +49,12 @@ function interact!(dv, v_particle_system, u_particle_system, backend, particle; init) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(particle_system) && distance < almostzero && return init + if skip_zero_distance(particle_system) && distance < almostzero(compact_support_) + return init + end # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/structure/discrete_element_method/rhs.jl b/src/schemes/structure/discrete_element_method/rhs.jl index ee16f2a63d..693d5554cf 100644 --- a/src/schemes/structure/discrete_element_method/rhs.jl +++ b/src/schemes/structure/discrete_element_method/rhs.jl @@ -6,14 +6,7 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the radius `r`, `distance^2` is in - # the order of `r^2`, so we need to check `distance < sqrt(eps(r^2))`. - # Note that `sqrt(eps(r^2)) != eps(r)`. r = maximum(particle_system.radius) - almostzero = sqrt(eps(r^2)) foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; @@ -21,7 +14,9 @@ function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, neighbor, pos_diff, distance - distance < almostzero && return + # Skip neighbors with (almost) the same position to avoid division by zero + # when computing the normal below (see `almostzero`). + distance < almostzero(r) && return # Retrieve particle properties m_a = particle_system.mass[particle] diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 01d5917f6b..1205af15fe 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -26,22 +26,16 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, system_coords = current_coordinates(u_particle_system, particle_system) neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(neighbor_system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, system_coords, neighbor_coords, semi; points=eachparticle) do particle, neighbor, pos_diff, distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(neighbor_system) && distance < almostzero && return + skip_zero_distance(neighbor_system) && distance < almostzero(h) && return # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index 3fa8b6ea86..49f29db990 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -21,14 +21,7 @@ end neighborhood_search = get_neighborhood_search(system, semi) backend = semi.parallelization_backend - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) @threaded semi for particle in eachparticle # We are looping over the particles of `system`, so it is guaranteed @@ -51,9 +44,10 @@ end initial_pos_diff, initial_distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - if skip_zero_distance(system) && initial_distance < almostzero + if skip_zero_distance(system) && initial_distance < almostzero(h) return zero(initial_pos_diff) end diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index ceca948796..89063ce028 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -525,14 +525,7 @@ end @inline function calc_deformation_grad!(deformation_grad, system, semi) (; mass, material_density) = system - # For `distance == 0`, the analytical gradient is zero, but the unsafe gradient - # and the density diffusion divide by zero. - # To account for rounding errors, we check if `distance` is almost zero. - # Since the coordinates are in the order of the smoothing length `h`, `distance^2` is in - # the order of `h^2`, so we need to check `distance < sqrt(eps(h^2))`. - # Note that `sqrt(eps(h^2)) != eps(h)`. h = initial_smoothing_length(system) - almostzero = sqrt(eps(h^2)) # Loop over all pairs of particles and neighbors within the kernel cutoff initial_coords = initial_coordinates(system) @@ -554,9 +547,12 @@ end initial_pos_diff, initial_distance - # Skip neighbors with the same position because the kernel gradient is zero. + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - skip_zero_distance(system) && initial_distance < almostzero && return zero(L_a) + if skip_zero_distance(system) && initial_distance < almostzero(h) + return zero(L_a) + end # Now that we know that `distance` is not zero, we can safely call the unsafe # version of the kernel gradient to avoid redundant zero checks. From 428b49e80f1bdca49b89a39d60db39d100d185f3 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 5 Oct 2026 13:33:48 +0300 Subject: [PATCH 21/46] Change remaining inconsistencies --- src/general/corrections.jl | 6 +++--- src/general/smoothing_kernels.jl | 6 +++--- src/schemes/fluid/surface_tension.jl | 21 +++++++++---------- .../density_diffusion.jl | 4 ++-- .../fluid/weakly_compressible_sph/rhs.jl | 4 ++-- src/schemes/structure/rigid_body/system.jl | 4 ++-- 6 files changed, 22 insertions(+), 23 deletions(-) diff --git a/src/general/corrections.jl b/src/general/corrections.jl index a24f2c86f0..47973e6934 100644 --- a/src/general/corrections.jl +++ b/src/general/corrections.jl @@ -234,7 +234,7 @@ function compute_correction_values!(system, # Only consider particles with a distance > 0 because the kernel gradient # is zero otherwise, but computing it would divide by zero (see `almostzero`). - if distance > almostzero(h) + if distance >= almostzero(h) # Now that we know that `distance` is not zero, we can safely call the # unsafe version of the kernel gradient to avoid redundant zero checks. grad_W = kernel_grad_unsafe(system_smoothing_kernel(system), pos_diff, @@ -364,7 +364,7 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, end neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - compact_support_ = compact_support(system, neighbor_system) + h = initial_smoothing_length(system) foreach_point_neighbor(system, neighbor_system, coordinates, neighbor_coords, semi) do particle, neighbor, pos_diff, distance @@ -388,7 +388,7 @@ function compute_gradient_correction_matrix!(corr_matrix::AbstractArray, system, # Skip neighbors with (almost) the same position because the kernel gradient # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - if skip_zero_distance(correction) && distance < almostzero(compact_support_) + if skip_zero_distance(correction) && distance < almostzero(h) return end diff --git a/src/general/smoothing_kernels.jl b/src/general/smoothing_kernels.jl index e7359f375a..46de7246e4 100644 --- a/src/general/smoothing_kernels.jl +++ b/src/general/smoothing_kernels.jl @@ -19,7 +19,7 @@ abstract type AbstractSmoothingKernel{NDIMS} end # For `distance == 0`, the analytical gradient is zero, but the code divides by zero. # See `almostzero` for an explanation of this check. compact_support_ = compact_support(kernel, h) - nonzero = distance < compact_support_ && distance > almostzero(h) + nonzero = distance < compact_support_ && distance >= almostzero(h) nonzero || return zero(pos_diff) # Now we can use `kernel_grad_unsafe` without worrying about division by zero @@ -44,9 +44,9 @@ end @inline function kernel_deriv(kernel, r::Real, h) # Zero out result if outside of compact support or if `r` is almost zero - # (to avoid division by zero in the unsafe version). + # to avoid division by zero in the unsafe version (see `almostzero`). compact_support_ = compact_support(kernel, h) - if r < compact_support_ && r^2 > eps(h^2) + if r < compact_support_ && r >= almostzero(h) # The unsafe version returns the kernel derivative divided by `r`, # so we multiply it by `r` to get the actual derivative. return kernel_deriv_div_r_unsafe(kernel, r, h) * r diff --git a/src/schemes/fluid/surface_tension.jl b/src/schemes/fluid/surface_tension.jl index 4c86316864..e67b642ead 100644 --- a/src/schemes/fluid/surface_tension.jl +++ b/src/schemes/fluid/surface_tension.jl @@ -156,7 +156,6 @@ end (; surface_tension_coefficient) = surface_tension # Eq. 2 - # We only reach this function when `sqrt(eps()) < distance <= support_radius` if distance > 0.5 * support_radius # Attractive force C = (support_radius - distance)^3 * distance^3 @@ -214,8 +213,8 @@ end surface_tension_correction) (; smoothing_kernel) = particle_system - # No cohesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No cohesion with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle m_b = hydrodynamic_mass(neighbor_system, neighbor) support_radius = compact_support(smoothing_kernel, @@ -240,8 +239,8 @@ end (; surface_tension_coefficient) = surface_tension_a smoothing_length_ = smoothing_length(particle_system, particle) - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No surface tension with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle m_b = hydrodynamic_mass(neighbor_system, neighbor) n_a = surface_normal(particle_system, particle) @@ -266,8 +265,8 @@ end surface_tension_correction) (; surface_tension_coefficient) = surface_tension_a - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No surface tension with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle n_a = surface_normal(particle_system, particle) curvature_a = curvature(particle_system, particle) @@ -341,8 +340,8 @@ end surface_tension_correction) (; surface_tension_coefficient) = surface_tension_a - # No surface tension with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No surface tension with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle S_a = stress_tensor(particle_system, particle) S_b = stress_tensor(neighbor_system, neighbor) @@ -362,8 +361,8 @@ end particle, neighbor, pos_diff, distance) (; adhesion_coefficient) = neighbor_system - # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No adhesion with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle # No reason to calculate the adhesion force if adhesion coefficient is near zero abs(adhesion_coefficient) < eps() && return dv_particle diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index e1dd0ce0d3..281f6372f5 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -216,11 +216,11 @@ end OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, particle, neighbor, pos_diff, distance, m_b, rho_a, rho_b, grad_kernel) - # Density diffusion terms are all zero for distance zero. + # Density diffusion terms are all zero for distance zero (see `almostzero`). # If `skip_zero_distance` is `true`, we can assume that this function isn't called # for distance zero because these neighbors have already been skipped. if !skip_zero_distance(particle_system) && - distance^2 < eps(initial_smoothing_length(particle_system)^2) + distance < almostzero(initial_smoothing_length(particle_system)) return drho_particle end diff --git a/src/schemes/fluid/weakly_compressible_sph/rhs.jl b/src/schemes/fluid/weakly_compressible_sph/rhs.jl index c9b4347f9e..0700e94f91 100644 --- a/src/schemes/fluid/weakly_compressible_sph/rhs.jl +++ b/src/schemes/fluid/weakly_compressible_sph/rhs.jl @@ -19,7 +19,7 @@ function interact!(dv, v_particle_system, u_particle_system, neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) backend = semi.parallelization_backend - compact_support_ = compact_support(particle_system, neighbor_system) + h = initial_smoothing_length(particle_system) @threaded semi for particle in eachparticle # We are looping over the particles of `particle_system`, so it is guaranteed @@ -52,7 +52,7 @@ function interact!(dv, v_particle_system, u_particle_system, # Skip neighbors with (almost) the same position because the kernel gradient # is zero, but computing it would divide by zero (see `almostzero`). # Note that `return` only exits the closure, i.e., skips the current neighbor. - if skip_zero_distance(particle_system) && distance < almostzero(compact_support_) + if skip_zero_distance(particle_system) && distance < almostzero(h) return init end diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index e4b49cea88..f68e47dd7a 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -292,8 +292,8 @@ end particle, neighbor, pos_diff, distance) (; adhesion_coefficient) = neighbor_system - # No adhesion with oneself. See `src/general/smoothing_kernels.jl` for more details. - distance^2 < eps(initial_smoothing_length(particle_system)^2) && return dv_particle + # No adhesion with oneself (see `almostzero`). + distance < almostzero(initial_smoothing_length(particle_system)) && return dv_particle abs(adhesion_coefficient) < eps() && return dv_particle From ebd5040e21fea12a9853e0263002a73544feff9f Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 5 Oct 2026 15:45:26 +0200 Subject: [PATCH 22/46] update --- test/systems/dem_system.jl | 70 ++++++++++++-------------------------- 1 file changed, 21 insertions(+), 49 deletions(-) diff --git a/test/systems/dem_system.jl b/test/systems/dem_system.jl index 70083bab69..a8e9ee1d0c 100644 --- a/test/systems/dem_system.jl +++ b/test/systems/dem_system.jl @@ -73,55 +73,27 @@ end Base.ndims(::DummySystem) = 2 @testset "DEM near-zero pair symmetry" begin - for T in (Float32, Float64) - ic = InitialCondition(; coordinates=zeros(T, 2, 1), mass=T[1], - density=one(T), particle_spacing=one(T)) - model = LinearContactModel(one(T)) - system_a = DEMSystem(ic; contact_model=model, radius=T(0.3), - damping_coefficient=zero(T), acceleration=(zero(T), zero(T))) - system_b = DEMSystem(ic; contact_model=model, radius=one(T), - damping_coefficient=zero(T), acceleration=(zero(T), zero(T))) - v = zeros(T, 2, 1) - u_a, u_b = ic.coordinates, copy(ic.coordinates) - semi = DummySemidiscretization() - - # Include coincidence, a separation between the old system-based cutoffs, - # the exact strict-comparison boundary, and a larger retained separation. - for factor in T.((0.0, 0.75, 1.0, 1.5)) - u_b[1, 1] = factor * sqrt(eps(T)) - dv_a, dv_b = zero(v), zero(v) - TrixiParticles.interact!(dv_a, v, u_a, v, u_b, - system_a, system_b, semi) - TrixiParticles.interact!(dv_b, v, u_b, v, u_a, - system_b, system_a, semi) - @test system_a.mass[1] * dv_a ≈ -system_b.mass[1] * dv_b - @test iszero(dv_a) == (factor < 1) - @test iszero(dv_b) == (factor < 1) - if factor >= 1 - expected_force = SVector(-(T(0.3) + one(T) - u_b[1, 1]), zero(T)) - @test system_a.mass[1] * dv_a[:, 1] ≈ expected_force - end - end - - # An unrelated large particle must not suppress the smaller pair's contact. - ic_large = InitialCondition(; coordinates=T[0 1.0e5; 0 0], mass=ones(T, 2), - density=one(T), particle_spacing=one(T)) - system_large = DEMSystem(ic_large; contact_model=model, radius=T(0.3), - damping_coefficient=zero(T), - acceleration=(zero(T), zero(T))) - system_large.radius[2] = T(1000) - u_b[1, 1] = T(0.75) * sqrt(eps(T)) * system_large.radius[2] - v_large = zeros(T, 2, 2) - dv_large, dv_b = zero(v_large), zero(v) - TrixiParticles.interact!(dv_large, v_large, ic_large.coordinates, v, u_b, - system_large, system_b, semi) - TrixiParticles.interact!(dv_b, v, u_b, v_large, ic_large.coordinates, - system_b, system_large, semi) - @test !iszero(dv_large[:, 1]) - @test iszero(dv_large[:, 2]) - @test system_large.mass[1] * dv_large[:, 1] ≈ -system_b.mass[1] * dv_b[:, 1] - expected_force = SVector(-(T(0.3) + one(T) - u_b[1, 1]), zero(T)) - @test system_large.mass[1] * dv_large[:, 1] ≈ expected_force + ic = InitialCondition(; coordinates=zeros(Float32, 2, 1), mass=Float32[1], + density=1.0f0, particle_spacing=1.0f0) + model = LinearContactModel(1.0f0) + system_a = DEMSystem(ic; contact_model=model, radius=0.3f0, + damping_coefficient=0.0f0, acceleration=(0.0f0, 0.0f0)) + system_b = DEMSystem(ic; contact_model=model, radius=1.0f0, + damping_coefficient=0.0f0, acceleration=(0.0f0, 0.0f0)) + v = zeros(Float32, 2, 1) + u_a, u_b = ic.coordinates, copy(ic.coordinates) + semi = DummySemidiscretization() + + # The first separation is between the old cutoffs; the second retains the contact. + for factor in (0.75f0, 1.5f0) + u_b[1, 1] = factor * sqrt(eps(Float32)) + dv_a, dv_b = zero(v), zero(v) + TrixiParticles.interact!(dv_a, v, u_a, v, u_b, + system_a, system_b, semi) + TrixiParticles.interact!(dv_b, v, u_b, v, u_a, + system_b, system_a, semi) + @test system_a.mass[1] * dv_a ≈ -system_b.mass[1] * dv_b + @test iszero(dv_a) == (factor < 1) end end From 237139223d2d7684d18787e317a9797be882130e Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 6 Oct 2026 00:59:51 +0200 Subject: [PATCH 23/46] Limit structure-fluid reaction fix to corrected gradients Use the existing upstream FSI implementation and evaluate the fluid-first gradient directly for non-odd kernel corrections. Extend the upstream force-balance tests and remove the superseded implementation and duplicate regressions. --- NEWS.md | 7 +- docs/src/systems/rigid_body.md | 8 - src/schemes/schemes.jl | 2 +- src/schemes/structure/fluid_interaction.jl | 205 ------------------ src/schemes/structure/rigid_body/rhs.jl | 11 - src/schemes/structure/structure.jl | 153 +++++++++++++ .../structure/total_lagrangian_sph/rhs.jl | 11 - test/schemes/fluid/rhs.jl | 43 +++- test/schemes/schemes.jl | 1 - test/schemes/structure/fluid_interaction.jl | 182 ---------------- 10 files changed, 196 insertions(+), 427 deletions(-) delete mode 100644 src/schemes/structure/fluid_interaction.jl create mode 100644 src/schemes/structure/structure.jl delete mode 100644 test/schemes/structure/fluid_interaction.jl diff --git a/NEWS.md b/NEWS.md index 7e43074cdb..21e0f1f175 100644 --- a/NEWS.md +++ b/NEWS.md @@ -17,11 +17,10 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes -- Corrected pressure and viscous reaction forces on TLSPH and rigid-body systems, - including asymmetric fluid gradients, free-surface factors, EDAC pressure - reduction, and the approaching-particle condition for artificial viscosity (#1338). +- Fixed structure-fluid reaction forces with non-odd corrected fluid kernel + gradients by evaluating the fluid-first gradient directly (#1338). - Fixed asymmetric DEM contact forces near coincidence by using a pair-local - radius scale for the near-zero distance cutoff (#1347). + radius scale for the near-zero distance cutoff (#1347). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/docs/src/systems/rigid_body.md b/docs/src/systems/rigid_body.md index 6ad8fcc622..27928499ce 100644 --- a/docs/src/systems/rigid_body.md +++ b/docs/src/systems/rigid_body.md @@ -4,14 +4,6 @@ Rigid bodies in TrixiParticles.jl are represented by particles whose motion is e with rigid-body translation and rotation. This allows fluid-structure interaction while keeping the structure kinematics rigid. -## [Fluid loads](@id fluid_structure_loads) - -Pressure, viscosity, and adhesion use fluid-first pair operators. The physical -fluid acceleration contributes the structural reaction `F_s = -m_f a_f`. -Rigid bodies sum particle forces and torques, while TLSPH converts force to -acceleration with the material mass. Shifting momentum terms remain in the fluid -RHS and are excluded from structural loads because they are transport corrections. - ## API ```@autodocs diff --git a/src/schemes/schemes.jl b/src/schemes/schemes.jl index d2b3d1f4fb..8330312467 100644 --- a/src/schemes/schemes.jl +++ b/src/schemes/schemes.jl @@ -7,6 +7,7 @@ include("fluid/weakly_compressible_sph/density_diffusion.jl") include("structure/rigid_body/rigid_body.jl") include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") include("structure/discrete_element_method/discrete_element_method.jl") +include("structure/structure.jl") # Monaghan-Kajtar repulsive boundary particles require the `WallBoundarySystem` # and the `TotalLagrangianSPHSystem`. include("boundary/wall_boundary/monaghan_kajtar.jl") @@ -18,7 +19,6 @@ include("fluid/weakly_compressible_sph/rhs.jl") include("fluid/entropically_damped_sph/rhs.jl") include("fluid/implicit_incompressible_sph/rhs.jl") include("boundary/wall_boundary/rhs.jl") -include("structure/fluid_interaction.jl") include("structure/rigid_body/rhs.jl") include("structure/total_lagrangian_sph/rhs.jl") include("structure/discrete_element_method/rhs.jl") diff --git a/src/schemes/structure/fluid_interaction.jl b/src/schemes/structure/fluid_interaction.jl deleted file mode 100644 index aca37f3239..0000000000 --- a/src/schemes/structure/fluid_interaction.jl +++ /dev/null @@ -1,205 +0,0 @@ -# Structure-fluid coupling shared by TLSPH and rigid-body systems. -@inline average_pressure(system, particle) = zero(eltype(system)) - -@inline interaction_force_correction(system, rho_a, rho_b) = (1, 1, 1) - -@inline function interaction_force_correction(system::WeaklyCompressibleSPHSystem, - rho_a, rho_b) - return free_surface_correction(system_correction(system), system, rho_a, rho_b) -end - -@inline function sum_interaction_contributions(a, b) - dv_a, drho_a = a - dv_b, drho_b = b - return dv_a + dv_b, drho_a + drho_b -end - -# The structure-fluid interaction computes the opposite of the force that the fluid -# experiences in the fluid-structure interaction. Therefore, both interactions must find -# the same pairs of particles, so the neighborhood search of the structure must use -# the compact support of the fluid. -# Note that this is only a restriction for `BoundaryModelDummyParticles`, since -# `BoundaryModelMonaghanKajtar` always uses the compact support of the fluid. -function check_compact_support_fsi(system, ::BoundaryModelDummyParticles, - neighbor_system::AbstractFluidSystem) - compact_support_structure = compact_support(system, neighbor_system) - compact_support_fluid = compact_support(neighbor_system, system) - - if !isapprox(compact_support_structure, compact_support_fluid) - throw(ArgumentError("the compact support of the boundary model of the " * - "`$(nameof(typeof(system)))` ($compact_support_structure) " * - "must be the same as the compact support of the fluid system " * - "($compact_support_fluid). Use the same smoothing kernel and " * - "smoothing length for the boundary model as for the fluid.")) - end - - return system -end - -check_compact_support_fsi(system, boundary_model, neighbor_system) = system - -# Fluid-first arguments: a=f, b=s, pos_diff=x_f-x_s, with the gradient evaluated at f. -# Return a_f^physical for the reaction F_s=-m_f*a_f^physical; shifting is excluded. -@propagate_inbounds function physical_fluid_pair_acceleration(particle_system, - neighbor_system, - v_particle_system, - v_neighbor_system, - particle, neighbor, - m_a, m_b, p_a, p_b, rho_a, - rho_b, - v_a, v_b, pos_diff, distance, - sound_speed, grad_kernel, - correction) - # EDAC must use the fluid particle's local mean for both pair pressures. - p_avg = average_pressure(particle_system, particle) - viscosity_correction, pressure_correction, - surface_tension_correction = interaction_force_correction(particle_system, rho_a, rho_b) - dv_pressure = pressure_acceleration(particle_system, neighbor_system, - particle, neighbor, m_a, m_b, - p_a - p_avg, p_b - p_avg, rho_a, rho_b, - pos_diff, distance, grad_kernel, correction) - dv_particle = dv_pressure * pressure_correction - # Fluid-first kinematics preserve artificial viscosity's approaching-particle test. - dv_particle = add_dv_viscosity(dv_particle, particle_system, neighbor_system, - v_particle_system, v_neighbor_system, - particle, neighbor, pos_diff, distance, sound_speed, - m_a, m_b, rho_a, rho_b, v_a, v_b, grad_kernel, - viscosity_correction) - surface_tension_a = surface_tension_model(particle_system) - surface_tension_b = surface_tension_model(neighbor_system) - dv_particle = add_dv_surface_tension(dv_particle, surface_tension_a, surface_tension_b, - particle_system, neighbor_system, particle, - neighbor, - pos_diff, distance, rho_a, rho_b, grad_kernel, - surface_tension_correction) - return add_dv_adhesion(dv_particle, surface_tension_a, - particle_system, neighbor_system, particle, neighbor, - pos_diff, distance) -end - -# Traversal labels are a=s, b=f, pos_diff=x_s-x_f; evaluate the fluid force with -pos_diff. -# Mechanical-work calculations override eachparticle to include clamped-particle loads. -function interact_structure_fluid!(dv, v_particle_system, u_particle_system, - v_neighbor_system, u_neighbor_system, - particle_system, - neighbor_system::AbstractFluidSystem, semi; - eachparticle=each_integrated_particle(particle_system)) - sound_speed = system_sound_speed(neighbor_system) - correction = system_correction(neighbor_system) - - system_coords = current_coordinates(u_particle_system, particle_system) - neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - neighborhood_search = get_neighborhood_search(particle_system, neighbor_system, semi) - backend = semi.parallelization_backend - - compact_support_ = compact_support(neighbor_system, particle_system) - h = initial_smoothing_length(neighbor_system) - - @threaded semi for particle in eachparticle - # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles - # corresponding to the rest density of the fluid and not the material density. - m_a = @inbounds hydrodynamic_mass(particle_system, particle) - rho_a = @inbounds current_density(v_particle_system, particle_system, particle) - v_a = @inbounds current_velocity(v_particle_system, particle_system, particle) - - init = (zero(v_a), zero(rho_a)) - - # Keep the returned name out of the closure to avoid allocations. - (force_particle_, - drho_particle_) = @inbounds mapreduce_neighbor(sum_interaction_contributions, - system_coords, - neighbor_coords, - neighborhood_search, backend, - particle; - init) do particle, - neighbor, - pos_diff, - distance - m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) - rho_b = @inbounds current_density(v_neighbor_system, neighbor_system, neighbor) - v_b = @inbounds current_velocity(v_neighbor_system, neighbor_system, neighbor) - - # Corrected coincident-particle gradients can be finite and nonzero. - if distance > compact_support_ || - (skip_zero_distance(neighbor_system) && distance < almostzero(h)) - return init - end - - drho_particle = @inbounds add_continuity_equation(zero(rho_a), - particle_system, - neighbor_system, - particle, neighbor, pos_diff, - distance, m_b, rho_a, rho_b, - v_a, v_b) - - # Corrected gradients need not be odd: evaluate grad_f W(x_f-x_s) - # directly instead of negating a gradient computed with x_s-x_f. - grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, - distance, neighbor) - - # Pair-local pressure mirroring needs p_f although the outer particle is s. - p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) - p_a = @inbounds neighbor_pressure(v_particle_system, particle_system, particle, - p_b) - - dv_fluid = @inbounds physical_fluid_pair_acceleration(neighbor_system, - particle_system, - v_neighbor_system, - v_particle_system, - neighbor, particle, - m_b, m_a, p_b, p_a, rho_b, - rho_a, - v_b, v_a, -pos_diff, - distance, - sound_speed, - grad_kernel_fluid, - correction) - - return -m_b * dv_fluid, drho_particle - end - - # TLSPH converts force with material mass; rigid bodies accumulate particle forces. - @inbounds write_fluid_force!(dv, particle_system, force_particle_, particle) - @inbounds write_drho_particle!(dv, particle_system, drho_particle_, - particle) - end - - return dv -end - -@inline function add_continuity_equation(drho_particle, - particle_system::AbstractStructureSystem, - neighbor_system::AbstractFluidSystem, - particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b) - return drho_particle -end - -@inline function add_continuity_equation(drho_particle, - particle_system::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, - TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, - neighbor_system::AbstractFluidSystem, - particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b) - # The legacy density operator uses the fluid kernel with structure-first - # orientation (v_s-v_f) dot grad_s W, independently of the reaction sign. - grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, - neighbor) - - return add_continuity_equation(drho_particle, - density_calculator(neighbor_system), - m_b, rho_a, rho_b, v_a, v_b, grad_kernel, particle) -end - -@inline function write_drho_particle!(dv, ::AbstractSystem, drho_particle, particle) - return dv -end - -@propagate_inbounds function write_drho_particle!(dv, - ::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, - TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, - drho_particle, particle) - dv[end, particle] += drho_particle - - return dv -end diff --git a/src/schemes/structure/rigid_body/rhs.jl b/src/schemes/structure/rigid_body/rhs.jl index ceb9500c7c..48fc8d26c8 100644 --- a/src/schemes/structure/rigid_body/rhs.jl +++ b/src/schemes/structure/rigid_body/rhs.jl @@ -33,17 +33,6 @@ function interact!(dv, v_particle_system, u_particle_system, particle_system, neighbor_system, semi) end -# Accumulate pair forces before reducing them to rigid-body resultants. -@propagate_inbounds function write_fluid_force!(dv, particle_system::RigidBodySystem, - force_particle, particle) - force_per_particle = particle_system.force_per_particle - for i in 1:ndims(particle_system) - force_per_particle[i, particle] += force_particle[i] - end - - return dv -end - # Reduce the accumulated fluid forces to rigid-body resultants and apply the corresponding # translational and rotational acceleration to every rigid particle. function apply_resultant_force_and_torque!(dv, particle_system::RigidBodySystem, semi) diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl new file mode 100644 index 0000000000..7a35f5e931 --- /dev/null +++ b/src/schemes/structure/structure.jl @@ -0,0 +1,153 @@ +# Shared structure-fluid interaction helpers used by multiple structure schemes. +@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, + particle_system::TotalLagrangianSPHSystem, + particle, m_b) + material_mass = particle_system.mass[particle] + for dim in eachindex(dv_fs) + dv[dim, particle] += dv_fs[dim] * m_b / material_mass + end +end + +@propagate_inbounds function accumulate_structure_fluid_pair!(dv, dv_fs, + particle_system::RigidBodySystem, + particle, m_b) + force_per_particle = particle_system.force_per_particle + for dim in eachindex(dv_fs) + force_per_particle[dim, particle] += dv_fs[dim] * m_b + end +end + +# The structure-fluid interaction computes the opposite of the force that the fluid +# experiences in the fluid-structure interaction. Therefore, both interactions must find +# the same pairs of particles, so the neighborhood search of the structure must use +# the compact support of the fluid. +# Note that this is only a restriction for `BoundaryModelDummyParticles`, since +# `BoundaryModelMonaghanKajtar` always uses the compact support of the fluid. +function check_compact_support_fsi(system, ::BoundaryModelDummyParticles, + neighbor_system::AbstractFluidSystem) + compact_support_structure = compact_support(system, neighbor_system) + compact_support_fluid = compact_support(neighbor_system, system) + + if !isapprox(compact_support_structure, compact_support_fluid) + throw(ArgumentError("the compact support of the boundary model of the " * + "`$(nameof(typeof(system)))` ($compact_support_structure) " * + "must be the same as the compact support of the fluid system " * + "($compact_support_fluid). Use the same smoothing kernel and " * + "smoothing length for the boundary model as for the fluid.")) + end + + return system +end + +check_compact_support_fsi(system, boundary_model, neighbor_system) = system + +function interact_structure_fluid!(dv, v_particle_system, u_particle_system, + v_neighbor_system, u_neighbor_system, + particle_system, + neighbor_system::AbstractFluidSystem, semi; + eachparticle=each_integrated_particle(particle_system)) + sound_speed = system_sound_speed(neighbor_system) + system_coords = current_coordinates(u_particle_system, particle_system) + neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) + + h = initial_smoothing_length(neighbor_system) + + # Loop over all pairs of particles and neighbors within the kernel cutoff. + foreach_point_neighbor(particle_system, neighbor_system, + system_coords, neighbor_coords, semi; + points=eachparticle) do particle, neighbor, pos_diff, distance + # Skip neighbors with (almost) the same position because the kernel gradient + # is zero, but computing it would divide by zero (see `almostzero`). + # Note that `return` only exits the closure, i.e., skips the current neighbor. + skip_zero_distance(neighbor_system) && distance < almostzero(h) && return + + # Now that we know that `distance` is not zero, we can safely call the unsafe + # version of the kernel gradient to avoid redundant zero checks. + # Note that we use the `neighbor_system` to compute the kernel gradient + # to obtain the same force as in the fluid-structure interaction. + grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, + distance, neighbor) + # Corrected gradients need not be odd, so evaluate the fluid-first gradient + # directly instead of negating the structure-first gradient. + grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, + distance, neighbor) + + m_b = hydrodynamic_mass(neighbor_system, neighbor) + + rho_a = current_density(v_particle_system, particle_system, particle) + rho_b = current_density(v_neighbor_system, neighbor_system, neighbor) + + v_a = current_velocity(v_particle_system, particle_system, particle) + v_b = current_velocity(v_neighbor_system, neighbor_system, neighbor) + + # In fluid-structure interaction, use the "hydrodynamic mass" of the structure particles + # corresponding to the rest density of the fluid and not the material density. + m_a = hydrodynamic_mass(particle_system, particle) + + # In fluid-structure interaction, use the "hydrodynamic pressure" of the structure + # particles corresponding to the chosen boundary model. + p_a = current_pressure(v_particle_system, particle_system, particle) + p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) + + # Compute the acceleration of the fluid particle due to the structure particle + # with the exact same function as in the fluid-structure interaction. + # Particle and neighbor (and the corresponding systems and particle quantities) + # are switched, so we use the fluid-first displacement and gradient. + # By Newton's third law, the structure particle experiences the opposite force. + # + # Note that the extra terms of shifting techniques in the momentum equation are + # intentionally not applied to the structure. + # Shifting makes the fluid particles quasi-Lagrangian, i.e., they don't move + # exactly with the fluid velocity. The extra terms correct for this by accounting + # for the momentum transported between fluid particles. They are not a force. + dv_fluid = add_momentum_equation(zero(v_b), neighbor_system, particle_system, + v_neighbor_system, v_particle_system, + neighbor, particle, -pos_diff, distance, + grad_kernel_fluid, sound_speed, m_b, m_a, p_b, p_a, + rho_b, rho_a, v_b, v_a) + dv_particle = -dv_fluid + + accumulate_structure_fluid_pair!(dv, dv_particle, particle_system, particle, m_b) + + drho_particle = add_continuity_equation(zero(rho_a), + particle_system, neighbor_system, + particle, neighbor, pos_diff, distance, + m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + + @inbounds write_drho_particle!(dv, particle_system, drho_particle, particle) + end + + return dv +end + +@inline function add_continuity_equation(drho_particle, + particle_system::AbstractStructureSystem, + neighbor_system::AbstractFluidSystem, + particle, neighbor, pos_diff, distance, + m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + return drho_particle +end + +@inline function add_continuity_equation(drho_particle, + particle_system::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, + TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, + neighbor_system::AbstractFluidSystem, + particle, neighbor, pos_diff, distance, + m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + return add_continuity_equation(drho_particle, + density_calculator(neighbor_system), + m_b, rho_a, rho_b, v_a, v_b, grad_kernel, particle) +end + +@inline function write_drho_particle!(dv, ::AbstractSystem, drho_particle, particle) + return dv +end + +@propagate_inbounds function write_drho_particle!(dv, + ::Union{RigidBodySystem{<:BoundaryModelDummyParticles{ContinuityDensity}}, + TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, + drho_particle, particle) + dv[end, particle] += drho_particle + + return dv +end diff --git a/src/schemes/structure/total_lagrangian_sph/rhs.jl b/src/schemes/structure/total_lagrangian_sph/rhs.jl index c6cbc778e4..49f29db990 100644 --- a/src/schemes/structure/total_lagrangian_sph/rhs.jl +++ b/src/schemes/structure/total_lagrangian_sph/rhs.jl @@ -111,17 +111,6 @@ function interact!(dv, v_particle_system, u_particle_system, particle_system, neighbor_system, semi; eachparticle) end -@propagate_inbounds function write_fluid_force!(dv, - particle_system::TotalLagrangianSPHSystem, - force_particle, particle) - material_mass = particle_system.mass[particle] - for i in 1:ndims(particle_system) - dv[i, particle] += force_particle[i] / material_mass - end - - return dv -end - # Structure-boundary interaction function interact!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 9d9847c876..6f0809da4e 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -281,7 +281,7 @@ exponent=1) function create_fluid_system(scheme, velocity, density, viscosity; - shifting_technique=nothing) + shifting_technique=nothing, correction=nothing) fluid = InitialCondition(; coordinates=zeros(2, 1), velocity=reshape(collect(velocity), 2, 1), mass=[fluid_density * particle_spacing^2], @@ -292,7 +292,8 @@ return WeaklyCompressibleSPHSystem(fluid; smoothing_kernel, smoothing_length, state_equation, density_calculator=ContinuityDensity(), - viscosity, shifting_technique) + viscosity, shifting_technique, + correction) end # Note that the average pressure reduction is enabled by default @@ -304,7 +305,8 @@ density_calculator=ContinuityDensity()) end - function create_structure_system(structure_type, viscosity) + function create_structure_system(structure_type, viscosity; + density_calculator=AdamiPressureExtrapolation()) # The material mass is twice the hydrodynamic mass, so using the wrong mass # to convert the force on the structure to an acceleration fails the test. structure = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), @@ -314,7 +316,7 @@ boundary_model = BoundaryModelDummyParticles([fluid_density], [fluid_density * particle_spacing^2], - AdamiPressureExtrapolation(), + density_calculator, smoothing_kernel, smoothing_length; state_equation, viscosity) @@ -447,6 +449,39 @@ end end + @testset "Corrected gradients `$(nameof(typeof(correction)))`" for correction in + (KernelCorrection(), + MixedKernelGradientCorrection()) + @testset "`$structure_type`, viscosity `$(nameof(typeof(viscosity)))`" for structure_type in + structure_types, + viscosity in + (nothing, + ViscosityAdami(nu=0.1), + ViscosityMorris(nu=0.1)) + + fluid_system = create_fluid_system("WCSPH", (1.0, 0.5), 1005.0, + viscosity; correction) + structure_system = create_structure_system(structure_type, viscosity; + density_calculator=SummationDensity()) + fluid, structure, arrays, semi = initialize(fluid_system, structure_system) + + # The correction adds a non-odd term. Negating the structure-first + # gradient therefore does not reproduce the fluid-first gradient. + pos_diff = SVector(1.5, 0.0) + grad_kernel = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, + 1.5, 1) + grad_kernel_fluid = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + -pos_diff, + 1.5, 1) + @test !isapprox(grad_kernel_fluid, -grad_kernel) + + force_fluid, force_structure = pair_forces(fluid, structure, arrays, semi) + @test !iszero(force_fluid) + @test isapprox(force_structure, -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + end + end + # The extra terms of the shifting techniques in the momentum equation act on the # fluid, but must not be applied to the structure. shifting_techniques = (ParticleShiftingTechnique(), diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index dc1941f0b4..bb6e9d5483 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,5 +1,4 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") -include("structure/fluid_interaction.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction.jl b/test/schemes/structure/fluid_interaction.jl deleted file mode 100644 index d4be91c49c..0000000000 --- a/test/schemes/structure/fluid_interaction.jl +++ /dev/null @@ -1,182 +0,0 @@ -@testset verbose=true "Structure-fluid force balance" begin - # One fluid/structure pair isolates cross-system forces from elastic forces. - # At r/h = 1.5 the cubic-spline gradient is nonzero and has a simple exact value. - particle_spacing = 1.0 - smoothing_kernel = SchoenbergCubicSplineKernel{2}() - smoothing_length = 1.0 - reference_density = 1000.0 - structure_density = 2000.0 - state_equation = StateEquationCole(; sound_speed=10.0, reference_density, exponent=1.0) - viscosities = (nothing, ViscosityAdami(nu=0.1), ViscosityMorris(nu=0.1), - ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) - # Exercise fluid-side prefactors as well as the reaction sign: Akinci changes - # viscosity scaling, kernel corrections need not be odd, and EDAC reduces pressure. - configurations = ((:wcsph, nothing, AdamiPressureExtrapolation()), - (:wcsph, nothing, ContinuityDensity()), - (:wcsph, AkinciFreeSurfaceCorrection(reference_density), - AdamiPressureExtrapolation()), - (:wcsph, KernelCorrection(), SummationDensity()), - (:wcsph, MixedKernelGradientCorrection(), SummationDensity()), - (:edac, nothing, AdamiPressureExtrapolation()), - (:edac_pressure_reduction, nothing, AdamiPressureExtrapolation())) - # Zero pressure isolates viscosity for approaching and receding particles. - # Nonzero pressure checks that pressure and viscosity accumulate consistently. - # The structure lies to the right: positive fluid vx approaches it, while - # negative vx must deactivate Monaghan artificial viscosity (but not physical viscosity). - fluid_states = ((velocity=(1.0, 0.5), density=reference_density), - (velocity=(-1.0, -0.5), density=reference_density), - (velocity=(1.0, 0.5), density=1005.0)) - - @testset "$fluid_scheme, $viscosity, $correction, $boundary_density" for viscosity in - viscosities, - (fluid_scheme, - correction, - boundary_density) in - configurations - - @testset "$structure_kind, $fluid_state" for structure_kind in - (:tlsph, :clamped_tlsph, :rigid), - fluid_state in fluid_states - - # `ContinuityDensity` is currently supported only for rigid structures. - if structure_kind != :rigid && boundary_density isa ContinuityDensity - continue - end - - fluid_velocity = reshape(collect(fluid_state.velocity), 2, 1) - fluid_ic = InitialCondition(; coordinates=reshape([0.0, 0.0], 2, 1), - velocity=fluid_velocity, - mass=[reference_density], - density=[fluid_state.density], - pressure=state_equation(fluid_state.density), - particle_spacing) - fluid_system = if fluid_scheme == :wcsph - WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - viscosity, correction, - density_calculator=ContinuityDensity(), - state_equation) - else - EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - sound_speed=10.0, viscosity, correction, - density_calculator=ContinuityDensity(), - average_pressure_reduction=fluid_scheme == - :edac_pressure_reduction) - end - - # Material mass is twice hydrodynamic mass. Using the wrong mass when - # converting reaction force to TLSPH acceleration cannot pass this check. - structure_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), - velocity=zeros(2, 1), mass=[structure_density], - density=[structure_density], particle_spacing) - boundary_model = BoundaryModelDummyParticles([reference_density], - [reference_density], - boundary_density, - smoothing_kernel, smoothing_length; - state_equation, viscosity) - structure_system = if structure_kind == :rigid - RigidBodySystem(structure_ic; boundary_model) - else - clamped_particles = structure_kind == :clamped_tlsph ? (1:1) : (1:0) - TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, - young_modulus=1.0e5, poisson_ratio=0.3, - clamped_particles, boundary_model) - end - - # TLS setup reports its deep copy; other setup logs, including warnings, - # are unexpected rather than being hidden by a null logger. - semi = if structure_system isa TotalLagrangianSPHSystem - @test_logs (:info, - r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin - Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) - end - else - @test_logs Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) - end - ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) - fluid, structure = ode.p.semi.systems - v_ode, u_ode = ode.u0.x - dv_ode = zero(v_ode) - # Run the normal RHS update sequence to populate boundary pressures, - # ghost velocities, and fluid correction/average-pressure caches. - TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) - v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) - u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - # Isolate this pair from corrected fluid self-interaction terms. - dv_fluid = zero(v_fluid) - TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, - v_structure, u_structure, fluid, structure, semi) - # Newton's third law uses the fluid particle's mass, regardless of the - # structure's material mass or how it stores its resultant force. - expected_force = -fluid.mass[1] * dv_fluid[1:2, 1] - - if correction isa KernelCorrection || - correction isa MixedKernelGradientCorrection - # Ensure that this fixture exercises a gradient that is not odd. - pos_diff = SVector(1.5, 0.0) - gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, - 1.5, 1) - reverse_gradient = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, - -pos_diff, - 1.5, 1) - @test !isapprox(gradient, -reverse_gradient) - end - - if fluid_state.density == reference_density - @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, 1)) - @test iszero(structure.boundary_model.pressure[1]) - if isnothing(viscosity) || - (viscosity isa ArtificialViscosityMonaghan && - fluid_state.velocity[1] < 0) - @test iszero(expected_force) - else - # The viscous reaction on the structure follows the fluid motion. - @test expected_force[1] * fluid_state.velocity[1] > 0 - end - elseif fluid_scheme == :edac_pressure_reduction && isnothing(viscosity) - # Uniform nonzero pressure produces no force after pressure reduction. - @test TrixiParticles.current_pressure(v_fluid, fluid, 1) ≈ - structure.boundary_model.pressure[1] - @test isapprox(expected_force, zeros(2); atol=sqrt(eps())) - else - @test !iszero(expected_force) - end - - if boundary_density isa ContinuityDensity - # Independently evaluate d(rho_s)/dt = (rho_s/rho_f) m_f (v_s-v_f) ⋅ ∇_s W. - # Cubic-spline derivative at r/h = 1.5 in 2D, with h = 1. - kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) - expected_density_rate = -reference_density / fluid_state.density * - fluid.mass[1] * fluid_state.velocity[1] * - kernel_derivative - dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) - @test dv_structure[end, 1] ≈ expected_density_rate - end - - if structure isa RigidBodySystem - # kick! must carry the particle reaction through to the body resultant. - @test isapprox(structure.resultant_force[], expected_force; - rtol=sqrt(eps()), atol=sqrt(eps())) - else - # Include clamped particles when checking the pair reaction directly. - dv_structure_fluid = zeros(eltype(structure), ndims(structure), - nparticles(structure)) - TrixiParticles.interact!(dv_structure_fluid, v_structure, u_structure, - v_fluid, u_fluid, structure, fluid, semi; - eachparticle=eachparticle(structure)) - @test isapprox(structure.mass[1] * dv_structure_fluid[:, 1], expected_force; - rtol=sqrt(eps()), atol=sqrt(eps())) - - if structure_kind == :tlsph - # An integrated particle must receive the same reaction in the full RHS. - dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) - @test isapprox(structure.mass[1] * dv_structure[1:2, 1], expected_force; - rtol=sqrt(eps()), atol=sqrt(eps())) - end - end - end - end -end From 94e3656b4834ea2647b469edf32e3258dafdecf8 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 6 Oct 2026 09:28:10 +0200 Subject: [PATCH 24/46] update --- NEWS.md | 2 +- src/schemes/structure/structure.jl | 23 ++- test/schemes/fluid/rhs.jl | 231 +++++++++++++++++++---------- 3 files changed, 170 insertions(+), 86 deletions(-) diff --git a/NEWS.md b/NEWS.md index 21e0f1f175..4031e34ac1 100644 --- a/NEWS.md +++ b/NEWS.md @@ -17,7 +17,7 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes -- Fixed structure-fluid reaction forces with non-odd corrected fluid kernel +- Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel gradients by evaluating the fluid-first gradient directly (#1338). - Fixed asymmetric DEM contact forces near coincidence by using a pair-local radius scale for the near-zero distance cutoff (#1347). diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 7a35f5e931..e655693966 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -51,6 +51,7 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) h = initial_smoothing_length(neighbor_system) + correction = system_correction(neighbor_system) # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -67,10 +68,9 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # to obtain the same force as in the fluid-structure interaction. grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, distance, neighbor) - # Corrected gradients need not be odd, so evaluate the fluid-first gradient - # directly instead of negating the structure-first gradient. - grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, - distance, neighbor) + grad_kernel_fluid = fluid_reaction_kernel_grad(correction, neighbor_system, + pos_diff, distance, neighbor, + grad_kernel) m_b = hydrodynamic_mass(neighbor_system, neighbor) @@ -120,6 +120,21 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, return dv end +@inline function fluid_reaction_kernel_grad(::Nothing, system, pos_diff, distance, particle, + grad_kernel) + # Reversing the displacement changes only the sign of the uncorrected gradient. + # Reuse it with the opposite sign to obtain the fluid-first gradient. + return -grad_kernel +end + +@inline function fluid_reaction_kernel_grad(correction, system, pos_diff, distance, + particle, + grad_kernel) + # With corrections, reversing the displacement may not be equivalent to negating + # the gradient. Evaluate it with the fluid-first displacement instead. + return smoothing_kernel_grad_unsafe(system, -pos_diff, distance, particle) +end + @inline function add_continuity_equation(drho_particle, particle_system::AbstractStructureSystem, neighbor_system::AbstractFluidSystem, diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 6f0809da4e..5bfba6ec87 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -306,7 +306,8 @@ end function create_structure_system(structure_type, viscosity; - density_calculator=AdamiPressureExtrapolation()) + boundary_density=AdamiPressureExtrapolation(), + clamped=false) # The material mass is twice the hydrodynamic mass, so using the wrong mass # to convert the force on the structure to an acceleration fails the test. structure = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), @@ -316,7 +317,7 @@ boundary_model = BoundaryModelDummyParticles([fluid_density], [fluid_density * particle_spacing^2], - density_calculator, + boundary_density, smoothing_kernel, smoothing_length; state_equation, viscosity) @@ -324,7 +325,8 @@ if structure_type === TotalLagrangianSPHSystem return TotalLagrangianSPHSystem(structure; smoothing_kernel, smoothing_length, young_modulus=1e5, - poisson_ratio=0.3, boundary_model) + poisson_ratio=0.3, boundary_model, + clamped_particles=clamped ? (1:1) : (1:0)) end return RigidBodySystem(structure; boundary_model) @@ -334,8 +336,16 @@ # for the viscosity, and the average pressure of EDAC. Return the systems # stored in the semidiscretization and the wrapped arrays. function initialize(fluid_system, structure_system) - semi = Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) + semi = if structure_system isa TotalLagrangianSPHSystem + @test_logs (:info, + r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin + Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end + else + @test_logs Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end ode = semidiscretize(semi, (0.0, 0.01)) v_ode, u_ode = ode.u0.x TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) @@ -347,7 +357,7 @@ TrixiParticles.wrap_v(v_ode, structure, semi), TrixiParticles.wrap_u(u_ode, structure, semi)) - return fluid, structure, arrays, semi + return fluid, structure, arrays, semi, ode end # Force on the fluid particle and force on the structure particle @@ -363,9 +373,17 @@ structure.force_per_particle .= 0 end - dv_structure = zero(v_structure) - TrixiParticles.interact!(dv_structure, v_structure, u_structure, - v_fluid, u_fluid, structure, fluid, semi) + # Include clamped TLSPH particles when checking their hydrodynamic loads. + dv_structure = zeros(eltype(v_structure), size(v_structure, 1), + nparticles(structure)) + if structure isa TotalLagrangianSPHSystem + TrixiParticles.interact!(dv_structure, v_structure, u_structure, + v_fluid, u_fluid, structure, fluid, semi; + eachparticle=eachparticle(structure)) + else + TrixiParticles.interact!(dv_structure, v_structure, u_structure, + v_fluid, u_fluid, structure, fluid, semi) + end if structure isa RigidBodySystem # The rigid body accumulates the forces per particle @@ -378,9 +396,7 @@ return force_fluid, force_structure end - # All viscosity models are tested with WCSPH. The EDAC variants differ only - # in the pressure term, so they are only tested without viscosity and with one - # viscosity model. + # Exercise all viscosity models with WCSPH and both EDAC pressure variants. configurations = [ ("WCSPH", nothing), ("WCSPH", ViscosityAdami(nu=0.1)), @@ -388,8 +404,13 @@ ("WCSPH", ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)), ("EDAC", nothing), ("EDAC", ViscosityAdami(nu=0.1)), + ("EDAC", ViscosityMorris(nu=0.1)), + ("EDAC", ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)), ("EDAC with average pressure reduction", nothing), - ("EDAC with average pressure reduction", ViscosityAdami(nu=0.1)) + ("EDAC with average pressure reduction", ViscosityAdami(nu=0.1)), + ("EDAC with average pressure reduction", ViscosityMorris(nu=0.1)), + ("EDAC with average pressure reduction", + ArtificialViscosityMonaghan(alpha=0.1, beta=0.2)) ] # The structure lies to the right of the fluid particle, so a positive @@ -402,83 +423,130 @@ ] structure_types = (TotalLagrangianSPHSystem, RigidBodySystem) + structure_configurations = ((TotalLagrangianSPHSystem, false), + (TotalLagrangianSPHSystem, true), + (RigidBodySystem, false)) + correction_methods = (nothing, AkinciFreeSurfaceCorrection(fluid_density), + KernelCorrection(), GradientCorrection(), + BlendedGradientCorrection(0.5), + MixedKernelGradientCorrection()) @testset "$(config[1]), Viscosity `$(nameof(typeof(config[2])))`" for config in configurations scheme, viscosity = config + corrections = scheme == "WCSPH" ? correction_methods : (nothing,) - @testset "`$structure_type`" for structure_type in structure_types - @testset "$(state.name)" for state in fluid_states - fluid_system = create_fluid_system(scheme, state.velocity, - state.density, viscosity) - structure_system = create_structure_system(structure_type, viscosity) - (fluid, structure, arrays, - semi) = initialize(fluid_system, structure_system) - (force_fluid, - force_structure) = pair_forces(fluid, structure, arrays, semi) - - # Newton's third law - @test isapprox(force_structure, -force_fluid, - rtol=sqrt(eps()), atol=sqrt(eps())) - - if state.density == fluid_density - if isnothing(viscosity) || - (viscosity isa ArtificialViscosityMonaghan && - state.velocity[1] < 0) - # No pressure, and Monaghan's artificial viscosity is only - # active for approaching particles. - @test iszero(force_structure) - else - # The fluid drags the structure along - @test force_structure[1] * state.velocity[1] > 0 - end - elseif isnothing(viscosity) - if scheme == "EDAC with average pressure reduction" - # With a single fluid particle, the average pressure equals - # the pressure of the fluid particle, which is also - # the extrapolated pressure of the structure particle. - @test isapprox(force_structure, zeros(2), atol=sqrt(eps())) - else - # Positive pressure pushes the structure away from the - # fluid particle, in positive x-direction. - @test force_structure[1] > 0 - end + @testset "Correction `$(nameof(typeof(correction)))`" for correction in + corrections + + @testset "`$structure_type`, clamped=$clamped" for (structure_type, + clamped) in + structure_configurations + + boundary_densities = if correction isa KernelCorrection || + correction isa MixedKernelGradientCorrection + (AdamiPressureExtrapolation(), SummationDensity()) + elseif scheme == "WCSPH" && isnothing(correction) && + structure_type === RigidBodySystem + (AdamiPressureExtrapolation(), ContinuityDensity()) + else + (AdamiPressureExtrapolation(),) end - end - end - end - @testset "Corrected gradients `$(nameof(typeof(correction)))`" for correction in - (KernelCorrection(), - MixedKernelGradientCorrection()) - @testset "`$structure_type`, viscosity `$(nameof(typeof(viscosity)))`" for structure_type in - structure_types, - viscosity in - (nothing, - ViscosityAdami(nu=0.1), - ViscosityMorris(nu=0.1)) + @testset "Boundary `$(nameof(typeof(boundary_density)))`" for boundary_density in + boundary_densities + + @testset "$(state.name)" for state in fluid_states + fluid_system = create_fluid_system(scheme, state.velocity, + state.density, viscosity; + correction) + structure_system = create_structure_system(structure_type, + viscosity; + boundary_density, + clamped) + (fluid, structure, arrays, + semi, ode) = initialize(fluid_system, structure_system) + # Isolate the pair using the same updated correction and + # boundary-interpolation caches as the full RHS. + v_ode, u_ode = ode.u0.x + dv_ode = zero(v_ode) + TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) + (force_fluid, + force_structure) = pair_forces(fluid, structure, arrays, semi) + v_fluid, _, _, _ = arrays + + if correction isa KernelCorrection || + correction isa MixedKernelGradientCorrection + # Verify that reversing the displacement does not just + # change the sign of the corrected gradient in this fixture. + pos_diff = SVector(1.5, 0.0) + grad_kernel = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + pos_diff, + 1.5, + 1) + grad_kernel_fluid = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + -pos_diff, + 1.5, + 1) + @test !isapprox(grad_kernel_fluid, -grad_kernel) + end - fluid_system = create_fluid_system("WCSPH", (1.0, 0.5), 1005.0, - viscosity; correction) - structure_system = create_structure_system(structure_type, viscosity; - density_calculator=SummationDensity()) - fluid, structure, arrays, semi = initialize(fluid_system, structure_system) - - # The correction adds a non-odd term. Negating the structure-first - # gradient therefore does not reproduce the fluid-first gradient. - pos_diff = SVector(1.5, 0.0) - grad_kernel = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, - 1.5, 1) - grad_kernel_fluid = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, - -pos_diff, - 1.5, 1) - @test !isapprox(grad_kernel_fluid, -grad_kernel) + # Newton's third law, including hydrodynamic/material mass conversion. + @test isapprox(force_structure, -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + + if state.density == fluid_density + @test iszero(TrixiParticles.current_pressure(v_fluid, fluid, + 1)) + @test iszero(structure.boundary_model.pressure[1]) + if isnothing(viscosity) || + (viscosity isa ArtificialViscosityMonaghan && + state.velocity[1] < 0) + # No pressure, and Monaghan viscosity is inactive for receding particles. + @test iszero(force_structure) + else + # The fluid drags the structure along. + @test force_structure[1] * state.velocity[1] > 0 + end + elseif isnothing(viscosity) + if scheme == "EDAC with average pressure reduction" + @test TrixiParticles.current_pressure(v_fluid, fluid, + 1) ≈ + structure.boundary_model.pressure[1] + @test isapprox(force_structure, zeros(2), + atol=sqrt(eps())) + else + @test force_structure[1] > 0 + end + else + @test !iszero(force_fluid) + end - force_fluid, force_structure = pair_forces(fluid, structure, arrays, semi) - @test !iszero(force_fluid) - @test isapprox(force_structure, -force_fluid, - rtol=sqrt(eps()), atol=sqrt(eps())) + # Also check that the normal RHS carries the pair reaction + # through to integrated TLSPH particles and rigid-body resultants. + dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) + if structure isa RigidBodySystem + @test isapprox(structure.resultant_force[], -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + elseif !clamped + @test isapprox(structure.mass[1] * dv_structure[1:2, 1], + -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + end + + if boundary_density isa ContinuityDensity + # Independently evaluate the structure-first continuity + # operator using the cubic-spline derivative at r/h = 1.5. + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -fluid_density / state.density * + fluid.mass[1] * state.velocity[1] * + kernel_derivative + @test dv_structure[end, 1] ≈ expected_density_rate + end + end + end + end end end @@ -495,7 +563,8 @@ fluid_system = create_fluid_system("WCSPH", (1.0, 0.5), 1005.0, viscosity; shifting_technique) structure_system = create_structure_system(structure_type, viscosity) - fluid, structure, arrays, semi = initialize(fluid_system, structure_system) + fluid, structure, arrays, semi, + _ = initialize(fluid_system, structure_system) # Compare the forces without and with a shifting velocity fluid.cache.delta_v .= 0 From bf34bfa003917d5da780002c4b9a9e512e128c1b Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 6 Oct 2026 12:18:10 +0200 Subject: [PATCH 25/46] Fold pressure-mirroring coverage into the FSI force-balance tests Drop the standalone pair fixtures and add PressureMirroring to the boundary-density matrix of the existing FSI tests instead. Skip the boundary-cache pressure comparison for mirroring, whose cache stays at its initial value. Keep the base branch NEWS entries verbatim and only add the pressure-mirroring entry. --- NEWS.md | 11 +- test/schemes/boundary/pressure_mirroring.jl | 69 ----------- test/schemes/fluid/rhs.jl | 19 +++- test/schemes/schemes.jl | 2 - .../structure/fluid_interaction_helpers.jl | 107 ------------------ 5 files changed, 16 insertions(+), 192 deletions(-) delete mode 100644 test/schemes/boundary/pressure_mirroring.jl delete mode 100644 test/schemes/structure/fluid_interaction_helpers.jl diff --git a/NEWS.md b/NEWS.md index e04b950ac9..908d382bc7 100644 --- a/NEWS.md +++ b/NEWS.md @@ -20,14 +20,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for - Fixed pressure mirroring for TLSPH and rigid-body neighbors and for EDAC momentum, pressure diffusion, and average-pressure reduction at walls and structures (#1341). - Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel - gradients by evaluating the fluid-first gradient directly, correcting pressure and - viscous reaction forces on TLSPH and rigid-body systems, including free-surface - factors, EDAC pressure reduction, and the approaching-particle condition for - artificial viscosity (#1338). -- Unified near-zero distance checks using the relative squared-distance criterion - `r^2 < eps(typeof(h)) * h^2` across kernels and particle operators, fixing - asymmetric DEM contact forces near coincidence with a pair-local radius scale - (#1347). + gradients by evaluating the fluid-first gradient directly (#1338). +- Fixed asymmetric DEM contact forces near coincidence by using a pair-local + radius scale for the near-zero distance cutoff (#1347). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode diff --git a/test/schemes/boundary/pressure_mirroring.jl b/test/schemes/boundary/pressure_mirroring.jl deleted file mode 100644 index f19d75f70b..0000000000 --- a/test/schemes/boundary/pressure_mirroring.jl +++ /dev/null @@ -1,69 +0,0 @@ -using .FSIPairFixtures: structure_fluid_pair_state - -@testset verbose=true "Pressure mirroring across fluid schemes" begin - # Prescribed pressure also exercises the IISPH pair RHS without a pressure solve. - for scheme in (:wcsph, :edac, :iisph), kind in (:wall, :tlsph, :rigid) - state = structure_fluid_pair_state(; fluid_scheme=scheme, structure_kind=kind, - boundary_density=PressureMirroring()) - (; fluid, structure, semi, v_fluid, u_fluid, v_structure, u_structure) = state - # The boundary cache intentionally holds 230 instead of the fluid's 500. - # Mirroring must be pair-local: reading or overwriting the cache would be wrong - # when neighboring fluid particles have different pressures. - @test TrixiParticles.neighbor_pressure(v_structure, structure, 1, 500.0) == 500.0 - @test structure.boundary_model.pressure[1] == 230.0 - dv_fluid = zero(v_fluid) - TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, - fluid, structure, semi) - # At r/h = 1.5, W'(r) = -15/(56pi); x_f - x_s points left, so grad_f points right. - grad_f = [15 / (56pi), 0.0] - # Evaluate each scheme's pressure law independently with p_s = p_f = 500. - # WCSPH uses m_s(p_f+p_s)/(rho_f rho_s); EDAC uses (V_f^2+V_s^2)p/m_f; - # IISPH uses m_s(p_f/rho_f^2+p_s/rho_s^2), with V = m/rho. - coefficient = if scheme == :wcsph - 700.0 * 1000.0 / (1005.0 * 950.0) - elseif scheme == :edac - ((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 * 500.0 - else - 700.0 * (500.0 / 1005.0^2 + 500.0 / 950.0^2) - end - @test dv_fluid[1:2, 1] ≈ -coefficient * grad_f - if kind != :wall - # Structural acceleration uses material mass; both representations must - # recover the same physical reaction -m_f a_f. Fixed walls have no RHS load. - dv_structure = zero(v_structure) - TrixiParticles.reset_interaction_caches!(structure) - TrixiParticles.interact!(dv_structure, v_structure, u_structure, v_fluid, - u_fluid, - structure, fluid, semi) - force = kind == :rigid ? structure.force_per_particle[:, 1] : - structure.mass[1] * dv_structure[1:2, 1] - @test force ≈ -1100.0 * dv_fluid[1:2, 1] - end - end - - @testset "EDAC wall pressure evolution and average" begin - for average_pressure_reduction in (false, true) - state = structure_fluid_pair_state(; fluid_scheme=:edac, structure_kind=:wall, - boundary_density=PressureMirroring(), - fluid_options=(; average_pressure_reduction)) - (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, - u_structure) = state - TrixiParticles.update_average_pressure!(fluid, fluid.average_pressure_reduction, - ode.u0.x[1], ode.u0.x[2], semi) - # Self and mirrored wall neighbors both contribute 500. Reading the stale - # wall cache (230) would change the mean and leave a spurious pressure force. - p_avg = average_pressure_reduction ? 500.0 : 0.0 - @test TrixiParticles.average_pressure(fluid, 1) == p_avg - dv_fluid = zero(v_fluid) - TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, u_structure, - fluid, structure, semi) - grad_f = [15 / (56pi), 0.0] - volume_term = ((1100.0 / 1005.0)^2 + (700.0 / 950.0)^2) / 1100.0 - @test dv_fluid[1:2, 1] ≈ -volume_term * (500.0 - p_avg) * grad_f - # Mirroring makes p_f-p_s zero, eliminating EDAC diffusion. Only its - # artificial EOS remains: dp_f/dt = m_s rho_f/rho_s c^2 (v_f-v_s) dot grad_f. - # The fixed wall has v_s = 0; row 3 stores pressure after the two velocity rows. - @test dv_fluid[3, 1] ≈ 700.0 * 1005.0 / 950.0 * 10.0^2 * dot([1.0, 0.5], grad_f) - end - end -end diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 5bfba6ec87..1131d90693 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -446,12 +446,14 @@ boundary_densities = if correction isa KernelCorrection || correction isa MixedKernelGradientCorrection - (AdamiPressureExtrapolation(), SummationDensity()) + (AdamiPressureExtrapolation(), SummationDensity(), + PressureMirroring()) elseif scheme == "WCSPH" && isnothing(correction) && structure_type === RigidBodySystem - (AdamiPressureExtrapolation(), ContinuityDensity()) + (AdamiPressureExtrapolation(), ContinuityDensity(), + PressureMirroring()) else - (AdamiPressureExtrapolation(),) + (AdamiPressureExtrapolation(), PressureMirroring()) end @testset "Boundary `$(nameof(typeof(boundary_density)))`" for boundary_density in @@ -511,9 +513,14 @@ end elseif isnothing(viscosity) if scheme == "EDAC with average pressure reduction" - @test TrixiParticles.current_pressure(v_fluid, fluid, - 1) ≈ - structure.boundary_model.pressure[1] + # `PressureMirroring` leaves the cache at its + # initial value, so only compare for Adami. + if boundary_density isa AdamiPressureExtrapolation + @test TrixiParticles.current_pressure(v_fluid, + fluid, + 1) ≈ + structure.boundary_model.pressure[1] + end @test isapprox(force_structure, zeros(2), atol=sqrt(eps())) else diff --git a/test/schemes/schemes.jl b/test/schemes/schemes.jl index 68a035b147..bb6e9d5483 100644 --- a/test/schemes/schemes.jl +++ b/test/schemes/schemes.jl @@ -1,6 +1,4 @@ include("structure/total_lagrangian_sph/total_lagrangian_sph.jl") -include("structure/fluid_interaction_helpers.jl") -include("boundary/pressure_mirroring.jl") include("boundary/dummy_particles/dummy_particles.jl") include("boundary/monaghan_kajtar/monaghan_kajtar.jl") include("boundary/open_boundary/open_boundary.jl") diff --git a/test/schemes/structure/fluid_interaction_helpers.jl b/test/schemes/structure/fluid_interaction_helpers.jl deleted file mode 100644 index 5018b0570d..0000000000 --- a/test/schemes/structure/fluid_interaction_helpers.jl +++ /dev/null @@ -1,107 +0,0 @@ -module FSIPairFixtures -using TrixiParticles -using LinearAlgebra: I -using Test: @test_logs - -export structure_fluid_pair_state - -# Prescribed pair states isolate interaction operators from density/pressure updates. -# Defaults put one fluid particle at the origin and a boundary particle at r/h = 1.5, -# inside the cubic-spline support. Unequal masses, densities, pressures, and velocities -# make swapped arguments or accidental use of material quantities observable. -function structure_fluid_pair_state(; fluid_scheme=:wcsph, structure_kind=:tlsph, - fluid_options=(;), - boundary_density=AdamiPressureExtrapolation(), - distance=1.5, dimensions=2, - coordinates=reshape([distance; zeros(dimensions - 1)], - dimensions, 1), - parallelization_backend=SerialBackend()) - smoothing_kernel = SchoenbergCubicSplineKernel{dimensions}() - smoothing_length = particle_spacing = 1.0 - state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1000.0, - exponent=1.0, clip_negative_pressure=false) - velocity = reshape([1.0, 0.5, 0.7][1:dimensions], dimensions, 1) - fluid_ic = InitialCondition(; coordinates=zeros(dimensions, 1), velocity, - mass=[1100.0], density=[1005.0], pressure=500.0, - particle_spacing) - options = (; density_calculator=ContinuityDensity(), reference_particle_spacing=1.0, - fluid_options...) - fluid = if fluid_scheme == :wcsph - WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - state_equation, options...) - elseif fluid_scheme == :edac - # Keep absolute pressure by default; individual reduction tests opt in explicitly. - options = (; average_pressure_reduction=false, options...) - EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - sound_speed=10.0, options...) - else - # Prescribe pressure for the IISPH pair RHS instead of invoking its PPE solve. - ImplicitIncompressibleSPHSystem(fluid_ic; smoothing_kernel, smoothing_length, - reference_density=1005.0, time_step=0.001, - viscosity=get(fluid_options, :viscosity, nothing)) - end - n = size(coordinates, 2) - structure_velocity = repeat(reshape([0.25, -0.4, 0.2][1:dimensions], dimensions, 1), 1, - n) - # Material masses differ from the boundary model's hydrodynamic masses below. - # Varying them with particle index also exercises nonuniform force/torque weights. - structure_ic = InitialCondition(; coordinates, velocity=structure_velocity, - mass=2100.0 .+ 300.0 .* (0:(n - 1)), - density=fill(2000.0, n), - particle_spacing) - viscosity = get(fluid_options, :viscosity, nothing) - boundary_model = BoundaryModelDummyParticles(fill(950.0, n), - 700.0 .+ 50.0 .* (0:(n - 1)), - boundary_density, smoothing_kernel, - smoothing_length; - state_equation, viscosity, - reference_particle_spacing=1.0) - structure = if structure_kind == :rigid - RigidBodySystem(structure_ic; boundary_model, adhesion_coefficient=0.25) - elseif structure_kind == :wall - WallBoundarySystem(structure_ic, boundary_model) - else - TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, smoothing_length, - young_modulus=1.0e5, poisson_ratio=0.3, boundary_model) - end - # Assert the expected TLS-copy notice and reject any other setup logs or warnings. - semi = if structure isa TotalLagrangianSPHSystem - @test_logs (:info, - r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin - Semidiscretization(fluid, structure; parallelization_backend) - end - else - @test_logs Semidiscretization(fluid, structure; parallelization_backend) - end - ode = semidiscretize(semi, (0.0, 0.01); reset_threads=false) - # Modify the semidiscretization-owned TLS copy used by the actual pair operators. - fluid, structure = semi.systems - v_ode, u_ode = ode.u0.x - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) - v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) - u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - # These states are imposed directly so pressure extrapolation or a density update - # cannot make the fluid and boundary values equal and hide an argument-order bug. - TrixiParticles.current_density(v_fluid, fluid) .= 1005.0 - TrixiParticles.current_pressure(v_fluid, fluid) .= 500.0 - structure.boundary_model.pressure .= 230.0 - # A single fluid neighbor gives the no-slip ghost velocity 2v_s - v_f. - !isnothing(viscosity) && - (structure.boundary_model.cache.wall_velocity .= 2 .* structure_velocity .- - velocity) - # Prescribed nonzero shifts and non-unit correction data give independent pair - # expectations; cache-construction tests must populate their own caches via updates. - for (field, value) in ((:delta_v, [0.4, -0.3, 0.2][1:dimensions]), - (:dw_gamma, [0.1, -0.2, 0.15][1:dimensions]), - (:kernel_correction_coefficient, 1.3), (:pressure_average, 120.0)) - haskey(fluid.cache, field) && (getproperty(fluid.cache, field) .= value) - end - if haskey(fluid.cache, :correction_matrix) - # The off-diagonal entry exposes component mixing for non-radial gradients. - fluid.cache.correction_matrix[:, :, 1] .= Matrix{Float64}(I, dimensions, dimensions) - fluid.cache.correction_matrix[1, 2, 1] = 0.3 - end - return (; fluid, structure, semi, ode, v_fluid, u_fluid, v_structure, u_structure) -end -end From dbbbd49fbb2a72bebc2aa3255db2d8d7cc3e0e11 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 6 Oct 2026 12:19:35 +0200 Subject: [PATCH 26/46] Restore CRLF line ending on the inherited NEWS entry --- NEWS.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NEWS.md b/NEWS.md index 908d382bc7..f580267136 100644 --- a/NEWS.md +++ b/NEWS.md @@ -22,7 +22,7 @@ used in the Julia ecosystem. Notable changes will be documented in this file for - Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel gradients by evaluating the fluid-first gradient directly (#1338). - Fixed asymmetric DEM contact forces near coincidence by using a pair-local - radius scale for the near-zero distance cutoff (#1347). + radius scale for the near-zero distance cutoff (#1347). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). - Fixed mathematical inconsistencies in the SPH documentation, including incorrect formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode From 138cfc5472c7b4e50e50b8cef1e34267d2422beb Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Sun, 18 Oct 2026 19:53:34 +0200 Subject: [PATCH 27/46] Update src/schemes/structure/structure.jl Co-authored-by: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> --- src/schemes/structure/structure.jl | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index e655693966..c036c3c40f 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -120,14 +120,14 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, return dv end -@inline function fluid_reaction_kernel_grad(::Nothing, system, pos_diff, distance, particle, +@inline function fluid_reaction_kernel_grad(correction, system, pos_diff, distance, particle, grad_kernel) # Reversing the displacement changes only the sign of the uncorrected gradient. # Reuse it with the opposite sign to obtain the fluid-first gradient. return -grad_kernel end -@inline function fluid_reaction_kernel_grad(correction, system, pos_diff, distance, +@inline function fluid_reaction_kernel_grad(::Union{SomeCorrection, AnotherCorrection}, system, pos_diff, distance, particle, grad_kernel) # With corrections, reversing the displacement may not be equivalent to negating From 552123903fc05ab723f1f47cef01f7505a51f397 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Sun, 18 Oct 2026 21:07:18 +0200 Subject: [PATCH 28/46] address review --- NEWS.md | 6 +- .../boundary/wall_boundary/dummy_particles.jl | 5 +- src/schemes/structure/rigid_body/system.jl | 2 +- src/schemes/structure/structure.jl | 79 +++++---- .../structure/total_lagrangian_sph/system.jl | 2 +- test/general/semidiscretization.jl | 160 ++++++++++-------- test/schemes/fluid/rhs.jl | 80 +++++---- 7 files changed, 193 insertions(+), 141 deletions(-) diff --git a/NEWS.md b/NEWS.md index 4031e34ac1..0530fa0f3e 100644 --- a/NEWS.md +++ b/NEWS.md @@ -11,9 +11,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for - Replaced the experimental `MechanicalWorkCalculatorCallback` with `MechanicalWorkCalculator`, which can be passed as a custom quantity to `PostprocessCallback` (#1228). -- The compact support of a `BoundaryModelDummyParticles` of a `TotalLagrangianSPHSystem` - or `RigidBodySystem` must now be the same as the compact support of all fluid systems - in the simulation (#1348). +- The smoothing kernel and smoothing length of a `BoundaryModelDummyParticles` of a + `TotalLagrangianSPHSystem` or `RigidBodySystem` must now be the same as those of all + fluid systems in the simulation (#1338, #1348). ### Important Bugfixes diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index 8e44218543..b8dd014f3a 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -15,10 +15,11 @@ Boundary model for [`WallBoundarySystem`](@ref). - `density_calculator`: Strategy to compute the hydrodynamic density of the boundary particles. See [the docs](@ref boundary_models) for more information. - `smoothing_kernel`: Smoothing kernel should be the same as for the adjacent fluid system. + For a [`TotalLagrangianSPHSystem`](@ref) or a [`RigidBodySystem`](@ref), + it must be the same as for all fluid systems in the simulation. - `smoothing_length`: Smoothing length should be the same as for the adjacent fluid system. For a [`TotalLagrangianSPHSystem`](@ref) or a [`RigidBodySystem`](@ref), - the compact support of `smoothing_kernel` and `smoothing_length` - must be the same as for all fluid systems in the simulation. + it must be the same as for all fluid systems in the simulation. # Keywords - `state_equation`: This should be the same as for the adjacent fluid system diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index 0255ad38d6..74222d7970 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -630,7 +630,7 @@ function check_configuration(system::RigidBodySystem, systems, nhs) "when simulating a fluid-structure interaction.")) end - check_compact_support_fsi(system, boundary_model, neighbor) + check_smoothing_kernel_fsi(system, boundary_model, neighbor) if neighbor isa AbstractFluidSystem && neighbor.surface_normal_method isa ColorfieldSurfaceNormal diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index c036c3c40f..fae631b4fe 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -19,27 +19,28 @@ end # The structure-fluid interaction computes the opposite of the force that the fluid # experiences in the fluid-structure interaction. Therefore, both interactions must find -# the same pairs of particles, so the neighborhood search of the structure must use -# the compact support of the fluid. +# the same pairs of particles. Reusing the structure-side gradient with the opposite +# sign also requires the same smoothing kernel and smoothing length. # Note that this is only a restriction for `BoundaryModelDummyParticles`, since # `BoundaryModelMonaghanKajtar` always uses the compact support of the fluid. -function check_compact_support_fsi(system, ::BoundaryModelDummyParticles, - neighbor_system::AbstractFluidSystem) - compact_support_structure = compact_support(system, neighbor_system) - compact_support_fluid = compact_support(neighbor_system, system) - - if !isapprox(compact_support_structure, compact_support_fluid) - throw(ArgumentError("the compact support of the boundary model of the " * - "`$(nameof(typeof(system)))` ($compact_support_structure) " * - "must be the same as the compact support of the fluid system " * - "($compact_support_fluid). Use the same smoothing kernel and " * - "smoothing length for the boundary model as for the fluid.")) +function check_smoothing_kernel_fsi(system, boundary_model::BoundaryModelDummyParticles, + neighbor_system::AbstractFluidSystem) + smoothing_kernel_structure = boundary_model.smoothing_kernel + smoothing_kernel_fluid = system_smoothing_kernel(neighbor_system) + smoothing_length_structure = initial_smoothing_length(boundary_model) + smoothing_length_fluid = initial_smoothing_length(neighbor_system) + + if smoothing_kernel_structure != smoothing_kernel_fluid || + smoothing_length_structure != smoothing_length_fluid + throw(ArgumentError("the smoothing kernel and smoothing length of the boundary " * + "model of the `$(nameof(typeof(system)))` must be the same " * + "as those of the fluid system `$(nameof(typeof(neighbor_system)))`.")) end return system end -check_compact_support_fsi(system, boundary_model, neighbor_system) = system +check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, @@ -51,7 +52,15 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) h = initial_smoothing_length(neighbor_system) + h_structure = initial_smoothing_length(particle_system) + support_structure = compact_support(system_smoothing_kernel(particle_system), + h_structure) correction = system_correction(neighbor_system) + # TLSPH may use a different kernel for solid mechanics. Only reuse its gradient + # when it is uncorrected and uses the same kernel and smoothing length as the fluid. + reuse_grad_kernel = system_smoothing_kernel(particle_system) == + system_smoothing_kernel(neighbor_system) && + h_structure == h && system_correction(particle_system) === nothing # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -62,15 +71,21 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(neighbor_system) && distance < almostzero(h) && return - # Now that we know that `distance` is not zero, we can safely call the unsafe - # version of the kernel gradient to avoid redundant zero checks. - # Note that we use the `neighbor_system` to compute the kernel gradient - # to obtain the same force as in the fluid-structure interaction. - grad_kernel = smoothing_kernel_grad_unsafe(neighbor_system, pos_diff, - distance, neighbor) - grad_kernel_fluid = fluid_reaction_kernel_grad(correction, neighbor_system, - pos_diff, distance, neighbor, - grad_kernel) + # The continuity equation uses the structure-side gradient. It may be zero + # at coincidence even when the corrected fluid gradient is nonzero. + grad_kernel = if distance >= support_structure || + (skip_zero_distance(particle_system) && + distance < almostzero(h_structure)) + zero(pos_diff) + else + smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) + end + grad_kernel_fluid = if reuse_grad_kernel + fluid_kernel_grad_unsafe(correction, neighbor_system, + pos_diff, distance, neighbor, grad_kernel) + else + smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, distance, neighbor) + end m_b = hydrodynamic_mass(neighbor_system, neighbor) @@ -120,18 +135,20 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, return dv end -@inline function fluid_reaction_kernel_grad(correction, system, pos_diff, distance, particle, - grad_kernel) - # Reversing the displacement changes only the sign of the uncorrected gradient. +@inline function fluid_kernel_grad_unsafe(correction, system, pos_diff, distance, particle, + grad_kernel) + # Matching uncorrected kernels change sign with the displacement. # Reuse it with the opposite sign to obtain the fluid-first gradient. return -grad_kernel end -@inline function fluid_reaction_kernel_grad(::Union{SomeCorrection, AnotherCorrection}, system, pos_diff, distance, - particle, - grad_kernel) - # With corrections, reversing the displacement may not be equivalent to negating - # the gradient. Evaluate it with the fluid-first displacement instead. +@inline function fluid_kernel_grad_unsafe(::Union{KernelCorrection, GradientCorrection, + BlendedGradientCorrection, + MixedKernelGradientCorrection}, + system, pos_diff, distance, particle, + grad_kernel) + # These corrections depend on the fluid particle's local neighborhood, so its + # gradient cannot be obtained by negating the structure-side gradient. return smoothing_kernel_grad_unsafe(system, -pos_diff, distance, particle) end diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 1ec1c4f536..9a345c96ca 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -870,6 +870,6 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) end foreach_system(systems) do neighbor - check_compact_support_fsi(system, boundary_model, neighbor) + check_smoothing_kernel_fsi(system, boundary_model, neighbor) end end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index 2734128b99..e2be95de7b 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -129,81 +129,97 @@ hydrodynamic_mass::Any end - # Mock fluid system - struct FluidSystemMock <: TrixiParticles.AbstractFluidSystem{2} - surface_tension::Nothing - surface_normal_method::Nothing - FluidSystemMock() = new(nothing, nothing) - end - - kernel = Val(:smoothing_kernel) - Base.ndims(::Val{:smoothing_kernel}) = 2 - TrixiParticles.compact_support(::Val{:smoothing_kernel}, h) = h - + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.0 ic = InitialCondition(; particle_spacing=1.0, coordinates=ones(2, 2), density=[1.0, 1.0]) + state_equation = StateEquationCole(; sound_speed=10.0, reference_density=1.0, + exponent=1) + fluid_systems = (WeaklyCompressibleSPHSystem(ic; smoothing_kernel, + smoothing_length, state_equation, + density_calculator=ContinuityDensity()), + EntropicallyDampedSPHSystem(ic; smoothing_kernel, + smoothing_length, sound_speed=10.0, + density_calculator=ContinuityDensity())) + + function create_structure_system(structure_type, boundary_model) + structure_type === RigidBodySystem && + return structure_type(ic; boundary_model) + return structure_type(ic; smoothing_kernel, smoothing_length, + young_modulus=1.0, poisson_ratio=1.0, boundary_model, + self_interaction_nhs=TrixiParticles.TrivialNeighborhoodSearch{2}()) + end - fluid_system = FluidSystemMock() - model_a = BoundaryModelMock(zeros(2)) - model_b = BoundaryModelDummyParticles([1.0, 1.0], [1.0, 1.0], - ContinuityDensity(), kernel, 1.0) - model_c = BoundaryModelMock(zeros(3)) - - # FSI without boundary model - structure_system1 = TotalLagrangianSPHSystem(ic; - smoothing_kernel=kernel, - smoothing_length=1.0, - young_modulus=1.0, - poisson_ratio=1.0) - - error_str = "a boundary model for `TotalLagrangianSPHSystem` must be " * - "specified when simulating a fluid-structure interaction." - @test_throws ArgumentError(error_str) Semidiscretization(fluid_system, - structure_system1, - neighborhood_search=nothing) - - # FSI with boundary model - structure_system2 = TotalLagrangianSPHSystem(ic; - smoothing_kernel=kernel, - smoothing_length=1.0, - young_modulus=1.0, - poisson_ratio=1.0, - boundary_model=model_a) - structure_system2 = TrixiParticles.initialize_self_interaction_nhs(structure_system2, - nothing, - nothing) - - @test_nowarn TrixiParticles.check_configuration((structure_system2, - fluid_system), - nothing) - - # FSI with wrong boundary model - structure_system3 = TotalLagrangianSPHSystem(ic; - smoothing_kernel=kernel, - smoothing_length=1.0, - young_modulus=1.0, - poisson_ratio=1.0, - boundary_model=model_b) - - error_str = "`BoundaryModelDummyParticles` with density calculator " * - "`ContinuityDensity` is not yet supported for a `TotalLagrangianSPHSystem`" - @test_throws ArgumentError(error_str) Semidiscretization(structure_system3, - fluid_system, - neighborhood_search=nothing) - - # FSI with wrong boundary model - structure_system4 = TotalLagrangianSPHSystem(ic; - smoothing_kernel=kernel, - smoothing_length=1.0, - young_modulus=1.0, - poisson_ratio=1.0, - boundary_model=model_c) - - error_str = "the boundary model was initialized with 3 particles, " * - "but the `TotalLagrangianSPHSystem` has 2 particles." - @test_throws ArgumentError(error_str) Semidiscretization(structure_system4, - fluid_system, - neighborhood_search=nothing) + boundary_configurations = (("matching", smoothing_kernel, smoothing_length, + true), + ("different kernel, same support", + WendlandC2Kernel{2}(), 1.0, false), + ("different kernel and length, same support", + SchoenbergQuinticSplineKernel{2}(), 2 / 3, false), + ("different smoothing length", smoothing_kernel, 0.8, + false), + ("nearby smoothing length", smoothing_kernel, + nextfloat(1.0), false)) + + @testset "$(nameof(typeof(fluid_system))), $structure_type" for fluid_system in fluid_systems, + structure_type in (TotalLagrangianSPHSystem, + RigidBodySystem) + + # Missing boundary model. + structure = create_structure_system(structure_type, nothing) + error_str = "a boundary model for `$structure_type` must be specified " * + "when simulating a fluid-structure interaction." + @test_throws ArgumentError(error_str) Semidiscretization(fluid_system, + structure; + neighborhood_search=nothing) + + # User-defined boundary models and particle counts. + structure = create_structure_system(structure_type, + BoundaryModelMock(zeros(2))) + @test_nowarn TrixiParticles.check_configuration((structure, fluid_system), + nothing) + structure = create_structure_system(structure_type, + BoundaryModelMock(zeros(3))) + error_str = "the boundary model was initialized with 3 particles, " * + "but the `$structure_type` has 2 particles." + @test_throws ArgumentError(error_str) Semidiscretization(structure, + fluid_system; + neighborhood_search=nothing) + + if structure_type === TotalLagrangianSPHSystem + boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, + ContinuityDensity(), + smoothing_kernel, + smoothing_length) + structure = create_structure_system(structure_type, boundary_model) + error_str = "`BoundaryModelDummyParticles` with density calculator " * + "`ContinuityDensity` is not yet supported for a `TotalLagrangianSPHSystem`" + @test_throws ArgumentError(error_str) Semidiscretization(structure, + fluid_system; + neighborhood_search=nothing) + end + + @testset "$name" for (name, boundary_kernel, boundary_length, + compatible) in boundary_configurations + boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, + AdamiPressureExtrapolation(), + boundary_kernel, + boundary_length; + state_equation) + structure = create_structure_system(structure_type, boundary_model) + if compatible + @test_nowarn Semidiscretization(fluid_system, structure; + neighborhood_search=nothing) + else + error_str = "the smoothing kernel and smoothing length of the boundary " * + "model of the `$structure_type` must be the same " * + "as those of the fluid system `$(nameof(typeof(fluid_system)))`." + @test_throws ArgumentError(error_str) Semidiscretization(fluid_system, + structure; + neighborhood_search=nothing) + end + end + end end @testset verbose=true "WCSPH-Boundary Interaction" begin diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 5bfba6ec87..77f1ef3896 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -307,7 +307,8 @@ function create_structure_system(structure_type, viscosity; boundary_density=AdamiPressureExtrapolation(), - clamped=false) + clamped=false, + structure_smoothing_length=smoothing_length) # The material mass is twice the hydrodynamic mass, so using the wrong mass # to convert the force on the structure to an acceleration fails the test. structure = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), @@ -324,7 +325,8 @@ if structure_type === TotalLagrangianSPHSystem return TotalLagrangianSPHSystem(structure; smoothing_kernel, - smoothing_length, young_modulus=1e5, + smoothing_length=structure_smoothing_length, + young_modulus=1e5, poisson_ratio=0.3, boundary_model, clamped_particles=clamped ? (1:1) : (1:0)) end @@ -423,9 +425,13 @@ ] structure_types = (TotalLagrangianSPHSystem, RigidBodySystem) - structure_configurations = ((TotalLagrangianSPHSystem, false), - (TotalLagrangianSPHSystem, true), - (RigidBodySystem, false)) + structure_configurations = ((TotalLagrangianSPHSystem, false, smoothing_length), + (TotalLagrangianSPHSystem, false, + 0.5 * smoothing_length), + (TotalLagrangianSPHSystem, true, smoothing_length), + (TotalLagrangianSPHSystem, true, + 0.5 * smoothing_length), + (RigidBodySystem, false, smoothing_length)) correction_methods = (nothing, AkinciFreeSurfaceCorrection(fluid_density), KernelCorrection(), GradientCorrection(), BlendedGradientCorrection(0.5), @@ -440,18 +446,16 @@ @testset "Correction `$(nameof(typeof(correction)))`" for correction in corrections - @testset "`$structure_type`, clamped=$clamped" for (structure_type, - clamped) in - structure_configurations + @testset "`$structure_type`, clamped=$clamped, h=$structure_smoothing_length" for (structure_type, + clamped, + structure_smoothing_length) in structure_configurations - boundary_densities = if correction isa KernelCorrection || - correction isa MixedKernelGradientCorrection + # TLSPH does not yet support `ContinuityDensity` boundaries. + boundary_densities = if structure_type === TotalLagrangianSPHSystem (AdamiPressureExtrapolation(), SummationDensity()) - elseif scheme == "WCSPH" && isnothing(correction) && - structure_type === RigidBodySystem - (AdamiPressureExtrapolation(), ContinuityDensity()) else - (AdamiPressureExtrapolation(),) + (AdamiPressureExtrapolation(), SummationDensity(), + ContinuityDensity()) end @testset "Boundary `$(nameof(typeof(boundary_density)))`" for boundary_density in @@ -464,14 +468,10 @@ structure_system = create_structure_system(structure_type, viscosity; boundary_density, - clamped) + clamped, + structure_smoothing_length) (fluid, structure, arrays, semi, ode) = initialize(fluid_system, structure_system) - # Isolate the pair using the same updated correction and - # boundary-interpolation caches as the full RHS. - v_ode, u_ode = ode.u0.x - dv_ode = zero(v_ode) - TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) (force_fluid, force_structure) = pair_forces(fluid, structure, arrays, semi) v_fluid, _, _, _ = arrays @@ -480,6 +480,7 @@ correction isa MixedKernelGradientCorrection # Verify that reversing the displacement does not just # change the sign of the corrected gradient in this fixture. + # These corrected kernels are not symmetric. pos_diff = SVector(1.5, 0.0) grad_kernel = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, pos_diff, @@ -511,11 +512,19 @@ end elseif isnothing(viscosity) if scheme == "EDAC with average pressure reduction" - @test TrixiParticles.current_pressure(v_fluid, fluid, - 1) ≈ - structure.boundary_model.pressure[1] - @test isapprox(force_structure, zeros(2), - atol=sqrt(eps())) + if boundary_density isa AdamiPressureExtrapolation + @test TrixiParticles.current_pressure(v_fluid, + fluid, + 1) ≈ + structure.boundary_model.pressure[1] + @test isapprox(force_structure, zeros(2), + atol=sqrt(eps())) + else + # The boundary pressure stays zero, so subtracting + # the fluid's average pressure makes it attractive. + @test iszero(structure.boundary_model.pressure[1]) + @test force_structure[1] < 0 + end else @test force_structure[1] > 0 end @@ -525,19 +534,28 @@ # Also check that the normal RHS carries the pair reaction # through to integrated TLSPH particles and rigid-body resultants. + v_ode, u_ode = ode.u0.x + dv_ode = zero(v_ode) + TrixiParticles.kick!(dv_ode, v_ode, u_ode, ode.p, 0.0) + # `kick!` refreshes the correction caches, so compare forces + # from this RHS evaluation rather than the earlier pair call. + dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) + force_fluid_rhs = fluid.mass[1] * dv_fluid[1:2, 1] dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) if structure isa RigidBodySystem - @test isapprox(structure.resultant_force[], -force_fluid, + @test isapprox(structure.resultant_force[], + -force_fluid_rhs, rtol=sqrt(eps()), atol=sqrt(eps())) elseif !clamped @test isapprox(structure.mass[1] * dv_structure[1:2, 1], - -force_fluid, + -force_fluid_rhs, rtol=sqrt(eps()), atol=sqrt(eps())) end if boundary_density isa ContinuityDensity - # Independently evaluate the structure-first continuity - # operator using the cubic-spline derivative at r/h = 1.5. + # Evaluate the structure-first continuity equation with + # the boundary's uncorrected cubic-spline gradient, + # independently of the fluid's correction method. kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) expected_density_rate = -fluid_density / state.density * fluid.mass[1] * state.velocity[1] * @@ -563,8 +581,8 @@ fluid_system = create_fluid_system("WCSPH", (1.0, 0.5), 1005.0, viscosity; shifting_technique) structure_system = create_structure_system(structure_type, viscosity) - fluid, structure, arrays, semi, - _ = initialize(fluid_system, structure_system) + (fluid, structure, arrays, semi, + _) = initialize(fluid_system, structure_system) # Compare the forces without and with a shifting velocity fluid.cache.delta_v .= 0 From b4e8499807603db8aa94429b8dc9f400731373aa Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Sun, 18 Oct 2026 21:33:35 +0200 Subject: [PATCH 29/46] format --- test/general/semidiscretization.jl | 9 ++++++--- test/schemes/fluid/rhs.jl | 5 +++-- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index e2be95de7b..fa3aae3a96 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -161,9 +161,11 @@ ("nearby smoothing length", smoothing_kernel, nextfloat(1.0), false)) - @testset "$(nameof(typeof(fluid_system))), $structure_type" for fluid_system in fluid_systems, - structure_type in (TotalLagrangianSPHSystem, - RigidBodySystem) + @testset "$(nameof(typeof(fluid_system))), $structure_type" for fluid_system in + fluid_systems, + structure_type in + (TotalLagrangianSPHSystem, + RigidBodySystem) # Missing boundary model. structure = create_structure_system(structure_type, nothing) @@ -201,6 +203,7 @@ @testset "$name" for (name, boundary_kernel, boundary_length, compatible) in boundary_configurations + boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, AdamiPressureExtrapolation(), boundary_kernel, diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 77f1ef3896..de7c456009 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -447,8 +447,9 @@ corrections @testset "`$structure_type`, clamped=$clamped, h=$structure_smoothing_length" for (structure_type, - clamped, - structure_smoothing_length) in structure_configurations + clamped, + structure_smoothing_length) in + structure_configurations # TLSPH does not yet support `ContinuityDensity` boundaries. boundary_densities = if structure_type === TotalLagrangianSPHSystem From 8eb58953498717058bf49b092d652caefa837740 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 20 Oct 2026 17:14:56 +0200 Subject: [PATCH 30/46] Update src/schemes/structure/structure.jl Co-authored-by: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> --- src/schemes/structure/structure.jl | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index fae631b4fe..ac2abbddba 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -147,8 +147,7 @@ end MixedKernelGradientCorrection}, system, pos_diff, distance, particle, grad_kernel) - # These corrections depend on the fluid particle's local neighborhood, so its - # gradient cannot be obtained by negating the structure-side gradient. + # These corrections produce asymmetric kernels, so we cannot just flip the sign of the gradient. return smoothing_kernel_grad_unsafe(system, -pos_diff, distance, particle) end From 8ac58538f8641e8ba71a5eb2dd5f7059e893abed Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 20 Oct 2026 20:07:39 +0200 Subject: [PATCH 31/46] review --- NEWS.md | 4 +- src/schemes/structure/structure.jl | 97 +++++++++--------- test/general/semidiscretization.jl | 4 +- test/schemes/fluid/rhs.jl | 153 +++++++++++++++++++++++++---- 4 files changed, 189 insertions(+), 69 deletions(-) diff --git a/NEWS.md b/NEWS.md index d03e1d92f1..fcc78cd9ce 100644 --- a/NEWS.md +++ b/NEWS.md @@ -23,7 +23,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel - gradients by evaluating the fluid-first gradient directly (#1338). + gradients by evaluating the fluid-first gradient directly. The continuity equation + of `RigidBodySystem` boundaries with `ContinuityDensity` now uses the kernel gradient + of the boundary model instead of the corrected fluid gradient (#1338). - Fixed asymmetric DEM contact forces near coincidence by using a pair-local radius scale for the near-zero distance cutoff (#1347). - Fixed the sign of the quadratic term in `ArtificialViscosityMonaghan` (#1295). diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index ac2abbddba..df3d2a2375 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -17,10 +17,8 @@ end end end -# The structure-fluid interaction computes the opposite of the force that the fluid -# experiences in the fluid-structure interaction. Therefore, both interactions must find -# the same pairs of particles. Reusing the structure-side gradient with the opposite -# sign also requires the same smoothing kernel and smoothing length. +# Both FSI directions must find the same particle pairs and use matching boundary and +# fluid kernels. The TLSPH kernel for solid mechanics may differ. # Note that this is only a restriction for `BoundaryModelDummyParticles`, since # `BoundaryModelMonaghanKajtar` always uses the compact support of the fluid. function check_smoothing_kernel_fsi(system, boundary_model::BoundaryModelDummyParticles, @@ -30,8 +28,9 @@ function check_smoothing_kernel_fsi(system, boundary_model::BoundaryModelDummyPa smoothing_length_structure = initial_smoothing_length(boundary_model) smoothing_length_fluid = initial_smoothing_length(neighbor_system) + # Allow rounding differences, e.g., from computing the smoothing lengths separately if smoothing_kernel_structure != smoothing_kernel_fluid || - smoothing_length_structure != smoothing_length_fluid + !isapprox(smoothing_length_structure, smoothing_length_fluid) throw(ArgumentError("the smoothing kernel and smoothing length of the boundary " * "model of the `$(nameof(typeof(system)))` must be the same " * "as those of the fluid system `$(nameof(typeof(neighbor_system)))`.")) @@ -52,15 +51,6 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) h = initial_smoothing_length(neighbor_system) - h_structure = initial_smoothing_length(particle_system) - support_structure = compact_support(system_smoothing_kernel(particle_system), - h_structure) - correction = system_correction(neighbor_system) - # TLSPH may use a different kernel for solid mechanics. Only reuse its gradient - # when it is uncorrected and uses the same kernel and smoothing length as the fluid. - reuse_grad_kernel = system_smoothing_kernel(particle_system) == - system_smoothing_kernel(neighbor_system) && - h_structure == h && system_correction(particle_system) === nothing # Loop over all pairs of particles and neighbors within the kernel cutoff. foreach_point_neighbor(particle_system, neighbor_system, @@ -71,21 +61,15 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # Note that `return` only exits the closure, i.e., skips the current neighbor. skip_zero_distance(neighbor_system) && distance < almostzero(h) && return - # The continuity equation uses the structure-side gradient. It may be zero - # at coincidence even when the corrected fluid gradient is nonzero. - grad_kernel = if distance >= support_structure || - (skip_zero_distance(particle_system) && - distance < almostzero(h_structure)) - zero(pos_diff) - else - smoothing_kernel_grad_unsafe(particle_system, pos_diff, distance, particle) - end - grad_kernel_fluid = if reuse_grad_kernel - fluid_kernel_grad_unsafe(correction, neighbor_system, - pos_diff, distance, neighbor, grad_kernel) - else - smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, distance, neighbor) - end + # Now that we know that `distance` is not zero, we can safely call the unsafe + # version of the kernel gradient to avoid redundant zero checks. + # Evaluate the gradient exactly as in the fluid-structure interaction, i.e., + # with the fluid particle's kernel and correction and the fluid-first displacement. + # Note that we cannot just flip the sign of the structure-first gradient, since + # corrections like `KernelCorrection` add a term that keeps its sign + # when the displacement is reversed. + grad_kernel_fluid = smoothing_kernel_grad_unsafe(neighbor_system, -pos_diff, + distance, neighbor) m_b = hydrodynamic_mass(neighbor_system, neighbor) @@ -127,7 +111,8 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, drho_particle = add_continuity_equation(zero(rho_a), particle_system, neighbor_system, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b, + grad_kernel_fluid) @inbounds write_drho_particle!(dv, particle_system, drho_particle, particle) end @@ -135,27 +120,11 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, return dv end -@inline function fluid_kernel_grad_unsafe(correction, system, pos_diff, distance, particle, - grad_kernel) - # Matching uncorrected kernels change sign with the displacement. - # Reuse it with the opposite sign to obtain the fluid-first gradient. - return -grad_kernel -end - -@inline function fluid_kernel_grad_unsafe(::Union{KernelCorrection, GradientCorrection, - BlendedGradientCorrection, - MixedKernelGradientCorrection}, - system, pos_diff, distance, particle, - grad_kernel) - # These corrections produce asymmetric kernels, so we cannot just flip the sign of the gradient. - return smoothing_kernel_grad_unsafe(system, -pos_diff, distance, particle) -end - @inline function add_continuity_equation(drho_particle, particle_system::AbstractStructureSystem, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b, grad_kernel_fluid) return drho_particle end @@ -164,12 +133,44 @@ end TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{ContinuityDensity}}}, neighbor_system::AbstractFluidSystem, particle, neighbor, pos_diff, distance, - m_b, rho_a, rho_b, v_a, v_b, grad_kernel) + m_b, rho_a, rho_b, v_a, v_b, grad_kernel_fluid) + (; boundary_model) = particle_system + + # As for a `WallBoundarySystem`, the density of the boundary particles evolves with + # the boundary model's kernel gradient and not with the corrected fluid gradient. + grad_kernel = boundary_continuity_kernel_grad(system_correction(neighbor_system), + boundary_model.correction, + boundary_model, pos_diff, distance, + particle, grad_kernel_fluid) + return add_continuity_equation(drho_particle, density_calculator(neighbor_system), m_b, rho_a, rho_b, v_a, v_b, grad_kernel, particle) end +@inline function boundary_continuity_kernel_grad(fluid_correction, boundary_correction, + boundary_model, pos_diff, distance, + particle, grad_kernel_fluid) + # Use the boundary model's kernel and smoothing length, which may differ from + # the TLSPH kernel for solid mechanics. + # The safe version also returns zero for coincident particles. + return smoothing_kernel_grad(boundary_model, pos_diff, distance, particle) +end + +@inline function boundary_continuity_kernel_grad(::Union{Nothing, + AkinciFreeSurfaceCorrection, + ShepardKernelCorrection}, + ::Union{Nothing, + AkinciFreeSurfaceCorrection, + ShepardKernelCorrection}, + boundary_model, pos_diff, distance, + particle, grad_kernel_fluid) + # Neither correction changes the gradient, and the boundary model's kernel and + # smoothing length match the fluid's (see `check_smoothing_kernel_fsi`). + # Reversing the displacement only flips the sign of the uncorrected gradient. + return -grad_kernel_fluid +end + @inline function write_drho_particle!(dv, ::AbstractSystem, drho_particle, particle) return dv end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index fa3aae3a96..fe829bf405 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -158,8 +158,8 @@ SchoenbergQuinticSplineKernel{2}(), 2 / 3, false), ("different smoothing length", smoothing_kernel, 0.8, false), - ("nearby smoothing length", smoothing_kernel, - nextfloat(1.0), false)) + ("smoothing length with rounding error", + smoothing_kernel, nextfloat(1.0), true)) @testset "$(nameof(typeof(fluid_system))), $structure_type" for fluid_system in fluid_systems, diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index de7c456009..cad35f838d 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -307,6 +307,7 @@ function create_structure_system(structure_type, viscosity; boundary_density=AdamiPressureExtrapolation(), + boundary_correction=nothing, clamped=false, structure_smoothing_length=smoothing_length) # The material mass is twice the hydrodynamic mass, so using the wrong mass @@ -321,7 +322,8 @@ boundary_density, smoothing_kernel, smoothing_length; - state_equation, viscosity) + state_equation, viscosity, + correction=boundary_correction) if structure_type === TotalLagrangianSPHSystem return TotalLagrangianSPHSystem(structure; smoothing_kernel, @@ -395,7 +397,7 @@ force_structure = structure.mass[1] * dv_structure[1:2, 1] end - return force_fluid, force_structure + return force_fluid, force_structure, dv_structure end # Exercise all viscosity models with WCSPH and both EDAC pressure variants. @@ -473,8 +475,13 @@ structure_smoothing_length) (fluid, structure, arrays, semi, ode) = initialize(fluid_system, structure_system) - (force_fluid, - force_structure) = pair_forces(fluid, structure, arrays, semi) + if haskey(fluid.cache, :correction_matrix) + # The one-pair setup otherwise gives an identity matrix, + # which would not catch using an uncorrected gradient. + fluid.cache.correction_matrix[:, :, 1] .= [2.0 0.3; 0.4 1.5] + end + (force_fluid, force_structure, + dv_structure) = pair_forces(fluid, structure, arrays, semi) v_fluid, _, _, _ = arrays if correction isa KernelCorrection || @@ -533,6 +540,15 @@ @test !iszero(force_fluid) end + if boundary_density isa ContinuityDensity + # Boundary density must not use the fluid's correction. + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -fluid_density / state.density * + fluid.mass[1] * state.velocity[1] * + kernel_derivative + @test dv_structure[end, 1] ≈ expected_density_rate + end + # Also check that the normal RHS carries the pair reaction # through to integrated TLSPH particles and rigid-body resultants. v_ode, u_ode = ode.u0.x @@ -552,23 +568,123 @@ -force_fluid_rhs, rtol=sqrt(eps()), atol=sqrt(eps())) end - - if boundary_density isa ContinuityDensity - # Evaluate the structure-first continuity equation with - # the boundary's uncorrected cubic-spline gradient, - # independently of the fluid's correction method. - kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) - expected_density_rate = -fluid_density / state.density * - fluid.mass[1] * state.velocity[1] * - kernel_derivative - @test dv_structure[end, 1] ≈ expected_density_rate - end end end end end end + # `ShepardKernelCorrection` requires `SummationDensity` for the fluid, + # so it cannot be tested with the prescribed fluid densities above. + shepard_configurations = ((TotalLagrangianSPHSystem, AdamiPressureExtrapolation()), + (RigidBodySystem, AdamiPressureExtrapolation()), + (RigidBodySystem, ContinuityDensity())) + + @testset "`ShepardKernelCorrection`, `$structure_type`, `$(nameof(typeof(boundary_density)))`" for (structure_type, + boundary_density) in + shepard_configurations + + viscosity = ViscosityAdami(nu=0.1) + velocity = (1.0, 0.5) + fluid_ic = InitialCondition(; coordinates=zeros(2, 1), + velocity=reshape(collect(velocity), 2, 1), + mass=[fluid_density * particle_spacing^2], + density=[fluid_density], particle_spacing) + fluid_system = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, state_equation, + density_calculator=SummationDensity(), + correction=ShepardKernelCorrection(), + viscosity) + structure_system = create_structure_system(structure_type, viscosity; + boundary_density) + (fluid, structure, arrays, + semi, _) = initialize(fluid_system, structure_system) + (force_fluid, force_structure, + dv_structure) = pair_forces(fluid, structure, arrays, semi) + + @test !iszero(force_fluid) + @test isapprox(force_structure, -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + + if boundary_density isa ContinuityDensity + # With `SummationDensity` for the fluid, the boundary density follows + # the time derivative of the density summation. + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -fluid.mass[1] * velocity[1] * kernel_derivative + @test dv_structure[end, 1] ≈ expected_density_rate + end + end + + # Without a fluid correction, the pair force only uses the fluid's kernel, + # so a correction of the structure's boundary model must not change it. + # The continuity equation of the boundary particles must use the boundary model. + boundary_corrections = (AkinciFreeSurfaceCorrection(fluid_density), + KernelCorrection()) + + @testset "Boundary Model Correction `$(nameof(typeof(boundary_correction)))`" for boundary_correction in + boundary_corrections + + viscosity = ViscosityAdami(nu=0.1) + velocity = (1.0, 0.5) + density = 1005.0 + forces = map((nothing, boundary_correction)) do boundary_correction_ + fluid_system = create_fluid_system("WCSPH", velocity, density, viscosity) + structure_system = create_structure_system(RigidBodySystem, viscosity; + boundary_density=ContinuityDensity(), + boundary_correction=boundary_correction_) + (fluid, structure, arrays, + semi, _) = initialize(fluid_system, structure_system) + + return (pair_forces(fluid, structure, arrays, semi)..., fluid, structure) + end + force_fluid_uncorrected = forces[1][1] + (force_fluid, force_structure, dv_structure, fluid, structure) = forces[2] + + @test force_fluid == force_fluid_uncorrected + @test isapprox(force_structure, -force_fluid, + rtol=sqrt(eps()), atol=sqrt(eps())) + + grad_kernel = TrixiParticles.smoothing_kernel_grad(structure.boundary_model, + SVector(1.5, 0.0), 1.5, 1) + expected_density_rate = -fluid_density / density * fluid.mass[1] * + velocity[1] * grad_kernel[1] + @test dv_structure[end, 1] ≈ expected_density_rate + end + + # TLSPH does not support `ContinuityDensity` boundaries yet. However, the continuity + # equation of structure boundaries must already use the kernel of the boundary + # model and not the TLSPH kernel for solid mechanics, which has a smaller support. + @testset "TLSPH Continuity Equation with Correction `$(nameof(typeof(correction)))`" for correction in + (nothing, + GradientCorrection()) + velocity = (1.0, 0.5) + density = 1005.0 + structure = create_structure_system(TotalLagrangianSPHSystem, nothing; + boundary_density=ContinuityDensity(), + structure_smoothing_length=0.5 * + smoothing_length) + fluid = create_fluid_system("WCSPH", velocity, density, nothing; correction) + if haskey(fluid.cache, :correction_matrix) + fluid.cache.correction_matrix[:, :, 1] .= [2.0 0.3; 0.4 1.5] + end + + pos_diff = SVector(1.5, 0.0) + grad_kernel_fluid = TrixiParticles.smoothing_kernel_grad_unsafe(fluid, + -pos_diff, + 1.5, 1) + drho = TrixiParticles.add_continuity_equation(0.0, structure, fluid, 1, 1, + pos_diff, 1.5, fluid.mass[1], + fluid_density, density, + SVector(0.0, 0.0), + SVector(velocity), + grad_kernel_fluid) + + kernel_derivative = -0.75 * (2 - 1.5)^2 * 10 / (7pi) + expected_density_rate = -fluid_density / density * fluid.mass[1] * + velocity[1] * kernel_derivative + @test drho ≈ expected_density_rate + end + # The extra terms of the shifting techniques in the momentum equation act on the # fluid, but must not be applied to the structure. shifting_techniques = (ParticleShiftingTechnique(), @@ -587,11 +703,12 @@ # Compare the forces without and with a shifting velocity fluid.cache.delta_v .= 0 - force_fluid, force_structure = pair_forces(fluid, structure, arrays, semi) + (force_fluid, force_structure, + _) = pair_forces(fluid, structure, arrays, semi) fluid.cache.delta_v .= [0.5, 0.2] - (force_fluid_shifting, - force_structure_shifting) = pair_forces(fluid, structure, arrays, semi) + (force_fluid_shifting, force_structure_shifting, + _) = pair_forces(fluid, structure, arrays, semi) # Make sure that the shifting terms act on the fluid. @test !isapprox(force_fluid_shifting, force_fluid) From 7f07eb5bc45ee83b6c7d93d0aba8a0f53f1a0f85 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Wed, 21 Oct 2026 16:53:25 +0200 Subject: [PATCH 32/46] Compute the no-slip wall velocity with `PressureMirroring` --- NEWS.md | 4 +- docs/src/systems/boundary.md | 2 + .../boundary/wall_boundary/dummy_particles.jl | 66 +++++++- .../dummy_particles/dummy_particles.jl | 156 ++++++++++++++++++ 4 files changed, 222 insertions(+), 6 deletions(-) diff --git a/NEWS.md b/NEWS.md index 56bc0496b7..33d6431662 100644 --- a/NEWS.md +++ b/NEWS.md @@ -23,7 +23,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Important Bugfixes - Fixed pressure mirroring for TLSPH and rigid-body neighbors and for EDAC momentum, - pressure diffusion, and average-pressure reduction at walls and structures (#1341). + pressure diffusion, and average-pressure reduction at walls and structures. + With a boundary viscosity, `PressureMirroring` now computes the wall velocity of the + no-slip condition, which was zero before (#1341). - Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel gradients by evaluating the fluid-first gradient directly. The continuity equation of `RigidBodySystem` boundaries with `ContinuityDensity` now uses the kernel gradient diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index c82603a030..098c50c0b6 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -90,6 +90,8 @@ Pressure mirroring also applies to TLSPH and rigid-body boundary models. In EDAC the mirrored pressure is used in the momentum equation, the pressure evolution equation, and the average-pressure reduction. Mirroring makes the pressure diffusion contribution from a fluid-boundary pair zero. +With a viscosity model, the wall velocity of the no-slip condition (see below) +is computed in the same way as with [`AdamiPressureExtrapolation`](@ref). #### 1. [`AdamiPressureExtrapolation`](@ref) diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index b8dd014f3a..7cf298f99d 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -258,13 +258,22 @@ function create_cache_model(::MixedKernelGradientCorrection, density, NDIMS, n_p end function create_cache_model(initial_density::AbstractVector, - ::Union{SummationDensity, PressureMirroring, PressureZeroing}, - NDIMS) + ::Union{SummationDensity, PressureZeroing}, NDIMS) density = copy(initial_density) return (; density) end +function create_cache_model(initial_density::AbstractVector, ::PressureMirroring, NDIMS) + density = copy(initial_density) + + # Sum of the kernel weights of the fluid neighbors to interpolate the fluid velocity + # for the no-slip condition (see `compute_pressure!`) + volume = similar(initial_density) + + return (; density, volume) +end + function create_cache_model(initial_density::AbstractVector, density_calculator::PressureBoundaries, NDIMS) ELTYPE = eltype(initial_density) @@ -572,14 +581,61 @@ function compute_adami_density!(boundary_model, system, v, particle) inverse_state_equation!(density, state_equation, pressure, particle) end -function compute_pressure!(boundary_model, - ::Union{PressureMirroring, PressureZeroing, PressureBoundaries}, +function compute_pressure!(boundary_model, ::Union{PressureZeroing, PressureBoundaries}, system, v, u, v_ode, u_ode, semi) - # No pressure update needed with `PressureMirroring` and `PressureZeroing`. + # No pressure update needed with `PressureZeroing`. # Pressure update for `PressureBoundaries` is be done by the PPE solver in IISPH return boundary_model end +function compute_pressure!(boundary_model, ::PressureMirroring, + system, v, u, v_ode, u_ode, semi) + (; cache, viscosity) = boundary_model + + # No pressure update needed, since the fluid pressure is mirrored in the momentum + # equation. Without a viscosity model, the wall velocity is not used either. + isnothing(viscosity) && return boundary_model + + # For the no-slip condition, interpolate the fluid velocity as in the pressure + # extrapolation of `AdamiPressureExtrapolation` (see `boundary_pressure_inner!`). + # Set `volume` and `wall_velocity` to zero. + reset_cache!(cache, viscosity) + + system_coords = current_coordinates(u, system) + + foreach_system(semi) do neighbor_system + # Only fluid particles contribute to the interpolated fluid velocity + neighbor_system isa AbstractFluidSystem || return + has_system_interaction(system, neighbor_system, semi) || return + + v_neighbor_system = wrap_v(v_ode, neighbor_system, semi) + u_neighbor_system = wrap_u(u_ode, neighbor_system, semi) + neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) + + foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, + semi; + points=eachparticle(system)) do particle, neighbor, + pos_diff, distance + kernel_weight = smoothing_kernel(boundary_model, distance, particle) + cache.volume[particle] += kernel_weight + + interpolate_fluid_velocity!(cache, viscosity, neighbor_system, + v_neighbor_system, kernel_weight, particle, + neighbor) + end + end + + @threaded semi for particle in eachparticle(system) + # The volume stays zero for boundary particles without fluid neighbors, + # whose wall velocity is not used. + if cache.volume[particle] > eps() + compute_wall_velocity!(viscosity, system, v, particle) + end + end + + return boundary_model +end + @inline function boundary_pressure_extrapolation!(parallel, boundary_model, system, neighbor_system, system_coords, neighbor_coords, v, v_neighbor_system, diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index ef997a1ed6..e7ee1d961f 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -696,6 +696,162 @@ end end end + + @testset verbose=true "Pressure Mirroring: No-Slip Wall Velocity" begin + # `PressureMirroring` does not extrapolate the boundary pressure, but the no-slip + # condition by Adami et al. (2012) requires the same wall velocity + # `v_w = 2 * v_boundary - ṽ_fluid` as with `AdamiPressureExtrapolation`. + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.2 + fluid_density = 1000.0 + state_equation = StateEquationCole(; sound_speed=10.0, + reference_density=fluid_density, exponent=1) + viscosity = ViscosityAdami(nu=0.1) + + # Fluid particles with different velocities above a row of boundary particles. + # The last boundary particle has no fluid neighbors. + fluid_ic = InitialCondition(; coordinates=[-1.0 0.0 -1.0 0.0; 1.0 1.0 2.0 2.0], + velocity=[1.0 0.0 -1.0 0.5; 0.0 1.0 0.5 -0.5], + mass=fill(fluid_density, 4), + density=fill(fluid_density, 4), particle_spacing=1.0) + n_boundary = 5 + boundary_coordinates = [collect(-1.0:3.0)'; zeros(1, n_boundary)] + + function create_systems(boundary_type, density_calculator, boundary_velocity) + fluid_system = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, state_equation, + density_calculator=ContinuityDensity(), + viscosity) + + velocity = repeat(collect(boundary_velocity), 1, n_boundary) + boundary_ic = InitialCondition(; coordinates=boundary_coordinates, + velocity, mass=fill(fluid_density, n_boundary), + density=fill(fluid_density, n_boundary), + particle_spacing=1.0) + boundary_model = BoundaryModelDummyParticles(boundary_ic.density, + boundary_ic.mass, + density_calculator, + smoothing_kernel, + smoothing_length; + state_equation, viscosity) + + boundary_system = if boundary_type === WallBoundarySystem + WallBoundarySystem(boundary_ic, boundary_model) + elseif boundary_type === TotalLagrangianSPHSystem + TotalLagrangianSPHSystem(boundary_ic; smoothing_kernel, smoothing_length, + young_modulus=1e5, poisson_ratio=0.3, + boundary_model) + else + RigidBodySystem(boundary_ic; boundary_model) + end + + return fluid_system, boundary_system + end + + # Run the regular update step, which computes the wall velocity + function initialize(fluid_system, boundary_system) + semi = if boundary_system isa TotalLagrangianSPHSystem + @test_logs (:info, + r"^To create the self-interaction neighborhood search") Semidiscretization(fluid_system, + boundary_system; + parallelization_backend=SerialBackend()) + else + Semidiscretization(fluid_system, boundary_system; + parallelization_backend=SerialBackend()) + end + ode = semidiscretize(semi, (0.0, 0.01)) + v_ode, u_ode = ode.u0.x + TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) + + return ode.p.semi, v_ode, u_ode + end + + # Walls are at rest, structures move + boundary_configurations = ((WallBoundarySystem, (0.0, 0.0)), + (TotalLagrangianSPHSystem, (0.2, -0.1)), + (RigidBodySystem, (0.2, -0.1))) + + @testset "`$boundary_type`" for (boundary_type, + boundary_velocity) in boundary_configurations + + semi, _, + _ = initialize(create_systems(boundary_type, + AdamiPressureExtrapolation(), + boundary_velocity)...) + wall_velocity_adami = semi.systems[2].boundary_model.cache.wall_velocity + + # The wall velocity is only computed for boundary particles with fluid neighbors + for particle in 1:(n_boundary - 1) + @test !iszero(wall_velocity_adami[:, particle]) + end + @test iszero(wall_velocity_adami[:, n_boundary]) + + semi, _, + _ = initialize(create_systems(boundary_type, PressureMirroring(), + boundary_velocity)...) + wall_velocity = semi.systems[2].boundary_model.cache.wall_velocity + + @test wall_velocity ≈ wall_velocity_adami + end + + # A structure moving through fluid at rest must drag the fluid along. + # The fluid pressure is zero, so both models have the reference density and zero + # pressure. Therefore, the pair force is purely viscous and must be the same. + @testset "Viscous Force of a Moving `$structure_type`" for structure_type in + (TotalLagrangianSPHSystem, + RigidBodySystem) + # A single fluid particle at rest and a single structure particle at `(1.5h, 0)` + fluid_ic_ = InitialCondition(; coordinates=zeros(2, 1), velocity=zeros(2, 1), + mass=[fluid_density], density=[fluid_density], + particle_spacing=1.0) + structure_velocity = SVector(1.0, 0.5) + structure_ic = InitialCondition(; + coordinates=reshape([1.5 * smoothing_length, + 0.0], 2, 1), + velocity=reshape(collect(structure_velocity), + 2, 1), + mass=[2 * fluid_density], + density=[2 * fluid_density], + particle_spacing=1.0) + + function viscous_force(density_calculator) + fluid_system = WeaklyCompressibleSPHSystem(fluid_ic_; smoothing_kernel, + smoothing_length, state_equation, + density_calculator=ContinuityDensity(), + viscosity) + boundary_model = BoundaryModelDummyParticles([fluid_density], + [fluid_density], + density_calculator, + smoothing_kernel, + smoothing_length; + state_equation, viscosity) + structure_system = if structure_type === TotalLagrangianSPHSystem + TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, + smoothing_length, young_modulus=1e5, + poisson_ratio=0.3, boundary_model) + else + RigidBodySystem(structure_ic; boundary_model) + end + + semi, v_ode, u_ode = initialize(fluid_system, structure_system) + fluid, structure = semi.systems + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) + u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) + + dv_fluid = zero(v_fluid) + TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, + u_structure, fluid, structure, semi) + + return fluid.mass[1] * dv_fluid[1:2, 1] + end + + force_adami = viscous_force(AdamiPressureExtrapolation()) + @test dot(force_adami, structure_velocity) > 0 + @test viscous_force(PressureMirroring()) ≈ force_adami + end + end end include("rhs.jl") From b5f514afbcf83787a931fb4c0d906127e94d6476 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Wed, 21 Oct 2026 16:53:25 +0200 Subject: [PATCH 33/46] Test pressure-mirroring magnitudes with EDAC --- .../dummy_particles/dummy_particles.jl | 80 +++++++++++++++++++ test/schemes/fluid/rhs.jl | 33 ++++++++ 2 files changed, 113 insertions(+) diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index e7ee1d961f..67af205ce5 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -852,6 +852,86 @@ @test viscous_force(PressureMirroring()) ≈ force_adami end end + + @testset verbose=true "Pressure Mirroring with EDAC" begin + # Two fluid particles with different pressures next to a wall particle. + # With pressure mirroring, fluid particle `a` sees the wall pressure `p_a`. + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.0 + fluid_density = 1000.0 + pressures = [500.0, 100.0] + + # Both fluid particles are neighbors of each other and of the wall particle + fluid_ic = InitialCondition(; coordinates=[0.0 0.5; 0.0 0.0], velocity=zeros(2, 2), + mass=fill(fluid_density, 2), + density=fill(fluid_density, 2), pressure=pressures, + particle_spacing=1.0) + distances = (1.5, 1.0) + wall_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), + mass=[fluid_density], density=[fluid_density], + particle_spacing=1.0) + + # Independent cubic-spline gradient ∇_a W_ab for `b` to the right of `a` + function grad_kernel(distance) + derivative = 10 / (7pi) * + (distance < 1 ? -3distance + 2.25distance^2 : + -0.75 * (2 - distance)^2) + return SVector(-derivative, 0.0) + end + + @testset "average_pressure_reduction=$average_pressure_reduction" for average_pressure_reduction in + (false, + true) + fluid_system = EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, sound_speed=10.0, + density_calculator=ContinuityDensity(), + average_pressure_reduction) + boundary_model = BoundaryModelDummyParticles(wall_ic.density, wall_ic.mass, + PressureMirroring(), + smoothing_kernel, smoothing_length) + wall_system = WallBoundarySystem(wall_ic, boundary_model) + semi = Semidiscretization(fluid_system, wall_system; + parallelization_backend=SerialBackend()) + ode = semidiscretize(semi, (0.0, 0.01)) + v_ode, u_ode = ode.u0.x + TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) + + semi = ode.p.semi + fluid, wall = semi.systems + + if average_pressure_reduction + # Each particle averages over itself, the other fluid particle and the wall + # particle, which has the mirrored pressure of the particle itself. + @test fluid.cache.pressure_average ≈ + [2 * pressures[1] + pressures[2], pressures[1] + 2 * pressures[2]] / + 3 + end + + v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) + u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) + v_wall = TrixiParticles.wrap_v(v_ode, wall, semi) + u_wall = TrixiParticles.wrap_u(u_ode, wall, semi) + dv = zero(v_fluid) + TrixiParticles.interact!(dv, v_fluid, u_fluid, v_wall, u_wall, fluid, wall, + semi) + + for particle in 1:2 + # `inter_particle_averaged_pressure` with the mirrored wall pressure + # `p_b = p_a` and the volumes `m_a / rho_a = m_b / rho_b = 1`. + # Without average pressure reduction, `average_pressure` returns zero. + reduced_pressure = pressures[particle] - + TrixiParticles.average_pressure(fluid, particle) + expected = -2 / fluid_density * reduced_pressure * + grad_kernel(distances[particle]) + + @test dv[1:2, particle] ≈ expected + end + + # The divergence term of the pressure evolution is zero for particles at rest, + # and the mirrored wall pressure makes the pressure diffusion term zero. + @test iszero(dv[3, :]) + end + end end include("rhs.jl") diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 59a9e78778..ce76db1d95 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -541,6 +541,21 @@ end else @test force_structure[1] > 0 + + if scheme == "EDAC" && + boundary_density isa PressureMirroring + # `inter_particle_averaged_pressure` with the + # mirrored pressure `p_b = p_a`. The hydrodynamic + # mass and density of the structure particle give + # a volume of 1. + p_a = TrixiParticles.current_pressure(v_fluid, + fluid, 1) + volume_a = fluid.mass[1] / state.density + grad_kernel = SVector(0.75 * (2 - 1.5)^2 * 10 / + (7pi), 0.0) + @test force_fluid ≈ + -(volume_a^2 + 1) * p_a * grad_kernel + end end else @test !iszero(force_fluid) @@ -555,6 +570,24 @@ @test dv_structure[end, 1] ≈ expected_density_rate end + if scheme != "WCSPH" && boundary_density isa PressureMirroring + # The mirrored pressure `p_b = p_a` makes the pressure + # diffusion of this pair vanish, so only the divergence + # term of the EDAC pressure evolution remains. + # The structure is at rest, and its hydrodynamic mass and + # density give a volume of 1. + _, u_fluid, v_structure, u_structure = arrays + dv_pair = zero(v_fluid) + TrixiParticles.interact!(dv_pair, v_fluid, u_fluid, + v_structure, u_structure, + fluid, structure, semi) + grad_kernel = SVector(0.75 * (2 - 1.5)^2 * 10 / (7pi), 0.0) + expected_pressure_rate = state.density * sound_speed^2 * + dot(SVector(state.velocity), + grad_kernel) + @test dv_pair[3, 1] ≈ expected_pressure_rate + end + # Also check that the normal RHS carries the pair reaction # through to integrated TLSPH particles and rigid-body resultants. v_ode, u_ode = ode.u0.x From 2f8df5df704f8e36ab905247a54a11394c615779 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Wed, 21 Oct 2026 16:53:29 +0200 Subject: [PATCH 34/46] Reject `SummationDensity` for structure boundary models --- NEWS.md | 4 ++++ docs/src/systems/boundary.md | 2 ++ src/schemes/structure/rigid_body/system.jl | 1 + src/schemes/structure/structure.jl | 13 +++++++++++++ .../structure/total_lagrangian_sph/system.jl | 1 + test/general/semidiscretization.jl | 18 +++++++++++++++++- test/schemes/fluid/rhs.jl | 5 +++-- test/systems/rigid_system.jl | 2 +- 8 files changed, 42 insertions(+), 4 deletions(-) diff --git a/NEWS.md b/NEWS.md index 33d6431662..c86b8f173a 100644 --- a/NEWS.md +++ b/NEWS.md @@ -14,6 +14,10 @@ used in the Julia ecosystem. Notable changes will be documented in this file for - The smoothing kernel and smoothing length of a `BoundaryModelDummyParticles` of a `TotalLagrangianSPHSystem` or `RigidBodySystem` must now be the same as those of all fluid systems in the simulation (#1338, #1348). +- A `BoundaryModelDummyParticles` with `SummationDensity` is no longer accepted for a + `TotalLagrangianSPHSystem` or `RigidBodySystem` interacting with a fluid. The boundary + density was never computed for structures, so this combination behaved like + `PressureZeroing`, which can be used instead (#1341). ### Features diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index 098c50c0b6..0f68bb9ec9 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -69,6 +69,8 @@ We provide six options to compute the boundary density and pressure, determined penetrations. 3. With [`SummationDensity`](@ref), the density is calculated by summation over the neighboring particles, and the pressure is computed from the density with the state equation. + This option is not yet supported for the boundary models of a [`TotalLagrangianSPHSystem`](@ref) + or a [`RigidBodySystem`](@ref) in fluid-structure interaction. 4. With [`ContinuityDensity`](@ref), the density is integrated from the continuity equation, and the pressure is computed from the density with the state equation. Note that this causes a gap between fluid and boundary where the boundary is initialized diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index 74222d7970..0224758508 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -631,6 +631,7 @@ function check_configuration(system::RigidBodySystem, systems, nhs) end check_smoothing_kernel_fsi(system, boundary_model, neighbor) + check_boundary_density_fsi(system, boundary_model, neighbor) if neighbor isa AbstractFluidSystem && neighbor.surface_normal_method isa ColorfieldSurfaceNormal diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index b653788e11..cc9c6581fe 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -41,6 +41,19 @@ end check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system +# The density of a structure boundary is computed by the pressure extrapolation or +# integrated with the continuity equation. The summation density is only computed for +# a `WallBoundarySystem`, so the density of a structure would stay at its initial value. +function check_boundary_density_fsi(system, + boundary_model::BoundaryModelDummyParticles{SummationDensity}, + neighbor_system::AbstractFluidSystem) + throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * + "`SummationDensity` is not yet supported for a " * + "`$(nameof(typeof(system)))` in a fluid-structure interaction")) +end + +check_boundary_density_fsi(system, boundary_model, neighbor_system) = system + function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, particle_system, diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 9a345c96ca..8e2c84b35a 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -871,5 +871,6 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) foreach_system(systems) do neighbor check_smoothing_kernel_fsi(system, boundary_model, neighbor) + check_boundary_density_fsi(system, boundary_model, neighbor) end end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index fe829bf405..70831768b6 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -201,6 +201,22 @@ neighborhood_search=nothing) end + # The summation density is never computed for structure boundaries + boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, + SummationDensity(), + smoothing_kernel, + smoothing_length) + structure = create_structure_system(structure_type, boundary_model) + error_str = "`BoundaryModelDummyParticles` with density calculator " * + "`SummationDensity` is not yet supported for a " * + "`$structure_type` in a fluid-structure interaction" + @test_throws ArgumentError(error_str) Semidiscretization(structure, + fluid_system; + neighborhood_search=nothing) + + # Without a fluid, the boundary density is not used + @test_nowarn TrixiParticles.check_configuration((structure,), nothing) + @testset "$name" for (name, boundary_kernel, boundary_length, compatible) in boundary_configurations @@ -306,7 +322,7 @@ particle_spacing=1.0) boundary_model = BoundaryModelDummyParticles(structure_ic.density, structure_ic.mass, - SummationDensity(), kernel, + PressureZeroing(), kernel, smoothing_length; state_equation, correction=nothing) diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index ce76db1d95..1bcfdaa07d 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -454,11 +454,12 @@ structure_configurations # TLSPH does not yet support `ContinuityDensity` boundaries. + # Structures don't support `SummationDensity` boundaries. boundary_densities = if structure_type === TotalLagrangianSPHSystem - (AdamiPressureExtrapolation(), SummationDensity(), + (AdamiPressureExtrapolation(), PressureZeroing(), PressureMirroring()) else - (AdamiPressureExtrapolation(), SummationDensity(), + (AdamiPressureExtrapolation(), PressureZeroing(), ContinuityDensity(), PressureMirroring()) end diff --git a/test/systems/rigid_system.jl b/test/systems/rigid_system.jl index d549363d9d..80de2f31c1 100644 --- a/test/systems/rigid_system.jl +++ b/test/systems/rigid_system.jl @@ -459,7 +459,7 @@ @test_throws ArgumentError Semidiscretization(fluid_system, rigid_system) rigid_boundary_model = BoundaryModelDummyParticles(density, mass, - SummationDensity(), + PressureZeroing(), smoothing_kernel, smoothing_length) rigid_system_with_dummy = RigidBodySystem(rigid_ic; From 3a1694d9ab4ad0838498331c03859ecd7de399b8 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Thu, 22 Oct 2026 01:17:39 +0200 Subject: [PATCH 35/46] review --- test/general/semidiscretization.jl | 31 +-- .../dummy_particles/dummy_particles.jl | 236 ------------------ test/schemes/fluid/rhs.jl | 93 ++++--- test/systems/edac_system.jl | 23 +- 4 files changed, 88 insertions(+), 295 deletions(-) diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index 70831768b6..808e846f9d 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -188,35 +188,28 @@ fluid_system; neighborhood_search=nothing) - if structure_type === TotalLagrangianSPHSystem + unsupported_densities = structure_type === TotalLagrangianSPHSystem ? + (ContinuityDensity(), SummationDensity()) : + (SummationDensity(),) + for density_calculator in unsupported_densities boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, - ContinuityDensity(), + density_calculator, smoothing_kernel, smoothing_length) structure = create_structure_system(structure_type, boundary_model) error_str = "`BoundaryModelDummyParticles` with density calculator " * - "`ContinuityDensity` is not yet supported for a `TotalLagrangianSPHSystem`" + "`$(nameof(typeof(density_calculator)))` is not yet supported " * + "for a `$structure_type`" + if density_calculator isa SummationDensity + error_str *= " in a fluid-structure interaction" + @test_nowarn TrixiParticles.check_configuration((structure,), + nothing) + end @test_throws ArgumentError(error_str) Semidiscretization(structure, fluid_system; neighborhood_search=nothing) end - # The summation density is never computed for structure boundaries - boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, - SummationDensity(), - smoothing_kernel, - smoothing_length) - structure = create_structure_system(structure_type, boundary_model) - error_str = "`BoundaryModelDummyParticles` with density calculator " * - "`SummationDensity` is not yet supported for a " * - "`$structure_type` in a fluid-structure interaction" - @test_throws ArgumentError(error_str) Semidiscretization(structure, - fluid_system; - neighborhood_search=nothing) - - # Without a fluid, the boundary density is not used - @test_nowarn TrixiParticles.check_configuration((structure,), nothing) - @testset "$name" for (name, boundary_kernel, boundary_length, compatible) in boundary_configurations diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index 67af205ce5..ef997a1ed6 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -696,242 +696,6 @@ end end end - - @testset verbose=true "Pressure Mirroring: No-Slip Wall Velocity" begin - # `PressureMirroring` does not extrapolate the boundary pressure, but the no-slip - # condition by Adami et al. (2012) requires the same wall velocity - # `v_w = 2 * v_boundary - ṽ_fluid` as with `AdamiPressureExtrapolation`. - smoothing_kernel = SchoenbergCubicSplineKernel{2}() - smoothing_length = 1.2 - fluid_density = 1000.0 - state_equation = StateEquationCole(; sound_speed=10.0, - reference_density=fluid_density, exponent=1) - viscosity = ViscosityAdami(nu=0.1) - - # Fluid particles with different velocities above a row of boundary particles. - # The last boundary particle has no fluid neighbors. - fluid_ic = InitialCondition(; coordinates=[-1.0 0.0 -1.0 0.0; 1.0 1.0 2.0 2.0], - velocity=[1.0 0.0 -1.0 0.5; 0.0 1.0 0.5 -0.5], - mass=fill(fluid_density, 4), - density=fill(fluid_density, 4), particle_spacing=1.0) - n_boundary = 5 - boundary_coordinates = [collect(-1.0:3.0)'; zeros(1, n_boundary)] - - function create_systems(boundary_type, density_calculator, boundary_velocity) - fluid_system = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, - smoothing_length, state_equation, - density_calculator=ContinuityDensity(), - viscosity) - - velocity = repeat(collect(boundary_velocity), 1, n_boundary) - boundary_ic = InitialCondition(; coordinates=boundary_coordinates, - velocity, mass=fill(fluid_density, n_boundary), - density=fill(fluid_density, n_boundary), - particle_spacing=1.0) - boundary_model = BoundaryModelDummyParticles(boundary_ic.density, - boundary_ic.mass, - density_calculator, - smoothing_kernel, - smoothing_length; - state_equation, viscosity) - - boundary_system = if boundary_type === WallBoundarySystem - WallBoundarySystem(boundary_ic, boundary_model) - elseif boundary_type === TotalLagrangianSPHSystem - TotalLagrangianSPHSystem(boundary_ic; smoothing_kernel, smoothing_length, - young_modulus=1e5, poisson_ratio=0.3, - boundary_model) - else - RigidBodySystem(boundary_ic; boundary_model) - end - - return fluid_system, boundary_system - end - - # Run the regular update step, which computes the wall velocity - function initialize(fluid_system, boundary_system) - semi = if boundary_system isa TotalLagrangianSPHSystem - @test_logs (:info, - r"^To create the self-interaction neighborhood search") Semidiscretization(fluid_system, - boundary_system; - parallelization_backend=SerialBackend()) - else - Semidiscretization(fluid_system, boundary_system; - parallelization_backend=SerialBackend()) - end - ode = semidiscretize(semi, (0.0, 0.01)) - v_ode, u_ode = ode.u0.x - TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) - - return ode.p.semi, v_ode, u_ode - end - - # Walls are at rest, structures move - boundary_configurations = ((WallBoundarySystem, (0.0, 0.0)), - (TotalLagrangianSPHSystem, (0.2, -0.1)), - (RigidBodySystem, (0.2, -0.1))) - - @testset "`$boundary_type`" for (boundary_type, - boundary_velocity) in boundary_configurations - - semi, _, - _ = initialize(create_systems(boundary_type, - AdamiPressureExtrapolation(), - boundary_velocity)...) - wall_velocity_adami = semi.systems[2].boundary_model.cache.wall_velocity - - # The wall velocity is only computed for boundary particles with fluid neighbors - for particle in 1:(n_boundary - 1) - @test !iszero(wall_velocity_adami[:, particle]) - end - @test iszero(wall_velocity_adami[:, n_boundary]) - - semi, _, - _ = initialize(create_systems(boundary_type, PressureMirroring(), - boundary_velocity)...) - wall_velocity = semi.systems[2].boundary_model.cache.wall_velocity - - @test wall_velocity ≈ wall_velocity_adami - end - - # A structure moving through fluid at rest must drag the fluid along. - # The fluid pressure is zero, so both models have the reference density and zero - # pressure. Therefore, the pair force is purely viscous and must be the same. - @testset "Viscous Force of a Moving `$structure_type`" for structure_type in - (TotalLagrangianSPHSystem, - RigidBodySystem) - # A single fluid particle at rest and a single structure particle at `(1.5h, 0)` - fluid_ic_ = InitialCondition(; coordinates=zeros(2, 1), velocity=zeros(2, 1), - mass=[fluid_density], density=[fluid_density], - particle_spacing=1.0) - structure_velocity = SVector(1.0, 0.5) - structure_ic = InitialCondition(; - coordinates=reshape([1.5 * smoothing_length, - 0.0], 2, 1), - velocity=reshape(collect(structure_velocity), - 2, 1), - mass=[2 * fluid_density], - density=[2 * fluid_density], - particle_spacing=1.0) - - function viscous_force(density_calculator) - fluid_system = WeaklyCompressibleSPHSystem(fluid_ic_; smoothing_kernel, - smoothing_length, state_equation, - density_calculator=ContinuityDensity(), - viscosity) - boundary_model = BoundaryModelDummyParticles([fluid_density], - [fluid_density], - density_calculator, - smoothing_kernel, - smoothing_length; - state_equation, viscosity) - structure_system = if structure_type === TotalLagrangianSPHSystem - TotalLagrangianSPHSystem(structure_ic; smoothing_kernel, - smoothing_length, young_modulus=1e5, - poisson_ratio=0.3, boundary_model) - else - RigidBodySystem(structure_ic; boundary_model) - end - - semi, v_ode, u_ode = initialize(fluid_system, structure_system) - fluid, structure = semi.systems - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) - v_structure = TrixiParticles.wrap_v(v_ode, structure, semi) - u_structure = TrixiParticles.wrap_u(u_ode, structure, semi) - - dv_fluid = zero(v_fluid) - TrixiParticles.interact!(dv_fluid, v_fluid, u_fluid, v_structure, - u_structure, fluid, structure, semi) - - return fluid.mass[1] * dv_fluid[1:2, 1] - end - - force_adami = viscous_force(AdamiPressureExtrapolation()) - @test dot(force_adami, structure_velocity) > 0 - @test viscous_force(PressureMirroring()) ≈ force_adami - end - end - - @testset verbose=true "Pressure Mirroring with EDAC" begin - # Two fluid particles with different pressures next to a wall particle. - # With pressure mirroring, fluid particle `a` sees the wall pressure `p_a`. - smoothing_kernel = SchoenbergCubicSplineKernel{2}() - smoothing_length = 1.0 - fluid_density = 1000.0 - pressures = [500.0, 100.0] - - # Both fluid particles are neighbors of each other and of the wall particle - fluid_ic = InitialCondition(; coordinates=[0.0 0.5; 0.0 0.0], velocity=zeros(2, 2), - mass=fill(fluid_density, 2), - density=fill(fluid_density, 2), pressure=pressures, - particle_spacing=1.0) - distances = (1.5, 1.0) - wall_ic = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), - mass=[fluid_density], density=[fluid_density], - particle_spacing=1.0) - - # Independent cubic-spline gradient ∇_a W_ab for `b` to the right of `a` - function grad_kernel(distance) - derivative = 10 / (7pi) * - (distance < 1 ? -3distance + 2.25distance^2 : - -0.75 * (2 - distance)^2) - return SVector(-derivative, 0.0) - end - - @testset "average_pressure_reduction=$average_pressure_reduction" for average_pressure_reduction in - (false, - true) - fluid_system = EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, - smoothing_length, sound_speed=10.0, - density_calculator=ContinuityDensity(), - average_pressure_reduction) - boundary_model = BoundaryModelDummyParticles(wall_ic.density, wall_ic.mass, - PressureMirroring(), - smoothing_kernel, smoothing_length) - wall_system = WallBoundarySystem(wall_ic, boundary_model) - semi = Semidiscretization(fluid_system, wall_system; - parallelization_backend=SerialBackend()) - ode = semidiscretize(semi, (0.0, 0.01)) - v_ode, u_ode = ode.u0.x - TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) - - semi = ode.p.semi - fluid, wall = semi.systems - - if average_pressure_reduction - # Each particle averages over itself, the other fluid particle and the wall - # particle, which has the mirrored pressure of the particle itself. - @test fluid.cache.pressure_average ≈ - [2 * pressures[1] + pressures[2], pressures[1] + 2 * pressures[2]] / - 3 - end - - v_fluid = TrixiParticles.wrap_v(v_ode, fluid, semi) - u_fluid = TrixiParticles.wrap_u(u_ode, fluid, semi) - v_wall = TrixiParticles.wrap_v(v_ode, wall, semi) - u_wall = TrixiParticles.wrap_u(u_ode, wall, semi) - dv = zero(v_fluid) - TrixiParticles.interact!(dv, v_fluid, u_fluid, v_wall, u_wall, fluid, wall, - semi) - - for particle in 1:2 - # `inter_particle_averaged_pressure` with the mirrored wall pressure - # `p_b = p_a` and the volumes `m_a / rho_a = m_b / rho_b = 1`. - # Without average pressure reduction, `average_pressure` returns zero. - reduced_pressure = pressures[particle] - - TrixiParticles.average_pressure(fluid, particle) - expected = -2 / fluid_density * reduced_pressure * - grad_kernel(distances[particle]) - - @test dv[1:2, particle] ≈ expected - end - - # The divergence term of the pressure evolution is zero for particles at rest, - # and the mirrored wall pressure makes the pressure diffusion term zero. - @test iszero(dv[3, :]) - end - end end include("rhs.jl") diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 1bcfdaa07d..3a754d6d99 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -279,6 +279,7 @@ sound_speed = 10.0 state_equation = StateEquationCole(; sound_speed, reference_density=fluid_density, exponent=1) + pair_gradient = SVector(15 / (56pi), 0.0) # Cubic-spline ∇W at (1.5h, 0) function create_fluid_system(scheme, velocity, density, viscosity; shifting_technique=nothing, correction=nothing) @@ -309,11 +310,12 @@ boundary_density=AdamiPressureExtrapolation(), boundary_correction=nothing, clamped=false, + velocity=(0.0, 0.0), structure_smoothing_length=smoothing_length) # The material mass is twice the hydrodynamic mass, so using the wrong mass # to convert the force on the structure to an acceleration fails the test. structure = InitialCondition(; coordinates=reshape([1.5, 0.0], 2, 1), - velocity=zeros(2, 1), + velocity=reshape(collect(velocity), 2, 1), mass=[2 * fluid_density * particle_spacing^2], density=[2 * fluid_density], particle_spacing) boundary_model = BoundaryModelDummyParticles([fluid_density], @@ -325,7 +327,11 @@ state_equation, viscosity, correction=boundary_correction) - if structure_type === TotalLagrangianSPHSystem + if structure_type === WallBoundarySystem + motion = PrescribedMotion((x, t) -> x + SVector(velocity) * t, t -> true) + return WallBoundarySystem(structure, boundary_model; + prescribed_motion=motion) + elseif structure_type === TotalLagrangianSPHSystem return TotalLagrangianSPHSystem(structure; smoothing_kernel, smoothing_length=structure_smoothing_length, young_modulus=1e5, @@ -542,21 +548,6 @@ end else @test force_structure[1] > 0 - - if scheme == "EDAC" && - boundary_density isa PressureMirroring - # `inter_particle_averaged_pressure` with the - # mirrored pressure `p_b = p_a`. The hydrodynamic - # mass and density of the structure particle give - # a volume of 1. - p_a = TrixiParticles.current_pressure(v_fluid, - fluid, 1) - volume_a = fluid.mass[1] / state.density - grad_kernel = SVector(0.75 * (2 - 1.5)^2 * 10 / - (7pi), 0.0) - @test force_fluid ≈ - -(volume_a^2 + 1) * p_a * grad_kernel - end end else @test !iszero(force_fluid) @@ -571,24 +562,6 @@ @test dv_structure[end, 1] ≈ expected_density_rate end - if scheme != "WCSPH" && boundary_density isa PressureMirroring - # The mirrored pressure `p_b = p_a` makes the pressure - # diffusion of this pair vanish, so only the divergence - # term of the EDAC pressure evolution remains. - # The structure is at rest, and its hydrodynamic mass and - # density give a volume of 1. - _, u_fluid, v_structure, u_structure = arrays - dv_pair = zero(v_fluid) - TrixiParticles.interact!(dv_pair, v_fluid, u_fluid, - v_structure, u_structure, - fluid, structure, semi) - grad_kernel = SVector(0.75 * (2 - 1.5)^2 * 10 / (7pi), 0.0) - expected_pressure_rate = state.density * sound_speed^2 * - dot(SVector(state.velocity), - grad_kernel) - @test dv_pair[3, 1] ≈ expected_pressure_rate - end - # Also check that the normal RHS carries the pair reaction # through to integrated TLSPH particles and rigid-body resultants. v_ode, u_ode = ode.u0.x @@ -598,6 +571,21 @@ # from this RHS evaluation rather than the earlier pair call. dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) force_fluid_rhs = fluid.mass[1] * dv_fluid[1:2, 1] + if scheme != "WCSPH" && boundary_density isa PressureMirroring + # Mirroring removes pressure diffusion; boundary volume is 1. + @test dv_fluid[3, 1] ≈ + state.density * sound_speed^2 * + dot(SVector(state.velocity), pair_gradient) + if isnothing(viscosity) + p = TrixiParticles.current_pressure(v_fluid, fluid, 1) - + TrixiParticles.average_pressure(fluid, 1) + expected = -((fluid.mass[1] / state.density)^2 + 1) * + p * + pair_gradient + @test isapprox(force_fluid_rhs, expected, + atol=sqrt(eps())) + end + end dv_structure = TrixiParticles.wrap_v(dv_ode, structure, semi) if structure isa RigidBodySystem @test isapprox(structure.resultant_force[], @@ -614,6 +602,41 @@ end end + @testset "Mirrored no-slip velocity: $boundary_type" for boundary_type in + (WallBoundarySystem, + structure_types...) + viscosity = ViscosityAdami(nu=0.1) + velocity = SVector(1.0, 0.5) + fluid_system = create_fluid_system("WCSPH", (0.0, 0.0), fluid_density, + viscosity) + boundary = create_structure_system(boundary_type, viscosity; + boundary_density=PressureMirroring(), + velocity) + fluid, boundary, arrays, semi, _ = initialize(fluid_system, boundary) + v, u, v_boundary, u_boundary = arrays + @test boundary.boundary_model.cache.wall_velocity[:, 1] ≈ 2 * velocity + dv = zero(v) + TrixiParticles.interact!(dv, v, u, v_boundary, u_boundary, fluid, boundary, + semi) + @test dot(dv[1:2, 1], velocity) > 0 # Moving boundary drags fluid at rest. + end + + @testset "Mirrored EDAC wall: $scheme" for scheme in + ("EDAC", + "EDAC with average pressure reduction") + fluid_system = create_fluid_system(scheme, (1.0, 0.5), 1005.0, nothing) + wall = create_structure_system(WallBoundarySystem, nothing; + boundary_density=PressureMirroring()) + fluid, wall, arrays, semi, _ = initialize(fluid_system, wall) + v, u, v_wall, u_wall = arrays + dv = zero(v) + TrixiParticles.interact!(dv, v, u, v_wall, u_wall, fluid, wall, semi) + p = 500.0 - TrixiParticles.average_pressure(fluid, 1) + expected = -((fluid.mass[1] / 1005.0)^2 + 1) * p * pair_gradient / fluid.mass[1] + @test isapprox(dv[1:2, 1], expected, atol=sqrt(eps())) + @test dv[3, 1] ≈ 1005.0 * sound_speed^2 * dot(SVector(1.0, 0.5), pair_gradient) + end + # `ShepardKernelCorrection` requires `SummationDensity` for the fluid, # so it cannot be tested with the prescribed fluid densities above. shepard_configurations = ((TotalLagrangianSPHSystem, AdamiPressureExtrapolation()), diff --git a/test/systems/edac_system.jl b/test/systems/edac_system.jl index dd7dda04fe..83fc48d6dc 100644 --- a/test/systems/edac_system.jl +++ b/test/systems/edac_system.jl @@ -219,15 +219,24 @@ smoothing_length = 1.6particle_spacing fluid = rectangular_patch(particle_spacing, (3, 3), seed=1) + wall = InitialCondition(; coordinates=zeros(2, 1), density=1000.0, particle_spacing) + model = BoundaryModelDummyParticles(wall.density, wall.mass, PressureMirroring(), + smoothing_kernel, smoothing_length) + wall_system = WallBoundarySystem(wall, model) transport_velocity = [nothing, TransportVelocityAdami(background_pressure=10000.0)] names = ["No TVF", "TransportVelocityAdami"] - @testset "$(names[i])" for i in eachindex(transport_velocity) + @testset "$(names[i]), mirrored wall=$mirrored_wall" for i in + eachindex(transport_velocity), + mirrored_wall in + (false, true) + system = EntropicallyDampedSPHSystem(fluid; smoothing_kernel, smoothing_length, sound_speed=0.0, shifting_technique=transport_velocity[i], average_pressure_reduction=true) - semi = Semidiscretization(system) + semi = mirrored_wall ? Semidiscretization(system, wall_system) : + Semidiscretization(system) TrixiParticles.initialize_neighborhood_searches!(semi) @@ -238,10 +247,14 @@ system.average_pressure_reduction, v_ode, u_ode, semi) - @test all(i -> system.cache.neighbor_counter[i] == nparticles(system), - nparticles(system)) - @test all(i -> isapprox(system.cache.pressure_average[i], -50.968532955185964), + n_neighbors = nparticles(system) + mirrored_wall + @test all(i -> system.cache.neighbor_counter[i] == n_neighbors, nparticles(system)) + # The wall contributes each fluid particle's own pressure, not its zero cache. + expected = mirrored_wall ? + (sum(fluid.pressure) .+ fluid.pressure) / n_neighbors : + fill(-50.968532955185964, nparticles(system)) + @test system.cache.pressure_average ≈ expected end end From ceaa9f3721e81c8444de0c70f7e5d3230706d43a Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Thu, 22 Oct 2026 10:21:08 +0200 Subject: [PATCH 36/46] fix system order inconsistency --- src/general/semidiscretization.jl | 16 ++++-- .../boundary/wall_boundary/dummy_particles.jl | 21 ++++---- src/schemes/boundary/wall_boundary/system.jl | 1 + .../implicit_incompressible_sph/system.jl | 28 ++++++----- src/schemes/structure/rigid_body/system.jl | 6 ++- src/schemes/structure/structure.jl | 6 +-- .../structure/total_lagrangian_sph/system.jl | 2 +- test/general/semidiscretization.jl | 17 ++++++- test/schemes/fluid/rhs.jl | 50 +++++++++++++++---- 9 files changed, 107 insertions(+), 40 deletions(-) diff --git a/src/general/semidiscretization.jl b/src/general/semidiscretization.jl index 67ceebb3d8..c5c258d1f8 100644 --- a/src/general/semidiscretization.jl +++ b/src/general/semidiscretization.jl @@ -123,7 +123,7 @@ function Semidiscretization(systems::Union{AbstractSystem, Nothing}...; # Check e.g. that the boundary systems are using a state equation if EDAC is not used. # Other checks might be added here later. - check_configuration(systems, neighborhood_search) + check_configuration(systems, neighborhood_search, interaction_matrix) sizes_u = [u_nvariables(system) * n_integrated_particles(system) for system in systems] @@ -507,12 +507,22 @@ end return reshape(view(array, range), Int.(size)) end -function check_configuration(systems, - nhs::Union{Nothing, AbstractNeighborhoodSearch}) +function check_configuration(systems::Union{Tuple, AbstractVector}, + nhs::Union{Nothing, AbstractNeighborhoodSearch}, + interaction_matrix=create_interaction_matrix(nothing, systems)) foreach_system(systems) do system check_configuration(system, systems, nhs) end + for i in eachindex(systems), j in eachindex(systems) + # Either direction may use the structure's boundary density. With both directions + # disabled, this is not a fluid-structure interaction. + if is_enabled_interaction(interaction_matrix[i, j]) || + is_enabled_interaction(interaction_matrix[j, i]) + check_boundary_density_fsi(systems[i], systems[j]) + end + end + check_system_color(systems) end diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index 7cf298f99d..0759cc0d9d 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -268,7 +268,7 @@ function create_cache_model(initial_density::AbstractVector, ::PressureMirroring density = copy(initial_density) # Sum of the kernel weights of the fluid neighbors to interpolate the fluid velocity - # for the no-slip condition (see `compute_pressure!`) + # for the no-slip condition (see `interpolate_wall_velocity!`) volume = similar(initial_density) return (; density, volume) @@ -464,8 +464,6 @@ function compute_density!(boundary_model, ::PressureBoundaries, system, v, u, v_ (; density) = cache # Density is in the cache for `SummationDensity` summation_density!(system, semi, u, u_ode, density; particles=eachparticle(system)) - - predict_advection!(system, v, u, v_ode, u_ode, semi) end function compute_pressure!(boundary_model, ::Union{SummationDensity, ContinuityDensity}, @@ -581,19 +579,24 @@ function compute_adami_density!(boundary_model, system, v, particle) inverse_state_equation!(density, state_equation, pressure, particle) end -function compute_pressure!(boundary_model, ::Union{PressureZeroing, PressureBoundaries}, +function compute_pressure!(boundary_model, + ::Union{PressureMirroring, PressureZeroing, PressureBoundaries}, system, v, u, v_ode, u_ode, semi) - # No pressure update needed with `PressureZeroing`. + # No pressure update needed with `PressureMirroring` and `PressureZeroing`. # Pressure update for `PressureBoundaries` is be done by the PPE solver in IISPH return boundary_model end -function compute_pressure!(boundary_model, ::PressureMirroring, - system, v, u, v_ode, u_ode, semi) +@inline function interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, + semi) + return boundary_model +end + +function interpolate_wall_velocity!(boundary_model::BoundaryModelDummyParticles{PressureMirroring}, + system, v, u, v_ode, u_ode, semi) (; cache, viscosity) = boundary_model - # No pressure update needed, since the fluid pressure is mirrored in the momentum - # equation. Without a viscosity model, the wall velocity is not used either. + # Without a viscosity model, the wall velocity is not used. isnothing(viscosity) && return boundary_model # For the no-slip condition, interpolate the fluid velocity as in the pressure diff --git a/src/schemes/boundary/wall_boundary/system.jl b/src/schemes/boundary/wall_boundary/system.jl index f9864ecc05..5a3b189e6e 100644 --- a/src/schemes/boundary/wall_boundary/system.jl +++ b/src/schemes/boundary/wall_boundary/system.jl @@ -214,6 +214,7 @@ function update_quantities!(system::WallBoundarySystem, v, u, v_ode, u_ode, semi (; boundary_model) = system update_density!(boundary_model, system, v, u, v_ode, u_ode, semi) + interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) return system end diff --git a/src/schemes/fluid/implicit_incompressible_sph/system.jl b/src/schemes/fluid/implicit_incompressible_sph/system.jl index 6bf1aba763..d9a7a94b76 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/system.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/system.jl @@ -204,7 +204,7 @@ end @inline density_calculator(system::ImplicitIncompressibleSPHSystem) = nothing -# Calculates the pressure values by solving a linear system with a relaxed Jacobi scheme +# Compute density before the prediction and pressure solve in `update_implicit_sph!`. function update_quantities!(system::ImplicitIncompressibleSPHSystem, v, u, v_ode, u_ode, semi, t) (; density) = system @@ -212,8 +212,7 @@ function update_quantities!(system::ImplicitIncompressibleSPHSystem, v, u, # Compute density by kernel summation summation_density!(system, semi, u, u_ode, density) - @trixi_timeit timer() "predict advection" predict_advection!(system, v, u, v_ode, u_ode, - semi) + return system end function update_implicit_sph!(semi, v_ode, u_ode, t) @@ -222,21 +221,24 @@ function update_implicit_sph!(semi, v_ode, u_ode, t) return semi end + # All densities and mirrored wall velocities are ready after `update_quantities!`. + # Predict every fluid velocity before computing coefficients that use neighboring + # predictions, including those of `PressureBoundaries`, regardless of system order. + @trixi_timeit timer() "predict advection" begin + foreach_system_wrapped(semi, v_ode, u_ode) do system, v, u + calculate_predicted_velocity_and_d_ii_values!(system, v, u, v_ode, u_ode, semi) + end + foreach_system_wrapped(semi, v_ode, u_ode) do system, v, u + calculate_diagonal_elements_and_predicted_density!(system, v, u, v_ode, u_ode, + semi) + end + end + @trixi_timeit timer() "pressure solver" pressure_solve!(semi, v_ode, u_ode) return semi end -function predict_advection!(system::Union{ImplicitIncompressibleSPHSystem, - WallBoundarySystem{<:BoundaryModelDummyParticles{<:PressureBoundaries}}}, - v, u, v_ode, u_ode, semi) - calculate_predicted_velocity_and_d_ii_values!(system, v, u, v_ode, u_ode, semi) - - calculate_diagonal_elements_and_predicted_density!(system, v, u, v_ode, u_ode, semi) - - return system -end - function calculate_predicted_velocity_and_d_ii_values!(system, v, u, v_ode, u_ode, semi) return system end diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index 0224758508..aa02998299 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -360,6 +360,11 @@ function restart_with!(system::RigidBodySystem, v, u) return system end +function update_quantities!(system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) + interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) + return system +end + function update_boundary_interpolation!(system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) return update_boundary_interpolation!(system.boundary_model, system, v, u, v_ode, @@ -631,7 +636,6 @@ function check_configuration(system::RigidBodySystem, systems, nhs) end check_smoothing_kernel_fsi(system, boundary_model, neighbor) - check_boundary_density_fsi(system, boundary_model, neighbor) if neighbor isa AbstractFluidSystem && neighbor.surface_normal_method isa ColorfieldSurfaceNormal diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index cc9c6581fe..6e3b677d39 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -44,15 +44,15 @@ check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system # The density of a structure boundary is computed by the pressure extrapolation or # integrated with the continuity equation. The summation density is only computed for # a `WallBoundarySystem`, so the density of a structure would stay at its initial value. -function check_boundary_density_fsi(system, - boundary_model::BoundaryModelDummyParticles{SummationDensity}, +function check_boundary_density_fsi(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{SummationDensity}}, + RigidBodySystem{<:BoundaryModelDummyParticles{SummationDensity}}}, neighbor_system::AbstractFluidSystem) throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * "`SummationDensity` is not yet supported for a " * "`$(nameof(typeof(system)))` in a fluid-structure interaction")) end -check_boundary_density_fsi(system, boundary_model, neighbor_system) = system +check_boundary_density_fsi(system, neighbor_system) = system function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 8e2c84b35a..84bd19cd37 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -492,6 +492,7 @@ end function update_quantities!(system::TotalLagrangianSPHSystem, v, u, v_ode, u_ode, semi, t) # Precompute PK1 stress tensor @trixi_timeit timer() "stress tensor" compute_pk1_corrected!(system, semi) + interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) return system end @@ -871,6 +872,5 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) foreach_system(systems) do neighbor check_smoothing_kernel_fsi(system, boundary_model, neighbor) - check_boundary_density_fsi(system, boundary_model, neighbor) end end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index 808e846f9d..e889ae0317 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -195,7 +195,8 @@ boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, density_calculator, smoothing_kernel, - smoothing_length) + smoothing_length; + state_equation) structure = create_structure_system(structure_type, boundary_model) error_str = "`BoundaryModelDummyParticles` with density calculator " * "`$(nameof(typeof(density_calculator)))` is not yet supported " * @@ -204,6 +205,20 @@ error_str *= " in a fluid-structure interaction" @test_nowarn TrixiParticles.check_configuration((structure,), nothing) + for systems in + ((structure, fluid_system), (fluid_system, structure)) + @test_nowarn Semidiscretization(systems...; + neighborhood_search=nothing, + interaction_matrix=[true false; + false true]) + end + for interaction_matrix in + ([true true; false true], [true false; true true]) + @test_throws ArgumentError(error_str) Semidiscretization(structure, + fluid_system; + neighborhood_search=nothing, + interaction_matrix) + end end @test_throws ArgumentError(error_str) Semidiscretization(structure, fluid_system; diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 3a754d6d99..b8c5b11f64 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -295,6 +295,11 @@ density_calculator=ContinuityDensity(), viscosity, shifting_technique, correction) + elseif scheme == "IISPH" + return ImplicitIncompressibleSPHSystem(fluid; smoothing_kernel, + smoothing_length, viscosity, + reference_density=fluid_density, + time_step=1e-3) end # Note that the average pressure reduction is enabled by default @@ -345,22 +350,26 @@ # Run the regular update step to compute the boundary pressure, the wall velocity # for the viscosity, and the average pressure of EDAC. Return the systems # stored in the semidiscretization and the wrapped arrays. - function initialize(fluid_system, structure_system) + function initialize(fluid_system, structure_system; boundary_first=false) + systems = boundary_first ? (structure_system, fluid_system) : + (fluid_system, structure_system) semi = if structure_system isa TotalLagrangianSPHSystem @test_logs (:info, r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin - Semidiscretization(fluid_system, structure_system; + Semidiscretization(systems...; parallelization_backend=SerialBackend()) end else - @test_logs Semidiscretization(fluid_system, structure_system; + @test_logs Semidiscretization(systems...; parallelization_backend=SerialBackend()) end ode = semidiscretize(semi, (0.0, 0.01)) v_ode, u_ode = ode.u0.x TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) - fluid, structure = ode.p.semi.systems + fluid, + structure = boundary_first ? reverse(ode.p.semi.systems) : + ode.p.semi.systems semi = ode.p.semi arrays = (TrixiParticles.wrap_v(v_ode, fluid, semi), TrixiParticles.wrap_u(u_ode, fluid, semi), @@ -602,23 +611,46 @@ end end - @testset "Mirrored no-slip velocity: $boundary_type" for boundary_type in - (WallBoundarySystem, - structure_types...) + no_slip_configurations = (("WCSPH", WallBoundarySystem, false), + ("WCSPH", TotalLagrangianSPHSystem, false), + ("WCSPH", RigidBodySystem, false), + ("IISPH", WallBoundarySystem, false), + ("IISPH", WallBoundarySystem, true)) + @testset "Mirrored no-slip velocity: $scheme, $boundary_type, boundary_first=$boundary_first" for (scheme, + boundary_type, + boundary_first) in + no_slip_configurations + viscosity = ViscosityAdami(nu=0.1) velocity = SVector(1.0, 0.5) - fluid_system = create_fluid_system("WCSPH", (0.0, 0.0), fluid_density, + fluid_system = create_fluid_system(scheme, (0.0, 0.0), fluid_density, viscosity) boundary = create_structure_system(boundary_type, viscosity; boundary_density=PressureMirroring(), velocity) - fluid, boundary, arrays, semi, _ = initialize(fluid_system, boundary) + fluid, boundary, arrays, semi, + ode = initialize(fluid_system, boundary; + boundary_first) v, u, v_boundary, u_boundary = arrays @test boundary.boundary_model.cache.wall_velocity[:, 1] ≈ 2 * velocity dv = zero(v) TrixiParticles.interact!(dv, v, u, v_boundary, u_boundary, fluid, boundary, semi) @test dot(dv[1:2, 1], velocity) > 0 # Moving boundary drags fluid at rest. + if scheme == "IISPH" + # The pressure predictor must use the same no-slip force as the RHS, + # both initially and after changing the fluid velocity. + # Pressure is zero in this one-pair setup, isolating viscosity. + @test fluid.advection_velocity[:, 1] ≈ + v[1:2, 1] + fluid.time_step * dv[1:2, 1] + v[1:2, 1] .= velocity / 2 + TrixiParticles.update_systems_and_nhs(ode.u0.x..., semi, 0.0) + fill!(dv, 0) + TrixiParticles.interact!(dv, v, u, v_boundary, u_boundary, fluid, boundary, + semi) + @test fluid.advection_velocity[:, 1] ≈ + v[1:2, 1] + fluid.time_step * dv[1:2, 1] + end end @testset "Mirrored EDAC wall: $scheme" for scheme in From 6e973f5c7bd4fd3cd08ad108eb20c1d2436c515f Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 13:22:00 +0100 Subject: [PATCH 37/46] address reviewer comments --- docs/src/systems/boundary.md | 2 +- src/general/semidiscretization.jl | 16 +- .../boundary/wall_boundary/dummy_particles.jl | 255 +++++++++--------- src/schemes/structure/rigid_body/system.jl | 5 +- src/schemes/structure/structure.jl | 13 +- .../structure/total_lagrangian_sph/system.jl | 5 +- test/general/semidiscretization.jl | 53 ++-- .../dummy_particles/dummy_particles.jl | 128 +++++---- test/schemes/fluid/rhs.jl | 45 +++- 9 files changed, 281 insertions(+), 241 deletions(-) diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index 0f68bb9ec9..5cd5028143 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -69,7 +69,7 @@ We provide six options to compute the boundary density and pressure, determined penetrations. 3. With [`SummationDensity`](@ref), the density is calculated by summation over the neighboring particles, and the pressure is computed from the density with the state equation. - This option is not yet supported for the boundary models of a [`TotalLagrangianSPHSystem`](@ref) + This option is not supported for the boundary models of a [`TotalLagrangianSPHSystem`](@ref) or a [`RigidBodySystem`](@ref) in fluid-structure interaction. 4. With [`ContinuityDensity`](@ref), the density is integrated from the continuity equation, and the pressure is computed from the density with the state equation. diff --git a/src/general/semidiscretization.jl b/src/general/semidiscretization.jl index 6cfaa102c4..d046fde1c7 100644 --- a/src/general/semidiscretization.jl +++ b/src/general/semidiscretization.jl @@ -123,7 +123,7 @@ function Semidiscretization(systems::Union{AbstractSystem, Nothing}...; # Check e.g. that the boundary systems are using a state equation if EDAC is not used. # Other checks might be added here later. - check_configuration(systems, neighborhood_search, interaction_matrix) + check_configuration(systems, neighborhood_search) sizes_u = [u_nvariables(system) * n_integrated_particles(system) for system in systems] @@ -510,22 +510,12 @@ end return reshape(view(array, range), Int.(size)) end -function check_configuration(systems::Union{Tuple, AbstractVector}, - nhs::Union{Nothing, AbstractNeighborhoodSearch}, - interaction_matrix=create_interaction_matrix(nothing, systems)) +function check_configuration(systems, + nhs::Union{Nothing, AbstractNeighborhoodSearch}) foreach_system(systems) do system check_configuration(system, systems, nhs) end - for i in eachindex(systems), j in eachindex(systems) - # Either direction may use the structure's boundary density. With both directions - # disabled, this is not a fluid-structure interaction. - if is_enabled_interaction(interaction_matrix[i, j]) || - is_enabled_interaction(interaction_matrix[j, i]) - check_boundary_density_fsi(systems[i], systems[j]) - end - end - check_system_color(systems) end diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index 0759cc0d9d..8d6620aa47 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -268,7 +268,7 @@ function create_cache_model(initial_density::AbstractVector, ::PressureMirroring density = copy(initial_density) # Sum of the kernel weights of the fluid neighbors to interpolate the fluid velocity - # for the no-slip condition (see `interpolate_wall_velocity!`) + # for the no-slip condition (see `interpolate_wall_velocity!`). volume = similar(initial_density) return (; density, volume) @@ -464,6 +464,9 @@ function compute_density!(boundary_model, ::PressureBoundaries, system, v, u, v_ (; density) = cache # Density is in the cache for `SummationDensity` summation_density!(system, semi, u, u_ode, density; particles=eachparticle(system)) + + # The boundary's diagonal elements and predicted density are computed in + # `update_implicit_sph!`, after all fluid velocities have been predicted. end function compute_pressure!(boundary_model, ::Union{SummationDensity, ContinuityDensity}, @@ -501,53 +504,17 @@ function compute_pressure!(boundary_model, ::Union{AdamiPressureExtrapolation, BernoulliPressureExtrapolation}, system, v, u, v_ode, u_ode, semi) - (; pressure, cache, viscosity) = boundary_model + (; pressure) = boundary_model (; allow_loop_flipping) = boundary_model.density_calculator set_zero!(pressure) - # Set `volume` to zero. When using a viscosity model, the `wall_velocity` is also set to zero. - reset_cache!(cache, viscosity) - - system_coords = current_coordinates(u, system) - - # Use enabled neighbor systems for the pressure extrapolation. This lets phase-specific - # walls isolate their auxiliary pressure state with the same ordered interaction matrix - # used for pairwise RHS dispatch. @trixi_timeit timer() "compute boundary pressure" begin - foreach_system(semi) do neighbor_system - has_system_interaction(system, neighbor_system, semi) || return - - v_neighbor_system = wrap_v(v_ode, neighbor_system, semi) - u_neighbor_system = wrap_u(u_ode, neighbor_system, semi) - - neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - - # This is an optimization for simulations with large and complex boundaries. - # Especially in 3D simulations with large and/or complex structures outside - # of areas with permanent flow. - # Note: The version iterating neighbors first is not thread-parallelizable - # and thus not GPU-compatible. - # The factor is based on the achievable speed-up of the thread parallelizable version. - # Use the parallel version if the number of boundary particles is not much larger - # than the number of fluid particles. - n_boundary_particles = nparticles(system) - n_fluid_particles = nparticles(neighbor_system) - speedup = ceil(Int, Threads.nthreads() / 2) - is_gpu = system_coords isa AbstractGPUArray - condition_boundary = n_boundary_particles < speedup * n_fluid_particles - parallelize = is_gpu || condition_boundary || !allow_loop_flipping - - # Loop over boundary particles and then the neighboring fluid particles - # to extrapolate fluid pressure to the boundaries. - boundary_pressure_extrapolation!(Val(parallelize), boundary_model, system, - neighbor_system, system_coords, - neighbor_coords, v, v_neighbor_system, semi) - end + interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi; + allow_loop_flipping) end - @trixi_timeit timer() "inverse state equation" @threaded semi for particle in - eachparticle(system) + @trixi_timeit timer() "inverse state equation" @threaded semi for particle in eachparticle(system) compute_adami_density!(boundary_model, system, v, particle) end end @@ -561,14 +528,14 @@ function compute_adami_density!(boundary_model, system, v, particle) # The summation is only over fluid particles, thus the volume stays zero when a boundary # particle isn't surrounded by fluid particles. - # Check the volume to avoid NaNs in pressure and velocity. + # Check the volume to avoid NaNs in pressure. if @inbounds volume[particle] > eps() @inbounds pressure[particle] /= volume[particle] - - # To impose no-slip condition - compute_wall_velocity!(viscosity, system, v, particle) end + # To impose no-slip condition + compute_wall_velocity!(viscosity, system, v, particle) + # Clip pressure to avoid sticking artifacts from negative pressures at free surfaces. # This is determined statically and has therefore no overhead. if clip_negative_pressure(boundary_model) @@ -594,117 +561,160 @@ end function interpolate_wall_velocity!(boundary_model::BoundaryModelDummyParticles{PressureMirroring}, system, v, u, v_ode, u_ode, semi) - (; cache, viscosity) = boundary_model + (; viscosity) = boundary_model # Without a viscosity model, the wall velocity is not used. isnothing(viscosity) && return boundary_model - # For the no-slip condition, interpolate the fluid velocity as in the pressure - # extrapolation of `AdamiPressureExtrapolation` (see `boundary_pressure_inner!`). - # Set `volume` and `wall_velocity` to zero. + interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi) + + @threaded semi for particle in eachparticle(system) + compute_wall_velocity!(viscosity, system, v, particle) + end + + return boundary_model +end + +function interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi; + allow_loop_flipping=false) + (; cache, viscosity, density_calculator) = boundary_model + + # Set `volume` to zero. When using a viscosity model, also reset `wall_velocity`. reset_cache!(cache, viscosity) system_coords = current_coordinates(u, system) + # Use the same ordered interaction matrix for interpolation and pairwise forces. foreach_system(semi) do neighbor_system - # Only fluid particles contribute to the interpolated fluid velocity - neighbor_system isa AbstractFluidSystem || return has_system_interaction(system, neighbor_system, semi) || return + # Mirroring only interpolates fluid velocity. Pressure extrapolation also + # supports dynamical-pressure open boundaries. + if density_calculator isa PressureMirroring && + !(neighbor_system isa AbstractFluidSystem) + return + end + v_neighbor_system = wrap_v(v_ode, neighbor_system, semi) u_neighbor_system = wrap_u(u_ode, neighbor_system, semi) - neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - - foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, - semi; - points=eachparticle(system)) do particle, neighbor, - pos_diff, distance - kernel_weight = smoothing_kernel(boundary_model, distance, particle) - cache.volume[particle] += kernel_weight - interpolate_fluid_velocity!(cache, viscosity, neighbor_system, - v_neighbor_system, kernel_weight, particle, - neighbor) - end - end + neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - @threaded semi for particle in eachparticle(system) - # The volume stays zero for boundary particles without fluid neighbors, - # whose wall velocity is not used. - if cache.volume[particle] > eps() - compute_wall_velocity!(viscosity, system, v, particle) - end + # This is an optimization for simulations with large and complex boundaries. + # Especially in 3D simulations with large and/or complex structures outside + # of areas with permanent flow. + # Note: The version iterating neighbors first is not thread-parallelizable + # and thus not GPU-compatible. + # The factor is based on the achievable speed-up of the thread parallelizable version. + # Use the parallel version if the number of boundary particles is not much larger + # than the number of fluid particles. + n_boundary_particles = nparticles(system) + n_fluid_particles = nparticles(neighbor_system) + speedup = ceil(Int, Threads.nthreads() / 2) + is_gpu = system_coords isa AbstractGPUArray + condition_boundary = n_boundary_particles < speedup * n_fluid_particles + parallelize = is_gpu || condition_boundary || !allow_loop_flipping + + interpolate_boundary_values!(Val(parallelize), boundary_model, system, + neighbor_system, system_coords, neighbor_coords, + v, v_neighbor_system, semi) end return boundary_model end -@inline function boundary_pressure_extrapolation!(parallel, boundary_model, system, - neighbor_system, system_coords, - neighbor_coords, v, v_neighbor_system, - semi) +@inline function interpolate_boundary_values!(parallel, boundary_model, system, + neighbor_system, system_coords, + neighbor_coords, v, v_neighbor_system, semi) return boundary_model end -@inline function boundary_pressure_extrapolation!(parallel::Val{true}, boundary_model, - system, - neighbor_system::Union{AbstractFluidSystem, - OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, - system_coords, neighbor_coords, v, - v_neighbor_system, semi) - (; pressure, cache, viscosity, density_calculator) = boundary_model - (; pressure_offset) = density_calculator +@inline function interpolate_boundary_values!(parallel::Val{true}, boundary_model, system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + system_coords, neighbor_coords, v, + v_neighbor_system, semi) + (; density_calculator) = boundary_model - @boundscheck checkbounds(pressure, eachparticle(system)) + @boundscheck checkbounds(boundary_model.cache.volume, eachparticle(system)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi; - points=eachparticle(system)) do particle, neighbor, - pos_diff, distance - @inbounds boundary_pressure_inner!(boundary_model, density_calculator, system, - neighbor_system, v, v_neighbor_system, - particle, neighbor, pos_diff, distance, - viscosity, cache, pressure, pressure_offset) + points=eachparticle(system) + ) do particle, neighbor, + pos_diff, distance + @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, + system, neighbor_system, v, + v_neighbor_system, particle, neighbor, + pos_diff, distance) end end # Loop over fluid particles and then the neighboring boundary particles -# to extrapolate fluid pressure to the boundaries. +# to interpolate fluid values to the boundaries. # Note that this needs to be serial, as we are writing into the same -# pressure entry from different loop iterations. -@inline function boundary_pressure_extrapolation!(parallel::Val{false}, boundary_model, - system, - neighbor_system::Union{AbstractFluidSystem, - OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, - system_coords, neighbor_coords, - v, v_neighbor_system, semi) - (; pressure, cache, viscosity, density_calculator) = boundary_model - (; pressure_offset) = density_calculator +# boundary-particle entries from different loop iterations. +@inline function interpolate_boundary_values!(parallel::Val{false}, boundary_model, system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + system_coords, neighbor_coords, + v, v_neighbor_system, semi) + (; density_calculator) = boundary_model - @boundscheck checkbounds(pressure, eachparticle(system)) + @boundscheck checkbounds(boundary_model.cache.volume, eachparticle(system)) # This needs to be serial to avoid race conditions when writing into `system` foreach_point_neighbor(neighbor_system, system, neighbor_coords, system_coords, semi; points=each_integrated_particle(neighbor_system), - parallelization_backend=SerialBackend()) do neighbor, particle, - pos_diff, distance + parallelization_backend=SerialBackend() + ) do neighbor, particle, + pos_diff, distance # Since neighbor and particle are switched pos_diff = -pos_diff - @inbounds boundary_pressure_inner!(boundary_model, density_calculator, system, - neighbor_system, v, v_neighbor_system, - particle, neighbor, pos_diff, distance, - viscosity, cache, pressure, pressure_offset) + @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, + system, neighbor_system, v, + v_neighbor_system, particle, neighbor, + pos_diff, distance) end end -@propagate_inbounds function boundary_pressure_inner!(boundary_model, - boundary_density_calculator, system, - neighbor_system::Union{AbstractFluidSystem, - OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, - v, v_neighbor_system, particle, - neighbor, pos_diff, distance, - viscosity, cache, pressure, - pressure_offset) +@propagate_inbounds function interpolate_boundary_values_inner!(boundary_model, + density_calculator, system, + neighbor_system, v, + v_neighbor_system, particle, + neighbor, pos_diff, + distance) + (; cache, viscosity) = boundary_model + + kernel_weight = smoothing_kernel(boundary_model, distance, particle) + + extrapolate_boundary_pressure!(boundary_model, density_calculator, system, + neighbor_system, v, v_neighbor_system, particle, + neighbor, pos_diff, distance, kernel_weight) + + cache.volume[particle] += kernel_weight + interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, + kernel_weight, particle, neighbor) +end + +@inline function extrapolate_boundary_pressure!(boundary_model, ::PressureMirroring, + system, neighbor_system, v, + v_neighbor_system, particle, neighbor, + pos_diff, distance, kernel_weight) + # Mirrored pressure is taken directly from the fluid during the pair interaction. + return boundary_model +end + +@propagate_inbounds function extrapolate_boundary_pressure!(boundary_model, + density_calculator::Union{AdamiPressureExtrapolation, + BernoulliPressureExtrapolation}, + system, neighbor_system, v, + v_neighbor_system, particle, + neighbor, pos_diff, distance, + kernel_weight) + (; pressure) = boundary_model + (; pressure_offset) = density_calculator + density_neighbor = current_density(v_neighbor_system, neighbor_system, neighbor) # Fluid pressure term @@ -717,7 +727,7 @@ end hydrostatic_pressure = dot(resulting_acceleration, density_neighbor * pos_diff) # Additional dynamic pressure term (only with `BernoulliPressureExtrapolation`) - dynamic_pressure_ = dynamic_pressure(boundary_density_calculator, + dynamic_pressure_ = dynamic_pressure(density_calculator, v, v_neighbor_system, system, neighbor_system, particle, neighbor, pos_diff, distance, density_neighbor) @@ -725,13 +735,9 @@ end sum_pressures = pressure_offset + fluid_pressure + dynamic_pressure_ + hydrostatic_pressure - kernel_weight = smoothing_kernel(boundary_model, distance, particle) - pressure[particle] += sum_pressures * kernel_weight - cache.volume[particle] += kernel_weight - interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, - kernel_weight, particle, neighbor) + return boundary_model end @inline function dynamic_pressure(boundary_density_calculator, v, @@ -781,7 +787,7 @@ end # by computing the wall velocity as v_w = 2 * v_boundary - ṽ_fluid, where ṽ_fluid is the # kernel-weighted interpolation of the surrounding fluid velocities: # ṽ_fluid = (Σ_b v_b W_ab) / (Σ_b W_ab) -# The denominator Σ_b W_ab is stored as `volume` and accumulated in `compute_wall_velocity!`. +# The denominator Σ_b W_ab is stored as `volume` by `interpolate_boundary_values_inner!`. @propagate_inbounds function interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, kernel_weight, particle, neighbor) @@ -803,6 +809,11 @@ end (; cache) = boundary_model (; volume, wall_velocity) = cache + # Boundary particles without fluid neighbors have no interpolated velocity. + # Skip them to avoid division by zero. + volume_particle = @inbounds volume[particle] + volume_particle > eps() || return viscosity + # Prescribed velocity of the boundary particle. # This velocity is zero when not using moving boundaries or TLSPH. # If not using TLSPH with velocity averaging, this function simply @@ -814,7 +825,7 @@ end # where ṽ_fluid = wall_velocity / volume is the kernel-weighted fluid velocity # interpolated to the boundary particle location by `interpolate_fluid_velocity!`. new_velocity = @inbounds 2 * v_boundary[dim] - - wall_velocity[dim, particle] / volume[particle] + wall_velocity[dim, particle] / volume_particle @inbounds wall_velocity[dim, particle] = new_velocity end return viscosity diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index aa02998299..e42f861bbe 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -361,7 +361,9 @@ function restart_with!(system::RigidBodySystem, v, u) end function update_quantities!(system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) - interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) + @trixi_timeit timer() "interpolate wall velocity" begin + interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) + end return system end @@ -635,6 +637,7 @@ function check_configuration(system::RigidBodySystem, systems, nhs) "when simulating a fluid-structure interaction.")) end + check_boundary_density_fsi(system, boundary_model, neighbor) check_smoothing_kernel_fsi(system, boundary_model, neighbor) if neighbor isa AbstractFluidSystem && diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 6e3b677d39..6672f53f95 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -41,18 +41,17 @@ end check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system -# The density of a structure boundary is computed by the pressure extrapolation or -# integrated with the continuity equation. The summation density is only computed for -# a `WallBoundarySystem`, so the density of a structure would stay at its initial value. -function check_boundary_density_fsi(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{SummationDensity}}, - RigidBodySystem{<:BoundaryModelDummyParticles{SummationDensity}}}, +# Summation density is only computed for wall boundary systems. Structures would +# retain their initial boundary density during fluid-structure interaction. +function check_boundary_density_fsi(system, + boundary_model::BoundaryModelDummyParticles{SummationDensity}, neighbor_system::AbstractFluidSystem) throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * - "`SummationDensity` is not yet supported for a " * + "`SummationDensity` is not supported for a " * "`$(nameof(typeof(system)))` in a fluid-structure interaction")) end -check_boundary_density_fsi(system, neighbor_system) = system +check_boundary_density_fsi(system, boundary_model, neighbor_system) = system function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 84bd19cd37..e5d78ebe2a 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -492,7 +492,9 @@ end function update_quantities!(system::TotalLagrangianSPHSystem, v, u, v_ode, u_ode, semi, t) # Precompute PK1 stress tensor @trixi_timeit timer() "stress tensor" compute_pk1_corrected!(system, semi) - interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) + @trixi_timeit timer() "interpolate wall velocity" begin + interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) + end return system end @@ -871,6 +873,7 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) end foreach_system(systems) do neighbor + check_boundary_density_fsi(system, boundary_model, neighbor) check_smoothing_kernel_fsi(system, boundary_model, neighbor) end end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index e889ae0317..3f15ba446b 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -188,38 +188,39 @@ fluid_system; neighborhood_search=nothing) - unsupported_densities = structure_type === TotalLagrangianSPHSystem ? - (ContinuityDensity(), SummationDensity()) : - (SummationDensity(),) - for density_calculator in unsupported_densities + # Summation density is unsupported for both structure types. + boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, + SummationDensity(), + smoothing_kernel, + smoothing_length; + state_equation) + structure = create_structure_system(structure_type, boundary_model) + error_str = "`BoundaryModelDummyParticles` with density calculator " * + "`SummationDensity` is not supported for a `$structure_type` " * + "in a fluid-structure interaction" + @test_nowarn TrixiParticles.check_configuration((structure,), nothing) + for systems in ((structure, fluid_system), (fluid_system, structure)), + interaction_matrix in ([true false; false true], + [true true; false true], + [true false; true true]) + @test_throws ArgumentError(error_str) Semidiscretization(systems...; + neighborhood_search=nothing, + interaction_matrix) + end + @test_throws ArgumentError(error_str) Semidiscretization(structure, + fluid_system; + neighborhood_search=nothing) + + # TLSPH also rejects continuity density. + if structure_type === TotalLagrangianSPHSystem boundary_model = BoundaryModelDummyParticles(ic.density, ic.mass, - density_calculator, + ContinuityDensity(), smoothing_kernel, smoothing_length; state_equation) structure = create_structure_system(structure_type, boundary_model) error_str = "`BoundaryModelDummyParticles` with density calculator " * - "`$(nameof(typeof(density_calculator)))` is not yet supported " * - "for a `$structure_type`" - if density_calculator isa SummationDensity - error_str *= " in a fluid-structure interaction" - @test_nowarn TrixiParticles.check_configuration((structure,), - nothing) - for systems in - ((structure, fluid_system), (fluid_system, structure)) - @test_nowarn Semidiscretization(systems...; - neighborhood_search=nothing, - interaction_matrix=[true false; - false true]) - end - for interaction_matrix in - ([true true; false true], [true false; true true]) - @test_throws ArgumentError(error_str) Semidiscretization(structure, - fluid_system; - neighborhood_search=nothing, - interaction_matrix) - end - end + "`ContinuityDensity` is not yet supported for a `TotalLagrangianSPHSystem`" @test_throws ArgumentError(error_str) Semidiscretization(structure, fluid_system; neighborhood_search=nothing) diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index ef997a1ed6..8b33f391c0 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -102,7 +102,7 @@ @test dynamic_pressure == 24.0 end - @testset verbose=true "Viscosity Adami/Bernoulli: Wall Velocity" begin + @testset verbose=true "Interpolated Wall Velocity" begin particle_spacing = 0.1 # Boundary particles in fluid compact support @@ -141,7 +141,7 @@ reference_density=257.0, exponent=7) - # Define pressure extrapolation methods to test + # Test pressure extrapolation and mirroring with the same analytic velocity fields. boundary_model_adami = BoundaryModelDummyParticles(boundary.density, boundary.mass, AdamiPressureExtrapolation(), smoothing_kernel, @@ -153,14 +153,22 @@ smoothing_kernel, smoothing_length; state_equation, viscosity) + boundary_model_mirroring = BoundaryModelDummyParticles(boundary.density, + boundary.mass, + PressureMirroring(), + smoothing_kernel, + smoothing_length; viscosity) boundary_systems = [ WallBoundarySystem(boundary, boundary_model_adami), WallBoundarySystem(boundary, boundary_model_bernoulli), + WallBoundarySystem(boundary, boundary_model_mirroring), RigidBodySystem(boundary; boundary_model=boundary_model_adami, particle_spacing), RigidBodySystem(boundary; boundary_model=boundary_model_bernoulli, particle_spacing), + RigidBodySystem(boundary; boundary_model=boundary_model_mirroring, + particle_spacing), TotalLagrangianSPHSystem(boundary; smoothing_kernel, smoothing_length, young_modulus=1e6, poisson_ratio=0.3, @@ -168,7 +176,11 @@ TotalLagrangianSPHSystem(boundary; smoothing_kernel, smoothing_length, young_modulus=1e6, poisson_ratio=0.3, - boundary_model=boundary_model_bernoulli) + boundary_model=boundary_model_bernoulli), + TotalLagrangianSPHSystem(boundary; smoothing_kernel, + smoothing_length, young_modulus=1e6, + poisson_ratio=0.3, + boundary_model=boundary_model_mirroring) ] # Create fluid system @@ -194,34 +206,34 @@ @testset "$system_name with $density_calculator" begin boundary_model = boundary_system.boundary_model - @testset "Wall Velocity $v_fluid" for v_fluid in velocities + @testset "Wall Velocity $v_fluid, $parallel" for v_fluid in velocities, + parallel in (Val(true), + Val(false)) viscosity = boundary_model.viscosity pressure = boundary_model.pressure volume = boundary_model.cache.volume - # Reset cache and perform pressure extrapolation + # Check both loop orders, including boundary particles without fluid neighbors. TrixiParticles.reset_cache!(boundary_model.cache, boundary_model.viscosity) - TrixiParticles.boundary_pressure_extrapolation!(Val(true), - boundary_model, - boundary_system, - fluid_system, - boundary.coordinates, - fluid.coordinates, - v_boundary, - v_fluid .* - ones(size(fluid.coordinates)), - semi) + TrixiParticles.interpolate_boundary_values!(parallel, + boundary_model, + boundary_system, + fluid_system, + boundary.coordinates, + fluid.coordinates, + v_boundary, + v_fluid .* + ones(size(fluid.coordinates)), + semi) # Compute wall velocities for particle in TrixiParticles.eachparticle(boundary_system) if volume[particle] > eps() pressure[particle] /= volume[particle] - TrixiParticles.compute_wall_velocity!(viscosity, - boundary_system, - v_boundary, - particle) end + TrixiParticles.compute_wall_velocity!(viscosity, boundary_system, + v_boundary, particle) end # Expected wall velocities @@ -238,7 +250,10 @@ # the wall velocity is `v_wall = -v_fluid` (see eq. 22 in Adami_2012). # With a staggered velocity profile, we can test the smoothed velocity field # for a variable velocity profile. - @testset "Wall Velocity Staggered: Factor $scale" for scale in scale_factors + @testset "Wall Velocity Staggered: Factor $scale, $parallel" for scale in scale_factors, + parallel in (Val(true), + Val(false)) + viscosity = boundary_model.viscosity pressure = boundary_model.pressure volume = boundary_model.cache.volume @@ -251,26 +266,25 @@ end end - # Reset cache and perform pressure extrapolation + # Reset cache and interpolate the staggered fluid velocities. TrixiParticles.reset_cache!(boundary_model.cache, boundary_model.viscosity) - TrixiParticles.boundary_pressure_extrapolation!(Val(true), - boundary_model, - boundary_system, - fluid_system, - boundary.coordinates, - fluid.coordinates, - v_boundary, v_fluid, - semi) + TrixiParticles.interpolate_boundary_values!(parallel, + boundary_model, + boundary_system, + fluid_system, + boundary.coordinates, + fluid.coordinates, + v_boundary, v_fluid, + semi) # Compute wall velocities for particle in TrixiParticles.eachparticle(boundary_system) if volume[particle] > eps() pressure[particle] /= volume[particle] - TrixiParticles.compute_wall_velocity!(viscosity, - boundary_system, - v_boundary, particle) end + TrixiParticles.compute_wall_velocity!(viscosity, boundary_system, + v_boundary, particle) end # Expected wall velocities @@ -349,14 +363,14 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.boundary_pressure_extrapolation!(Val(true), boundary_model, - boundary_system, - fluid_system1, - tank1.boundary.coordinates, - tank1.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.interpolate_boundary_values!(Val(true), boundary_model, + boundary_system, + fluid_system1, + tank1.boundary.coordinates, + tank1.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, @@ -388,14 +402,14 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.boundary_pressure_extrapolation!(Val(true), boundary_model, - boundary_system, - fluid_system2, - tank2.boundary.coordinates, - tank2.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.interpolate_boundary_values!(Val(true), boundary_model, + boundary_system, + fluid_system2, + tank2.boundary.coordinates, + tank2.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, @@ -628,15 +642,15 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.boundary_pressure_extrapolation!(flipped_condition, - boundary_model, - boundary_system, - fluid_system3, - tank3.boundary.coordinates, - tank3.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.interpolate_boundary_values!(flipped_condition, + boundary_model, + boundary_system, + fluid_system3, + tank3.boundary.coordinates, + tank3.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index b8c5b11f64..0839ddfedf 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -367,9 +367,8 @@ v_ode, u_ode = ode.u0.x TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) - fluid, - structure = boundary_first ? reverse(ode.p.semi.systems) : - ode.p.semi.systems + (fluid, structure) = boundary_first ? reverse(ode.p.semi.systems) : + ode.p.semi.systems semi = ode.p.semi arrays = (TrixiParticles.wrap_v(v_ode, fluid, semi), TrixiParticles.wrap_u(u_ode, fluid, semi), @@ -581,17 +580,30 @@ dv_fluid = TrixiParticles.wrap_v(dv_ode, fluid, semi) force_fluid_rhs = fluid.mass[1] * dv_fluid[1:2, 1] if scheme != "WCSPH" && boundary_density isa PressureMirroring - # Mirroring removes pressure diffusion; boundary volume is 1. - @test dv_fluid[3, 1] ≈ - state.density * sound_speed^2 * - dot(SVector(state.velocity), pair_gradient) + # Row 3 is the EDAC pressure derivative. Mirroring gives + # p_b = p_a, so pressure diffusion vanishes. With the + # boundary at rest, only rho_a * c^2 * V_b * v_a ⋅ ∇W_ab remains. + # The boundary's hydrodynamic mass is rho_b * particle_spacing^2. + boundary_volume = particle_spacing^2 + expected_pressure_rate = state.density * sound_speed^2 * + boundary_volume * + dot(SVector(state.velocity), + pair_gradient) + @test dv_fluid[3, 1] ≈ expected_pressure_rate if isnothing(viscosity) - p = TrixiParticles.current_pressure(v_fluid, fluid, 1) - - TrixiParticles.average_pressure(fluid, 1) - expected = -((fluid.mass[1] / state.density)^2 + 1) * - p * - pair_gradient - @test isapprox(force_fluid_rhs, expected, + # Equal mirrored pressures reduce the density-weighted + # pressure average to p_a - p_avg. Multiplying the + # acceleration by m_a gives F_a = -(V_a^2 + V_b^2) * + # (p_a - p_avg) * ∇W_ab. + fluid_volume = fluid.mass[1] / state.density + effective_pressure = TrixiParticles.current_pressure(v_fluid, + fluid, + 1) - + TrixiParticles.average_pressure(fluid, + 1) + expected_force = -(fluid_volume^2 + boundary_volume^2) * + effective_pressure * pair_gradient + @test isapprox(force_fluid_rhs, expected_force, atol=sqrt(eps())) end end @@ -611,6 +623,10 @@ end end + # For fluid at rest, the no-slip ghost velocity is 2 * v_boundary. + # Check that a moving mirrored-pressure boundary drags the fluid along. + # For IISPH, check that the predictor and RHS use the same viscous force, + # including after a fluid-velocity change and for both system orderings. no_slip_configurations = (("WCSPH", WallBoundarySystem, false), ("WCSPH", TotalLagrangianSPHSystem, false), ("WCSPH", RigidBodySystem, false), @@ -653,6 +669,9 @@ end end + # Check mirrored wall pressure in EDAC's acceleration and pressure derivative, + # both with and without average-pressure reduction. Since p_b = p_a, pressure + # diffusion vanishes and the pressure force uses p_a - p_avg on both sides. @testset "Mirrored EDAC wall: $scheme" for scheme in ("EDAC", "EDAC with average pressure reduction") From 2bf7984f84a123fdfaf26eb82cf8a9413b5869f2 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 14:47:48 +0100 Subject: [PATCH 38/46] Format with JuliaFormatter Restores the formatting of three hunks in `dummy_particles.jl` that were identical to `main` before and fixes the formatting check of the tests. --- .../boundary/wall_boundary/dummy_particles.jl | 13 ++++++------- .../boundary/dummy_particles/dummy_particles.jl | 11 +++++++---- test/schemes/fluid/rhs.jl | 5 +++-- 3 files changed, 16 insertions(+), 13 deletions(-) diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index 8d6620aa47..dd90792bd1 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -514,7 +514,8 @@ function compute_pressure!(boundary_model, allow_loop_flipping) end - @trixi_timeit timer() "inverse state equation" @threaded semi for particle in eachparticle(system) + @trixi_timeit timer() "inverse state equation" @threaded semi for particle in + eachparticle(system) compute_adami_density!(boundary_model, system, v, particle) end end @@ -640,9 +641,8 @@ end # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi; - points=eachparticle(system) - ) do particle, neighbor, - pos_diff, distance + points=eachparticle(system)) do particle, neighbor, + pos_diff, distance @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, system, neighbor_system, v, v_neighbor_system, particle, neighbor, @@ -666,9 +666,8 @@ end # This needs to be serial to avoid race conditions when writing into `system` foreach_point_neighbor(neighbor_system, system, neighbor_coords, system_coords, semi; points=each_integrated_particle(neighbor_system), - parallelization_backend=SerialBackend() - ) do neighbor, particle, - pos_diff, distance + parallelization_backend=SerialBackend()) do neighbor, particle, + pos_diff, distance # Since neighbor and particle are switched pos_diff = -pos_diff @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index 8b33f391c0..85a3eeacb6 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -208,7 +208,8 @@ @testset "Wall Velocity $v_fluid, $parallel" for v_fluid in velocities, parallel in (Val(true), - Val(false)) + Val(false)) + viscosity = boundary_model.viscosity pressure = boundary_model.pressure volume = boundary_model.cache.volume @@ -250,9 +251,11 @@ # the wall velocity is `v_wall = -v_fluid` (see eq. 22 in Adami_2012). # With a staggered velocity profile, we can test the smoothed velocity field # for a variable velocity profile. - @testset "Wall Velocity Staggered: Factor $scale, $parallel" for scale in scale_factors, - parallel in (Val(true), - Val(false)) + @testset "Wall Velocity Staggered: Factor $scale, $parallel" for scale in + scale_factors, + parallel in + (Val(true), + Val(false)) viscosity = boundary_model.viscosity pressure = boundary_model.pressure diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 0839ddfedf..26a8f24673 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -367,8 +367,9 @@ v_ode, u_ode = ode.u0.x TrixiParticles.update_systems_and_nhs(v_ode, u_ode, ode.p.semi, 0.0) - (fluid, structure) = boundary_first ? reverse(ode.p.semi.systems) : - ode.p.semi.systems + (fluid, + structure) = boundary_first ? reverse(ode.p.semi.systems) : + ode.p.semi.systems semi = ode.p.semi arrays = (TrixiParticles.wrap_v(v_ode, fluid, semi), TrixiParticles.wrap_u(u_ode, fluid, semi), From 65a8b910bb91a9985aad5a5fa508be41f1fadf9d Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 14:47:51 +0100 Subject: [PATCH 39/46] Use the mirrored pressure in the open-boundary interaction The interaction of the buffer particles of `BoundaryModelDynamicalPressureZhang` read the pressure of the neighbor directly. For walls and structures with `PressureMirroring`, this is the unused pressure stored in the boundary model instead of the pressure of the buffer particle. Use `neighbor_pressure` like the fluid systems do. With EDAC, this also removes the pressure diffusion between the buffer particle and the mirrored wall. --- src/schemes/boundary/open_boundary/rhs.jl | 7 +- .../open_boundary/dynamical_pressure.jl | 106 ++++++++++++++++++ 2 files changed, 112 insertions(+), 1 deletion(-) diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 1385023c3f..12d9fa7536 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -42,7 +42,12 @@ function interact!(dv, v_particle_system, u_particle_system, m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) - p_b = @inbounds current_pressure(v_neighbor_system, neighbor_system, neighbor) + # The following call is equivalent to + # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` + # For boundaries and structures using `PressureMirroring`, this returns + # `p_b = p_a`, which is the pressure of the buffer particle. + p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, + neighbor, p_a) dv_pressure = pressure_acceleration(particle_system, neighbor_system, particle, neighbor, diff --git a/test/schemes/boundary/open_boundary/dynamical_pressure.jl b/test/schemes/boundary/open_boundary/dynamical_pressure.jl index bd325eb690..3838a6ed4d 100644 --- a/test/schemes/boundary/open_boundary/dynamical_pressure.jl +++ b/test/schemes/boundary/open_boundary/dynamical_pressure.jl @@ -168,4 +168,110 @@ # Integrated: velocity + pressure + density (`BoundaryModelDynamicalPressureZhang` always uses `ContinuityDensity`) @test TrixiParticles.v_nvariables(open_boundary_edac_2) == n_dims + 2 end + + # A wall with `PressureMirroring` has no pressure of its own. Instead, each fluid + # particle sees its own pressure at the wall. The buffer particles of the open + # boundary are part of the fluid and must do the same, i.e., they must not read the + # (unused) pressure stored in the wall. + @testset verbose=true "Mirrored Wall Neighbor: $scheme" for scheme in ("WCSPH", "EDAC") + particle_spacing = 0.1 + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 1.2 * particle_spacing + sound_speed = 20.0 + fluid_density = 1020.0 + wall_density = 1000.0 + pressure = 8000.0 + + # Fluid, buffer and wall particle, all within the kernel support of each other + fluid_ic = InitialCondition(; coordinates=reshape([particle_spacing, 0.0], 2, 1), + density=fluid_density, particle_spacing) + buffer_ic = InitialCondition(; coordinates=zeros(2, 1), density=fluid_density, + particle_spacing) + wall_ic = InitialCondition(; coordinates=reshape([0.0, -particle_spacing], 2, 1), + density=wall_density, particle_spacing) + + if scheme == "WCSPH" + # The pressure of the fluid is `sound_speed^2 * (ρ - ρ_0) = pressure` + state_equation = StateEquationCole(; sound_speed, exponent=1, + reference_density=wall_density) + fluid = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, state_equation, + density_calculator=ContinuityDensity()) + else + state_equation = nothing + fluid = EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, + smoothing_length, sound_speed, + density_calculator=ContinuityDensity()) + end + + wall_model = BoundaryModelDummyParticles(wall_ic.density, wall_ic.mass, + PressureMirroring(), smoothing_kernel, + smoothing_length; state_equation) + wall_system = WallBoundarySystem(wall_ic, wall_model) + + zone = BoundaryZone(; initial_condition=buffer_ic, boundary_type=InFlow(), + boundary_face=([0.5particle_spacing, -1.0], + [0.5particle_spacing, 1.0]), + face_normal=[1.0, 0.0], open_boundary_layers=3, + density=fluid_density, particle_spacing, + reference_velocity=[0.0, 0.0]) + open_boundary_system = OpenBoundarySystem(zone; fluid_system=fluid, buffer_size=0, + boundary_model=BoundaryModelDynamicalPressureZhang()) + + semi = Semidiscretization(fluid, wall_system, open_boundary_system; + parallelization_backend=SerialBackend()) + ode = semidiscretize(semi, (0.0, 1.0)) + v_ode, u_ode = ode.u0.x + _, wall, open_boundary = semi.systems + v_open = TrixiParticles.wrap_v(v_ode, open_boundary, semi) + u_open = TrixiParticles.wrap_u(u_ode, open_boundary, semi) + v_wall = TrixiParticles.wrap_v(v_ode, wall, semi) + u_wall = TrixiParticles.wrap_u(u_ode, wall, semi) + + # The pressure of the EDAC buffer particle is an integrated variable + scheme == "EDAC" && + (TrixiParticles.current_pressure(v_open, open_boundary) .= pressure) + TrixiParticles.update_systems_and_nhs(v_ode, u_ode, semi, 0.0) + + p_a = TrixiParticles.current_pressure(v_open, open_boundary, 1) + @test p_a ≈ pressure + + # Interaction of the buffer particle with the wall particle + function interact_buffer_wall(wall_pressure) + # The pressure stored in a mirrored wall is not used + wall.boundary_model.pressure .= wall_pressure + + dv_buffer = zero(v_open) + TrixiParticles.interact!(dv_buffer, v_open, u_open, v_wall, u_wall, + open_boundary, wall, semi) + + return dv_buffer + end + + dv = interact_buffer_wall(0.0) + @test dv ≈ interact_buffer_wall(1234.0) + @test dv ≈ interact_buffer_wall(pressure) + + # The pressure force equals the force of a wall particle with pressure `p_a`. + # The buffer particle is at rest, so there is no viscosity and no continuity term. + m_a = TrixiParticles.hydrodynamic_mass(open_boundary, 1) + m_b = TrixiParticles.hydrodynamic_mass(wall, 1) + pos_diff = SVector(0.0, particle_spacing) + grad_kernel = TrixiParticles.kernel_grad(smoothing_kernel, pos_diff, + particle_spacing, smoothing_length) + if scheme == "WCSPH" + # -m_b * (p_a + p_b) / (ρ_a * ρ_b) * ∇W_ab with `p_b = p_a` + expected = -m_b * (p_a + p_a) / (fluid_density * wall_density) * grad_kernel + else + # -(V_a^2 + V_b^2) / m_a * p̃ * ∇W_ab, where `p̃ = p_a` for `p_b = p_a` + volume_term = ((m_a / fluid_density)^2 + (m_b / wall_density)^2) / m_a + expected = -volume_term * p_a * grad_kernel + + # The pressure difference between the buffer particle and the wall is zero, + # so there is no pressure diffusion. + @test dv[3, 1] == 0 + end + @test dv[1:2, 1] ≈ expected + @test !iszero(expected) + end end From 88fa41370362ef070aa82166796d26183318a59c Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 14:48:02 +0100 Subject: [PATCH 40/46] Keep the wall velocity of structures in SplitIntegrationCallback sub-steps The sub-steps of the `SplitIntegrationCallback` call `update_quantities!` of the `TotalLagrangianSPHSystem`s for a semidiscretization without any fluid systems. Interpolating the no-slip wall velocity of `PressureMirroring` there reset the `wall_velocity` of the boundary model to zero after every sub-step, while `AdamiPressureExtrapolation` keeps it, since the split integration skips `update_boundary_interpolation!`. Interpolate the wall velocity of structures in `update_boundary_interpolation!` instead. This is not required for IISPH, which does not support structures. Walls still interpolate it in `update_quantities!` to provide it to the IISPH advection prediction. --- src/schemes/boundary/wall_boundary/system.jl | 4 ++ src/schemes/structure/rigid_body/system.jl | 10 +--- .../structure/total_lagrangian_sph/system.jl | 11 ++-- test/callbacks/callbacks.jl | 1 + test/callbacks/split_integration.jl | 57 +++++++++++++++++++ 5 files changed, 72 insertions(+), 11 deletions(-) create mode 100644 test/callbacks/split_integration.jl diff --git a/src/schemes/boundary/wall_boundary/system.jl b/src/schemes/boundary/wall_boundary/system.jl index 5a3b189e6e..b13fb39c04 100644 --- a/src/schemes/boundary/wall_boundary/system.jl +++ b/src/schemes/boundary/wall_boundary/system.jl @@ -214,6 +214,10 @@ function update_quantities!(system::WallBoundarySystem, v, u, v_ode, u_ode, semi (; boundary_model) = system update_density!(boundary_model, system, v, u, v_ode, u_ode, semi) + + # The wall velocity of the no-slip condition only depends on the fluid velocity, + # so it can be interpolated here. This makes it available for the advection + # prediction of IISPH, which is computed after all `update_quantities!`. interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) return system diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index e42f861bbe..9350b24cfd 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -360,13 +360,6 @@ function restart_with!(system::RigidBodySystem, v, u) return system end -function update_quantities!(system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) - @trixi_timeit timer() "interpolate wall velocity" begin - interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) - end - return system -end - function update_boundary_interpolation!(system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) return update_boundary_interpolation!(system.boundary_model, system, v, u, v_ode, @@ -380,6 +373,9 @@ end function update_boundary_interpolation!(boundary_model, system::RigidBodySystem, v, u, v_ode, u_ode, semi, t) + @trixi_timeit timer() "interpolate wall velocity" begin + interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) + end update_pressure!(boundary_model, system, v, u, v_ode, u_ode, semi) return system end diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index e5d78ebe2a..306eb754a6 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -492,9 +492,6 @@ end function update_quantities!(system::TotalLagrangianSPHSystem, v, u, v_ode, u_ode, semi, t) # Precompute PK1 stress tensor @trixi_timeit timer() "stress tensor" compute_pk1_corrected!(system, semi) - @trixi_timeit timer() "interpolate wall velocity" begin - interpolate_wall_velocity!(system.boundary_model, system, v, u, v_ode, u_ode, semi) - end return system end @@ -503,7 +500,13 @@ function update_boundary_interpolation!(system::TotalLagrangianSPHSystem, v, u, v_ode, u_ode, semi, t) (; boundary_model) = system - # Only update boundary model + # Only update boundary model. + # The wall velocity of the no-slip condition is interpolated from the fluid and must + # therefore be updated here and not in `update_quantities!`, which is also called + # by the `SplitIntegrationCallback` without any fluid systems. + @trixi_timeit timer() "interpolate wall velocity" begin + interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) + end update_pressure!(boundary_model, system, v, u, v_ode, u_ode, semi) end diff --git a/test/callbacks/callbacks.jl b/test/callbacks/callbacks.jl index b7b91c3951..ed10011b72 100644 --- a/test/callbacks/callbacks.jl +++ b/test/callbacks/callbacks.jl @@ -58,4 +58,5 @@ include("solution_saving.jl") include("density_reinit.jl") include("steady_state_reached.jl") + include("split_integration.jl") end diff --git a/test/callbacks/split_integration.jl b/test/callbacks/split_integration.jl new file mode 100644 index 0000000000..e3dabaf6c4 --- /dev/null +++ b/test/callbacks/split_integration.jl @@ -0,0 +1,57 @@ +using OrdinaryDiffEqLowStorageRK + +@testset verbose=true "SplitIntegrationCallback" begin + # The sub-steps of the split integration only contain the `TotalLagrangianSPHSystem`s, + # but no fluid systems. The no-slip wall velocity in the boundary model of a structure + # is interpolated from the fluid and must not be reset by the sub-steps. + @testset verbose=true "No-Slip Wall Velocity: $(nameof(typeof(density_calculator)))" for density_calculator in + (PressureMirroring(), + AdamiPressureExtrapolation()) + particle_spacing = 0.1 + smoothing_length = 1.2 * particle_spacing * sqrt(2) + smoothing_kernel = WendlandC2Kernel{2}() + fluid_density = 1000.0 + viscosity = ViscosityAdami(nu=0.05) + + # Fluid moving along a clamped plate. Since the plate is at rest, + # the wall velocity of the no-slip condition is `-v_fluid` (see Adami et al. 2012). + fluid = RectangularShape(particle_spacing, (8, 4), (0.0, 0.0), + density=fluid_density, velocity=(1.0, 0.0)) + plate = RectangularShape(particle_spacing, (8, 2), (0.0, -2 * particle_spacing), + density=2700.0) + + fluid_system = EntropicallyDampedSPHSystem(fluid; smoothing_kernel, + smoothing_length, sound_speed=20.0, + viscosity) + + hydrodynamic_density = fill(fluid_density, nparticles(plate)) + boundary_model = BoundaryModelDummyParticles(hydrodynamic_density, + hydrodynamic_density * + particle_spacing^2, + density_calculator, smoothing_kernel, + smoothing_length; viscosity) + structure_system = TotalLagrangianSPHSystem(plate; smoothing_kernel, + smoothing_length, young_modulus=1e5, + poisson_ratio=0.3, boundary_model, + clamped_particles=1:8) + + semi = @test_logs (:info, + r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin + Semidiscretization(fluid_system, structure_system; + parallelization_backend=SerialBackend()) + end + ode = semidiscretize(semi, (0.0, 2e-3)) + + split_integration = SplitIntegrationCallback(CarpenterKennedy2N54(williamson_condition=false), + callback=StepsizeCallback(cfl=1.6), + dt=1.0) + sol = solve(ode, RDPK3SpFSAL35(), dt=1e-5, abstol=1e-7, reltol=1e-5, + save_everystep=false, callback=split_integration) + @test sol.t[end] == 2e-3 + + # The final split integration is done after the last update of the wall velocity + # in the large integrator, which has to remain available. + wall_velocity = structure_system.boundary_model.cache.wall_velocity + @test !iszero(wall_velocity) + end +end From 99b02351fccdf7ba7d910f6215e9bbef95afeeb7 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 14:48:05 +0100 Subject: [PATCH 41/46] Respect the interaction matrix in the SummationDensity check for structures The check was changed to reject `SummationDensity` for structures independent of the interaction matrix, which contradicts the PR description. Restore the previous behavior: only reject it if the structure interacts with a fluid in either direction. The boundary density of a structure is not used otherwise. --- src/general/semidiscretization.jl | 18 +++++++++++++--- src/schemes/structure/rigid_body/system.jl | 1 - src/schemes/structure/structure.jl | 11 +++++----- .../structure/total_lagrangian_sph/system.jl | 1 - test/general/semidiscretization.jl | 21 ++++++++++++------- 5 files changed, 35 insertions(+), 17 deletions(-) diff --git a/src/general/semidiscretization.jl b/src/general/semidiscretization.jl index d046fde1c7..b990989b1f 100644 --- a/src/general/semidiscretization.jl +++ b/src/general/semidiscretization.jl @@ -123,7 +123,7 @@ function Semidiscretization(systems::Union{AbstractSystem, Nothing}...; # Check e.g. that the boundary systems are using a state equation if EDAC is not used. # Other checks might be added here later. - check_configuration(systems, neighborhood_search) + check_configuration(systems, neighborhood_search, interaction_matrix) sizes_u = [u_nvariables(system) * n_integrated_particles(system) for system in systems] @@ -510,12 +510,24 @@ end return reshape(view(array, range), Int.(size)) end -function check_configuration(systems, - nhs::Union{Nothing, AbstractNeighborhoodSearch}) +function check_configuration(systems::Union{Tuple, AbstractVector}, + nhs::Union{Nothing, AbstractNeighborhoodSearch}, + interaction_matrix=create_interaction_matrix(nothing, systems)) foreach_system(systems) do system check_configuration(system, systems, nhs) end + for i in eachindex(systems), j in eachindex(systems) + # `check_boundary_density_fsi` only checks (structure, fluid) pairs, so we loop over + # both orders to be independent of the order of the systems. + # The boundary density of a structure is used by the interaction in either direction. + # With both directions disabled, this is not a fluid-structure interaction. + if is_enabled_interaction(interaction_matrix[i, j]) || + is_enabled_interaction(interaction_matrix[j, i]) + check_boundary_density_fsi(systems[i], systems[j]) + end + end + check_system_color(systems) end diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index 9350b24cfd..cbf91ced2d 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -633,7 +633,6 @@ function check_configuration(system::RigidBodySystem, systems, nhs) "when simulating a fluid-structure interaction.")) end - check_boundary_density_fsi(system, boundary_model, neighbor) check_smoothing_kernel_fsi(system, boundary_model, neighbor) if neighbor isa AbstractFluidSystem && diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 6672f53f95..4e45f49c3b 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -41,17 +41,18 @@ end check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system -# Summation density is only computed for wall boundary systems. Structures would -# retain their initial boundary density during fluid-structure interaction. -function check_boundary_density_fsi(system, - boundary_model::BoundaryModelDummyParticles{SummationDensity}, +# The density of a structure boundary is computed by the pressure extrapolation or +# integrated with the continuity equation. The summation density is only computed for +# a `WallBoundarySystem`, so the density of a structure would stay at its initial value. +function check_boundary_density_fsi(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{SummationDensity}}, + RigidBodySystem{<:BoundaryModelDummyParticles{SummationDensity}}}, neighbor_system::AbstractFluidSystem) throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * "`SummationDensity` is not supported for a " * "`$(nameof(typeof(system)))` in a fluid-structure interaction")) end -check_boundary_density_fsi(system, boundary_model, neighbor_system) = system +check_boundary_density_fsi(system, neighbor_system) = system function interact_structure_fluid!(dv, v_particle_system, u_particle_system, v_neighbor_system, u_neighbor_system, diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 306eb754a6..7748f29072 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -876,7 +876,6 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) end foreach_system(systems) do neighbor - check_boundary_density_fsi(system, boundary_model, neighbor) check_smoothing_kernel_fsi(system, boundary_model, neighbor) end end diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index 3f15ba446b..d114af917a 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -199,13 +199,20 @@ "`SummationDensity` is not supported for a `$structure_type` " * "in a fluid-structure interaction" @test_nowarn TrixiParticles.check_configuration((structure,), nothing) - for systems in ((structure, fluid_system), (fluid_system, structure)), - interaction_matrix in ([true false; false true], - [true true; false true], - [true false; true true]) - @test_throws ArgumentError(error_str) Semidiscretization(systems...; - neighborhood_search=nothing, - interaction_matrix) + for systems in ((structure, fluid_system), (fluid_system, structure)) + # With both directions disabled, this is not a fluid-structure + # interaction, so the boundary density is never used. + @test_nowarn Semidiscretization(systems...; + neighborhood_search=nothing, + interaction_matrix=[true false; + false true]) + # Either direction uses the boundary density of the structure. + for interaction_matrix in ([true true; false true], + [true false; true true]) + @test_throws ArgumentError(error_str) Semidiscretization(systems...; + neighborhood_search=nothing, + interaction_matrix) + end end @test_throws ArgumentError(error_str) Semidiscretization(structure, fluid_system; From 8b0cde58c632bf6be3ef371ad7a0c774fec2b7e5 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 14:48:08 +0100 Subject: [PATCH 42/46] Fix the neighbor count test and add the IISPH prediction fix to NEWS `all(f, nparticles(system))` only checked the last particle, because it iterates over the integer. Check the neighbor count of all particles. --- NEWS.md | 4 ++++ test/systems/edac_system.jl | 4 ++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 82a4529d3b..cfa9611bfc 100644 --- a/NEWS.md +++ b/NEWS.md @@ -37,6 +37,10 @@ used in the Julia ecosystem. Notable changes will be documented in this file for pressure diffusion, and average-pressure reduction at walls and structures. With a boundary viscosity, `PressureMirroring` now computes the wall velocity of the no-slip condition, which was zero before (#1341). +- Fixed the advection prediction of `ImplicitIncompressibleSPHSystem` depending on the + order of the systems in the `Semidiscretization`. The densities and predicted velocities + of systems that are updated later in the same step were taken from the previous update. + This affected `PressureBoundaries` and simulations with multiple IISPH systems (#1341). - Fixed structure-fluid reaction forces with asymmetric corrected fluid kernel gradients by evaluating the fluid-first gradient directly. The continuity equation of `RigidBodySystem` boundaries with `ContinuityDensity` now uses the kernel gradient diff --git a/test/systems/edac_system.jl b/test/systems/edac_system.jl index 83fc48d6dc..3a93b4141f 100644 --- a/test/systems/edac_system.jl +++ b/test/systems/edac_system.jl @@ -247,9 +247,9 @@ system.average_pressure_reduction, v_ode, u_ode, semi) + # Every particle has all particles (including itself) and the wall as neighbors n_neighbors = nparticles(system) + mirrored_wall - @test all(i -> system.cache.neighbor_counter[i] == n_neighbors, - nparticles(system)) + @test all(==(n_neighbors), system.cache.neighbor_counter) # The wall contributes each fluid particle's own pressure, not its zero cache. expected = mirrored_wall ? (sum(fluid.pressure) .+ fluid.pressure) / n_neighbors : From ea94d8267d8ee91fd3c8ca8e635cb3f11907da38 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Mon, 9 Nov 2026 15:42:21 +0100 Subject: [PATCH 43/46] Reduce the size of the pressure-mirroring fix Reuse the existing pair loops of the pressure extrapolation for the mirrored wall velocity instead of renaming and moving them. `boundary_pressure_extrapolation!` and `boundary_pressure_inner!` keep their names, so the tests that call them don't change. `PressureMirroring` only adds a velocity-only method of `boundary_pressure_inner!`, and `interpolate_wall_velocity!` calls the existing pair loops. This includes the buffer particles of `BoundaryModelDynamicalPressureZhang` like the pressure extrapolation does. The kernel weights are only allocated if a viscosity model is used. Make the new tests smaller: - Test the open-boundary interaction with the mirrored wall without a `Semidiscretization`, like the other tests in that file. - Replace the test that runs the `SplitIntegrationCallback` by a unit test that calls the update function of the callback for a semidiscretization without fluid. It is part of the existing no-slip tests, so `test/callbacks` is not changed. Revert the comment-only change in the IISPH interaction and shorten comments. --- src/schemes/boundary/open_boundary/rhs.jl | 6 +- .../boundary/wall_boundary/dummy_particles.jl | 259 +++++++++--------- src/schemes/boundary/wall_boundary/system.jl | 4 +- .../fluid/implicit_incompressible_sph/rhs.jl | 5 +- .../structure/total_lagrangian_sph/system.jl | 5 +- test/callbacks/callbacks.jl | 1 - test/callbacks/split_integration.jl | 57 ---- .../dummy_particles/dummy_particles.jl | 131 ++++----- .../open_boundary/dynamical_pressure.jl | 123 +++------ test/schemes/fluid/rhs.jl | 22 ++ 10 files changed, 249 insertions(+), 364 deletions(-) delete mode 100644 test/callbacks/split_integration.jl diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 12d9fa7536..726c531a67 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -42,10 +42,8 @@ function interact!(dv, v_particle_system, u_particle_system, m_b = @inbounds hydrodynamic_mass(neighbor_system, neighbor) p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) - # The following call is equivalent to - # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # For boundaries and structures using `PressureMirroring`, this returns - # `p_b = p_a`, which is the pressure of the buffer particle. + # Equivalent to `current_pressure(v_neighbor_system, neighbor_system, neighbor)`, + # but returns `p_a` for boundaries and structures using `PressureMirroring` p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index dd90792bd1..ed8f039029 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -97,6 +97,12 @@ function BoundaryModelDummyParticles(initial_density, hydrodynamic_mass, create_cache_model(initial_density, density_calculator, NDIMS)..., create_cache_model(correction, initial_density, NDIMS, n_particles)...) + # The pressure extrapolation already provides the sum of the kernel weights to interpolate + # the fluid velocity for the no-slip condition. Other density calculators need it as well. + if !isnothing(viscosity) && !haskey(cache, :volume) + cache = (; cache..., volume=similar(cache.wall_velocity, n_particles)) + end + # If the `reference_density_spacing` is set calculate the `ideal_neighbor_count` if reference_particle_spacing > 0 # `reference_particle_spacing` has to be set for surface normals to be determined @@ -258,22 +264,13 @@ function create_cache_model(::MixedKernelGradientCorrection, density, NDIMS, n_p end function create_cache_model(initial_density::AbstractVector, - ::Union{SummationDensity, PressureZeroing}, NDIMS) + ::Union{SummationDensity, PressureMirroring, PressureZeroing}, + NDIMS) density = copy(initial_density) return (; density) end -function create_cache_model(initial_density::AbstractVector, ::PressureMirroring, NDIMS) - density = copy(initial_density) - - # Sum of the kernel weights of the fluid neighbors to interpolate the fluid velocity - # for the no-slip condition (see `interpolate_wall_velocity!`). - volume = similar(initial_density) - - return (; density, volume) -end - function create_cache_model(initial_density::AbstractVector, density_calculator::PressureBoundaries, NDIMS) ELTYPE = eltype(initial_density) @@ -504,14 +501,49 @@ function compute_pressure!(boundary_model, ::Union{AdamiPressureExtrapolation, BernoulliPressureExtrapolation}, system, v, u, v_ode, u_ode, semi) - (; pressure) = boundary_model + (; pressure, cache, viscosity) = boundary_model (; allow_loop_flipping) = boundary_model.density_calculator set_zero!(pressure) + # Set `volume` to zero. When using a viscosity model, the `wall_velocity` is also set to zero. + reset_cache!(cache, viscosity) + + system_coords = current_coordinates(u, system) + + # Use enabled neighbor systems for the pressure extrapolation. This lets phase-specific + # walls isolate their auxiliary pressure state with the same ordered interaction matrix + # used for pairwise RHS dispatch. @trixi_timeit timer() "compute boundary pressure" begin - interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi; - allow_loop_flipping) + foreach_system(semi) do neighbor_system + has_system_interaction(system, neighbor_system, semi) || return + + v_neighbor_system = wrap_v(v_ode, neighbor_system, semi) + u_neighbor_system = wrap_u(u_ode, neighbor_system, semi) + + neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) + + # This is an optimization for simulations with large and complex boundaries. + # Especially in 3D simulations with large and/or complex structures outside + # of areas with permanent flow. + # Note: The version iterating neighbors first is not thread-parallelizable + # and thus not GPU-compatible. + # The factor is based on the achievable speed-up of the thread parallelizable version. + # Use the parallel version if the number of boundary particles is not much larger + # than the number of fluid particles. + n_boundary_particles = nparticles(system) + n_fluid_particles = nparticles(neighbor_system) + speedup = ceil(Int, Threads.nthreads() / 2) + is_gpu = system_coords isa AbstractGPUArray + condition_boundary = n_boundary_particles < speedup * n_fluid_particles + parallelize = is_gpu || condition_boundary || !allow_loop_flipping + + # Loop over boundary particles and then the neighboring fluid particles + # to extrapolate fluid pressure to the boundaries. + boundary_pressure_extrapolation!(Val(parallelize), boundary_model, system, + neighbor_system, system_coords, + neighbor_coords, v, v_neighbor_system, semi) + end end @trixi_timeit timer() "inverse state equation" @threaded semi for particle in @@ -529,13 +561,13 @@ function compute_adami_density!(boundary_model, system, v, particle) # The summation is only over fluid particles, thus the volume stays zero when a boundary # particle isn't surrounded by fluid particles. - # Check the volume to avoid NaNs in pressure. + # Check the volume to avoid NaNs in pressure and velocity. if @inbounds volume[particle] > eps() @inbounds pressure[particle] /= volume[particle] - end - # To impose no-slip condition - compute_wall_velocity!(viscosity, system, v, particle) + # To impose no-slip condition + compute_wall_velocity!(viscosity, system, v, particle) + end # Clip pressure to avoid sticking artifacts from negative pressures at free surfaces. # This is determined statically and has therefore no overhead. @@ -562,106 +594,82 @@ end function interpolate_wall_velocity!(boundary_model::BoundaryModelDummyParticles{PressureMirroring}, system, v, u, v_ode, u_ode, semi) - (; viscosity) = boundary_model + (; cache, viscosity) = boundary_model # Without a viscosity model, the wall velocity is not used. isnothing(viscosity) && return boundary_model - interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi) - - @threaded semi for particle in eachparticle(system) - compute_wall_velocity!(viscosity, system, v, particle) - end - - return boundary_model -end - -function interpolate_boundary_values!(boundary_model, system, v, u, v_ode, u_ode, semi; - allow_loop_flipping=false) - (; cache, viscosity, density_calculator) = boundary_model - - # Set `volume` to zero. When using a viscosity model, also reset `wall_velocity`. + # For the no-slip condition, interpolate the fluid velocity like the pressure extrapolation + # of `AdamiPressureExtrapolation`, but without extrapolating the pressure. + # Set `volume` and `wall_velocity` to zero. reset_cache!(cache, viscosity) system_coords = current_coordinates(u, system) - # Use the same ordered interaction matrix for interpolation and pairwise forces. foreach_system(semi) do neighbor_system has_system_interaction(system, neighbor_system, semi) || return - # Mirroring only interpolates fluid velocity. Pressure extrapolation also - # supports dynamical-pressure open boundaries. - if density_calculator isa PressureMirroring && - !(neighbor_system isa AbstractFluidSystem) - return - end - v_neighbor_system = wrap_v(v_ode, neighbor_system, semi) u_neighbor_system = wrap_u(u_ode, neighbor_system, semi) - neighbor_coords = current_coordinates(u_neighbor_system, neighbor_system) - # This is an optimization for simulations with large and complex boundaries. - # Especially in 3D simulations with large and/or complex structures outside - # of areas with permanent flow. - # Note: The version iterating neighbors first is not thread-parallelizable - # and thus not GPU-compatible. - # The factor is based on the achievable speed-up of the thread parallelizable version. - # Use the parallel version if the number of boundary particles is not much larger - # than the number of fluid particles. - n_boundary_particles = nparticles(system) - n_fluid_particles = nparticles(neighbor_system) - speedup = ceil(Int, Threads.nthreads() / 2) - is_gpu = system_coords isa AbstractGPUArray - condition_boundary = n_boundary_particles < speedup * n_fluid_particles - parallelize = is_gpu || condition_boundary || !allow_loop_flipping - - interpolate_boundary_values!(Val(parallelize), boundary_model, system, - neighbor_system, system_coords, neighbor_coords, - v, v_neighbor_system, semi) + boundary_pressure_extrapolation!(Val(true), boundary_model, system, + neighbor_system, system_coords, neighbor_coords, + v, v_neighbor_system, semi) + end + + @threaded semi for particle in eachparticle(system) + # The volume stays zero for boundary particles without fluid neighbors, + # whose wall velocity is not used. + if cache.volume[particle] > eps() + compute_wall_velocity!(viscosity, system, v, particle) + end end return boundary_model end -@inline function interpolate_boundary_values!(parallel, boundary_model, system, - neighbor_system, system_coords, - neighbor_coords, v, v_neighbor_system, semi) +@inline function boundary_pressure_extrapolation!(parallel, boundary_model, system, + neighbor_system, system_coords, + neighbor_coords, v, v_neighbor_system, + semi) return boundary_model end -@inline function interpolate_boundary_values!(parallel::Val{true}, boundary_model, system, - neighbor_system::Union{AbstractFluidSystem, - OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, - system_coords, neighbor_coords, v, - v_neighbor_system, semi) - (; density_calculator) = boundary_model +@inline function boundary_pressure_extrapolation!(parallel::Val{true}, boundary_model, + system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + system_coords, neighbor_coords, v, + v_neighbor_system, semi) + (; pressure, cache, viscosity, density_calculator) = boundary_model - @boundscheck checkbounds(boundary_model.cache.volume, eachparticle(system)) + @boundscheck checkbounds(pressure, eachparticle(system)) # Loop over all pairs of particles and neighbors within the kernel cutoff foreach_point_neighbor(system, neighbor_system, system_coords, neighbor_coords, semi; points=eachparticle(system)) do particle, neighbor, pos_diff, distance - @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, - system, neighbor_system, v, - v_neighbor_system, particle, neighbor, - pos_diff, distance) + @inbounds boundary_pressure_inner!(boundary_model, density_calculator, system, + neighbor_system, v, v_neighbor_system, + particle, neighbor, pos_diff, distance, + viscosity, cache, pressure) end end # Loop over fluid particles and then the neighboring boundary particles -# to interpolate fluid values to the boundaries. +# to extrapolate fluid pressure to the boundaries. # Note that this needs to be serial, as we are writing into the same -# boundary-particle entries from different loop iterations. -@inline function interpolate_boundary_values!(parallel::Val{false}, boundary_model, system, - neighbor_system::Union{AbstractFluidSystem, - OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, - system_coords, neighbor_coords, - v, v_neighbor_system, semi) - (; density_calculator) = boundary_model +# pressure entry from different loop iterations. +@inline function boundary_pressure_extrapolation!(parallel::Val{false}, boundary_model, + system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + system_coords, neighbor_coords, + v, v_neighbor_system, semi) + (; pressure, cache, viscosity, density_calculator) = boundary_model - @boundscheck checkbounds(boundary_model.cache.volume, eachparticle(system)) + @boundscheck checkbounds(pressure, eachparticle(system)) # This needs to be serial to avoid race conditions when writing into `system` foreach_point_neighbor(neighbor_system, system, neighbor_coords, system_coords, semi; @@ -670,49 +678,21 @@ end pos_diff, distance # Since neighbor and particle are switched pos_diff = -pos_diff - @inbounds interpolate_boundary_values_inner!(boundary_model, density_calculator, - system, neighbor_system, v, - v_neighbor_system, particle, neighbor, - pos_diff, distance) + @inbounds boundary_pressure_inner!(boundary_model, density_calculator, system, + neighbor_system, v, v_neighbor_system, + particle, neighbor, pos_diff, distance, + viscosity, cache, pressure) end end -@propagate_inbounds function interpolate_boundary_values_inner!(boundary_model, - density_calculator, system, - neighbor_system, v, - v_neighbor_system, particle, - neighbor, pos_diff, - distance) - (; cache, viscosity) = boundary_model - - kernel_weight = smoothing_kernel(boundary_model, distance, particle) - - extrapolate_boundary_pressure!(boundary_model, density_calculator, system, - neighbor_system, v, v_neighbor_system, particle, - neighbor, pos_diff, distance, kernel_weight) - - cache.volume[particle] += kernel_weight - interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, - kernel_weight, particle, neighbor) -end - -@inline function extrapolate_boundary_pressure!(boundary_model, ::PressureMirroring, - system, neighbor_system, v, - v_neighbor_system, particle, neighbor, - pos_diff, distance, kernel_weight) - # Mirrored pressure is taken directly from the fluid during the pair interaction. - return boundary_model -end - -@propagate_inbounds function extrapolate_boundary_pressure!(boundary_model, - density_calculator::Union{AdamiPressureExtrapolation, - BernoulliPressureExtrapolation}, - system, neighbor_system, v, - v_neighbor_system, particle, - neighbor, pos_diff, distance, - kernel_weight) - (; pressure) = boundary_model - (; pressure_offset) = density_calculator +@propagate_inbounds function boundary_pressure_inner!(boundary_model, + boundary_density_calculator, system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + v, v_neighbor_system, particle, + neighbor, pos_diff, distance, + viscosity, cache, pressure) + (; pressure_offset) = boundary_density_calculator density_neighbor = current_density(v_neighbor_system, neighbor_system, neighbor) @@ -726,7 +706,7 @@ end hydrostatic_pressure = dot(resulting_acceleration, density_neighbor * pos_diff) # Additional dynamic pressure term (only with `BernoulliPressureExtrapolation`) - dynamic_pressure_ = dynamic_pressure(density_calculator, + dynamic_pressure_ = dynamic_pressure(boundary_density_calculator, v, v_neighbor_system, system, neighbor_system, particle, neighbor, pos_diff, distance, density_neighbor) @@ -734,9 +714,29 @@ end sum_pressures = pressure_offset + fluid_pressure + dynamic_pressure_ + hydrostatic_pressure + kernel_weight = smoothing_kernel(boundary_model, distance, particle) + pressure[particle] += sum_pressures * kernel_weight + cache.volume[particle] += kernel_weight - return boundary_model + interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, + kernel_weight, particle, neighbor) +end + +# With `PressureMirroring`, the fluid pressure is used directly in the pair interaction. +# Only the fluid velocity is interpolated to the boundary particles for the no-slip condition. +@propagate_inbounds function boundary_pressure_inner!(boundary_model, ::PressureMirroring, + system, + neighbor_system::Union{AbstractFluidSystem, + OpenBoundarySystem{<:BoundaryModelDynamicalPressureZhang}}, + v, v_neighbor_system, particle, + neighbor, pos_diff, distance, + viscosity, cache, pressure) + kernel_weight = smoothing_kernel(boundary_model, distance, particle) + + cache.volume[particle] += kernel_weight + interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, + kernel_weight, particle, neighbor) end @inline function dynamic_pressure(boundary_density_calculator, v, @@ -786,7 +786,7 @@ end # by computing the wall velocity as v_w = 2 * v_boundary - ṽ_fluid, where ṽ_fluid is the # kernel-weighted interpolation of the surrounding fluid velocities: # ṽ_fluid = (Σ_b v_b W_ab) / (Σ_b W_ab) -# The denominator Σ_b W_ab is stored as `volume` by `interpolate_boundary_values_inner!`. +# The denominator Σ_b W_ab is stored as `volume` and accumulated in `compute_wall_velocity!`. @propagate_inbounds function interpolate_fluid_velocity!(cache, viscosity, neighbor_system, v_neighbor_system, kernel_weight, particle, neighbor) @@ -808,11 +808,6 @@ end (; cache) = boundary_model (; volume, wall_velocity) = cache - # Boundary particles without fluid neighbors have no interpolated velocity. - # Skip them to avoid division by zero. - volume_particle = @inbounds volume[particle] - volume_particle > eps() || return viscosity - # Prescribed velocity of the boundary particle. # This velocity is zero when not using moving boundaries or TLSPH. # If not using TLSPH with velocity averaging, this function simply @@ -824,7 +819,7 @@ end # where ṽ_fluid = wall_velocity / volume is the kernel-weighted fluid velocity # interpolated to the boundary particle location by `interpolate_fluid_velocity!`. new_velocity = @inbounds 2 * v_boundary[dim] - - wall_velocity[dim, particle] / volume_particle + wall_velocity[dim, particle] / volume[particle] @inbounds wall_velocity[dim, particle] = new_velocity end return viscosity diff --git a/src/schemes/boundary/wall_boundary/system.jl b/src/schemes/boundary/wall_boundary/system.jl index b13fb39c04..5a2e575e02 100644 --- a/src/schemes/boundary/wall_boundary/system.jl +++ b/src/schemes/boundary/wall_boundary/system.jl @@ -215,9 +215,7 @@ function update_quantities!(system::WallBoundarySystem, v, u, v_ode, u_ode, semi update_density!(boundary_model, system, v, u, v_ode, u_ode, semi) - # The wall velocity of the no-slip condition only depends on the fluid velocity, - # so it can be interpolated here. This makes it available for the advection - # prediction of IISPH, which is computed after all `update_quantities!`. + # Only depends on the fluid velocity, so it is available for the IISPH prediction interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) return system diff --git a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl index 3ef0421486..21feadd4c8 100644 --- a/src/schemes/fluid/implicit_incompressible_sph/rhs.jl +++ b/src/schemes/fluid/implicit_incompressible_sph/rhs.jl @@ -44,8 +44,9 @@ function interact!(dv, v_particle_system, u_particle_system, p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) # The following call is equivalent to # `p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor)` - # For boundaries and structures using `PressureMirroring`, this returns - # `p_b = p_a`, which is the pressure of the fluid particle. + # Only when the neighbor system is a `WallBoundarySystem` + # or a `TotalLagrangianSPHSystem` with the boundary model `PressureMirroring`, + # this will return `p_b = p_a`, which is the pressure of the fluid particle. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index 7748f29072..bfa0a912d8 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -501,9 +501,8 @@ function update_boundary_interpolation!(system::TotalLagrangianSPHSystem, v, u, (; boundary_model) = system # Only update boundary model. - # The wall velocity of the no-slip condition is interpolated from the fluid and must - # therefore be updated here and not in `update_quantities!`, which is also called - # by the `SplitIntegrationCallback` without any fluid systems. + # Not in `update_quantities!`, which the `SplitIntegrationCallback` also calls + # without any fluid systems to interpolate the wall velocity from. @trixi_timeit timer() "interpolate wall velocity" begin interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) end diff --git a/test/callbacks/callbacks.jl b/test/callbacks/callbacks.jl index ed10011b72..b7b91c3951 100644 --- a/test/callbacks/callbacks.jl +++ b/test/callbacks/callbacks.jl @@ -58,5 +58,4 @@ include("solution_saving.jl") include("density_reinit.jl") include("steady_state_reached.jl") - include("split_integration.jl") end diff --git a/test/callbacks/split_integration.jl b/test/callbacks/split_integration.jl deleted file mode 100644 index e3dabaf6c4..0000000000 --- a/test/callbacks/split_integration.jl +++ /dev/null @@ -1,57 +0,0 @@ -using OrdinaryDiffEqLowStorageRK - -@testset verbose=true "SplitIntegrationCallback" begin - # The sub-steps of the split integration only contain the `TotalLagrangianSPHSystem`s, - # but no fluid systems. The no-slip wall velocity in the boundary model of a structure - # is interpolated from the fluid and must not be reset by the sub-steps. - @testset verbose=true "No-Slip Wall Velocity: $(nameof(typeof(density_calculator)))" for density_calculator in - (PressureMirroring(), - AdamiPressureExtrapolation()) - particle_spacing = 0.1 - smoothing_length = 1.2 * particle_spacing * sqrt(2) - smoothing_kernel = WendlandC2Kernel{2}() - fluid_density = 1000.0 - viscosity = ViscosityAdami(nu=0.05) - - # Fluid moving along a clamped plate. Since the plate is at rest, - # the wall velocity of the no-slip condition is `-v_fluid` (see Adami et al. 2012). - fluid = RectangularShape(particle_spacing, (8, 4), (0.0, 0.0), - density=fluid_density, velocity=(1.0, 0.0)) - plate = RectangularShape(particle_spacing, (8, 2), (0.0, -2 * particle_spacing), - density=2700.0) - - fluid_system = EntropicallyDampedSPHSystem(fluid; smoothing_kernel, - smoothing_length, sound_speed=20.0, - viscosity) - - hydrodynamic_density = fill(fluid_density, nparticles(plate)) - boundary_model = BoundaryModelDummyParticles(hydrodynamic_density, - hydrodynamic_density * - particle_spacing^2, - density_calculator, smoothing_kernel, - smoothing_length; viscosity) - structure_system = TotalLagrangianSPHSystem(plate; smoothing_kernel, - smoothing_length, young_modulus=1e5, - poisson_ratio=0.3, boundary_model, - clamped_particles=1:8) - - semi = @test_logs (:info, - r"^To create the self-interaction neighborhood search of a `TotalLagrangianSPHSystem`") begin - Semidiscretization(fluid_system, structure_system; - parallelization_backend=SerialBackend()) - end - ode = semidiscretize(semi, (0.0, 2e-3)) - - split_integration = SplitIntegrationCallback(CarpenterKennedy2N54(williamson_condition=false), - callback=StepsizeCallback(cfl=1.6), - dt=1.0) - sol = solve(ode, RDPK3SpFSAL35(), dt=1e-5, abstol=1e-7, reltol=1e-5, - save_everystep=false, callback=split_integration) - @test sol.t[end] == 2e-3 - - # The final split integration is done after the last update of the wall velocity - # in the large integrator, which has to remain available. - wall_velocity = structure_system.boundary_model.cache.wall_velocity - @test !iszero(wall_velocity) - end -end diff --git a/test/schemes/boundary/dummy_particles/dummy_particles.jl b/test/schemes/boundary/dummy_particles/dummy_particles.jl index 85a3eeacb6..ef997a1ed6 100644 --- a/test/schemes/boundary/dummy_particles/dummy_particles.jl +++ b/test/schemes/boundary/dummy_particles/dummy_particles.jl @@ -102,7 +102,7 @@ @test dynamic_pressure == 24.0 end - @testset verbose=true "Interpolated Wall Velocity" begin + @testset verbose=true "Viscosity Adami/Bernoulli: Wall Velocity" begin particle_spacing = 0.1 # Boundary particles in fluid compact support @@ -141,7 +141,7 @@ reference_density=257.0, exponent=7) - # Test pressure extrapolation and mirroring with the same analytic velocity fields. + # Define pressure extrapolation methods to test boundary_model_adami = BoundaryModelDummyParticles(boundary.density, boundary.mass, AdamiPressureExtrapolation(), smoothing_kernel, @@ -153,22 +153,14 @@ smoothing_kernel, smoothing_length; state_equation, viscosity) - boundary_model_mirroring = BoundaryModelDummyParticles(boundary.density, - boundary.mass, - PressureMirroring(), - smoothing_kernel, - smoothing_length; viscosity) boundary_systems = [ WallBoundarySystem(boundary, boundary_model_adami), WallBoundarySystem(boundary, boundary_model_bernoulli), - WallBoundarySystem(boundary, boundary_model_mirroring), RigidBodySystem(boundary; boundary_model=boundary_model_adami, particle_spacing), RigidBodySystem(boundary; boundary_model=boundary_model_bernoulli, particle_spacing), - RigidBodySystem(boundary; boundary_model=boundary_model_mirroring, - particle_spacing), TotalLagrangianSPHSystem(boundary; smoothing_kernel, smoothing_length, young_modulus=1e6, poisson_ratio=0.3, @@ -176,11 +168,7 @@ TotalLagrangianSPHSystem(boundary; smoothing_kernel, smoothing_length, young_modulus=1e6, poisson_ratio=0.3, - boundary_model=boundary_model_bernoulli), - TotalLagrangianSPHSystem(boundary; smoothing_kernel, - smoothing_length, young_modulus=1e6, - poisson_ratio=0.3, - boundary_model=boundary_model_mirroring) + boundary_model=boundary_model_bernoulli) ] # Create fluid system @@ -206,35 +194,34 @@ @testset "$system_name with $density_calculator" begin boundary_model = boundary_system.boundary_model - @testset "Wall Velocity $v_fluid, $parallel" for v_fluid in velocities, - parallel in (Val(true), - Val(false)) - + @testset "Wall Velocity $v_fluid" for v_fluid in velocities viscosity = boundary_model.viscosity pressure = boundary_model.pressure volume = boundary_model.cache.volume - # Check both loop orders, including boundary particles without fluid neighbors. + # Reset cache and perform pressure extrapolation TrixiParticles.reset_cache!(boundary_model.cache, boundary_model.viscosity) - TrixiParticles.interpolate_boundary_values!(parallel, - boundary_model, - boundary_system, - fluid_system, - boundary.coordinates, - fluid.coordinates, - v_boundary, - v_fluid .* - ones(size(fluid.coordinates)), - semi) + TrixiParticles.boundary_pressure_extrapolation!(Val(true), + boundary_model, + boundary_system, + fluid_system, + boundary.coordinates, + fluid.coordinates, + v_boundary, + v_fluid .* + ones(size(fluid.coordinates)), + semi) # Compute wall velocities for particle in TrixiParticles.eachparticle(boundary_system) if volume[particle] > eps() pressure[particle] /= volume[particle] + TrixiParticles.compute_wall_velocity!(viscosity, + boundary_system, + v_boundary, + particle) end - TrixiParticles.compute_wall_velocity!(viscosity, boundary_system, - v_boundary, particle) end # Expected wall velocities @@ -251,12 +238,7 @@ # the wall velocity is `v_wall = -v_fluid` (see eq. 22 in Adami_2012). # With a staggered velocity profile, we can test the smoothed velocity field # for a variable velocity profile. - @testset "Wall Velocity Staggered: Factor $scale, $parallel" for scale in - scale_factors, - parallel in - (Val(true), - Val(false)) - + @testset "Wall Velocity Staggered: Factor $scale" for scale in scale_factors viscosity = boundary_model.viscosity pressure = boundary_model.pressure volume = boundary_model.cache.volume @@ -269,25 +251,26 @@ end end - # Reset cache and interpolate the staggered fluid velocities. + # Reset cache and perform pressure extrapolation TrixiParticles.reset_cache!(boundary_model.cache, boundary_model.viscosity) - TrixiParticles.interpolate_boundary_values!(parallel, - boundary_model, - boundary_system, - fluid_system, - boundary.coordinates, - fluid.coordinates, - v_boundary, v_fluid, - semi) + TrixiParticles.boundary_pressure_extrapolation!(Val(true), + boundary_model, + boundary_system, + fluid_system, + boundary.coordinates, + fluid.coordinates, + v_boundary, v_fluid, + semi) # Compute wall velocities for particle in TrixiParticles.eachparticle(boundary_system) if volume[particle] > eps() pressure[particle] /= volume[particle] + TrixiParticles.compute_wall_velocity!(viscosity, + boundary_system, + v_boundary, particle) end - TrixiParticles.compute_wall_velocity!(viscosity, boundary_system, - v_boundary, particle) end # Expected wall velocities @@ -366,14 +349,14 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.interpolate_boundary_values!(Val(true), boundary_model, - boundary_system, - fluid_system1, - tank1.boundary.coordinates, - tank1.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.boundary_pressure_extrapolation!(Val(true), boundary_model, + boundary_system, + fluid_system1, + tank1.boundary.coordinates, + tank1.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, @@ -405,14 +388,14 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.interpolate_boundary_values!(Val(true), boundary_model, - boundary_system, - fluid_system2, - tank2.boundary.coordinates, - tank2.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.boundary_pressure_extrapolation!(Val(true), boundary_model, + boundary_system, + fluid_system2, + tank2.boundary.coordinates, + tank2.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, @@ -645,15 +628,15 @@ TrixiParticles.reset_cache!(boundary_system.boundary_model.cache, viscosity) - TrixiParticles.interpolate_boundary_values!(flipped_condition, - boundary_model, - boundary_system, - fluid_system3, - tank3.boundary.coordinates, - tank3.fluid.coordinates, - v_fluid, - nothing, # Not used - semi) + TrixiParticles.boundary_pressure_extrapolation!(flipped_condition, + boundary_model, + boundary_system, + fluid_system3, + tank3.boundary.coordinates, + tank3.fluid.coordinates, + v_fluid, + nothing, # Not used + semi) for particle in TrixiParticles.eachparticle(boundary_system) TrixiParticles.compute_adami_density!(boundary_model, boundary_system, diff --git a/test/schemes/boundary/open_boundary/dynamical_pressure.jl b/test/schemes/boundary/open_boundary/dynamical_pressure.jl index 3838a6ed4d..db9612fa1a 100644 --- a/test/schemes/boundary/open_boundary/dynamical_pressure.jl +++ b/test/schemes/boundary/open_boundary/dynamical_pressure.jl @@ -169,109 +169,56 @@ @test TrixiParticles.v_nvariables(open_boundary_edac_2) == n_dims + 2 end - # A wall with `PressureMirroring` has no pressure of its own. Instead, each fluid - # particle sees its own pressure at the wall. The buffer particles of the open - # boundary are part of the fluid and must do the same, i.e., they must not read the - # (unused) pressure stored in the wall. - @testset verbose=true "Mirrored Wall Neighbor: $scheme" for scheme in ("WCSPH", "EDAC") + # The buffer particles are part of the fluid. Like all fluid particles, they see their + # own pressure at a wall with `PressureMirroring`, and not the (unused) pressure + # stored in the wall. + @testset verbose=true "Mirrored Wall Neighbor" begin particle_spacing = 0.1 smoothing_kernel = SchoenbergCubicSplineKernel{2}() smoothing_length = 1.2 * particle_spacing - sound_speed = 20.0 - fluid_density = 1020.0 - wall_density = 1000.0 - pressure = 8000.0 - - # Fluid, buffer and wall particle, all within the kernel support of each other - fluid_ic = InitialCondition(; coordinates=reshape([particle_spacing, 0.0], 2, 1), - density=fluid_density, particle_spacing) - buffer_ic = InitialCondition(; coordinates=zeros(2, 1), density=fluid_density, + state_equation = StateEquationCole(; sound_speed=20.0, exponent=1, + reference_density=1000.0) + + # A buffer particle and a wall particle within the kernel support + buffer_ic = InitialCondition(; coordinates=zeros(2, 1), density=1020.0, particle_spacing) wall_ic = InitialCondition(; coordinates=reshape([0.0, -particle_spacing], 2, 1), - density=wall_density, particle_spacing) - - if scheme == "WCSPH" - # The pressure of the fluid is `sound_speed^2 * (ρ - ρ_0) = pressure` - state_equation = StateEquationCole(; sound_speed, exponent=1, - reference_density=wall_density) - fluid = WeaklyCompressibleSPHSystem(fluid_ic; smoothing_kernel, - smoothing_length, state_equation, - density_calculator=ContinuityDensity()) - else - state_equation = nothing - fluid = EntropicallyDampedSPHSystem(fluid_ic; smoothing_kernel, - smoothing_length, sound_speed, - density_calculator=ContinuityDensity()) - end + density=1000.0, particle_spacing) + fluid = WeaklyCompressibleSPHSystem(buffer_ic; smoothing_kernel, smoothing_length, + state_equation, + density_calculator=ContinuityDensity()) + zone = BoundaryZone(; initial_condition=buffer_ic, boundary_type=InFlow(), + boundary_face=([0.5particle_spacing, -1.0], + [0.5particle_spacing, 1.0]), + face_normal=[1.0, 0.0], open_boundary_layers=3, density=1020.0, + particle_spacing, reference_velocity=[0.0, 0.0]) + open_boundary = OpenBoundarySystem(zone; fluid_system=fluid, buffer_size=0, + boundary_model=BoundaryModelDynamicalPressureZhang()) wall_model = BoundaryModelDummyParticles(wall_ic.density, wall_ic.mass, PressureMirroring(), smoothing_kernel, smoothing_length; state_equation) - wall_system = WallBoundarySystem(wall_ic, wall_model) + wall = WallBoundarySystem(wall_ic, wall_model) - zone = BoundaryZone(; initial_condition=buffer_ic, boundary_type=InFlow(), - boundary_face=([0.5particle_spacing, -1.0], - [0.5particle_spacing, 1.0]), - face_normal=[1.0, 0.0], open_boundary_layers=3, - density=fluid_density, particle_spacing, - reference_velocity=[0.0, 0.0]) - open_boundary_system = OpenBoundarySystem(zone; fluid_system=fluid, buffer_size=0, - boundary_model=BoundaryModelDynamicalPressureZhang()) + # Overwrite the pressure of the buffer particle because we skip the update step + p_buffer = 8000.0 + open_boundary.cache.pressure .= p_buffer + v_open = vcat(buffer_ic.velocity, buffer_ic.density') - semi = Semidiscretization(fluid, wall_system, open_boundary_system; - parallelization_backend=SerialBackend()) - ode = semidiscretize(semi, (0.0, 1.0)) - v_ode, u_ode = ode.u0.x - _, wall, open_boundary = semi.systems - v_open = TrixiParticles.wrap_v(v_ode, open_boundary, semi) - u_open = TrixiParticles.wrap_u(u_ode, open_boundary, semi) - v_wall = TrixiParticles.wrap_v(v_ode, wall, semi) - u_wall = TrixiParticles.wrap_u(u_ode, wall, semi) - - # The pressure of the EDAC buffer particle is an integrated variable - scheme == "EDAC" && - (TrixiParticles.current_pressure(v_open, open_boundary) .= pressure) - TrixiParticles.update_systems_and_nhs(v_ode, u_ode, semi, 0.0) - - p_a = TrixiParticles.current_pressure(v_open, open_boundary, 1) - @test p_a ≈ pressure - - # Interaction of the buffer particle with the wall particle function interact_buffer_wall(wall_pressure) - # The pressure stored in a mirrored wall is not used wall.boundary_model.pressure .= wall_pressure - - dv_buffer = zero(v_open) - TrixiParticles.interact!(dv_buffer, v_open, u_open, v_wall, u_wall, - open_boundary, wall, semi) - - return dv_buffer + dv = zero(v_open) + TrixiParticles.interact!(dv, v_open, buffer_ic.coordinates, nothing, + wall_ic.coordinates, open_boundary, wall, + DummySemidiscretization()) + return dv end + # The result is the same as for a wall particle with the pressure of the buffer + # particle, independent of the pressure stored in the wall. dv = interact_buffer_wall(0.0) - @test dv ≈ interact_buffer_wall(1234.0) - @test dv ≈ interact_buffer_wall(pressure) - - # The pressure force equals the force of a wall particle with pressure `p_a`. - # The buffer particle is at rest, so there is no viscosity and no continuity term. - m_a = TrixiParticles.hydrodynamic_mass(open_boundary, 1) - m_b = TrixiParticles.hydrodynamic_mass(wall, 1) - pos_diff = SVector(0.0, particle_spacing) - grad_kernel = TrixiParticles.kernel_grad(smoothing_kernel, pos_diff, - particle_spacing, smoothing_length) - if scheme == "WCSPH" - # -m_b * (p_a + p_b) / (ρ_a * ρ_b) * ∇W_ab with `p_b = p_a` - expected = -m_b * (p_a + p_a) / (fluid_density * wall_density) * grad_kernel - else - # -(V_a^2 + V_b^2) / m_a * p̃ * ∇W_ab, where `p̃ = p_a` for `p_b = p_a` - volume_term = ((m_a / fluid_density)^2 + (m_b / wall_density)^2) / m_a - expected = -volume_term * p_a * grad_kernel - - # The pressure difference between the buffer particle and the wall is zero, - # so there is no pressure diffusion. - @test dv[3, 1] == 0 - end - @test dv[1:2, 1] ≈ expected - @test !iszero(expected) + @test !iszero(dv) + @test dv ≈ interact_buffer_wall(p_buffer) + @test dv ≈ interact_buffer_wall(2 * p_buffer) end end diff --git a/test/schemes/fluid/rhs.jl b/test/schemes/fluid/rhs.jl index 26a8f24673..a006f68a97 100644 --- a/test/schemes/fluid/rhs.jl +++ b/test/schemes/fluid/rhs.jl @@ -662,6 +662,8 @@ v[1:2, 1] + fluid.time_step * dv[1:2, 1] v[1:2, 1] .= velocity / 2 TrixiParticles.update_systems_and_nhs(ode.u0.x..., semi, 0.0) + @test boundary.boundary_model.cache.wall_velocity[:, 1] ≈ + 2 * velocity - v[1:2, 1] fill!(dv, 0) TrixiParticles.interact!(dv, v, u, v_boundary, u_boundary, fluid, boundary, semi) @@ -670,6 +672,26 @@ end end + # The `SplitIntegrationCallback` updates the structure in a semidiscretization + # without fluid. This must not reset the wall velocity of the no-slip condition. + @testset "Mirrored no-slip velocity: update without fluid" begin + viscosity = ViscosityAdami(nu=0.1) + fluid_system = create_fluid_system("WCSPH", (0.0, 0.0), fluid_density, + viscosity) + structure = create_structure_system(TotalLagrangianSPHSystem, viscosity; + boundary_density=PressureMirroring(), + velocity=SVector(1.0, 0.5)) + _, structure, _, _, _ = initialize(fluid_system, structure) + wall_velocity = copy(structure.boundary_model.cache.wall_velocity) + @test !iszero(wall_velocity) + + semi_split = Semidiscretization(structure; + parallelization_backend=SerialBackend()) + v_ode, u_ode = semidiscretize(semi_split, (0.0, 1.0)).u0.x + TrixiParticles.update_systems_split!(semi_split, v_ode, u_ode, 0.0) + @test structure.boundary_model.cache.wall_velocity == wall_velocity + end + # Check mirrored wall pressure in EDAC's acceleration and pressure derivative, # both with and without average-pressure reduction. Since p_b = p_a, pressure # diffusion vanishes and the pressure force uses p_a - p_avg on both sides. From f553f391b48d05a990c16fd9bd28a8b2194d7fab Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 17 Nov 2026 22:46:11 +0100 Subject: [PATCH 44/46] add comment --- src/schemes/structure/structure.jl | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 4e45f49c3b..d1188ecea5 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -41,9 +41,12 @@ end check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system -# The density of a structure boundary is computed by the pressure extrapolation or -# integrated with the continuity equation. The summation density is only computed for -# a `WallBoundarySystem`, so the density of a structure would stay at its initial value. +# Dummy-particle pressure and density are separate from the TLSPH material state. +# Adami extrapolation already uses the current fluid neighborhood. Summation density +# additionally needs current boundary/structure neighbors and the boundary model's kernel; +# the reference-configuration TLSPH self-search cannot supply those neighbors. +# Structure updates do not perform this density summation, so accepting this configuration +# would retain the initial boundary density. function check_boundary_density_fsi(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{SummationDensity}}, RigidBodySystem{<:BoundaryModelDummyParticles{SummationDensity}}}, neighbor_system::AbstractFluidSystem) From 01d14cfe69cf85978737ed2a401a9cfbb85dd4e0 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Tue, 17 Nov 2026 23:06:01 +0100 Subject: [PATCH 45/46] add comment --- src/schemes/structure/total_lagrangian_sph/system.jl | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index bfa0a912d8..e633242a7f 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -868,6 +868,10 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) end end + # `ContinuityDensity` requires integrating the boundary density of all particles, + # including clamped ones. The ODE state only contains `n_integrated_particles`, with + # `v_nvariables` variables per particle. Increasing `v_nvariables` therefore does not + # provide density unknowns for clamped particles, whose motion must remain prescribed. if boundary_model isa BoundaryModelDummyParticles && boundary_model.density_calculator isa ContinuityDensity throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * From 3bbf776354d9eeb78f2ce8f57d4032c7acb29680 Mon Sep 17 00:00:00 2001 From: Sven Berger Date: Wed, 18 Nov 2026 13:27:58 +0100 Subject: [PATCH 46/46] review --- NEWS.md | 6 +++--- docs/src/systems/boundary.md | 12 ++++-------- src/general/semidiscretization.jl | 16 ++-------------- src/schemes/boundary/open_boundary/rhs.jl | 2 +- .../boundary/wall_boundary/dummy_particles.jl | 5 ++--- src/schemes/boundary/wall_boundary/system.jl | 1 - src/schemes/structure/rigid_body/system.jl | 7 ++++--- src/schemes/structure/structure.jl | 14 ++++++-------- .../structure/total_lagrangian_sph/system.jl | 12 +++++++----- test/general/semidiscretization.jl | 18 +++++++----------- .../open_boundary/dynamical_pressure.jl | 2 +- test/systems/rigid_system.jl | 2 +- 12 files changed, 38 insertions(+), 59 deletions(-) diff --git a/NEWS.md b/NEWS.md index 95a71acd6a..26f04ac19b 100644 --- a/NEWS.md +++ b/NEWS.md @@ -15,9 +15,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for `TotalLagrangianSPHSystem` or `RigidBodySystem` must now be the same as those of all fluid systems in the simulation (#1338, #1348). - A `BoundaryModelDummyParticles` with `SummationDensity` is no longer accepted for a - `TotalLagrangianSPHSystem` or `RigidBodySystem` interacting with a fluid. The boundary - density was never computed for structures, so this combination behaved like - `PressureZeroing`, which can be used instead (#1341). + `TotalLagrangianSPHSystem` or `RigidBodySystem`. The boundary density was never computed + for structures, so this combination behaved like `PressureZeroing`, which can be used + instead (#1341). - The `correction` of a `BoundaryModelDummyParticles` of a `TotalLagrangianSPHSystem` or `RigidBodySystem` must now be `nothing`. Previously, it was ignored or caused an error (#1342). diff --git a/docs/src/systems/boundary.md b/docs/src/systems/boundary.md index b5c125b959..978e9c801e 100644 --- a/docs/src/systems/boundary.md +++ b/docs/src/systems/boundary.md @@ -70,7 +70,7 @@ We provide six options to compute the boundary density and pressure, determined 3. With [`SummationDensity`](@ref), the density is calculated by summation over the neighboring particles, and the pressure is computed from the density with the state equation. This option is not supported for the boundary models of a [`TotalLagrangianSPHSystem`](@ref) - or a [`RigidBodySystem`](@ref) in fluid-structure interaction. + or a [`RigidBodySystem`](@ref). 4. With [`ContinuityDensity`](@ref), the density is integrated from the continuity equation, and the pressure is computed from the density with the state equation. This option is not supported for a [`TotalLagrangianSPHSystem`](@ref). @@ -88,13 +88,9 @@ We provide six options to compute the boundary density and pressure, determined momentum equation. This option is not recommended due to stability issues. See [`PressureMirroring`](@ref) for more details. - -Pressure mirroring also applies to TLSPH and rigid-body boundary models. In EDAC, -the mirrored pressure is used in the momentum equation, the pressure evolution -equation, and the average-pressure reduction. Mirroring makes the pressure -diffusion contribution from a fluid-boundary pair zero. -With a viscosity model, the wall velocity of the no-slip condition (see below) -is computed in the same way as with [`AdamiPressureExtrapolation`](@ref). + In EDAC, the mirrored pressure is used in the momentum equation, + the pressure evolution equation, and the average-pressure reduction. + Mirroring makes the pressure diffusion contribution from a fluid-boundary pair zero. #### 1. [`AdamiPressureExtrapolation`](@ref) diff --git a/src/general/semidiscretization.jl b/src/general/semidiscretization.jl index b990989b1f..6610586591 100644 --- a/src/general/semidiscretization.jl +++ b/src/general/semidiscretization.jl @@ -123,7 +123,7 @@ function Semidiscretization(systems::Union{AbstractSystem, Nothing}...; # Check e.g. that the boundary systems are using a state equation if EDAC is not used. # Other checks might be added here later. - check_configuration(systems, neighborhood_search, interaction_matrix) + check_configuration(systems, neighborhood_search) sizes_u = [u_nvariables(system) * n_integrated_particles(system) for system in systems] @@ -511,23 +511,11 @@ end end function check_configuration(systems::Union{Tuple, AbstractVector}, - nhs::Union{Nothing, AbstractNeighborhoodSearch}, - interaction_matrix=create_interaction_matrix(nothing, systems)) + nhs::Union{Nothing, AbstractNeighborhoodSearch}) foreach_system(systems) do system check_configuration(system, systems, nhs) end - for i in eachindex(systems), j in eachindex(systems) - # `check_boundary_density_fsi` only checks (structure, fluid) pairs, so we loop over - # both orders to be independent of the order of the systems. - # The boundary density of a structure is used by the interaction in either direction. - # With both directions disabled, this is not a fluid-structure interaction. - if is_enabled_interaction(interaction_matrix[i, j]) || - is_enabled_interaction(interaction_matrix[j, i]) - check_boundary_density_fsi(systems[i], systems[j]) - end - end - check_system_color(systems) end diff --git a/src/schemes/boundary/open_boundary/rhs.jl b/src/schemes/boundary/open_boundary/rhs.jl index 726c531a67..8ad6c5d382 100644 --- a/src/schemes/boundary/open_boundary/rhs.jl +++ b/src/schemes/boundary/open_boundary/rhs.jl @@ -43,7 +43,7 @@ function interact!(dv, v_particle_system, u_particle_system, p_a = @inbounds current_pressure(v_particle_system, particle_system, particle) # Equivalent to `current_pressure(v_neighbor_system, neighbor_system, neighbor)`, - # but returns `p_a` for boundaries and structures using `PressureMirroring` + # but returns `p_a` for boundaries and structures using `PressureMirroring`. p_b = @inbounds neighbor_pressure(v_neighbor_system, neighbor_system, neighbor, p_a) diff --git a/src/schemes/boundary/wall_boundary/dummy_particles.jl b/src/schemes/boundary/wall_boundary/dummy_particles.jl index 751947ed36..f32bbfcf8b 100644 --- a/src/schemes/boundary/wall_boundary/dummy_particles.jl +++ b/src/schemes/boundary/wall_boundary/dummy_particles.jl @@ -496,9 +496,6 @@ function compute_density!(boundary_model, ::PressureBoundaries, system, v, u, v_ (; density) = cache # Density is in the cache for `SummationDensity` summation_density!(system, semi, u, u_ode, density; particles=eachparticle(system)) - - # The boundary's diagonal elements and predicted density are computed in - # `update_implicit_sph!`, after all fluid velocities have been predicted. end function compute_pressure!(boundary_model, ::Union{SummationDensity, ContinuityDensity}, @@ -622,6 +619,8 @@ function compute_pressure!(boundary_model, return boundary_model end +# The wall velocity for `AdamiPressureExtrapolation` and `BernoulliPressureExtrapolation` +# is computed later in the pressure extrapolation. @inline function interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) return boundary_model diff --git a/src/schemes/boundary/wall_boundary/system.jl b/src/schemes/boundary/wall_boundary/system.jl index 5a2e575e02..3a83fc1958 100644 --- a/src/schemes/boundary/wall_boundary/system.jl +++ b/src/schemes/boundary/wall_boundary/system.jl @@ -215,7 +215,6 @@ function update_quantities!(system::WallBoundarySystem, v, u, v_ode, u_ode, semi update_density!(boundary_model, system, v, u, v_ode, u_ode, semi) - # Only depends on the fluid velocity, so it is available for the IISPH prediction interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) return system diff --git a/src/schemes/structure/rigid_body/system.jl b/src/schemes/structure/rigid_body/system.jl index 4ee111c3bd..128eb1db76 100644 --- a/src/schemes/structure/rigid_body/system.jl +++ b/src/schemes/structure/rigid_body/system.jl @@ -20,9 +20,9 @@ torque and applied consistently to all rigid particles. # Keywords - `boundary_model`: Boundary model for fluid-structure interaction (see [Boundary Models](@ref boundary_models)). - For [`BoundaryModelDummyParticles`](@ref), `correction` must be `nothing`, - since corrections at the boundary particles of structures are not - supported yet. + For [`BoundaryModelDummyParticles`](@ref), [`SummationDensity`](@ref) + is not supported and `correction` must be `nothing`, since corrections + at the boundary particles of structures are not supported yet. - `contact_model`: Optional rigid contact model. If specified, rigid-wall and rigid-rigid collisions are enabled. - `acceleration`: Global acceleration vector applied to all rigid particles. @@ -630,6 +630,7 @@ function check_configuration(system::RigidBodySystem, systems, nhs) end end + check_boundary_model_density(system, boundary_model) check_boundary_model_correction(system, boundary_model) foreach_system(systems) do neighbor diff --git a/src/schemes/structure/structure.jl b/src/schemes/structure/structure.jl index 45c29e27b7..9939a2adc9 100644 --- a/src/schemes/structure/structure.jl +++ b/src/schemes/structure/structure.jl @@ -104,17 +104,15 @@ check_smoothing_kernel_fsi(system, boundary_model, neighbor_system) = system # Adami extrapolation already uses the current fluid neighborhood. Summation density # additionally needs current boundary/structure neighbors and the boundary model's kernel; # the reference-configuration TLSPH self-search cannot supply those neighbors. -# Structure updates do not perform this density summation, so accepting this configuration -# would retain the initial boundary density. -function check_boundary_density_fsi(system::Union{TotalLagrangianSPHSystem{<:BoundaryModelDummyParticles{SummationDensity}}, - RigidBodySystem{<:BoundaryModelDummyParticles{SummationDensity}}}, - neighbor_system::AbstractFluidSystem) +# There is currently no NHS to find current structure neighbors with the boundary model's kernel. +function check_boundary_model_density(system, + ::BoundaryModelDummyParticles{SummationDensity}) throw(ArgumentError("`BoundaryModelDummyParticles` with density calculator " * "`SummationDensity` is not supported for a " * - "`$(nameof(typeof(system)))` in a fluid-structure interaction")) + "`$(nameof(typeof(system)))`")) end -check_boundary_density_fsi(system, neighbor_system) = system +check_boundary_model_density(system, boundary_model) = system # The correction values of a boundary particle are sums over its complete hydrodynamic # neighborhood in the current configuration, including the particles of its own structure @@ -185,7 +183,7 @@ function interact_structure_fluid!(dv, v_particle_system, u_particle_system, # particles corresponding to the chosen boundary model. # The following call is equivalent to # `p_a = current_pressure(v_particle_system, particle_system, particle)` - # For structures using `PressureMirroring`, this returns `p_a = p_b`, which is + # except for structures using `PressureMirroring`, where this returns `p_a = p_b`, which is # the pressure of the fluid particle, mirroring the fluid-structure interaction. p_b = current_pressure(v_neighbor_system, neighbor_system, neighbor) p_a = neighbor_pressure(v_particle_system, particle_system, particle, p_b) diff --git a/src/schemes/structure/total_lagrangian_sph/system.jl b/src/schemes/structure/total_lagrangian_sph/system.jl index c04d719980..f9ebcfc4ea 100644 --- a/src/schemes/structure/total_lagrangian_sph/system.jl +++ b/src/schemes/structure/total_lagrangian_sph/system.jl @@ -33,9 +33,10 @@ See [Total Lagrangian SPH](@ref tlsph) for more details on the method. See [`PrescribedMotion`](@ref) for details. - `boundary_model`: Boundary model to compute the hydrodynamic density and pressure for fluid-structure interaction (see [Boundary Models](@ref boundary_models)). - For [`BoundaryModelDummyParticles`](@ref), [`ContinuityDensity`](@ref) - is not supported and `correction` must be `nothing`, since corrections - at the boundary particles of structures are not supported yet. + For [`BoundaryModelDummyParticles`](@ref), [`SummationDensity`](@ref) + and [`ContinuityDensity`](@ref) are not supported and `correction` + must be `nothing`, since corrections at the boundary particles of + structures are not supported yet. - `penalty_force`: Penalty force to ensure regular particle position under large deformations (see [`PenaltyForceGanzenmueller`](@ref)). - `viscosity`: Artificial viscosity model to stabilize both the TLSPH and the FSI. @@ -508,8 +509,8 @@ function update_boundary_interpolation!(system::TotalLagrangianSPHSystem, v, u, v_ode, u_ode, semi, t) (; boundary_model) = system - # Only update boundary model. - # Not in `update_quantities!`, which the `SplitIntegrationCallback` also calls + # Only update the boundary model. This cannot be in `update_quantities!`, + # which the `SplitIntegrationCallback` also calls # without any fluid systems to interpolate the wall velocity from. @trixi_timeit timer() "interpolate wall velocity" begin interpolate_wall_velocity!(boundary_model, system, v, u, v_ode, u_ode, semi) @@ -857,6 +858,7 @@ function check_configuration(system::TotalLagrangianSPHSystem, systems, nhs) end end + check_boundary_model_density(system, boundary_model) check_boundary_model_correction(system, boundary_model) foreach_system(systems) do neighbor diff --git a/test/general/semidiscretization.jl b/test/general/semidiscretization.jl index 75531727e7..0c6fd45e8e 100644 --- a/test/general/semidiscretization.jl +++ b/test/general/semidiscretization.jl @@ -169,6 +169,7 @@ # Missing boundary model. structure = create_structure_system(structure_type, nothing) + @test_nowarn Semidiscretization(structure; neighborhood_search=nothing) error_str = "a boundary model for `$structure_type` must be specified " * "when simulating a fluid-structure interaction." @test_throws ArgumentError(error_str) Semidiscretization(fluid_system, @@ -196,18 +197,13 @@ state_equation) structure = create_structure_system(structure_type, boundary_model) error_str = "`BoundaryModelDummyParticles` with density calculator " * - "`SummationDensity` is not supported for a `$structure_type` " * - "in a fluid-structure interaction" - @test_nowarn TrixiParticles.check_configuration((structure,), nothing) + "`SummationDensity` is not supported for a `$structure_type`" + @test_throws ArgumentError(error_str) Semidiscretization(structure; + neighborhood_search=nothing) for systems in ((structure, fluid_system), (fluid_system, structure)) - # With both directions disabled, this is not a fluid-structure - # interaction, so the boundary density is never used. - @test_nowarn Semidiscretization(systems...; - neighborhood_search=nothing, - interaction_matrix=[true false; - false true]) - # Either direction uses the boundary density of the structure. - for interaction_matrix in ([true true; false true], + # The boundary model is unsupported even with FSI disabled. + for interaction_matrix in ([true false; false true], + [true true; false true], [true false; true true]) @test_throws ArgumentError(error_str) Semidiscretization(systems...; neighborhood_search=nothing, diff --git a/test/schemes/boundary/open_boundary/dynamical_pressure.jl b/test/schemes/boundary/open_boundary/dynamical_pressure.jl index db9612fa1a..1153067cae 100644 --- a/test/schemes/boundary/open_boundary/dynamical_pressure.jl +++ b/test/schemes/boundary/open_boundary/dynamical_pressure.jl @@ -169,7 +169,7 @@ @test TrixiParticles.v_nvariables(open_boundary_edac_2) == n_dims + 2 end - # The buffer particles are part of the fluid. Like all fluid particles, they see their + # The open boundary particles are part of the fluid. Like all fluid particles, they see their # own pressure at a wall with `PressureMirroring`, and not the (unused) pressure # stored in the wall. @testset verbose=true "Mirrored Wall Neighbor" begin diff --git a/test/systems/rigid_system.jl b/test/systems/rigid_system.jl index 80de2f31c1..8b46546af5 100644 --- a/test/systems/rigid_system.jl +++ b/test/systems/rigid_system.jl @@ -11,7 +11,7 @@ smoothing_kernel = SchoenbergCubicSplineKernel{2}() smoothing_length = 0.12 boundary_model = BoundaryModelDummyParticles(material_densities, mass, - SummationDensity(), + PressureZeroing(), smoothing_kernel, smoothing_length)