pybop#

Submodules#

Attributes#

Classes#

AdamW

Implements the AdamW optimisation algorithm in PyBOP.

AdamWImpl

AdamW optimiser (adaptive moment estimation with weight decay), as described in [1].

AdaptiveCovarianceMCMC

Implements the Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

BaseCost

Base class for defining cost functions.

BaseLikelihood

Base class for likelihoods

BaseModel

A base class for constructing and simulating models using PyBaMM.

BaseOptimiser

A base class for defining optimisation methods.

BasePintsOptimiser

A base class for defining optimisation methods from the PINTS library.

BasePintsSampler

Base class for PINTS samplers.

BasePrior

A base class for defining prior distributions.

BaseProblem

Base class for defining a problem within the PyBOP framework, compatible with PINTS.

BaseSampler

Base class for Monte Carlo samplers.

BaseSciPyOptimiser

A base class for defining optimisation methods from the SciPy library.

CMAES

Adapter for the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) optimiser in PINTS.

CuckooSearch

Adapter for the Cuckoo Search optimiser in PyBOP.

CuckooSearchImpl

Cuckoo Search (CS) optimisation algorithm, inspired by the brood parasitism

DREAM

Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm.

Dataset

Represents a collection of experimental observations.

DesignCost

Overwrites and extends BaseCost class for design-related cost functions.

DesignProblem

Problem class for design optimization problems.

DifferentialEvolutionMCMC

Implements the Differential Evolution Markov Chain Monte Carlo (MCMC) algorithm.

DramACMC

Implements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance Markov Chain

EmceeHammerMCMC

Implements the Emcee Hammer Markov Chain Monte Carlo (MCMC) algorithm.

Experiment

Light wrapper of the PyBaMM Experiment class for generating experiment conditions for PyBaMM models.

Exponential

Represents an exponential distribution with a specified scale parameter.

ExponentialDecayModel

Exponential decay model defined by the equation:

FittingProblem

Problem class for fitting (parameter estimation) problems.

Gaussian

Represents a Gaussian (normal) distribution with a given mean and standard deviation.

GaussianLogLikelihood

This class represents a Gaussian Log Likelihood, which assumes that the

GaussianLogLikelihoodKnownSigma

This class represents a Gaussian Log Likelihood with a known sigma,

GradientDescent

Implements a simple gradient descent optimisation algorithm.

GradientDescentImpl

Gradient descent method with a fixed, per-dimension learning rate.

GravimetricEnergyDensity

Calculates the gravimetric energy density (specific energy) of a battery cell,

GravimetricPowerDensity

Calculates the gravimetric power density (specific power) of a battery cell,

HaarioACMC

Implements the Haario Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

HaarioBardenetACMC

Implements the Haario-Bardenet Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

HamiltonianMCMC

Implements the Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm.

IRPropMin

Implements the iRpropMin optimisation algorithm.

JointLogPrior

Represents a joint prior distribution composed of multiple prior distributions.

LogPosterior

The Log Posterior for a given problem.

MALAMCMC

Implements the Metropolis Adjusted Langevin Algorithm (MALA) Markov Chain Monte Carlo (MCMC) algorithm.

MCMCSampler

A high-level class for MCMC sampling.

MetropolisRandomWalkMCMC

Implements the Metropolis Random Walk Markov Chain Monte Carlo (MCMC) algorithm.

Minkowski

The Minkowski distance is a generalisation of several distance metrics,

MonomialGammaHamiltonianMCMC

Implements the Monomial Gamma Hamiltonian Markov Chain Monte Carlo (MCMC) algorithm.

MultiFittingProblem

Problem class for joining mulitple fitting problems into one combined fitting problem.

MultiOptimisationResult

Multi run optimisation result class. Stores the results

NUTS

Implements the No-U-Turn Sampler (NUTS) algorithm.

NelderMead

Implements the Nelder-Mead downhill simplex method from PINTS.

Observer

An observer of a time series state. Observers:

ObserverCost

Observer cost function.

Optimisation

A high-level class for optimisation using PyBOP or PINTS optimisers.

OptimisationResult

Stores the result of the optimisation.

PSO

Implements a particle swarm optimisation (PSO) algorithm.

Parameter

Represents a parameter within the PyBOP framework.

ParameterSet

Handles the import and export of parameter sets for battery models.

Parameters

Represents a set of uncertain parameters within the PyBOP framework.

PopulationMCMC

Implements the Population Markov Chain Monte Carlo (MCMC) algorithm.

PosteriorSummary

RandomSearch

Adapter for the Random Search optimiser in PyBOP.

RandomSearchImpl

Random Search (RS) optimisation algorithm.

RaoBlackwellACMC

Implements the Rao-Blackwell Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

RelativisticMCMC

Implements the Relativistic Markov Chain Monte Carlo (MCMC) algorithm.

RootMeanSquaredError

Root mean square error cost function.

SNES

Implements the stochastic natural evolution strategy (SNES) optimisation algorithm.

ScaledLogLikelihood

This class scaled a BaseLogLikelihood class by the number of observations.

SciPyDifferentialEvolution

Adapts SciPy's differential_evolution function for global optimisation.

SciPyEvaluator

Evaluates a function (or callable object) for the SciPy optimisers

SciPyMinimize

Adapts SciPy's minimize function for use as an optimisation strategy.

SequentialJaxEvaluator

Sequential evaluates a function (or callable object)

SliceDoublingMCMC

Implements the Slice Doubling Markov Chain Monte Carlo (MCMC) algorithm.

SliceRankShrinkingMCMC

Implements the Slice Rank Shrinking Markov Chain Monte Carlo (MCMC) algorithm.

SliceStepoutMCMC

Implements the Slice Stepout Markov Chain Monte Carlo (MCMC) algorithm.

SumSquaredError

Sum of squared errors cost function.

SumofPower

The Sum of Power [1] is a generalised cost function based on the p-th power

SymbolReplacer

Helper class to replace all instances of one or more symbols in an expression tree

TimeSeriesState

The current state of a time series model that is a pybamm model.

Uniform

Represents a uniform distribution over a specified interval.

UnscentedKalmanFilterObserver

An observer using the unscented Kalman filter. This is a wrapper class for PyBOP, see class SquareRootUKF for more details on the method.

VolumetricEnergyDensity

Calculates the (volumetric) energy density of a battery cell, when applied to a

VolumetricPowerDensity

Calculates the (volumetric) power density of a battery cell, when applied to a

WeightedCost

A subclass for constructing a linear combination of cost functions as

XNES

Implements the Exponential Natural Evolution Strategy (XNES) optimiser from PINTS.

Functions#

classify_using_hessian(result[, dx, cost_tolerance])

A simple check for parameter correlations based on numerical approximation

is_numeric(x)

Check if a variable is numeric.

Package Contents#

class pybop.AdamW(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements the AdamW optimisation algorithm in PyBOP.

This class extends the AdamW optimiser, which is a variant of the Adam optimiser that incorporates weight decay. AdamW is designed to be more robust and stable for training deep neural networks, particularly when using larger learning rates.

Note that this optimiser does not support boundary constraints.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pybop.AdamWImpl

The PyBOP implementation this class is based on.

class pybop.AdamWImpl(x0, sigma0=0.015, boundaries=None)[source]#

Bases: pints.Optimiser

AdamW optimiser (adaptive moment estimation with weight decay), as described in [1].

This method is an extension of the Adam optimiser that introduces weight decay, which helps to regularise the weights and prevent overfitting.

This class reimplements the Pints’ Adam Optimiser, but with the weight decay functionality mentioned above. Original creation and credit is attributed to Pints.

Pseudo-code is given below. Here the value of the j-th parameter at iteration i is given as p_j[i] and the corresponding derivative is denoted g_j[i]:

m_j[i] = beta1 * m_j[i - 1] + (1 - beta1) * g_j[i]
v_j[i] = beta2 * v_j[i - 1] + (1 - beta2) * g_j[i]**2

m_j' = m_j[i] / (1 - beta1**(1 + i))
v_j' = v_j[i] / (1 - beta2**(1 + i))

p_j[i] = p_j[i - 1] - alpha * (m_j' / (sqrt(v_j') + eps) + lam * p_j[i - 1])

The initial values of the moments are m_j[0] = v_j[0] = 0, after which they decay with rates beta1 and beta2. The default values for these are, beta1 = 0.9 and beta2 = 0.999.

The terms m_j' and v_j' are “initialisation bias corrected” versions of m_j and v_j (see section 2 of the paper).

The parameter alpha is a step size, which is set as min(sigma0) in this implementation.

The parameter lam is the weight decay rate, which is set to 0.01 by default in this implementation.

Finally, eps is a small constant used to avoid division by zero, set to ``eps = np.finfo(float).eps in this implementation.

This is an unbounded method: Any boundaries will be ignored.

References

ask()[source]#

Returns a list of next points in the parameter-space to evaluate from the optimiser.

f_best()[source]#

Returns the best score found so far.

f_guessed()[source]#

Returns the score of the last guessed point.

n_hyper_parameters()[source]#

The number of hyper-parameters used by this optimiser.

name()[source]#

Returns the name of the optimiser.

needs_sensitivities()[source]#

Returns False if this optimiser does not require gradient, and True otherwise.

running()[source]#

Returns True if the optimisation is in progress.

tell(reply)[source]#

Receives a list of function values from the cost function from points previously specified by self.ask(), and updates the optimiser state accordingly.

x_best()[source]#

Returns the best parameter values found so far.

x_guessed()[source]#

Returns the last guessed parameter values.

_alpha#
_b1 = 0.9#
_b1t = 1#
_b2 = 0.999#
_b2t = 1#
_current#
_current_df = None#
_current_f#
_eps#
_f_best#
_lam = 0.01#
_m#
_proposed#
_ready_for_tell = False#
_running = False#
_v#
_x_best#
property b1#
property b2#
boundaries = None#
property lam#
class pybop.AdaptiveCovarianceMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

This class extends the Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method adapts the proposal distribution covariance matrix during the sampling process to improve efficiency and convergence.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Adaptive Covariance MCMC sampler.

class pybop.BaseCost(problem: pybop.BaseProblem | None = None)[source]#

Base class for defining cost functions.

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 the model predictions and the observed data, with a lower cost value indicating a better fit.

Parameters:
  • problem (object) – A problem instance containing the data and functions necessary for evaluating the cost function.

  • target (array-like) – An array containing the target data to fit.

  • n_outputs (int) – The number of outputs in the model.

  • has_separable_problem (bool) – If True, the problem is separable from the cost function and will be evaluated in advance of the call to self.compute() (default: False).

  • _de (float) – The gradient of the cost function to use if an error occurs during evaluation. Defaults to 1.0.

  • minimising (bool, optional, default=True) – If False, switches the sign of the cost and gradient to perform maximisation instead of minimisation.

__call__(inputs: pybop.parameters.parameter.Inputs | list, calculate_grad: bool = False, apply_transform: bool = False, for_optimiser: bool = False) float | tuple[float, numpy.ndarray][source]#

This method calls the forward model via problem.evaluate(inputs), and computes the cost for the given output by calling self.compute().

Parameters:
  • inputs (Inputs or list-like) – The input parameters for which the cost and optionally the gradient will be computed.

  • calculate_grad (bool, optional, default=False) – If True, both the cost and gradient will be computed. Otherwise, only the cost is computed.

  • apply_transform (bool, optional, default=False) – If True, applies a transformation to the inputs before evaluating the model.

  • for_optimiser (bool, optional, default=False) – If True, returns the cost value if self.minimising=True and the negative of the cost value if self.minimising=False (i.e. the cost is being maximised).

Returns:

  • If calculate_grad is False, returns the computed cost (float).

  • If calculate_grad is True, returns a tuple containing the cost (float) and the gradient (np.ndarray).

Return type:

float or tuple

Raises:

ValueError – If an error occurs during the calculation of the cost.

_apply_transformations(inputs)[source]#

Apply transformation if needed

abstract compute(y: dict, dy: numpy.ndarray, calculate_grad: bool = False)[source]#

Compute the cost and if calculate_grad is True, its gradient with respect to the predictions.

This method only computes the cost, without calling the problem.evaluate(). This method must be implemented by subclasses.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The calculated cost function value.

Return type:

float

Raises:

NotImplementedError – If the method has not been implemented by the subclass.

join_parameters(parameters)[source]#

Setter for joining parameters. This method sets the fail gradient if the join adds parameters.

set_fail_gradient(de: float = 1.0)[source]#

