materialsproject / pymatgen

Python Materials Genomics (pymatgen) is a robust materials analysis code that defines classes for structures and molecules with support for many electronic structure codes. It powers the Materials Project.
https://pymatgen.org
Other
1.48k stars 852 forks source link

`MSONAtoms` may not serialize appropriately if the `.info` flag is populated #3668

Closed Andrew-S-Rosen closed 6 months ago

Andrew-S-Rosen commented 6 months ago

Python version

3.9+

Pymatgen version

2024.3.1

Operating system version

No response

Current behavior

The recently introduced MSONAtoms class in https://github.com/materialsproject/pymatgen/pull/3619 gives Pymatgen additional flexibility in making ASE Atoms objects MSONable, helping with lossless (de)serialization. This method generally works well, but JSON serialization can fail if the .info attribute of the Atoms object contains an MSONable entry.

Expected Behavior

The MSONAtoms should be JSON serializable via the various monty utilities (for instance).

Minimal example

from pymatgen.core import Structure
from monty.serialization import dumpfn

structure = Structure(
    lattice=[[0, 2.13, 2.13], [2.13, 0, 2.13], [2.13, 2.13, 0]],
    species=["Mg", "O"],
    coords=[[0, 0, 0], [0.5, 0.5, 0.5]],
)
mson_atoms = structure.to_ase_atoms()
mson_atoms.info["test"] = structure
dumpfn(mson_atoms, "test.json")

or...

from ase.build import bulk
from pymatgen.io.ase import AseAtomsAdaptor
from monty.serialization import dumpfn

atoms = bulk("Cu")
atoms.info["test"] = AseAtomsAdaptor().get_structure(atoms)
structure = AseAtomsAdaptor.get_structure(atoms)
mson_atoms = structure.to_ase_atoms()
dumpfn(mson_atoms, "test.json")

In both cases, you get

TypeError: Cannot convert object of type <class 'pymatgen.core.structure.Structure'> to dictionary for JSON
Andrew-S-Rosen commented 6 months ago

I don't actually know that this one is readily solvable since people can dump whatever they want into .info, and the logic for the (de)serialization is in monty.

I'll close this as a result but wanted to report it anyway.