Skip to content

Commit

Permalink
Merge pull request #49 from FaradayInstitution/develop
Browse files Browse the repository at this point in the history
Merge develop into main for v0.4.0 release
  • Loading branch information
rtimms committed Nov 20, 2023
2 parents 7a4ce12 + 64c6470 commit b9da91c
Show file tree
Hide file tree
Showing 35 changed files with 1,803 additions and 70 deletions.
25 changes: 25 additions & 0 deletions .readthedocs.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# .readthedocs.yaml
# Read the Docs configuration file
# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details

# Required
version: 2

# Set the version of Python and other tools you might need
build:
os: ubuntu-22.04
tools:
python: "3.11"

# Build documentation in the docs/ directory with Sphinx
sphinx:
builder: html
configuration: docs/conf.py
fail_on_warning: false

# Optionally declare the Python requirements required to build your docs
python:
install:
- method: pip
path: .

25 changes: 18 additions & 7 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,15 +1,26 @@
# [v0.3.1](https://github.com/pybamm-team/BPX/releases/tag/v0.3.1)
- Temporarily pin Pydantic version ([#35](https://github.com/pybamm-team/BPX/pull/35))
# [v0.4.0](https://github.com/FaradayInstitution/BPX/releases/tag/v0.4.0)

# [v0.3.0](https://github.com/pybamm-team/BPX/releases/tag/v0.3.0)
- Added five parametrisation examples (two DFN parametrisation examples from About:Energy open-source release, blended electrode definition, user-defined 0th-order hysteresis, and SPM parametrisation). ([#45](https://github.com/FaradayInstitution/BPX/pull/45))
- Allow user-defined parameters to be added using the field ["Parameterisation"]["User-defined"] ([#44](https://github.com/FaradayInstitution/BPX/pull/44))
- Added basic API documentation ([#43](https://github.com/FaradayInstitution/BPX/pull/43))
- Added validation based on models: SPM, SPMe, DFN ([#34](https://github.com/FaradayInstitution/BPX/pull/34)). A warning will be produced if the user-defined model type does not match the parameter set (e.g., if the model is `SPM`, but the full DFN model parameters are provided).
- Added support for well-mixed, blended electrodes that contain more than one active material ([#33](https://github.com/FaradayInstitution/BPX/pull/33))
- Added validation of the STO limits subbed into the OCPs vs the upper/lower cut-off voltage limits for non-blended electrodes with the OCPs defined as functions ([#32](https://github.com/FaradayInstitution/BPX/pull/32)). The user can provide a tolerance by updating the settings variable `BPX.settings.tolerances["Voltage [V]"]` or by passing extra option `v_tol` to `parse_bpx_file()`, `parse_bpx_obj()` or `parse_bpx_str()` functions. Default value of the tolerance is 1 mV. The tolerance cannot be negative.
- Added the target SOC check in `get_electrode_concentrations()` function. Raise a warning if the SOC is outside of [0,1] interval.

# [v0.3.1](https://github.com/FaradayInstitution/BPX/releases/tag/v0.3.1)

- Temporarily pin Pydantic version ([#35](https://github.com/FaradayInstitution/BPX/pull/35))

# [v0.3.0](https://github.com/FaradayInstitution/BPX/releases/tag/v0.3.0)

- Added a missing factor of 2 in the definition of the interfacial current, see the Butler-Volmer equation (2a) in the associated BPX standard document. The interfacial current is now given by $j=2j_0\sinh(F\eta/2/R/T)$ instead of $j=j_0\sinh(F\eta/2/R/T)$.

# [v0.2.0](https://github.com/pybamm-team/BPX/releases/tag/v0.2.0)
# [v0.2.0](https://github.com/FaradayInstitution/BPX/releases/tag/v0.2.0)

- Parsing a BPX json file with additional (unexpected) fields now raises a `ValidationError` ([#16](https://github.com/pybamm-team/BPX/pull/16))
- Fixed a bug in the experiment schema ([#13](https://github.com/pybamm-team/BPX/pull/13))
- Parsing a BPX json file with additional (unexpected) fields now raises a `ValidationError` ([#16](https://github.com/FaradayInstitution/BPX/pull/16))
- Fixed a bug in the experiment schema ([#13](https://github.com/FaradayInstitution/BPX/pull/13))

# [v0.1.0](https://github.com/pybamm-team/BPX/releases/tag/v0.1.0)
# [v0.1.0](https://github.com/FaradayInstitution/BPX/releases/tag/v0.1.0)

Initial release of the Battery Parameter eXchange (BPX) format.
File renamed without changes.
50 changes: 24 additions & 26 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# BPX
![tests](https://github.com/pybamm-team/BPX/actions/workflows/test.yml/badge.svg)
[![codecov](https://codecov.io/gh/pybamm-team/BPX/branch/main/graph/badge.svg?token=Krv0JW3gYZ)](https://codecov.io/gh/pybamm-team/BPX)
# 🔋 BPX
![tests](https://github.com/FaradayInstitution/BPX/actions/workflows/test.yml/badge.svg)
[![codecov](https://codecov.io/gh/FaradayInstitution/BPX/branch/main/graph/badge.svg?token=Krv0JW3gYZ)](https://codecov.io/gh/FaradayInstitution/BPX)

An implementation of the Battery Parameter eXchange (BPX) format in Pydantic. BPX, an outcome of the Faraday Institution [Multi-scale Modelling project](https://www.faraday.ac.uk/research/lithium-ion/battery-system-modelling/), is an open standard for physics-based Li-ion battery models that has been developed to reduce costs and time-to-market through a common definition of physics-based battery models that can be used widely across industry. To find out more, visit the [BPX website](https://bpxstandard.com/).

Expand All @@ -9,38 +9,26 @@ This repository features a Pydantic-based parser for JSON files in the BPX forma
To support the new open standard, [About:Energy](https://www.aboutenergy.io/) have supplied two parameters sets for an NMC and LFP cell. The BPX files and associated examples and information can be found on the [A:E BPX Parameterisation repository](https://github.com/About-Energy-OpenSource/About-Energy-BPX-Parameterisation/).

To see how to use BPX with [PyBaMM](https://www.pybamm.org/), check out the [BPX example repository](https://github.com/pybamm-team/bpx-example).
## Prerequisites

- Python 3+

## Installation

Create a new virtual environment, or activate an existing one (this example uses the python `venv` module, but you could use Anaconda and a `conda` environment)

```bash
python3 -m venv env
source env/bin/activate
```

Install the `BPX` module using pip

## 🚀 Installation
The BPX package can be installed using pip
```bash
pip install bpx
```

## Usage

Create a python script similar to that below
BPX is available on GNU/Linux, MacOS and Windows. We strongly recommend to install PyBaMM within a python [virtual environment](https://docs.python.org/3/tutorial/venv.html), in order not to alter any distribution python files.

## 💻 Usage
To create a BPX object from a JSON file, you can use the `parse_bpx_file` function
```python
import bpx

filename = 'path/to/my/file.json'
my_params = bpx.parse_bpx_file(filename)
```
`my_params` will now be of type `BPX`, which acts like a python dataclass with the same attributes as the BPX format. To obatin example files, see the `examples` folder, the [A:E BPX Parameterisation repository](https://github.com/About-Energy-OpenSource/About-Energy-BPX-Parameterisation/), or the [BPX example repository](https://github.com/pybamm-team/bpx-example).

`my_params` will now be of type `BPX`, which acts like a python dataclass with the same attributes as the BPX format. For example, you can print out the initial temperature of the cell using

Attributes of the class can be printed out using the standard Python dot notation, for example, you can print out the initial temperature of the cell using
```python
print('Initial temperature of cell:', my_params.parameterisation.cell.initial_temperature)
```
Expand All @@ -51,25 +39,35 @@ my_params_dict = my_params.dict(by_alias=True)
print('Initial temperature of cell:', my_params_dict["Parameterisation"]["Cell"]["Initial temperature [K]"])
```

If you want to pretty print the entire object, you can use the `devtools` package to do this (remember to `pip install devtools`)

The entire BPX object can be pretty printed using the `devtools` package
```python
from devtools import pprint
pprint(my_params)
```

You can convert any `Function` objects in `BPX` to regular callable Python functions, for example:

```python
positive_electrode_diffusivity = my_params.parameterisation.positive_electrode.diffusivity.to_python_function()
diff_at_one = positive_electrode_diffusivity(1.0)
print('positive electrode diffusivity at x = 1.0:', diff_at_one)
```

If you want to output the complete JSON schema in order to build a custom tool yourself, you can do so:

```python
print(bpx.BPX.schema_json(indent=2))
```

According to the `pydantic` docs, the generated schemas are compliant with the specifications: JSON Schema Core, JSON Schema Validation and OpenAPI.

## 📖 Documentation
API documentation for the `bpx` package can be built locally using [Sphinx](https://www.sphinx-doc.org/en/master/). To build the documentation first [clone the repository](https://github.com/git-guides/git-clone), install the `bpx` package, and then run the following command:
```bash
sphinx-build docs docs/_build/html
```
This will generate a number of html files in the `docs/_build/html` directory. To view the documentation, open the file `docs/_build/html/index.html` in a web browser, e.g. by running
```bash
open docs/_build/html/index.html
```

## 📫 Get in touch
If you have any questions please get in touch via email <bpx@faraday.ac.uk>.
4 changes: 3 additions & 1 deletion bpx/__init__.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
"""BPX schema and parsers"""
# flake8: noqa F401

__version__ = "0.3.1"
__version__ = "0.4.0"


from .interpolated_table import InterpolatedTable
from .expression_parser import ExpressionParser
from .function import Function
from .validators import check_sto_limits
from .schema import BPX
from .parsers import parse_bpx_str, parse_bpx_obj, parse_bpx_file
from .utilities import get_electrode_stoichiometries, get_electrode_concentrations
5 changes: 5 additions & 0 deletions bpx/expression_parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@


class ExpressionParser:
"""
An expression parser for mathematical expressions. For valid expressions,
please see :class:`bpx.Function`.
"""

ParseException = pp.ParseException

def __init__(self):
Expand Down
10 changes: 10 additions & 0 deletions bpx/function.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,16 @@ def __repr__(self):
return f"Function({super().__repr__()})"

def to_python_function(self, preamble: str = None) -> Callable:
"""
Return a python function that can be called with a single argument 'x'
Parameters
----------
preamble: str, optional
A string of python code to be prepended to the function
definition. This can be used to import modules or define
helper functions.
"""
if preamble is None:
preamble = copy.copy(self.default_preamble)
preamble += "\n\n"
Expand Down
5 changes: 5 additions & 0 deletions bpx/interpolated_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@


class InterpolatedTable(BaseModel):
"""
A table of values that can be interpolated to give a function. The table is defined
by two lists of floats, x and y. The function is defined by interpolation.
"""

x: List[float]
y: List[float]

Expand Down
41 changes: 33 additions & 8 deletions bpx/parsers.py
Original file line number Diff line number Diff line change
@@ -1,49 +1,74 @@
from bpx import BPX


def parse_bpx_file(filename: str) -> BPX:
def parse_bpx_file(filename: str, v_tol: float = 0.001) -> BPX:
"""
A convenience function to parse a bpx file into a BPX model.
Parameters
----------
filename: str
a filepath to a bpx file
v_tol: float
absolute tolerance in [V] to validate the voltage limits, 1 mV by default
Returns
-------
BPX:
BPX: :class:`bpx.BPX`
a parsed BPX model
"""
if v_tol < 0:
raise ValueError("v_tol should not be negative")

BPX.settings.tolerances["Voltage [V]"] = v_tol

return BPX.parse_file(filename)


def parse_bpx_obj(bpx: dict) -> BPX:
def parse_bpx_obj(bpx: dict, v_tol: float = 0.001) -> BPX:
"""
A convenience function to parse a bpx dict into a BPX model.
Parameters
----------
bpx: dict
a dict object in bpx format
v_tol: float
absolute tolerance in [V] to validate the voltage limits, 1 mV by default
Returns
-------
BPX:
BPX: :class:`bpx.BPX`
a parsed BPX model
"""
if v_tol < 0:
raise ValueError("v_tol should not be negative")

BPX.settings.tolerances["Voltage [V]"] = v_tol

return BPX.parse_obj(bpx)


def parse_bpx_str(bpx: str) -> BPX:
def parse_bpx_str(bpx: str, v_tol: float = 0.001) -> BPX:
"""
A convenience function to parse a json formatted string in bpx format into a BPX
model.
Parameters
----------
bpx: str
a json formatted string in bpx format
v_tol: float
absolute tolerance in [V] to validate the voltage limits, 1 mV by default
Returns
-------
BPX:
a parsed BPX model
"""
if v_tol < 0:
raise ValueError("v_tol should not be negative")

BPX.settings.tolerances["Voltage [V]"] = v_tol

return BPX.parse_raw(bpx)
Loading

0 comments on commit b9da91c

Please sign in to comment.