atomict 1.2.4.1__py3-none-any.whl → 1.2.8__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
atomict/io/msgpack.py ADDED
@@ -0,0 +1,499 @@
1
+ from typing import Union, List, Dict, Any, Tuple
2
+
3
+
4
+ def atoms_to_dict(atoms_list, selective=False):
5
+ """Extract all properties from ASE Atoms objects into a standardized dictionary.
6
+
7
+ Parameters:
8
+ -----------
9
+ atoms_list : List[Atoms]
10
+ List of ASE Atoms objects
11
+ selective : bool
12
+ If True, only include non-default properties
13
+
14
+ Returns:
15
+ --------
16
+ Dict
17
+ Dictionary with all extracted properties
18
+ """
19
+ import numpy as np
20
+
21
+ # Create data structure with common properties
22
+ data = {
23
+ 'n_frames': len(atoms_list),
24
+ 'n_atoms': [len(a) for a in atoms_list],
25
+ }
26
+
27
+ # Process all symbols efficiently
28
+ unique_symbols = set()
29
+ for a in atoms_list:
30
+ unique_symbols.update(a.get_chemical_symbols())
31
+ unique_symbols = sorted(list(unique_symbols))
32
+
33
+ # Store symbols data differently for variable atom count trajectories
34
+ data['unique_symbols'] = unique_symbols
35
+ data['symbols'] = []
36
+ for a in atoms_list:
37
+ # Convert each atom's symbols to indices in the unique_symbols list
38
+ symbols_idx = [unique_symbols.index(s) for s in a.get_chemical_symbols()]
39
+ data['symbols'].append(np.array(symbols_idx, dtype=np.uint16))
40
+
41
+ # Store standard properties
42
+ data['positions'] = [a.get_positions() for a in atoms_list]
43
+
44
+ # Handle cell objects consistently
45
+ cells = []
46
+ for a in atoms_list:
47
+ cell = a.get_cell()
48
+ # Handle Cell object vs numpy array
49
+ if hasattr(cell, 'array'):
50
+ cells.append(np.array(cell.array, dtype=np.float32))
51
+ else:
52
+ cells.append(np.array(cell, dtype=np.float32))
53
+ data['cell'] = cells
54
+
55
+ data['pbc'] = [a.get_pbc() for a in atoms_list]
56
+ data['numbers'] = [a.get_atomic_numbers() for a in atoms_list]
57
+
58
+ # Always include masses for proper atomic weights
59
+ data['masses'] = [a.get_masses() for a in atoms_list]
60
+
61
+ # For selective mode, only include non-default properties
62
+ if selective:
63
+ # Include tags only if they're non-zero
64
+ has_tags = any(np.any(a.get_tags() != 0) for a in atoms_list)
65
+ if has_tags:
66
+ data['tags'] = [a.get_tags() for a in atoms_list]
67
+
68
+ # Include momenta only if they're non-zero
69
+ has_momenta = any(np.any(np.abs(a.get_momenta()) > 1e-10) for a in atoms_list)
70
+ if has_momenta:
71
+ data['momenta'] = [a.get_momenta() for a in atoms_list]
72
+
73
+ # Include charges only if they're non-zero
74
+ has_charges = any(np.any(np.abs(a.get_initial_charges()) > 1e-10) for a in atoms_list)
75
+ if has_charges:
76
+ data['initial_charges'] = [a.get_initial_charges() for a in atoms_list]
77
+
78
+ # Include magmoms only if they're non-zero
79
+ has_magmoms = any(np.any(np.abs(a.get_initial_magnetic_moments()) > 1e-10) for a in atoms_list)
80
+ if has_magmoms:
81
+ data['initial_magmoms'] = [a.get_initial_magnetic_moments() for a in atoms_list]
82
+ else:
83
+ # Always include these for maximum compatibility
84
+ data['tags'] = [a.get_tags() for a in atoms_list]
85
+ data['momenta'] = [a.get_momenta() for a in atoms_list]
86
+ data['initial_charges'] = [a.get_initial_charges() for a in atoms_list]
87
+ data['initial_magmoms'] = [a.get_initial_magnetic_moments() for a in atoms_list]
88
+
89
+ # Get all constraints
90
+ if any(a.constraints for a in atoms_list):
91
+ data['constraints'] = [[c.todict() for c in a.constraints] for a in atoms_list]
92
+
93
+ # Handle custom properties
94
+ if any(hasattr(a, 'ase_objtype') for a in atoms_list):
95
+ data['ase_objtype'] = [getattr(a, 'ase_objtype', None) for a in atoms_list]
96
+
97
+ if any(hasattr(a, 'top_mask') for a in atoms_list):
98
+ data['top_mask'] = [getattr(a, 'top_mask', None) for a in atoms_list]
99
+
100
+ # Handle forces array
101
+ if any('forces' in a.arrays for a in atoms_list):
102
+ data['forces'] = [a.arrays.get('forces', np.zeros((len(a), 3), dtype=np.float32))
103
+ for a in atoms_list]
104
+
105
+ # Handle calculator data - store in all cases where a calculator exists
106
+ has_calc = False
107
+ calc_data_list = []
108
+
109
+ for a in atoms_list:
110
+ calc_data = {}
111
+ calc_found = False
112
+
113
+ # First try getting data from the calculator object directly
114
+ if hasattr(a, 'calc') and a.calc is not None:
115
+ has_calc = True
116
+ calc_found = True
117
+ # Store calculator name and results
118
+ calc_name = a.calc.__class__.__name__
119
+ calc_data['name'] = calc_name
120
+
121
+ # Try all standard properties
122
+ for prop in ['energy', 'free_energy', 'forces', 'stress', 'dipole', 'charges', 'magmom', 'magmoms']:
123
+ try:
124
+ if hasattr(a.calc, 'results') and prop in a.calc.results:
125
+ calc_data[prop] = a.calc.results[prop]
126
+ else:
127
+ value = a.calc.get_property(prop, a)
128
+ if value is not None:
129
+ calc_data[prop] = value
130
+ except Exception:
131
+ pass
132
+
133
+ # If no calculator directly available, try to get data from atoms.info
134
+ if not calc_found and hasattr(a, 'info'):
135
+ # Check for calculator data stored in info
136
+ calc_name = a.info.get('_calc_name')
137
+
138
+ if calc_name:
139
+ has_calc = True
140
+ calc_data['name'] = calc_name
141
+
142
+ # Extract stored calculator properties
143
+ for key, value in a.info.items():
144
+ if key.startswith('_calc_') and key != '_calc_name':
145
+ prop_name = key[6:] # Remove '_calc_' prefix
146
+ calc_data[prop_name] = value
147
+
148
+ # If we found any calculator info, mark as found
149
+ if len(calc_data) > 1: # More than just the name
150
+ calc_found = True
151
+
152
+ calc_data_list.append(calc_data)
153
+
154
+ if has_calc:
155
+ data['calc_results'] = calc_data_list
156
+
157
+ # Include stress only if present in any frame
158
+ has_stress = any(hasattr(a, 'stress') and a.stress is not None for a in atoms_list)
159
+ if has_stress:
160
+ data['stress'] = [getattr(a, 'stress', np.zeros(6, dtype=np.float32)) for a in atoms_list]
161
+
162
+ # Store atom info dictionaries
163
+ if any(a.info for a in atoms_list):
164
+ infos = []
165
+ for a in atoms_list:
166
+ info = a.info.copy()
167
+ # Call to_dict on each info dictionary
168
+ for key, value in info.items():
169
+ if hasattr(value, 'to_dict') and callable(value.to_dict):
170
+ info[key] = value.to_dict()
171
+ elif hasattr(value, 'todict') and callable(value.todict):
172
+ info[key] = value.todict()
173
+ else:
174
+ info[key] = value
175
+ infos.append(info)
176
+ data['atom_infos'] = infos
177
+
178
+ # Extract custom arrays
179
+ standard_arrays = {'numbers', 'positions', 'momenta', 'masses', 'tags', 'charges'}
180
+ custom_arrays = {}
181
+
182
+ for i, atom in enumerate(atoms_list):
183
+ for key, value in atom.arrays.items():
184
+ if key not in standard_arrays:
185
+ if key not in custom_arrays:
186
+ custom_arrays[key] = [None] * len(atoms_list)
187
+ custom_arrays[key][i] = value
188
+
189
+ if custom_arrays:
190
+ data['custom_arrays'] = custom_arrays
191
+
192
+ return data
193
+
194
+
195
+ def dict_to_atoms(data):
196
+ """Create ASE Atoms objects from a dictionary of properties.
197
+
198
+ Parameters:
199
+ -----------
200
+ data : Dict
201
+ Dictionary with all properties
202
+
203
+ Returns:
204
+ --------
205
+ List[Atoms]
206
+ List of ASE Atoms objects
207
+ """
208
+ try:
209
+ import numpy as np
210
+ from ase import Atoms
211
+ from ase.constraints import dict2constraint
212
+ from ase.calculators.singlepoint import SinglePointCalculator
213
+ except ImportError:
214
+ raise ImportError("You need to install with `pip install atomict[tools]` to use msgpack I/O")
215
+
216
+ n_frames = data['n_frames']
217
+ atoms_list = []
218
+
219
+ # Get unique symbols
220
+ unique_symbols = data['unique_symbols']
221
+ symbols_map = data['symbols']
222
+
223
+ # Loop through frames
224
+ for i in range(n_frames):
225
+ # Get symbols for this frame - handle both old and new format
226
+ if isinstance(symbols_map[i], np.ndarray):
227
+ frame_symbols = [unique_symbols[idx] for idx in symbols_map[i]]
228
+ else:
229
+ # Legacy format - symbols were stored as a 2D array
230
+ idx = i * data['n_atoms'][i]
231
+ frame_symbols = [unique_symbols[symbols_map[idx + j]] for j in range(data['n_atoms'][i])]
232
+
233
+ # Create atoms object with basic properties
234
+ atoms = Atoms(
235
+ symbols=frame_symbols,
236
+ positions=data['positions'][i],
237
+ cell=data['cell'][i],
238
+ pbc=data['pbc'][i],
239
+ )
240
+
241
+ # Set optional properties if they exist
242
+ if 'tags' in data:
243
+ atoms.set_tags(data['tags'][i])
244
+
245
+ if 'masses' in data:
246
+ atoms.set_masses(data['masses'][i])
247
+
248
+ if 'momenta' in data:
249
+ atoms.set_momenta(data['momenta'][i])
250
+
251
+ if 'initial_charges' in data:
252
+ atoms.set_initial_charges(data['initial_charges'][i])
253
+
254
+ if 'initial_magmoms' in data:
255
+ atoms.set_initial_magnetic_moments(data['initial_magmoms'][i])
256
+
257
+ if 'top_mask' in data and i < len(data['top_mask']) and data['top_mask'][i] is not None:
258
+ atoms.top_mask = np.array(data['top_mask'][i], dtype=bool)
259
+
260
+ if 'numbers' in data:
261
+ atoms.set_atomic_numbers(data['numbers'][i])
262
+
263
+ if 'constraints' in data and i < len(data['constraints']):
264
+ for c in data['constraints'][i]:
265
+ atoms.constraints.append(dict2constraint(c))
266
+
267
+ if 'ase_objtype' in data and i < len(data['ase_objtype']) and data['ase_objtype'][i] is not None:
268
+ atoms.ase_objtype = data['ase_objtype'][i]
269
+
270
+ if 'forces' in data and i < len(data['forces']):
271
+ atoms.arrays['forces'] = data['forces'][i]
272
+
273
+ if 'stress' in data and i < len(data['stress']):
274
+ atoms.stress = np.array(data['stress'][i], dtype=np.float64).copy()
275
+
276
+ # Restore atom info
277
+ if 'atom_infos' in data and i < len(data['atom_infos']):
278
+ atoms.info.update(data['atom_infos'][i])
279
+
280
+ # Restore custom arrays
281
+ if 'custom_arrays' in data:
282
+ for key, values in data['custom_arrays'].items():
283
+ if i < len(values) and values[i] is not None:
284
+ atoms.arrays[key] = values[i]
285
+
286
+ # Restore calculator if present
287
+ calc_created = False
288
+ calc_data = {}
289
+
290
+ # First try from calc_results (new format)
291
+ if 'calc_results' in data and i < len(data['calc_results']):
292
+ calc_data = data['calc_results'][i]
293
+
294
+ if calc_data and len(calc_data) > 1: # Only create calculator if there's data beyond just the name
295
+ # Initialize a SinglePointCalculator
296
+ calc = SinglePointCalculator(atoms)
297
+
298
+ # Set all available results directly to results dict
299
+ for key, value in calc_data.items():
300
+ if key != 'name': # Skip calculator name
301
+ calc.results[key] = value
302
+
303
+ # Only set calculator if we have actual results
304
+ if calc.results:
305
+ atoms.calc = calc
306
+ calc_created = True
307
+
308
+ # If no calculator created yet, check atoms.info for calculator data
309
+ if not calc_created:
310
+ calc_info = {}
311
+ for key, value in atoms.info.items():
312
+ if key.startswith('_calc_') and key != '_calc_name':
313
+ prop_name = key[6:] # Remove '_calc_' prefix
314
+ calc_info[prop_name] = value
315
+
316
+ # Create calculator if we have any info data
317
+ if calc_info:
318
+ calc = SinglePointCalculator(atoms)
319
+ for key, value in calc_info.items():
320
+ calc.results[key] = value
321
+ atoms.calc = calc
322
+
323
+ atoms_list.append(atoms)
324
+
325
+ return atoms_list
326
+
327
+
328
+ def load_msgpack(filename: str, strict_map_key: bool = True) -> Union['ase.Atoms', List['ase.Atoms']]:
329
+ """Load atoms from a msgpack file with high efficiency and speed.
330
+
331
+ Parameters:
332
+ -----------
333
+ filename : str
334
+ The input filename
335
+ strict_map_key : bool, default=False
336
+ If True, only allow string keys in msgpack dictionaries
337
+ If False, allow integer and other keys in msgpack dictionaries
338
+ """
339
+
340
+ try:
341
+ import msgpack
342
+ import msgpack_numpy as m
343
+ except ImportError:
344
+ raise ImportError("You need to install with `pip install atomict[tools]` to use msgpack I/O")
345
+
346
+ # Enable numpy array deserialization
347
+ m.patch()
348
+
349
+ # Load data
350
+ with open(filename, 'rb') as f:
351
+ data = msgpack.unpack(f, raw=False, strict_map_key=strict_map_key)
352
+
353
+ # Convert to atoms objects
354
+ atoms_list = dict_to_atoms(data)
355
+
356
+ # Return single atom or list based on input
357
+ return atoms_list[0] if data['n_frames'] == 1 else atoms_list
358
+
359
+
360
+ def save_msgpack(atoms: Union['ase.Atoms', List['ase.Atoms']], filename: str):
361
+ """Save atoms to a msgpack file with high efficiency and speed."""
362
+
363
+ try:
364
+ import msgpack
365
+ import msgpack_numpy as m
366
+ from ase import Atoms
367
+ except ImportError:
368
+ raise ImportError("You need to install with `pip install atomict[tools]` to use msgpack I/O")
369
+
370
+ # Enable numpy array serialization
371
+ m.patch()
372
+
373
+ # Single atoms case - convert to list
374
+ if isinstance(atoms, Atoms):
375
+ atoms_list = [atoms]
376
+ else:
377
+ atoms_list = atoms
378
+
379
+ # Extract properties to dictionary - use selective mode for single atoms
380
+ # to avoid storing default properties
381
+ selective = len(atoms_list) == 1
382
+ data = atoms_to_dict(atoms_list, selective=selective)
383
+
384
+ # Pack and save
385
+ with open(filename, 'wb') as f:
386
+ msgpack.pack(data, f, use_bin_type=True)
387
+
388
+
389
+ def save_msgpack_trajectory(atoms: Union['ase.Atoms', List['ase.Atoms']], filename: str, metadata: Dict = None):
390
+ """Save atoms to a msgpack trajectory file with metadata.
391
+
392
+ Parameters:
393
+ -----------
394
+ atoms : Atoms or list of Atoms
395
+ The atoms to save
396
+ filename : str
397
+ The output filename
398
+ metadata : dict, optional
399
+ Additional metadata to store with the trajectory
400
+ """
401
+ try:
402
+ import msgpack
403
+ import msgpack_numpy as m
404
+ from ase import Atoms
405
+ except ImportError:
406
+ raise ImportError("You need to install with `pip install atomict[tools]` to use msgpack I/O")
407
+
408
+ # Enable numpy array serialization
409
+ m.patch()
410
+
411
+ # Single atoms case - convert to list
412
+ if isinstance(atoms, Atoms):
413
+ atoms_list = [atoms]
414
+ else:
415
+ atoms_list = atoms
416
+
417
+ # Create container for the trajectory data
418
+ traj_data = {
419
+ 'format_version': 1, # Version for future compatibility
420
+ 'metadata': metadata or {},
421
+ }
422
+
423
+ # Extract properties to dictionary - no selective mode for trajectories
424
+ atoms_data = atoms_to_dict(atoms_list, selective=False)
425
+
426
+ # Add atoms data to the trajectory container
427
+ traj_data['atoms_data'] = atoms_data
428
+
429
+ # Pack and save
430
+ with open(filename, 'wb') as f:
431
+ msgpack.pack(traj_data, f, use_bin_type=True)
432
+
433
+
434
+ def load_msgpack_trajectory(filename: str, strict_map_key: bool = True) -> Tuple[List['ase.Atoms'], Dict]:
435
+ """Load atoms from a msgpack trajectory file with metadata.
436
+
437
+ Parameters:
438
+ -----------
439
+ filename : str
440
+ The input filename
441
+ strict_map_key : bool, default=False
442
+ If True, only allow string keys in msgpack dictionaries
443
+ If False, allow integer and other keys in msgpack dictionaries
444
+
445
+ Returns:
446
+ --------
447
+ atoms_list : list of Atoms
448
+ The loaded atoms
449
+ metadata : dict
450
+ The metadata stored with the trajectory
451
+ """
452
+ try:
453
+ import msgpack
454
+ import msgpack_numpy as m
455
+ except ImportError:
456
+ raise ImportError("You need to install with `pip install atomict[tools]` to use msgpack I/O")
457
+
458
+ # Enable numpy array deserialization
459
+ m.patch()
460
+
461
+ # Load data
462
+ with open(filename, 'rb') as f:
463
+ traj_data = msgpack.unpack(f, raw=False, strict_map_key=strict_map_key)
464
+
465
+ # Check if this is a new-style trajectory with format_version
466
+ if isinstance(traj_data, dict) and 'format_version' in traj_data:
467
+ metadata = traj_data.get('metadata', {})
468
+ atoms_data = traj_data.get('atoms_data', {})
469
+ else:
470
+ # Legacy format - just raw atoms data
471
+ metadata = {}
472
+ atoms_data = traj_data
473
+
474
+ # Ensure that calculated properties are transferred to the calculator in dict_to_atoms
475
+ if 'calc_results' not in atoms_data and hasattr(atoms_data, 'get') and atoms_data.get('forces') is not None:
476
+ # If we have forces in the data but no calc_results, create calc_results entries
477
+ calc_data_list = []
478
+ n_frames = atoms_data.get('n_frames', 0)
479
+
480
+ for i in range(n_frames):
481
+ calc_data = {'name': 'SinglePointCalculator'}
482
+ if 'forces' in atoms_data and i < len(atoms_data['forces']):
483
+ calc_data['forces'] = atoms_data['forces'][i]
484
+ if 'stress' in atoms_data and i < len(atoms_data['stress']):
485
+ calc_data['stress'] = atoms_data['stress'][i]
486
+ if 'energy' in atoms_data and i < len(atoms_data['energy']):
487
+ calc_data['energy'] = atoms_data['energy'][i]
488
+ calc_data_list.append(calc_data)
489
+
490
+ atoms_data['calc_results'] = calc_data_list
491
+
492
+ # Convert to atoms objects
493
+ atoms_list = dict_to_atoms(atoms_data)
494
+
495
+ # Make sure atoms_list is always a list
496
+ if not isinstance(atoms_list, list):
497
+ atoms_list = [atoms_list]
498
+
499
+ return atoms_list, metadata