pybop#

Submodules#

Attributes#

Classes#

AdamW

Adapter for adaptive moment estimation with weight decay (AdamW), a variant of the Adam

AdaptiveCovarianceMCMC

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

BaseApplication

A base class for PyBOP's application methods.

BaseOptimiser

A base class for defining optimisation methods.

BasePintsOptimiser

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

BasePintsSampler

Base class for PINTS samplers.

BasePrior

A base class for defining prior distributions.

BaseSampler

Base class for Monte Carlo samplers.

BaseSciPyOptimiser

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

BaseSimulator

Base simulator.

CMAES

Adapter for the covariance matrix adaptation evolution strategy (CMA-ES), an evolutionary

ChainProcessor

Base class for chain processing.

CuckooSearch

Adapter for cuckoo search, a population-based optimisation algorithm inspired by the brood

DREAM

Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm.

Dataset

Represents a collection of experimental observations.

DesignCost

Base design cost.

DifferentialEvolutionMCMC

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

DramACMC

Implements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance MCMC algorithm.

EmceeHammerMCMC

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

ErrorMeasure

Base fitting cost (error measure).

Exponential

Represents an exponential distribution with a specified scale parameter.

ExponentialDecayModel

Exponential decay model defined by the equation:

FailedSolution

return isinstance(x, int | float | np.number)

FailedVariable

Check if a variable is numeric.

GITTFit

Fit the diffusion timescale of each pulse from a galvanostatic intermittent

GITTPulseFit

Fit the diffusion timescale of one pulse from a galvanostatic intermittent

Gaussian

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

GaussianLogLikelihood

This class represents a Gaussian log-likelihood, which computes the log-likelihood under

GaussianLogLikelihoodKnownSigma

This class represents a Gaussian log-likelihood with a known sigma, which computes the

GradientDescent

Adapter for gradient descent, a canonical method that takes steps in the opposite direction

HaarioACMC

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

HaarioBardenetACMC

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

HamiltonianMCMC

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

IRPropMin

Adapter for improved resilient backpropagation (without weight-backtracking), an optimisation

IRPropPlus

Adapter for improved resilient backpropagation with weight-backtracking, an optimisation

Interpolant

A class that returns a pybamm.Interpolant to pybamm models and otherwise

InverseOCV

A class to find the stoichiometry corresponding to a given open-circuit

JointPrior

Represents a joint prior distribution composed of multiple prior distributions.

LogLikelihood

Base class for likelihoods.

LogPosterior

The log-posterior defined as the sum of the log-likelihood and the log-prior.

Logger

Records the parameter values and corresponding cost values.

MALAMCMC

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

MeanAbsoluteError

Mean absolute error (MAE) cost function.

MeanSquaredError

Mean square error (MSE) cost function.

MetaProblem

Problem class for joining mulitple problems into one combined problem.

MetropolisRandomWalkMCMC

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

Minkowski

The Minkowski distance is a generalisation of several distance metrics,

MonomialGammaHamiltonianMCMC

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

MultiChainProcessor

Processor for simultaneous chains.

NUTS

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

NelderMead

Adpater for the Nelder-Mead downhill simplex method, a deterministic local optimiser that does

OCPAverage

Estimate the equlilibrium open-circuit potential (OCP) by averaging the charge

OCPCapacityToStoichiometry

Estimate the stoichiometry from a measurement of open-circuit voltage versus

OCPMerge

Generate a representative open-circuit potential (OCP) without hysteresis by

OptimiserOptions

A base class for optimiser options.

PSO

Adapter for particle swarm optimisation (PSO), a metaheuristic optimisation method inspired by

Parameter

Represents a parameter within the PyBOP framework.

Parameters

Container for managing multiple Parameter objects with additional functionality.

PintsOptions

A class to hold PINTS options for the optimisation process.

PintsSamplerOptions

Pints sampler options.

PopulationEvaluator

Evaluates a function (or callable object) for multiple positions.

PopulationMCMC

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

PosteriorSummary

Problem

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

RandomSearch

Adapter for random search, a simple algorithm which samples parameter values randomly and

RaoBlackwellACMC

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

RecommendedSolver

A shortcut for creating the PyBaMM solver recommended for optimisation.

RelativisticMCMC

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

RootMeanSquaredError

Root mean square error (RMSE) cost function.

SNES

Adapter for the stochastic natural evolution strategy (SNES), an evolutionary algorithm that

SamplerOptions

Base options for the sampler.

ScalarEvaluator

Evaluates a function (or callable object) for a single input.

SciPyDifferentialEvolution

Adapter for SciPy's differential_evolution function for global optimisation, useful for problems

SciPyDifferentialEvolutionOptions

Options for the SciPy differential evolution method.

SciPyMinimize

Adapter for various scalar minimisation algorithms implemented in SciPy, allowing fine-tuning

SciPyMinimizeOptions

Options for the SciPy minimize method.

SequentialEvaluator

Evaluates a function (or callable object) for a list of input values, and

SimulatedAnnealing

Adapter for simulated annealing, a probabilistic optimisation method inspired by the annealing

SingleChainProcessor

Processor for individual chains.

SliceDoublingMCMC

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

SliceRankShrinkingMCMC

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

SliceStepoutMCMC

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

SumOfPower

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

SumSquaredError

Sum of squared error (SSE) cost function.

SymbolReplacer

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

Uniform

Represents a uniform distribution over a specified interval.

WeightedCost

A subclass for constructing a linear combination of cost functions as

XNES

Adapter for the exponential natural evolution strategy (XNES), an evolutionary algorithm that

Functions#

add_spaces(string)

Return the class name as a string with spaces before each new capitalised word.

is_numeric(x)

Check if a variable is numeric.

Package Contents#

