From 40b0165c7e841df6971b6d2960623a127c20e81c Mon Sep 17 00:00:00 2001 From: "Haoyu (Daniel)" Date: Tue, 14 May 2024 22:54:21 +0800 Subject: [PATCH] Guard `TYPE_CHECKING` only imports (#3827) * flake8 --select=TYP001 * fix type import * format docstring to google style * fix more unguarded typecheck imports * format more docs to Google format * trigger CI (better var names) --------- Co-authored-by: Janosh Riebesell --- pymatgen/alchemy/materials.py | 3 +- pymatgen/alchemy/transmuters.py | 3 +- .../coordination_geometries.py | 4 +- .../utils/coordination_geometry_utils.py | 4 +- pymatgen/analysis/elasticity/elastic.py | 3 +- pymatgen/analysis/elasticity/strain.py | 3 +- pymatgen/analysis/ewald.py | 22 ++-- pymatgen/analysis/interface_reactions.py | 5 +- pymatgen/analysis/magnetism/jahnteller.py | 4 +- pymatgen/analysis/phase_diagram.py | 3 +- pymatgen/analysis/pourbaix_diagram.py | 4 +- pymatgen/analysis/structure_matcher.py | 3 +- pymatgen/cli/pmg_config.py | 3 +- pymatgen/command_line/bader_caller.py | 4 +- pymatgen/core/interface.py | 3 +- pymatgen/core/periodic_table.py | 4 +- pymatgen/core/structure.py | 39 +++--- pymatgen/core/units.py | 4 +- .../electronic_structure/bandstructure.py | 4 +- pymatgen/electronic_structure/boltztrap.py | 4 +- pymatgen/electronic_structure/cohp.py | 4 +- pymatgen/entries/__init__.py | 6 +- pymatgen/entries/compatibility.py | 4 +- pymatgen/entries/computed_entries.py | 4 +- pymatgen/entries/entry_tools.py | 3 +- pymatgen/ext/matproj_legacy.py | 3 +- pymatgen/io/aims/inputs.py | 3 +- pymatgen/io/aims/outputs.py | 3 +- pymatgen/io/aims/parsers.py | 3 +- pymatgen/io/aims/sets/base.py | 112 +++++++----------- pymatgen/io/aims/sets/bs.py | 48 +++----- pymatgen/io/aims/sets/core.py | 64 ++++------ pymatgen/io/cif.py | 4 +- pymatgen/io/cp2k/inputs.py | 5 +- pymatgen/io/lammps/data.py | 4 +- pymatgen/io/lobster/inputs.py | 4 +- pymatgen/io/lobster/outputs.py | 4 +- pymatgen/io/pwscf.py | 4 +- pymatgen/io/qchem/inputs.py | 3 +- pymatgen/io/qchem/outputs.py | 4 +- pymatgen/io/qchem/sets.py | 4 +- pymatgen/io/res.py | 3 +- pymatgen/io/shengbte.py | 10 +- pymatgen/io/vasp/outputs.py | 4 +- pymatgen/io/vasp/sets.py | 13 +- pymatgen/phonon/bandstructure.py | 3 +- pymatgen/phonon/plotter.py | 4 +- pymatgen/phonon/thermal_displacements.py | 3 +- pymatgen/symmetry/analyzer.py | 7 +- pymatgen/symmetry/groups.py | 7 +- pymatgen/symmetry/kpath.py | 6 +- pymatgen/util/plotting.py | 3 +- pymatgen/util/testing/__init__.py | 3 +- pymatgen/vis/structure_vtk.py | 3 +- tests/util/test_typing.py | 5 +- 55 files changed, 260 insertions(+), 233 deletions(-) diff --git a/pymatgen/alchemy/materials.py b/pymatgen/alchemy/materials.py index cfbf08025e2..16c515420d3 100644 --- a/pymatgen/alchemy/materials.py +++ b/pymatgen/alchemy/materials.py @@ -8,7 +8,7 @@ import datetime import json import re -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from warnings import warn from monty.json import MSONable, jsanitize @@ -22,6 +22,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any from typing_extensions import Self diff --git a/pymatgen/alchemy/transmuters.py b/pymatgen/alchemy/transmuters.py index 9516eeb5bf2..545876d53e1 100644 --- a/pymatgen/alchemy/transmuters.py +++ b/pymatgen/alchemy/transmuters.py @@ -12,13 +12,14 @@ import os import re from multiprocessing import Pool -from typing import TYPE_CHECKING, Callable +from typing import TYPE_CHECKING from pymatgen.alchemy.materials import TransformedStructure from pymatgen.io.vasp.sets import MPRelaxSet, VaspInputSet if TYPE_CHECKING: from collections.abc import Sequence + from typing import Callable from typing_extensions import Self diff --git a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py index 61ae5892d8c..142fe838f7e 100644 --- a/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py +++ b/pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py @@ -13,13 +13,15 @@ import itertools import json import os -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.json import MontyDecoder, MSONable from scipy.special import factorial if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self __author__ = "David Waroquiers" diff --git a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py index edddcf9166e..38fc59adcb5 100644 --- a/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py +++ b/pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py @@ -3,7 +3,7 @@ from __future__ import annotations import math -from typing import TYPE_CHECKING, Callable +from typing import TYPE_CHECKING import numpy as np from numpy.linalg import norm @@ -14,6 +14,8 @@ from pymatgen.analysis.chemenv.utils.chemenv_errors import SolidAngleError if TYPE_CHECKING: + from typing import Callable + from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/analysis/elasticity/elastic.py b/pymatgen/analysis/elasticity/elastic.py index 919c5dc6cfa..4097af9837b 100644 --- a/pymatgen/analysis/elasticity/elastic.py +++ b/pymatgen/analysis/elasticity/elastic.py @@ -9,7 +9,7 @@ import itertools import math import warnings -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np import sympy as sp @@ -25,6 +25,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Literal from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/analysis/elasticity/strain.py b/pymatgen/analysis/elasticity/strain.py index 9edaf989c42..99fe716a249 100644 --- a/pymatgen/analysis/elasticity/strain.py +++ b/pymatgen/analysis/elasticity/strain.py @@ -8,7 +8,7 @@ import collections import itertools -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np import scipy @@ -18,6 +18,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Literal from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/analysis/ewald.py b/pymatgen/analysis/ewald.py index 7b4fa243dce..18c55d8eaca 100644 --- a/pymatgen/analysis/ewald.py +++ b/pymatgen/analysis/ewald.py @@ -3,10 +3,10 @@ from __future__ import annotations import bisect +import math from copy import copy, deepcopy from datetime import datetime -from math import log, pi, sqrt -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from warnings import warn import numpy as np @@ -18,6 +18,8 @@ from pymatgen.util.due import Doi, due if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self __author__ = "Shyue Ping Ong, William Davidson Richard" @@ -55,7 +57,7 @@ class EwaldSummation(MSONable): """ # Converts unit of q*q/r into eV - CONV_FACT = 1e10 * constants.e / (4 * pi * constants.epsilon_0) + CONV_FACT = 1e10 * constants.e / (4 * math.pi * constants.epsilon_0) def __init__( self, @@ -102,12 +104,12 @@ def __init__( self._acc_factor = acc_factor # set screening length - self._eta = eta or (len(structure) * w / (self._vol**2)) ** (1 / 3) * pi - self._sqrt_eta = sqrt(self._eta) + self._eta = eta or (len(structure) * w / (self._vol**2)) ** (1 / 3) * math.pi + self._sqrt_eta = math.sqrt(self._eta) # acc factor used to automatically determine the optimal real and # reciprocal space cutoff radii - self._accf = sqrt(log(10**acc_factor)) + self._accf = math.sqrt(math.log(10**acc_factor)) self._rmax = real_space_cut or self._accf / self._sqrt_eta self._gmax = recip_space_cut or 2 * self._sqrt_eta * self._accf @@ -307,7 +309,7 @@ def _calc_recip(self): This method is heavily vectorized to utilize numpy's C backend for speed. """ n_sites = len(self._struct) - prefactor = 2 * pi / self._vol + prefactor = 2 * math.pi / self._vol e_recip = np.zeros((n_sites, n_sites), dtype=np.float64) forces = np.zeros((n_sites, 3), dtype=np.float64) coords = self._coords @@ -332,7 +334,7 @@ def _calc_recip(self): for g, g2, gr, exp_val, s_real, s_imag in zip(gs, g2s, grs, exp_vals, s_reals, s_imags): # Uses the identity sin(x)+cos(x) = 2**0.5 sin(x + pi/4) - m = np.sin((gr[None, :] + pi / 4) - gr[:, None]) + m = np.sin((gr[None, :] + math.pi / 4) - gr[:, None]) m *= exp_val / g2 e_recip += m @@ -350,7 +352,7 @@ def _calc_recip(self): def _calc_real_and_point(self): """Determine the self energy -(eta/pi)**(1/2) * sum_{i=1}^{N} q_i**2.""" frac_coords = self._struct.frac_coords - force_pf = 2 * self._sqrt_eta / sqrt(pi) + force_pf = 2 * self._sqrt_eta / math.sqrt(math.pi) coords = self._coords n_sites = len(self._struct) e_real = np.empty((n_sites, n_sites), dtype=np.float64) @@ -359,7 +361,7 @@ def _calc_real_and_point(self): qs = np.array(self._oxi_states) - e_point = -(qs**2) * sqrt(self._eta / pi) + e_point = -(qs**2) * math.sqrt(self._eta / math.pi) for idx in range(n_sites): nf_coords, rij, js, _ = self._struct.lattice.get_points_in_sphere( diff --git a/pymatgen/analysis/interface_reactions.py b/pymatgen/analysis/interface_reactions.py index c388341df55..ffdf0a06c8b 100644 --- a/pymatgen/analysis/interface_reactions.py +++ b/pymatgen/analysis/interface_reactions.py @@ -8,7 +8,7 @@ import json import os import warnings -from typing import Literal +from typing import TYPE_CHECKING import matplotlib.pyplot as plt import numpy as np @@ -23,6 +23,9 @@ from pymatgen.util.plotting import pretty_plot from pymatgen.util.string import htmlify, latexify +if TYPE_CHECKING: + from typing import Literal + __author__ = "Yihan Xiao, Matthew McDermott" __maintainer__ = "Matthew McDermott" __email__ = "mcdermott@lbl.gov" diff --git a/pymatgen/analysis/magnetism/jahnteller.py b/pymatgen/analysis/magnetism/jahnteller.py index d55db392309..f5decc005f6 100644 --- a/pymatgen/analysis/magnetism/jahnteller.py +++ b/pymatgen/analysis/magnetism/jahnteller.py @@ -4,7 +4,7 @@ import os import warnings -from typing import TYPE_CHECKING, Any, Literal, cast +from typing import TYPE_CHECKING, Literal, cast import numpy as np @@ -14,6 +14,8 @@ from pymatgen.symmetry.analyzer import SpacegroupAnalyzer if TYPE_CHECKING: + from typing import Any + from pymatgen.core import Structure MODULE_DIR = os.path.dirname(os.path.abspath(__file__)) diff --git a/pymatgen/analysis/phase_diagram.py b/pymatgen/analysis/phase_diagram.py index df170efe088..9f72089363b 100644 --- a/pymatgen/analysis/phase_diagram.py +++ b/pymatgen/analysis/phase_diagram.py @@ -11,7 +11,7 @@ import warnings from collections import defaultdict from functools import lru_cache -from typing import TYPE_CHECKING, Any, Literal, no_type_check +from typing import TYPE_CHECKING, no_type_check import matplotlib.pyplot as plt import numpy as np @@ -38,6 +38,7 @@ if TYPE_CHECKING: from collections.abc import Collection, Iterator, Sequence from io import StringIO + from typing import Any, Literal from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/analysis/pourbaix_diagram.py b/pymatgen/analysis/pourbaix_diagram.py index 6e67c5654ae..55203146f63 100644 --- a/pymatgen/analysis/pourbaix_diagram.py +++ b/pymatgen/analysis/pourbaix_diagram.py @@ -12,7 +12,7 @@ from copy import deepcopy from functools import cmp_to_key, partial from multiprocessing import Pool -from typing import TYPE_CHECKING, Any, no_type_check +from typing import TYPE_CHECKING, no_type_check import numpy as np from monty.json import MontyDecoder, MSONable @@ -31,6 +31,8 @@ from pymatgen.util.string import Stringify if TYPE_CHECKING: + from typing import Any + import matplotlib.pyplot as plt from typing_extensions import Self diff --git a/pymatgen/analysis/structure_matcher.py b/pymatgen/analysis/structure_matcher.py index e1d2468b4f4..a2640c127ee 100644 --- a/pymatgen/analysis/structure_matcher.py +++ b/pymatgen/analysis/structure_matcher.py @@ -4,7 +4,7 @@ import abc import itertools -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -16,6 +16,7 @@ if TYPE_CHECKING: from collections.abc import Mapping, Sequence + from typing import Literal from typing_extensions import Self diff --git a/pymatgen/cli/pmg_config.py b/pymatgen/cli/pmg_config.py index 49132e37384..d3c135b7c71 100755 --- a/pymatgen/cli/pmg_config.py +++ b/pymatgen/cli/pmg_config.py @@ -8,7 +8,7 @@ import shutil import subprocess from glob import glob -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING from urllib.request import urlretrieve from monty.json import jsanitize @@ -21,6 +21,7 @@ if TYPE_CHECKING: from argparse import Namespace + from typing import Literal def setup_cp2k_data(cp2k_data_dirs: list[str]) -> None: diff --git a/pymatgen/command_line/bader_caller.py b/pymatgen/command_line/bader_caller.py index 9c022b6f859..d621fba43cc 100644 --- a/pymatgen/command_line/bader_caller.py +++ b/pymatgen/command_line/bader_caller.py @@ -22,7 +22,7 @@ from pathlib import Path from shutil import which from tempfile import TemporaryDirectory -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.dev import deprecated @@ -34,6 +34,8 @@ from pymatgen.io.vasp.outputs import Chgcar if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self from pymatgen.core import Structure diff --git a/pymatgen/core/interface.py b/pymatgen/core/interface.py index d7feabd3833..84decc4f108 100644 --- a/pymatgen/core/interface.py +++ b/pymatgen/core/interface.py @@ -8,7 +8,7 @@ from functools import reduce from itertools import chain, combinations, product from math import cos, floor, gcd -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.fractions import lcm @@ -25,6 +25,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/core/periodic_table.py b/pymatgen/core/periodic_table.py index 14694066ce9..e50461aee16 100644 --- a/pymatgen/core/periodic_table.py +++ b/pymatgen/core/periodic_table.py @@ -11,7 +11,7 @@ from enum import Enum, unique from itertools import combinations, product from pathlib import Path -from typing import TYPE_CHECKING, Any, Callable, Literal +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -20,6 +20,8 @@ from pymatgen.util.string import Stringify, formula_double_format if TYPE_CHECKING: + from typing import Any, Callable, Literal + from typing_extensions import Self from pymatgen.util.typing import SpeciesLike diff --git a/pymatgen/core/structure.py b/pymatgen/core/structure.py index 61b84690166..e0227a492d4 100644 --- a/pymatgen/core/structure.py +++ b/pymatgen/core/structure.py @@ -22,7 +22,7 @@ from fnmatch import fnmatch from inspect import isclass from io import StringIO -from typing import TYPE_CHECKING, Any, Callable, Literal, SupportsIndex, cast, get_args +from typing import TYPE_CHECKING, Literal, cast, get_args import numpy as np from monty.dev import deprecated @@ -50,6 +50,7 @@ if TYPE_CHECKING: from collections.abc import Iterable, Iterator, Sequence from pathlib import Path + from typing import Any, Callable, SupportsIndex from ase import Atoms from ase.calculators.calculator import Calculator @@ -2460,12 +2461,12 @@ def site_label(site): sites = sorted(self._sites, key=site_label) grouped_sites = [list(a[1]) for a in itertools.groupby(sites, key=site_label)] - grouped_fcoords = [np.array([s.frac_coords for s in g]) for g in grouped_sites] + grouped_frac_coords = [np.array([s.frac_coords for s in g]) for g in grouped_sites] # min_vecs are approximate periodicities of the cell. The exact # periodicities from the supercell matrices are checked against these # first - min_fcoords = min(grouped_fcoords, key=len) + min_fcoords = min(grouped_frac_coords, key=len) min_vecs = min_fcoords - min_fcoords[0] # fractional tolerance in the supercell @@ -2486,7 +2487,7 @@ def pbc_coord_intersection(fc1, fc2, tol): # reduction. # This reduction is O(n^3) so usually is an improvement. Using double # the tolerance because both vectors are approximate - for group in sorted(grouped_fcoords, key=len): + for group in sorted(grouped_frac_coords, key=len): for frac_coords in group: min_vecs = pbc_coord_intersection(min_vecs, group - frac_coords, super_ftol_2) @@ -2522,8 +2523,8 @@ def factors(n: int): # we can't let sites match to their neighbors in the supercell grouped_non_nbrs = [] - for gfcoords in grouped_fcoords: - fdist = gfcoords[None, :, :] - gfcoords[:, None, :] + for gf_coords in grouped_frac_coords: + fdist = gf_coords[None, :, :] - gf_coords[:, None, :] fdist -= np.round(fdist) np.abs(fdist, fdist) non_nbrs = np.any(fdist > 2 * super_ftol[None, None, :], axis=-1) @@ -2543,7 +2544,7 @@ def factors(n: int): any_close = np.any(is_close, axis=-1) inds = np.all(any_close, axis=-1) - for inv_m, m in zip(inv_ms[inds], ms[inds]): + for inv_m, latt_mat in zip(inv_ms[inds], ms[inds]): new_m = np.dot(inv_m, self.lattice.matrix) ftol = np.divide(tolerance, np.sqrt(np.sum(new_m**2, axis=1))) @@ -2552,8 +2553,8 @@ def factors(n: int): new_sp = [] new_props = defaultdict(list) new_labels = [] - for gsites, gfcoords, non_nbrs in zip(grouped_sites, grouped_fcoords, grouped_non_nbrs): - all_frac = np.dot(gfcoords, m) + for gsites, gf_coords, non_nbrs in zip(grouped_sites, grouped_frac_coords, grouped_non_nbrs): + all_frac = np.dot(gf_coords, latt_mat) # calculate grouping of equivalent sites, represented by # adjacency matrix @@ -2578,14 +2579,14 @@ def factors(n: int): # add the new sites, averaging positions added = np.zeros(len(gsites)) new_fcoords = all_frac % 1 - for i, group in enumerate(groups): - if not added[i]: + for grp_idx, group in enumerate(groups): + if not added[grp_idx]: added[group] = True inds = np.where(group)[0] coords = new_fcoords[inds[0]] - for n, j in enumerate(inds[1:]): - offset = new_fcoords[j] - coords - coords += (offset - np.round(offset)) / (n + 2) + for inner_idx, ind in enumerate(inds[1:]): + offset = new_fcoords[ind] - coords + coords += (offset - np.round(offset)) / (inner_idx + 2) new_sp.append(gsites[inds[0]].species) for k in gsites[inds[0]].properties: new_props[k].append(gsites[inds[0]].properties[k]) @@ -2593,7 +2594,7 @@ def factors(n: int): new_coords.append(coords) if valid: - inv_m = np.linalg.inv(m) + inv_m = np.linalg.inv(latt_mat) new_latt = Lattice(np.dot(inv_m, self.lattice.matrix)) struct = Structure( new_latt, @@ -2605,22 +2606,22 @@ def factors(n: int): ) # Default behavior - p = struct.get_primitive_structure( + primitive = struct.get_primitive_structure( tolerance=tolerance, use_site_props=use_site_props, constrain_latt=constrain_latt ).get_reduced_structure() if not constrain_latt: - return p + return primitive # Only return primitive structures that # satisfy the restriction condition - prim_latt, self_latt = p.lattice, self.lattice + prim_latt, self_latt = primitive.lattice, self.lattice keys = tuple(constrain_latt) is_dict = isinstance(constrain_latt, dict) if np.allclose( [getattr(prim_latt, key) for key in keys], [constrain_latt[key] if is_dict else getattr(self_latt, key) for key in keys], ): - return p + return primitive return self.copy() diff --git a/pymatgen/core/units.py b/pymatgen/core/units.py index 268c0526a25..11364373f98 100644 --- a/pymatgen/core/units.py +++ b/pymatgen/core/units.py @@ -13,12 +13,14 @@ from collections import defaultdict from functools import partial from numbers import Number -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np import scipy.constants as const if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self __author__ = "Shyue Ping Ong, Matteo Giantomassi" diff --git a/pymatgen/electronic_structure/bandstructure.py b/pymatgen/electronic_structure/bandstructure.py index f40bea2d16b..4ac2785fe84 100644 --- a/pymatgen/electronic_structure/bandstructure.py +++ b/pymatgen/electronic_structure/bandstructure.py @@ -7,7 +7,7 @@ import re import warnings from collections import defaultdict -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -18,6 +18,8 @@ from pymatgen.util.coord import pbc_diff if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self __author__ = "Geoffroy Hautier, Shyue Ping Ong, Michael Kocher" diff --git a/pymatgen/electronic_structure/boltztrap.py b/pymatgen/electronic_structure/boltztrap.py index 869b3c1e961..9788d1249d1 100644 --- a/pymatgen/electronic_structure/boltztrap.py +++ b/pymatgen/electronic_structure/boltztrap.py @@ -25,7 +25,7 @@ import tempfile import time from shutil import which -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np from monty.dev import requires @@ -44,6 +44,8 @@ from pymatgen.symmetry.bandstructure import HighSymmKpath if TYPE_CHECKING: + from typing import Literal + from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/electronic_structure/cohp.py b/pymatgen/electronic_structure/cohp.py index 4b5514c903f..92a98733cac 100644 --- a/pymatgen/electronic_structure/cohp.py +++ b/pymatgen/electronic_structure/cohp.py @@ -13,7 +13,7 @@ import re import sys import warnings -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -29,6 +29,8 @@ from pymatgen.util.num import round_to_sigfigs if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self __author__ = "Marco Esters, Janine George" diff --git a/pymatgen/entries/__init__.py b/pymatgen/entries/__init__.py index 8a22d729e08..51e6d6cee5a 100644 --- a/pymatgen/entries/__init__.py +++ b/pymatgen/entries/__init__.py @@ -7,8 +7,8 @@ from __future__ import annotations -from abc import ABC, ABCMeta, abstractmethod -from typing import TYPE_CHECKING, Literal +from abc import ABC, abstractmethod +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -16,6 +16,8 @@ from pymatgen.core.composition import Composition if TYPE_CHECKING: + from typing import Literal + from pymatgen.core import DummySpecies, Element, Species diff --git a/pymatgen/entries/compatibility.py b/pymatgen/entries/compatibility.py index 0346fb45af5..20558be0851 100644 --- a/pymatgen/entries/compatibility.py +++ b/pymatgen/entries/compatibility.py @@ -9,7 +9,7 @@ import os import warnings from collections import defaultdict -from typing import TYPE_CHECKING, Literal, Union +from typing import TYPE_CHECKING, Union import numpy as np from monty.design_patterns import cached_class @@ -33,9 +33,11 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Literal from pymatgen.util.typing import CompositionLike + __author__ = "Amanda Wang, Ryan Kingsbury, Shyue Ping Ong, Anubhav Jain, Stephen Dacek, Sai Jayaraman" __copyright__ = "Copyright 2012-2020, The Materials Project" __version__ = "1.0" diff --git a/pymatgen/entries/computed_entries.py b/pymatgen/entries/computed_entries.py index 09615cdcc8d..a247989847f 100644 --- a/pymatgen/entries/computed_entries.py +++ b/pymatgen/entries/computed_entries.py @@ -13,7 +13,7 @@ import os import warnings from itertools import combinations -from typing import TYPE_CHECKING, Literal, cast +from typing import TYPE_CHECKING, cast import numpy as np from monty.json import MontyDecoder, MontyEncoder, MSONable @@ -25,6 +25,8 @@ from pymatgen.util.due import Doi, due if TYPE_CHECKING: + from typing import Literal + from typing_extensions import Self from pymatgen.core import Structure diff --git a/pymatgen/entries/entry_tools.py b/pymatgen/entries/entry_tools.py index 1e2dda0c02b..da2903f0d20 100644 --- a/pymatgen/entries/entry_tools.py +++ b/pymatgen/entries/entry_tools.py @@ -13,7 +13,7 @@ import multiprocessing as mp import re from collections import defaultdict -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING from monty.json import MontyDecoder, MontyEncoder, MSONable @@ -23,6 +23,7 @@ if TYPE_CHECKING: from collections.abc import Iterable + from typing import Literal from typing_extensions import Self diff --git a/pymatgen/ext/matproj_legacy.py b/pymatgen/ext/matproj_legacy.py index 26868d9156d..40ae2456186 100644 --- a/pymatgen/ext/matproj_legacy.py +++ b/pymatgen/ext/matproj_legacy.py @@ -16,7 +16,7 @@ import warnings from enum import Enum, unique from time import sleep -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING import requests from monty.json import MontyDecoder, MontyEncoder @@ -34,6 +34,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any, Literal from typing_extensions import Self diff --git a/pymatgen/io/aims/inputs.py b/pymatgen/io/aims/inputs.py index 4bcf92752e0..64877178e73 100644 --- a/pymatgen/io/aims/inputs.py +++ b/pymatgen/io/aims/inputs.py @@ -11,7 +11,7 @@ from copy import deepcopy from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.io import zopen @@ -21,6 +21,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any from typing_extensions import Self diff --git a/pymatgen/io/aims/outputs.py b/pymatgen/io/aims/outputs.py index 51124e96243..1a846030107 100644 --- a/pymatgen/io/aims/outputs.py +++ b/pymatgen/io/aims/outputs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.json import MontyDecoder, MSONable @@ -17,6 +17,7 @@ if TYPE_CHECKING: from collections.abc import Sequence from pathlib import Path + from typing import Any from typing_extensions import Self diff --git a/pymatgen/io/aims/parsers.py b/pymatgen/io/aims/parsers.py index 33286b8620f..44ff922a026 100644 --- a/pymatgen/io/aims/parsers.py +++ b/pymatgen/io/aims/parsers.py @@ -5,7 +5,7 @@ import gzip from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any, cast +from typing import TYPE_CHECKING, cast import numpy as np @@ -15,6 +15,7 @@ if TYPE_CHECKING: from collections.abc import Generator, Sequence from io import TextIOWrapper + from typing import Any from pymatgen.util.typing import Matrix3D, Vector3D diff --git a/pymatgen/io/aims/sets/base.py b/pymatgen/io/aims/sets/base.py index dcd427af6f5..b868a8621d8 100644 --- a/pymatgen/io/aims/sets/base.py +++ b/pymatgen/io/aims/sets/base.py @@ -180,12 +180,11 @@ class AimsInputGenerator(InputGenerator): """ A class to generate Aims input sets. - Parameters - ---------- - user_params: dict[str, Any] - Updates the default parameters for the FHI-aims calculator - user_kpoints_settings: dict[str, Any] - The settings used to create the k-grid parameters for FHI-aims + Attributes: + user_params (dict[str, Any]): Updates the default + parameters for the FHI-aims calculator + user_kpoints_settings (dict[str, Any]): The settings + used to create the k-grid parameters for FHI-aims """ user_params: dict[str, Any] = field(default_factory=dict) @@ -199,14 +198,11 @@ def get_input_set( # type: ignore ) -> AimsInputSet: """Generate an AimsInputSet object. - Parameters - ---------- - structure : Structure or Molecule - Structure or Molecule to generate the input set for. - prev_dir: str or Path - Path to the previous working directory - properties: list[str] - System properties that are being calculated + Args: + structure (Structure or Molecule): Structure or + Molecule to generate the input set for. + prev_dir (str or Path): Path to the previous working directory + properties (list[str]): System properties that are being calculated Returns: AimsInputSet: The input set for the calculation of structure @@ -229,10 +225,8 @@ def _read_previous( ) -> tuple[Structure | Molecule | None, dict[str, Any], dict[str, Any]]: """Read in previous results. - Parameters - ---------- - prev_dir: str or Path - The previous directory for the calculation + Args: + prev_dir (str or Path): The previous directory for the calculation """ prev_structure: Structure | Molecule | None = None prev_parameters = {} @@ -266,12 +260,9 @@ def _get_properties( ) -> list[str]: """Get the properties to calculate. - Parameters - ---------- - properties: list[str] - The currently requested properties - parameters: dict[str, Any] - The parameters for this calculation + Args: + properties (list[str]): The currently requested properties + parameters (dict[str, Any]): The parameters for this calculation Returns: list[str]: The list of properties to calculate @@ -301,12 +292,11 @@ def _get_input_parameters( ) -> dict[str, Any]: """Create the input parameters. - Parameters - ---------- - structure: Structure | Molecule - The structure or molecule for the system - prev_parameters: dict[str, Any] - The previous calculation's calculation parameters + Args: + structure (Structure | Molecule): The structure + or molecule for the system + prev_parameters (dict[str, Any]): The previous + calculation's calculation parameters Returns: dict: The input object @@ -353,12 +343,9 @@ def _get_input_parameters( def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters: dict[str, Any]) -> dict[str, Any]: """Update the parameters for a given calculation type. - Parameters - ---------- - structure : Structure or Molecule - The system to run - prev_parameters: dict[str, Any] - Previous calculation parameters. + Args: + structure (Structure or Molecule): The system to run + prev_parameters (dict[str, Any]): Previous calculation parameters. Returns: dict: A dictionary of updates to apply. @@ -375,14 +362,13 @@ def d2k( inspired by [ase.calculators.calculator.kptdensity2monkhorstpack] - Parameters - ---------- - structure: Structure - Contains unit cell and information about boundary conditions. - kptdensity: float or list of floats - Required k-point density. Default value is 5.0 point per Ang^-1. - even: bool - Round up to even numbers. + Args: + + structure (Structure): Contains unit cell and + information about boundary conditions. + kptdensity (float | list[float]): Required k-point + density. Default value is 5.0 point per Ang^-1. + even (bool): Round up to even numbers. Returns: dict: Monkhorst-Pack grid size in all directions @@ -393,12 +379,11 @@ def d2k( def k2d(self, structure: Structure, k_grid: np.ndarray[int]): """Generate the kpoint density in each direction from given k_grid. - Parameters - ---------- - structure: Structure - Contains unit cell and information about boundary conditions. - k_grid: np.ndarray[int] - k_grid that was used. + Args: + structure: Structure + Contains unit cell and information about boundary conditions. + k_grid: np.ndarray[int] + k_grid that was used. Returns: dict: Density of kpoints in each direction. result.mean() computes average density @@ -416,16 +401,13 @@ def d2k_recipcell( ) -> Sequence[int]: """Convert k-point density to Monkhorst-Pack grid size. - Parameters - ---------- - recipcell: Cell - The reciprocal cell - pbc: Sequence[bool] - If element of pbc is True then system is periodic in that direction - kptdensity: float or list[floats] - Required k-point density. Default value is 3.5 point per Ang^-1. - even: bool - Round up to even numbers. + Args: + recipcell (Cell): The reciprocal cell + pbc (Sequence[bool]): If element of pbc is True + then system is periodic in that direction + kptdensity (float or list[floats]): Required k-point + density. Default value is 3.5 point per Ang^-1. + even(bool): Round up to even numbers. Returns: dict: Monkhorst-Pack grid size in all directions @@ -449,16 +431,14 @@ def recursive_update(dct: dict, up: dict) -> dict: """ Update a dictionary recursively and return it. - Parameters - ---------- - dct (dict): Input dictionary to modify - up (dict): updates to apply + Args: + dct (dict): Input dictionary to modify + up (dict): updates to apply Returns: dict: The updated dictionary. - Example - ------- + Example: d = {'activate_hybrid': {"hybrid_functional": "HSE06"}} u = {'activate_hybrid': {"cutoff_radius": 8}} diff --git a/pymatgen/io/aims/sets/bs.py b/pymatgen/io/aims/sets/bs.py index d0833f16999..7c1cafaa7ef 100644 --- a/pymatgen/io/aims/sets/bs.py +++ b/pymatgen/io/aims/sets/bs.py @@ -3,7 +3,7 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, TypedDict +from typing import TYPE_CHECKING, TypedDict from pymatgen.core import Molecule, Structure from pymatgen.io.aims.sets.base import AimsInputGenerator @@ -11,6 +11,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any class _SegmentDict(TypedDict): @@ -22,12 +23,9 @@ class _SegmentDict(TypedDict): def prepare_band_input(structure: Structure, density: float = 20): """Prepare the band information needed for the FHI-aims control.in file. - Parameters - ---------- - structure: Structure - The structure for which the band path is calculated - density: float - Number of kpoints per Angstrom. + Args: + structure (Structure): The structure for which the band path is calculated + density (float): Number of kpoints per Angstrom. """ bp = HighSymmKpath(structure) points, labels = bp.get_kpoints(line_density=density, coords_are_cartesian=False) @@ -64,12 +62,9 @@ def prepare_band_input(structure: Structure, density: float = 20): class BandStructureSetGenerator(AimsInputGenerator): """A generator for the band structure calculation input set. - Parameters - ---------- - calc_type: str - The type of calculations - k_point_density: float - The number of k_points per angstrom + Attributes: + calc_type (str): The type of calculations + k_point_density (float): The number of k_points per angstrom """ calc_type: str = "bands" @@ -80,12 +75,9 @@ def get_parameter_updates( ) -> dict[str, Sequence[str]]: """Get the parameter updates for the calculation. - Parameters - ---------- - structure: Structure - The structure to calculate the bands for - prev_parameters: Dict[str, Any] - The previous parameters + Args: + structure (Structure): The structure to calculate the bands for + prev_parameters (Dict[str, Any]): The previous parameters Returns: dict: The updated for the parameters for the output section of FHI-aims @@ -103,12 +95,9 @@ class GWSetGenerator(AimsInputGenerator): """ A generator for the input set for calculations employing GW self-energy correction. - Parameters - ---------- - calc_type: str - The type of calculations - k_point_density: float - The number of k_points per angstrom + Attributes: + calc_type (str): The type of calculations + k_point_density (float): The number of k_points per angstrom """ calc_type: str = "GW" @@ -117,12 +106,9 @@ class GWSetGenerator(AimsInputGenerator): def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters: dict[str, Any]) -> dict[str, Any]: """Get the parameter updates for the calculation. - Parameters - ---------- - structure: Structure or Molecule - The structure to calculate the bands for - prev_parameters: Dict[str, Any] - The previous parameters + Args: + structure (Structure or Molecule): The structure to calculate the bands for + prev_parameters (Dict[str, Any]): The previous parameters Returns: dict: The updated for the parameters for the output section of FHI-aims diff --git a/pymatgen/io/aims/sets/core.py b/pymatgen/io/aims/sets/core.py index e3b3659be81..db689c60701 100644 --- a/pymatgen/io/aims/sets/core.py +++ b/pymatgen/io/aims/sets/core.py @@ -3,12 +3,14 @@ from __future__ import annotations from dataclasses import dataclass -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from pymatgen.core import Structure from pymatgen.io.aims.sets.base import AimsInputGenerator if TYPE_CHECKING: + from typing import Any + from pymatgen.core import Molecule @@ -16,10 +18,8 @@ class StaticSetGenerator(AimsInputGenerator): """Common class for ground-state generators. - Parameters - ---------- - calc_type: str - The type of calculation + Attributes: + calc_type (str): The type of calculation """ calc_type: str = "static" @@ -27,12 +27,9 @@ class StaticSetGenerator(AimsInputGenerator): def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters: dict[str, Any]) -> dict[str, Any]: """Get the parameter updates for the calculation. - Parameters - ---------- - structure: Structure or Molecule - The structure to calculate the bands for - prev_parameters: Dict[str, Any] - The previous parameters + Args: + structure (Structure or Molecule): The structure to calculate the bands for + prev_parameters (Dict[str, Any]): The previous parameters Returns: dict: The updated for the parameters for the output section of FHI-aims @@ -44,16 +41,11 @@ def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters class RelaxSetGenerator(AimsInputGenerator): """Generate FHI-aims relax sets for optimizing internal coordinates and lattice params. - Parameters - ---------- - calc_type: str - The type of calculation - relax_cell: bool - If True then relax the unit cell from the structure - max_force: float - Maximum allowed force in the calculation - method: str - Method used for the geometry optimization + Attributes: + calc_type (str): The type of calculation + relax_cell (bool): If True then relax the unit cell from the structure + max_force (float): Maximum allowed force in the calculation + method (str): Method used for the geometry optimization """ calc_type: str = "relaxation" @@ -64,12 +56,9 @@ class RelaxSetGenerator(AimsInputGenerator): def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters: dict[str, Any]) -> dict: """Get the parameter updates for the calculation. - Parameters - ---------- - structure: Structure or Molecule - The structure to calculate the bands for - prev_parameters: Dict[str, Any] - The previous parameters + Args: + structure (Structure or Molecule): The structure to calculate the bands for + prev_parameters (Dict[str, Any]): The previous parameters Returns: dict: The updated for the parameters for the output section of FHI-aims @@ -87,14 +76,10 @@ def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters class SocketIOSetGenerator(AimsInputGenerator): """Generate FHI-aims input sets for running with the socket. - Parameters - ---------- - calc_type: str - The type of calculation - host: str - The hostname for the server the socket is on - port: int - The port the socket server is listening on + Attributes: + calc_type (str): The type of calculation + host (str): The hostname for the server the socket is on + port (int): The port the socket server is listening on """ calc_type: str = "multi_scf" @@ -104,12 +89,9 @@ class SocketIOSetGenerator(AimsInputGenerator): def get_parameter_updates(self, structure: Structure | Molecule, prev_parameters: dict[str, Any]) -> dict: """Get the parameter updates for the calculation. - Parameters - ---------- - structure: Structure or Molecule - The structure to calculate the bands for - prev_parameters: Dict[str, Any] - The previous parameters + Args: + structure (Structure or Molecule): The structure to calculate the bands for + prev_parameters (Dict[str, Any]): The previous parameters Returns: dict: The updated for the parameters for the output section of FHI-aims diff --git a/pymatgen/io/cif.py b/pymatgen/io/cif.py index 188d36b5133..2696ce34dda 100644 --- a/pymatgen/io/cif.py +++ b/pymatgen/io/cif.py @@ -13,7 +13,7 @@ from io import StringIO from itertools import groupby from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING import numpy as np from monty.dev import deprecated @@ -30,6 +30,8 @@ from pymatgen.util.coord import find_in_coord_list_pbc, in_coord_list_pbc if TYPE_CHECKING: + from typing import Any, Literal + from typing_extensions import Self from pymatgen.util.typing import Vector3D diff --git a/pymatgen/io/cp2k/inputs.py b/pymatgen/io/cp2k/inputs.py index ee8bcb5b6d3..081f16525b8 100644 --- a/pymatgen/io/cp2k/inputs.py +++ b/pymatgen/io/cp2k/inputs.py @@ -32,7 +32,7 @@ from collections.abc import Iterable, Sequence from dataclasses import dataclass, field from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING from monty.dev import deprecated from monty.io import zopen @@ -45,6 +45,9 @@ from pymatgen.symmetry.analyzer import SpacegroupAnalyzer if TYPE_CHECKING: + from collections.abc import Sequence + from typing import Any, Literal + from typing_extensions import Self from pymatgen.core.lattice import Lattice diff --git a/pymatgen/io/lammps/data.py b/pymatgen/io/lammps/data.py index 1938d196be9..98730ee2483 100644 --- a/pymatgen/io/lammps/data.py +++ b/pymatgen/io/lammps/data.py @@ -20,7 +20,7 @@ import warnings from io import StringIO from pathlib import Path -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np import pandas as pd @@ -35,7 +35,7 @@ if TYPE_CHECKING: from collections.abc import Sequence - from typing import Any + from typing import Any, Literal from typing_extensions import Self diff --git a/pymatgen/io/lobster/inputs.py b/pymatgen/io/lobster/inputs.py index a19d4ac62c6..2fb1d96295e 100644 --- a/pymatgen/io/lobster/inputs.py +++ b/pymatgen/io/lobster/inputs.py @@ -15,7 +15,7 @@ import re import warnings from collections import UserDict -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np import spglib @@ -30,6 +30,8 @@ from pymatgen.util.due import Doi, due if TYPE_CHECKING: + from typing import Any + from typing_extensions import Self from pymatgen.core.composition import Composition diff --git a/pymatgen/io/lobster/outputs.py b/pymatgen/io/lobster/outputs.py index cb3262b625e..2deb1127286 100644 --- a/pymatgen/io/lobster/outputs.py +++ b/pymatgen/io/lobster/outputs.py @@ -17,7 +17,7 @@ import re import warnings from collections import defaultdict -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.io import zopen @@ -32,6 +32,8 @@ from pymatgen.util.due import Doi, due if TYPE_CHECKING: + from typing import Any + from pymatgen.core.structure import IStructure __author__ = "Janine George, Marco Esters" diff --git a/pymatgen/io/pwscf.py b/pymatgen/io/pwscf.py index edefc0ea0c7..12b865df388 100644 --- a/pymatgen/io/pwscf.py +++ b/pymatgen/io/pwscf.py @@ -4,7 +4,7 @@ import re from collections import defaultdict -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from monty.io import zopen from monty.re import regrep @@ -14,7 +14,7 @@ if TYPE_CHECKING: from pathlib import Path - from typing import ClassVar + from typing import Any, ClassVar from typing_extensions import Self diff --git a/pymatgen/io/qchem/inputs.py b/pymatgen/io/qchem/inputs.py index 6f2071bf1d2..8996477c38e 100644 --- a/pymatgen/io/qchem/inputs.py +++ b/pymatgen/io/qchem/inputs.py @@ -4,7 +4,7 @@ import logging import re -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING from monty.io import zopen @@ -15,6 +15,7 @@ if TYPE_CHECKING: from pathlib import Path + from typing import Literal from typing_extensions import Self diff --git a/pymatgen/io/qchem/outputs.py b/pymatgen/io/qchem/outputs.py index 5c238fe85e2..957880c0a0c 100644 --- a/pymatgen/io/qchem/outputs.py +++ b/pymatgen/io/qchem/outputs.py @@ -9,7 +9,7 @@ import re import struct import warnings -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import networkx as nx import numpy as np @@ -34,6 +34,8 @@ openbabel = None if TYPE_CHECKING: + from typing import Any + from numpy.typing import NDArray __author__ = "Samuel Blau, Brandon Wood, Shyam Dwaraknath, Evan Spotte-Smith, Ryan Kingsbury" diff --git a/pymatgen/io/qchem/sets.py b/pymatgen/io/qchem/sets.py index dbba6a31f71..6b5f7661d99 100644 --- a/pymatgen/io/qchem/sets.py +++ b/pymatgen/io/qchem/sets.py @@ -5,7 +5,7 @@ import logging import os import warnings -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING from monty.io import zopen @@ -13,6 +13,8 @@ from pymatgen.io.qchem.utils import lower_and_check_unique if TYPE_CHECKING: + from typing import Literal + from pymatgen.core.structure import Molecule __author__ = "Samuel Blau, Brandon Wood, Shyam Dwaraknath, Evan Spotte-Smith, Ryan Kingsbury" diff --git a/pymatgen/io/res.py b/pymatgen/io/res.py index 38f7a700596..d2859d24a1d 100644 --- a/pymatgen/io/res.py +++ b/pymatgen/io/res.py @@ -13,7 +13,7 @@ import datetime import re from dataclasses import dataclass -from typing import TYPE_CHECKING, Any, Callable, Literal +from typing import TYPE_CHECKING from monty.io import zopen from monty.json import MSONable @@ -26,6 +26,7 @@ from collections.abc import Iterator from datetime import date from pathlib import Path + from typing import Any, Callable, Literal from typing_extensions import Self diff --git a/pymatgen/io/shengbte.py b/pymatgen/io/shengbte.py index 745c5f04665..0e566b05b3a 100644 --- a/pymatgen/io/shengbte.py +++ b/pymatgen/io/shengbte.py @@ -3,7 +3,7 @@ from __future__ import annotations import warnings -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.dev import requires @@ -12,14 +12,16 @@ from pymatgen.core.structure import Structure from pymatgen.io.vasp import Kpoints -if TYPE_CHECKING: - from typing_extensions import Self - try: import f90nml except ImportError: f90nml = None +if TYPE_CHECKING: + from typing import Any + + from typing_extensions import Self + __author__ = "Rees Chang, Alex Ganose" __copyright__ = "Copyright 2019, The Materials Project" __version__ = "0.1" diff --git a/pymatgen/io/vasp/outputs.py b/pymatgen/io/vasp/outputs.py index 85a96365073..89ac4e85db2 100644 --- a/pymatgen/io/vasp/outputs.py +++ b/pymatgen/io/vasp/outputs.py @@ -16,7 +16,7 @@ from glob import glob from io import StringIO from pathlib import Path -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np from monty.io import reverse_readfile, zopen @@ -43,6 +43,8 @@ from pymatgen.util.num import make_symmetric_matrix_from_upper_tri if TYPE_CHECKING: + from typing import Literal + from typing_extensions import Self logger = logging.getLogger(__name__) diff --git a/pymatgen/io/vasp/sets.py b/pymatgen/io/vasp/sets.py index 469ecccd1a3..88e5e7811f9 100644 --- a/pymatgen/io/vasp/sets.py +++ b/pymatgen/io/vasp/sets.py @@ -40,7 +40,7 @@ from glob import glob from itertools import chain from pathlib import Path -from typing import TYPE_CHECKING, Literal, Union, cast +from typing import TYPE_CHECKING, cast from zipfile import ZipFile import numpy as np @@ -60,12 +60,16 @@ from pymatgen.util.typing import Kpoint if TYPE_CHECKING: - from typing import Any + from typing import Any, Literal, Union from typing_extensions import Self from pymatgen.util.typing import Vector3D + UserPotcarFunctional = Union[ + Literal["PBE", "PBE_52", "PBE_54", "LDA", "LDA_52", "LDA_54", "PW91", "LDA_US", "PW91_US"], None + ] + MODULE_DIR = Path(__file__).resolve().parent # TODO (janosh): replace with following line once PMG is py3.9+ only # which guarantees absolute path to __file__ @@ -247,11 +251,6 @@ def _load_yaml_config(fname): return config -UserPotcarFunctional = Union[ - Literal["PBE", "PBE_52", "PBE_54", "LDA", "LDA_52", "LDA_54", "PW91", "LDA_US", "PW91_US"], None -] - - @dataclass class DictSet(VaspInputSet): """ diff --git a/pymatgen/phonon/bandstructure.py b/pymatgen/phonon/bandstructure.py index abc1c391d4e..56d09582939 100644 --- a/pymatgen/phonon/bandstructure.py +++ b/pymatgen/phonon/bandstructure.py @@ -3,7 +3,7 @@ from __future__ import annotations import json -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -15,6 +15,7 @@ if TYPE_CHECKING: from collections.abc import Sequence from os import PathLike + from typing import Any from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/phonon/plotter.py b/pymatgen/phonon/plotter.py index a9325aa21c1..ad4fb598cef 100644 --- a/pymatgen/phonon/plotter.py +++ b/pymatgen/phonon/plotter.py @@ -3,7 +3,7 @@ from __future__ import annotations import logging -from typing import TYPE_CHECKING, Callable, NamedTuple +from typing import TYPE_CHECKING, NamedTuple import matplotlib.pyplot as plt import numpy as np @@ -19,7 +19,7 @@ if TYPE_CHECKING: from collections.abc import Sequence from os import PathLike - from typing import Any, Literal + from typing import Any, Callable, Literal from matplotlib.axes import Axes from matplotlib.figure import Figure diff --git a/pymatgen/phonon/thermal_displacements.py b/pymatgen/phonon/thermal_displacements.py index f336a510902..3df4e1ff2e0 100644 --- a/pymatgen/phonon/thermal_displacements.py +++ b/pymatgen/phonon/thermal_displacements.py @@ -4,7 +4,7 @@ import re from functools import partial -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import numpy as np from monty.json import MSONable @@ -22,6 +22,7 @@ if TYPE_CHECKING: from os import PathLike + from typing import Literal from numpy.typing import ArrayLike from typing_extensions import Self diff --git a/pymatgen/symmetry/analyzer.py b/pymatgen/symmetry/analyzer.py index 07658794941..8842be66279 100644 --- a/pymatgen/symmetry/analyzer.py +++ b/pymatgen/symmetry/analyzer.py @@ -20,7 +20,7 @@ from fractions import Fraction from functools import lru_cache from math import cos, sin -from typing import TYPE_CHECKING, Any, Literal +from typing import TYPE_CHECKING import numpy as np import scipy.cluster @@ -34,13 +34,16 @@ from pymatgen.util.due import Doi, due if TYPE_CHECKING: + from typing import Any, Literal + from pymatgen.core import Element, Species from pymatgen.core.sites import Site from pymatgen.symmetry.groups import CrystalSystem + LatticeType = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "rhombohedral", "tetragonal", "triclinic"] + logger = logging.getLogger(__name__) -LatticeType = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "rhombohedral", "tetragonal", "triclinic"] cite_conventional_cell_algo = due.dcite( Doi("10.1016/j.commatsci.2010.05.010"), diff --git a/pymatgen/symmetry/groups.py b/pymatgen/symmetry/groups.py index b1040f31355..e68fe464ce1 100644 --- a/pymatgen/symmetry/groups.py +++ b/pymatgen/symmetry/groups.py @@ -12,7 +12,7 @@ from collections.abc import Sequence from fractions import Fraction from itertools import product -from typing import TYPE_CHECKING, ClassVar, Literal, overload +from typing import TYPE_CHECKING, overload import numpy as np from monty.design_patterns import cached_class @@ -21,6 +21,8 @@ from pymatgen.util.string import Stringify if TYPE_CHECKING: + from typing import ClassVar, Literal + from numpy.typing import ArrayLike from typing_extensions import Self @@ -29,9 +31,10 @@ # Don't import at runtime to avoid circular import from pymatgen.core.operations import SymmOp # noqa: TCH004 + CrystalSystem = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "tetragonal", "triclinic", "trigonal"] + SYMM_DATA = loadfn(os.path.join(os.path.dirname(__file__), "symm_data.json")) -CrystalSystem = Literal["cubic", "hexagonal", "monoclinic", "orthorhombic", "tetragonal", "triclinic", "trigonal"] class SymmetryGroup(Sequence, Stringify, ABC): diff --git a/pymatgen/symmetry/kpath.py b/pymatgen/symmetry/kpath.py index cfce933cdfc..88562624430 100644 --- a/pymatgen/symmetry/kpath.py +++ b/pymatgen/symmetry/kpath.py @@ -5,7 +5,7 @@ import abc import itertools from math import ceil, cos, e, pi, sin, tan -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING from warnings import warn import networkx as nx @@ -23,6 +23,8 @@ get_path = None if TYPE_CHECKING: + from typing import Any + from pymatgen.core import Structure from pymatgen.util.typing import SpeciesLike @@ -92,7 +94,7 @@ def get_kpoints(self, line_density=20, coords_are_cartesian=True): distance = np.linalg.norm( self._rec_lattice.get_cartesian_coords(start) - self._rec_lattice.get_cartesian_coords(end) ) - nb = int(ceil(distance * line_density)) + nb = ceil(distance * line_density) if nb == 0: continue sym_point_labels.extend([k_path[path_step - 1]] + [""] * (nb - 1) + [k_path[path_step]]) diff --git a/pymatgen/util/plotting.py b/pymatgen/util/plotting.py index be9de10c08c..13958cc9b22 100644 --- a/pymatgen/util/plotting.py +++ b/pymatgen/util/plotting.py @@ -6,7 +6,7 @@ import math from functools import wraps from string import ascii_letters -from typing import TYPE_CHECKING, Literal +from typing import TYPE_CHECKING import matplotlib.pyplot as plt import numpy as np @@ -17,6 +17,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Literal from matplotlib.axes import Axes from matplotlib.figure import Figure diff --git a/pymatgen/util/testing/__init__.py b/pymatgen/util/testing/__init__.py index 8c9ce59233f..c95fff8eada 100644 --- a/pymatgen/util/testing/__init__.py +++ b/pymatgen/util/testing/__init__.py @@ -11,7 +11,7 @@ import pickle # use pickle, not cPickle so that we get the traceback in case of errors import string from pathlib import Path -from typing import TYPE_CHECKING, Any, ClassVar +from typing import TYPE_CHECKING from unittest import TestCase import pytest @@ -22,6 +22,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import Any, ClassVar MODULE_DIR = Path(__file__).absolute().parent STRUCTURES_DIR = MODULE_DIR / ".." / "structures" diff --git a/pymatgen/vis/structure_vtk.py b/pymatgen/vis/structure_vtk.py index 94fa31a9bf0..cedb7b54941 100644 --- a/pymatgen/vis/structure_vtk.py +++ b/pymatgen/vis/structure_vtk.py @@ -7,7 +7,7 @@ import os import subprocess import time -from typing import TYPE_CHECKING, ClassVar +from typing import TYPE_CHECKING import numpy as np from monty.dev import requires @@ -26,6 +26,7 @@ if TYPE_CHECKING: from collections.abc import Sequence + from typing import ClassVar module_dir = os.path.dirname(os.path.abspath(__file__)) EL_COLORS = loadfn(f"{module_dir}/ElementColorSchemes.yaml") diff --git a/tests/util/test_typing.py b/tests/util/test_typing.py index 6112e05a933..ec04deffbb7 100644 --- a/tests/util/test_typing.py +++ b/tests/util/test_typing.py @@ -7,7 +7,7 @@ import sys from pathlib import Path from types import GenericAlias -from typing import Any, get_args +from typing import TYPE_CHECKING, get_args import pytest @@ -15,6 +15,9 @@ from pymatgen.entries import Entry from pymatgen.util.typing import CompositionLike, EntryLike, PathLike, PbcLike, SpeciesLike +if TYPE_CHECKING: + from typing import Any + __author__ = "Janosh Riebesell" __date__ = "2022-10-20" __email__ = "janosh@lbl.gov"