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

Move ruff, coverage, and pytest configs to pyproject.toml #3557

Merged
merged 12 commits into from
Nov 27, 2023
3 changes: 0 additions & 3 deletions .coveragerc

This file was deleted.

2 changes: 2 additions & 0 deletions .git-blame-ignore-revs
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,5 @@
a63e49ece0f9336d1f5c2562f7459e555c6e6693
# activated standard pre-commits - https://github.com/pybamm-team/PyBaMM/pull/3192
5273214b585c5a4286609aed40e0b092d0e05f42
# migrate config to pyproject.toml - https://github.com/pybamm-team/PyBaMM/pull/3557
12c5d77203bd93542785d237bac00bad5ed5469a
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 @@ -96,7 +96,7 @@
plt.savefig(f"benchmarks/benchmark_images/time_vs_abstols_{pybamm.__version__}.png")


content = f"# PyBaMM {pybamm.__version__}\n## Solve Time vs Abstols\n<img src='./benchmark_images/time_vs_abstols_{pybamm.__version__}.png'>\n" # noqa
content = f"# PyBaMM {pybamm.__version__}\n## Solve Time vs Abstols\n<img src='./benchmark_images/time_vs_abstols_{pybamm.__version__}.png'>\n"

with open("./benchmarks/release_work_precision_sets.md", "r") as original:
data = original.read()
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 @@ -98,7 +98,7 @@
plt.savefig(f"benchmarks/benchmark_images/time_vs_dt_max_{pybamm.__version__}.png")


content = f"## Solve Time vs dt_max\n<img src='./benchmark_images/time_vs_dt_max_{pybamm.__version__}.png'>\n" # noqa
content = f"## Solve Time vs dt_max\n<img src='./benchmark_images/time_vs_dt_max_{pybamm.__version__}.png'>\n"

with open("./benchmarks/release_work_precision_sets.md", "r") as original:
data = original.read()
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 @@ -78,7 +78,7 @@
plt.savefig(f"benchmarks/benchmark_images/time_vs_mesh_size_{pybamm.__version__}.png")


content = f"## Solve Time vs Mesh size\n<img src='./benchmark_images/time_vs_mesh_size_{pybamm.__version__}.png'>\n" # noqa
content = f"## Solve Time vs Mesh size\n<img src='./benchmark_images/time_vs_mesh_size_{pybamm.__version__}.png'>\n"

with open("./benchmarks/release_work_precision_sets.md", "r") as original:
data = original.read()
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 @@ -82,7 +82,7 @@
)


content = f"## Solve Time vs Number of states\n<img src='./benchmark_images/time_vs_no_of_states_{pybamm.__version__}.png'>\n" # noqa
content = f"## Solve Time vs Number of states\n<img src='./benchmark_images/time_vs_no_of_states_{pybamm.__version__}.png'>\n"

with open("./benchmarks/release_work_precision_sets.md", "r") as original:
data = original.read()
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 @@ -102,7 +102,7 @@
plt.savefig(f"benchmarks/benchmark_images/time_vs_reltols_{pybamm.__version__}.png")


content = f"## Solve Time vs Reltols\n<img src='./benchmark_images/time_vs_reltols_{pybamm.__version__}.png'>\n" # noqa
content = f"## Solve Time vs Reltols\n<img src='./benchmark_images/time_vs_reltols_{pybamm.__version__}.png'>\n"

