Base Solver#

class pybamm.BaseSolver(method=None, rtol=1e-06, atol=1e-06, root_method=None, root_tol=1e-06, extrap_tol=None, on_extrapolation=None, on_failure=None, output_variables=None)[source]#

Solve a discretised model.

Parameters:
  • method (str, optional) – The method to use for integration, specific to each solver

  • rtol (float, optional) – The relative tolerance for the solver (default is 1e-6).

  • atol (float, optional) – The absolute tolerance for the solver (default is 1e-6).

  • root_method (str or pybamm algebraic solver class, optional) – The method to use to find initial conditions (for DAE solvers). If a solver class, must be an algebraic solver class. If “casadi”, the solver uses casadi’s Newton rootfinding algorithm to find initial conditions. Otherwise, the solver uses ‘scipy.optimize.root’ with method specified by ‘root_method’ (e.g. “lm”, “hybr”, …)

  • root_tol (float, optional) – The tolerance for the initial-condition solver (default is 1e-6).

  • extrap_tol (float, optional) – The tolerance to assert whether extrapolation occurs or not. Default is 0.

  • output_variables (list[str], optional) – List of variables to calculate and return. If none are specified then the complete state vector is returned (can be very large) (default is [])

  • on_extrapolation (str, optional) – What to do if the solver is extrapolating. Options are “warn”, “error”, or “ignore”. Default is “warn”.

  • on_failure (str, optional) – What to do if a solver error flag occurs. Options are “warn”, “error”, or “ignore”. Default is “error”.

calculate_consistent_state(model: BaseModel, time: float = 0, inputs: list[dict] | None = None)[source]#

Calculate consistent state for the algebraic equations through root-finding. model.y0_list is used as the initial guess for rootfinding

Parameters:
  • model (pybamm.BaseModel) – The model for which to calculate initial conditions.

  • time (float) – The time at which to calculate the initial conditions

  • inputs (list of dict, optional) – Any input parameters to pass to the model when solving

Returns:

y0_consistent – Initial conditions that are consistent with the algebraic equations (roots of the algebraic equations). If self.root_method == None then returns model.y0_list.

Return type:

array-like, same shape as y0_guess

check_extrapolation(solution, events)[source]#

Check if extrapolation occurred for any of the interpolants. Note that with the current approach (evaluating all the events at the solution times) some extrapolations might not be found if they only occurred for a small period of time.

Parameters:
copy()[source]#

Returns a copy of the solver

static filter_discontinuities(t_discon: list, t_eval: list) ndarray[source]#

Filter the discontinuities to only include the unique and sorted values within the t_eval range (non-exclusive of end points).

Parameters:
  • t_discon (list) – The list of all possible discontinuity times.

  • t_eval (list) – The integration time points.

Returns:

The filtered list of discontinuities within the range of t_eval.

Return type:

np.ndarray

static from_config(data: dict) BaseSolver[source]#

Create a solver from a config dict.

Parameters:

data (dict) – Config dict as produced by to_config(), with a "type" key and solver-specific keyword arguments.

Return type:

BaseSolver

static get_termination_reason(solution, events)[source]#

Identify the cause for termination. In particular, if the solver terminated due to an event, (try to) pinpoint which event was responsible. If an event occurs the event time and state are added to the solution object. Note that the current approach (evaluating all the events and then finding which one is smallest at the final timestep) is pretty crude, but is the easiest one that works for all the different solvers.

Parameters:
set_up(model: BaseModel, inputs: dict | list[dict] | None = None, t_eval=None, ics_only=False)[source]#

Unpack model, perform checks, and calculate jacobian.

Parameters:
  • model (pybamm.BaseModel) – The model whose solution to calculate. Must have attributes rhs and initial_conditions

  • inputs (dict or list of dict, optional) – Any input parameters to pass to the model when solving

  • t_eval (numeric type, optional) – The times at which to stop the integration due to a discontinuity in time.

solve(model, t_eval=None, inputs: list[dict] | dict | None = None, nproc=None, calculate_sensitivities=False, t_interp=None)[source]#

Execute the solver setup and calculate the solution of the model at specified times.

