High level interface
Input types
BattMo.AbstractInput Type
AbstractInputAbstract type for all parameter sets that can be given as an input to BattMo.
For any structure of this type, it is possible to access and set the values of the object using the same syntax as a standard Julia dictionary.
sourceBattMo.CyclingProtocol Type
Parameter set type that represents the cycling protocol related parameters
sourceBattMo.SimulationSettings Type
Parameter set type that represents the simulation related settings
sourceRead input
BattMo.load_cell_parameters Function
load_cell_parameters(; from_file_path::String = nothing, from_default_set::String = nothing, from_model_template::ModelConfigured = nothing)Reads and loads cell parameters either from a JSON file, a default set, or a model template.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing cell parameters.from_default_set ::String: (Optional) The name of the default set to load cell parameters from.from_model_template ::ModelConfigured: (Optional) AModelConfiguredinstance used to load an empty set of cell parameters required for the concerning model.
Returns
An instance of CellParameters.
Errors
Throws an ArgumentError if none of the arguments are provided.
BattMo.load_cycling_protocol Function
load_cycling_protocol(; from_file_path::String = nothing, from_default_set::String = nothing)Reads and loads cycling protocol either from a JSON file or a default set.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing cycling protocol.from_default_set ::String: (Optional) The name of the default set to load cycling protocol from.
Returns
An instance of CyclingProtocol.
Errors
Throws an ArgumentError if neither from_file_path nor from_default_set is provided.
BattMo.load_model_settings Function
load_model_settings(; from_file_path::String = nothing, from_default_set::String = nothing)Reads and loads model settings either from a JSON file or a default set.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing model settings.from_default_set ::String: (Optional) The name of the default set to load model settings from.
Returns
An instance of ModelSettings.
Errors
Throws an ArgumentError if neither from_file_path nor from_default_set is provided.
BattMo.load_simulation_settings Function
load_simulation_settings(; from_file_path::String = nothing, from_default_set::String = nothing, from_model_template::ModelConfigured = nothing)Reads and loads simulation settings either from a JSON file, a default set, or a model template.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing simulation settings.from_default_set ::String: (Optional) The name of the default set to load simulation settings from.from_model_template ::ModelConfigured: (Optional) AModelConfiguredinstance used to load an empty set of simulation settings required for the concerning model.
Returns
An instance of SimulationSettings.
Errors
Throws an ArgumentError if none of the arguments are provided.
BattMo.load_solver_settings Function
load_solver_settings(; from_file_path::String = nothing, from_default_set::String = nothing)Reads and loads solver settings either from a JSON file or a default set.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing solver settings.from_default_set ::String: (Optional) The name of the default set to load solver settings from.
Returns
An instance of SolverSettings.
Errors
Throws an ArgumentError if none of the arguments are provided.
BattMo.load_full_simulation_input Function
load_full_simulation_input(; from_file_path::String = nothing, from_default_set::String = nothing)Reads and loads a full simulation input either from a JSON file or a default set. A full simulation input should contain cell parameters, cycling protocol, model settings, the base model, simulation settings, and optionally solver settings.
Arguments
from_file_path ::String: (Optional) Path to the JSON file containing the full simulation input.from_default_set ::String: (Optional) The name of the default set to load the full simulation input from.
Returns
An instance of FullSimulationInput.
Errors
Throws an ArgumentError if none of the arguments are provided.
Model types
BattMo.ModelConfigured Type
abstract type ModelConfiguredAbstract type representing a model. All models should inherit from this type.
sourceBattMo.LithiumIonBattery Type
struct LithiumIonBattery <: BatteryRepresents a lithium-ion battery model based on the Doyle-Fuller-Newman approach.
Fields
name ::String: A descriptive name for the model.model_settings ::ModelSettings: Settings specific to the model.
Constructor
LithiumIonBattery(; model_settings = get_default_model_settings(LithiumIonBattery))Creates an instance of LithiumIonBattery with the specified or default model settings. The model name is automatically generated based on the model geometry.
BattMo.SodiumIonBattery Type
struct SodiumIonBattery <: BatteryRepresents a lithium-ion battery model based on the Doyle-Fuller-Newman approach.
Fields
name ::String: A descriptive name for the model.model_settings ::ModelSettings: Settings specific to the model.
Constructor
SodiumIonBattery(; model_settings = get_default_model_settings(SodiumIonBattery))Creates an instance of SodiumIonBattery with the specified or default model settings. The model name is automatically generated based on the model geometry.
Forward simulation
BattMo.Simulation Type
Simulation(model::ModelConfigured, cell_parameters::CellParameters, cycling_protocol::CyclingProtocol; simulation_settings::SimulationSettings = get_default_simulation_settings(model))Constructs a Simulation object that sets up and validates all necessary components for simulating a battery model.
Arguments
model::ModelConfigured: A fully configured model object that includes the physical and numerical setup.cell_parameters::CellParameters: Parameters defining the physical characteristics of the battery cell.cycling_protocol::CyclingProtocol: The protocol specifying the charging/discharging cycles for the simulation.simulation_settings::SimulationSettings(optional): Configuration settings controlling solver behavior, time stepping, etc. If not provided, default settings are generated based on the model.
Behavior
Validates
model,cell_parameters,cycling_protocol, andsimulation_settings.Sets up default solver options if not explicitly defined.
Initializes computational grids and couplings.
Configures the physical model and parameters.
Prepares the initial simulation state and external forcing functions.
Instantiates a
Simulatorfrom the Jutul framework with the prepared state and parameters.Defines the time-stepping strategy for the simulation.
Assembles a simulation configuration object used to control execution.
Returns
A Simulation struct instance that includes:
Validation flag (
is_valid)Prepared simulation components: model, grids, couplings, parameters, initial state, forces, time steps, and simulator instance.
Throws
- An error if
model.is_valid == false, halting construction with a helpful message.
BattMo.solve Method
solve(problem::Simulation; accept_invalid = false, hook = nothing, info_level = 0, end_report = info_level > -1, kwargs...)Solves a battery Simulation problem by executing the simulation workflow defined in solve_simulation.
Arguments
problem::Simulation: A fully constructedSimulationobject, containing all model parameters, solver settings, and initial conditions.accept_invalid::Bool(optional): Iftrue, bypasses the internal validation check on theSimulationobject. Use with caution. Default isfalse.hook(optional): A user-defined callback or observer function that can be inserted into the simulation loop.info_level::Int(optional): Controls verbosity of simulation logging and output. Default is0.end_report::Bool(optional): Whether to print a summary report after simulation. Defaults totrueifinfo_level > -1.kwargs...: Additional keyword arguments forwarded tosolve_simulation.
Behavior
Validates the
Simulationobject unlessaccept_invalidistrue.Prepares simulation configuration options, including verbosity and report behavior.
Calls
solve_simulation, passing in the simulation problem and configuration.
Returns
- The result of
solve_simulation, typically containing simulation outputs such as state trajectories, solver diagnostics, and performance metrics.
Throws
- An error if the
Simulationobject is invalid andaccept_invalidis not set totrue.
Example
sim = Simulation(model, cell_parameters, cycling_protocol)
result = solve(sim; info_level = 1)BattMo.run_simulation Function
run_simulation(simulation_input::FullSimulationInput; kwargs...)Provides a headless UI for running a simulation.
Arguments
simulation_input::FullSimulationInput: A FullSimulationInput instance containing all the parameters and settings needed to run and solve a simulation.kwargs...: Additional keyword arguments passed to the lower-level solver configuration.
Behavior
Extracts all relevant parameter sets and settings from the FullSimulationInput instance.
Instantiates a ModelConfigured using the provided model settings.
Instantiates a Simulation using the ModelConfigured, and the cell parameters, cycling protocol parameters, and simulation settings from the FullSimulationInput.
Solves the simulation by passing the Simulation instance and the solver settings from the FullSimulationInput to
BattMo.solve.
Returns
A NamedTuple containing the simulation results.
Example
simulation_input = load_full_simulation_input(;from_default_set="chen_2020")
output = run_simulation(simulation_input)
plot_dashboard(output)Plotting
BattMo.plot_dashboard Function
BattMo.plot_dashboard(output; plot_type="simple")Plot a dashboard summarizing simulation output with selectable styles.
Arguments
output: Simulation output NamedTuple.plot_type: One of"simple","line", or"contour"(default"simple").
Description
"simple": Shows time series of current and voltage."line": Adds interactive line plots of concentrations and potentials with a time slider."contour": Shows contour plots of concentrations and potentials over time and position.
Example
using GLMakie
fig = BattMo.plot_dashboard(output; plot_type="line")BattMo.plot_output Function
BattMo.plot_output(output, output_variables; layout=nothing)Plot specified variables from simulation output using GLMakie.
Arguments
output: NamedTuple with simulation data.output_variables: Vector of variable names or groups of names to plot.layout: Optional (nrows, ncols) tuple to set subplot arrangement.
Notes
Requires GLMakie to be imported beforehand.
Automatically chooses layout if none provided.
Supports line plots (1D data) and contour plots (2D data).
Displays units and metadata in labels.
Example
using GLMakie
fig = BattMo.plot_output(output,
["Voltage vs Time",
["NegativeElectrodeActiveMaterialSurfaceConcentration vs Time at Position index 1", "NegativeElectrodeActiveMaterialSurfaceConcentration vs Time at Position index 10"],
"ElectrolytePotential vs time and Position",
]; layout=(3,1))BattMo.plot_interactive_3d Function
plot_interactive_3d
Launch an interactive plot for visualizing simulation results of 3D geometries.
sourceBattMo.plot_cell_curves Function
BattMo.plot_cell_curves_impl(cell_parameters::CellParameters; new_window = true)Plot functional parameter curves from a cell parameter set.
Scans cell_parameters for known functional properties (e.g., open-circuit potential, diffusion coefficient, reaction rate constant, conductivity) and plots their dependence on concentration and temperature.
Arguments
cell_parameters::CellParameters: Cell parameter object containing model data.new_window::Bool = true: Iftrue, display the figure in a new window.
Returns
fig::Figure: A Makie figure with subplots of all detected functional parameter curves.
Notes
Only functional (non-constant) parameters are plotted.
The layout and axes are auto-scaled based on the number and type of parameters.
Tools that print extra information
BattMo.print_info Method
print_info(input::S; view = nothing) where {S <: ParameterSet}Print a formatted overview of parameters in a ParameterSet.
Lists parameter names, units, types, and values in a structured table, using available metadata for labeling and formatting.
Arguments
input::ParameterSet: Parameter set (e.g., cell, cycling, solver, or simulation settings).view::Union{Nothing, String}(optional): If provided, filters and displays only parameters whose path contains the given string.
Notes
Recursively traverses nested dictionaries within the parameter set.
Default parameters are marked as
(default).Used for quick inspection of model inputs in BattMo.
If
viewis specified, only matching parameters are shown.
BattMo.print_info Method
print_info(output::SimulationOutput)Print a structured overview of all available output variables in a simulation result.
Displays variable names, units, and shapes grouped by category (time series, metrics, and states), based on BattMo output metadata.
Arguments
output::SimulationOutput: Simulation results object to inspect.
Notes
Only variables present in the simulation output are listed.
Groups variables by case for easier browsing.
Intended for quick post-simulation inspection within BattMo.
BattMo.print_info Method
print_info(from_name::String; view::Union{Nothing, String}=nothing) -> NothingPrints information on specific parameters, settings, and output variables. Searches available metadata categories for entries matching from_name and prints detailed information about each match. The output is formatted with emojis, section headers, and aligned labels for readability.
Arguments
from_name::String: the (partial or full) name to search for in the metadata.
Keywords
view::Union{Nothing, String}=nothing: restricts the search to a specific category. Must be one of:"CellParameters","CyclingProtocol","ModelSettings","SimulationSettings","SolverSettings", or"OutputVariable". Ifnothing(default), all categories are searched.
Returns
Nothing: this function only prints formatted results to the console.
Throws
ErrorException: ifviewis provided but not one of the allowed categories.
Notes
Each matching entry prints metadata fields such as:
Name,Category,Keyword argument,Description,Type,Shape,UnitOptions,Minimum value,Maximum value,Documentation,Ontology link
Output formatting adjusts automatically depending on the detected output format.
Example
<Badge type="info" class="source-link" text="source"><a href="https://github.com/BattMoTeam/BattMo.jl/blob/980f28a5b15f15ac79b2dfd4fe5161e950b12002/src/tools/print_info.jl#L80-L114" target="_blank" rel="noreferrer">source</a></Badge>
</details>
<details class='jldocstring custom-block' open>
<summary><a id='BattMo.print_info-Tuple{AbstractCalibration}' href='#BattMo.print_info-Tuple{AbstractCalibration}'><span class="jlbinding">BattMo.print_info</span></a> <Badge type="info" class="jlObjectType jlMethod" text="Method" /></summary>
```julia
print_info(calibration::AbstractCalibration) -> NothingPrints an overview of the calibration parameters and their current values for a given calibration object. This is a convenience wrapper around print_calibration_overview, which performs the actual display.
Arguments
calibration::AbstractCalibration: the calibration object containing parameter targets and (optionally) optimized values.
Returns
Nothing: this function only prints formatted output to the console.
Notes
Delegates to
print_calibration_overviewto display:Parameter names
Initial values
Bounds
Optimized values (if available)
Percentage change from initial values
If the calibration has not been performed, only initial values and bounds are shown.
Example
<Badge type="info" class="source-link" text="source"><a href="https://github.com/BattMoTeam/BattMo.jl/blob/980f28a5b15f15ac79b2dfd4fe5161e950b12002/src/tools/print_info.jl#L49-L75" target="_blank" rel="noreferrer">source</a></Badge>
</details>
<details class='jldocstring custom-block' open>
<summary><a id='BattMo.quick_cell_check-Tuple{CellParameters}' href='#BattMo.quick_cell_check-Tuple{CellParameters}'><span class="jlbinding">BattMo.quick_cell_check</span></a> <Badge type="info" class="jlObjectType jlMethod" text="Method" /></summary>
```julia
quick_cell_check(cell::CellParameters; cell_2::Union{Nothing, CellParameters} = nothing)Print key performance indicators (KPIs) and basic properties for one or two battery cells.
Compares input and derived quantities (mass, capacity, N:P ratio, loadings, etc.) between cells and displays results in a formatted, color-coded table.
Arguments
cell::CellParameters: Primary cell to inspect.cell_2::Union{Nothing, CellParameters} = nothing: Optional second cell for comparison.
Notes
Blue values indicate input parameters, green indicate calculated values.
Displays deltas when comparing two cells.
Intended for quick text-based validation and comparison within BattMo.
BattMo.print_submodels Method
print_submodels()Prints an overview of configurable submodels available within the simulation framework, including valid options and documentation links.
Behavior
Retrieves model configuration metadata using
get_model_settings_meta_data().Filters the metadata to include only entries marked with
"is_sub_model" => true.Extracts:
The submodel parameter name
The list of valid options (or
"N/A"if not specified)A documentation link (if available)
Prints a well-formatted table summarizing each submodel, with aligned columns:
Parameter – the submodel key name (e.g.,
"electrolyte_transport")Options – available values that can be assigned to the parameter
Documentation – a URL (formatted with
format_link) or-if missing
Output
Directly prints a structured table to the console.
Uses consistent width formatting for readability.
Includes Unicode symbols and horizontal lines for visual structure.
Use Case
Helps users understand which submodels are configurable and how to select between them.
Useful for exploring model flexibility and guiding configuration in notebooks, scripts, or GUIs.
BattMo.print_default_input_sets Method
print_default_input_sets()Prints a structured overview of all available default input sets for battery simulations, including high-level summaries and detailed metadata for each set.
Behavior
Scans the
defaults/directory (located relative to the script file) for available JSON input sets organized by category (subfolders).Prints:
📋 A concise aligned list of categories and their corresponding default set names.
📖 A detailed description for each default set, including:
- Cell name and case
- Source (with optional formatted link)
- Supported models
- Set description- Metadata is extracted using helper functions such as
read_meta_dataandread_source_from_meta_data, which pull structured data (e.g., description, model support) from the JSON files.
Output
Prints directly to the console using
println, formatted for clarity with Unicode symbols and horizontal dividers.Output includes:
Folder/category names (e.g.,
CellParameters")Available JSON set names (e.g.,
"chen_2020")Descriptions and intended use cases for each set
Use Case
Helps users quickly understand what predefined inputs are available for simulation without needing to inspect the files manually.
Useful for educational purposes, rapid prototyping, or configuration setup.
Notes
Only
.jsonfiles are considered valid input sets.Requires that the
defaults/directory structure and expected metadata fields are present and correctly formatted.
Tools that write files
BattMo.generate_default_parameter_files Function
generate_default_parameter_files()
generate_default_parameter_files("/some/path", force = true)
generate_default_parameter_files("/some/path", name = "my_json_files")Make a local copy of the default JSON parameter files in the specified directory. The default name is "battmo_json". If the directory already exists, an error is thrown unless force is set to true. The default path is the current working directory.
BattMo.write_to_json_file Function
write_to_json_file(file_path::String, data::AbstractInput)Writes the contents of data to a JSON file at the specified file_path.
Arguments
file_path::String: The path (including filename) where the JSON file will be saved.data::AbstractInput: An object containing the data to serialize. The function accesses the.allfield/property ofdatato retrieve the content to write.
Behavior
Opens the file at
file_pathin write mode.Serializes the
data.allobject to JSON format with indentation of 4 spaces.Writes the JSON data to the file.
Prints a success message upon completion.
If an error occurs (e.g., file system permission issues), catches the exception and prints an error message.
Returns
- Nothing (side-effect only: writes file and prints status messages).
Example
write_to_json_file("output/config.json", sim_input)Voltage Calibration
BattMo.VoltageCalibration Type
mutable struct VoltageCalibration <: AbstractCalibrationRepresents a voltage calibration problem for a battery simulation.
Fields
t::AnyTime vector corresponding to the calibration voltage data points.v::AnyVoltage vector containing calibration voltage data.sim::AnyA deep copy of theSimulationobject used for calibration, allowing reuse of the original simulation.parameter_targets::AnyDictionary mapping parameter name vectors (keys) to tuples(initial_value, lower_bound, upper_bound)specifying calibration targets.calibrated_cell_parameters::AnyHolds the cell parameters obtained after calibration is solved.history::AnyStores the optimization process history, including iteration details and convergence info.
Constructors
VoltageCalibration(t, v, sim)Creates a new calibration object from time vectort, voltage vectorv, and a simulationsim. Ensures time vectortis strictly increasing and matches length ofv.VoltageCalibration(t_and_v, sim; normalize_time = false)Alternative constructor that takes a 2D arrayt_and_vwhere the first column is time and the second is voltage. Optionally normalizes the time vector to start at zero ifnormalize_timeis true.
Example
t = [0.0, 10.0, 20.0, 30.0]
v = [3.7, 3.6, 3.5, 3.4]
sim = Simulation(...)
calib = VoltageCalibration(t, v, sim)
# or with combined data
data = [0.0 3.7; 10.0 3.6; 20.0 3.5; 30.0 3.4]
calib2 = VoltageCalibration(data, sim, normalize_time=true)BattMo.solve Method
solve(vc::AbstractCalibration; kwargs...) -> (calibrated_parameters, history)Solve the calibration problem by optimizing model parameters to fit target data.
Description
Performs parameter calibration for a model using the LBFGS optimizer (or a user-supplied optimizer). The method minimizes an objective function derived from the discrepancy between simulation output and calibration targets.
Keyword Arguments
grad_tol: Gradient norm stopping tolerance (default:1e-6)obj_change_tol: Objective change tolerance (default:1e-6)opt_fun: Optional custom optimization functionbackend_arg: Tuple controlling sparsity and preprocessing (default settings shown in source)Other keyword arguments are passed to the optimizer.
Returns
A tuple (calibrated_cell_parameters, optimization_history).
Example
calibrated_params, history = solve(vc; grad_tol = 1e-7)BattMo.free_calibration_parameter! Function
free_calibration_parameter!(vc::AbstractCalibration, parameter_name::Vector{String};
initial_value = missing,
lower_bound = missing,
upper_bound = missing
)Set a calibration parameter to be free for optimization. The parameter is specified by parameter_name, which is a vector of strings representing the nested structure of the parameter in the simulation's cell parameters.
Notes
The
initial_valueis optional and can be set tomissingif not provided.The
lower_boundandupper_boundmust be provided and cannot bemissing.
BattMo.print_calibration_overview Function
print_calibration_overview(vc::AbstractCalibration)Print an overview of the calibration parameters and their current values. If the calibration has been performed, the table will also include the optimized values and the percentage change from the initial values.
source