Skip to content

Commit

Permalink
MaterialsProjectCompatibility issue silencable deprecation warning (#…
Browse files Browse the repository at this point in the history
…3017)

* MaterialsProjectCompatibility issue silencable deprecation warning

* SymmetrizedStructure type hints
  • Loading branch information
janosh authored May 26, 2023
1 parent 0743fdc commit cc0b7b4
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 42 deletions.
6 changes: 3 additions & 3 deletions pymatgen/core/lattice.py
Original file line number Diff line number Diff line change
Expand Up @@ -971,17 +971,17 @@ def as_dict(self, verbosity: int = 0) -> dict:
verbosity (int): Verbosity level. Default of 0 only includes the
matrix representation. Set to 1 for more details.
"""
d = {
dct = {
"@module": type(self).__module__,
"@class": type(self).__name__,
"matrix": self._matrix.tolist(),
"pbc": self._pbc,
}
if verbosity > 0:
keys = ["a", "b", "c", "alpha", "beta", "gamma", "volume"]
d.update(dict(zip(keys, [*self.parameters, self.volume])))
dct.update(dict(zip(keys, [*self.parameters, self.volume])))

return d
return dct

def find_all_mappings(
self,
Expand Down
20 changes: 10 additions & 10 deletions pymatgen/core/sites.py
Original file line number Diff line number Diff line change
Expand Up @@ -599,13 +599,13 @@ def as_dict(self, verbosity: int = 0) -> dict:
"""
species_list = []
for spec, occu in self._species.items():
d = spec.as_dict()
del d["@module"]
del d["@class"]
d["occu"] = occu
species_list.append(d)
dct = spec.as_dict()
del dct["@module"]
del dct["@class"]
dct["occu"] = occu
species_list.append(dct)

d = {
dct = {
"species": species_list,
"abc": [float(c) for c in self._frac_coords], # type: ignore
"lattice": self._lattice.as_dict(verbosity=verbosity),
Expand All @@ -614,12 +614,12 @@ def as_dict(self, verbosity: int = 0) -> dict:
}

if verbosity > 0:
d["xyz"] = [float(c) for c in self.coords]
d["label"] = self.species_string
dct["xyz"] = [float(c) for c in self.coords]
dct["label"] = self.species_string

d["properties"] = self.properties
dct["properties"] = self.properties

return d
return dct

@classmethod
def from_dict(cls, d, lattice=None) -> PeriodicSite:
Expand Down
14 changes: 7 additions & 7 deletions pymatgen/core/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -2357,7 +2357,7 @@ def get_orderings(self, mode: Literal["enum", "sqs"] = "enum", **kwargs) -> list
return [run_mcsqs(self, **kwargs).bestsqs]
raise ValueError("Invalid mode!")

def as_dict(self, verbosity=1, fmt=None, **kwargs):
def as_dict(self, verbosity=1, fmt=None, **kwargs) -> dict[str, Any]:
"""
Dict representation of Structure.
Expand Down Expand Up @@ -2386,21 +2386,21 @@ def as_dict(self, verbosity=1, fmt=None, **kwargs):
latt_dict = self._lattice.as_dict(verbosity=verbosity)
del latt_dict["@module"]
del latt_dict["@class"]

d = {
sites = []
dct = {
"@module": type(self).__module__,
"@class": type(self).__name__,
"charge": self.charge,
"lattice": latt_dict,
"sites": [],
}
for site in self:
site_dict = site.as_dict(verbosity=verbosity)
site_dict = site.as_dict(verbosity=verbosity) # type: ignore[call-arg]
del site_dict["lattice"]
del site_dict["@module"]
del site_dict["@class"]
d["sites"].append(site_dict)
return d
sites.append(site_dict)
dct["sites"] = sites
return dct

def as_dataframe(self):
"""
Expand Down
6 changes: 6 additions & 0 deletions pymatgen/entries/compatibility.py
Original file line number Diff line number Diff line change
Expand Up @@ -790,7 +790,13 @@ def __init__(
correct_peroxide: Specify whether peroxide/superoxide/ozonide
corrections are to be applied or not.
check_potcar_hash (bool): Use potcar hash to verify potcars are correct.
silence_deprecation (bool): Silence deprecation warning. Defaults to False.
"""
warnings.warn( # added by @janosh on 2023-05-25
"MaterialsProjectCompatibility is deprecated, Materials Project formation energies "
"use the newer MaterialsProject2020Compatibility scheme.",
DeprecationWarning,
)
self.compat_type = compat_type
self.correct_peroxide = correct_peroxide
self.check_potcar_hash = check_potcar_hash
Expand Down
41 changes: 23 additions & 18 deletions pymatgen/symmetry/structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,16 @@

from __future__ import annotations

from typing import Sequence
from typing import TYPE_CHECKING, Sequence

import numpy as np
from tabulate import tabulate

from pymatgen.core.structure import PeriodicSite, Structure

if TYPE_CHECKING:
from pymatgen.symmetry.analyzer import SpacegroupOperations


class SymmetrizedStructure(Structure):
"""
Expand All @@ -27,17 +30,16 @@ class SymmetrizedStructure(Structure):
def __init__(
self,
structure: Structure,
spacegroup,
spacegroup: SpacegroupOperations,
equivalent_positions: Sequence[int],
wyckoff_letters: Sequence[str],
):
) -> None:
"""
Args:
structure (Structure): Original structure
spacegroup (SpacegroupOperations): An input SpacegroupOperations from
SpacegroupAnalyzer.
equivalent_positions: Equivalent positions from SpacegroupAnalyzer.
wyckoff_letters: Wyckoff letters
spacegroup (SpacegroupOperations): An input SpacegroupOperations from SpacegroupAnalyzer.
equivalent_positions (list[int]): Equivalent positions from SpacegroupAnalyzer.
wyckoff_letters (list[str]): Wyckoff letters
"""
self.spacegroup = spacegroup
u, inv = np.unique(equivalent_positions, return_inverse=True)
Expand Down Expand Up @@ -73,13 +75,16 @@ def copy(self):
wyckoff_letters=self.wyckoff_letters,
)

