pybop#

Submodules#

Attributes#

Classes#

AdamW

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

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.

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.

DesignCost

Base design cost.

DifferentialEvolutionMCMC

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

Distribution

A base class for defining parameter distributions.

DramACMC

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

EPBOLFIOptions

A class to hold EP-BOLFI options for the optimisation process.

EP_BOLFI

Wraps the Bayesian Optimization algorithm EP-BOLFI.

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:

ExponentialFeatureDistance

Exponential fit cost function.

FailedSolution

Container for a failed PyBaMM solution that returns [np.inf] for all processed variables.

FailedVariable

Container for a failed PyBaMM variable that returns np.inf.

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 evaluates the log-likelihood under

GaussianLogLikelihoodKnownSigma

This class represents a Gaussian log-likelihood with a known sigma, which evaluates 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

JointDistribution

Represents a joint distribution composed of multiple distributions.

LogLikelihood

Base class for likelihoods.

LogPDF

A problem that evaluates the log of an (unnormalised) probability density function.

LogPosterior

The log of the proportional posterior, defined as the sum of the log-likelihood and

LogPrior

The log-prior as a cost, to be used with the LogPosterior class.

Logger

Records the parameter values and corresponding cost values.

MALAMCMC

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

MarginalDistribution

Represents a univariate marginal distribution of a pybop.BaseMultivariateDistribution.

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.

MultivariateGaussian

Represents a multivariate Gaussian (normal) distribution with a

MultivariateLogNormal

Represents a multivariate log-normal distribution with a

MultivariateNonparametric

Represents a "freeform" distribution, i.e., one that is defined from

MultivariateUniform

Represents a multivariate uniform distribution.

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

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.

RelativisticMCMC

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

Result

Stores the result produced by an optimiser or sampler.

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.

Solution

A class to store simulation results, inspired by pybamm.Solution.

SquareRootFeatureDistance

Square-root fit cost function.

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.

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.

load_data_dict(→ dict)

Load data as dictionary from a given file. Restores data saved with

save_data_dict(→ str | None)

Save data from given data dictionary

Package Contents#

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

Bases: pybop.optimisers.base_pints_optimiser.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.BaseApplication[source]#

A base class for PyBOP’s application methods.

check_monotonicity(voltage: numpy.ndarray) None[source]#

Check if voltage data is monotonic and warn if not.

Parameters:

voltage (np.ndarray) – Voltage array to check for monotonicity.

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

Contains the logic for the optimisation algorithm.

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

Raises:

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

abstractmethod _set_up_optimiser()[source]#

Parse optimiser options and prepare the optimiser.

This method should be implemented by child classes.

Raises:

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

static default_options() OptimiserOptions[source]#

Returns the default options for the optimiser.

abstractmethod name() str[source]#

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

Returns:

The name of the optimiser

Return type:

str

run() OptimisationResult[source]#

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

Returns:

result – The pybop optimisation result class.

Return type:

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.optimisers.base_optimiser.OptimisationResult[source]#

Internal method to run the optimisation using a PINTS optimiser.

Returns:

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

Return type:

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 evaluator: pybop._evaluation.PopulationEvaluator | pybop._evaluation.SequentialEvaluator#
property iteration#
property max_iterations#

Returns the maximum number of iterations for the optimisation.

property name#

Returns the name of the PINTS optimisation strategy.

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

Bases: pybop.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.LogPDF) – The negative unnormalised posterior distribution.

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

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

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

The results including a numpy array containing the samples from the posterior distribution if chains are stored in memory, otherwise None.

Return type:

SamplingResult

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

  • Details:

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

    • Initialises iterations, evaluations, and other required

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

_chain_files = None#
_chains_in_memory = True#
_evaluation_files = None#
_initial_phase#
_initial_phase_iterations = 250#
_log_filename = None#
_log_to_screen = True#
_loop_iters = 0#
_max_iterations = 500#
_needs_sensitivities#
_sampler#
_single_chain#
_verbose = False#
_warm_up = 0#
property active#
property chains_in_memory#
iter_time = 0.0#
property iteration#
property max_iterations#
property n_samples#
property needs_sensitivities#
property sampled_logpdf#
property sampled_prior#
property samplers#
property single_chain#
class pybop.BaseSampler(log_pdf: pybop.problems.log_pdf.LogPDF, options: SamplerOptions | None = None)[source]#

Base class for Monte Carlo samplers.

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

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

_validate_covariance_matrix() None[source]#

Check or create the initial covariance matrix.

static default_options() SamplerOptions[source]#

Get the default options for the sampler.

abstractmethod run() SamplingResult[source]#

Sample from the posterior distribution.

Returns:

Samples from the posterior distribution.

Return type:

np.ndarray

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

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

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

Set the maximum number of iterations for the sampler.

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

Set the number of warm up iterations for the sampler.

_cov0#
_log_pdf#
_logger = None#
_mean0#
_n_parameters#
_options#
property cov0: numpy.ndarray#
property log_pdf: pybop.problems.log_pdf.LogPDF#
property logger: pybop._logging.Logger | None#
property mean0: numpy.ndarray#
property options: SamplerOptions#
class pybop.BaseSciPyOptimiser(problem: pybop.problems.problem.Problem, options: pybop.optimisers.base_optimiser.OptimiserOptions | None)[source]#

Bases: pybop.optimisers.base_optimiser.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 | dict | None = None)[source]#

Base simulator.

copy()[source]#

Return a copy of the simulator.

get_parameters_from_dict(parameter_values: dict)[source]#

