Skip to content

Commit

Permalink
add types to ChargemolAnalysis.__init__
Browse files Browse the repository at this point in the history
fix typos
  • Loading branch information
janosh committed Oct 23, 2023
1 parent 7a29896 commit c5e4f89
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 53 deletions.
21 changes: 10 additions & 11 deletions pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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),
Expand All @@ -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
Expand All @@ -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.
"""

Expand All @@ -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.
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
76 changes: 38 additions & 38 deletions pymatgen/command_line/chargemol_caller.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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"
Expand All @@ -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."
Expand Down Expand Up @@ -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] != "/":
Expand Down Expand Up @@ -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

Expand All @@ -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])

Expand Down Expand Up @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/core/composition.py
Original file line number Diff line number Diff line change
Expand Up @@ -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():
Expand All @@ -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():
Expand Down
2 changes: 1 addition & 1 deletion pymatgen/symmetry/analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit c5e4f89

Please sign in to comment.