Skip to content

Commit

Permalink
Re-export SiteCollection + DummySpecies from pymatgen.core (#2995)
Browse files Browse the repository at this point in the history
* rename dict vars d -> dct

* re-export DummySpecie + SiteCollection from pymatgen.core
  • Loading branch information
janosh authored May 17, 2023
1 parent 0a4c571 commit 2b47486
Show file tree
Hide file tree
Showing 25 changed files with 185 additions and 182 deletions.
14 changes: 7 additions & 7 deletions dev_scripts/regen_libxcfunc.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,27 +21,27 @@ def parse_libxc_docs(path):
"""

def parse_section(section):
d = {}
dct = {}
for line in section:
key, value = line.split(":")
d[key.strip()] = value.strip()
dct[key.strip()] = value.strip()

return int(d["Number"]), d
return int(dct["Number"]), dct

d = {}
dct = {}
with open(path) as fh:
section = []
for line in fh:
if not line.startswith("-"):
section.append(line)
else:
num, entry = parse_section(section)
assert num not in d
d[num] = entry
assert num not in dct
dct[num] = entry
section = []
assert not section

return d
return dct


def write_libxc_docs_json(xcfuncs, jpath):
Expand Down
12 changes: 6 additions & 6 deletions pymatgen/alchemy/filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,15 +113,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): Dict representation
dct (dict): Dict representation
Returns:
Filter
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class SpecieProximityFilter(AbstractStructureFilter):
Expand Down Expand Up @@ -176,15 +176,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): Dict representation
dct (dict): Dict representation
Returns:
Filter
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class RemoveDuplicatesFilter(AbstractStructureFilter):
Expand Down
11 changes: 7 additions & 4 deletions pymatgen/analysis/energy_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,15 @@ def get_energy(self, structure) -> float:
return 0.0

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
:param d: Dict representation
:return: EnergyModel
Args:
dct (dict): Dict representation
Returns:
EnergyModel
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class EwaldElectrostaticModel(EnergyModel):
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/analysis/local_env.py
Original file line number Diff line number Diff line change
Expand Up @@ -666,10 +666,10 @@ def get_local_order_parameters(self, structure: Structure, n: int):
lostops = LocalStructOrderParams(types, parameters=params)
sites = [structure[n], *self.get_nn(structure, n)]
lostop_vals = lostops.get_order_parameters(sites, 0, indices_neighs=list(range(1, cn + 1))) # type: ignore
d = {}
dct = {}
for i, lostop in enumerate(lostop_vals):
d[names[i]] = lostop
return d
dct[names[i]] = lostop
return dct
return None


Expand Down Expand Up @@ -4223,7 +4223,7 @@ def extend_structure_molecules(self):
@staticmethod
def from_preset(preset):
"""
Initialise a CutOffDictNN according to a preset set of cut-offs.
Initialize a CutOffDictNN according to a preset set of cut-offs.
Args:
preset (str): A preset name. The list of supported presets are:
Expand Down
38 changes: 19 additions & 19 deletions pymatgen/analysis/magnetism/heisenberg.py
Original file line number Diff line number Diff line change
Expand Up @@ -881,28 +881,28 @@ def as_dict(self):
"""
Because some dicts have tuple keys, some sanitization is required for json compatibility.
"""
d = {}
d["@module"] = type(self).__module__
d["@class"] = type(self).__name__
d["@version"] = __version__
d["formula"] = self.formula
d["structures"] = [s.as_dict() for s in self.structures]
d["energies"] = self.energies
d["cutoff"] = self.cutoff
d["tol"] = self.tol
d["sgraphs"] = [sgraph.as_dict() for sgraph in self.sgraphs]
d["dists"] = self.dists
d["ex_params"] = self.ex_params
d["javg"] = self.javg
d["igraph"] = self.igraph.as_dict()
dct = {}
dct["@module"] = type(self).__module__
dct["@class"] = type(self).__name__
dct["@version"] = __version__
dct["formula"] = self.formula
dct["structures"] = [s.as_dict() for s in self.structures]
dct["energies"] = self.energies
dct["cutoff"] = self.cutoff
dct["tol"] = self.tol
dct["sgraphs"] = [sgraph.as_dict() for sgraph in self.sgraphs]
dct["dists"] = self.dists
dct["ex_params"] = self.ex_params
dct["javg"] = self.javg
dct["igraph"] = self.igraph.as_dict()

# Sanitize tuple & int keys
d["ex_mat"] = jsanitize(self.ex_mat)
d["nn_interactions"] = jsanitize(self.nn_interactions)
d["unique_site_ids"] = jsanitize(self.unique_site_ids)
d["wyckoff_ids"] = jsanitize(self.wyckoff_ids)
dct["ex_mat"] = jsanitize(self.ex_mat)
dct["nn_interactions"] = jsanitize(self.nn_interactions)
dct["unique_site_ids"] = jsanitize(self.unique_site_ids)
dct["wyckoff_ids"] = jsanitize(self.wyckoff_ids)

return d
return dct

@classmethod
def from_dict(cls, d):
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -165,15 +165,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d(dict): Dict representation
dct (dict): Dict representation
Returns:
Class
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class SubstitutionPredictor:
Expand Down
18 changes: 9 additions & 9 deletions pymatgen/apps/borg/hive.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,15 +184,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): Dict Representation
dct (dict): Dict Representation
Returns:
VaspToComputedEntryDrone
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class SimpleVaspToComputedEntryDrone(VaspToComputedEntryDrone):
Expand Down Expand Up @@ -297,15 +297,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): Dict Representation
dct (dict): Dict Representation
Returns:
SimpleVaspToComputedEntryDrone
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


