Skip to content

Commit

Permalink
Merge remote-tracking branch 'trunk/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
gmatteo committed Nov 16, 2023
2 parents b4920a9 + bc5edc5 commit 7cdfcbf
Show file tree
Hide file tree
Showing 75 changed files with 624 additions and 530 deletions.
9 changes: 4 additions & 5 deletions dev_scripts/potcar_scrambler.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import warnings

import numpy as np
from monty.os.path import zpath
from monty.serialization import zopen

from pymatgen.core import SETTINGS
Expand Down Expand Up @@ -51,7 +52,7 @@ def _rand_float_from_str_with_prec(self, input_str: str, bloat: float = 1.5):
def _read_fortran_str_and_scramble(self, input_str: str, bloat: float = 1.5):
input_str = input_str.strip()

if input_str.lower() in ["t", "f"] or input_str.lower() in ["true", "false"]:
if input_str.lower() in ("t", "f", "true", "false"):
return bool(np.random.randint(2))

if input_str.upper() == input_str.lower() and input_str[0].isnumeric():
Expand Down Expand Up @@ -128,10 +129,8 @@ def generate_fake_potcar_libraries():
for psp_name in psp_variants:
rebase_dir = f"{output_dir}/{func_dir}/{psp_name}/"
paths_to_try = [
f"{func_dir}/POTCAR.{psp_name}",
f"{func_dir}/POTCAR.{psp_name}.gz",
f"{func_dir}/{psp_name}/POTCAR",
f"{func_dir}/{psp_name}/POTCAR.gz",
zpath(f"{func_dir}/POTCAR.{psp_name}"),
zpath(f"{func_dir}/{psp_name}/POTCAR"),
]
if not any(map(os.path.isfile, paths_to_try)):
warnings.warn(f"Could not find {psp_name} in {paths_to_try}")
Expand Down
37 changes: 21 additions & 16 deletions pymatgen/analysis/chemenv/connectivity/connected_components.py
Original file line number Diff line number Diff line change
Expand Up @@ -574,32 +574,28 @@ def is_0d(self) -> bool:
"""Whether this connected component is 0-dimensional."""
if self._periodicity_vectors is None:
self.compute_periodicity()
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
return len(self._periodicity_vectors) == 0
return len(self._periodicity_vectors) == 0 # type: ignore[arg-type]

@property
def is_1d(self) -> bool:
"""Whether this connected component is 1-dimensional."""
if self._periodicity_vectors is None:
self.compute_periodicity()
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
return len(self._periodicity_vectors) == 1
return len(self._periodicity_vectors) == 1 # type: ignore[arg-type]

@property
def is_2d(self) -> bool:
"""Whether this connected component is 2-dimensional."""
if self._periodicity_vectors is None:
self.compute_periodicity()
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
return len(self._periodicity_vectors) == 2
return len(self._periodicity_vectors) == 2 # type: ignore[arg-type]

@property
def is_3d(self) -> bool:
"""Whether this connected component is 3-dimensional."""
if self._periodicity_vectors is None:
self.compute_periodicity()
assert self._periodicity_vectors is not None # fix mypy arg 1 to len has incompatible type Optional
return len(self._periodicity_vectors) == 3
return len(self._periodicity_vectors) == 3 # type: ignore[arg-type]

@staticmethod
def _order_vectors(vectors):
Expand Down Expand Up @@ -654,10 +650,10 @@ def elastic_centered_graph(self, start_node=None):
logging.info("In elastic centering")
# Loop on start_nodes, sometimes some nodes cannot be elastically taken
# inside the cell if you start from a specific node
ntest_nodes = 0
n_test_nodes = 0
start_node = next(iter(self.graph.nodes()))

