atomict 1.2.20__py3-none-any.whl → 1.2.22__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/__version__.py CHANGED
@@ -1 +1 @@
1
- __version__ = "1.2.20"
1
+ __version__ = "1.2.22"
@@ -1,5 +1,5 @@
1
1
  from concurrent.futures import ThreadPoolExecutor
2
- from typing import Dict, List, Optional, Tuple, Union, TYPE_CHECKING
2
+ from typing import Dict, List, Optional, Tuple, Union, TYPE_CHECKING, Any, cast
3
3
 
4
4
  if TYPE_CHECKING:
5
5
  from ase import Atoms
@@ -15,6 +15,145 @@ def _chunk_size(max_workers: int) -> int:
15
15
  return max(1, max_workers * 4)
16
16
 
17
17
 
18
+ def _read_tess_header(filename: str) -> Dict[str, Any]:
19
+
20
+ try:
21
+ import msgpack
22
+ import msgpack_numpy as m
23
+ import mmap
24
+ except ImportError:
25
+ raise ImportError("You need to install with `pip install atomict[utils]` to use the newer formats")
26
+
27
+ # Enable numpy array deserialization for header contents that may include numpy arrays
28
+ m.patch()
29
+
30
+ with open(filename, 'rb') as f:
31
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
32
+ try:
33
+ # Advise the kernel we'll read sequentially if available
34
+ if hasattr(mm, 'madvise'):
35
+ import mmap as mmap_module
36
+ if hasattr(mmap_module, 'MADV_SEQUENTIAL'):
37
+ mm.madvise(mmap_module.MADV_SEQUENTIAL)
38
+
39
+ file_size = mm.size()
40
+ header_start = int.from_bytes(mm[file_size - 8:file_size], 'little')
41
+ header_bytes = mm[header_start:file_size - 8]
42
+ header = msgpack.unpackb(header_bytes, raw=False, strict_map_key=False)
43
+
44
+ format_version = header.get('format_version', 1)
45
+ if format_version not in {2, 3, 4, 5}:
46
+ raise ValueError("Invalid format version")
47
+
48
+ # Normalize frame_offsets to a list of tuples for convenience
49
+ if 'frame_offsets' in header and isinstance(header['frame_offsets'], list):
50
+ header['frame_offsets'] = [tuple(offset) for offset in header['frame_offsets']]
51
+
52
+ return header
53
+ finally:
54
+ mm.close()
55
+
56
+
57
+ def _decode_frame(frame_bytes: bytes, header: Dict[str, Any], template_atoms: Optional['Atoms'] = None) -> 'Atoms':
58
+
59
+ try:
60
+ import msgpack
61
+ import msgpack_numpy as m
62
+ from atomict.io.atoms import dict_to_atoms
63
+ from ase import Atoms
64
+ from ase.calculators.singlepoint import SinglePointCalculator
65
+ import zlib
66
+ import lz4.block
67
+ except ImportError:
68
+ raise ImportError("You need to install with `pip install atomict[utils]` to use the newer formats")
69
+
70
+ # Enable numpy array deserialization for any numpy contents
71
+ m.patch()
72
+
73
+ compression_info = header.get('compression')
74
+ if isinstance(compression_info, dict):
75
+ compression_type = compression_info.get('type', 'none')
76
+ elif isinstance(compression_info, str):
77
+ compression_type = compression_info
78
+ else:
79
+ compression_type = 'none'
80
+ compression_type = (compression_type or 'none').lower()
81
+
82
+ # Decompress if needed
83
+ if compression_type == 'zlib':
84
+ frame_bytes = zlib.decompress(frame_bytes)
85
+ elif compression_type == 'lz4':
86
+ frame_bytes = lz4.block.decompress(frame_bytes)
87
+
88
+ # Unpack frame
89
+ frame_dict = msgpack.unpackb(frame_bytes, raw=False, strict_map_key=False)
90
+
91
+ format_version = header.get('format_version', 1)
92
+
93
+ # Fast path for v4/v5 using static header data
94
+ if format_version in {4, 5}:
95
+ static_data = header.get('static_data', {})
96
+
97
+ # Either copy provided template or construct one from static data
98
+ if template_atoms is not None:
99
+ atoms = template_atoms.copy()
100
+ else:
101
+ numbers = static_data['numbers']
102
+ masses = static_data['masses']
103
+ pbc = static_data['pbc']
104
+ atoms = Atoms(numbers=numbers, pbc=pbc)
105
+ atoms.set_masses(masses)
106
+ if 'cell' in static_data and static_data['cell'] is not None:
107
+ atoms.set_cell(static_data['cell'])
108
+ if 'tags' in static_data and static_data['tags'] is not None:
109
+ atoms.set_tags(static_data['tags'])
110
+ if 'initial_charges' in static_data and static_data['initial_charges'] is not None:
111
+ atoms.set_initial_charges(static_data['initial_charges'])
112
+ if 'initial_magmoms' in static_data and static_data['initial_magmoms'] is not None:
113
+ atoms.set_initial_magnetic_moments(static_data['initial_magmoms'])
114
+
115
+ # Per-frame updates
116
+ atoms.set_positions(frame_dict['positions'])
117
+ if static_data.get('cell_changes', True) and 'cell' in frame_dict:
118
+ atoms.set_cell(frame_dict['cell'])
119
+
120
+ if format_version == 5:
121
+ if 'tags' in frame_dict:
122
+ atoms.set_tags(frame_dict['tags'])
123
+ if 'initial_charges' in frame_dict:
124
+ atoms.set_initial_charges(frame_dict['initial_charges'])
125
+ if 'initial_magmoms' in frame_dict:
126
+ atoms.set_initial_magnetic_moments(frame_dict['initial_magmoms'])
127
+ if 'momenta' in frame_dict:
128
+ atoms.set_momenta(frame_dict['momenta'])
129
+ if 'forces' in frame_dict:
130
+ atoms.arrays['forces'] = frame_dict['forces']
131
+ if 'info' in frame_dict and isinstance(frame_dict['info'], dict):
132
+ atoms.info.update(frame_dict['info'])
133
+ if 'custom_arrays' in frame_dict and isinstance(frame_dict['custom_arrays'], dict):
134
+ for k, v in frame_dict['custom_arrays'].items():
135
+ atoms.arrays[k] = v
136
+
137
+ # Calculator results (merge stress if present)
138
+ calc_data = {}
139
+ if 'calc_results' in frame_dict and isinstance(frame_dict['calc_results'], dict):
140
+ calc_data = dict(frame_dict['calc_results'])
141
+ if 'stress' in frame_dict:
142
+ calc_data['stress'] = frame_dict['stress']
143
+ if len(calc_data) > 0:
144
+ calc = SinglePointCalculator(atoms)
145
+ for key, value in calc_data.items():
146
+ if key != 'name':
147
+ calc.results[key] = value
148
+ if calc.results:
149
+ atoms.calc = calc
150
+
151
+ return atoms
152
+
153
+ # Legacy path: v1-v3 store full atoms dict per frame
154
+ atoms_list, _ = dict_to_atoms(frame_dict)
155
+ return atoms_list[0]
156
+
18
157
  def write_tess(
19
158
  atoms: Union['Atoms', List['Atoms']],
20
159
  filename: str,
@@ -67,14 +206,106 @@ def write_tess(
67
206
  positions_list = [a.get_positions().astype(np.float32) for a in frames_list]
68
207
  if cell_changes:
69
208
  cells_list = [np.array(a.get_cell(), dtype=np.float32) for a in frames_list]
209
+
210
+ # Ensure constant atom count and species across frames for tess format
211
+ first_numbers = np.asarray(frames_list[0].get_atomic_numbers())
212
+ for a in frames_list[1:]:
213
+ if len(a) != len(frames_list[0]) or not np.array_equal(np.asarray(a.get_atomic_numbers()), first_numbers):
214
+ raise ValueError("tess format requires constant atom count and species across frames")
215
+
216
+ # Determine static vs per-frame ASE arrays
217
+ first_tags = np.asarray(frames_list[0].get_tags())
218
+ tags_static = all(np.array_equal(np.asarray(a.get_tags()), first_tags) for a in frames_list)
219
+
220
+ first_init_charges = np.asarray(frames_list[0].get_initial_charges())
221
+ init_charges_static = all(np.array_equal(np.asarray(a.get_initial_charges()), first_init_charges) for a in frames_list)
222
+
223
+ first_init_magmoms = np.asarray(frames_list[0].get_initial_magnetic_moments())
224
+ init_magmoms_static = all(np.array_equal(np.asarray(a.get_initial_magnetic_moments()), first_init_magmoms) for a in frames_list)
225
+
226
+ # Per-frame dynamic arrays/props presence checks
227
+ has_any_momenta = any(np.any(np.abs(a.get_momenta()) > 1e-10) for a in frames_list)
228
+ has_any_forces = any('forces' in a.arrays for a in frames_list)
229
+ has_any_stress = any(hasattr(a, 'stress') and getattr(a, 'stress') is not None for a in frames_list)
230
+
231
+ # Helper to extract calculator results per frame (aligned with atoms_to_dict)
232
+ def _calc_results_for(a):
233
+ calc_data = {}
234
+ calc_found = False
235
+ if hasattr(a, 'calc') and a.calc is not None:
236
+ calc_found = True
237
+ calc_data['name'] = a.calc.__class__.__name__
238
+ for prop in ['energy', 'free_energy', 'forces', 'stress', 'dipole', 'charges', 'magmom', 'magmoms']:
239
+ try:
240
+ if hasattr(a.calc, 'results') and prop in a.calc.results:
241
+ calc_data[prop] = a.calc.results[prop]
242
+ else:
243
+ value = a.calc.get_property(prop, a)
244
+ if value is not None:
245
+ calc_data[prop] = value
246
+ except Exception:
247
+ pass
248
+ if not calc_found and hasattr(a, 'info'):
249
+ calc_name = a.info.get('_calc_name')
250
+ if calc_name:
251
+ calc_data['name'] = calc_name
252
+ for key, value in a.info.items():
253
+ if key.startswith('_calc_') and key != '_calc_name':
254
+ calc_data[key[6:]] = value
255
+ return calc_data if len(calc_data) > 0 else None
256
+
257
+ has_any_calc = any(_calc_results_for(a) is not None for a in frames_list)
258
+
259
+ # Helper to serialize info dict values (to_dict/todict if available)
260
+ def _serialize_info(info: Dict) -> Dict:
261
+ out = {}
262
+ for k, v in (info or {}).items():
263
+ if hasattr(v, 'to_dict') and callable(v.to_dict):
264
+ out[k] = v.to_dict()
265
+ elif hasattr(v, 'todict') and callable(v.todict):
266
+ out[k] = v.todict()
267
+ else:
268
+ out[k] = v
269
+ return out
70
270
 
71
271
  # Optimized frame serialization - pack only essential per-frame data
72
272
  def _pack_frame(i: int) -> bytes:
73
273
  # Only pack data that changes between frames
274
+ a = frames_list[i]
74
275
  frame_dict = {'positions': positions_list[i]}
75
276
  if cell_changes:
76
277
  frame_dict['cell'] = cells_list[i]
77
- return msgpack.packb(frame_dict, use_bin_type=True)
278
+ # Per-frame arrays
279
+ if has_any_momenta:
280
+ frame_dict['momenta'] = a.get_momenta()
281
+ if not tags_static:
282
+ frame_dict['tags'] = a.get_tags()
283
+ if not init_charges_static:
284
+ frame_dict['initial_charges'] = a.get_initial_charges()
285
+ if not init_magmoms_static:
286
+ frame_dict['initial_magmoms'] = a.get_initial_magnetic_moments()
287
+ # Forces/stress
288
+ if has_any_forces and 'forces' in a.arrays:
289
+ frame_dict['forces'] = a.arrays['forces']
290
+ if has_any_stress and hasattr(a, 'stress') and getattr(a, 'stress') is not None:
291
+ frame_dict['stress'] = np.asarray(getattr(a, 'stress'), dtype=np.float64)
292
+ # Calculator results
293
+ if has_any_calc:
294
+ calc_data = _calc_results_for(a)
295
+ if calc_data is not None:
296
+ frame_dict['calc_results'] = calc_data
297
+ # Info dict
298
+ if hasattr(a, 'info') and a.info:
299
+ frame_dict['info'] = _serialize_info(a.info)
300
+ # Custom arrays
301
+ standard_arrays = {'numbers', 'positions', 'momenta', 'masses', 'tags', 'charges', 'forces'}
302
+ custom_arrays = {}
303
+ for key, value in a.arrays.items():
304
+ if key not in standard_arrays:
305
+ custom_arrays[key] = value
306
+ if custom_arrays:
307
+ frame_dict['custom_arrays'] = custom_arrays
308
+ return cast(bytes, msgpack.packb(frame_dict, use_bin_type=True))
78
309
 
79
310
  with open(filename, 'wb', buffering=1024*1024) as f:
80
311
  frame_offsets: List[Tuple[int, int]] = []
@@ -121,8 +352,8 @@ def write_tess(
121
352
  symbols_idx = np.array([unique_symbols_lookup[s] for s in symbols], dtype=np.uint16)
122
353
 
123
354
  # Write header
124
- header_dict: Dict[str, object] = {
125
- 'format_version': 4,
355
+ header_dict: Dict[str, Any] = {
356
+ 'format_version': 5,
126
357
  'metadata': dict(metadata or {}),
127
358
  'unique_symbols': unique_symbols,
128
359
  'num_frames': len(frames_list),
@@ -138,14 +369,20 @@ def write_tess(
138
369
  'cell_changes': cell_changes,
139
370
  }
140
371
  }
372
+ # Add static arrays when invariant across frames
373
+ if tags_static:
374
+ header_dict['static_data']['tags'] = first_tags
375
+ if init_charges_static:
376
+ header_dict['static_data']['initial_charges'] = first_init_charges
377
+ if init_magmoms_static:
378
+ header_dict['static_data']['initial_magmoms'] = first_init_magmoms
141
379
  if compression_mode != 'none':
142
- header_dict['compression'] = {
143
- 'type': compression_mode,
144
- }
380
+ comp_dict: Dict[str, Any] = {'type': compression_mode}
145
381
  if compression_mode == 'zlib':
146
- header_dict['compression']['level'] = compression_level
382
+ comp_dict['level'] = int(compression_level)
383
+ header_dict['compression'] = comp_dict
147
384
  header_dict['frame_uncompressed_lengths'] = uncompressed_lengths
148
- header_bytes = msgpack.packb(header_dict, use_bin_type=True)
385
+ header_bytes = cast(bytes, msgpack.packb(header_dict, use_bin_type=True))
149
386
  header_start = f.tell()
150
387
  f.write(header_bytes)
151
388
 
@@ -163,12 +400,33 @@ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tupl
163
400
  import mmap
164
401
  import zlib
165
402
  import lz4.block
403
+ import numpy as np
404
+ from ase.calculators.singlepoint import SinglePointCalculator
166
405
  except ImportError:
167
406
  raise ImportError("You need to install with `pip install atomict[utils]` to use the newer formats")
168
407
 
169
408
  # Enable numpy array deserialization
170
409
  m.patch()
171
410
 
411
+ # Read header once using helper
412
+ header = _read_tess_header(filename)
413
+
414
+ format_version = header.get('format_version', 1)
415
+ compression_info = header.get('compression')
416
+ if isinstance(compression_info, dict):
417
+ compression_type = compression_info.get('type', 'none')
418
+ elif isinstance(compression_info, str):
419
+ compression_type = compression_info
420
+ else:
421
+ compression_type = 'none'
422
+ compression_type = (compression_type or 'none').lower()
423
+ if compression_type not in {'none', 'zlib', 'lz4'}:
424
+ raise ValueError(f"Unsupported compression type '{compression_type}' in tess file")
425
+
426
+ metadata = header.get('metadata', {})
427
+ frame_offsets = [tuple(offset) for offset in header['frame_offsets']]
428
+ num_frames = len(frame_offsets)
429
+
172
430
  with open(filename, 'rb') as f:
173
431
  # Use mmap with larger read-ahead hint
174
432
  mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
@@ -178,30 +436,6 @@ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tupl
178
436
  import mmap as mmap_module
179
437
  if hasattr(mmap_module, 'MADV_SEQUENTIAL'):
180
438
  mm.madvise(mmap_module.MADV_SEQUENTIAL)
181
-
182
- file_size = mm.size()
183
- header_start = int.from_bytes(mm[file_size - 8:file_size], 'little')
184
- header_bytes = mm[header_start:file_size - 8]
185
- header = msgpack.unpackb(header_bytes, raw=False, strict_map_key=False)
186
-
187
- format_version = header.get('format_version', 1)
188
- if format_version not in {2, 3, 4}:
189
- raise ValueError("Invalid format version")
190
-
191
- compression_info = header.get('compression')
192
- if isinstance(compression_info, dict):
193
- compression_type = compression_info.get('type', 'none')
194
- elif isinstance(compression_info, str):
195
- compression_type = compression_info
196
- else:
197
- compression_type = 'none'
198
- compression_type = (compression_type or 'none').lower()
199
- if compression_type not in {'none', 'zlib', 'lz4'}:
200
- raise ValueError(f"Unsupported compression type '{compression_type}' in tess file")
201
-
202
- metadata = header.get('metadata', {})
203
- frame_offsets = [tuple(offset) for offset in header['frame_offsets']]
204
- num_frames = len(frame_offsets)
205
439
 
206
440
  # Determine which frames to load
207
441
  if frames_indices is not None:
@@ -218,10 +452,10 @@ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tupl
218
452
  filtered_offsets = [(i, offset) for i, offset in enumerate(frame_offsets)]
219
453
 
220
454
  # Pre-allocate the result list based on requested frames
221
- atoms_list = [None] * len(frames_to_load)
222
-
223
- # Handle format version 4 with static data
224
- if format_version == 4:
455
+ atoms_list: List[Optional[Atoms]] = [None] * len(frames_to_load)
456
+
457
+ # Handle format version 4/5 with static data
458
+ if format_version in {4, 5}:
225
459
  static_data = header.get('static_data', {})
226
460
  unique_symbols = header['unique_symbols']
227
461
  symbols_idx = static_data['symbols']
@@ -231,53 +465,33 @@ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tupl
231
465
  pbc = static_data['pbc']
232
466
  static_cell = static_data.get('cell')
233
467
  cell_changes = static_data.get('cell_changes', True)
234
-
468
+ static_tags = static_data.get('tags')
469
+ static_init_charges = static_data.get('initial_charges')
470
+ static_init_magmoms = static_data.get('initial_magmoms')
471
+
235
472
  # Create a template Atoms object to clone for efficiency
236
- import numpy as np
237
473
  template_atoms = Atoms(numbers=numbers, pbc=pbc)
238
474
  template_atoms.set_masses(masses)
239
475
  if static_cell is not None:
240
476
  template_atoms.set_cell(static_cell)
477
+ if static_tags is not None:
478
+ template_atoms.set_tags(static_tags)
479
+ if static_init_charges is not None:
480
+ template_atoms.set_initial_charges(static_init_charges)
481
+ if static_init_magmoms is not None:
482
+ template_atoms.set_initial_magnetic_moments(static_init_magmoms)
241
483
  else:
242
484
  convert = dict_to_atoms
243
485
  static_data = None
244
486
  cell_changes = True
245
-
246
- # Process frames with minimal overhead
247
- if compression_type == 'zlib' and len(filtered_offsets) > 0:
248
-
249
- def _decompress(idx_offset: Tuple[int, Tuple[int, int]]) -> Tuple[int, bytes]:
250
- orig_idx, (start, length) = idx_offset
251
- compressed = mm[start:start + length]
252
- return orig_idx, zlib.decompress(compressed)
253
-
254
- worker_count = _max_workers(len(filtered_offsets))
255
- chunk_size = _chunk_size(worker_count)
256
487
 
257
- with ThreadPoolExecutor(max_workers=worker_count) as executor:
258
- for chunk_start in range(0, len(filtered_offsets), chunk_size):
259
- offset_chunk = filtered_offsets[chunk_start:chunk_start + chunk_size]
260
- for result_idx, (orig_idx, frame_bytes) in enumerate(
261
- executor.map(_decompress, offset_chunk), start=0
262
- ):
263
- frame_dict = msgpack.unpackb(
264
- frame_bytes, raw=False, strict_map_key=False
265
- )
266
- if format_version == 4:
267
- # Fast path for v4: clone template and update only changing data
268
- atoms = template_atoms.copy()
269
- atoms.set_positions(frame_dict['positions'])
270
- if cell_changes and 'cell' in frame_dict:
271
- atoms.set_cell(frame_dict['cell'])
272
- atoms_list[chunk_start + result_idx] = atoms
273
- else:
274
- atoms_list[chunk_start + result_idx] = convert(frame_dict)[0]
275
- elif compression_type == 'lz4' and len(filtered_offsets) > 0:
276
-
277
- def _decompress(idx_offset: Tuple[int, Tuple[int, int]]) -> Tuple[int, bytes]:
488
+ # Process frames with minimal overhead
489
+ if len(filtered_offsets) > 0:
490
+ # Unified decode path using helper; still parallelized
491
+ def _decode(idx_offset: Tuple[int, Tuple[int, int]]) -> Tuple[int, 'Atoms']:
278
492
  orig_idx, (start, length) = idx_offset
279
- compressed = mm[start:start + length]
280
- return orig_idx, lz4.block.decompress(compressed)
493
+ raw_slice = mm[start:start + length]
494
+ return orig_idx, _decode_frame(raw_slice, header, template_atoms if format_version in {4, 5} else None)
281
495
 
282
496
  worker_count = _max_workers(len(filtered_offsets))
283
497
  chunk_size = _chunk_size(worker_count)
@@ -285,35 +499,11 @@ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tupl
285
499
  with ThreadPoolExecutor(max_workers=worker_count) as executor:
286
500
  for chunk_start in range(0, len(filtered_offsets), chunk_size):
287
501
  offset_chunk = filtered_offsets[chunk_start:chunk_start + chunk_size]
288
- for result_idx, (orig_idx, frame_bytes) in enumerate(
289
- executor.map(_decompress, offset_chunk), start=0
502
+ for result_idx, (orig_idx, atoms) in enumerate(
503
+ executor.map(_decode, offset_chunk), start=0
290
504
  ):
291
- frame_dict = msgpack.unpackb(
292
- frame_bytes, raw=False, strict_map_key=False
293
- )
294
- if format_version == 4:
295
- atoms = template_atoms.copy()
296
- atoms.set_positions(frame_dict['positions'])
297
- if cell_changes and 'cell' in frame_dict:
298
- atoms.set_cell(frame_dict['cell'])
299
- atoms_list[chunk_start + result_idx] = atoms
300
- else:
301
- atoms_list[chunk_start + result_idx] = convert(frame_dict)[0]
302
- else:
303
- for result_idx, (orig_idx, (start, length)) in enumerate(filtered_offsets):
304
- frame_slice = mm[start:start + length]
305
- frame_dict = msgpack.unpackb(
306
- frame_slice, raw=False, strict_map_key=False
307
- )
308
- if format_version == 4:
309
- atoms = template_atoms.copy()
310
- atoms.set_positions(frame_dict['positions'])
311
- if cell_changes and 'cell' in frame_dict:
312
- atoms.set_cell(frame_dict['cell'])
313
- atoms_list[result_idx] = atoms
314
- else:
315
- atoms_list[result_idx] = convert(frame_dict)[0]
505
+ atoms_list[chunk_start + result_idx] = atoms
316
506
  finally:
317
507
  mm.close()
318
508
 
319
- return atoms_list, metadata
509
+ return cast(List[Atoms], atoms_list), metadata
@@ -0,0 +1,263 @@
1
+ from typing import Any, Dict, Iterator, List, Optional, Union, TYPE_CHECKING
2
+
3
+ if TYPE_CHECKING:
4
+ from ase import Atoms
5
+
6
+ try:
7
+ from ase.parallel import world
8
+ except Exception:
9
+ # Fallback if ASE parallel is unavailable
10
+ class _DummyWorld:
11
+ rank = 0
12
+
13
+ def sum_scalar(self, x):
14
+ return x
15
+
16
+ world = _DummyWorld() # type: ignore[assignment]
17
+
18
+
19
+ class TrajectoryWriter:
20
+ """Unified trajectory writer supporting .traj (ASE), .atraj and .tess formats.
21
+
22
+ Mirrors the ASE TrajectoryWriter API for use in optimizers (e.g., BFGS(trajectory=...)).
23
+ Frames are written incrementally for .traj and buffered for .atraj/.tess (flushed on close).
24
+ """
25
+
26
+ def __init__(
27
+ self,
28
+ filename: str,
29
+ mode: str = "w",
30
+ atoms: Optional['Atoms'] = None,
31
+ properties: Optional[List[str]] = None,
32
+ master: Optional[bool] = None,
33
+ comm: Any = world,
34
+ metadata: Optional[Dict] = None,
35
+ tess_compression: Optional[str] = "zlib",
36
+ tess_compression_level: int = 1,
37
+ ) -> None:
38
+ """Create a trajectory writer.
39
+
40
+ Parameters mirror ASE's writer; extra kwargs configure tess compression and metadata.
41
+ """
42
+ # Deferred imports to avoid hard dependency during import time
43
+ from ase import Atoms # type: ignore
44
+
45
+ if mode not in {"w", "a"}:
46
+ raise ValueError('mode must be "w" or "a".')
47
+
48
+ self.filename = filename
49
+ self.mode = mode
50
+ self.atoms_default: Optional[Atoms] = atoms
51
+ self.properties = properties
52
+ self.comm = comm
53
+ self.master = (comm.rank == 0) if master is None else bool(master)
54
+ self._description: Dict[str, Any] = dict(metadata or {})
55
+
56
+ # Backend selection by extension
57
+ lower = filename.lower()
58
+ if lower.endswith(".traj"):
59
+ # Stream via ASE backend
60
+ from ase.io.trajectory import TrajectoryWriter as _ASEWriter
61
+
62
+ self._backend = _ASEWriter(filename, mode=mode, atoms=atoms, properties=properties, master=self.master, comm=comm)
63
+ self._backend_is_ase = True
64
+ self._buffer: Optional[List[Atoms]] = None
65
+ else:
66
+ # Buffer frames and flush on close for msgpack-based formats
67
+ self._backend = None
68
+ self._backend_is_ase = False
69
+ self._buffer = []
70
+ # Tess config
71
+ self._tess_compression = tess_compression
72
+ self._tess_compression_level = int(tess_compression_level)
73
+
74
+ def __enter__(self) -> "TrajectoryWriter":
75
+ return self
76
+
77
+ def __exit__(self, exc_type, exc_value, tb) -> None:
78
+ self.close()
79
+
80
+ def set_description(self, description: Dict[str, Any]) -> None:
81
+ # match ASE method name for compatibility
82
+ self._description.update(description or {})
83
+
84
+ def write(self, atoms: Optional['Atoms'] = None, **kwargs: Any) -> None:
85
+ """Write a single frame. If atoms is None, uses atoms passed to __init__.
86
+
87
+ For .traj, delegates to ASE. For .atraj/.tess, buffers frames and writes on close.
88
+ """
89
+ from ase import Atoms # type: ignore
90
+
91
+ image: Optional[Atoms] = atoms if atoms is not None else self.atoms_default
92
+ if image is None:
93
+ raise ValueError("No Atoms provided to write() and no default atoms set.")
94
+
95
+ if self._backend_is_ase:
96
+ # Pass through calculator properties if provided in kwargs, ASE handles it
97
+ self._backend.write(image, **kwargs)
98
+ else:
99
+ # Buffer plain ASE Atoms; handle OptimizableAtoms or wrappers
100
+ from ase import Atoms # type: ignore
101
+
102
+ plain: Optional[Atoms] = None
103
+ if isinstance(image, Atoms):
104
+ plain = image
105
+ else:
106
+ # Try common wrapper escape hatches
107
+ get_atoms = getattr(image, 'get_atoms', None)
108
+ if callable(get_atoms):
109
+ maybe_atoms = get_atoms()
110
+ if isinstance(maybe_atoms, Atoms):
111
+ plain = maybe_atoms
112
+ if plain is None:
113
+ inner = getattr(image, 'atoms', None)
114
+ if isinstance(inner, Atoms):
115
+ plain = inner
116
+ if plain is None:
117
+ # Best-effort reconstruction
118
+ numbers = getattr(image, 'get_atomic_numbers', lambda: None)()
119
+ positions = getattr(image, 'get_positions', lambda: None)()
120
+ cell = getattr(image, 'get_cell', lambda: None)()
121
+ pbc = getattr(image, 'get_pbc', lambda: None)()
122
+ if numbers is None or positions is None:
123
+ raise TypeError('Unsupported atoms-like object; expected ASE Atoms or compatible wrapper')
124
+ plain = Atoms(numbers=numbers, positions=positions, cell=cell, pbc=pbc)
125
+ self._buffer.append(plain)
126
+
127
+ def close(self) -> None:
128
+ """Flush buffered frames and/or close backend."""
129
+ if self._backend_is_ase:
130
+ self._backend.close()
131
+ return
132
+
133
+ # Write buffered frames using the chosen msgpack-based format
134
+ if not self.master:
135
+ # Only master writes similar to ASE semantics
136
+ self._buffer = []
137
+ return
138
+
139
+ if not self._buffer:
140
+ # Nothing to write
141
+ return
142
+
143
+ lower = self.filename.lower()
144
+ frames = self._buffer
145
+
146
+ if lower.endswith('.atraj'):
147
+ from atomict.io.formats.atraj import write_atraj
148
+
149
+ write_atraj(frames, self.filename, metadata=self._description or None)
150
+ elif lower.endswith('.tess'):
151
+ from atomict.io.formats.tess import write_tess
152
+
153
+ write_tess(
154
+ frames,
155
+ self.filename,
156
+ metadata=self._description or None,
157
+ compression=self._tess_compression,
158
+ compression_level=self._tess_compression_level,
159
+ )
160
+ else:
161
+ # Fallback: use ASE .traj if unknown extension
162
+ from ase.io.trajectory import TrajectoryWriter as _ASEWriter
163
+
164
+ with _ASEWriter(self.filename, mode=self.mode, properties=self.properties, master=self.master, comm=self.comm) as tw:
165
+ for fr in frames:
166
+ tw.write(fr)
167
+
168
+ # Clear buffer after writing
169
+ self._buffer = []
170
+
171
+ def __len__(self) -> int:
172
+ if self._backend_is_ase:
173
+ return self.comm.sum_scalar(len(self._backend))
174
+ return len(self._buffer or [])
175
+
176
+
177
+ class TrajectoryReader:
178
+ """Unified trajectory reader supporting .traj (ASE), .atraj and .tess formats.
179
+
180
+ Provides random access (__getitem__), slicing, iteration, and length like ASE's reader.
181
+ """
182
+
183
+ def __init__(self, filename: str) -> None:
184
+ self.filename = filename
185
+ self._metadata: Dict[str, Any] = {}
186
+ lower = filename.lower()
187
+ if lower.endswith('.traj'):
188
+ from ase.io.trajectory import TrajectoryReader as _ASEReader
189
+
190
+ self._backend = _ASEReader(filename)
191
+ self._backend_is_ase = True
192
+ self._frames: Optional[List['Atoms']] = None
193
+ elif lower.endswith('.atraj'):
194
+ from atomict.io.formats.atraj import read_atraj
195
+
196
+ frames, meta = read_atraj(filename)
197
+ self._frames = frames
198
+ self._metadata = meta or {}
199
+ self._backend = None
200
+ self._backend_is_ase = False
201
+ elif lower.endswith('.tess'):
202
+ from atomict.io.formats.tess import read_tess
203
+
204
+ frames, meta = read_tess(filename)
205
+ self._frames = frames
206
+ self._metadata = meta or {}
207
+ self._backend = None
208
+ self._backend_is_ase = False
209
+ else:
210
+ # Fallback to ASE reader
211
+ from ase.io.trajectory import TrajectoryReader as _ASEReader
212
+
213
+ self._backend = _ASEReader(filename)
214
+ self._backend_is_ase = True
215
+ self._frames = None
216
+
217
+ def __enter__(self) -> "TrajectoryReader":
218
+ return self
219
+
220
+ def __exit__(self, exc_type, exc_value, tb) -> None:
221
+ self.close()
222
+
223
+ def close(self) -> None:
224
+ if self._backend_is_ase and self._backend is not None:
225
+ self._backend.close()
226
+
227
+ def __len__(self) -> int:
228
+ if self._backend_is_ase and self._backend is not None:
229
+ return len(self._backend)
230
+ return len(self._frames or [])
231
+
232
+ def __getitem__(self, i: Union[int, slice]) -> Union['Atoms', List['Atoms']]:
233
+ if isinstance(i, slice):
234
+ if self._backend_is_ase and self._backend is not None:
235
+ return list(self._backend[i])
236
+ return (self._frames or [])[i]
237
+ # int index
238
+ if self._backend_is_ase and self._backend is not None:
239
+ return self._backend[i]
240
+ return (self._frames or [])[i]
241
+
242
+ def __iter__(self) -> Iterator['Atoms']:
243
+ if self._backend_is_ase and self._backend is not None:
244
+ for i in range(len(self._backend)):
245
+ yield self._backend[i]
246
+ else:
247
+ for fr in (self._frames or []):
248
+ yield fr
249
+
250
+ @property
251
+ def metadata(self) -> Dict[str, Any]:
252
+ return dict(self._metadata)
253
+
254
+
255
+ def Trajectory(filename: str, mode: str = 'r', atoms: Optional['Atoms'] = None, properties: Optional[List[str]] = None, master: Optional[bool] = None, comm: Any = world, **kwargs: Any):
256
+ """Factory matching ASE's ase.io.trajectory.Trajectory API.
257
+
258
+ Returns TrajectoryReader in read mode, TrajectoryWriter otherwise.
259
+ """
260
+ if mode == 'r':
261
+ return TrajectoryReader(filename)
262
+ return TrajectoryWriter(filename, mode=mode, atoms=atoms, properties=properties, master=master, comm=comm, **kwargs)
263
+
@@ -67,6 +67,16 @@ def create_phonon_run(project_id: str, source_geometry_id: str, action: str, nam
67
67
  if action not in ["LAUNCH", "DRAFT"]:
68
68
  raise ValueError(f"Invalid action: {action} (must be 'LAUNCH' or 'DRAFT')")
69
69
 
70
+ # Validate model is one of the supported constants
71
+ valid_models = [
72
+ MODEL_ORB_D3_V2,
73
+ MODEL_MATTERSIM_1_0_0_5M,
74
+ MODEL_ORB_V3_CONSERVATIVE,
75
+ MODEL_ESEN_30M_OAM,
76
+ ]
77
+ if model not in valid_models:
78
+ raise ValueError(f"Invalid model: {model}")
79
+
70
80
  payload = {
71
81
  "project_id": project_id,
72
82
  "source_geometry_id": source_geometry_id,
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: atomict
3
- Version: 1.2.20
3
+ Version: 1.2.22
4
4
  Summary: The client application for the https://atomictessellator.com/
5
5
  Author-email: Steven Anderson <steven@atomictessellator.com>, Alain Richardt <alain@atomictessellator.com>
6
6
  License: MIT
@@ -1,5 +1,5 @@
1
1
  atomict/__init__.py,sha256=nMXg9GFsk8gCcyBnh1MAeUPvo4Zcuv3sdwGHZrxfpPE,36
2
- atomict/__version__.py,sha256=nQtXpLTEUbMtAPecTV_hZAJZb9EhWc8glRv6hgKyvG4,23
2
+ atomict/__version__.py,sha256=P6UdnfqZMN8bM1yBQGaUu5LMabVISCCurCBNtZJOvTE,23
3
3
  atomict/api.py,sha256=1aI2qPMm6V9VY4PLR8LBMm2WwVCBB9pAL7sEowvjhtc,6706
4
4
  atomict/auth.py,sha256=yMEaxaSg44tSDxr4x-bjwjjn9zIsqw_bVoKd01Zd9LU,987
5
5
  atomict/env.py,sha256=RqK5SUfCDJ6aMGtCPhNmSrwsNZSjlGaDQYYk41oeBDc,2115
@@ -43,10 +43,11 @@ atomict/io/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
43
43
  atomict/io/atoms.py,sha256=kdMnto7eyiY2zmoOvLlzbuTGUCIp4ViQGwLmf2m9fGU,13144
44
44
  atomict/io/cif.py,sha256=o7oe6alug5ais2QnJhv88X7sAbZSbTkEWhHa-4Dkw1E,6040
45
45
  atomict/io/fhiaims.py,sha256=4Z5oImjZuP-k8AudrMrXqvsO0IHajDy__h5NmLr1LGY,1197
46
+ atomict/io/trajectory.py,sha256=dXquH2Y5FfFeGr0dt20S8U7DMlMDKnp7nY-TVNnkgy4,9785
46
47
  atomict/io/utils.py,sha256=ncA8XchNN3lJT8EhJK6tLJE9TvmHmPlxizTnY5ASvEc,272
47
48
  atomict/io/formats/__init__.py,sha256=_wKNHpV0VZKh7mzO6kRfaETYPxg_DYbrJwH4kqduD9Q,300
48
49
  atomict/io/formats/atraj.py,sha256=2aqS5Gcr_SzE-d-wG9FLr_ckyKFkLHSAqhZUR9cXyR4,3355
49
- atomict/io/formats/tess.py,sha256=frQYIdNWE8NQL19F6BWV_lW6nJ9WwMX-yBrx_xmtSUA,14044
50
+ atomict/io/formats/tess.py,sha256=tUyMucFgfEQDBWVM1-2yGzpkvNym0v0_RfSxE5H6sW0,21952
50
51
  atomict/io/formats/traj.py,sha256=AaojyrUzTMiobt2Nhyc7UCjNX1efGnvhV6z1avPtK-4,2273
51
52
  atomict/ml/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
52
53
  atomict/ml/model.py,sha256=Ug6IyRNNQ5_SHnQabFHnCCAGTHa9jxrRAUAkBsdcjgo,279
@@ -72,7 +73,7 @@ atomict/simulation/mattergen.py,sha256=ybzJy0nwIAZhG8IIuhlmi-_J6lLyci3aVo35h2ni_
72
73
  atomict/simulation/md.py,sha256=C32Sh2sv9PQ1lyGaWYFmG5evKk3Jqw0wel2ml4uPnJw,770
73
74
  atomict/simulation/mlrelax.py,sha256=ZS9WoO9efHeSNXM-MxuqQMSWN54qDKLscBgxL4monfI,2841
74
75
  atomict/simulation/models.py,sha256=RSVLldNurx7F-ijlrLuVyljMS06bsZCBFMXNcdzdOuU,115
75
- atomict/simulation/phonon.py,sha256=Mmk0LveKHGkw0Jo7GJCphKXsxbZCFZE9tKRkGGwNcUs,2785
76
+ atomict/simulation/phonon.py,sha256=UG6v-mpfF-STw0DK-620v26Rpc2EzAx4K-8KykzHtm8,3080
76
77
  atomict/simulation/qe.py,sha256=3PpqpA0Pn3FCGEgjaMnCidguhopGxFUDMaxwfIQF2FE,1700
77
78
  atomict/simulation/sh.py,sha256=YymnH9q8aD_THiielicTKgPGcRunsAcoV5bZKu__L0w,609
78
79
  atomict/simulation/sqs.py,sha256=1neQRVUy21R_UVusML6ocz6RVwxGUVh81CMr2TljGbw,1132
@@ -84,9 +85,9 @@ atomict/utils/tenacity.py,sha256=phc6YPEk7idqiFFeHeK-ngiAaqVOZFYp8S7dX1k-YXc,998
84
85
  atomict/utils/traj.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
85
86
  atomict/utils/fhiaims/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
86
87
  atomict/utils/fhiaims/geometry.py,sha256=3Ap6gO7UsLFXBl9Ohv8Vmfpvwu0fohpzgdxOFGg6Tmc,2281
87
- atomict-1.2.20.dist-info/licenses/LICENSE,sha256=fzvTkxUzi2u1cea_aRtmg5_mRk6ZyLWJJRr49K28qKg,1075
88
- atomict-1.2.20.dist-info/METADATA,sha256=Sk30hOT87B04NfvZjw-rYasA_Xkf03tA_swSWn2aH3A,3359
89
- atomict-1.2.20.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
90
- atomict-1.2.20.dist-info/entry_points.txt,sha256=PozguIUgJUHgS65PSZBHNPUiwYGDwXa4vLZ7hde3aq8,47
91
- atomict-1.2.20.dist-info/top_level.txt,sha256=CCo525YmAj7ZbToMmQcVKQ-JiIiFKiq3GmhIYCG2gaM,8
92
- atomict-1.2.20.dist-info/RECORD,,
88
+ atomict-1.2.22.dist-info/licenses/LICENSE,sha256=fzvTkxUzi2u1cea_aRtmg5_mRk6ZyLWJJRr49K28qKg,1075
89
+ atomict-1.2.22.dist-info/METADATA,sha256=XxRDMiy2U6X_dUN-zP4zyazSrIws3uBF42MGC6_7Ho8,3359
90
+ atomict-1.2.22.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
91
+ atomict-1.2.22.dist-info/entry_points.txt,sha256=PozguIUgJUHgS65PSZBHNPUiwYGDwXa4vLZ7hde3aq8,47
92
+ atomict-1.2.22.dist-info/top_level.txt,sha256=CCo525YmAj7ZbToMmQcVKQ-JiIiFKiq3GmhIYCG2gaM,8
93
+ atomict-1.2.22.dist-info/RECORD,,