Base Model#

class pybamm.BaseModel(name='Unnamed model')[source]#

Base model class for other models to extend.

name#

A string representing the name of the model.

Type:

str

submodels#

A dictionary of submodels that the model is composed of.

Type:

dict

use_jacobian#

Whether to use the Jacobian when solving the model (default is True).

Type:

bool

convert_to_format#

Specifies the format to convert the expression trees representing the RHS, algebraic equations, Jacobian, and events. Options are:

  • None: retain PyBaMM expression tree structure.

  • “python”: convert to Python code for evaluating evaluate(t, y) on expressions.

  • “casadi”: convert to CasADi expression tree for Jacobian calculation.

  • “jax”: convert to JAX expression tree.

Default is “casadi”.

Type:

str

is_discretised#

Indicates whether the model has been discretised (default is False).

Type:

bool

y_slices#

Slices of the concatenated state vector after discretisation, used to track different submodels in the full concatenated solution vector.

Type:

None or list

property algebraic#

Returns a dictionary mapping expressions (variables) to expressions that represent the algebraic equations of the model.

static apply_builtin_overrides(model: BaseModel, data: dict) None[source]#

Apply variable and event overrides from a built-in config.

This is the inverse of serialise_builtin_overrides(). It mutates model in-place.

Parameters:
  • model (BaseModel) – A freshly-constructed built-in model.

  • data (dict) – The config dictionary, which may contain custom_variables, removed_variables, and/or events.

property boundary_conditions#

Returns a dictionary mapping expressions (variables) to expressions representing the boundary conditions of the model.

build_initial_state_mapper(from_model)[source]#

Build a mapper that maps a final state vector from a discretised model to this model’s discretised initial conditions.

Parameters:

from_model (pybamm.BaseModel) – The discretised model that provides the final state vector.

property built#

Returns a boolean for the model built status.

property calc_esoh#

Whether to include eSOH variables in the summary variables.

property can_process_symbols: bool#

Returns True if the model has a symbol processor that is capable of processing symbols.

check_algebraic_equations(post_discretisation)[source]#

Check that the algebraic equations are well-posed. After discretisation, there must be at least one StateVector in each algebraic equation.

check_discretised_or_discretise_inplace_if_0D()[source]#

Discretise model if it isn’t already discretised This only works with purely 0D models, as otherwise the mesh and spatial method should be specified by the user

check_ics_bcs()[source]#

Check that the initial and boundary conditions are well-posed.

check_no_repeated_keys()[source]#

Check that no equation keys are repeated.

check_well_determined(post_discretisation)[source]#

Check that the model is not under- or over-determined.

check_well_posedness(post_discretisation=False)[source]#

Check that the model is well-posed by executing the following tests: - Model is not over- or underdetermined, by comparing keys and equations in rhs and algebraic. Overdetermined if more equations than variables, underdetermined if more variables than equations. - There is an initial condition in self.initial_conditions for each variable/equation pair in self.rhs - There are appropriate boundary conditions in self.boundary_conditions for each variable/equation pair in self.rhs and self.algebraic

Parameters:

post_discretisation (boolean) – A flag indicating tests to be skipped after discretisation

property concatenated_algebraic#

Returns the concatenated algebraic equations for the model after discretisation.

property concatenated_initial_conditions#

Returns the initial conditions for all variables after discretization, providing the initial values for the state variables.

property concatenated_rhs#

Returns the concatenated right-hand side (RHS) expressions for the model after discretisation.

property coupled_variables#

Returns a dictionary mapping strings to expressions representing variables needed by the model but whose equations were set by other models.

property default_geometry#

Returns a dictionary of the default geometry for the model, which is empty by default.

property default_parameter_values#

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

property default_solver#

Returns the default solver for the model, based on whether it is an ODE/DAE or algebraic model.

property default_spatial_methods#

Returns a dictionary of the default spatial methods for the model, which is empty by default.

property default_submesh_types#

Returns a dictionary of the default submesh types for the model, which is empty by default.

property default_var_pts#

Returns a dictionary of the default variable points for the model, which is empty by default.

classmethod deserialise(properties: dict)[source]#

Create a model instance from a serialised object.

disable_solution_observability(reason: ModelSolutionObservability)[source]#

Disable observing the solution with solution.observe(symbol).

Parameters:

reason (ModelSolutionObservability) – The reason why the solution is or is not observable.

disable_symbol_processing(reason: ModelSolutionObservability)[source]#

Disable custom symbol processing by the model.

Parameters:

reason (ModelSolutionObservability, optional) – The reason why symbol processing is being disabled. Defaults to ModelSolutionObservability.DISABLED.

property events#

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

export_casadi_objects(variable_names, input_parameter_order=None)[source]#

Export the constituent parts of the model (rhs, algebraic, initial conditions, etc) as casadi objects.

Parameters:
  • variable_names (list) – Variables to be exported alongside the model structure

  • input_parameter_order (list, optional) – Order in which the input parameters should be stacked. If input_parameter_order=None and len(self.input_parameters) > 1, a ValueError is raised (this helps to avoid accidentally using the wrong order)