ntest_nodes += 1
n_test_nodes += 1
centered_connected_subgraph = nx.MultiGraph()
centered_connected_subgraph.add_nodes_from(self.graph.nodes())
centered_connected_subgraph.add_edges_from(self.graph.edges(data=True))
Expand Down Expand Up @@ -782,12 +778,21 @@ def _retuplify_edgedata(edata):
"""
Private method used to cast back lists to tuples where applicable in an edge data.
The format of the edge data is :
{'start': STARTINDEX, 'end': ENDINDEX, 'delta': TUPLE(DELTAX, DELTAY, DELTAZ),
'ligands': [TUPLE(LIGAND_1_INDEX, TUPLE(DELTAX_START_LIG_1, DELTAY_START_LIG_1, DELTAZ_START_LIG_1),
TUPLE(DELTAX_END_LIG_1, DELTAY_END_LIG_1, DELTAZ_END_LIG_1)),
TUPLE(LIGAND_2_INDEX, ...),
... ]}
The format of the edge data is:
{
"start": STARTINDEX,
"end": ENDINDEX,
"delta": TUPLE(DELTAX, DELTAY, DELTAZ),
"ligands": [
TUPLE(
LIGAND_1_INDEX,
TUPLE(DELTAX_START_LIG_1, DELTAY_START_LIG_1, DELTAZ_START_LIG_1),
TUPLE(DELTAX_END_LIG_1, DELTAY_END_LIG_1, DELTAZ_END_LIG_1),
),
TUPLE(LIGAND_2_INDEX, ...),
...,
],
}
When serializing to json/bson, these tuples are transformed into lists. This method transforms these lists
back to tuples.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1191,8 +1191,7 @@ def get_coordination_symmetry_measures(self, only_minimum=True, all_csms=True, o
def _update_results_all_csms(self, result_dict, permutations, imin, geometry):
permutation = permutations[imin]
# Without central site, centered on the centroid (centroid does not include the central site)
# result_dict[geometry.mp_symbol]['csm_wocs_ctwocc'] = \
# result[imin]
# result_dict[geometry.mp_symbol]['csm_wocs_ctwocc'] = result[imin]
pdist = self.local_geometry.points_wocs_ctwocc(permutation=permutation)
pperf = self.perfect_geometry.points_wocs_ctwocc()
sm_info = symmetry_measure(points_distorted=pdist, points_perfect=pperf)
Expand Down Expand Up @@ -1585,9 +1584,9 @@ def coordination_geometry_symmetry_measures_separation_plane_optim(
Returns:
tuple: Continuous symmetry measures for the given coordination geometry for each plane and permutation
investigated, corresponding permutations, corresponding algorithms,
corresponding mappings from local to perfect environment and corresponding mappings
from perfect to local environment.
investigated, corresponding permutations, corresponding algorithms,
corresponding mappings from local to perfect environment and corresponding mappings
from perfect to local environment.
"""
if optimization == 2:
logging.log(level=5, msg="... using optimization = 2")
Expand Down
28 changes: 14 additions & 14 deletions pymatgen/analysis/chemenv/utils/coordination_geometry_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,23 +205,23 @@ def diamond_functions(xx, yy, y_x0, x_y0):
Returns:
A dictionary with the lower and upper diamond functions.
"""
npxx = np.array(xx)
npyy = np.array(yy)
if np.any(npxx == npyy):
np_xx = np.array(xx)
np_yy = np.array(yy)
if np.any(np_xx == np_yy):
raise RuntimeError("Invalid points for diamond_functions")
if np.all(npxx < npyy) or np.all(npxx > npyy):
if npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
if np.all(np_xx < np_yy) or np.all(np_xx > np_yy):
if np_xx[0] < np_yy[0]:
p1 = np_xx
p2 = np_yy
else:
p1 = npyy
p2 = npxx
elif npxx[0] < npyy[0]:
p1 = npxx
p2 = npyy
p1 = np_yy
p2 = np_xx
elif np_xx[0] < np_yy[0]:
p1 = np_xx
p2 = np_yy
else:
p1 = npyy
p2 = npxx
p1 = np_yy
p2 = np_xx
slope = (p2[1] - p1[1]) / (p2[0] - p1[0])
if slope > 0.0:
x_bpoint = p1[0] + x_y0
Expand Down
10 changes: 2 additions & 8 deletions pymatgen/analysis/elasticity/stress.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,7 @@ def piola_kirchoff_1(self, def_grad):
def_grad (3x3 array-like): deformation gradient tensor
"""
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
raise ValueError("The stress tensor is not symmetric, PK stress is based on a symmetric stress tensor.")
def_grad = SquareTensor(def_grad)
return def_grad.det * np.dot(self, def_grad.inv.trans)

