Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable Flake8-bugbear #3859

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
97ea28a
Enable flake8-bugbear
lorenzofavaro Mar 3, 2024
17bcc6c
Show exception chain (B904)
lorenzofavaro Mar 6, 2024
4c7de48
Disable single lint check (B019)
lorenzofavaro Mar 6, 2024
9271b1a
delay xarray.DataArray initialization
valentinsulzer Mar 4, 2024
4c5f594
revert example
valentinsulzer Mar 5, 2024
69e64dd
Bump the actions group with 1 update (#3861)
dependabot[bot] Mar 4, 2024
4a5c6eb
Make `typing-extensions` and `sympy` required dependencies to fix PyB…
arjxn-py Mar 5, 2024
885fe90
Rename have_optional_dependency (#3866)
kratman Mar 5, 2024
4fcf584
update changelog for #3862 (#3869)
valentinsulzer Mar 6, 2024
724040b
fix deprecation warning and check for electrode/particle diffusivity
valentinsulzer Mar 7, 2024
fce31a6
update test
valentinsulzer Mar 7, 2024
1034e70
Edit naming for unused loop control variable (B007)
lorenzofavaro Mar 8, 2024
393060e
#3883 updates to install from source (#3884)
martinjrobins Mar 11, 2024
971be85
Disable benchmarks on PRs (#3876)
kratman Mar 11, 2024
9c9b436
Remove`[ latexify` extra (#3888)
kratman Mar 12, 2024
3bbc8bb
Improve Getting Started notebooks (#3750)
brosaplanella Mar 12, 2024
b762f75
chore: update pre-commit hooks (#3890)
pre-commit-ci[bot] Mar 13, 2024
34d9e71
style: pre-commit fixes
pre-commit-ci[bot] Mar 13, 2024
870656f
Resolve conflicts (B904, B028, B020)
lorenzofavaro Mar 13, 2024
8a89e86
Added a schedule on `needs-reply remove` workflow (#3891)
santacodes Mar 13, 2024
2cdaabb
Merge branch 'develop' into flake8-bugbear-patch
lorenzofavaro Mar 13, 2024
3600062
style: pre-commit fixes
pre-commit-ci[bot] Mar 13, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
arjxn-py marked this conversation as resolved.
Show resolved Hide resolved
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):
lorenzofavaro marked this conversation as resolved.
Show resolved Hide resolved
"""
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
Loading