From 74befc8630a88aaa716daee60d84d90aabfee164 Mon Sep 17 00:00:00 2001 From: Shyue Ping Ong Date: Thu, 15 Aug 2024 10:21:10 -0700 Subject: [PATCH] Ruff fixes. --- .devcontainer/devcontainer.json | 21 ----- .devcontainer/repro_template.ipynb | 84 ------------------- src/pymatgen/analysis/local_env.py | 3 +- src/pymatgen/analysis/molecule_matcher.py | 3 +- src/pymatgen/analysis/surface_analysis.py | 3 +- src/pymatgen/cli/pmg_analyze.py | 3 +- src/pymatgen/core/molecular_orbitals.py | 3 +- .../electronic_structure/boltztrap.py | 3 +- src/pymatgen/electronic_structure/cohp.py | 6 +- src/pymatgen/io/abinit/pseudos.py | 4 +- src/pymatgen/io/cp2k/sets.py | 6 +- src/pymatgen/io/lobster/inputs.py | 3 +- src/pymatgen/io/nwchem.py | 3 +- src/pymatgen/io/vasp/inputs.py | 4 +- tests/io/exciting/test_inputs.py | 8 +- tests/io/vasp/test_outputs.py | 4 +- 16 files changed, 24 insertions(+), 137 deletions(-) delete mode 100644 .devcontainer/devcontainer.json delete mode 100644 .devcontainer/repro_template.ipynb diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json deleted file mode 100644 index 58b5c7371ae..00000000000 --- a/.devcontainer/devcontainer.json +++ /dev/null @@ -1,21 +0,0 @@ -{ - "image": "mcr.microsoft.com/devcontainers/universal:2", - "hostRequirements": { - "cpus": 1 // configurable up to 16 cores - }, - "waitFor": "onCreateCommand", - "updateContentCommand": "pip install -r requirements.txt", - "postCreateCommand": "pip install pymatgen", - "customizations": { - "codespaces": { - "openFiles": [".devcontainer/repro_template.ipynb"] - }, - "vscode": { - "extensions": ["ms-toolsai.jupyter", "ms-python.python"], - "settings": { - "jupyter.notebookFileRoot": "${workspaceFolder}", - "jupyter.defaultKernel": "python3" - } - } - } -} diff --git a/.devcontainer/repro_template.ipynb b/.devcontainer/repro_template.ipynb deleted file mode 100644 index 7220451def5..00000000000 --- a/.devcontainer/repro_template.ipynb +++ /dev/null @@ -1,84 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "# `pymatgen` issue repro template\n", - "\n", - "[Codespaces](https://docs.github.com/codespaces/overview) enable you to effortlessly reproduce and debug Pymatgen issues.\n", - "\n", - "- Skip the hassle of environment setup\n", - "- Streamline information collection for faster issue reports\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Collect Python version, pymatgen version and current date\n", - "from __future__ import annotations\n", - "\n", - "import platform\n", - "import sys\n", - "from datetime import datetime\n", - "from importlib.metadata import version\n", - "\n", - "print(f\"date: {datetime.today():%Y-%m-%d}\")\n", - "print(f\"Python version: {sys.version.split()[0]}\")\n", - "print(f\"pymatgen version: {version('pymatgen')}\")\n", - "print(f\"OS: {platform.system()} {platform.release()}\")" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "## Code to reproduce issue goes below\n" - ] - }, - { - "cell_type": "code", - "execution_count": null, - "metadata": {}, - "outputs": [], - "source": [ - "# Your code to reproduce issue goes here, for example:\n", - "from pymatgen.core.structure import Molecule\n", - "\n", - "c_monox = Molecule([\"C\", \"O\"], [[0.0, 0.0, 0.0], [0.0, 0.0, 1.2]])\n", - "print(c_monox)" - ] - }, - { - "cell_type": "markdown", - "metadata": {}, - "source": [ - "### Now share the code and outputs in a [new GitHub issue](https://github.com/materialsproject/pymatgen/issues/new?&labels=bug&template=bug_report.yaml)\n" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.11.6" - } - }, - "nbformat": 4, - "nbformat_minor": 2 -} diff --git a/src/pymatgen/analysis/local_env.py b/src/pymatgen/analysis/local_env.py index 31f628c8381..e47af954ad8 100644 --- a/src/pymatgen/analysis/local_env.py +++ b/src/pymatgen/analysis/local_env.py @@ -4184,8 +4184,7 @@ def __init__(self, cut_off_dict: dict | None = None) -> None: for (sp1, sp2), dist in self.cut_off_dict.items(): lookup_dict[sp1][sp2] = dist lookup_dict[sp2][sp1] = dist - if dist > self._max_dist: - self._max_dist = dist + self._max_dist = max(dist, self._max_dist) self._lookup_dict = lookup_dict @property diff --git a/src/pymatgen/analysis/molecule_matcher.py b/src/pymatgen/analysis/molecule_matcher.py index 0474bfd88a4..d6ca253bbd4 100644 --- a/src/pymatgen/analysis/molecule_matcher.py +++ b/src/pymatgen/analysis/molecule_matcher.py @@ -321,8 +321,7 @@ def _virtual_molecule(self, mol, ilabels, eq_atoms): for idx in range(1, vmol.NumAtoms() + 1): va = vmol.GetAtom(idx) distance = math.sqrt((c1x - va.x()) ** 2 + (c1y - va.y()) ** 2 + (c1z - va.z()) ** 2) - if distance < min_distance: - min_distance = distance + min_distance = min(distance, min_distance) if min_distance > 0.2: a1 = vmol.NewAtom() a1.SetAtomicNum(9) diff --git a/src/pymatgen/analysis/surface_analysis.py b/src/pymatgen/analysis/surface_analysis.py index f5aacb13c42..8abe6d0b43d 100644 --- a/src/pymatgen/analysis/surface_analysis.py +++ b/src/pymatgen/analysis/surface_analysis.py @@ -1029,8 +1029,7 @@ def monolayer_vs_BE(self, plot_eads=False): if ads_entry.get_monolayer not in ml_be_dict: ml_be_dict[ads_entry.get_monolayer] = 1000 be = ads_entry.gibbs_binding_energy(eads=plot_eads) - if be < ml_be_dict[ads_entry.get_monolayer]: - ml_be_dict[ads_entry.get_monolayer] = be + ml_be_dict[ads_entry.get_monolayer] = min(be, ml_be_dict[ads_entry.get_monolayer]) # sort the binding energies and monolayers # in order to properly draw a line plot vals = sorted(ml_be_dict.items()) diff --git a/src/pymatgen/cli/pmg_analyze.py b/src/pymatgen/cli/pmg_analyze.py index c12ef4186ef..3d17eb00dcb 100644 --- a/src/pymatgen/cli/pmg_analyze.py +++ b/src/pymatgen/cli/pmg_analyze.py @@ -119,8 +119,7 @@ def get_magnetizations(dirc: str, ion_list: list[int]): for ion in all_ions: row.append(str(_mags[ion])) data.append(row) - if len(all_ions) > max_row: - max_row = len(all_ions) + max_row = max(len(all_ions), max_row) except Exception: pass diff --git a/src/pymatgen/core/molecular_orbitals.py b/src/pymatgen/core/molecular_orbitals.py index 86649af3e2c..80aae62bab3 100644 --- a/src/pymatgen/core/molecular_orbitals.py +++ b/src/pymatgen/core/molecular_orbitals.py @@ -63,8 +63,7 @@ def max_electronegativity(self) -> float: """ maximum: float = 0.0 for e1, e2 in combinations(self.elements, 2): - if abs(Element(e1).X - Element(e2).X) > maximum: - maximum = abs(Element(e1).X - Element(e2).X) + maximum = max(abs(Element(e1).X - Element(e2).X), maximum) return maximum def aos_as_list(self) -> list[tuple[str, str, float]]: diff --git a/src/pymatgen/electronic_structure/boltztrap.py b/src/pymatgen/electronic_structure/boltztrap.py index 4025822e2df..ee1f2ee056c 100644 --- a/src/pymatgen/electronic_structure/boltztrap.py +++ b/src/pymatgen/electronic_structure/boltztrap.py @@ -552,8 +552,7 @@ def run( run_type = self.run_type if run_type in ("BANDS", "DOS", "FERMI"): convergence = False - if self.lpfac > max_lpfac: - max_lpfac = self.lpfac + max_lpfac = max(self.lpfac, max_lpfac) if run_type == "BANDS" and self.bs.is_spin_polarized: print( diff --git a/src/pymatgen/electronic_structure/cohp.py b/src/pymatgen/electronic_structure/cohp.py index be757cbce95..f7b980832d5 100644 --- a/src/pymatgen/electronic_structure/cohp.py +++ b/src/pymatgen/electronic_structure/cohp.py @@ -1344,14 +1344,12 @@ def extremum_icohpvalue( for value in self._icohplist.values(): if not value.is_spin_polarized or not summed_spin_channels: if not self._are_coops and not self._are_cobis: - if value.icohpvalue(spin) < extremum: - extremum = value.icohpvalue(spin) + extremum = min(value.icohpvalue(spin), extremum) elif value.icohpvalue(spin) > extremum: extremum = value.icohpvalue(spin) elif not self._are_coops and not self._are_cobis: - if value.summed_icohp < extremum: - extremum = value.summed_icohp + extremum = min(value.summed_icohp, extremum) elif value.summed_icohp > extremum: extremum = value.summed_icohp diff --git a/src/pymatgen/io/abinit/pseudos.py b/src/pymatgen/io/abinit/pseudos.py index e2a5ec6815a..d2b03705505 100644 --- a/src/pymatgen/io/abinit/pseudos.py +++ b/src/pymatgen/io/abinit/pseudos.py @@ -16,7 +16,7 @@ import traceback from collections import defaultdict from typing import TYPE_CHECKING, NamedTuple -from xml.etree import ElementTree as Et +from xml.etree import ElementTree as ET import numpy as np from monty.collections import AttrDict, Namespace @@ -1242,7 +1242,7 @@ def __getstate__(self): @lazy_property def root(self): """Root tree of XML.""" - tree = Et.parse(self.filepath) + tree = ET.parse(self.filepath) return tree.getroot() @property diff --git a/src/pymatgen/io/cp2k/sets.py b/src/pymatgen/io/cp2k/sets.py index b5ea47cb1f1..0f8fb97cb32 100644 --- a/src/pymatgen/io/cp2k/sets.py +++ b/src/pymatgen/io/cp2k/sets.py @@ -1180,7 +1180,7 @@ def activate_fast_minimization(self, on) -> None: algorithm="IRAC", linesearch="2PNT", ) - self |= {"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}} # type: ignore[assignment] + self.update({"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}}) # type: ignore[assignment] def activate_robust_minimization(self) -> None: """Modify the set to use more robust SCF minimization technique.""" @@ -1190,7 +1190,7 @@ def activate_robust_minimization(self) -> None: algorithm="STRICT", linesearch="3PNT", ) - self |= {"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}} # type: ignore[assignment] + self.update({"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}}) # type: ignore[assignment] def activate_very_strict_minimization(self) -> None: """Method to modify the set to use very strict SCF minimization scheme.""" @@ -1200,7 +1200,7 @@ def activate_very_strict_minimization(self) -> None: algorithm="STRICT", linesearch="GOLD", ) - self |= {"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}} # type: ignore[assignment] + self.update({"FORCE_EVAL": {"DFT": {"SCF": {"OT": ot}}}}) # type: ignore[assignment] def activate_nonperiodic(self, solver="ANALYTIC") -> None: """ diff --git a/src/pymatgen/io/lobster/inputs.py b/src/pymatgen/io/lobster/inputs.py index bd80f07a927..21d51854f4e 100644 --- a/src/pymatgen/io/lobster/inputs.py +++ b/src/pymatgen/io/lobster/inputs.py @@ -249,7 +249,8 @@ def write_lobsterin( overwritedict (dict): dict that can be used to update lobsterin, e.g. {"skipdos": True} """ # Update previous entries - self |= {} if overwritedict is None else overwritedict + if overwritedict is not None: + self.update(overwritedict) with open(path, mode="w", encoding="utf-8") as file: for key in self: diff --git a/src/pymatgen/io/nwchem.py b/src/pymatgen/io/nwchem.py index d3ddddbc440..ab5b32175c4 100644 --- a/src/pymatgen/io/nwchem.py +++ b/src/pymatgen/io/nwchem.py @@ -632,8 +632,7 @@ def get_excitation_spectrum(self, width=0.1, npoints=2000): de = (emax - emin) / npoints # Use width of at least two grid points - if width < 2 * de: - width = 2 * de + width = max(width, 2 * de) energies = [emin + ie * de for ie in range(npoints)] diff --git a/src/pymatgen/io/vasp/inputs.py b/src/pymatgen/io/vasp/inputs.py index fb888857bfe..3b0eb0a65cf 100644 --- a/src/pymatgen/io/vasp/inputs.py +++ b/src/pymatgen/io/vasp/inputs.py @@ -2742,9 +2742,9 @@ def __init__( """ super().__init__(**kwargs) self._potcar_filename = "POTCAR" + (".spec" if potcar_spec else "") - self |= {"INCAR": incar, "KPOINTS": kpoints, "POSCAR": poscar, self._potcar_filename: potcar} + self.update({"INCAR": incar, "KPOINTS": kpoints, "POSCAR": poscar, self._potcar_filename: potcar}) if optional_files is not None: - self |= optional_files + self.update(optional_files) def __str__(self) -> str: output: list = [] diff --git a/tests/io/exciting/test_inputs.py b/tests/io/exciting/test_inputs.py index a5a221221b3..7b539401cda 100644 --- a/tests/io/exciting/test_inputs.py +++ b/tests/io/exciting/test_inputs.py @@ -1,6 +1,6 @@ from __future__ import annotations -from xml.etree import ElementTree +from xml.etree import ElementTree as ET from numpy.testing import assert_allclose @@ -102,7 +102,7 @@ def test_writebandstr(self): [0.5, 0.5, 0.5], ] label_ref = ["GAMMA", "X", "S", "Y", "GAMMA", "Z", "U", "R", "T", "Z", "Y", "T", "U", "X", "S", "R"] - root = ElementTree.fromstring(band_str) + root = ET.fromstring(band_str) for plot1d in root.iter("plot1d"): for point in plot1d.iter("point"): coord.append([float(i) for i in point.get("coord").split()]) @@ -140,8 +140,8 @@ def test_param_dict(self): # read reference file filepath = f"{TEST_DIR}/input_exciting2.xml" - tree = ElementTree.parse(filepath) + tree = ET.parse(filepath) root = tree.getroot() - ref_str = ElementTree.tostring(root, encoding="unicode") + ref_str = ET.tostring(root, encoding="unicode") assert ref_str.strip() == test_str.strip() diff --git a/tests/io/vasp/test_outputs.py b/tests/io/vasp/test_outputs.py index 59a9305d642..9d0d9bcd60d 100644 --- a/tests/io/vasp/test_outputs.py +++ b/tests/io/vasp/test_outputs.py @@ -7,7 +7,7 @@ from io import StringIO from pathlib import Path from shutil import copyfile, copyfileobj -from xml.etree import ElementTree +from xml.etree import ElementTree as ET import numpy as np import pytest @@ -123,7 +123,7 @@ def test_vasprun_with_more_than_two_unlabelled_dielectric_functions(self): Vasprun(f"{VASP_OUT_DIR}/vasprun.dielectric_bad.xml.gz") def test_bad_vasprun(self): - with pytest.raises(ElementTree.ParseError): + with pytest.raises(ET.ParseError): Vasprun(f"{VASP_OUT_DIR}/vasprun.bad.xml.gz") with pytest.warns(