Coverage for ase/io/jsonio.py: 89.29%
112 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1import datetime
2import json
4import numpy as np
6from ase.utils import reader, writer
8# Note: We are converting JSON classes to the recommended mechanisms
9# by the json module. That means instead of classes, we will use the
10# functions default() and object_hook().
11#
12# The encoder classes are to be deprecated (but maybe not removed, if
13# widely used).
16def default(obj):
17 if hasattr(obj, 'todict'):
18 dct = obj.todict()
20 if not isinstance(dct, dict):
21 raise RuntimeError(
22 'todict() of {} returned object of type {} '
23 'but should have returned dict'.format(obj, type(dct))
24 )
25 if hasattr(obj, 'ase_objtype'):
26 # We modify the dictionary, so it is wise to take a copy.
27 dct = dct.copy()
28 dct['__ase_objtype__'] = obj.ase_objtype
30 return dct
31 if isinstance(obj, np.ndarray):
32 flatobj = obj.ravel()
33 if np.iscomplexobj(obj):
34 flatobj = flatobj.view(obj.real.dtype)
35 # We use str(obj.dtype) here instead of obj.dtype.name, because
36 # they are not always the same (e.g. for numpy arrays of strings).
37 # Using obj.dtype.name can break the ability to recursively decode/
38 # encode such arrays.
39 return {'__ndarray__': (obj.shape, str(obj.dtype), flatobj.tolist())}
40 if isinstance(obj, np.integer):
41 return int(obj)
42 if isinstance(obj, np.floating):
43 return float(obj)
44 if isinstance(obj, np.bool_):
45 return bool(obj)
46 if isinstance(obj, datetime.datetime):
47 return {'__datetime__': obj.isoformat()}
48 if isinstance(obj, complex):
49 return {'__complex__': (obj.real, obj.imag)}
51 raise TypeError(
52 f'Cannot convert object of type {type(obj)} to dictionary for JSON'
53 )
56class MyEncoder(json.JSONEncoder):
57 def default(self, obj):
58 # (Note the name "default" comes from the outer namespace, so
59 # not actually recursive)
60 return default(obj)
63encode = MyEncoder().encode
66def object_hook(dct):
67 if '__datetime__' in dct:
68 return datetime.datetime.strptime(
69 dct['__datetime__'], '%Y-%m-%dT%H:%M:%S.%f'
70 )
72 if '__complex__' in dct:
73 return complex(*dct['__complex__'])
75 if '__ndarray__' in dct:
76 return create_ndarray(*dct['__ndarray__'])
78 # No longer used (only here for backwards compatibility):
79 if '__complex_ndarray__' in dct:
80 r, i = (np.array(x) for x in dct['__complex_ndarray__'])
81 return r + i * 1j
83 if '__ase_objtype__' in dct:
84 objtype = dct.pop('__ase_objtype__')
85 dct = numpyfy(dct)
86 return create_ase_object(objtype, dct)
88 return dct
91def create_ndarray(shape, dtype, data):
92 """Create ndarray from shape, dtype and flattened data."""
93 array = np.empty(shape, dtype=dtype)
94 flatbuf = array.ravel()
95 if np.iscomplexobj(array):
96 flatbuf = flatbuf.view(array.real.dtype)
97 flatbuf[:] = data
98 return array
101def create_ase_object(objtype, dct):
102 # We just try each object type one after another and instantiate
103 # them manually, depending on which kind it is.
104 # We can formalize this later if it ever becomes necessary.
105 if objtype == 'cell':
106 from ase.cell import Cell
108 dct.pop('pbc', None) # compatibility; we once had pbc
109 obj = Cell(**dct)
110 elif objtype == 'bandstructure':
111 from ase.spectrum.band_structure import BandStructure
113 obj = BandStructure(**dct)
114 elif objtype == 'bandpath':
115 from ase.dft.kpoints import BandPath
117 obj = BandPath(path=dct.pop('labelseq'), **dct)
118 elif objtype == 'atoms':
119 from ase import Atoms
121 obj = Atoms.fromdict(dct)
122 elif objtype == 'vibrationsdata':
123 from ase.vibrations import VibrationsData
125 obj = VibrationsData.fromdict(dct)
126 else:
127 raise ValueError(
128 'Do not know how to decode object type {} '
129 'into an actual object'.format(objtype)
130 )
131 assert obj.ase_objtype == objtype
132 return obj
135mydecode = json.JSONDecoder(object_hook=object_hook).decode
138def intkey(key):
139 """Convert str to int if possible."""
140 try:
141 return int(key)
142 except ValueError:
143 return key
146def fix_int_keys_in_dicts(obj):
147 """Convert "int" keys: "1" -> 1.
149 The json.dump() function will convert int keys in dicts to str keys.
150 This function goes the other way.
151 """
152 if isinstance(obj, dict):
153 return {
154 intkey(key): fix_int_keys_in_dicts(value)
155 for key, value in obj.items()
156 }
157 return obj
160def numpyfy(obj):
161 if isinstance(obj, dict):
162 if '__complex_ndarray__' in obj:
163 r, i = (np.array(x) for x in obj['__complex_ndarray__'])
164 return r + i * 1j
165 if isinstance(obj, list) and len(obj) > 0:
166 try:
167 a = np.array(obj)
168 except ValueError:
169 pass
170 else:
171 if a.dtype in [bool, int, float]:
172 return a
173 obj = [numpyfy(value) for value in obj]
174 return obj
177def decode(txt, always_array=True):
178 obj = mydecode(txt)
179 obj = fix_int_keys_in_dicts(obj)
180 if always_array:
181 obj = numpyfy(obj)
182 return obj
185@reader
186def read_json(fd, always_array=True):
187 dct = decode(fd.read(), always_array=always_array)
188 return dct
191@writer
192def write_json(fd, obj):
193 fd.write(encode(obj))