Skip to content

Commit

Permalink
Enable Flake8-bugbear (pybamm-team#3859)
Browse files Browse the repository at this point in the history
* Enable flake8-bugbear

Fix unused-loop-control-variable (B007)

Fix function-uses-loop-variable (B023)

Fix raise-without-from-inside-except (B904)

Fix mutable-argument-default (B006)

Fix no-explicit-stacklevel (B028)

Fix get-attr-with-constant (B009)

Fix loop-variable-overrides-iterator (B020)

Fix unary-prefix-increment-decrement (B002)

Fix function-call-in-default-argument (B008)

Fix cached-instance-method (B019)

* Show exception chain (B904)

* Disable single lint check (B019)

* delay xarray.DataArray initialization

* revert example

* Bump the actions group with 1 update (pybamm-team#3861)

Bumps the actions group with 1 update: [awalsh128/cache-apt-pkgs-action](https://github.com/awalsh128/cache-apt-pkgs-action).


Updates `awalsh128/cache-apt-pkgs-action` from 1.4.1 to 1.4.2
- [Release notes](https://github.com/awalsh128/cache-apt-pkgs-action/releases)
- [Commits](awalsh128/cache-apt-pkgs-action@v1.4.1...v1.4.2)

---
updated-dependencies:
- dependency-name: awalsh128/cache-apt-pkgs-action
  dependency-type: direct:production
  update-type: version-update:semver-patch
  dependency-group: actions
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>

* Make `typing-extensions` and `sympy` required dependencies to fix PyBaMM import (pybamm-team#3848)

* import `typing_extensions` as optional_dependency

* Make `typing-extensions` a required dependency

* Try forward referencing for `sympy` in `IndependentVariable`

* Make `sympy` a required dependency

* Update docs for SymPy

* Import `sympy` without `have_optional_dependency`

* Import `sympy` without `TYPE_CHECKING`

* Changelog

* Update CHANGELOG.md

Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>

* Rearrange position in changelog

---------

Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>
Co-authored-by: Eric G. Kratz <kratman@users.noreply.github.com>

* Rename have_optional_dependency (pybamm-team#3866)

* Rename have_optional_dependency

* Change log

* Fix import

* style: pre-commit fixes

* Update pybamm/util.py

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Arjun Verma <arjunverma.oc@gmail.com>

* update changelog for pybamm-team#3862 (pybamm-team#3869)

* update changelog for pybamm-team#3862

* reword

* fix deprecation warning and check for electrode/particle diffusivity

* update test

* Edit naming for unused loop control variable (B007)

* pybamm-team#3883 updates to install from source (pybamm-team#3884)

* Disable benchmarks on PRs (pybamm-team#3876)

* Remove`[ latexify` extra (pybamm-team#3888)

* Improve Getting Started notebooks (pybamm-team#3750)

* improve tutorials 1 to 3

* use new syntax for plot_voltage_components

* style: pre-commit fixes

* simplify notebook by removing drive cycle

* add additional comment on dynamic_plot

* improve tutorial 5

* remove the use of solution in notebook 5, this is introduced in notebook 6

* fix minor typo

* minor text updates

* style: pre-commit fixes

* minor text updates plus extra links

* minor text updates!

* minor text updates

* remove tutorial 10 as very similar to tutorial 3 in creating models

* move and rename tutorial 11 to creating models section

* style: pre-commit fixes

* fix minor typo in current_with_time

* implement Rob & Eric's comments

* update docs links

* Valentin's comments

* style: pre-commit fixes

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Eric G. Kratz <kratman@users.noreply.github.com>

* chore: update pre-commit hooks (pybamm-team#3890)

* chore: update pre-commit hooks

updates:
- [github.com/astral-sh/ruff-pre-commit: v0.2.2 → v0.3.2](astral-sh/ruff-pre-commit@v0.2.2...v0.3.2)

* style: pre-commit fixes

* Update .git-blame-ignore-revs

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>

* style: pre-commit fixes

* Resolve conflicts (B904, B028, B020)

* Added a schedule on `needs-reply remove` workflow  (pybamm-team#3891)

* added schedule to need-reply workflow

* added schedule to need-reply workflow

---------

Co-authored-by: Arjun Verma <arjunverma.oc@gmail.com>

* style: pre-commit fixes

---------

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: Valentin Sulzer <valentinsulzer@hotmail.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
Co-authored-by: Arjun Verma <arjunverma.oc@gmail.com>
Co-authored-by: Agriya Khetarpal <74401230+agriyakhetarpal@users.noreply.github.com>
Co-authored-by: Eric G. Kratz <kratman@users.noreply.github.com>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Martin Robinson <martinjrobins@gmail.com>
Co-authored-by: Ferran Brosa Planella <Ferran.Brosa-Planella@warwick.ac.uk>
Co-authored-by: Santhosh <52504160+santacodes@users.noreply.github.com>
  • Loading branch information
10 people authored and js1tr3 committed Aug 12, 2024
1 parent 0a469b3 commit f83261f
Show file tree
Hide file tree
Showing 46 changed files with 147 additions and 114 deletions.
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 @@ -102,8 +102,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 @@ -47,8 +47,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 @@ -590,7 +590,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 @@ -677,7 +677,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 @@ -701,7 +701,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 @@ -873,8 +873,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 @@ -1001,7 +1001,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 @@ -1242,6 +1242,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
4 changes: 2 additions & 2 deletions pybamm/models/submodels/thermal/base_thermal.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ def _get_standard_coupled_variables(self, variables):
# Total Ohmic heating
Q_ohm = Q_ohm_s + Q_ohm_e

num_phases = int(getattr(self.options, "positive")["particle phases"])
num_phases = int(self.options.positive["particle phases"])
phase_names = [""]
if num_phases > 1:
phase_names = ["primary ", "secondary "]
Expand All @@ -135,7 +135,7 @@ def _get_standard_coupled_variables(self, variables):
dUdT_p = variables[f"Positive electrode {phase}entropic change [V.K-1]"]
Q_rev_p += a_j_p * T_p * dUdT_p

num_phases = int(getattr(self.options, "negative")["particle phases"])
num_phases = int(self.options.negative["particle phases"])
phase_names = [""]
if num_phases > 1:
phase_names = ["primary", "secondary"]
Expand Down
8 changes: 5 additions & 3 deletions pybamm/parameters/base_parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,9 @@ def __getattribute__(self, name):
return super().__getattribute__(name)
except AttributeError as e:
if name == "cap_init":
warnings.warn("Parameter 'cap_init' has been renamed to 'Q_init'")
warnings.warn(
"Parameter 'cap_init' has been renamed to 'Q_init'", stacklevel=2
)
return self.Q_init
for domain in ["n", "s", "p"]:
if f"_{domain}_" in name or name.endswith(f"_{domain}"):
Expand All @@ -32,14 +34,14 @@ def __getattribute__(self, name):
raise AttributeError(
f"param.{name} does not exist. It has been renamed to "
f"param.{domain}.{name_without_domain}"
)
) from e
elif hasattr(self_domain, "prim") and hasattr(
self_domain.prim, name_without_domain
):
raise AttributeError(
f"param.{name} does not exist. It has been renamed to "
f"param.{domain}.prim.{name_without_domain}"
)
) from e
else:
raise e
else:
Expand Down
Loading

0 comments on commit f83261f

Please sign in to comment.