tracmass.runsetup#
Resolve settings-driven arguments of the integrators.
Covers monitor / recorder (lifecycle-managed here via
manage_run_io()) and no_wflux (a plain bool derived from the
move_vertically setting via resolve_no_wflux()).
The multi-window integration routines
(time_dependent(),
time_dependent_patched(),
time_dependent_streaming()) each accept a
monitor and a recorder argument. Historically the caller had to
build a RunMonitor / ParticleRecorder
and drive its context manager by hand:
with (RunMonitor(backend="rich") as mon,
ParticleRecorder("run.parquet") as rec):
tracmass.time_dependent_patched(..., monitor=mon, recorder=rec)
The manage_run_io() decorator removes that boilerplate. Applied to an
integrator it accepts the same two arguments in any of four forms and owns
the lifecycle of whatever it constructs itself:
value |
behaviour |
|---|---|
an instance |
used as-is; the caller owns its lifecycle |
a |
|
|
feature disabled |
omitted ( |
built from |
“Entered on the ExitStack” means the object’s __exit__ runs
automatically when the integrator returns or raises, so a with block
around the call is no longer required.
Settings keys consulted for the omitted (_UNSET) case#
runmonitor_backendBackend for the auto-built
RunMonitor("print","log", or"rich"). Default"print".output_nameFilename stem for the auto-built recorder. Setting it also enables auto-recording. Default stem when auto-recording via
auto_record:trm_{active-env}.auto_recordTruthy value enables auto-recording even when
output_nameis unset.base_output_dirDirectory the auto-built recorder writes into. Default: current directory.
use_sub_folderWhen truthy, the auto-built recorder writes into a sub-directory of
base_output_dirnamed afteroutput_name, else the active environment. DefaultFalse. Missing directories are created.
The auto-built filename is
{stem}_{forward|reverse}_{dtm_start.date()}.parquet — the direction token
comes from grid.reverse and the date from fluxes.dtm.
When neither output_name nor auto_record is set, an omitted
recorder resolves to None (no trajectory file) — the historical
default.
Vertical advection#
move_verticallyWhen an integrator’s
no_wfluxargument is not passed explicitly,resolve_no_wflux()setsno_wflux = not move_verticallyfrom this setting (defaultTrue— particles do move vertically, matching the historicalno_wflux=Falsedefault). An explicitno_wflux=always wins. The ECCO2 adapter reads the same setting for itsinclude_wfluxargument (seetracmass.config.move_vertically()).
Particle batching#
n_particle_batchesWhen an integrator’s
n_particle_batchesargument is not passed explicitly,resolve_n_particle_batches()takes it from this setting (default1— no batching). An explicit value always wins; both are clamped to>= 1. The full-grid integrators (steady_state(),time_dependent()) act on it with a particle-batchedlax.while_loop; the streaming integrators accept it for API symmetry only.
Ramp-up saves#
rampup_windows/rampup_substepsWhen an integrator’s
rampup_windows/rampup_substepsarguments are not passed,resolve_rampup()takes them from these settings (defaults0— no ramp-up — and5). During the firstrampup_windowswindows positions are also savedrampup_substeps - 1times inside each window, asevent_type="rampup"rows;rampup_metadata()describes the resulting save times in the trajectory file.
- tracmass.runsetup.resolve_no_wflux(no_wflux)[source]#
Normalise an integrator
no_wfluxargument to a plain bool.- Parameters:
no_wflux (
boolor_UNSET) – An explicit bool is returned unchanged (the caller always wins)._UNSET(the argument was omitted) is resolved from settings asnot move_vertically()— seetracmass.config.move_vertically().- Returns:
- Return type:
- tracmass.runsetup.resolve_n_particle_batches(n_particle_batches)[source]#
Normalise an integrator
n_particle_batchesargument to a plain int.- Parameters:
n_particle_batches (
intor_UNSET) – An explicit value is returned asmax(1, int(...))(the caller always wins)._UNSET(the argument was omitted) is resolved from then_particle_batchessetting — seetracmass.config.n_particle_batches()(default1).- Returns:
int– Batching factor, clamped to>= 1.- Return type:
- tracmass.runsetup.resolve_rampup(rampup_windows, rampup_substeps)[source]#
Normalise the integrators’ ramp-up arguments to
(windows, substeps).- Parameters:
- Returns:
tuple[int,int]–(rampup_windows, rampup_substeps);(0, 1)when ramp-up is off (either is0/1).- Raises:
ValueError – If either is negative / below 1, or not an integer.
- Return type:
- tracmass.runsetup.window_ends(win, rampup_windows, rampup_substeps)[source]#
Normalised times at which window win stops to save positions.
[win + 1]normally;[win + 1/k, win + 2/k, ..., win + 1]withk = rampup_substepsduring the first rampup_windows windows. All but the last are ramp-up saves; the last is the next window’s snapshot.
- tracmass.runsetup.rampup_metadata(n_windows, timestep_seconds, rampup_windows, rampup_substeps)[source]#
Run-metadata keys describing when positions are saved.
- Returns:
dict–rampup_windows,rampup_substepsandsave_dt_seconds: the time between consecutive saved positions (snapshotandrampuprows, in file order), one entry per interval, so the n-th save is atsum(save_dt_seconds[:n])after the start. Covers the planned n_windows; a run that stops early (no active particles left) saves fewer.- Parameters:
- Return type:
- tracmass.runsetup.resolve_n_windows(n_windows, fluxes)[source]#
Normalise an integrator
n_windowsargument to a plain int.- Parameters:
n_windows (
intorNone) – An explicit value is returned unchanged (the caller always wins).Noneis resolved fromfluxes.n_windows— the number of windows fromfluxes.dtmto the dtm_end given totracmass.gcm.new_flux()— falling back to1when no dtm_end was given (or fluxes is not aLazyFluxFields).fluxes (
LazyFluxFieldsorFluxFields) – The flux buffer passed to the integrator.
- Returns:
- Return type:
- tracmass.runsetup.resolve_seed_freq(seed_freq)[source]#
Normalise an integrator
seed_freqargument.- Parameters:
seed_freq (
strorNoneor_UNSET) – A pandas frequency ("30D","MS", …) orNone(seed once) is returned unchanged; the caller always wins._UNSET(the argument was omitted) is resolved fromseed_freqin the[env.seed]settings table, defaultNone.- Returns:
strorNone– The frequency, orNonewhen particles are seeded only at the start (also for an empty string orfalse).- Return type:
str | None
- tracmass.runsetup.seed_windows(seed_freq, dtm_start, timestep, n_windows, reverse=False)[source]#
Windows at whose start a repeat seed is released.
The seed times are dtm_start stepped by the pandas offset seed_freq — forward in time, or backward for a backward run — and each is placed on the window that starts at it. A seed time inside a window moves to the start of the next window. The initial seed (window 0) is not included.
- Parameters:
seed_freq (
strorNone) – Pandas frequency string, e.g."30D","7D","MS"(month starts) or"QS".None→ no repeat seeds.dtm_start (
strorpd.Timestamp) – Start time of window 0.timestep (
pd.Timedeltaordatetime.timedelta) – Window length.n_windows (
int) – Number of windows in the run; seeds at or after its end are dropped.reverse (
bool, optional) – Backward run (windows step back in time). DefaultFalse.
- Returns:
listofint– Sorted, unique window indices, all in1 .. n_windows - 1.- Raises:
ValueError – If seed_freq is not a valid pandas frequency.
- Return type:
Examples
>>> seed_windows("10D", "2010-06-01", pd.Timedelta("1D"), 30) [10, 20] >>> seed_windows("MS", "2010-06-15", pd.Timedelta("1D"), 40) [16]
- tracmass.runsetup.reseed(state, seed, win, tseas)[source]#
Append a copy of seed released at the start of window win.
The copy’s clock is moved forward by win windows (
ttandt0bywin * tseasseconds,tsby win) and its iteration counter is reset, so it starts as a fresh set of particles at that time. Active flags and reasons come from seed (particles seeded inactive stay so).- Parameters:
- Returns:
ParticleState–ParticleState.concat(state, shifted_seed): existing particles keep their indices (and outputid), the new ones follow.
- tracmass.runsetup.seed_metadata(seed_freq, windows)[source]#
Run-metadata keys describing repeat seeding.
- tracmass.runsetup.traj_max_seconds(traj_max_time, dtm_start=None, reverse=False)[source]#
Convert a trajectory lifetime to seconds.
- Parameters:
traj_max_time (
strorpd.TimedeltaorfloatorNone) – The longest a particle may live, counted from its release. Apd.Timedeltastring ("30D","12h","2W"), or calendar months / quarters / years as"M","Q","Y"with an optional count ("1M","6M","2Y"). A number is taken as seconds;Nonemeans no limit.dtm_start (
strorpd.Timestamp, optional) – The run’s start time. Calendar units have no fixed length, so they are measured from here (backward for a backward run):"1M"from 2010-02-01 is 28 days. Needed only for calendar units.reverse (
bool, optional) – Backward run.
- Returns:
float– Lifetime in seconds (1e20for no limit).- Raises:
ValueError – If traj_max_time cannot be parsed, is not positive, or is in calendar units without dtm_start.
- Return type:
- tracmass.runsetup.resolve_timax(timax_seconds, traj_max_time, dtm_start=None, reverse=False)[source]#
Resolve the trajectory lifetime of an integrator call.
- Parameters:
timax_seconds (
floator_UNSET) – Lifetime in seconds. An explicit value wins.traj_max_time (
strorNoneor_UNSET) – Lifetime as a pandas-style string, seetraj_max_seconds()._UNSETis resolved from thetraj_max_timesetting, default no limit.dtm_start (
strorpd.Timestamp, optional) – The run’s start time, for calendar units.reverse (
bool, optional) – Backward run.
- Returns:
tuple[float,dict]–timax_secondsand run-metadata keys (traj_max_timeandtimax_seconds; empty without a limit).- Raises:
ValueError – If both arguments are given explicitly.
- Return type:
- tracmass.runsetup.resolve_monitor(monitor, stack)[source]#
Normalise monitor to a
RunMonitorinstance orNone.- Parameters:
monitor (
RunMonitororstrorNoneor_UNSET) – See the module docstring for the four accepted forms.stack (
contextlib.ExitStack) – A monitor constructed here is registered on this stack so its__exit__runs when the integrator returns or raises. A monitor passed in by the caller is returned untouched.
- Returns:
RunMonitororNone- Return type:
RunMonitor | None
- tracmass.runsetup.resolve_recorder(recorder, stack, *, dtm_start=None, reverse=False)[source]#
Normalise recorder to a
ParticleRecorderinstance orNone.- Parameters:
recorder (
ParticleRecorderorstroros.PathLikeorNoneor_UNSET) – See the module docstring for the four accepted forms.stack (
contextlib.ExitStack) – A recorder constructed here is registered on this stack so its Parquet writer is closed when the integrator returns or raises. A recorder passed in by the caller is returned untouched.dtm_start (
pandas.Timestampordatetime-like, optional) – Start timestamp of the run, used only for the auto-built filename.reverse (
bool, optional) – Direction of the run (grid.reverse). Selects theforward/reversetoken in the auto-built filename. DefaultFalse.
- Returns:
ParticleRecorderorNone- Return type:
ParticleRecorder | None
- tracmass.runsetup.run_metadata(fn, grid, fluxes)[source]#
Describe a run for the
"tracmass.run"metadata of its trajectory file.- Parameters:
fn (
callable) – The integrator; its name is stored asintegrator.grid (
GridFields) – Supplies the run direction and time step.fluxes (
LazyFluxFieldsorFluxFields) – Supplies the start / end time and the GCM adapter (fluxes_fn).
- Returns:
dict– JSON-serialisable; keys whose value is unknown are left out:gcmAdapter name (
"glorys","ecco2", …) whenfluxes_fnis atracmass.gcmadapter, elsefluxes_fn("module.qualname") for a custom flux function.gcm_productThe adapter’s data product (
tracmass.seagrid.<gcm>.settings ["product"]), e.g."glorys12v1".gcm_subsetThe adapter’s
subsetsetting, unset edges left out.envActive
tracmass.tomlenvironment.integratorName of the integrator function.
direction"forward"or"reverse".dtm_start,dtm_end,timestep_secondsTime span of the run and the GCM timestep.
tracmass_version,createdPackage version and creation time (UTC, ISO 8601).
- Return type:
- tracmass.runsetup.manage_run_io(fn)[source]#
Decorate an integrator to own its monitor / recorder lifecycle.
The wrapped function is always called with
monitorandrecorderalready normalised to an instance orNone(viaresolve_monitor()/resolve_recorder()), with verbose debug output on if theverbosesetting is true (tracmass.verbose), wrapped in acontextlib.ExitStackthat closes any object constructed on the caller’s behalf when the integrator returns or raises. The function body no longer interprets sentinels or constructs these objects itself.- Parameters:
fn (
callable) – An integrator called asfn(state, grid, fluxes, ...)—gridsupplies the run direction (grid.reverse) andfluxesthe run start timestamp (fluxes.dtm) for the auto-built recorder filename — and which accepts keyword-onlymonitorandrecorderparameters. The recorder’sgrid_offsetis set fromgrid.i_offset/grid.j_offsetso it writes full-grid positions, andrun_metadata()is added to its metadata (keys already there are kept).- Returns:
callable– Wrapper carrying fn’s name, docstring and signature viafunctools.wraps().- Return type: