PyTracerLab.model.solver module

Optimization wrapper for Model.

class PyTracerLab.model.solver.Solver(model: PyTracerLab.model.model.Model)[source]

Bases: object

Optimization wrapper for Model.

The solver interacts only with the model’s parameter registry. It constructs a free-parameter vector and corresponding bounds, runs a chosen optimizer, and writes the best solution back to the registry (and thus the Units via write-through).

Notes

Parameters with fixed=True are excluded from optimization but their current values are honored in the simulation. The mixing fraction of a binary mixture is an ordinary bounded parameter (see Model), so all solvers can calibrate it. A warning is issued if there are more free parameters than observations.

Measurement uncertainty. All solver methods accept the measurement uncertainty of the observations as sigma (absolute standard deviation, in the unit of the tracer) and sigma_rel (relative standard deviation as a fraction of the observed value, e.g. 0.05 for 5 %). sigma can be a scalar, one value per tracer, or one value per observation (same shape as the observations, e.g. the uncertainty of a series read with read_series(), with nan where no value is given). For each observation, the standard deviation \(\sigma_i\) is taken from sigma where it is given and is otherwise computed from sigma_rel; an error is raised if an observation is left without a positive standard deviation. The residuals \(r_i\) (simulated minus observed) are weighted by \(1/\sigma_i\): differential evolution minimizes the mean of \((r_i/\sigma_i)^2\), least squares minimizes their sum, and the MCMC samplers use the Gaussian log-likelihood

\[\log L = -\frac{1}{2} \sum_i \left(\frac{r_i}{\sigma_i}\right)^2 - \sum_i \log \sigma_i - \frac{n}{2} \log (2 \pi).\]

If neither sigma nor sigma_rel is given, differential evolution and least squares weight all observations equally, and the MCMC samplers treat the standard deviation of each tracer \(k\) as unknown and marginalize it (Jeffreys prior), which gives \(\log L = -\sum_k \frac{n_k}{2} \log \mathrm{SSE}_k\) with the sum of squared residuals \(\mathrm{SSE}_k\) and the number of observations \(n_k\) of tracer \(k\).

differential_evolution(maxiter: int = 10000, popsize: int = 100, mutation: Tuple[float, float] = (0.5, 1.99), recombination: float = 0.5, tol: float = 0.001, sigma: float | Sequence[float] | numpy.ndarray | None = None, random_state: int | None = None, sigma_rel: float | Sequence[float] | None = None) → Tuple[Dict[str, float], numpy.ndarray][source]

Run differential evolution and return the best solution.

Minimizes the mean of the squared residuals, each divided by the measurement uncertainty of the observation if sigma or sigma_rel is given (see Solver).

Parameters:
  • maxiter (int, optional) – Max iterations in SciPy’s DE.

  • popsize (int, optional) – Population size multiplier.

  • mutation ((float, float), optional) – DE mutation constants.

  • recombination (float, optional) – DE recombination constant.

  • tol (float, optional) – Convergence tolerance.

  • sigma (float | array_like | None, optional) – Measurement uncertainty (standard deviation): scalar, one value per tracer, or one value per observation (e.g. obs.uncertainty, nan where not given). If neither sigma nor sigma_rel is given, all observations are weighted equally.

  • random_state (int | None, optional) – Random seed.

  • sigma_rel (float | array_like | None, optional) – Relative measurement uncertainty as a fraction of the observed value (e.g. 0.05), scalar or one value per tracer. Used for all observations for which sigma gives no value.

Returns:

Mapping from parameter key to optimized value, and the simulated series at that optimum.

Return type:

(dict, ndarray)

dream_sample(n_samples: int, n_chains: int | None = None, burn_in: int = 1000, thin: int = 1, n_diff_pairs: int = 3, cr: float | Sequence[float] = [0.5, 1.0], gamma: float | None = None, gamma_jitter: float = 0.1, jitter: float = 1e-06, sigma: float | Sequence[float] | np.ndarray | None = None, init_state_sigma: float = 1e-06, log_prior: callable | None = None, start: Sequence[float] | np.ndarray | None = None, random_state: int | np.random.Generator | None = None, return_sim: bool = False, set_model_state: bool = True, sigma_rel: float | Sequence[float] | None = None, outlier_check: bool = True)[source]