with open("./benchmarks/release_work_precision_sets.md", "r") as original:
data = original.read()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
"delta = pybamm.Parameter(\"Current collector thickness\")\n",
"delta_p = delta # assume same thickness\n",
"delta_n = delta # assume same thickness\n",
"l = 1/2 - delta_p - delta_n # active material thickness # noqa: E741\n",
"l = 1/2 - delta_p - delta_n # active material thickness\n",
"sigma_p = pybamm.Parameter(\"Positive current collector conductivity\")\n",
"sigma_n = pybamm.Parameter(\"Negative current collector conductivity\")\n",
"sigma_a = pybamm.Parameter(\"Active material conductivity\")"
Expand Down
2 changes: 1 addition & 1 deletion docs/source/examples/notebooks/models/latexify.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -1252,7 +1252,7 @@
"source": [
"spme_latex = model_spme.latexify(newline=False)\n",
"for line in spme_latex:\n",
" display(line) # noqa: F821"
" display(line)"
]
},
{
Expand Down
1 change: 1 addition & 0 deletions docs/source/user_guide/installation/index.rst
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,7 @@ Dependency
`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.
Expand Down
6 changes: 3 additions & 3 deletions examples/scripts/print_model_parameter_combinations.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,13 +19,13 @@
try:
model = pybamm.lithium_ion.SPM(options.copy())
except pybamm.OptionError as e:
print(f"Cannot create model with {options}. (OptionError: {str(e)})")
print(f"Cannot create model with {options}. (OptionError: {e!s})")
except pybamm.ModelError as e:
# todo: properly resolve the cases that raise these errors
print(f"Cannot create model with {options}. (ModelError: {str(e)})")
print(f"Cannot create model with {options}. (ModelError: {e!s})")
except AttributeError as e:
# todo: properly resolve the cases that raise these errors
print(f"Cannot create model with {options}. (AttributeError: {str(e)})")
print(f"Cannot create model with {options}. (AttributeError: {e!s})")
else:
output = f"{options} with {parameter_set} parameters: "
try:
Expand Down
4 changes: 2 additions & 2 deletions noxfile.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ def set_environment_variables(env_dict, session):

@nox.session(name="pybamm-requires")
def run_pybamm_requires(session):
"""Download, compile, and install the build-time requirements for Linux and macOS: the SuiteSparse and SUNDIALS libraries.""" # noqa: E501
"""Download, compile, and install the build-time requirements for Linux and macOS: the SuiteSparse and SUNDIALS libraries."""
set_environment_variables(PYBAMM_ENV, session=session)
if sys.platform != "win32":
session.install("wget", "cmake", silent=False)
Expand All @@ -64,7 +64,7 @@ def run_coverage(session):
session.install("-e", ".[all,odes,jax]", silent=False)
else:
session.install("-e", ".[all]", silent=False)
session.run("coverage", "run", "--rcfile=.coveragerc", "run-tests.py", "--nosub")
session.run("coverage", "run", "run-tests.py", "--nosub")
session.run("coverage", "combine")
session.run("coverage", "xml")

Expand Down
2 changes: 1 addition & 1 deletion pybamm/citations.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ def print_citations(filename=None, output_format="text", verbose=False):
if verbose: # pragma: no cover
if filename is not None: # pragma: no cover
raise Exception(
"Verbose output is available only for the terminal and not for printing to files", # noqa: E501
"Verbose output is available only for the terminal and not for printing to files",
)
else:
citations.print(filename, output_format, verbose=True)
Expand Down
4 changes: 2 additions & 2 deletions pybamm/discretisations/discretisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -461,7 +461,7 @@ def process_boundary_conditions(self, model):
if (
self.mesh[subdomain].coord_sys
in ["spherical polar", "cylindrical polar"]
and list(self.mesh.geometry[subdomain].values())[0]["min"] == 0
and next(iter(self.mesh.geometry[subdomain].values()))["min"] == 0
):
if bcs["left"][0].value != 0 or bcs["left"][1] != "Neumann":
raise pybamm.ModelError(
Expand Down Expand Up @@ -753,7 +753,7 @@ def _process_symbol(self, symbol):
spatial_method = self.spatial_methods[symbol.domain[0]]
# If boundary conditions are provided, need to check for BCs on tabs
if self.bcs:
key_id = list(self.bcs.keys())[0]
key_id = next(iter(self.bcs.keys()))
if any("tab" in side for side in list(self.bcs[key_id].keys())):
self.bcs[key_id] = self.check_tab_conditions(
symbol, self.bcs[key_id]
Expand Down
2 changes: 1 addition & 1 deletion pybamm/expression_tree/array.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ def entries_string(self, value):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`."""
self._id = hash(
(self.__class__, self.name) + self.entries_string + tuple(self.domain)
(self.__class__, self.name, *self.entries_string, *tuple(self.domain))
)

def _jac(self, variable):
Expand Down
4 changes: 1 addition & 3 deletions pybamm/expression_tree/interpolant.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,9 +222,7 @@ def entries_string(self, value):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`."""
self._id = hash(
(self.__class__, self.name, self.entries_string)
+ tuple([child.id for child in self.children])
+ tuple(self.domain)
(self.__class__, self.name, self.entries_string, *tuple([child.id for child in self.children]), *tuple(self.domain))
)

def _function_new_copy(self, children):
Expand Down
4 changes: 2 additions & 2 deletions pybamm/expression_tree/operations/evaluate_python.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ class JaxCooMatrix:
def __init__(self, row, col, data, shape):
if not pybamm.have_jax(): # pragma: no cover
raise ModuleNotFoundError(
"Jax or jaxlib is not installed, please see https://docs.pybamm.org/en/latest/source/user_guide/installation/GNU-linux.html#optional-jaxsolver" # noqa: E501
"Jax or jaxlib is not installed, please see https://docs.pybamm.org/en/latest/source/user_guide/installation/GNU-linux.html#optional-jaxsolver"
)

self.row = jax.numpy.array(row)
Expand Down Expand Up @@ -537,7 +537,7 @@ class EvaluatorJax:
def __init__(self, symbol):
if not pybamm.have_jax(): # pragma: no cover
raise ModuleNotFoundError(
"Jax or jaxlib is not installed, please see https://docs.pybamm.org/en/latest/source/user_guide/installation/GNU-linux.html#optional-jaxsolver" # noqa: E501
"Jax or jaxlib is not installed, please see https://docs.pybamm.org/en/latest/source/user_guide/installation/GNU-linux.html#optional-jaxsolver"
)

constants, python_str = pybamm.to_python(symbol, debug=False, output_jax=True)
Expand Down
6 changes: 3 additions & 3 deletions pybamm/expression_tree/operations/latexify.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,9 +93,9 @@ def _get_bcs_displays(self, var):

if bcs:
# Take range minimum from the first domain
var_name = list(self.model.default_geometry[var.domain[0]].keys())[0]
rng_left = list(self.model.default_geometry[var.domain[0]].values())[0]
rng_right = list(self.model.default_geometry[var.domain[-1]].values())[0]
var_name = next(iter(self.model.default_geometry[var.domain[0]].keys()))
rng_left = next(iter(self.model.default_geometry[var.domain[0]].values()))
rng_right = next(iter(self.model.default_geometry[var.domain[-1]].values()))

# Trim name (r_n --> r)
var_name = re.findall(r"(.)_*.*", str(var_name))[0]
Expand Down
4 changes: 1 addition & 3 deletions pybamm/expression_tree/parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,9 +152,7 @@ def input_names(self, inp=None):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id`"""
self._id = hash(
(self.__class__, self.name, self.diff_variable)
+ tuple([child.id for child in self.children])
+ tuple(self.domain)
(self.__class__, self.name, self.diff_variable, *tuple([child.id for child in self.children]), *tuple(self.domain))
)

def diff(self, variable):
Expand Down
3 changes: 1 addition & 2 deletions pybamm/expression_tree/state_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,8 +107,7 @@ def set_evaluation_array(self, y_slices, evaluation_array):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name, tuple(self.evaluation_array))
+ tuple(self.domain)
(self.__class__, self.name, tuple(self.evaluation_array), *tuple(self.domain))
)

def _jac_diff_vector(self, variable):
Expand Down
4 changes: 1 addition & 3 deletions pybamm/expression_tree/symbol.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,9 +403,7 @@ def set_id(self):
need to hash once.
"""
self._id = hash(
(self.__class__, self.name)
+ tuple([child.id for child in self.children])
+ tuple([(k, tuple(v)) for k, v in self.domains.items() if v != []])
(self.__class__, self.name, *tuple([child.id for child in self.children]), *tuple([(k, tuple(v)) for k, v in self.domains.items() if v != []]))
)

@property
Expand Down
31 changes: 6 additions & 25 deletions pybamm/expression_tree/unary_operators.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,14 +287,7 @@ def _unary_jac(self, child_jac):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(
self.__class__,
self.name,
self.slice.start,
self.slice.stop,
self.children[0].id,
)
+ tuple(self.domain)
(self.__class__, self.name, self.slice.start, self.slice.stop, self.children[0].id, *tuple(self.domain))
)

def _unary_evaluate(self, child):
Expand Down Expand Up @@ -554,15 +547,7 @@ def integration_variable(self):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name)
+ tuple(
[
integration_variable.id
for integration_variable in self.integration_variable
]
)
+ (self.children[0].id,)
+ tuple(self.domain)
(self.__class__, self.name, *tuple([integration_variable.id for integration_variable in self.integration_variable]), self.children[0].id, *tuple(self.domain))
)

def _unary_new_copy(self, child):
Expand Down Expand Up @@ -702,9 +687,7 @@ def __init__(self, child, vector_type="row"):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name, self.vector_type)
+ (self.children[0].id,)
+ tuple(self.domain)
(self.__class__, self.name, self.vector_type, self.children[0].id, *tuple(self.domain))
)

def _unary_new_copy(self, child):
Expand Down Expand Up @@ -757,7 +740,7 @@ def __init__(self, child, region="entire"):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name) + (self.children[0].id,) + tuple(self.domain)
(self.__class__, self.name, self.children[0].id, *tuple(self.domain))
)

def _unary_new_copy(self, child):
Expand Down Expand Up @@ -798,8 +781,7 @@ def __init__(self, child, side, domain):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name, self.side, self.children[0].id)
+ tuple([(k, tuple(v)) for k, v in self.domains.items()])
(self.__class__, self.name, self.side, self.children[0].id, *tuple([(k, tuple(v)) for k, v in self.domains.items()]))
)

def _evaluates_on_edges(self, dimension):
Expand Down Expand Up @@ -857,8 +839,7 @@ def __init__(self, name, child, side):
def set_id(self):
"""See :meth:`pybamm.Symbol.set_id()`"""
self._id = hash(
(self.__class__, self.name, self.side, self.children[0].id)
+ tuple([(k, tuple(v)) for k, v in self.domains.items()])
(self.__class__, self.name, self.side, self.children[0].id, *tuple([(k, tuple(v)) for k, v in self.domains.items()]))
)

def _unary_new_copy(self, child):
Expand Down
3 changes: 1 addition & 2 deletions pybamm/expression_tree/variable.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,8 +103,7 @@ def bounds(self, values):

def set_id(self):
self._id = hash(
(self.__class__, self.name, self.scale, self.reference)
+ tuple([(k, tuple(v)) for k, v in self.domains.items() if v != []])
(self.__class__, self.name, self.scale, self.reference, *tuple([(k, tuple(v)) for k, v in self.domains.items() if v != []]))
)

def create_copy(self):
Expand Down
2 changes: 1 addition & 1 deletion pybamm/install_odes.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ def install_sundials(download_dir, install_dir):

print("-" * 10, "Running CMake prepare", "-" * 40)
subprocess.run(
["cmake", "../sundials-{}".format(sundials_version)] + cmake_args,
["cmake", "../sundials-{}".format(sundials_version), *cmake_args],
cwd=build_directory,
check=True,
)
Expand Down
2 changes: 1 addition & 1 deletion pybamm/meshes/zero_dimensional_submesh.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def __init__(self, position, npts=None):
raise pybamm.GeometryError("position should only contain a single variable")

# extract the position
position = list(position.values())[0]
position = next(iter(position.values()))
spatial_position = position["position"]
self.nodes = np.array([spatial_position])
self.edges = np.array([spatial_position])
Expand Down
2 changes: 1 addition & 1 deletion pybamm/models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -1205,7 +1205,7 @@ def check_and_convert_equations(self, equations):
for var, eqn in equations.items():
if eqn.has_symbol_of_classes(pybamm.Variable):
unpacker = pybamm.SymbolUnpacker(pybamm.Variable)
variable_in_equation = list(unpacker.unpack_symbol(eqn))[0]
variable_in_equation = next(iter(unpacker.unpack_symbol(eqn)))
raise TypeError(
"Initial conditions cannot contain 'Variable' objects, "
"but '{!r}' found in initial conditions for '{}'".format(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ class FullAlgebraic(BaseModel):
The parameters to use for this submodel
options : dict, optional
A dictionary of options to be passed to the model.
""" # noqa: E501
"""

def __init__(self, param, domain, options=None):
super().__init__(param, domain, options)
Expand Down Expand Up @@ -258,7 +258,7 @@ class FullDifferential(BaseModel):
The parameters to use for this submodel
options : dict, optional
A dictionary of options to be passed to the model.
""" # noqa: E501
"""

def __init__(self, param, domain, options=None):
super().__init__(param, domain, options)
Expand Down
2 changes: 1 addition & 1 deletion pybamm/parameters_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ def raise_error():
raise NotImplementedError(
"parameters cli has been deprecated. "
"Parameters should now be defined via python files (see "
"https://github.com/pybamm-team/PyBaMM/tree/develop/pybamm/input/parameters/lithium_ion/Ai2020.py" # noqa: E501
"https://github.com/pybamm-team/PyBaMM/tree/develop/pybamm/input/parameters/lithium_ion/Ai2020.py"
" for example)"
)

Expand Down
6 changes: 3 additions & 3 deletions pybamm/plotting/quick_plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -534,7 +534,7 @@ def plot(self, t, dynamic=False):
# 1D plot: plot as a function of x at time t
# Read dictionary of spatial variables
spatial_vars = self.spatial_variable_dict[key]
spatial_var_name = list(spatial_vars.keys())[0]
spatial_var_name = next(iter(spatial_vars.keys()))
ax.set_xlabel(
"{} [{}]".format(spatial_var_name, self.spatial_unit),
)
Expand Down Expand Up @@ -568,12 +568,12 @@ def plot(self, t, dynamic=False):
# different order based on whether the domains are x-r, x-z or y-z, etc
if self.x_first_and_y_second[key] is False:
x_name = list(spatial_vars.keys())[1][0]
y_name = list(spatial_vars.keys())[0][0]
y_name = next(iter(spatial_vars.keys()))[0]
x = self.second_spatial_variable[key]
y = self.first_spatial_variable[key]
var = variable(t_in_seconds, **spatial_vars, warn=False)
else:
x_name = list(spatial_vars.keys())[0][0]
x_name = next(iter(spatial_vars.keys()))[0]
y_name = list(spatial_vars.keys())[1][0]
x = self.first_spatial_variable[key]
y = self.second_spatial_variable[key]
Expand Down
2 changes: 1 addition & 1 deletion pybamm/simulation.py
Original file line number Diff line number Diff line change
Expand Up @@ -375,7 +375,7 @@ def set_initial_soc(self, initial_soc):
param = self._model.param
if options["open-circuit potential"] == "MSMR":
self._parameter_values = (
self._unprocessed_parameter_values.set_initial_ocps( # noqa: E501
self._unprocessed_parameter_values.set_initial_ocps(
initial_soc, param=param, inplace=False, options=options
)
)
Expand Down
Loading
Loading