From fb4f944c05808f733e53ba0598b3bf3320a6ea58 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 20:41:22 +0530 Subject: [PATCH 01/11] Move ruff, coverage, and pytest configs to pyproject.toml --- .coveragerc | 3 - docs/source/user_guide/installation/index.rst | 1 + pyproject.toml | 75 +++++++++++++++++++ pytest.ini | 15 ---- ruff.toml | 8 -- 5 files changed, 76 insertions(+), 26 deletions(-) delete mode 100644 .coveragerc delete mode 100644 pytest.ini delete mode 100644 ruff.toml diff --git a/.coveragerc b/.coveragerc deleted file mode 100644 index a174f5aced..0000000000 --- a/.coveragerc +++ /dev/null @@ -1,3 +0,0 @@ -[run] -source = pybamm -concurrency = multiprocessing diff --git a/docs/source/user_guide/installation/index.rst b/docs/source/user_guide/installation/index.rst index 983f66842e..e771611a37 100644 --- a/docs/source/user_guide/installation/index.rst +++ b/docs/source/user_guide/installation/index.rst @@ -154,6 +154,7 @@ Dependency `pre-commit `__ \- dev For managing and maintaining multi-language pre-commit hooks. `ruff `__ \- dev For code formatting. `nox `__ \- dev For running testing sessions in multiple environments. +`coverage `__ \- dev For calculating coverage of tests. `pytest `__ 6.0.0 dev For running Jupyter notebooks tests. `pytest-xdist `__ \- dev For running tests in parallel across distributed workers. `nbmake `__ \- dev A ``pytest`` plugin for executing Jupyter notebooks. diff --git a/pyproject.toml b/pyproject.toml index 4569c7c6c3..40455454b1 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -102,6 +102,8 @@ dev = [ "ruff", # For running testing sessions "nox", + # For coverage + coverage[toml], # For testing Jupyter notebooks "pytest>=6", "pytest-xdist", @@ -172,3 +174,76 @@ pybamm = [ [tool.setuptools.packages.find] include = ["pybamm", "pybamm.*"] + +[tool.ruff] +extend-include = ["*.ipynb"] +extend-exclude = ["__init__.py"] + +[tool.ruff.lint] +extend-select = [ + # "B", # flake8-bugbear + # "I", # isort + # "ARG", # flake8-unused-arguments + # "C4", # flake8-comprehensions + # "ICN", # flake8-import-conventions + # "ISC", # flake8-implicit-str-concat + # "PGH", # pygrep-hooks + # "PIE", # flake8-pie + # "PL", # pylint + # "PT", # flake8-pytest-style + # "PTH", # flake8-use-pathlib + # "RET", # flake8-return + "RUF", # Ruff-specific + # "SIM", # flake8-simplify + # "T20", # flake8-print + # "UP", # pyupgrade + "YTT", # flake8-2020 +] +ignore = [ + "E741", # Ambiguous variable name + "RUF012", # Mutable class attributes should be annotated with `typing.ClassVar` + "SIM108", # Use ternary operator + "ARG001", # Unused function argument: + "ARG002", # Unused method arguments + "PLR2004", # Magic value used in comparison + "PLR0915", # Too many statements + "PLR0913", # Too many arguments + "PLR0912", # Too many branches + "RET504", # Unnecessary assignment + "RET505", # Unnecessary `else` + "RET506", # Unnecessary `elif` + "B018", # Found useless expression + "RUF002", # Docstring contains ambiguous +] + +[tool.ruff.lint.per-file-ignores] +"tests/*" = ["T20"] +"docs/*" = ["T20"] +"examples/*" = ["T20"] +"**.ipynb" = ["E402", "E703"] + +# NOTE: currently used only for notebook tests with the nbmake plugin. +[tool.pytest] +# Use pytest-xdist to run tests in parallel by default, exit with +# error if not installed +required_plugins = [ + "pytest-xdist", +] +addopts = [ + "-nauto", + "-v", +] +testpaths = [ + "docs/source/examples/", +] +console_output_style = "progress" + +# Logging configuration +log_cli = "true" +log_cli_level = "INFO" +log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" +log_date_format = "%Y-%m-%d %H:%M:%S" + +[tool.coverage.run] +source = pybamm +concurrency = multiprocessing diff --git a/pytest.ini b/pytest.ini deleted file mode 100644 index ac90f5d695..0000000000 --- a/pytest.ini +++ /dev/null @@ -1,15 +0,0 @@ -; NOTE: currently used only for notebook tests with the nbmake plugin. -[pytest] -; Use pytest-xdist to run tests in parallel by default, exit with -; error if not installed -required_plugins = pytest-xdist -addopts = -nauto -v -testpaths = - docs/source/examples -console_output_style = progress - -; Logging configuration -log_cli = true -log_cli_level = INFO -log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" -log_date_format = %Y-%m-%d %H:%M:%S diff --git a/ruff.toml b/ruff.toml deleted file mode 100644 index 7304d64570..0000000000 --- a/ruff.toml +++ /dev/null @@ -1,8 +0,0 @@ -extend-include = ["*.ipynb"] -extend-exclude = ["__init__.py"] - -[lint] -ignore = ["E741"] - -[lint.per-file-ignores] -"**.ipynb" = ["E402", "E703"] From b8b2f4c561de4010eb28b553b6749b075e1030cd Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 20:41:59 +0530 Subject: [PATCH 02/11] Add coverage as a dev dep --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 40455454b1..ae84321206 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -103,7 +103,7 @@ dev = [ # For running testing sessions "nox", # For coverage - coverage[toml], + "coverage[toml]", # For testing Jupyter notebooks "pytest>=6", "pytest-xdist", From 2f7908b8df0236317ef0743c4b14c8a874b1d9fe Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 20:42:25 +0530 Subject: [PATCH 03/11] Fix coverage config --- pyproject.toml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index ae84321206..2ee63d7eb2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -245,5 +245,5 @@ log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" log_date_format = "%Y-%m-%d %H:%M:%S" [tool.coverage.run] -source = pybamm -concurrency = multiprocessing +source = "pybamm" +concurrency = "multiprocessing" From 12c5d77203bd93542785d237bac00bad5ed5469a Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 20:43:14 +0530 Subject: [PATCH 04/11] New ruff and flake8 fixes --- .../work_precision_sets/time_vs_abstols.py | 2 +- .../work_precision_sets/time_vs_dt_max.py | 2 +- .../work_precision_sets/time_vs_mesh_size.py | 2 +- .../time_vs_no_of_states.py | 2 +- .../work_precision_sets/time_vs_reltols.py | 2 +- .../notebooks/models/jelly-roll-model.ipynb | 2 +- .../examples/notebooks/models/latexify.ipynb | 2 +- .../print_model_parameter_combinations.py | 6 +-- noxfile.py | 2 +- pybamm/citations.py | 2 +- pybamm/discretisations/discretisation.py | 4 +- pybamm/expression_tree/array.py | 2 +- pybamm/expression_tree/interpolant.py | 4 +- .../operations/evaluate_python.py | 4 +- pybamm/expression_tree/operations/latexify.py | 6 +-- pybamm/expression_tree/parameter.py | 4 +- pybamm/expression_tree/state_vector.py | 3 +- pybamm/expression_tree/symbol.py | 4 +- pybamm/expression_tree/unary_operators.py | 31 +++------------ pybamm/expression_tree/variable.py | 3 +- pybamm/install_odes.py | 2 +- pybamm/meshes/zero_dimensional_submesh.py | 2 +- pybamm/models/base_model.py | 2 +- .../full_surface_form_conductivity.py | 4 +- pybamm/parameters_cli.py | 2 +- pybamm/plotting/quick_plot.py | 6 +-- pybamm/simulation.py | 2 +- pybamm/solvers/jax_bdf_solver.py | 10 ++--- pybamm/solvers/jax_solver.py | 2 +- pybamm/spatial_methods/finite_volume.py | 4 +- run-tests.py | 4 +- scripts/fix_casadi_rpath_mac.py | 20 +++++----- scripts/install_KLU_Sundials.py | 2 +- scripts/update_version.py | 4 +- setup.py | 19 +++------- tests/unit/test_citations.py | 2 +- .../test_operations/test_evaluate_python.py | 38 +++++++++---------- tests/unit/test_models/test_base_model.py | 4 +- .../test_base_battery_model.py | 2 +- .../test_parameters/test_parameter_values.py | 4 +- 40 files changed, 93 insertions(+), 131 deletions(-) diff --git a/benchmarks/work_precision_sets/time_vs_abstols.py b/benchmarks/work_precision_sets/time_vs_abstols.py index 6447884083..9a96f07514 100644 --- a/benchmarks/work_precision_sets/time_vs_abstols.py +++ b/benchmarks/work_precision_sets/time_vs_abstols.py @@ -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\n" # noqa +content = f"# PyBaMM {pybamm.__version__}\n## Solve Time vs Abstols\n\n" with open("./benchmarks/release_work_precision_sets.md", "r") as original: data = original.read() diff --git a/benchmarks/work_precision_sets/time_vs_dt_max.py b/benchmarks/work_precision_sets/time_vs_dt_max.py index 3926a4bcd6..3e428b702c 100644 --- a/benchmarks/work_precision_sets/time_vs_dt_max.py +++ b/benchmarks/work_precision_sets/time_vs_dt_max.py @@ -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\n" # noqa +content = f"## Solve Time vs dt_max\n\n" with open("./benchmarks/release_work_precision_sets.md", "r") as original: data = original.read() diff --git a/benchmarks/work_precision_sets/time_vs_mesh_size.py b/benchmarks/work_precision_sets/time_vs_mesh_size.py index 7b4d4145d4..f0f13f706b 100644 --- a/benchmarks/work_precision_sets/time_vs_mesh_size.py +++ b/benchmarks/work_precision_sets/time_vs_mesh_size.py @@ -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\n" # noqa +content = f"## Solve Time vs Mesh size\n\n" with open("./benchmarks/release_work_precision_sets.md", "r") as original: data = original.read() diff --git a/benchmarks/work_precision_sets/time_vs_no_of_states.py b/benchmarks/work_precision_sets/time_vs_no_of_states.py index 0a88ac8b52..eb27aba322 100644 --- a/benchmarks/work_precision_sets/time_vs_no_of_states.py +++ b/benchmarks/work_precision_sets/time_vs_no_of_states.py @@ -82,7 +82,7 @@ ) -content = f"## Solve Time vs Number of states\n\n" # noqa +content = f"## Solve Time vs Number of states\n\n" with open("./benchmarks/release_work_precision_sets.md", "r") as original: data = original.read() diff --git a/benchmarks/work_precision_sets/time_vs_reltols.py b/benchmarks/work_precision_sets/time_vs_reltols.py index 12e41b526f..93964910a8 100644 --- a/benchmarks/work_precision_sets/time_vs_reltols.py +++ b/benchmarks/work_precision_sets/time_vs_reltols.py @@ -102,7 +102,7 @@ plt.savefig(f"benchmarks/benchmark_images/time_vs_reltols_{pybamm.__version__}.png") -content = f"## Solve Time vs Reltols\n\n" # noqa +content = f"## Solve Time vs Reltols\n\n" with open("./benchmarks/release_work_precision_sets.md", "r") as original: data = original.read() diff --git a/docs/source/examples/notebooks/models/jelly-roll-model.ipynb b/docs/source/examples/notebooks/models/jelly-roll-model.ipynb index fe6173f1ce..557366099a 100644 --- a/docs/source/examples/notebooks/models/jelly-roll-model.ipynb +++ b/docs/source/examples/notebooks/models/jelly-roll-model.ipynb @@ -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\")" diff --git a/docs/source/examples/notebooks/models/latexify.ipynb b/docs/source/examples/notebooks/models/latexify.ipynb index 63e7c0d519..c2a45ff2c8 100644 --- a/docs/source/examples/notebooks/models/latexify.ipynb +++ b/docs/source/examples/notebooks/models/latexify.ipynb @@ -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)" ] }, { diff --git a/examples/scripts/print_model_parameter_combinations.py b/examples/scripts/print_model_parameter_combinations.py index 8d24f919c3..f7f00714fb 100644 --- a/examples/scripts/print_model_parameter_combinations.py +++ b/examples/scripts/print_model_parameter_combinations.py @@ -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: diff --git a/noxfile.py b/noxfile.py index 7a57ad5820..1ab383bddc 100644 --- a/noxfile.py +++ b/noxfile.py @@ -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) diff --git a/pybamm/citations.py b/pybamm/citations.py index b72262989b..e73351a4c6 100644 --- a/pybamm/citations.py +++ b/pybamm/citations.py @@ -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) diff --git a/pybamm/discretisations/discretisation.py b/pybamm/discretisations/discretisation.py index a120adecc0..bb6e678f4c 100644 --- a/pybamm/discretisations/discretisation.py +++ b/pybamm/discretisations/discretisation.py @@ -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( @@ -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] diff --git a/pybamm/expression_tree/array.py b/pybamm/expression_tree/array.py index 2736886d95..adbdc88dc2 100644 --- a/pybamm/expression_tree/array.py +++ b/pybamm/expression_tree/array.py @@ -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): diff --git a/pybamm/expression_tree/interpolant.py b/pybamm/expression_tree/interpolant.py index cd0df4d077..28188ce68f 100644 --- a/pybamm/expression_tree/interpolant.py +++ b/pybamm/expression_tree/interpolant.py @@ -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): diff --git a/pybamm/expression_tree/operations/evaluate_python.py b/pybamm/expression_tree/operations/evaluate_python.py index 1f44a69784..d0cd4c776d 100644 --- a/pybamm/expression_tree/operations/evaluate_python.py +++ b/pybamm/expression_tree/operations/evaluate_python.py @@ -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) @@ -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) diff --git a/pybamm/expression_tree/operations/latexify.py b/pybamm/expression_tree/operations/latexify.py index 9f2949069e..572f01a560 100644 --- a/pybamm/expression_tree/operations/latexify.py +++ b/pybamm/expression_tree/operations/latexify.py @@ -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] diff --git a/pybamm/expression_tree/parameter.py b/pybamm/expression_tree/parameter.py index eebe77ad2f..00a28017b8 100644 --- a/pybamm/expression_tree/parameter.py +++ b/pybamm/expression_tree/parameter.py @@ -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): diff --git a/pybamm/expression_tree/state_vector.py b/pybamm/expression_tree/state_vector.py index 6ef8bee904..437ba752ed 100644 --- a/pybamm/expression_tree/state_vector.py +++ b/pybamm/expression_tree/state_vector.py @@ -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): diff --git a/pybamm/expression_tree/symbol.py b/pybamm/expression_tree/symbol.py index 8f1608e7ba..5fe765af33 100644 --- a/pybamm/expression_tree/symbol.py +++ b/pybamm/expression_tree/symbol.py @@ -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 diff --git a/pybamm/expression_tree/unary_operators.py b/pybamm/expression_tree/unary_operators.py index 81c3dc28c2..95306ebad5 100644 --- a/pybamm/expression_tree/unary_operators.py +++ b/pybamm/expression_tree/unary_operators.py @@ -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): @@ -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): @@ -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): @@ -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): @@ -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): @@ -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): diff --git a/pybamm/expression_tree/variable.py b/pybamm/expression_tree/variable.py index 0d1e1fd424..22b176b6fc 100644 --- a/pybamm/expression_tree/variable.py +++ b/pybamm/expression_tree/variable.py @@ -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): diff --git a/pybamm/install_odes.py b/pybamm/install_odes.py index 4bf310a0f2..0fbbcdc637 100644 --- a/pybamm/install_odes.py +++ b/pybamm/install_odes.py @@ -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, ) diff --git a/pybamm/meshes/zero_dimensional_submesh.py b/pybamm/meshes/zero_dimensional_submesh.py index 5b2f38e29f..82e8cb6524 100644 --- a/pybamm/meshes/zero_dimensional_submesh.py +++ b/pybamm/meshes/zero_dimensional_submesh.py @@ -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]) diff --git a/pybamm/models/base_model.py b/pybamm/models/base_model.py index 08890757b7..a88f6f4255 100644 --- a/pybamm/models/base_model.py +++ b/pybamm/models/base_model.py @@ -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( diff --git a/pybamm/models/submodels/electrolyte_conductivity/surface_potential_form/full_surface_form_conductivity.py b/pybamm/models/submodels/electrolyte_conductivity/surface_potential_form/full_surface_form_conductivity.py index 7afeeac47e..83bcfb8027 100644 --- a/pybamm/models/submodels/electrolyte_conductivity/surface_potential_form/full_surface_form_conductivity.py +++ b/pybamm/models/submodels/electrolyte_conductivity/surface_potential_form/full_surface_form_conductivity.py @@ -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) @@ -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) diff --git a/pybamm/parameters_cli.py b/pybamm/parameters_cli.py index 90950b23ee..e3d4a273b8 100644 --- a/pybamm/parameters_cli.py +++ b/pybamm/parameters_cli.py @@ -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)" ) diff --git a/pybamm/plotting/quick_plot.py b/pybamm/plotting/quick_plot.py index ff657ee375..0e56c17c75 100644 --- a/pybamm/plotting/quick_plot.py +++ b/pybamm/plotting/quick_plot.py @@ -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), ) @@ -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] diff --git a/pybamm/simulation.py b/pybamm/simulation.py index f9aebb1c54..bdd97f6894 100644 --- a/pybamm/simulation.py +++ b/pybamm/simulation.py @@ -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 ) ) diff --git a/pybamm/solvers/jax_bdf_solver.py b/pybamm/solvers/jax_bdf_solver.py index 2f334ed8ec..8f5b8ed817 100644 --- a/pybamm/solvers/jax_bdf_solver.py +++ b/pybamm/solvers/jax_bdf_solver.py @@ -676,7 +676,7 @@ def while_body(while_state): # ) (state, step_accepted) = tree_map( - partial(jnp.where, converged * (error_norm > 1)), # noqa: E712 + partial(jnp.where, converged * (error_norm > 1)), (_update_step_size_and_lu(state, factor), False), (state, converged), ) @@ -883,9 +883,7 @@ def arg_dicts_to_values(args): """ return sum((tuple(b.values()) for b in args if isinstance(b, dict)), ()) - aug_mass = (mass, mass, onp.array(1.0)) + arg_dicts_to_values( - tree_map(arg_to_identity, args) - ) + aug_mass = (mass, mass, onp.array(1.0), *arg_dicts_to_values(tree_map(arg_to_identity, args))) def scan_fun(carry, i): y_bar, t0_bar, args_bar = carry @@ -961,7 +959,7 @@ def ravel_first_arg(f, unravel): @lu.transformation def ravel_first_arg_(unravel, y_flat, *args): y = unravel(y_flat) - ans = yield (y,) + args, {} + ans = yield (y, *args), {} ans_flat, _ = ravel_pytree(ans) yield ans_flat @@ -1007,7 +1005,7 @@ def jax_bdf_integrate(func, y0, t_eval, *args, rtol=1e-6, atol=1e-6, mass=None): """ if not pybamm.have_jax(): 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" ) def _check_arg(arg): diff --git a/pybamm/solvers/jax_solver.py b/pybamm/solvers/jax_solver.py index 4c9759008a..313fddc208 100644 --- a/pybamm/solvers/jax_solver.py +++ b/pybamm/solvers/jax_solver.py @@ -61,7 +61,7 @@ def __init__( ): if not pybamm.have_jax(): 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" ) # note: bdf solver itself calculates consistent initial conditions so can set diff --git a/pybamm/spatial_methods/finite_volume.py b/pybamm/spatial_methods/finite_volume.py index ecbae69796..5c32e5a2c0 100644 --- a/pybamm/spatial_methods/finite_volume.py +++ b/pybamm/spatial_methods/finite_volume.py @@ -620,10 +620,10 @@ def add_ghost_nodes(self, symbol, discretised_symbol, bcs): # Dirichlet boundary conditions n_bcs = 0 if lbc_type == "Dirichlet": - domain = [domain[0] + "_left ghost cell"] + domain + domain = [domain[0] + "_left ghost cell", *domain] n_bcs += 1 if rbc_type == "Dirichlet": - domain = domain + [domain[-1] + "_right ghost cell"] + domain = [*domain, domain[-1] + "_right ghost cell"] n_bcs += 1 # Calculate values for ghost nodes for any Dirichlet boundary conditions diff --git a/run-tests.py b/run-tests.py index b9d421daa2..25b1731b18 100755 --- a/run-tests.py +++ b/run-tests.py @@ -156,7 +156,7 @@ def test_script(path, executable="python"): env["MPLBACKEND"] = "Template" # Run in subprocess - cmd = [executable] + [path] + cmd = [executable, path] try: p = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env @@ -214,7 +214,7 @@ def test_script(path, executable="python"): parser.add_argument( "--examples", action="store_true", - help="Test all Jupyter notebooks in `docs/source/examples/` (deprecated, use nox or pytest instead).", # noqa: E501 + help="Test all Jupyter notebooks in `docs/source/examples/` (deprecated, use nox or pytest instead).", ) parser.add_argument( "--debook", diff --git a/scripts/fix_casadi_rpath_mac.py b/scripts/fix_casadi_rpath_mac.py index 23c8a32d59..3f7f71e834 100644 --- a/scripts/fix_casadi_rpath_mac.py +++ b/scripts/fix_casadi_rpath_mac.py @@ -30,15 +30,15 @@ os.path.join(casadi_dir, libcasadi_37_name), ] -subprocess.run(["otool"] + ["-L", os.path.join(casadi_dir, libcasadi_name)]) +subprocess.run(["otool", "-L", os.path.join(casadi_dir, libcasadi_name)]) -print(" ".join(["install_name_tool"] + install_name_tool_args_for_libcasadi_name)) -subprocess.run(["install_name_tool"] + install_name_tool_args_for_libcasadi_name) +print(" ".join(["install_name_tool", *install_name_tool_args_for_libcasadi_name])) +subprocess.run(["install_name_tool", *install_name_tool_args_for_libcasadi_name]) -print(" ".join(["install_name_tool"] + install_name_tool_args_for_libcasadi_37_name)) -subprocess.run(["install_name_tool"] + install_name_tool_args_for_libcasadi_37_name) +print(" ".join(["install_name_tool", *install_name_tool_args_for_libcasadi_37_name])) +subprocess.run(["install_name_tool", *install_name_tool_args_for_libcasadi_37_name]) -subprocess.run(["otool"] + ["-L", os.path.join(casadi_dir, libcasadi_name)]) +subprocess.run(["otool", "-L", os.path.join(casadi_dir, libcasadi_name)]) install_name_tool_args = [ "-change", @@ -46,12 +46,12 @@ os.path.join(casadi_dir, libcppabi_name), os.path.join(casadi_dir, libcpp_name), ] -subprocess.run(["otool"] + ["-L", os.path.join(casadi_dir, libcpp_name)]) +subprocess.run(["otool", "-L", os.path.join(casadi_dir, libcpp_name)]) -print(" ".join(["install_name_tool"] + install_name_tool_args)) -subprocess.run(["install_name_tool"] + install_name_tool_args) +print(" ".join(["install_name_tool", *install_name_tool_args])) +subprocess.run(["install_name_tool", *install_name_tool_args]) -subprocess.run(["otool"] + ["-L", os.path.join(casadi_dir, libcpp_name)]) +subprocess.run(["otool", "-L", os.path.join(casadi_dir, libcpp_name)]) # Copy libcasadi.3.7.dylib and libc++.1.0.dylib to LD_LIBRARY_PATH # This is needed for the casadi python bindings to work while repairing the wheel diff --git a/scripts/install_KLU_Sundials.py b/scripts/install_KLU_Sundials.py index 96e60aeb0e..8f41f5969a 100755 --- a/scripts/install_KLU_Sundials.py +++ b/scripts/install_KLU_Sundials.py @@ -156,7 +156,7 @@ def download_extract_library(url, download_dir): sundials_src = "../sundials-{}".format(sundials_version) print("-" * 10, "Running CMake prepare", "-" * 40) -subprocess.run(["cmake", sundials_src] + cmake_args, cwd=build_dir, check=True) +subprocess.run(["cmake", sundials_src, *cmake_args], cwd=build_dir, check=True) print("-" * 10, "Building the sundials", "-" * 40) make_cmd = ["make", "install"] diff --git a/scripts/update_version.py b/scripts/update_version.py index 8a2d832e59..ccdec661e2 100644 --- a/scripts/update_version.py +++ b/scripts/update_version.py @@ -78,7 +78,7 @@ def update_version(): file.write(replace_version) # Get latest commit id from pybamm-team/sundials-vcpkg-registry - cmd = "git ls-remote https://github.com/pybamm-team/sundials-vcpkg-registry | grep refs/heads/main | cut -f 1 | tr -d '\n'" # noqa: E501 + cmd = "git ls-remote https://github.com/pybamm-team/sundials-vcpkg-registry | grep refs/heads/main | cut -f 1 | tr -d '\n'" latest_commit_id = os.popen(cmd).read() # vcpkg-configuration.json @@ -93,7 +93,7 @@ def update_version(): file.write(replace_commit_id) changelog_line1 = "# [Unreleased](https://github.com/pybamm-team/PyBaMM/)\n" - changelog_line2 = f"# [v{release_version}](https://github.com/pybamm-team/PyBaMM/tree/v{release_version}) - {last_day_of_month}\n\n" # noqa: E501 + changelog_line2 = f"# [v{release_version}](https://github.com/pybamm-team/PyBaMM/tree/v{release_version}) - {last_day_of_month}\n\n" # CHANGELOG.md with open(os.path.join(pybamm.root_dir(), "CHANGELOG.md"), "r+") as file: diff --git a/setup.py b/setup.py index 9cfc4df4ff..ef82e65e70 100644 --- a/setup.py +++ b/setup.py @@ -42,10 +42,7 @@ def set_vcpkg_environment_variables(): # ---------- CMakeBuild class (custom build_ext for IDAKLU target) --------------------- class CMakeBuild(build_ext): - user_options = build_ext.user_options + [ - ("suitesparse-root=", None, "suitesparse source location"), - ("sundials-root=", None, "sundials source location"), - ] + user_options = [*build_ext.user_options, ("suitesparse-root=", None, "suitesparse source location"), ("sundials-root=", None, "sundials source location")] def initialize_options(self): build_ext.initialize_options(self) @@ -136,7 +133,7 @@ def run(self): cmake_list_dir = os.path.abspath(os.path.dirname(__file__)) print("-" * 10, "Running CMake for IDAKLU solver", "-" * 40) subprocess.run( - ["cmake", cmake_list_dir] + cmake_args, cwd=build_dir, env=build_env + ["cmake", cmake_list_dir, *cmake_args], cwd=build_dir, env=build_env , check=True) if os.path.isfile(os.path.join(build_dir, "CMakeError.log")): @@ -144,7 +141,7 @@ def run(self): "cmake configuration steps encountered errors, and the IDAKLU module" " could not be built. Make sure dependencies are correctly " "installed. See " - "https://docs.pybamm.org/en/latest/source/user_guide/installation/install-from-source.html" # noqa: E501 + "https://docs.pybamm.org/en/latest/source/user_guide/installation/install-from-source.html" ) raise RuntimeError(msg) else: @@ -201,10 +198,7 @@ def move_output(self, ext): class CustomInstall(install): """A custom install command to add 2 build options""" - user_options = install.user_options + [ - ("suitesparse-root=", None, "suitesparse source location"), - ("sundials-root=", None, "sundials source location"), - ] + user_options = [*install.user_options, ("suitesparse-root=", None, "suitesparse source location"), ("sundials-root=", None, "sundials source location")] def initialize_options(self): install.initialize_options(self) @@ -228,10 +222,7 @@ def run(self): class bdist_wheel(orig.bdist_wheel): """A custom install command to add 2 build options""" - user_options = orig.bdist_wheel.user_options + [ - ("suitesparse-root=", None, "suitesparse source location"), - ("sundials-root=", None, "sundials source location"), - ] + user_options = [*orig.bdist_wheel.user_options, ("suitesparse-root=", None, "suitesparse source location"), ("sundials-root=", None, "sundials source location")] def initialize_options(self): orig.bdist_wheel.initialize_options(self) diff --git a/tests/unit/test_citations.py b/tests/unit/test_citations.py index 5fde193af3..b3e2c88422 100644 --- a/tests/unit/test_citations.py +++ b/tests/unit/test_citations.py @@ -101,7 +101,7 @@ def test_overwrite_citation(self): pybamm.citations.register(r"@article{NotACitation, title = {A New Title}}") pybamm.citations._parse_citation( r"@article{NotACitation, title = {A New Title}}" - ) # noqa: E501 + ) self.assertIn("NotACitation", pybamm.citations._papers_to_cite) self.assertNotEqual( pybamm.citations._all_citations["NotACitation"], old_citation diff --git a/tests/unit/test_expression_tree/test_operations/test_evaluate_python.py b/tests/unit/test_expression_tree/test_operations/test_evaluate_python.py index 50c9dbb744..ca36804ba0 100644 --- a/tests/unit/test_expression_tree/test_operations/test_evaluate_python.py +++ b/tests/unit/test_expression_tree/test_operations/test_evaluate_python.py @@ -35,12 +35,12 @@ def test_find_symbols(self): self.assertEqual(len(constant_symbols), 0) # test keys of known_symbols - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.id) # test values of variable_symbols - self.assertEqual(list(variable_symbols.values())[0], "y[0:1]") + self.assertEqual(next(iter(variable_symbols.values())), "y[0:1]") self.assertEqual(list(variable_symbols.values())[1], "y[1:2]") var_a = pybamm.id_to_python_variable(a.id) @@ -57,13 +57,13 @@ def test_find_symbols(self): self.assertEqual(len(constant_symbols), 0) # test keys of variable_symbols - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.children[0].id) self.assertEqual(list(variable_symbols.keys())[3], expr.id) # test values of variable_symbols - self.assertEqual(list(variable_symbols.values())[0], "y[0:1]") + self.assertEqual(next(iter(variable_symbols.values())), "y[0:1]") self.assertEqual(list(variable_symbols.values())[1], "y[1:2]") self.assertEqual( list(variable_symbols.values())[2], "{} + {}".format(var_a, var_b) @@ -82,13 +82,13 @@ def test_find_symbols(self): self.assertEqual(len(constant_symbols), 0) # test keys of variable_symbols - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.children[1].id) self.assertEqual(list(variable_symbols.keys())[3], expr.id) # test values of variable_symbols - self.assertEqual(list(variable_symbols.values())[0], "y[0:1]") + self.assertEqual(next(iter(variable_symbols.values())), "y[0:1]") self.assertEqual(list(variable_symbols.values())[1], "y[1:2]") self.assertEqual(list(variable_symbols.values())[2], "-{}".format(var_b)) var_child = pybamm.id_to_python_variable(expr.children[1].id) @@ -101,11 +101,11 @@ def test_find_symbols(self): variable_symbols = OrderedDict() expr = pybamm.Function(test_function, a) pybamm.find_symbols(expr, constant_symbols, variable_symbols) - self.assertEqual(list(constant_symbols.keys())[0], expr.id) - self.assertEqual(list(constant_symbols.values())[0], test_function) - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(constant_symbols.keys())), expr.id) + self.assertEqual(next(iter(constant_symbols.values())), test_function) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], expr.id) - self.assertEqual(list(variable_symbols.values())[0], "y[0:1]") + self.assertEqual(next(iter(variable_symbols.values())), "y[0:1]") var_funct = pybamm.id_to_python_variable(expr.id, True) self.assertEqual( list(variable_symbols.values())[1], "{}({})".format(var_funct, var_a) @@ -117,9 +117,9 @@ def test_find_symbols(self): A = pybamm.Matrix([[1, 2], [3, 4]]) pybamm.find_symbols(A, constant_symbols, variable_symbols) self.assertEqual(len(variable_symbols), 0) - self.assertEqual(list(constant_symbols.keys())[0], A.id) + self.assertEqual(next(iter(constant_symbols.keys())), A.id) np.testing.assert_allclose( - list(constant_symbols.values())[0], np.array([[1, 2], [3, 4]]) + next(iter(constant_symbols.values())), np.array([[1, 2], [3, 4]]) ) # test sparse matrix @@ -128,9 +128,9 @@ def test_find_symbols(self): A = pybamm.Matrix(scipy.sparse.csr_matrix(np.array([[0, 2], [0, 4]]))) pybamm.find_symbols(A, constant_symbols, variable_symbols) self.assertEqual(len(variable_symbols), 0) - self.assertEqual(list(constant_symbols.keys())[0], A.id) + self.assertEqual(next(iter(constant_symbols.keys())), A.id) np.testing.assert_allclose( - list(constant_symbols.values())[0].toarray(), A.entries.toarray() + next(iter(constant_symbols.values())).toarray(), A.entries.toarray() ) # test numpy concatentate @@ -139,7 +139,7 @@ def test_find_symbols(self): expr = pybamm.NumpyConcatenation(a, b) pybamm.find_symbols(expr, constant_symbols, variable_symbols) self.assertEqual(len(constant_symbols), 0) - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.id) self.assertEqual( @@ -153,7 +153,7 @@ def test_find_symbols(self): expr = pybamm.NumpyConcatenation(a, b) pybamm.find_symbols(expr, constant_symbols, variable_symbols) self.assertEqual(len(constant_symbols), 0) - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.id) self.assertEqual( @@ -194,7 +194,7 @@ def test_domain_concatenation(self): constant_symbols = OrderedDict() variable_symbols = OrderedDict() pybamm.find_symbols(expr, constant_symbols, variable_symbols) - self.assertEqual(list(variable_symbols.keys())[0], a.id) + self.assertEqual(next(iter(variable_symbols.keys())), a.id) self.assertEqual(list(variable_symbols.keys())[1], b.id) self.assertEqual(list(variable_symbols.keys())[2], expr.id) @@ -468,9 +468,9 @@ def test_find_symbols_jax(self): A = pybamm.Matrix(scipy.sparse.csr_matrix(np.array([[0, 2], [0, 4]]))) pybamm.find_symbols(A, constant_symbols, variable_symbols, output_jax=True) self.assertEqual(len(variable_symbols), 0) - self.assertEqual(list(constant_symbols.keys())[0], A.id) + self.assertEqual(next(iter(constant_symbols.keys())), A.id) np.testing.assert_allclose( - list(constant_symbols.values())[0].toarray(), A.entries.toarray() + next(iter(constant_symbols.values())).toarray(), A.entries.toarray() ) @unittest.skipIf(not pybamm.have_jax(), "jax or jaxlib is not installed") diff --git a/tests/unit/test_models/test_base_model.py b/tests/unit/test_models/test_base_model.py index 4167d5fff5..1e90e28f81 100644 --- a/tests/unit/test_models/test_base_model.py +++ b/tests/unit/test_models/test_base_model.py @@ -694,7 +694,7 @@ def test_set_initial_conditions(self): new_model_disc = model_disc.set_initial_conditions_from(sol, inplace=False) # Test new initial conditions - var_scalar = list(new_model_disc.initial_conditions.keys())[0] + var_scalar = next(iter(new_model_disc.initial_conditions.keys())) self.assertIsInstance( new_model_disc.initial_conditions[var_scalar], pybamm.Vector ) @@ -826,7 +826,7 @@ def test_set_initial_conditions(self): new_model_disc = model_disc.set_initial_conditions_from(sol_dict, inplace=False) # Test new initial conditions - var_scalar = list(new_model_disc.initial_conditions.keys())[0] + var_scalar = next(iter(new_model_disc.initial_conditions.keys())) self.assertIsInstance( new_model_disc.initial_conditions[var_scalar], pybamm.Vector ) diff --git a/tests/unit/test_models/test_full_battery_models/test_base_battery_model.py b/tests/unit/test_models/test_full_battery_models/test_base_battery_model.py index 79c6d8a720..e2c408bb9a 100644 --- a/tests/unit/test_models/test_full_battery_models/test_base_battery_model.py +++ b/tests/unit/test_models/test_full_battery_models/test_base_battery_model.py @@ -49,7 +49,7 @@ 'total interfacial current density as a state': 'false' (possible: ['false', 'true']) 'working electrode': 'both' (possible: ['both', 'positive']) 'x-average side reactions': 'false' (possible: ['false', 'true']) -""" # noqa: E501 +""" class TestBaseBatteryModel(TestCase): diff --git a/tests/unit/test_parameters/test_parameter_values.py b/tests/unit/test_parameters/test_parameter_values.py index fa6e2398ee..37ec89068f 100644 --- a/tests/unit/test_parameters/test_parameter_values.py +++ b/tests/unit/test_parameters/test_parameter_values.py @@ -968,9 +968,9 @@ def test_process_model(self): self.assertIsInstance(model.initial_conditions[var1], pybamm.Scalar) self.assertEqual(model.initial_conditions[var1].value, 2) # boundary conditions - bc_key = list(model.boundary_conditions.keys())[0] + bc_key = next(iter(model.boundary_conditions.keys())) self.assertIsInstance(bc_key, pybamm.Variable) - bc_value = list(model.boundary_conditions.values())[0] + bc_value = next(iter(model.boundary_conditions.values())) self.assertIsInstance(bc_value["left"][0], pybamm.Scalar) self.assertEqual(bc_value["left"][0].value, 3) self.assertIsInstance(bc_value["right"][0], pybamm.Scalar) From 7208df551d9e50727ae042260ab7aad6aee48075 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 20:44:26 +0530 Subject: [PATCH 05/11] Preserve git blame --- .git-blame-ignore-revs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.git-blame-ignore-revs b/.git-blame-ignore-revs index 228a76373e..9e59bd7f07 100644 --- a/.git-blame-ignore-revs +++ b/.git-blame-ignore-revs @@ -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 From 909f6ce5d89bb6f194b611aa5b7551919ebdef0b Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sat, 25 Nov 2023 21:55:01 +0530 Subject: [PATCH 06/11] Fix coverage and notebook sessions --- noxfile.py | 2 +- pyproject.toml | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/noxfile.py b/noxfile.py index 1ab383bddc..5db08ee92f 100644 --- a/noxfile.py +++ b/noxfile.py @@ -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") diff --git a/pyproject.toml b/pyproject.toml index 2ee63d7eb2..74d60de081 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -174,6 +174,8 @@ pybamm = [ [tool.setuptools.packages.find] include = ["pybamm", "pybamm.*"] +# TODO: remove once https://github.com/pybamm-team/PyBaMM/issues/3480 is resolved +exclude = ["pybind11*"] [tool.ruff] extend-include = ["*.ipynb"] From 93aee4f74897dc04c1b6ea4d427fb5b6389e668e Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sun, 26 Nov 2023 00:21:42 +0530 Subject: [PATCH 07/11] concurrency should be a list Co-authored-by: Eric G. Kratz --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 74d60de081..293ac3728c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -248,4 +248,4 @@ log_date_format = "%Y-%m-%d %H:%M:%S" [tool.coverage.run] source = "pybamm" -concurrency = "multiprocessing" +concurrency = ["multiprocessing"] From a02f685f45ec161b8c408bd2d83193b53d930422 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sun, 26 Nov 2023 00:33:46 +0530 Subject: [PATCH 08/11] Ignore pybind11 --- pyproject.toml | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 74d60de081..c5e674d14f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -174,8 +174,6 @@ pybamm = [ [tool.setuptools.packages.find] include = ["pybamm", "pybamm.*"] -# TODO: remove once https://github.com/pybamm-team/PyBaMM/issues/3480 is resolved -exclude = ["pybind11*"] [tool.ruff] extend-include = ["*.ipynb"] @@ -234,6 +232,7 @@ required_plugins = [ addopts = [ "-nauto", "-v", + "--ignore=pybind11", ] testpaths = [ "docs/source/examples/", From 51fe23c31b9b12030bb5143b89710aaab326e899 Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sun, 26 Nov 2023 01:00:27 +0530 Subject: [PATCH 09/11] Use tool.pytest.ini_options --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index d2fc3f3435..b94a4fa30e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -223,7 +223,7 @@ ignore = [ "**.ipynb" = ["E402", "E703"] # NOTE: currently used only for notebook tests with the nbmake plugin. -[tool.pytest] +[tool.pytest.ini_options] # Use pytest-xdist to run tests in parallel by default, exit with # error if not installed required_plugins = [ From 352555d1e9affea2a2f576a242264f4c9c77304f Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sun, 26 Nov 2023 01:13:44 +0530 Subject: [PATCH 10/11] Remove --ignore --- pyproject.toml | 1 - 1 file changed, 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index b94a4fa30e..25be1e518e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -232,7 +232,6 @@ required_plugins = [ addopts = [ "-nauto", "-v", - "--ignore=pybind11", ] testpaths = [ "docs/source/examples/", From 5322895e74c7d549706339bdc0af269c7997f95a Mon Sep 17 00:00:00 2001 From: Saransh Chopra Date: Sun, 26 Nov 2023 01:27:23 +0530 Subject: [PATCH 11/11] tool.coverage.run.source should be a list --- pyproject.toml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pyproject.toml b/pyproject.toml index 25be1e518e..eae0575117 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -245,5 +245,5 @@ log_format = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" log_date_format = "%Y-%m-%d %H:%M:%S" [tool.coverage.run] -source = "pybamm" +source = ["pybamm"] concurrency = ["multiprocessing"]