Returns:

casadi_dict – Dictionary of {str: casadi object} pairs representing the model in casadi format

Return type:

dict

property fixed_input_parameters: set[Symbol]#

Returns a set of all fixed input parameter symbols used in the parameter values.

static from_config(config: str | dict) BaseModel[source]#

Load a model from a config dict, raw model dict, or file path.

Accepts:

  1. Built-in config: {"type": "SPM", "module": "lithium_ion"}

  2. Custom config: {"type": "custom", "model": ...}

  3. Raw model dict from to_json()

  4. A path to a JSON file in any of the above formats

Parameters:

config (str or dict) – Config or model dictionary, or path to a JSON file.

Returns:

The reconstructed symbolic model.

Return type:

pybamm.BaseModel or subclass

static from_json(filename: str | dict) BaseModel[source]#

Load a custom (symbolic) model from a JSON file or dictionary.

Use this for models saved with to_json(). For discretised models saved with save_model(), use pybamm.load_model() instead. For the wrapped config format (from to_config()), use from_config() instead.

Parameters:

filename (str or dict) – Path to a JSON file containing the saved model, or a dictionary (e.g. from to_json()).

Returns:

The reconstructed symbolic model.

Return type:

pybamm.BaseModel or subclass

Examples

>>> model = pybamm.lithium_ion.SPM()
>>> loaded = pybamm.BaseModel.from_json(model.to_json())
>>> loaded = pybamm.BaseModel.from_json("model.json")
generate(filename, variable_names, input_parameter_order=None, cg_options=None)[source]#

Generate the model in C, using CasADi.

Parameters:
  • filename (str) – Name of the file to which to save the code

  • variable_names (list) – Variables to be exported alongside the model structure

  • input_parameter_order (list, optional) – Order in which the input parameters should be stacked. If input_parameter_order=None and len(self.input_parameters) > 1, a ValueError is raised (this helps to avoid accidentally using the wrong order)

  • cg_options (dict) – Options to pass to the code generator. See https://web.casadi.org/docs/#generating-c-code

property geometry#

Returns the geometry of the model.

get_parameter_info(by_submodel=False)[source]#

Extracts the parameter information and returns it as a dictionary. To get a list of all parameter-like objects without extra information, use model.parameters.

Parameters:

by_submodel (bool, optional) – Whether to return the parameter info sub-model wise or not (default False)

get_processed_variable(name: str) Symbol[source]#

Get a processed variable by name.

Parameters:

name (str) – The name of the variable to get.

Returns:

The processed variable.

Return type:

pybamm.Symbol

Raises:

KeyError – If the variable is not found.

get_processed_variable_or_event(name: str) Symbol[source]#

Get a processed variable or event by name.

Parameters:

name (str) – The name of the variable or event to get.

Returns:

The processed variable or event expression.

Return type:

pybamm.Symbol

Raises:

KeyError – If the variable or event is not found.

get_processed_variables_dict() dict[str, Symbol][source]#

Get a dictionary of processed variables.

info(symbol_name)[source]#

Provides helpful summary information for a symbol.

Parameters:

symbol_name (str)

property initial_conditions#

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

property input_parameters#

Returns a list of all input parameter symbols used in the model.

property is_processed: bool#

Returns True if the model is processed by Discretisation.process_model or ParameterValues.process_model.

property is_standard_form_dae: bool#

Check if the model is a DAE in standard form with a mass matrix that is all zeros except for along the diagonal, which is either ones or zeros.

property jacobian#

Returns the Jacobian matrix for the model, computed automatically if use_jacobian is True.

property jacobian_algebraic#

Returns the Jacobian matrix for the algebraic part of the model, computed automatically during solver setup if use_jacobian is True.

property jacobian_rhs#

Returns the Jacobian matrix for the right-hand side (RHS) part of the model, computed if use_jacobian is True.

latexify(filename=None, newline=True, output_variables=None)[source]#

Converts all model equations in latex.

