PyTracerLab.model.model module¶
Model container with a parameter registry.
- class PyTracerLab.model.model.Model(dt: float, lambda_: Union[float, np.ndarray], input_series: np.ndarray, production: Optional[Union[bool, Sequence[bool]]] = False, target_series: Optional[np.ndarray] = None, steady_state_input: Optional[Union[float, Sequence[float]]] = None, n_warmup_half_lives: int = 2, n_warmup_steps: int = None, time_steps: Optional[Union[Sequence, np.ndarray]] = None, units: List[Unit] = <factory>, unit_fractions: List[float] = <factory>, param_uncert: Dict[str, List[float, float, float]] = None, param_map: Dict[str, float] = None)[source]¶
Bases:
objectForward model container with a parameter registry.
The model aggregates units, keeps their mixing fractions, and performs the convolution-based simulation. It also manages an explicit parameter registry that stores current values, initial values, optimizer bounds, and fixed flags per parameter.
- Parameters:
dt (float) – Time step of the simulation (same units as
mttused by units).lambda (float or ndarray) – Decay constant(s) in 1/time units. Provide a scalar for single-tracer runs or an array-like of length
n_tracersfor multi-tracer runs.input_series (ndarray) – Forcing time series of shape
(N,)for single tracer or(N, K)forKtracers.production (bool or sequence of bool, optional) – If True, simulate production from decay. If a bool, this is a global setting. Use a sequence of bools for per-tracer specification. The order of the sequence must match the order of the columns in the
input_series. The input should contain the parent tracer from which production is simulated.target_series (ndarray, optional) – Observed output series of shape
(N,)or(N, K); used only for calibration/loss and reporting.steady_state_input (float or sequence of float, optional) – Tracer input before the start of
input_series, assumed constant (steady state) for all earlier times. Supply a scalar for single-tracer runs or one value per tracer for multi-tracer runs (for a produced tracer, e.g. tritiogenic 3He, the value of its parent). If omitted, water that recharged before the start of the input series is assumed to contain no tracer, and a warning is issued; give0to confirm this without a warning.n_warmup_half_lives (int, optional) – No effect since v0.3.0 (kept for compatibility): the steady-state input is accounted for exactly, without a warm-up period.
n_warmup_steps (int, optional) – No effect since v0.3.0 (kept for compatibility).
Notes
Input before the record. The contribution of the steady-state input to the output at time step
iis computed exactly assteady_state_input * (M - sum(h[:i + 1]))for each unit, wherehis the unit’s response within the input series andMits response summed over all travel times (total_response()). No warm-up period is simulated, so there is no limit on the length of the steady-state period (e.g. for 14C) or of the travel times.Units are added via
add_unit(). The method also registers unit parameters into the model’s registry.Bounds are optimization bounds only and can be provided at add time or later via
set_bounds().Mixing fraction. For a binary mixture (exactly two units), the fraction of the first unit is a registry parameter
"<prefix>.fraction"(bounds(0, 1)); the second unit contributes1 - fraction. It is fixed by default and can be calibrated like any other parameter:m.add_unit(lab.EPMUnit(mtt=10.0, eta=1.5), fraction=0.6, prefix="young", bounds=[(1.0, 100.0), (1.0, 3.0)]) m.add_unit(lab.PMUnit(mtt=500.0), fraction=0.4, prefix="old", bounds=[(100.0, 1000.0)]) m.set_fixed("old.mtt") # often necessary, see below m.set_fixed("young.fraction", False) # calibrate the mixing fraction m.set_bounds("young.fraction", (0.2, 0.8))
Whether the fraction and the mean travel times of both units can be determined together depends on the number of independent observations and on the tracers (e.g. tracers with contrasting input histories). If the information is limited, fix one mean travel time. With three or more units, the fractions are fixed model properties.
- add_unit(unit: PyTracerLab.model.units.Unit, fraction: float, prefix: str | None = None, bounds: List[Tuple[float, float]] | None = None) None[source]¶
Add a unit, register its parameters, and set its mixture fraction.
Adding the second unit also registers the mixing fraction of the first unit as parameter
"<prefix>.fraction"(fixed by default, bounds(0, 1)); adding a third unit removes it again, because mixing fractions can only be calibrated for binary mixtures (seeModel).Unit parameters are registered as free, except those the unit marks as fixed by default (
"fixed": Truein itsPARAMS, e.g. the screen geometry ofPEMUnit); free them withset_fixed(). Parameters with a range fixed by their definition (unit.intrinsic_bounds(), e.g. the coordinates ofAgeBinUnitin[0, 1]) get this range as bounds ifboundsis omitted.- Parameters:
unit (
Unit) – The unit instance to add.fraction (float) – Mixture fraction of this unit in the overall response, between 0 and 1. Fractions must sum to ~1 across all units.
prefix (str, optional) – Namespace prefix for the unit’s parameters (e.g.,
"epm"). If omitted,"u{index}"is used in insertion order.bounds (list of (float, float), optional) – Optimizer bounds for the unit’s parameters in the same order as returned by
unit.param_values(). If omitted, bounds are left asNone(except for intrinsic ranges, see above) and can be supplied later viaset_bounds().
- Raises:
ValueError – If
boundsis provided and its length does not match the number of unit parameters or a bound lies outside an intrinsic range, iffractionis not between 0 and 1, if the prefix is already used, or if a third unit is added while the mixing fraction of a binary mixture is free.
- fraction_key() str | None[source]¶
Key of the mixing-fraction parameter, or
None.The parameter exists only for binary mixtures (exactly two units); it holds the fraction of the first unit.
- get_bounds(free_only: bool = False) List[Tuple[float, float]][source]¶
Return bounds for parameters in registry order.
Raises a
ValueErrorif any addressed parameter has no bounds set.
- get_ttds(n_steps: int | None = None) List[numpy.ndarray][source]¶
Return travel time distributions for all units using current registry values.
- Returns:
Dict of unit fractions and travel time distributions for all units. Each travel time distribution is a numpy array with one element per time step. Time steps and time step units correspond to general model settings. Fractions can be used to determine a global model-impulse response from the unit-specific responses.
- Return type:
Dict
- get_vector(which: str = 'value', free_only: bool = False) List[float][source]¶
Export parameter values as a flat vector in registry order.
- Parameters:
which ({"value", "initial"}) – Whether to export current values or initial guesses.
free_only (bool, optional) – If
True, export only free parameters.
- Returns:
Parameter vector following
param_keys()order.- Return type:
- input_series: np.ndarray¶
- property n_warmup: int¶
always 0 since v0.3.0.
Kept for compatibility; the steady-state input before the record is accounted for exactly (see
Model).- Type:
Number of warm-up steps prepended to the series
- set_bounds(key: str, bounds: Tuple[float, float]) None[source]¶
Set optimizer bounds for a single parameter.
- set_fixed(key: str, fixed: bool = True) None[source]¶
Mark a parameter as fixed (not optimized) or, with
fixed=False, as free.
- set_initial(key: str, value: float) None[source]¶
Set a single parameter’s initial value used for optimization seeding.
- set_param(key: str, value: float) None[source]¶
Set a single parameter’s current value and update the unit.
This is a convenience wrapper around
set_vector()for one value. Setting the mixing fraction also sets the fraction of the second unit to1 - value.
- set_vector(vec: Sequence[float], which: str = 'value', free_only: bool = False) None[source]¶
Write a vector into the registry (and units) in registry order.
- simulate() numpy.ndarray[source]¶
Run the forward model using current registry values.
Water older than the input series has the steady-state input concentration (decayed according to its travel time); without a steady-state input, it contains no tracer (see
Model).- Returns:
Simulated output aligned with
input_seriesandtarget_series.- Return type:
ndarray
- write_report(filename: str, frequency: str, tracer: str | None = None, sim: str | Sequence[str] | None = None, title: str = 'Model Report', include_initials: bool = True, include_bounds: bool = True, convert_mtt_to_years: bool = False) str[source]¶
Create a simple text report of the current model configuration and fit.
- Parameters:
filename (str) – Path of the text file to write.
frequency (str) – Simulation frequency (e.g.,
"1h"). This is not checked internally and directly written to the report.tracer (str or sequence of str, optional) – Name(s) of the tracer(s) in the report. If not given, decay constants are shown for all tracers instead of tracer names.
sim (ndarray, optional) – Simulated series corresponding to the current parameters. If not provided and target_series is present, the method will call
simulate()to compute one.title (str, optional) – Title shown at the top of the report.
include_initials (bool, optional) – Whether to include initial values in the parameter table.
include_bounds (bool, optional) – Whether to include optimizer bounds in the parameter table.
convert_mtt_to_years (bool, optional) – Whether to convert mean travel times to years from months.
- Returns:
The full report text that was written to filename.
- Return type:
Notes
Parameters are grouped by their namespace prefix (e.g.,
"epm"in keys like"epm.mtt").If target_series is available, the report includes the mean squared error (MSE) between the simulation and observations using overlapping, non-NaN entries.
- exception PyTracerLab.model.model.PyTracerLabWarning[source]¶
Bases:
UserWarningWarning about the model or calibration setup (e.g. a capped warm-up).