Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Module-scoped imports #3464

Merged
merged 4 commits into from
Nov 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion pymatgen/analysis/diffraction/neutron.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,6 @@ class NDCalculator(AbstractDiffractionPatternCalculator):
Reference:
Marc De Graef and Michael E. McHenry, Structure of Materials 2nd ed,
Chapter13, Cambridge University Press 2003.

"""

def __init__(self, wavelength=1.54184, symprec: float = 0, debye_waller_factors=None):
Expand Down
9 changes: 3 additions & 6 deletions pymatgen/analysis/ewald.py
Original file line number Diff line number Diff line change
Expand Up @@ -496,12 +496,9 @@ class EwaldMinimizer:
ALGO_FAST = 0
ALGO_COMPLETE = 1
ALGO_BEST_FIRST = 2

"""
ALGO_TIME_LIMIT: Slowly increases the speed (with the cost of decreasing
accuracy) as the minimizer runs. Attempts to limit the run time to
approximately 30 minutes.
"""
# ALGO_TIME_LIMIT: Slowly increases the speed (with the cost of decreasing
# accuracy) as the minimizer runs. Attempts to limit the run time to
# approximately 30 minutes.
ALGO_TIME_LIMIT = 3

def __init__(self, matrix, m_list, num_to_return=1, algo=ALGO_FAST):
Expand Down
18 changes: 6 additions & 12 deletions pymatgen/analysis/ferroelectricity/polarization.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
from __future__ import annotations

import numpy as np
from scipy.interpolate import UnivariateSpline

from pymatgen.core.lattice import Lattice
from pymatgen.core.structure import Structure
Expand Down Expand Up @@ -131,19 +132,16 @@ def get_nearest_site(self, coords, site, r=None):

class Polarization:
"""
Class for recovering the same branch polarization for a set of
polarization calculations along the nonpolar - polar distortion
path of a ferroelectric.
Class for recovering the same branch polarization for a set of polarization
calculations along the nonpolar - polar distortion path of a ferroelectric.

p_elecs, p_ions, and structures lists should be given in order
of nonpolar to polar! For example, the structures returned from:
nonpolar.interpolate(polar,interpolate_lattices=True)
if nonpolar is the nonpolar Structure and polar is the polar structure.

It is assumed that the electronic and ionic dipole moment values
are given in electron Angstroms along the three lattice directions
(a,b,c).

It is assumed that the electronic and ionic dipole moment values are given in
electron Angstroms along the three lattice directions (a,b,c).
"""

def __init__(
Expand Down Expand Up @@ -371,10 +369,8 @@ def get_polarization_change_norm(self, convert_to_muC_per_cm2=True, all_in_polar
def same_branch_splines(self, convert_to_muC_per_cm2=True, all_in_polar=True):
"""
Fit splines to same branch polarization. This is used to assess any jumps
in the same branch polarizaiton.
in the same branch polarization.
"""
from scipy.interpolate import UnivariateSpline

tot = self.get_same_branch_polarization_data(
convert_to_muC_per_cm2=convert_to_muC_per_cm2, all_in_polar=all_in_polar
)
Expand Down Expand Up @@ -430,8 +426,6 @@ def __init__(self, energies):

def spline(self):
"""Fit spline to energy trend data."""
from scipy.interpolate import UnivariateSpline

return UnivariateSpline(range(len(self.energies)), self.energies, k=4)

def smoothness(self):
Expand Down
12 changes: 4 additions & 8 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -4310,9 +4310,8 @@ def get_bonded_structure(self, structure: Structure, decorate: bool = False) ->
Returns:
StructureGraph: Bonded structure
"""
# not a top-level import because critic2 is an optional
# dependency, only want to raise an import error if
# Critic2NN() is used
# not a top-level import because critic2 is an optional dependency, only want
# to raise an import error if Critic2NN() is used
from pymatgen.command_line.critic2_caller import Critic2Caller

if structure == self.__last_structure:
Expand All @@ -4337,13 +4336,11 @@ def get_nn_info(self, structure: Structure, n: int):

Args:
structure (Structure): input structure.
n (int): index of site for which to determine near-neighbor
sites.
n (int): index of site for which to determine near-neighbor sites.