Basic DREAM sampler.

Uses multiple chains and differential-evolution proposals with crossover/subspace updates. Returns samples after burn-in and thinning.

During burn-in, chains that are caught in a region of low posterior density (e.g. a local optimum) are moved to the current state of the best chain (outlier test of Vrugt et al., 2008, para. 35; see also Vrugt, 2016): at 10 %, 20 %, …, 90 % of the burn-in, the mean log-posterior of each chain over the second half of its history so far is compared with the other chains; chains below Q1 - 2 IQR (first quartile minus twice the interquartile range) are outliers. There is no check in the last tenth of the burn-in, so every moved chain has at least a tenth of the burn-in left before sampling starts (Vrugt et al., 2008, apply another burn-in after an outlier). The test is not applied after burn-in, so the returned samples are not affected by it. It needs at least 4 chains (with 3 chains, no chain can fall below the threshold).

Parameters:
  • n_samples (int) – Number of samples to keep per chain.

  • n_chains (int, optional) – Number of parallel chains (at least 3; at least 4 for the outlier test; at least 2 * n_diff_pairs + 1). Default is max(4, 2 * d, 2 * n_diff_pairs + 1) for d free parameters.

  • burn_in (int, optional) – Number of samples to discard as burn-in.

  • thin (int, optional) – Thinning factor.

  • n_diff_pairs (int, optional) – Number of differential evolution pairs.

  • cr (float | Sequence[float], optional) – Crossover probability (or list of probabilities to sample from).

  • gamma (float | None, optional) – Differential evolution scale. If None, uses 2.38 / sqrt(2 * m), where m is the number of updated dimensions.

  • gamma_jitter (float, optional) – Relative jitter applied to gamma (uniform in +/- gamma_jitter).

  • jitter (float, optional) – Small Gaussian jitter scale relative to bounds.

  • sigma (float | array_like | None, optional) – Measurement uncertainty (standard deviation of the Gaussian likelihood): scalar, one value per tracer, or one value per observation (e.g. obs.uncertainty, nan where not given). If neither sigma nor sigma_rel is given, the standard deviation of each tracer is marginalized (see Solver).

  • init_state_sigma (float, optional) – Standard deviation of the Gaussian noise added to the starting point to ensure all chains are initialized at different points. Has no effect if no starting point is given or if starting points are given for all chains.

  • log_prior (callable | None, optional) – Log prior, if not uniform within bounds.

  • start (Sequence[float] | ndarray | None, optional) – Starting point(s) for chains. If 1D, it is used as a base for all chains with small jitter. If 2D, shape must be (n_chains, d).

  • random_state (int | np.random.Generator | None, optional) – Random seed.

  • return_sim (bool, optional) – Return simulated series at each sample.

  • set_model_state (bool, optional) – Set model state to the posterior median at the end.

  • sigma_rel (float | array_like | None, optional) – Relative measurement uncertainty as a fraction of the observed value (e.g. 0.05), scalar or one value per tracer. Used for all observations for which sigma gives no value.

  • outlier_check (bool, optional) – Move outlier chains to the best chain during burn-in (default True, see above). Has no effect without burn-in.

Returns:

Dictionary with keys: ‘param_names’, ‘samples’, ‘logpost’, ‘accept_rate’, ‘posterior_mean’, ‘posterior_median’, ‘posterior_map’, ‘map_logpost’, ‘gelman_rubin’, ‘n_outlier_resets’ (number of outlier chains moved during burn-in), plus chain-level arrays and [‘sims’ if requested].

Return type:

dict

gelman_rubin(samples: numpy.ndarray) → numpy.ndarray[source]

Compute the Gelman-Rubin statistic for a set of MCMC samples.

Parameters:

samples (array-like) – Array of MCMC samples of shape (n_chains, n_samples, n_params).

Returns:

Gelman-Rubin statistic for each parameter.

Return type:

np.ndarray

least_squares(ftol: float = 1e-08, xtol: float = 1e-08, gtol: float = 1e-08, max_nfev: int = 10000, sigma: float | Sequence[float] | numpy.ndarray | None = None, sigma_rel: float | Sequence[float] | None = None) → Tuple[Dict[str, float], numpy.ndarray][source]

Run gradient-based non-linear least squares and return the best solution.