class GaussianToComputedEntryDrone(AbstractDrone):
Expand Down Expand Up @@ -422,15 +422,15 @@ def as_dict(self):
}

@classmethod
def from_dict(cls, d):
def from_dict(cls, dct):
"""
Args:
d (dict): Dict Representation
dct (dict): Dict Representation
Returns:
GaussianToComputedEntryDrone
"""
return cls(**d["init_args"])
return cls(**dct["init_args"])


def _get_transformation_history(path):
Expand Down
8 changes: 4 additions & 4 deletions pymatgen/cli/pmg_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,17 +272,17 @@ def add_config_var(tokens: list[str], backup_suffix: str) -> None:
else:
# if neither exists, create new config file
fpath = SETTINGS_FILE
d = {}
dct = {}
if os.path.exists(fpath):
if backup_suffix:
shutil.copy(fpath, fpath + backup_suffix)
print(f"Existing {fpath} backed up to {fpath}{backup_suffix}")
d = loadfn(fpath)
dct = loadfn(fpath)
if len(tokens) % 2 != 0:
raise ValueError(f"Uneven number {len(tokens)} of tokens passed to pmg config. Needs a value for every key.")
for key, val in zip(tokens[0::2], tokens[1::2]):
d[key] = val
dumpfn(d, fpath)
dct[key] = val
dumpfn(dct, fpath)
print(f"New {fpath} written!")


Expand Down
2 changes: 2 additions & 0 deletions pymatgen/core/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from pymatgen.core.composition import Composition as Composition
from pymatgen.core.lattice import Lattice as Lattice
from pymatgen.core.operations import SymmOp as SymmOp
from pymatgen.core.periodic_table import DummySpecie as DummySpecie
from pymatgen.core.periodic_table import DummySpecies as DummySpecies
from pymatgen.core.periodic_table import Element as Element
from pymatgen.core.periodic_table import Species as Species
Expand All @@ -21,6 +22,7 @@
from pymatgen.core.structure import IMolecule as IMolecule
from pymatgen.core.structure import IStructure as IStructure
from pymatgen.core.structure import Molecule as Molecule
from pymatgen.core.structure import SiteCollection as SiteCollection
from pymatgen.core.structure import Structure as Structure
from pymatgen.core.units import ArrayWithUnit as ArrayWithUnit
from pymatgen.core.units import FloatWithUnit as FloatWithUnit
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/core/tensors.py
Original file line number Diff line number Diff line change
Expand Up @@ -249,7 +249,7 @@ def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs):
list of index groups where tensor values are equivalent to
within tolerances
"""
d = {}
dct = {}
array = self.voigt if voigt else self
grouped = self.get_grouped_indices(voigt=voigt, **kwargs)
p = 0 if zero_index else 1
Expand All @@ -258,8 +258,8 @@ def get_symbol_dict(self, voigt=True, zero_index=False, **kwargs):
sym_string += "".join(str(i + p) for i in indices[0])
value = array[indices[0]]
if not np.isclose(value, 0):
d[sym_string] = array[indices[0]]
return d
dct[sym_string] = array[indices[0]]
return dct

def round(self, decimals=0):
"""
Expand Down
6 changes: 3 additions & 3 deletions pymatgen/core/tests/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,10 @@ def g():