Returns:
siw (list of tuples (Site, array, float)): tuples, each one
of which represents a coordinated site, its image location,
and its weight.
of which represents a coordinated site, its image location, and its weight.
"""
sg = self.get_bonded_structure(structure)

Expand Down Expand Up @@ -4411,7 +4408,6 @@ def metal_edge_extender(
Returns:
mol_graph: pymatgen.analysis.graphs.MoleculeGraph object with additional
metal bonds (if any found) added

"""
if metals is None:
metals = []
Expand Down
9 changes: 2 additions & 7 deletions pymatgen/analysis/pourbaix_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,17 +12,12 @@
from copy import deepcopy
from functools import cmp_to_key, partial
from multiprocessing import Pool
from typing import TYPE_CHECKING, Any, no_type_check

import numpy as np
from monty.json import MontyDecoder, MSONable
from scipy.spatial import ConvexHull, HalfspaceIntersection

try:
from scipy.special import comb
except ImportError:
from scipy.misc import comb

from typing import TYPE_CHECKING, Any, no_type_check
from scipy.special import comb

from pymatgen.analysis.phase_diagram import PDEntry, PhaseDiagram
from pymatgen.analysis.reaction_calculator import Reaction, ReactionError
Expand Down
1 change: 0 additions & 1 deletion pymatgen/analysis/quasirrho.py
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ class QuasiRRHO:
free_energy_ho (float): Free energy calculated without the Quasi-RRHO
method, i.e. with a harmonic oscillator approximation for the
vibrational entropy [Ha]

"""

def __init__(
Expand Down
1 change: 0 additions & 1 deletion pymatgen/analysis/solar/slme.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,6 @@ def slme(

Returns:
The calculated maximum efficiency.

"""
# Defining constants for tidy equations
c = constants.c # speed of light, m/s
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from monty.json import MSONable
from numpy import dot, pi, transpose
from numpy.linalg import inv
from scipy.spatial import Voronoi

from pymatgen.util.coord import pbc_shortest_vectors
from pymatgen.util.due import Doi, due
Expand Down Expand Up @@ -1222,8 +1223,6 @@ def get_wigner_seitz_cell(self) -> list[list[np.ndarray]]:
for ii, jj, kk in itertools.product([-1, 0, 1], [-1, 0, 1], [-1, 0, 1]):
list_k_points.append(ii * vec1 + jj * vec2 + kk * vec3)

from scipy.spatial import Voronoi

tess = Voronoi(list_k_points)
out = []
for r in tess.ridge_dict:
Expand Down
13 changes: 3 additions & 10 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@
from numpy import cross, eye
from numpy.linalg import norm
from ruamel.yaml import YAML
from scipy.linalg import expm
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.linalg import expm, polar
from scipy.spatial.distance import squareform
from tabulate import tabulate

