Skip to content

Commit

Permalink
Merge branch 'pybamm-team:develop' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
santacodes authored Mar 18, 2024
2 parents b20a153 + 8056d22 commit 5d8417b
Show file tree
Hide file tree
Showing 52 changed files with 270 additions and 232 deletions.
2 changes: 1 addition & 1 deletion .all-contributorsrc
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"files": [
"README.md"
"all_contributors.md"
],
"imageSize": 100,
"commit": false,
Expand Down
1 change: 1 addition & 0 deletions .github/workflows/lychee_url_checker.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ jobs:
--exclude-path ./scripts/update_version.py
--exclude-path asv.conf.json
--exclude-path docs/conf.py
--exclude-path all_contributors.md
'./**/*.rst'
'./**/*.md'
'./**/*.py'
Expand Down
5 changes: 4 additions & 1 deletion .github/workflows/need_reply_remove.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
name: Remove needs-reply label

on:
schedule:
- cron: '0 3 * * 1'
issue_comment:
types:
- created
Expand All @@ -11,7 +13,8 @@ jobs:
if: |
github.event.comment.author_association != 'OWNER' &&
github.event.comment.author_association != 'COLLABORATOR' &&
github.repository_owner == 'pybamm-team'
github.repository_owner == 'pybamm-team' &&
github.event_name != 'pull_request'
steps:
- name: Remove needs-reply label
uses: octokit/[email protected]
Expand Down
2 changes: 1 addition & 1 deletion MANIFEST.in
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ graft pybamm
include CITATION.cff
prune tests

exclude CHANGELOG.md CODE-OF-CONDUCT.md CONTRIBUTING.md CMakeLists.txt
exclude CHANGELOG.md CODE-OF-CONDUCT.md CONTRIBUTING.md CMakeLists.txt all_contributors.md

global-exclude __pycache__ *.py[cod] .venv
118 changes: 3 additions & 115 deletions README.md

Large diffs are not rendered by default.

113 changes: 113 additions & 0 deletions all_contributors.md

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion benchmarks/work_precision_sets/time_vs_abstols.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@
solver.solve(model, t_eval=t_eval)
time = 0
runs = 20
for k in range(0, runs):
for _ in range(0, runs):
solution = solver.solve(model, t_eval=t_eval)
time += solution.solve_time.value
time = time / runs
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/work_precision_sets/time_vs_dt_max.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@
solver.solve(model, t_eval=t_eval)
time = 0
runs = 20
for k in range(0, runs):
for _ in range(0, runs):
solution = solver.solve(model, t_eval=t_eval)
time += solution.solve_time.value
time = time / runs
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/work_precision_sets/time_vs_mesh_size.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

time = 0
runs = 20
for k in range(0, runs):
for _ in range(0, runs):
solution = sim.solve([0, 3500])
time += solution.solve_time.value
time = time / runs
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/work_precision_sets/time_vs_no_of_states.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@

time = 0
runs = 20
for k in range(0, runs):
for _ in range(0, runs):
solution = sim.solve([0, 3500])
time += solution.solve_time.value
time = time / runs
Expand Down
2 changes: 1 addition & 1 deletion benchmarks/work_precision_sets/time_vs_reltols.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@
solver.solve(model, t_eval=t_eval)
time = 0
runs = 20
for k in range(0, runs):
for _ in range(0, runs):
solution = solver.solve(model, t_eval=t_eval)
time += solution.solve_time.value
time = time / runs
Expand Down
4 changes: 2 additions & 2 deletions docs/source/examples/notebooks/batch_study.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -199,7 +199,7 @@
"\n",
"# changing the value of \"Current function [A]\" in all the parameter values present in the\n",
"# parameter_values dictionary\n",
"for k, v, current_value in zip(\n",
"for _, v, current_value in zip(\n",
" parameter_values.keys(), parameter_values.values(), current_values\n",
"):\n",
" v[\"Current function [A]\"] = current_value\n",
Expand Down Expand Up @@ -505,7 +505,7 @@
"inner_sei_oc_v_values = [2.0e-4, 2.7e-4, 3.4e-4]\n",
"\n",
"# updating the value of \"Inner SEI open-circuit potential [V]\" in all the dictionary items\n",
"for k, v, inner_sei_oc_v in zip(\n",
"for _, v, inner_sei_oc_v in zip(\n",
" parameter_values.keys(), parameter_values.values(), inner_sei_oc_v_values\n",
"):\n",
" v.update(\n",
Expand Down
7 changes: 4 additions & 3 deletions pybamm/citations.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ def _add_citation(self, key, entry):
# Warn if overwriting a previous citation
new_citation = entry.to_string("bibtex")
if key in self._all_citations and new_citation != self._all_citations[key]:
warnings.warn(f"Replacing citation for {key}")
warnings.warn(f"Replacing citation for {key}", stacklevel=2)