@unitized("pm")
def h():
d = {}
dct = {}
for i in range(3):
d[i] = i * 20
return d
dct[i] = i * 20
return dct

assert str(h()[1]) == "20.0 pm"
assert isinstance(h(), dict)
Expand Down
28 changes: 14 additions & 14 deletions pymatgen/ext/matproj.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,44 +215,44 @@ def __init__(

try:
with open(MP_LOG_FILE) as f:
d = dict(yaml.load(f))
dct = dict(yaml.load(f))
except (OSError, TypeError):
# TypeError: 'NoneType' object is not iterable occurs if MP_LOG_FILE exists but is empty
d = {}
dct = {}

d = d or {}
dct = dct or {}

if "MAPI_DB_VERSION" not in d:
d["MAPI_DB_VERSION"] = {"LOG": {}, "LAST_ACCESSED": None}
if "MAPI_DB_VERSION" not in dct:
dct["MAPI_DB_VERSION"] = {"LOG": {}, "LAST_ACCESSED": None}
else:
# ensure data is parsed as dict, rather than ordered dict,
# due to change in YAML parsing behavior
d["MAPI_DB_VERSION"] = dict(d["MAPI_DB_VERSION"])
dct["MAPI_DB_VERSION"] = dict(dct["MAPI_DB_VERSION"])

if "LOG" in d["MAPI_DB_VERSION"]:
d["MAPI_DB_VERSION"]["LOG"] = dict(d["MAPI_DB_VERSION"]["LOG"])
if "LOG" in dct["MAPI_DB_VERSION"]:
dct["MAPI_DB_VERSION"]["LOG"] = dict(dct["MAPI_DB_VERSION"]["LOG"])

# store a log of what database versions are being connected to
if db_version not in d["MAPI_DB_VERSION"]["LOG"]:
d["MAPI_DB_VERSION"]["LOG"][db_version] = 1
if db_version not in dct["MAPI_DB_VERSION"]["LOG"]:
dct["MAPI_DB_VERSION"]["LOG"][db_version] = 1
else:
d["MAPI_DB_VERSION"]["LOG"][db_version] += 1
dct["MAPI_DB_VERSION"]["LOG"][db_version] += 1

# alert user if db version changed
last_accessed = d["MAPI_DB_VERSION"]["LAST_ACCESSED"]
last_accessed = dct["MAPI_DB_VERSION"]["LAST_ACCESSED"]
if last_accessed and last_accessed != db_version:
print(
f"This database version has changed from the database last accessed ({last_accessed}).\n"
f"Please see release notes on materialsproject.org for information about what has changed."
)
d["MAPI_DB_VERSION"]["LAST_ACCESSED"] = db_version
dct["MAPI_DB_VERSION"]["LAST_ACCESSED"] = db_version

# write out new database log if possible
# base Exception is not ideal (perhaps a PermissionError, etc.) but this is not critical
# and should be allowed to fail regardless of reason
try:
with open(MP_LOG_FILE, "w") as f:
yaml.dump(d, f)
yaml.dump(dct, f)
except Exception:
pass

Expand Down
22 changes: 11 additions & 11 deletions pymatgen/io/abinit/abiobjects.py
Original file line number Diff line number Diff line change
Expand Up @@ -600,17 +600,17 @@ def nspden(self):

def as_dict(self):
"""Json friendly dict representation"""
d = {}
d["@module"] = type(self).__module__
d["@class"] = type(self).__name__
d["spin_mode"] = self.spin_mode.as_dict()
d["smearing"] = self.smearing.as_dict()
d["algorithm"] = self.algorithm.as_dict() if self.algorithm else None
d["nband"] = self.nband
d["fband"] = self.fband
d["charge"] = self.charge
d["comment"] = self.comment
return d
dct = {}
dct["@module"] = type(self).__module__
dct["@class"] = type(self).__name__
dct["spin_mode"] = self.spin_mode.as_dict()
dct["smearing"] = self.smearing.as_dict()
dct["algorithm"] = self.algorithm.as_dict() if self.algorithm else None
dct["nband"] = self.nband
dct["fband"] = self.fband
dct["charge"] = self.charge
dct["comment"] = self.comment
return dct

@classmethod
def from_dict(cls, d):
Expand Down
Loading

0 comments on commit 2b47486

Please sign in to comment.