Objectives¶
The base class for all objectives is BaseObjective.
- class ionworkspipeline.data_fits.objectives.BaseObjective(options=None, callbacks=None, custom_parameters=None, cost=None, constraints=None, penalties=None, parameters=None)¶
A pipeline element that constructs an objective function for either fitting or design optimization.
Parameters¶
- optionsdict, optional
A dictionary of options to pass to the data fit.
- callbacks
ionworkspipeline.callbacks.Callbackor list of callbacks A class with methods that get called at various points during the data fit process
- custom_parametersdict, optional
A dictionary of custom parameters to use for the objective. Deprecated, use parameters instead.
- cost
ionworkspipeline.costs.ObjectiveFunctionor str, optional The cost function to use for the objective. If not provided, the default cost function will be used.
- constraintslist[Constraint], optional
A list of equality and inequality constraints to apply to the objective.
- penaltieslist[Penalty], optional
A list of penalties to apply to the objective.
- parametersdict or
pybamm.ParameterValues, optional Objective-specific parameter values merged into the global parameter values before fitting. Default is None.
Extends:
ConfigMixinSee also:
BaseObjective— field-level documentation.- adopt_callbacks(other)¶
Share another objective’s live callbacks by reference (no copy).
Used by the execution engine: a worker clone is created before the driver resets per-start callbacks. Adopting the live callbacks keeps the worker-side iteration callback and the driver-side build/start/finish dispatch on the same objects.
Parameters¶
- otherBaseObjective
Objective whose current callbacks should be shared.
- build(parameter_values: ParameterValues)¶
Build the objective.
Parameters¶
- parameter_valuespybamm.ParameterValues
The parameter values to use for the objective.
- property can_calculate_initial_state_of_charge: bool¶
Whether the objective can calculate the initial state of charge using self._get_initial_state_of_charge(inputs).
- complete(parameter_values: ParameterValues)¶
Complete the objective by evaluating custom parameters, merging objective-specific parameter values, building the objective, and applying regularization postfix.
Parameters¶
- parameter_valuespybamm.ParameterValues
The parameter values to use for the objective.
- create_validation_plots(validation_result: dict, plots: list[str] | None = None, include_bokehjs: str | bool = 'cdn', include_plotlyjs: str | bool = 'cdn', backend: str = 'bokeh', **plot_kwargs) list[str]¶
Create validation plots for this objective in HTML format.
Parameters¶
- validation_resultdict
The validation results data.
- plotslist[str] | None
List of plot types to create.
- include_bokehjsstr | bool
Whether to include bokeh.js in the output (for bokeh backend).
- include_plotlyjsstr | bool
Whether to include plotly.js in the output (for plotly backend).
- backendstr
Plotting backend to use: “bokeh” (default) or “plotly”.
**plot_kwargsAdditional keyword arguments for plotting.
Returns¶
- list[str]
List of HTML strings for each plot.
- create_validation_plots_data(validation_result: dict, plots: list[str] | None = None, **plot_kwargs) list[dict]¶
Create validation plot data as plain trace arrays without Plotly serialization.
Generates Plotly figure objects internally (so derived traces such as error and log-error are computed correctly), then extracts
trace.x,trace.y, andtrace.nameas plain Python lists before any JSON serialization. This avoids Plotly’s binary transport encoding (bdata/dtype) and the corresponding decode complexity in the API layer.Parameters¶
- validation_resultdict
The validation results data (output of
prepare_validation_results).- plotslist[str] | None, optional
List of plot types to create. Defaults to
self.default_validation_plot_types.- **plot_kwargs
Additional keyword arguments forwarded to
_create_validation_figures.
Returns¶
- list[dict]
One dict per plot, each containing:
"type": plot type name (e.g."model data","error")."plot_index": zero-based index of this plot within the objective."traces": list of{"name": str, "x": list, "y": list}dicts."layout":{"xaxis": {"title": str | None}, "yaxis": {"title": str | None}}.
- create_validation_plots_json(validation_result: dict, plots: list[str] | None = None, backend: str = 'bokeh', **plot_kwargs) list[dict]¶
Create validation plots for this objective in JSON format.
Parameters¶
- validation_resultdict
The validation results data.
- plotslist[str] | None
List of plot types to create.
- backendstr
Plotting backend to use: “bokeh” (default) or “plotly”.
- plot_kwargs
Additional keyword arguments for plotting.
Returns¶
- list[dict]
List of dictionaries containing plot information:
“type”: plot type name
“figure”: JSON string representation of the figure. For bokeh backend, can be embedded with Bokeh.embed.json_item(). For plotly backend, can be loaded with plotly.io.from_json().
- property default_on_failure: str¶
Default
solver.on_failuremode for every objective.Always
"ignore". The solver returns a partial solution on failure, with NaN values for time points beyond the failure. The cost function’snan_policy(defaultConstantFill(1e6)) then fills only the NaN portions with penalty values, preserving valid data from the partial solution for gradient information. Only an output with no valid data at all marks the evaluation failed.Returns¶
- str
The string
"ignore".
- default_validation_plot_types: list[str] | None = None¶
Default list of validation plot type names for this objective.
Subclasses that support validation should override. Return
Noneto use the pipeline fallback (e.g.["model data", "error"]); return[]for no plots.
- failed_validation_statistics(summary_stats: list) list[dict]¶
NaN summary statistics for this objective, used when its validation failed.
Labelled as
prepare_validation_results()would label a successful solve, so the failed objective lines up with the others in a summary.Parameters¶
- summary_statslist
Summary statistic cost functions the validation computes.
Returns¶
- list[dict]
One
{"name": ..., "metric": nan}entry per statistic and variable.
- property has_simulation_experiment: bool¶
Whether the simulation kwargs contain a pybamm Experiment.
- prepare_validation_results(results: dict, summary_stats: list) tuple[list[dict[str, float]], dict[str, float]]¶
Prepare validation results for this objective.
Parameters¶
- resultsdict
The raw results from running the objective.
- summary_statslist
List of summary statistic cost functions to compute.
Returns¶
- tuple[list[dict[str, float]], dict[str, float]]
A tuple of (computed_statistics, validation_result) where:
computed_statistics is a list of dictionaries with computed metric names and values
validation_result is a dictionary of validation data
Raises¶
- NotImplementedError
If the objective does not support validation.
- provides_output_sensitivities: bool = False¶
Whether this objective lifts the solver’s analytic parameter sensitivities to output-variable sensitivities (i.e. its
_runcallsFittingObjective._capture_output_sensitivities()). Subclasses that do so set this True so the fit enables the analytic Jacobian path; default off.
- property remove_model_events: bool¶
Whether to remove the model events during simulation. Default is False.
- reset_callbacks()¶
Reset the callbacks to the original state using a deepcopy of the original callbacks. This is used with multiprocessing to make the Objective reusable for different DataFit jobs.
- summary_stat_name(cost, variable: str) str¶
Label of summary statistic
costcomputed onvariable.The unit is taken from the variable name, e.g.
"LLI [%]"gives"RMSE [%] (LLI [%])".
- to_config() dict¶
Convert the objective back to parser configuration format.
Returns¶
- dict
Configuration dictionary for this objective
- validate_fitted_parameters(fitted_parameter_values: dict) None¶
Check the fitted parameters for violations the fit could not enforce.
Called by
ionworkspipeline.DataFit.run()once the fit has finished, so an objective whose constraints are only softly enforced can surface a violated one instead of returning it silently. Skipped when the DataFit’s"validate"option isFalse.Parameters¶
- fitted_parameter_valuesdict
The fitted parameter values, keyed by parameter name.
- class ionworkspipeline.data_fits.objectives.SimulationObjective(data_input, options=None, callbacks=None, custom_parameters=None, cost=None, constraints=None, penalties=None, parameters=None)¶
A pipeline element that constructs an objective function used to fit a model to data. SimulationObjective is a subclass of Objective that intended for use with objectives that run a pybamm simulation.
Parameters¶
- data_inputstr, dict, pd.DataFrame, or ionworks.data.DataLoader
The data to use for the fit. Can be a string giving the path to the data, a pandas DataFrame, an ionworks.data DataLoader, or a dictionary with keys “data” and “metadata”. “data” should be a DataFrame or DataLoader that supplies the raw data, and “metadata” should be a dictionary that supplies metadata about the data.
- optionsdict, optional
A dictionary of options to pass to the data fit. Every subclass needs a model to run its simulation against, given either as
options={"model": <pybamm model>}or, for a model stored on the platform, asoptions={"parameterized_model_id": <id>}. Construction fails without one.- callbacks
ionworkspipeline.callbacks.Callbackor list of callbacks A class with methods that get called at various points during the datafit process
- custom_parametersdict, optional
A dictionary of custom parameters to use for the objective. Deprecated, use parameters instead.
- constraintslist[Constraint], optional
A list of equality and inequality constraints to apply to the objective.
- penaltieslist[Penalty], optional
A list of penalties to apply to the objective.
- parametersdict or
pybamm.ParameterValues, optional Objective-specific parameter values merged into the global parameter values before fitting. Default is None.
Extends:
InitialStateOfChargeMixinSee also:
SimulationObjective— field-level documentation.
Objectives fitted against measured data derive from
FittingObjective;
those that need an initial SOC also mix in
InitialStateOfChargeMixin.
- class ionworkspipeline.data_fits.objectives.fitting_objective.FittingObjective(data_input, options=None, callbacks=None, custom_parameters=None, cost=None, constraints=None, penalties=None, parameters=None)¶
A pipeline element that constructs an objective function used to fit a model to data.
Parameters¶
- data_inputstr, dict, pd.DataFrame, or ionworks.data.DataLoader
The data to use for the fit. Can be a string giving the path to the data, a pandas DataFrame, an ionworks.data DataLoader, or a dictionary with keys “data” and “metadata”. “data” should be a DataFrame or DataLoader that supplies the raw data, and “metadata” should be a dictionary that supplies metadata about the data. An
ionworks.data.AnalysisLoader, or the dict it serializes to, reads one of that measurement’s stored analyses as the data instead of its time series, selected byanalysis_id,analysis_typeand/orname.- optionsdict, optional
A dictionary of options to pass to the data fit.
- callbacks
ionworkspipeline.callbacks.Callbackor list of callbacks A class with methods that get called at various points during the datafit process
- cost
ionworkspipeline.costs.ObjectiveFunctionor str, optional The cost function to use for the objective. If not provided, the default cost function will be used.
- constraintslist[Constraint], optional
A list of equality and inequality constraints to apply to the objective.
- penaltieslist[Penalty], optional
A list of penalties to apply to the objective.
- custom_parametersdict, optional
A dictionary of custom parameters to use for the objective. Deprecated, use parameters instead.
- parametersdict or
pybamm.ParameterValues, optional Objective-specific parameter values merged into the global parameter values before fitting. Default is None.
Extends:
BaseObjectiveSee also:
FittingObjective— field-level documentation.- complete(parameter_values: ParameterValues)¶
Complete the objective by evaluating custom parameters, merging objective-specific parameter values, building the objective, and applying regularization postfix.
Parameters¶
- parameter_valuespybamm.ParameterValues
The parameter values to use for the objective.
- property fit_data¶
The targets the cost scores, keyed by objective variable.
Distinct from
processed_data, which is everything the objective holds — the independent variable, columns it needs for its own maths, and every row it can plot. An objective that is not scored at every row it describes narrows this to the ones it is; the cost compares what it is given point for point and has no way to tell which rows those are.Returns¶
- dict
Every column of
processed_data, unless a subclass narrows it.
- classmethod from_schema(schema)¶
Construct from a validated ionworks.pipeline objective instance.
Extends the default
ConfigMixin.from_schema()(which converts nested schema fields such asconstraints/penalties) to also rebuild a model supplied as a serialized config dict inoptions["model"]viaparse_model— handling both built-in andtype == "custom"models. A live model object (the common case) is a no-op and passes through unchanged.Parameters¶
- schemaionworks.pipeline.objectives.BaseObjective
The validated schema objective to convert.
Returns¶
- FittingObjective
The constructed runtime objective.
- run(inputs, full_output=False, raise_on_failure=False)¶
Run the objective, reusing the last solve when the analytic-Jacobian path re-invokes it at the same inputs.
With the analytic Jacobian active the optimizer evaluates the residual and the Jacobian at the same point, and the sensitivities
d(var)/dpare computed on every solve — so the model would otherwise be solved twice per point. A one-deep memo keyed on the inputs returns the cached outputs and captured sensitivities for the repeat, collapsing the two solves to one.
- class ionworkspipeline.data_fits.objectives.fitting_objective.InitialStateOfChargeMixin¶
Mixin class that provides sophisticated custom parameter evaluation logic.
This mixin handles the evaluation of custom parameters, especially those created by initial_concentration_from_voltage, which may require special handling to set the initial SOC correctly.
For the objectives that are implemented in the pipeline, see the following sections.
- Open-circuit potential objectives
- Open-circuit potential objectives with MSMR model
- Objectives
- Utility functions
get_msmr_params_for_fit()default_msmr_bounds_function()get_msmr_capacity_params_for_fit()default_msmr_capacity_bounds_function()msmr_half_cell_initial_guess()get_initial_capacity_and_lower_excess_capacity()get_theta_half_cell_msmr()get_q_half_cell_msmr()plot_each_species_msmr()plot_half_cell_ocp()plot_full_cell_ocv()msmr_Qj_to_Xj()msmr_Xj_to_Qj()msmr_sort_params()
- Callbacks
- Resistance objective
- Pulse objective
- Current-driven objective
CurrentDrivenCurrentDriven.build()CurrentDriven.complete()CurrentDriven.default_options()CurrentDriven.default_validation_plot_typesCurrentDriven.prepare_validation_results()CurrentDriven.provides_output_sensitivitiesCurrentDriven.remove_model_eventsCurrentDriven.summary_stat_name()CurrentDriven.validation_plots_data()
- EIS objective
- Calendar ageing objective
- Cycle ageing objective