Models#

Manage battery models in Ionworks Studio.

For usage examples and guides, see Managing models on docs.ionworks.com.

Custom model client for managing battery models and custom variables.

This module provides the ModelClient for creating, reading, updating, and deleting custom battery models within an organization, as well as adding custom variables to those models.

ionworks.custom_model.ModelChemistry#

Allowed values for the chemistry field on uploaded custom models. Mirrors the ModelChemistry Literal on the backend.

alias of Literal[‘lithium_ion’, ‘lithium_sulfur’, ‘ecm’, ‘generic’]

class ionworks.custom_model.ModelClient(client)[source]#

Bases: object

Client for managing custom battery models.

Provides methods to create, read, update, and delete custom models within an organization. Also supports adding custom variables to models.

Parameters:

client (Any)

__init__(client)[source]#

Initialize the ModelClient.

Parameters:

client (Any) – The HTTP client instance for making API requests.

Return type:

None

get(model_id)[source]#

Get a specific model by ID, including its config.

Parameters:

model_id (str) – The ID of the model to retrieve.

Returns:

The requested model object (includes config field).

Return type:

Model

get_simulation_settings(model_id)[source]#

Return a model’s persisted simulation settings, ready to fold into a fit.

Standard datafit / validation objective configs are hand-authored by the caller, so a saved model’s persisted mesh + solver are not applied automatically the way they are for plain simulations and design optimization. Use this to fetch them and merge them into an objective’s options["simulation_kwargs"] so the fit/validation runs with the same discretization the model was configured with:

sim_kwargs = client.model.get_simulation_settings(model_id)
objective = iws.objectives.CurrentDriven(
    data_input="…",
    options={"model": {"type": "SPMe"}, "simulation_kwargs": sim_kwargs},
)

For a validation against a parameterized model, read client.parameterized_model.get(pm_id).simulation_settings instead (its parameter-specific settings take precedence over the base model’s).

Parameters:

model_id (str) – The ID of the (base) model.

Returns:

The flat simulation_settings bag (var_pts / submesh_types / spatial_methods / solver), or an empty dict if the model has none persisted.

Return type:

dict[str, Any]

list(limit=None, offset=None, *, name=None, name_exact=None, created_by_email=None, created_after=None, created_before=None, updated_after=None, updated_before=None, order_by=None, order=None)[source]#

List models with optional filtering.

Parameters:
  • limit (int | None, optional) – Maximum number of models to return per page.

  • offset (int | None, optional) – Number of models to skip for pagination.

  • name (str | None, optional) – Case-insensitive substring match on model name.

  • name_exact (str | None, optional) – Exact match on model name.

  • created_by_email (str | None, optional) – Case-insensitive substring match on the creator’s email.

  • created_after (str | None, optional) – ISO datetime; return models created after this time.

  • created_before (str | None, optional) – ISO datetime; return models created before this time.

  • updated_after (str | None, optional) – ISO datetime; return models updated after this time.

  • updated_before (str | None, optional) – ISO datetime; return models updated before this time.

  • order_by (str | None, optional) – Column to sort by.

  • order (str | None, optional) – Sort direction: "asc" or "desc".

Returns:

A list of model objects.

Return type:

PaginatedList[Model]

create(data=None)[source]#

Create a new model.

Parameters:

data (dict[str, Any]) –

Dictionary containing the model data. Required fields: name, config. Optional fields: description, pybamm_version, simulation_settings.

config may be a {"type": ...} dict or a built-in pybamm.BaseModel instance (e.g. pybamm.lithium_ion.SPMe()), which is serialized for you the same way ionworks_schema accepts a pybamm model as a fit’s model. Custom pybamm models go through upload_custom() instead.

simulation_settings is a persistent bag of pybamm simulation kwargs (var_pts / submesh_types / spatial_methods / solver) re-applied whenever the model is simulated. Build it from live pybamm objects with the schema wrapper:

import ionworks_schema as iws
import pybamm

settings = iws.models.SimulationSettings(
    var_pts={"r_n": 16, "r_p": 16},
    submesh_types={
        "negative particle": pybamm.MeshGenerator(
            pybamm.Exponential1DSubMesh, {"side": "right"}
        ),
    },
)
client.model.create({"name": "SPMe", "config": {"type": "SPMe"},
                     "simulation_settings": settings})

The SimulationSettings object is serialized for you; an already-serialized config dict (settings.to_config()) is equally accepted.

Returns:

The newly created model object.

Return type:

Model

upload_custom(model, *, name, chemistry='lithium_ion', description=None)[source]#

