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

  • The objective is currently mean squared error against target_series.

  • Parameters with fixed=True are excluded from optimization but their current values are honored in the simulation.

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] | None = None, random_state: int | None = None) Tuple[Dict[str, float], numpy.ndarray][source]

Run differential evolution and return the best solution.

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 | Sequence[float] | None, optional) – Error standard deviation(s) for weighted mean squared error.

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

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] | 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)[source]

Basic DREAM sampler.

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

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

  • n_chains (int, optional) – Number of parallel chains. Default is max(3, 2 * d).

  • 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 | Sequence[float] | None, optional) – Standard deviation(s) of Gaussian likelihood.

  • 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.

Returns:

Dictionary with keys: ‘param_names’, ‘samples’, ‘logpost’, ‘accept_rate’, ‘posterior_mean’, ‘posterior_median’, ‘posterior_map’, ‘map_logpost’, 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] | None = None) Tuple[Dict[str, float], numpy.ndarray][source]

Run non-linear least squares and return the best solution as well as the parameter covariance matrix at the optimum.

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 | Sequence[float] | None, optional) – Standard deviation of error. By default (None), all errors are assumed to have equal magnitude (no relative differences). See the documentation of scipy.optimize.curve_fit for details. If a single float, it is used for all tracers. If a sequence of length equal to the number of tracers, a constant sigma is used for each tracer (all observations). If a sequence of shape (num_obs, num_tracers), a different sigma is used for each observation and each tracer type.

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] | 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)[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 | None, optional) – Standard deviation of Gaussian likelihood.

  • 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.

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.