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

Move needlessly function-scoped imports to module scope #3462

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
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ ci:

repos:
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.1.4
rev: v0.1.5
hooks:
- id: ruff
args: [--fix]
Expand Down
3 changes: 1 addition & 2 deletions dev_scripts/regen_libxcfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import json
import os
import sys
from copy import deepcopy


def parse_libxc_docs(path):
Expand Down Expand Up @@ -46,8 +47,6 @@ def parse_section(section):

def write_libxc_docs_json(xcfuncs, jpath):
"""Write json file with libxc metadata to path jpath."""
from copy import deepcopy

xcfuncs = deepcopy(xcfuncs)

# Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable.
Expand Down
9 changes: 3 additions & 6 deletions dev_scripts/update_pt_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,13 @@

from __future__ import annotations

import collections
import json
import re
from itertools import product

import requests
from bs4 import BeautifulSoup
from monty.serialization import dumpfn, loadfn
from ruamel import yaml

Expand Down Expand Up @@ -160,7 +163,6 @@ def update_ionic_radii():
def parse_shannon_radii():
with open("periodic_table.yaml") as f:
data = yaml.load(f)
import collections

from openpyxl import load_workbook

Expand Down Expand Up @@ -250,8 +252,6 @@ def gen_iupac_ordering():

def add_electron_affinities():
"""Update the periodic table data file with electron affinities."""
import requests
from bs4 import BeautifulSoup

req = requests.get("https://wikipedia.org/wiki/Electron_affinity_(data_page)")
soup = BeautifulSoup(req.text, "html.parser")
Expand All @@ -276,9 +276,6 @@ def add_electron_affinities():

def add_ionization_energies():
"""Update the periodic table data file with ground level and ionization energies from NIST."""
import collections

from bs4 import BeautifulSoup

with open("NIST Atomic Ionization Energies Output.html") as f:
soup = BeautifulSoup(f.read(), "html.parser")
Expand Down
4 changes: 2 additions & 2 deletions docs/apidoc/conf.py

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions pymatgen/analysis/bond_valence.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ class BVAnalyzer:
is selected.
"""

CHARGE_NEUTRALITY_TOLERANCE = 0.00001
CHARGE_NEUTRALITY_TOLERANCE = 0.000_01

def __init__(
self,
symm_tol=0.1,
max_radius=4,
max_permutations=100000,
max_permutations=100_000,
distance_scale_factor=1.015,
charge_neutrality_tolerance=CHARGE_NEUTRALITY_TOLERANCE,
forbidden_species=None,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import itertools
import logging

import matplotlib.pyplot as plt
import networkx as nx
import numpy as np
from matplotlib.patches import Circle, FancyArrowPatch
Expand Down Expand Up @@ -533,7 +534,6 @@ def show_graph(
If not provided, the graph is not saved.
drawing_type (str): The type of drawing to use. Can be "internal" or "external".
"""
import matplotlib.pyplot as plt

shown_graph = self._connected_subgraph if graph is None else graph