# Add to database
self._all_citations[key] = new_citation
Expand Down Expand Up @@ -165,9 +165,9 @@ def _parse_citation(self, key):
# Add to _papers_to_cite set
self._papers_to_cite.add(key)
return
except PybtexError:
except PybtexError as error:
# Unable to parse / unknown key
raise KeyError(f"Not a bibtex citation or known citation: {key}")
raise KeyError(f"Not a bibtex citation or known citation: {key}") from error

def _tag_citations(self):
"""Prints the citation tags for the citations that have been registered
Expand Down Expand Up @@ -226,6 +226,7 @@ def print(self, filename=None, output_format="text", verbose=False):
warnings.warn(
message=f'\nCitation with key "{key}" is invalid. Please try again\n',
category=UserWarning,
stacklevel=2,
)
# delete the invalid citation from the set
self._unknown_citations.remove(key)
Expand Down
6 changes: 3 additions & 3 deletions pybamm/discretisations/discretisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -280,7 +280,7 @@ def set_variable_slices(self, variables):
sec_points = spatial_method._get_auxiliary_domain_repeats(
variable.domains
)
for i in range(sec_points):
for _ in range(sec_points):
for child, mesh in meshes.items():
for domain_mesh in mesh:
end += domain_mesh.npts_for_broadcast_to_nodes
Expand Down Expand Up @@ -886,14 +886,14 @@ def _process_symbol(self, symbol):
# model.check_well_posedness, but won't be if debug_mode is False
try:
y_slices = self.y_slices[symbol]
except KeyError:
except KeyError as error:
raise pybamm.ModelError(
f"""
No key set for variable '{symbol.name}'. Make sure it is included in either
model.rhs or model.algebraic in an unmodified form
(e.g. not Broadcasted)
"""
)
) from error
# Add symbol's reference and multiply by the symbol's scale
# so that the state vector is of order 1
return symbol.reference + symbol.scale * pybamm.StateVector(
Expand Down
4 changes: 2 additions & 2 deletions pybamm/experiment/step/_steps_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,8 +287,8 @@ def _convert_electric(value_string):
}
try:
typ = units_to_type[unit]
except KeyError:
except KeyError as error:
raise ValueError(
f"units must be 'A', 'V', 'W', 'Ohm', or 'C'. For example: {_examples}"
)
) from error
return typ, value
2 changes: 1 addition & 1 deletion pybamm/expression_tree/concatenations.py
Original file line number Diff line number Diff line change
Expand Up @@ -337,7 +337,7 @@ def create_slices(self, node: pybamm.Symbol) -> defaultdict:
"""Concatenation and children must have the same number of
points in secondary dimensions"""
)
for i in range(second_pts):
for _ in range(second_pts):
for dom in node.domain:
end += self.full_mesh[dom].npts
slices[dom].append(slice(start, end))
Expand Down
4 changes: 2 additions & 2 deletions pybamm/expression_tree/input_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,8 +100,8 @@ def _base_evaluate(
try:
input_eval = inputs[self.name]
# raise more informative error if can't find name in dict
except KeyError:
raise KeyError(f"Input parameter '{self.name}' not found")
except KeyError as error:
raise KeyError(f"Input parameter '{self.name}' not found") from error

if isinstance(input_eval, numbers.Number):
input_size = 1
Expand Down
4 changes: 2 additions & 2 deletions pybamm/expression_tree/operations/jacobian.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,10 +90,10 @@ def _jac(self, symbol: pybamm.Symbol, variable: pybamm.Symbol):
else:
try:
jac = symbol._jac(variable)
except NotImplementedError:
except NotImplementedError as error:
raise NotImplementedError(
f"Cannot calculate Jacobian of symbol of type '{type(symbol)}'"
)
) from error

# Jacobian by default removes the domain(s)
if self._clear_domain:
Expand Down
5 changes: 3 additions & 2 deletions pybamm/expression_tree/operations/latexify.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ def _get_geometry_displays(self, var):
rng_min = get_rng_min_max_name(rng, "min")

# Take range maximum from the last domain
for var_name, rng in self.model.default_geometry[var.domain[-1]].items():
for _, rng in self.model.default_geometry[var.domain[-1]].items():
rng_max = get_rng_min_max_name(rng, "max")

geo_latex = f"\quad {rng_min} < {name} < {rng_max}"
Expand Down Expand Up @@ -303,7 +303,8 @@ def latexify(self, output_variables=None):
# When equations are too huge, set output resolution to default
except RuntimeError: # pragma: no cover
warnings.warn(
"RuntimeError - Setting the output resolution to default"
"RuntimeError - Setting the output resolution to default",
stacklevel=2,
)
return sympy.preview(
eqn_new_line,
Expand Down
16 changes: 9 additions & 7 deletions pybamm/expression_tree/symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import numpy as np
import sympy
from scipy.sparse import csr_matrix, issparse
from functools import lru_cache, cached_property
from functools import cached_property
from typing import TYPE_CHECKING, Sequence, cast

import pybamm
Expand Down Expand Up @@ -876,7 +876,7 @@ def evaluate_ignoring_errors(self, t: float | None = 0):
return None
raise pybamm.ShapeError(
f"Cannot find shape (original error: {error})"
) # pragma: no cover
) from error # pragma: no cover
return result

def evaluates_to_number(self):
Expand All @@ -895,7 +895,6 @@ def evaluates_to_number(self):
def evaluates_to_constant_number(self):
return self.evaluates_to_number() and self.is_constant()

@lru_cache
def evaluates_on_edges(self, dimension: str) -> bool:
"""
Returns True if a symbol evaluates on an edge, i.e. symbol contains a gradient
Expand All @@ -914,9 +913,12 @@ def evaluates_on_edges(self, dimension: str) -> bool:
Whether the symbol evaluates on edges (in the finite volume discretisation
sense)
"""
eval_on_edges = self._evaluates_on_edges(dimension)
self._saved_evaluates_on_edges[dimension] = eval_on_edges
return eval_on_edges
if dimension not in self._saved_evaluates_on_edges:
self._saved_evaluates_on_edges[dimension] = self._evaluates_on_edges(
dimension
)

return self._saved_evaluates_on_edges[dimension]

def _evaluates_on_edges(self, dimension):
# Default behaviour: return False
Expand Down Expand Up @@ -1039,7 +1041,7 @@ def test_shape(self):
try:
self.shape_for_testing
except ValueError as e:
raise pybamm.ShapeError(f"Cannot find shape (original error: {e})")
raise pybamm.ShapeError(f"Cannot find shape (original error: {e})") from e

@property
def print_name(self):
Expand Down
4 changes: 2 additions & 2 deletions pybamm/install_odes.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,8 @@ def install_sundials(download_dir, install_dir):

try:
subprocess.run(["cmake", "--version"])
except OSError:
raise RuntimeError("CMake must be installed to build SUNDIALS.")
except OSError as error:
raise RuntimeError("CMake must be installed to build SUNDIALS.") from error

url = f"https://github.com/LLNL/sundials/releases/download/v{SUNDIALS_VERSION}/sundials-{SUNDIALS_VERSION}.tar.gz"
logger.info("Downloading sundials")
Expand Down
6 changes: 3 additions & 3 deletions pybamm/meshes/meshes.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,8 @@ def __init__(self, geometry, submesh_types, var_pts):
for spatial_variable, spatial_limits in geometry[domain].items():
# process tab information if using 1 or 2D current collectors
if spatial_variable == "tabs":
for tab, position_size in spatial_limits.items():
for position_size, sym in position_size.items():
for tab, position_info in spatial_limits.items():
for position_size, sym in position_info.items():
if isinstance(sym, pybamm.Symbol):
sym_eval = sym.evaluate()
geometry[domain]["tabs"][tab][position_size] = sym_eval
Expand All @@ -102,7 +102,7 @@ def __init__(self, geometry, submesh_types, var_pts):
"geometry. Make sure that something like "
"`param.process_geometry(geometry)` has been "
"run."
)
) from error
else:
raise error
elif isinstance(sym, numbers.Number):
Expand Down
13 changes: 7 additions & 6 deletions pybamm/models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ def build_coupled_variables(self):
f"Missing variable for submodel '{submodel_name}': {key}.\n"
+ "Check the selected "
"submodels provide all of the required variables."
)
) from key
else:
# try setting coupled variables on next loop through
pybamm.logger.debug(
Expand Down Expand Up @@ -679,7 +679,7 @@ def set_initial_conditions_from(self, solution, inplace=True, return_type="model
"model.initial_conditions must appear in the solution with "
"the same key as the variable name. In the solution provided, "
f"'{e.args[0]}' was not found."
)
) from e
if isinstance(solution, pybamm.Solution):
final_state = final_state.data
if final_state.ndim == 0:
Expand All @@ -703,7 +703,7 @@ def set_initial_conditions_from(self, solution, inplace=True, return_type="model
"model.initial_conditions must appear in the solution with "
"the same key as the variable name. In the solution "
f"provided, {e.args[0]}"
)
) from e
if isinstance(solution, pybamm.Solution):
final_state = final_state.data
if final_state.ndim == 2:
Expand Down Expand Up @@ -875,8 +875,8 @@ def check_well_determined(self, post_discretisation):
]
)
all_vars_in_eqns.update(vars_in_eqns)
for var, side_eqn in self.boundary_conditions.items():
for side, (eqn, typ) in side_eqn.items():
for _, side_eqn in self.boundary_conditions.items():
for _, (eqn, _) in side_eqn.items():
vars_in_eqns = unpacker.unpack_symbol(eqn)
all_vars_in_eqns.update(vars_in_eqns)

Expand Down Expand Up @@ -1003,7 +1003,7 @@ def check_discretised_or_discretise_inplace_if_0D(self):
raise pybamm.DiscretisationError(
"Cannot automatically discretise model, model should be "
f"discretised before exporting casadi functions ({e})"
)
) from e

def export_casadi_objects(self, variable_names, input_parameter_order=None):
"""
Expand Down Expand Up @@ -1244,6 +1244,7 @@ def save_model(self, filename=None, mesh=None, variables=None):
Plotting may not be available.
""",
pybamm.ModelWarning,
stacklevel=2,
)

Serialise().save_model(self, filename=filename, mesh=mesh, variables=variables)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,21 @@ def get_initial_stoichiometry_half_cell(
return x


def get_min_max_stoichiometries(
parameter_values, options={"working electrode": "positive"}
):
def get_min_max_stoichiometries(parameter_values, options=None):
"""
Get the minimum and maximum stoichiometries from the parameter values
Parameters
----------
parameter_values : pybamm.ParameterValues
The parameter values to use in the calculation
options : dict, optional
A dictionary of options to be passed to the parameters, see
:class:`pybamm.BatteryModelOptions`.
If None, the default is used: {"working electrode": "positive"}
"""
if options is None:
options = {"working electrode": "positive"}
esoh_model = pybamm.lithium_ion.ElectrodeSOHHalfCell("ElectrodeSOH")
param = pybamm.LithiumIonParameters(options)
esoh_sim = pybamm.Simulation(esoh_model, parameter_values=parameter_values)
Expand Down
Loading

0 comments on commit 5d8417b

Please sign in to comment.