Python API

Run UCP simulations and submit parameterization pipelines programmatically with the ionworks Python client

The ionworks Python package lets you run simulations and submit parameterization pipelines programmatically. For installation and authentication, see the Python API client page.

To save, validate, parse, or convert the protocols you run here, see the Protocol API page.

Running simulations

Use client.simulation to run simulations. A simulation requires a parameterized model and a protocol in UCP format.

Single simulation

response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": """
global:
  initial_soc: 1
  temperature: 25
steps:
  - Discharge:
      mode: C-rate
      value: 1
      ends:
        - "Voltage < 2.5"
""",
        "name": "1C Discharge",
    },
})

print(f"Simulation ID: {response.simulation_id}")
print(f"Job ID: {response.job_id}")

You can also pass experiment parameters and design parameters:

response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": """
global:
  initial_soc: input["Initial SOC"]
steps:
  - Discharge:
      mode: C-rate
      value: input["C-rate"]
      ends:
        - "Voltage < 2.5"
""",
        "name": "Parameterized Discharge",
    },
    "experiment_parameters": {
        "Initial SOC": 1.0,
        "C-rate": 0.5,
    },
    "design_parameters": {
        "Positive electrode thickness [m]": 75e-6,
    },
})

design_parameters is a single-simulation convenience field on protocol(). Pass a flat dict of parameter overrides, each a number or a table for a function-valued parameter. Use it when you want to vary one or more design parameters for a single run without writing out the full DOE schema.

In protocol(), design_parameters and design_parameters_doe are mutually exclusive, and any DOE you supply must resolve to exactly one simulation. Passing both, or a DOE that would expand to multiple simulations, raises ValueError — use protocol_batch for multi-simulation sweeps instead.

For a model with hysteresis, experiment_parameters also accepts "Initial hysteresis state": the cell's hysteresis history at the start of the run, from -1 (after a discharge) through 0 (average) to 1 (after a charge). It is rejected for a model without hysteresis.

Function-valued parameters

A parameter that is a function, such as electrolyte conductivity, can be overridden with a lookup table of x and y values. The table replaces the function with an interpolant in its first input, and the other inputs are ignored: a table of conductivity against concentration replaces a function of concentration and temperature.

"design_parameters": {
    "Electrolyte conductivity [S.m-1]": {
        "x": [0.0, 1000.0, 2000.0],  # concentration [mol.m-3]
        "y": [0.2, 1.0, 0.6],
        "interpolator": "linear",  # or "cubic", "pchip"
    },
},

x must be strictly increasing, with at least two points and one y per x. interpolator defaults to "linear". Tables work in protocol() and in the conditions of protocol_batch().

To run a protocol you have already saved, pass protocol_id in place of protocol_experiment — exactly one of the two. project_id is then optional and defaults to the saved protocol's own project:

response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_id": "your-protocol-id",
})

Config keys are checked before anything is sent. A misspelt or misplaced key raises a ValueError naming it and listing the valid top-level keys, rather than being ignored.

Storing only output variables

By default a run stores the solver's full state, so any model variable can be computed from it later. For large batches, long degradation runs or 3D models that state is large. Set outputs_only to store only the variables the run outputs: voltage, current, power and temperature, the names in extra_variables, and the variables the protocol's metrics read.

response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_id": "your-protocol-id",
    "extra_variables": ["Battery open-circuit voltage [V]"],
    "outputs_only": True,
})

A variable the run did not keep cannot be read from it afterwards: asking for one raises an error that lists the variables it kept. Run again with the variable added to extra_variables to get it. Values between stored points are interpolated linearly in time.

Running at an operating limit

Pass operating_limit to run the protocol at the limit of one of its inputs, instead of at a given value. The limit is found by bisection and reported in the simulation's metrics, and the stored results are the run at the limit.

For peak power, the protocol's pulse step reads input["Power [W]"]; earlier steps set the state it starts from:

response = client.simulation.protocol({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": """
global:
  initial_state_type: soc_percentage
  initial_state_value: 100
steps:
  - Discharge: {mode: C-rate, value: 1, duration: 1800}
  - Discharge: {mode: Power, value: 'input["Power [W]"]', duration: 10}