Expand All @@ -97,8 +94,5 @@ def piola_kirchoff_2(self, def_grad):
"""
def_grad = SquareTensor(def_grad)
if not self.is_symmetric:
raise ValueError(
"The stress tensor is not symmetric, \
PK stress is based on a symmetric stress tensor."
)
raise ValueError("The stress tensor is not symmetric, PK stress is based on a symmetric stress tensor.")
return def_grad.det * np.dot(np.dot(def_grad.inv, self), def_grad.inv.trans)
11 changes: 5 additions & 6 deletions pymatgen/analysis/eos.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __init__(self, volumes, energies):
self.volumes = np.array(volumes)
self.energies = np.array(energies)
# minimum energy(e0), buk modulus(b0),
# derivative of bulk modulus wrt pressure(b1), minimum volume(v0)
# derivative of bulk modulus w.r.t. pressure(b1), minimum volume(v0)
self._params = None
# the eos function parameters. It is the same as _params except for
# equation of states that uses polynomial fits(delta_factor and
Expand Down Expand Up @@ -147,7 +147,7 @@ def b0_GPa(self):

@property
def b1(self):
"""Returns the derivative of bulk modulus wrt pressure(dimensionless)."""
"""Returns the derivative of bulk modulus w.r.t. pressure(dimensionless)."""
return self._params[2]

@property
Expand Down Expand Up @@ -191,7 +191,7 @@ def plot(self, width=8, height=None, ax: plt.Axes = None, dpi=None, **kwargs):
f"Minimum energy = {self.e0:1.2f} eV",
f"Minimum or reference volume = {self.v0:1.2f} Ang^3",
f"Bulk modulus = {self.b0:1.2f} eV/Ang^3 = {self.b0_GPa:1.2f} GPa",
f"Derivative of bulk modulus wrt pressure = {self.b1:1.2f}",
f"Derivative of bulk modulus w.r.t. pressure = {self.b1:1.2f}",
]
text = "\n".join(lines)
text = kwargs.get("text", text)
Expand Down Expand Up @@ -239,7 +239,7 @@ def plot_ax(self, ax: plt.Axes = None, fontsize=12, **kwargs):
f"Minimum energy = {self.e0:1.2f} eV",
f"Minimum or reference volume = {self.v0:1.2f} Ang^3",
f"Bulk modulus = {self.b0:1.2f} eV/Ang^3 = {self.b0_GPa:1.2f} GPa",
f"Derivative of bulk modulus wrt pressure = {self.b1:1.2f}",
f"Derivative of bulk modulus w.r.t. pressure = {self.b1:1.2f}",
]
text = "\n".join(lines)
text = kwargs.get("text", text)
Expand Down Expand Up @@ -357,8 +357,7 @@ def _set_params(self):
and set to the _params attribute.
"""
fit_poly = np.poly1d(self.eos_params)
# the volume at min energy, used as the initial guess for the
# optimization wrt volume.
# the volume at min energy, used as the initial guess for the optimization w.r.t. volume.
v_e_min = self.volumes[np.argmin(self.energies)]
# evaluate e0, v0, b0 and b1
min_wrt_v = minimize(fit_poly, v_e_min)
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/graphs.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,13 +1086,13 @@ def __mul__(self, scaling_matrix):
raise NotImplementedError("Not tested with 3x3 scaling matrices yet.")
new_lattice = Lattice(np.dot(scale_matrix, self.structure.lattice.matrix))

f_lat = lattice_points_in_supercell(scale_matrix)
c_lat = new_lattice.get_cartesian_coords(f_lat)
frac_lattice = lattice_points_in_supercell(scale_matrix)
cart_lattice = new_lattice.get_cartesian_coords(frac_lattice)

new_sites = []
new_graphs = []

for v in c_lat:
for v in cart_lattice:
# create a map of nodes from original graph to its image
mapping = {n: n + len(new_sites) for n in range(len(self.structure))}

Expand Down
3 changes: 2 additions & 1 deletion pymatgen/analysis/hhi.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,8 @@
__date__ = "Oct 27, 2014"