class pybop.AdamW(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for adaptive moment estimation with weight decay (AdamW), a variant of the Adam optimiser which does not support boundary constraints.

This optimiser is designed to be more robust and stable for training deep neural networks, particularly when using larger learning rates.

Parameters:

See also

pybop.AdamWImpl

The PyBOP implementation this class is based on.

class pybop.AdaptiveCovarianceMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class wraps the Adaptive Covariance MCMC sampler from the PINTS library. The proposal distribution’s covariance matrix is adapted during sampling to improve efficiency and convergence.

Parameters:
class pybop.BaseApplication[source]#

A base class for PyBOP’s application methods.

check_monotonicity(voltage)[source]#
class pybop.BaseOptimiser(problem: pybop.problems.problem.Problem, options: OptimiserOptions | None = None)[source]#

A base class for defining optimisation methods.

This class serves as a base class for creating optimisers. It provides a basic structure for an optimisation algorithm, including the initial setup and a method stub for performing the optimisation process. Child classes should override _set_up_optimiser and the _run method with a specific algorithm.

Parameters:
abstractmethod _run() pybop._result.OptimisationResult[source]#

Contains the logic for the optimisation algorithm.

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

Raises:

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

abstractmethod _set_up_optimiser()[source]#

Parse optimiser options and prepare the optimiser.

This method should be implemented by child classes.

Raises:

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

static default_options() OptimiserOptions[source]#

Returns the default options for the optimiser.

abstractmethod name() str[source]#

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

Returns:

The name of the optimiser

Return type:

str

run() pybop._result.OptimisationResult[source]#

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

Returns:

results – The pybop optimisation result class.

Return type:

OptimisationResult

_logger = None#
_multistart = 1#
_needs_sensitivities = None#
_options#
_problem#
default_max_iterations = 1000#
property logger: pybop._logging.Logger | None#
property options: OptimiserOptions#

Returns the options for the optimiser.

property problem: pybop.problems.problem.Problem#

Returns the optimisation problem object.

verbose = False#
verbose_print_rate = 50#
class pybop.BasePintsOptimiser(problem: pybop.problems.problem.Problem, pints_optimiser: pints.Optimiser, options: PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_optimiser.BaseOptimiser

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

Parameters:
  • problem (pybop.Problem) – The problem to minimise.

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

  • options (PintsOptions, optional) – Options for the PINTS optimiser. If None, default options are used.

_run() pybop.OptimisationResult[source]#

Internal method to run the optimisation using a PINTS optimiser.

Returns:

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

Return type:

pybop.OptimisationResult

See also

This

_set_up_optimiser()[source]#

Parse optimiser options and create an instance of the PINTS optimiser.

static default_options() PintsOptions[source]#

Returns the default options for the PINTS optimiser.

f_guessed_tracking()[source]#

Check if f_guessed instead of f_best is being tracked. Credit: PINTS

Returns:

True if f_guessed is being tracked, False otherwise.

Return type:

bool

set_f_guessed_tracking(use_f_guessed=False)[source]#

Set the method used to track the optimiser progress. Credit: PINTS

Parameters:

use_f_guessed (bool, optional) – If True, track f_guessed; otherwise, track f_best (default: False).

set_max_evaluations(evaluations=None)[source]#

Set a maximum number of evaluations stopping criterion. Credit: PINTS

Parameters:

evaluations (int, optional) – The maximum number of evaluations after which to stop the optimisation (default: None).

set_max_iterations(iterations: str | int | None = 'default')[source]#

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

Parameters:

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

set_max_unchanged_iterations(iterations=15, absolute_tolerance=1e-05, relative_tolerance=0.01)[source]#

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

Parameters:
  • iterations (int, optional) – The maximum number of unchanged iterations to run (default: 15). Set to None to remove this stopping criterion.

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

  • relative_tolerance (float, optional) – The minimum significant proportional change (relative tolerance) in the objective function value that resets the unchanged iteration counter (default: 1e-2).

set_min_iterations(iterations=2)[source]#

Set the minimum number of iterations as a stopping criterion.

Parameters:

iterations (int, optional) – The minimum number of iterations to run (default: 2). Set to None to remove this stopping criterion.

set_population_size(population_size=None)[source]#

Set the population size for population-based optimisers, if specified.

set_threshold(threshold=None)[source]#

Adds a stopping criterion, allowing the routine to halt once the objective function goes below a set threshold.

This criterion is disabled by default, but can be enabled by calling this method with a valid threshold. To disable it, use set_threshold(None). Credit: PINTS

Parameters:

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

_pints_optimiser#
property iteration#
property max_iterations#

Returns the maximum number of iterations for the optimisation.

property name#

Returns the name of the PINTS optimisation strategy.

property optimiser: pints.Optimiser#
class pybop.BasePintsSampler(log_pdf: pybop.problems.problem.Problem, sampler: type[pints.SingleChainMCMC | pints.MultiChainMCMC], options: PintsSamplerOptions | None = None)[source]#

Bases: pybop.BaseSampler

Base class for PINTS samplers.

This class extends the BaseSampler class to provide a common interface for PINTS samplers. The class provides a sample() method that can be used to sample from the posterior distribution using a PINTS sampler.

Parameters:
  • log_pdf (pybop.Problem) – The negative unnormalised posterior distribution.

  • sampler (pints.MCMCSampler) – The PINTS sampler to be used for sampling.

  • options (Optional[PintsSamplerOptions]) – Options for the sampler, by default None.

_ask_for_samples()[source]#
_check_initial_phase()[source]#

Set initial phase if needed

_check_stopping_criteria()[source]#

Verify that at least one stopping criterion is defined.

_end_initial_phase()[source]#
_finalise_logging()[source]#
_initialise_chain_processor()[source]#

Initialise the appropriate chain processor based on configuration.

_initialise_logging()[source]#
_initialise_storage()[source]#
_process_chains()[source]#

Process chains using the appropriate processor.

static default_options() PintsSamplerOptions[source]#

Get the default options for the sampler.

run() numpy.ndarray[source]#

Executes the Monte Carlo sampling process and generates samples from the posterior distribution.

This method orchestrates the entire sampling process, managing iterations, evaluations, logging, and stopping criteria. It initialises the necessary structures, handles both single and multi-chain scenarios, and manages parallel evaluation based on the configuration.

Returns:

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

Return type:

np.ndarray

Raises:
  • ValueError – If no stopping criterion is set (i.e.,

  • _max_iterations is None).

Details:
  • Checks and ensures at least one stopping criterion is set.

  • Initialises iterations, evaluations, and other required

structures. - Sets up the parallel evaluator based on the configuration. - Handles the initial phase, if applicable, and manages intermediate steps in the sampling process. - Logs progress and relevant information based on the logging configuration. - Iterates through the sampling process, evaluating the log PDF, updating chains, and managing the stopping criteria. - Finalises and returns the collected samples, or None if chains are not stored in memory.

_chain_files = None#
_chains_in_memory = True#
_evaluation_files = None#
_initial_phase#
_initial_phase_iterations = 250#
_log_filename = None#
_log_to_screen = True#
_loop_iters = 0#
_max_iterations = 500#
_n_parameters#
_needs_sensitivities#
_sampler#
_single_chain#
_verbose = False#
_warm_up = 0#
property active#
property chains_in_memory#
iter_time = 0.0#
property iteration#
property max_iterations#
property n_samples#
property needs_sensitivities#
property sampled_logpdf#
property sampled_prior#
property samplers#
property single_chain#
class pybop.BasePrior[source]#

A base class for defining prior distributions.

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

prior#

The underlying continuous random variable distribution.

Type:

scipy.stats.rv_continuous

loc#

The location parameter of the distribution.

Type:

float

scale#

The scale parameter of the distribution.

Type:

float

__call__(x)[source]#

Evaluates the distribution at x.

Parameters:

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

Returns:

The value(s) of the distribution at x.

Return type:

float

__repr__()[source]#

Returns a string representation of the object.

abstractmethod _logpdfS1(x)[source]#

Evaluates the first derivative of the distribution at x.

Parameters:

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

Returns:

The value(s) of the first derivative at x.

Return type:

float

abstractmethod bounds() tuple[float, float] | None[source]#
cdf(x)[source]#

Calculates the cumulative distribution function (CDF) of the distribution at x.

Parameters:

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

Returns:

The cumulative distribution function value at x.

Return type:

float

icdf(q)[source]#

Calculates the inverse cumulative distribution function (CDF) of the distribution at q.

Parameters:

q (float) – The point(s) at which to evaluate the inverse CDF.

Returns:

The inverse cumulative distribution function value at q.

Return type:

float

logpdf(x)[source]#

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

Parameters:

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

Returns:

The logarithm of the probability density function value at x.

Return type:

float

logpdfS1(x)[source]#

Evaluates the first derivative of the distribution at x.

Parameters:

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

Returns:

The value(s) of the first derivative at x.

Return type:

float

pdf(x)[source]#

Calculates the probability density function (PDF) of the distribution at x.

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

rvs(size=1, random_state=None)[source]#

Generates random variates from the distribution.

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

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

Returns:

An array of random variates from the distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

verify(x)[source]#

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

property mean#

Get the mean of the distribution.

Returns:

The mean of the distribution.

Return type:

float

property sigma#

Get the standard deviation of the distribution.

Returns:

The standard deviation of the distribution.

Return type:

float

class pybop.BaseSampler(log_pdf: pybop.problems.problem.Problem, options: SamplerOptions | None = None)[source]#

Base class for Monte Carlo samplers.

Parameters:
  • log_pdf (pybop.Problem) – The negative unnormalised posterior distribution.

  • options (SamplerOptions, optional) – Options for the sampler. If None, default options are used.

static default_options() SamplerOptions[source]#

Get the default options for the sampler.

abstractmethod run() numpy.ndarray[source]#

Sample from the posterior distribution.

Returns:

Samples from the posterior distribution.

Return type:

np.ndarray

set_initial_phase_iterations(iterations: int = 250)[source]#

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

set_max_iterations(iterations: int = 500)[source]#

Set the maximum number of iterations for the sampler.

set_warm_up_iterations(iterations: int = 250)[source]#

Set the number of warm up iterations for the sampler.

_log_pdf#
_options#
_x0#
property cov0: numpy.ndarray#
property log_pdf: pybop.problems.problem.Problem#
property options: SamplerOptions#
property x0: numpy.ndarray#
class pybop.BaseSciPyOptimiser(problem: pybop.problems.problem.Problem, options: pybop.OptimiserOptions | None)[source]#

Bases: pybop.BaseOptimiser

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

Parameters:
_set_callback()[source]#

Add a callback to record the iteration number.

scipy_bounds() scipy.optimize.Bounds[source]#
class pybop.BaseSimulator(parameters: pybop.parameters.parameter.Parameters | None = None)[source]#

Base simulator.

copy()[source]#

Return a copy of the simulator.

set_output_variables(target: list[str])[source]#
simulate(inputs: Inputs | None = None, calculate_sensitivities: bool = False) dict[str, numpy.ndarray] | tuple[dict[str, numpy.ndarray], dict[str, dict[str, numpy.ndarray]]][source]#

Returns the output of a simulation for the given inputs as a dictionary, along with the sensitivities of the output with respect to the input parameters if calculate_sensitivities=True.

property has_sensitivities#
parameters = None#
class pybop.CMAES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for the covariance matrix adaptation evolution strategy (CMA-ES), an evolutionary algorithm for difficult non-linear non-convex optimisation problems.

It adapts the covariance matrix of a multivariate normal distribution to capture the shape of the cost landscape.

Parameters:

See also

pints.CMAES

PINTS implementation of CMA-ES algorithm.

class pybop.ChainProcessor(mcmc_sampler)[source]#

Base class for chain processing.

This clas architecture implements a strategy-pattern for selection between multi-chain and single-chain samplers as implemented in child classes.

Parameters:

mcmc_sampler (pybop.BasePintsSampler) – A BasePintsSampler object.

abstractmethod _extract_log_pdf(fy_value, chain_idx)[source]#

Extract log-pdf for an accepted sample.

get_evaluation_metrics(chain_idx)[source]#

Get evaluation metrics for the current sample.

abstractmethod process_chain()[source]#

Process the chain

store_samples(values, chain_idx)[source]#

Store samples based on memory configuration. Samples shape: [n_chains, n_iterations, n_parameters]

update_accepted_sample(chain_idx, y, fy_value)[source]#

Update stored values for an accepted sample.

sampler#
class pybop.CuckooSearch(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for cuckoo search, a population-based optimisation algorithm inspired by the brood parasitism of some cuckoo species which is suitable for global optimisation problems.

Cuckoo search is designed to be simple, efficient, and robust. It explores the search space by randomly suggesting candidate “nests” and abandoning poorly performing “nests” throughout the process.

Parameters:

See also

pybop.CuckooSearchImpl

PyBOP implementation of Cuckoo Search algorithm.

class pybop.DREAM(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

Implements the DiffeRential Evolution Adaptive Metropolis (DREAM) algorithm.

This class wraps the DREAM sampler from the PINTS library. DREAM combines Differential Evolution and Adaptive Metropolis to efficiently explore complex parameter spaces using a population of chains.

Parameters:
class pybop.Dataset(data_dictionary, domain: str | None = None)[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.

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

__getitem__(key)[source]#

Return the data corresponding to a particular key.

Parameters:

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

Returns:

The data series corresponding to the key.

Return type:

list or np.ndarray

Raises:

ValueError – The key must exist in the dataset.

__repr__()[source]#

Return a string representation of the Dataset instance.

Returns:

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

Return type:

str

__setitem__(key, value)[source]#

Set the data corresponding to a particular key.

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

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

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

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

Parameters:
  • domain (str, optional) – If not None, updates the domain of the dataset.

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

Returns:

True if the dataset has the expected attributes.

Return type:

bool

Raises:

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

get_subset(index: list | numpy.ndarray)[source]#

Reduce the dataset to a subset defined by the list of indices.

data#
domain = 'Time [s]'#
class pybop.DesignCost(target: str)[source]#

Bases: pybop.costs.base_cost.BaseCost

Base design cost.

Note that design costs are maximised by default. Change to minimising by setting the attribute minimising=True.

Parameters:

target (str) – The name of the target variable.

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

Returns the value of the cost variable.

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

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

Returns:

The value of the output variable.

Return type:

float

verify_prediction(y: dict)[source]#

Verify that the prediction matches the target data.

Parameters:

y (dict) – A dictionary of predictions with keys designating the output variables for fitting.

Returns:

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

Return type:

bool

domain = 'Time [s]'#
minimising = False#
target#
class pybop.DifferentialEvolutionMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class wraps the Differential Evolution MCMC sampler from the PINTS library. Uses a population of chains and differential evolution proposals for efficient exploration of the parameter space.

Parameters:
class pybop.DramACMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

Implements the Delayed Rejection Adaptive Metropolis (DRAM) Adaptive Covariance MCMC algorithm.

This class wraps the DRAM Adaptive Covariance MCMC sampler from the PINTS library. Combines delayed rejection and adaptive covariance for robust and efficient sampling.

Parameters:
class pybop.EmceeHammerMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

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

Parameters:
class pybop.ErrorMeasure(dataset: pybop._dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: pybop.costs.base_cost.BaseCost

Base fitting cost (error measure).

This class is intended to be subclassed to create specific cost functions for evaluating model predictions against a set of data. The cost function quantifies the goodness-of-fit between model predictions and the target data, with a lower cost value indicating a better fit.

Parameters:
  • dataset (pybop.Dataset) – Dataset object containing the target data.

  • target (list[str]) – The name(s) of the target variable(s).

  • weighting (Union[str, np.ndarray], optional) – The type of weighting to use when taking the sum or mean of the error measure.

dataset#

The dictionary from a Dataset object containing the target data.

Type:

dictionary

domain#

The name of the domain (default: “Time [s]”).

Type:

str

domain_data#

The domain points in the dataset.

Type:

np.ndarray

n_domain_data#

The number of domain points.

Type:

int

target_data#

The target values of the output variables.

Type:

np.ndarray

abstractmethod __call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

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

Computes the cost function for the given predictions.

Parameters:
  • y (dict[str, np.ndarray[np.float64]]) – The dictionary of predictions with keys designating the output variables for fitting.

  • dy (dict[str, dict[str, np.ndarray]], optional) – The corresponding sensitivities to each parameter for each output variable.

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

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

Set the target data from a pybop.Dataset.

set_weighting(weighting: float | str | numpy.ndarray)[source]#
verify_prediction(y: dict)[source]#

Verify that the prediction matches the target data.

Parameters:

y (dict) – A dictionary of predictions with keys designating the output variables for fitting.

Returns:

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

Return type:

bool

property dataset#
property domain_data#
property name#
target#
property target_data#
class pybop.Exponential(scale, loc=0, random_state=None)[source]#

Bases: BasePrior

Represents an exponential distribution with a specified scale parameter.

This class provides methods to calculate the pdf, the log pdf, and to generate random variates from the distribution.

Parameters:

scale (float) – The scale parameter (lambda) of the exponential distribution.

_logpdfS1(x)[source]#

Evaluates the first derivative of the log exponential distribution at x.

Parameters:

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

Returns:

The value(s) of the first derivative at x.

Return type:

float

bounds() None[source]#
_n_parameters = 1#
loc = 0#
name = 'Exponential'#
prior#
scale#
class pybop.ExponentialDecayModel(name: str = 'Experimental Decay Model', n_states: int = 1)[source]#

Bases: pybamm.models.base_model.BaseModel

Exponential decay model defined by the equation:

dy/dt = -k * y, y(0) = y0

Note: The output variables are named “y_{i}” for each state. For example, the first state is “y_0”, the second is “y_1”, etc.

The model parameters are “k” (decay rate) and “y0” (initial condition).

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

  • n_states (int) – Number of states in the system, must be >= 1 (default is 1).

property default_parameter_values: pybamm.ParameterValues#

Returns the default parameter values for the model (an empty set of parameters by default).

property default_quick_plot_variables#

Returns the default variables for quick plotting (None by default).

initial_conditions#

Returns a dictionary mapping expressions (variables) to expressions that represent the initial conditions for the state variables.

n_states = 1#
rhs#

Returns a dictionary mapping expressions (variables) to expressions that represent the right-hand side (RHS) of the model’s differential equations.

variables#

Returns a dictionary mapping strings to expressions representing the model’s useful variables.

class pybop.FailedSolution(variable_names: list[str], parameter_names: list[str])[source]#

return isinstance(x, int | float | np.number) Container for a failed PyBaMM solution that returns [np.inf] for all processed variables.

This class mimics the interface of a successful PyBaMM solution but returns infinity values to indicate failure while maintaining API compatibility.

Parameters:
  • variable_names – List of variable names in the solution

  • parameter_names – List of parameter names for sensitivity analysis

Example

>>> solution = FailedSolution(["Voltage [V]"], ["Negative particle radius [m]"])
>>> voltage = solution["Voltage [V]"]
>>> print(voltage.data)  # np.ndarray([inf])
__getattr__(name)[source]#
__getitem__(key)[source]#
_initialise_variables() None[source]#

Initialise all variables with failed state.

_validate_inputs(variable_names: list[str], parameter_names: list[str] | None) None[source]#

Validate constructor inputs.

copy()[source]#
items() list[tuple[str, FailedVariable]][source]#

Get all variable name-value pairs.

keys() list[str][source]#

Get all variable names.

plot(*args, **kwargs)[source]#
save(*args, **kwargs)[source]#
values() list[FailedVariable][source]#

Get all variables.

_parameter_names#
_t_eval: numpy.ndarray#
_variable_names#
_variables: {str, FailedVariable}#
cycles: int | None = None#
integration_time: float = 0.0#
property parameter_names: list[str]#

Get list of parameter names (read-only).

solve_time: float = 0.0#
property t_eval: numpy.ndarray#

Time evaluation points (returns [inf] for failed solutions).

termination: str = 'failure'#
property variable_names: list[str]#

Get list of variable names (read-only).

class pybop.FailedVariable[source]#

Check if a variable is numeric. Container for a failed PyBaMM variable that returns np.inf.

Parameters:
  • name – Variable name

  • data – Array data, defaults to [np.inf]

  • sensitivities – Sensitivity data mapping parameter names to arrays

__post_init__() None[source]#

Validate inputs after initialisation.

data: numpy.ndarray#
name: str#
sensitivities: {str, np.ndarray}#
class pybop.GITTFit(gitt_dataset: pybop.Dataset, pulse_index: list[numpy.ndarray], parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = pybop.SciPyMinimize, verbose: bool = False)[source]#

Bases: pybop.BaseApplication

Fit the diffusion timescale of each pulse from a galvanostatic intermittent titration technique (GITT) measurement.

Parameters:
  • gitt_dataset (pybop.Dataset) – A dataset containing the “Time [s]”, “Current function [A]” and “Voltage [V]” for a GITT measurement.

  • pulse_index (list[np.ndarray]) – A nested list of integers representing the indices of each pulse in the dataset.

  • parameter_values (pybamm.ParameterValues) – A parameter set containing values for the parameters of the SPDiffusion model.

  • cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).

  • optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).

  • verbose (bool, optional) – If True, progress messages are printed (default: False).

__call__() pybop.Dataset[source]#
cost#
gitt_dataset#
gitt_pulse#
optimiser#
parameter_values#
pulse_index#
verbose = False#
class pybop.GITTPulseFit(parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = pybop.SciPyMinimize, verbose: bool = True)[source]#

Bases: pybop.BaseApplication

Fit the diffusion timescale of one pulse from a galvanostatic intermittent titration technique (GITT) measurement using the diffusion model for a single, spherical particle representing the working electrode.

The cost function requires a “domain”-based weighting to fit (possibly non-uniform) data consistently across the observed time period.

Parameters:
  • gitt_pulse (pybop.Dataset) – A dataset containing the “Time [s]”, “Current function [A]” and “Voltage [V]” for one pulse obtained from a GITT measurement.

  • parameter_values (pybamm.ParameterValues) – A parameter set containing values for the parameters of the SPDiffusion model.

  • cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).

  • optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).

  • verbose (bool, optional) – If True, progress messages are printed (default: True).

__call__(gitt_pulse: pybop.Dataset) pybop.OptimisationResult[source]#
cost#
model#
optim = None#
optimiser#
parameter_values#
parameters#
results = None#
verbose = True#
class pybop.Gaussian(mean, sigma, random_state=None)[source]#

Bases: BasePrior

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

This class provides methods to calculate the probability density function (pdf), the logarithm of the pdf, and to generate random variates (rvs) from the distribution.

Parameters:
  • mean (float) – The mean (mu) of the Gaussian distribution.

  • sigma (float) – The standard deviation (sigma) of the Gaussian distribution.

_logpdfS1(x)[source]#

Evaluates the first derivative of the gaussian (log) distribution at x.

Parameters:

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

Returns:

The value(s) of the first derivative at x.

Return type:

float

bounds() None[source]#
_n_parameters = 1#
loc#
name = 'Gaussian'#
prior#
scale#
class pybop.GaussianLogLikelihood(dataset: pybop._dataset.Dataset, sigma0: float | list[float] | list[pybop.parameters.parameter.Parameter] = 0.01, dsigma_scale: float = 1.0, target: str | list[str] = None)[source]#

Bases: LogLikelihood

This class represents a Gaussian log-likelihood, which computes the log-likelihood under the assumption that measurement noise on the target data follows a Gaussian distribution.

This class estimates the standard deviation of the Gaussian distribution alongside the parameters of the model.

_logpi#

Precomputed offset value for the log-likelihood function.

Type:

float

_dsigma_scale#

Scale factor for derivative of standard deviation.

Type:

float

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Compute the Gaussian log-likelihood for the given parameters.

_add_single_sigma(index, value)[source]#
_pad_sigma0(sigma0)[source]#
set_sigma0(sigma0: float | list[float] | list[pybop.parameters.parameter.Parameter])[source]#

Set sigma0 after checking its validity.

_dsigma_scale = 1.0#
_logpi#
property dsigma_scale#

Scaling factor for the dsigma term in the gradient calculation.

class pybop.GaussianLogLikelihoodKnownSigma(dataset: pybop._dataset.Dataset, sigma0: list[float] | float, target: str | list[str] = None)[source]#

Bases: LogLikelihood

This class represents a Gaussian log-likelihood with a known sigma, which computes the log-likelihood under the assumption that measurement noise on the target data follows a Gaussian distribution.

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.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

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

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

Set sigma0 after checking its validity.

class pybop.GradientDescent(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for gradient descent, a canonical method that takes steps in the opposite direction of the cost gradient with respect to the parameters (does not support boundary constraints).

Gradient descent is designed to minimise a scalar function of one or more variables. Due to the fixed step-size, the convergence rate commonly decreases as the gradient shrinks when approaching a local minima.

Parameters:

See also

pints.GradientDescent

The PINTS implementation this class is based on.

class pybop.HaarioACMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Haario Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method adapts the proposal distribution’s covariance matrix based on the history of the chain, improving sampling efficiency and convergence.

Parameters:
class pybop.HaarioBardenetACMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Haario-Bardenet Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method combines the adaptive covariance approach with an additional mechanism to improve performance in high-dimensional parameter spaces.

Parameters:
class pybop.HamiltonianMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Hamiltonian MCMC sampler from the PINTS library. This MCMC method uses Hamiltonian dynamics to propose new states, allowing for efficient exploration of high-dimensional parameter spaces.

Parameters:
class pybop.IRPropMin(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for improved resilient backpropagation (without weight-backtracking), an optimisation algorithm designed to handle problems with large plateaus, noisy gradients, and local minima.

This method uses gradient information for the proposal direction with a separated step-size.

Parameters:

See also

pints.IRPropMin

The PINTS implementation this class is based on.

class pybop.IRPropPlus(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for improved resilient backpropagation with weight-backtracking, an optimisation algorithm designed to handle problems with large plateaus, noisy gradients, and local minima.

Parameters:

See also

pints.IRPropMin

The PINTS implementation this class is based on.

class pybop.Interpolant(x, y, name=None, bounds_error=False, fill_value='extrapolate', axis=0)[source]#

A class that returns a pybamm.Interpolant to pybamm models and otherwise a numeric interpolant.

__call__(x)[source]#
interp1d#
name = None#
x#
y#
class pybop.InverseOCV(ocv_function: collections.abc.Callable, optimiser: pybop.BaseOptimiser | None = pybop.SciPyMinimize, verbose: bool = False)[source]#

A class to find the stoichiometry corresponding to a given open-circuit voltage.

Parameters:
  • ocv_function (Callable) – The open-circuit voltage as a function of stoichiometry.

  • optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).

  • verbose (bool, optional) – If True, progress messages are printed (default: False).

__call__(ocv_value: float)[source]#

Estimate and return the stoichiometry.

Parameters:

ocv_value (float) – The open-circuit voltage value [V] for which to estimate the stoichiometry.

Returns:

The stoichiometry corresponding to the open-circuit voltage value.

Return type:

float

ocv_function#
optimiser#
verbose = False#
class pybop.JointPrior(*priors: BasePrior)[source]#

Bases: BasePrior

Represents a joint prior distribution composed of multiple prior distributions.

Parameters:

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

__repr__() str[source]#

Returns a string representation of the object.

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

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

Parameters:

x (float | np.ndarray) – The point(s) at which to evaluate the first derivative. The length of x should match the total number of parameters in the joint distribution.

Returns:

A tuple containing the log-probability density and its first derivative at x.

Return type:

Tuple[float, np.ndarray]

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

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

Parameters:

x (float | np.ndarray) – The point(s) at which to evaluate the distribution. The length of x should match the total number of parameters in the joint distribution.

Returns:

The joint log-probability density of the distribution at x.

Return type:

float

_n_parameters = 0#
_priors: list[BasePrior] = []#
class pybop.LogLikelihood(dataset: pybop._dataset.Dataset, target: str | list[str] = None)[source]#

Bases: pybop.costs.error_measures.ErrorMeasure

Base class for likelihoods.

Exists to distinguish between error measures and likelihood-based costs.

abstractmethod set_sigma0(sigma0: numpy.ndarray | float, n_outputs: int, n_data: int)[source]#

Set sigma0 after checking its validity.

minimising = False#
parameters#
sigma0 = None#
class pybop.LogPosterior(log_likelihood: LogLikelihood, prior: pybop.parameters.priors.BasePrior | scipy.stats.rv_continuous | None = None, gradient_step: float = 0.001)[source]#

Bases: LogLikelihood

The log-posterior defined as the sum of the log-likelihood and the log-prior.

Additional Parameters#

log_likelihoodLogLikelihood

The likelihood class of type LogLikelihood.

priorOptional, Union[pybop.BasePrior, stats.rv_continuous]

The prior class of type BasePrior or stats.rv_continuous. If not provided, the prior class will be taken from the parameter priors constructed in the pybop.Parameters class.

gradient_stepfloat, default: 1e-3

The step size for the finite-difference gradient calculation

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

set_joint_prior()[source]#
gradient_step = 0.001#
joint_prior = None#
log_likelihood#
parameters#
prior = None#
class pybop.Logger(minimising: bool, verbose: bool = False, verbose_print_rate: int = 50)[source]#

Records the parameter values and corresponding cost values.

Parameters:
  • verbose (bool) – If True, the optimisation progress and results are printed.

  • verbose_print_rate (int) – The distance between iterations to print verbose output.

  • iteration (int) – The current iteration number.

  • x_model (list[np.ndarray]) – The history of model parameters.

  • x_search (list[np.ndarray]) – The history of search parameters.

  • cost (list[float]) – The history of the cost value.

  • iteration_number (list[int]) – The history of the iteration number.

  • evaluations (int) – The current number of evaluations.

  • x_model_best (list[np.ndarray]) – The current best model parameters.

  • cost_best (list[float]) – The current best cost value.

_print_verbose_output()[source]#

Print verbose optimisation information if enabled.

extend_log(x_model: list[numpy.ndarray], x_search: list[numpy.ndarray], cost: list[float])[source]#

Update the log with new values.

Parameters:
  • x_model (list[np.ndarray]) – The model parameters.

  • x_search (list[np.ndarray]) – The search parameters.

  • cost (list[float]) – The cost associated with the parameters.

reset()[source]#
_minimising#
property cost_convergence#

Get the convergence of the cost during the optimisation.

iteration = None#
verbose = False#
verbose_print_rate = 50#
property x0#

Get the initial parameter values.

class pybop.MALAMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the MALA MCMC sampler from the PINTS library. This MCMC method combines the Metropolis-Hastings algorithm with Langevin dynamics to improve sampling efficiency and convergence.

Parameters:
class pybop.MeanAbsoluteError(dataset: pybop._dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

Mean absolute error (MAE) cost function.

Computes the mean absolute error (MAE) between model predictions and target data. The MAE is a measure of the average magnitude of errors in a set of predictions, without considering their direction.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

class pybop.MeanSquaredError(dataset: pybop._dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

Mean square error (MSE) cost function.

Computes the mean square error between model predictions and the target data, providing a measure of the differences between predicted values and observed values.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

class pybop.MetaProblem(*problems, weights: list[float] | None = None)[source]#

Bases: pybop.Problem

Problem class for joining mulitple problems into one combined problem.

Evaluates multiple problems, which must first be defined individually.

Parameters:

problems (pybop.Problem) – The individual PyBOP fitting problems.

single_call(inputs: pybop.parameters.parameter.Inputs, calculate_grad: bool) float | tuple[float, numpy.ndarray][source]#

Evaluate the problem and (optionally) the gradient for a single set of inputs.

_has_sensitivities = True#
parameters#
problems#
class pybop.MetropolisRandomWalkMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Metropolis Random Walk MCMC sampler from the PINTS library. This classic MCMC method uses a simple random walk proposal distribution and the Metropolis-Hastings acceptance criterion.

Parameters:
class pybop.Minkowski(dataset: pybop._dataset.Dataset, p: float = 2.0, target: str | list[str] = None, weighting: str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

The Minkowski distance is a generalisation of several distance metrics, including the Euclidean and Manhattan distances. It is defined as:

\[L_p(x, y) = ( \sum_i |x_i - y_i|^p )^(1/p)\]

where p > 0 is the order of the Minkowski distance. For p ≥ 1, the Minkowski distance is a metric. For 0 < p < 1, it is not a metric, as it does not satisfy the triangle inequality, although a metric can be obtained by removing the (1/p) exponent.

Special cases:

  • p = 1: Manhattan distance

  • p = 2: Euclidean distance

  • p → ∞: Chebyshev distance (not implemented as yet)

This class implements the Minkowski distance as a cost function for optimisation problems, allowing for flexible distance-based optimisation across various problem domains.

Additional Attributes#

pfloat, optional

The order of the Minkowski distance.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

p#
class pybop.MonomialGammaHamiltonianMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Monomial Gamma Hamiltonian MCMC sampler from the PINTS library. This MCMC method uses Hamiltonian dynamics with a monomial gamma distribution for efficient exploration of the parameter space.

Parameters:
class pybop.MultiChainProcessor(mcmc_sampler)[source]#

Bases: ChainProcessor

Processor for simultaneous chains.

_extract_log_pdf(fy_value, chain_idx)[source]#

Extract log PDF value for multi-chain mode.

process_chain()[source]#

Process the chain

class pybop.NUTS(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class wraps the NUTS sampler from the PINTS library. NUTS is a Markov chain Monte Carlo (MCMC) method for sampling from a probability distribution, extending Hamiltonian Monte Carlo with an adaptive integration time for efficient exploration.

Parameters:
class pybop.NelderMead(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adpater for the Nelder-Mead downhill simplex method, a deterministic local optimiser that does not use gradient information or support boundary constraints.

In most update steps, it performs either one evaluation, or two sequential evaluations, so that it will not typically benefit from parallelisation.

Parameters:

See also

pints.NelderMead

PINTS implementation of Nelder-Mead algorithm.

class pybop.OCPAverage(ocp_discharge: pybop.Dataset, ocp_charge: pybop.Dataset, n_sto_points: int = 101, allow_stretching: bool = True, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = pybop.SciPyMinimize, verbose: bool = True)[source]#

Bases: pybop.BaseApplication

Estimate the equlilibrium open-circuit potential (OCP) by averaging the charge and discharge branches, using a method loosely based on method 4(a) proposed by Lu et al. (2021) available at: https://doi.org/10.1149/1945-7111/ac11a5

Parameters:
  • ocp_discharge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a discharge measurement.

  • ocp_charge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a charge measurement.

  • n_sto_points (int, optional) – The number of points in stoichiometry at which to calculate the voltage.

  • allow_stretching (bool, optional) – If True, the OCPs are allowed to stretch as well as shift with respect to the stoichiometry (default: True)

  • cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).

  • optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).

  • verbose (bool, optional) – If True, progress messages are printed (default: True).

__call__() pybop.Dataset[source]#
allow_stretching = True#
cost#
n_sto_points = 101#
ocp_charge#
ocp_discharge#
optimiser#
verbose = True#
class pybop.OCPCapacityToStoichiometry(ocv_dataset: pybop.Dataset, ocv_function: collections.abc.Callable, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = pybop.SciPyMinimize, verbose: bool = True)[source]#

Bases: pybop.BaseApplication

Estimate the stoichiometry from a measurement of open-circuit voltage versus charge capacity.

Parameters:
  • ocv_dataset (pybop.Dataset) – A dataset containing the “Charge capacity [A.h]” and “Voltage [V]” obtained from an OCV measurement.

  • ocv_function (Callable) – The open-circuit voltage as a function of stoichiometry.

  • cost (pybop.ErrorMeasure | pybop.LogLikelihood, optional) – The cost function to quantify the error (default: pybop.RootMeanSquaredError).

  • optimiser (pybop.BaseOptimiser, optional) – The optimisation algorithm to use (default: pybop.SciPyMinimize).

  • verbose (bool, optional) – If True, progress messages are printed (default: True).

__call__() pybop.Dataset[source]#
cost#
ocv_dataset#
ocv_function#
optimiser#
verbose = True#
class pybop.OCPMerge(ocp_discharge: pybop.Dataset, ocp_charge: pybop.Dataset, n_sto_points: int = 101)[source]#

Bases: pybop.BaseApplication

Generate a representative open-circuit potential (OCP) without hysteresis by merging the provided charge and discharge branches of the OCP.

Parameters:
  • ocp_discharge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a discharge measurement.

  • ocp_charge (pybop.Dataset) – A dataset containing the “Stoichiometry” and “Voltage [V]” obtained from a charge measurement.

  • n_sto_points (int, optional) – The number of points in stoichiometry at which to calculate the voltage.

__call__() pybop.Dataset[source]#
n_sto_points = 101#
ocp_charge#
ocp_discharge#
class pybop.OptimiserOptions[source]#

A base class for optimiser options.

multistart#

Number of times to multistart the optimiser.

Type:

int

verbose#

The verbosity level.

Type:

bool

verbose_print_rate#

The distance between iterations to print verbose output.

Type:

int

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

multistart: int = 1#
verbose: bool = False#
verbose_print_rate: int = 50#
class pybop.PSO(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for particle swarm optimisation (PSO), a metaheuristic optimisation method inspired by the social behavior of birds flocking or fish schooling, suitable for global optimisation problems.

The method considers “particles” moving around the search space. Global optima convergence is guaranteed in the infinite limit for the number of optimiser iterations.

Parameters:

See also

pints.PSO

The PINTS implementation this class is based on.

class pybop.Parameter(*, initial_value: float = None, current_value: float = None, bounds: BoundsPair | None = None, prior: pybop.parameters.priors.BasePrior | None = None, transformation: pybop.transformation.base_transformation.Transformation | None = None, margin: float = 0.0001)[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 optimisation or sampling.

Parameters:
  • initial_value (NumericValue, optional) – Initial parameter value

  • current_value (NumericValue, optional) – Current parameter value (defaults to initial_value)

  • bounds (tuple[float, float], optional) – Parameter bounds as (lower, upper)

  • prior (pybop.BasePrior, optional) – Prior distribution object

  • transformation (Transformation, optional) – Parameter transformation

  • margin (float, default=1e-4) – Safety margin for bounds sampling

__call__(*unused_args, **unused_kwargs) float[source]#

Return the current value. The unused arguments are to pass pybamm.ParameterValues checks.

__hash__() int[source]#

Hash based on name.

__repr__() str[source]#

String representation of the parameter.

_set_margin(margin: float) None[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.

_validate_values_within_bounds() None[source]#

Validate that initial values are within bounds.

get_initial_value_transformed() numpy.typing.NDArray | None[source]#

Get initial value in transformed space.

reset_to_initial() None[source]#

Reset current value to initial value.

sample_from_prior(n_samples: int = 1, *, random_state: int | None = None, transformed: bool = False) numpy.typing.NDArray[numpy.floating] | None[source]#

Sample from parameter’s prior distribution.

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

  • random_state (int, optional) – Random seed for reproducibility.

  • transformed (bool) – Whether to apply transformation to samples (default: False).

Returns:

Array of samples, or None if no prior exists

Return type:

NDArray[np.floating] or None

set_bounds(bounds: BoundsPair) None[source]#

Set new parameter bounds.

Parameters:

bounds (tuple[float, float]) – New bounds as (lower, upper)

update_initial_value(value: NumericValue) None[source]#

Update the initial parameter value.

Parameters:

value (NumericValue) – New initial value

update_value(value: NumericValue) None[source]#

Update the current parameter value.

Parameters:

value (NumericValue) – New parameter value.

_bounds: Bounds | None = None#
_current_value#
_initial_value#
_prior = None#
_transformation#
property bounds: BoundsPair | None#

Parameter bounds as (lower, upper) tuple.

property current_value: float#
property initial_value: float#
property prior: Any | None#
property transformation: pybop.transformation.base_transformation.Transformation#
class pybop.Parameters(parameters: dict | Parameters = None)[source]#

Container for managing multiple Parameter objects with additional functionality.

This class provides a comprehensive interface for parameter management including validation, transformation, serialisation, and bulk operations.

__contains__(name: str) bool[source]#
__getitem__(name: str) Parameter[source]#
__iter__() collections.abc.Iterator[Parameter][source]#
__len__() int[source]#
__repr__() str[source]#
_add(name: str, parameter: Parameter, update_transform: bool = True) None[source]#

Internal method to add a parameter to the collection.

Parameters:
  • parameter (Parameter) – Parameter to add

  • update_transform (bool, optional) – Whether to update the transformation after adding (default: True)

_bulk_update_bounds(bounds: collections.abc.Sequence[BoundsPair] | dict[str, BoundsPair]) None[source]#

Update bounds in bulk.

_bulk_update_initial_values(values: ArrayLike | Inputs) None[source]#

Update initial values in bulk.

_bulk_update_values(values: ArrayLike | Inputs) None[source]#

Update current values in bulk.

add(name: str, parameter: Parameter) None[source]#

Add a parameter to the collection.

construct_transformation() pybop.transformation.base_transformation.Transformation[source]#

Create a ComposedTransformation object from the individual parameter transformations.

copy() Parameters[source]#

Create a deep copy of the Parameters object.

get(name: str) Parameter[source]#

Get a parameter by name.

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

Get bounds, for either all or no parameters.

Parameters:

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

get_bounds_array(transformed: bool = False) numpy.ndarray[source]#

Retrieve parameter bounds in numpy format.

Returns:

bounds – An array of shape (n_parameters, 2) containing the bounds for each parameter.

Return type:

numpy.ndarray

get_bounds_for_plotly(transformed: bool = False) numpy.ndarray[source]#

Retrieve parameter bounds in the format expected by Plotly.

Returns:

bounds – An array of shape (n_parameters, 2) containing the bounds for each parameter.

Return type:

numpy.ndarray

get_initial_values(*, transformed: bool = False) numpy.typing.NDArray[numpy.floating][source]#

Get initial values as array.

Parameters:

transformed (bool, default=False) – Whether to apply transformations to bounds

Returns:

Array of initial values

Return type:

NDArray[np.floating]

get_sigma0(transformed: bool = False) list[source]#

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

Parameters:

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

get_values(*, transformed: bool = False) numpy.typing.NDArray[numpy.floating][source]#

Get current values as array.

Parameters:

transformed (bool, default=False) – Whether to apply transformations

Returns:

Array of current values

Return type:

NDArray[np.floating]

items() collections.abc.Iterator[tuple[str, Parameter]][source]#

Iterate over (name, parameter) pairs.

join(parameters=None)[source]#

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

Parameters:

parameters (pybop.Parameters)

keys() collections.abc.Iterator[str][source]#

Iterate over parameter names.

priors() list[source]#

Return the prior distribution of each parameter.

remove(name: str) Parameter[source]#

Remove parameter and return it.

remove_bounds() None[source]#
reset_to_initial(names: collections.abc.Sequence[str] | None = None) None[source]#

Reset parameters to initial values.

sample_from_priors(n_samples: int = 1, *, random_state: int | None = None, transformed: bool = False) numpy.typing.NDArray[numpy.floating] | None[source]#

Sample from all parameter priors.

Returns:

Array of shape (n_samples, n_parameters) or None if any prior is missing

Return type:

NDArray[np.floating] or None

to_dict(values: str | ArrayLike | None = None) Inputs[source]#

Convert to parameter dictionary.

Parameters:

values (str or array-like, optional) – Which values to use (‘current’, ‘initial’) or custom array. Default is “current”.

Returns:

Dictionary mapping parameter names to values

Return type:

Inputs

to_inputs(values: numpy.ndarray | list[numpy.ndarray]) list[Inputs][source]#

Return parameter values as a list of dictionaries, as required for multiprocessing.

update(*, values: ArrayLike | Inputs | None = None, initial_values: ArrayLike | Inputs | None = None, bounds: collections.abc.Sequence[BoundsPair] | dict[str, BoundsPair] | None = None, **individual_updates: dict[str, Any]) None[source]#

Update multiple parameters efficiently.

Parameters:
  • values (array-like or dict, optional) – New current values (by position or name)

  • initial_values (array-like or dict, optional) – New initial values (by position or name)

  • bounds (sequence or dict, optional) – New bounds (by position or name)

  • **individual_updates (dict) – Individual parameter updates with parameter names as keys

values() collections.abc.Iterator[Parameter][source]#

Iterate over parameters.

verify_inputs(inputs: Inputs) bool[source]#

Check if the inputs are valid parameters.

_parameters#
_transform = None#
property names: list[str]#
property transformation: pybop.transformation.base_transformation.Transformation#

Get the transformation for the parameters.

class pybop.PintsOptions[source]#

Bases: pybop.optimisers.base_optimiser.OptimiserOptions

A class to hold PINTS options for the optimisation process.

default_max_iterations#

Default maximum number of iterations (default: 1000).

Type:

int

max_iterations#

Maximum number of iterations for the optimisation (default: None).

Type:

int

min_iterations#

Minimum number of iterations required (default: 2).

Type:

int

sigma#

Standard deviation or step-size parameter for the optimiser (default: 5e-2).

Type:

float | np.ndarray | list

max_unchanged_iterations#

Maximum iterations without improvement before stopping (default: 15).

Type:

int

use_f_guessed#

Whether to use guessed function values (default: False).

Type:

bool

absolute_tolerance#

Absolute tolerance for convergence (default: 1e-5).

Type:

float

relative_tolerance#

Relative tolerance for convergence (default: 1e-2).

Type:

float

max_evaluations#

Maximum number of function evaluations (default: None).

Type:

int | None

threshold#

Threshold value for optimisation stopping criteria (default: None).

Type:

float | None

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

absolute_tolerance: float = 1e-05#
default_max_iterations = 1000#
max_evaluations: int | None = None#
max_iterations: int = 1000#
max_unchanged_iterations: int = 15#
min_iterations: int = 2#
relative_tolerance: float = 0.01#
sigma: float | numpy.ndarray | list | None = None#
threshold: float | None = None#
use_f_guessed: bool = False#
class pybop.PintsSamplerOptions[source]#

Bases: pybop.samplers.base_sampler.SamplerOptions

Pints sampler options.

n_chains#

The number of chains to concurrently sample from (default: 1).

Type:

int

cov#

Covariance matrix (default: 0.05).

Type:

float | np.ndarray

max_iterations#

Maximum number of iterations to run (default: 500).

Type:

int

verbose#

If True, additional information will be printed (default: False).

Type:

bool

warm_up_iterations#

Number of iterations to warm up the sampler (default: 250).

Type:

int

chains_in_memory#

Whether to store the chains in memory (default: True).

Type:

bool

log_to_screen#

If True (default), the sampler will print information during the sampling.

Type:

bool

log_filename#

The name of the file to save the sampler log to (default: None).

Type:

str

chain_files#

The name of the file to save the chains in (default: None).

Type:

list

evaluation_files#

The name of the file to save the evaluations in (default: None).

Type:

list

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

chain_files: list[str] | None = None#
chains_in_memory: bool = True#
evaluation_files: list[str] | None = None#
initial_phase_iterations: int = 250#
log_filename: str | None = None#
log_to_screen: bool = True#
max_iterations: int = 500#
verbose: bool = False#
warm_up_iterations: int = 0#
class pybop.PopulationEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#

Bases: BaseEvaluator

Evaluates a function (or callable object) for multiple positions.

Parameters:
  • function (callable) – The function to evaluate. This function should accept a list-like object of positions to be evaluated.

  • args (sequence, optional) – A sequence containing extra arguments to be passed to the function. If specified, the function will be called as function(x, *args).

_evaluate(positions)[source]#

See evaluate().

class pybop.PopulationMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Population MCMC sampler from the PINTS library. This MCMC method uses a population of chains at different temperatures to explore the parameter space more efficiently and avoid local minima.

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

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

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

Calculate statistics from callable fun.

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

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

effective_sample_size(mixed_chains=False)[source]#

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

Parameters:

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

Returns:

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

Return type:

list

Raises:

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

get_summary_statistics()[source]#

Calculate summary statistics for the posterior samples.

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

plot_chains(**kwargs)[source]#

Plot posterior distributions for each chain.

plot_posterior(**kwargs)[source]#

Plot the summed posterior distribution across chains.

plot_trace(**kwargs)[source]#

Plot trace plots for the posterior samples.

rhat()[source]#

Computes the Gelman-Rubin statistic which diagnoses MCMC convergence. For well-mixed and stationary chains R-hat will be close to one, otherwise it is higher.

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

Rounds array x to p significant digits.

summary_table()[source]#

Display summary statistics in a table.

all_samples#
chains#
go = None#
num_parameters#
sig_digits = 4#
class pybop.Problem(simulator: pybop.simulators.base_simulator.BaseSimulator = None, cost: pybop.costs.base_cost.BaseCost = None)[source]#

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

Parameters:
  • simulator (pybop.BaseSimulator) – The model, protocol and optional dataset combined into a simulator object.

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

  • cost (pybop.BaseCost, optional) – An cost e.g. an error measure, a log-likelihood or a design cost.

target_data#

An array containing the target data to fit.

Type:

array-like

n_outputs#

The number of outputs in the model.

Type:

int

minimising#

If False, tells the optimiser to switch the sign of the cost and gradient to maximise by default rather than minimise (default: True).

Type:

bool, optional

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

Compute cost and optional gradient for given input parameters.

Parameters:
  • inputs (Inputs | list[Inputs] | list[float] | np.adarray) – Input parameters for cost computation. Supports list-like evaluation of multiple input values, shaped [N,M] where N is the number of input positions to evaluate and M is the number of inputs for the underlying model (i.e. parameters).

  • calculate_grad (bool) – If True, the gradient will be computed as well as the cost (default: False).

Returns:

  • Single input, no gradient: float

  • Multiple inputs, no gradient: list[float]

  • Single input with gradient: tuple[float, np.ndarray]

  • Multiple inputs with gradient: list[tuple[float, np.ndarray]]

Return type:

Union[float, list, tuple[float, np.ndarray], list[tuple[float, np.ndarray]]]

batch_call(inputs_list: list[pybop.parameters.parameter.Inputs], calculate_grad: bool) list[float] | list[tuple[float, numpy.ndarray]][source]#

Evaluate the cost and (optionally) the gradient for a list of inputs.

get_finite_initial_cost()[source]#

Compute the absolute initial cost, resampling the initial parameters if needed.

join_parameters(parameters)[source]#

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

sensitivity_analysis(n_samples: int = 256, calc_second_order: bool = False) dict[source]#

Computes the parameter sensitivities on the combined cost function using SOBOL analysis. See pybop.analysis.sensitivity_analysis for more details.

Parameters:
  • n_samples (int, optional) – Number of samples for SOBOL sensitivity analysis, performs best as a power of 2, i.e. 128, 256, etc.

  • calc_second_order (bool, optional) – Whether to calculate second-order sensitivities.

simulate(inputs: pybop.parameters.parameter.Inputs) dict[str, numpy.ndarray] | tuple[dict[str, numpy.ndarray], dict[str, dict[str, numpy.ndarray]]][source]#

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

Parameters:

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

Returns:

The simulated model output y(t), or y(ω) for EIS, for the given inputs.

Return type:

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

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

Evaluate the model with the given parameters and return the target and their 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) for each parameter x and output variables y simulated with the given inputs.

Return type:

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

single_call(inputs: pybop.parameters.parameter.Inputs, calculate_grad: bool) float | tuple[float, numpy.ndarray][source]#

Evaluate the cost and (optionally) the gradient for a single set of inputs.

_cost#
_has_sensitivities#
_minimising = True#
_simulator#
property cost#
domain = 'Time [s]'#
property domain_data#
property eis#
property has_sensitivities#
property minimising#
property n_outputs#
property n_parameters#
property parameters#
property simulator#
property target#
property target_data#
class pybop.RandomSearch(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for random search, a simple algorithm which samples parameter values randomly and stores the current best proposal based on fitness (not recommended for optimisation).

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

Parameters:

See also

pybop.RandomSearchImpl

PyBOP implementation of Random Search algorithm.

class pybop.RaoBlackwellACMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Rao-Blackwell Adaptive Covariance MCMC sampler from the PINTS library. This MCMC method improves sampling efficiency by combining Rao-Blackwellisation with adaptive covariance strategies.

Parameters:
class pybop.RecommendedSolver(output_variables: list[str] | None = None)[source]#

Bases: pybamm.IDAKLUSolver

A shortcut for creating the PyBaMM solver recommended for optimisation.

class pybop.RelativisticMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Relativistic MCMC sampler from the PINTS library. This MCMC method uses concepts from relativistic mechanics to propose new states, allowing for efficient exploration of the parameter space.

Parameters:
class pybop.RootMeanSquaredError(dataset: pybop._dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

Root mean square error (RMSE) cost function.

Computes the root mean square error between model predictions and the target data, providing a measure of the differences between predicted values and observed values.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

class pybop.SNES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for the stochastic natural evolution strategy (SNES), an evolutionary algorithm that evolves a probability distribution on the parameter space, guiding the search for the optimum based on the natural gradient of expected fitness.

Parameters:

See also

pints.SNES

The PINTS implementation this class is based on.

class pybop.SamplerOptions[source]#

Base options for the sampler.

n_chains#

The number of chains to concurrently sample from.

Type:

int

cov#

Covariance matrix.

Type:

float | np.ndarray

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

cov: float | numpy.ndarray = 0.05#
n_chains: int = 1#
class pybop.ScalarEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#

Bases: BaseEvaluator

Evaluates a function (or callable object) for a single input.

Parameters:
  • function (callable) – The function to evaluate. This function should accept an input and optionally additional arguments, returning either a single value or a tuple.

  • args (sequence, optional) – A sequence containing extra arguments to be passed to the function. If specified, the function will be called as function(x, *args).

_evaluate(x)[source]#

See evaluate().

class pybop.SciPyDifferentialEvolution(problem: pybop.problems.problem.Problem, options: SciPyDifferentialEvolutionOptions | None = None)[source]#

Bases: BaseSciPyOptimiser

Adapter for SciPy’s differential_evolution function for global optimisation, useful for problems involving continuous parameters and potentially multiple local minima.

Parameters:

See also

scipy.optimize.differential_evolution

The SciPy method this class is based on.

Notes

Differential Evolution is a stochastic population based method that is useful for global optimisation problems. At each pass through the population the algorithm mutates each candidate solution by mixing with other candidate solutions to create a trial candidate. The fitness of all candidates is then evaluated and for each candidate if the trial candidate is an improvement, it takes its place in the population for the next iteration.

_run()[source]#

Executes the optimisation process using SciPy’s differential_evolution function.

Returns:

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

Return type:

scipy.optimize.OptimizeResult

_set_up_optimiser()[source]#

Parse optimiser options.

static default_options() SciPyDifferentialEvolutionOptions[source]#

Returns the default options for the optimiser.

property name#

Provides the name of the optimisation strategy.

class pybop.SciPyDifferentialEvolutionOptions[source]#

Bases: pybop.OptimiserOptions

Options for the SciPy differential evolution method.

Parameters:
  • strategy (str, optional) – The differential evolution strategy to use. Should be one of: - ‘best1bin’ - ‘best1exp’ - ‘rand1exp’ - ‘randtobest1exp’ - ‘currenttobest1exp’ - ‘best2exp’ - ‘rand2exp’ - ‘randtobest1bin’ - ‘currenttobest1bin’ - ‘best2bin’ - ‘rand2bin’ - ‘rand1bin’ Default is ‘best1bin’.

  • maxiter (int, optional) – Maximum number of generations (default: 1000).

  • popsize (int, optional) – Multiplier for setting the total population size. The population has popsize * len(x) individuals (default: 15).

  • tol (float, optional) – Relative tolerance for convergence (default: 0.01).

  • mutation (float or tuple(float, float), optional) – The mutation constant. If specified as a float, should be in [0, 2]. If specified as a tuple (min, max), dithering is used (default: (0.5, 1.0)).

  • recombination (float, optional) – The recombination constant, should be in [0, 1] (default: 0.7).

  • seed (int, optional) – Random seed for reproducibility.

  • disp (bool, optional) – Display status messages (default: False).

  • callback (Callable, optional) – Called after each iteration with the current result as argument.

  • polish (bool, optional) – If True, performs a local optimisation on the solution (default: True).

  • init (str or array-like, optional) – Specify initial population. Can be ‘latinhypercube’, ‘random’, or an array of shape (M, len(x)).

  • atol (float, optional) – Absolute tolerance for convergence (default: 0).

  • updating ({'immediate', 'deferred'}, optional) – If ‘immediate’, best solution vector is continuously updated within a single generation (default: ‘immediate’).

  • workers (int or map-like Callable, optional) – If workers is an int the population is subdivided into workers sections and evaluated in parallel (default: 1).

  • constraints ({NonlinearConstraint, LinearConstraint, Bounds}, optional) – Constraints on the solver.

to_dict() dict[source]#

Convert the options to a dictionary format.

atol: float | None = None#
callback: collections.abc.Callable | None = None#
disp: bool | None = None#
init: str | numpy.ndarray | None = None#
maxiter: int = 1000#
mutation: float | tuple | None = None#
polish: bool | None = None#
popsize: int | None = None#
recombination: float | None = None#
seed: int | None = None#
strategy: str = 'best1bin'#
tol: float = 0.01#
class pybop.SciPyMinimize(problem: pybop.problems.problem.Problem, options: SciPyMinimizeOptions | None = None)[source]#

Bases: BaseSciPyOptimiser

Adapter for various scalar minimisation algorithms implemented in SciPy, allowing fine-tuning of the optimisation process through method selection and option configuration.

Parameters:
  • problem (pybop.Problem) – The problem to optimise.

  • options (ScipyMinizeOptions, optional) – Options for the SciPy minimize method (default: None).

See also

scipy.optimize.minimize

The SciPy method this class is based on.

Notes

Different optimisation methods may support different options. Consult SciPy’s documentation for method-specific options and constraints.

_run()[source]#

Executes the optimisation process using SciPy’s minimize function.

Returns:

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

Return type:

scipy.optimize.OptimizeResult

_set_up_optimiser()[source]#

Parse optimiser options.

cost_wrapper(x)[source]#

Scale the cost function, preserving the sign, and eliminate nan values.

static default_options() SciPyMinimizeOptions[source]#

Returns the default options for the optimiser.

property name#

Provides the name of the optimisation strategy.

class pybop.SciPyMinimizeOptions[source]#

Bases: pybop.OptimiserOptions

Options for the SciPy minimize method.

method#

The optimisation method to use (default: None).

Type:

str, optional

jac#

Method for computing the gradient vector (default: None).

Type:

bool, optional

tol#

Tolerance for termination (default: None).

Type:

float, optional

maxiter#

Maximum number of iterations (default: 1000).

Type:

int, optional

disp#

Set to True to print convergence messages (default: False).

Type:

bool, optional

constraints#

Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.

Type:

scipy constraint or list of scipy constraints, optional

solver_options#

A dictionary of additional solver options, not including maxiter or disp.

Type:

dict, optional

to_dict() dict[source]#

Convert the options to a dictionary format.

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

constraints: list | None = None#
disp: bool = False#
jac: bool | None = None#
maxiter: int = 1000#
method: str | None = None#
solver_options: dict | None = None#
tol: float | None = None#
class pybop.SequentialEvaluator(problem: pybop.problems.problem.Problem, minimise: bool, with_sensitivities: bool, logger: pybop._logging.Logger)[source]#

Bases: BaseEvaluator

Evaluates a function (or callable object) for a list of input values, and returns a list containing the calculated function evaluations.

Parameters:
  • function (callable) – The function to evaluate.

  • args (sequence) – An optional tuple containing extra arguments to f. If args is specified, f will be called as f(x, *args).

_evaluate(positions)[source]#

See evaluate().

class pybop.SimulatedAnnealing(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for simulated annealing, a probabilistic optimisation method inspired by the annealing process in metallurgy which is suitable for global optimisation problems.

It works by iteratively proposing new solutions and accepting them based on both their fitness and a temperature parameter that decreases over time. This allows the algorithm to initially explore broadly and gradually focus on local optimisation as the temperature decreases.

Parameters:

See also

pybop.SimulatedAnnealingImpl

PyBOP implementation of Simulated Annealing algorithm.

class pybop.SingleChainProcessor(mcmc_sampler)[source]#

Bases: ChainProcessor

Processor for individual chains.

_extract_log_pdf(fy_value, chain_idx)[source]#

Extract log PDF value for single chain mode.

process_chain()[source]#

Process the chain

class pybop.SliceDoublingMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Slice Doubling MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a doubling procedure to propose new states, allowing for efficient exploration of the parameter space.

Parameters:
class pybop.SliceRankShrinkingMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Slice Rank Shrinking MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a rank shrinking procedure to propose new states, allowing for efficient exploration of the parameter space.

Parameters:
class pybop.SliceStepoutMCMC(log_pdf: pybop.problems.problem.Problem, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.BasePintsSampler

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

This class extends the Slice Stepout MCMC sampler from the PINTS library. This MCMC method uses slice sampling with a stepout procedure to propose new states, allowing for efficient exploration of the parameter space.

Parameters:
class pybop.SumOfPower(dataset: pybop._dataset.Dataset, p: float = 2.0, target: str | list[str] = None, weighting: str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

The Sum of Power [1] is a generalised cost function based on the p-th power of absolute differences between two vectors. It is defined as:

\[C_p(x, y) = \sum_i |x_i - y_i|^p\]

where p ≥ 0 is the power order.

This class implements the Sum of Power as a cost function for optimisation problems, allowing for flexible power-based optimisation across various problem domains.

Special cases:

  • p = 1: Sum of Absolute Differences

  • p = 2: Sum of Squared Differences

  • p → ∞: Maximum Absolute Difference

Note that this is not normalised, unlike distance metrics. To get a distance metric, you would need to take the p-th root of the result.

[1]: https://mathworld.wolfram.com/PowerSum.html

Additional Attributes#

pfloat, optional

The power order for Sum of Power.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

p#
class pybop.SumSquaredError(dataset: pybop._dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: ErrorMeasure

Sum of squared error (SSE) cost function.

Computes the sum of the squares of the differences between model predictions and target data, which serves as a measure of the total error between the predicted and observed values.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • r (np.ndarray) – The residual difference between the model prediction and the target. The dimensions of r are (len(target), len(domain_data)).

  • dy (np.ndarray, optional) – The corresponding gradient with respect to the parameters for each output variable. The dimensions of dy are (len(parameters), len(target), len(domain_data)).

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

class pybop.SymbolReplacer(symbol_replacement_map: dict[pybamm.Symbol, pybamm.Symbol], processed_symbols: dict[pybamm.Symbol, pybamm.Symbol] | None = None, process_initial_conditions: bool = True)[source]#

Helper class to replace all instances of one or more symbols in an expression tree with another symbol, as defined by the dictionary symbol_replacement_map Originally developed by pybamm: pybamm-team/pybamm

Parameters:
  • symbol_replacement_map (dict {pybamm.Symbol -> pybamm.Symbol}) – Map of which symbols should be replaced by which.

  • processed_symbols (dict {pybamm.Symbol -> pybamm.Symbol}, optional) – cached replaced symbols

  • process_initial_conditions (bool, optional) – Whether to process initial conditions, default is True

_process_events(events: list) list[source]#
_process_symbol(symbol: pybamm.Symbol) pybamm.Symbol[source]#
process_boundary_conditions(model)[source]#

Process boundary conditions for a PybaMM model class Boundary conditions are dictionaries {“left”: left bc, “right”: right bc} in general, but may be imposed on the tabs (or not on the tab) for a small number of variables, e.g. {“negative tab”: neg. tab bc, “positive tab”: pos. tab bc “no tab”: no tab bc}.

process_model(unprocessed_model, inplace=True)[source]#

Replace all instances of a symbol in a PyBaMM model class.

Parameters:
  • unprocessed_model (pybamm.BaseModel) – Model class to assign parameter values to

  • inplace (bool, optional) – If True, replace the parameters in the model in place. Otherwise, return a new model with parameter values set (default: True).

process_symbol(symbol)[source]#

This function recurses down the tree, replacing any symbols in self._symbol_replacement_map.keys() with their corresponding value

Parameters:

symbol (pybamm.Symbol) – The symbol to replace

Returns:

Symbol with all replacements performed

Return type:

pybamm.Symbol

_process_initial_conditions = True#
_processed_symbols#
_symbol_replacement_map#
class pybop.Uniform(lower, upper, random_state=None)[source]#

Bases: BasePrior

Represents a uniform distribution over a specified interval.

This class provides methods to calculate the pdf, the log pdf, and to generate random variates from the distribution.

Parameters:
  • lower (float) – The lower bound of the distribution.

  • upper (float) – The upper bound of the distribution.

_logpdfS1(x)[source]#

Evaluates the first derivative of the log uniform distribution at x.

Parameters:

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

Returns:

The value(s) of the first derivative at x.

Return type:

float

bounds() tuple[float, float][source]#
_n_parameters = 1#
loc#
lower#
property mean#

Returns the mean of the distribution.

name = 'Uniform'#
prior#
scale#
property sigma#

Returns the standard deviation of the distribution.

upper#
class pybop.WeightedCost(*costs, weights: list[float] | None = None)[source]#

Bases: pybop.costs.base_cost.BaseCost

A subclass for constructing a linear combination of cost functions as a single weighted cost function.

Parameters:
  • costs (pybop.BaseCost) – The individual PyBOP cost objects.

  • weights (list[float]) – A list of values with which to weight the cost values.

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

Computes the cost function for the given predictions.

Parameters:
  • y (dict[str, np.ndarray[np.float64]]) – The dictionary of predictions with keys designating the output variables for fitting.

  • dy (dict[str, dict[str, np.ndarray]], optional) – The corresponding sensitivities to each parameter for each output variable.

Returns:

If dy is not None, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

np.float64 or tuple[np.float64, np.ndarray[np.float64]]

costs#
domain#
target = []#
class pybop.XNES(problem: pybop.Problem, options: pybop.PintsOptions | None = None)[source]#

Bases: pybop.optimisers.base_pints_optimiser.BasePintsOptimiser

Adapter for the exponential natural evolution strategy (XNES), an evolutionary algorithm that samples from a multivariate normal distribution, which is updated iteratively to fit the distribution of successful solutions.

Parameters:

See also

pints.XNES

PINTS implementation of XNES algorithm.

pybop.add_spaces(string)[source]#

Return the class name as a string with spaces before each new capitalised word.

pybop.is_numeric(x)[source]#

Check if a variable is numeric.

pybop.FLOAT_FORMAT = '{: .17e}'[source]#
pybop.__version__[source]#
pybop.error_message = Multiline-String[source]#
Show Value
"""Multiprocessing context could not be set. Continuing import without setting context.
Error: Instance of builtins.Exception"""
pybop.script_path[source]#