""",
        "name": "Peak power",
    },
    "operating_limit": {"kind": "peak_power"},
})
client.simulation.wait_for_completion(response.simulation_id)
peak = client.simulation.get_result(response.simulation_id).metrics["Peak power [W]"]

peak_power also takes voltage_limit (defaults to the protocol's own safety limit, else the model's cut-off), direction ("Discharge" or "Charge") and bounds (defaults to 1/100 to 100 times the cell's 1C power).

For any other input, give the range to search, what to optimize, and the bounds the run must stay within. The longest cruise that still stays above 3.0 V:

"operating_limit": {
    "kind": "operating_limit",
    "input": "Cruise time [s]",  # read as input["Cruise time [s]"]
    "bounds": [1, 7200],
    "objective": {"action": "Maximize", "variable": "Time [s]"},
    "constraints": [{"variable": "Voltage [V]", "min": 3.0}],
    "name": "Max cruise [s]",
},

The typed forms are iw.api.PeakPowerSpec and iw.api.OperatingLimitSpec (with LimitObjective and LimitConstraint).

The bounds must bracket the limit: one feasible, the other not. When both are feasible, metrics["Operating limit status"] is "beyond bounds" and the run is at the bound with the better objective; when neither is, the simulation fails with a configuration error. A value given for the searched input in experiment_parameters is ignored.

Waiting for results

Use wait_for_completion to poll until the simulation finishes. The method detects failed and canceled jobs immediately rather than waiting for the timeout.

result = client.simulation.wait_for_completion(
    response.simulation_id,
    timeout=120,        # seconds (default: 60)
    poll_interval=2,    # seconds between polls (default: 2)
    verbose=True,       # print status updates (default: True)
)

When a simulation fails or is canceled, the IonworksError it raises has error_code "JOB_FAILED", and its data["detail"] carries the failure's job_error_code and job_error to branch on; see Failed jobs.

Set raise_on_failure=False to get the result dict instead of raising an exception when a simulation fails:

result = client.simulation.wait_for_completion(
    response.simulation_id,
    raise_on_failure=False,
)

Batch simulations with design of experiments

Run multiple simulations across a parameter sweep using protocol_batch:

responses = client.simulation.protocol_batch({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_experiment": {
        "protocol": "...",
        "name": "C-rate Sweep",
    },
    "design_parameters_doe": {
        "sampling": "grid",
        "rows": [
            {
                "type": "discrete",
                "name": "Positive electrode thickness [m]",
                "values": [50e-6, 75e-6, 100e-6],
            },
        ],
    },
})

# Wait for all simulations
results = client.simulation.wait_for_completion(
    [r.simulation_id for r in responses],
    timeout=300,
)

Supported DOE row types:

TypeFieldsDescription
discretevaluesSpecific values to test
rangemin, max, countEvenly spaced values between min and max
normalmean, std, countValues sampled around the mean

Sampling strategies: grid (all combinations), random, latin_hypercube.

Explicit list of runs

When the runs are not a sampled design, list them with conditions instead of design_parameters_doe. Each condition is one simulation with its own experiment_parameters and design_parameters; nothing is crossed. A top-level experiment_parameters is a shared default that each condition can override. conditions and design_parameters_doe cannot be combined.

responses = client.simulation.protocol_batch({
    "parameterized_model": "your-parameterized-model-id",
    "protocol_id": "your-protocol-id",
    "experiment_parameters": {"Initial SOC [%]": 100},
    "conditions": [
        {"experiment_parameters": {"Temperature [°C]": 10}},
        {
            "experiment_parameters": {"Temperature [°C]": 40},
            "design_parameters": {"Negative electrode porosity": 0.35},
        },
    ],
})

Checking many simulations at once

get_statuses returns the status of many simulations in one request per 100 ids, which is cheaper than calling get() per id. Unknown ids are omitted from the result.

statuses = client.simulation.get_statuses([r.simulation_id for r in responses])
for s in statuses:
    print(s["simulation_id"], s["status"])

Retrieving simulation data

# List simulations, newest first
simulations = client.simulation.list()

# Get a specific simulation
simulation = client.simulation.get(simulation_id)

# Get result data (time series, steps, metrics)
result = client.simulation.get_result(simulation_id)

list() scopes by parameterized_model_id or study_id (not both), and protocol_id narrows either to one saved protocol (or scopes by protocol alone), so all runs of one model on one protocol are a single request. state keeps only queued, running, completed or failed runs, and summary=True leaves out each run's metrics. With limit or offset, list() returns a page whose .total counts every match. Each run carries protocol_id and protocol_name.

page = client.simulation.list(
    parameterized_model_id="your-parameterized-model-id",
    protocol_id="your-protocol-id",
    state="completed",
    summary=True,
    limit=100,
)
print(page.total)

You don't need to check for an existing run before starting one. Submitting a simulation identical to an existing one (same model, protocol, inputs, design and options), finished or still running, returns that run with already_existed=True instead of starting a new one.

run = client.simulation.protocol(config)
if run.already_existed:
    print("Reusing", run.simulation_id)

To solve it again anyway, add "force_rerun": True to the config. The existing simulation restarts in place under the same id, and its earlier result is replaced when the new run finishes.

get_result returns a typed SimulationResult dataclass with three fields:

FieldTypeDescription
result.time_seriesDataFrameOne row per time point; columns are signal names (e.g. "Time [s]", "Voltage [V]", "Current [A]").
result.stepsDataFrameOne row per protocol step (e.g. "Step count", "Step type", "Duration [s]").
result.metricsdict[str, Any]Scalar metrics computed over the run (e.g. cycle-level summaries).

To read only the step summary, get_steps skips the time series, which is far larger:

steps = client.simulation.get_steps(simulation_id)

It returns the same frame as result.steps, and raises a 404 until the run has completed.

time_series and steps are returned as polars DataFrames by default. Call set_dataframe_backend("pandas") once at session start to receive pandas DataFrames instead.

import ionworks as iw

client = iw.api.Client()
simulation_id = "your-simulation-id"  # e.g. response.simulation_id from a submitted run
result = client.simulation.get_result(simulation_id)

# Plot voltage vs time. With the default polars backend, convert to pandas first;
# with the pandas backend (set_dataframe_backend("pandas")), use result.time_series directly.
ts = result.time_series.to_pandas()  # drop .to_pandas() on the pandas backend
ts.plot(x="Time [s]", y="Voltage [V]")

# Inspect protocol steps
print(result.steps)

# Read scalar metrics
print(result.metrics)

Discharge capacity [A.h] and Charge capacity [A.h] in time_series reset to 0 at each step boundary. Use "Step count" to join time_series to steps, or accumulate per-step end values if you need a continuous cumulative capacity trace.

Deleting a simulation

client.simulation.delete("your-simulation-id")

Running PyBaMM simulations

import ionworks.pybamm as pybamm is PyBaMM with Simulation.solve running on Ionworks. Each solve is an ordinary simulation in your project, and returns a RemoteSolution you read like a pybamm.Solution:

import ionworks.pybamm as pybamm

model = pybamm.lithium_ion.SPM()
sim = pybamm.Simulation(model, parameter_values=pybamm.ParameterValues("Chen2020"))
sol = sim.solve([0, 3600], initial_soc=1)

sol["Voltage [V]"].entries
sim.plot()

solve prints the run's link in the web app, which sol.url also holds. It returns at once; the first read of a variable waits for the run, up to 10 minutes by default. A read that times out raises TimeoutError, but the run keeps going: read again to keep waiting, or set sol.timeout = 6 * 3600 first to wait longer. pybamm.configure(timeout=...) sets the wait for later solves.

Interrupting a read stops only the wait. sol.cancel() stops the run itself; it returns False if the run had already finished. A run that fails because the solver did raises pybamm.SolverError on its first read, so except pybamm.SolverError works as it does locally.

Lithium-ion models (except Basic3DThermalSPM) and plain solves of an unedited pybamm.equivalent_circuit.Thevenin run on Ionworks. Basic3DThermalSPM, lead-acid and sodium-ion models, an ECM with an experiment, custom and resistance steps, and Simulation.step raise NotImplementedError before anything is sent; run those locally with pybamm.configure(local=True).

To collect a run later, in another session, run the same script again: an identical run is reused, so solve returns the earlier run instead of solving it again. Or keep sol.simulation_id and read it with the client: client.simulation.solution("your-simulation-id").

Spatial variables read as they do locally. entries has pybamm's axis order, space then time (r, x, then time for a particle concentration), and calling the variable interpolates in time and space as pybamm does. sim.plot(), sol.plot(), pybamm.dynamic_plot(sol) and pybamm.QuickPlot(sol) draw them with pybamm's own plot, time slider included:

c_e = sol["Electrolyte concentration [mol.m-3]"]
c_e.entries.shape  # (points in x, len(sol.t))
c_e(t=1800, x=c_e.first_dim_pts)

c_s = sol["Negative particle concentration [mol.m-3]"]
c_s(t=1800, r=5e-6, x=c_s.second_dim_pts)

sol.plot(["Voltage [V]", "Electrolyte concentration [mol.m-3]"])

Each solution, cycle or step reads a spatial variable at its own stored times, the solver's values there, on first use; rows already read are kept. One read holds up to 10 million values (about 25,000 stored times of a 20 x 20 particle concentration, 165,000 of a 60-point electrolyte concentration). Past that, the read takes each step's first and last time and a spread between, warns, and its t_pts and entries are at those times rather than the solution's t; read a cycle or step (sol.cycles[-1][name]) to get every stored time of it. Between stored times values are interpolated linearly, where pybamm interpolates cubically. Variables on a 2D or 3D current-collector or unstructured mesh are not served.

A sweep keeps pybamm's shape. Pass a list of inputs and solve returns one solution per dict, sent to Ionworks as one batch request; pybamm.BatchStudy takes pybamm.BatchStudy's arguments and submits every run at once:

name = "Negative particle diffusivity [m2.s-1]"
params = pybamm.ParameterValues("Chen2020")
params[name] = "[input]"
sim = pybamm.Simulation(model, parameter_values=params)

sols = sim.solve(
    [0, 3600], initial_soc=1, inputs=[{name: d} for d in (1e-14, 3.3e-14, 1e-13)]
)

Runs batch into one request only when they share a model, parameters and protocol. An input that sets the current changes the protocol, so sweep model parameters as inputs, and give each rate its own pybamm.Experiment.

Drive cycles run as they do locally: a current or power profile step such as pybamm.step.current(np.column_stack([t, I])) in an experiment, or a plain solve under an interpolated "Current function [A]".

Experiment terminations on time ("10 hours", except alongside a profile step) and voltage ("2.5 V") run as they do locally, as do step temperatures (temperature="45oC") and scheduled steps (start_time). Capacity terminations ("80% capacity", "4 Ah capacity") are not supported: PyBaMM checks them after each cycle against that cycle's eSOH capacity, which Ionworks cannot reproduce.

Without initial_soc, a remote solve starts from the parameter set's initial concentrations, as pybamm does; pass initial_soc when no SOC reproduces them (e.g. composite electrode phases out of equilibrium). direction sets the starting hysteresis branch as in pybamm.

With an experiment, the solution splits by cycle as pybamm's does: sol.cycles[i].steps[j] is step j of cycle i, sol.summary_variables holds the per-cycle summary (with eSOH variables when pybamm would compute them; calc_esoh works as in pybamm), and solve(..., save_at_cycles=...) keeps the same cycles as in pybamm.

Recording intervals (period) work as in pybamm, including a different period on each step, except in an experiment with scheduled steps. Each step is reported at pybamm's times; values between the server's points are interpolated within the step, so they are close to a local solve rather than equal to it.

An identical run in the project is reused rather than solved again. pybamm.configure(force_rerun=True) solves every later run again, until you set it back to False.

pybamm.configure(study="Rate sweep") adds every later run, sweeps and BatchStudy included, to that study, creating it if the project has none by that name. A reused run joins the study too and stays in any study it was already in.

A run stores its outputs, not the solver's states: voltage, current, power, temperature, the capacity, energy and step columns, the variables sim.plot() draws and, with an experiment, what sol.summary_variables reads. List any other variable on the solver, as in PyBaMM, with pybamm.IDAKLUSolver(output_variables=[...]); reading one that was not kept raises KeyError. pybamm.configure(outputs_only=False) stores the states instead.

A remote solve needs the same pybamm year.month release Ionworks runs (for example 26.11; any patch of it works). Set IONWORKS_PYBAMM_LOCAL=1 to solve locally instead. See the ionworks.pybamm reference for batches, client.simulation.submit and what is supported.

For complete scripts, see the PyBaMM examples: rate capability, a rate capability design sweep, pulse resistance, cycle ageing, a degradation parameter sweep and a 3D pouch cell.

Running pipelines

Pipelines have moved to their own page. See the Pipelines API how-to for submitting pipelines, polling them, reading results, and managing submissions.

Managing studies

Use client.study to create, list, update, and delete studies. Studies are scoped to a project.

All client.study.* methods accept project_id as an optional keyword argument. When omitted, they use the default project configured on the client (or resolved from IONWORKS_PROJECT_ID). Pass project_id= explicitly to override on a per-call basis.

Listing studies

# Uses the default project from the client
studies = client.study.list()
for study in studies:
    print(f"{study.name} (ID: {study.id})")

# Filter by name
studies = client.study.list(name="Discharge")

# Paginate results
studies = client.study.list(limit=10, offset=0)

# Override the project for a single call
studies = client.study.list(project_id="other-project-id")

Supported filters: name, name_exact, order_by, order.

Getting a study

study = client.study.get("your-study-id")

Creating a study

study = client.study.create({
    "name": "1C Discharge Sweep",
    "description": "Comparing discharge curves across temperatures",
})

Updating a study

study = client.study.update("your-study-id", {
    "name": "1C Discharge Sweep v2",
})

Assigning simulations and measurements

# Assign a simulation to a study
client.study.assign_simulation("your-study-id", "simulation-id")

# Remove a simulation from a study
client.study.remove_simulation("your-study-id", "simulation-id")

# Assign a measurement to a study
client.study.assign_measurement("your-study-id", "measurement-id")

# List measurements in a study
measurements = client.study.list_measurements("your-study-id")

# Remove a measurement from a study
client.study.remove_measurement("your-study-id", "measurement-id")

Deleting a study

client.study.delete("your-study-id")

You can find the ID for any resource from the Ionworks Studio web app. The ID is displayed in the URL when you navigate to a resource's detail page.

Next steps

On this page