pybop#

Subpackages#

Submodules#

Package Contents#

Classes#

Adam

Implements the Adam optimization algorithm.

BaseCost

Base class for defining cost functions.

BaseModel

A base class for constructing and simulating models using PyBaMM.

BaseOptimiser

A base class for defining optimisation methods.

CMAES

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

Dataset

Represents a collection of experimental observations.

DesignProblem

Problem class for design optimization problems.

Exponential

Represents an exponential distribution with a specified scale parameter.

FittingProblem

Problem class for fitting (parameter estimation) problems.

Gaussian

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

GradientDescent

Implements a simple gradient descent optimization algorithm.

IRPropMin

Implements the iRpropMin optimization algorithm.

NLoptOptimize

Extends BaseOptimiser to utilize the NLopt library for nonlinear optimization.

Optimisation

A class for conducting optimization using PyBOP or PINTS optimisers.

PSO

Implements a particle swarm optimization (PSO) algorithm.

Parameter

Represents a parameter within the PyBOP framework.

ParameterSet

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

PlotlyManager

Manages the installation and configuration of Plotly for generating visualizations.

RootMeanSquaredError

Root mean square error cost function.

SNES

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

SciPyDifferentialEvolution

Adapts SciPy's differential_evolution function for global optimization.

SciPyMinimize

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

StandardPlot

A class for creating and displaying Plotly figures for model output comparison.

SumSquaredError

Sum of squared errors cost function.

Uniform

Represents a uniform distribution over a specified interval.

XNES

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

Functions#

plot_convergence(optim[, xaxis_title, yaxis_title, title])

Plot the convergence of the optimisation algorithm.

plot_cost2d(cost[, bounds, optim, steps])

Plot a 2D visualization of a cost landscape using Plotly.

plot_parameters(optim[, xaxis_titles, yaxis_titles, title])

Plot the evolution of parameters during the optimization process using Plotly.

quick_plot(params, cost[, title, width, height])

Quickly plot the target dataset against minimized model output.

Attributes#

FLOAT_FORMAT

__version__

script_path