Parameters:
  • filename (str (optional)) – Accepted file formats - any image format, pdf and tex Default is None, When None returns all model equations in latex If not None, returns all model equations in given file format.

  • newline (bool (optional)) – Default is True, If True, returns every equation in a new line. If False, returns the list of all the equations.

  • model (Load)

  • pybamm.lithium_ion.SPM() (>>> model =)

  • png (This will returns all model equations in)

  • doctest (>>> model.latexify(newline=False) #)

  • latex (This will return all the model equations in)

  • doctest

  • equations (This will return first five model)

  • doctest

  • equations

  • model.latexify(newline=False)[1 (>>>)

property mass_matrix#

Returns the mass matrix for the system of differential equations after discretisation.

new_copy()[source]#

Creates a copy of the model, explicitly copying all the mutable attributes to avoid issues with shared objects.

property options#

Returns the model options dictionary that allows customization of the model’s behavior.

property param#

Returns a dictionary to store parameter values for the model.

property parameters#

Returns a list of all parameter symbols used in the model.

print_parameter_info(by_submodel=False)[source]#

Print parameter information in a formatted table from a dictionary of parameters

Parameters:

by_submodel (bool, optional) – Whether to print the parameter info sub-model wise or not (default False)

process_and_register_variable(name: str, symbol: Symbol)[source]#

Process a variable and store it in _variables_processed.

This method does NOT modify self.variables - the original variable expression is preserved. The processed variable is stored separately in _variables_processed.

CoupledVariables in the symbol are resolved by recursively getting the processed version of the referenced variable.

Parameters:
  • name (str) – The name of the variable.

  • symbol (pybamm.Symbol) – The unprocessed variable symbol.

process_parameters_and_discretise(symbol, parameter_values, disc)[source]#

Process parameters and discretise a symbol.

This method is deprecated. Please process the model first with ParameterValues.process_model() and Discretisation.process_model(), then call model.process_symbol(symbol)().

property required_input_parameters#

Returns a list of all input parameter symbols used in the model.

property rhs#

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

save_model(filename=None, mesh=None, variables=None)[source]#

Write out a discretised model to a JSON file

Parameters:
  • filename (str, optional)

  • provided (The desired name of the JSON file. If no name is)

  • created (one will be)

  • name (based on the model)

  • datetime. (and the current)

serialise_builtin_overrides(model_config: dict) None[source]#

Detect and serialise user modifications to a built-in model.

Compares the current model’s variables keys and events against a freshly-constructed reference model (same class and options). Any differences are written into model_config using the following optional keys:

custom_variables

dict[str, json] – variables the user added (keys not present in the reference model). Each value is the symbolic expression serialised via convert_symbol_to_json().

removed_variables

list[str] – variable names that exist in the reference model but have been deleted by the user.

events

list[dict] – full serialised events list, included only when the events differ from the reference model (by count or by name set).

If the model is unmodified, no extra keys are added and the config stays identical to the previous compact format.

Note

Only added/removed variable keys are tracked. Overwriting an existing variable’s expression with a new one is not detected in this version.

Parameters:

model_config (dict) – The compact config dict (mutated in-place).

set_initial_conditions_from(solution, inputs=None, inplace=True, return_type='model', mesh=None)[source]#

Update initial conditions with the final states from a Solution object or from a dictionary. This assumes that, for each variable in self.initial_conditions, there is a corresponding variable in the solution with the same name and size.

Parameters:
  • solution (pybamm.Solution, or dict) – The solution to use to initialize the model

  • inputs (dict) – The dictionary of model input parameters.

  • inplace (bool, optional) – Whether to modify the model inplace or create a new model (default True)

  • return_type (str, optional) – Whether to return the model (default) or initial conditions (“ics”)

  • mesh (pybamm.Mesh, optional) – The mesh to use to initialize the model

property solution_observable: bool#

Returns the observability state for solution.observe(symbol).

Returns ModelSolutionObservability.ENABLED if observable, otherwise returns a reason why the solution is not observable.

property solution_observable_status: ModelSolutionObservability#

Returns the status of the solution observability as a string.

to_config(filename: str | Path | None = None, compress: bool = False) dict[source]#

Convert the model to a config dictionary.

Built-in models (those found in pybamm.lithium_ion, pybamm.lead_acid, etc.) produce a compact format:

{"type": "SPM", "module": "lithium_ion", "options": {...}}

Custom or user-defined models produce the full serialised format:

{"type": "custom", "model": ..., "geometry": ..., ...}
Parameters:
  • filename (str or pathlib.Path, optional) – If provided, save the config dict to this file. Must end with .json.

  • compress (bool, optional) – If True, the inner model data is compressed (zlib + base64). Default is False.

Returns:

Config dictionary.

Return type:

dict

to_json(filename: str | Path | None = None, compress: bool = False) dict[source]#

Convert the model to a JSON-serialisable dictionary (raw format).

Optionally saves to a file. Works for custom (non-discretised) models that are subclasses of BaseModel. Use save_model() for discretised models. For a wrapped config format (type + model), use to_config() instead.

Parameters:
  • filename (str or pathlib.Path, optional) – The filename to save the JSON file to. If not provided, the dictionary is not saved. Must end with .json if provided.

  • compress (bool, optional) – If True, the model data will be compressed (zlib + base64) in the returned dict and in the file if filename is set. Default is False.

Returns:

The JSON-serialisable dictionary (optionally compressed).

Return type:

dict

Examples

>>> model = pybamm.lithium_ion.SPM()
>>> param_dict = model.to_json()  # Get dictionary only
>>> isinstance(param_dict, dict)
True
>>> model.to_json("model.json")  # Save and return dict
{'schema_version': '1.1', ...}
update(*submodels)[source]#

Update model to add new physics from submodels

Parameters:

submodel (iterable of pybamm.BaseModel) – The submodels from which to create new model

update_processed_variables(processed_vars: dict[str, Symbol])[source]#

Update the _variables_processed dict with new processed variables.

Parameters:

processed_vars (dict or list) – Either a dictionary of {name: processed_symbol} pairs, or a list of names (for backward compatibility, where the processed symbol is taken from self.variables).

property variables#

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

property variables_and_events#

Returns a dictionary containing both models variables and events.