Uses scipy.optimize.curve_fit() with parameter bounds, i.e., the trust-region reflective algorithm, starting from the initial parameter values. Minimizes the sum of the squared residuals, each divided by the measurement uncertainty of the observation if sigma or sigma_rel is given (see Solver).

Parameters:
  • ftol (float, optional) – Tolerance for termination by the change of the cost function.

  • xtol (float, optional) – Tolerance for termination by the change of the independent variables.

  • gtol (float, optional) – Tolerance for termination by the norm of the gradient.

  • max_nfev (int, optional) – Maximum number of function evaluations.

  • sigma (float | array_like | None, optional) – Measurement uncertainty (standard deviation): scalar, one value per tracer, or one value per observation (e.g. obs.uncertainty, nan where not given). If neither sigma nor sigma_rel is given, all observations are weighted equally.

  • sigma_rel (float | array_like | None, optional) – Relative measurement uncertainty as a fraction of the observed value (e.g. 0.05), scalar or one value per tracer. Used for all observations for which sigma gives no value.

Returns:

Mapping from parameter key to optimized value, and the simulated series at that optimum.

Return type:

(dict, ndarray)

mcmc_sample(n_samples: int, burn_in: int = 1000, thin: int = 1, rw_scale: float = 0.05, rw_scale_isotropic: bool = True, sigma: float | Sequence[float] | np.ndarray | None = None, log_prior: callable | None = None, start: Sequence[float] | None = None, random_state: int | np.random.Generator | None = None, return_sim: bool = False, set_model_state: bool = True, sigma_rel: float | Sequence[float] | None = None)[source]

Random-Walk Metropolis–Hastings over free parameters.

Run Metropolis–Hastings MCMC with a RW proposal distribution for the free parameters. The method only returns effective samples (after burn-in and thinning).

Parameters:
  • n_samples (int) – Number of accepted samples to draw.

  • burn_in (int, optional) – Number of samples to discard as burn-in.

  • thin (int, optional) – Thinning factor.

  • rw_scale (float | Sequence[float], optional) – Variance of RW proposal distribution. If given as a sequence (one scale element for each free parameter in the model), the order of the elements has to match the order from model.param_keys(free_only=True).

  • rw_scale_isotropic (bool, optional) – If True, use an isotropic RW proposal with rw_scale as variance.

  • sigma (float | array_like | None, optional) – Measurement uncertainty (standard deviation of the Gaussian likelihood): scalar, one value per tracer, or one value per observation (e.g. obs.uncertainty, nan where not given). If neither sigma nor sigma_rel is given, the standard deviation of each tracer is marginalized (see Solver).

  • log_prior (callable | None, optional) – Log prior, if not uniform.

  • start (Sequence[float] | None, optional) – Starting point for MCMC.

  • random_state (int | np.random.Generator | None, optional) – Random seed.

  • return_sim (bool, optional) – Return simulated series at each sample.

  • set_model_state (bool, optional) – Set model state to the posterior median at the end.

  • sigma_rel (float | array_like | None, optional) – Relative measurement uncertainty as a fraction of the observed value (e.g. 0.05), scalar or one value per tracer. Used for all observations for which sigma gives no value.

Returns:

Dictionary with keys: ‘param_names’, ‘samples’, ‘logpost’, ‘accept_rate’, ‘posterior_mean’, ‘posterior_map’, ‘map_logpost’, [‘sims’ if requested]

Return type:

dict

model: Model
PyTracerLab.model.solver.available_solvers() → List[Tuple[str, str]][source]

List available solvers.

Returns:

Pairs of registry key and human-readable display name.

Return type:

list of (str, str)

PyTracerLab.model.solver.run_solver(model: PyTracerLab.model.model.Model, key: str, params: Dict[str, Any] | None = None) → Dict[str, object][source]

Run a registered solver and return a standardized payload.

Parameters:
  • model (PyTracerLab.model.model.Model) – Model instance with inputs, targets, and parameter registry.

  • key (str) – Solver registry key (e.g., "de" or "mcmc").

  • params (dict, optional) – Solver-specific keyword parameters.

Returns:

Standardized payload consumed by the GUI, including at minimum the simulated series under the "sim" key; for MCMC also uncertainty envelopes and metadata.

Return type:

dict

Raises:

ValueError – If the solver key is not registered.