from pymatgen.core.bonds import CovalentBond, get_bond_length
Expand Down Expand Up @@ -2218,8 +2220,6 @@ def interpolate(

if interpolate_lattices:
# interpolate lattice matrices using polar decomposition
from scipy.linalg import polar

# u is a unitary rotation, p is stretch
u, p = polar(np.dot(end_structure.lattice.matrix.T, np.linalg.inv(self.lattice.matrix.T)))
lvec = p - np.identity(3)
Expand Down Expand Up @@ -4235,9 +4235,6 @@ def merge_sites(self, tol: float = 0.01, mode: Literal["sum", "delete", "average
"average" means that the site is deleted but the properties are averaged
Only first letter is considered.
"""
from scipy.cluster.hierarchy import fcluster, linkage
from scipy.spatial.distance import squareform

dist_mat = self.distance_matrix
np.fill_diagonal(dist_mat, 0)
clusters = fcluster(linkage(squareform((dist_mat + dist_mat.T) / 2)), tol, "distance")
Expand Down Expand Up @@ -4632,10 +4629,6 @@ def rotate_sites(
axis (3x1 array): Rotation axis vector.
anchor (3x1 array): Point of rotation.
"""
from numpy import cross, eye
from numpy.linalg import norm
from scipy.linalg import expm

if indices is None:
indices = range(len(self))

Expand Down
4 changes: 1 addition & 3 deletions pymatgen/core/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -735,12 +735,10 @@ def unitized(unit):
Args:
unit: Specific unit (eV, Ha, m, ang, etc.).

Example usage::

Example:
@unitized(unit="kg")
def get_mass():
return 123.45

"""

def wrap(func):
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/electronic_structure/boltztrap.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from monty.json import MSONable, jsanitize
from monty.os import cd
from scipy import constants
from scipy.optimize import fsolve
from scipy.spatial import distance

from pymatgen.core.lattice import Lattice
Expand Down Expand Up @@ -2264,8 +2265,6 @@ def eta_from_seebeck(seeb, Lambda):
Returns:
float: eta where the two seebeck coefficients are equal (reduced chemical potential).
"""
from scipy.optimize import fsolve

out = fsolve(lambda x: (seebeck_spb(x, Lambda) - abs(seeb)) ** 2, 1.0, full_output=True)
return out[0][0]

Expand Down
17 changes: 8 additions & 9 deletions pymatgen/electronic_structure/dos.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import numpy as np
from monty.json import MSONable
from scipy.constants import value as _cd
from scipy.ndimage import gaussian_filter1d
from scipy.signal import hilbert

from pymatgen.core import Structure, get_el_sp
Expand Down Expand Up @@ -220,13 +221,11 @@ def get_smeared_densities(self, sigma: float):
Returns:
Dict of Gaussian-smeared densities.
"""
from scipy.ndimage import gaussian_filter1d

smeared_dens = {}
diff = [self.energies[i + 1] - self.energies[i] for i in range(len(self.energies) - 1)]
avgdiff = sum(diff) / len(diff)
avg_diff = sum(diff) / len(diff)
for spin, dens in self.densities.items():
smeared_dens[spin] = gaussian_filter1d(dens, sigma / avgdiff)
smeared_dens[spin] = gaussian_filter1d(dens, sigma / avg_diff)
return smeared_dens

def __add__(self, other):
Expand Down Expand Up @@ -343,14 +342,14 @@ def get_gap(self, tol: float = 0.001, abs_tol: bool = False, spin: Spin | None =
def __str__(self):
"""Returns a string which can be easily plotted (using gnuplot)."""
if Spin.down in self.densities:
stringarray = [f"#{'Energy':30s} {'DensityUp':30s} {'DensityDown':30s}"]
str_arr = [f"#{'Energy':30s} {'DensityUp':30s} {'DensityDown':30s}"]
for i, energy in enumerate(self.energies):
stringarray.append(f"{energy:.5f} {self.densities[Spin.up][i]:.5f} {self.densities[Spin.down][i]:.5f}")
str_arr.append(f"{energy:.5f} {self.densities[Spin.up][i]:.5f} {self.densities[Spin.down][i]:.5f}")
else:
stringarray = [f"#{'Energy':30s} {'DensityUp':30s}"]
str_arr = [f"#{'Energy':30s} {'DensityUp':30s}"]
for i, energy in enumerate(self.energies):
stringarray.append(f"{energy:.5f} {self.densities[Spin.up][i]:.5f}")
return "\n".join(stringarray)
str_arr.append(f"{energy:.5f} {self.densities[Spin.up][i]:.5f}")
return "\n".join(str_arr)

@classmethod
def from_dict(cls, d) -> Dos:
Expand Down
5 changes: 2 additions & 3 deletions pymatgen/electronic_structure/plotter.py
Original file line number Diff line number Diff line change
Expand Up @@ -4217,7 +4217,7 @@ def plot_points(points, lattice=None, coords_are_cartesian=False, fold=False, ax


@add_fig_kwargs
def plot_brillouin_zone_from_kpath(kpath, ax: plt.Axes = None, **kwargs):
def plot_brillouin_zone_from_kpath(kpath, ax: plt.Axes = None, **kwargs) -> plt.Axes:
"""Gives the plot (as a matplotlib object) of the symmetry line path in
the Brillouin Zone.

Expand All @@ -4227,8 +4227,7 @@ def plot_brillouin_zone_from_kpath(kpath, ax: plt.Axes = None, **kwargs):
**kwargs: provided by add_fig_kwargs decorator

Returns:
matplotlib figure

plt.Axes: matplotlib Axes
"""
lines = [[kpath.kpath["kpoints"][k] for k in p] for p in kpath.kpath["path"]]
return plot_brillouin_zone(
Expand Down
1 change: 0 additions & 1 deletion pymatgen/entries/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ class Entry(MSONable, metaclass=ABCMeta):
a specific chemical composition. This base class is not
intended to be instantiated directly. Note that classes
which inherit from Entry must define a .energy property.

"""

def __init__(self, composition: Composition | str | dict[str, float], energy: float) -> None:
Expand Down
17 changes: 7 additions & 10 deletions pymatgen/entries/compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -206,7 +206,7 @@ def get_correction(self, entry) -> ufloat:
# set error to 0 because old MPCompatibility doesn't have errors

# only correct GGA or GGA+U entries
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
return ufloat(0.0, 0.0)

rform = entry.composition.reduced_formula
Expand Down Expand Up @@ -253,7 +253,7 @@ def get_correction(self, entry) -> ufloat:
correction = ufloat(0.0, 0.0)

# only correct GGA or GGA+U entries
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
return ufloat(0.0, 0.0)

# Check for sulfide corrections
Expand Down Expand Up @@ -347,14 +347,12 @@ def get_correction(self, entry) -> ufloat:
Returns:
Correction, Uncertainty.
"""
from pymatgen.analysis.pourbaix_diagram import MU_H2O

comp = entry.composition
rform = comp.reduced_formula
cpd_energies = self.cpd_energies

# only correct GGA or GGA+U entries
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
return ufloat(0.0, 0.0)

correction = ufloat(0.0, 0.0)
Expand Down Expand Up @@ -467,21 +465,20 @@ def get_correction(self, entry) -> ufloat:
Returns:
Correction, Uncertainty.
"""
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
raise CompatibilityError(
f"Entry {entry.entry_id} has invalid run type {entry.parameters.get('run_type')}. Discarding."
)

calc_u = entry.parameters.get("hubbards")
calc_u = defaultdict(int) if calc_u is None else calc_u
calc_u = entry.parameters.get("hubbards") or defaultdict(int)
comp = entry.composition

elements = sorted((el for el in comp.elements if comp[el] > 0), key=lambda el: el.X)
most_electroneg = elements[-1].symbol
correction = ufloat(0.0, 0.0)

# only correct GGA or GGA+U entries
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
return ufloat(0.0, 0.0)

u_corr = self.u_corrections.get(most_electroneg, {})
Expand Down Expand Up @@ -934,7 +931,7 @@ def get_adjustments(self, entry: AnyComputedEntry) -> list[EnergyAdjustment]:
Raises:
CompatibilityError if the entry is not compatible
"""
if entry.parameters.get("run_type") not in ["GGA", "GGA+U"]:
if entry.parameters.get("run_type") not in ("GGA", "GGA+U"):
raise CompatibilityError(
f"Entry {entry.entry_id} has invalid run type {entry.parameters.get('run_type')}. "
f"Must be GGA or GGA+U. Discarding."
Expand Down
3 changes: 1 addition & 2 deletions pymatgen/ext/matproj_legacy.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
from pymatgen.core import SETTINGS, Composition, Element, Structure
from pymatgen.core import __version__ as PMG_VERSION
from pymatgen.core.surface import get_symmetrically_equivalent_miller_indices
from pymatgen.entries.compatibility import MaterialsProject2020Compatibility
from pymatgen.entries.computed_entries import ComputedEntry, ComputedStructureEntry
from pymatgen.entries.exp_entries import ExpEntry
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
Expand Down Expand Up @@ -557,8 +558,6 @@ def get_entries(
)
entries.append(e)
if compatible_only:
from pymatgen.entries.compatibility import MaterialsProject2020Compatibility

# suppress the warning about missing oxidation states
with warnings.catch_warnings():
warnings.filterwarnings("ignore", message="Failed to guess oxidation states.*")
Expand Down
Loading