Upload a custom PyBaMM model.

Serialises a pybamm.BaseModel subclass instance (or accepts an already-serialised JSON file) and POSTs it to /models/upload-custom as multipart form data.

Parameters:
  • model (pybamm.BaseModel | str | os.PathLike | IO[bytes]) – The model to upload. Either a pybamm.BaseModel instance (will be serialised via Serialise().save_custom_model), a path to an existing serialised JSON file, or an open binary file object positioned at the start of the JSON content.

  • name (str) – Display name for the uploaded model.

  • chemistry (ModelChemistry, optional) – Chemistry tag controlling which simulation-pipeline path the model goes through. Defaults to "lithium_ion". Use "lithium_sulfur" for Li-S models, "ecm" for custom ECM models, or "generic" to opt out of all chemistry-specific enrichment.

  • description (str | None, optional) – Optional human-readable description.

Returns:

The created model record (is_custom_model=True).

Return type:

Model

Raises:

IonworksError – On any HTTP error from the upload endpoint.

Notes

Serialise().serialise_custom_model(model) returns a dict that contains EventType enums which aren’t JSON-serialisable. When a pybamm.BaseModel is passed in, this method routes through save_custom_model(filename=...) (which handles the enum conversion) via a temp file that is unlinked after upload.

serialize(name, *, options=None)[source]#

Build an ionworks model server-side and return its JSON.

Asks the API to construct an ionworks model (e.g. "ECM", "LumpedSPMR", the MSMR models, or "GITTModel") and serialise it to a pybamm Serialise document. This is the raw counterpart to download(): it returns the serialized dict without loading it, which is handy for saving to disk or re-uploading via upload_custom().

The server builds the model — defined in the licensed ionworkspipeline package — so the caller does not need an ionworkspipeline license. Only ionworks models are served; standard pybamm models ("SPM", "DFN", …) are already usable directly with pybamm.

Parameters:
  • name (str) – Ionworks model class name, e.g. "ECM", "LumpedSPMR", "MSMRFullCellModel", "GITTModel". One of the names listed under "ionworks_models" by client.pybamm_models().

  • options (dict[str, Any] | None, optional) – Options dict passed to the model constructor.

Returns:

The serialized pybamm model document.

Return type:

dict[str, Any]

Raises:

IonworksError – If the model isn’t an ionworks model, can’t be built (e.g. invalid options), or the response isn’t JSON.

download(name, *, options=None, path=None)[source]#

Download an ionworks model as a ready-to-use pybamm model.

Fetches the serialized model from the API and loads it locally with pybamm — so models defined in the licensed ionworkspipeline package (ECM, LumpedSPMR, the MSMR models, GITTModel, …) can be used with only pybamm installed, no ionworkspipeline license required.

Parameters:
  • name (str) – Ionworks model class name, e.g. "ECM", "LumpedSPMR", "MSMRFullCellModel", "GITTModel". One of the names listed under "ionworks_models" by client.pybamm_models().

  • options (dict[str, Any] | None, optional) – Options dict passed to the model constructor.

  • path (str | os.PathLike[str] | None, optional) – If given, also write the serialized model JSON to this path. The file can later be re-uploaded with upload_custom().

Returns:

The deserialized model, ready to pass to pybamm.Simulation.

Return type:

pybamm.BaseModel

Notes

Serialization captures the model’s mathematical structure (rhs, algebraic, variables, events, initial conditions) but not Python helper methods such as set_initial_state or classmethods.

When path is given, the written file may contain bare Infinity/NaN tokens (pybamm uses infinite bounds and event thresholds). Python’s json and Serialise.load_custom_model read these fine, but they are not strictly valid JSON — strict parsers (JS JSON.parse, jq, …) will reject the file.

update(model_id, data=None)[source]#

Update an existing model.

Parameters:
  • model_id (str) – The ID of the model to update.

  • data (dict[str, Any]) – Dictionary containing the fields to update. Supports name, description, pybamm_version, and simulation_settings (a SimulationSettings object or its config dict; send null to clear the persisted settings).

Returns:

The updated model object.

Return type:

Model

delete(model_id)[source]#

Delete a model by ID.

Parameters:

model_id (str) – The ID of the model to delete.

Return type:

None

add_custom_variable(model_id, data=None)[source]#

Add a custom variable to a model.

Parameters:
  • model_id (str) – The ID of the model to add the custom variable to.

  • data (dict[str, Any]) – Dictionary containing the custom variable data. Required fields: name, expression.

Returns:

The updated model object (includes config with the new variable).

Return type:

Model