Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ 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).

### Features

- 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

- Fixed mathematical inconsistencies in the SPH documentation, including incorrect
Expand Down
1 change: 1 addition & 0 deletions src/callbacks/post_process.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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()

Expand Down
1 change: 1 addition & 0 deletions src/callbacks/solution_saving.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
11 changes: 10 additions & 1 deletion src/callbacks/sorting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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},
Expand Down Expand Up @@ -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
Expand Down
52 changes: 49 additions & 3 deletions src/callbacks/update.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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[]
Expand All @@ -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`
Expand Down Expand Up @@ -111,8 +150,8 @@ function (update_callback!::UpdateCallback)(integrator)
end

foreach_system(semi) do system
particle_shifting_from_callback!(u_ode, shifting_technique(system), system,
v_ode, semi, integrator)
update_density_diffusion_from_callback!(system, density_diffusion(system),
Comment thread
efaulhaber marked this conversation as resolved.
Resolved
v_ode, u_ode, semi, integrator)
end

# If TLSPH is not integrated, the averaged velocity will be updated in the
Expand All @@ -122,6 +161,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
Expand Down
11 changes: 11 additions & 0 deletions src/schemes/fluid/shifting_techniques.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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) = (;)

Expand Down Expand Up @@ -559,6 +560,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)

Expand Down
98 changes: 88 additions & 10 deletions src/schemes/fluid/weakly_compressible_sph/density_diffusion.jl
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,17 @@ 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, integrator)
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
Expand Down Expand Up @@ -88,7 +97,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
Expand All @@ -112,17 +121,36 @@ 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`, 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.
"""
struct DensityDiffusionAntuono{ELTYPE} <: AbstractDensityDiffusion
struct DensityDiffusionAntuono{ELTYPE, UPDATE_EVERYSTAGE} <: AbstractDensityDiffusion
delta::ELTYPE

function DensityDiffusionAntuono(; delta)
new{typeof(delta)}(delta)
function DensityDiffusionAntuono(; delta, update_everystage::Bool=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,
Expand All @@ -131,10 +159,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)
Expand All @@ -143,8 +169,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

Expand Down Expand Up @@ -173,7 +201,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

Expand Down Expand Up @@ -210,6 +250,44 @@ 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, integrator)
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

# 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

# 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!`.
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,
Expand Down
5 changes: 5 additions & 0 deletions src/schemes/fluid/weakly_compressible_sph/system.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
1 change: 1 addition & 0 deletions test/callbacks/postprocess.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
45 changes: 44 additions & 1 deletion test/callbacks/sorting.jl
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down
Loading
Loading