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
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
.vscode
.DS_Store
Manifest.toml
# Machine-specific reconstruction benchmark results (local regression references)
benchmark/surface_reconstruction/baselines/*.json
out
out_*
docs/build
Expand Down
5 changes: 5 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,11 @@ used in the Julia ecosystem. Notable changes will be documented in this file for

- Added an optional Makie recipe for rendering two- and three-dimensional particle systems
with `plot`, `plot!`, `trixi2makie`, and `trixi2makie!`.
- Added 2D/3D free-surface reconstruction from fluid particles with `SurfaceReconstruction`,
`reconstruct_surface`, `reconstruct_surface!`, and `SurfaceReconstructionCallback`,
producing closed area-corrected contours or volume-corrected triangle meshes. The
callback writes VTK PolyData time series (PLY optional); meshes can be reconstructed
offline from particle data, systems, solutions, and initial conditions.

## Version 0.5.3

Expand Down
2 changes: 2 additions & 0 deletions Project.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ GPUArraysCore = "46192b85-c4d5-4398-a991-12ede77f4527"
JSON = "682c06a0-de6a-54ab-a142-c8b1cf79cde6"
KernelAbstractions = "63c18a36-062a-441e-b654-da1e3ab1ce7c"
LinearAlgebra = "37e2e46d-f89d-539d-b4ee-838fcccc9c8e"
MarchingCubes = "299715c1-40a9-479a-aaf9-4a633d36f717"
PointNeighbors = "1c4d5385-0a27-49de-8e2c-43b175c8985c"
Polyester = "f517fe37-dbe3-4b94-8317-1923a5111588"
Printf = "de0858da-6303-5e67-8744-51eddeeeb8d7"
Expand Down Expand Up @@ -63,6 +64,7 @@ JSON = "1"
KernelAbstractions = "0.9"
LinearAlgebra = "1"
Makie = "0.24"
MarchingCubes = "0.1.11"
OrdinaryDiffEqLowStorageRK = "3"
OrdinaryDiffEqCore = "4"
OrdinaryDiffEqSymplecticRK = "2"
Expand Down
5 changes: 5 additions & 0 deletions benchmark/surface_reconstruction/Project.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
[deps]
TrixiParticles = "66699cd8-9c01-4e9d-a059-b96c86d16b3a"

[compat]
julia = "1.10, 1.11, 1.12"
80 changes: 80 additions & 0 deletions benchmark/surface_reconstruction/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
# Surface reconstruction benchmarks

Deterministic micro- and meso-scale benchmarks for `SurfaceReconstruction`. No extra
dependencies beyond the package itself: timings use `time_ns`, allocations use
`@allocated`.

## Workloads

- `block_small`: 7³ lattice, the numerical reference geometry (sanity + smoke).
- `block_1e4`: ~22³ lattice; covers the full pipeline at a still-interactive scale.
- `boundaries`: 7³ lattice plus one lattice boundary cube exercising the BVH
signed-distance constraint path.
- `sparse`: 7³ lattice plus an isolated droplet with the sparse-component fallback
enabled, exercising the graph search and fallback-mesh path.
- `wave_tank` (opt-in): synthetic production-scale frame with 1.1e6 particles in a
2 m × 4 m × 1 m tank at the particle spacing of the production wave tank
(599×1180×309 grid). Every repeat restarts the isovalue correction at the base
isovalue, so it times the full correction of a new frame. The workspace needs about
3.5 GB of memory (5 GB peak); run it with all available threads.

The default suite runs all workloads except `wave_tank` in well under a minute
(excluding one-time compilation).

Workloads reuse one `SurfaceReconstruction` across warmup and repeats, so timings reflect
the warm-started steady state (typically a single correction evaluation on identical
input). Short workloads are evaluated several times per timing sample. This keeps the
regression signal low-noise; cold-start behavior is covered by the numerical reference tests.

The `sparse` workload has no warm-started steady state: its second correction pass
excludes the droplet from the target volume, so every call runs both passes and ends at a
slightly different isovalue within the volume tolerance. The number of calls per run is
fixed, so the reported results are still reproducible.

## Run locally

```bash
julia --project=benchmark/surface_reconstruction \
benchmark/surface_reconstruction/run_benchmarks.jl \
--workloads=block_small,block_1e4 --repeats=3 --output=results.json
```

Optionally record a local baseline, then compare against it (exit code 1 on regression
beyond `--tolerance` relative time or 5% allocation growth). Workstation-specific
baselines are ignored by git; the runner warns when thread counts differ.

```bash
julia --project=benchmark/surface_reconstruction \
benchmark/surface_reconstruction/run_benchmarks.jl \
--output=benchmark/surface_reconstruction/baselines/dev-workstation-julia1.11.json
julia --project=benchmark/surface_reconstruction \
benchmark/surface_reconstruction/run_benchmarks.jl \
--baseline=benchmark/surface_reconstruction/baselines/dev-workstation-julia1.11.json
```

Production-scale timing:

```bash
julia --project=benchmark/surface_reconstruction --threads=auto \
benchmark/surface_reconstruction/run_benchmarks.jl --workloads=wave_tank
```

For cross-thread scaling, set `JULIA_NUM_THREADS` (bitwise-identical meshes are required
at 1 and N threads; see the determinism guard in the test suite).

## Determinism check

`benchmark/surface_reconstruction/determinism.jl` prints SHA-256 mesh checksums and
selected statistics for a reference block and two wave tanks. The larger case also
exercises fixed-bucket mesh reductions. The output must agree byte-for-byte across
thread counts on the same platform
(required by pipelines that hash outputs for auditing). A local baseline is a developer
regression reference for its machine, not a portable CI threshold.

```bash
JULIA_NUM_THREADS=1 julia --project=benchmark/surface_reconstruction \
benchmark/surface_reconstruction/determinism.jl > det1.txt
JULIA_NUM_THREADS=4 julia --project=benchmark/surface_reconstruction \
benchmark/surface_reconstruction/determinism.jl > det4.txt
diff <(grep -v "^threads=" det1.txt) <(grep -v "^threads=" det4.txt) && echo DETERMINISTIC
```
68 changes: 68 additions & 0 deletions benchmark/surface_reconstruction/determinism.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
#!/usr/bin/env julia
# Cross-thread-count determinism check for the reconstruction pipeline.
#
# Prints mesh checksums and selected statistics for the reference block and two wave tanks.
# The medium case has enough faces to exercise fixed-bucket parallel mesh reductions.
# Run twice with different thread counts and compare the output:
#
# JULIA_NUM_THREADS=1 julia --project=benchmark/surface_reconstruction \
# benchmark/surface_reconstruction/determinism.jl > det1.txt
# JULIA_NUM_THREADS=4 julia --project=benchmark/surface_reconstruction \
# benchmark/surface_reconstruction/determinism.jl > det4.txt
# diff <(grep -v "^threads=" det1.txt) <(grep -v "^threads=" det4.txt) && echo DETERMINISTIC
#
# Grid writes are disjoint and reduction buckets have fixed bounds, so the results must
# agree bitwise across thread counts on the same platform.
using Pkg

Pkg.develop(path=normpath(joinpath(@__DIR__, "..", "..")))
Pkg.instantiate()

include(joinpath(@__DIR__, "workloads.jl"))

using .Workloads
using TrixiParticles
using SHA: SHA

function report(name, (mesh, stats))
bytes = vcat(reinterpret(UInt8, mesh.vertices), reinterpret(UInt8, mesh.faces))
println("$name: mesh_sha256=$(bytes2hex(SHA.sha256(bytes)))")
println("$name: vertices=$(length(mesh.vertices)) faces=$(length(mesh.faces))")
println("$name: effective_isovalue=$(repr(stats["effective_isovalue"]))")
println("$name: volume=$(repr(stats["volume"]))")
end

function main()
println("threads=$(Threads.nthreads())")

# Numerical reference block
spacing = 0.1
points, volumes = Workloads.lattice_block(7, spacing)
reconstruction = SurfaceReconstruction(; particle_spacing=spacing,
voxel_size=spacing / 2,
tank_size=(1.0, 1.0, 1.0))
report("block", reconstruct_surface!(reconstruction, points, volumes))

# Coarse wave tank, large enough to split all threaded loops and with several
# isovalue correction evaluations
spacing = 0.03
points, volumes = Workloads.wave_tank_particles(spacing)
reconstruction = SurfaceReconstruction(; particle_spacing=spacing,
tank_size=(2.0, 4.0, 1.0))
report("wave_tank", reconstruct_surface!(reconstruction, points, volumes))

# Explicitly guard coverage above the parallel mesh-reduction threshold, even if
# the other workloads' particle counts or grid dimensions change.
spacing = 0.018
points, volumes = Workloads.wave_tank_particles(spacing)
reconstruction = SurfaceReconstruction(; particle_spacing=spacing,
tank_size=(2.0, 4.0, 1.0))
mesh, stats = reconstruct_surface!(reconstruction, points, volumes)
length(mesh.faces) >= TrixiParticles.PARALLEL_REDUCTION_MIN_FACES ||
error("wave-tank determinism case does not exercise parallel mesh reductions")
report("wave_tank_mesh_reductions", (mesh, stats))

return 0
end

exit(main())
170 changes: 170 additions & 0 deletions benchmark/surface_reconstruction/run_benchmarks.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,170 @@
#!/usr/bin/env julia
# Run surface reconstruction benchmarks and optionally compare against a baseline.
#
# Usage:
# julia --project=benchmark/surface_reconstruction \
# benchmark/surface_reconstruction/run_benchmarks.jl \
# [--workloads=block_small,block_1e4] [--repeats=3] \
# [--output=results.json] \
# [--baseline=benchmark/surface_reconstruction/baselines/<file>.json] \
# [--tolerance=0.10]
#
# Without `--workloads`, all workloads except the opt-in `wave_tank` are run.
# Exit code is 1 when any workload regresses beyond `--tolerance` relative time
# (minimum) or 5% relative allocation growth.
using Pkg

Pkg.develop(path=normpath(joinpath(@__DIR__, "..", "..")))
Pkg.instantiate()

include(joinpath(@__DIR__, "workloads.jl"))

using .Workloads
using Printf: @printf

function parse_args(args)
options = Dict{String, String}(
"workloads" => join(Workloads.DEFAULT_WORKLOADS, ","),
"repeats" => "3",
"output" => "",
"baseline" => "",
"tolerance" => "0.10"
)
for arg in args
startswith(arg, "--") && occursin("=", arg) ||
error("expected `--option=value`, got: $arg")
key, value = split(arg[3:end], "="; limit=2)
haskey(options, key) || error("unknown option: $key")
options[key] = value
end
return options
end

function git_sha()
project_dir = dirname(Base.active_project())
current = pwd()
try
cd(project_dir)
return chomp(read(`git rev-parse --short HEAD`, String))
catch
return "unknown"
finally
cd(current)
end
end

function write_json(path, data::Dict, sha)
open(path, "w") do io
println(io, "{")
println(io, " \"meta\": {")
println(io, " \"julia\": \"$(VERSION)\",")
println(io, " \"threads\": $(Threads.nthreads()),")
println(io, " \"machine\": \"$(gethostname())\",")
println(io, " \"git\": \"$sha\"")
println(io, " },")
println(io, " \"workloads\": {")
names = sort(collect(keys(data)))
for (index, name) in enumerate(names)
result = data[name]
comma = index < length(names) ? "," : ""
println(io, " \"$name\": {")
println(io, " \"time_min_seconds\": $(result["time_min_seconds"]),")
println(io, " \"time_median_seconds\": $(result["time_median_seconds"]),")
println(io, " \"allocated_bytes\": $(result["allocated_bytes"]),")
println(io, " \"workspace_bytes\": $(result["workspace_bytes"]),")
println(io, " \"particles\": $(result["particles"]),")
println(io, " \"grid_dimensions\": $(result["grid_dimensions"]),")
println(io,
" \"n_correction_evaluations\": $(result["n_correction_evaluations"]),")
println(io, " \"vertices\": $(result["vertices"]),")
println(io, " \"faces\": $(result["faces"]),")
println(io, " \"volume\": $(result["volume"]),")
println(io, " \"effective_isovalue\": $(result["effective_isovalue"])")
println(io, " }$comma")
end
println(io, " }")
println(io, "}")
end
return path
end

function read_simple_json(path)
# Minimal reader for files written by `write_json` (flat numeric/string values).
# Returns the workload results and the thread count of the run.
data = Dict{String, Any}()
threads = 0
current = ""
for line in eachline(path)
m = match(r"^ \"threads\": ([0-9]+),?$", line)
if !isnothing(m)
threads = parse(Int, m.captures[1])
continue
end
m = match(r"^ \"([^\"]+)\": \{$", line)
if !isnothing(m)
current = m.captures[1]
data[current] = Dict{String, Any}()
continue
end
m = match(r"^ \"([^\"]+)\": ([0-9.e+\-]+),?$", line)
if !isnothing(m) && !isempty(current)
data[current][m.captures[1]] = parse(Float64, m.captures[2])
end
end
return data, threads
end

function main()
options = parse_args(ARGS)
workload_names = split(options["workloads"], ",")
repeats = parse(Int, options["repeats"])
tolerance = parse(Float64, options["tolerance"])
Workloads.set_repeats!(repeats)

results = Dict{String, Any}()
for name in workload_names
haskey(Workloads.WORKLOADS, name) || error("unknown workload: $name")
println("running workload $name (repeats=$repeats, threads=$(Threads.nthreads()))")
results[name] = Workloads.WORKLOADS[name]()
result = results[name]
@printf(" min %.3f s | median %.3f s | allocated %.1f MiB | grid %s | evaluations %d\n",
result["time_min_seconds"], result["time_median_seconds"],
result["allocated_bytes"] / 2^20,
join(result["grid_dimensions"], "x"), result["n_correction_evaluations"])
end

if !isempty(options["output"])
mkpath(dirname(options["output"]))
write_json(options["output"], results, git_sha())
println("wrote $(options["output"])")
end

exit_code = 0
if !isempty(options["baseline"])
baseline, baseline_threads = read_simple_json(options["baseline"])
println()
if baseline_threads != Threads.nthreads()
println("WARNING: the baseline was recorded with $baseline_threads threads, " *
"this run uses $(Threads.nthreads()); time ratios are not comparable")
end
println("workload | time ratio (min) | alloc ratio | verdict")
for name in workload_names
if !haskey(baseline, name)
@printf("%-12s | not in baseline\n", name)
continue
end
base = baseline[name]
result = results[name]
time_ratio = result["time_min_seconds"] / base["time_min_seconds"]
alloc_ratio = result["allocated_bytes"] / base["allocated_bytes"]
ok = time_ratio <= 1 + tolerance && alloc_ratio <= 1.05
exit_code = ok ? exit_code : 1
@printf("%-12s | %8.3f | %8.3f | %s\n", name, time_ratio, alloc_ratio,
ok ? "OK" : "REGRESSION")
end
end

return exit_code
end

exit(main())
Loading
Loading