Skip to content
Draft
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
60 changes: 45 additions & 15 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,27 +4,57 @@ TrixiParticles.jl follows the interpretation of
[semantic versioning (semver)](https://julialang.github.io/Pkg.jl/dev/compatibility/#Version-specifier-format-1)
used in the Julia ecosystem. Notable changes will be documented in this file for human readability.

## Version 0.5.4

### API Changes

- Replaced the experimental `MechanicalWorkCalculatorCallback` with
`MechanicalWorkCalculator`, which can be passed as a custom quantity to
`PostprocessCallback` (#1228).
## Version 0.6.0

### API Changes

- Renamed the fluid-system keyword `surface_normal_method` to `surface_method` and added
detection-only surface methods. The old constructor keyword and accessor are deprecated.
- The fluid `color_value` phase identifier is now always recorded in `meta.json` and written
as `color` field data in VTK output, also for fluids without a surface method.

### Important Bugfixes

- Fixed Morris surface-tension curvature to accumulate the SPH sum over all interacting
systems before normalizing, making the result independent of system ordering and of
same-phase partitioning into multiple systems.
- Fixed spurious curvature for `SurfaceTensionMorris` at planar multicolor interfaces by
restricting the curvature divergence stencil to same-phase neighbors with consistently
normalized normals, which also makes mixing Morris and Akinci systems well-defined.
- Fixed interpolated `surface_activity` to apply the same minimum-support and
`ideal_density_threshold` rejection criteria as particle-based surface detection.
- Fixed fluid VTK output with system buffers: `surface_activity`, `neighbor_count`,
`curvature`, `surface_tension` and `surface_stress_tensor` now hold exactly one value
per active particle.
- Fixed the `dam_break_oil_film_2d.jl` example to assign distinct phase colors to water
and oil, so their interface is actually detected.

## Version 0.5.4

### API Changes

- Replaced the experimental `MechanicalWorkCalculatorCallback` with
`MechanicalWorkCalculator`, which can be passed as a custom quantity to
`PostprocessCallback` (#1228).

### Important Bugfixes

- Fixed mathematical inconsistencies in the SPH documentation, including incorrect
formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode
commands (#1086).
- Fixed restarting with EDAC from solution objects (#1213) and from VTK files (#1297).
- Fixed the custom quantities `kinetic_energy`, `total_mass`, `max_pressure`, `min_pressure`,
`avg_pressure`, `max_density`, `min_density` and `avg_density` to only take active particles
into account (#1184).
- Hardened surface tension model configuration by validating coefficients and surface-normal
thresholds, avoiding unnecessary normal allocation for `CohesionForceAkinci`, and stabilizing
Akinci cohesion and adhesion kernels across floating-point scales.
- Added color-weighted fluid-fluid interface normals and consistently applied surface-normal
validity thresholds to standalone, Akinci, and Morris calculations.
- Fixed mathematical inconsistencies in the SPH documentation, including incorrect
formulas, inconsistent force-vs-acceleration notation, and wrong LaTeX text-mode
commands (#1086).
- Fixed restarting with EDAC from solution objects (#1213) and from VTK files (#1297).
- Fixed the custom quantities `kinetic_energy`, `total_mass`, `max_pressure`, `min_pressure`,
`avg_pressure`, `max_density`, `min_density` and `avg_density` to only take active particles
into account (#1184).

## Version 0.5.3

### Features
### Features

- Added normal vectors to `InitialCondition`, with automatic computation for boundary
particles generated by `RectangularTank` and `SphereShape` (#1036).
Expand Down
134 changes: 111 additions & 23 deletions docs/src/systems/fluid.md
Original file line number Diff line number Diff line change
Expand Up @@ -216,52 +216,122 @@ Pages = [joinpath("general", "corrections.jl")]

---

## [Surface Normals](@id surface_normal)
## [Surface Detection And Normals](@id surface_normal)

### Overview of surface normal calculation in SPH

Surface normals are essential for modeling surface tension as they provide the directionality
of forces acting at the fluid interface. They are calculated based on the particle properties and
their spatial distribution.
Surface normals characterize the local orientation of an interface. In SPH, this geometric
information can be used for interface detection and reconstruction, curvature estimation,
interfacial boundary conditions, and interfacial force models. The computed normal field is also
available for analysis and VTK output.

#### Color field and gradient-based surface normals

The surface normal at a particle is derived from the color field, a scalar field assigned to particles
to distinguish between different fluid phases or between fluid and air. The color field gradients point
towards the interface, and the normalized gradient defines the surface normal direction.
The surface normal at a particle can be derived from a color field, a scalar marker used to
distinguish phases or materials. Its gradient is perpendicular to the color-field level sets and
therefore provides an interface-normal estimate; its orientation depends on the chosen color
convention. For a free surface whose exterior phase is not represented by particles, truncation of
the kernel support creates the corresponding discrete color-field gradient.

In the literature, the unnormalized surface normal ``\bm{n}_a`` is commonly written as
For phase ``a``, the unnormalized surface normal is computed from a phase-local indicator
``\chi_a``:

```math
\bm{n}_a = \sum_b m_b \frac{c_b}{\rho_b} \nabla_a W_{ab},
\bm{n}_a = \sum_b m_b \frac{\chi_a(b)}{\rho_b} \nabla_a W_{ab},
```

where:

- ``c_b`` is the color field value for particle ``b``,
- ``\chi_a(b)`` is one when particles ``a`` and ``b`` have the same `color_value` and
zero otherwise,
- ``m_b`` is the mass of particle ``b``,
- ``\rho_b`` is the density of particle ``b``,
- ``\nabla_a W_{ab}`` is the gradient of the smoothing kernel ``W_{ab}`` with respect to particle ``a``.

For single-fluid surface-normal calculations, ``c_b = 1`` for neighboring fluid particles.
The numeric magnitude and sign of `color_value` therefore have no physical meaning. For a
single fluid, ``\chi_a(b) = 1`` for neighboring fluid particles, including when the phase is
labeled zero.

#### Normalization of surface normals

The calculated normals are normalized to unit vectors:
The Morris surface-tension models normalize the calculated normals to unit vectors:

```math
\hat{\bm{n}}_a = \frac{\bm{n}_a}{\Vert \bm{n}_a \Vert}.
```

Normalization ensures that the magnitude of the normals does not bias the curvature calculations or the resulting surface tension forces.
Normalization ensures that their magnitude does not bias curvature calculations. The Akinci
model retains the unnormalized phase-local gradient required by its force formulation.

#### Surface methods and activity

Fluid systems configure interface geometry with the `surface_method` keyword. Every surface
method computes a smooth `surface_activity`. Methods derived from
`AbstractSurfaceNormalMethod` additionally provide a normal, so normal calculation always
includes detection.

`ColorfieldSurfaceDetection` computes activity only. `ColorfieldSurfaceNormal` uses the same
colorfield accumulation and additionally filters and stores the gradient as a surface normal.
Different `color_value`s detect interfaces between represented liquids. Any constant phase
label, including zero, detects a free surface because its kernel support ends at the
unrepresented exterior. Equal labels do not create an internal interface. Relabeling phases
without changing phase membership does not change activity, normals, or surface-tension
forces.

Colorfield wall correction currently requires `BoundaryModelDummyParticles` with
`reference_particle_spacing` set. Other boundary models are rejected during
semidiscretization instead of being treated as free surfaces.

`surface_activity` is available in particle VTK output and as a custom quantity for
`SolutionSavingCallback` and `PostprocessCallback`. `surf_normal` is written only for
normal-capable methods. The per-system `color_value` is always recorded in `meta.json`
and written as `color` field data in particle VTK output, also for fluids without a
surface method, since their phase label still enters other systems' colorfield detection.
All per-particle VTK arrays, including `surface_activity` and `neighbor_count`, hold one
value per active particle when a system buffer is used.

Point and plane interpolation apply the same colorfield phase and boundary-contact eligibility
rules as particle detection. With `cut_off_bnd=true`,
kernel-weighted color contributions also determine whether a point belongs to the reference
phase. This prevents extrapolation through both free surfaces and interfaces with another
liquid while retaining the existing solid-boundary cutoff. Interpolated `surface_activity`
applies the same minimum-support and `ideal_density_threshold` rejection criteria as the
particle-based detection.

#### Handling noise and errors in normal calculation

In regions distant from the interface, the calculated normals may be small or inaccurate due to the
smoothing kernel's support radius. To mitigate this:
Away from an interface, the exact color-field gradient vanishes, but particle disorder and
incomplete kernel support can produce small or poorly resolved normal estimates. The
[`ColorfieldSurfaceNormal`](@ref) thresholds mitigate this as follows:

1. Normals below a threshold are excluded from further calculations.
2. Curvature calculations use a corrected formulation to reduce errors near interface fringes.
1. Normals with insufficient particle support are discarded.
2. `interface_threshold` rejects gradients for which the dimensionless magnitude
``R\lVert n\rVert`` does not exceed the configured cutoff, where ``R`` is the kernel support
radius. This applies to standalone, Akinci, and Morris normals.
3. `ideal_density_threshold` optionally suppresses particles whose neighbor count is close to
ideal full support. This heuristic is intended only for a free surface with an unrepresented
exterior phase. It must remain zero for fully represented multiphase interfaces, where valid
interface particles can have full support.
4. Curvature calculations use a corrected formulation to reduce errors near interface fringes.

#### Morris curvature with phase-local normals

Because the stored normals are phase-local (they point into their own phase), the Morris curvature

```math
\kappa_a = \frac{\sum_b V_b (\hat{\bm{n}}_b - \hat{\bm{n}}_a) \cdot \nabla_a W_{ab}}
{\sum_b V_b W_{ab}}
```

is evaluated with consistently normalized normals. Normals from unlike `color_value`s are
reoriented into the target phase before entering the divergence stencil, while neighboring
systems may store unnormalized gradients (for example with Akinci surface tension). Both
the numerator and denominator are accumulated over all interacting systems before division,
so the result does not depend on system ordering or on how one physical phase is partitioned
into systems. A planar two-phase interface therefore converges toward zero curvature under
refinement. Interpolated surface activity uses the same boundary-contact, minimum-support,
and `ideal_density_threshold` criteria as particles, so sparse or under-resolved regions are
inactive in interpolated output, too.

```@autodocs
Modules = [TrixiParticles]
Expand Down Expand Up @@ -296,6 +366,17 @@ In the following table some values are shown for reference. The values marked wi
| **Water** | 0.07288 [Lange](@cite Lange2005) |
| **Mercury** | 0.486502 [Lange](@cite Lange2005) |

### Model configuration

All surface tension coefficients must be finite and non-negative. A zero coefficient disables
the fluid-fluid surface force. Wall adhesion is controlled independently by the boundary's
`adhesion_coefficient`.

`CohesionForceAkinci` only evaluates the pairwise cohesion and optional wall-adhesion forces.
It does not require surface normals or `reference_particle_spacing`. The full
`SurfaceTensionAkinci` model and both Morris models require a surface-normal method. When one
of these models is selected without an explicit method, `ColorfieldSurfaceNormal()` is used.

### [Akinci-based intra-particle force surface tension and wall adhesion model](@id akinci_ipf)

The [Akinci](@cite Akinci2013) model divides surface tension into distinct force components,
Expand Down Expand Up @@ -329,15 +410,18 @@ C(r)=\frac{32}{\pi h_c^9}
\end{cases}
```

#### Surface area minimization contribution
#### Surface area minimization force

The surface area minimization term models curvature reduction by using the difference between the
raw color gradients. In the implementation it is evaluated in acceleration form as

The surface area minimization contribution models curvature reduction and acts on the
difference in surface normals. TrixiParticles.jl uses the local smoothing length:
```math
\left.\frac{\mathrm{d}\bm{v}_a}{\mathrm{d} t}\right|_{ab}^{\text{curvature}}
= -\sigma h (\bm{n}_a - \bm{n}_b),
a_{a,\text{area}} = -\sigma h_a (n_a - n_b),
```
where ``\bm{n}_a`` and ``\bm{n}_b`` are the surface normals of the interacting particles.

where ``n_a`` and ``n_b`` are the unnormalized color gradients of the interacting particles and
``h_a`` is the smoothing length of particle ``a``. The factor ``h_a`` makes the color-normal term
dimensionless, consistent with the Akinci formulation.

#### Wall adhesion contribution

Expand All @@ -359,6 +443,10 @@ A(r) = \frac{0.007}{h_c^{3.25}}
\end{cases}
```

The published adhesion kernel uses a three-dimensional normalization. In two-dimensional
simulations, `adhesion_coefficient` is therefore an empirical numerical parameter and may need
to be adjusted when changing the particle spacing or smoothing length.

---

### [Morris surface tension model](@id morris_csf)
Expand Down
2 changes: 2 additions & 0 deletions examples/fluid/dam_break_2d.jl
Original file line number Diff line number Diff line change
Expand Up @@ -64,12 +64,14 @@ viscosity_fluid = ArtificialViscosityMonaghan(; alpha, beta=0.0)
# by Antuono. This simulation is short enough to use the faster model.
density_diffusion = DensityDiffusionMolteniColagrossi(delta=0.1)
# density_diffusion = DensityDiffusionAntuono(delta=0.1)
surface_method = nothing

fluid_system = WeaklyCompressibleSPHSystem(tank.fluid; smoothing_kernel, smoothing_length,
density_calculator=fluid_density_calculator,
state_equation, viscosity=viscosity_fluid,
density_diffusion, acceleration=(0.0, -gravity),
correction=nothing, surface_tension=nothing,
surface_method,
reference_particle_spacing=0)

# ==========================================================================================
Expand Down
4 changes: 3 additions & 1 deletion examples/fluid/dam_break_oil_film_2d.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ trixi_include(@__MODULE__, joinpath(examples_dir(), "fluid", "dam_break_2d.jl");
sol=nothing, fluid_particle_spacing, tspan,
viscosity_fluid=ViscosityMorris(nu=nu_sim_water), smoothing_length, gravity,
density_diffusion=nothing, sound_speed, prefix="",
surface_method=ColorfieldSurfaceNormal(),
reference_particle_spacing=fluid_particle_spacing)

# ==========================================================================================
Expand Down Expand Up @@ -67,7 +68,8 @@ oil_system = WeaklyCompressibleSPHSystem(oil;
acceleration=(0.0, -gravity),
surface_tension=SurfaceTensionAkinci(surface_tension_coefficient=0.01),
correction=AkinciFreeSurfaceCorrection(oil_density),
reference_particle_spacing=fluid_particle_spacing)
reference_particle_spacing=fluid_particle_spacing,
color_value=2)

# oil_system = WeaklyCompressibleSPHSystem(oil;
# smoothing_kernel, smoothing_length,
Expand Down
4 changes: 3 additions & 1 deletion examples/fluid/falling_water_spheres_2d.jl
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,9 @@ sphere = WeaklyCompressibleSPHSystem(sphere2; smoothing_kernel=fluid_smoothing_k
smoothing_length=fluid_smoothing_length,
density_calculator=fluid_density_calculator,
state_equation, viscosity, density_diffusion,
acceleration)
acceleration,
surface_method=ColorfieldSurfaceNormal(),
reference_particle_spacing=fluid_particle_spacing)

# ==========================================================================================
# ==== Boundary
Expand Down
2 changes: 1 addition & 1 deletion examples/fluid/sphere_surface_tension_2d.jl
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ fluid_system = EntropicallyDampedSPHSystem(fluid; smoothing_kernel=fluid_smoothi
density_calculator=ContinuityDensity(),
reference_particle_spacing=particle_spacing,
acceleration=zeros(length(fluid_size)),
surface_normal_method=ColorfieldSurfaceNormal(),
surface_method=ColorfieldSurfaceNormal(),
surface_tension=SurfaceTensionMorris(surface_tension_coefficient=50 *
0.0728))

Expand Down
4 changes: 3 additions & 1 deletion src/TrixiParticles.jl
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,9 @@ export interpolate_line, interpolate_points, interpolate_plane_3d, interpolate_p
interpolate_plane_2d_vtk
export SurfaceTensionAkinci, CohesionForceAkinci, SurfaceTensionMorris,
SurfaceTensionMomentumMorris
export ColorfieldSurfaceNormal
export AbstractSurfaceMethod, AbstractSurfaceNormalMethod, ColorfieldSurfaceDetection,
ColorfieldSurfaceNormal, surface_method, computes_surface_normal, surface_activity,
surface_normal
export SymplecticPositionVerlet
export coordinates_eltype

Expand Down
21 changes: 21 additions & 0 deletions src/general/custom_quantities.jl
Original file line number Diff line number Diff line change
Expand Up @@ -141,4 +141,25 @@ function avg_density(system, dv_ode, du_ode, v_ode, u_ode, semi, t)
return NaN
end

"""
surface_activity

Return the per-particle smooth surface activity, or `nothing` for systems without a
configured surface method.
"""
function surface_activity(system::AbstractFluidSystem, dv_ode, du_ode, v_ode, u_ode,
semi, t)
hasproperty(system.cache, :surface_activity) || return nothing
return view(system.cache.surface_activity, each_active_particle(system))
end

surface_activity(system, dv_ode, du_ode, v_ode, u_ode, semi, t) = nothing

function surface_normal(system::AbstractFluidSystem, dv_ode, du_ode, v_ode, u_ode, semi, t)
computes_surface_normal(surface_method(system)) || return nothing
return view(system.cache.surface_normal, :, each_active_particle(system))
end

surface_normal(system, dv_ode, du_ode, v_ode, u_ode, semi, t) = nothing

@inline active_values(values, system) = view(values, each_active_particle(system))
Loading
Loading