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.api.custom_model.ModelChemistry¶
Allowed values for the
chemistryfield on uploaded custom models. Mirrors theModelChemistryLiteral on the backend.alias of
Literal[‘lithium_ion’, ‘lithium_sulfur’, ‘ecm’, ‘generic’]
- class ionworks.api.custom_model.ZooImport(model: Model, parameterized_model: ParameterizedModel)[source]¶
Bases:
NamedTupleThe records
ModelClient.create_from_zoo()creates.- parameterized_model: ParameterizedModel¶
Alias for field number 1
- class ionworks.api.custom_model.ModelClient(client: Any)[source]¶
Bases:
objectClient 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.
- __init__(client: Any) None[source]¶
Initialize the ModelClient.
- Parameters:
client (Any) – The HTTP client instance for making API requests.
- get_simulation_settings(model_id: str) dict[str, Any][source]¶
Return a model’s persisted simulation settings, ready to fold into a fit.
Fits do not apply a model’s saved mesh and solver automatically, as simulations do; merge these into the objective’s
options["simulation_kwargs"]. For a parameterized model, readclient.parameterized_model.get(pm_id).simulation_settings, which takes precedence over the base model’s.- Parameters:
model_id (str) – The ID of the (base) model.
- Returns:
The flat
simulation_settingsbag (var_pts/submesh_types/spatial_methods/solver), or an empty dict if the model has none persisted.- Return type:
Examples
>>> sim_kwargs = client.model.get_simulation_settings(model_id) >>> objective = iw.pipeline.objectives.CurrentDriven( ... data_input="…", ... options={"model": {"type": "SPMe"}, "simulation_kwargs": sim_kwargs}, ... )
- list(limit: int | None = None, offset: int | None = None, *, project_id: str | None = None, name: str | None = None, name_exact: str | None = None, created_by_email: str | None = None, created_after: str | None = None, created_before: str | None = None, updated_after: str | None = None, updated_before: str | None = None, order_by: str | None = None, order: str | None = None) PaginatedList[Model][source]¶
List a project’s 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.
project_id (str | None, optional) – Project whose models to list. Defaults to the client’s project (
IONWORKS_PROJECT_ID).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:
- Raises:
ValueError – If no
project_idis given and the client has no default.
- create(data: dict[str, Any] | None = None) Model[source]¶
Create a new model in a project.
- Parameters:
Dictionary containing the model data. Required fields:
name,config. Optional fields:project_id(defaults to the client’s project),description,pybamm_version,simulation_settings.configmay be a{"type": ...}dict or a built-inpybamm.BaseModelinstance (e.g.pybamm.lithium_ion.SPMe()), which is serialized for you the same wayionworks.pipelineaccepts a pybamm model as a fit’s model. Custom pybamm models go throughupload_custom()instead.simulation_settingsis 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 as iw import pybamm settings = iw.pipeline.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
SimulationSettingsobject is serialized for you; an already-serialized configdict(settings.to_config()) is equally accepted.- Returns:
The newly created model object.
- Return type:
- Raises:
ValueError – If
datahas noproject_idand the client has no default.
- upload_custom(model: Any, *, name: str, chemistry: Literal['lithium_ion', 'lithium_sulfur', 'ecm', 'generic'] = 'lithium_ion', description: str | None = None, project_id: str | None = None) Model[source]¶
Upload a custom PyBaMM model into a project.
Serialises a
pybamm.BaseModelsubclass instance (or accepts an already-serialised JSON file) and POSTs it to/models/upload-customas multipart form data.- Parameters:
model (pybamm.BaseModel | str | os.PathLike | IO[bytes]) – The model to upload. Either a
pybamm.BaseModelinstance (will be serialised viaSerialise().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.
project_id (str | None, optional) – Project to upload into. Defaults to the client’s project (
IONWORKS_PROJECT_ID).
- Returns:
The created model record (
is_custom_model=True).- Return type:
- Raises:
IonworksError – On any HTTP error from the upload endpoint.
ValueError – If no
project_idis given and the client has no default.
Notes
Serialise().serialise_custom_model(model)returns a dict that containsEventTypeenums which aren’t JSON-serialisable. When apybamm.BaseModelis passed in, this method routes throughsave_custom_model(filename=...)(which handles the enum conversion) via a temp file that is unlinked after upload.
- create_from_zoo(name: str, *, cell_spec_id: str | None = None, options: dict[str, Any] | None = None, model_kwargs: dict[str, Any] | None = None, parameter_values: Any = None, model_name: str | None = None, parameterized_model_name: str | None = None, description: str | None = None, chemistry: Literal['lithium_ion', 'lithium_sulfur', 'ecm', 'generic'] = 'lithium_ion', project_id: str | None = None) ZooImport[source]¶
Create a model and a parameterized model from the PyBaMM model zoo.
Builds the zoo model locally, uploads it as a custom model (see
upload_custom()), then creates a parameterized model for it, undercell_spec_idor in the project. The zoo is not a dependency of this package; install it withpip install pybamm-model-zoo, plus the model’szoo-<slug>extra if it has one. Under a cell specification, the backend overrides the parameterized model’s nominal capacity, voltage cut-offs, and current with the specification’s values.- Parameters:
name (str) – Registered zoo model name, one of
pybamm_model_zoo.list_models()(e.g."LinearisedSPM").cell_spec_id (str | None, optional) – Cell specification the parameterized model belongs to, in the same project as the model. Defaults to None: the parameterized model has no cell specification and keeps the parameter set’s capacity and cut-offs.
options (dict[str, Any] | None, optional) – Model options passed to the zoo model’s constructor.
model_kwargs (dict[str, Any] | None, optional) – Other constructor arguments for zoo models that take them, e.g.
{"num_physical_layers": 4}forMultiLayer3DThermalSPM. Seehelp(pybamm_model_zoo.load(name))for a model’s arguments.parameter_values (pybamm.ParameterValues | str | dict | None, optional) – Parameters for the parameterized model: a
pybamm.ParameterValues, the name of a pybamm parameter set (e.g."Chen2020"), or an already-serialized parameters dict. Defaults to the zoo model’sdefault_parameter_values. A named set orParameterValuesis passed through the model’sapply_stack_scaling, for zoo models that have one, to add the model’s own parameters; a dict is sent as is.model_name (str | None, optional) – Display name for the model. Defaults to the zoo model’s name.
parameterized_model_name (str | None, optional) – Display name for the parameterized model. Defaults to
model_name.description (str | None, optional) – Description for both records. Defaults to the zoo entry’s summary.
chemistry (ModelChemistry, optional) – Chemistry tag for the uploaded model, as for
upload_custom(). Defaults to"lithium_ion".project_id (str | None, optional) – Project to create the model in. Defaults to the client’s project (
IONWORKS_PROJECT_ID).
- Returns:
The created
modelandparameterized_model.- Return type:
- Raises:
ImportError – If
pybamm-model-zoois not installed.KeyError – If
nameis not a registered zoo model.pybamm_model_zoo.ModelUnavailableError – If the model’s
zoo-<slug>extra is not installed.pybamm_model_zoo.ManifestError – If the zoo entry’s manifest is malformed.
ValueError – If no
project_idis given and the client has no default.IonworksError – If either record cannot be created. When the server rejects the parameterized model (a 4xx), the uploaded model is deleted again, so a retry does not duplicate it. On any other failure the outcome is unknown, so the model is kept and the error notes its id.
Examples
>>> zoo = client.model.create_from_zoo( ... "LinearisedSPM", cell_spec_id=spec.id, parameter_values="Chen2020" ... )
- serialize(name: str, *, options: dict[str, Any] | None = None) dict[str, Any][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 pybammSerialisedocument. This is the raw counterpart todownload(): it returns the serialized dict without loading it, which is handy for saving to disk or re-uploading viaupload_custom().The server builds the model — defined in the licensed
ionworkspipelinepackage — so the caller does not need anionworkspipelinelicense. Only ionworks models are served; standard pybamm models ("SPM","DFN", …) are already usable directly withpybamm.- Parameters:
- Returns:
The serialized pybamm model document.
- Return type:
- 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: str, *, options: dict[str, Any] | None = None, path: str | PathLike[str] | None = None) Any[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 licensedionworkspipelinepackage (ECM,LumpedSPMR, the MSMR models,GITTModel, …) can be used with onlypybamminstalled, noionworkspipelinelicense required.- Parameters:
name (str) – Ionworks model class name, e.g.
"ECM","LumpedSPMR","MSMRFullCellModel","GITTModel". One of the names listed under"ionworks_models"byclient.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_stateor classmethods.When
pathis given, the written file may contain bareInfinity/NaNtokens (pybamm uses infinite bounds and event thresholds). Python’sjsonandSerialise.load_custom_modelread these fine, but they are not strictly valid JSON — strict parsers (JSJSON.parse,jq, …) will reject the file.
- update(model_id: str, data: dict[str, Any] | None = None) Model[source]¶
Update an existing model.
- Parameters:
- Returns:
The updated model object.
- Return type:
- delete(model_id: str) None[source]¶
Delete a model by ID.
- Parameters:
model_id (str) – The ID of the model to delete.