class pybop.Adam(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.Adam

Implements 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:
  • x0 (array_like) – Initial position from which optimization will start.

  • sigma0 (float, optional) – Initial step size (default is 0.1).

  • bounds (sequence or Bounds, optional) – Ignored by this optimiser, provided for API consistency.

See also

pints.Adam

The PINTS implementation this class is based on.

class pybop.BaseCost(problem)[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.

  • x0 (array-like) – The initial guess for the model parameters.

  • bounds (tuple) – The bounds for the model parameters.

  • n_parameters (int) – The number of parameters in the model.

abstract __call__(x, grad=None)[source]#

Calculate the cost function value for a given set of parameters.

This method must be implemented by subclasses.

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:

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

class pybop.BaseModel(name='Base Model')[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 behavior.

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#
build(dataset=None, parameters=None, check_model=True, init_soc=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 discretization if needed, and prepares the model for simulations.

Parameters:
  • dataset (pybamm.Dataset, optional) – The dataset to be used in the model construction.

  • parameters (dict, optional) – A 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.

predict(inputs=None, t_eval=None, parameter_set=None, experiment=None, init_soc=None)[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 (dict or array-like, optional) – Input parameters for the simulation. If the input is array-like, it is converted to a dictionary using the model’s fitting keys. 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.

set_init_soc(init_soc)[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()[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, t_eval)[source]#

Execute the forward model simulation 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.

  • 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, t_eval)[source]#

Perform the forward model simulation with sensitivities.

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.

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

class pybop.BaseOptimiser[source]#

A base class for defining optimisation methods.

This class serves as a template 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 the optimise and _runoptimise methods with specific algorithms.

_runoptimise(cost_function, x0=None, bounds=None)[source]#

Contains the logic for the optimisation algorithm.

This method should be implemented by child classes to perform the actual optimisation.

Parameters:
  • cost_function (callable) – The cost function to be minimised by the optimiser.

  • x0 (ndarray, optional) – Initial guess for the parameters. Default is None.

  • bounds (sequence or Bounds, optional) – Bounds on the parameters. Default is None.

Returns:

  • This method is expected to return the result of the optimisation, the format of which

  • will be determined by the child class implementation.

name()[source]#

Returns the name of the optimiser.

Returns:

The name of the optimiser, which is “BaseOptimiser” for this base class.

Return type:

str

optimise(cost_function, x0=None, bounds=None, maxiter=None)[source]#

Initiates the optimisation process.

This method should be overridden by child classes with the specific optimisation algorithm.

Parameters:
  • cost_function (callable) – The cost function to be minimised by the optimiser.

  • x0 (ndarray, optional) – Initial guess for the parameters. Default is None.

  • bounds (sequence or Bounds, optional) – Bounds on the parameters. Default is None.

  • maxiter (int, optional) – Maximum number of iterations to perform. Default is None.

Return type:

The result of the optimisation process. The specific type of this result will depend on the child implementation.

class pybop.CMAES(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.CMAES

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 optimization problems. It adapts the covariance matrix of a multivariate normal distribution to capture the shape of the cost landscape.

Parameters:
  • x0 (array_like) – The initial parameter vector to optimize.

  • sigma0 (float, optional) – Initial standard deviation of the sampling distribution, defaults to 0.1.

  • bounds (dict, optional) – 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.CMAES

PINTS implementation of CMA-ES algorithm.

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:
  • name (str) – The name of the dataset, providing a label for identification.

  • data (array-like) – The actual experimental data, typically in a structured form such as a NumPy array or a pandas DataFrame.

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.

__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.DesignProblem(model, parameters, experiment, check_model=True, signal=['Voltage [V]'], init_soc=None, x0=None)[source]#

Bases: 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 (list) – List of parameters for the problem.

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

evaluate(x)[source]#

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

Parameters:

x (np.ndarray) – Parameter values to evaluate the model at.

evaluateS1(x)[source]#

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

Parameters:

x (np.ndarray) – Parameter values to evaluate the model at.

class pybop.Exponential(scale)[source]#

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.

__repr__()[source]#

Returns a string representation of the Uniform object.

logpdf(x)[source]#

Calculates the logarithm of the pdf of the exponential distribution at x.

Parameters:

x (float) – The point at which to evaluate the log pdf.

Returns:

The log of the probability density function value at x.

Return type:

float

pdf(x)[source]#

Calculates the probability density function of the exponential distribution at x.

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

rvs(size)[source]#

Generates random variates from the exponential distribution.

Parameters:

size (int) – The number of random variates to generate.

Returns:

An array of random variates from the exponential distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

class pybop.FittingProblem(model, parameters, dataset, check_model=True, signal=['Voltage [V]'], init_soc=None, x0=None)[source]#

Bases: 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 (list) – List of parameters for the problem.

  • dataset (list) – List of data objects to fit the model to.

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

evaluate(x)[source]#

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

Parameters:

x (np.ndarray) – Parameter values to evaluate the model at.

evaluateS1(x)[source]#

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

Parameters:

x (np.ndarray) – Parameter values to evaluate the model at.

class pybop.Gaussian(mean, sigma)[source]#

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.

__repr__()[source]#

Returns a string representation of the Gaussian object.

logpdf(x)[source]#

Calculates the logarithm of the probability density function of the Gaussian distribution at x.

Parameters:

x (float) – The point 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 of the Gaussian distribution at x.

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

rvs(size)[source]#

Generates random variates from the Gaussian distribution.

Parameters:

size (int) – The number of random variates to generate.

Returns:

An array of random variates from the Gaussian distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

class pybop.GradientDescent(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.GradientDescent

Implements 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:
  • x0 (array_like) – Initial position from which optimization will start.

  • sigma0 (float, optional) – Initial step size (default is 0.1).

  • bounds (sequence or Bounds, optional) – Ignored by this optimiser, provided for API consistency.

See also

pints.GradientDescent

The PINTS implementation this class is based on.

class pybop.IRPropMin(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.IRPropMin

Implements 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:
  • x0 (array_like) – Initial position from which optimization will start.

  • sigma0 (float, optional) – Initial step size (default is 0.1).

  • bounds (dict, optional) – Lower and upper bounds for each optimization parameter.

See also

pints.IRPropMin

The PINTS implementation this class is based on.

class pybop.NLoptOptimize(n_param, xtol=None, method=None, maxiter=None)[source]#

Bases: pybop.optimisers.base_optimiser.BaseOptimiser

Extends BaseOptimiser to utilize the NLopt library for nonlinear optimization.

This class serves as an interface to the NLopt optimization algorithms. It allows the user to define an optimization problem with bounds, initial guesses, and to select an optimization method provided by NLopt.

Parameters:
  • n_param (int) – Number of parameters to optimize.

  • xtol (float, optional) – The relative tolerance for optimization (stopping criteria). If not provided, a default of 1e-5 is used.

  • method (nlopt.algorithm, optional) – The NLopt algorithm to use for optimization. If not provided, LN_BOBYQA is used by default.

  • maxiter (int, optional) – The maximum number of iterations to perform during optimization. If not provided, NLopt’s default is used.

_runoptimise(cost_function, x0, bounds)[source]#

Runs the optimization process using the NLopt library.

Parameters:
  • cost_function (callable) – The objective function to minimize. It should take an array of parameter values and return the scalar cost.

  • x0 (array_like) – The initial guess for the parameters.

  • bounds (dict) – A dictionary containing the ‘lower’ and ‘upper’ bounds arrays for the parameters.

Returns:

A tuple containing the optimized parameter values and the final cost.

Return type:

tuple

name()[source]#

Returns the name of this optimiser instance.

Returns:

The name ‘NLoptOptimize’ representing this NLopt optimization class.

Return type:

str

needs_sensitivities()[source]#

Indicates if the optimiser requires gradient information for the cost function.

Returns:

False, as the default NLopt algorithms do not require gradient information.

Return type:

bool

class pybop.Optimisation(cost, optimiser=None, sigma0=None, verbose=False)[source]#

A class for conducting optimization using PyBOP or PINTS optimisers.

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

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

x0#

Initial parameter values for the optimization.

Type:

numpy.ndarray

bounds#

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

Type:

dict

n_parameters#

Number of parameters in the optimization problem.

Type:

int

sigma0#

Initial step size or standard deviation for the optimiser.

Type:

float or sequence

log#

Log of the optimization process.

Type:

list

_run_pints()[source]#

Internal method to run the optimization using a PINTS optimiser.

Returns:

  • x (numpy.ndarray) – The best parameter set found by the optimization.

  • final_cost (float) – The final cost associated with the best parameters.

See also

This

_run_pybop()[source]#

Internal method to run the optimization using a PyBOP optimiser.

Returns:

  • x (numpy.ndarray) – The best parameter set found by the optimization.

  • final_cost (float) – The final cost associated with the best parameters.

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

run()[source]#

Run the optimization and return the optimized parameters and final cost.

Returns:

  • x (numpy.ndarray) – The best parameter set found by the optimization.

  • final_cost (float) – The final cost associated with the best parameters.

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 optimization (default: None).

set_max_iterations(iterations=1000)[source]#

Set the maximum number of iterations as a stopping criterion. Credit: PINTS

Parameters:

iterations (int, optional) – The maximum number of iterations to run (default is 1000). Set to None to remove this stopping criterion.

set_max_unchanged_iterations(iterations=25, threshold=1e-05)[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 is 25). Set to None to remove this stopping criterion.

  • threshold (float, optional) – The minimum significant change in the objective function value that resets the unchanged iteration counter (default is 1e-5).

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

store_optimised_parameters(x)[source]#

Update the problem parameters with optimized values.

The optimized parameter values are stored within the associated PyBOP parameter class.

Parameters:

x (array-like) – Optimized parameter values.

class pybop.PSO(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.PSO

Implements 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:
  • x0 (array_like) – Initial positions of particles, which the optimization will use.

  • sigma0 (float, optional) – Spread of the initial particle positions (default is 0.1).

  • bounds (dict, optional) – Lower and upper bounds for each optimization parameter.

See also

pints.PSO

The PINTS implementation this class is based on.

class pybop.Parameter(name, initial_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)[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_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(value)[source]#

Update the parameter’s current value.

Parameters:

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

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.

_handle_special_cases()[source]#

Processes special cases for parameter values that require custom handling.

For example, if the open-circuit voltage is specified as ‘default’, it will fetch the default value from the PyBaMM empirical Thevenin model.

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

Retrieves a PyBaMM parameter set by name.

Parameters:

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

Returns:

A PyBaMM parameter set corresponding to the provided name.

Return type:

pybamm.ParameterValues

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.

install_plotly()[source]#

Install the Plotly package using pip. Exit if installation fails.

post_install_setup()[source]#

Import Plotly modules and set the default renderer after installation.

prompt_for_plotly_installation()[source]#

Prompt the user for Plotly installation and install it upon agreement.

class pybop.RootMeanSquaredError(problem)[source]#

Bases: 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.

__call__(x, grad=None)[source]#

Calculate the root mean square error 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 root mean square error.

Return type:

float

Raises:

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

class pybop.SNES(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.SNES

Implements 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:
  • x0 (array_like) – Initial position from which optimization will start.

  • sigma0 (float, optional) – Initial step size (default is 0.1).

  • bounds (dict, optional) – Lower and upper bounds for each optimization parameter.

See also

pints.SNES

The PINTS implementation this class is based on.

class pybop.SciPyDifferentialEvolution(bounds=None, strategy='best1bin', maxiter=1000, popsize=15)[source]#

Bases: pybop.optimisers.base_optimiser.BaseOptimiser

Adapts 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 (sequence or Bounds) – Bounds for variables. Must be provided as it is essential for differential evolution.

  • strategy (str, optional) – The differential evolution strategy to use. Defaults to ‘best1bin’.

  • maxiter (int, optional) – Maximum number of iterations to perform. Defaults to 1000.

  • popsize (int, optional) – The number of individuals in the population. Defaults to 15.

_runoptimise(cost_function, x0=None, bounds=None)[source]#

Executes the optimization process using SciPy’s differential_evolution function.

Parameters:
  • cost_function (callable) – The objective function to minimize.

  • x0 (array_like, optional) – Ignored parameter, provided for API consistency.

  • bounds (sequence or Bounds) – Bounds for the variables, required for differential evolution.

Returns:

A tuple (x, final_cost) containing the optimized parameters and the value of cost_function at the optimum.

Return type:

tuple

name()[source]#

Provides the name of the optimization strategy.

Returns:

The name ‘SciPyDifferentialEvolution’.

Return type:

str

needs_sensitivities()[source]#

Determines if the optimization algorithm requires gradient information.

Returns:

False, indicating that gradient information is not required for differential evolution.

Return type:

bool

class pybop.SciPyMinimize(method=None, bounds=None, maxiter=None)[source]#

Bases: pybop.optimisers.base_optimiser.BaseOptimiser

Adapts 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:
  • method (str, optional) – The type of solver to use. If not specified, defaults to ‘COBYLA’.

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

  • maxiter (int, optional) – Maximum number of iterations to perform.

_runoptimise(cost_function, x0, bounds)[source]#

Executes the optimization process using SciPy’s minimize function.

Parameters:
  • cost_function (callable) – The objective function to minimize.

  • x0 (array_like) – Initial guess for the parameters.

  • bounds (sequence or Bounds) – Bounds for the variables.

Returns:

A tuple (x, final_cost) containing the optimized parameters and the value of cost_function at the optimum.

Return type:

tuple

name()[source]#

Provides the name of the optimization strategy.

Returns:

The name ‘SciPyMinimize’.

Return type:

str

needs_sensitivities()[source]#

Determines if the optimization algorithm requires gradient information.

Returns:

False, indicating that gradient information is not required.

Return type:

bool

class pybop.StandardPlot(x, y, cost, y2=None, title=None, xaxis_title=None, yaxis_title=None, trace_name=None, width=1024, height=576)[source]#

A class for creating and displaying Plotly figures for model output comparison.

Generates interactive plots comparing simulated model output with an optional target dataset and visualizes uncertainty.

Parameters:
  • x (list or np.ndarray) – X-axis data points.

  • y (list or np.ndarray) – Primary Y-axis data points for simulated model output.

  • cost (float) – Cost associated with the model output.

  • y2 (list or np.ndarray, optional) – Secondary Y-axis data points for the target dataset (default: None).

  • title (str, optional) – Title of the plot (default: None).

  • xaxis_title (str, optional) – Title for the x-axis (default: None).

  • yaxis_title (str, optional) – Title for the y-axis (default: None).

  • trace_name (str, optional) – Name for the primary trace (default: “Simulated”).

  • width (int, optional) – Width of the figure in pixels (default: 1024).

  • height (int, optional) – Height of the figure in pixels (default: 576).

__call__()[source]#

Generate the Plotly figure.

Returns:

The generated Plotly figure.

Return type:

plotly.graph_objs.Figure

create_layout()[source]#

Create the layout for the Plotly figure.

Returns:

The layout for the Plotly figure.

Return type:

plotly.graph_objs.Layout

create_traces()[source]#

Create traces for the Plotly figure.

Returns:

A list of plotly.graph_objs.Scatter objects to be used as traces.

Return type:

list

static wrap_text(text, width)[source]#

Wrap text to a specified width with HTML line breaks.

Parameters:
  • text (str) – The text to wrap.

  • width (int) – The width to wrap the text to.

Returns:

The wrapped text.

Return type:

str

class pybop.SumSquaredError(problem)[source]#

Bases: 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.

Additional Attributes#

_defloat

The gradient of the cost function to use if an error occurs during evaluation. Defaults to 1.0.

__call__(x, grad=None)[source]#

Calculate the sum of squared errors 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 sum of squared errors.

Return type:

float

Raises:

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

evaluateS1(x)[source]#

Compute the cost and its gradient with respect to the 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.

set_fail_gradient(de)[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.

class pybop.Uniform(lower, upper)[source]#

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.

__repr__()[source]#

Returns a string representation of the Uniform object.

logpdf(x)[source]#

Calculates the logarithm of the pdf of the uniform distribution at x.

Parameters:

x (float) – The point at which to evaluate the log pdf.

Returns:

The log of the probability density function value at x.

Return type:

float

pdf(x)[source]#

Calculates the probability density function of the uniform distribution at x.

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

rvs(size)[source]#

Generates random variates from the uniform distribution.

Parameters:

size (int) – The number of random variates to generate.

Returns:

An array of random variates from the uniform distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

class pybop.XNES(x0, sigma0=0.1, bounds=None)[source]#

Bases: pints.XNES

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:
  • x0 (array_like) – The initial parameter vector to optimize.

  • sigma0 (float, optional) – Initial standard deviation of the sampling distribution, defaults to 0.1.

  • bounds (dict, optional) – 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.XNES

PINTS implementation of XNES algorithm.

pybop.plot_convergence(optim, xaxis_title='Iteration', yaxis_title='Cost', title='Convergence')[source]#

Plot the convergence of the optimisation algorithm.

Parameters:
  • optim (optimisation object) – Optimisation object containing the cost function and optimiser.

  • xaxis_title (str, optional) – Title for the x-axis (default is “Iteration”).

  • yaxis_title (str, optional) – Title for the y-axis (default is “Cost”).

  • title (str, optional) – Title of the plot (default is “Convergence”).

Returns:

fig – The Plotly figure object for the convergence plot.

Return type:

plotly.graph_objs.Figure

pybop.plot_cost2d(cost, bounds=None, optim=None, steps=10)[source]#

Plot a 2D visualization 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 (callable) – The cost function to be evaluated. Must accept a list of parameters and return a cost value.

  • bounds (numpy.ndarray, optional) – A 2x2 array specifying the [min, max] bounds for each parameter. If None, uses get_param_bounds.

  • optim (object, optional) – An optimiser instance which, if provided, overlays its specific trace on the plot.

  • steps (int, optional) – The number of intervals to divide the parameter space into along each dimension (default is 10).

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_parameters(optim, xaxis_titles='Iteration', yaxis_titles=None, title='Convergence')[source]#

Plot the evolution of parameters during the optimization process using Plotly.

Parameters:
  • optim (object) – The optimization object containing the history of parameter values and associated cost.

  • xaxis_titles (str, optional) – Title for the x-axis, defaulting to “Iteration”.

  • yaxis_titles (list of str, optional) – Titles for the y-axes, one for each parameter. If None, parameter names are used.

  • title (str, optional) – Title of the plot, defaulting to “Convergence”.

Returns:

A Plotly figure object showing the parameter evolution over iterations.

Return type:

plotly.graph_objs.Figure

pybop.quick_plot(params, cost, title='Scatter Plot', width=1024, height=576)[source]#

Quickly plot the target dataset against minimized model output.

Parameters:
  • params (array-like) – Optimized parameters.

  • cost (object) – Cost object with problem, dataset, and signal attributes.

  • title (str, optional) – Title of the plot (default: “Scatter Plot”).

  • width (int, optional) – Width of the figure in pixels (default: 1024).

  • height (int, optional) – Height of the figure in pixels (default: 576).

Returns:

The Plotly figure object for the scatter plot.

Return type:

plotly.graph_objs.Figure

pybop.FLOAT_FORMAT = '{: .17e}'[source]#
pybop.__version__ = '23.12'[source]#
pybop.script_path[source]#