Skip to content

Commit

Permalink
deprecate from_dict as_dict
Browse files Browse the repository at this point in the history
  • Loading branch information
htz1992213 committed Aug 25, 2021
1 parent 0997df4 commit cab0331
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 108 deletions.
114 changes: 13 additions & 101 deletions pymatgen/io/lammps/data.py
Expand Up @@ -880,60 +880,6 @@ def from_structure(cls, structure, ff_elements=None, atom_style="charge", is_sor
topo = Topology(boxed_s)
return cls.from_ff_and_topologies(box=box, ff=ff, topologies=[topo], atom_style=atom_style)

@classmethod
def from_dict(cls, d):
"""
Constructor that reads in a dictionary.
Args:
d (dict): Dictionary to read.
"""

def decode_df(s):
return pd.read_json(s, orient="split", dtype=False)

items = dict()
items["box"] = LammpsBox.from_dict(d["box"])
items["masses"] = decode_df(d["masses"])
items["atoms"] = decode_df(d["atoms"])
items["atom_style"] = d["atom_style"]

velocities = d["velocities"]
if velocities:
velocities = decode_df(velocities)
items["velocities"] = velocities
force_field = d["force_field"]
if force_field:
force_field = {k: decode_df(v) for k, v in force_field.items()}
items["force_field"] = force_field
topology = d["topology"]
if topology:
topology = {k: decode_df(v) for k, v in topology.items()}
items["topology"] = topology
return cls(**items)

def as_dict(self):
"""
Returns the LammpsData as a dict.
"""

def encode_df(df):
return df.to_json(orient="split")

d = dict()
d["@module"] = self.__class__.__module__
d["@class"] = self.__class__.__name__
d["box"] = self.box.as_dict()
d["masses"] = encode_df(self.masses)
d["atoms"] = encode_df(self.atoms)
d["atom_style"] = self.atom_style

d["velocities"] = None if self.velocities is None else encode_df(self.velocities)
d["force_field"] = None if not self.force_field else {k: encode_df(v) for k, v in self.force_field.items()}
d["topology"] = None if not self.topology else {k: encode_df(v) for k, v in self.topology.items()}
return d


class Topology(MSONable):
"""
Expand Down Expand Up @@ -1294,16 +1240,21 @@ def __init__(
"""

max_xyz = coordinates[["x", "y", "z"]].max().max()
min_xyz = coordinates[["x", "y", "z"]].min().min()
self._list_of_molecules = list_of_molecules
self._list_of_names = list_of_names
self._list_of_numbers = list_of_numbers
self._coordinates = coordinates
self._coordinates.index = self._coordinates.index.map(int)
max_xyz = self._coordinates[["x", "y", "z"]].max().max()
min_xyz = self._coordinates[["x", "y", "z"]].min().min()
self.box = LammpsBox(np.array(3 * [[min_xyz - 0.5, max_xyz + 0.5]]))
self.atom_style = atom_style
self.n = sum(list_of_numbers)
self.n = sum(self._list_of_numbers)
self.names = list()
for name in list_of_names:
for name in self._list_of_names:
self.names.append("_".join(re.findall(r"\w+", name)))
self.mols = list_of_molecules
self.nums = list_of_numbers
self.mols = self._list_of_molecules
self.nums = self._list_of_numbers
self.masses = pd.concat([mol.masses.copy() for mol in self.mols], ignore_index=True)
self.masses.index += 1
all_ff_kws = SECTION_KEYWORDS["ff"] + SECTION_KEYWORDS["class2"]
Expand Down Expand Up @@ -1335,8 +1286,8 @@ def __init__(
type_count += len(mol.masses)
mol_count += self.nums[i] * mols_in_data
self.atoms.index += 1
assert len(self.atoms) == len(coordinates), "Wrong number of coordinates."
self.atoms.update(coordinates)
assert len(self.atoms) == len(self._coordinates), "Wrong number of coordinates."
self.atoms.update(self._coordinates)

self.velocities = None
assert self.mols[0].velocities is None, "Velocities not supported"
Expand Down Expand Up @@ -1531,45 +1482,6 @@ def get_string(self, distance=6, velocity=8, charge=4, hybrid=True):
lines.insert(1, info)
return "\n".join(lines)

@classmethod
def from_dict(cls, d):
"""
Constructor that reads in a dictionary.
Args:
d (dict): Dictionary to read.
"""

def decode_df(s):
return pd.read_json(s, orient="split", dtype=False)

items = dict()
items["list_of_molecules"] = [LammpsData.from_dict(mol) for mol in d["list_of_molecules"]]
items["list_of_numbers"] = d["list_of_numbers"]
items["coordinates"] = decode_df(d["coordinates"])
items["list_of_names"] = d["list_of_names"]
items["atom_style"] = d["atom_style"]

return cls(**items)

def as_dict(self):
"""
Returns the CombinedData as a dict.
"""

def encode_df(df):
return df.to_json(orient="split")

d = dict()
d["@module"] = self.__class__.__module__
d["@class"] = self.__class__.__name__
d["list_of_molecules"] = [mol.as_dict() for mol in self.mols]
d["list_of_numbers"] = self.nums.copy()
d["list_of_names"] = self.names.copy()
d["coordinates"] = encode_df(self.atoms[["x", "y", "z"]])
d["atom_style"] = self.atom_style

return d

def as_lammpsdata(self):
"""
Convert a CombinedData object to a LammpsData object. attributes are deepcopied.
Expand Down
21 changes: 14 additions & 7 deletions pymatgen/io/lammps/tests/test_data.py
Expand Up @@ -10,6 +10,7 @@

import numpy as np
import pandas as pd
from monty.json import MontyEncoder, MontyDecoder

from pymatgen.core import yaml
from pymatgen.core.periodic_table import Element
Expand Down Expand Up @@ -516,19 +517,22 @@ def test_from_structure(self):
np.testing.assert_array_equal(ld.atoms["type"], [2] * 4 + [3] * 16)

def test_json_dict(self):
encoded = json.dumps(self.ethane.as_dict())
decoded = json.loads(encoded)
c2h6 = LammpsData.from_dict(decoded)
encoded = json.dumps(self.ethane.as_dict(), cls=MontyEncoder)
c2h6 = json.loads(encoded, cls=MontyDecoder)
c2h6.masses.index = c2h6.masses.index.map(int)
c2h6.atoms.index = c2h6.atoms.index.map(int)
pd.testing.assert_frame_equal(c2h6.masses, self.ethane.masses)
pd.testing.assert_frame_equal(c2h6.atoms, self.ethane.atoms)
ff = self.ethane.force_field
key, target_df = random.sample(ff.items(), 1)[0]
c2h6.force_field[key].index = c2h6.force_field[key].index.map(int)
self.assertIsNone(
pd.testing.assert_frame_equal(c2h6.force_field[key], target_df, check_dtype=False),
key,
)
topo = self.ethane.topology
key, target_df = random.sample(topo.items(), 1)[0]
c2h6.topology[key].index = c2h6.topology[key].index.map(int)
self.assertIsNone(pd.testing.assert_frame_equal(c2h6.topology[key], target_df), key)

@classmethod
Expand Down Expand Up @@ -1112,34 +1116,37 @@ def test_disassemble(self):
self.assertDictEqual(v_ff.maps["Atoms"], dict(Qa1=1))

def test_json_dict(self):
encoded = json.dumps(self.li_ec.as_dict())
decoded = json.loads(encoded)
lic3o3h4 = CombinedData.from_dict(decoded)
encoded = json.dumps(self.li_ec.as_dict(), cls=MontyEncoder)
lic3o3h4 = json.loads(encoded, cls=MontyDecoder)
self.assertEqual(lic3o3h4.nums, self.li_ec.nums)
self.assertEqual(lic3o3h4.names, self.li_ec.names)
self.assertEqual(lic3o3h4.atom_style, self.li_ec.atom_style)
pd.testing.assert_frame_equal(lic3o3h4.masses, self.li_ec.masses)
pd.testing.assert_frame_equal(lic3o3h4.atoms, self.li_ec.atoms)
ff = self.li_ec.force_field
key, target_df = random.sample(ff.items(), 1)[0]
lic3o3h4.force_field[key].index = lic3o3h4.force_field[key].index.map(int)
self.assertIsNone(
pd.testing.assert_frame_equal(lic3o3h4.force_field[key], target_df, check_dtype=False),
key,
)
topo = self.li_ec.topology
key, target_df = random.sample(topo.items(), 1)[0]
self.assertIsNone(pd.testing.assert_frame_equal(lic3o3h4.topology[key], target_df), key)

lic3o3h4.mols[1].masses.index = lic3o3h4.mols[1].masses.index.map(int)
lic3o3h4.mols[1].atoms.index = lic3o3h4.mols[1].atoms.index.map(int)
pd.testing.assert_frame_equal(lic3o3h4.mols[1].masses, self.li_ec.mols[1].masses)
pd.testing.assert_frame_equal(lic3o3h4.mols[1].atoms, self.li_ec.mols[1].atoms)
ff_1 = self.li_ec.mols[1].force_field
key, target_df = random.sample(ff_1.items(), 1)[0]
lic3o3h4.mols[1].force_field[key].index = lic3o3h4.mols[1].force_field[key].index.map(int)
self.assertIsNone(
pd.testing.assert_frame_equal(lic3o3h4.mols[1].force_field[key], target_df, check_dtype=False),
key,
)
topo_1 = self.li_ec.mols[1].topology
key, target_df = random.sample(topo_1.items(), 1)[0]
lic3o3h4.mols[1].topology[key].index = lic3o3h4.mols[1].topology[key].index.map(int)
self.assertIsNone(pd.testing.assert_frame_equal(lic3o3h4.mols[1].topology[key], target_df), key)

def test_as_lammpsdata(self):
Expand Down

0 comments on commit cab0331

Please sign in to comment.