pybop#
Subpackages#
Submodules#
Attributes#
Classes#
Implements the Adam optimization algorithm. |
|
Implements the AdamW optimisation algorithm in PyBOP. |
|
AdamW optimiser (adaptive moment estimation with weight decay), as described in [1]. |
|
Base class for defining cost functions. |
|
Base class for likelihoods |
|
A base class for constructing and simulating models using PyBaMM. |
|
A base class for defining optimisation methods. |
|
A base class for defining optimisation methods from the PINTS library. |
|
A base class for defining prior distributions. |
|
Base class for defining a problem within the PyBOP framework, compatible with PINTS. |
|
A base class for defining optimisation methods from the SciPy library. |
|
Adapter for the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) optimiser in PINTS. |
|
Adapter for the Cuckoo Search optimiser in PyBOP. |
|
Cuckoo Search (CS) optimisation algorithm, inspired by the brood parasitism |
|
Represents a collection of experimental observations. |
|
Overwrites and extends BaseCost class for design-related cost functions. |
|
Problem class for design optimization problems. |
|
Wraps the Experiment class for generating experiment conditions for PyBaMM models. |
|
Represents an exponential distribution with a specified scale parameter. |
|
Problem class for fitting (parameter estimation) problems. |
|
Represents a Gaussian (normal) distribution with a given mean and standard deviation. |
|
This class represents a Gaussian Log Likelihood, which assumes that the |
|
This class represents a Gaussian Log Likelihood with a known sigma, |
|
Implements a simple gradient descent optimization algorithm. |
|
Represents the gravimetric energy density of a battery cell, calculated based |
|
Implements the iRpropMin optimization algorithm. |
|
Maximum a posteriori cost function. |
|
Implements the Nelder-Mead downhill simplex method from PINTS. |
|
An observer of a time series state. Observers: |
|
Observer cost function. |
|
A high-level class for optimisation using PyBOP or PINTS optimisers. |
|
Implements a particle swarm optimization (PSO) algorithm. |
|
Represents a parameter within the PyBOP framework. |
|
Handles the import and export of parameter sets for battery models. |
|
Represents a set of uncertain parameters within the PyBOP framework. |
|
Manages the installation and configuration of Plotly for generating visualizations. |
|
Stores the result of the optimisation. |
|
Root mean square error cost function. |
|
Implements the stochastic natural evolution strategy (SNES) optimization algorithm. |
|
Adapts SciPy's differential_evolution function for global optimization. |
|
Adapts SciPy's minimize function for use as an optimization strategy. |
|
A class for creating and displaying interactive Plotly figures. |
|
A class for creating and displaying a set of interactive Plotly figures in a grid layout. |
|
Sum of squared errors cost function. |
|
The current state of a time series model that is a pybamm model. |
|
Represents a uniform distribution over a specified interval. |
|
An observer using the unscented Kalman filter. This is a wrapper class for PyBOP, see class SquareRootUKF for more details on the method. |
|
Represents the volumetric energy density of a battery cell, calculated based |
|
Implements the Exponential Natural Evolution Strategy (XNES) optimiser from PINTS. |
Functions#
|
Check if a variable is numeric. |
|
Plot a 2D visualisation of a cost landscape using Plotly. |
|
Plot the convergence of the optimisation algorithm. |
|
Quickly plot a PyBOP Dataset using Plotly. |
|
Plot the evolution of parameters during the optimization process using Plotly. |
|
Quickly plot one or more trajectories using Plotly. |
|
Quickly plot the target dataset against optimised model output. |
Package Contents#
- class pybop.Adam(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements the Adam optimization algorithm.
This class extends the Adam optimiser from the PINTS library, which combines ideas from RMSProp and Stochastic Gradient Descent with momentum. Note that this optimiser does not support boundary constraints.
- Parameters:
**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.
See also
pints.AdamThe PINTS implementation this class is based on.
- class pybop.AdamW(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements 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.
- Parameters:
**optimiser_kwargs (optional) –
Valid PyBOP option keys and their values, for example: x0 : array_like
Initial position from which optimisation will start.
- sigma0float
Initial step size.
See also
pybop.AdamWImplThe PyBOP implementation this class is based on.
- class pybop.AdamWImpl(x0, sigma0=0.015, boundaries=None)[source]#
Bases:
pints.OptimiserAdamW 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 denotedg_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) + lambda * p_j[i - 1])
The initial values of the moments are
m_j[0] = v_j[0] = 0, after which they decay with ratesbeta1andbeta2. The default values for these are,beta1 = 0.9andbeta2 = 0.999.The terms
m_j'andv_j'are “initialisation bias corrected” versions ofm_jandv_j(see section 2 of the paper).The parameter
alphais a step size, which is set asmin(sigma0)in this implementation.The parameter
lambdais the weight decay rate, which is set to0.01by default in this implementation.Finally,
epsis 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
boundarieswill be ignored.References
- needs_sensitivities()[source]#
Returns
Falseif this optimiser does not require gradient, andTrueotherwise.
- set_lambda(lambda_: float = 0.01) None[source]#
Sets the lambda_ decay constant. This is the weight decay rate that helps in finding the optimal solution.
- class pybop.BaseCost(problem=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.
- abstract _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Calculate the cost function value for a given set of parameters.
This method must be implemented by subclasses.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The calculated cost function value.
- Return type:
float
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- abstract _evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#
Compute the cost and its gradient with respect to the parameters.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- evaluate(x, grad=None)[source]#
Call the evaluate function for a given set of parameters.
- Parameters:
x (array-like) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The calculated cost function value.
- Return type:
float
- Raises:
ValueError – If an error occurs during the calculation of the cost.
- evaluateS1(x)[source]#
Call _evaluateS1 for a given set of parameters.
- Parameters:
x (array-like) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
ValueError – If an error occurs during the calculation of the cost or gradient.
- property n_parameters#
- class pybop.BaseLikelihood(problem: pybop.problems.base_problem.BaseProblem)[source]#
Bases:
pybop.costs.base_cost.BaseCostBase class for likelihoods
- class pybop.BaseModel(name='Base Model', parameter_set=None)[source]#
A base class for constructing and simulating models using PyBaMM.
This class serves as a foundation for building specific models in PyBaMM. 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.
- _check_params(inputs: pybop.parameters.parameter.Inputs = None, 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.
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(inputs: pybop.parameters.parameter.Inputs)[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:
inputs (Inputs) – The parameters that are the inputs of the model.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- build(dataset: pybop.Dataset = None, parameters: pybop.Parameters | Dict = None, check_model: bool = True, init_soc: float = None) None[source]#
Construct the PyBaMM model if not already built, and set parameters.
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:
dataset (pybamm.Dataset, optional) – The dataset to be used in the model construction.
parameters (pybop.Parameters or Dict, optional) – A pybop Parameters class or dictionary containing parameter values to apply to the model.
check_model (bool, optional) – If True, the model will be checked for correctness after construction.
init_soc (float, optional) – The initial state of charge to be used in simulations.
- 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 (dict, optional) – A dictionary containing the parameter values necessary for the mass calculations.
- 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 (dict, optional) – A dictionary containing the parameter values necessary for the volume calculation.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- check_params(inputs: pybop.parameters.parameter.Inputs = None, parameter_set: pybop.ParameterSet = None, allow_infeasible_solutions: bool = True)[source]#
Check compatibility of the model parameters.
- Parameters:
inputs (Inputs) – The input parameters for the simulation.
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_and_update_parameters(parameters: pybop.Parameters)[source]#
Update the parameter values according to their classification as either ‘rebuild_parameters’ which require a model rebuild and ‘standard_parameters’ which do not.
- Parameters:
parameters (pybop.Parameters)
- 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)
- predict(inputs: pybop.parameters.parameter.Inputs = None, t_eval: numpy.array = None, parameter_set: pybop.ParameterSet = None, experiment: pybop.Experiment = None, init_soc: float = 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 (if any), and initial state of charge (if 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 (pybamm.ParameterValues, optional) – A PyBaMM ParameterValues object or a dictionary 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.
init_soc (float, optional) – The initial state of charge for the simulation, as a fraction (between 0 and 1). Defaults to None.
- Returns:
The solution object returned after solving the simulation.
- 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.
- rebuild(dataset: pybop.Dataset = None, parameters: pybop.Parameters | Dict = None, parameter_set: pybop.ParameterSet = None, check_model: bool = True, init_soc: float = None) None[source]#
Rebuild the PyBaMM model for a given parameter set.
This method requires the self.build() method to be called first, and then rebuilds the model for a given parameter set. Specifically, this method applies the given parameters, sets up the mesh and discretisation if needed, and prepares the model for simulations.
- Parameters:
dataset (pybamm.Dataset, optional) – The dataset to be used in the model construction.
parameters (pybop.Parameters or Dict, optional) – A pybop Parameters class or dictionary containing parameter values to apply to the model.
parameter_set (pybop.parameter_set, optional) – A PyBOP parameter set object or a dictionary containing the parameter values
check_model (bool, optional) – If True, the model will be checked for correctness after construction.
init_soc (float, optional) – The initial state of charge to be used in simulations.
- 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_init_soc(init_soc: float)[source]#
Set the initial state of charge for the battery model.
- Parameters:
init_soc (float) – The initial state of charge to be used in the model.
- set_params(rebuild=False)[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.
- simulate(inputs: pybop.parameters.parameter.Inputs, t_eval: numpy.array) Dict[str, numpy.ndarray[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.
- 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)[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.
- Returns:
A tuple containing the simulation result and the sensitivities.
- Return type:
tuple
- 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)
- property built_model#
- property geometry#
- property mesh#
- property model_with_set_params#
- property parameter_set#
- 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
- minimising#
If True, the target is to minimise the cost, else target is to maximise by minimising the negative cost (default: True).
- Type:
bool, optional
- physical_viability#
If True, the feasibility of the optimised parameters is checked (default: True).
- 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.
- check_optimal_parameters(x)[source]#
Check if the optimised parameters are physically viable.
- Parameters:
x (array-like) – Optimised parameter values.
- name()[source]#
Returns the name of the optimiser, to be overwritten by child classes.
- Returns:
The name of the optimiser, which is “Optimisation” for this base class.
- Return type:
str
- run()[source]#
Run the optimisation and return the optimised parameters and final cost.
- Returns:
x (numpy.ndarray) – The best parameter set found by the optimisation.
final_cost (float) – The final cost associated with the best parameters.
- set_allow_infeasible_solutions(allow=True)[source]#
Set whether to allow infeasible solutions or not.
- Parameters:
iterations (bool, optional) – Whether to allow infeasible solutions.
- class pybop.BasePintsOptimiser(cost, pints_optimiser, **optimiser_kwargs)[source]#
Bases:
pybop.BaseOptimiserA base class for defining optimisation methods from the PINTS library.
- Parameters:
**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.
- _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:
See also
This
- 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]#
Provides the name of the optimisation strategy.
- Returns:
The name given by PINTS.
- Return type:
str
- 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_threshold(threshold=None)[source]#
Adds a stopping criterion, allowing the routine to halt once the objective function goes below a set
threshold.This criterion is disabled by default, but can be enabled by calling this method with a valid
threshold. To disable it, useset_threshold(None). Credit: PINTS- Parameters:
threshold (float, optional) – The threshold below which the objective function value is considered optimal (default: None).
- 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
- 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
- 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.
- 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, model=None, check_model=True, signal=['Voltage [V]'], additional_variables=[], init_soc=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: []).
init_soc (float, optional) – Initial state of charge (default: None).
- abstract 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.
- 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_target(dataset)[source]#
Set the target dataset.
- Parameters:
target (np.ndarray) – The target dataset array.
- property model#
- property n_parameters#
- class pybop.BaseSciPyOptimiser(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BaseOptimiserA 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.
- class pybop.CMAES(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserAdapter for the Covariance Matrix Adaptation Evolution Strategy (CMA-ES) optimiser in PINTS.
CMA-ES is an evolutionary algorithm for difficult non-linear non-convex optimization problems. It adapts the covariance matrix of a multivariate normal distribution to capture the shape of the cost landscape.
- Parameters:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
The initial parameter vector to optimise.
- sigma0float
Initial standard deviation of the sampling distribution.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters. If
None, no bounds are enforced.
See also
pints.CMAESPINTS implementation of CMA-ES algorithm.
- class pybop.CuckooSearch(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserAdapter 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:
**optimiser_kwargs (optional) –
Valid PyBOP option keys and their values, for example: x0 : array_like
Initial parameter values.
- sigma0float
Initial step size.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.
See also
pybop.CuckooSearchPyBOP implementation of Cuckoo Search algorithm.
- class pybop.CuckooSearchImpl(x0, sigma0=0.05, boundaries=None, pa=0.25)[source]#
Bases:
pints.PopulationBasedOptimiserCuckoo 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:
Initialise population of n host nests
- While (t < max_generations):
Get a cuckoo randomly by Lévy flights
Evaluate its quality/fitness F
Choose a nest among n (say, j) randomly
- If (F > fitness of j):
Replace j with the new solution
Abandon a fraction (pa) of the worst nests and build new ones
Keep the best solutions/nests
Rank the solutions and find the current best
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.
- 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.
- Interpolant()[source]#
Create an interpolation function of the dataset based on the independent variable.
Currently, only time-based interpolation is supported. This method modifies the instance’s Interpolant attribute to be an interpolation function that can be evaluated at different points in time.
- Raises:
NotImplementedError – If the independent variable for interpolation is not supported.
- __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
- class pybop.DesignCost(problem, update_capacity=False)[source]#
Bases:
pybop.costs.base_cost.BaseCostOverwrites 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.
- parameter_setobject)
The set of parameters from the problem’s model.
- dtfloat
The time step size used in the simulation.
- abstract _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Computes the value of the cost function.
This method must be implemented by subclasses.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost.
grad (array, optional) – Gradient information, not used in this method.
- Raises:
NotImplementedError – If the method has not been implemented by the subclass.
- class pybop.DesignProblem(model, parameters, experiment, check_model=True, signal=['Voltage [V]'], additional_variables=[], init_soc=None)[source]#
Bases:
pybop.BaseProblemProblem 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]”]).
init_soc (float, optional) – Initial state of charge (default: None).
- class pybop.Experiment(operating_conditions, period='1 minute', temperature=None, termination=None, drive_cycles=None, cccv_handling=None)[source]#
Bases:
ExperimentWraps the 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:
BasePriorRepresents 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.
- class pybop.FittingProblem(model, parameters, dataset, check_model=True, signal=['Voltage [V]'], additional_variables=[], init_soc=None)[source]#
Bases:
pybop.BaseProblemProblem 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 (Dataset) – Dataset object containing the data to fit the model to.
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]”]).
init_soc (float, optional) – Initial state of charge (default: None).
- 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) and the sensitivities dy/dx(t) evaluated with given inputs.
- Return type:
tuple
- class pybop.Gaussian(mean, sigma, random_state=None)[source]#
Bases:
BasePriorRepresents 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.
- class pybop.GaussianLogLikelihood(problem: pybop.problems.base_problem.BaseProblem, sigma0: float | List[float] | List[pybop.parameters.parameter.Parameter] = 0.002, dsigma_scale: float = 1.0)[source]#
Bases:
BaseLikelihoodThis 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
- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad: None | numpy.ndarray = None) float[source]#
Evaluates the Gaussian log-likelihood for the given parameters.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the log-likelihood, including the n_outputs standard deviations of the Gaussian distributions.
- Returns:
The log-likelihood value, or -inf if the standard deviations are non-positive.
- Return type:
float
- _evaluateS1(inputs: pybop.parameters.parameter.Inputs) Tuple[float, numpy.ndarray][source]#
Calls the problem.evaluateS1 method and calculates the log-likelihood.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the log-likelihood.
- Returns:
The log-likelihood and its gradient.
- Return type:
Tuple[float, np.ndarray]
- property dsigma_scale#
- Scaling factor for the dsigma term in the gradient calculation.
- class pybop.GaussianLogLikelihoodKnownSigma(problem: pybop.problems.base_problem.BaseProblem, sigma0: List[float] | float)[source]#
Bases:
BaseLikelihoodThis 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.
- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad: None | numpy.ndarray = None) float[source]#
Evaluates the Gaussian log-likelihood for the given parameters with known sigma.
- class pybop.GradientDescent(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements a simple gradient descent optimization 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:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
Initial position from which optimisation will start.
- sigma0float
The learning rate / Initial step size (default: 0.02).
See also
pints.GradientDescentThe PINTS implementation this class is based on.
- class pybop.GravimetricEnergyDensity(problem, update_capacity=False)[source]#
Bases:
DesignCostRepresents the gravimetric energy density of a battery cell, calculated based on a normalised discharge from upper to lower voltage limits. The goal is to maximise the energy density, which is achieved by setting minimising = False in the optimiser settings.
Inherits all parameters and attributes from
DesignCost.- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Computes the cost function for the energy density.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost.
grad (array, optional) – Gradient information, not used in this method.
- Returns:
The gravimetric energy density or -infinity in case of infeasible parameters.
- Return type:
float
- class pybop.IRPropMin(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements the iRpropMin optimization 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:
**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.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.
See also
pints.IRPropMinThe PINTS implementation this class is based on.
- class pybop.MAP(problem, likelihood, sigma0=None, gradient_step=0.001)[source]#
Bases:
BaseLikelihoodMaximum a posteriori cost function.
Computes the maximum a posteriori cost function, which is the sum of the log likelihood and the log prior. The goal of maximising is achieved by setting minimising = False in the optimiser settings.
Inherits all parameters and attributes from
BaseLikelihood.- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None) float[source]#
Calculate the maximum a posteriori cost for a given set of parameters.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The maximum a posteriori cost.
- Return type:
float
- _evaluateS1(inputs: pybop.parameters.parameter.Inputs) Tuple[float, numpy.ndarray][source]#
Compute the maximum a posteriori with respect to the parameters. The method passes the likelihood gradient to the optimiser without modification.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
ValueError – If an error occurs during the calculation of the cost or gradient.
- class pybop.NelderMead(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements 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.
- Parameters:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
The initial parameter vector to optimise.
- sigma0float
Initial standard deviation of the sampling distribution. Does not appear to be used.
See also
pints.NelderMeadPINTS implementation of Nelder-Mead algorithm.
- class pybop.Observer(parameters: pybop.parameters.parameter.Parameters, model: pybop.models.base_model.BaseModel, check_model=True, signal=['Voltage [V]'], additional_variables=[], init_soc=None)[source]#
Bases:
pybop.BaseProblem- An observer of a time series state. Observers:
keep track of the distribution of a current time series model state
predict forward in time the distribution of the state
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: []).
init_soc (float, optional) – Initial state of charge (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_state() pybop.models.base_model.TimeSeriesState[source]#
Returns the current state of the model.
- 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.
- Covariance#
- class pybop.ObserverCost(observer: pybop.observers.observer.Observer)[source]#
Bases:
pybop.costs.base_cost.BaseCostObserver 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.- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Calculate the observer cost for a given set of parameters.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The observer cost (negative of the log likelihood).
- Return type:
float
- abstract evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#
Compute the cost and its gradient with respect to the parameters.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
ValueError – If an error occurs during the calculation of the cost or gradient.
- 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 optimization (default: None).
sigma0 (float or sequence, optional) – Initial step size or standard deviation for the optimiser (default: None).
verbose (bool, optional) – If True, the optimization 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
- class pybop.PSO(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements a particle swarm optimization (PSO) algorithm.
This class extends the PSO optimiser from the PINTS library. PSO is a metaheuristic optimization method inspired by the social behavior of birds flocking or fish schooling, suitable for global optimization problems.
- Parameters:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
Initial positions of particles, which the optimisation will use.
- sigma0float
Spread of the initial particle positions.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.
See also
pints.PSOThe PINTS implementation this class is based on.
- class pybop.Parameter(name, initial_value=None, true_value=None, prior=None, bounds=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
- rvs(n_samples, random_state=None)[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.
- 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=6)[source]#
Set the upper and lower bounds.
- 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: 6).
- 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.
- 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.
- 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
- 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
- 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:
- Raises:
ValueError – The key must be the name of one of the parameters.
- 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
- get_bounds_for_plotly()[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
- join(parameters=None)[source]#
Join two Parameters objects into the first by copying across each Parameter.
- Parameters:
parameters (pybop.Parameters)
- rvs(n_samples: int) List[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.
- Returns:
An array of samples drawn from the prior distribution within each parameter’s bounds.
- Return type:
array-like
- class pybop.PlotlyManager[source]#
Manages the installation and configuration of Plotly for generating visualizations.
This class ensures that Plotly is installed and properly configured to display plots in a web browser.
Upon instantiation, it checks for Plotly’s presence, installs it if missing, and configures the default renderer and browser settings.
- go#
The Plotly graph_objects module for creating figures.
- Type:
module
- pio#
The Plotly input/output module for configuring the renderer.
- Type:
module
- make_subplots#
The function from Plotly for creating subplot figures.
- Type:
function
Examples
>>> plotly_manager = PlotlyManager()
- check_browser_availability()[source]#
Confirm a web browser is available for Plotly’s ‘browser’ renderer; provide guidance if not.
- check_renderer_settings()[source]#
Check and provide information on setting the Plotly renderer if it’s not already set.
- ensure_plotly_installed()[source]#
Check if Plotly is installed and import necessary modules; prompt for installation if missing.
- class pybop.Result(x: numpy.ndarray = None, final_cost: float = None, n_iterations: int = 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
- nit#
Number of iterations performed by the optimiser.
- Type:
int
- scipy_result#
The result obtained from a SciPy optimiser.
- Type:
scipy.optimize.OptimizeResult, optional
- class pybop.RootMeanSquaredError(problem)[source]#
Bases:
pybop.costs.base_cost.BaseCostRoot 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.- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Calculate the root mean square error for a given set of parameters.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The root mean square error.
- Return type:
float
- _evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#
Compute the cost and its gradient with respect to the parameters.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
ValueError – If an error occurs during the calculation of the cost or gradient.
- class pybop.SNES(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements the stochastic natural evolution strategy (SNES) optimization 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:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
Initial position from which optimisation will start.
- sigma0float
Initial standard deviation of the sampling distribution.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upper bounds on the parameters.
See also
pints.SNESThe PINTS implementation this class is based on.
- class pybop.SciPyDifferentialEvolution(cost, **optimiser_kwargs)[source]#
Bases:
BaseSciPyOptimiserAdapts SciPy’s differential_evolution function for global optimization.
This class provides a global optimization 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.
**optimiser_kwargs (optional) –
Valid SciPy option keys and their values, for example: strategy : str
The differential evolution strategy to use.
- maxiterint
Maximum number of iterations to perform.
- popsizeint
The number of individuals in the population.
See also
scipy.optimize.differential_evolutionThe SciPy method this class is based on.
- class pybop.SciPyMinimize(cost, **optimiser_kwargs)[source]#
Bases:
BaseSciPyOptimiserAdapts SciPy’s minimize function for use as an optimization strategy.
This class provides an interface to various scalar minimization algorithms implemented in SciPy, allowing fine-tuning of the optimization process through method selection and option configuration.
- Parameters:
**optimiser_kwargs (optional) –
Valid SciPy Minimize option keys and their values, For example: x0 : array_like
Initial position from which optimisation will start.
- boundsdict, sequence or scipy.optimize.Bounds
Bounds for variables as supported by the selected method.
- 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’.
See also
scipy.optimize.minimizeThe SciPy method this class is based on.
- class pybop.StandardPlot(x, y, layout=None, layout_options=DEFAULT_LAYOUT_OPTIONS.copy(), trace_options=DEFAULT_TRACE_OPTIONS.copy(), trace_names=None, trace_name_width=40)[source]#
A class for creating and displaying interactive Plotly figures.
- Parameters:
x (list or np.ndarray) – X-axis data points.
y (list or np.ndarray) – Primary Y-axis data points for simulated model output.
layout (Plotly layout, optional) – A layout for the figure, overrides the layout options (default: None).
layout_options (dict, optional) – Settings to modify the default layout (default: DEFAULT_LAYOUT_OPTIONS).
trace_options (dict, optional) – Settings to modify the default trace type (default: DEFAULT_TRACE_OPTIONS).
trace_names (str, optional) – Name(s) for the primary trace(s) (default: None).
trace_name_width (int, optional) – Maximum length of the trace names before text wrapping is used (default: 40).
- Returns:
The generated Plotly figure.
- Return type:
plotly.graph_objs.Figure
- __call__(show=True)[source]#
Generate and show the figure.
- Parameters:
show (bool, optional) – If True, the figure is shown upon creation (default: True).
- create_trace(x, y, **trace_options)[source]#
Create a trace for the Plotly figure.
- Returns:
A trace for a Plotly figure.
- Return type:
plotly.graph_objs.Scatter
- class pybop.StandardSubplot(x, y, num_rows=None, num_cols=None, axis_titles=None, layout=None, layout_options=DEFAULT_LAYOUT_OPTIONS.copy(), subplot_options=DEFAULT_SUBPLOT_OPTIONS.copy(), trace_options=DEFAULT_SUBPLOT_TRACE_OPTIONS.copy(), trace_names=None, trace_name_width=40)[source]#
Bases:
StandardPlotA class for creating and displaying a set of interactive Plotly figures in a grid layout.
- Parameters:
x (list or np.ndarray) – X-axis data points.
y (list or np.ndarray) – Primary Y-axis data points for simulated model output.
num_rows (int, optional) – Number of rows of subplots, can be set automatically (default: None).
num_cols (int, optional) – Number of columns of subplots, can be set automatically (default: None).
layout (Plotly layout, optional) – A layout for the figure, overrides the layout options (default: None).
layout_options (dict, optional) – Settings to modify the default layout (default: DEFAULT_LAYOUT_OPTIONS).
trace_options (dict, optional) – Settings to modify the default trace type (default: DEFAULT_TRACE_OPTIONS).
trace_names (str, optional) – Name(s) for the primary trace(s) (default: None).
trace_name_width (int, optional) – Maximum length of the trace names before text wrapping is used (default: 40).
- Returns:
The generated Plotly figure.
- Return type:
plotly.graph_objs.Figure
- class pybop.SumSquaredError(problem)[source]#
Bases:
pybop.costs.base_cost.BaseCostSum 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.Additional Attributes#
- _defloat
The gradient of the cost function to use if an error occurs during evaluation. Defaults to 1.0.
- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Calculate the sum of squared errors for a given set of parameters.
- Parameters:
inputs (Inputs) – The parameters for which to evaluate the cost.
grad (array-like, optional) – An array to store the gradient of the cost function with respect to the parameters.
- Returns:
The sum of squared errors.
- Return type:
float
- _evaluateS1(inputs: pybop.parameters.parameter.Inputs)[source]#
Compute the cost and its gradient with respect to the parameters.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost and gradient.
- Returns:
A tuple containing the cost and the gradient. The cost is a float, and the gradient is an array-like of the same length as x.
- Return type:
tuple
- Raises:
ValueError – If an error occurs during the calculation of the cost or gradient.
- class pybop.TimeSeriesState[source]#
Bases:
objectThe current state of a time series model that is a pybamm model.
- inputs: pybop.parameters.parameter.Inputs#
- sol: pybamm.Solution#
- t: float = 0.0#
- class pybop.Uniform(lower, upper, random_state=None)[source]#
Bases:
BasePriorRepresents 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.
- property mean#
- Returns the mean of the distribution.
- property sigma#
- Returns the standard deviation of the distribution.
- 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=None, check_model=True, signal=['Voltage [V]'], additional_variables=[], init_soc=None)[source]#
Bases:
pybop.observers.observer.ObserverAn 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.
init_soc (float, optional) – Initial state of charge (default: None).
- 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.
- Covariance#
- class pybop.VolumetricEnergyDensity(problem, update_capacity=False)[source]#
Bases:
DesignCostRepresents the volumetric energy density of a battery cell, calculated based on a normalised discharge from upper to lower voltage limits. The goal is to maximise the energy density, which is achieved by setting minimising = False in the optimiser settings.
Inherits all parameters and attributes from
DesignCost.- _evaluate(inputs: pybop.parameters.parameter.Inputs, grad=None)[source]#
Computes the cost function for the energy density.
- Parameters:
inputs (Inputs) – The parameters for which to compute the cost.
grad (array, optional) – Gradient information, not used in this method.
- Returns:
The volumetric energy density or -infinity in case of infeasible parameters.
- Return type:
float
- class pybop.XNES(cost, **optimiser_kwargs)[source]#
Bases:
pybop.BasePintsOptimiserImplements 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:
**optimiser_kwargs (optional) –
Valid PINTS option keys and their values, for example: x0 : array_like
The initial parameter vector to optimise.
- sigma0float
Initial standard deviation of the sampling distribution.
- boundsdict
A dictionary with ‘lower’ and ‘upper’ keys containing arrays for lower and upperbounds on the parameters. If
None, no bounds are enforced.
See also
pints.XNESPINTS implementation of XNES algorithm.
- pybop.plot2d(cost_or_optim, gradient: bool = False, bounds: numpy.ndarray = None, steps: int = 10, show: bool = True, use_optim_log: bool = False, **layout_kwargs)[source]#
Plot a 2D visualisation of a cost landscape using Plotly.
This function generates a contour plot representing the cost landscape for a provided callable cost function over a grid of parameter values within the specified bounds.
- Parameters:
cost_or_optim (a callable cost function, pybop Cost or Optimisation object) – Either: - the cost function to be evaluated. Must accept a list of parameter values and return a cost value. - an Optimisation object which provides a specific optimisation trace overlaid on the cost landscape.
gradient (bool, optional) – If True, the gradient is shown (default: False).
bounds (numpy.ndarray, optional) – A 2x2 array specifying the [min, max] bounds for each parameter. If None, uses cost.parameters.get_bounds_for_plotly.
steps (int, optional) – The number of grid points to divide the parameter space into along each dimension (default: 10).
show (bool, optional) – If True, the figure is shown upon creation (default: True).
use_optim_log (bool, optional) – If True, the optimisation log is used to shape the cost landscape (default: False).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time [s]” or xaxis={“title”: “Time [s]”, “titlefont_size”: 18}.
- Returns:
The Plotly figure object containing the cost landscape plot.
- Return type:
plotly.graph_objs.Figure
- Raises:
ValueError – If the cost function does not return a valid cost when called with a parameter list.
- pybop.plot_convergence(optim, show=True, **layout_kwargs)[source]#
Plot the convergence of the optimisation algorithm.
- Parameters:
optim (object) – Optimisation object containing the cost function and optimiser.
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time [s]” or xaxis={“title”: “Time [s]”, “titlefont_size”: 18}.
- Returns:
fig – The Plotly figure object for the convergence plot.
- Return type:
plotly.graph_objs.Figure
- pybop.plot_dataset(dataset, signal=['Voltage [V]'], trace_names=None, show=True, **layout_kwargs)[source]#
Quickly plot a PyBOP Dataset using Plotly.
- Parameters:
dataset (object) – A PyBOP dataset.
signal (list or str, optional) – The name of the time series to plot (default: “Voltage [V]”).
trace_names (list or str, optional) – Name(s) for the trace(s) (default: “Data”).
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time / s” or xaxis={“title”: “Time / s”, “titlefont_size”: 18}.
- Returns:
The Plotly figure object for the scatter plot.
- Return type:
plotly.graph_objs.Figure
- pybop.plot_parameters(optim, show=True, **layout_kwargs)[source]#
Plot the evolution of parameters during the optimization process using Plotly.
- Parameters:
optim (object) – Optimisation object containing the history of parameter values and associated cost.
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time [s]” or xaxis={“title”: “Time [s]”, “titlefont_size”: 18}.
- Returns:
A Plotly figure object showing the parameter evolution over iterations.
- Return type:
plotly.graph_objs.Figure
- pybop.plot_trajectories(x, y, trace_names=None, show=True, **layout_kwargs)[source]#
Quickly plot one or more trajectories using Plotly.
- Parameters:
x (list or np.ndarray) – X-axis data points.
y (list or np.ndarray) – Y-axis data points for each trajectory.
trace_names (list or str, optional) – Name(s) for the trace(s) (default: None).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time / s” or xaxis={“title”: “Time / s”, “titlefont_size”: 18}.
- Returns:
The Plotly figure object for the scatter plot.
- Return type:
plotly.graph_objs.Figure
- pybop.quick_plot(problem, problem_inputs: pybop.parameters.parameter.Inputs = None, show=True, **layout_kwargs)[source]#
Quickly plot the target dataset against optimised model output.
Generates an interactive plot comparing the simulated model output with an optional target dataset and visualises uncertainty.
- Parameters:
problem (object) – Problem object with dataset and signal attributes.
problem_inputs (Inputs) – Optimised (or example) parameter values.
show (bool, optional) – If True, the figure is shown upon creation (default: True).
**layout_kwargs (optional) – Valid Plotly layout keys and their values, e.g. xaxis_title=”Time / s” or xaxis={“title”: “Time / s”, “titlefont_size”: 18}.
- Returns:
The Plotly figure object for the scatter plot.
- Return type:
plotly.graph_objs.Figure