csv_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "hhi_data.csv")
module_dir = os.path.dirname(os.path.abspath(__file__))
csv_path = f"{module_dir}/hhi_data.csv"


@singleton
Expand Down
15 changes: 7 additions & 8 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,16 +46,16 @@
__status__ = "Production"
__date__ = "August 17, 2017"

_directory = os.path.join(os.path.dirname(__file__))
module_dir = os.path.dirname(os.path.abspath(__file__))
yaml = YAML()

with open(f"{_directory}/op_params.yaml") as f:
with open(f"{module_dir}/op_params.yaml") as f:
default_op_params = yaml.load(f)

with open(f"{_directory}/cn_opt_params.yaml") as f:
with open(f"{module_dir}/cn_opt_params.yaml") as f:
cn_opt_params = yaml.load(f)

with open(f"{_directory}/ionic_radii.json") as fp:
with open(f"{module_dir}/ionic_radii.json") as fp:
_ion_radii = json.load(fp)


Expand Down Expand Up @@ -1210,7 +1210,7 @@ def __init__(
self.min_bond_distance = min_bond_distance

# Load elemental radii table
bonds_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "bonds_jmol_ob.yaml")
bonds_file = f"{module_dir}/bonds_jmol_ob.yaml"
with open(bonds_file) as f:
yaml = YAML()
self.el_radius = yaml.load(f)
Expand Down Expand Up @@ -4204,14 +4204,13 @@ def from_preset(cls, preset) -> CutOffDictNN:
Args:
preset (str): A preset name. The list of supported presets are:
- "vesta_2019": The distance cutoffs used by the VESTA
visualisation program.
- "vesta_2019": The distance cutoffs used by the VESTA visualisation program.
Returns:
A CutOffDictNN using the preset cut-off dictionary.
"""
if preset == "vesta_2019":
cut_offs = loadfn(f"{_directory}/vesta_cutoffs.yaml")
cut_offs = loadfn(f"{module_dir}/vesta_cutoffs.yaml")
return cls(cut_off_dict=cut_offs)

raise ValueError(f"Unknown {preset=}")
Expand Down
4 changes: 2 additions & 2 deletions pymatgen/analysis/phase_diagram.py
Original file line number Diff line number Diff line change
Expand Up @@ -2374,7 +2374,7 @@ class (pymatgen.analysis.chempot_diagram).
Args:
elements: Sequence of elements to be considered as independent
variables. E.g., if you want to show the stability ranges of
all Li-Co-O phases wrt to uLi and uO, you will supply
all Li-Co-O phases w.r.t. to uLi and uO, you will supply
[Element("Li"), Element("O")]
referenced: if True, gives the results with a reference being the
energy of the elemental phase. If False, gives absolute values.
Expand All @@ -2392,7 +2392,7 @@ class (pymatgen.analysis.chempot_diagram).
Args:
elements: Sequence of elements to be considered as independent
variables. E.g., if you want to show the stability ranges of
all Li-Co-O phases wrt to uLi and uO, you will supply
all Li-Co-O phases w.r.t. to uLi and uO, you will supply
[Element("Li"), Element("O")]
referenced: if True, gives the results with a reference being the
energy of the elemental phase. If False, gives absolute values.
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/analysis/prototypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from pymatgen.core import Structure

module_dir = os.path.dirname(os.path.abspath(__file__))
AFLOW_PROTOTYPE_LIBRARY = loadfn(os.path.join(os.path.dirname(os.path.abspath(__file__)), "aflow_prototypes.json"))
AFLOW_PROTOTYPE_LIBRARY = loadfn(f"{module_dir}/aflow_prototypes.json")


@due.dcite(
Expand Down Expand Up @@ -66,8 +66,8 @@ def __init__(self, initial_ltol=0.2, initial_stol=0.3, initial_angle_tol=5):
def _match_prototype(structure_matcher, structure):
tags = []
for d in AFLOW_PROTOTYPE_LIBRARY:
p = d["snl"].structure
match = structure_matcher.fit_anonymous(p, structure)
struct = d["snl"].structure
match = structure_matcher.fit_anonymous(struct, structure)
if match:
tags.append(d)
return tags
Expand Down
Loading

0 comments on commit 7cdfcbf

Please sign in to comment.