text
stringlengths
865
15.6k
source
stringlengths
21
98
.. Root of all pybamm docs .. Remove the right side-bar for the home page :html_theme.sidebar_secondary.remove: #################### PyBaMM documentation #################### .. This TOC defines what goes in the top navbar .. toctree:: :maxdepth: 1 :hidden: User Guide <source/user_guide/index> source/api/index source/examples/index Contributing <source/user_guide/contributing> **Version**: |version| **Useful links**: `Project Home Page <https://www.pybamm.org>`_ | `Installation <source/user_guide/installation/index.html>`_ | `Source Repository <https://github.com/pybamm-team/pybamm>`_ | `Issue Tracker <https://github.com/pybamm-team/pybamm/issues>`_ | `Discussions <https://github.com/pybamm-team/pybamm/discussions>`_ PyBaMM (Python Battery Mathematical Modelling) is an open-source battery simulation package written in Python. Our mission is to accelerate battery modelling research by providing open-source tools for multi-institutional, interdisciplinary collaboration. Broadly, PyBaMM consists of #. a framework for writing and solving systems of differential equations, #. a library of battery models and parameters, and #. specialized tools for simulating battery-specific experiments and visualizing the results. Together, these enable flexible model definitions and fast battery simulations, allowing users to explore the effect of different battery designs and modeling assumptions under a variety of operating scenarios. .. grid:: 2 .. grid-item-card:: :img-top: _static/index-images/getting_started.svg User Guide ^^^^^^^^^^ The user guide is the best place to start learning PyBaMM. It contains an installation guide, an introduction to the main concepts and links to additional tutorials. +++ .. button-ref:: source/user_guide/index :expand: :color: secondary :click-parent: To the user guide .. grid-item-card:: :img-top: _static/index-images/examples.svg Examples ^^^^^^^^ Examples and tutorials can be viewed on the GitHub examples page, which also provides a link to run them online through Google Colab. +++ .. button-ref:: source/examples/index :expand: :color: secondary :click-parent: To the examples .. grid-item-card:: :img-top: _static/index-images/api.svg API Documentation ^^^^^^^^^^^^^^^^^ The reference guide contains a detailed description of the functions, modules, and objects included in PyBaMM. The reference describes how the methods work and which parameters can be used. +++ .. button-ref:: source/api/index :expand: :color: secondary :click-parent: To the API documentation .. grid-item-card:: :img-top: _static/index-images/contributor.svg Contributor's Guide ^^^^^^^^^^^^^^^^^^^ Contributions to PyBaMM and its development are welcome! If you have ideas for features, bug fixes, models, spatial methods, or solvers, we would love to hear from you. +++ .. button-link:: source/user_guide/contributing.html :expand: :color: secondary :click-parent: To the contributor's guide
PyBaMM/docs/index.rst
# Getting Started The easiest way to use PyBaMM is to run a 1C constant-current discharge with a model of your choice with all the default settings: ```python import pybamm model = pybamm.lithium_ion.DFN() # Doyle-Fuller-Newman model sim = pybamm.Simulation(model) sim.solve([0, 3600]) # solve for 1 hour sim.plot() ``` or simulate an experiment such as a constant-current discharge followed by a constant-current-constant-voltage charge: ```python import pybamm experiment = pybamm.Experiment( [ ( "Discharge at C/10 for 10 hours or until 3.3 V", "Rest for 1 hour", "Charge at 1 A until 4.1 V", "Hold at 4.1 V until 50 mA", "Rest for 1 hour", ) ] * 3, ) model = pybamm.lithium_ion.DFN() sim = pybamm.Simulation(model, experiment=experiment, solver=pybamm.CasadiSolver()) sim.solve() sim.plot() ``` However, much greater customisation is available. It is possible to change the physics, parameter values, geometry, submesh type, number of submesh points, methods for spatial discretisation and solver for integration (see DFN [script](https://github.com/pybamm-team/PyBaMM/blob/develop/examples/scripts/DFN.py) or [notebook](https://github.com/pybamm-team/PyBaMM/blob/develop/docs/source/examples/notebooks/models/DFN.ipynb)). For new users we recommend the [Getting Started](https://github.com/pybamm-team/PyBaMM/tree/develop/docs/source/examples/notebooks/getting_started/) guides. These are intended to be very simple step-by-step guides to show the basic functionality of PyBaMM, and can either be downloaded and used locally, or used online through [Google Colab](https://colab.research.google.com/github/pybamm-team/PyBaMM/blob/main/). Further details can be found in a number of [detailed examples](https://github.com/pybamm-team/PyBaMM/blob/develop/docs/source/examples/index.rst), hosted on GitHub. In addition, full details of classes and methods can be found in the [](api_docs). Additional supporting material can be found [here](https://github.com/pybamm-team/pybamm-supporting-material/).
PyBaMM/docs/source/user_guide/getting_started.md
Install from source (Windows Subsystem for Linux) ================================================= To make it easier to install PyBaMM, we recommend using the Windows Subsystem for Linux (WSL) along with Visual Studio Code. This guide will walk you through the process. Install WSL ----------- Install Ubuntu 22.04 or 20.04 LTS as a distribution for WSL following `Microsoft's guide to install WSL <https://docs.microsoft.com/en-us/windows/wsl/install-win10>`__. For a seamless development environment, refer to `this guide <https://docs.microsoft.com/en-us/windows/wsl/setup/environment>`__. Install PyBaMM -------------- Get PyBaMM's Source Code ~~~~~~~~~~~~~~~~~~~~~~~~ 1. Open a terminal in your Ubuntu distribution by selecting "Ubuntu" from the Start menu. You'll get a bash prompt in your home directory. 2. Install Git by typing the following command: .. code:: bash sudo apt install git-core 3. Clone the PyBaMM repository: .. code:: bash git clone https://github.com/pybamm-team/PyBaMM.git 4. Enter the PyBaMM Directory by running: .. code:: bash cd PyBaMM 5. Follow the Installation Steps ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Follow the `installation instructions for PyBaMM on Linux <gnu-linux-mac.html>`__. Using Visual Studio Code with the WSL --------------------------------------- To use Visual Studio Code with the Windows Subsystem for Linux (WSL), follow these steps: 1. Open Visual Studio Code. 2. Install the "Remote - WSL" extension if not already installed. 3. Open the PyBaMM directory in Visual Studio Code. 4. In the bottom pane, select the "+" sign and choose "New WSL Window." 5. This opens a WSL terminal in the PyBaMM directory within the WSL. Now you can develop and edit PyBaMM code using Visual Studio Code while utilizing the WSL environment.
PyBaMM/docs/source/user_guide/installation/windows-wsl.rst
Install from source (GNU Linux and macOS) ========================================= .. contents:: This page describes the build and installation of PyBaMM from the source code, available on GitHub. Note that this is **not the recommended approach for most users** and should be reserved to people wanting to participate in the development of PyBaMM, or people who really need to use bleeding-edge feature(s) not yet available in the latest released version. If you do not fall in the two previous categories, you would be better off installing PyBaMM using pip or conda. Lastly, familiarity with the Python ecosystem is recommended (pip, virtualenvs). Here is a gentle introduction/refresher: `Python Virtual Environments: A Primer <https://realpython.com/python-virtual-environments-a-primer/>`_. Prerequisites --------------- The following instructions are valid for both GNU/Linux distributions and MacOS. If you are running Windows, consider using the `Windows Subsystem for Linux (WSL) <https://docs.microsoft.com/en-us/windows/wsl/install-win10>`_. To obtain the PyBaMM source code, clone the GitHub repository .. code:: bash git clone https://github.com/pybamm-team/PyBaMM.git or download the source archive on the repository's homepage. To install PyBaMM, you will need: - Python 3 (PyBaMM supports versions 3.8, 3.9, 3.10, 3.11, and 3.12) - The Python headers file for your current Python version. - A BLAS library (for instance `openblas <https://www.openblas.net/>`_). - A C compiler (ex: ``gcc``). - A Fortran compiler (ex: ``gfortran``). - ``graphviz`` (optional), if you wish to build the documentation locally. You can install the above with .. tab:: Ubuntu .. code:: bash sudo apt install python3.X python3.X-dev libopenblas-dev gcc gfortran graphviz Where ``X`` is the version sub-number. .. note:: On Windows, you can install ``graphviz`` using the `Chocolatey <https://chocolatey.org/>`_ package manager, or follow the instructions on the `graphviz website <https://graphviz.org/download/>`_. .. tab:: MacOS .. code:: bash brew install python openblas gcc gfortran graphviz libomp Finally, we recommend using `Nox <https://nox.thea.codes/en/stable/>`_. You can install it with .. code:: bash python3.X -m pip install --user nox Depending on your operating system, you may or may not have ``pip`` installed along Python. If ``pip`` is not found, you probably want to install the ``python3-pip`` package. Installing the build-time requirements -------------------------------------- PyBaMM comes with a DAE solver based on the IDA solver provided by the SUNDIALS library. To use this solver, you must make sure that you have the necessary SUNDIALS components installed on your system. The IDA-based solver is currently unavailable on windows. If you are running windows, you can simply skip this section and jump to :ref:`pybamm-install`. .. code:: bash # in the PyBaMM/ directory nox -s pybamm-requires This will download, compile and install the SuiteSparse and SUNDIALS libraries. Both libraries are installed in ``~/.local``. For users requiring more control over the installation process, the ``pybamm-requires`` session supports additional command-line arguments: - ``--install-dir``: Specify a custom installation directory for SUNDIALS and SuiteSparse. Example: .. code:: bash nox -s pybamm-requires -- --install-dir [custom_directory_path] - ``--force``: Force the installation of SUNDIALS and SuiteSparse, even if they are already found in the specified directory. Example: .. code:: bash nox -s pybamm-requires -- --force Manual install of build time requirements ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ If you'd rather do things yourself, 1. Make sure you have CMake installed 2. Compile and install SuiteSparse (PyBaMM only requires the ``KLU`` component). 3. Compile and install SUNDIALS. 4. Clone the pybind11 repository in the ``PyBaMM/`` directory (make sure the directory is named ``pybind11``). PyBaMM ships with a Python script that automates points 2. and 3. You can run it with .. code:: bash python scripts/install_KLU_Sundials.py This script supports optional arguments for custom installations: - ``--install-dir``: Specify a custom installation directory for SUNDIALS and SuiteSparse. By default, they are installed in ``~/.local``. Example: .. code:: bash python scripts/install_KLU_Sundials.py --install-dir [custom_directory_path] - ``--force``: Force the installation of SUNDIALS and SuiteSparse, even if they are already found in the specified directory. Example: .. code:: bash python scripts/install_KLU_Sundials.py --force .. _pybamm-install: Installing PyBaMM ----------------- You should now have everything ready to build and install PyBaMM successfully. Using ``Nox`` (recommended) ~~~~~~~~~~~~~~~~~~~~~~~~~~~ .. code:: bash # in the PyBaMM/ directory nox -s dev .. note:: It is recommended to use ``--verbose`` or ``-v`` to see outputs of all commands run. This creates a virtual environment ``venv/`` inside the ``PyBaMM/`` directory. It comes ready with PyBaMM and some useful development tools like `pre-commit <https://pre-commit.com/>`_ and `ruff <https://beta.ruff.rs/docs/>`_. You can now activate the environment with .. tab:: GNU/Linux and MacOS .. code:: bash source venv/bin/activate .. tab:: Windows .. code:: bash venv\Scripts\activate.bat and run the tests to check your installation. Manual install ~~~~~~~~~~~~~~ From the ``PyBaMM/`` directory, you can install PyBaMM using .. code:: bash pip install . If you intend to contribute to the development of PyBaMM, it is convenient to install in "editable mode", along with all the optional dependencies and useful tools for development and documentation: .. code:: bash pip install -e .[all,dev,docs] If you are using ``zsh``, you would need to use different pattern matching: .. code:: bash pip install -e '.[all,dev,docs]' Before you start contributing to PyBaMM, please read the `contributing guidelines <https://github.com/pybamm-team/PyBaMM/blob/develop/CONTRIBUTING.md>`__. Running the tests ----------------- Using Nox (recommended) ~~~~~~~~~~~~~~~~~~~~~~~ You can use ``Nox`` to run the unit tests and example notebooks in isolated virtual environments. The default command .. code:: bash nox will run pre-commit, install ``Linux`` and ``macOS`` dependencies, and run the unit tests. This can take several minutes. To just run the unit tests, use .. code:: bash nox -s unit Similarly, to run the integration tests, use .. code:: bash nox -s integration Finally, to run the unit and the integration suites sequentially, use .. code:: bash nox -s tests Using the test runner ~~~~~~~~~~~~~~~~~~~~~~ You can run unit tests for PyBaMM using .. code:: bash # in the PyBaMM/ directory python run-tests.py --unit The above starts a sub-process using the current python interpreter (i.e. using your current Python environment) and run the unit tests. This can take a few minutes. You can also use the test runner to run the doctests: .. code:: bash python run-tests.py --doctest There is more to the PyBaMM test runner. To see a list of all options, type .. code:: bash python run-tests.py --help How to build the PyBaMM documentation ------------------------------------- The documentation is built using .. code:: bash nox -s docs This will build the documentation and serve it locally (thanks to `sphinx-autobuild <https://github.com/GaretJax/sphinx-autobuild>`_) for preview. The preview will be updated automatically following changes. Doctests, examples, and coverage -------------------------------- ``Nox`` can also be used to run doctests, run examples, and generate a coverage report using: - ``nox -s examples``: Run the Jupyter notebooks in ``docs/source/examples/notebooks/``. - ``nox -s examples -- <path-to-notebook-1.ipynb> <path-to_notebook-2.ipynb>``: Run specific Jupyter notebooks. - ``nox -s scripts``: Run the example scripts in ``examples/scripts/``. - ``nox -s doctests``: Run doctests. - ``nox -s coverage``: Measure current test coverage and generate a coverage report. - ``nox -s quick``: Run integration tests, unit tests, and doctests sequentially. Extra tips while using ``Nox`` ------------------------------ Here are some additional useful commands you can run with ``Nox``: - ``--verbose or -v``: Enables verbose mode, providing more detailed output during the execution of Nox sessions. - ``--list or -l``: Lists all available Nox sessions and their descriptions. - ``--stop-on-first-error``: Stops the execution of Nox sessions immediately after the first error or failure occurs. - ``--envdir <path>``: Specifies the directory where Nox creates and manages the virtual environments used by the sessions. In this case, the directory is set to ``<path>``. - ``--install-only``: Skips the test execution and only performs the installation step defined in the Nox sessions. - ``--nocolor``: Disables the color output in the console during the execution of Nox sessions. - ``--report output.json``: Generates a JSON report of the Nox session execution and saves it to the specified file, in this case, "output.json". - ``nox -s docs --non-interactive``: Builds the documentation without serving it locally (using ``sphinx-build`` instead of ``sphinx-autobuild``). Troubleshooting --------------- **Problem:** I have made edits to source files in PyBaMM, but these are not being used when I run my Python script. **Solution:** Make sure you have installed PyBaMM using the ``-e`` flag, i.e. ``pip install -e .``. This sets the installed location of the source files to your current directory. **Problem:** Errors when solving model ``ValueError: Integrator name ida does not exist``, or ``ValueError: Integrator name cvode does not exist``. **Solution:** This could mean that you have not installed ``scikits.odes`` correctly, check the instructions given above and make sure each command was successful. One possibility is that you have not set your ``LD_LIBRARY_PATH`` to point to the sundials library, type ``echo $LD_LIBRARY_PATH`` and make sure one of the directories printed out corresponds to where the SUNDIALS libraries are located. Another common reason is that you forget to install a BLAS library such as OpenBLAS before installing SUNDIALS. Check the cmake output when you configured SUNDIALS, it might say: :: -- A library with BLAS API not found. Please specify library location. -- LAPACK requires BLAS If this is the case, on a Debian or Ubuntu system you can install OpenBLAS using ``sudo apt-get install libopenblas-dev`` (or ``brew install openblas`` for Mac OS) and then re-install SUNDIALS using the instructions above.
PyBaMM/docs/source/user_guide/installation/install-from-source.rst
Install from source (Docker) ============================ .. contents:: This page describes the build and installation of PyBaMM using a Dockerfile, available on GitHub. Note that this is **not the recommended approach for most users** and should be reserved to people wanting to participate in the development of PyBaMM, or people who really need to use bleeding-edge feature(s) not yet available in the latest released version. If you do not fall in the two previous categories, you would be better off installing PyBaMM using ``pip`` or ``conda``. Prerequisites ------------- Before you begin, make sure you have Docker installed on your system. You can download and install Docker from the official `Docker website <https://www.docker.com/get-started/>`_. Ensure Docker installation by running: .. code:: bash docker --version Pulling the Docker image ------------------------ Use the following command to pull the PyBaMM Docker image from Docker Hub: .. tab:: No optional solver .. code:: bash docker pull pybamm/pybamm:latest .. tab:: Scikits.odes solver .. code:: bash docker pull pybamm/pybamm:odes .. tab:: JAX solver .. code:: bash docker pull pybamm/pybamm:jax .. tab:: IDAKLU solver .. code:: bash docker pull pybamm/pybamm:idaklu .. tab:: All solvers .. code:: bash docker pull pybamm/pybamm:all Running the Docker container ---------------------------- Once you have pulled the Docker image, you can run a Docker container with the PyBaMM environment: 1. In your terminal, use the following command to start a Docker container from the pulled image: .. tab:: Basic .. code:: bash docker run -it pybamm/pybamm:latest .. tab:: ODES Solver .. code:: bash docker run -it pybamm/pybamm:odes .. tab:: JAX Solver .. code:: bash docker run -it pybamm/pybamm:jax .. tab:: IDAKLU Solver .. code:: bash docker run -it pybamm/pybamm:idaklu .. tab:: All Solver .. code:: bash docker run -it pybamm/pybamm:all 2. You will now be inside the Docker container's shell. You can use PyBaMM and its dependencies as if you were in a virtual environment. 3. You can execute PyBaMM-related commands, run tests develop & contribute from the container. Exiting the Docker container ---------------------------- To exit the Docker container's shell, you can simply type: .. code-block:: bash exit This will return you to your host machine's terminal. Building Docker image locally from source ----------------------------------------- If you want to build the PyBaMM Docker image locally from the PyBaMM source code, follow these steps: 1. Clone the PyBaMM GitHub repository to your local machine if you haven't already: .. code-block:: bash git clone https://github.com/pybamm-team/PyBaMM.git 2. Change into the PyBaMM directory: .. code-block:: bash cd PyBaMM 3. Build the Docker image using the following command: .. code-block:: bash docker build -t pybamm -f scripts/Dockerfile . 4. Once the image is built, you can run a Docker container using: .. code-block:: bash docker run -it pybamm 5. Activate PyBaMM development environment inside docker container using: .. code-block:: bash conda activate pybamm Building Docker images with optional arguments ---------------------------------------------- When building the PyBaMM Docker images locally, you have the option to include specific solvers by using optional arguments. These solvers include: - ``IDAKLU``: For IDA solver provided by the SUNDIALS plus KLU. - ``ODES``: For scikits.odes solver for ODE & DAE problems. - ``JAX``: For Jax solver. - ``ALL``: For all the above solvers. To build the Docker images with optional arguments, you can follow these steps for each solver: .. tab:: Scikits.odes solver .. code-block:: bash docker build -t pybamm:odes -f scripts/Dockerfile --build-arg ODES=true . .. tab:: JAX solver .. code-block:: bash docker build -t pybamm:jax -f scripts/Dockerfile --build-arg JAX=true . .. tab:: IDAKLU solver .. code-block:: bash docker build -t pybamm:idaklu -f scripts/Dockerfile --build-arg IDAKLU=true . .. tab:: All solvers .. code-block:: bash docker build -t pybamm:all -f scripts/Dockerfile --build-arg ALL=true . After building the Docker images with the desired solvers, use the ``docker run`` command followed by the desired image name. For example, to run a container from the image built with all optional solvers: .. code-block:: bash docker run -it pybamm:all Activate PyBaMM development environment inside docker container using: .. code-block:: bash conda activate pybamm If you want to exit the Docker container's shell, you can simply type: .. code-block:: bash exit Using Git inside a running Docker container ------------------------------------------- .. note:: You might require re-configuring git while running the docker container for the first time. You can run ``git config --list`` to ensure if you have desired git configuration already. 1. Setting up git configuration .. code-block:: bash git config --global user.name "Your Name" git config --global user.email [email protected] 2. Setting a git remote .. code-block:: bash git remote set-url origin <fork_url> git remote add upstream https://github.com/pybamm-team/PyBaMM git fetch --all Using Visual Studio Code inside a running Docker container ---------------------------------------------------------- You can easily use Visual Studio Code inside a running Docker container by attaching it directly. This provides a seamless development environment within the container. Here's how: 1. Install the "Docker" extension from Microsoft in your local Visual Studio Code if it's not already installed. 2. Pull and run the Docker image containing PyBaMM development environment. 3. In your local Visual Studio Code, open the "Docker" extension by clicking on the Docker icon in the sidebar. 4. Under the "Containers" section, you'll see a list of running containers. Right-click the running PyBaMM container. 5. Select "Attach Visual Studio Code" from the context menu. 6. Visual Studio Code will now connect to the container, and a new VS Code window will open up, running inside the container. You can now edit, debug, and work on your code using VS Code as if you were working directly on your local machine.
PyBaMM/docs/source/user_guide/installation/install-from-docker.rst
Installation ============ PyBaMM is available on GNU/Linux, MacOS and Windows. It can be installed using ``pip`` or ``conda``, or from source. .. tab:: GNU/Linux and Windows .. tab:: pip PyBaMM can be installed via pip from `PyPI <https://pypi.org/project/pybamm>`__. .. code:: bash pip install pybamm .. tab:: conda PyBaMM is part of the `Anaconda <https://docs.continuum.io/anaconda/>`_ distribution and is available as a conda package through the conda-forge channel. .. code:: bash conda install -c conda-forge pybamm .. tab:: macOS .. tab:: pip PyBaMM can be installed via pip from `PyPI <https://pypi.org/project/pybamm>`__. .. code:: bash brew install sundials && pip install pybamm .. tab:: conda PyBaMM is part of the `Anaconda <https://docs.continuum.io/anaconda/>`_ distribution and is available as a conda package through the conda-forge channel. .. code:: bash conda install -c conda-forge pybamm Optional solvers ---------------- Following GNU/Linux and macOS solvers are optionally available: * `scikits.odes <https://scikits-odes.readthedocs.io/en/latest/>`_ -based solver, see `Optional - scikits.odes solver <https://docs.pybamm.org/en/latest/source/user_guide/installation/gnu-linux-mac.html#optional-scikits-odes-solver>`_. * `jax <https://jax.readthedocs.io/en/latest/notebooks/quickstart.html>`_ -based solver, see `Optional - JaxSolver <https://docs.pybamm.org/en/latest/source/user_guide/installation/gnu-linux-mac.html#optional-jaxsolver>`_. Dependencies ------------ .. _install.required_dependencies: Required dependencies ~~~~~~~~~~~~~~~~~~~~~ PyBaMM requires the following dependencies. ================================================================ ========================== Package Minimum supported version ================================================================ ========================== `NumPy <https://numpy.org>`__ 1.23.5 `SciPy <https://docs.scipy.org/doc/scipy/>`__ 1.9.3 `CasADi <https://web.casadi.org/docs/>`__ 3.6.3 `Xarray <https://docs.xarray.dev/en/stable/>`__ 2022.6.0 `Anytree <https://anytree.readthedocs.io/en/stable/>`__ 2.8.0 ================================================================ ========================== .. _install.optional_dependencies: Optional Dependencies ~~~~~~~~~~~~~~~~~~~~~ PyBaMM has a number of optional dependencies for different functionalities. If the optional dependency is not installed, PyBaMM will raise an ImportError when the method requiring that dependency is called. If you are using ``pip``, optional PyBaMM dependencies can be installed or managed in a file (e.g., setup.py, or pyproject.toml) as optional extras (e.g.,``pybamm[dev,plot]``). All optional dependencies can be installed with ``pybamm[all]``, and specific sets of dependencies are listed in the sections below. .. _install.plot_dependencies: Plot dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[plot]"`` =========================================================== ================== ================== ================================================================== Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ================================================================== `imageio <https://imageio.readthedocs.io/en/stable/>`__ 2.3.0 plot For generating simulation GIFs. `matplotlib <https://matplotlib.org/stable/>`__ 3.6.0 plot To plot various battery models, and analyzing battery performance. =========================================================== ================== ================== ================================================================== .. _install.pandas_dependencies: Pandas dependencies ^^^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[pandas]"`` =========================================================== ================== ================== ================================================================== Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ================================================================== `pandas <https://pandas.pydata.org/docs/>`__ 1.5.0 pandas For data manipulation and analysis. =========================================================== ================== ================== ================================================================== .. _install.docs_dependencies: Docs dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[docs]"`` ================================================================================================= ================== ================== ======================================================================= Dependency Minimum Version pip extra Notes ================================================================================================= ================== ================== ======================================================================= `sphinx <https://www.sphinx-doc.org/en/master/>`__ \- docs Sphinx makes it easy to create intelligent and beautiful documentation. `pydata-sphinx-theme <https://pydata-sphinx-theme.readthedocs.io/en/stable/>`__ \- docs A clean, Bootstrap-based Sphinx theme. `sphinx_design <https://sphinx-design.readthedocs.io/en/latest/>`__ \- docs A sphinx extension for designing. `sphinx-copybutton <https://sphinx-copybutton.readthedocs.io/en/latest/>`__ \- docs To copy codeblocks. `myst-parser <https://myst-parser.readthedocs.io/en/latest/>`__ \- docs For technical & scientific documentation. `sphinx-inline-tabs <https://sphinx-inline-tabs.readthedocs.io/en/latest/>`__ \- docs Add inline tabbed content to your Sphinx documentation. `sphinxcontrib-bibtex <https://sphinxcontrib-bibtex.readthedocs.io/en/latest/>`__ \- docs For BibTeX citations. `sphinx-autobuild <https://sphinx-extensions.readthedocs.io/en/latest/sphinx-autobuild.html>`__ \- docs For re-building docs once triggered. ================================================================================================= ================== ================== ======================================================================= .. _install.examples_dependencies: Examples dependencies ^^^^^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[examples]"`` ================================================================================ ================== ================== ================================ Dependency Minimum Version pip extra Notes ================================================================================ ================== ================== ================================ `jupyter <https://docs.jupyter.org/en/latest/>`__ \- examples For example notebooks rendering. ================================================================================ ================== ================== ================================ .. _install.dev_dependencies: Dev dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[dev]"`` ================================================================================ ================== ================== ============================================================= Dependency Minimum Version pip extra Notes ================================================================================ ================== ================== ============================================================= `pre-commit <https://pre-commit.com/index.html>`__ \- dev For managing and maintaining multi-language pre-commit hooks. `ruff <https://beta.ruff.rs/docs/>`__ \- dev For code formatting. `nox <https://nox.thea.codes/en/stable/>`__ \- dev For running testing sessions in multiple environments. `coverage <https://coverage.readthedocs.io/en/>`__ \- dev For calculating coverage of tests. `pytest <https://docs.pytest.org/en/stable/>`__ 6.0.0 dev For running Jupyter notebooks tests. `pytest-xdist <https://pytest-xdist.readthedocs.io/en/latest/>`__ \- dev For running tests in parallel across distributed workers. `nbmake <https://github.com/treebeardtech/nbmake/>`__ \- dev A ``pytest`` plugin for executing Jupyter notebooks. ================================================================================ ================== ================== ============================================================= .. _install.cite_dependencies: Cite dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[cite]"`` =========================================================== ================== ================== ========================================= Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ========================================= `pybtex <https://docs.pybtex.org/>`__ 0.24.0 cite BibTeX-compatible bibliography processor. =========================================================== ================== ================== ========================================= .. _install.latexify_dependencies: Latexify dependencies ^^^^^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[latexify]"`` =========================================================== ================== ================== ========================= Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ========================= `sympy <https://docs.sympy.org/latest/index.html>`__ 1.9.3 latexify For symbolic mathematics. =========================================================== ================== ================== ========================= .. _install.bpx_dependencies: bpx dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[bpx]"`` =========================================================== ================== ================== ========================== Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ========================== `bpx <https://pypi.org/project/bpx/>`__ \- bpx Battery Parameter eXchange =========================================================== ================== ================== ========================== .. _install.tqdm_dependencies: tqdm dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[tqdm]"`` =========================================================== ================== ================== ================== Dependency Minimum Version pip extra Notes =========================================================== ================== ================== ================== `tqdm <https://tqdm.github.io/>`__ \- tqdm For logging loops. =========================================================== ================== ================== ================== .. _install.jax_dependencies: Jax dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[jax]"``, currently supported on Python 3.9-3.11. ========================================================================= ================== ================== ======================= Dependency Minimum Version pip extra Notes ========================================================================= ================== ================== ======================= `JAX <https://jax.readthedocs.io/en/latest/notebooks/quickstart.html>`__ 0.4.20 jax For the JAX solver `jaxlib <https://pypi.org/project/jaxlib/>`__ 0.4.20 jax Support library for JAX ========================================================================= ================== ================== ======================= .. _install.odes_dependencies: odes dependencies ^^^^^^^^^^^^^^^^^ Installable with ``pip install "pybamm[odes]"`` ======================================================================================================================================= ================== ================== ============================= Dependency Minimum Version pip extra Notes ======================================================================================================================================= ================== ================== ============================= `scikits.odes <https://docs.pybamm.org/en/latest/source/user_guide/installation/gnu-linux-mac.html#optional-scikits-odes-solver>`__ \- odes For scikits ODE & DAE solvers ======================================================================================================================================= ================== ================== ============================= .. note:: Before running ``pip install "pybamm[odes]"``, make sure to install ``scikits.odes`` build-time requirements as described `here <https://docs.pybamm.org/en/latest/source/user_guide/installation/gnu-linux-mac.html#optional-scikits-odes-solver>`_ . Full installation guide ----------------------- Installing a specific version? Installing from source? Check the advanced installation pages below .. toctree:: :maxdepth: 1 gnu-linux-mac windows windows-wsl install-from-source install-from-docker
PyBaMM/docs/source/user_guide/installation/index.rst
Windows ======= .. contents:: Prerequisites ------------- To use PyBaMM, you must have Python 3.8, 3.9, 3.10, 3.11, or 3.12 installed. To install Python 3 download the installation files from `Python’s website <https://www.python.org/downloads/windows/>`__. Make sure to tick the box on ``Add Python 3.X to PATH``. For more detailed instructions please see the `official Python on Windows guide <https://docs.python.org/3.9/using/windows.html>`__. Install PyBaMM -------------- User install ~~~~~~~~~~~~ Launch the Command Prompt and go to the directory where you want to install PyBaMM. You can find a reminder of how to navigate the terminal `here <http://www.cs.columbia.edu/~sedwards/classes/2015/1102-fall/Command%20Prompt%20Cheatsheet.pdf>`__. We recommend to install PyBaMM within a virtual environment, in order not to alter any distribution python files. To install ``virtualenv``, type: .. code:: bash python -m pip install virtualenv To create a virtual environment ``env`` within your current directory type: .. code:: bash python -m virtualenv env You can then “activate” the environment using: .. code:: env\Scripts\activate.bat Now all the calls to pip described below will install PyBaMM and its dependencies into the environment ``env``. When you are ready to exit the environment and go back to your original system, just type: .. code:: bash deactivate PyBaMM can be installed via pip: .. code:: bash pip install pybamm PyBaMM’s dependencies (such as ``numpy``, ``scipy``, etc) will be installed automatically when you install PyBaMM using ``pip``. For an introduction to virtual environments, see (https://realpython.com/python-virtual-environments-a-primer/). Optional - JaxSolver ~~~~~~~~~~~~~~~~~~~~ Users can install ``jax`` and ``jaxlib`` to use the Jax solver. .. note:: The Jax solver is only supported for Python versions 3.9 through 3.12. .. code:: bash pip install "pybamm[jax]" The ``pip install "pybamm[jax]"`` command automatically downloads and installs ``pybamm`` and the compatible versions of ``jax`` and ``jaxlib`` on your system. (``pybamm_install_jax`` is deprecated.) Uninstall PyBaMM ---------------- PyBaMM can be uninstalled by running .. code:: bash pip uninstall pybamm in your virtual environment. Installation using WSL ---------------------- If you want to install the optional PyBaMM solvers, you have to use the Windows Subsystem for Linux (WSL). You can find the installation instructions `here <windows-wsl.html>`__.
PyBaMM/docs/source/user_guide/installation/windows.rst
GNU/Linux & macOS ================= .. contents:: Prerequisites ------------- To use PyBaMM, you must have Python 3.8, 3.9, 3.10, 3.11, or 3.12 installed. .. tab:: Debian-based distributions (Debian, Ubuntu, Linux Mint) To install Python 3 on Debian-based distributions (Debian, Ubuntu, Linux Mint), open a terminal and run .. code:: bash sudo apt update sudo apt install python3 .. tab:: Fedora/CentOS On Fedora or CentOS, you can use DNF or Yum. For example .. code:: bash sudo dnf install python3 .. tab:: macOS On macOS, you can use the ``homebrew`` package manager. First, `install brew <https://docs.python-guide.org/starting/install3/osx/>`__: .. code:: bash ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" then follow instructions in the link on adding ``brew`` to path, and run .. code:: bash brew install python3 Install PyBaMM -------------- .. _user-install-label: User install ~~~~~~~~~~~~ We recommend to install PyBaMM within a virtual environment, in order not to alter any distribution Python files. First, make sure you are using Python 3.8, 3.9, 3.10, 3.11, or 3.12. To create a virtual environment ``env`` within your current directory type: .. code:: bash virtualenv env You can then “activate” the environment using: .. code:: bash source env/bin/activate Now all the calls to pip described below will install PyBaMM and its dependencies into the environment ``env``. When you are ready to exit the environment and go back to your original system, just type: .. code:: bash deactivate PyBaMM can be installed via pip. On macOS, it is necessary to install the `SUNDIALS <https://computing.llnl.gov/projects/sundials/>`__ library beforehand. .. tab:: GNU/Linux In a terminal, run the following command: .. code:: bash pip install pybamm .. tab:: macOS In a terminal, run the following commands: .. code:: bash brew install sundials pip install pybamm PyBaMM’s required dependencies (such as ``numpy``, ``casadi``, etc) will be installed automatically when you install PyBaMM using ``pip``. For an introduction to virtual environments, see (https://realpython.com/python-virtual-environments-a-primer/). .. _scikits.odes-label: Optional - scikits.odes solver ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Users can install `scikits.odes <https://github.com/bmcage/odes>`__ to utilize its interfaced SUNDIALS ODE and DAE `solvers <https://docs.pybamm.org/en/latest/source/api/solvers/scikits_solvers.html>`__ wrapped in PyBaMM. .. note:: Currently, only GNU/Linux and macOS are supported. .. note:: The ``scikits.odes`` solver is not supported on Python 3.12 yet. Please refer to https://github.com/bmcage/odes/issues/162. There is support for Python 3.8, 3.9, 3.10, and 3.11. .. tab:: GNU/Linux In a terminal, run the following commands: .. code:: bash apt-get install libopenblas-dev pip install wget cmake pybamm_install_odes system (under ``~/.local``), before installing ``scikits.odes``. (Alternatively, one can install SUNDIALS without this script and run ``pip install pybamm[odes]`` to install ``pybamm`` with ``scikits.odes``.) .. tab:: macOS In a terminal, run the following command: .. code:: bash brew install openblas gcc gfortran pip install wget cmake pybamm_install_odes The ``pybamm_install_odes`` command, installed with PyBaMM, automatically downloads and installs the SUNDIALS library on your system (under ``~/.local``), before installing `scikits.odes <https://scikits-odes.readthedocs.io/en/stable/installation.html>`__ . (Alternatively, one can install SUNDIALS without this script and run ``pip install pybamm[odes]`` to install ``pybamm`` with `scikits.odes <https://scikits-odes.readthedocs.io/en/stable/installation.html>`__) To avoid installation failures when using ``pip install pybamm[odes]``, make sure to set the ``SUNDIALS_INST`` environment variable. If you have installed SUNDIALS using Homebrew, set the variable to the appropriate location. For example: .. code:: bash export SUNDIALS_INST=$(brew --prefix sundials) Ensure that the path matches the installation location on your system. You can verify the installation location by running: .. code:: bash brew info sundials Look for the installation path, and use that path to set the ``SUNDIALS_INST`` variable. Note: The location where Homebrew installs SUNDIALS might vary based on the system architecture (ARM or Intel). Adjust the path in the ``export SUNDIALS_INST`` command accordingly. To avoid manual setup of path the ``pybamm_install_odes`` is recommended for a smoother installation process, as it takes care of automatically downloading and installing the SUNDIALS library on your system. Optional - JaxSolver ~~~~~~~~~~~~~~~~~~~~ Users can install ``jax`` and ``jaxlib`` to use the Jax solver. .. note:: The Jax solver is only supported for Python versions 3.9 through 3.12. .. code:: bash pip install "pybamm[jax]" The ``pip install "pybamm[jax]"`` command automatically downloads and installs ``pybamm`` and the compatible versions of ``jax`` and ``jaxlib`` on your system. (``pybamm_install_jax`` is deprecated.) Uninstall PyBaMM ---------------- PyBaMM can be uninstalled by running .. code:: bash pip uninstall pybamm in your virtual environment.
PyBaMM/docs/source/user_guide/installation/gnu-linux-mac.rst
# Fundamentals PyBaMM (Python Battery Mathematical Modelling) is an open-source battery simulation package written in Python. Our mission is to accelerate battery modelling research by providing open-source tools for multi-institutional, interdisciplinary collaboration. Broadly, PyBaMM consists of 1. a framework for writing and solving systems of differential equations, 2. a library of battery models and parameters, and 3. specialized tools for simulating battery-specific experiments and visualizing the results. Together, these enable flexible model definitions and fast battery simulations, allowing users to explore the effect of different battery designs and modeling assumptions under a variety of operating scenarios. > **NOTE**: This user-guide is a work-in-progress, we hope that this brief but incomplete overview will be useful to you. ## Core framework The core of the framework is a custom computer algebra system to define mathematical equations, and a domain specific modeling language to combine these equations into systems of differential equations (usually partial differential equations for variables depending on space and time). The [expression tree](https://github.com/pybamm-team/PyBaMM/blob/develop/docs/source/examples/notebooks/expression_tree/expression-tree.ipynb) example gives an introduction to the computer algebra system, and the [Getting Started](https://github.com/pybamm-team/PyBaMM/tree/develop/docs/source/examples/notebooks/getting_started/) tutorials walk through creating models of increasing complexity. Once a model has been defined symbolically, PyBaMM solves it using the Method of Lines. First, the equations are discretised in the spatial dimension, using the finite volume method. Then, the resulting system is solved using third-party numerical solvers. Depending on the form of the model, the system can be ordinary differential equations (ODEs) (if only `model.rhs` is defined), or algebraic equations (if only `model.algebraic` is defined), or differential-algebraic equations (DAEs) (if both `model.rhs` and `model.algebraic` are defined). Jupyter notebooks explaining the solvers can be found [here](https://github.com/pybamm-team/PyBaMM/tree/develop/docs/source/examples/notebooks/solvers). ## Model and Parameter Library PyBaMM contains an extensive library of battery models and parameters. The bulk of the library consists of models for lithium-ion, but there are also some other chemistries (lead-acid, lithium metal). Models are first divided broadly into common named models of varying complexity, such as the single particle model (SPM) or Doyle-Fuller-Newman model (DFN). Most options can be applied to any model, but some are model-specific (an error will be raised if you attempt to set an option is not compatible with a model). See [](base_battery_model) for a list of options. The parameter library is simply a collection of python files each defining a complete set of parameters for a particular battery chemistry, covering all major lithium-ion chemistries (NMC, LFP, NCA, ...). External parameter sets can be linked using entry points (see [](parameter_sets)). ## Battery-specific tools One of PyBaMM's unique features is the `Experiment` class, which allows users to define synthetic experiments using simple instructions in English ```python pybamm.Experiment( [ ( "Discharge at C/10 for 10 hours or until 3.3 V", "Rest for 1 hour", "Charge at 1 A until 4.1 V", "Hold at 4.1 V until 50 mA", "Rest for 1 hour", ) ] * 3, ) ``` The above instruction will conduct a standard discharge / rest / charge / rest cycle three times, with a 10 hour discharge and 1 hour rest at the end of each cycle. The `Simulation` class handles simulating an `Experiment`, as well as calculating additional outputs such as capacity as a function of cycle number. For example, the following code will simulate the experiment above and plot the standard output variables: ```python import pybamm import matplotlib.pyplot as plt # load model and parameter values model = pybamm.lithium_ion.DFN() sim = pybamm.Simulation(model, experiment=experiment) solution = sim.solve() solution.plot() ``` Finally, PyBaMM provides custom visualization tools: - [](quick_plot): for easily plotting simulation outputs in a grid, including comparing multiple simulations - [](pybamm.plot_voltage_components): for plotting the component overpotentials that make up a voltage curve Users are not limited to these tools and can plot the output of a simulation solution by accessing the underlying numpy array for the solution variables as ```python solution["variable name"].data ``` and using the plotting library of their choice.
PyBaMM/docs/source/user_guide/fundamentals/index.md
# Battery Models References for the battery models used in PyBaMM simulations can be found calling ```python pybamm.print_citations() ``` However, a few papers are provided in this section for anyone interested in reading the theory behind the models before doing the tutorials. ## Review Articles [Review of physics-based lithium-ion battery models](https://doi.org/10.1088/2516-1083/ac7d31) [Review of parameterisation and a novel database for Li-ion battery models](https://doi.org/10.1088/2516-1083/ac692c) ## Model References ### Lithium-Ion Batteries [Doyle-Fuller-Newman model](https://doi.org/10.1149/1.2221597) [Single particle model](https://doi.org/10.1149/2.0341915jes) ### Lead-Acid Batteries [Isothermal porous-electrode model](https://doi.org/10.1149/2.0301910jes) [Leading-Order Quasi-Static model](https://doi.org/10.1149/2.0441908jes)
PyBaMM/docs/source/user_guide/fundamentals/battery_models.md
# Tutorial 9 - Changing the mesh In [Tutorial 8](./tutorial-8-solver-options.ipynb) we saw how to change the solver options. In this tutorial we will change the mesh used in the simulation, and show how to investigate the influence of the mesh on the solution. All models in PyBaMM have a default number of mesh points used in a simulation. However, depending on things like the operating conditions you are simulating or the parameters you are using, you may find you need to increase the number points in the mesh to obtain an accurate solution. On the other hand, you may find that you are able to decrease the number of mesh points and still obtain a solution with an acceptable degree of accuracy but in a shorter amount of computational time. It is always good practice to conduct a mesh refinement study, where you simulate the same problem with a finer mesh and compare the results. Here will show how to do this graphically, but in practice you may wish to do a more detailed calculation of the relative error. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` ## Changing the number of points in the mesh First we load a model ``` model = pybamm.lithium_ion.SPMe() ``` We can then look at the default number of points, which are stored as a dictionary whose keys are the variables for each domain ``` model.default_var_pts ``` To run a simulation with a different number of points we can define our own dictionary ``` # create our dictionary var_pts = { "x_n": 10, # negative electrode "x_s": 10, # separator "x_p": 10, # positive electrode "r_n": 10, # negative particle "r_p": 10, # positive particle } ``` We then create and solve a simulation, passing the dictionary of points as a keyword argument ``` sim = pybamm.Simulation(model, var_pts=var_pts) sim.solve([0, 3600]) ``` and plot the solution in the usual way ``` sim.plot() ``` ## Conducting a mesh refinement study In order to investigate the influence of the mesh on the solution we must solve the model multiple times, increasing the mesh resolution as we go. We first create a list of the number of points per domain we would like to use ``` npts = [4, 8, 16, 32, 64] ``` and now we can loop over the list, creating and solving simulations as we go. The solutions are stored in the list `solutions` ``` # choose model and parameters model = pybamm.lithium_ion.DFN() parameter_values = pybamm.ParameterValues("Ecker2015") # choose solver solver = pybamm.CasadiSolver(mode="fast") # loop over number of mesh points solutions = [] for N in npts: var_pts = { "x_n": N, # negative electrode "x_s": N, # separator "x_p": N, # positive electrode "r_n": N, # negative particle "r_p": N, # positive particle } sim = pybamm.Simulation( model, solver=solver, parameter_values=parameter_values, var_pts=var_pts ) sim.solve([0, 3600]) solutions.append(sim.solution) ``` We can now pass our list of solutions to the dynamic plot method, allowing use to see the influence of the mesh on the computed voltage. We pass our list of points using the `labels` keyword so that the plots are labeled with the number of points used in the simulation ``` pybamm.dynamic_plot(solutions, ["Voltage [V]"], time_unit="seconds", labels=npts) ``` In the [next tutorial](./tutorial-10-creating-a-model.ipynb) we show how to create a basic model from scratch in PyBaMM. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-9-changing-the-mesh.ipynb
# Tutorial 11 - Creating a submodel In [Tutorial 10](./tutorial-10-creating-a-model.ipynb) we showed how to create a simple model from scratch in PyBaMM. In this tutorial we will solve the same problem, but using separate submodels for the linear diffusion problem and the model for the surface flux. In this simple example the surface flux is just some known function of the concentration, so we could just explicitly define it in the model for diffusion. However, we write it as a separate model to show how submodels interact. We solved the problem of linear diffusion on a unit sphere with a flux at the boundary that depends on the concentration $$ \frac{\partial c}{\partial t} = \nabla \cdot (\nabla c), $$ with the following boundary and initial conditions: $$ \left.\frac{\partial c}{\partial r}\right\vert_{r=0} = 0, \quad \left.\frac{\partial c}{\partial r}\right\vert_{r=1} = -j, \quad \left.c\right\vert_{t=0} = c_0, $$ where $$ j = \left.j_0(1-c)^{1/2}c^{1/2}\right\vert_{r=1} $$ Here $c_0$ and $j_0$ are parameters we can control. Again we will assume that everything is non-dimensional and focus on how to set up and solve the model rather than any specific physical interpretation. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` ## Setting up the model Again we start with an empty `BaseModel` class ``` model = pybamm.BaseModel() ``` Next we set up the submodel for diffusion in the particle using a `pybamm.BaseSubModel`. Each submodel has methods that define the variables, equations, initial and boundary conditions corresponding to the physics the model describes. First `get_fundamental_variables` defines any variables that can be defined independently of any other submodels that may be included in our model. Here we can define the concentration, surface concentration and flux, and add them to the dictionary of variables. Next we can use `get_coupled_variables` to define any variables that _do_ depend on variables defined in another submodel. In this simple example we don't have any variables to define here. However, if we had included a temperature dependent diffusivity, for example, then we would have needed to define the flux in `get_coupled_variables` since it would now depend on the temperature which would be defined in a separate submodel. Once we have defined all the variables we need we can write down our equations. Any equations that include time derivatives will turn into ordinary differential equations after discretisation. We set the right hand sides of such equations in the `set_rhs` method. In this example we add the right hand side of the diffusion equation to the `rhs` dictionary. Equations that don't contain time derivatives give algebraic constraints in our model. These equations are set in the `set_algebraic` method. In this example we don't have any algebraic equations, so we can skip this method. Finally we set the boundary and initial conditions using the methods `set_boundary_conditions` and `set_initial_conditions`, respectively. ``` class Particle(pybamm.BaseSubModel): def __init__(self, param, domain, options=None): super().__init__(param, domain, options=options) def get_fundamental_variables(self): # create concentration variable c = pybamm.Variable("Concentration", domain="negative particle") # define concentration at the surface of the sphere c_surf = pybamm.surf(c) # define flux N = -pybamm.grad(c) # create dictionary of model variables variables = { "Concentration": c, "Surface concentration": c_surf, "Flux": N, } return variables def get_coupled_variables(self, variables): return variables def set_rhs(self, variables): # extract the variables we need c = variables["Concentration"] N = variables["Flux"] # define the rhs of the PDE dcdt = -pybamm.div(N) # add it to the submodel dictionary self.rhs = {c: dcdt} def set_algebraic(self, variables): pass def set_boundary_conditions(self, variables): # extract the variables we need c = variables["Concentration"] j = variables["Boundary flux"] # add the boundary conditions to the submodel dictionary self.boundary_conditions = { c: {"left": (0, "Neumann"), "right": (-j, "Neumann")} } def set_initial_conditions(self, variables): # extract the variable we need c = variables["Concentration"] # define the initial concentration parameter c0 = pybamm.Parameter("Initial concentration") # add the initial conditions to the submodel dictionary self.initial_conditions = {c: c0} ``` ``` class BoundaryFlux(pybamm.BaseSubModel): def __init__(self, param, domain, options=None): super().__init__(param, domain, options=options) def get_coupled_variables(self, variables): # extract the variable we need c_surf = variables["Surface concentration"] # define the flux parameter j0 = pybamm.Parameter("Flux parameter") j = j0 * (1 - c_surf) ** (1 / 2) * c_surf ** (1 / 2) # prescribed boundary flux # update dictionary of model variables variables.update({"Boundary flux": j}) return variables ``` We can now set the submodels in a model by assigning a dictionary to `model.submodels`. The dictionary key is the name we want to give to the submodel and the value is an instance of the submodel class we want to use. When we instantiate a submodel we are required to pass in `param`, a class of parameter symbols we are going to call, and `domain`, the domain on which the submodel lives. In this example we will simply set `param` to `None` and hard-code the definition of our parameters into the submodel. When writing lots of submodels it is more efficient to define _all_ the parameters in a shared class, and pass this to each submodel. For the domain we will choose "Negative". ``` model.submodels = { "Particle": Particle(None, "Negative"), "Boundary flux": BoundaryFlux(None, "Negative"), } ``` At this stage we have just told the model which submodels it is constructed from, but the variables and equations have not yet been created. For example if we look at the `rhs` dictionary it is empty. ``` model.rhs ``` To populate the model variables, equations, boundary and initial conditions we need to "build" the model. To do this we call `build_model` ``` model.build_model() ``` This loops through all of the submodels, first creating the "fundamental variables", followed by the "coupled variables" and finally the equations (`rhs` and `algebraic`) and the boundary and initial conditions. Now we see that `model.rhs` contains our diffusion equation. ``` model.rhs ``` ## Using the model We can now use our model as in the previous tutorial. We first set up our geometry and mesh ``` r = pybamm.SpatialVariable( "r", domain=["negative particle"], coord_sys="spherical polar" ) geometry = {"negative particle": {r: {"min": 0, "max": 1}}} spatial_methods = {"negative particle": pybamm.FiniteVolume()} submesh_types = {"negative particle": pybamm.Uniform1DSubMesh} var_pts = {r: 20} mesh = pybamm.Mesh(geometry, submesh_types, var_pts) ``` and then set up our simulation, remembering to set values for our parameters ``` parameter_values = pybamm.ParameterValues( { "Initial concentration": 0.9, "Flux parameter": 0.8, } ) solver = pybamm.ScipySolver() sim = pybamm.Simulation( model, geometry=geometry, parameter_values=parameter_values, submesh_types=submesh_types, var_pts=var_pts, spatial_methods=spatial_methods, solver=solver, ) ``` Finally we can solve the model ``` sim.solve([0, 1]) ``` and plot the results ``` # pass in a list of the variables we want to plot sim.plot(["Concentration", "Surface concentration", "Flux", "Boundary flux"]) ``` In this notebook we saw how to split a model up into submodels. Although this was a simple example it let us understand how to construct submodels and see how they interact via coupled variables. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-11-creating-a-submodel.ipynb
# Tutorial 10 - Creating a model In [Tutorial 9](./tutorial-9-changing-the-mesh.ipynb) we showed how to change the mesh using on of the built-in battery models in PyBaMM. In this tutorial we show how to create a simple model from scratch in PyBaMM. As simple example, we consider the problem of linear diffusion on a unit sphere with a flux at the boundary that depends on the concentration. We solve $$ \frac{\partial c}{\partial t} = \nabla \cdot (\nabla c), $$ with the following boundary and initial conditions: $$ \left.\frac{\partial c}{\partial r}\right\vert_{r=0} = 0, \quad \left.\frac{\partial c}{\partial r}\right\vert_{r=1} = -j, \quad \left.c\right\vert_{t=0} = c_0, $$ where $$ j = \left.j_0(1-c)^{1/2}c^{1/2}\right\vert_{r=1} $$ Here $c_0$ and $j_0$ are parameters we can control. In this example we will assume that everything is non-dimensional and focus on how to set up and solve the model rather than any specific physical interpretation. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` ## Setting up the model First we load an empty model. We use the `BaseModel` class that sets up all the basic framework on which our model will be built. ``` model = pybamm.BaseModel() ``` We then define our variables and parameters using the `Variable` and `Parameter` classes, respectively. Since we are solving a PDE we need to tell PyBaMM the domain each variable belongs to so that it can be discretised in space in the correct way. This is done by passing the keyword argument `domain`, and in this example we arbitrarily choose the domain "negative particle". ``` c = pybamm.Variable("Concentration", domain="negative particle") c0 = pybamm.Parameter("Initial concentration") j0 = pybamm.Parameter("Flux parameter") ``` We then state out governing equations. In PyBaMM we distinguish between Ordinary Differential Equations of the form $dy/dt = \text{rhs}$ and Algebraic Equations of the form $f(y) = 0$. The model equations are stored in dictionaries where the key is the variable and the value is the rhs for ODEs and the residual ($f(y)$) for algebraic equations. Sometime it is useful to define intermediate quantities in order to express the governing equations more easily. In this example we define the flux, then define the rhs to be minus the divergence of the flux. The equation is then added to the dictionary `model.rhs` ``` N = -pybamm.grad(c) # define the flux dcdt = -pybamm.div(N) # define the rhs equation model.rhs = {c: dcdt} # add the equation to rhs dictionary with the variable as the key ``` Next we add the necessary boundary and initial conditions to the model. These are also stored in dictionaries called `model.boundary_conditions` and `model.initial_conditions`, respectively. ``` # boundary conditions c_surf = pybamm.surf(c) # concentration at the surface of the sphere j = j0 * (1 - c_surf) ** (1 / 2) * c_surf ** (1 / 2) # prescribed boundary flux model.boundary_conditions = {c: {"left": (0, "Neumann"), "right": (-j, "Neumann")}} # initial conditions model.initial_conditions = {c: c0} ``` We can add any variables of interest to the dictionary `model.variables`. These can simply be the variables we solve for (in this case $c$) or any other user-defined quantities. ``` model.variables = { "Concentration": c, "Surface concentration": c_surf, "Flux": N, "Boundary flux": j, } ``` ## Setting up the geometry and mesh In order to solve the model we need to define the geometry and choose how we are going to discretise the equations in space. We first define our radial coordinate using `pybamm.SpatialVariable`. When we define our spatial variable we pass in a name, the domain on which the variable lives, and the coordinate system we want to use. ``` r = pybamm.SpatialVariable( "r", domain=["negative particle"], coord_sys="spherical polar" ) ``` We can then define our geometry using a dictionary. The key is the name of the domain, and the value is another dictionary which gives the coordinate to use and the limits. In this case we solve on a unit sphere, so we pass out `SpatialVariable`, `r`, and the limit 0 and 1. ``` geometry = {"negative particle": {r: {"min": 0, "max": 1}}} ``` Finally we choose how we are going to discretise in space. We choose to use the Finite Volume method on a uniform mesh with 20 volumes. ``` spatial_methods = {"negative particle": pybamm.FiniteVolume()} submesh_types = {"negative particle": pybamm.Uniform1DSubMesh} var_pts = {r: 20} # create a mesh of our geometry, using a uniform grid with 20 volumes mesh = pybamm.Mesh(geometry, submesh_types, var_pts) ``` ## Solving the model Now we are ready to solve the model. First we need to provide values for the parameters in our model. We do this by passing a dictionary of parameter names and values to the `pybamm.ParameterValues` class. ``` parameter_values = pybamm.ParameterValues( { "Initial concentration": 0.9, "Flux parameter": 0.8, } ) ``` Next we choose a solver. Since this is a system of ODEs we can use the `ScipySolver` which uses a Runge-Kutta scheme by default. ``` solver = pybamm.ScipySolver() ``` We can then create a simulation by passing information about the model, geometry, parameters, discretisation and solver to the `pybamm.Simulation` class. ``` sim = pybamm.Simulation( model, geometry=geometry, parameter_values=parameter_values, submesh_types=submesh_types, var_pts=var_pts, spatial_methods=spatial_methods, solver=solver, ) ``` Finally we can solve the model ``` sim.solve([0, 1]) # solve up to a time of 1 ``` The easiest way to quickly plot the results is to call `sim.plot` to create a slider plot. Note that at present the `plot` method is set up to plot dimensional results from battery simulations, so the labels include units which can be ignored (the model assumes a default length scale of 1m and default time scale of 1s). Alternatively we could extract the solution data as seen in [Tutorial 6](./tutorial-6-managing-simulation-outputs.ipynb) and create the plots manually. You can find out more about customising plots in [this notebook](../plotting/customize-quick-plot.ipynb). ``` # pass in a list of the variables we want to plot sim.plot(["Concentration", "Surface concentration", "Flux", "Boundary flux"]) ``` Here we have seen how to create a basic model from scratch in PyBaMM. In the [next tutorial](./tutorial-11-creating-a-submodel.ipynb) we will see how to split this model up into separate submodels. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-10-creating-a-model.ipynb
# Tutorial 3 - Basic plotting In [Tutorial 2](./tutorial-2-compare-models.ipynb), we made use of PyBaMM's automatic plotting function when comparing models. This gave a good quick overview of many of the key variables in the model. However, by passing in just a few arguments it is easy to plot any of the many other variables that may be of interest to you. We start by building and solving a model as before: ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm import matplotlib.pyplot as plt model_dfn = pybamm.lithium_ion.DFN() sim_dfn = pybamm.Simulation(model_dfn) sim_dfn.solve([0, 3600]) ``` We now want to plot a selection of the model variables. To see a full list of the available variables just type: ``` model_dfn.variable_names() ``` There are a _lot_ of variables. You can also search the list of variables for a particular string (e.g. "electrolyte") ``` model_dfn.variables.search("electrolyte") ``` We have tried to make variables names fairly self explanatory. As a first example, we choose to plot the voltage. We add this to a list and then pass this list to the `plot` method of our simulation: ``` output_variables = ["Voltage [V]"] sim_dfn.plot(output_variables=output_variables) ``` Alternatively, we may be interested in plotting both the electrolyte concentration and the voltage. In which case, we would do: ``` output_variables = ["Electrolyte concentration [mol.m-3]", "Voltage [V]"] sim_dfn.plot(output_variables=output_variables) ``` You can also plot multiple variables on the same plot by nesting lists ``` sim_dfn.plot( [ ["Electrode current density [A.m-2]", "Electrolyte current density [A.m-2]"], "Voltage [V]", ] ) ``` ``` sim_dfn.plot() ``` For plotting the voltage components you can use the `plot_votage_components` function ``` sim_dfn.plot_voltage_components() ``` And with a few modifications (by creating subplots and by providing the axes on which the voltage components have to be plotted), it can also be used to compare the voltage components of different simulations ``` # simulating and solving Single Particle Model model_spm = pybamm.lithium_ion.SPM() sim_spm = pybamm.Simulation(model_spm) sim_spm.solve([0, 3700]) # comparing voltage components for Doyle-Fuller-Newman model and Single Particle Model fig, axes = plt.subplots(1, 2, figsize=(15, 6), sharey=True) sim_dfn.plot_voltage_components(ax=axes.flat[0]) sim_spm.plot_voltage_components(ax=axes.flat[1]) axes.flat[0].set_title("Doyle-Fuller-Newman Model") axes.flat[1].set_title("Single Particle Model") plt.show() ``` In this tutorial we have seen how to use the plotting functionality in PyBaMM. In [Tutorial 4](./tutorial-4-setting-parameter-values.ipynb) we show how to change parameter values. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-3-basic-plotting.ipynb
# Tutorial 8 - Solver options In [Tutorial 7](./tutorial-7-model-options.ipynb) we saw how to change the model options. In this tutorial we will show how to pass options to the solver. All models in PyBaMM have a default solver which is typically different depending on whether the model results in a system of ordinary differential equations (ODEs) or differential algebraic equations (DAEs). One of the most common options you will want to change is the solver tolerances. By default all tolerances are set to $10^{-6}$. However, depending on your simulation you may find you want to tighten the tolerances to obtain a more accurate solution, or you may want to loosen the tolerances to reduce the solve time. It is good practice to conduct a tolerance study, where you simulate the same problem with a tighter tolerances and compare the results. We do not show how to do this here, but we give an example of a mesh resolution study in the [next tutorial](./tutorial-9-changing-the-mesh.ipynb), which is conducted in a similar way. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` Here we will change the absolute and relative tolerances, as well as the "mode" of the `CasadiSolver`. For a list of all the solver options please consult the [documentation](https://docs.pybamm.org/en/latest/source/api/solvers/index.html). The `CasadiSolver` can operate in a number of modes, including "safe" (default) and "fast". Safe mode performs step-and-check integration and supports event handling (e.g. you can integrate until you hit a certain voltage), and is the recommended for simulations of a full charge or discharge. Fast mode performs direct integration, ignoring events, and is recommended when simulating a drive cycle or other simulation where no events should be triggered. We'll solve the DFN with all the default options in both "safe" and "fast" mode and compare the solutions. For both simulations we'll use $10^{-3}$ for both the absolute and relative tolerance. For demonstration purposes we'll change the cut-off voltage to 3.6V so we can observe the different behaviour of the two solver modes. ``` # load model and parameters model = pybamm.lithium_ion.DFN() param = model.default_parameter_values param["Lower voltage cut-off [V]"] = 3.6 # load solvers safe_solver = pybamm.CasadiSolver(atol=1e-3, rtol=1e-3, mode="safe") fast_solver = pybamm.CasadiSolver(atol=1e-3, rtol=1e-3, mode="fast") # create simulations safe_sim = pybamm.Simulation(model, parameter_values=param, solver=safe_solver) fast_sim = pybamm.Simulation(model, parameter_values=param, solver=fast_solver) # solve safe_sim.solve([0, 3600]) print(f"Safe mode solve time: {safe_sim.solution.solve_time}") fast_sim.solve([0, 3600]) print(f"Fast mode solve time: {fast_sim.solution.solve_time}") # plot solutions pybamm.dynamic_plot([safe_sim, fast_sim]) ``` We see that both solvers give the same solution up to the time at which the cut-off voltage is reached. At this point the solver using "safe" mode stops, but the solver using "fast" mode carries on integrating until the final time. As its name suggests, "fast" mode integrates more quickly that "safe" mode, but is unsuitable if your simulation required events to be handled. Usually the default solver options provide a good combination of speed and accuracy, but we encourage you to investigate different solvers and options to find the best combination for your problem. In the [next tutorial](./tutorial-9-changing-the-mesh.ipynb) we show how to change the mesh. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-8-solver-options.ipynb
# Tutorial 6 - Managing simulation outputs In the previous tutorials we have interacted with the outputs of the simulation via the default dynamic plot. However, usually we need to access the output data to manipulate it or transfer to another software which is the topic of this notebook. We start by building and solving our model as shown in previous notebooks: ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm model = pybamm.lithium_ion.SPMe() sim = pybamm.Simulation(model) sim.solve([0, 3600]) ``` ## Accessing solution variables We can now access the solved variables directly to visualise or create our own plots. We first extract the solution object: ``` solution = sim.solution ``` and now we can create a post-processed variable (for a list of all the available variables see [Tutorial 3](./tutorial-3-basic-plotting.ipynb)) ``` t = solution["Time [s]"] V = solution["Voltage [V]"] ``` One option is to visualise the data set returned by the solver directly ``` V.entries ``` which correspond to the data at the times ``` t.entries ``` In addition, post-processed variables can be called at any time (by interpolation) ``` V([200, 400, 780, 1236]) # times in seconds ``` ## Saving the simulation and output data In some cases simulations might take a long time to run so it is advisable to save in your computer so it can be analysed later without re-running the simulation. You can save the whole simulation doing: ``` sim.save("SPMe.pkl") ``` If you now check the root directory of your notebooks you will notice that a new file called `"SPMe.pkl"` has appeared. We can load the stored simulation doing ``` sim2 = pybamm.load("SPMe.pkl") ``` which allows the same manipulation as the original simulation would allow ``` sim2.plot() ``` Alternatively, we can just save the solution of the simulation in a similar way ``` sol = sim.solution sol.save("SPMe_sol.pkl") ``` and load it in a similar way too ``` sol2 = pybamm.load("SPMe_sol.pkl") pybamm.dynamic_plot(sol2) ``` Another option is to just save the data for some variables ``` sol.save_data("sol_data.pkl", ["Current [A]", "Voltage [V]"]) ``` or save in csv or mat format ``` sol.save_data("sol_data.csv", ["Current [A]", "Voltage [V]"], to_format="csv") # matlab needs names without spaces sol.save_data( "sol_data.mat", ["Current [A]", "Voltage [V]"], to_format="matlab", short_names={"Current [A]": "I", "Voltage [V]": "V"}, ) ``` In this notebook we have shown how to extract and store the outputs of PyBaMM's simulations. Next, in [Tutorial 7](./tutorial-7-model-options.ipynb) we will show how to change the model options. Before finishing we will remove the data files we saved so that we leave the directory as we found it ``` import os os.remove("SPMe.pkl") os.remove("SPMe_sol.pkl") os.remove("sol_data.pkl") os.remove("sol_data.csv") os.remove("sol_data.mat") ``` ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-6-managing-simulation-outputs.ipynb
# Tutorial 5 - Run experiments In [Tutorial 4](./tutorial-4-setting-parameter-values.ipynb) we saw how to change the parameters, including the applied current. However, in some cases we might want to prescribe a given voltage, a given power or switch between different conditions to simulate experimental setups. We can use the Experiment class for these simulations. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm import numpy as np ``` ## String-based instructions We start defining an experiment, which consists on a set of instructions on how to cycle the battery. For example, we can set the following experiment: ``` experiment = pybamm.Experiment( [ ( "Discharge at C/10 for 10 hours or until 3.3 V", "Rest for 1 hour", "Charge at 1 A until 4.1 V", "Hold at 4.1 V until 50 mA", "Rest for 1 hour", ), ] * 3 ) ``` A cycle is defined by a tuple of operating instructions. In this case, the experiment consists of a cycle of constant current C/10 discharge, a one hour rest, a constant current (1 A) constant voltage (4.1 V) and another one hour rest, all of it repeated three times (notice the * 3). Then we can choose our model ``` model = pybamm.lithium_ion.DFN() ``` and create our simulation, passing our experiment using a keyword argument ``` sim = pybamm.Simulation(model, experiment=experiment) ``` We then solve and plot the solution ``` sim.solve() sim.plot() ``` As we have seen, experiments allow us to define complex simulations using a very simple syntax. The instructions can be of the form "(Dis)charge at x A/C/W", "Rest", or "Hold at x V". The running time should be a time in seconds, minutes or hours, e.g. "10 seconds", "3 minutes" or "1 hour". The stopping conditions should be a circuit state, e.g. "1 A", "C/50" or "3 V". Some examples of experiment instructions are: ```python "Discharge at 1C for 0.5 hours", "Discharge at C/20 for 0.5 hours", "Charge at 0.5 C for 45 minutes", "Discharge at 1 A for 90 seconds", "Charge at 200mA for 45 minutes", "Discharge at 1 W for 0.5 hours", "Charge at 200 mW for 45 minutes", "Rest for 10 minutes", "Hold at 1 V for 20 seconds", "Charge at 1 C until 4.1V", "Hold at 4.1 V until 50 mA", "Hold at 3V until C/50", ``` Additionally, we can use the operators `+` and `*` on lists in order to combine and repeat cycles: ``` [("Discharge at 1C for 0.5 hours", "Discharge at C/20 for 0.5 hours")] * 3 + [ ("Charge at 0.5 C for 45 minutes",) ] ``` To pass additional arguments such as a period, temperature, or tags, the method `pybamm.step.string` should be used, for example: ``` pybamm.step.string( "Discharge at 1C for 1 hour", period="1 minute", temperature="25oC", tags=["tag1"] ) ``` ## Direct instructions Experiments can also be specified programmatically without having to use string formatting. For example, ``` pybamm.step.current(1, duration="1 hour", termination="2.5 V") ``` is equivalent to ``` pybamm.step.string("Discharge at 1A for 1 hour or until 2.5V") ``` The available methods are `current`, `c_rate`, `voltage`, `power`, and `resistance`. The period, temperature, and tags options are the same as for `pybamm.step.string`. These methods can also be used for drive cycles: ``` t = np.linspace(0, 1, 60) sin_t = 0.5 * np.sin(2 * np.pi * t) drive_cycle_power = np.column_stack([t, sin_t]) experiment = pybamm.Experiment([pybamm.step.power(drive_cycle_power)]) sim = pybamm.Simulation(model, experiment=experiment) sim.solve() sim.plot() ``` For a drive cycle, the duration is until the final time provided and the period is the smallest time step. For best results, we recommend using a constant time step size. In this notebook we have seen how to use the Experiment class to run simulations of more complex operating conditions. In [Tutorial 6](./tutorial-6-managing-simulation-outputs.ipynb) we will see how to manage the outputs of the simulation. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-5-run-experiments.ipynb
# Tutorial 2 - Compare models In [Tutorial 1](./tutorial-1-how-to-run-a-model.ipynb), we saw how to run a PyBaMM simulation of the DFN model. However, PyBaMM includes other standard electrochemical models such as the Single Particle Model (SPM) and the Single Particle Model with electrolyte (SPMe). In this tutorial, we will see how to simulate and compare these three models. Again, the first step is to import the pybamm library into the notebook: ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` We start creating a list of all the models we wish to solve ``` models = [ pybamm.lithium_ion.SPM(), pybamm.lithium_ion.SPMe(), pybamm.lithium_ion.DFN(), ] ``` and now we can loop over the list, creating and solving simulations as we go. The solved simulations are stored in the list `sims` ``` sims = [] for model in models: sim = pybamm.Simulation(model) sim.solve([0, 3600]) sims.append(sim) ``` We can now pass our list of simulations to the dynamic plot method, which will plot the different outputs in the same figure ``` pybamm.dynamic_plot(sims, time_unit="seconds") ``` In this tutorial we have seen how easy it is to run and compare different electrochemical models. In [Tutorial 3](./tutorial-3-basic-plotting.ipynb) we show how to create different plots using PyBaMM's built-in plotting capability. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-2-compare-models.ipynb
# Tutorial 7 - Model options In all of the previous tutorials, we have made use of the default forms of the inbuilt models in PyBaMM. However, PyBaMM provides a high-level interface for tweaking these models for your particular application. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` In this tutorial, we add a thermal model to the SPMe. From the [documentation](https://docs.pybamm.org/en/latest/source/api/models/base_models/base_battery_model.html), we see that we have a choice of either a 'x-full' thermal model or a number of different lumped thermal models. For a deeper look at the thermal models see the [thermal models notebook](../models/thermal-models.ipynb). We choose the full thermal model, which solves the spatially-dependent heat equation on our battery geometry, and couples the temperature with the electrochemistry. We set the model options by creating a Python dictionary: ``` options = {"thermal": "x-full"} ``` and passing it to the model. Then, the model can be solved as shown in previous notebooks. We also increase the current to amplify the thermal effects: ``` model = pybamm.lithium_ion.SPMe(options=options) # loading in options sim = pybamm.Simulation(model) sim.solve([0, 3600]) ``` We now plot the cell temperature and the total heating by passing these variables to the `plot` method as we saw in [Tutorial 3](./tutorial-3-basic-plotting.ipynb): ``` sim.plot( ["Cell temperature [K]", "Total heating [W.m-3]", "Current [A]", "Voltage [V]"] ) ``` In this tutorial we have seen how to adjust the model options. To see all of the options currently available in PyBaMM, please take a look at the documentation [here](https://docs.pybamm.org/en/latest/source/api/models/base_models/base_battery_model.html). In the [next tutorial](./tutorial-8-solver-options.ipynb) we show how to change the solver options. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-7-model-options.ipynb
# Tutorial 1 - How to run a model Welcome to PyBaMM! In this notebook, we will run your first PyBaMM model in just a few simple lines. To run through this jupyter notebook simply shift-enter to run the cells. If you are unfamiliar with Jupyter notebooks we recommend checking out this [cheat sheet](https://www.cheatography.com/weidadeyue/cheat-sheets/jupyter-notebook/pdf_bw/). We begin by importing the PyBaMM library into this notebook: ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm ``` We now load the model that we wish to run. For this notebook, we choose the Doyle-Fuller-Newman (DFN) model: ``` model = pybamm.lithium_ion.DFN() ``` We now use this model to create a PyBaMM Simulation, which is used to process and solve the model: ``` sim = pybamm.Simulation(model) ``` We can then call 'solve' on our simulation object to solve the model, passing the window of time to solve for in seconds (here 1 hour): ``` sim.solve([0, 3600]) ``` Finally, we can call 'plot' to generate a dynamic plot of the key variables: ``` sim.plot() ``` In this tutorial, we have solved a model with the inbuilt default settings. However, PyBaMM is designed to be highly customisable. Over the course of the getting started tutorials, we will see how various settings can be changed so that the model is appropriate for your situation. In [Tutorial 2](./tutorial-2-compare-models.ipynb) we cover how to simulate and compare different models. ## References If you write a paper that uses PyBaMM, we would be grateful if you could cite the papers relevant to your code. These will change depending on what models and solvers you use. To find out which papers you should cite, you can run: ``` pybamm.print_citations() ``` Alternatively, you can print the citations in BibTeX format by running ```python pybamm.print_citations(output_format="bibtex") ``` In both cases, you can pass the extra argument `filename` to store the citations into a file.
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-1-how-to-run-a-model.ipynb
# Tutorial 4 - Setting parameter values In [Tutorial 1](./tutorial-1-how-to-run-a-model.ipynb) and [Tutorial 2](./tutorial-2-compare-models.ipynb), we saw how to run a PyBaMM model with all the default settings. However, PyBaMM also allows you to tweak these settings for your application. In this tutorial, we will see how to change the parameters in PyBaMM. ``` %pip install "pybamm[plot,cite]" -q # install PyBaMM if it is not installed import pybamm import os os.chdir(pybamm.__path__[0] + "/..") ``` ## Change the whole parameter set PyBaMM has a number of in-built parameter sets (check the list [here](https://docs.pybamm.org/en/latest/source/api/parameters/parameter_sets.html)), which can be selected doing ``` parameter_values = pybamm.ParameterValues("Chen2020") ``` We can see all the parameters stored in the dictionary ``` parameter_values ``` or we can search for a particular parameter ``` parameter_values.search("electrolyte") ``` To run a simulation with this parameter set, we can proceed as usual but passing the parameters as a keyword argument ``` model = pybamm.lithium_ion.DFN() sim = pybamm.Simulation(model, parameter_values=parameter_values) sim.solve([0, 3600]) sim.plot() ``` More details on each subset can be found [here](https://github.com/pybamm-team/PyBaMM/tree/develop/pybamm/input/parameters). ## Change individual parameters We often want to quickly change a small number of parameter values to investigate how the behaviour or the battery changes. In such cases, we can change parameter values without having to leave the notebook or script you are working in. We start initialising the model and the parameter values ``` model = pybamm.lithium_ion.DFN() parameter_values = pybamm.ParameterValues("Chen2020") ``` In this example we will change the current to 10 A ``` parameter_values["Current function [A]"] = 10 parameter_values["Open-circuit voltage at 100% SOC [V]"] = 3.4 parameter_values["Open-circuit voltage at 0% SOC [V]"] = 3.0 ``` Now we just need to run the simulation with the new parameter values ``` sim = pybamm.Simulation(model, parameter_values=parameter_values) sim.solve([0, 3600], initial_soc=1) sim.plot() ``` Note that we still passed the interval `[0, 3600]` to `sim.solve()`, but the simulation terminated early as the lower voltage cut-off was reached. ### Drive cycle You can implement drive cycles importing the dataset and creating an interpolant to pass as the current function. ``` import pandas as pd # needed to read the csv data file # Import drive cycle from file drive_cycle = pd.read_csv( "pybamm/input/drive_cycles/US06.csv", comment="#", header=None ).to_numpy() # Create interpolant current_interpolant = pybamm.Interpolant(drive_cycle[:, 0], drive_cycle[:, 1], pybamm.t) # Set drive cycle parameter_values["Current function [A]"] = current_interpolant ``` Note that your drive cycle data can be stored anywhere, you just need to pass the path of the file. Then, again, the model can be solved as usual but notice that now, if `t_eval` is not specified, the solver will take the time points from the data set. ``` model = pybamm.lithium_ion.SPMe() sim = pybamm.Simulation(model, parameter_values=parameter_values) sim.solve() sim.plot(["Current [A]", "Voltage [V]"]) ``` ### Custom current function Alternatively, we can define the current to be an arbitrary function of time ``` import numpy as np def my_current(t): return pybamm.sin(2 * np.pi * t / 60) parameter_values["Current function [A]"] = my_current ``` and we can now solve the model again. In this case, we can pass `t_eval` to the solver to make sure we have enough time points to resolve the function in our output. ``` model = pybamm.lithium_ion.SPMe() sim = pybamm.Simulation(model, parameter_values=parameter_values) t_eval = np.arange(0, 121, 1) sim.solve(t_eval=t_eval) sim.plot(["Current [A]", "Voltage [V]"]) ``` In this notebook we have seen how we can change the parameters of our model. In [Tutorial 5](./tutorial-5-run-experiments.ipynb) we show how can we define and run experiments. ## References The relevant papers for this notebook are: ``` pybamm.print_citations() ```
PyBaMM/docs/source/examples/notebooks/getting_started/tutorial-4-setting-parameter-values.ipynb
README.md exists but content is empty. Use the Edit dataset card button to edit it.
Downloads last month
37
Edit dataset card