Skip to content

Commit e59888e

Browse files
author
Shyue Ping Ong
committed
Merge branch 'master' of github.com:materialsproject/pymatgen
2 parents 30ca255 + 8082052 commit e59888e

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+744
-383
lines changed

.pre-commit-config.yaml

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ ci:
88

99
repos:
1010
- repo: https://github.com/astral-sh/ruff-pre-commit
11-
rev: v0.1.5
11+
rev: v0.1.7
1212
hooks:
1313
- id: ruff
1414
args: [--fix]
@@ -22,7 +22,7 @@ repos:
2222
- id: trailing-whitespace
2323

2424
- repo: https://github.com/pre-commit/mirrors-mypy
25-
rev: v1.6.1
25+
rev: v1.7.1
2626
hooks:
2727
- id: mypy
2828

@@ -35,7 +35,7 @@ repos:
3535
additional_dependencies: [tomli] # needed to read pyproject.toml below py3.11
3636

3737
- repo: https://github.com/MarcoGorelli/cython-lint
38-
rev: v0.15.0
38+
rev: v0.16.0
3939
hooks:
4040
- id: cython-lint
4141
args: [--no-pycodestyle]

pymatgen/analysis/adsorption.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -576,12 +576,12 @@ def substitute(site, i):
576576
# surface atoms, i.e. search for sites above (below) the bottom (top) surface
577577
sorted_sites = sorted(sym_slab, key=lambda site: site.frac_coords[2])
578578
if sorted_sites[0].surface_properties == "surface":
579-
d = sorted_sites[0].frac_coords[2] + dist_from_surf
579+
dist = sorted_sites[0].frac_coords[2] + dist_from_surf
580580
else:
581-
d = sorted_sites[-1].frac_coords[2] - dist_from_surf
581+
dist = sorted_sites[-1].frac_coords[2] - dist_from_surf
582582