Set the fail gradient to a specified value.

The fail gradient is used if an error occurs during the calculation of the gradient. This method allows updating the default gradient value.

Parameters:

de (float) – The new fail gradient value to be used.

verify_args(dy: numpy.ndarray, calculate_grad: bool)[source]#
verify_prediction(y)[source]#

Verify that the prediction matches the target data.

Parameters:

y (dict) – The model predictions.

Returns:

True if the prediction matches the target data, otherwise False.

Return type:

bool

_de = 1.0#
_has_separable_problem = False#
_parameters#
_transformation = None#
dy = None#
property has_separable_problem#
minimising = True#
property n_parameters#
property name#
property parameters#
problem = None#
property target#
property transformation#
verbose = False#
y = None#
class pybop.BaseLikelihood(problem: pybop.problems.base_problem.BaseProblem)[source]#

Bases: pybop.costs.base_cost.BaseCost

Base class for likelihoods

minimising = False#
n_data#
class pybop.BaseModel(name: str = 'Base Model', parameter_set: pybop.ParameterSet | None = None, check_params: Callable = None, eis: bool = False)[source]#

A base class for constructing and simulating models using PyBaMM.

This class serves as a foundation for constructing models based on PyBaMM models. It provides methods to set up the model, define parameters, and perform simulations. The class is designed to be subclassed for creating models with custom behaviour.

This class is based on PyBaMM’s Simulation class. A PyBOP model is set up via a similar 3-step process. The pybamm_model attributes echoes the model attribute of a simulation, which tracks the model through the build process. Firstly, note that a PyBaMM model must first be built via build_model before a simulation or PyBOP model can be built. The 3-step process is then as follows.

The pybamm_model attribute is first defined as an instance of the imported PyBaMM model, using any given model options. This initial version of the model is saved as the _unprocessed_model for future reference. Next, the type of each parameter in the parameter set as well as the geometry of the model is set. Parameters may be set as an input, interpolant, functional or just a standard PyBaMM parameter. This version of the model is referred to as the model_with_set_params. After its creation, the pybamm_model attribute is updated to point at this version of the model. Finally, the model required for simulations is built by defining the mesh and processing the discretisation. The complete model is referred to as the built_model and this version is used to run simulations.

In order to rebuild a model with a different initial state or geometry, the built_model and the model_with_set_params must be cleared and the pybamm_model reset to the unprocessed_model in order to start the build process again.

_check_params(inputs: pybop.parameters.parameter.Inputs, parameter_set: pybop.ParameterSet, allow_infeasible_solutions: bool = True)[source]#

A compatibility check for the model parameters which can be implemented by subclasses if required, otherwise it returns True by default.

Parameters:
  • inputs (Inputs) – The input parameters for the simulation.

  • parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values.

  • allow_infeasible_solutions (bool, optional) – If True, infeasible parameter values will be allowed in the optimisation (default: True).

Returns:

A boolean which signifies whether the parameters are compatible.

Return type:

bool

abstract approximate_capacity(parameter_set: pybop.ParameterSet = None)[source]#

Calculate a new estimate for the nominal capacity based on the theoretical energy density and an average voltage.

This method must be implemented by subclasses.

Parameters:

parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values.

Raises:

NotImplementedError – If the method has not been implemented by the subclass.

build(parameters: pybop.Parameters | dict = None, inputs: pybop.parameters.parameter.Inputs | None = None, initial_state: dict | None = None, dataset: pybop.Dataset | None = None, check_model: bool = True) None[source]#

Construct the PyBaMM model, if not already built or if there are changes to any rebuild_parameters or the initial state.

This method initializes the model components, applies the given parameters, sets up the mesh and discretisation if needed, and prepares the model for simulations.

