From 126682bc1fbfeb34940986612f44e4a8b9451f8f Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 24 Aug 2026 11:08:17 +0200 Subject: [PATCH 1/8] Add option to update `DensityDiffusionAntuono` between time steps --- NEWS.md | 5 ++ src/callbacks/update.jl | 5 ++ .../density_diffusion.jl | 60 +++++++++++++++++-- .../fluid/weakly_compressible_sph/system.jl | 5 ++ test/examples/examples_fluid.jl | 19 ++++++ .../density_diffusion.jl | 10 +++- 6 files changed, 97 insertions(+), 7 deletions(-) diff --git a/NEWS.md b/NEWS.md index 5e9256aecd..681f1db708 100644 --- a/NEWS.md +++ b/NEWS.md @@ -6,6 +6,11 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ## Version 0.5.4 +### Features + +- Added option to update `DensityDiffusionAntuono` between time steps instead of updating + in every stage of the time integration scheme (#1301). + ### Important Bugfixes - Fixed mathematical inconsistencies in the SPH documentation, including incorrect diff --git a/src/callbacks/update.jl b/src/callbacks/update.jl index 4b5346ad1f..14274099c4 100644 --- a/src/callbacks/update.jl +++ b/src/callbacks/update.jl @@ -115,6 +115,11 @@ function (update_callback!::UpdateCallback)(integrator) v_ode, semi, integrator) end + foreach_system(semi) do system + update_density_diffusion_from_callback!(system, density_diffusion(system), + v_ode, u_ode, semi) + end + # If TLSPH is not integrated, the averaged velocity will be updated in the # split integration. if semi.integrate_tlsph[] diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index e1dd0ce0d3..ae901fd140 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -15,8 +15,15 @@ See [Density Diffusion](@ref density_diffusion) for a comparison and more detail """ abstract type AbstractDensityDiffusion end +@inline requires_update_callback(::AbstractDensityDiffusion) = false + @inline density_diffusion(system) = nothing +function update_density_diffusion_from_callback!(system, density_diffusion, + v_ode, u_ode, semi) + return system +end + # Most density diffusion formulations don't need updating function update!(density_diffusion, v, u, system, semi) return density_diffusion @@ -88,7 +95,7 @@ end end @doc raw""" - DensityDiffusionAntuono(; delta) + DensityDiffusionAntuono(; delta, update_everystage=true) The commonly used density diffusion terms by [Antuono (2010)](@cite Antuono2010), also referred to as δ-SPH. The density diffusion term by [Molteni (2009)](@cite Molteni2009) is extended by a second @@ -112,17 +119,29 @@ L_a := \left( -\sum_{b} V_b r_{ab} \otimes \nabla W_{ab} \right)^{-1} \in \R^{d ``` where ``d`` is the number of dimensions. +# Keywords +- `delta`: Density diffusion coefficient. +- `update_everystage=true`: Update the renormalized density gradient in every stage. + If `false`, update it between time steps from an + [`UpdateCallback`](@ref), which is then required. + See [`AbstractDensityDiffusion`](@ref TrixiParticles.AbstractDensityDiffusion) for an overview and comparison of implemented density diffusion terms. """ -struct DensityDiffusionAntuono{ELTYPE} <: AbstractDensityDiffusion +struct DensityDiffusionAntuono{ELTYPE, UPDATE_EVERYSTAGE} <: AbstractDensityDiffusion delta::ELTYPE - function DensityDiffusionAntuono(; delta) - new{typeof(delta)}(delta) + function DensityDiffusionAntuono(; delta, update_everystage=true) + new{typeof(delta), update_everystage}(delta) end end +@inline function requires_update_callback(::DensityDiffusionAntuono{<:Any, false}) + return true +end + +@inline update_everystage(::DensityDiffusionAntuono{<:Any, UPDATE_EVERYSTAGE}) where {UPDATE_EVERYSTAGE} = UPDATE_EVERYSTAGE + create_cache_density_diffusion(initial_condition, density_diffusion) = (;) function create_cache_density_diffusion(initial_condition, @@ -143,8 +162,10 @@ end function Base.show(io::IO, density_diffusion::DensityDiffusionAntuono) @nospecialize density_diffusion # reduce precompilation time - print(io, "DensityDiffusionAntuono(") + print(io, "DensityDiffusionAntuono(delta=") print(io, density_diffusion.delta) + print(io, ", update_everystage=") + print(io, update_everystage(density_diffusion)) print(io, ")") end @@ -173,7 +194,19 @@ end return div_fast(result, distance^2) * pos_diff end -function update!(density_diffusion::DensityDiffusionAntuono, v, u, system, semi) +function update!(density_diffusion::DensityDiffusionAntuono{<:Any, true}, v, u, system, + semi) + return update_density_diffusion!(density_diffusion, v, u, system, semi) +end + +# With `update_everystage=false`, the regular stage update is disabled. +function update!(density_diffusion::DensityDiffusionAntuono{<:Any, false}, v, u, system, + semi) + return density_diffusion +end + +function update_density_diffusion!(density_diffusion::DensityDiffusionAntuono, v, u, + system, semi) density_diffusion_correction_matrix = system.cache.density_diffusion_correction_matrix normalized_density_gradient = system.cache.density_diffusion_normalized_density_gradient @@ -210,6 +243,21 @@ function update!(density_diffusion::DensityDiffusionAntuono, v, u, system, semi) return density_diffusion end +# Only the callback-updated variant is updated from the `UpdateCallback`. +function update_density_diffusion_from_callback!(system, + density_diffusion::DensityDiffusionAntuono{<:Any, + false}, + v_ode, u_ode, semi) + v = wrap_v(v_ode, system, semi) + u = wrap_u(u_ode, system, semi) + + @trixi_timeit timer() "update density diffusion" begin + update_density_diffusion!(density_diffusion, v, u, system, semi) + end + + return system +end + @propagate_inbounds function add_density_diffusion(drho_particle, density_diffusion::AbstractDensityDiffusion, particle_system::Union{AbstractFluidSystem, diff --git a/src/schemes/fluid/weakly_compressible_sph/system.jl b/src/schemes/fluid/weakly_compressible_sph/system.jl index eea0607d7d..a8f6569315 100644 --- a/src/schemes/fluid/weakly_compressible_sph/system.jl +++ b/src/schemes/fluid/weakly_compressible_sph/system.jl @@ -288,6 +288,11 @@ end @inline density_diffusion(system::WeaklyCompressibleSPHSystem) = system.density_diffusion +@inline function requires_update_callback(system::WeaklyCompressibleSPHSystem, semi) + return requires_update_callback(shifting_technique(system)) || + requires_update_callback(density_diffusion(system)) +end + function update_quantities!(system::WeaklyCompressibleSPHSystem, v, u, v_ode, u_ode, semi, t) (; density_calculator, density_diffusion, correction) = system diff --git a/test/examples/examples_fluid.jl b/test/examples/examples_fluid.jl index fe302529bf..97f50ea5ec 100644 --- a/test/examples/examples_fluid.jl +++ b/test/examples/examples_fluid.jl @@ -553,6 +553,25 @@ @test count_rhs_allocations(sol) == 0 end + @trixi_testset "fluid/vortex_street_2d.jl with callback-updated density diffusion" begin + density_diffusion = DensityDiffusionAntuono(; delta=0.1, + update_everystage=false) + @trixi_test_nowarn trixi_include(@__MODULE__, + joinpath(examples_dir(), "fluid", + "vortex_street_2d.jl"); + tspan=(0.0, 0.015), density_diffusion, + saving_callback=nothing) + @test sol.retcode == ReturnCode.Success + @test count_rhs_allocations(sol) == 0 + + # The final time t = 0.015 is right after activating inactive particles. + # The following test fails if the DD is not updated AFTER the open boundaries. + normalized_density_gradient = fluid_system.cache.density_diffusion_normalized_density_gradient + @test all(TrixiParticles.each_integrated_particle(fluid_system)) do particle + !iszero(sum(abs, @view(normalized_density_gradient[:, particle]))) + end + end + @trixi_testset "fluid/lid_driven_cavity_2d.jl (EDAC)" begin @trixi_test_nowarn trixi_include(@__MODULE__, joinpath(examples_dir(), "fluid", diff --git a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index 7dafc0377e..949afd377c 100644 --- a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -4,7 +4,15 @@ @trixi_testset "show" begin density_diffusion = DensityDiffusionAntuono(delta=0.1) - @test repr(density_diffusion) == "DensityDiffusionAntuono(0.1)" + @test repr(density_diffusion) == + "DensityDiffusionAntuono(delta=0.1, update_everystage=true)" + + callback_density_diffusion = DensityDiffusionAntuono(delta=0.1, + update_everystage=false) + @test repr(callback_density_diffusion) == + "DensityDiffusionAntuono(delta=0.1, update_everystage=false)" + @test !TrixiParticles.requires_update_callback(density_diffusion) + @test TrixiParticles.requires_update_callback(callback_density_diffusion) end end end From 2d1a22aafc2908277c8328196d0532404ab8a07d Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 24 Aug 2026 12:08:17 +0200 Subject: [PATCH 2/8] Fix --- src/callbacks/update.jl | 12 +++++++----- .../weakly_compressible_sph/density_diffusion.jl | 1 + 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/callbacks/update.jl b/src/callbacks/update.jl index 14274099c4..b5bf9ce6f7 100644 --- a/src/callbacks/update.jl +++ b/src/callbacks/update.jl @@ -110,11 +110,6 @@ function (update_callback!::UpdateCallback)(integrator) update_transport_velocity!(system, v_ode, semi, integrator) end - foreach_system(semi) do system - particle_shifting_from_callback!(u_ode, shifting_technique(system), system, - v_ode, semi, integrator) - end - foreach_system(semi) do system update_density_diffusion_from_callback!(system, density_diffusion(system), v_ode, u_ode, semi) @@ -127,6 +122,13 @@ function (update_callback!::UpdateCallback)(integrator) compute_averaged_velocity!(system, v_ode, semi, t) end end + + # Shifting must be the last step because it potentially updates the particle + # positions without updating the neighborhood search accordingly. + foreach_system(semi) do system + particle_shifting_from_callback!(u_ode, shifting_technique(system), system, + v_ode, semi, integrator) + end end return integrator diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index ae901fd140..8d81c07436 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -124,6 +124,7 @@ where ``d`` is the number of dimensions. - `update_everystage=true`: Update the renormalized density gradient in every stage. If `false`, update it between time steps from an [`UpdateCallback`](@ref), which is then required. + The cadence is controlled by the `UpdateCallback`. See [`AbstractDensityDiffusion`](@ref TrixiParticles.AbstractDensityDiffusion) for an overview and comparison of implemented density diffusion terms. From a178cd23856d78518f8939a212704284c07e529e Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 24 Aug 2026 12:11:40 +0200 Subject: [PATCH 3/8] Fix uninitialized memory --- .../fluid/weakly_compressible_sph/density_diffusion.jl | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index 8d81c07436..bb7d4385a1 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -151,10 +151,8 @@ function create_cache_density_diffusion(initial_condition, ELTYPE = eltype(initial_condition) n_particles = nparticles(initial_condition) - density_diffusion_correction_matrix = Array{ELTYPE, 3}(undef, NDIMS, NDIMS, - n_particles) - density_diffusion_normalized_density_gradient = Array{ELTYPE, 2}(undef, NDIMS, - n_particles) + density_diffusion_correction_matrix = zeros(ELTYPE, NDIMS, NDIMS, n_particles) + density_diffusion_normalized_density_gradient = zeros(ELTYPE, NDIMS, n_particles) return (; density_diffusion_correction_matrix, density_diffusion_normalized_density_gradient) From 56fec78cf4f007ee77ff315105c5239fcc259b02 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Mon, 24 Aug 2026 12:19:47 +0200 Subject: [PATCH 4/8] Implement suggestions --- src/callbacks/update.jl | 2 +- .../fluid/weakly_compressible_sph/density_diffusion.jl | 10 +++++++--- 2 files changed, 8 insertions(+), 4 deletions(-) diff --git a/src/callbacks/update.jl b/src/callbacks/update.jl index b5bf9ce6f7..b009ccf98f 100644 --- a/src/callbacks/update.jl +++ b/src/callbacks/update.jl @@ -112,7 +112,7 @@ function (update_callback!::UpdateCallback)(integrator) foreach_system(semi) do system update_density_diffusion_from_callback!(system, density_diffusion(system), - v_ode, u_ode, semi) + v_ode, u_ode, semi, integrator) end # If TLSPH is not integrated, the averaged velocity will be updated in the diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index bb7d4385a1..b4cda10143 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -20,7 +20,7 @@ abstract type AbstractDensityDiffusion end @inline density_diffusion(system) = nothing function update_density_diffusion_from_callback!(system, density_diffusion, - v_ode, u_ode, semi) + v_ode, u_ode, semi, integrator) return system end @@ -132,7 +132,7 @@ for an overview and comparison of implemented density diffusion terms. struct DensityDiffusionAntuono{ELTYPE, UPDATE_EVERYSTAGE} <: AbstractDensityDiffusion delta::ELTYPE - function DensityDiffusionAntuono(; delta, update_everystage=true) + function DensityDiffusionAntuono(; delta, update_everystage::Bool=true) new{typeof(delta), update_everystage}(delta) end end @@ -246,7 +246,7 @@ end function update_density_diffusion_from_callback!(system, density_diffusion::DensityDiffusionAntuono{<:Any, false}, - v_ode, u_ode, semi) + v_ode, u_ode, semi, integrator) v = wrap_v(v_ode, system, semi) u = wrap_u(u_ode, system, semi) @@ -254,6 +254,10 @@ function update_density_diffusion_from_callback!(system, update_density_diffusion!(density_diffusion, v, u, system, semi) end + # Updating the density diffusion changes data used by the RHS, which means that + # cached derivatives need to be recomputed. + derivative_discontinuity!(integrator, true) + return system end From 237aae430fb921b45fb7f583bd7dd0e35d8cf9b9 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Fri, 20 Nov 2026 13:59:23 +0100 Subject: [PATCH 5/8] Fix sorting with frozen DD and shifting --- src/callbacks/sorting.jl | 11 ++++- src/schemes/fluid/shifting_techniques.jl | 10 +++++ .../density_diffusion.jl | 10 +++++ test/callbacks/sorting.jl | 45 ++++++++++++++++++- 4 files changed, 74 insertions(+), 2 deletions(-) diff --git a/src/callbacks/sorting.jl b/src/callbacks/sorting.jl index 14bdc7f698..63f39ff1ec 100644 --- a/src/callbacks/sorting.jl +++ b/src/callbacks/sorting.jl @@ -125,7 +125,7 @@ function sort_particles!(system::RequiresSortingSystem, v, u, nhs, semi) throw(ArgumentError("`SortingCallback` can only be used with a `GridNeighborhoodSearch`")) end -# TODO: Sort also masses and particle spacings for variable smoothing lengths. +# TODO: Sort also particle spacings for variable smoothing lengths. function sort_particles!(system::RequiresSortingSystem, v, u, nhs::GridNeighborhoodSearch, semi) cell_coords = allocate(semi.parallelization_backend, SVector{ndims(system), Int}, @@ -153,10 +153,19 @@ function sort_system!(system, v, u, perm, buffer::Nothing) system_velocity .= system_velocity[:, perm] system_pressure .= system_pressure[perm] system_density .= system_density[perm] + system.mass .= system.mass[perm] + + # Permute cached per-particle quantities that are only updated in the `UpdateCallback` + # and are therefore not recomputed before the next evaluation of the RHS. + sort_cache!(system, density_diffusion(system), perm) + sort_cache!(system, shifting_technique(system), perm) return system end +# Most cached quantities are recomputed in every stage and don't need to be permuted. +sort_cache!(system, feature, perm) = system + function initial_sort(::DiscreteCallback{<:Any, <:SortingCallback, typeof(initial_sort!)}) return true end diff --git a/src/schemes/fluid/shifting_techniques.jl b/src/schemes/fluid/shifting_techniques.jl index c746412f89..5116bb752b 100644 --- a/src/schemes/fluid/shifting_techniques.jl +++ b/src/schemes/fluid/shifting_techniques.jl @@ -559,6 +559,16 @@ function apply_particle_shifting!(u_ode, ::ParticleShiftingTechnique{true}, return u_ode end +# `ParticleShiftingTechnique{<:Any, false}` means `update_everystage=false`. +# The shifting velocity is kept between updates from the `UpdateCallback`, +# so it has to be permuted when sorting particles. +function sort_cache!(system, ::ParticleShiftingTechnique{<:Any, false}, perm) + (; delta_v) = system.cache + delta_v .= delta_v[:, perm] + + return system +end + """ TransportVelocityAdami(; background_pressure::Real, modify_continuity_equation=false) diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index b4cda10143..b5c9255d5e 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -261,6 +261,16 @@ function update_density_diffusion_from_callback!(system, return system end +# With `update_everystage=false`, the normalized density gradient is kept between +# updates from the `UpdateCallback`, so it has to be permuted when sorting particles. +# The correction matrix is only used within `update_density_diffusion!`. +function sort_cache!(system, ::DensityDiffusionAntuono{<:Any, false}, perm) + gradient = system.cache.density_diffusion_normalized_density_gradient + gradient .= gradient[:, perm] + + return system +end + @propagate_inbounds function add_density_diffusion(drho_particle, density_diffusion::AbstractDensityDiffusion, particle_system::Union{AbstractFluidSystem, diff --git a/test/callbacks/sorting.jl b/test/callbacks/sorting.jl index 7e47a05a04..347de6ce81 100644 --- a/test/callbacks/sorting.jl +++ b/test/callbacks/sorting.jl @@ -101,7 +101,8 @@ velocity = [13.0 11.0 14.0 12.0 23.0 21.0 24.0 22.0] density = [103.0, 101.0, 104.0, 102.0] - mass = ones(4) + # Non-uniform masses, as they result from e.g. a hydrostatic initial density. + mass = [1.3, 1.1, 1.4, 1.2] state_equation = Val(:state_equation) smoothing_kernel = SchoenbergCubicSplineKernel{2}() smoothing_length = 0.1 @@ -124,6 +125,48 @@ @test v == velocity[:, perm] @test system.cache.density == density[perm] @test system.pressure == [203.0, 201.0, 204.0, 202.0][perm] + @test system.mass == mass[perm] + end + + @testset verbose=true "`sort_system!` permutes caches only updated by the `UpdateCallback`" begin + coordinates = [3.0 1.0 4.0 2.0 + 30.0 10.0 40.0 20.0] + velocity = zeros(2, 4) + density = [103.0, 101.0, 104.0, 102.0] + mass = ones(4) + state_equation = Val(:state_equation) + smoothing_kernel = SchoenbergCubicSplineKernel{2}() + smoothing_length = 0.1 + + # Both features are only updated by the `UpdateCallback` with + # `update_everystage=false`, so their caches are kept between time steps. + density_diffusion = DensityDiffusionAntuono(delta=0.1, update_everystage=false) + shifting_technique = ParticleShiftingTechnique(update_everystage=false) + + initial_condition = InitialCondition(; coordinates, velocity, mass, density) + system = WeaklyCompressibleSPHSystem(initial_condition; + smoothing_kernel, smoothing_length, + density_calculator=ContinuityDensity(), + state_equation, density_diffusion, + shifting_technique) + + # With `ContinuityDensity`, the density is stored in the last row of `v`. + v = vcat(velocity, density') + u = copy(coordinates) + + # Fill the caches with values that identify the particle they belong to. + gradient = [1.0 2.0 3.0 4.0 + 5.0 6.0 7.0 8.0] + delta_v = 10 * gradient + system.cache.density_diffusion_normalized_density_gradient .= gradient + system.cache.delta_v .= delta_v + + perm = [2, 4, 1, 3] + TrixiParticles.sort_system!(system, v, u, perm, nothing) + + @test system.cache.density_diffusion_normalized_density_gradient == + gradient[:, perm] + @test system.cache.delta_v == delta_v[:, perm] end @testset "Illegal Input" begin From 6c3c321e6df1502b3295c3c970f80177bdb750f3 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:55:04 +0100 Subject: [PATCH 6/8] Add more tests --- test/examples/examples_fluid.jl | 60 ++++++++-- .../density_diffusion.jl | 112 ++++++++++++++++++ 2 files changed, 162 insertions(+), 10 deletions(-) diff --git a/test/examples/examples_fluid.jl b/test/examples/examples_fluid.jl index 97f50ea5ec..e30c764c07 100644 --- a/test/examples/examples_fluid.jl +++ b/test/examples/examples_fluid.jl @@ -556,20 +556,60 @@ @trixi_testset "fluid/vortex_street_2d.jl with callback-updated density diffusion" begin density_diffusion = DensityDiffusionAntuono(; delta=0.1, update_everystage=false) + + # Record which fluid particles are active right before the `UpdateCallback`, + # which activates particles in the open boundary before updating the DD. + # The fluid system is the first system in the semidiscretization. + active_before_update = Bool[] + function record_active_particles!(integrator) + fluid_system_ = integrator.p.semi.systems[1] + copy!(active_before_update, fluid_system_.buffer.active_particle) + + # This callback doesn't modify the ODE state. + TrixiParticles.derivative_discontinuity!(integrator, false) + + return integrator + end + record_callback = TrixiParticles.DiscreteCallback((u, t, integrator) -> true, + record_active_particles!, + save_positions=(false, false)) + @trixi_test_nowarn trixi_include(@__MODULE__, joinpath(examples_dir(), "fluid", "vortex_street_2d.jl"); tspan=(0.0, 0.015), density_diffusion, - saving_callback=nothing) - @test sol.retcode == ReturnCode.Success - @test count_rhs_allocations(sol) == 0 - - # The final time t = 0.015 is right after activating inactive particles. - # The following test fails if the DD is not updated AFTER the open boundaries. - normalized_density_gradient = fluid_system.cache.density_diffusion_normalized_density_gradient - @test all(TrixiParticles.each_integrated_particle(fluid_system)) do particle - !iszero(sum(abs, @view(normalized_density_gradient[:, particle]))) - end + callbacks=CallbackSet(record_callback, + UpdateCallback())) + @test sol.retcode == ReturnCode.Success + @test count_rhs_allocations(sol) == 0 + + # Particles that were activated in the last `UpdateCallback`. + # This must not be empty, or the following test is meaningless. + active_particle = fluid_system.buffer.active_particle + newly_activated = findall(active_particle .& .!active_before_update) + @test !isempty(newly_activated) + + # The DD must have been updated after activating these particles, so the cache + # must match a recomputation from the final state. + # Note that `update_density_diffusion!` itself is tested in the unit tests. + cached_gradient = copy(fluid_system.cache.density_diffusion_normalized_density_gradient) + + v_ode, u_ode = copy.(sol.u[end].x) + v = TrixiParticles.wrap_v(v_ode, fluid_system, semi) + u = TrixiParticles.wrap_u(u_ode, fluid_system, semi) + TrixiParticles.update_systems_and_nhs(v_ode, u_ode, semi, sol.t[end]) + TrixiParticles.update_density_diffusion!(density_diffusion, v, u, fluid_system, + semi) + recomputed_gradient = fluid_system.cache.density_diffusion_normalized_density_gradient + + @test all(isfinite, cached_gradient[:, newly_activated]) + @test isapprox(cached_gradient[:, newly_activated], + recomputed_gradient[:, newly_activated], rtol=1e-12) + + # The same must hold for all other active particles. + active = collect(TrixiParticles.each_integrated_particle(fluid_system)) + @test isapprox(cached_gradient[:, active], recomputed_gradient[:, active], + rtol=1e-12) end @trixi_testset "fluid/lid_driven_cavity_2d.jl (EDAC)" begin diff --git a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index 949afd377c..465ab4268b 100644 --- a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -14,5 +14,117 @@ @test !TrixiParticles.requires_update_callback(density_diffusion) @test TrixiParticles.requires_update_callback(callback_density_diffusion) end + + @trixi_testset "Update from `UpdateCallback` with `update_everystage=false`" begin + using OrdinaryDiffEqLowStorageRK: CarpenterKennedy2N54 + + # Independent reference implementation of the renormalized density gradient + # as defined in the docstring of `DensityDiffusionAntuono`. + # It loops over all pairs of particles instead of using the NHS. + function reference_density_gradient(system, v, u) + NDIMS = ndims(system) + result = zeros(NDIMS, TrixiParticles.nparticles(system)) + + for particle in TrixiParticles.eachparticle(system) + rho_a = TrixiParticles.current_density(v, system, particle) + x_a = TrixiParticles.current_coords(u, system, particle) + + L = zeros(NDIMS, NDIMS) + gradient_a = zeros(NDIMS) + for neighbor in TrixiParticles.eachparticle(system) + pos_diff = x_a - + TrixiParticles.current_coords(u, system, neighbor) + distance = norm(pos_diff) + + if neighbor == particle || + distance > TrixiParticles.compact_support(system, system) + continue + end + + rho_b = TrixiParticles.current_density(v, system, neighbor) + volume_b = system.mass[neighbor] / rho_b + grad_kernel = TrixiParticles.smoothing_kernel_grad(system, + pos_diff, + distance, + particle) + + L -= volume_b * grad_kernel * pos_diff' + gradient_a -= (rho_a - rho_b) * volume_b * grad_kernel + end + + result[:, particle] = inv(L) * gradient_a + end + + return result + end + + # 6x6 particles with a non-uniform density and mass. + # The compressive velocity field makes the density change in every step, + # and the particles move, so the gradient changes in every step as well. + particle_spacing = 0.1 + center = SVector(0.3, 0.3) + coordinates = RectangularShape(particle_spacing, (6, 6), (0.0, 0.0), + density=1000.0).coordinates + velocity = -0.5 * (coordinates .- center) + density = 1000 .+ 10 * sin.(5 * coordinates[1, :]) .+ + 5 * cos.(7 * coordinates[2, :]) + initial_condition = InitialCondition(; coordinates, velocity, density, + particle_spacing) + + density_diffusion = DensityDiffusionAntuono(delta=0.1, + update_everystage=false) + state_equation = StateEquationCole(sound_speed=10.0, + reference_density=1000.0, exponent=7) + system = WeaklyCompressibleSPHSystem(initial_condition; + smoothing_kernel=WendlandC2Kernel{2}(), + smoothing_length=1.2 * particle_spacing, + density_calculator=ContinuityDensity(), + state_equation, density_diffusion) + semi = Semidiscretization(system) + ode = semidiscretize(semi, (0.0, 1.0)) + + # Refresh the cache at initialization and after every second time step. + # The time step is well below the CFL limit. + # Note that a staggered scheme like `SymplecticEuler` cannot be used here, + # since its initialization modifies `v` after the callbacks are initialized. + integrator = init(ode, CarpenterKennedy2N54(williamson_condition=false), + dt=1e-4, adaptive=false, + save_everystep=false, + callback=UpdateCallback(interval=2)) + + semi = integrator.p.semi + system = semi.systems[1] + cached_gradient = system.cache.density_diffusion_normalized_density_gradient + + function current_reference(integrator) + v_ode, u_ode = integrator.u.x + v = TrixiParticles.wrap_v(v_ode, system, semi) + u = TrixiParticles.wrap_u(u_ode, system, semi) + + return reference_density_gradient(system, v, u) + end + + # `initial_update!` computes the gradient from the initial state. + # Since the density is non-uniform, a correct gradient is non-zero. + @test all(isfinite, cached_gradient) + @test !iszero(cached_gradient) + @test isapprox(cached_gradient, current_reference(integrator), rtol=1e-12) + cached_gradient_initial = copy(cached_gradient) + + # After one step, the `UpdateCallback` is not triggered + # (number of accepted steps 1 % 2 != 0), so the cache must not be changed, + # although a refresh would now yield a different gradient. + step!(integrator) + @test integrator.stats.naccept == 1 + @test cached_gradient == cached_gradient_initial + @test !isapprox(cached_gradient, current_reference(integrator), rtol=1e-6) + + # After the second step, the scheduled refresh must yield the gradient + # of the current state. + step!(integrator) + @test integrator.stats.naccept == 2 + @test cached_gradient != cached_gradient_initial + @test isapprox(cached_gradient, current_reference(integrator), rtol=1e-12) + end end end From 4234634e153a13deaa4dab2617e09083c9a99ec0 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:34:24 +0100 Subject: [PATCH 7/8] Fix callback order issues --- src/callbacks/post_process.jl | 1 + src/callbacks/solution_saving.jl | 1 + src/callbacks/update.jl | 41 ++++- src/schemes/fluid/shifting_techniques.jl | 1 + .../density_diffusion.jl | 23 ++- test/callbacks/postprocess.jl | 1 + .../density_diffusion.jl | 169 ++++++++++++------ 7 files changed, 177 insertions(+), 60 deletions(-) diff --git a/src/callbacks/post_process.jl b/src/callbacks/post_process.jl index 6e4aafab09..014062e9ae 100644 --- a/src/callbacks/post_process.jl +++ b/src/callbacks/post_process.jl @@ -124,6 +124,7 @@ end function initialize_postprocess_callback!(cb::PostprocessCallback, u, t, integrator) semi = integrator.p.semi set_callbacks_used!(semi, integrator) + initialize_update_callback_caches!(semi, integrator) cb.git_hash[] = compute_git_hash() diff --git a/src/callbacks/solution_saving.jl b/src/callbacks/solution_saving.jl index 95150bca01..fc9357fd2f 100644 --- a/src/callbacks/solution_saving.jl +++ b/src/callbacks/solution_saving.jl @@ -161,6 +161,7 @@ function initialize_save_cb!(solution_callback::SolutionSavingCallback, u, t, in save_initial_solution) semi = integrator.p.semi set_callbacks_used!(semi, integrator) + initialize_update_callback_caches!(semi, integrator) # Reset collection state solution_callback.collection_initialized = false diff --git a/src/callbacks/update.jl b/src/callbacks/update.jl index b009ccf98f..6e9980a778 100644 --- a/src/callbacks/update.jl +++ b/src/callbacks/update.jl @@ -59,6 +59,22 @@ function initial_update!(cb::UpdateCallback, vu_ode, t, integrator) # Tell the semidiscretization that the `UpdateCallback` is used semi.update_callback_used[] = true + initialize_update_callback_caches!(v_ode, u_ode, semi, t) + + return cb(integrator) +end + +# Initialize the caches that are otherwise only updated by the `UpdateCallback` +# from the current state without modifying the ODE state. +# Callbacks like the `SolutionSavingCallback` and `PostprocessCallback` evaluate the RHS +# at initialization, which requires these caches to be initialized. +# However, if one of these callbacks appears BEFORE the `UpdateCallback` +# in the `CallbackSet`, then the `UpdateCallback` has not been initialized yet. +# Therefore, these callbacks call this function as well. +function initialize_update_callback_caches!(v_ode, u_ode, semi, t) + # Update quantities and neighborhood search for the current state. + update_systems_and_nhs(v_ode, u_ode, semi, t) + # If TLSPH is not integrated, the averaged velocity will be initialized in the # split integration. if semi.integrate_tlsph[] @@ -67,7 +83,30 @@ function initial_update!(cb::UpdateCallback, vu_ode, t, integrator) end end - return cb(integrator) + foreach_system(semi) do system + v = wrap_v(v_ode, system, semi) + u = wrap_u(u_ode, system, semi) + + initialize_density_diffusion_from_callback!(system, density_diffusion(system), + v, u, semi) + end + + # Only update the shifting velocity, but don't apply shifting to the particles. + foreach_system(semi) do system + update_shifting_from_callback!(system, shifting_technique(system), + v_ode, u_ode, semi) + end + + return semi +end + +# Initialize the caches when another callback evaluates the RHS at initialization. +# This is a no-op when no `UpdateCallback` is used. +function initialize_update_callback_caches!(semi, integrator) + semi.update_callback_used[] || return semi + + v_ode, u_ode = integrator.u.x + return initialize_update_callback_caches!(v_ode, u_ode, semi, integrator.t) end # `condition` diff --git a/src/schemes/fluid/shifting_techniques.jl b/src/schemes/fluid/shifting_techniques.jl index 5116bb752b..3aa314ec15 100644 --- a/src/schemes/fluid/shifting_techniques.jl +++ b/src/schemes/fluid/shifting_techniques.jl @@ -13,6 +13,7 @@ requires_update_callback(::AbstractShiftingTechnique) = false # This is called from the `UpdateCallback` particle_shifting_from_callback!(u_ode, shifting, system, v_ode, semi, integrator) = u_ode +update_shifting_from_callback!(system, shifting, v_ode, u_ode, semi) = system create_cache_shifting(initial_condition, ::Nothing) = (;) diff --git a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index b5c9255d5e..0e5104c849 100644 --- a/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -24,6 +24,8 @@ function update_density_diffusion_from_callback!(system, density_diffusion, return system end +initialize_density_diffusion_from_callback!(system, density_diffusion, v, u, semi) = system + # Most density diffusion formulations don't need updating function update!(density_diffusion, v, u, system, semi) return density_diffusion @@ -122,9 +124,15 @@ where ``d`` is the number of dimensions. # Keywords - `delta`: Density diffusion coefficient. - `update_everystage=true`: Update the renormalized density gradient in every stage. - If `false`, update it between time steps from an - [`UpdateCallback`](@ref), which is then required. - The cadence is controlled by the `UpdateCallback`. + If `false`, the gradient is computed at initialization and + whenever the [`UpdateCallback`](@ref) runs (by default after + every time step), and it is frozen in between. + The `UpdateCallback` is then required. + The diffusion term still uses the current densities and + positions in every stage. + This avoids recomputing the gradient in every stage, + but it reduces the order of the time integration scheme, + so a slightly smaller time step might be necessary. See [`AbstractDensityDiffusion`](@ref TrixiParticles.AbstractDensityDiffusion) for an overview and comparison of implemented density diffusion terms. @@ -261,6 +269,15 @@ function update_density_diffusion_from_callback!(system, return system end +# Initialize the callback-updated variant before the first evaluation of the RHS. +# See `initialize_update_callback_caches!`. +function initialize_density_diffusion_from_callback!(system, + density_diffusion::DensityDiffusionAntuono{<:Any, + false}, + v, u, semi) + return update_density_diffusion!(density_diffusion, v, u, system, semi) +end + # With `update_everystage=false`, the normalized density gradient is kept between # updates from the `UpdateCallback`, so it has to be permuted when sorting particles. # The correction matrix is only used within `update_density_diffusion!`. diff --git a/test/callbacks/postprocess.jl b/test/callbacks/postprocess.jl index f8b38ed3ae..0b26864039 100644 --- a/test/callbacks/postprocess.jl +++ b/test/callbacks/postprocess.jl @@ -33,6 +33,7 @@ end TrixiParticles.set_callbacks_used!(semi::Nothing, integrator) = nothing + TrixiParticles.initialize_update_callback_caches!(semi::Nothing, integrator) = nothing TrixiParticles.initialize_postprocess_callback!(postprocess_callback, nothing, 0.0, integrator) diff --git a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl index 465ab4268b..2cd6d7a4f4 100644 --- a/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl +++ b/test/schemes/fluid/weakly_compressible_sph/density_diffusion.jl @@ -61,70 +61,127 @@ # 6x6 particles with a non-uniform density and mass. # The compressive velocity field makes the density change in every step, # and the particles move, so the gradient changes in every step as well. - particle_spacing = 0.1 - center = SVector(0.3, 0.3) - coordinates = RectangularShape(particle_spacing, (6, 6), (0.0, 0.0), - density=1000.0).coordinates - velocity = -0.5 * (coordinates .- center) - density = 1000 .+ 10 * sin.(5 * coordinates[1, :]) .+ - 5 * cos.(7 * coordinates[2, :]) - initial_condition = InitialCondition(; coordinates, velocity, density, - particle_spacing) - - density_diffusion = DensityDiffusionAntuono(delta=0.1, - update_everystage=false) - state_equation = StateEquationCole(sound_speed=10.0, - reference_density=1000.0, exponent=7) - system = WeaklyCompressibleSPHSystem(initial_condition; - smoothing_kernel=WendlandC2Kernel{2}(), - smoothing_length=1.2 * particle_spacing, - density_calculator=ContinuityDensity(), - state_equation, density_diffusion) - semi = Semidiscretization(system) - ode = semidiscretize(semi, (0.0, 1.0)) - - # Refresh the cache at initialization and after every second time step. + function semidiscretize_patch(; shifting_technique=nothing) + particle_spacing = 0.1 + center = SVector(0.3, 0.3) + coordinates = RectangularShape(particle_spacing, (6, 6), (0.0, 0.0), + density=1000.0).coordinates + velocity = -0.5 * (coordinates .- center) + density = 1000 .+ 10 * sin.(5 * coordinates[1, :]) .+ + 5 * cos.(7 * coordinates[2, :]) + initial_condition = InitialCondition(; coordinates, velocity, density, + particle_spacing) + + density_diffusion = DensityDiffusionAntuono(delta=0.1, + update_everystage=false) + state_equation = StateEquationCole(sound_speed=10.0, + reference_density=1000.0, exponent=7) + system = WeaklyCompressibleSPHSystem(initial_condition; + smoothing_kernel=WendlandC2Kernel{2}(), + smoothing_length=1.2 * + particle_spacing, + density_calculator=ContinuityDensity(), + state_equation, density_diffusion, + shifting_technique) + semi = Semidiscretization(system) + + return semidiscretize(semi, (0.0, 1.0)) + end + # The time step is well below the CFL limit. # Note that a staggered scheme like `SymplecticEuler` cannot be used here, # since its initialization modifies `v` after the callbacks are initialized. - integrator = init(ode, CarpenterKennedy2N54(williamson_condition=false), - dt=1e-4, adaptive=false, - save_everystep=false, - callback=UpdateCallback(interval=2)) + function init_integrator(ode, callback) + return init(ode, CarpenterKennedy2N54(williamson_condition=false), + dt=1e-4, adaptive=false, save_everystep=false, callback=callback) + end - semi = integrator.p.semi - system = semi.systems[1] - cached_gradient = system.cache.density_diffusion_normalized_density_gradient + @testset verbose=true "Refresh only when the `UpdateCallback` is triggered" begin + # Refresh the cache at initialization and after every second time step. + integrator = init_integrator(semidiscretize_patch(), + UpdateCallback(interval=2)) - function current_reference(integrator) - v_ode, u_ode = integrator.u.x - v = TrixiParticles.wrap_v(v_ode, system, semi) - u = TrixiParticles.wrap_u(u_ode, system, semi) + semi = integrator.p.semi + system = semi.systems[1] + cached_gradient = system.cache.density_diffusion_normalized_density_gradient + + function current_reference(integrator) + v_ode, u_ode = integrator.u.x + v = TrixiParticles.wrap_v(v_ode, system, semi) + u = TrixiParticles.wrap_u(u_ode, system, semi) - return reference_density_gradient(system, v, u) + return reference_density_gradient(system, v, u) + end + + # `initial_update!` computes the gradient from the initial state. + # Since the density is non-uniform, a correct gradient is non-zero. + @test all(isfinite, cached_gradient) + @test !iszero(cached_gradient) + @test isapprox(cached_gradient, current_reference(integrator), + rtol=1e-12) + cached_gradient_initial = copy(cached_gradient) + + # After one step, the `UpdateCallback` is not triggered + # (number of accepted steps 1 % 2 != 0), so the cache must not be + # changed, although a refresh would now yield a different gradient. + step!(integrator) + @test integrator.stats.naccept == 1 + @test cached_gradient == cached_gradient_initial + @test !isapprox(cached_gradient, current_reference(integrator), + rtol=1e-6) + + # After the second step, the scheduled refresh must yield the gradient + # of the current state. + step!(integrator) + @test integrator.stats.naccept == 2 + @test cached_gradient != cached_gradient_initial + @test isapprox(cached_gradient, current_reference(integrator), + rtol=1e-12) end - # `initial_update!` computes the gradient from the initial state. - # Since the density is non-uniform, a correct gradient is non-zero. - @test all(isfinite, cached_gradient) - @test !iszero(cached_gradient) - @test isapprox(cached_gradient, current_reference(integrator), rtol=1e-12) - cached_gradient_initial = copy(cached_gradient) - - # After one step, the `UpdateCallback` is not triggered - # (number of accepted steps 1 % 2 != 0), so the cache must not be changed, - # although a refresh would now yield a different gradient. - step!(integrator) - @test integrator.stats.naccept == 1 - @test cached_gradient == cached_gradient_initial - @test !isapprox(cached_gradient, current_reference(integrator), rtol=1e-6) - - # After the second step, the scheduled refresh must yield the gradient - # of the current state. - step!(integrator) - @test integrator.stats.naccept == 2 - @test cached_gradient != cached_gradient_initial - @test isapprox(cached_gradient, current_reference(integrator), rtol=1e-12) + @testset verbose=true "Callback evaluating the RHS before the `UpdateCallback`" begin + # The `PostprocessCallback` evaluates the RHS at initialization. + # When it comes before the `UpdateCallback` in the `CallbackSet`, + # the `UpdateCallback` has not been initialized yet, but the RHS must + # already use the initialized caches. + # This also covers the shifting velocity of PST with + # `update_everystage=false`, which is used in the RHS when it is + # integrated (`integrate_shifting_velocity=true`). + shifting_technique = ParticleShiftingTechnique(update_everystage=false) + ode = semidiscretize_patch(; shifting_technique) + + # Record the RHS that the `PostprocessCallback` sees. + recorded_dv = [] + function record_dv(system, dv_ode, du_ode, v_ode, u_ode, semi, t) + push!(recorded_dv, copy(TrixiParticles.wrap_v(dv_ode, system, semi))) + + # Don't store any values in the `PostprocessCallback`. + return nothing + end + postprocess_callback = PostprocessCallback(; interval=1000, + write_csv=false, + write_json=false, record_dv) + + integrator = init_integrator(ode, + CallbackSet(postprocess_callback, + UpdateCallback())) + semi = integrator.p.semi + system = semi.systems[1] + + # Make sure that both caches are non-trivial, so that the test is + # meaningful. + @test !iszero(system.cache.density_diffusion_normalized_density_gradient) + @test !iszero(system.cache.delta_v) + + # The RHS after all callbacks have been initialized. + v_ode, u_ode = integrator.u.x + dv_ode = similar(v_ode) + TrixiParticles.kick!(dv_ode, v_ode, u_ode, integrator.p, integrator.t) + + @test length(recorded_dv) == 1 + @test isapprox(only(recorded_dv), + TrixiParticles.wrap_v(dv_ode, system, semi), rtol=1e-12) + end end end end From b8e9382e82792807376c9442bae4308db30f6fb0 Mon Sep 17 00:00:00 2001 From: Erik Faulhaber <44124897+efaulhaber@users.noreply.github.com> Date: Wed, 25 Nov 2026 10:41:34 +0100 Subject: [PATCH 8/8] Improve NEWS.md entry --- NEWS.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/NEWS.md b/NEWS.md index 79fcdfbdfe..de1220ce16 100644 --- a/NEWS.md +++ b/NEWS.md @@ -14,8 +14,9 @@ used in the Julia ecosystem. Notable changes will be documented in this file for ### Features -- Added option to update `DensityDiffusionAntuono` between time steps instead of updating - in every stage of the time integration scheme (#1301). +- Added `update_everystage=false` to `DensityDiffusionAntuono`, which freezes the + renormalized density gradient between refreshes by the `UpdateCallback` instead of + recomputing it in every stage of the time integration scheme (#1301). ### Important Bugfixes