Extract any pybop.Parameter objects and replace with the “[input]” string.

set_output_variables(target: list[str])[source]#
solve(inputs: Inputs | list[Inputs] | None = None, calculate_sensitivities: bool = False) pybop.simulators.solution.Solution | list[pybop.simulators.solution.Solution][source]#

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

solve_batch(inputs: list[Inputs], calculate_sensitivities: bool = False) list[pybop.simulators.solution.Solution | pybop.simulators.failed_solution.FailedSolution][source]#

Run the simulation for each set of inputs and return dict-like simulation results and (optionally) the sensitivities with respect to each input parameter.

Parameters:
  • inputs (list[Inputs]) – A list of input parameters.

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

A list of len(inputs) containing the simulation result(s) and (optionally) the sensitivities with respect to each input parameter.

Return type:

list[Solution]

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

Bases: pybop.optimisers.base_pints_optimiser.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.log_pdf.LogPDF, 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.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.

evaluate(solution: pybop.simulators.base_simulator.Solution | pybop.simulators.failed_solution.FailedSolution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float[source]#

Returns the value of the cost variable.

Parameters:
  • solution (pybop.Solution | pybamm.Solution) – The simulation result.

  • inputs (Inputs, optional) – Input parameters (default: None).

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

The value of the output variable.

Return type:

float

minimising = False#
class pybop.DifferentialEvolutionMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.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.Distribution(distribution: scipy.stats.distributions.rv_frozen | None = None)[source]#

A base class for defining parameter distributions.

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

distribution#

The underlying continuous random variable distribution.

Type:

scipy.stats.distributions.rv_frozen

__repr__()[source]#

Returns a string representation of the object.

_dlogpdf_dx(x)[source]#

Evaluates the first derivative of the log distribution at x.

Overwrite this function in a subclass to improve upon this generic finite difference approximation.

Parameters:

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

Returns:

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

Return type:

float

cdf(x)[source]#

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

Parameters:

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

Returns:

The cumulative distribution function value at x.

Return type:

float

icdf(q)[source]#

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

Parameters:

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

Returns:

The inverse cumulative distribution function value at q.

Return type:

float

logpdf(x)[source]#

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

Parameters:

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

Returns:

The logarithm of the probability density function value at x.

Return type:

float

logpdfS1(x)[source]#

Evaluates the first derivative of the distribution at x.

Parameters:

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

Returns:

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

Return type:

float

mean()[source]#

Get the mean of the distribution.

Returns:

The mean of the distribution.

Return type:

float

pdf(x)[source]#

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

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

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

Generates random variates from the distribution.

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

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

Returns:

An array of random variates from the distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

std()[source]#

Get the standard deviation of the distribution.

Returns:

The standard deviation of the distribution.

Return type:

float

support()[source]#
verify(x)[source]#

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

distribution = None#
class pybop.DramACMC(log_pdf: pybop.problems.log_pdf.LogPDF, 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.EPBOLFIOptions[source]#

Bases: pybop.OptimiserOptions

A class to hold EP-BOLFI options for the optimisation process.

For detailed descriptions of the options, consult the EP-BOLFI documentation at YannickNoelStephanKuhn/EP-BOLFI; you’ll find its PDF attached to the newest release. Note that the variable names have been rewritten for clarity here, so you’ll have to look up their “original” names in the ep_bolfi.EP_BOLFI constructor call within the _set_up_optimiser routine of the pybop.EP_BOLFI class.

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

bolfi_initial_sobol_samples: int | None = None#
bolfi_optimally_acquired_samples: int | None = None#
bolfi_posterior_effective_sample_size: int | None = None#
boundaries_in_standard_deviations: int = 0#
covariance_scaled_mean: numpy.ndarray | None = None#
covariance_scaled_means_per_feature: numpy.ndarray | None = None#
ep_iterations: int = 1#
ep_randomise_feature_order: bool = False#
ep_stepwise_dampener: float | None = None#
ep_total_dampening: float | None = None#
max_posterior_sampling_retries: int = 10#
model_parameter_boundaries: dict#
parallel: bool = False#
posterior_actual_sample_size_increase: float = 1.2#
posterior_ess_ratio_threshold_evaluation_at_centre: int = -1#
posterior_ess_ratio_threshold_resampling: int = 5#
posterior_ess_ratio_threshold_skip_feature: int = -1#
posterior_gelman_rubin_threshold: float | None = None#
posterior_model_resample_size_increase: float = 1.1#
precision_matrices_per_feature: numpy.ndarray | None = None#
precision_matrix: numpy.ndarray | None = None#
seed: int = 0#
class pybop.EP_BOLFI(problem: pybop.Problem, options: EPBOLFIOptions | None = None)[source]#

Bases: pybop.optimisers.base_optimiser.BaseOptimiser

Wraps the Bayesian Optimization algorithm EP-BOLFI.

For implementation details and background information, consult the relevant publication at https://doi.org/10.1002/batt.202200374 and visit YannickNoelStephanKuhn/EP-BOLFI.

Note that all properties may and should be given here as PyBOP objects, but will be converted to an ep_bolfi.EP_BOLFI instance upon instantiation of this class. To change attributes, re-init.

Only compatible with MultivariateParameters with a MultivariateGaussian distribution.

_run() BayesianOptimisationResult[source]#

Contains the logic for the optimisation algorithm.

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

Raises:

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

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

name()[source]#

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

Returns:

The name of the optimiser

Return type:

str

class pybop.EmceeHammerMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, 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.processing.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_data#

The number of domain points.

Type:

int

target_data#

The target values of the output variables.

Type:

np.ndarray

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

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

evaluate(solution: pybop.simulators.solution.Solution | pybamm.Solution | pybop.simulators.failed_solution.FailedSolution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • solution (pybop.Solution | pybamm.Solution) – The simulation result.

  • inputs (Inputs, optional) – Input parameters (default: None).

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

If the solution has sensitivities, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

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

set_weighting(weighting: float | str | numpy.ndarray)[source]#
verify_prediction(solution: pybop.simulators.solution.Solution)[source]#

Verify that the prediction matches the target data.

Parameters:

solution (pybop.Solution | pybamm.Solution) – The simulation result.

Returns:

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

Return type:

bool

class pybop.Exponential(scale: float, loc: float = 0)[source]#

Bases: Distribution

Represents an exponential distribution with a specified scale parameter.

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

Parameters:

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

__repr__()[source]#

Returns a string representation of the object.

_dlogpdf_dx(x)[source]#

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

Parameters:

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

Returns:

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

Return type:

float

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

Bases: pybamm.models.base_model.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.ExponentialFeatureDistance(domain_data: numpy.ndarray, target_data: numpy.ndarray, feature: str = 'inverse_timescale', time_start: float = None, time_end: float = None)[source]#

Bases: FeatureDistance

Exponential fit cost function.

Fits an exponential and compares either its asymptote, its magnitude, or its timescale between model predictions and target data.

_feature_selection(fit)[source]#
_fit_guess(t, y)[source]#
_inverse_fit_function(y, b, c, d)[source]#

Logarithm function to transform data for a linear fit.

_supported_features = ['asymptote', 'magnitude', 'timescale', 'inverse_timescale']#
class pybop.FailedSolution(variable_names: list[str], parameter_names: list[str])[source]#

Container for a failed PyBaMM solution that returns [np.inf] for all processed variables.

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

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

  • parameter_names – List of parameter names for sensitivity analysis

Example

>>> solution = FailedSolution(["Voltage [V]"], ["Negative particle radius [m]"])
>>> voltage = solution["Voltage [V]"]
>>> print(voltage.data)  # np.ndarray([inf])
__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: dict[str, FailedVariable]#
cycles: int | None = None#
integration_time: float = 0.0#
property parameter_names: list[str]#

Get list of parameter names (read-only).

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

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

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

Get list of variable names (read-only).

class pybop.FailedVariable[source]#

Container for a failed PyBaMM variable that returns np.inf.

Parameters:
  • name – Variable name

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

  • sensitivities – Sensitivity data mapping parameter names to arrays

__post_init__() None[source]#

Validate inputs after initialisation.

data: numpy.ndarray#
name: str#
sensitivities: dict[str, numpy.ndarray]#
class pybop.GITTFit(gitt_dataset: pybop.Dataset, pulse_index: list[numpy.ndarray], parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#

Bases: pybop.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 [A]” and “Voltage [V]” for a GITT measurement.

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

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

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

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

  • optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.

__call__() pybop.Dataset[source]#
cost#
gitt_dataset#
inverse_ocp#
optimiser#
optimiser_options#
pulse_fit#
pulse_index#
class pybop.GITTPulseFit(parameter_values: pybamm.ParameterValues, cost: pybop.ErrorMeasure | pybop.LogLikelihood | None = None, optimiser: pybop.BaseOptimiser | None = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#

Bases: pybop.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 one electrode.

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

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

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

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

  • optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.

__call__(gitt_pulse: pybop.Dataset, initial_parameter_values: dict[str, float] | None = None) pybop.Result[source]#
cost#
model#
optimiser#
optimiser_options#
parameter_values#
parameters#
problem = None#
class pybop.Gaussian(mean, sigma, truncated_at: list[float] = None)[source]#

Bases: Distribution

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.

_dlogpdf_dx(x)[source]#

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

Parameters:

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

Returns:

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

Return type:

float

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

Bases: LogLikelihood

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

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

_logpi#

Precomputed offset value for the log-likelihood function.

Type:

float

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Compute the Gaussian log-likelihood for the given parameters.

_add_single_sigma(index, value)[source]#
_pad_sigma(sigma)[source]#
set_sigma(sigma: float | list[float] | list[pybop.parameters.parameter.Parameter])[source]#

Set the noise variance (sigma) after checking its validity.

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

Bases: LogLikelihood

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

Parameters:

sigma (scalar or array) – Initial standard deviation around x0. Either a scalar value (one standard deviation for all coordinates) or an array with one entry per dimension.

__call__(r: numpy.ndarray, dy: numpy.ndarray | None = None, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

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

set_sigma(sigma: numpy.ndarray | float)[source]#

Set sigma 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.log_pdf.LogPDF, 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.log_pdf.LogPDF, 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.log_pdf.LogPDF, 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: numpy.ndarray, y: numpy.ndarray, name: str | None = None, bounds_error: bool = False, fill_value: str | float = 'extrapolate', axis: int = 0)[source]#

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

Parameters:
  • x (array_like) – Input coordinates.

  • y (array_like) – Output values corresponding to x.

  • name (str, optional) – Name for the interpolant when used in PyBaMM.

  • bounds_error (bool, optional) – If True, raise error when interpolating outside bounds.

  • fill_value (str or float, optional) – Value to use for out-of-bounds interpolation.

  • axis (int, optional) – Axis along which to interpolate.

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

Evaluate the interpolant at given points.

Parameters:

x (float or array_like) – Points at which to evaluate the interpolant.

Returns:

Interpolated values or PyBaMM interpolant object.

Return type:

float, array_like, or pybamm.Interpolant

_create_interpolant(bounds_error: bool, fill_value: str | float, axis: int)[source]#

Create the scipy interpolation function.

_interp_func#
name = None#
x#
y#
class pybop.InverseOCV(ocv_function: collections.abc.Callable, optimiser: BaseOptimiser | None = None, optimiser_options: OptimiserOptions | None = None)[source]#

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

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

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

  • optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.

__call__(ocv_value: float) float[source]#

Estimate and return the stoichiometry.

Parameters:

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

Returns:

The stoichiometry corresponding to the open-circuit voltage value.

Return type:

float

cost#
ocv_root#
optimiser#
optimiser_options#
class pybop.JointDistribution(*distributions: Distribution | scipy.stats.distributions.rv_frozen)[source]#

Bases: Distribution

Represents a joint distribution composed of multiple distributions.

Parameters:

distributions (Distribution) – One or more distributions to combine into a joint distribution.

__repr__() str[source]#

Returns a string representation of the object.

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

Evaluates the log of the joint distribution at a given point.

Parameters:

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

Returns:

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

Return type:

float

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

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

Parameters:

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

Returns:

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

Return type:

Tuple[float, np.ndarray]

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

Sample each distribution individually and then compile.

_distributions_list: list[Distribution]#
_n_parameters = 0#
class pybop.LogLikelihood(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None)[source]#

Bases: pybop.costs.error_measures.ErrorMeasure

Base class for likelihoods.

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

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

Set the noise variance (sigma) after checking its validity.

minimising = False#
parameters#
sigma = None#
class pybop.LogPDF(simulator: pybop.simulators.base_simulator.BaseSimulator, cost: pybop.costs.log_likelihoods.LogLikelihood)[source]#

Bases: pybop.problems.problem.Problem

A problem that evaluates the log of an (unnormalised) probability density function.

class pybop.LogPosterior(simulator: pybop.simulators.base_simulator.BaseSimulator, cost: pybop.costs.log_likelihoods.LogLikelihood)[source]#

Bases: LogPDF

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

_cost#
log_likelihood#
log_prior#
class pybop.LogPrior(parameters)[source]#

Bases: BaseCost

The log-prior as a cost, to be used with the LogPosterior class.

evaluate(solution: pybop.simulators.solution.Solution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the log-prior for the given inputs, and optionally the sensitivities.

minimising = False#
parameters#
class pybop.Logger(minimising: bool, verbose: bool = False, verbose_print_rate: int = 50)[source]#

Records the parameter values and corresponding cost values.

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

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

  • iteration (int) – The current iteration number.

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

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

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

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

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

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

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

_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.log_pdf.LogPDF, 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.MarginalDistribution(parent_distribution: BaseMultivariateDistribution, position: int)[source]#

Bases: pybop.parameters.distributions.Distribution

Represents a univariate marginal distribution of a pybop.BaseMultivariateDistribution. Relies on the “marginal” method of the multivariate distribution.

Sub-class of pybop.Distribution with the additional properties “parent_distribution” and “position”

Parameters:
  • parent_distribution (pybop.BaseMultivariateDistribution) – A multivariate distribution

  • position (int) – position of the parameter for which to create the marginal distribution

mean()[source]#

Get the mean of the distribution.

Returns:

The mean of the distribution.

Return type:

float

std()[source]#

Get the standard deviation of the distribution.

Returns:

The standard deviation of the distribution.

Return type:

float

_position#
parent_distribution#
property position#
class pybop.MeanAbsoluteError(dataset: pybop.processing.dataset.Dataset, target: str | list[str] = None, weighting: float | str | numpy.ndarray = None)[source]#

Bases: 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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: 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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: pybop.problems.problem.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.

evaluate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool) numpy.ndarray | tuple[numpy.ndarray, numpy.ndarray][source]#

Evaluate each problem for each set of inputs and return the cost values and (optionally) the sensitivities with respect to each input parameter.

Parameters:
  • inputs (list[Inputs]) – A list of input parameters.

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

Cost values of len(inputs) and (optionally) the gradient of the cost with respect to each input parameter with shape (len(inputs), len(parameters)).

Return type:

Evaluation

get_problem_inputs(inputs: pybop.parameters.parameter.Inputs, i: int)[source]#
set_target(value: list[str] | str | None = None)[source]#
_has_sensitivities = True#
_parameters#
property has_sensitivities#
problems#
class pybop.MetropolisRandomWalkMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.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.processing.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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: pybop.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.MultivariateGaussian(mean=None, covariance=None, bounds=None, random_state=None)[source]#

Bases: BaseMultivariateDistribution

Represents a multivariate Gaussian (normal) distribution with a given mean and covariance.

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

Parameters:
  • mean (numpy.ndarray) – The mean (µ) of the multivariate Gaussian distribution.

  • covariance (numpy.ndarray) – The covariance matrix (Σ) of the multivariate Gaussian distribution. Note that what is called σ in 1D would be the square root of Σ here.

  • bounds (numpy.ndarray) – Lower and upper bounds (2nd dim) of the parameters (1st dim).

marginal(position)[source]#

Return univariate marginal distribution of parameter with index ‘position’

transformed_properties(transformation)[source]#

Return distribution properties in search space

_n_parameters#
property compatible_transformations#
property mean#

Get the mean of the distribution.

Returns:

The mean of the distribution.

Return type:

float

name = 'MultivariateGaussian'#
properties#
property sigma#
sigma2 = None#
class pybop.MultivariateLogNormal(mean_log_x=None, covariance_log_x=None)[source]#

Bases: BaseMultivariateDistribution

Represents a multivariate log-normal distribution with a given mean and covariance of the normally distributed log(x).

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

Parameters:
  • mean_log_x (numpy.ndarray) – The mean (µ) of the multivariate Gaussian distribution of log(x).

  • covariance_log_x (numpy.ndarray) – The covariance matrix (Σ) of the multivariate Gaussian distribution of log(x). Note that what is called σ in 1D would be the square root of Σ here.

_get_covariance_and_mean()[source]#

Method to compute the covariance and mean in the model space based on the covariance and mean of log(x) (i.e. in the search space)

cdf(x)[source]#

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

Parameters:

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

Returns:

The cumulative distribution function value at x.

Return type:

float

logpdf(x)[source]#

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

Parameters:

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

Returns:

The logarithm of the probability density function value at x.

Return type:

float

marginal(position)[source]#

Return univariate marginal distribution of parameter with index ‘position’

pdf(x)[source]#

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

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

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

Generates random variates from the distribution.

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

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

Returns:

An array of random variates from the distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

transformed_properties(transformation)[source]#

Return distribution properties in search space

_n_parameters#
property compatible_transformations#
distribution_log_x#
name = 'MultivariateLogNormal'#
properties#
properties_log_x#
sigma2#
class pybop.MultivariateNonparametric(samples, random_state=None)[source]#

Bases: BaseMultivariateDistribution

Represents a “freeform” distribution, i.e., one that is defined from a random sampling and a kernel density estimate on that sampling.

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

Parameters:

samples (numpy.ndarray) – The random variates to base the distribution on.

logpdf(x)[source]#

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

Parameters:

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

Returns:

The logarithm of the probability density function value at x.

Return type:

float

marginal(position)[source]#

Return univariate marginal distribution of parameter with index ‘position’

pdf(x)[source]#

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

Parameters:

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

Returns:

The probability density function value at x.

Return type:

float

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

Generates random variates from the distribution.

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

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

Returns:

An array of random variates from the distribution.

Return type:

array_like

Raises:

ValueError – If the size parameter is negative.

transformed_properties(transformation)[source]#

Return distribution properties in search space

_n_parameters#
property compatible_transformations#
name = 'MultivariateNonparametric'#
properties#
class pybop.MultivariateUniform(bounds, random_state=None)[source]#

Bases: BaseMultivariateDistribution

Represents a multivariate uniform distribution.

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

Parameters:

bounds (numpy.ndarray) – The lower and upper bounds for the uniform distribution.

marginal(position)[source]#

Return univariate marginal distribution of parameter with index ‘position’

_n_parameters#
property compatible_transformations#
name = 'MultivariateUniform'#
properties#
class pybop.NUTS(log_pdf: pybop.problems.log_pdf.LogPDF, options: pybop.PintsSamplerOptions | None = None)[source]#

Bases: pybop.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 = None, optimiser_options: pybop.OptimiserOptions | None = None)[source]#

Bases: pybop.BaseApplication

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

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

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

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

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

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

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

  • optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.

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

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

  • optimiser_options (pybop.OptimiserOptions, optional) – Options for the optimiser.

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

Bases: pybop.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(distribution: scipy.stats.distributions.rv_frozen | pybop.parameters.distributions.Distribution | None = None, bounds: BoundsPair | None = None, initial_value: float = None, transformation: pybop.transformation.base_transformation.Transformation | None = None)[source]#

Represents a parameter within the PyBOP framework.

This class encapsulates the definition of a parameter, including its initial value, bounds.

Parameters:
  • distribution (stats.distribution.rv_frozen | Distribution, optional) – Distribution of the parameter

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

  • initial_value (NumericValue, optional) – Initial parameter value

  • transformation (Transformation, optional) – Parameter transformation

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

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

__repr__() str[source]#

String representation of the parameter.

_check_compatible_transformation() None[source]#

Raise an error if the transformation is not compatible with the distribution.

_validate_initial_value_within_bounds() None[source]#

Validate that the initial value is within the bounds.

get_initial_value(transformed: bool = False) numpy.typing.NDArray | None[source]#

Get initial value in either the model space or the transformed search space.

get_mean(transformed: bool = False)[source]#

Get the mean of each parameter, or its initial value.

get_std(transformed: bool = False)[source]#

Get the standard deviation, or an estimate of it.

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

Sample from parameter’s distribution.

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

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

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

Returns:

Array of samples, or None if no distribution exists exists

Return type:

NDArray[np.floating] or None

update_initial_value(value: NumericValue | None) None[source]#

Update the initial parameter value.

_bounds = None#
_distribution = None#
_initial_value = None#
_transformation#
property bounds: tuple | None#

Parameter bounds as (lower, upper) tuple.

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

Container for managing multiple Parameter objects with additional functionality.

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

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

Internal method to add a parameter to the collection.

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

  • parameter (pybop.Parameter) – The parameter to add.

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

  • update_distribution (bool, optional) – Whether to update the joint or multivariate distribution (default: True).

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

Update initial values in bulk.

_collect_parameters(parameters)[source]#
add(name: str, parameter: Parameter, update_distribution: bool = True) None[source]#

Add a parameter to the collection.

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

Create a ComposedTransformation object from the individual parameter transformations.

convert_grad_to_array(grad: dict[str, numpy.ndarray]) numpy.ndarray[source]#

Get an array of sensitivities with the parameters in the expected order.

copy() Parameters[source]#

Create a deep copy of the Parameters object.

get(name: str) Parameter[source]#

Get a parameter by name.

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

Get bounds for each parameter as a dictionary.

Parameters:

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

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

Retrieve parameter bounds in numpy format.

Returns:

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

Return type:

numpy.ndarray

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

Retrieve parameter bounds in the format expected by Plotly.

Returns:

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

Return type:

numpy.ndarray

get_covariance(transformed: bool = False)[source]#

Get the covariance matrix, or an estimate of it.

Parameters:

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

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

Get initial values as array.

Parameters:

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

Returns:

Array of initial values

Return type:

NDArray[np.floating]

get_mean(transformed: bool = False)[source]#

Get the mean of each parameter, or its initial value.

Parameters:

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

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

Get the standard deviation, or an estimate of it, for each parameter.

Parameters:

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

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

Iterate over (name, parameter) pairs.

join(parameters=None)[source]#

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

Parameters:

parameters (pybop.Parameters)

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

Iterate over parameter names.

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

Sample from a joint or multivariate distribution.

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

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

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

Returns:

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

Return type:

NDArray[np.floating] or None

set(name: str, param: Parameter, update_distribution: bool = True) None[source]#

Set a parameter by name.

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

Return values as a dictionary of inputs.

Parameters:

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

Returns:

Dictionary mapping parameter names to values

Return type:

Inputs

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

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

update(*, initial_values: ArrayLike | Inputs | None = None, **individual_updates: dict[str, Any]) None[source]#

Update multiple parameters efficiently.

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

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

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

update_distribution()[source]#

Method to determine whether to construct a JointDistribution or a MultivariateDistribution and to set up the distribution.

Multivariate distributions are passed to individual parameters via the corresponding marginal distribution. The pybop.MarginalDistribution class retains the underlying pybop.MultivariateDistribution in the parent_distribution property.

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

Iterate over parameters.

verify_inputs(inputs: Inputs) bool[source]#

Check if the inputs are valid parameters.

_distribution = None#
_multivariate = None#
_parameters = None#
_transform = None#
property distribution: pybop.parameters.multivariate_distributions.BaseMultivariateDistribution | pybop.parameters.distributions.JointDistribution | None#

Return the joint or multivariate distribution.

property names: list[str]#
property transformation: pybop.transformation.base_transformation.Transformation#

Get the transformation for the parameters.

property transformed_distribution_properties#
class pybop.PintsOptions[source]#

Bases: pybop.optimisers.base_optimiser.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

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#
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

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.log_pdf.LogPDF, 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.Problem(simulator: pybop.simulators.base_simulator.BaseSimulator = None, cost: pybop.costs.base_cost.BaseCost = None)[source]#

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

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

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

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

target_data#

An array containing the target data to fit.

Type:

array-like

n_outputs#

The number of outputs in the model.

Type:

int

minimising#

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

Type:

bool, optional

__call__(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs]) float | list[float][source]#

Evaluate the cost for one or more sets of inputs and return the cost value(s).

Parameters:

inputs (Inputs | list[Inputs]) – Input parameters for cost evaluation. Supports a list of inputs.

Returns:

The cost value(s).

Return type:

float | list[float]

evaluate(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.costs.evaluation.Evaluation[source]#

Evaluate the cost for one or more sets of inputs and return the cost value(s) and (optionally) the sensitivities.

Parameters:
  • inputs (Inputs | list[Inputs]) – Input parameters for cost evaluation. Supports a list of inputs.

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

The cost value(s) and (optionally) the gradient of the cost with respect to each input parameter.

Return type:

Evaluation

evaluate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.costs.evaluation.Evaluation[source]#

Evaluate the cost for each set of inputs and return the cost value(s) and (optionally) the sensitivities.

Parameters:
  • inputs (list[Inputs]) – A list of input parameters.

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

Cost values of len(inputs) and (optionally) the gradient of the cost with respect to each input parameter with shape (len(inputs), len(parameters)).

Return type:

Evaluation

get_finite_initial_cost()[source]#

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

get_model_inputs(inputs: pybop.parameters.parameter.Inputs)[source]#
sensitivity_analysis(n_samples: int = 256, calc_second_order: bool = False) dict[source]#

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

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

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

set_target(value: list[str] | str | None = None)[source]#
simulate(inputs: pybop.parameters.parameter.Inputs | list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) pybop.simulators.base_simulator.Solution | list[pybop.simulators.base_simulator.Solution][source]#

Simulate the model for one or more sets of inputs and return the solution and (optionally) the sensitivities.

Parameters:
  • inputs (Inputs | list[Inputs]) – Input parameters. Support a list of inputs.

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

The simulated model output y(t) and (optionally) the sensitivities dy/dx(t)

for output variable(s) y, domain t and parameter(s) x.

Return type:

Solution | list[Solution]

simulate_batch(inputs: list[pybop.parameters.parameter.Inputs], calculate_sensitivities: bool = False) list[pybop.simulators.base_simulator.Solution | pybop.simulators.failed_solution.FailedSolution][source]#

Simulate the model for each set of inputs and return the solution and (optionally) the sensitivities.

Parameters:

inputs (list[Inputs]) – A list of input parameters.

Returns:

A list of length(inputs) containing the simulated model output y(t) and (optionally) the sensitivities dy/dx(t) for output variable(s) y, domain t and parameter(s) x.

Return type:

list[Solution]

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

Bases: pybop.optimisers.base_pints_optimiser.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.log_pdf.LogPDF, 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.RelativisticMCMC(log_pdf: pybop.problems.log_pdf.LogPDF, 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.Result(problem: pybop.problems.problem.Problem, logger: pybop._logging.Logger, time: float, method_name: str | None = None, message: str | None = None, scipy_result=None)[source]#

Stores the result produced by an optimiser or sampler.

problem#

The optimisation problem used to generate the results.

Type:

pybop.Problem

logger#

The log of the optimisation or sampling process.

Type:

pybop.Logger

time#

The time taken.

Type:

float

method_name#

The name of the optimiser or sampler.

Type:

str

message#

The reason for stopping given by the optimiser or sampler.

Type:

str

__str__() str[source]#

A string representation of the Result object.

Returns:

A formatted string containing optimisation result information.

Return type:

str

_check_for_finite_cost() None[source]#

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

Raises:

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

_get_single_or_all(attr)[source]#
_validate()[source]#

Check that there is a finite cost and update best run.

static combine(results: list[Result]) Result[source]#

Combine multiple Result objects into a single one.

Parameters:

results (list[Result]) – List of Result objects to combine.

Returns:

Combined Result object.

Return type:

Result

data_dict() dict[source]#

return result data as dictionary for saving to file

static load(filename: str) Result[source]#

Load a saved Result.

static load_data(filename: str, file_format: str = 'pickle') dict[source]#

Load results data as dictionary from a given file. Restores data saved with save_data.

Calls load_data_dict defined in _utils.py and provides the keys of data that is 0-d and 1-d to ensure consistent data dimensions.

Parameters:
  • filename (str) – The name of the file containing the data.

  • file_format (str, optional) – The format the data was save to. Options are: - ‘pickle’ (default) - ‘matlab’ - ‘csv’ - ‘json’

Returns:

python dictionary containing the data in the file.

Return type:

data_dict

plot_contour(**kwargs)[source]#

Generate and plot a 2D visualisation of the cost landscape with the optimisation trace.

Parameters:
  • gradient (bool, optional) – If True, gradient plots are also generated (default: False).

  • bounds (numpy.ndarray | list[list[float]], optional) – A 2x2 array specifying the [min, max] bounds for each parameter.

  • transformed (bool, optional) – Uses the transformed parameter values, as seen by the optimiser (default: False).

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

  • show (bool, optional) – If True, the figure is shown upon creation (default: True).

  • **layout_kwargs (optional) – Valid Plotly layout keys and their values.

plot_convergence(**kwargs)[source]#

Plot the evolution of the best cost during the optimisation.

Parameters:
  • show (bool, optional) – If True, the figure is shown upon creation (default: True).

  • **layout_kwargs (optional) – Valid Plotly layout keys and their values.

plot_parameters(**kwargs)[source]#

Plot the evolution of parameter values during the optimisation.

Parameters:
  • show (bool, optional) – If True, the figure is shown upon creation (default: True).

  • **layout_kwargs (optional) – Valid Plotly layout keys and their values.

plot_surface(**kwargs)[source]#

Plot a 2D representation of the Voronoi diagram with color-coded regions.

Parameters:
  • bounds (numpy.ndarray, optional) – A 2x2 array specifying the [min, max] bounds for each parameter.

  • normalise (bool, optional) – If True, the voronoi regions are computed using the Euclidean distance between points normalised with respect to the bounds (default: True).

  • resolution (int, optional) – Resolution of the plot (default: 500).

  • show (bool, optional) – If True, the figure is shown upon creation (default: True).

  • **layout_kwargs (optional) – Valid Plotly layout keys and their values.

save(filename) None[source]#

Save the whole result using pickle

save_data(filename=None, to_format='pickle') str | None[source]#

Save result data

Based on pybamm.Solution.save_data

Parameters:
  • filename (str, optional) – The name of the file to save data to. If None, then a str is returned for json format or an error is thrown for pickle/matlab.

  • to_format (str, optional) –

    The format to save to. Options are:

    • ’pickle’ (default): creates a pickle file with the data dictionary

    • ’matlab’: creates a .mat file, for loading in matlab

    • ’json’: creates a json file

Returns:

data – str if ‘json’ is chosen and filename is None, otherwise None

Return type:

str, optional

total_evaluations() numpy.floating | None[source]#

Calculates the total number of evaluations across all runs.

total_iterations() numpy.floating | None[source]#

Calculates the total number of iterations across all runs.

total_runtime() numpy.floating | None[source]#

Calculates the total runtime across all runs.

_best_cost#
_best_run = None#
_cost#
_initial_cost#
_iteration_number#
_message#
_minimising#
_n_evaluations#
_n_iterations#
_problem#
_scipy_result#
_time#
_x#
_x0#
_x_model#
property best_cost: float#

The best cost value(s).

property best_inputs: dict[str, numpy.ndarray]#

The best parameters as a dictionary.

property cost: numpy.ndarray#

The log of the cost values.

property initial_cost: float#

The initial cost value(s).

property iteration_number: numpy.ndarray | None#

The number of iterations.

property message: str | None#

The optimisation termination message(s).

method_name = None#
property minimising: bool#

Whether the cost was minimised (or maximised).

property n_evaluations: int#

The number of evaluations.

property n_iterations: int#

The number of iterations.

n_runs = 1#
property problem: pybop.problems.problem.Problem#

The optimisation problem.

property scipy_result#

The SciPy result.

property time: float | None#

The optimisation time(s).

property x: numpy.ndarray#

The best parameter values (in model space).

property x0: numpy.ndarray#

The initial parameter values.

property x_model: numpy.ndarray#

The log of the evaluated parameters (in model space).

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

Bases: 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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: pybop.optimisers.base_pints_optimiser.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.

property name: str#

Overwrite misspelling of separable from Pints 0.5.1.

class pybop.SamplerOptions[source]#

Base options for the sampler.

n_chains#

The number of chains to concurrently sample from.

Type:

int

validate()[source]#

Validate the options.

Raises:

ValueError – If the options are invalid.

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.optimisers.base_optimiser.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.optimisers.base_optimiser.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.log_pdf.LogPDF, 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.log_pdf.LogPDF, 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.log_pdf.LogPDF, 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.Solution(inputs: pybop.parameters.parameter.Inputs = None)[source]#

A class to store simulation results, inspired by pybamm.Solution.

__getitem__(key)[source]#
set_solution_variable(variable_name: str, data: numpy.ndarray, sensitivities: dict[str, numpy.ndarray] | None = None)[source]#
_dict#
all_inputs#
class pybop.SquareRootFeatureDistance(domain_data: numpy.ndarray, target_data: numpy.ndarray, feature: str = 'inverse_slope', time_start: float = None, time_end: float = None)[source]#

Bases: FeatureDistance

Square-root fit cost function.

Fits a square-root fit function and compares either its offset or its slope between model predictions and target data.

_feature_selection(fit)[source]#
_fit_guess(t, y)[source]#
_inverse_fit_function(y, b, c)[source]#

Square function to transform data for a linear fit.

_supported_features = ['offset', 'slope', 'inverse_slope']#
class pybop.SumOfPower(dataset: pybop.processing.dataset.Dataset, p: float = 2.0, target: str | list[str] = None, weighting: str | numpy.ndarray = None)[source]#

Bases: 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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: 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, inputs: pybop.parameters.parameter.Inputs | None = None) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

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

  • dy (dict[str, np.ndarray], optional) – The corresponding gradients dy/dx(t) for each output variable y with respect to each parameter x over the domain t. The dictionary keys are the parameter names and the arrays are of dimensions (len(target), len(domain_data)).

Returns:

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

Return type:

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

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

Bases: Distribution

Represents a uniform distribution over a specified interval.

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

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

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

__repr__()[source]#

Returns a string representation of the object.

_dlogpdf_dx(x)[source]#

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

Parameters:

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

Returns:

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

Return type:

float

mean()[source]#

Returns the mean of the distribution.

_n_parameters = 1#
lower#
name = 'Uniform'#
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.

evaluate(solution: pybop.simulators.solution.Solution, inputs: pybop.parameters.parameter.Inputs | None = None, calculate_sensitivities: bool = False) float | tuple[float, numpy.ndarray][source]#

Computes the cost function for the given predictions.

Parameters:
  • solution (pybop.Solution | pybamm.Solution) – The simulation result.

  • inputs (Inputs, optional) – Input parameters (default: None).

  • calculate_sensitivities (bool) – Whether to also return the sensitivities (default: False).

Returns:

If the solution has sensitivities, returns a tuple containing the cost (float) and the gradient with dimension (len(parameters)), otherwise returns only the cost.

Return type:

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

set_target(target: list[list[str]] | list[str] | str | None = None)[source]#

Set the target variable for all costs. Expecting a list of list[str] the same length as self.costs.

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

Bases: pybop.optimisers.base_pints_optimiser.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.load_data_dict(filename: str, file_format: str = 'pickle', data_keys_0d: list[str] | None = None, data_keys_1d: list[str] | None = None) dict[source]#

Load data as dictionary from a given file. Restores data saved with save_data_dict.

Parameters:
  • filename (str) – The name of the file containing the data.

  • file_format (str, optional) – The format the data was save to. Options are: - ‘pickle’ (default) - ‘matlab’ - ‘csv’ - ‘json’

  • data_keys_0d (list[str], optional) – A list of keys for which the data is a scalar/0-dimensional. This is only needed for file_format=’matlab’ or file_format = ‘csv’. scipy.io.savemat turns any data into a multi-dimensional array with at least 2 dimensions. If provided, data dimensions will be consistent with the original data.

  • data_keys_1d (list[str], optional) – A list of keys for which the data is a 1-dimensional list or array. This is only needed for file_format=’matlab’. scipy.io.savemat turns any data into a multi-dimensional array with at least 2 dimensions. If provided, data dimensions will be consistent with the original data.

Returns:

python dictionary containing the data in the file.

Return type:

data_dict

pybop.save_data_dict(data_dict: dict, filename: str | None = None, to_format: str = 'pickle') str | None[source]#

Save data from given data dictionary

Based on pybamm.Solution.save_data

Parameters:
  • filename (str, optional) – The name of the file to save data to. If None, then a str is returned

  • to_format (str, optional) –

    The format to save to. Options are:

    • ’pickle’ (default): creates a pickle file with the data dictionary

    • ’matlab’: creates a .mat file, for loading in matlab

    • ’csv’: creates a csv file (0D variables only)

    • ’json’: creates a json file

Returns:

data – str if ‘json’ is chosen and filename is None, otherwise None

Return type:

str, optional

pybop.FLOAT_FORMAT = '{: .17e}'#
pybop.__version__#
pybop.script_path#