Parameters:
  • parameters (pybop.Parameters or Dict, optional) – A pybop Parameters class or dictionary containing parameter values to apply to the model.

  • inputs (Inputs) – The input parameters to be used when building the model.

  • initial_state (dict, optional) – A valid initial state, e.g. the initial state of charge or open-circuit voltage. Defaults to None, indicating that the existing initial state of charge (for an ECM) or initial concentrations (for an EChem model) will be used. Accepted keys either “Initial open-circuit voltage [V]” or ``”Initial SoC”`

  • dataset (pybop.Dataset or dict, optional) – The dataset to be used in the model construction.

  • check_model (bool, optional) – If True, the model will be checked for correctness after construction.

calculate_impedance(frequency)[source]#

Calculate the impedance for a given frequency.

This method computes the system matrix, solves the linear system, and calculates the impedance based on the solution.

Parameters:

like) (frequency (np.ndarray | list)

Return type:

The calculated impedance (complex np.ndarray).

abstract cell_mass(parameter_set: pybop.ParameterSet = None)[source]#

Calculate the cell mass in kilograms.

This method must be implemented by subclasses.

Parameters:

parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values.

Raises:

NotImplementedError – If the method has not been implemented by the subclass.

abstract cell_volume(parameter_set: pybop.ParameterSet = None)[source]#

Calculate the cell volume in m3.

This method must be implemented by subclasses.

Parameters:

parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values.

Raises:

NotImplementedError – If the method has not been implemented by the subclass.

check_params(inputs: pybop.parameters.parameter.Inputs | None = None, parameter_set: pybop.ParameterSet | None = None, allow_infeasible_solutions: bool = True)[source]#

Check compatibility of the model parameters.

Parameters:
  • inputs (Inputs) – The input parameters for the simulation.

  • parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values.

  • allow_infeasible_solutions (bool, optional) – If True, infeasible parameter values will be allowed in the optimisation (default: True).

Returns:

A boolean which signifies whether the parameters are compatible.

Return type:

bool

classify_parameters(parameters: pybop.Parameters | None = None, inputs: pybop.parameters.parameter.Inputs | None = None)[source]#

Check for any ‘rebuild_parameters’ which require a model rebuild and update the unprocessed_parameter_set if a rebuild is required.

Parameters:
  • parameters (Parameters, optional) – The optimisation parameters. Defaults to None, resulting in the internal pybop.Parameters object to be used.

  • inputs (Inputs, optional) – The input parameters for the simulation (default: None).

clear()[source]#

Clear any built PyBaMM model.

convert_to_pybamm_initial_state(initial_state: dict)[source]#

Convert an initial state of charge into a float and an initial open-circuit voltage into a string ending in “V”.

Parameters:

initial_state (dict) – A valid initial state, e.g. the initial state of charge or open-circuit voltage.

Returns:

If float, this value is used as the initial state of charge (as a decimal between 0 and 1). If str ending in “V”, this value is used as the initial open-circuit voltage.

Return type:

float or str

Raises:

ValueError – If the input is not a dictionary with a single, valid key.

copy()[source]#

Return a copy of the model.

Returns:

A copy of the model.

Return type:

BaseModel

get_parameter_info(print_info: bool = False)[source]#

Extracts the parameter names and types and returns them as a dictionary.

get_state(inputs: pybop.parameters.parameter.Inputs, t: float, x: numpy.ndarray) TimeSeriesState[source]#

Returns the given state for the problem (inputs are assumed constant since last reinit)

initialise_eis_simulation(inputs: pybop.parameters.parameter.Inputs | None = None)[source]#

Initialise the Electrochemical Impedance Spectroscopy (EIS) simulation.

This method sets up the mass matrix and solver, converts inputs to the appropriate format, extracts necessary attributes from the model, and prepares matrices for the simulation.

Parameters:

inputs (dict (optional)) – The input parameters for the simulation.

jaxify_solver(t_eval, calculate_sensitivities=False)[source]#

Jaxify the IDAKLU Solver and store a copy for future reconstruction. Handles sensitivity calculations during solver construction.

new_copy()[source]#

Return a new copy of the model, explicitly copying all the mutable attributes to avoid issues with shared objects.

Returns:

A new copy of the model.

Return type:

BaseModel

predict(inputs: pybop.parameters.parameter.Inputs | None = None, t_eval: numpy.array | None = None, parameter_set: pybop.ParameterSet | None = None, experiment: pybop.Experiment | None = None, initial_state: dict | None = None) dict[str, numpy.ndarray[numpy.float64]][source]#

Solve the model using PyBaMM’s simulation framework and return the solution.

This method sets up a PyBaMM simulation by configuring the model, parameters, experiment or time vector, and initial state of charge (if provided). Either ‘t_eval’ or ‘experiment’ must be provided. It then solves the simulation and returns the resulting solution object.

Parameters:
  • inputs (Inputs, optional) – Input parameters for the simulation. Defaults to None, indicating that the default parameters should be used.

  • t_eval (array-like, optional) – An array of time points at which to evaluate the solution. Defaults to None, which means the time points need to be specified within experiment or elsewhere.

  • parameter_set (Union[pybop.ParameterSet, pybamm.ParameterValues], optional) – A dict-like object containing the parameter values to use for the simulation. Defaults to the model’s current ParameterValues if None.

  • experiment (pybamm.Experiment, optional) – A PyBaMM Experiment object specifying the experimental conditions under which the simulation should be run. Defaults to None, indicating no experiment.

  • initial_state (dict, optional) – A valid initial state, e.g. the initial state of charge or open-circuit voltage. Defaults to None, indicating that the existing initial state of charge (for an ECM) or initial concentrations (for an EChem model) will be used.

Returns:

The solution object returned by a PyBaMM simulation, or a pybamm error in the case where the parameter values are infeasible and infeasible solutions are not allowed.

Return type:

pybamm.Solution

Raises:

ValueError – If the model has not been configured properly before calling this method or if PyBaMM models are not supported by the current simulation method.

reinit(inputs: pybop.parameters.parameter.Inputs, t: float = 0.0, x: numpy.ndarray | None = None) TimeSeriesState[source]#

Initialises the solver with the given inputs and returns the initial state of the problem

set_current_function(dataset: pybop.Dataset | dict)[source]#

Update the input current function according to the data.

Parameters:

dataset (pybop.Dataset or dict, optional) – The dataset to be used in the model construction.

set_initial_state(initial_state: dict, inputs: pybop.parameters.parameter.Inputs | None = None)[source]#

Set the initial state of charge or concentrations for the battery model.

Parameters:
  • initial_state (dict) – A valid initial state, e.g. the initial state of charge or open-circuit voltage.

  • inputs (Inputs) – The input parameters to be used when building the model.

set_parameters()[source]#

Assign the parameters to the model.

This method processes the model with the given parameters, sets up the geometry, and updates the model instance.

set_up_for_eis(model)[source]#

Set up the model for electrochemical impedance spectroscopy (EIS) simulations.

This method sets up the model for EIS simulations by adding the necessary algebraic equations and variables to the model. Originally developed by pybamm-eis: pybamm-team/pybamm-eis

Parameters:

model (pybamm.Model) – The PyBaMM model to be used for EIS simulations.

simulate(inputs: pybop.parameters.parameter.Inputs, t_eval: numpy.array, initial_state: dict | None = None) pybamm.Solution | list[numpy.float64][source]#

Execute the forward model simulation and return the result.

Parameters:
  • inputs (Inputs) – The input parameters for the simulation.

  • t_eval (array-like) – An array of time points at which to evaluate the solution.

  • initial_state (dict, optional) – A valid initial state, e.g. the initial state of charge or open-circuit voltage. Defaults to None, indicating that the existing initial state of charge (for an ECM) or initial concentrations (for an EChem model) will be used.

Returns:

The solution object returned by a PyBaMM simulation, or a pybamm error in the case where the parameter values are infeasible and infeasible solutions are not allowed.

Return type:

pybamm.Solution

Raises:

ValueError – If the model has not been built before simulation.

simulateEIS(inputs: pybop.parameters.parameter.Inputs, f_eval: list, initial_state: dict | None = None) dict[str, numpy.ndarray][source]#

Compute the forward model simulation with electrochemical impedance spectroscopy and return the result.

Parameters:
  • inputs (dict or array-like) – The input parameters for the simulation. If array-like, it will be converted to a dictionary using the model’s fit keys.

  • f_eval (array-like) – An array of frequency points at which to evaluate the solution.

Returns:

The simulation result corresponding to the specified signal.

Return type:

array-like

Raises:

ValueError – If the model has not been built before simulation.

simulateS1(inputs: pybop.parameters.parameter.Inputs, t_eval: numpy.array, initial_state: dict | None = None)[source]#

Perform the forward model simulation with sensitivities.

Parameters:
  • inputs (Inputs) – The input parameters for the simulation.

  • t_eval (array-like) – An array of time points at which to evaluate the solution and its sensitivities.

  • initial_state (dict, optional) – A valid initial state, e.g. the initial state of charge or open-circuit voltage. Defaults to None, indicating that the existing initial state of charge (for an ECM) or initial concentrations (for an EChem model) will be used.

Returns:

The solution object returned by a PyBaMM simulation, or a pybamm error in the case where the parameter values are infeasible and infeasible solutions are not allowed.

Return type:

pybamm.Solution

Raises:

ValueError – If the model has not been built before simulation.

step(state: TimeSeriesState, time: numpy.ndarray) TimeSeriesState[source]#

Step forward in time from the given state until the given time.

Parameters:
  • state (TimeSeriesState) – The current state of the model

  • time (np.ndarray) – The time to simulate the system until (in whatever time units the model is in)

_calculate_sensitivities = False#
allow_infeasible_solutions = True#
property built_initial_soc#
property built_model#
property calculate_sensitivities#
property disc#
eis = False#
property geometry#
property mesh#
property model_with_set_params#
name = 'Base Model'#
param_check_counter = 0#
param_checker = None#
property parameter_set#
parameters#
pybamm_model = None#
property solver#
property spatial_methods#
property submesh_types#
property var_pts#
class pybop.BaseOptimiser(cost, **optimiser_kwargs)[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:
  • cost (pybop.BaseCost or pints.ErrorMeasure) – An objective function to be optimised, which can be either a pybop.Cost or PINTS error measure

  • **optimiser_kwargs (optional) – Valid option keys and their values.

x0#

Initial parameter values for the optimisation.

Type:

numpy.ndarray

bounds#

Dictionary containing the parameter bounds with keys ‘lower’ and ‘upper’.

Type:

dict

sigma0#

Initial step size or standard deviation around x0. Either a scalar value (one standard deviation for all coordinates) or an array with one entry per dimension. Not all methods will use this information.

Type:

float or sequence

verbose#

If True, the optimisation progress is printed (default: False).

Type:

bool, optional

physical_viability#

If True, the feasibility of the optimised parameters is checked (default: False).

Type:

bool, optional

allow_infeasible_solutions#

If True, infeasible parameter values will be allowed in the optimisation (default: True).

Type:

bool, optional

log#

A log of the parameter values tried during the optimisation and associated costs.

Type:

dict

abstract _run()[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.

abstract _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.

cost_call(x: pybop.Inputs | list, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Call the cost function to minimise, applying any given transformation to the input parameters.

Parameters:
  • x (Inputs or list-like) – The input parameters for which the cost and optionally the gradient will be computed.

  • calculate_grad (bool, optional, default=False) – If True, both the cost and gradient will be computed. Otherwise, only the cost is computed.

Returns:

  • If calculate_grad is False, returns the computed cost (float).

  • If calculate_grad is True, returns a tuple containing the cost (float) and the gradient (np.ndarray).

Return type:

float or tuple

log_update(x=None, x_best=None, cost=None, cost_best=None, x0=None)[source]#

Update the log with new values.

Parameters:
  • x (list or array-like, optional) – Parameter values (default: None).

  • x_best (list or array-like, optional) – Parameter values corresponding to the best cost yet (default: None).

  • cost (list, optional) – Cost values corresponding to x (default: None).

  • cost_best – Cost values corresponding to x_best (default: None).

abstract name()[source]#

Returns the name of the optimiser, to be overwritten by child classes.

Returns:

The name of the optimiser

Return type:

str

run()[source]#

Run the optimisation and return the optimised parameters and final cost.

Returns:

results – The pybop optimisation result class.

Return type:

MultiOptimisationResult

set_allow_infeasible_solutions(allow: bool = True)[source]#

Set whether to allow infeasible solutions or not.

Parameters:

iterations (bool, optional) – Whether to allow infeasible solutions.

set_base_options()[source]#

Update the base optimiser options and remove them from the options dictionary.

_minimising = True#
_needs_sensitivities = False#
_transformation = None#
allow_infeasible_solutions = False#
bounds = None#
default_max_iterations = 1000#
log#
property minimising#
property needs_sensitivities#
parameters#
physical_viability = False#
result = None#
sigma0 = 0.02#
unset_options#
unset_options_store#
verbose = True#
x0#
class pybop.BasePintsOptimiser(cost, pints_optimiser, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BaseOptimiser

A base class for defining optimisation methods from the PINTS library.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • pints_optimiser (class) – The PINTS optimiser class to be used.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimization will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to track guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

_run()[source]#

Internal method to run the optimization using a PINTS optimiser.

Returns:

result – The result of the optimisation including the optimised parameter values and cost.

Return type:

pybop.Result

See also

This

_sanitise_inputs()[source]#

Check and remove any duplicate optimiser options.

_set_up_optimiser()[source]#

Parse optimiser options and create an instance of 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

name()[source]#

Returns the name of the PINTS optimisation strategy.

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='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_parallel(parallel=False)[source]#

Enable or disable parallel evaluation. Credit: PINTS

Parameters:

parallel (bool or int, optional) – If True, use as many worker processes as there are CPU cores. If an integer, use that many workers. If False or 0, disable parallelism (default: False).

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, use set_threshold(None). Credit: PINTS

Parameters:

threshold (float, optional) – The threshold below which the objective function value is considered optimal (default: None).

_absolute_tolerance = 1e-05#
_boundaries = None#
_callback = None#
_evaluations = None#
_iterations = None#
_max_evaluations = None#
_n_workers = 1#
_needs_sensitivities = None#
_pints_optimiser#
_relative_tolerance = 0.01#
_threshold = None#
_unchanged_max_iterations = 15#
_use_f_guessed = None#
option_methods#
class pybop.BasePintsSampler(log_pdf: pybop.LogPosterior, sampler, chains: int = 1, warm_up=None, x0=None, cov0=0.1, **kwargs)[source]#

Bases: pybop.BaseSampler

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

_check_stopping_criteria()[source]#
_create_evaluator()[source]#
_inverse_transform(y, log_pdf)[source]#
_process_multi_chain()[source]#
_process_single_chain()[source]#
run() numpy.ndarray | None[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 or sequential evaluation based on the configuration.

Returns:

A numpy array containing the samples from the posterior distribution if chains are stored in memory, otherwise returns None.

Return type:

np.ndarray

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 evaluator (parallel or sequential) 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#
_chains_in_memory#
_evaluation_files#
_initial_phase#
_initial_phase_iterations#
_iteration = 0#
_log_filename#
_log_to_screen#
_loop_iters = 0#
_max_iterations#
_n_workers = 1#
_needs_sensitivities#
_parallel#
_single_chain#
_verbose#
_warm_up = None#
iter_time#
sampler#
class pybop.BasePrior[source]#

A base class for defining prior distributions.

This class provides a foundation for implementing various prior distributions. It includes methods for calculating the probability density function (PDF), log probability density function (log PDF), and generating random variates from the distribution.

prior#

The underlying continuous random variable distribution.

Type:

scipy.stats.rv_continuous

loc#

The location parameter of the distribution.

Type:

float

scale#

The scale parameter of the distribution.

Type:

float

__call__(x)[source]#

Evaluates the distribution at x.

Parameters:

x (float) – The point(s) at which to evaluate the distribution.

Returns:

The value(s) of the distribution at x.

Return type:

float

__repr__()[source]#

Returns a string representation of the object.

abstract _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

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

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.

verify(x)[source]#

Verifies that the input is a numpy array and converts it if necessary.

property mean#

Get the mean of the distribution.

Returns:

The mean of the distribution.

Return type:

float

property sigma#

Get the standard deviation of the distribution.

Returns:

The standard deviation of the distribution.

Return type:

float

class pybop.BaseProblem(parameters: pybop.Parameters, model: pybop.BaseModel | None = None, check_model: bool = True, signal: list[str] | None = None, additional_variables: list[str] | None = None, initial_state: dict | None = None)[source]#

Base class for defining a problem within the PyBOP framework, compatible with PINTS.

Parameters:
  • parameters (pybop.Parameter or pybop.Parameters) – An object or list of the parameters for the problem.

  • model (object, optional) – The model to be used for the problem (default: None).

  • check_model (bool, optional) – Flag to indicate if the model should be checked (default: True).

  • signal (list[str]) – The signal to observe.

  • additional_variables (list[str], optional) – Additional variables to observe and store in the solution (default: []).

  • initial_state (dict, optional) – A valid initial state (default: None).

abstract evaluate(inputs: pybop.parameters.parameter.Inputs, eis=False)[source]#

Evaluate the model with the given parameters and return the signal.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Raises:

NotImplementedError – This method must be implemented by subclasses.

abstract evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#

Evaluate the model with the given parameters and return the signal and its derivatives.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Raises:

NotImplementedError – This method must be implemented by subclasses.

get_target()[source]#

Return the target dataset.

Returns:

The target dataset array.

Return type:

np.ndarray

set_initial_state(initial_state: dict | None = None)[source]#

Set the initial state to be applied to evaluations of the problem.

Parameters:

initial_state (dict, optional) – A valid initial state (default: None).

set_target(dataset: pybop.Dataset)[source]#

Set the target dataset.

Parameters:

target (Dataset) – The target dataset array.

_dataset = None#
_model#
_target = None#
additional_variables = []#
check_model = True#
property dataset#
domain = 'Time [s]'#
property domain_data#
eis = False#
exception = ['These parameter values are infeasible.']#
failure_output#
property model#
property n_outputs#
property n_parameters#
output_vars = ('Voltage [V]',)#
parameters#
signal = ['Voltage [V]']#
property target#
verbose = False#
class pybop.BaseSampler(log_pdf: pybop.LogPosterior, x0, chains: int, cov0: numpy.ndarray | float)[source]#

Base class for Monte Carlo samplers.

_ask_for_samples()[source]#
_check_initial_phase()[source]#
_end_initial_phase()[source]#
_finalise_logging()[source]#
_initialise_logging()[source]#
_initialise_storage()[source]#
abstract run() numpy.ndarray[source]#

Sample from the posterior distribution.

Returns:

Samples from the posterior distribution.

Return type:

np.ndarray

set_initial_phase_iterations(iterations=250)[source]#

Set the number of iterations for the initial phase of the sampler.

Parameters:

iterations (int) – Number of iterations for the initial phase.

set_max_iterations(iterations=500)[source]#

Set the maximum number of iterations for the sampler.

Parameters:

iterations (int) – Maximum number of iterations.

set_parallel(parallel=False)[source]#

Enable or disable parallel evaluation. Credit: PINTS

Parameters:

parallel (bool or int, optional) – If True, use as many worker processes as there are CPU cores. If an integer, use that many workers. If False or 0, disable parallelism (default: False).

_cov0#
_log_pdf#
_n_chains#
_x0#
class pybop.BaseSciPyOptimiser(cost, **optimiser_kwargs)[source]#

Bases: pybop.BaseOptimiser

A base class for defining optimisation methods from the SciPy library.

Parameters:
  • x0 (array_like) – Initial position from which optimisation will start.

  • bounds (dict, sequence or scipy.optimize.Bounds, optional) – Bounds for variables as supported by the selected method.

  • **optimiser_kwargs (optional) – Valid SciPy option keys and their values.

_run()[source]#

Internal method to run the optimisation using a PyBOP optimiser.

Returns:

result – The result of the optimisation including the optimised parameter values and cost.

Return type:

pybop.Result

_sanitise_inputs()[source]#

Check and remove any duplicate optimiser options.

key_mapping#
num_resamples = 40#
class pybop.CMAES(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Adapter for the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) optimiser in PINTS.

CMA-ES is 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:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.CMAES

PINTS implementation of CMA-ES algorithm.

class pybop.CuckooSearch(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Adapter for the Cuckoo Search optimiser in PyBOP.

Cuckoo Search is a population-based optimisation algorithm inspired by the brood parasitism of some cuckoo species. It is designed to be simple, efficient, and robust, and is suitable for global optimisation problems.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pybop.CuckooSearchImpl

PyBOP implementation of Cuckoo Search algorithm.

class pybop.CuckooSearchImpl(x0, sigma0=0.05, boundaries=None, pa=0.25)[source]#

Bases: pints.PopulationBasedOptimiser

Cuckoo Search (CS) optimisation algorithm, inspired by the brood parasitism of some cuckoo species. This algorithm was introduced by Yang and Deb in 2009.

The algorithm uses a population of host nests (solutions), where each cuckoo (new solution) tries to replace a worse nest in the population. The quality or fitness of the nests is determined by the cost function. A fraction of the worst nests is abandoned at each generation, and new ones are built randomly.

The pseudo-code for the Cuckoo Search is as follows:

  1. Initialise population of n host nests

  2. While (t < max_generations):
    1. Get a cuckoo randomly by Lévy flights

    2. Evaluate its quality/fitness F

    3. Choose a nest among n (say, j) randomly

    4. If (F > fitness of j):
      1. Replace j with the new solution

    5. Abandon a fraction (pa) of the worst nests and build new ones

    6. Keep the best solutions/nests

    7. Rank the solutions and find the current best

  3. End While

This implementation also uses a decreasing step size for the Lévy flights, calculated as sigma = sigma0 / sqrt(iterations), where sigma0 is the initial step size and iterations is the current iteration number.

Parameters: - pa: Probability of discovering alien eggs/solutions (abandoning rate)

References: - X. -S. Yang and Suash Deb, “Cuckoo Search via Lévy flights,”

2009 World Congress on Nature & Biologically Inspired Computing (NaBIC), Coimbatore, India, 2009, pp. 210-214, https://doi.org/10.1109/NABIC.2009.5393690.

  • S. Walton, O. Hassan, K. Morgan, M.R. Brown, Modified cuckoo search: A new gradient free optimisation algorithm, Chaos, Solitons & Fractals, Volume 44, Issue 9, 2011, Pages 710-718, ISSN 0960-0779, https://doi.org/10.1016/j.chaos.2011.06.004.

_suggested_population_size()[source]#

Inherited from Pints:PopulationBasedOptimiser. Returns a suggested population size, based on the dimension of the parameter space.

abandon_nests(idx)[source]#

Updates the nests to abandon the worst performers and reinitialise.

ask()[source]#

Returns a list of next points in the parameter-space to evaluate from the optimiser.

clip_nests(x)[source]#

Clip the input array to the boundaries if available.

f_best()[source]#

Returns the best score found so far.

levy_flight(alpha, size)[source]#

Generate step sizes via the Mantegna’s algorithm for Levy flights

name()[source]#

Returns the name of the optimiser.

running()[source]#

Returns True if the optimisation is in progress.

tell(replies)[source]#

Receives a list of function values from the cost function from points previously specified by self.ask(), and updates the optimiser state accordingly.

x_best()[source]#

Returns the best parameter values found so far.

_dim#
_f_best#
_fitness#
_iterations = 0#
_pa = 0.25#
_ready_for_tell = False#
_running = False#
_x_best#
beta = 1.5#
step_size#
class pybop.DREAM(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm.

This class extends the DREAM sampler from the PINTS library. DREAM is a Markov chain Monte Carlo (MCMC) method for sampling from a probability distribution. It combines the Differential Evolution (DE) algorithm with the Adaptive Metropolis (AM) algorithm to explore the parameter space more efficiently.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the DREAM sampler.

class pybop.Dataset(data_dictionary)[source]#

Represents a collection of experimental observations.

This class provides a structured way to store and work with experimental data, which may include applying operations such as interpolation.

Parameters:

data_dictionary (dict or instance of pybamm.solvers.solution.Solution) – The experimental data to store within the dataset.

__getitem__(key)[source]#

Return the data corresponding to a particular key.

Parameters:

key (str) – The name of a data series within the dataset.

Returns:

The data series corresponding to the key.

Return type:

list or np.ndarray

Raises:

ValueError – The key must exist in the dataset.

__repr__()[source]#

Return a string representation of the Dataset instance.

Returns:

A string that includes the type and contents of the dataset.

Return type:

str

__setitem__(key, value)[source]#

Set the data corresponding to a particular key.

Parameters:
  • key (str) – The name of the key to be set.

  • value (list or np.ndarray) – The data series to be stored in the dataset.

_check_data_consistency(domain_data: numpy.ndarray, signals: list[str]) None[source]#
static _check_frequency_constraints(freq_data: numpy.ndarray) None[source]#
static _check_time_constraints(time_data: numpy.ndarray) None[source]#
check(domain: str = None, signal: str | list[str] = None) bool[source]#

Check the consistency of a PyBOP Dataset against the expected format.

Parameters:
  • domain (str, optional) – The domain of the dataset. Defaults to “Time [s]”.

  • signal (str or List[str], optional) – The signal(s) to check. Defaults to [“Voltage [V]”].

Returns:

True if the dataset has the expected attributes.

Return type:

bool

Raises:

ValueError – If the time series and the data series are not consistent.

data#
names#
class pybop.DesignCost(problem)[source]#

Bases: pybop.costs.base_cost.BaseCost

Overwrites and extends BaseCost class for design-related cost functions.

Inherits all parameters and attributes from BaseCost.

Additional Attributes#

problemobject

The associated problem containing model and evaluation methods.

minimising = False#
class pybop.DesignProblem(model: pybop.BaseModel, parameters: pybop.Parameters, experiment: pybop.Experiment | None, check_model: bool = True, signal: list[str] | None = None, additional_variables: list[str] | None = None, initial_state: dict | None = None, update_capacity: bool = False)[source]#

Bases: pybop.BaseProblem

Problem class for design optimization problems.

Extends BaseProblem with specifics for applying a model to an experimental design.

Parameters:
  • model (object) – The model to apply the design to.

  • parameters (pybop.Parameter or pybop.Parameters) – An object or list of the parameters for the problem.

  • experiment (object) – The experimental setup to apply the model to.

  • check_model (bool, optional) – Flag to indicate if the model parameters should be checked for feasibility each iteration (default: True).

  • signal (str, optional) – The signal to fit (default: “Voltage [V]”).

  • additional_variables (list[str], optional) – Additional variables to observe and store in the solution (default additions are: [“Time [s]”, “Current [A]”]).

  • initial_state (dict, optional) – A valid initial state (default: {“Initial SoC”: 1.0}).

  • update_capacity (bool, optional) – If True, the nominal capacity is updated with an approximate value for each design.

evaluate(inputs: pybop.parameters.parameter.Inputs)[source]#

Evaluate the model with the given parameters and return the signal.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

y – The model output y(t) simulated with inputs.

Return type:

np.ndarray

set_initial_state(initial_state: dict)[source]#

Set the initial state to be applied to evaluations of the problem.

Parameters:

initial_state (dict, optional) – A valid initial state (default: None).

_dataset = None#
_domain_data#
_target#
additional_variables#
experiment#
update_capacity = False#
warning_patterns = ['Ah is greater than', 'Non-physical point encountered']#
class pybop.DifferentialEvolutionMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the Differential Evolution Markov Chain Monte Carlo (MCMC) algorithm.

This class extends the Differential Evolution MCMC sampler from the PINTS library. This MCMC method uses the Differential Evolution algorithm to explore the parameter space more efficiently by evolving a population of chains.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Differential Evolution MCMC sampler.

class pybop.DramACMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance Markov Chain Monte Carlo (MCMC) algorithm.

This class extends the DRAM Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method combines Delayed Rejection with Adaptive Metropolis to enhance the efficiency and robustness of the sampling process.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the DRAM Adaptive Covariance MCMC sampler.

class pybop.EmceeHammerMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the Emcee Hammer Markov Chain Monte Carlo (MCMC) algorithm.

This class extends the Emcee Hammer MCMC sampler from the PINTS library. The Emcee Hammer is an affine-invariant ensemble sampler for MCMC, which is particularly effective for high-dimensional parameter spaces.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Emcee Hammer MCMC sampler.

class pybop.Experiment(operating_conditions, period=None, temperature=None, termination=None)[source]#

Bases: Experiment

Light wrapper of the PyBaMM Experiment class for generating experiment conditions for PyBaMM models. Credit: PyBaMM

Base class for experimental conditions under which to run the model. In general, a list of operating conditions should be passed in. Each operating condition should be either a pybamm.step._Step class, created using one of the methods pybamm.step.current, pybamm.step.c_rate, pybamm.step.voltage , pybamm.step.power, pybamm.step.resistance, or pybamm.step.string, or a string, in which case the string is passed to pybamm.step.string.

Parameters:
  • operating_conditions (list) – List of operating conditions

  • period (string, optional) – Period (1/frequency) at which to record outputs. Default is 1 minute. Can be overwritten by individual operating conditions.

  • temperature (float, optional) – The ambient air temperature in degrees Celsius at which to run the experiment. Default is None whereby the ambient temperature is taken from the parameter set. This value is overwritten if the temperature is specified in a step.

  • termination (list, optional) – List of conditions under which to terminate the experiment. Default is None. This is different from the termination for individual steps. Termination for individual steps is specified in the step itself, and the simulation moves to the next step when the termination condition is met (e.g. 2.5V discharge cut-off). Termination for the experiment as a whole is specified here, and the simulation stops when the termination condition is met (e.g. 80% capacity).

class pybop.Exponential(scale, loc=0, random_state=None)[source]#

Bases: BasePrior

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

_logpdfS1(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'#
prior#
scale#
class pybop.ExponentialDecayModel(name: str = 'Experimental Decay Model', parameter_set: pybamm.ParameterValues = None, n_states: int = 1, solver=None)[source]#

Bases: pybop.models.base_model.BaseModel

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

n_states#

Number of states in the system (default is 1).

Type:

int

pybamm_model#

PyBaMM model representation.

Type:

pybamm.BaseModel

default_parameter_values#

Default parameter values for the model, with “k” (decay rate) and “y0” (initial condition).

Type:

pybamm.ParameterValues

Parameters:
  • name (str) – Name of the model (default: “Experimental Decay Model”).

  • parameter_set (pybamm.ParameterValues) – Parameter values for the model.

  • n_states (int) – Number of states in the system. Must be >= 1.

_built_initial_soc = None#
_built_model = None#
_disc = None#
_geometry#
_mesh = None#
_model_with_set_params = None#
_parameter_set#
_solver#
_spatial_methods#
_submesh_types#
_unprocessed_model#
_unprocessed_parameter_set#
_var_pts#
default_parameter_values#
geometric_parameters#
n_states = 1#
pybamm_model#
class pybop.FittingProblem(model: pybop.BaseModel, parameters: pybop.parameters.parameter.Parameters, dataset: pybop.Dataset, check_model: bool = True, signal: list[str] | None = None, additional_variables: list[str] | None = None, initial_state: dict | None = None)[source]#

Bases: pybop.BaseProblem

Problem class for fitting (parameter estimation) problems.

Extends BaseProblem with specifics for fitting a model to a dataset.

Parameters:
  • model (object) – The model to fit.

  • parameters (pybop.Parameter or pybop.Parameters) – An object or list of the parameters for the problem.

  • dataset (dictionary) – Dataset object containing the data to fit the model to.

  • check_model (bool, optional) – Flag to indicate if the model should be checked (default: True).

  • signal (str, optional) – The variable used for fitting (default: “Voltage [V]”).

  • additional_variables (list[str], optional) – Additional variables to observe and store in the solution (default additions are: [“Time [s]”]).

  • initial_state (dict, optional) – A valid initial state, e.g. the initial open-circuit voltage (default: None).

  • Attributes (Additional)

  • ---------------------

  • dataset – The dictionary from a Dataset object containing the signal keys and values to fit the model to.

  • domain_data (np.ndarray) – The domain points in the dataset.

  • n_domain_data (int) – The number of domain points.

  • target (np.ndarray) – The target values of the signals.

_evaluate(func, inputs, calculate_grad=False) dict[str, numpy.ndarray[numpy.float64]][source]#

Perform simulation using the specified method and handle exceptions.

Parameters:
  • func (callable) – The method to be used for simulation.

  • inputs (Inputs) – Parameters for evaluation of the model.

Returns:

The simulated model output.

Return type:

dict[str, np.ndarray[np.float64]]

evaluate(inputs: pybop.parameters.parameter.Inputs) dict[str, numpy.ndarray[numpy.float64]][source]#

Evaluate the model with the given parameters and return the signal.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

y – The simulated model output y(t) for self.eis == False, and y(ω) for self.eis == True for the given inputs.

Return type:

np.ndarray

evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#

Evaluate the model with the given parameters and return the signal and its derivatives.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

A tuple containing the simulation result y(t) as a dictionary and the sensitivities dy/dx(t) evaluated with given inputs.

Return type:

tuple[dict, np.ndarray]

set_initial_state(initial_state: dict | None = None)[source]#

Set the initial state to be applied to evaluations of the problem.

Parameters:

initial_state (dict, optional) – A valid initial state (default: None).

_dataset#
_domain_data#
_n_parameters#
n_data#
class pybop.Gaussian(mean, sigma, random_state=None)[source]#

Bases: BasePrior

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

_logpdfS1(x)[source]#

Evaluates the first derivative of the gaussian (log) 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

_multip#
_n_parameters = 1#
_offset#
loc#
name = 'Gaussian'#
prior#
scale#
sigma2#
class pybop.GaussianLogLikelihood(problem: pybop.problems.base_problem.BaseProblem, sigma0: float | list[float] | list[pybop.parameters.parameter.Parameter] = 0.01, dsigma_scale: float = 1.0)[source]#

Bases: BaseLikelihood

This class represents a Gaussian Log Likelihood, which assumes that the data follows a Gaussian distribution and computes the log-likelihood of observed data under this assumption.

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

_dsigma_scale#

Scale factor for derivative of standard deviation.

Type:

float

_add_sigma_parameters(sigma0)[source]#
_add_single_sigma(index, value)[source]#
_pad_sigma0(sigma0)[source]#
compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Compute the Gaussian log-likelihood for the given parameters.

This method only computes the likelihood, without calling problem.evaluate().

Returns:

The log-likelihood value, or -inf if the standard deviations are non-positive.

Return type:

float

_dsigma_scale = 1.0#
_logpi#
property dsigma_scale#

Scaling factor for the dsigma term in the gradient calculation.

sigma#
transformation = None#
class pybop.GaussianLogLikelihoodKnownSigma(problem: pybop.problems.base_problem.BaseProblem, sigma0: list[float] | float)[source]#

Bases: BaseLikelihood

This class represents a Gaussian Log Likelihood with a known sigma, which assumes that the data follows a Gaussian distribution and computes the log-likelihood of observed data under this assumption.

Parameters:

sigma0 (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.

check_sigma0(sigma0: numpy.ndarray | float)[source]#

Check the validity of sigma0.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Compute the Gaussian log-likelihood for the given parameters with known sigma.

This method only computes the likelihood, without calling the problem.evaluateS1.

_multip#
_offset#
sigma2#
class pybop.GradientDescent(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements a simple gradient descent optimisation algorithm.

This class extends the gradient descent optimiser from the PINTS library, designed to minimize a scalar function of one or more variables.

Note that this optimiser does not support boundary constraints.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.GradientDescent

The PINTS implementation this class is based on.

class pybop.GradientDescentImpl(x0, sigma0=0.02, boundaries=None)[source]#

Bases: pints.Optimiser

Gradient descent method with a fixed, per-dimension learning rate.

Gradient descent updates the current position in the direction of the steepest descent, as determined by the negative of the gradient of the function.

The update rule for each iteration is given by:

\[x_{t+1} = x_t - \eta * \nabla f(x_t)\]
where:
  • \(x_t\) are the current parameter values at iteration t,

  • \(\nabla f(x_t)\) is the gradient of the function at \(x_t\),

  • \(\eta\) is the learning rate, which controls the step size.

This class reimplements the Pints’ Gradient Descent, but with multidimensional, fixed learning rates. Original creation and credit is attributed to Pints.

Parameters:
  • x0 (array-like) – Initial starting point for the optimisation. This should be a 1D array representing the starting parameter values for the function being optimised.

  • sigma0 (float or array-like, optional) – Initial learning rate or rates for each dimension. If a scalar is provided, the same learning rate is applied across all dimensions. If an array is provided, each dimension will have its own learning rate. Defaults to 0.02.

  • boundaries (pybop.Boundaries, optional) – Boundaries for the parameters. This optimiser ignores boundaries and operates as an unbounded method. Defaults to None.

_x_best#

The best parameter values (solution) found so far.

Type:

array-like

_f_best#

The best function value (objective value) found so far.

Type:

float

_current#

The current parameter values at the latest iteration.

Type:

array-like

_eta#

The current learning rate(s). Can be a scalar or per-dimension array.

Type:

array-like

_running#

Indicates whether the optimisation process is running.

Type:

bool

_ready_for_tell#

Indicates whether the optimiser is ready to receive feedback from the objective function.

Type:

bool

ask()[source]#

Proposes the next point for evaluation.

f_best()[source]#

Returns the best objective value found.

learning_rate()[source]#

Returns the learning rate(s).

n_hyper_parameters()[source]#

Returns the number of hyper-parameters (learning rate).

name()[source]#

Returns the name of the optimiser.

needs_sensitivities()[source]#

Indicates this optimiser requires gradient information.

running()[source]#

Returns whether the optimiser is running.

set_hyper_parameters(x)[source]#

Sets hyper-parameters (learning rate).

set_learning_rate(eta)[source]#

Sets the learning rate. Supports per-dimension rates.

Parameters:

eta (float or array-like) – New learning rate(s).

tell(reply)[source]#

Updates optimiser with function evaluation results.

x_best()[source]#

Returns the best solution found.

_eta#
_f_best#
_ready_for_tell = False#
_running = False#
class pybop.GravimetricEnergyDensity(problem)[source]#

Bases: DesignCost

Calculates the gravimetric energy density (specific energy) of a battery cell, when applied to a normalised discharge from upper to lower voltage limits. The goal of maximising the energy density is achieved with self.minimising=False.

The gravimetric energy density [Wh.kg-1] is calculated as

\[\frac{1}{3600 m} \int_{t=0}^{t=T} I(t) V(t) \mathrm{d}t\]

where m is the cell mass, t is the time, T is the total time, I is the current and V is the voltage. The factor of 1/3600 is included to convert from seconds to hours.

Inherits all parameters and attributes from DesignCost.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float[source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal. Note: not used in design optimisation classes.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The gravimetric energy density or -infinity in case of infeasible parameters.

Return type:

float

class pybop.GravimetricPowerDensity(problem, target_time: int | float = 3600)[source]#

Bases: DesignCost

Calculates the gravimetric power density (specific power) of a battery cell, when applied to a discharge from upper to lower voltage limits. The goal of maximising the power density is achieved with self.minimising=False.

The time-averaged gravimetric power density [W.kg-1] is calculated as

\[\frac{1}{3600 m T} \int_{t=0}^{t=T} I(t) V(t) \mathrm{d}t\]

where m is the cell mass, t is the time, T is the total time, I is the current and V is the voltage. The factor of 1/3600 is included to convert from seconds to hours.

Inherits all parameters and attributes from DesignCost.

Additional parameters#

target_timeint

The length of time (seconds) over which the power should be sustained.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float[source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal. Note: not used in design optimisation classes.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The gravimetric power density or -infinity in case of infeasible parameters.

Return type:

float

target_time = 3600#
class pybop.HaarioACMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Haario Adaptive Covariance MCMC sampler.

class pybop.HaarioBardenetACMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Haario-Bardenet Adaptive Covariance MCMC sampler.

class pybop.HamiltonianMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Hamiltonian MCMC sampler.

class pybop.IRPropMin(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements the iRpropMin optimisation algorithm.

This class inherits from the PINTS IRPropMin class, which is an optimiser that uses resilient backpropagation with weight-backtracking. It is designed to handle problems with large plateaus, noisy gradients, and local minima.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.IRPropMin

The PINTS implementation this class is based on.

class pybop.JointLogPrior(*priors: BasePrior)[source]#

Bases: BasePrior

Represents a joint prior distribution composed of multiple prior distributions.

Parameters:

priors (BasePrior) – One or more prior distributions to combine into a joint distribution.

__repr__() str[source]#

Returns a string representation of the object.

_logpdfS1(x: float | numpy.ndarray) tuple[float, numpy.ndarray][source]#

Evaluates the first derivative of the joint log-prior distribution at a given point.

Parameters:

x (Union[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]

logpdf(x: float | numpy.ndarray) float[source]#

Evaluates the joint log-prior distribution at a given point.

Parameters:

x (Union[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

_n_parameters = 0#
_priors: list[BasePrior] = []#
class pybop.LogPosterior(log_likelihood: BaseLikelihood, log_prior: pybop.BasePrior | scipy.stats.rv_continuous | None = None, gradient_step: float = 0.001)[source]#

Bases: BaseMetaLikelihood

The Log Posterior for a given problem.

Computes the log posterior which is proportional to the sum of the log likelihood and the log prior.

Parameters:
  • log_likelihood (BaseLikelihood) – The likelihood class of type BaseLikelihood.

  • log_prior (Optional, Union[pybop.BasePrior, stats.rv_continuous]) – The prior class of type BasePrior or stats.rv_continuous. If not provided, the prior class will be taken from the parameter priors constructed in the pybop.Parameters class.

  • gradient_step (float, default: 1e-3) – The step size for the finite-difference gradient calculation if the log_prior is not of type BasePrior.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Calculate the posterior cost for a given forward model prediction.

Parameters:
  • y (dict) – The data for which to evaluate the cost.

  • dy (np.ndarray, optional) – The correspond sensitivities in the data.

  • calculate_grad (bool, optional) – Whether to calculate the gradient of the cost function.

Returns:

The posterior cost, and optionally the gradient.

Return type:

Union[float, Tuple[float, np.ndarray]]

gradient_step = 0.001#
property prior: pybop.parameters.priors.BasePrior#
class pybop.MALAMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the MALA MCMC sampler.

class pybop.MCMCSampler(log_pdf, chains, sampler=AdaptiveCovarianceMCMC, x0=None, cov0=None, **kwargs)[source]#

A high-level class for MCMC sampling.

This class provides an alternative API to the PyBOP.Sampler() API, specifically allowing for single user-friendly interface for the optimisation process.

__getattr__(attr)[source]#

Delegate attribute access to the underlying sampler if the attribute is not found in the MCMCSampler instance.

Parameters:

attr (str) – The attribute name to be accessed.

Returns:

The attribute value from the underlying sampler.

Return type:

Any

Raises:

AttributeError – If the attribute is not found in both the MCMCSampler instance and the underlying sampler.

__setattr__(name: str, value) None[source]#

Delegate attribute setting to the underlying sampler if the attribute exists in the sampler and not in the MCMCSampler instance.

Parameters:
  • name (str) – The attribute name to be set.

  • value (Any) – The value to be set to the attribute.

run()[source]#

Run the MCMC sampling process.

Returns:

The result of the sampling process.

Return type:

list

sampler#
class pybop.MetropolisRandomWalkMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Metropolis Random Walk MCMC sampler.

class pybop.Minkowski(problem, p: float = 2.0)[source]#

Bases: pybop.costs.base_cost.BaseCost

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

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The Minkowski cost.

Return type:

float

p#
class pybop.MonomialGammaHamiltonianMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Monomial Gamma Hamiltonian MCMC sampler.

class pybop.MultiFittingProblem(*args)[source]#

Bases: pybop.BaseProblem

Problem class for joining mulitple fitting problems into one combined fitting problem.

Extends BaseProblem in a similar way to FittingProblem but for multiple parameter estimation problems, which must first be defined individually.

Additional Attributes#

problemspybop.FittingProblem

The individual PyBOP fitting problems.

evaluate(inputs: pybop.parameters.parameter.Inputs)[source]#

Evaluate the model with the given parameters and return the signal.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

y – The model output y(t) simulated with given inputs.

Return type:

np.ndarray

evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#

Evaluate the model with the given parameters and return the signal and its derivatives.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

A tuple containing the simulation result y(t) as a dictionary and the sensitivities dy/dx(t) evaluated with given inputs.

Return type:

tuple[dict, np.ndarray]

set_initial_state(initial_state: dict | None = None)[source]#

Set the initial state to be applied to evaluations of the problem.

Parameters:

initial_state (dict, optional) – A valid initial state (default: None).

_dataset#
_domain_data#
n_domain_data#
problems = []#
class pybop.MultiOptimisationResult[source]#

Multi run optimisation result class. Stores the results of multiple optimisation runs.

results#

The list of OptimisationResults for each optimisation run

Type:

list

Properties#
----------
x#

The solution of the best optimisation run.

Type:

ndarray

final_cost#

The cost associated with the best solution x.

Type:

float

n_iterations#

Number of iterations performed by the optimiser for the best optimisation run.

Type:

int

scipy_result#

The result obtained from a SciPy optimiser for the best optimisation run.

Type:

scipy.optimize.OptimizeResult, optional

time#

The total time across all optimisation runs.

Type:

float

__str__() str[source]#

A string representation of the MultiOptimisationResult object.

Returns:

A formatted string containing optimisation result information.

Return type:

str

add_run(result: OptimisationResult)[source]#

Adds a new optimisation result.

average_iterations() float | None[source]#

Calculates the average number of iterations across all runs.

best_run() OptimisationResult | None[source]#

Returns the result with the best final cost.

best_x() float | None[source]#

Returns the best parameters, x across the optimisation

check_physical_viability(x)[source]#
get_scipy_result()[source]#
total_runtime() float | None[source]#

Calculates the total runtime across all runs.

property final_cost#
property n_evaluations#
property n_iterations#
results: list[OptimisationResult] = []#
property scipy_result#
property time#
property x#
property x0#
class pybop.NUTS(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements the No-U-Turn Sampler (NUTS) algorithm.

This class extends the NUTS sampler from the PINTS library. NUTS is a Markov chain Monte Carlo (MCMC) method for sampling from a probability distribution. It is an extension of the Hamiltonian Monte Carlo (HMC) method, which uses a dynamic integration time to explore the parameter space more efficiently.

Parameters:
  • log_pdf ((pybop.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the NUTS sampler.

class pybop.NelderMead(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements the Nelder-Mead downhill simplex method from PINTS.

This is a deterministic local optimiser. In most update steps it performs either one evaluation, or two sequential evaluations, so that it will not typically benefit from parallelisation.

Note that this optimiser does not support boundary constraints.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.NelderMead

PINTS implementation of Nelder-Mead algorithm.

class pybop.Observer(parameters: pybop.parameters.parameter.Parameters, model: pybop.models.base_model.BaseModel, check_model: bool = True, signal: list[str] | None = None, additional_variables: list[str] | None = None, initial_state: dict | None = None)[source]#

Bases: pybop.BaseProblem

An observer of a time series state. Observers:
  1. keep track of the distribution of a current time series model state

  2. predict forward in time the distribution of the state

  3. update the distribution of the state with new observations

Parameters:
  • parameters (pybop.Parameter or pybop.Parameters) – An object or list of the parameters for the problem.

  • model (BaseModel) – The model to observe.

  • check_model (bool, optional) – Flag to indicate if the model should be checked (default: True).

  • signal (list[str]) – The signal to observe.

  • additional_variables (list[str], optional) – Additional variables to observe and store in the solution (default: []).

  • initial_state (dict, optional) – A valid initial state, e.g. the initial open-circuit voltage (default: None).

evaluate(inputs: pybop.models.base_model.Inputs)[source]#

Evaluate the model with the given parameters and return the signal.

Parameters:

inputs (Inputs) – Parameters for evaluation of the model.

Returns:

y – The model output y(t) simulated with given inputs.

Return type:

np.ndarray

get_current_covariance() Covariance[source]#

Returns the current covariance of the model.

get_current_measure() numpy.ndarray[source]#

Returns the current measurement.

get_current_state() pybop.models.base_model.TimeSeriesState[source]#

Returns the current state of the model.

get_current_time() float[source]#

Returns the current time.

get_measure(x: pybop.models.base_model.TimeSeriesState) numpy.ndarray[source]#
log_likelihood(values: dict, times: numpy.ndarray, inputs: pybop.models.base_model.Inputs) float[source]#

Returns the log likelihood of the model given the values and inputs.

Parameters:
  • values (np.ndarray) – The values of the model.

  • times (np.ndarray) – The times at which to observe the model.

  • inputs (Inputs) – The inputs to the model.

observe(time: float, value: numpy.ndarray | None = None) float[source]#

Predict the time series model until t = time and optionally observe the measurement value.

Returns the log likelihood of the model given the value and inputs. If no value is given, the log likelihood is 0.

The base observer does not perform any value observation and always returns 0.

Parameters:
  • time (float) – The time of the new observation.

  • value (np.ndarray (optional)) – The new observation.

reset(inputs: pybop.models.base_model.Inputs) None[source]#
Covariance#
_state#
class pybop.ObserverCost(observer: pybop.observers.observer.Observer)[source]#

Bases: pybop.costs.base_cost.BaseCost

Observer cost function.

Computes the cost function for an observer model, which is log likelihood of the data points given the model parameters.

Inherits all parameters and attributes from BaseCost.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float[source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The observer cost (negative of the log likelihood).

Return type:

float

_has_separable_problem = False#
_observer#
class pybop.Optimisation(cost, optimiser=None, **optimiser_kwargs)[source]#

A high-level class for optimisation using PyBOP or PINTS optimisers.

This class provides an alternative API to the PyBOP.Optimiser() API, specifically allowing for single user-friendly interface for the optimisation process.The class can be used with either PyBOP or PINTS optimisers.

Parameters:
  • cost (pybop.BaseCost or pints.ErrorMeasure) – An objective function to be optimized, which can be either a pybop.Cost

  • optimiser (pybop.Optimiser or subclass of pybop.BaseOptimiser, optional) – An optimiser from either the PINTS or PyBOP framework to perform the optimisation (default: None).

  • sigma0 (float or sequence, optional) – Initial step size or standard deviation for the optimiser (default: None).

  • verbose (bool, optional) – If True, the optimisation progress is printed (default: False).

  • physical_viability (bool, optional) – If True, the feasibility of the optimised parameters is checked (default: True).

  • allow_infeasible_solutions (bool, optional) – If True, infeasible parameter values will be allowed in the optimisation (default: True).

All attributes from the pybop.optimiser() class
__getattr__(attr)[source]#
__setattr__(name: str, value) None[source]#
run()[source]#
class pybop.OptimisationResult(optim: BaseOptimiser, x: pybop.Inputs | numpy.ndarray = None, final_cost: float | None = None, n_iterations: int | None = None, n_evaluations: int | None = None, time: float | None = None, scipy_result=None)[source]#

Stores the result of the optimisation.

x#

The solution of the optimisation.

Type:

ndarray

final_cost#

The cost associated with the solution x.

Type:

float

n_iterations#

Number of iterations performed by the optimiser.

Type:

int

scipy_result#

The result obtained from a SciPy optimiser.

Type:

scipy.optimize.OptimizeResult, optional

__str__() str[source]#

A string representation of the OptimisationResult object.

Returns:

A formatted string containing optimisation result information.

Return type:

str

_calculate_final_cost() float[source]#

Calculate the final cost using the cost function and optimised parameters.

Returns:

The calculated final cost.

Return type:

float

_validate_parameters() None[source]#

Validate the optimised parameters and ensure they produce a finite cost value.

Raises:

ValueError – If the optimized parameters do not produce a finite cost value.

check_physical_viability(x)[source]#

Check if the optimised parameters are physically viable.

Parameters:

x (array-like) – Optimised parameter values.

get_scipy_result() scipy.optimize.OptimizeResult | None[source]#

Get the SciPy optimisation result object.

Returns:

The SciPy optimisation result object if available, None otherwise.

Return type:

OptimizeResult or None

_transformation#
cost#
final_cost#
fisher = None#
minimising#
n_evaluations = None#
n_iterations = None#
optim#
scipy_result = None#
time = None#
x#
class pybop.PSO(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements a particle swarm optimisation (PSO) algorithm.

This class extends the PSO optimiser from the PINTS library. PSO is a metaheuristic optimisation method inspired by the social behavior of birds flocking or fish schooling, suitable for global optimisation problems.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.PSO

The PINTS implementation this class is based on.

class pybop.Parameter(name, initial_value=None, true_value=None, prior=None, bounds=None, transformation=None)[source]#

Represents a parameter within the PyBOP framework.

This class encapsulates the definition of a parameter, including its name, prior distribution, initial value, bounds, and a margin to ensure the parameter stays within feasible limits during optimization or sampling.

Parameters:
  • name (str) – The name of the parameter.

  • initial_value (float, optional) – The initial value to be assigned to the parameter. Defaults to None.

  • prior (scipy.stats distribution, optional) – The prior distribution from which parameter values are drawn. Defaults to None.

  • bounds (tuple, optional) – A tuple defining the lower and upper bounds for the parameter. Defaults to None.

Raises:

ValueError – If the lower bound is not strictly less than the upper bound, or if the margin is set outside the interval (0, 1).

__repr__()[source]#

Return a string representation of the Parameter instance.

Returns:

A string including the parameter’s name, prior, bounds, and current value.

Return type:

str

get_initial_value(apply_transform: bool = False) float[source]#

Return the initial value of each parameter.

Parameters:

apply_transform (bool) – If True, the transformation is applied to the output (default: False).

rvs(n_samples: int = 1, random_state=None, apply_transform: bool = False)[source]#

Draw random samples from the parameter’s prior distribution.

The samples are constrained to be within the parameter’s bounds, excluding a predefined margin at the boundaries.

Parameters:
  • n_samples (int) – The number of samples to draw (default: 1).

  • random_state (int, optional) – The random state seed for reproducibility (default: None).

  • apply_transform (bool) – If True, the transformation is applied to the output (default: False).

Returns:

An array of samples drawn from the prior distribution within the parameter’s bounds.

Return type:

array-like

set_bounds(bounds=None, boundary_multiplier=15)[source]#

Set the upper and lower bounds and applies default values from the prior if no bounds are provided. The default values are calculated using the boundary_multiplier and the parameters prior sigma value.

Parameters:
  • bounds (tuple, optional) – A tuple defining the lower and upper bounds for the parameter. Defaults to None.

  • boundary_multiplier (float, optional) – Used to define the bounds when no bounds are passed but the parameter has a prior distribution (default: 15).

Raises:

ValueError – If the lower bound is not strictly less than the upper bound, or if the margin is set outside the interval (0, 1).

set_margin(margin)[source]#

Set the margin to a specified positive value less than 1.

The margin is used to ensure parameter samples are not drawn exactly at the bounds, which may be problematic in some optimization or sampling algorithms.

Parameters:

margin (float) – The new margin value to be used, which must be in the interval (0, 1).

Raises:

ValueError – If the margin is not between 0 and 1.

update(initial_value=None, value=None)[source]#

Update the parameter’s current value.

Parameters:

value (float) – The new value to be assigned to the parameter.

applied_prior_bounds = False#
bounds = None#
initial_value = None#
lower_bound = None#
margin = 0.0001#
name#
prior = None#
transformation = None#
true_value = None#
upper_bound = None#
value = None#
class pybop.ParameterSet(json_path=None, params_dict=None)[source]#

Handles the import and export of parameter sets for battery models.

This class provides methods to load parameters from a JSON file and to export them back to a JSON file. It also includes custom logic to handle special cases, such as parameter values that require specific initialization.

Parameters:
  • json_path (str, optional) – Path to a JSON file containing parameter data. If provided, parameters will be imported from this file during initialization.

  • params_dict (dict, optional) – A dictionary of parameters to initialize the ParameterSet with. If not provided, an empty dictionary is used.

__call__()[source]#
__getitem__(key)[source]#
__setitem__(key, value)[source]#
static evaluate_symbol(symbol: pybamm.Symbol | numbers.Number, params: dict)[source]#

Evaluate a parameter in the parameter set.

Parameters:

symbol (pybamm.Symbol or Number) – The parameter to evaluate.

Returns:

The value of the parameter.

Return type:

float

export_parameters(output_json_path, fit_params=None)[source]#

Exports parameters to a JSON file specified by output_json_path.

The current state of the params attribute is written to the file. If fit_params is provided, these parameters are updated before export. Non-serializable values are handled and noted in the output JSON.

Parameters:
  • output_json_path (str) – The file path where the JSON output will be saved.

  • fit_params (list of fitted parameter objects, optional) – Parameters that have been fitted and need to be included in the export.

Raises:

ValueError – If there are no parameters to export.

import_from_bpx(json_path=None)[source]#

Imports parameters from a JSON file in the BPX format specified by the json_path attribute. Credit: PyBaMM

If a json_path is provided at initialization or as an argument, that JSON file is loaded and the parameters are stored in the params attribute.

Parameters:

json_path (str, optional) – Path to the JSON file from which to import parameters. If provided, it overrides the instance’s json_path.

Returns:

The dictionary containing the imported parameters.

Return type:

dict

Raises:

FileNotFoundError – If the specified JSON file cannot be found.

import_parameters(json_path=None)[source]#

Imports parameters from a JSON file specified by the json_path attribute.

If a json_path is provided at initialization or as an argument, that JSON file is loaded and the parameters are stored in the params attribute. Special cases are handled appropriately.

Parameters:

json_path (str, optional) – Path to the JSON file from which to import parameters. If provided, it overrides the instance’s json_path.

Returns:

The dictionary containing the imported parameters.

Return type:

dict

Raises:

FileNotFoundError – If the specified JSON file cannot be found.

is_json_serializable(value)[source]#

Determines if the given value can be serialized to JSON format.

Parameters:

value (any) – The value to check for JSON serializability.

Returns:

True if the value is JSON serializable, False otherwise.

Return type:

bool

keys() list[source]#

A list of parameter names

classmethod pybamm(name, formation_concentrations=False)[source]#

Retrieves a PyBaMM parameter set by name.

Parameters:
  • name (str) – The name of the PyBaMM parameter set to retrieve.

  • set_formation_concentrations (bool, optional) – If True, re-calculates the initial concentrations of lithium in the active material (default: False).

Returns:

A PyBaMM parameter set corresponding to the provided name.

Return type:

pybamm.ParameterValues

update(params_dict=None)[source]#

Update the parameter dictionary.

chemistry = None#
json_path = None#
params#
class pybop.Parameters(*args)[source]#

Represents a set of uncertain parameters within the PyBOP framework.

This class encapsulates the definition of a parameter, including its name, prior distribution, initial value, bounds, and a margin to ensure the parameter stays within feasible limits during optimisation or sampling.

Parameters:

parameter_list (pybop.Parameter or Dict)

__getitem__(key: str) Parameter[source]#

Return the parameter dictionary corresponding to a particular key.

Parameters:

key (str) – The name of a parameter.

Returns:

The Parameter object.

Return type:

pybop.Parameter

Raises:

ValueError – The key must be the name of one of the parameters.

__iter__()[source]#
__len__() int[source]#
__next__()[source]#
__repr__()[source]#

Return a string representation of the Parameters instance.

Returns:

A string including the number of parameters and a summary of each parameter.

Return type:

str

add(parameter)[source]#

Construct the parameter class with a name, initial value, prior, and bounds.

as_dict(values=None) dict[source]#
Parameters:

values (list or str, optional) – A list of parameter values or one of the strings “initial” or “true” which can be used to obtain a dictionary of parameters.

Returns:

A parameters dictionary.

Return type:

Inputs

construct_transformation()[source]#

Create a ComposedTransformation object from the individual parameter transformations.

current_value() numpy.ndarray[source]#

Return the current value of each parameter.

get_bounds(apply_transform: bool = False) dict[source]#

Get bounds, for either all or no parameters.

Parameters:

apply_transform (bool) – If True, the transformation is applied to the output (default: False).

get_bounds_for_plotly(apply_transform: 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_sigma0(apply_transform: bool = False) list[source]#

Get the standard deviation, for either all or no parameters.

Parameters:

apply_transform (bool) – If True, the transformation is applied to the output (default: False).

get_transformations()[source]#

Get the transformations for each parameter.

initial_value(apply_transform: bool = False) numpy.ndarray[source]#

Return the initial value of each parameter.

Parameters:

apply_transform (bool) – If True, the transformation is applied to the output (default: False).

join(parameters=None)[source]#

Join two Parameters objects into the first by copying across each Parameter.

Parameters:

parameters (pybop.Parameters)

keys() list[source]#

A list of parameter names

priors() list[source]#

Return the prior distribution of each parameter.

remove(parameter_name)[source]#

Remove the Parameter object from the Parameters dictionary.

reset_initial_value(apply_transform: bool = False) numpy.ndarray[source]#

Reset and return the initial value of each parameter.

Parameters:

apply_transform (bool) – If True, the transformation is applied to the output (default: False).

rvs(n_samples: int = 1, apply_transform: bool = False) numpy.ndarray[source]#

Draw random samples from each parameter’s prior distribution.

The samples are constrained to be within the parameter’s bounds, excluding a predefined margin at the boundaries.

Parameters:
  • n_samples (int) – The number of samples to draw (default: 1).

  • apply_transform (bool) – If True, the transformation is applied to the output (default: False).

Returns:

An array of samples drawn from the prior distribution within each parameter’s bounds.

Return type:

array-like

true_value() numpy.ndarray[source]#

Return the true value of each parameter.

update(initial_values=None, values=None, bounds=None)[source]#

Set value of each parameter.

verify(inputs: Inputs | None = None)[source]#

Verify that the inputs are an Inputs dictionary or numeric values which can be used to construct an Inputs dictionary

Parameters:

inputs (Inputs or numeric)

param#
class pybop.PopulationMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Population MCMC sampler.

class pybop.PosteriorSummary(chains: numpy.ndarray, significant_digits: int = 4)[source]#
_autocorrelate_negative(autocorrelation)[source]#

Returns the index of the first negative entry in autocorrelation, or len(autocorrelation) if a negative entry is not found.

_calculate_statistics(fun, attr_name, *args, **kwargs)[source]#

Calculate statistics from callable fun.

autocorrelation(x: numpy.ndarray) numpy.ndarray[source]#

Computes the autocorrelation (Pearson correlation coefficient) of a numpy array representing samples.

effective_sample_size(mixed_chains=False)[source]#

Computes the effective sample size (ESS) for each parameter in each chain.

Parameters:

mixed_chains (bool, optional) – If True, the ESS is computed for all samplers mixed into a single chain. Defaults to False.

Returns:

A list of effective sample sizes for each parameter in each chain, or for the mixed chain if mixed_chains is True.

Return type:

list

Raises:

ValueError – If there are fewer than two samples in the data.

get_summary_statistics()[source]#

Calculate summary statistics for the posterior samples.

Returns: dict: Summary statistics including mean, median, standard deviation, and 95% credible interval.

plot_chains(**kwargs)[source]#

Plot posterior distributions for each chain.

plot_posterior(**kwargs)[source]#

Plot the summed posterior distribution across chains.

plot_trace(**kwargs)[source]#

Plot trace plots for the posterior samples.

rhat()[source]#
signif(x, p: int)[source]#

Rounds array x to p significant digits.

summary_table()[source]#

Display summary statistics in a table.

all_samples#
chains#
go = None#
num_parameters#
sig_digits = 4#
class pybop.RandomSearch(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Adapter for the Random Search optimiser in PyBOP.

Random Search is a simple optimisation algorithm that samples parameter sets randomly within the given boundaries and identifies the best solution based on fitness.

This optimiser has been implemented for benchmarking and comparisons, convergence will be better with one of other optimisers in the majority of cases.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    population_sizeint

    Number of solutions to evaluate per iteration.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pybop.RandomSearchImpl

PyBOP implementation of Random Search algorithm.

class pybop.RandomSearchImpl(x0, sigma0=0.05, boundaries=None)[source]#

Bases: pints.PopulationBasedOptimiser

Random Search (RS) optimisation algorithm. This algorithm explores the parameter space by randomly sampling points.

The algorithm does the following: 1. Initialise a population of solutions. 2. At each iteration, generate n number of random positions within boundaries. 3. Evaluate the quality/fitness of the positions. 4. Replace the best position with improved position if found.

Parameters:

population_size (optional) – Number of solutions to evaluate per iteration.

References: The Random Search algorithm implemented in this work is based on principles outlined in “Introduction to Stochastic Search and Optimization: Estimation, Simulation, and Control” by Spall, J. C. (2003).

The implementation inherits from the PINTS PopulationOptimiser.

_suggested_population_size()[source]#

Returns a suggested population size based on the dimension of the parameter space.

ask()[source]#

Returns a list of positions to evaluate in the optimiser-space.

clip_candidates(x)[source]#

Clip the input array to the boundaries if available.

f_best()[source]#

Returns the best score found so far.

name()[source]#

Returns the name of the optimiser.

running()[source]#

Returns True if the optimisation is in progress.

tell(replies)[source]#

Receives a list of cost function values from points previously specified by self.ask(), and updates the optimiser state accordingly.

x_best()[source]#

Returns the best parameter values found so far.

_dim#
_f_best#
_ready_for_tell = False#
_running = False#
_x_best#
class pybop.RaoBlackwellACMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Rao-Blackwell Adaptive Covariance MCMC sampler.

class pybop.RelativisticMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Relativistic MCMC sampler.

class pybop.RootMeanSquaredError(problem)[source]#

Bases: pybop.costs.base_cost.BaseCost

Root mean square error 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.

Inherits all parameters and attributes from BaseCost.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The root mean square error.

Return type:

float

class pybop.SNES(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements the stochastic natural evolution strategy (SNES) optimisation algorithm.

Inheriting from the PINTS SNES class, this optimiser is 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:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.SNES

The PINTS implementation this class is based on.

class pybop.ScaledLogLikelihood(log_likelihood: BaseLikelihood)[source]#

Bases: BaseMetaLikelihood

This class scaled a BaseLogLikelihood class by the number of observations. The scaling factor is given below:

\[\mathcal{\hat{L(\theta)}} = \frac{1}{N} \mathcal{L(\theta)}\]

This class aims to provide numerical values with lower magnitude than the canonical likelihoods, which can improve optimiser convergence in certain cases.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Compute the cost and if calculate_grad is True, its gradient with respect to the predictions.

This method only computes the cost, without calling the problem.evaluate(). This method must be implemented by subclasses.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The calculated cost function value.

Return type:

float

Raises:

NotImplementedError – If the method has not been implemented by the subclass.

class pybop.SciPyDifferentialEvolution(cost, **optimiser_kwargs)[source]#

Bases: BaseSciPyOptimiser

Adapts SciPy’s differential_evolution function for global optimisation.

This class provides a global optimisation strategy based on differential evolution, useful for problems involving continuous parameters and potentially multiple local minima.

Parameters:
  • bounds (dict, sequence or scipy.optimize.Bounds) – Bounds for variables. Must be provided as it is essential for differential evolution. Each element is a tuple (min, max) for the corresponding variable.

  • **optimiser_kwargs (optional) –

    Valid SciPy differential_evolution options: 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’.

    maxiterint, optional

    Maximum number of generations. Default is 1000.

    popsizeint, optional

    Multiplier for setting the total population size. The population has popsize * len(x) individuals. Default is 15.

    tolfloat, optional

    Relative tolerance for convergence. Default is 0.01.

    mutationfloat 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 is (0.5, 1.0).

    recombinationfloat, optional

    The recombination constant, should be in [0, 1]. Default is 0.7.

    seedint, optional

    Random seed for reproducibility.

    dispbool, optional

    Display status messages. Default is False.

    callbackcallable, optional

    Called after each iteration with the current result as argument.

    polishbool, optional

    If True, performs a local optimisation on the solution. Default is True.

    initstr or array-like, optional

    Specify initial population. Can be ‘latinhypercube’, ‘random’, or an array of shape (M, len(x)).

    atolfloat, optional

    Absolute tolerance for convergence. Default is 0.

    updating{‘immediate’, ‘deferred’}, optional

    If ‘immediate’, best solution vector is continuously updated within a single generation. Default is ‘immediate’.

    workersint or map-like callable, optional

    If workers is an int the population is subdivided into workers sections and evaluated in parallel. Default is 1.

    constraints{NonlinearConstraint, LinearConstraint, Bounds}, optional

    Constraints on the solver.

See also

scipy.optimize.differential_evolution

The 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_optimiser()[source]#

Executes the optimization 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

_set_up_optimiser()[source]#

Parse optimiser options.

name()[source]#

Provides the name of the optimisation strategy.

class pybop.SciPyEvaluator(function, args=None)[source]#

Bases: pints.Evaluator

Evaluates a function (or callable object) for the SciPy optimisers for either a single or multiple positions.

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

_evaluate(positions)[source]#

See evaluate().

class pybop.SciPyMinimize(cost, **optimiser_kwargs)[source]#

Bases: BaseSciPyOptimiser

Adapts SciPy’s minimize function for use as an optimisation strategy.

This class provides an interface to various scalar minimisation algorithms implemented in SciPy, allowing fine-tuning of the optimisation process through method selection and option configuration.

Parameters:

**optimiser_kwargs (optional) –

Valid SciPy Minimize option keys and their values: x0 : array_like

Initial position from which optimisation will start.

methodstr

The optimisation method, options include: ‘Nelder-Mead’, ‘Powell’, ‘CG’, ‘BFGS’, ‘Newton-CG’, ‘L-BFGS-B’, ‘TNC’, ‘COBYLA’, ‘SLSQP’, ‘trust-constr’, ‘dogleg’, ‘trust-ncg’, ‘trust-exact’, ‘trust-krylov’.

jac{callable, ‘2-point’, ‘3-point’, ‘cs’, bool}, optional

Method for computing the gradient vector.

hess{callable, ‘2-point’, ‘3-point’, ‘cs’, HessianUpdateStrategy}, optional

Method for computing the Hessian matrix.

hesspcallable, optional

Hessian of objective function times an arbitrary vector p.

boundssequence or scipy.optimize.Bounds, optional

Bounds on variables for L-BFGS-B, TNC, SLSQP, trust-constr methods.

constraints{Constraint, dict} or List of {Constraint, dict}, optional

Constraints definition for constrained optimisation.

tolfloat, optional

Tolerance for termination.

optionsdict, optional

Method-specific options. Common options include: maxiter : int

Maximum number of iterations.

dispbool

Set to True to print convergence messages.

ftolfloat

Function tolerance for termination.

gtolfloat

Gradient tolerance for termination.

epsfloat

Step size for finite difference approximation.

maxfevint

Maximum number of function evaluations.

maxcorint

Maximum number of variable metric corrections (L-BFGS-B).

See also

scipy.optimize.minimize

The 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_optimiser()[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

_set_up_optimiser()[source]#

Parse optimiser options.

cost_wrapper(x)[source]#

Scale the cost function, preserving the sign convention, and eliminate nan values

name()[source]#

Provides the name of the optimisation strategy.

_cost0 = 1.0#
class pybop.SequentialJaxEvaluator(function, args=None)[source]#

Bases: pints.Evaluator

Sequential evaluates a function (or callable object) for either a single or multiple positions. This class is based off the PintsSequentialEvaluator class, with additions for PyBOP’s JAX cost classes.

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

_evaluate(positions)[source]#

See evaluate().

class pybop.SliceDoublingMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Slice Doubling MCMC sampler.

class pybop.SliceRankShrinkingMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Slice Rank Shrinking MCMC sampler.

class pybop.SliceStepoutMCMC(log_pdf, chains, x0=None, cov0=None, **kwargs)[source]#

Bases: pybop.BasePintsSampler

Implements 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.LogPosterior or List[pybop.LogPosterior])) – A function that calculates the log-probability density.

  • chains (int) – The number of chains to run.

  • x0 (ndarray, optional) – Initial positions for the chains.

  • cov0 (ndarray, optional) – Initial covariance matrix.

  • **kwargs – Additional arguments to pass to the Slice Stepout MCMC sampler.

class pybop.SumSquaredError(problem)[source]#

Bases: pybop.costs.base_cost.BaseCost

Sum of squared errors 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.

Inherits all parameters and attributes from BaseCost.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The Sum of Squared Error.

Return type:

float

class pybop.SumofPower(problem, p: float = 2.0)[source]#

Bases: pybop.costs.base_cost.BaseCost

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

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The Sum of Power cost.

Return type:

float

p#
class pybop.SymbolReplacer(symbol_replacement_map: dict[pybamm.Symbol, pybamm.Symbol], processed_symbols: dict[pybamm.Symbol, pybamm.Symbol] | None = None, process_initial_conditions: bool = True)[source]#

Helper class to replace all instances of one or more symbols in an expression tree with another symbol, as defined by the dictionary symbol_replacement_map Originally developed by pybamm: pybamm-team/pybamm

Parameters:
  • symbol_replacement_map (dict {pybamm.Symbol -> pybamm.Symbol}) – Map of which symbols should be replaced by which.

  • processed_symbols (dict {pybamm.Symbol -> pybamm.Symbol}, optional) – cached replaced symbols

  • process_initial_conditions (bool, optional) – Whether to process initial conditions, default is True

_process_events(events: list) list[source]#
_process_symbol(symbol: pybamm.Symbol) pybamm.Symbol[source]#
process_boundary_conditions(model)[source]#

Process boundary conditions for a PybaMM model class Boundary conditions are dictionaries {“left”: left bc, “right”: right bc} in general, but may be imposed on the tabs (or not on the tab) for a small number of variables, e.g. {“negative tab”: neg. tab bc, “positive tab”: pos. tab bc “no tab”: no tab bc}.

process_model(unprocessed_model, inplace=True)[source]#

Replace all instances of a symbol in a PyBaMM model class.

Parameters:
  • unprocessed_model (pybamm.BaseModel) – Model class to assign parameter values to

  • inplace (bool, optional) – If True, replace the parameters in the model in place. Otherwise, return a new model with parameter values set. Default is True.

process_symbol(symbol)[source]#

This function recurses down the tree, replacing any symbols in self._symbol_replacement_map.keys() with their corresponding value

Parameters:

symbol (pybamm.Symbol) – The symbol to replace

Returns:

Symbol with all replacements performed

Return type:

pybamm.Symbol

_process_initial_conditions = True#
_processed_symbols#
_symbol_replacement_map#
class pybop.TimeSeriesState[source]#

The current state of a time series model that is a pybamm model.

__len__()[source]#
as_ndarray() numpy.ndarray[source]#
inputs: pybop.parameters.parameter.Inputs#
sol: pybamm.Solution#
t: float = 0.0#
class pybop.Uniform(lower, upper, random_state=None)[source]#

Bases: BasePrior

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

_logpdfS1(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#
loc#
lower#
property mean#

Returns the mean of the distribution.

name = 'Uniform'#
prior#
scale#
property sigma#

Returns the standard deviation of the distribution.

upper#
class pybop.UnscentedKalmanFilterObserver(parameters: list[pybop.parameters.parameter.Parameter], model: pybop.models.base_model.BaseModel, sigma0: Covariance | float, process: Covariance | float, measure: Covariance | float, dataset: pybop._dataset.Dataset | None = None, check_model: bool = True, signal: list[str] | None = None, additional_variables: list[str] | None = None, initial_state: float | None = None)[source]#

Bases: pybop.observers.observer.Observer

An observer using the unscented Kalman filter. This is a wrapper class for PyBOP, see class SquareRootUKF for more details on the method.

Parameters:
  • parameters (Parameters) – The parameters for the model.

  • model (BaseModel) – The model to observe.

  • sigma0 (np.ndarray | float) – The covariance matrix of the initial state. If a float is provided, the covariance matrix is set to sigma0 * np.eye(n), where n is the number of states. To remove a state from the filter, set the corresponding row and col to zero in both sigma0 and process.

  • process (np.ndarray | float) – The covariance matrix of the process noise. If a float is provided, the covariance matrix is set to process * np.eye(n), where n is the number of states. To remove a state from the filter, set the corresponding row and col to zero in both sigma0 and process.

  • measure (np.ndarray | float) – The covariance matrix of the measurement noise. If a float is provided, the covariance matrix is set to measure * np.eye(m), where m is the number of measurements.

  • dataset (Dataset) – Dataset object containing the data to fit the model to.

  • check_model (bool, optional) – Flag to indicate if the model should be checked (default: True).

  • signal (str) – The signal to observe.

  • initial_state (dict, optional) – A valid initial state, e.g. the initial open-circuit voltage (default: None).

get_current_covariance() Covariance[source]#

Returns the current covariance of the model.

observe(time: float, value: numpy.ndarray) float[source]#

Predict the time series model until t = time and optionally observe the measurement value.

Returns the log likelihood of the model given the value and inputs. If no value is given, the log likelihood is 0.

The base observer does not perform any value observation and always returns 0.

Parameters:
  • time (float) – The time of the new observation.

  • value (np.ndarray (optional)) – The new observation.

reset(inputs: pybop.models.base_model.Inputs) None[source]#
Covariance#
_process#
_sigma0#
_ukf#
class pybop.VolumetricEnergyDensity(problem)[source]#

Bases: DesignCost

Calculates the (volumetric) energy density of a battery cell, when applied to a normalised discharge from upper to lower voltage limits. The goal of maximising the energy density is achieved with self.minimising = False.

The volumetric energy density [Wh.m-3] is calculated as

\[\frac{1}{3600 v} \int_{t=0}^{t=T} I(t) V(t) \mathrm{d}t\]

where v is the cell volume, t is the time, T is the total time, I is the current and V is the voltage. The factor of 1/3600 is included to convert from seconds to hours.

Inherits all parameters and attributes from DesignCost.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float[source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal. Note: not used in design optimisation classes.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The volumetric energy density or -infinity in case of infeasible parameters.

Return type:

float

class pybop.VolumetricPowerDensity(problem, target_time: int | float = 3600)[source]#

Bases: DesignCost

Calculates the (volumetric) power density of a battery cell, when applied to a discharge from upper to lower voltage limits. The goal of maximising the power density is achieved with self.minimising=False.

The time-averaged volumetric power density [W.m-3] is calculated as

\[\frac{1}{3600 v T} \int_{t=0}^{t=T} I(t) V(t) \mathrm{d}t\]

where v is the cell volume, t is the time, T is the total time, I is the current and V is the voltage. The factor of 1/3600 is included to convert from seconds to hours.

Inherits all parameters and attributes from DesignCost.

Additional parameters#

target_timeint

The length of time (seconds) over which the power should be sustained.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float[source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal. Note: not used in design optimisation classes.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The volumetric power density or -infinity in case of infeasible parameters.

Return type:

float

target_time = 3600#
class pybop.WeightedCost(*costs, weights: list[float] | None = None)[source]#

Bases: pybop.BaseCost

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

  • has_identical_problems (bool) – If True, the shared problem will be evaluated once and saved before the self.compute() method of each cost is called (default: False).

  • has_separable_problem (bool) – This attribute must be set to False for WeightedCost objects. If the corresponding attribute of an individual cost is True, the problem is separable from the cost function and will be evaluated before the individual cost evaluation is called.

compute(y: dict, dy: numpy.ndarray = None, calculate_grad: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • y (dict) – The dictionary of predictions with keys designating the signals for fitting.

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each signal.

  • calculate_grad (bool, optional) – A bool condition designating whether to calculate the gradient.

Returns:

The weighted cost value.

Return type:

float

_has_identical_problems#
_has_separable_problem = False#
costs#
property has_identical_problems#
class pybop.XNES(cost, max_iterations: int = None, min_iterations: int = 2, max_unchanged_iterations: int = 15, multistart: int = 1, parallel: bool = False, **optimiser_kwargs)[source]#

Bases: pybop.BasePintsOptimiser

Implements the Exponential Natural Evolution Strategy (XNES) optimiser from PINTS.

XNES is an evolutionary algorithm that samples from a multivariate normal distribution, which is updated iteratively to fit the distribution of successful solutions.

Parameters:
  • cost (callable) – The cost function to be minimized.

  • max_iterations (int, optional) – Maximum number of iterations for the optimisation.

  • min_iterations (int, optional (default=2)) – Minimum number of iterations before termination.

  • max_unchanged_iterations (int, optional (default=15)) – Maximum number of iterations without improvement before termination.

  • multistart (int, optional (default=1)) – Number of optimiser restarts from randomly sample position. These positions are sampled from the priors.

  • parallel (bool, optional (default=False)) – Whether to run the optimisation in parallel.

  • **optimiser_kwargs (optional) –

    Valid PINTS option keys and their values, for example: x0 : array_like

    Initial position from which optimisation will start.

    sigma0float

    Initial step size or standard deviation depending on the optimiser.

    boundsdict

    A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.

    use_f_guessedbool

    Whether to return the guessed function values.

    absolute_tolerancefloat

    Absolute tolerance for convergence checking.

    relative_tolerancefloat

    Relative tolerance for convergence checking.

    max_evaluationsint

    Maximum number of function evaluations.

    thresholdfloat

    Threshold value for early termination.

See also

pints.XNES

PINTS implementation of XNES algorithm.

pybop.classify_using_hessian(result: pybop.OptimisationResult, dx=None, cost_tolerance: float | None = 1e-05)[source]#

A simple check for parameter correlations based on numerical approximation of the Hessian matrix at the optimal point using central finite differences.

Parameters:
  • result (OptimisationResult) – The PyBOP optimisation results.

  • dx (array-like, optional) – An array of small positive values used to check proximity to the parameter bounds and as the perturbation distance in the finite difference calculations.

  • cost_tolerance (float, optional) – A small positive tolerance used for cost value comparisons (default: 1e-5).

pybop.is_numeric(x)[source]#

Check if a variable is numeric.

pybop.FLOAT_FORMAT = '{: .17e}'[source]#
pybop.Inputs[source]#
pybop.__version__[source]#
pybop.error_message = Multiline-String[source]#
Show Value
"""Multiprocessing context could not be set. Continuing import without setting context.
Error: Instance of builtins.Exception"""
pybop.script_path[source]#