Repository navigation
Tracers: flux-based advection and dynamical injection - #141
mfournier01 wants to merge 144 commits into
Conversation
filled in values for s_i
small edits in the par_reduce in the computation of the correlations
fixed a bug in computing the correlations
Comparisons showed this method wasn't performing any better than the cell-centered velocity interpolation (vinterp) it was meant to improve on, so remove it rather than carry the extra complexity/maintenance burden. This also removes the underlying hazard we'd been chasing: fvel was computed as mass_flux / reconstructed_face_density with no floor, and unlike the main conserved-variable update, that division was never protected by first_order_flux_correct (which only patches cons.flux, computed separately and earlier). A near-zero or reconstruction-overshot negative face density -- more likely at coarser resolution for the same turbulence forcing -- silently produced an Inf/NaN fvel that would eventually poison a tracer's position and abort on the neighbor-index bounds check. - tracers.hpp: drop Flux from AdvectMethod (now MonteCarlo, VInterp, None). - tracers.cpp: remove the "fluxinterp" input string branch (default advection_method falls back to "vinterp" instead), the fvel field registration, the fvel_pack setup, and the whole AdvectMethod::Flux branch in AdvectTracers; drop the now-unused TE type alias; update stale comments describing the (now two, not three) advection methods. - hydro.cpp: remove the fvel pack and the three per-direction fvel(...) = flux/wl|wr(IDN,...) assignment blocks (x1/x2/x3) computed during CalculateFluxes. - tst/regression: delete the particle_advection_fluxinterp test suite and its CMakeLists.txt registration -- can't test a removed method. - docs/input.md: advection_method now documents vinterp (default) and montecarlo (requires vl2), instead of the removed fluxinterp default. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Addresses a batch of code-review findings on the tracer particle
implementation:
- Guard against Monte Carlo advection + adaptive refinement, and dynamic
injection + adaptive refinement: both rely on per-block state (RNG pools,
ID offset slices) established once at startup with no re-allocation
strategy for blocks created/reassigned by AMR. Fail loudly at startup
instead of crashing or silently corrupting IDs mid-run.
- Initialize velocity, refinement level, and (for the turbulence pgen) the
s/sdot density history for dynamically-injected tracers at injection
time, instead of leaving them at stale/zero defaults until the next
FillTracers call (after Advect/Center already used them).
- Fix duplicate tracer IDs when dynamic injection runs without
random_per_block seeding: reserve each block's ID slice once at startup
regardless of initial_seed_method, instead of only inside that one
seeding path.
- Fix the Monte Carlo transfer probability's mass denominator: snapshot
M_cell once at stage 1 (FillTracerMCell), not on every VL2 stage, so it
reflects the true start-of-step mass instead of the predictor state.
- Fix coarse-to-fine tracer centering: derive the two valid child cells
per axis from Xtoijk's actual floor semantics ({i-1,i}, not {i-1,i+1}),
and branch child count/z-handling on ndim instead of assuming 3D.
- Consume per-swarm initial RNG seeds (previously stored but ignored) and
give each tracer population an independent stream, including for
dynamic injection.
- Validate that a temperature-based injection/removal criterion has the
required unit/composition conversion available, and that enabled
injection has positive num_target/timescale, instead of silently
evaluating a bogus negative "temperature" or injecting nothing.
- Fix 2D FillTracers diagnostics that discarded valid out-of-plane
velocity/B-field components and their in-plane derivatives, treating
"no z-derivatives" as "no out-of-plane component" instead.
- Make the jet injection criterion share the same time-dependent,
possibly tilted/precessing jet axis as the actual kinetic feedback,
instead of always assuming a fixed z-axis cylinder.
- Regression tests: compare tracer IDs with exact integer equality
instead of floating-point tolerances that can't distinguish nearby
uint64 IDs.
- Fix tracer documentation: criterion parameter names, a nonworking
swarm-output example, obsolete API signatures/enum name/argument
order, stale doc links, an incorrect "updates only before output"
claim, missing restrictions, and the Monte Carlo algorithm description.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Ran ./scripts/format.sh (clang-format 20.1.8, black 26.5.1, matching requirements-format.txt) over the files touched in 2917360. Purely cosmetic: line wrapping/indentation, no behavior change. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Monte Carlo advection (stay or hop, which face) and the child-cell pick
in CenterTracers drew from per-block Kokkos::Random_XorShift64_Pool
states ("rng_block_<gid>"). Which state serves which tracer depends on
the backend (one state on Serial, one per thread on GPUs), on thread
scheduling and on the tracer's slot in the swarm. The pools were also
not saved in restart files: SeedInitialTracers re-seeded them from
(ncycle, gid) at every start. So cluster_tracers only reproduced its
reference on the platform that generated it, and a restart from t=0.1
gave bitwise identical gas but put 92-95 of the 168 tracers in other
cells.
Every Monte Carlo draw is now TracerRoll(seed, swarm index, tracer ID,
ncycle, tag): a SplitMix64 hash chain over the population's rng_seed and
index, the tracer's ID, the cycle and one tag per call site. It keeps no
state, so it does not depend on the backend or thread, on which block or
rank holds the tracer, or on where it sits in the swarm. The ID travels
with the tracer and is written to restart files, and Parthenon restores
ncycle, so a restarted run draws the same numbers as an uninterrupted
one. The swarm index keeps populations apart: each numbers its tracers
independently and all default to seed 0.
The t=0 random_per_block placement keeps its per-block pool, so initial
positions (and the turbulence test's reference) are unchanged.
- Remove the rng_block_<gid> pools.
- Keep the Monte Carlo + adaptive refinement guard, but replace its stale
RNG-pool rationale.
- cluster_tracers: compare IDs and levels exactly, positions and
injection times to 1e-12, and the sampled gas with rtol=1e-8 and
atol=1e-12. The time can differ in its last bits between backends: a
Serial run of the commit that made the old reference differs from it by
up to 2.8e-17. Fix the exact-ID branch, which tested "id" instead of
"swarm.id". Regenerate its reference (Kokkos Serial, macOS arm64).
- Update the docs on Monte Carlo randomness.
Checked on Kokkos Serial: cluster_tracers and particle_advection pass.
Restarting cluster_tracers from its t=0.1 dump reproduces the final swarm
and gas bitwise. The turbulence test's tracer and gas output is bitwise
identical to before this change.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
SeedInitialTracers reserves each block's tracer ID range (tracers_offsets) and is guarded by the restart param initial_seed_done. The "user" and "random_per_block" paths set it, but "none" (the default) returned without it. Every restart then reset the restored offsets, and tracers injected after the restart reused earlier IDs. Since the Monte Carlo draws are keyed on the tracer ID, tracers sharing an ID also made correlated moves. hydro_agn_feedback_tracers.in with initial_seed_method=none, restarted from its t = 0.1 dump: 78 IDs shared by 156 of the 168 tracers (0 when run through), and different tracer data at the end. With the fix the restart skips the seeding, has no duplicates and ends bitwise identical to the uninterrupted run. Enabling tracers on a restart of a run without them seeds once, and a later restart is again bitwise identical. - cluster_tracers: run with initial_seed_method=none (bitwise identical to random_per_block with 0 tracers per cell, so ref_data.pkl is unchanged), and add a step that restarts from the t = 0.1 dump. Both final dumps get the reference checks. Without the fix, only the restarted step fails (duplicate IDs, 15 variables). - docs/input.md: document "none" and that seeding runs once per simulation. Checked on Kokkos Serial: cluster_tracers (2 steps) and particle_advection pass. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
InjectParticles gave each injected particle its swarm slot and its ID (block offset + n) from an atomic counter, i.e. in the order threads reached it. Since the Monte Carlo draws are keyed on the tracer ID, the Monte Carlo paths then depended on thread scheduling. That is the case on GPUs and with parallel loop layouts. CPU builds with SIMDFOR_LOOP were unaffected, as that layout runs multi-dimensional par_for as a serial loop nest. The fill pass is now an exclusive par_scan over the block's cells in the order of that serial loop (k, then j, then i): each injected particle gets slot and ID n_before, the number of particles injected in the cells before it. The injection decision is a stateless hash of the cell, so it is the same in every scan pass. Serial results are bitwise unchanged (same order), so cluster_tracers' ref_data.pkl still holds. Checked with a Kokkos Threads build with MANUAL1D_LOOP, 4 threads, on a turbulence box with Monte Carlo tracers injected everywhere (32^3, 8 blocks, ~160 injections per block and step, 12214 tracers after 10 cycles): before, 12113 tracers ended at other positions than in the Serial run under the same ID, and repeated runs differed in 7373 and 8048; after, none, and repeated runs are identical. The cluster_tracers jet injects too few tracers per block and step to race, which is likely why its reference held on the CUDA CI. Serial: cluster_tracers (2 steps) and particle_advection pass; cluster_tracers also passes on the Threads build. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Monte Carlo hops used the last stage's mass fluxes times dt, which is the step's actual mass transfer only for vl2. Accumulate the stage mass fluxes right after each stage's flux correction with the update's own recursion (acc = gam0 acc + beta F), and hop on that instead. For rk1, rk2, rk3 and vl2 this reproduces the cells' mass change to round-off, refinement boundaries included. For vl2 it is bitwise unchanged (0 * F1 + 1 * F2), so cluster_tracers still matches its reference. This also fixes Monte Carlo tracers never moving with diffusion/integrator = rkl2: the final RKL2 step reset the flux arrays before AdvectTracers read them. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
cluster_tracers_rkl2 reruns cluster_tracers with RKL2 conduction, whose final half step used to reset the flux arrays before the Monte Carlo tracers moved, freezing them. tracer_mass_fluxes checks without reference data that step_mass_flux reproduces every cell's density change to round-off for rk2 and rk3, on a 2D shear flow with a refined patch. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Port of the RAMSES CIC Itô-2 tracers (ramses-organisation/ramses@51123de) as tracers/advection_method = ito. Each step a tracer moves by the CIC- interpolated mean displacement of a Monte Carlo hop plus a uniform kick with the matching variance, both computed per cell from the final mass fluxes of the step. The moments need one ghost layer for the CIC stencil. They get their own exchange once per step, and hydro's exchanges use a copy of "base" without them, so no extra data rides along the per-stage and RKL2 exchanges. At physical boundaries the moments are always extrapolated with zero gradient. Nothing changes when ito is not selected. Adds the cluster_ito_tracers regression test (subclass of cluster_tracers). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Also matches the third central moment of the Monte Carlo jump, with the piecewise skew uniform kick of Moseley et al. (2026, Eqs. 38-39). The skewness is formed from the CIC-interpolated moments rather than by interpolating it directly, as near-static cells have skewness ~ C^-1/2. The default stays ito_order = 2, bitwise unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tracers/derivatives_at = particle computes the pressure gradient, divergence, vorticity, magnetic curl, tension and grad B^2 at the cell centers around each tracer and interpolates them linearly to its position, using the second ghost layer and no extra communication. The default, cell, keeps the host-cell values unchanged. The stencils move to inline functions in tracers.hpp (AddCellDerivatives, ParticleDerivatives), shared by both options. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
pgrete
left a comment
There was a problem hiding this comment.
Next bunch of comments. I'm about half-way through.
| - **Note**: the random number generator seed uses the unique block id. Therefore, simulations with the mesh decomposition (mesh and meshblock sizes) are identical independent of the number of MPI ranks used, but if the meshblock size is changed for given mesh (and thus the total number of blocks) the initial state will be different. | ||
| - Controlled by: | ||
| - `tracers0_initial_num_tracers_per_cell` | ||
| - Optional: `initial_rng_seed` to customize randomness |
There was a problem hiding this comment.
Question remains. Should be explicit here.
| tracers1_injection_enabled = true | ||
| tracers1_injection_criterion = density_above | ||
| tracers1_injection_threshold = 8.0 # in code units | ||
| tracers1_injection_timescale = 0.05 | ||
| tracers1_injection_num_target = 1 |
There was a problem hiding this comment.
Parameters need more documentation.
| PARTHENON_REQUIRE_THROWS(pin->DoesParameterExist("tracers", "swarm_names"), | ||
| "Need to define at least one particle population via " | ||
| "'swarm_names' when tracers are enabled."); | ||
| auto swarm_names = pin->GetVector<std::string>("tracers", "swarm_names"); | ||
| tracers_pkg->AddParam<>("swarm_names", swarm_names); |
There was a problem hiding this comment.
Could we get backwards compatibility?
I.e., checking if swarm_names exists and if now assuming that there's just one population named tracers?
There was a problem hiding this comment.
Fixed; now if no swarm names are provided it just implicitely create a tracers population
| // Package initialization happens before the Mesh exists, so mirror Mesh's | ||
| // multilevel input check here when deciding which swarm values to register. | ||
| const auto refinement = pin->GetOrAddString( | ||
| "parthenon/mesh", "refinement", "none", | ||
| std::vector<std::string>{"none", "static", "adaptive"}, "mesh refinement mode"); | ||
| const bool multilevel = | ||
| refinement != "none" || pin->GetOrAddBoolean("parthenon/mesh", "multigrid", false, | ||
| "enable a multigrid mesh"); |
There was a problem hiding this comment.
This will eventually cause trouble as an internal upstream change in Parthenon will lead this lines of code to fail (given a potential mismatch in default values/doc), but it's fine to leave it for now.
| // ... and the step's mass flux through each cell's lower x1, x2 and x3 faces (the | ||
| // last cells' upper faces are stored in the first ghost layer) | ||
| m = Metadata({Metadata::Cell, Metadata::Derived, Metadata::OneCopy}, | ||
| std::vector<int>({3})); | ||
| tracers_pkg->AddField("step_mass_flux", m); |
There was a problem hiding this comment.
We now have FaceCentered vars and/or could add the WithFluxes MetaData to M_cell.
However, I'd be fine to let this pass for now when you open an issue as follow up cleanup (to make it easier to review as the changes would not be "hidden" inside this already large PR).
| const int ito_order = pin->GetOrAddInteger("tracers", "ito_order", 2); | ||
| PARTHENON_REQUIRE_THROWS(ito_order == 2 || ito_order == 3, | ||
| "tracers/ito_order must be 2 or 3."); |
There was a problem hiding this comment.
Could use the restricted interface only allowing 2 and 3 as input as above.
| } else if (injection_criterion == "jet") { | ||
| // Geometric criterion selecting cells within the kinetic AGN jet region; | ||
| // the jet_radius/jet_offset/jet_thickness geometry itself is problem | ||
| // specific and populated via ProblemInitTracerData (see cluster.cpp). | ||
| inj_crit = ParticlesCriterion::Jet; |
There was a problem hiding this comment.
Eventually, this should be a problem specific call back but that's for another day.
There was a problem hiding this comment.
Yes, good point (this shouldn't actually be there anymore, I thought I had got rid of it. Will keep it for now
pgrete
left a comment
There was a problem hiding this comment.
Done with the full re-view. Feel free to push the addressed changes.
| PARTHENON_REQUIRE_THROWS( | ||
| (!pin->DoesParameterExist("tracers", "num_tracers_per_cell") && | ||
| !pin->DoesParameterExist("tracers", "initial_num_tracers_per_cell")), | ||
| "'tracers/num_tracers_per_cell' and 'tracers/initial_num_tracers_per_cell' " | ||
| "parameters have been deprecated. Please update your " | ||
| "input file to use 'tracers/initial_seed_method=random_per_block' with " | ||
| "'tracers/SWARM_NAME_initial_num_tracers_per_cell=NUMBER'."); |
There was a problem hiding this comment.
This may need to move down (or the logic below to skip on initial_seed_done) needs to move up, because old restarts likely would fail here.
| fmax(Mflux_pack(b, d, k + dk, j + dj, i + di) * area * dt, 0.0); | ||
| const Real dM_m = fmax(-Mflux_pack(b, d, k, j, i) * area * dt, 0.0); |
| auto *pmesh = md->GetParentPointer(); | ||
| const auto advection_method = | ||
| pmesh->packages.Get("tracers")->Param<AdvectMethod>("advection_method"); |
There was a problem hiding this comment.
I'm surprised this works without crashing.
It seems to be called in the driver independent of the presence of tracers, so if tracers are not initialized (e.g., not tracer block in the input file) I wold have expected this line to throw/crash.
Also, I'm not a big fan of the current layout as this tracer function "leaks" into the general driver (even when tracers are disabled).
I'll think about this some more.
There was a problem hiding this comment.
Since this is only related to îto tracers, an alternative possibility would be to keep the îto tracers out of the moment and only keep velocity and Monte Carlo tracers, then keep îto for later.
There was a problem hiding this comment.
Also, reason why it doesn't crash is that hydro.cpp always register tracer packages no matter what, even when enable=False a default value for advection_method is also defined
Line 59 in 4b5aa30
There was a problem hiding this comment.
Given the extent of the PR I'm think I'm happy to keep this temporarily for now and immediately (say on a 1-2 weeks timescale) fix it in a smaller subsequent PR.
| const Real dM_xp = fmax(Mflux_pack(0, k, j, i + 1) * area_x * dt, 0.0); | ||
| const Real dM_xm = fmax(-Mflux_pack(0, k, j, i) * area_x * dt, 0.0); | ||
| const Real dM_yp = fmax(Mflux_pack(1, k, j + 1, i) * area_y * dt, 0.0); | ||
| const Real dM_ym = fmax(-Mflux_pack(1, k, j, i) * area_y * dt, 0.0); |
|
|
||
| switch (crit) { | ||
| case ParticlesCriterion::DensityAbove: | ||
| return prim(IDN, k, j, i) >= threshold; |
There was a problem hiding this comment.
Technically all these threshold should come without the = comparator, isn't it?
| int s_idx; | ||
| // A particle injected this cycle has no real history yet: seed every | ||
| // lookback slot with its current value instead of shifting in zeros. | ||
| if (track_injection_time && t_inj(n) == current_time) { | ||
| for (s_idx = 0; s_idx < n_lookback; s_idx++) { | ||
| s(s_idx, n) = Kokkos::log(rho(n)); | ||
| sdot(s_idx, n) = 0.0; | ||
| } | ||
| } else { | ||
| s_idx = n_lookback - 1; | ||
| while (s_idx > 0) { | ||
| if (current_cycle % (dncycles_d(s_idx) - dncycles_d(s_idx - 1)) == 0) { | ||
| s(s_idx, n) = s(s_idx - 1, n); | ||
| sdot(s_idx, n) = sdot(s_idx - 1, n); | ||
| } | ||
| s_idx -= 1; |
There was a problem hiding this comment.
This needs to be reverted and a guard should be put in place to prevent dynamical injection for the turbulence pgen for now.
The reason is that the logic further down assumes that the time bins for all particles are identical.
If that doesn't hold anymore logic would be more complex as additional masking would be required.
| # IDs are integers spanning the uint64 range (see EncodeOffset/ | ||
| # DecodeOffset): rtol=2e-6 at that magnitude allows ~1e13 of | ||
| # slop, so they need exact, not approximate, comparison. | ||
| if var == "id": | ||
| np.testing.assert_array_equal(var_data_sorted, ref_data[var]) | ||
| # For serial tests, be more stringent. | ||
| # Need to track down the tiny differences when run with MPI. | ||
| if parameters.mpi_cmd == "": | ||
| elif False and parameters.mpi_cmd == "": | ||
| np.testing.assert_array_max_ulp( | ||
| var_data_sorted, ref_data[var], maxulp=2 | ||
| ) | ||
| else: | ||
| np.testing.assert_allclose( | ||
| var_data_sorted, ref_data[var], rtol=8.1e-7 | ||
| var_data_sorted, ref_data[var], rtol=2.0e-6 |
There was a problem hiding this comment.
I don't understand the changes (including the new comment). What does the uint64 range have to do with the relative error?
There was a problem hiding this comment.
Raising the tolerance from 8.1e-7 to 2.0e-6 comes from one of your commit (bcb3f71, September 11).
There was a problem hiding this comment.
Regarding the comment: it was not super transparent indeed but the idea was that the code needs to be fixed. Currently the if var == "id" does an exact comparison with the expected ref_data. But since the variable is actually called swarm.id, the if condition is always false, so the ids get accidentally compared to the reference data through the else, which offers a tolerance of 2.0e-6. The comment basically said that such a tolerance is way too large for ids since we now allow them to be uint64s (so such a large tolerance couldn't tell the difference between two large uint64 numbers). I will fix that.
Co-authored-by: Philipp Grete <pgrete@hs.uni-hamburg.de>
Co-authored-by: Philipp Grete <pgrete@hs.uni-hamburg.de>
Co-authored-by: Philipp Grete <pgrete@hs.uni-hamburg.de>
Inputs without tracers/swarm_names now define one population named "tracers", and tracers/initial_num_tracers_per_cell is the default for each population again, like tracers/initial_rng_seed. Restrict ito_order through the input interface, use the Kokkos math functions in PiecewiseSkewUniform, and fix the removal exception comment: the lifetime is extended by another full lifetime, not by 50%. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
user_pgen.md is for problem specific callbacks, so drop injection, removal and advection from it. input.md now documents the per-population parameters, that initial_seed_method is global and how initial_rng_seed is resolved. It also uses DOIs for the references and gets back the comments of the output example. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
ProblemFillTracers assumes that the time bins of all particles are identical, so seeding the history of just-injected tracers isn't enough. Restore the original history update and stop at startup instead. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Such a restart keeps initial_seed_done at its default, so it seeded a second set of tracers on top of the restored ones, with duplicate IDs. Treat restored tracers as seeded and reserve new IDs above theirs. The deprecated parameter check now also comes after this, so it doesn't reject old restarts. Other review comments: - Pick a coarse cell's children half a fine cell above its center, as round-off at that fine cell corner could tip Xtoijk's floor to either side. - Use strict comparisons for the above/below criteria. - Remove the unused src/utils/custom_rng.hpp copy and unused variables. - Use Kokkos math functions in tracer kernels. - Rename ParticleDerivatives to AddParticleDerivatives. Update copyright headers. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…items Move the advection method branch outside the kernel, so each method has its own par_for and an unknown method fails. Compare swarm.id exactly in the turbulence test (the old "id" name never matched), use Kokkos::isfinite in the Ito kernel, and apply the remaining review suggestions in custom_rng.hpp, CMakeLists.txt and the injection_threshold docs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| PARTHENON_REQUIRE_THROWS(ito_order == 2 || ito_order == 3, | ||
| "tracers/ito_order must be 2 or 3."); | ||
| // (parsed as a string as ParameterInput only restricts the values of strings) | ||
| const int ito_order = std::stoi(pin->GetOrAddString( |
There was a problem hiding this comment.
Why parsing this as string and not int?
|
And one final Codex comment: |
|
Alright, getting reaaaally close here. |
The main modifications are:
AdvectTracerroutine into two separate methods. Method 0 corresponds to the already implemented velocity field interpolation method. Method 1 is the new flux-based method. The method can be specified in the input file within the<tracer>section, using themethodparameter.A comparison of the two methods is presented below, and can be compared to Fig. 9 from https://ui.adsabs.harvard.edu/abs/2013MNRAS.435.1426G/abstract.
hydro_density.mp4
A 2D test using the Kelvin-Helmholtz and method 1 is also presented below.
hydro_density.mp4