Simulation
Setting up a simulation
A PHARE simulation is configured entirely from a Python script, by declaring
a small number of objects. Each is declared once (diagnostics may be declared
several times, once per output), and Simulation must always be declared
first - every other block below depends on it.
# ------------ MANDATORY BLOCKS
ph.Simulation(
# time evolution, domain, AMR, restart and diagnostics-output parameters
)
ph.MaxwellianFluidModel(
# magnetic field profile and ion population(s), for a Hybrid simulation
)
# -- or, for an MHD simulation --
ph.MHDModel(
# density, velocity, magnetic field and pressure profiles
)
ph.ElectronModel(
# electron fluid closure - required for a Hybrid simulation
)
# ------------ END OF MANDATORY BLOCKS
# ------------ OPTIONAL BLOCKS
ph.LoadBalancer(
# tune how work is redistributed across MPI ranks
)
ph.ElectromagDiagnostics(...) # E and B field outputs
ph.FluidDiagnostics(...) # ion moment outputs
ph.ParticleDiagnostics(...) # particle outputs
ph.MHDDiagnostics(...) # MHD fluid outputs
ph.InfoDiagnostics(...) # run-monitoring outputs
# ------------ END OF OPTIONAL BLOCKS
See Models for MaxwellianFluidModel/MHDModel/ElectronModel,
Diagnostics for the diagnostics blocks, and Load balancing for
LoadBalancer. This page covers the Simulation block itself.
The Simulation block
Simulation sets the overall numerical and physical parameters of the
run: how long it evolves and at what resolution, the physical domain and
mesh, adaptive mesh refinement, restart checkpoints, and where diagnostics
are written.
- class pyphare.pharein.Simulation(**kwargs_in)[source]
Usage example:
This declares a 2D simulation of 100x100 cells with an isotropic mesh size of 0.2. The simulation will run 1000 time steps of dt=0.001 and so will stop at t=1
The simulation will run with adaptive mesh refinement and evolve up to 3 levels, i.e. a base coarsest mesh with up to 2 additional refinement levels.
Diagnostics, if declared, will be saved as native PHARE HDF5 (default format) in the directory diag_outputs and will overwrite any existing h5 files there.
The resistivity and hyper-resistivity are set to constant custom values.
import pyphare.pharein as ph ph.Simulation( # time evolution parameters time_step_nbr=1000, time_step=0.001, # Domain parameters cells=(100,100), dl=(0.2, 0.2), # AMR parameters refinement="tagging", max_nbr_levels=3, # general physics parameters hyper_resistivity=0.001, resistivity=0.001, # diagnostics and restart parameters diag_options={"format": "phareh5", "options": {"dir": diag_outputs, "mode":"overwrite"}}, )
Time parameters:
final_time (
float), final simulation time. Use with time_step OR time_step_nbrtime_step (
float), simulation time step. Use with time_step_nbr OR final_timetime_step_nbr (
int), number of time step to perform. Use with final_time OR time_step
time_stepmay also be given as a dict selecting the time-stepping mode:{"mode": "constant", "value": <dt>}- equivalent to passingtime_step=<dt>("value"is optional and may be replaced byfinal_time/time_step_nbr).{"mode": "adaptive", "cfl_wave": <w>, "cfl_diffusive": <d>}- the time step is recomputed each step from a CFL constraint. Requiresfinal_timeand is incompatible withtime_step_nbr.cfl_wave (
float), hyperbolic/wave CFL coefficient. Normalized so 1 is the stability limit; choose in (0, 1]. In hall mhd and hybrid, whistler wave speed limits is used.cfl_diffusive (
float), diffusive CFL coefficient. Normalized so 1 is the diffusion stability limit; choose in (0, 1]. Defaults tocfl_wave. Only relevant when resistivity is non-zero.
With adaptive stepping there is no fixed dump grid, so diagnostics require explicit
write_timestamps.
ph.Simulation( time_step_nbr=1000, time_step=0.001, # .... )
is equivalent to:
ph.Simulation( time_step_nbr=1000, final_time=1., # .... )
or even to:
ph.Simulation( time_step=0.001, final_time=1., # .... )
Domain/grid parameters:
The number of dimensions of the simulation is deduced from the length of these parameters.
dl (
float,tuple) grid spacing dx, (dx,dy) or (dx,dy,dz) in 1D, 2D or 3D. A single float value in 2D or 3D are assumed equal for each dimension. Use this parameter with either domain_size OR cellsdomain_size (
floatortuple) size of the physical domain Lx, (Lx,Ly), (Lx,Ly,Lz) in 1D, 2D or 3D Single float is assumed equal for each direction. Use this parameter with either cells or dlcells (
intortuple) number of cells nx or (nx, ny) or (nx, ny, nz) in 1, 2 and 3D. Single int is assumed equal for each direction Use this parameter with either domain_size or dl
Expert parameters:
These parameters are more advanced, modify them at your own risk
layout (
str), layout of the physical quantities on the mesh (default = “yee”)
For instance:
ph.Simulation( dl=(0.1, 0.1), domain_size=(100,100), # .... )
is equivalent to:
ph.Simulation( cells=(1000, 1000), domain_size=(100,100), # .... )
or even to:
ph.Simulation( cells=(1000, 1000), dl=(0.1,0.1), # .... )
Diagnostics output parameters:
- diag_options (
dict) format (
str), {“phareh5” (default), “pharevtkhdf”}, on-disk format of the diagnostics files. See Diagnostics for what each format means.- options (
dict) dir (
str) directory where diagnostics files are written (default : ‘./’)mode (
str), {“overwrite”}, if set to “overwrite”, any existing diagnostics file in dir is truncated (wiped) at the start of the run. If omitted (the default), an existing file is opened and kept as-is instead, so new data is added onto it - useful when restarting a simulation, so diagnostics keep accumulating in the same file rather than being lost.fine_dump_lvl_max (
int), default=None. This does not affect the regular diagnostics dumps, which always cover the whole hierarchy at the times given by each diagnostic’s write_timestamps. If set, it additionally triggers an extra dump on every substep (much more frequent than the regular schedule on refined levels), limited to levels up to and including fine_dump_lvl_max. If left unset (the default), no such extra dump happens at all - only the regular, whole-hierarchy dumps occur.allow_emergency_dumps (
bool), default=False, if True, allows PHARE to write an out-of-schedule diagnostics dump when the run is interrupted abnormally.
- options (
Note: diag_options[“format”] (the diagnostics file format) is unrelated to the separate, unused-today diag_export_format keyword below - the latter is reserved for a currently single-valued option (“hdf5”) and should not be confused with the former.
- diag_options (
diag_export_format (
str), currently always “hdf5” (no other value is accepted).
Adaptive Mesh Refinement (AMR) parameters:
refinement (
str), {“boxes” (default), “tagging”}, how refined regions are chosen.“tagging” - refined regions are recomputed at run time from the solution itself: cells where a gradient-based criterion exceeds tagging_threshold are tagged, then clustered into patches (buffered by tag_buffer). Refined regions therefore move and grow/shrink as the physics evolves. This is the mode used for actual science production runs.
“boxes” - refined regions are the fixed, user-given refinement_boxes, identical at every time step. Mostly used in tests, where fully deterministic, reproducible refined regions matter more than adapting to the physics.
tagging_threshold (
float), default=0.1, used only when refinement=”tagging”. Threshold of the tagging criterion above which a cell is flagged for refinement. Lower values tag more cells and produce more/larger refined regions. See Tagging for refinement for the underlying theory.max_nbr_levels (
int), default=1, max number of levels in the hierarchy. With refinement=”boxes” this is derived automatically from the number of levels given in refinement_boxes; with refinement=”tagging” it must be given explicitly (it otherwise silently defaults to 1, i.e. no refinement).tag_buffer (
int), default=1, number of cells by which each tagged cell is grown, in every direction, before clustering into boxes. E.g. with tag_buffer=1, a single tagged cell becomes surrounded by a 1-cell-wide layer of also-tagged cells: 3 tagged cells in 1D, 9 in 2D. The larger tag_buffer, the wider refined regions will be around tagged cells.clustering (
str), {“berger”, “tile” (default)}, type of Clustering to use for AMR. tile results in wider patches, less artifacts and better scalability than berger.
Expert parameters:
These parameters are more advanced, modify them at your own risk
nesting_buffer (
ìnt), default=1 minimum gap in coarse cells from the border of a level and any refined patch border. Has no effect (and is not sent to SAMRAI) if the simulation has no refinement levels.refinement_boxes (
dict), default=None, used only when refinement=”boxes”. Explicitly gives the fixed refined regions to create, level by level.Each key
"Li"("L0","L1", …) identifies a level. Its value describes the box(es), given in levelLi’s own cell-index coordinates, that will be refined into levelLi+1. So boxes under"L0"define where level 1 patches will be, boxes under"L1"define where level 2 patches will be, and so on.For a given level, boxes are given as a dict mapping an arbitrary box name (
"B0","B1", …, only used to identify boxes in error messages) to a pair of index tuples(lower, upper): the lower and upper cell indices of that box, inclusive, in x, (x, y) or (x, y, z) depending on the simulation’s dimension.
refinement_boxes={ "L0": {"B0": [(10,), (19,)]}, # 1D: on L0, cells 10 to 19 become refined into L1 "L1": {"B0": [(30,), (49,)]}, # on L1, cells 30 to 49 (L1's own indexing) become L2 }
would produce a hierarchy with 3 levels (L0, L1, L2), the number of levels being deduced from the number of keys given here (max_nbr_levels does not need to be set in that case).
Warning
These boxes are fixed for the entire simulation: they never move, grow or shrink, regardless of how the physics evolves. Level boundaries therefore stay at the same location for the whole run, which lets high-frequency noise generated at those boundaries accumulate there over time instead of being swept away as a tagging-based refined region would do. For this reason refinement_boxes is mostly useful for tests, where deterministic, reproducible refined regions matter more than accuracy - see refinement=”tagging” above for the mode intended for science production runs.
smallest_patch_size (
intortuple), minimum number of cells in a patch in each direction This parameter cannot be smaller than the number of field ghost nodeslargest_patch_size (
intortuple), maximum size of a patch in each direction
Restart parameters:
These parameters control both how checkpoints are dumped during a simulation and how a simulation restarts from a previous checkpoint.
- restart_options (
dict), default=None (no restart files are read or written at all) dir (
str), default=”./”, path for restart files- mode (
str), default=”conserve”, mode of the restart files “conserve” - (default), will conserve existing files
“overwrite” - will overwrite existing files
- mode (
restart_time (
floator"auto"), default=None (fresh start, not a restart), time at which to restart the simulation. If “auto”, the latest available restart file in dir is used.timestamps (
list), default=None, list of simulation times at which to dump a restart file. Must be in ascending order and consistent with time_step. If neither this nor elapsed_timestamps is set, no restart file is ever dumped.elapsed_timestamps (
listoffloatseconds ordatetime.timedelta), default=None, dump a restart file every time this much wall-clock time has elapsed since the simulation started, instead of at fixed simulation times. Can be combined with timestamps.keep_last (
int), default=None (keep every restart directory ever written, nothing is deleted). If set, only the keep_last most recent restart directories are kept - older ones are deleted automatically as new ones are written. It is a count rather than a bool because it expresses how many to retain, not just whether to prune at all.
- restart_options (
Hybrid parameters:
These parameters only apply to a Hybrid simulation, i.e. one declared with
model_options=["HybridModel"](the default, paired with aMaxwellianFluidModelblock instead of anMHDModelone). They are ignored on pure-MHD runs.interp_order (
int), 1, 2 or 3 (default=1 if “HybridModel” is amongmodel_options) particle b-spline order; omit it for a run with no hybrid model, where it has no meaningparticle_pusher (
str), algo to push particles (default = “modifiedBoris”)resistivity (
float), default=0.0, Hybrid Ohm’s law resistivity valuehyper_resistivity (
float), default=0.0001, Hybrid Ohm’s law hyper-resistivity valuehyper_mode (
str), {“constant” (default), “spatial”}, “constant” uses hyper_resistivity as is; “spatial” scales it locally by(|B|/(n + 0.1) + 1) / 4**level
Expert parameters:
These parameters are more advanced, modify them at your own risk
refined_particle_nbr (
ìnt), number of refined particles per coarse particle. This is not a free parameter: only a handful of values are valid, and which ones depends on ndim and interp_order. The authoritative list of valid combinations is possibleSimulators() in src/core/utilities/meta/meta_utilities.hpp, since each combination corresponds to a distinct pre-compiled instantiation of the code - passing a value outside that list raises an error at Simulation construction time (mirrored on the Python side in valid_refined_particle_nbr, pyphare/pharein/simulation.py). If omitted, the first valid value for the given ndim/interp_order is used as the default.
MHD parameters:
These parameters only apply to an MHD simulation, i.e. one declared with
model_options=["MHDModel"](paired with anMHDModelblock instead of aMaxwellianFluidModelone). PHARE currently runs either a Hybrid (kinetic ions / fluid electrons) or an MHD simulation, never a mix of both in the same hierarchy.model_options (
strorlist), {“HybridModel” (default), “MHDModel”}, which physics this simulation evolves.max_mhd_level (
int), default=0, number of AMR levels evolved with MHD. Must be <= max_nbr_levels; for an MHD simulation it is typically set equal to max_nbr_levels (every level is MHD).gamma (
float), default=5/3, adiabatic index (heat capacity ratio) of the MHD fluid.eta (
float), default=0.0, MHD resistivity.nu (
float), default=0.0, MHD hyper-resistivity.hall (
bool), default=False, whether the Hall term is included in the MHD Ohm’s law.reconstruction (
str), spatial reconstruction scheme used by the MHD finite-volume solver (e.g. “WENOZ”).limiter (
str), slope limiter used with the reconstruction scheme (e.g. “None”).riemann (
str), Riemann solver used at cell interfaces (e.g. “Rusanov”).mhd_timestepper (
str), mandatory for an MHD simulation, time integration scheme for the MHD solver (e.g. “TVDRK3”).
reconstruction, limiter, riemann and hall select which pre-compiled MHD module is loaded, so their combination must be one that was built (see
res/sim/all.txt).Misc:
description (
string), [default=None] arbitrary string for per simulation context - injected in output files when feasiblestrict (
bool), turns warnings into errors (default False)dry_run (
bool), default=False (or the PHARE_DRY_RUN environment variable if set), builds and validates the simulation - constructing models, populating the dict, building the hierarchy - without actually initializing or advancing it. Simulator.initialize(), advance() and run() become no-ops. Useful to check that a script is well-formed without paying for a real run.domain_boundaries (
dict) domain boundaries per location (e.g. “xlower”); a direction is periodic unless both of its locations are given (MHD only)
Domain and time, worked example
The domain can be given as any two of cells (number of mesh cells),
dl (mesh spacing) and domain_size (physical size) - the third is
derived. Likewise for time, any two of time_step, time_step_nbr and
final_time:
import pyphare.pharein as ph
ph.Simulation(
cells=(100, 100),
dl=(0.2, 0.2), # domain_size is derived: (20, 20)
time_step=0.001,
time_step_nbr=1000, # final_time is derived: ~1.0
refinement="tagging",
max_nbr_levels=3,
)
Note
When final_time and time_step are both given, time_step is
kept exactly as given and final_time is treated as a target: the
actual number of steps is rounded to the nearest integer, so the run may
stop slightly before or after the requested final_time.
Restarts and diagnostics output
See Restarts for restart_options and Diagnostics for
diag_options and the diagnostics blocks themselves.