atomict 1.2.17__py3-none-any.whl → 1.2.20__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/trajectory.py DELETED
@@ -1,437 +0,0 @@
1
- """Trajectory implementation using msgpack storage"""
2
- import os
3
- import contextlib
4
- import io
5
-
6
- __all__ = ['Trajectory']
7
-
8
-
9
- def Trajectory(filename, mode='r', atoms=None, properties=None, master=None, comm=None, flush_interval=1):
10
- """A Trajectory can be created in read, write or append mode.
11
-
12
- Parameters:
13
-
14
- filename: str
15
- The name of the file. Traditionally ends in .traj, but .mpk is recommended for msgpack.
16
- mode: str
17
- The mode. 'r' is read mode, the file should already exist, and
18
- no atoms argument should be specified.
19
- 'w' is write mode. The atoms argument specifies the Atoms
20
- object to be written to the file, if not given it must instead
21
- be given as an argument to the write() method.
22
- 'a' is append mode. It acts as write mode, except that
23
- data is appended to a preexisting file.
24
- atoms: Atoms object
25
- The Atoms object to be written in write or append mode.
26
- properties: list of str
27
- If specified, these calculator properties are saved in the
28
- trajectory. If not specified, all supported quantities are
29
- saved. Possible values: energy, forces, stress, dipole,
30
- charges, magmom and magmoms.
31
- master: bool
32
- Controls which process does the actual writing. The
33
- default is that process number 0 does this. If this
34
- argument is given, processes where it is True will write.
35
- comm: Communicator object
36
- Communicator to handle parallel file reading and writing.
37
- flush_interval: int
38
- Controls how often the trajectory is written to disk. By default,
39
- the trajectory is written to disk after every frame (flush_interval=1).
40
- For production runs with many frames, a higher value like 10 or 100
41
- can significantly improve performance by reducing I/O operations.
42
-
43
- The atoms, properties and master arguments are ignored in read mode.
44
- """
45
- if comm is None:
46
- try:
47
- from ase.parallel import world
48
- comm = world
49
- except ImportError:
50
- comm = _DummyComm()
51
-
52
- if mode == 'r':
53
- return TrajectoryReader(filename)
54
- return TrajectoryWriter(filename, mode, atoms, properties, master=master, comm=comm, flush_interval=flush_interval)
55
-
56
-
57
- class _DummyComm:
58
- """Dummy communicator for when ASE is not installed."""
59
- @property
60
- def rank(self):
61
- return 0
62
-
63
- def sum_scalar(self, value):
64
- return value
65
-
66
-
67
- class TrajectoryWriter:
68
- """Writes Atoms objects to a .mpk file using msgpack."""
69
-
70
- def __init__(self, filename, mode='w', atoms=None, properties=None, master=None, comm=None, flush_interval=1):
71
- """A Trajectory writer, in write or append mode.
72
-
73
- Parameters:
74
-
75
- filename: str
76
- The name of the file. .mpk extension is recommended for msgpack.
77
- mode: str
78
- The mode. 'w' is write mode. The atoms argument specifies the Atoms
79
- object to be written to the file, if not given it must instead
80
- be given as an argument to the write() method.
81
- 'a' is append mode. It acts as write mode, except that
82
- data is appended to a preexisting file.
83
- atoms: Atoms object
84
- The Atoms object to be written in write or append mode.
85
- properties: list of str
86
- If specified, these calculator properties are saved in the
87
- trajectory. If not specified, all supported quantities are
88
- saved. Possible values: energy, forces, stress, dipole,
89
- charges, magmom and magmoms.
90
- master: bool
91
- Controls which process does the actual writing. The
92
- default is that process number 0 does this. If this
93
- argument is given, processes where it is True will write.
94
- comm: MPI communicator
95
- MPI communicator for this trajectory writer, by default world.
96
- flush_interval: int
97
- Controls how often the trajectory is written to disk. By default,
98
- the trajectory is written to disk after every frame (flush_interval=1).
99
- For production runs with many frames, a higher value like 10 or 100
100
- can significantly improve performance by reducing I/O operations.
101
- """
102
- try:
103
- import msgpack
104
- import msgpack_numpy as m
105
- except ImportError:
106
- raise ImportError("You need to install with `pip install atomict[utils]` to use msgpack I/O")
107
-
108
- # Enable numpy array serialization
109
- m.patch()
110
-
111
- if comm is None:
112
- try:
113
- from ase.parallel import world
114
- comm = world
115
- except ImportError:
116
- comm = _DummyComm()
117
-
118
- if master is None:
119
- master = comm.rank == 0
120
-
121
- self.filename = filename
122
- self.mode = mode
123
- self.atoms = atoms
124
- self.properties = properties
125
- self.master = master
126
- self.comm = comm
127
- self.description = {}
128
- self.flush_interval = max(1, flush_interval) # Ensure at least 1
129
-
130
- # Track if this is first write to ensure it's always flushed
131
- self._is_first_write = True
132
- self._frames = []
133
- self._frames_since_last_flush = 0
134
- self._total_frames_added = 0 # Track total frames added for flush interval
135
-
136
- # Get ASE version if available
137
- try:
138
- from ase import __version__ as ase_version
139
- except ImportError:
140
- ase_version = "not_installed"
141
-
142
- # Store metadata in separate dict to ensure it's preserved
143
- self._metadata = {
144
- "description": {},
145
- "ase_version": ase_version
146
- }
147
-
148
- self._open(filename, mode)
149
-
150
- def __enter__(self):
151
- return self
152
-
153
- def __exit__(self, exc_type, exc_value, tb):
154
- self.close()
155
-
156
- def set_description(self, description):
157
- """Set the description metadata for the trajectory."""
158
- self.description.update(description)
159
- self._metadata["description"].update(description)
160
-
161
- def _open(self, filename, mode):
162
- if mode not in 'aw':
163
- raise ValueError('mode must be "w" or "a".')
164
-
165
- if mode == 'a' and os.path.exists(self.filename) and self.master:
166
- # Load existing data in append mode
167
- with TrajectoryReader(self.filename) as reader:
168
- self._frames = [atoms for atoms in reader]
169
- # Copy description if available
170
- if reader.description:
171
- self.description.update(reader.description)
172
- self._metadata["description"].update(reader.description)
173
- self._is_first_write = False
174
- self._total_frames_added = len(self._frames)
175
- else:
176
- self._frames = []
177
- self._is_first_write = True
178
- self._total_frames_added = 0
179
-
180
- def write(self, atoms=None, **kwargs):
181
- """Write the atoms to the file.
182
-
183
- If the atoms argument is not given, the atoms object specified
184
- when creating the trajectory object is used.
185
-
186
- Use keyword arguments to add extra properties::
187
-
188
- writer.write(atoms, energy=117, dipole=[0, 0, 1.0])
189
- """
190
- if atoms is None:
191
- atoms = self.atoms
192
-
193
- for image in atoms.iterimages():
194
- self._write_atoms(image, **kwargs)
195
-
196
- def _write_atoms(self, atoms, **kwargs):
197
- if not self.master:
198
- return
199
-
200
- # Apply calculator properties if provided
201
- if kwargs and hasattr(atoms, 'calc'):
202
- try:
203
- from ase.calculators.singlepoint import SinglePointCalculator
204
- # Create a SinglePointCalculator with the provided properties
205
- calc = SinglePointCalculator(atoms, **kwargs)
206
- atoms.calc = calc
207
- except ImportError:
208
- # If ASE not available, store properties directly in atoms.info
209
- for key, value in kwargs.items():
210
- atoms.info[f'_calc_{key}'] = value
211
-
212
- # IMPORTANT: Make a deep copy to preserve calculator data
213
- atoms_copy = atoms.copy()
214
-
215
- # CRITICAL: If there's a calculator, make sure we preserve its data in atoms_copy.info
216
- if hasattr(atoms, 'calc') and atoms.calc is not None:
217
- # Store calculator name
218
- atoms_copy.info['_calc_name'] = atoms.calc.__class__.__name__
219
-
220
- # Try to preserve all calculator results in atoms_copy.info
221
- if hasattr(atoms.calc, 'results'):
222
- for key, value in atoms.calc.results.items():
223
- atoms_copy.info[f'_calc_{key}'] = value
224
-
225
- # Make sure energy, forces, and stress are included if available
226
- try:
227
- if 'energy' not in atoms.calc.results and hasattr(atoms.calc, 'get_potential_energy'):
228
- energy = atoms.calc.get_potential_energy(atoms)
229
- atoms_copy.info['_calc_energy'] = energy
230
-
231
- if 'forces' not in atoms.calc.results and hasattr(atoms.calc, 'get_forces'):
232
- forces = atoms.calc.get_forces(atoms)
233
- atoms_copy.info['_calc_forces'] = forces
234
-
235
- if 'stress' not in atoms.calc.results and hasattr(atoms.calc, 'get_stress'):
236
- stress = atoms.calc.get_stress(atoms)
237
- atoms_copy.info['_calc_stress'] = stress
238
- except:
239
- pass
240
-
241
- # Save the copy
242
- self._frames.append(atoms_copy)
243
- self._frames_since_last_flush += 1
244
- self._total_frames_added += 1
245
-
246
- # Save to disk if:
247
- # 1. First write (always flush first frame)
248
- # 2. We've accumulated enough frames based on flush interval
249
- if self._is_first_write or self._total_frames_added % self.flush_interval == 0:
250
- self._save()
251
- self._frames_since_last_flush = 0
252
- self._is_first_write = False
253
-
254
- def _save(self):
255
- """Save all frames to the file."""
256
- if not self.master or not self._frames:
257
- return
258
-
259
- from .msgpack import save_msgpack_trajectory
260
-
261
- # Save with metadata - directly use msgpack functions
262
- save_msgpack_trajectory(self._frames, self.filename, metadata=self._metadata)
263
-
264
- def flush(self):
265
- """Flush the trajectory to disk."""
266
- if self.master and self._frames_since_last_flush > 0:
267
- self._save()
268
- self._frames_since_last_flush = 0
269
-
270
- def close(self):
271
- """Close the trajectory file."""
272
- if self.master and self._frames_since_last_flush > 0:
273
- self._save()
274
- self._frames_since_last_flush = 0
275
-
276
- def __len__(self):
277
- return self.comm.sum_scalar(len(self._frames))
278
-
279
-
280
- class TrajectoryReader:
281
- """Reads Atoms objects from a msgpack trajectory file."""
282
-
283
- def __init__(self, filename):
284
- """A Trajectory in read mode.
285
-
286
- The filename traditionally ends in .traj, but .mpk is recommended for msgpack.
287
- """
288
- self.filename = filename
289
- self._frames = None
290
- self.description = None
291
- self.ase_version = None
292
-
293
- self._open(filename)
294
-
295
- def __enter__(self):
296
- return self
297
-
298
- def __exit__(self, exc_type, exc_value, tb):
299
- self.close()
300
-
301
- def _open(self, filename):
302
- from .msgpack import load_msgpack_trajectory
303
-
304
- # Load trajectory with metadata - directly use msgpack functions
305
- atoms_list, metadata = load_msgpack_trajectory(filename)
306
-
307
- self._frames = atoms_list
308
-
309
- # Extract description and version from metadata
310
- if metadata and 'description' in metadata:
311
- self.description = metadata['description']
312
- else:
313
- self.description = {}
314
-
315
- if metadata and 'ase_version' in metadata:
316
- self.ase_version = metadata['ase_version']
317
- else:
318
- self.ase_version = 'unknown'
319
-
320
- def close(self):
321
- """Close the trajectory file."""
322
- # Nothing to do for msgpack files
323
- pass
324
-
325
- def __getitem__(self, i=-1):
326
- if isinstance(i, slice):
327
- return SlicedTrajectory(self, i)
328
-
329
- # Get a copy of the frame
330
- atoms = self._frames[i].copy()
331
-
332
- # Explicitly restore calculator if calc data exists in atoms.info
333
- if any(key.startswith('_calc_') for key in atoms.info):
334
- try:
335
- from ase.calculators.singlepoint import SinglePointCalculator
336
- calc = SinglePointCalculator(atoms)
337
-
338
- # Collect all calc data from info
339
- for key, value in atoms.info.items():
340
- if key.startswith('_calc_') and key != '_calc_name':
341
- prop_name = key[6:] # Remove '_calc_' prefix
342
- calc.results[prop_name] = value
343
-
344
- # Only set calculator if we have results
345
- if calc.results:
346
- atoms.calc = calc
347
- except ImportError:
348
- pass
349
-
350
- return atoms
351
-
352
- def __len__(self):
353
- return len(self._frames)
354
-
355
- def __iter__(self):
356
- for i in range(len(self)):
357
- yield self[i]
358
-
359
-
360
- class SlicedTrajectory:
361
- """Wrapper to return a slice from a trajectory without loading
362
- from disk. Initialize with a trajectory (in read mode) and the
363
- desired slice object."""
364
-
365
- def __init__(self, trajectory, sliced):
366
- self.trajectory = trajectory
367
- self.map = range(len(self.trajectory))[sliced]
368
-
369
- def __getitem__(self, i):
370
- if isinstance(i, slice):
371
- # Map directly to the original traj, not recursively.
372
- traj = SlicedTrajectory(self.trajectory, slice(0, None))
373
- traj.map = self.map[i]
374
- return traj
375
-
376
- # Use the trajectory's __getitem__ method to get calculator-restored atoms
377
- return self.trajectory[self.map[i]]
378
-
379
- def __len__(self):
380
- return len(self.map)
381
-
382
-
383
- def read_traj(fd, index):
384
- """Read msgpack trajectory for ase.io.read()."""
385
- trj = TrajectoryReader(fd)
386
-
387
- for i in range(*index.indices(len(trj))):
388
- yield trj[i]
389
-
390
-
391
- @contextlib.contextmanager
392
- def defer_compression(fd):
393
- """Defer the file compression until all the configurations are read."""
394
- # We do this because the trajectory and compressed-file
395
- # internals do not play well together.
396
- # Be advised not to defer compression of very long trajectories
397
- # as they use a lot of memory.
398
- try:
399
- from ase.io.formats import is_compressed
400
- except ImportError:
401
- # Simple fallback check for compression
402
- def is_compressed(filename):
403
- if hasattr(filename, 'name'):
404
- filename = filename.name
405
- return (filename.endswith('.gz') or filename.endswith('.bz2') or
406
- filename.endswith('.xz'))
407
-
408
- if is_compressed(fd):
409
- with io.BytesIO() as bytes_io:
410
- try:
411
- # write the uncompressed data to the buffer
412
- yield bytes_io
413
- finally:
414
- # write the buffered data to the compressed file
415
- bytes_io.seek(0)
416
- fd.write(bytes_io.read())
417
- else:
418
- yield fd
419
-
420
-
421
- def write_traj(fd, images):
422
- """Write image(s) to msgpack trajectory."""
423
- try:
424
- from ase.atoms import Atoms
425
- except ImportError:
426
- # Just do a type check
427
- Atoms = None
428
-
429
- if Atoms is not None and isinstance(images, Atoms):
430
- images = [images]
431
- elif not isinstance(images, list):
432
- images = [images]
433
-
434
- with defer_compression(fd) as fd_uncompressed:
435
- trj = TrajectoryWriter(fd_uncompressed)
436
- for atoms in images:
437
- trj.write(atoms)