Parameters:
  • model (pybamm.BaseModel) – The model whose solution to calculate. Must have attributes rhs and initial_conditions. All calls to solve must pass in the same model or an error is raised

  • t_eval (None, list or ndarray, optional) – The times (in seconds) at which to compute the solution. Defaults to None.

  • inputs (dict or list of dict, optional) – A dictionary or list of dictionaries describing any input parameters to pass to the model when solving

  • nproc (int, optional) – Number of processes to use when solving for more than one set of input parameters. Defaults to value returned by “os.cpu_count()”.

  • calculate_sensitivities (list of str or bool, optional) – Whether the solver calculates sensitivities of all input parameters. Defaults to False. If only a subset of sensitivities are required, can also pass a list of input parameter names. Limitations: sensitivities are not calculated up to numerical tolerances so are not guarenteed to be within the tolerances set by the solver, please raise an issue if you require this functionality. Also, when using this feature with pybamm.Experiment, the sensitivities do not take into account the movement of step-transitions wrt input parameters, so do not use this feature if the timings of your experimental protocol change rapidly with respect to your input parameters.

  • t_interp (None, list or ndarray, optional) – The times (in seconds) at which to interpolate the solution. Defaults to None. Only valid for solvers that support intra-solve interpolation (IDAKLUSolver).

Returns:

If type of inputs is list, return a list of corresponding pybamm.Solution objects.

Return type:

pybamm.Solution or list of pybamm.Solution objects.

Raises:
  • pybamm.ModelError – If an empty model is passed (model.rhs = {} and model.algebraic={} and model.variables = {})

  • RuntimeError – If multiple calls to solve pass in different models

step(old_solution, model, dt, t_eval=None, npts=None, inputs=None, save=True, calculate_sensitivities=False, t_interp=None, state_mapper=None)[source]#

Step the solution of the model forward by a given time increment. The first time this method is called it executes the necessary setup by calling self.set_up(model).

Parameters:
  • old_solution (pybamm.Solution or None) – The previous solution to be added to. If None, a new solution is created.

  • model (pybamm.BaseModel) – The model whose solution to calculate. Must have attributes rhs and initial_conditions

  • dt (numeric type) – The timestep (in seconds) over which to step the solution

  • t_eval (list or numpy.ndarray, optional) – An array of times at which to stop the simulation and return the solution during the step (Note: t_eval is the time measured from the start of the step, so should start at 0 and end at dt). By default, the solution is returned at t0 and t0 + dt.

  • npts (deprecated)

  • inputs (dict, optional) – Any input parameters to pass to the model when solving

  • save (bool, optional) – Save solution with all previous timesteps. Defaults to True.

  • calculate_sensitivities (list of str or bool, optional) – Whether the solver calculates sensitivities of all input parameters. Defaults to False. If only a subset of sensitivities are required, can also pass a list of input parameter names. Limitations: sensitivities are not calculated up to numerical tolerances so are not guaranteed to be within the tolerances set by the solver, please raise an issue if you require this functionality. Also, when using this feature with pybamm.Experiment, the sensitivities do not take into account the movement of step-transitions wrt input parameters, so do not use this feature if the timings of your experimental protocol change rapidly with respect to your input parameters.

  • t_interp (None, list or ndarray, optional) – The times (in seconds) at which to interpolate the solution. Defaults to None. Only valid for solvers that support intra-solve interpolation (IDAKLUSolver).

  • state_mapper (tuple of (function, jacobian_y, jacobian_p), optional) – A tuple containing a function and its Jacobians to map the state from the old solution to the new solution. function, jacobian_y and jacobian_p are casadi/jax/python functions that have been processed using BaseSolver.process. If not provided, then BaseModel.set_initial_conditions_from is used to map the state from the old solution to the new solution

Raises:

pybamm.ModelError – If an empty model is passed (model.rhs = {} and model.algebraic = {} and model.variables = {})

to_config() dict[source]#

Convert this solver to a JSON-serialisable config dict.

Returns a dict with a "type" key (the solver class name) and one key per serialisable __init__ parameter. CompositeSolver instances include a "sub_solvers" key with nested config dicts.

Returns:

Config dict suitable for passing back to from_config().

Return type:

dict