PyTracerLab.model.units module¶
Base classes for model units.
- class PyTracerLab.model.units.AgeBinUnit(edges: Sequence[float], weights: Sequence[float] | None = None)[source]¶
Bases:
PyTracerLab.model.units.UnitAge-bin model: a discrete, shape-free travel time distribution.
The travel time distribution is a histogram with
Kbins between fixed edgesa_0 < a_1 < ... < a_Kand a uniform distribution within each bin (age histogram or discrete age distribution model; Visser et al., 2013, Eq. 3; McCallum et al., 2014):g(τ) = w_k / (a_k - a_(k-1)) for a_(k-1) < τ <= a_k,
with bin weights
w_k >= 0that sum to 1. No shape is prescribed; the weights are calibrated. The mean travel timeΣ w_k (a_(k-1) + a_k) / 2is derived from the weights (mtt).Parameters. The weights are not registered directly, because they must sum to 1. Instead, the unit has
K - 1coordinatesu1, ..., u(K-1)in[0, 1]that are mapped one-to-one to the weights (stick-breaking):b_i = 1 - (1 - u_i)^(1 / (K - i)), w_1 = b_1, w_k = b_k (1 - b_1) ... (1 - b_(k-1)), w_K = (1 - b_1) ... (1 - b_(K-1)).
Every point of the unit box is a valid histogram, so all solvers work with the plain bounds
(0, 1), which are registered automatically. A uniform distribution of the coordinates in the box corresponds to the uniform (flat Dirichlet) distribution of the weights: with the default uniform prior ofmcmc_sample()anddream_sample(), every histogram is equally probable a priori. With two bins,u1is the weight of the first bin. Useweights,cumulativeandmttfor the current state andweights_from_samples()for posterior samples.- Parameters:
edges (sequence of float) – Bin edges
a_0, ..., a_K(K >= 1), strictly increasing,a_0 >= 0, in the time unit of the model (same asmttof the other units). Bins may reach beyond the start of the input series (e.g. a wide last bin for old water); like for all units, water older than the series has the steady-state input concentration.weights (sequence of float, optional) – Initial bin weights (
Kvalues>= 0that sum to 1). Default: equal weights.
Notes
The response of each time step is the exact integral of the histogram with decay (sum of uniform blocks, as in the linear model).
Tracer data usually constrain only a few properties of the travel time distribution, such as the mean and the young fraction (McCallum et al., 2014). Use few bins (e.g. 3 to 6) and a sampler (
dream_sample()) to see which weights the data determine. No smoothness regularisation is applied.Examples
bins = lab.AgeBinUnit(edges=[0, 10, 20, 40, 60, 1000]) m = lab.Model(dt=1.0, lambda_=lab.decay_constant("Tritium"), input_series=inp.values, target_series=obs.values, steady_state_input=5.0) m.add_unit(bins, fraction=1.0, prefix="bins") # bounds (0, 1) set res = lab.Solver(m).dream_sample(n_samples=2000, sigma=obs.uncertainty) w = bins.weights_from_samples(res, "bins") # (n, K) weights mtt = w @ bins.centres # mean travel times
- PREFIX = 'bins'¶
- property centres: numpy.ndarray¶
Bin centres;
weights @ centresis the mean travel time.
- coords_from_weights(weights: Sequence[float]) Dict[str, float][source]¶
Coordinates (local parameter values) for given bin weights.
Use it to set initial values of a unit that is already part of a model, e.g.:
for name, v in bins.coords_from_weights([0.4, 0.3, 0.2, 0.1]).items(): m.set_initial(f"bins.{name}", v)
- property cumulative: numpy.ndarray¶
Fraction of water younger than each edge (length
K + 1, from 0 to 1).
- property edges: numpy.ndarray¶
Bin edges
a_0, ..., a_K(read-only array).
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
Age-bin response of each time step (exact integral) with decay.
- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If a coordinate is outside
[0, 1].
- report_lines(time_divisor: float = 1.0) List[str][source]¶
Edges, weights, cumulative fractions and mean travel time.
- total_response(lambda_: float, prod: bool = False) float[source]¶
Response over all travel times (see
Unit.total_response()).
- property weights: numpy.ndarray¶
Current bin weights (length
K).
- weights_from(coords: Sequence[float] | numpy.ndarray) numpy.ndarray[source]¶
Bin weights for coordinates
u(vectorised).- Parameters:
coords (array_like, shape
(..., K - 1)) – Coordinates in[0, 1].- Returns:
Bin weights (
>= 0, sum 1 along the last axis).- Return type:
ndarray, shape
(..., K)
- weights_from_samples(result: Mapping[str, Any], prefix: str) numpy.ndarray[source]¶
Bin weights of each sample of an MCMC or DREAM result.
- Parameters:
- Returns:
Weights; coordinates that were fixed keep their current value.
np.cumsum(w, axis=1)gives the fractions younger than each upper edge,w @ unit.centresthe mean travel times.- Return type:
ndarray, shape
(n_samples, K)
- class PyTracerLab.model.units.DMUnit(mtt: float, DP: float)[source]¶
Bases:
PyTracerLab.model.units.UnitDispersion Model (DM) unit.
- Parameters:
mtt (float) – Mean travel time.
DP (float) – Dispersion parameter. Represents the inverse of the Peclet number. Also represents the ratio of the dispersion coefficient to the velocity and outlet / sampling position
PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Note (The parameter key for the mean travel time (
mtt) is used in the)and (GUI explicitly. The GUI assumes the parameter is given in years)
it. (internally converts)
- PARAMS = [{'bounds': (1.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}, {'bounds': (0.0001, 10.0), 'default': 1.0, 'key': 'DP', 'label': 'Dispersion Param.'}]¶
- PREFIX = 'dm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
DM impulse response with decay.
The continuous-time DM response (without decay) is
h(τ) = (1/mtt) * 1 / (sqrt(K)) * exp((1 - τ / mtt)^2 / K)withK = 4 pi DP (τ / mtt). We also apply an exponential decay termexp(-λ τ).- Parameters:
- Returns:
Impulse response evaluated at
tau.- Return type:
ndarray
- class PyTracerLab.model.units.EMUnit(mtt: float)[source]¶
Bases:
PyTracerLab.model.units.UnitExponential Model (EM) unit.
- Parameters:
mtt (float) – Mean travel time.
PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Note (The parameter key for the mean travel time (
mtt) is used in the)and (GUI explicitly. The GUI assumes the parameter is given in years)
it. (internally converts)
- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}]¶
- PREFIX = 'em'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
EM impulse response with decay.
The continuous-time EPM response (without decay) is
h(τ) = (1/mtt) * exp(-τ / mtt). We also apply an exponential decay termexp(-λ τ).- Parameters:
- Returns:
Impulse response evaluated at
tau.- Return type:
ndarray
- class PyTracerLab.model.units.EPMUnit(mtt: float, eta: float)[source]¶
Bases:
PyTracerLab.model.units.UnitExponential Piston-Flow Model (EPM) unit.
- Parameters:
mtt (float) – Mean travel time.
eta (float) – Ratio of total volume to the exponential reservoir (>= 1).
eta=1reduces to a pure exponential model;eta>1adds a piston component.PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Note (The parameter key for the mean travel time (
mtt) is used in the)and (GUI explicitly. The GUI assumes the parameter is given in years)
it. (internally converts)
- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}, {'bounds': (1.0, 2.0), 'default': 1.1, 'key': 'eta', 'label': 'Eta'}]¶
- PREFIX = 'epm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
EPM response of each time step (exact integral) with decay.
The continuous-time EPM response (without decay) is
h(τ) = (η/mtt) * exp(-η τ / mtt + η - 1)forτ >= mtt*(1 - 1/η)and0otherwise, i.e. an exponential distribution with rateη/mttshifted by the piston-flow timemtt*(1 - 1/η). Each time step receives the exact integral ofh(τ) exp(-λ τ)over the step.- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If
mttis not positive oretais smaller than 1.
- class PyTracerLab.model.units.ExEPMUnit(mtt: float, exp_part: float, piston_part: float)[source]¶
Bases:
PyTracerLab.model.units.UnitExplicit xponential Piston-Flow Model (EPM) unit. This model is essentially the same as the EPMUnit, but the EPM ratio (total volume / exponential volume or total area / area receiving recharge) is defined via two parameters instead of one aggregated parameter. Those two parameters are directly related and can never be estimated simultaneously.
- Parameters:
mtt (float) – Mean travel time.
exp_part (float) – Area receiving recharge or exponential volume of the system.
piston_part (float) – Area not receiving recharge or piston-flow volume of the system.
PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Note (The parameter key for the mean travel time (
mtt) is used in the)and (GUI explicitly. The GUI assumes the parameter is given in years)
it. (internally converts)
- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}, {'bounds': (0.0, 100.0), 'default': 0.5, 'key': 'exp_part', 'label': 'Exponential Part'}, {'bounds': (0.0, 100.0), 'default': 1.0, 'key': 'piston_part', 'label': 'Piston Part'}]¶
- PREFIX = 'epm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
ExEPM response of each time step (exact integral) with decay.
Same response as
EPMUnitwithη = piston_part / exp_part + 1.- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If
mttorexp_partis not positive orpiston_partis negative.
- class PyTracerLab.model.units.GMUnit(mtt: float, alpha: float)[source]¶
Bases:
PyTracerLab.model.units.UnitGamma Model (GM) unit.
Travel time distribution (Kirchner et al., 2000; Kirchner, 2016, Eq. 2; cf. the general gamma model of Amin and Campana, 1996):
g(τ) = τ^(α-1) exp(-α τ / mtt) / ((mtt / α)^α Γ(α)), τ > 0
with mean
mttand standard deviationmtt / sqrt(α).α = 1gives the exponential model;α < 1gives many short and many long travel times (g is infinite at τ = 0, but integrable);α > 1gives a peaked distribution that approaches piston flow for largeα.- Parameters:
Notes
The response of each time step is the exact integral of the TTD with decay,
G_λ(τ) = (ρ / (ρ + λ))^α P(α, (ρ + λ) τ)withρ = α / mttandPthe regularised lower incomplete gamma function.The parameter key for the mean travel time (
mtt) is used in the GUI explicitly. The GUI assumes the parameter is given in years and internally converts it.- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}, {'bounds': (0.1, 10.0), 'default': 1.0, 'key': 'alpha', 'label': 'Shape Factor'}]¶
- PREFIX = 'gm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
GM response of each time step (exact integral) with decay.
- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If
mttoralphais not positive.
- class PyTracerLab.model.units.LMUnit(mtt: float)[source]¶
Bases:
PyTracerLab.model.units.UnitLinear Model (LM) unit.
Travel time distribution (Maloszewski and Zuber, 1996, Eq. 14; Eriksson, 1958; Maloszewski and Zuber, 1982):
g(τ) = 1 / (2 mtt) for 0 <= τ <= 2 mtt, 0 otherwise,
i.e. travel times are uniformly distributed between 0 and twice the mean travel time (“all the flow lines have the same velocity but linearly increasing flow time”; no mixing between flow lines, the sample is mixed in the spring, stream or well).
- Parameters:
Notes
The response of each time step is the exact integral of the TTD with decay, so it changes smoothly with
mttalso when2 mttfalls between two grid points.The parameter key for the mean travel time (
mtt) is used in the GUI explicitly. The GUI assumes the parameter is given in years and internally converts it.- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}]¶
- PREFIX = 'lm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
LM response of each time step (exact integral) with decay.
- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If
mttis not positive.
- class PyTracerLab.model.units.PEMUnit(mtt: float, above: float, screen: float, below: float)[source]¶
Bases:
PyTracerLab.model.units.UnitPartial Exponential Model (PEM) unit.
A well (or spring) in a homogeneous unconfined aquifer of constant thickness with uniform recharge, which is open only over part of the saturated thickness (Jurgens et al., 2012, Appendix A, Eq. A6; Jurgens et al., 2016). The age of groundwater increases logarithmically with depth, as in the exponential model, and the well samples only the ages between the top and the bottom of the screen:
g(τ) = exp(-τ / τ_aq) / (τ_aq (1/n1 - 1/n2)) for t1 <= τ <= t2,
with
n1 = H / (H - z1),n2 = H / (H - z2),t1 = τ_aq ln n1,t2 = τ_aq ln n2,Hthe saturated thickness,z1andz2the depths of the top and bottom of the screen below the water table, andτ_aqthe mean travel time of the whole aquifer.The geometry is given as three thicknesses in any (common) length unit; only their ratios matter. Like in TracerLPM,
mttis the mean travel time of the sampled water;τ_aqfollows from it (Jurgens et al., 2012, Eq. A4; seemtt_aquifer).Special cases:
above = below = 0gives the exponential model; withbelow = 0(screen reaching the base of the aquifer) the PEM is the model implemented in TracerLPM with “PEM ratio” =above / screenand is identical to the EPM withη = 1 + ln(1 + above / screen)(Jurgens et al., 2012, Eqs. 10 and 12).- Parameters:
mtt (float) – Mean travel time of the sampled water (> 0).
above (float) – Unsampled thickness above the screen, i.e. depth of the top of the screen below the water table (>= 0).
screen (float) – Length of the screen, i.e. sampled thickness (> 0).
below (float) – Unsampled thickness below the screen, i.e. distance from the bottom of the screen to the base of the aquifer (>= 0).
PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Notes
The geometry parameters are registered as fixed when the unit is added to a
Model, because they are normally known from the well construction; free them withModel.set_fixed(key, False).The response of each time step is the exact integral of the TTD with decay.
The parameter key for the mean travel time (
mtt) is used in the GUI explicitly. The GUI assumes the parameter is given in years and internally converts it.- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}, {'bounds': (0.0, 1000.0), 'default': 10.0, 'fixed': True, 'key': 'above', 'label': 'Unsampled Thickness Above Screen'}, {'bounds': (0.01, 1000.0), 'default': 20.0, 'fixed': True, 'key': 'screen', 'label': 'Screen Length'}, {'bounds': (0.0, 1000.0), 'default': 20.0, 'fixed': True, 'key': 'below', 'label': 'Unsampled Thickness Below Screen'}]¶
- PREFIX = 'pem'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
PEM response of each time step (exact integral) with decay.
- Parameters:
- Returns:
Response of each time step on the grid
tau.- Return type:
ndarray
- Raises:
ValueError – If
mttorscreenis not positive, oraboveorbelowis negative.
- property mtt_aquifer: float¶
Mean travel time of the whole aquifer (
τ_aq) for the current parameters.
- class PyTracerLab.model.units.PMUnit(mtt: float)[source]¶
Bases:
PyTracerLab.model.units.UnitPiston-Flow Model (discrete delta at the mean travel time) with decay.
- Parameters:
mtt (float) – Mean travel time where all mass is transported as a plug flow.
PREFIX (str) – Prefix for local parameter names. Helper for GUI.
PARAMS (List[Dict[str, Any]]) – List of (default) parameter definitions. Helper for GUI.
Note (The parameter key for the mean travel time (
mtt) is used in the)and (GUI explicitly. The GUI assumes the parameter is given in years)
it. (internally converts)
- PARAMS = [{'bounds': (0.0, 10000.0), 'default': 10.0, 'key': 'mtt', 'label': 'Mean Travel Time'}]¶
- PREFIX = 'pm'¶
- get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False) numpy.ndarray[source]¶
Discrete delta response on the grid with exponential decay.
The delta is represented by setting the bin at
round(mtt/dt)to1(times the decay factor), which preserves unit mass. Travel times between 0 and 1.5 time steps use the bin1(the input of the previous time step).mtt = 0uses the bin0: water with zero travel time, which has the input concentration of the current time step (e.g. the “piston flow with age 0” component of a binary mixture in TracerLPM).- Parameters:
- Returns:
Impulse response evaluated at
tau.- Return type:
ndarray
- class PyTracerLab.model.units.Unit[source]¶
Bases:
abc.ABCAbstract base class for a model unit.
Concrete units represent hydrological transport schemata and must expose and accept their local parameter values via a mapping. Units are intentionally unaware of optimization bounds; those live in the Model’s parameter registry.
Notes
Implementations must keep local parameter names stable over time so that the Model’s registry stays consistent.
Names should be short (e.g.,
"mtt","eta").
- get_block(h: numpy.ndarray, tau: numpy.ndarray, dt: float, lambda_: float, prod: bool = False, window_mass: float = 1.0) numpy.ndarray[source]¶
Get 1-dt block response.
h(the TTD sampled ontau) is scaled so that its trapezoidal area equalswindow_mass, the share of all travel times that lie withintau(the rest is accounted for by the steady-state input, seetotal_response()).
- abstractmethod get_impulse_response(tau: numpy.ndarray, dt: float, lambda_: float) numpy.ndarray[source]¶
Evaluate the unit’s impulse response on a time grid.
- intrinsic_bounds() Dict[str, Tuple[float, float]][source]¶
Ranges that follow from the definition of the unit’s parameters.
The
Modelregisters them as optimizer bounds if a unit is added without bounds, and rejects bounds outside these ranges. Most units have none (empty mapping);AgeBinUnituses it for its coordinates in[0, 1].
- normalize_response(h: numpy.ndarray, dt: float) numpy.ndarray[source]¶
Normalize impulse response to unit area for conservation of mass.
- report_lines(time_divisor: float = 1.0) List[str][source]¶
Extra lines for
write_report().- Parameters:
time_divisor (float, optional) – Time quantities are divided by this value (e.g.
12to report years for a model in months).
- abstractmethod set_param_values(values: Dict[str, float]) None[source]¶
Set one or more local parameter values.
- total_response(lambda_: float, prod: bool = False) float | None[source]¶
Response summed over all travel times,
0to infinity.The integral of
g(τ) exp(-λτ)(withprod: ofg(τ) (1 - exp(-λτ))) over all travel times. The model uses it for the steady-state input before the start of the input series: at time stepi, water older than the series contributessteady_state_input * (total - sum(h[: i + 1])).Units that do not implement it return
None; for them, the response within the simulation period is taken as complete.