Expand All @@ -550,12 +550,8 @@ def show_graph(
plt.savefig(save_file)
# nx.draw(self._connected_subgraph)
elif drawing_type == "draw_graphviz":
import networkx as nx

nx.nx_pydot.graphviz_layout(shown_graph)
elif drawing_type == "draw_random":
import networkx as nx

nx.draw_random(shown_graph)

@property
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -697,15 +697,15 @@ def pauling_stability_ratio(self):
if self.ce_symbol in ["S:1", "L:2"]:
self._pauling_stability_ratio = 0.0
else:
min_dist_anions = 1000000.0
min_dist_cation_anion = 1000000.0
min_dist_anions = 1_000_000
min_dist_cation_anion = 1_000_000
for ipt1 in range(len(self.points)):
pt1 = np.array(self.points[ipt1])
min_dist_cation_anion = min(min_dist_cation_anion, np.linalg.norm(pt1 - self.central_site))
for ipt2 in range(ipt1 + 1, len(self.points)):
pt2 = np.array(self.points[ipt2])
min_dist_anions = min(min_dist_anions, np.linalg.norm(pt1 - pt2))
anion_radius = min_dist_anions / 2.0
anion_radius = min_dist_anions / 2
cation_radius = min_dist_cation_anion - anion_radius
self._pauling_stability_ratio = cation_radius / anion_radius
return self._pauling_stability_ratio
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@

from __future__ import annotations

from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from matplotlib.colors import Normalize
from matplotlib.gridspec import GridSpec
from matplotlib.patches import Polygon
from monty.json import MontyDecoder, MSONable, jsanitize

from pymatgen.analysis.chemenv.coordination_environments.coordination_geometries import AllCoordinationGeometries
Expand All @@ -19,9 +22,6 @@
from pymatgen.analysis.chemenv.utils.defs_utils import AdditionalConditions
from pymatgen.core import Element, PeriodicNeighbor, PeriodicSite, Species, Structure

if TYPE_CHECKING:
import matplotlib.pyplot as plt

__author__ = "David Waroquiers"
__copyright__ = "Copyright 2012, The Materials Project"
__credits__ = "Geoffroy Hautier"
Expand Down Expand Up @@ -645,11 +645,6 @@ def plot_csm_and_maps(self, isite, max_csm=8.0):
isite: Index of the site for which the plot has to be done
max_csm: Maximum continuous symmetry measure to be shown.
"""
try:
import matplotlib.pyplot as plt
except ImportError:
print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
return
fig = self.get_csm_and_maps(isite=isite, max_csm=max_csm)
if fig is None:
return
Expand All @@ -673,13 +668,6 @@ def get_csm_and_maps(
Returns:
Matplotlib figure and axes representing the CSM and maps.
"""
try:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
except ImportError:
print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
return None

if symmetry_measure_type is None:
symmetry_measure_type = "csm_wcs_ctwcc"
# Initializes the figure
Expand Down Expand Up @@ -826,15 +814,6 @@ def get_environments_figure(
Returns:
tuple[plt.Figure, plt.Axes]: matplotlib figure and axes representing the environments.
"""
try:
import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.colors import Normalize
from matplotlib.patches import Polygon
except ImportError:
print('Plotting Chemical Environments requires matplotlib ... exiting "plot" function')
return None

# Initializes the figure
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import logging
import time

import matplotlib.pyplot as plt
import numpy as np
from monty.json import MSONable
from scipy.spatial import Voronoi
Expand Down Expand Up @@ -793,8 +794,6 @@ def get_rdf_figure(self, isite, normalized=True, figsize=None, step_function=Non
def dp_func(dp):
return 1.0 - 1.0 / np.power(dp, 3.0)

import matplotlib.pyplot as plt

if step_function is None:
step_function = {"type": "normal_cdf", "scale": 0.0001}

Expand Down Expand Up @@ -845,8 +844,6 @@ def get_sadf_figure(self, isite, normalized=True, figsize=None, step_function=No
def ap_func(ap):
return np.power(ap, -0.1)

import matplotlib.pyplot as plt

if step_function is None:
step_function = {"type": "step_function", "scale": 0.0001}

Expand Down
3 changes: 1 addition & 2 deletions pymatgen/analysis/diffraction/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import collections
from typing import TYPE_CHECKING

import matplotlib.pyplot as plt
import numpy as np
from matplotlib import pyplot as plt

from pymatgen.core.spectrum import Spectrum
from pymatgen.util.plotting import add_fig_kwargs, pretty_plot
Expand Down Expand Up @@ -186,7 +186,6 @@ def plot_structures(self, structures, fontsize=6, **kwargs):
long version, e.g. (1, 0, 0). If None, do not show anything.
fontsize: (int) fontsize for peak labels.
"""
import matplotlib.pyplot as plt

nrows = len(structures)
fig, axes = plt.subplots(nrows=nrows, ncols=1, sharex=True, squeeze=False)
Expand Down
5 changes: 1 addition & 4 deletions pymatgen/analysis/dimensionality.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
import itertools
from collections import defaultdict

import networkx as nx
import numpy as np
from networkx.readwrite import json_graph

Expand Down Expand Up @@ -121,8 +122,6 @@ def get_structure_components(
- "molecule_graph": If inc_molecule_graph is `True`, the site a
MoleculeGraph object for zero-dimensional components.
"""
import networkx as nx # optional dependency therefore not top level import

comp_graphs = (bonded_structure.graph.subgraph(c) for c in nx.weakly_connected_components(bonded_structure.graph))

components = []
Expand Down Expand Up @@ -261,8 +260,6 @@ def zero_d_graph_to_molecule_graph(bonded_structure, graph):
Returns:
(MoleculeGraph): A MoleculeGraph object of the component.
"""
import networkx as nx

seen_indices = []
sites = []

Expand Down
10 changes: 4 additions & 6 deletions pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""
This module implements various equation of states.
"""This module implements various equation of states.

Note: Most of the code were initially adapted from ASE and deltafactor by
@gmatteo but has since undergone major refactoring.
Expand All @@ -20,7 +19,7 @@
from pymatgen.util.plotting import add_fig_kwargs, get_ax_fig, pretty_plot

if TYPE_CHECKING:
from matplotlib import pyplot as plt
import matplotlib.pyplot as plt

__author__ = "Kiran Mathew, gmatteo"
__credits__ = "Cormac Toher"
Expand Down Expand Up @@ -426,12 +425,11 @@ def fit(self, min_ndata_factor=3, max_poly_order_factor=5, min_poly_order=2):
Args:
min_ndata_factor (int): parameter that controls the minimum number
of data points that will be used for fitting.
minimum number of data points =
total data points-2*min_ndata_factor
minimum number of data points = total data points-2*min_ndata_factor
max_poly_order_factor (int): parameter that limits the max order
of the polynomial used for fitting.
max_poly_order = number of data points used for fitting -
max_poly_order_factor
max_poly_order_factor
min_poly_order (int): minimum order of the polynomial to be
considered for fitting.
"""
Expand Down
4 changes: 1 addition & 3 deletions pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1041,9 +1041,7 @@ def as_dict(self):

@classmethod
def from_dict(cls, d):
"""
As in pymatgen.core.Structure except
restoring graphs using `from_dict_of_dicts`
"""As in pymatgen.core.Structure except restoring graphs using from_dict_of_dicts
from NetworkX to restore graph information.
"""
struct = Structure.from_dict(d["structure"])
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -301,7 +301,7 @@ def get_cn(
'take_max_species' will use Fe as the site specie.

Returns:
cn (int or float): coordination number.
cn (float): coordination number.
"""
structure = _handle_disorder(structure, on_disorder)
siw = self.get_nn_info(structure, n)
Expand Down Expand Up @@ -4009,7 +4009,7 @@ def get_cn(self, structure: Structure, n: int, **kwargs) -> float: # type: igno
'take_max_species' will use Fe as the site specie.

Returns:
cn (int or float): coordination number.
cn (float): coordination number.
"""
use_weights = kwargs.get("use_weights", False)
if self.weighted_cn != use_weights:
Expand Down
Loading