pybop#
Submodules#
Attributes#
Classes#
Adapter for adaptive moment estimation with weight decay (AdamW), a variant of the Adam |
|
A base class for PyBOP's application methods. |
|
A base class for defining optimisation methods. |
|
A base class for defining optimisation methods from the PINTS library. |
|
Base class for PINTS samplers. |
|
Base class for Monte Carlo samplers. |
|
A base class for defining optimisation methods from the SciPy library. |
|
Base simulator. |
|
Adapter for the covariance matrix adaptation evolution strategy (CMA-ES), an evolutionary |
|
Base class for chain processing. |
|
Adapter for cuckoo search, a population-based optimisation algorithm inspired by the brood |
|
Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm. |
|
Base design cost. |
|
Implements the Differential Evolution Markov Chain Monte Carlo (MCMC) algorithm. |
|
A base class for defining parameter distributions. |
|
Implements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance MCMC algorithm. |
|
A class to hold EP-BOLFI options for the optimisation process. |
|
Wraps the Bayesian Optimization algorithm EP-BOLFI. |
|
Implements the Emcee Hammer Markov Chain Monte Carlo (MCMC) algorithm. |
|
Base fitting cost (error measure). |
|
Represents an exponential distribution with a specified scale parameter. |
|
Exponential decay model defined by the equation: |
|
Exponential fit cost function. |
|
Container for a failed PyBaMM solution that returns [np.inf] for all processed variables. |
|
Container for a failed PyBaMM variable that returns np.inf. |
|
Fit the diffusion timescale of each pulse from a galvanostatic intermittent |
|
Fit the diffusion timescale of one pulse from a galvanostatic intermittent |
|
Represents a Gaussian (normal) distribution with a given mean and standard deviation. |
|
This class represents a Gaussian log-likelihood, which evaluates the log-likelihood under |
|
This class represents a Gaussian log-likelihood with a known sigma, which evaluates the |
|
Adapter for gradient descent, a canonical method that takes steps in the opposite direction |
|
Implements the Haario Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm. |
|
Implements the Haario-Bardenet Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm. |
|
Implements the Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm. |
|
Adapter for improved resilient backpropagation (without weight-backtracking), an optimisation |
|
Adapter for improved resilient backpropagation with weight-backtracking, an optimisation |
|
A class that returns a pybamm.Interpolant to pybamm models and otherwise |
|
A class to find the stoichiometry corresponding to a given open-circuit |
|
Represents a joint distribution composed of multiple distributions. |
|
Base class for likelihoods. |
|
A problem that evaluates the log of an (unnormalised) probability density function. |
|
The log of the proportional posterior, defined as the sum of the log-likelihood and |
|
The log-prior as a cost, to be used with the LogPosterior class. |
|
Records the parameter values and corresponding cost values. |
|
Implements the Metropolis Adjusted Langevin Algorithm (MALA) Markov Chain Monte Carlo (MCMC) algorithm. |
|
Represents a univariate marginal distribution of a pybop.BaseMultivariateDistribution. |
|
Mean absolute error (MAE) cost function. |
|
Mean square error (MSE) cost function. |
|
Problem class for joining mulitple problems into one combined problem. |
|
Implements the Metropolis Random Walk Markov Chain Monte Carlo (MCMC) algorithm. |
|
The Minkowski distance is a generalisation of several distance metrics, |
|
Implements the Monomial Gamma Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm. |
|
Processor for simultaneous chains. |
|
Represents a multivariate Gaussian (normal) distribution with a |
|
Represents a multivariate log-normal distribution with a |
|
Represents a "freeform" distribution, i.e., one that is defined from |
|
Represents a multivariate uniform distribution. |
|
Implements the No-U-Turn Sampler (NUTS) algorithm. |
|
Adpater for the Nelder-Mead downhill simplex method, a deterministic local optimiser that does |
|
Estimate the equilibrium open-circuit potential (OCP) by averaging the charge |
|
Estimate the stoichiometry from a measurement of open-circuit voltage versus |
|
Generate a representative open-circuit potential (OCP) without hysteresis by |
|
A base class for optimiser options. |
|
Adapter for particle swarm optimisation (PSO), a metaheuristic optimisation method inspired by |
|
Represents a parameter within the PyBOP framework. |
|
Container for managing multiple Parameter objects with additional functionality. |
|
A class to hold PINTS options for the optimisation process. |
|
Pints sampler options. |
|
Evaluates a function (or callable object) for multiple positions. |
|
Implements the Population Markov Chain Monte Carlo (MCMC) algorithm. |
|
Base class for defining a problem within the PyBOP framework, compatible with PINTS. |
|
Adapter for random search, a simple algorithm which samples parameter values randomly and |
|
Implements the Rao-Blackwell Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm. |
|
Implements the Relativistic Markov Chain Monte Carlo (MCMC) algorithm. |
|
Stores the result produced by an optimiser or sampler. |
|
Root mean square error (RMSE) cost function. |
|
Adapter for the stochastic natural evolution strategy (SNES), an evolutionary algorithm that |
|
Base options for the sampler. |
|
Evaluates a function (or callable object) for a single input. |
|
Adapter for SciPy's differential_evolution function for global optimisation, useful for problems |
|
Options for the SciPy differential evolution method. |
|
Adapter for various scalar minimisation algorithms implemented in SciPy, allowing fine-tuning |
|
Options for the SciPy minimize method. |
|
Evaluates a function (or callable object) for a list of input values, and |
|
Adapter for simulated annealing, a probabilistic optimisation method inspired by the annealing |
|
Processor for individual chains. |
|
Implements the Slice Doubling Markov Chain Monte Carlo (MCMC) algorithm. |
|
Implements the Slice Rank Shrinking Markov Chain Monte Carlo (MCMC) algorithm. |
|
Implements the Slice Stepout Markov Chain Monte Carlo (MCMC) algorithm. |
|
A class to store simulation results, inspired by pybamm.Solution. |
|
Square-root fit cost function. |
|
The Sum of Power [1] is a generalised cost function based on the p-th power |
|
Sum of squared error (SSE) cost function. |
|
Represents a uniform distribution over a specified interval. |
|
A subclass for constructing a linear combination of cost functions as |
|
Adapter for the exponential natural evolution strategy (XNES), an evolutionary algorithm that |
Functions#
|
Return the class name as a string with spaces before each new capitalised word. |
|
Check if a variable is numeric. |
|
Load data as dictionary from a given file. Restores data saved with |
|
Save data from given data dictionary |
Package Contents#
- class pybop.AdamW(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for adaptive moment estimation with weight decay (AdamW), a variant of the Adam optimiser which does not support boundary constraints.
This optimiser is designed to be more robust and stable for training deep neural networks, particularly when using larger learning rates.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pybop.AdamWImplThe PyBOP implementation this class is based on.
- class pybop.BaseOptimiser(problem: pybop.problems.problem.Problem, options: OptimiserOptions | None = None)[source]#
A base class for defining optimisation methods.
This class serves as a base class for creating optimisers. It provides a basic structure for an optimisation algorithm, including the initial setup and a method stub for performing the optimisation process. Child classes should override _set_up_optimiser and the _run method with a specific algorithm.
- Parameters:
problem (pybop.Problem) – The problem to optimise.
options (pybop.OptimiserOptions , optional) – Options for the optimiser, such as multistart.
- abstractmethod _run() OptimisationResult[source]#
Contains the logic for the optimisation algorithm.
This method should be implemented by child classes to perform the actual optimisation.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- abstractmethod _set_up_optimiser()[source]#
Parse optimiser options and prepare the optimiser.
This method should be implemented by child classes.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- static default_options() OptimiserOptions[source]#
Returns the default options for the optimiser.
- abstractmethod name() str[source]#
Returns the name of the optimiser, to be overwritten by child classes.
- Returns:
The name of the optimiser
- Return type:
str
- run() OptimisationResult[source]#
Run the optimisation and return the optimised parameters and final cost.
- Returns:
result – The pybop optimisation result class.
- Return type:
- _logger = None#
- _multistart = 1#
- _needs_sensitivities = None#
- _options#
- _problem#
- default_max_iterations = 1000#
- property logger: pybop._logging.Logger | None#
- property options: OptimiserOptions#
Returns the options for the optimiser.
- property problem: pybop.problems.problem.Problem#
Returns the optimisation problem object.
- verbose = False#
- verbose_print_rate = 50#
- class pybop.BasePintsOptimiser(problem: pybop.problems.problem.Problem, pints_optimiser: pints.Optimiser, options: PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_optimiser.BaseOptimiserA base class for defining optimisation methods from the PINTS library.
- Parameters:
problem (pybop.Problem) – The problem to minimise.
pints_optimiser (pints.Optimiser) – The PINTS optimiser class to be used.
options (PintsOptions, optional) – Options for the PINTS optimiser. If None, default options are used.
- _run() pybop.optimisers.base_optimiser.OptimisationResult[source]#
Internal method to run the optimisation using a PINTS optimiser.
- Returns:
result – The result of the optimisation including the optimised parameter values and cost.
- Return type:
See also
This
- static default_options() PintsOptions[source]#
Returns the default options for the PINTS optimiser.
- f_guessed_tracking()[source]#
Check if f_guessed instead of f_best is being tracked. Credit: PINTS
- Returns:
True if f_guessed is being tracked, False otherwise.
- Return type:
bool
- set_f_guessed_tracking(use_f_guessed=False)[source]#
Set the method used to track the optimiser progress. Credit: PINTS
- Parameters:
use_f_guessed (bool, optional) – If True, track f_guessed; otherwise, track f_best (default: False).
- set_max_evaluations(evaluations=None)[source]#
Set a maximum number of evaluations stopping criterion. Credit: PINTS
- Parameters:
evaluations (int, optional) – The maximum number of evaluations after which to stop the optimisation (default: None).
- set_max_iterations(iterations: str | int | None = 'default')[source]#
Set the maximum number of iterations as a stopping criterion. Credit: PINTS
- Parameters:
iterations (int, optional) – The maximum number of iterations to run. Set to None to remove this stopping criterion.
- set_max_unchanged_iterations(iterations=15, absolute_tolerance=1e-05, relative_tolerance=0.01)[source]#
Set the maximum number of iterations without significant change as a stopping criterion. Credit: PINTS
- Parameters:
iterations (int, optional) – The maximum number of unchanged iterations to run (default: 15). Set to None to remove this stopping criterion.
absolute_tolerance (float, optional) – The minimum significant change (absolute tolerance) in the objective function value that resets the unchanged iteration counter (default: 1e-5).
relative_tolerance (float, optional) – The minimum significant proportional change (relative tolerance) in the objective function value that resets the unchanged iteration counter (default: 1e-2).
- set_min_iterations(iterations=2)[source]#
Set the minimum number of iterations as a stopping criterion.
- Parameters:
iterations (int, optional) – The minimum number of iterations to run (default: 2). Set to None to remove this stopping criterion.
- set_population_size(population_size=None)[source]#
Set the population size for population-based optimisers, if specified.
- set_threshold(threshold=None)[source]#
Adds a stopping criterion, allowing the routine to halt once the objective function goes below a set
threshold.This criterion is disabled by default, but can be enabled by calling this method with a valid
threshold. To disable it, useset_threshold(None). Credit: PINTS- Parameters:
threshold (float, optional) – The threshold below which the objective function value is considered optimal (default: None).
- _pints_optimiser#
- property evaluator: pybop._evaluation.PopulationEvaluator | pybop._evaluation.SequentialEvaluator#
- property iteration#
- property max_iterations#
Returns the maximum number of iterations for the optimisation.
- property name#
Returns the name of the PINTS optimisation strategy.
- property optimiser: pints.Optimiser#
- class pybop.BasePintsSampler(log_pdf: pybop.problems.log_pdf.LogPDF, sampler: type[pints.SingleChainMCMC | pints.MultiChainMCMC], options: PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BaseSamplerBase class for PINTS samplers.
This class extends the BaseSampler class to provide a common interface for PINTS samplers. The class provides a sample() method that can be used to sample from the posterior distribution using a PINTS sampler.
- Parameters:
log_pdf (pybop.LogPDF) – The negative unnormalised posterior distribution.
sampler (pints.MCMCSampler) – The PINTS sampler to be used for sampling.
options (Optional[PintsSamplerOptions]) – Options for the sampler, by default None.
- _initialise_chain_processor()[source]#
Initialise the appropriate chain processor based on configuration.
- static default_options() PintsSamplerOptions[source]#
Get the default options for the sampler.
- run() numpy.ndarray[source]#
Executes the Monte Carlo sampling process and generates samples from the posterior distribution.
This method orchestrates the entire sampling process, managing iterations, evaluations, logging, and stopping criteria. It initialises the necessary structures, handles both single and multi-chain scenarios, and manages parallel evaluation based on the configuration.
- Returns:
The results including a numpy array containing the samples from the posterior distribution if chains are stored in memory, otherwise None.
- Return type:
- Raises:
ValueError – If no stopping criterion is set (i.e., _max_iterations is None).
Details: –
Checks and ensures at least one stopping criterion is set.
Initialises iterations, evaluations, and other required
structures. - Sets up the parallel evaluator based on the configuration. - Handles the initial phase, if applicable, and manages intermediate steps in the sampling process. - Logs progress and relevant information based on the logging configuration. - Iterates through the sampling process, evaluating the log PDF, updating chains, and managing the stopping criteria. - Finalises and returns the collected samples, or None if chains are not stored in memory.
- _chain_files = None#
- _chains_in_memory = True#
- _evaluation_files = None#
- _initial_phase#
- _initial_phase_iterations = 250#
- _log_filename = None#
- _log_to_screen = True#
- _loop_iters = 0#
- _max_iterations = 500#
- _needs_sensitivities#
- _sampler#
- _single_chain#
- _verbose = False#
- _warm_up = 0#
- property active#
- property chains_in_memory#
- iter_time = 0.0#
- property iteration#
- property max_iterations#
- property n_samples#
- property needs_sensitivities#
- property sampled_logpdf#
- property sampled_prior#
- property samplers#
- property single_chain#
- class pybop.BaseSampler(log_pdf: pybop.problems.log_pdf.LogPDF, options: SamplerOptions | None = None)[source]#
Base class for Monte Carlo samplers.
- Parameters:
log_pdf (pybop.LogPDF) – The negative unnormalised posterior distribution.
options (SamplerOptions, optional) – Options for the sampler. If None, default options are used.
- static default_options() SamplerOptions[source]#
Get the default options for the sampler.
- abstractmethod run() SamplingResult[source]#
Sample from the posterior distribution.
- Returns:
Samples from the posterior distribution.
- Return type:
np.ndarray
- set_initial_phase_iterations(iterations: int = 250)[source]#
Set the number of iterations for the initial phase of the sampler.
- set_max_iterations(iterations: int = 500)[source]#
Set the maximum number of iterations for the sampler.
- set_warm_up_iterations(iterations: int = 250)[source]#
Set the number of warm up iterations for the sampler.
- _cov0#
- _log_pdf#
- _logger = None#
- _mean0#
- _n_parameters#
- _options#
- property cov0: numpy.ndarray#
- property log_pdf: pybop.problems.log_pdf.LogPDF#
- property logger: pybop._logging.Logger | None#
- property mean0: numpy.ndarray#
- property options: SamplerOptions#
- class pybop.BaseSciPyOptimiser(problem: pybop.problems.problem.Problem, options: pybop.optimisers.base_optimiser.OptimiserOptions | None)[source]#
Bases:
pybop.optimisers.base_optimiser.BaseOptimiserA base class for defining optimisation methods from the SciPy library.
- Parameters:
problem (pybop.Problem) – The problem to optimise.
options (pybop.OptimiserOptions) – Valid SciPy option keys and their values.
- class pybop.BaseSimulator(parameters: pybop.parameters.parameter.Parameters | dict | None = None)[source]#
Base simulator.
- get_parameters_from_dict(parameter_values: dict)[source]#
Extract any pybop.Parameter objects and replace with the “[input]” string.
- solve(inputs: Inputs | list[Inputs] | None = None, calculate_sensitivities: bool = False) pybop.simulators.solution.Solution | list[pybop.simulators.solution.Solution][source]#
Returns the output of a simulation for one or more sets of inputs as a dictionary, along with the sensitivities of the output with respect to the input parameters if calculate_sensitivities=True.
- solve_batch(inputs: list[Inputs], calculate_sensitivities: bool = False) list[pybop.simulators.solution.Solution | pybop.simulators.failed_solution.FailedSolution][source]#
Run the simulation for each set of inputs and return dict-like simulation results and (optionally) the sensitivities with respect to each input parameter.
- Parameters:
inputs (list[Inputs]) – A list of input parameters.
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
A list of len(inputs) containing the simulation result(s) and (optionally) the sensitivities with respect to each input parameter.
- Return type:
list[Solution]
- property has_sensitivities#
- parameters = None#
- class pybop.CMAES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for the covariance matrix adaptation evolution strategy (CMA-ES), an evolutionary algorithm for difficult non-linear non-convex optimisation problems.
It adapts the covariance matrix of a multivariate normal distribution to capture the shape of the cost landscape.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.CMAESPINTS implementation of CMA-ES algorithm.
- class pybop.ChainProcessor(mcmc_sampler)[source]#
Base class for chain processing.
This clas architecture implements a strategy-pattern for selection between multi-chain and single-chain samplers as implemented in child classes.
- Parameters:
mcmc_sampler (pybop.BasePintsSampler) – A BasePintsSampler object.
- abstractmethod _extract_log_pdf(fy_value, chain_idx)[source]#
Extract log-pdf for an accepted sample.
- store_samples(values, chain_idx)[source]#
Store samples based on memory configuration. Samples shape: [n_chains, n_iterations, n_parameters]
- update_accepted_sample(chain_idx, y, fy_value)[source]#
Update stored values for an accepted sample.
- sampler#
- class pybop.CuckooSearch(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for cuckoo search, a population-based optimisation algorithm inspired by the brood parasitism of some cuckoo species which is suitable for global optimisation problems.
Cuckoo search is designed to be simple, efficient, and robust. It explores the search space by randomly suggesting candidate “nests” and abandoning poorly performing “nests” throughout the process.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pybop.CuckooSearchImplPyBOP implementation of Cuckoo Search algorithm.
- class pybop.DREAM(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm.
This class wraps the DREAM sampler from the PINTS library. DREAM combines Differential Evolution and Adaptive Metropolis to efficiently explore complex parameter spaces using a population of chains.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.DesignCost(target: str)[source]#
Bases:
pybop.costs.base_cost.BaseCostBase design cost.
Note that design costs are maximised by default. Change to minimising by setting the attribute minimising=True.
- Parameters:
target (str) – The name of the target variable.
- evaluate(solution: pybop.simulators.base_simulator.Solution | pybop.simulators.failed_solution.FailedSolution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float[source]#
Returns the value of the cost variable.
- Parameters:
solution (pybop.Solution | pybamm.Solution) – The simulation result.
inputs (Inputs, optional) – Input parameters (default: None).
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
The value of the output variable.
- Return type:
float
- minimising = False#
- class pybop.DifferentialEvolutionMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Differential Evolution Markov Chain Monte Carlo (MCMC) algorithm.
This class wraps the Differential Evolution MCMC sampler from the PINTS library. Uses a population of chains and differential evolution proposals for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.Distribution(distribution: scipy.stats.distributions.rv_frozen | None = None)[source]#
A base class for defining parameter distributions.
This class provides a foundation for implementing various distributions. It includes methods for calculating the probability density function (PDF), log probability density function (log PDF), and generating random variates from the distribution.
- distribution#
The underlying continuous random variable distribution.
- Type:
scipy.stats.distributions.rv_frozen
- _dlogpdf_dx(x)[source]#
Evaluates the first derivative of the log distribution at x.
Overwrite this function in a subclass to improve upon this generic finite difference approximation.
- Parameters:
x (float) – The point(s) at which to evaluate the first derivative.
- Returns:
The value(s) of the first derivative at x.
- Return type:
float
- cdf(x)[source]#
Calculates the cumulative distribution function (CDF) of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the CDF.
- Returns:
The cumulative distribution function value at x.
- Return type:
float
- icdf(q)[source]#
Calculates the inverse cumulative distribution function (CDF) of the distribution at q.
- Parameters:
q (float) – The point(s) at which to evaluate the inverse CDF.
- Returns:
The inverse cumulative distribution function value at q.
- Return type:
float
- logpdf(x)[source]#
Calculates the logarithm of the probability density function of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the log pdf.
- Returns:
The logarithm of the probability density function value at x.
- Return type:
float
- logpdfS1(x)[source]#
Evaluates the first derivative of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the first derivative.
- Returns:
The value(s) of the first derivative at x.
- Return type:
float
- mean()[source]#
Get the mean of the distribution.
- Returns:
The mean of the distribution.
- Return type:
float
- pdf(x)[source]#
Calculates the probability density function (PDF) of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the pdf.
- Returns:
The probability density function value at x.
- Return type:
float
- rvs(size=1, random_state=None)[source]#
Generates random variates from the distribution.
- Parameters:
size (int) – The number of random variates to generate.
random_state (int, optional) – The random state seed for reproducibility. Default is None.
- Returns:
An array of random variates from the distribution.
- Return type:
array_like
- Raises:
ValueError – If the size parameter is negative.
- std()[source]#
Get the standard deviation of the distribution.
- Returns:
The standard deviation of the distribution.
- Return type:
float
- distribution = None#
- class pybop.DramACMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance MCMC algorithm.
This class wraps the DRAM Adaptive Covariance MCMC sampler from the PINTS library. Combines delayed rejection and adaptive covariance for robust and efficient sampling.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.EPBOLFIOptions[source]#
Bases:
pybop.OptimiserOptionsA class to hold EP-BOLFI options for the optimisation process.
For detailed descriptions of the options, consult the EP-BOLFI documentation at YannickNoelStephanKuhn/EP-BOLFI; you’ll find its PDF attached to the newest release. Note that the variable names have been rewritten for clarity here, so you’ll have to look up their “original” names in the ep_bolfi.EP_BOLFI constructor call within the _set_up_optimiser routine of the pybop.EP_BOLFI class.
- bolfi_initial_sobol_samples: int | None = None#
- bolfi_optimally_acquired_samples: int | None = None#
- bolfi_posterior_effective_sample_size: int | None = None#
- boundaries_in_standard_deviations: int = 0#
- covariance_scaled_mean: numpy.ndarray | None = None#
- covariance_scaled_means_per_feature: numpy.ndarray | None = None#
- ep_iterations: int = 1#
- ep_randomise_feature_order: bool = False#
- ep_stepwise_dampener: float | None = None#
- ep_total_dampening: float | None = None#
- max_posterior_sampling_retries: int = 10#
- model_parameter_boundaries: dict#
- parallel: bool = False#
- posterior_actual_sample_size_increase: float = 1.2#
- posterior_ess_ratio_threshold_evaluation_at_centre: int = -1#
- posterior_ess_ratio_threshold_resampling: int = 5#
- posterior_ess_ratio_threshold_skip_feature: int = -1#
- posterior_gelman_rubin_threshold: float | None = None#
- posterior_model_resample_size_increase: float = 1.1#
- precision_matrices_per_feature: numpy.ndarray | None = None#
- precision_matrix: numpy.ndarray | None = None#
- seed: int = 0#
- class pybop.EP_BOLFI(problem: pybop.Problem, options: EPBOLFIOptions | None = None)[source]#
Bases:
pybop.optimisers.base_optimiser.BaseOptimiserWraps the Bayesian Optimization algorithm EP-BOLFI.
For implementation details and background information, consult the relevant publication at https://doi.org/10.1002/batt.202200374 and visit YannickNoelStephanKuhn/EP-BOLFI.
Note that all properties may and should be given here as PyBOP objects, but will be converted to an ep_bolfi.EP_BOLFI instance upon instantiation of this class. To change attributes, re-init.
Only compatible with MultivariateParameters with a MultivariateGaussian distribution.
- _run() BayesianOptimisationResult[source]#
Contains the logic for the optimisation algorithm.
This method should be implemented by child classes to perform the actual optimisation.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- class pybop.EmceeHammerMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Emcee Hammer Markov Chain Monte Carlo (MCMC) algorithm.
This class wraps the Emcee Hammer MCMC sampler from the PINTS library. The Emcee Hammer is an affine-invariant ensemble sampler, effective for high-dimensional parameter spaces.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.ErrorMeasure(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#
Bases:
pybop.costs.base_cost.BaseCostBase fitting cost (error measure).
This class is intended to be subclassed to create specific cost functions for evaluating model predictions against a set of data. The cost function quantifies the goodness-of-fit between model predictions and the target data, with a lower cost value indicating a better fit.
- Parameters:
dataset (pybop.Dataset) – Dataset object containing the target data.
target (list[str]) – The name(s) of the target variable(s).
weighting (Union[str, np.ndarray], optional) – The type of weighting to use when taking the sum or mean of the error measure.
- dataset#
The dictionary from a Dataset object containing the target data.
- Type:
dictionary
- domain#
The name of the domain (default: “Time [s]”).
- Type:
str
- domain_data#
The domain points in the dataset.
- Type:
np.ndarray
- n_data#
The number of domain points.
- Type:
int
- target_data#
The target values of the output variables.
- Type:
np.ndarray
- abstractmethod __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- evaluate(solution: pybop.simulators.solution.Solution | pybamm.Solution | pybop.simulators.failed_solution.FailedSolution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
solution (pybop.Solution | pybamm.Solution) – The simulation result.
inputs (Inputs, optional) – Input parameters (default: None).
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
If the solution has sensitivities, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- verify_prediction(solution: pybop.simulators.solution.Solution)[source]#
Verify that the prediction matches the target data.
- Parameters:
solution (pybop.Solution | pybamm.Solution) – The simulation result.
- Returns:
True if the prediction matches the target data, otherwise False.
- Return type:
bool
- class pybop.Exponential(scale: float, loc: float = 0)[source]#
Bases:
DistributionRepresents an exponential distribution with a specified scale parameter.
This class provides methods to calculate the pdf, the log pdf, and to generate random variates from the distribution.
- Parameters:
scale (float) – The scale parameter (lambda) of the exponential distribution.
- _dlogpdf_dx(x)[source]#
Evaluates the first derivative of the log exponential distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the first derivative.
- Returns:
The value(s) of the first derivative at x.
- Return type:
float
- _n_parameters = 1#
- loc = 0#
- name = 'Exponential'#
- scale#
- class pybop.ExponentialDecayModel(name: str = 'Experimental Decay Model', n_states: int = 1)[source]#
Bases:
pybamm.models.base_model.BaseModelExponential decay model defined by the equation:
dy/dt = -k * y, y(0) = y0
Note: The output variables are named “y_{i}” for each state. For example, the first state is “y_0”, the second is “y_1”, etc.
The model parameters are “k” (decay rate) and “y0” (initial condition).
- Parameters:
name (str) – Name of the model (default: “Experimental Decay Model”).
n_states (int) – Number of states in the system, must be >= 1 (default is 1).
- property default_parameter_values: pybamm.ParameterValues#
Returns the default parameter values for the model (an empty set of parameters by default).
- property default_quick_plot_variables#
Returns the default variables for quick plotting (None by default).
- initial_conditions#
Returns a dictionary mapping expressions (variables) to expressions that represent the initial conditions for the state variables.
- n_states = 1#
- rhs#
Returns a dictionary mapping expressions (variables) to expressions that represent the right-hand side (RHS) of the model’s differential equations.
- variables#
Returns a dictionary mapping strings to expressions representing the model’s useful variables.
- class pybop.ExponentialFeatureDistance(domain_data: numpy.ndarray, target_data: numpy.ndarray, feature: str = 'inverse_timescale', time_start: float = None, time_end: float = None)[source]#
Bases:
FeatureDistanceExponential fit cost function.
Fits an exponential and compares either its asymptote, its magnitude, or its timescale between model predictions and target data.
- _supported_features = ['asymptote', 'magnitude', 'timescale', 'inverse_timescale']#
- class pybop.FailedSolution(variable_names: list[str], parameter_names: list[str])[source]#
Container for a failed PyBaMM solution that returns [np.inf] for all processed variables.
This class mimics the interface of a successful PyBaMM solution but returns infinity values to indicate failure while maintaining API compatibility.
- Parameters:
variable_names – List of variable names in the solution
parameter_names – List of parameter names for sensitivity analysis
Example
>>> solution = FailedSolution(["Voltage [V]"], ["Negative particle radius [m]"]) >>> voltage = solution["Voltage [V]"] >>> print(voltage.data) # np.ndarray([inf])
- _validate_inputs(variable_names: list[str], parameter_names: list[str] | None) None[source]#
Validate constructor inputs.
- items() list[tuple[str, FailedVariable]][source]#
Get all variable name-value pairs.
- values() list[FailedVariable][source]#
Get all variables.
- _parameter_names#
- _t_eval: numpy.ndarray#
- _variable_names#
- _variables: dict[str, FailedVariable]#
- cycles: int | None = None#
- integration_time: float = 0.0#
- property parameter_names: list[str]#
Get list of parameter names (read-only).
- solve_time: float = 0.0#
- property t_eval: numpy.ndarray#
Time evaluation points (returns [inf] for failed solutions).
- termination: str = 'failure'#
- property variable_names: list[str]#
Get list of variable names (read-only).
- class pybop.FailedVariable[source]#
Container for a failed PyBaMM variable that returns np.inf.
- Parameters:
name – Variable name
data – Array data, defaults to [np.inf]
sensitivities – Sensitivity data mapping parameter names to arrays
- data: numpy.ndarray#
- name: str#
- sensitivities: dict[str, numpy.ndarray]#
- class pybop.GITTFit(gitt_dataset: pybop.Dataset, pulse_index: list[numpy.ndarray], parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#
Bases:
pybop.BaseApplicationFit the diffusion timescale of each pulse from a galvanostatic intermittent titration technique (GITT) measurement.
- Parameters:
gitt_dataset (pybop.Dataset) – A dataset containing the “Time [s]”, “Current [A]” and “Voltage [V]” for a GITT measurement.
pulse_index (list[np.ndarray]) – A nested list of integers representing the indices of each pulse in the dataset.
parameter_values (pybamm.ParameterValues) – A parameter set containing values for the parameters of the SPDiffusion model.
cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).
optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).
optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.
- cost#
- gitt_dataset#
- inverse_ocp#
- optimiser#
- optimiser_options#
- pulse_fit#
- pulse_index#
- class pybop.GITTPulseFit(parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#
Bases:
pybop.BaseApplicationFit the diffusion timescale of one pulse from a galvanostatic intermittent titration technique (GITT) measurement using the diffusion model for a single, spherical particle representing one electrode.
The cost function requires a “domain”-based weighting to fit (possibly non-uniform) data consistently across the observed time period.
- Parameters:
parameter_values (pybamm.ParameterValues) – A parameter set containing values for the parameters of the SPDiffusion model.
cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).
optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).
optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.
- __call__(gitt_pulse: pybop.Dataset, initial_parameter_values: dict[str, float] | None = None) pybop.Result[source]#
- cost#
- model#
- optimiser#
- optimiser_options#
- parameter_values#
- parameters#
- problem = None#
- class pybop.Gaussian(mean, sigma, truncated_at: list[float] = None)[source]#
Bases:
DistributionRepresents a Gaussian (normal) distribution with a given mean and standard deviation.
This class provides methods to calculate the probability density function (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.
- Parameters:
mean (float) – The mean (mu) of the Gaussian distribution.
sigma (float) – The standard deviation (sigma) of the Gaussian distribution.
- _dlogpdf_dx(x)[source]#
Evaluates the first derivative of the log Gaussian distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the first derivative.
- Returns:
The value(s) of the first derivative at x.
- Return type:
float
- _n_parameters = 1#
- loc#
- name = 'Gaussian'#
- scale#
- class pybop.GaussianLogLikelihood(dataset: pybop.processing.dataset.Dataset, sigma: float | list[float] | list[pybop.parameters.parameter.Parameter] = 0.01, target: str | list[str] = None)[source]#
Bases:
LogLikelihoodThis class represents a Gaussian log-likelihood, which evaluates the log-likelihood under the assumption that measurement noise on the target data follows a Gaussian distribution.
This class estimates the standard deviation of the Gaussian distribution alongside the parameters of the model.
- _logpi#
Precomputed offset value for the log-likelihood function.
- Type:
float
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Compute the Gaussian log-likelihood for the given parameters.
- set_sigma(sigma: float | list[float] | list[pybop.parameters.parameter.Parameter])[source]#
Set the noise variance (sigma) after checking its validity.
- _logpi#
- class pybop.GaussianLogLikelihoodKnownSigma(dataset: pybop.processing.dataset.Dataset, sigma: list[float] | float, target: str | list[str] = None)[source]#
Bases:
LogLikelihoodThis class represents a Gaussian log-likelihood with a known sigma, which evaluates the log-likelihood under the assumption that measurement noise on the target data follows a Gaussian distribution.
- Parameters:
sigma (scalar or array) – Initial standard deviation around
x0. Either a scalar value (one standard deviation for all coordinates) or an array with one entry per dimension.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Compute the Gaussian log-likelihood for the given parameters with known sigma.
- class pybop.GradientDescent(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for gradient descent, a canonical method that takes steps in the opposite direction of the cost gradient with respect to the parameters (does not support boundary constraints).
Gradient descent is designed to minimise a scalar function of one or more variables. Due to the fixed step-size, the convergence rate commonly decreases as the gradient shrinks when approaching a local minima.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.GradientDescentThe PINTS implementation this class is based on.
- class pybop.HaarioACMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Haario Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Haario Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method adapts the proposal distribution’s covariance matrix based on the history of the chain, improving sampling efficiency and convergence.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.HaarioBardenetACMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Haario-Bardenet Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Haario-Bardenet Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method combines the adaptive covariance approach with an additional mechanism to improve performance in high-dimensional parameter spaces.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.HamiltonianMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Hamiltonian MCMC sampler from the PINTS library. This MCMC method uses Hamiltonian dynamics to propose new states, allowing for efficient exploration of high-dimensional parameter spaces.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.IRPropMin(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for improved resilient backpropagation (without weight-backtracking), an optimisation algorithm designed to handle problems with large plateaus, noisy gradients, and local minima.
This method uses gradient information for the proposal direction with a separated step-size.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.IRPropMinThe PINTS implementation this class is based on.
- class pybop.IRPropPlus(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for improved resilient backpropagation with weight-backtracking, an optimisation algorithm designed to handle problems with large plateaus, noisy gradients, and local minima.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.IRPropMinThe PINTS implementation this class is based on.
- class pybop.Interpolant(x: numpy.ndarray, y: numpy.ndarray, name: str | None = None, bounds_error: bool = False, fill_value: str | float = 'extrapolate', axis: int = 0)[source]#
A class that returns a pybamm.Interpolant to pybamm models and otherwise a numeric interpolant.
- Parameters:
x (array_like) – Input coordinates.
y (array_like) – Output values corresponding to x.
name (str, optional) – Name for the interpolant when used in PyBaMM.
bounds_error (bool, optional) – If True, raise error when interpolating outside bounds.
fill_value (str or float, optional) – Value to use for out-of-bounds interpolation.
axis (int, optional) – Axis along which to interpolate.
- __call__(x: float | numpy.ndarray)[source]#
Evaluate the interpolant at given points.
- Parameters:
x (float or array_like) – Points at which to evaluate the interpolant.
- Returns:
Interpolated values or PyBaMM interpolant object.
- Return type:
float, array_like, or pybamm.Interpolant
- _create_interpolant(bounds_error: bool, fill_value: str | float, axis: int)[source]#
Create the scipy interpolation function.
- _interp_func#
- name = None#
- x#
- y#
- class pybop.InverseOCV(ocv_function: collections.abc.Callable, optimiser: BaseOptimiser | None = None, optimiser_options: OptimiserOptions | None = None)[source]#
A class to find the stoichiometry corresponding to a given open-circuit voltage.
- Parameters:
ocv_function (Callable) – The open-circuit voltage as a function of stoichiometry.
optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).
optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.
- __call__(ocv_value: float) float[source]#
Estimate and return the stoichiometry.
- Parameters:
ocv_value (float) – The open-circuit voltage value [V] for which to estimate the stoichiometry.
- Returns:
The stoichiometry corresponding to the open-circuit voltage value.
- Return type:
float
- cost#
- ocv_root#
- optimiser#
- optimiser_options#
- class pybop.JointDistribution(*distributions: Distribution | scipy.stats.distributions.rv_frozen)[source]#
Bases:
DistributionRepresents a joint distribution composed of multiple distributions.
- Parameters:
distributions (Distribution) – One or more distributions to combine into a joint distribution.
- logpdf(x: float | numpy.ndarray) float[source]#
Evaluates the log of the joint distribution at a given point.
- Parameters:
x (float | np.ndarray) – The point(s) at which to evaluate the distribution. The length of x should match the total number of parameters in the joint distribution.
- Returns:
The joint log-probability density of the distribution at x.
- Return type:
float
- logpdfS1(x: float | numpy.ndarray) tuple[float, numpy.ndarray][source]#
Evaluates the first derivative of the log of the joint distribution at a given point.
- Parameters:
x (float | np.ndarray) – The point(s) at which to evaluate the first derivative. The length of x should match the total number of parameters in the joint distribution.
- Returns:
A tuple containing the log-probability density and its first derivative at x.
- Return type:
Tuple[float, np.ndarray]
- _distributions_list: list[Distribution]#
- _n_parameters = 0#
- class pybop.LogLikelihood(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None)[source]#
Bases:
pybop.costs.error_measures.ErrorMeasureBase class for likelihoods.
Exists to distinguish between error measures and likelihood-based costs.
- abstractmethod set_sigma(sigma: numpy.ndarray | float, n_outputs: int, n_data: int)[source]#
Set the noise variance (sigma) after checking its validity.
- minimising = False#
- parameters#
- sigma = None#
- class pybop.LogPDF(simulator: pybop.simulators.base_simulator.BaseSimulator, cost: pybop.costs.log_likelihoods.LogLikelihood)[source]#
Bases:
pybop.problems.problem.ProblemA problem that evaluates the log of an (unnormalised) probability density function.
- class pybop.LogPosterior(simulator: pybop.simulators.base_simulator.BaseSimulator, cost: pybop.costs.log_likelihoods.LogLikelihood)[source]#
Bases:
LogPDFThe log of the proportional posterior, defined as the sum of the log-likelihood and the log-prior.
- _cost#
- log_likelihood#
- log_prior#
- class pybop.LogPrior(parameters)[source]#
Bases:
BaseCostThe log-prior as a cost, to be used with the LogPosterior class.
- evaluate(solution: pybop.simulators.solution.Solution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#
Computes the log-prior for the given inputs, and optionally the sensitivities.
- minimising = False#
- parameters#
- class pybop.Logger(minimising: bool, verbose: bool = False, verbose_print_rate: int = 50)[source]#
Records the parameter values and corresponding cost values.
- Parameters:
verbose (bool) – If True, the optimisation progress and results are printed.
verbose_print_rate (int) – The distance between iterations to print verbose output.
iteration (int) – The current iteration number.
x_model (list[np.ndarray]) – The history of model parameters.
x_search (list[np.ndarray]) – The history of search parameters.
cost (list[float]) – The history of the cost value.
iteration_number (list[int]) – The history of the iteration number.
evaluations (int) – The current number of evaluations.
x_model_best (list[np.ndarray]) – The current best model parameters.
cost_best (list[float]) – The current best cost value.
- extend_log(x_model: list[numpy.ndarray], x_search: list[numpy.ndarray], cost: list[float])[source]#
Update the log with new values.
- Parameters:
x_model (list[np.ndarray]) – The model parameters.
x_search (list[np.ndarray]) – The search parameters.
cost (list[float]) – The cost associated with the parameters.
- _minimising#
- property cost_convergence#
Get the convergence of the cost during the optimisation.
- iteration = None#
- verbose = False#
- verbose_print_rate = 50#
- property x0#
Get the initial parameter values.
- class pybop.MALAMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Metropolis Adjusted Langevin Algorithm (MALA) Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the MALA MCMC sampler from the PINTS library. This MCMC method combines the Metropolis-Hastings algorithm with Langevin dynamics to improve sampling efficiency and convergence.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.MarginalDistribution(parent_distribution: BaseMultivariateDistribution, position: int)[source]#
Bases:
pybop.parameters.distributions.DistributionRepresents a univariate marginal distribution of a pybop.BaseMultivariateDistribution. Relies on the “marginal” method of the multivariate distribution.
Sub-class of pybop.Distribution with the additional properties “parent_distribution” and “position”
- Parameters:
parent_distribution (pybop.BaseMultivariateDistribution) – A multivariate distribution
position (int) – position of the parameter for which to create the marginal distribution
- mean()[source]#
Get the mean of the distribution.
- Returns:
The mean of the distribution.
- Return type:
float
- std()[source]#
Get the standard deviation of the distribution.
- Returns:
The standard deviation of the distribution.
- Return type:
float
- _position#
- parent_distribution#
- property position#
- class pybop.MeanAbsoluteError(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureMean absolute error (MAE) cost function.
Computes the mean absolute error (MAE) between model predictions and target data. The MAE is a measure of the average magnitude of errors in a set of predictions, without considering their direction.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- class pybop.MeanSquaredError(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureMean square error (MSE) cost function.
Computes the mean square error between model predictions and the target data, providing a measure of the differences between predicted values and observed values.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- class pybop.MetaProblem(*problems, weights: list[float] | None = None)[source]#
Bases:
pybop.problems.problem.ProblemProblem class for joining mulitple problems into one combined problem.
Evaluates multiple problems, which must first be defined individually.
- Parameters:
problems (pybop.Problem) – The individual PyBOP fitting problems.
- evaluate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool) numpy.ndarray | tuple[numpy.ndarray, numpy.ndarray][source]#
Evaluate each problem for each set of inputs and return the cost values and (optionally) the sensitivities with respect to each input parameter.
- Parameters:
inputs (list[Inputs]) – A list of input parameters.
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
Cost values of len(inputs) and (optionally) the gradient of the cost with respect to each input parameter with shape (len(inputs), len(parameters)).
- Return type:
- get_problem_inputs(inputs: pybop.parameters.parameter.Inputs, i: int)[source]#
- _has_sensitivities = True#
- _parameters#
- property has_sensitivities#
- problems#
- class pybop.MetropolisRandomWalkMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Metropolis Random Walk Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Metropolis Random Walk MCMC sampler from the PINTS library. This classic MCMC method uses a simple random walk proposal distribution and the Metropolis-Hastings acceptance criterion.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.Minkowski(dataset: pybop.processing.dataset.Dataset, p: float = 2.0, target: str | list[str] = None, weighting: str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureThe Minkowski distance is a generalisation of several distance metrics, including the Euclidean and Manhattan distances. It is defined as:
\[L_p(x, y) = ( \sum_i |x_i - y_i|^p )^(1/p)\]where p > 0 is the order of the Minkowski distance. For p ≥ 1, the Minkowski distance is a metric. For 0 < p < 1, it is not a metric, as it does not satisfy the triangle inequality, although a metric can be obtained by removing the (1/p) exponent.
Special cases:
p = 1: Manhattan distance
p = 2: Euclidean distance
p → ∞: Chebyshev distance (not implemented as yet)
This class implements the Minkowski distance as a cost function for optimisation problems, allowing for flexible distance-based optimisation across various problem domains.
Additional Attributes#
- pfloat, optional
The order of the Minkowski distance.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- property __name__#
- p#
- class pybop.MonomialGammaHamiltonianMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Monomial Gamma Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Monomial Gamma Hamiltonian MCMC sampler from the PINTS library. This MCMC method uses Hamiltonian dynamics with a monomial gamma distribution for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.MultiChainProcessor(mcmc_sampler)[source]#
Bases:
ChainProcessorProcessor for simultaneous chains.
- class pybop.MultivariateGaussian(mean=None, covariance=None, bounds=None, random_state=None)[source]#
Bases:
BaseMultivariateDistributionRepresents a multivariate Gaussian (normal) distribution with a given mean and covariance.
This class provides methods to calculate the probability density function (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.
- Parameters:
mean (numpy.ndarray) – The mean (µ) of the multivariate Gaussian distribution.
covariance (numpy.ndarray) – The covariance matrix (Σ) of the multivariate Gaussian distribution. Note that what is called σ in 1D would be the square root of Σ here.
bounds (numpy.ndarray) – Lower and upper bounds (2nd dim) of the parameters (1st dim).
- marginal(position)[source]#
Return univariate marginal distribution of parameter with index ‘position’
- _n_parameters#
- property compatible_transformations#
- property mean#
Get the mean of the distribution.
- Returns:
The mean of the distribution.
- Return type:
float
- name = 'MultivariateGaussian'#
- properties#
- property sigma#
- sigma2 = None#
- class pybop.MultivariateLogNormal(mean_log_x=None, covariance_log_x=None)[source]#
Bases:
BaseMultivariateDistributionRepresents a multivariate log-normal distribution with a given mean and covariance of the normally distributed log(x).
This class provides methods to calculate the probability density function (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.
- Parameters:
mean_log_x (numpy.ndarray) – The mean (µ) of the multivariate Gaussian distribution of log(x).
covariance_log_x (numpy.ndarray) – The covariance matrix (Σ) of the multivariate Gaussian distribution of log(x). Note that what is called σ in 1D would be the square root of Σ here.
- _get_covariance_and_mean()[source]#
Method to compute the covariance and mean in the model space based on the covariance and mean of log(x) (i.e. in the search space)
- cdf(x)[source]#
Calculates the cumulative distribution function (CDF) of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the CDF.
- Returns:
The cumulative distribution function value at x.
- Return type:
float
- logpdf(x)[source]#
Calculates the logarithm of the probability density function of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the log pdf.
- Returns:
The logarithm of the probability density function value at x.
- Return type:
float
- marginal(position)[source]#
Return univariate marginal distribution of parameter with index ‘position’
- pdf(x)[source]#
Calculates the probability density function (PDF) of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the pdf.
- Returns:
The probability density function value at x.
- Return type:
float
- rvs(size=1, random_state=None)[source]#
Generates random variates from the distribution.
- Parameters:
size (int) – The number of random variates to generate.
random_state (int, optional) – The random state seed for reproducibility. Default is None.
- Returns:
An array of random variates from the distribution.
- Return type:
array_like
- Raises:
ValueError – If the size parameter is negative.
- _n_parameters#
- property compatible_transformations#
- distribution_log_x#
- name = 'MultivariateLogNormal'#
- properties#
- properties_log_x#
- sigma2#
- class pybop.MultivariateNonparametric(samples, random_state=None)[source]#
Bases:
BaseMultivariateDistributionRepresents a “freeform” distribution, i.e., one that is defined from a random sampling and a kernel density estimate on that sampling.
This class provides methods to calculate the probability density function (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.
- Parameters:
samples (numpy.ndarray) – The random variates to base the distribution on.
- logpdf(x)[source]#
Calculates the logarithm of the probability density function of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the log pdf.
- Returns:
The logarithm of the probability density function value at x.
- Return type:
float
- marginal(position)[source]#
Return univariate marginal distribution of parameter with index ‘position’
- pdf(x)[source]#
Calculates the probability density function (PDF) of the distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the pdf.
- Returns:
The probability density function value at x.
- Return type:
float
- rvs(size=1, random_state=None)[source]#
Generates random variates from the distribution.
- Parameters:
size (int) – The number of random variates to generate.
random_state (int, optional) – The random state seed for reproducibility. Default is None.
- Returns:
An array of random variates from the distribution.
- Return type:
array_like
- Raises:
ValueError – If the size parameter is negative.
- _n_parameters#
- property compatible_transformations#
- name = 'MultivariateNonparametric'#
- properties#
- class pybop.MultivariateUniform(bounds, random_state=None)[source]#
Bases:
BaseMultivariateDistributionRepresents a multivariate uniform distribution.
This class provides methods to calculate the probability density fuction (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.
- Parameters:
bounds (numpy.ndarray) – The lower and upper bounds for the uniform distribution.
- marginal(position)[source]#
Return univariate marginal distribution of parameter with index ‘position’
- _n_parameters#
- property compatible_transformations#
- name = 'MultivariateUniform'#
- properties#
- class pybop.NUTS(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the No-U-Turn Sampler (NUTS) algorithm.
This class wraps the NUTS sampler from the PINTS library. NUTS is a Markov chain Monte Carlo (MCMC) method for sampling from a probability distribution, extending Hamiltonian Monte Carlo with an adaptive integration time for efficient exploration.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.NelderMead(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdpater for the Nelder-Mead downhill simplex method, a deterministic local optimiser that does not use gradient information or support boundary constraints.
In most update steps, it performs either one evaluation, or two sequential evaluations, so that it will not typically benefit from parallelisation.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.NelderMeadPINTS implementation of Nelder-Mead algorithm.
- class pybop.OCPAverage(ocp_discharge: pybop.Dataset, ocp_charge: pybop.Dataset, n_sto_points: int = 101, allow_stretching: bool = True, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#
Bases:
pybop.BaseApplicationEstimate the equilibrium open-circuit potential (OCP) by averaging the charge and discharge branches, using a method loosely based on method 4(a) proposed by Lu et al. (2021) available at: https://doi.org/10.1149/1945-7111/ac11a5
- Parameters:
ocp_discharge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a discharge measurement.
ocp_charge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a charge measurement.
n_sto_points (int, optional) – The number of points in stoichiometry at which to calculate the voltage.
allow_stretching (bool, optional) – If True, the OCPs are allowed to stretch as well as shift with respect to the stoichiometry (default: True)
cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).
optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).
optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.
- allow_stretching = True#
- cost#
- differential_capacity_interpolant#
- n_sto_points = 101#
- ocp_charge#
- ocp_discharge#
- optimiser#
- optimiser_options#
- class pybop.OCPCapacityToStoichiometry(ocv_dataset: pybop.Dataset, ocv_function: collections.abc.Callable, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#
Bases:
pybop.BaseApplicationEstimate the stoichiometry from a measurement of open-circuit voltage versus charge capacity.
- Parameters:
ocv_dataset (pybop.Dataset) – A dataset containing the “Charge capacity [A.h]” and “Voltage [V]” obtained from an OCV measurement.
ocv_function (Callable) – The open-circuit voltage as a function of stoichiometry.
cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).
optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).
optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.
- cost#
- ocv_dataset#
- ocv_function#
- optimiser#
- optimiser_options#
- class pybop.OCPMerge(ocp_discharge: pybop.Dataset, ocp_charge: pybop.Dataset, n_sto_points: int = 101)[source]#
Bases:
pybop.BaseApplicationGenerate a representative open-circuit potential (OCP) without hysteresis by merging the provided charge and discharge branches of the OCP.
- Parameters:
ocp_discharge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a discharge measurement.
ocp_charge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a charge measurement.
n_sto_points (int, optional) – The number of points in stoichiometry at which to calculate the voltage.
- n_sto_points = 101#
- ocp_charge#
- ocp_discharge#
- class pybop.OptimiserOptions[source]#
A base class for optimiser options.
- multistart#
Number of times to multistart the optimiser.
- Type:
int
- verbose#
The verbosity level.
- Type:
bool
- verbose_print_rate#
The distance between iterations to print verbose output.
- Type:
int
- multistart: int = 1#
- verbose: bool = False#
- verbose_print_rate: int = 50#
- class pybop.PSO(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for particle swarm optimisation (PSO), a metaheuristic optimisation method inspired by the social behavior of birds flocking or fish schooling, suitable for global optimisation problems.
The method considers “particles” moving around the search space. Global optima convergence is guaranteed in the infinite limit for the number of optimiser iterations.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.PSOThe PINTS implementation this class is based on.
- class pybop.Parameter(distribution: scipy.stats.distributions.rv_frozen | pybop.parameters.distributions.Distribution | None = None, bounds: BoundsPair | None = None, initial_value: float = None, transformation: pybop.transformation.base_transformation.Transformation | None = None)[source]#
Represents a parameter within the PyBOP framework.
This class encapsulates the definition of a parameter, including its initial value, bounds.
- Parameters:
distribution (stats.distribution.rv_frozen | Distribution, optional) – Distribution of the parameter
bounds (tuple[float, float], optional) – Parameter bounds as (lower, upper)
initial_value (NumericValue, optional) – Initial parameter value
transformation (Transformation, optional) – Parameter transformation
- __call__(*unused_args, **unused_kwargs) float | None[source]#
Return the initial value. The unused arguments are to pass pybamm.ParameterValues checks.
- _check_compatible_transformation() None[source]#
Raise an error if the transformation is not compatible with the distribution.
- _validate_initial_value_within_bounds() None[source]#
Validate that the initial value is within the bounds.
- get_initial_value(transformed: bool = False) numpy.typing.NDArray | None[source]#
Get initial value in either the model space or the transformed search space.
- sample_from_distribution(n_samples: int = 1, *, random_state: int | None = None, transformed: bool = False) numpy.typing.NDArray[numpy.floating] | None[source]#
Sample from parameter’s distribution.
- Parameters:
n_samples (int) – Number of samples to draw (default: 1).
random_state (int, optional) – Random seed for reproducibility.
transformed (bool, optional) – Whether to apply transformation to samples (default: False).
- Returns:
Array of samples, or None if no distribution exists exists
- Return type:
NDArray[np.floating] or None
- update_initial_value(value: NumericValue | None) None[source]#
Update the initial parameter value.
- _bounds = None#
- _distribution = None#
- _initial_value = None#
- _transformation#
- property bounds: tuple | None#
Parameter bounds as (lower, upper) tuple.
- property distribution: Any | None#
- property initial_value: float | None#
- property transformation: pybop.transformation.base_transformation.Transformation#
- class pybop.Parameters(parameters: dict | Parameters | None = None)[source]#
Container for managing multiple Parameter objects with additional functionality.
This class provides a comprehensive interface for parameter management including validation, transformation, serialisation, and bulk operations.
- _add(name: str, parameter: Parameter, update_transform: bool = True, update_distribution: bool = True) None[source]#
Internal method to add a parameter to the collection.
- Parameters:
name (str) – Name of the parameter.
parameter (pybop.Parameter) – The parameter to add.
update_transform (bool, optional) – Whether to update the transformation after adding (default: True).
update_distribution (bool, optional) – Whether to update the joint or multivariate distribution (default: True).
- _bulk_update_initial_values(values: ArrayLike | Inputs) None[source]#
Update initial values in bulk.
- add(name: str, parameter: Parameter, update_distribution: bool = True) None[source]#
Add a parameter to the collection.
- construct_transformation() pybop.transformation.base_transformation.Transformation[source]#
Create a ComposedTransformation object from the individual parameter transformations.
- convert_grad_to_array(grad: dict[str, numpy.ndarray]) numpy.ndarray[source]#
Get an array of sensitivities with the parameters in the expected order.
- copy() Parameters[source]#
Create a deep copy of the Parameters object.
- get_bounds(transformed: bool = False) dict[source]#
Get bounds for each parameter as a dictionary.
- Parameters:
transformed (bool) – If True, the transformation is applied to the output (default: False).
- get_bounds_array(transformed: bool = False) numpy.ndarray[source]#
Retrieve parameter bounds in numpy format.
- Returns:
bounds – An array of shape (n_parameters, 2) containing the bounds for each parameter.
- Return type:
numpy.ndarray
- get_bounds_for_plotly(transformed: bool = False) numpy.ndarray[source]#
Retrieve parameter bounds in the format expected by Plotly.
- Returns:
bounds – An array of shape (n_parameters, 2) containing the bounds for each parameter.
- Return type:
numpy.ndarray
- get_covariance(transformed: bool = False)[source]#
Get the covariance matrix, or an estimate of it.
- Parameters:
transformed (bool, optional) – If True, the transformation is applied to the output (default: False).
- get_initial_values(*, transformed: bool = False) numpy.typing.NDArray[numpy.floating][source]#
Get initial values as array.
- Parameters:
transformed (bool, default=False) – Whether to apply transformations to bounds
- Returns:
Array of initial values
- Return type:
NDArray[np.floating]
- get_mean(transformed: bool = False)[source]#
Get the mean of each parameter, or its initial value.
- Parameters:
transformed (bool, optional) – If True, the transformation is applied to the output (default: False).
- get_std(transformed: bool = False) list[source]#
Get the standard deviation, or an estimate of it, for each parameter.
- Parameters:
transformed (bool, optional) – If True, the transformation is applied to the output (default: False).
- items() collections.abc.Iterator[tuple[str, Parameter]][source]#
Iterate over (name, parameter) pairs.
- join(parameters=None)[source]#
Join two Parameters objects into the first by copying across each Parameter.
- Parameters:
parameters (pybop.Parameters)
- sample_from_distribution(n_samples: int = 1, *, random_state: int | None = None, transformed: bool = False) numpy.typing.NDArray[numpy.floating] | None[source]#
Sample from a joint or multivariate distribution.
- Parameters:
n_samples (int) – The number of samples to draw (default: 1).
random_state (int, optional) – The random state seed for reproducibility (default: None).
transformed (bool, optional) – If True, the transformation is applied to the output (default: False).
- Returns:
Array of shape (n_samples, n_parameters) or None if any distribution is missing
- Return type:
NDArray[np.floating] or None
- set(name: str, param: Parameter, update_distribution: bool = True) None[source]#
Set a parameter by name.
- to_dict(values: str | ArrayLike | None = None) Inputs[source]#
Return values as a dictionary of inputs.
- Parameters:
values (str or array-like, optional) – Which values to use (‘initial’) or custom array. Default is “initial”.
- Returns:
Dictionary mapping parameter names to values
- Return type:
- to_inputs_list(values: numpy.ndarray | list[numpy.ndarray]) list[Inputs][source]#
Return parameter values as a list of dictionaries, as required for multiprocessing.
- update(*, initial_values: ArrayLike | Inputs | None = None, **individual_updates: dict[str, Any]) None[source]#
Update multiple parameters efficiently.
- Parameters:
initial_values (array-like or dict, optional) – New initial values (by position or name)
bounds (sequence or dict, optional) – New bounds (by position or name)
**individual_updates (dict) – Individual parameter updates with parameter names as keys
- update_distribution()[source]#
Method to determine whether to construct a JointDistribution or a MultivariateDistribution and to set up the distribution.
Multivariate distributions are passed to individual parameters via the corresponding marginal distribution. The pybop.MarginalDistribution class retains the underlying pybop.MultivariateDistribution in the parent_distribution property.
- _distribution = None#
- _multivariate = None#
- _parameters = None#
- _transform = None#
- property distribution: pybop.parameters.multivariate_distributions.BaseMultivariateDistribution | pybop.parameters.distributions.JointDistribution | None#
Return the joint or multivariate distribution.
- property names: list[str]#
- property transformation: pybop.transformation.base_transformation.Transformation#
Get the transformation for the parameters.
- property transformed_distribution_properties#
- class pybop.PintsOptions[source]#
Bases:
pybop.optimisers.base_optimiser.OptimiserOptionsA class to hold PINTS options for the optimisation process.
- default_max_iterations#
Default maximum number of iterations (default: 1000).
- Type:
int
- max_iterations#
Maximum number of iterations for the optimisation (default: None).
- Type:
int
- min_iterations#
Minimum number of iterations required (default: 2).
- Type:
int
- max_unchanged_iterations#
Maximum iterations without improvement before stopping (default: 15).
- Type:
int
- use_f_guessed#
Whether to use guessed function values (default: False).
- Type:
bool
- absolute_tolerance#
Absolute tolerance for convergence (default: 1e-5).
- Type:
float
- relative_tolerance#
Relative tolerance for convergence (default: 1e-2).
- Type:
float
- max_evaluations#
Maximum number of function evaluations (default: None).
- Type:
int | None
- threshold#
Threshold value for optimisation stopping criteria (default: None).
- Type:
float | None
- absolute_tolerance: float = 1e-05#
- default_max_iterations = 1000#
- max_evaluations: int | None = None#
- max_iterations: int = 1000#
- max_unchanged_iterations: int = 15#
- min_iterations: int = 2#
- relative_tolerance: float = 0.01#
- threshold: float | None = None#
- use_f_guessed: bool = False#
- class pybop.PintsSamplerOptions[source]#
Bases:
pybop.samplers.base_sampler.SamplerOptionsPints sampler options.
- n_chains#
The number of chains to concurrently sample from (default: 1).
- Type:
int
- max_iterations#
Maximum number of iterations to run (default: 500).
- Type:
int
- verbose#
If True, additional information will be printed (default: False).
- Type:
bool
- warm_up_iterations#
Number of iterations to warm up the sampler (default: 250).
- Type:
int
- chains_in_memory#
Whether to store the chains in memory (default: True).
- Type:
bool
- log_to_screen#
If True (default), the sampler will print information during the sampling.
- Type:
bool
- log_filename#
The name of the file to save the sampler log to (default: None).
- Type:
str
- chain_files#
The name of the file to save the chains in (default: None).
- Type:
list
- evaluation_files#
The name of the file to save the evaluations in (default: None).
- Type:
list
- chain_files: list[str] | None = None#
- chains_in_memory: bool = True#
- evaluation_files: list[str] | None = None#
- initial_phase_iterations: int = 250#
- log_filename: str | None = None#
- log_to_screen: bool = True#
- max_iterations: int = 500#
- verbose: bool = False#
- warm_up_iterations: int = 0#
- class pybop.PopulationEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#
Bases:
BaseEvaluatorEvaluates a function (or callable object) for multiple positions.
- Parameters:
function (callable) – The function to evaluate. This function should accept a list-like object of positions to be evaluated.
args (sequence, optional) – A sequence containing extra arguments to be passed to the function. If specified, the function will be called as function(x, *args).
- class pybop.PopulationMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Population Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Population MCMC sampler from the PINTS library. This MCMC method uses a population of chains at different temperatures to explore the parameter space more efficiently and avoid local minima.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.Problem(simulator: pybop.simulators.base_simulator.BaseSimulator = None, cost: pybop.costs.base_cost.BaseCost = None)[source]#
Base class for defining a problem within the PyBOP framework, compatible with PINTS.
- Parameters:
simulator (pybop.BaseSimulator) – The model, protocol and optional dataset combined into a simulator object.
parameters (list[pybop.Parameter] or pybop.Parameters) – An object or list of the parameters for the problem.
cost (pybop.BaseCost, optional) – An cost e.g. an error measure, a log-likelihood or a design cost.
- target_data#
An array containing the target data to fit.
- Type:
array-like
- n_outputs#
The number of outputs in the model.
- Type:
int
- minimising#
If False, tells the optimiser to switch the sign of the cost and gradient to maximise by default rather than minimise (default: True).
- Type:
bool, optional
- __call__(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs]) float | list[float][source]#
Evaluate the cost for one or more sets of inputs and return the cost value(s).
- evaluate(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.costs.evaluation.Evaluation[source]#
Evaluate the cost for one or more sets of inputs and return the cost value(s) and (optionally) the sensitivities.
- Parameters:
- Returns:
The cost value(s) and (optionally) the gradient of the cost with respect to each input parameter.
- Return type:
- evaluate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.costs.evaluation.Evaluation[source]#
Evaluate the cost for each set of inputs and return the cost value(s) and (optionally) the sensitivities.
- Parameters:
inputs (list[Inputs]) – A list of input parameters.
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
Cost values of len(inputs) and (optionally) the gradient of the cost with respect to each input parameter with shape (len(inputs), len(parameters)).
- Return type:
- get_finite_initial_cost()[source]#
Compute the absolute initial cost, resampling the initial parameters if needed.
- get_model_inputs(inputs: pybop.parameters.parameter.Inputs)[source]#
- sensitivity_analysis(n_samples: int = 256, calc_second_order: bool = False) dict[source]#
Computes the parameter sensitivities on the combined cost function using SOBOL analysis. See pybop.analysis.sensitivity_analysis for more details.
- Parameters:
n_samples (int, optional) – Number of samples for SOBOL sensitivity analysis, performs best as a power of 2, i.e. 128, 256, etc.
calc_second_order (bool, optional) – Whether to calculate second-order sensitivities.
- simulate(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.simulators.base_simulator.Solution | list[pybop.simulators.base_simulator.Solution][source]#
Simulate the model for one or more sets of inputs and return the solution and (optionally) the sensitivities.
- Parameters:
- Returns:
- The simulated model output y(t) and (optionally) the sensitivities dy/dx(t)
for output variable(s) y, domain t and parameter(s) x.
- Return type:
- simulate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) list[pybop.simulators.base_simulator.Solution | pybop.simulators.failed_solution.FailedSolution][source]#
Simulate the model for each set of inputs and return the solution and (optionally) the sensitivities.
- _cost#
- _has_sensitivities#
- _minimising = True#
- _parameters#
- _simulator#
- property cost#
- property domain#
- property domain_data#
- property has_sensitivities#
- property minimising#
- property n_parameters#
- property parameters#
- property simulator#
- property target#
- property target_data#
- class pybop.RandomSearch(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for random search, a simple algorithm which samples parameter values randomly and stores the current best proposal based on fitness (not recommended for optimisation).
This optimiser has been implemented for benchmarking and comparisons, convergence will be better with one of other optimisers in the majority of cases.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pybop.RandomSearchImplPyBOP implementation of Random Search algorithm.
- class pybop.RaoBlackwellACMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Rao-Blackwell Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Rao-Blackwell Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method improves sampling efficiency by combining Rao-Blackwellisation with adaptive covariance strategies.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.RelativisticMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Relativistic Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Relativistic MCMC sampler from the PINTS library. This MCMC method uses concepts from relativistic mechanics to propose new states, allowing for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.Result(problem: pybop.problems.problem.Problem, logger: pybop._logging.Logger, time: float, method_name: str | None = None, message: str | None = None, scipy_result=None)[source]#
Stores the result produced by an optimiser or sampler.
- problem#
The optimisation problem used to generate the results.
- Type:
- logger#
The log of the optimisation or sampling process.
- Type:
- time#
The time taken.
- Type:
float
- method_name#
The name of the optimiser or sampler.
- Type:
str
- message#
The reason for stopping given by the optimiser or sampler.
- Type:
str
- __str__() str[source]#
A string representation of the Result object.
- Returns:
A formatted string containing optimisation result information.
- Return type:
str
- _check_for_finite_cost() None[source]#
Validate the optimised parameters and ensure they produce a finite cost value.
- Raises:
ValueError – If the optimised parameters do not produce a finite cost value.
- static combine(results: list[Result]) Result[source]#
Combine multiple Result objects into a single one.
- static load_data(filename: str, file_format: str = 'pickle') dict[source]#
Load results data as dictionary from a given file. Restores data saved with save_data.
Calls load_data_dict defined in _utils.py and provides the keys of data that is 0-d and 1-d to ensure consistent data dimensions.
- Parameters:
filename (str) – The name of the file containing the data.
file_format (str, optional) – The format the data was save to. Options are: - ‘pickle’ (default) - ‘matlab’ - ‘csv’ - ‘json’
- Returns:
python dictionary containing the data in the file.
- Return type:
data_dict
- plot_contour(**kwargs)[source]#
Generate and plot a 2D visualisation of the cost landscape with the optimisation trace.
- Parameters:
gradient (bool, optional) – If True, gradient plots are also generated (default: False).
bounds (numpy.ndarray | list[list[float]], optional) – A 2x2 array specifying the [min, max] bounds for each parameter.
transformed (bool, optional) – Uses the transformed parameter values, as seen by the optimiser (default: False).
steps (int, optional) – The number of grid points to divide the parameter space into along each dimension (default: 10).
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values.
- plot_convergence(**kwargs)[source]#
Plot the evolution of the best cost during the optimisation.
- Parameters:
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values.
- plot_parameters(**kwargs)[source]#
Plot the evolution of parameter values during the optimisation.
- Parameters:
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values.
- plot_surface(**kwargs)[source]#
Plot a 2D representation of the Voronoi diagram with color-coded regions.
- Parameters:
bounds (numpy.ndarray, optional) – A 2x2 array specifying the [min, max] bounds for each parameter.
normalise (bool, optional) – If True, the voronoi regions are computed using the Euclidean distance between points normalised with respect to the bounds (default: True).
resolution (int, optional) – Resolution of the plot (default: 500).
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values.
- save_data(filename=None, to_format='pickle') str | None[source]#
Save result data
Based on pybamm.Solution.save_data
- Parameters:
filename (str, optional) – The name of the file to save data to. If None, then a str is returned for json format or an error is thrown for pickle/matlab.
to_format (str, optional) –
The format to save to. Options are:
’pickle’ (default): creates a pickle file with the data dictionary
’matlab’: creates a .mat file, for loading in matlab
’json’: creates a json file
- Returns:
data – str if ‘json’ is chosen and filename is None, otherwise None
- Return type:
str, optional
- total_evaluations() numpy.floating | None[source]#
Calculates the total number of evaluations across all runs.
- total_iterations() numpy.floating | None[source]#
Calculates the total number of iterations across all runs.
- _best_cost#
- _best_run = None#
- _cost#
- _initial_cost#
- _iteration_number#
- _message#
- _minimising#
- _n_evaluations#
- _n_iterations#
- _problem#
- _scipy_result#
- _time#
- _x#
- _x0#
- _x_model#
- property best_cost: float#
The best cost value(s).
- property best_inputs: dict[str, numpy.ndarray]#
The best parameters as a dictionary.
- property cost: numpy.ndarray#
The log of the cost values.
- property initial_cost: float#
The initial cost value(s).
- property iteration_number: numpy.ndarray | None#
The number of iterations.
- property message: str | None#
The optimisation termination message(s).
- method_name = None#
- property minimising: bool#
Whether the cost was minimised (or maximised).
- property n_evaluations: int#
The number of evaluations.
- property n_iterations: int#
The number of iterations.
- n_runs = 1#
- property problem: pybop.problems.problem.Problem#
The optimisation problem.
- property scipy_result#
The SciPy result.
- property time: float | None#
The optimisation time(s).
- property x: numpy.ndarray#
The best parameter values (in model space).
- property x0: numpy.ndarray#
The initial parameter values.
- property x_model: numpy.ndarray#
The log of the evaluated parameters (in model space).
- class pybop.RootMeanSquaredError(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureRoot mean square error (RMSE) cost function.
Computes the root mean square error between model predictions and the target data, providing a measure of the differences between predicted values and observed values.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- class pybop.SNES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for the stochastic natural evolution strategy (SNES), an evolutionary algorithm that evolves a probability distribution on the parameter space, guiding the search for the optimum based on the natural gradient of expected fitness.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.SNESThe PINTS implementation this class is based on.
- property name: str#
Overwrite misspelling of separable from Pints 0.5.1.
- class pybop.SamplerOptions[source]#
Base options for the sampler.
- n_chains#
The number of chains to concurrently sample from.
- Type:
int
- n_chains: int = 1#
- class pybop.ScalarEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#
Bases:
BaseEvaluatorEvaluates a function (or callable object) for a single input.
- Parameters:
function (callable) – The function to evaluate. This function should accept an input and optionally additional arguments, returning either a single value or a tuple.
args (sequence, optional) – A sequence containing extra arguments to be passed to the function. If specified, the function will be called as function(x, *args).
- class pybop.SciPyDifferentialEvolution(problem: pybop.problems.problem.Problem, options: SciPyDifferentialEvolutionOptions | None = None)[source]#
Bases:
BaseSciPyOptimiserAdapter for SciPy’s differential_evolution function for global optimisation, useful for problems involving continuous parameters and potentially multiple local minima.
- Parameters:
problem (pybop.Problem) – The problem to optimise.
options (SciPyDifferentialEvolutionOptions, optional) – Options for the SciPy differential evolution method (default: None).
See also
scipy.optimize.differential_evolutionThe SciPy method this class is based on.
Notes
Differential Evolution is a stochastic population based method that is useful for global optimisation problems. At each pass through the population the algorithm mutates each candidate solution by mixing with other candidate solutions to create a trial candidate. The fitness of all candidates is then evaluated and for each candidate if the trial candidate is an improvement, it takes its place in the population for the next iteration.
- _run()[source]#
Executes the optimisation process using SciPy’s differential_evolution function.
- Returns:
result – The result of the optimisation including the optimised parameter values and cost.
- Return type:
scipy.optimize.OptimizeResult
- static default_options() SciPyDifferentialEvolutionOptions[source]#
Returns the default options for the optimiser.
- property name#
Provides the name of the optimisation strategy.
- class pybop.SciPyDifferentialEvolutionOptions[source]#
Bases:
pybop.optimisers.base_optimiser.OptimiserOptionsOptions for the SciPy differential evolution method.
- Parameters:
strategy (str, optional) – The differential evolution strategy to use. Should be one of: - ‘best1bin’ - ‘best1exp’ - ‘rand1exp’ - ‘randtobest1exp’ - ‘currenttobest1exp’ - ‘best2exp’ - ‘rand2exp’ - ‘randtobest1bin’ - ‘currenttobest1bin’ - ‘best2bin’ - ‘rand2bin’ - ‘rand1bin’ Default is ‘best1bin’.
maxiter (int, optional) – Maximum number of generations (default: 1000).
popsize (int, optional) – Multiplier for setting the total population size. The population has popsize * len(x) individuals (default: 15).
tol (float, optional) – Relative tolerance for convergence (default: 0.01).
mutation (float or tuple(float, float), optional) – The mutation constant. If specified as a float, should be in [0, 2]. If specified as a tuple (min, max), dithering is used (default: (0.5, 1.0)).
recombination (float, optional) – The recombination constant, should be in [0, 1] (default: 0.7).
seed (int, optional) – Random seed for reproducibility.
disp (bool, optional) – Display status messages (default: False).
callback (Callable, optional) – Called after each iteration with the current result as argument.
polish (bool, optional) – If True, performs a local optimisation on the solution (default: True).
init (str or array-like, optional) – Specify initial population. Can be ‘latinhypercube’, ‘random’, or an array of shape (M, len(x)).
atol (float, optional) – Absolute tolerance for convergence (default: 0).
updating ({'immediate', 'deferred'}, optional) – If ‘immediate’, best solution vector is continuously updated within a single generation (default: ‘immediate’).
workers (int or map-like Callable, optional) – If workers is an int the population is subdivided into workers sections and evaluated in parallel (default: 1).
constraints ({NonlinearConstraint, LinearConstraint, Bounds}, optional) – Constraints on the solver.
- atol: float | None = None#
- callback: collections.abc.Callable | None = None#
- disp: bool | None = None#
- init: str | numpy.ndarray | None = None#
- maxiter: int = 1000#
- mutation: float | tuple | None = None#
- polish: bool | None = None#
- popsize: int | None = None#
- recombination: float | None = None#
- seed: int | None = None#
- strategy: str = 'best1bin'#
- tol: float = 0.01#
- class pybop.SciPyMinimize(problem: pybop.problems.problem.Problem, options: SciPyMinimizeOptions | None = None)[source]#
Bases:
BaseSciPyOptimiserAdapter for various scalar minimisation algorithms implemented in SciPy, allowing fine-tuning of the optimisation process through method selection and option configuration.
- Parameters:
problem (pybop.Problem) – The problem to optimise.
options (ScipyMinizeOptions, optional) – Options for the SciPy minimize method (default: None).
See also
scipy.optimize.minimizeThe SciPy method this class is based on.
Notes
Different optimisation methods may support different options. Consult SciPy’s documentation for method-specific options and constraints.
- _run()[source]#
Executes the optimisation process using SciPy’s minimize function.
- Returns:
result – The result of the optimisation including the optimised parameter values and cost.
- Return type:
scipy.optimize.OptimizeResult
- static default_options() SciPyMinimizeOptions[source]#
Returns the default options for the optimiser.
- property name#
Provides the name of the optimisation strategy.
- class pybop.SciPyMinimizeOptions[source]#
Bases:
pybop.optimisers.base_optimiser.OptimiserOptionsOptions for the SciPy minimize method.
- method#
The optimisation method to use (default: None).
- Type:
str, optional
- jac#
Method for computing the gradient vector (default: None).
- Type:
bool, optional
- tol#
Tolerance for termination (default: None).
- Type:
float, optional
- maxiter#
Maximum number of iterations (default: 1000).
- Type:
int, optional
- disp#
Set to True to print convergence messages (default: False).
- Type:
bool, optional
- constraints#
Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
- Type:
scipy constraint or list of scipy constraints, optional
- solver_options#
A dictionary of additional solver options, not including maxiter or disp.
- Type:
dict, optional
- constraints: list | None = None#
- disp: bool = False#
- jac: bool | None = None#
- maxiter: int = 1000#
- method: str | None = None#
- solver_options: dict | None = None#
- tol: float | None = None#
- class pybop.SequentialEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#
Bases:
BaseEvaluatorEvaluates a function (or callable object) for a list of input values, and returns a list containing the calculated function evaluations.
- Parameters:
function (callable) – The function to evaluate.
args (sequence) – An optional tuple containing extra arguments to
f. Ifargsis specified,fwill be called asf(x, *args).
- class pybop.SimulatedAnnealing(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for simulated annealing, a probabilistic optimisation method inspired by the annealing process in metallurgy which is suitable for global optimisation problems.
It works by iteratively proposing new solutions and accepting them based on both their fitness and a temperature parameter that decreases over time. This allows the algorithm to initially explore broadly and gradually focus on local optimisation as the temperature decreases.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pybop.SimulatedAnnealingImplPyBOP implementation of Simulated Annealing algorithm.
- class pybop.SingleChainProcessor(mcmc_sampler)[source]#
Bases:
ChainProcessorProcessor for individual chains.
- class pybop.SliceDoublingMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Slice Doubling Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Slice Doubling MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a doubling procedure to propose new states, allowing for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.SliceRankShrinkingMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Slice Rank Shrinking Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Slice Rank Shrinking MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a rank shrinking procedure to propose new states, allowing for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options for the sampler.
- class pybop.SliceStepoutMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#
Bases:
pybop.BasePintsSamplerImplements the Slice Stepout Markov Chain Monte Carlo (MCMC) algorithm.
This class extends the Slice Stepout MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a stepout procedure to propose new states, allowing for efficient exploration of the parameter space.
- Parameters:
log_pdf (pybop.LogPDF) – The log-posterior to sample.
options (pybop.PintsSamplerOptions, optional) – Additional options to pass to the sampler.
- class pybop.Solution(inputs: pybop.parameters.parameter.Inputs = None)[source]#
A class to store simulation results, inspired by pybamm.Solution.
- set_solution_variable(variable_name: str, data: numpy.ndarray, sensitivities: dict[str, numpy.ndarray] | None = None)[source]#
- _dict#
- all_inputs#
- class pybop.SquareRootFeatureDistance(domain_data: numpy.ndarray, target_data: numpy.ndarray, feature: str = 'inverse_slope', time_start: float = None, time_end: float = None)[source]#
Bases:
FeatureDistanceSquare-root fit cost function.
Fits a square-root fit function and compares either its offset or its slope between model predictions and target data.
- _supported_features = ['offset', 'slope', 'inverse_slope']#
- class pybop.SumOfPower(dataset: pybop.processing.dataset.Dataset, p: float = 2.0, target: str | list[str] = None, weighting: str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureThe Sum of Power [1] is a generalised cost function based on the p-th power of absolute differences between two vectors. It is defined as:
\[C_p(x, y) = \sum_i |x_i - y_i|^p\]where p ≥ 0 is the power order.
This class implements the Sum of Power as a cost function for optimisation problems, allowing for flexible power-based optimisation across various problem domains.
Special cases:
p = 1: Sum of Absolute Differences
p = 2: Sum of Squared Differences
p → ∞: Maximum Absolute Difference
Note that this is not normalised, unlike distance metrics. To get a distance metric, you would need to take the p-th root of the result.
[1]: https://mathworld.wolfram.com/PowerSum.html
Additional Attributes#
- pfloat, optional
The power order for Sum of Power.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- __name__()#
- p#
- class pybop.SumSquaredError(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#
Bases:
ErrorMeasureSum of squared error (SSE) cost function.
Computes the sum of the squares of the differences between model predictions and target data, which serves as a measure of the total error between the predicted and observed values.
- __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).
dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).
- Returns:
If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- class pybop.Uniform(lower, upper)[source]#
Bases:
DistributionRepresents a uniform distribution over a specified interval.
This class provides methods to calculate the pdf, the log pdf, and to generate random variates from the distribution.
- Parameters:
lower (float) – The lower bound of the distribution.
upper (float) – The upper bound of the distribution.
- _dlogpdf_dx(x)[source]#
Evaluates the first derivative of the log uniform distribution at x.
- Parameters:
x (float) – The point(s) at which to evaluate the first derivative.
- Returns:
The value(s) of the first derivative at x.
- Return type:
float
- _n_parameters = 1#
- lower#
- name = 'Uniform'#
- upper#
- class pybop.WeightedCost(*costs, weights: list[float] | None = None)[source]#
Bases:
pybop.costs.base_cost.BaseCostA subclass for constructing a linear combination of cost functions as a single weighted cost function.
- Parameters:
costs (pybop.BaseCost) – The individual PyBOP cost objects.
weights (list[float]) – A list of values with which to weight the cost values.
- evaluate(solution: pybop.simulators.solution.Solution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#
Computes the cost function for the given predictions.
- Parameters:
solution (pybop.Solution | pybamm.Solution) – The simulation result.
inputs (Inputs, optional) – Input parameters (default: None).
calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).
- Returns:
If the solution has sensitivities, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.
- Return type:
np.float64 or tuple[np.float64, np.ndarray[np.float64]]
- set_target(target: list[list[str]] | list[str] | str | None = None)[source]#
Set the target variable for all costs. Expecting a list of list[str] the same length as self.costs.
- _domain#
- costs#
- property target#
- class pybop.XNES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#
Bases:
pybop.optimisers.base_pints_optimiser.BasePintsOptimiserAdapter for the exponential natural evolution strategy (XNES), an evolutionary algorithm that samples from a multivariate normal distribution, which is updated iteratively to fit the distribution of successful solutions.
- Parameters:
problem (pybop.Problem) – The problem to optimse.
options (pybop.PintsOptions) – Optimisation options.
See also
pints.XNESPINTS implementation of XNES algorithm.
- pybop.add_spaces(string)[source]#
Return the class name as a string with spaces before each new capitalised word.
- pybop.load_data_dict(filename: str, file_format: str = 'pickle', data_keys_0d: list[str] | None = None, data_keys_1d: list[str] | None = None) dict[source]#
Load data as dictionary from a given file. Restores data saved with save_data_dict.
- Parameters:
filename (str) – The name of the file containing the data.
file_format (str, optional) – The format the data was save to. Options are: - ‘pickle’ (default) - ‘matlab’ - ‘csv’ - ‘json’
data_keys_0d (list[str], optional) – A list of keys for which the data is a scalar/0-dimensional. This is only needed for file_format=’matlab’ or file_format = ‘csv’. scipy.io.savemat turns any data into a multi-dimensional array with at least 2 dimensions. If provided, data dimensions will be consistent with the original data.
data_keys_1d (list[str], optional) – A list of keys for which the data is a 1-dimensional list or array. This is only needed for file_format=’matlab’. scipy.io.savemat turns any data into a multi-dimensional array with at least 2 dimensions. If provided, data dimensions will be consistent with the original data.
- Returns:
python dictionary containing the data in the file.
- Return type:
data_dict
- pybop.save_data_dict(data_dict: dict, filename: str | None = None, to_format: str = 'pickle') str | None[source]#
Save data from given data dictionary
Based on pybamm.Solution.save_data
- Parameters:
filename (str, optional) – The name of the file to save data to. If None, then a str is returned
to_format (str, optional) –
The format to save to. Options are:
’pickle’ (default): creates a pickle file with the data dictionary
’matlab’: creates a .mat file, for loading in matlab
’csv’: creates a csv file (0D variables only)
’json’: creates a json file
- Returns:
data – str if ‘json’ is chosen and filename is None, otherwise None
- Return type:
str, optional
- pybop.FLOAT_FORMAT = '{: .17e}'#
- pybop.__version__#
- pybop.script_path#