def find_equivalent_sites(self, site) -> list[PeriodicSite]:
def find_equivalent_sites(self, site: PeriodicSite) -> list[PeriodicSite]:
"""
Finds all symmetrically equivalent sites for a particular site
Args:
site (PeriodicSite): A site in the structure
Raises:
ValueError: if site is not in the structure.
Returns:
([PeriodicSite]): List of all symmetrically equivalent sites.
"""
Expand All @@ -89,22 +94,22 @@ def find_equivalent_sites(self, site) -> list[PeriodicSite]:

raise ValueError("Site not in structure")

def __repr__(self):
def __repr__(self) -> str:
return str(self)

def __str__(self):
def __str__(self) -> str:
outs = [
"SymmetrizedStructure",
f"Full Formula ({self.composition.formula})",
f"Reduced Formula: {self.composition.reduced_formula}",
f"Spacegroup: {self.spacegroup.int_symbol} ({self.spacegroup.int_number})",
]

def to_s(x):
def to_str(x):
return f"{x:0.6f}"

outs.append("abc : " + " ".join(to_s(i).rjust(10) for i in self.lattice.abc))
outs.append("angles: " + " ".join(to_s(i).rjust(10) for i in self.lattice.angles))
outs.append("abc : " + " ".join(to_str(i).rjust(10) for i in self.lattice.abc))
outs.append("angles: " + " ".join(to_str(i).rjust(10) for i in self.lattice.angles))
if self._charge:
if self._charge >= 0:
outs.append(f"Overall Charge: +{self._charge}")
Expand All @@ -114,13 +119,13 @@ def to_s(x):
data = []
props = self.site_properties
keys = sorted(props)
for i, sites in enumerate(self.equivalent_sites):
for idx, sites in enumerate(self.equivalent_sites):
site = sites[0]
row = [str(i), site.species_string]
row.extend([to_s(j) for j in site.frac_coords])
row.append(self.wyckoff_symbols[i])
row = [str(idx), site.species_string]
row.extend([to_str(j) for j in site.frac_coords])
row.append(self.wyckoff_symbols[idx])
for k in keys:
row.append(props[k][i])
row.append(props[k][idx])
data.append(row)
outs.append(
tabulate(
Expand Down
7 changes: 3 additions & 4 deletions pymatgen/symmetry/tests/test_analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,10 +168,9 @@ def test_get_refined_structure(self):
refined_struct = sg.get_refined_structure(keep_site_properties=False)
assert refined_struct.site_properties.get("magmom") is None

def test_get_symmetrized_structure(self):
def test_symmetrized_structure(self):
symm_struct = self.sg.get_symmetrized_structure()
for a in symm_struct.lattice.angles:
assert a == 90
assert symm_struct.lattice.angles == (90, 90, 90)
assert len(symm_struct.equivalent_sites) == 5

symm_struct = self.disordered_sg.get_symmetrized_structure()
Expand All @@ -190,7 +189,7 @@ def test_get_symmetrized_structure(self):

ss = SymmetrizedStructure.from_dict(d)
assert ss.wyckoff_symbols[0] == "16h"
assert "SymmetrizedStructure" in str(ss)
assert str(ss).startswith("SymmetrizedStructure\nFull Formula (Li20.2 Ge2.06 P3.94 S24)\nReduced Formula: ")

def test_find_primitive(self):
"""F m -3 m Li2O testing of converting to primitive cell."""
Expand Down

0 comments on commit cc0b7b4

Please sign in to comment.