From c5e4f8961b4c4411698f8a67b6bcaabd4f6e348d Mon Sep 17 00:00:00 2001 From: Janosh Riebesell Date: Mon, 23 Oct 2023 16:00:50 -0700 Subject: [PATCH] add types to ChargemolAnalysis.__init__ fix typos --- pymatgen/analysis/eos.py | 21 +++---- pymatgen/analysis/local_env.py | 2 +- pymatgen/command_line/chargemol_caller.py | 76 +++++++++++------------ pymatgen/core/composition.py | 4 +- pymatgen/symmetry/analyzer.py | 2 +- 5 files changed, 52 insertions(+), 53 deletions(-) diff --git a/pymatgen/analysis/eos.py b/pymatgen/analysis/eos.py index f4dbe3d9413..deff4e4a525 100644 --- a/pymatgen/analysis/eos.py +++ b/pymatgen/analysis/eos.py @@ -65,10 +65,10 @@ def _initial_guess(self): b0 = 2 * a * v0 b1 = 4 # b1 is usually a small number like 4 - vmin, vmax = min(self.volumes), max(self.volumes) + vol_min, vol_max = min(self.volumes), max(self.volumes) - if not vmin < v0 and v0 < vmax: - raise EOSError("The minimum volume of a fitted parabola is not in the input volumes\n.") + if not vol_min < v0 and v0 < vol_max: + raise EOSError("The minimum volume of a fitted parabola is not in the input volumes.") return e0, b0, b1, v0 @@ -77,8 +77,7 @@ def fit(self): Do the fitting. Does least square fitting. If you want to use custom fitting, must override this. """ - # the objective function that will be minimized in the least square - # fitting + # the objective function that will be minimized in the least square fitting self._params = self._initial_guess() self.eos_params, ierr = leastsq( lambda pars, x, y: y - self._func(x, pars), @@ -87,7 +86,7 @@ def fit(self): ) # e0, b0, b1, v0 self._params = self.eos_params - if ierr not in [1, 2, 3, 4]: + if ierr not in (1, 2, 3, 4): raise EOSError("Optimal parameters not found") @abstractmethod @@ -97,8 +96,8 @@ def _func(self, volume, params): that derive from this abstract class. Args: - volume (float/numpy.array) - params (list/tuple): values for the parameters other than the + volume (float | list[float]) + params (list | tuple): values for the parameters other than the volume used by the eos. """ @@ -108,17 +107,17 @@ def func(self, volume): to the ones obtained from fitting. Args: - volume (list/numpy.array) + volume (float | list[float]): volumes in Ang^3 Returns: numpy.array """ return self._func(np.array(volume), self.eos_params) - def __call__(self, volume): + def __call__(self, volume: float) -> float: """ Args: - volume (): Volume. + volume (float | list[float]): volume(s) in Ang^3 Returns: Compute EOS with this volume. diff --git a/pymatgen/analysis/local_env.py b/pymatgen/analysis/local_env.py index adc110d32cb..065d03d6017 100644 --- a/pymatgen/analysis/local_env.py +++ b/pymatgen/analysis/local_env.py @@ -1878,7 +1878,7 @@ def get_nn_info(self, structure: Structure, n: int): def _get_vire(structure: Structure | IStructure): - """Get the ValenceIonicRadiusEvaluator object for an structure taking + """Get the ValenceIonicRadiusEvaluator object for a structure taking advantage of caching. Args: diff --git a/pymatgen/command_line/chargemol_caller.py b/pymatgen/command_line/chargemol_caller.py index d32ef43c268..06fe7ba1958 100644 --- a/pymatgen/command_line/chargemol_caller.py +++ b/pymatgen/command_line/chargemol_caller.py @@ -47,6 +47,7 @@ import warnings from glob import glob from shutil import which +from typing import TYPE_CHECKING import numpy as np from monty.tempfile import ScratchDir @@ -55,6 +56,9 @@ from pymatgen.io.vasp.inputs import Potcar from pymatgen.io.vasp.outputs import Chgcar +if TYPE_CHECKING: + from pathlib import Path + __author__ = "Martin Siron, Andrew S. Rosen" __version__ = "0.1" __maintainer__ = "Shyue Ping Ong" @@ -74,24 +78,23 @@ class ChargemolAnalysis: def __init__( self, - path=None, - atomic_densities_path=None, - run_chargemol=True, - ): + path: str | Path | None = None, + atomic_densities_path: str | Path | None = None, + run_chargemol: bool = True, + ) -> None: """Initializes the Chargemol Analysis. Args: path (str): Path to the CHGCAR, POTCAR, AECCAR0, and AECCAR files. The files can be gzipped or not. Default: None (current working directory). - atomic_densities_path (str|None): Path to the atomic densities directory + atomic_densities_path (str | None): Path to the atomic densities directory required by Chargemol. If None, Pymatgen assumes that this is defined in a "DDEC6_ATOMIC_DENSITIES_DIR" environment variable. Only used if run_chargemol is True. Default: None. run_chargemol (bool): Whether to run the Chargemol analysis. If False, the existing Chargemol output files will be read from path. Default: True. """ - if not path: - path = os.getcwd() + path = path or os.getcwd() if run_chargemol and not CHARGEMOL_EXE: raise OSError( "ChargemolAnalysis requires the Chargemol executable to be in PATH." @@ -362,17 +365,17 @@ def _write_jobscript_for_chargemol( ) # atomic_densities dir - atomic_densities_path = self._atomic_densities_path or os.getenv("DDEC6_ATOMIC_DENSITIES_DIR", None) + atomic_densities_path = self._atomic_densities_path or os.getenv("DDEC6_ATOMIC_DENSITIES_DIR") if atomic_densities_path is None: raise OSError( "The DDEC6_ATOMIC_DENSITIES_DIR environment variable must be set or the atomic_densities_path must" " be specified" ) if not os.path.exists(atomic_densities_path): - raise OSError(f"Cannot find the path to the atomic densities at {atomic_densities_path}") + raise FileNotFoundError(f"{atomic_densities_path=} does not exist") # This is to fix a Chargemol filepath nuance - if os.name == "nt": + if os.name == "nt": # Windows if atomic_densities_path[-1] != "\\": atomic_densities_path += "\\" elif atomic_densities_path[-1] != "/": @@ -400,21 +403,21 @@ def _get_dipole_info(filepath): Args: filepath (str): The path to the DDEC6_even_tempered_net_atomic_charges.xyz file """ - i = 0 + idx = 0 start = False dipoles = [] with open(filepath) as r: for line in r: if "The following XYZ" in line: start = True - i += 1 + idx += 1 continue if start and line.strip() == "": break - if i >= 2: + if idx >= 2: dipoles.append([float(d) for d in line.strip().split()[7:10]]) if start: - i += 1 + idx += 1 return dipoles @@ -441,15 +444,14 @@ def _get_bond_order_info(filename): end_el = Element(split[14]) bo = float(split[20]) spin_bo = float(split[-1]) - bond_order_info[start_idx]["bonded_to"].append( - { - "index": end_idx, - "element": end_el, - "bond_order": bo, - "direction": direction, - "spin_polarization": spin_bo, - } - ) + bonded_to = { + "index": end_idx, + "element": end_el, + "bond_order": bo, + "direction": direction, + "spin_polarization": spin_bo, + } + bond_order_info[start_idx]["bonded_to"].append(bonded_to) elif "The sum of bond orders for this atom" in line: bond_order_info[start_idx]["bond_order_sum"] = float(split[-1]) @@ -478,24 +480,22 @@ def get_property_decorated_structure(self): def summary(self): """Returns a dictionary summary of the Chargemol analysis { - "ddec": { - "partial_charges": List[float], - "spin_moments": List[float], - "dipoles": List[float], - "rsquared_moments": List[float], - "rcubed_moments": List[float], - "rfourth_moments": List[float], - "bond_order_dict": Dict - }, - "cm5": { - "partial_charges": List[float], - } + "ddec": { + "partial_charges": list[float], + "spin_moments": list[float], + "dipoles": list[float], + "rsquared_moments": list[float], + "rcubed_moments": list[float], + "rfourth_moments": list[float], + "bond_order_dict": dict + }, + "cm5": { + "partial_charges": list[float], + } }. """ summary = {} - ddec_summary = { - "partial_charges": self.ddec_charges, - } + ddec_summary = {"partial_charges": self.ddec_charges} if self.bond_order_sums: ddec_summary["bond_order_sums"] = self.bond_order_sums if self.ddec_spin_moments: diff --git a/pymatgen/core/composition.py b/pymatgen/core/composition.py index 3641632b87f..75367188129 100644 --- a/pymatgen/core/composition.py +++ b/pymatgen/core/composition.py @@ -632,7 +632,7 @@ def get_el_amt_dict(self) -> dict[str, float]: """ Returns: dict[str, float]: element symbol and (unreduced) amount. E.g. - {"Fe": 4.0, "O":6.0} or {"Fe3+": 4.0, "O2-":6.0}. + {"Fe": 4.0, "O": 6.0}. """ dct: dict[str, float] = collections.defaultdict(float) for el, amt in self.items(): @@ -645,7 +645,7 @@ def as_dict(self) -> dict[str, float]: Returns: dict[str, float]: element symbol and (unreduced) amount. E.g. - {"Fe": 4.0, "O":6.0} or {"Fe3+": 4.0, "O2-":6.0} + {"Fe": 4.0, "O": 6.0} or {"Fe3+": 4.0, "O2-": 6.0} """ dct: dict[str, float] = collections.defaultdict(float) for el, amt in self.items(): diff --git a/pymatgen/symmetry/analyzer.py b/pymatgen/symmetry/analyzer.py index 8c833d1fc3d..774d5bb0c0f 100644 --- a/pymatgen/symmetry/analyzer.py +++ b/pymatgen/symmetry/analyzer.py @@ -369,7 +369,7 @@ def find_primitive(self, keep_site_properties=False): Returns: A primitive cell in the input cell is searched and returned - as an Structure object. If no primitive cell is found, None is + as a Structure object. If no primitive cell is found, None is returned. """ lattice, scaled_positions, numbers = spglib.find_primitive(self._cell, symprec=self._symprec)