### Navigate to PyBOP examples directory Source: https://github.com/pybop-team/pybop/blob/develop/docs/quick_start.rst This command shows the typical path to access PyBOP's example files after cloning the repository. These examples are useful for learning and experimentation. ```console path/to/pybop/examples ``` -------------------------------- ### Example Benchmark File Structure Source: https://github.com/pybop-team/pybop/blob/develop/benchmarks/README.md Define benchmark classes with setup, teardown, and timing methods. The `setup` method runs before each benchmark, `time_` methods contain the benchmark code, and `teardown` runs after. ```python class ExampleBenchmarks: def setup(self): # Code to run before each benchmark method is executed pass def time_example_benchmark(self): # The actual benchmark code pass def teardown(self): # Code to run after each benchmark method is executed pass ``` -------------------------------- ### Initializing and Running the Simulator Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/cost_compute_methods.ipynb Combine the model, parameters, and dataset to construct a `Simulator` class. This class is used to evaluate the forward model for parameter fitting. Run the simulator to get an example solution. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, output_variables=["Voltage [V]"] ) inputs = simulator.parameters.to_dict([0.5, 0.5]) solution = simulator.solve(inputs=inputs) ``` -------------------------------- ### Install PyBOP for Development Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Installs PyBOP with all dependencies for development. Use the `[all]` flag and the `dev` dependency group. ```sh pip install -e '.[all]' pip install --group dev ``` ```sh pip install -e .[all] pip install --group dev ``` -------------------------------- ### Install PyBOP with All Optional Dependencies Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install PyBOP including all available optional dependencies. Refer to pyproject.toml for a full list. ```console pip install pybop[all] ``` -------------------------------- ### Install Dependencies and Import Libraries Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_salib.ipynb Installs necessary packages and imports required libraries for PyBOP and SALib. Fixes the random seed for consistent output. ```python %pip install --upgrade openpyxl pandas -q import time import matplotlib.pyplot as plt import numpy as np import pandas as pd import pybamm from pybamm import Parameter from SALib.analyze import morris as morris_analyze from SALib.analyze import sobol from SALib.sample import morris as morris_sample from SALib.sample import sobol as sobol_sample import pybop pybop.plot.PlotlyManager().pio.renderers.default = "notebook_connected" np.random.seed(8) # users can remove this line ``` -------------------------------- ### Install ASV Benchmark Tool Source: https://github.com/pybop-team/pybop/blob/develop/benchmarks/README.md Install the airspeed velocity (asv) benchmarking tool using pip. It is recommended to do this within a virtual environment. ```bash pip install asv ``` -------------------------------- ### Install Dependencies and Import Libraries Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_multipulse_identification.ipynb Upgrades necessary dependencies and imports PyBaMM and PyBOP libraries. Fixes the random seed for consistent output. Ensure PyBOP is installed via the installation guide. ```python %pip install --upgrade openpyxl pandas -q import numpy as np import pandas as pd import pybamm import pybop pybop.plot.PlotlyManager().pio.renderers.default = "notebook_connected" np.random.seed(8) # users can remove this line ``` -------------------------------- ### Install PyBOP with BPX Optional Requirement Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install PyBOP with the optional requirement for the Battery Parameter eXchange (BPX) package. ```console pip install pybop[bpx] ``` -------------------------------- ### Install and Use Pre-commit Hooks Manually Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Installs pre-commit manually and sets up hooks for local commits. This ensures code is formatted correctly before each commit. ```sh pip install pre-commit pre-commit install ``` -------------------------------- ### Build Documentation Locally with Nox Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Use the Nox session 'docs' to build the documentation locally. This command also starts a live-reloading server for viewing the documentation in a browser. ```bash nox -s docs ``` -------------------------------- ### Run Optimization with XNES Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_salib.ipynb Sets up optimization options and runs the XNES optimization algorithm on the defined problem. The maximum iterations are limited for this example. ```python options = pybop.PintsOptions( max_unchanged_iterations=30, max_iterations=100, ) optim = pybop.XNES(problem, options=options) result = optim.run() print(result) ``` -------------------------------- ### Local PyBOP Installation from Source Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install PyBOP in editable mode from a local clone of the repository. Changes to the source code will be reflected immediately without reinstallation. ```console pip install -e "path/to/pybop" ``` -------------------------------- ### Install and Use Pre-commit Hooks with Nox Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Installs and configures pre-commit hooks using Nox. This automates code formatting and prettifying. ```sh nox -s pre-commit ``` -------------------------------- ### Test PyBOP Installation Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Verifies the PyBOP installation by running unit tests. Use either Nox or pytest for testing. ```sh nox -s unit ``` ```sh $ pytest --unit -v ``` -------------------------------- ### Install PyBOP with Scientific FEM Dependencies Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install PyBOP with optional dependencies for multi-dimensional PyBaMM models, including scikit-fem. ```console pip install pybop[scifem] ``` -------------------------------- ### Install Latest PyBOP with Pip Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Use this command to install the most recent stable release of PyBOP from PyPI. ```console pip install pybop ``` -------------------------------- ### Install PyBOP Development Version from GitHub Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install the latest code directly from the 'develop' branch on GitHub. This provides access to the newest features but may be less stable. ```console pip install git+https://github.com/pybop-team/PyBOP.git@develop ``` -------------------------------- ### Verify PyBOP Installation Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Run this Python command to check if PyBOP is installed correctly and to display its version number. ```python python -c "import pybop; print(pybop.__version__)" ``` -------------------------------- ### Select PyBaMM Models Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/echem_identification_pitfalls.ipynb Instantiate the PyBaMM models that will be used for parameter estimation. This example includes the Standard Particle Model (SPM) and its electrolyte-extended version (SPMe). ```python models = [ pybamm.lithium_ion.SPM(), pybamm.lithium_ion.SPMe(), ] ``` -------------------------------- ### Install PyBOP with Plotting Dependencies Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install PyBOP along with optional dependencies required for plotting functionality, which utilizes plotly. ```console pip install pybop[plot] ``` -------------------------------- ### Install Snakeviz Profiler Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Install the `snakeviz` package using pip to enable detailed code profiling. This tool provides a visual representation of profiling data. ```bash pip install snakeviz ``` -------------------------------- ### Evaluating Cost with a Dataset Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/cost_compute_methods.ipynb Define a cost function using `pybop.SumOfPower` with the example dataset. Use the `evaluate` method to compute the cost for a given solution and inputs. ```python cost = pybop.SumOfPower(dataset) cost.evaluate(solution, inputs=inputs) ``` -------------------------------- ### Set up Simulator, Cost, and Problem Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_hessian.ipynb Initialises the simulator with the model and updated parameter values, defines the cost function (Sum of Squared Errors), and creates the optimisation problem. ```python parameter_values.set_initial_state(initial_soc) simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### Import Libraries and Set Random Seed Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/setting_optimiser_options.ipynb Imports necessary libraries for PyBOP and sets a random seed for reproducible results. Ensure PyBOP is installed via the installation guide. ```python import json import numpy as np import pybamm import pybop pybop.plot.PlotlyManager().pio.renderers.default = "notebook_connected" np.random.seed(8) # users can remove this line ``` -------------------------------- ### Setting up the Environment and Importing Libraries Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/cost_compute_methods.ipynb Import necessary libraries like NumPy and PyBAMM, and PyBOP. It's recommended to fix the random seed for consistent output during development. ```python import numpy as np import pybamm import pybop pybop.plot.PlotlyManager().pio.renderers.default = "notebook_connected" np.random.seed(8) # users can remove this line ``` -------------------------------- ### Publish and Preview Benchmark Results Source: https://github.com/pybop-team/pybop/blob/develop/benchmarks/README.md Generate and serve a local web preview of the benchmark results. Run `asv publish` first to generate the necessary files. ```bash asv publish ``` ```bash asv preview ``` -------------------------------- ### Set up PyBOP Problem and Simulator Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_multipulse_identification.ipynb Configure the simulator with the model, parameter values, and solver. Define the cost function and create the problem object. ```python parameter_values.set_initial_state(f"{df['Voltage'].to_numpy()[0]} V") simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, solver=pybamm.CasadiSolver(mode="safe", dt_max=40), cache_esoh=False, ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### Set up Optimization Problem Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/lgm50_pulse_validation.ipynb Instantiate the Simulator, define the cost function (SumSquaredError), and create a Problem object to hold these components for optimization. The simulator requires the model, parameter values, and dataset. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, cache_esoh=False ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### Set up and Run Optimiser Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_hessian.ipynb Configures the SciPy Differential Evolution optimiser with specific options and executes the optimisation process. The results are then printed. ```python options = pybop.SciPyDifferentialEvolutionOptions(maxiter=35, popsize=7) optim = pybop.SciPyDifferentialEvolution(problem, options=options) result = optim.run() print(result) ``` -------------------------------- ### Set up Optimisation Problem with Initial Learning Rate Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/comparison_examples/optimiser_calibration.ipynb Configures the simulator, cost function, and problem for optimisation. Initializes the Gradient Descent optimiser with a small learning rate and sets it. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) options = pybop.PintsOptions(max_iterations=100) optim = pybop.GradientDescent(problem, options=options) optim.optimiser.set_learning_rate(eta=0.01) ``` -------------------------------- ### Configure and Instantiate Optimizer Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/design_optimisation/energy_based_electrode_design.ipynb Sets up the options for the Particle Swarm Optimisation (PSO) algorithm, including verbosity and maximum iterations, and then instantiates the optimiser. ```python options = pybop.PintsOptions(verbose=True, max_iterations=15) optim = pybop.PSO(problem, options=options) ``` -------------------------------- ### Install a specific version of PyBOP Source: https://github.com/pybop-team/pybop/blob/develop/README.md Install a previous release of PyBOP by specifying the version number. Replace 'v24.3' with the desired version tag. ```bash pip install pybop==v24.3 ``` -------------------------------- ### Configure and Run PINTS Optimiser (XNES) Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/setting_optimiser_options.ipynb Sets up and runs the XNES optimiser from the PINTS library using PintsOptions for configuration. Alternative set/get methods can be used for optimiser arguments. ```python options = pybop.PintsOptions( max_iterations=50, max_unchanged_iterations=25, absolute_tolerance=1e-9, ) optim_one = pybop.XNES( problem, options=options ) # Direct optimiser class with options object optim_one.set_max_iterations( 50 ) # Alternative set() / get() methods for PINTS optimisers result = optim_one.run() print(result) ``` -------------------------------- ### Run Quick Test Suite with Nox Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Execute both standard and documentation tests using nox. This is a comprehensive test run for a quick check. ```bash nox -s quick ``` -------------------------------- ### Install Specific PyBOP Version with Pip Source: https://github.com/pybop-team/pybop/blob/develop/docs/installation.rst Install a particular version of PyBOP by specifying the version number. This is useful for ensuring compatibility with existing projects. ```console pip install pybop==23.11 ``` -------------------------------- ### Set up Thevenin Model and Parameters Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_monte_carlo_sampling.ipynb Constructs a two-RC element Thevenin equivalent circuit model and initializes parameter values. Updates parameters with specific cell capacity, voltage cut-offs, the defined OCV function, and placeholder values for R2 and C2. ```python model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 2}) parameter_values = pybamm.ParameterValues("ECM_Example") parameter_values.update( { "Cell capacity [A.h]": 22.651, # 083/828 - C/20 "Nominal cell capacity [A.h]": 22.651, "Current function [A]": 22.651, "Initial SoC": 1.0, "Upper voltage cut-off [V]": 4.25, # Extended to avoid hitting event "Lower voltage cut-off [V]": 2.5, "Open-circuit voltage [V]": ocv, "R2 [Ohm]": 1e-4, # placeholder "C2 [F]": 4e5, # placeholder "Element-2 initial overpotential [V]": 0, } ) ``` -------------------------------- ### Initialize and Run SciPy Minimizer Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_scipy_constraints.ipynb Instantiate the SciPy minimizer with the defined problem and options. The `run()` method then executes the parameter identification process, applying the constraints. ```python optim = pybop.SciPyMinimize(problem, options=options) ``` ```python result = optim.run() ``` -------------------------------- ### Test Documentation Build with Nox Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Run the Nox session 'doctests' to verify that the documentation builds correctly without errors. ```bash nox -s doctests ``` -------------------------------- ### Maximise Energy Delivered with XNES Source: https://context7.com/pybop-team/pybop/llms.txt Example of using the XNES optimiser to maximise discharge energy. Requires a Problem object. ```python optim = pybop.XNES(problem) result = optim.run() print("Optimal thickness [m]:", result.x) print("Max discharge energy [W.h]:", result.best_cost) ``` -------------------------------- ### Set up Model, Problem, and Cost Objects Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/setting_optimiser_options.ipynb Defines a Thevenin model, loads parameter values from a JSON file, generates synthetic data, and constructs the problem and cost objects for optimisation. ```python # Define the model model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 1}) # Load the parameters with open("../../parameters/initial_ecm_parameters.json") as file: parameter_values = pybamm.ParameterValues(json.load(file)) parameter_values.update( { "Open-circuit voltage [V]": model.default_parameter_values[ "Open-circuit voltage [V]" ] } ) # Generate synthetic data t_eval = np.arange(0, 900, 2) solution = pybamm.Simulation(model, parameter_values=parameter_values).solve( t_eval=t_eval, t_interp=t_eval ) dataset = pybop.import_pybamm_solution( solution, variables=["Time [s]", "Current [A]", "Voltage [V]"] ) # Define the fitting parameter parameter_values.update( { "R0 [Ohm]": pybop.Parameter( pybop.Gaussian( 0.0002, 0.0001, truncated_at=[1e-4, 1e-2], ) ) } ) # Construct problem and cost simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### SciPyDifferentialEvolution for Global Optimization Source: https://context7.com/pybop-team/pybop/llms.txt Example of using SciPyDifferentialEvolution for global optimization. Requires a Problem object and SciPyDifferentialEvolutionOptions specifying max_iterations and popsize. ```python options_de = pybop.SciPyDifferentialEvolutionOptions(max_iterations=100, popsize=15) optim_de = pybop.SciPyDifferentialEvolution(problem, options=options_de) result_de = optim_de.run() print("Differential Evolution result:", result_de.x) ``` -------------------------------- ### Run Ruff Linter Manually Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Manually trigger the Ruff linter to check for PEP standards adherence. Ensure pre-commit is installed. ```bash python -m pip install pre-commit pre-commit run ruff ``` -------------------------------- ### Run Haario-Bardenet MCMC sampler and analyze results Source: https://context7.com/pybop-team/pybop/llms.txt Demonstrates setting up and running the Haario-Bardenet adaptive MCMC sampler with multiple chains. Includes diagnostics like R-hat and effective sample size, and plotting functions for posterior analysis. ```python import numpy as np import pybamm import pybop model = pybamm.equivalent_circuit.Thevenin() params = model.default_parameter_values.copy() t = np.linspace(0, 900, 300) sol = pybamm.Simulation(model, parameter_values=params).solve(t_eval=t) ds = pybop.Dataset({ "Time [s]": t, "Current [A]": sol["Current [A]"](t), "Voltage [V]": sol["Voltage [V]"](t) + np.random.normal(0, 1e-3, 300), }) params["R0 [Ohm]"] = pybop.Parameter( pybop.Gaussian(mean=2e-4, sigma=5e-5, truncated_at=[1e-4, 1e-2]), initial_value=2e-4, ) sim = pybop.pybamm.Simulator(model, parameter_values=params, protocol=ds) ll = pybop.GaussianLogLikelihood(ds, sigma=1e-3) log_post = pybop.LogPosterior(sim, ll) # Haario-Bardenet adaptive MCMC with 3 chains sampler_opts = pybop.PintsSamplerOptions(n_chains=3) sampler = pybop.HaarioBardenetACMC(log_post, options=sampler_opts) sampler.set_max_iterations(1000) sampler.set_warm_up_iterations(200) result = sampler.run() # Diagnostics stats = result.get_summary_statistics(significant_digits=4) print("Posterior mean R0:", stats["mean"]) print("95% CI lower:", stats["ci_lower"]) print("95% CI upper:", stats["ci_upper"]) print("R-hat:", result.rhat()) # close to 1.0 → converged print("ESS:", result.effective_sample_size(mixed_chains=True)) # Plotting result.plot_trace() result.plot_posterior() result.plot_predictive() ``` -------------------------------- ### Run AdamW Optimisation Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/optimising_with_adamw.ipynb Executes the AdamW optimisation algorithm to estimate the parameters of the model based on the provided dataset and problem setup. ```python result = optim.run() ``` -------------------------------- ### Configure and Run SciPy Optimiser (Nelder-Mead) Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/setting_optimiser_options.ipynb Sets up and runs the Nelder-Mead optimiser from SciPy using SciPyMinimizeOptions for configuration. The method and tolerance can be specified. ```python options = pybop.SciPyMinimizeOptions( maxiter=50, method="Nelder-Mead", tol=1e-9, ) optim_two = pybop.SciPyMinimize(problem, options=options) result2 = optim_two.run() print(result2) ``` -------------------------------- ### Set up PyBOP Problems for Inference Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/maximum_a_posteriori.ipynb Instantiate a simulator, define the cost function (e.g., Gaussian Log-Likelihood), and create PyBOP Problem objects for the log prior, log likelihood, and log posterior. The log posterior combines the simulator, cost, and parameters. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, ) cost = pybop.GaussianLogLikelihoodKnownSigma(dataset, sigma=sigma) log_prior = pybop.Problem(simulator, pybop.LogPrior(simulator.parameters)) log_likelihood = pybop.Problem(simulator, cost) log_pdf = pybop.LogPosterior(simulator, cost) ``` -------------------------------- ### Import PyBOP in Python Source: https://github.com/pybop-team/pybop/blob/develop/docs/quick_start.rst Import the PyBOP library into your Python scripts or notebooks after installation. This makes PyBOP's functionalities available for use. ```python import pybop ``` -------------------------------- ### Print PyBOP Citations Source: https://github.com/pybop-team/pybop/blob/develop/README.md Use this command at the end of your script to print BibTeX information relevant to the models and methods used. Ensure PyBOP is installed. ```python pybamm.print_citations() ``` -------------------------------- ### Constructing a Model, Dataset, and Simulator Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/cost_compute_methods.ipynb Create a PyBAMM model, define parameter values, specify evaluation time points, and solve the simulation to obtain a solution. This solution is then converted into a PyBOP dataset. ```python model = pybamm.lithium_ion.SPM() parameter_values = pybamm.ParameterValues("Chen2020") t_eval = np.linspace(0, 10, 100) solution = pybamm.Simulation(model, parameter_values=parameter_values).solve( t_eval=t_eval, t_interp=t_eval ) dataset = pybop.import_pybamm_solution(solution) ``` -------------------------------- ### Evaluate Problem Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/lgm50_pulse_validation.ipynb Evaluate the problem with a given set of input parameters to get the cost function value. This is useful for testing or understanding the cost landscape. ```python inputs = problem.parameters.to_dict([0.01, 0.01, 0.01, 10000, 10000]) evaluation = problem.evaluate(inputs) evaluation.get_values()[0] ``` -------------------------------- ### Construct Simulator and Problem Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_salib.ipynb Constructs the simulator using an initial OCV state from the dataset and defines the cost function and problem for optimization. ```python parameter_values.set_initial_state(f"{df['Voltage'].to_numpy()[0]} V") simulator = pybop.pybamm.Simulator(model, parameter_values=parameter_values, protocol=dataset) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### Construct Experiment and Simulator Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/design_optimisation/energy_based_electrode_design.ipynb Defines the experimental protocol for discharging the cell and sets up the simulator with the model, parameter values, experiment, and initial state of charge. ```python experiment = pybamm.Experiment(["Discharge at 1C until 2.5 V (5 seconds period)"]) initial_soc = 0.7 simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=experiment, initial_state={"Initial SoC": initial_soc}, solver=pybamm.CasadiSolver(), ) ``` -------------------------------- ### AdamW Optimiser for Gradient-Based Optimization Source: https://context7.com/pybop-team/pybop/llms.txt Example of using the AdamW optimiser, a gradient-based method. Sensitivities must be available (no initial_state or pybamm.Experiment). Requires a Problem object and PintsOptions. ```python import numpy as np import pybamm import pybop model = pybamm.lithium_ion.SPM() params = pybamm.ParameterValues("Chen2020") t = np.linspace(0, 600, 200) sol = pybamm.Simulation(model, parameter_values=params).solve(t_eval=t) ds = pybop.Dataset({ "Time [s]": t, "Current [A]": sol["Current [A]"](t), "Voltage [V]": sol["Voltage [V]"](t), }) params["Positive electrode active material volume fraction"] = pybop.Parameter( bounds=[0.3, 0.9], initial_value=0.6 ) # NOTE: No initial_state and no pybamm.Experiment → sensitivities are available sim = pybop.pybamm.Simulator(model, parameter_values=params, protocol=ds) cost = pybop.SumSquaredError(ds) problem = pybop.Problem(sim, cost) print("Has sensitivities:", problem.has_sensitivities) # True options = pybop.PintsOptions(max_iterations=150, learning_rate=1e-3) optim = pybop.AdamW(problem, options=options) result = optim.run() print("AdamW result:", result.x) ``` -------------------------------- ### Use IPython Embed for Debugging Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Utilize `IPython.embed()` to start an interactive IPython session at a breakpoint, allowing the use of IPython magic commands during debugging. This can be combined with `ipdb.set_trace()`. ```python from IPython import embed embed() import ipdb ipdb.set_trace() ``` -------------------------------- ### Define Optimisation Parameters Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_hessian.ipynb Sets up parameters for optimisation, specifying which parameters are unknown and their bounds and initial values. The actual values are commented out for reference. ```python parameter_values = pybamm.ParameterValues("Chen2020") parameter_values.update( { "Negative particle diffusivity [m2.s-1]": pybop.Parameter( bounds=[1e-15, 1e-11], initial_value=1.68e-12, # actual value: 3.3e-14 ), "Positive particle diffusivity [m2.s-1]": pybop.Parameter( bounds=[1e-17, 1e-13], initial_value=1.32e-16, # actual value: 4e-15 ), } ) ``` -------------------------------- ### Setting up the Equivalent Circuit Model Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/sensitivity_analysis_salib.ipynb Defines a two RC branch Thevenin model using PyBaMM and updates parameter values. This includes setting cell capacity, initial overpotentials, voltage cut-offs, and resistance/time constant values. ```python model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 2}) parameter_values = pybamm.ParameterValues("ECM_Example") parameter_values.update( { "Cell capacity [A.h]": 3, "Nominal cell capacity [A.h]": 3, "Element-1 initial overpotential [V]": 0, "Element-2 initial overpotential [V]": 0, "Upper voltage cut-off [V]": 4.2, "Lower voltage cut-off [V]": 2.5, "R0 [Ohm]": 1e-3, "R1 [Ohm]": 0.1, "R2 [Ohm]": 0.001, "Tau1 [s]": 1.0, "Tau2 [s]": 100.0, "C1 [F]": Parameter("Tau1 [s]") / (Parameter("R1 [Ohm]") + np.finfo(float).eps), "C2 [F]": Parameter("Tau2 [s]") / (Parameter("R2 [Ohm]") + np.finfo(float).eps), } ) ``` -------------------------------- ### Install and Import Libraries Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_monte_carlo_sampling.ipynb Upgrades pandas, imports necessary libraries (numpy, pandas, pybamm, pybop), and sets the default renderer for Plotly. Fixes the random seed for consistent output. ```python %pip install --upgrade pandas -q import numpy as np import pandas as pd import pybamm import pybop pybop.plot.PlotlyManager().pio.renderers.default = "notebook_connected" np.random.seed(8) # users can remove this line ``` -------------------------------- ### Assemble Dataset for Optimization Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/electrode_balancing.ipynb Creates a PyBOP dataset from measured data, converting capacity to proxy time by shifting and scaling. A constant negative current is used to simulate lithiation. ```python # Shift the capacity values to start from zero minimum_capacity_recorded = np.min(measured_data["Capacity [A.h]"]) proxy_time_data = ( measured_data["Capacity [A.h]"] - minimum_capacity_recorded ) * 3600 dataset = pybop.Dataset( { "Time [s]": proxy_time_data, "Current [A]": -np.ones(len(measured_data["Capacity [A.h]"])), "Voltage [V]": measured_data["Voltage [V]"] } ) ``` -------------------------------- ### Create and Filter Pandas DataFrame Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/lgm50_pulse_validation.ipynb Constructs a Pandas DataFrame from selected pulse data and filters it to ensure monotonically increasing time samples without duplicates. Time is reset to start from zero. ```python df = pd.DataFrame(pulse_data["LGM50_5Ah_Pulse"]["T0"]["SoC9"]["Cell19"]["data"]) df["ProgTime"] = df["ProgTime"] - df["ProgTime"].min() df.drop_duplicates(subset=["ProgTime"], inplace=True) ``` -------------------------------- ### Import and Filter Cycling Data Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_monte_carlo_sampling.ipynb Reads cycling data from a CSV file and filters it to a specific subset (a full cycle) to reduce computation time for inference. Resets the time to start from zero for the filtered data. ```python cycling_df = pd.read_csv( "../../data/Tesla_4680/601-828_Capacity_03_MB_CB1_subset.txt", sep="\t", ) filter_cycling = cycling_df.loc[54811:61000].copy() # Full cycle is [54811:127689] filter_cycling["time/s"] = filter_cycling["time/s"] - filter_cycling["time/s"].iloc[0] ``` -------------------------------- ### Compare SumOfPower (p=2) with SSE Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/comparison_examples/comparing_cost_functions.ipynb Instantiate and evaluate the SumOfPower cost function with p=2, and plot its results alongside RMSE*N and SSE for comparison. This demonstrates the equivalence between SumOfPower(p=2) and SSE. ```python sumofpower = pybop.SumOfPower(dataset, p=2) y_sumofpower = sumofpower.evaluate(solution, inputs).get_values() fig = go.Figure() fig.add_trace( go.Scatter( x=x_range, y=np.asarray(y_RMSE) * np.sqrt(len(t_eval)), mode="lines", name="RMSE*N", ) ) fig.add_trace( go.Scatter( x=x_range, y=y_SSE, mode="lines", line=dict(dash="dash"), name="SSE", ) ) fig.add_trace( go.Scatter( x=x_range, y=y_sumofpower, mode="lines", line=dict(dash="dot"), name="Sum of Power", ) ) fig.show() ``` -------------------------------- ### Set Up Optimization Problem and Optimiser Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/pouch_cell_identification.ipynb Configures the simulation, cost function, and optimization problem using PyBOP. It initializes a CMAES optimiser with specified options. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset, var_pts=var_pts, ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) options = pybop.PintsOptions(max_iterations=30) optim = pybop.CMAES(problem, options=options) ``` -------------------------------- ### Construct Optimization Problem Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/using_transformations.ipynb Combines the model, parameter values, and dataset to create a PyBOP Simulator and a cost function (SumOfPower). These are then used to construct the Problem class. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset ) cost = pybop.SumOfPower(dataset) problem = pybop.Problem(simulator, cost) ``` -------------------------------- ### Define Parameters for Estimation Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/pouch_cell_identification.ipynb Sets up the parameters to be estimated by defining their distributions and bounds using PyBOP's Gaussian and Parameter classes. This prepares the problem for optimization. ```python parameter_values.update( { "Negative electrode active material volume fraction": pybop.Parameter( pybop.Gaussian(0.7, 0.05, truncated_at=[0.45, 0.9]), ), "Positive electrode active material volume fraction": pybop.Parameter( pybop.Gaussian(0.58, 0.05, truncated_at=[0.5, 0.8]), ), } ) ``` -------------------------------- ### Configure SciPy Minimizer Options Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_scipy_constraints.ipynb Set up the options for the SciPy minimizer, specifying the 'trust-constr' method and including the previously defined nonlinear constraint. This prepares the optimiser to handle the specified bounds during the fitting process. ```python options = pybop.SciPyMinimizeOptions( method="trust-constr", constraints=tau_constraint, maxiter=100, ) ``` -------------------------------- ### Run Optimisation and Print Results Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/design_optimisation/energy_based_electrode_design.ipynb Executes the optimisation process and prints the initial and optimised gravimetric energy densities. ```python result = optim.run() print(f"Initial gravimetric energy density: {result.cost[0]:.2f} W.h.kg-1") print(f"Optimised gravimetric energy density: {result.best_cost:.2f} W.h.kg-1") ``` -------------------------------- ### Apply parameter transformations for optimization Source: https://context7.com/pybop-team/pybop/llms.txt Illustrates the use of different parameter transformations like `LogTransformation` and `UnitHyperCube` to map parameters between physical model space and an unconstrained search space. Shows how to attach transformations to parameters. ```python import numpy as np import pybop # Log transformation — useful for parameters spanning orders of magnitude log_t = pybop.LogTransformation(n_parameters=1) x_model = np.array([1e-14]) x_search = log_t.to_search(x_model) # log(1e-14) ≈ -32.24 back = log_t.to_model(x_search) # back to 1e-14 print(np.allclose(x_model, back)) # True # Unit hypercube — map [lower, upper] → [0, 1] uc = pybop.UnitHyperCube(lower=np.array([0.3, 1e-4]), upper=np.array([0.9, 1e-2])) print(uc.to_search(np.array([0.6, 5e-3]))) # approx [0.5, 0.495] # Attach a log-transform to a Parameter p = pybop.Parameter( distribution=pybop.Gaussian(mean=3.9e-14, sigma=1e-14, truncated_at=[1e-15, 1e-13]), transformation=pybop.LogTransformation(), ) print(p.get_initial_value(transformed=True)) # initial value in log space # ComposedTransformation — per-parameter transforms in a single object composed = pybop.ComposedTransformation([ pybop.LogTransformation(), pybop.IdentityTransformation(), ]) x = np.array([1e-14, 0.6]) print(composed.to_search(x)) # [log(1e-14), 0.6] print(composed.to_model(composed.to_search(x))) # original values restored ``` -------------------------------- ### Run Detailed Profiling with Snakeviz Source: https://github.com/pybop-team/pybop/blob/develop/CONTRIBUTING.md Use IPython's `%load_ext snakeviz` and `%snakeviz` magic commands to run a detailed profiler and visualize the results in a browser window. ```ipython %load_ext snakeviz %snakeviz command_to_time() ``` -------------------------------- ### Run XNES Optimisation Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_multipulse_identification.ipynb Instantiate and run the XNES optimisation algorithm with specified options. Adjust max_iterations to control runtime. ```python options = pybop.PintsOptions( max_unchanged_iterations=20, max_iterations=100, ) optim = pybop.XNES(problem, options=options) result = optim.run() ``` -------------------------------- ### Run All Benchmarks Source: https://github.com/pybop-team/pybop/blob/develop/benchmarks/README.md Execute all defined benchmarks in the current Python environment. Optionally, specify a range of commits to benchmark against. ```bash asv run ``` ```bash asv run .. ``` -------------------------------- ### XNES with Multistart Source: https://context7.com/pybop-team/pybop/llms.txt Utilises the XNES optimiser with multistart enabled to help escape local minima. Requires a Problem object and PintsOptions with multistart set. ```python multi_options = pybop.PintsOptions(max_iterations=100, multistart=5) optim_ms = pybop.XNES(problem, options=multi_options) result_ms = optim_ms.run() print("Best of 5 starts:", result_ms.best_cost) ``` -------------------------------- ### Construct Model, Problem, and Likelihood Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_monte_carlo_sampling.ipynb Initialises a PyBAMM simulator with the model, parameter values, and dataset. A Gaussian Log Likelihood cost function is defined, and a LogPosterior is created by combining the simulator and cost. ```python parameter_values.set_initial_state(f"{dataset_hundred['Voltage [V]'][0]} V") simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset_hundred ) cost = pybop.GaussianLogLikelihood(dataset_hundred) log_pdf = pybop.LogPosterior(simulator, cost) ``` -------------------------------- ### Set Up PyBaMM Model and Parameters Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/electrode_balancing.ipynb Configures a PyBaMM Thevenin model with zero RC elements and sets specific parameter values, including a custom OCV function derived from reference data. ```python model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 0}) def ocv(sto): return pybamm.Interpolant( reference_data["Stoichiometry"].to_numpy(), reference_data["Voltage [V]"].to_numpy(), sto, "reference OCV", ) parameter_values = model.default_parameter_values parameter_values.update( { "Initial SoC": 0, "Entropic change [V/K]": 0, "R0 [Ohm]": 0, "Lower voltage cut-off [V]": 0, "Upper voltage cut-off [V]": 5, "Open-circuit voltage [V]": ocv, } ) ``` -------------------------------- ### Set Up Thevenin ECM Model Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/ecm_multipulse_identification.ipynb Initializes a Thevenin model with two RC elements and updates parameter values. This includes cell capacity, voltage cut-offs, and resistance/capacitance values for both RC branches. ```python model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 2}) parameter_values = pybamm.ParameterValues("ECM_Example") parameter_values.update( { "Cell capacity [A.h]": 3, "Nominal cell capacity [A.h]": 3, "Element-1 initial overpotential [V]": 0, "Upper voltage cut-off [V]": 4.2, "Lower voltage cut-off [V]": 2.5, "R0 [Ohm]": 1e-3, "R1 [Ohm]": 3e-3, "C1 [F]": 5e2, } ) # Optional arguments - only needed for two RC pairs parameter_values.update( { "R2 [Ohm]": 2e-3, "C2 [F]": 3e4, "Element-2 initial overpotential [V]": 0, } ) ``` -------------------------------- ### Set up Optimisation Problem with AdamW Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/getting_started/optimising_with_adamw.ipynb Configures the parameter estimation problem by setting up a simulator, a cost function (SumSquaredError), and the AdamW optimiser. Maximum iterations and unchanged iterations are also set. ```python simulator = pybop.pybamm.Simulator( model, parameter_values=parameter_values, protocol=dataset ) cost = pybop.SumSquaredError(dataset) problem = pybop.Problem(simulator, cost) optim = pybop.AdamW(problem) optim.set_max_unchanged_iterations(40) optim.set_max_iterations(150) # Reduce the momentum influence for the reduced number of optimiser iterations optim.optimiser.b1 = 0.75 optim.optimiser.b2 = 0.75 ``` -------------------------------- ### Run All Benchmarks Quickly Source: https://github.com/pybop-team/pybop/blob/develop/benchmarks/README.md Run all benchmarks once per commit, returning a single value for each. This is useful for quick checks. ```bash asv run --quick ``` -------------------------------- ### Run Optimiser and Print Results Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/comparison_examples/optimiser_calibration.ipynb Executes the optimisation process and prints the true parameter values alongside the estimated values obtained with the initial learning rate. ```python result = optim.run() print("True values:", true_values) print("Estimates:", result.x) ``` -------------------------------- ### Initialize PyBAMM Model and Parameter Values Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/lgm50_pulse_validation.ipynb Initializes a two-RC equivalent circuit model using PyBAMM and sets up initial parameter values. This includes chemistry, initial conditions, cell properties, and model-specific parameters. ```python model = pybamm.equivalent_circuit.Thevenin(options={"number of rc elements": 2}) parameter_values = pybamm.ParameterValues( { "chemistry": "ecm", "Initial SoC": 0.9 - 0.01, "Initial temperature [K]": 25 + 273.15, "Cell capacity [A.h]": 5, "Nominal cell capacity [A.h]": 5, "Ambient temperature [K]": 25 + 273.15, "Current function [A]": 4.85, "Upper voltage cut-off [V]": 4.2, "Lower voltage cut-off [V]": 3.0, "Cell thermal mass [J/K]": 1000, "Cell-jig heat transfer coefficient [W/K]": 10, "Jig thermal mass [J/K]": 500, "Jig-air heat transfer coefficient [W/K]": 10, "Open-circuit voltage [V]": ocv_LGM50, "R0 [Ohm]": 0.005, "Element-1 initial overpotential [V]": 0, "Element-2 initial overpotential [V]": 0, "R1 [Ohm]": 0.0001, "R2 [Ohm]": 0.0001, "C1 [F]": 3000, "C2 [F]": 6924, "Entropic change [V/K]": 0.0004, } ) ``` -------------------------------- ### Define Synthetic Data Model and Parameters Source: https://github.com/pybop-team/pybop/blob/develop/examples/notebooks/battery_parameterisation/echem_identification_pitfalls.ipynb Initializes a detailed lithium-ion DFN model with particle size distribution and sets up parameter values using a predefined dataset ('Chen2020'). It also extracts and sets size distribution parameters. ```python synth_model = pybamm.lithium_ion.DFN(options={"particle size": "distribution"}) parameter_values = pybamm.ParameterValues("Chen2020") parameter_values = pybamm.get_size_distribution_parameters(parameter_values) parameter_values.set_initial_state(0.5); ```