Skip to content

Commit

Permalink
Merge pull request #1036 from pyiron/pickle_atoms
Browse files Browse the repository at this point in the history
Pickle atoms
  • Loading branch information
liamhuber authored Jun 6, 2023
2 parents b954db3 + b3a3aae commit bd1022c
Show file tree
Hide file tree
Showing 3 changed files with 34 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pyiron_atomistics/atomistics/structure/atoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,14 @@ def __init__(
# Velocities were not handled at all during file writing
self._velocities = None

def __setstate__(self, state):
self.__dict__.update(state)

def __getstate__(self):
# Only necessary to support pickling in python <3.11
# https://docs.python.org/release/3.11.2/library/pickle.html#object.__getstate__
return self.__dict__

@property
def velocities(self):
return self._velocities
Expand Down
19 changes: 19 additions & 0 deletions pyiron_atomistics/atomistics/structure/periodic_table.py
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,14 @@ def __getitem__(self, item):
if item in self.sub.index:
return self.sub[item]

def __setstate__(self, state):
self.__dict__.update(state)

def __getstate__(self):
# Only necessary to support pickling in python <3.11
# https://docs.python.org/release/3.11.2/library/pickle.html#object.__getstate__
return self.__dict__

def __eq__(self, other):
if self is other:
return True
Expand Down Expand Up @@ -223,6 +231,17 @@ def __getitem__(self, item):
if item in self.dataframe.index.values:
return self.dataframe.loc[item]

def __setstate__(self, state):
"""
Used by (cloud)pickle; force the state update to avoid recursion pickling Atoms
"""
self.__dict__.update(state)

def __getstate__(self):
# Only necessary to support pickling in python <3.11
# https://docs.python.org/release/3.11.2/library/pickle.html#object.__getstate__
return self.__dict__

def from_hdf(self, hdf):
"""
loads an element with his parameters from the hdf5 job file by creating an Object of the ChemicalElement type.
Expand Down
7 changes: 7 additions & 0 deletions tests/atomistics/structure/test_atoms.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import unittest
import numpy as np
import os
import pickle
import time
import warnings
from pyiron_atomistics.atomistics.structure.atom import Atom
Expand Down Expand Up @@ -1953,6 +1954,12 @@ def test_calc_to_hdf(self):
msg=f"Calculator parameter {k} not correctly restored from HDF!",
)

def test_pickle(self):
pickled = pickle.dumps(self.C3)
unpickled = pickle.loads(pickled)
self.assertEqual(unpickled, self.C3)
self.assertTrue(np.allclose(unpickled.cell, self.C3.cell))


def generate_fcc_lattice(a=4.2):
positions = [[0, 0, 0]]
Expand Down

0 comments on commit bd1022c

Please sign in to comment.