583583
for idx, site in enumerate(sym_slab):
584-
if d - range_tol < site.frac_coords[2] < d + range_tol and (
584+
if dist - range_tol < site.frac_coords[2] < dist + range_tol and (
585585
target_species and site.species_string in target_species or not target_species
586586
):
587587
substituted_slabs.append(substitute(site, idx))

pymatgen/analysis/chemenv/connectivity/connected_components.py

Lines changed: 1 addition & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -155,14 +155,7 @@ def make_supergraph(graph, multiplicity, periodicity_vectors):
155155
connecting_edges.append((n1, n2, key, new_data))
156156
else:
157157
if not np.all(np.array(data["delta"]) == 0):
158-
print(
159-
"delta not equal to periodicity nor 0 ... : ",
160-
n1,
161-
n2,
162-
key,
163-
data["delta"],
164-
data,
165-
)
158+
print("delta not equal to periodicity nor 0 ... : ", n1, n2, key, data["delta"], data)
166159
input("Are we ok with this ?")
167160
other_edges.append((n1, n2, key, data))
168161

pymatgen/analysis/chemenv/coordination_environments/chemenv_strategies.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1129,22 +1129,22 @@ def _get_map(self, isite):
11291129
target_cns = [cg.coordination_number for cg in target_cgs]
11301130
for ii in range(min([len(maps_and_surfaces), self.max_nabundant])):
11311131
my_map_and_surface = maps_and_surfaces[order[ii]]
1132-
mymap = my_map_and_surface["map"]
1133-
cn = mymap[0]
1132+
my_map = my_map_and_surface["map"]
1133+
cn = my_map[0]
11341134
if cn not in target_cns or cn > 12 or cn == 0:
11351135
continue
11361136
all_conditions = [params[2] for params in my_map_and_surface["parameters_indices"]]
11371137
if self._additional_condition not in all_conditions:
11381138
continue
1139-
cg, cgdict = self.structure_environments.ce_list[self.structure_environments.sites_map[isite]][mymap[0]][
1140-
mymap[1]
1139+
cg, cgdict = self.structure_environments.ce_list[self.structure_environments.sites_map[isite]][my_map[0]][
1140+
my_map[1]
11411141
].minimum_geometry(symmetry_measure_type=self._symmetry_measure_type)
11421142
if (
11431143
cg in self.target_environments
11441144
and cgdict["symmetry_measure"] <= self.max_csm
11451145
and cgdict["symmetry_measure"] < current_target_env_csm
11461146
):
1147-
current_map = mymap
1147+
current_map = my_map
11481148
current_target_env_csm = cgdict["symmetry_measure"]
11491149
if current_map is not None:
11501150
return current_map

pymatgen/analysis/chemenv/coordination_environments/coordination_geometries.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -882,19 +882,19 @@ def __init__(self, permutations_safe_override=False, only_symbols=None):
882882
dict.__init__(self)
883883
self.cg_list = []
884884
if only_symbols is None:
885-
with open(f"{module_dir}/coordination_geometries_files/allcg.txt") as f:
886-
data = f.readlines()
885+
with open(f"{module_dir}/coordination_geometries_files/allcg.txt") as file:
886+
data = file.readlines()
887887
for line in data:
888888
cg_file = f"{module_dir}/{line.strip()}"
889-
with open(cg_file) as f:
890-
dd = json.load(f)
889+
with open(cg_file) as file:
890+
dd = json.load(file)
891891
self.cg_list.append(CoordinationGeometry.from_dict(dd))
892892
else:
893893
for symbol in only_symbols:
894894
fsymbol = symbol.replace(":", "#")
895895
cg_file = f"{module_dir}/coordination_geometries_files/{fsymbol}.json"
896-
with open(cg_file) as f:
897-
dd = json.load(f)
896+
with open(cg_file) as file:
897+
dd = json.load(file)
898898
self.cg_list.append(CoordinationGeometry.from_dict(dd))
899899

900900
self.cg_list.append(CoordinationGeometry(UNKNOWN_ENVIRONMENT_SYMBOL, "Unknown environment", deactivate=True))

pymatgen/analysis/elasticity/elastic.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -599,7 +599,6 @@ def get_tgt(self, temperature: float | None = None, structure: Structure = None,
599599
"""
600600
if temperature and not structure:
601601
raise ValueError("If using temperature input, you must also include structure")
602-
assert structure # for mypy
603602

604603
quad = quad or DEFAULT_QUAD
605604
points = quad["points"]
@@ -611,7 +610,7 @@ def get_tgt(self, temperature: float | None = None, structure: Structure = None,
611610
us = [u / np.linalg.norm(u) for u in np.transpose(us)]
612611
for u in us:
613612
# TODO: this should be benchmarked
614-
if temperature:
613+
if temperature and structure:
615614
c = self.get_heat_capacity(temperature, structure, p, u)
616615
num += c * self.get_ggt(p, u) * w
617616
denom += c * w

pymatgen/analysis/phase_diagram.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2276,7 +2276,11 @@ def show(self, *args, **kwargs) -> None:
22762276
*args: Passed to get_plot.
22772277
**kwargs: Passed to get_plot.
22782278
"""
2279-
self.get_plot(*args, **kwargs).show()
2279+
plot = self.get_plot(*args, **kwargs)
2280+
if self.backend == "matplotlib":
2281+
plot.get_figure().show()
2282+
else:
2283+
plot.show()
22802284

22812285
def write_image(self, stream: str | StringIO, image_format: str = "svg", **kwargs) -> None:
22822286
"""

pymatgen/analysis/pourbaix_diagram.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -473,15 +473,15 @@ def __init__(
473473
for entry in ion_entries:
474474
ion_elts = list(set(entry.elements) - ELEMENTS_HO)
475475
# TODO: the logic here for ion concentration setting is in two
476-
# places, in PourbaixEntry and here, should be consolidated
476+
# places, in PourbaixEntry and here, should be consolidated
477477
if len(ion_elts) == 1:
478478
entry.concentration = conc_dict[ion_elts[0].symbol] * entry.normalization_factor
479479
elif len(ion_elts) > 1 and not entry.concentration:
480480
raise ValueError("Elemental concentration not compatible with multi-element ions")
481481

482482
self._unprocessed_entries = solid_entries + ion_entries
483483

484-
if not len(solid_entries + ion_entries) == len(entries):
484+
if len(solid_entries + ion_entries) != len(entries):
485485
raise ValueError('All supplied entries must have a phase type of either "Solid" or "Ion"')
486486

487487
if self.filter_solids:

pymatgen/core/composition.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -363,7 +363,7 @@ def get_reduced_formula_and_factor(self, iupac_ordering: bool = False) -> tuple[
363363
if not all_int:
364364
return self.formula.replace(" ", ""), 1
365365
d = {k: int(round(v)) for k, v in self.get_el_amt_dict().items()}
366-
(formula, factor) = reduce_formula(d, iupac_ordering=iupac_ordering)
366+
formula, factor = reduce_formula(d, iupac_ordering=iupac_ordering)
367367

368368
if formula in Composition.special_formulas:
369369
formula = Composition.special_formulas[formula]

pymatgen/core/structure.py

Lines changed: 22 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -357,6 +357,11 @@ def formula(self) -> str:
357357
"""Returns the formula as a string."""
358358
return self.composition.formula
359359

360+
@property
361+
def alphabetical_formula(self) -> str:
362+
"""Returns the formula as a string."""
363+
return self.composition.alphabetical_formula
364+
360365
@property
361366
def elements(self) -> list[Element | Species | DummySpecies]:
362367
"""Returns the elements in the structure as a list of Element objects."""
@@ -1172,11 +1177,9 @@ def from_magnetic_spacegroup(
11721177
f"{msg.sg_symbol}!"
11731178
)
11741179

1175-
if len(species) != len(coords):
1176-
raise ValueError(f"Supplied species and coords lengths ({len(species)} vs {len(coords)}) are different!")
1177-
1178-
if len(species) != len(magmoms):
1179-
raise ValueError(f"Supplied species and magmom lengths ({len(species)} vs {len(magmoms)}) are different!")
1180+
for name, var in (("coords", coords), ("magmoms", magmoms)):
1181+
if len(var) != len(species):
1182+
raise ValueError(f"Length mismatch: len({name})={len(var)} != {len(species)=}")
11801183

11811184
frac_coords = coords if not coords_are_cartesian else latt.get_fractional_coords(coords)
11821185

@@ -2138,13 +2141,16 @@ def interpolate(
21382141
interpolate_lattices: bool = False,
21392142
pbc: bool = True,
21402143
autosort_tol: float = 0,
2144+
end_amplitude: float = 1,
21412145
) -> list[IStructure | Structure]:
21422146
"""Interpolate between this structure and end_structure. Useful for
2143-
construction of NEB inputs.
2147+
construction of NEB inputs. To obtain useful results, the cell setting
2148+
and order of sites must consistent across the start and end structures.
21442149
21452150
Args:
21462151
end_structure (Structure): structure to interpolate between this
2147-
structure and end.
2152+
structure and end. Must be in the same setting and have the
2153+
same site ordering to yield useful results.
21482154
nimages (int,list): No. of interpolation images or a list of
21492155
interpolation images. Defaults to 10 images.
21502156
interpolate_lattices (bool): Whether to interpolate the lattices.
@@ -2157,6 +2163,13 @@ def interpolate(
21572163
closest points in this particular structure. This is usually
21582164
what you want in a NEB calculation. 0 implies no sorting.
21592165
Otherwise, a 0.5 value usually works pretty well.
2166+
end_amplitude (float): The fractional amplitude of the endpoint
2167+
of the interpolation, or a cofactor of the distortion vector
2168+
connecting structure to end_structure. Thus, 0 implies no
2169+
distortion, 1 implies full distortion to end_structure
2170+
(default), 0.5 implies distortion to a point halfway
2171+
between structure and end_structure, and -1 implies full
2172+
distortion in the opposite direction to end_structure.
21602173
21612174
Returns:
21622175
List of interpolated structures. The starting and ending
@@ -2212,7 +2225,7 @@ def interpolate(
22122225

22132226
end_coords = sorted_end_coords
22142227

2215-
vec = end_coords - start_coords
2228+
vec = end_amplitude * (end_coords - start_coords)
22162229
if pbc:
22172230
vec[:, self.pbc] -= np.round(vec[:, self.pbc])
22182231
sp = self.species_and_occu
@@ -2222,7 +2235,7 @@ def interpolate(
22222235
# interpolate lattice matrices using polar decomposition
22232236
# u is a unitary rotation, p is stretch
22242237
u, p = polar(np.dot(end_structure.lattice.matrix.T, np.linalg.inv(self.lattice.matrix.T)))
2225-
lvec = p - np.identity(3)
2238+
lvec = end_amplitude * (p - np.identity(3))
22262239
lstart = self.lattice.matrix.T
22272240

22282241
for x in images:

0 commit comments

Comments
 (0)