atomict 1.2.20__tar.gz → 1.2.22__tar.gz

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.
Files changed (101) hide show
  1. {atomict-1.2.20 → atomict-1.2.22}/PKG-INFO +1 -1
  2. atomict-1.2.22/atomict/__version__.py +1 -0
  3. atomict-1.2.22/atomict/io/formats/tess.py +509 -0
  4. atomict-1.2.22/atomict/io/trajectory.py +263 -0
  5. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/phonon.py +10 -0
  6. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/PKG-INFO +1 -1
  7. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/SOURCES.txt +1 -0
  8. atomict-1.2.20/atomict/__version__.py +0 -1
  9. atomict-1.2.20/atomict/io/formats/tess.py +0 -319
  10. {atomict-1.2.20 → atomict-1.2.22}/LICENSE +0 -0
  11. {atomict-1.2.20 → atomict-1.2.22}/README.md +0 -0
  12. {atomict-1.2.20 → atomict-1.2.22}/atomict/__init__.py +0 -0
  13. {atomict-1.2.20 → atomict-1.2.22}/atomict/api.py +0 -0
  14. {atomict-1.2.20 → atomict-1.2.22}/atomict/ase/atatoms.py +0 -0
  15. {atomict-1.2.20 → atomict-1.2.22}/atomict/auth.py +0 -0
  16. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/__init__.py +0 -0
  17. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/adsorbate.py +0 -0
  18. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/ai_assist.py +0 -0
  19. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/catalysis.py +0 -0
  20. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/common.py +0 -0
  21. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/exploration/__init__.py +0 -0
  22. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/exploration/soec.py +0 -0
  23. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/exploration/sqs.py +0 -0
  24. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/helpers.py +0 -0
  25. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/k8s.py +0 -0
  26. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/login.py +0 -0
  27. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/organization.py +0 -0
  28. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/project.py +0 -0
  29. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation/__init__.py +0 -0
  30. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation/catalysis.py +0 -0
  31. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation/fhiaims.py +0 -0
  32. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation/kpoint.py +0 -0
  33. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation/vibes.py +0 -0
  34. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/simulation.py +0 -0
  35. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/task.py +0 -0
  36. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/token.py +0 -0
  37. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/traj.py +0 -0
  38. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/upload.py +0 -0
  39. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/commands/user.py +0 -0
  40. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/core/client.py +0 -0
  41. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/core/config.py +0 -0
  42. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/core/utils.py +0 -0
  43. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/ext/custom_classes.py +0 -0
  44. {atomict-1.2.20 → atomict-1.2.22}/atomict/cli/main.py +0 -0
  45. {atomict-1.2.20 → atomict-1.2.22}/atomict/env.py +0 -0
  46. {atomict-1.2.20 → atomict-1.2.22}/atomict/exceptions.py +0 -0
  47. {atomict-1.2.20 → atomict-1.2.22}/atomict/infra/__init__.py +0 -0
  48. {atomict-1.2.20 → atomict-1.2.22}/atomict/infra/distwork/__init__.py +0 -0
  49. {atomict-1.2.20 → atomict-1.2.22}/atomict/infra/distwork/environment.py +0 -0
  50. {atomict-1.2.20 → atomict-1.2.22}/atomict/infra/distwork/task.py +0 -0
  51. {atomict-1.2.20 → atomict-1.2.22}/atomict/infra/logging.py +0 -0
  52. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/__init__.py +0 -0
  53. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/atoms.py +0 -0
  54. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/cif.py +0 -0
  55. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/fhiaims.py +0 -0
  56. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/formats/__init__.py +0 -0
  57. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/formats/atraj.py +0 -0
  58. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/formats/traj.py +0 -0
  59. {atomict-1.2.20 → atomict-1.2.22}/atomict/io/utils.py +0 -0
  60. {atomict-1.2.20 → atomict-1.2.22}/atomict/ml/__init__.py +0 -0
  61. {atomict-1.2.20 → atomict-1.2.22}/atomict/ml/model.py +0 -0
  62. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/__init__.py +0 -0
  63. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/link.py +0 -0
  64. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/note.py +0 -0
  65. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/project.py +0 -0
  66. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/tags.py +0 -0
  67. {atomict-1.2.20 → atomict-1.2.22}/atomict/project/workbench.py +0 -0
  68. {atomict-1.2.20 → atomict-1.2.22}/atomict/reality/__init__.py +0 -0
  69. {atomict-1.2.20 → atomict-1.2.22}/atomict/reality/oqmd.py +0 -0
  70. {atomict-1.2.20 → atomict-1.2.22}/atomict/reality/slabs.py +0 -0
  71. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/__init__.py +0 -0
  72. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/cantera.py +0 -0
  73. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/catalysis.py +0 -0
  74. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/counterfactual.py +0 -0
  75. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/defect.py +0 -0
  76. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/ea.py +0 -0
  77. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/fhi_aims.py +0 -0
  78. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/impact.py +0 -0
  79. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/kpoint.py +0 -0
  80. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/mattergen.py +0 -0
  81. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/md.py +0 -0
  82. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/mlrelax.py +0 -0
  83. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/models.py +0 -0
  84. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/qe.py +0 -0
  85. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/sh.py +0 -0
  86. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/sqs.py +0 -0
  87. {atomict-1.2.20 → atomict-1.2.22}/atomict/simulation/utils.py +0 -0
  88. {atomict-1.2.20 → atomict-1.2.22}/atomict/user/__init__.py +0 -0
  89. {atomict-1.2.20 → atomict-1.2.22}/atomict/user/files.py +0 -0
  90. {atomict-1.2.20 → atomict-1.2.22}/atomict/user/workspace.py +0 -0
  91. {atomict-1.2.20 → atomict-1.2.22}/atomict/utils/fhiaims/__init__.py +0 -0
  92. {atomict-1.2.20 → atomict-1.2.22}/atomict/utils/fhiaims/geometry.py +0 -0
  93. {atomict-1.2.20 → atomict-1.2.22}/atomict/utils/tenacity.py +0 -0
  94. {atomict-1.2.20 → atomict-1.2.22}/atomict/utils/traj.py +0 -0
  95. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/dependency_links.txt +0 -0
  96. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/entry_points.txt +0 -0
  97. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/requires.txt +0 -0
  98. {atomict-1.2.20 → atomict-1.2.22}/atomict.egg-info/top_level.txt +0 -0
  99. {atomict-1.2.20 → atomict-1.2.22}/pyproject.toml +0 -0
  100. {atomict-1.2.20 → atomict-1.2.22}/requirements.txt +0 -0
  101. {atomict-1.2.20 → atomict-1.2.22}/setup.cfg +0 -0
@@ -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
@@ -0,0 +1 @@
1
+ __version__ = "1.2.22"
@@ -0,0 +1,509 @@
1
+ from concurrent.futures import ThreadPoolExecutor
2
+ from typing import Dict, List, Optional, Tuple, Union, TYPE_CHECKING, Any, cast
3
+
4
+ if TYPE_CHECKING:
5
+ from ase import Atoms
6
+
7
+
8
+ def _max_workers(task_count: int) -> int:
9
+ if task_count <= 1:
10
+ return 1
11
+ return max(1, min(task_count, 24))
12
+
13
+
14
+ def _chunk_size(max_workers: int) -> int:
15
+ return max(1, max_workers * 4)
16
+
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
+
157
+ def write_tess(
158
+ atoms: Union['Atoms', List['Atoms']],
159
+ filename: str,
160
+ metadata: Optional[Dict] = None,
161
+ compression: Optional[str] = 'none',
162
+ compression_level: int = 0,
163
+ ) -> None:
164
+
165
+ try:
166
+ import msgpack
167
+ import msgpack_numpy as m
168
+ from ase import Atoms
169
+ import zlib
170
+ import lz4.block
171
+ import numpy as np
172
+ except ImportError:
173
+ raise ImportError("You need to install with `pip install atomict[utils]` to use the newer formats")
174
+
175
+ # Enable numpy array serialization
176
+ m.patch()
177
+
178
+ if isinstance(atoms, Atoms):
179
+ frames_list = [atoms]
180
+ else:
181
+ frames_list = list(atoms)
182
+
183
+ compression_mode = (compression or 'none').lower()
184
+ if compression_mode not in {'none', 'zlib', 'lz4'}:
185
+ raise ValueError(
186
+ f"Unsupported compression mode '{compression_mode}' for tess format"
187
+ )
188
+ if compression_mode == 'zlib' and not (0 <= compression_level <= 9):
189
+ raise ValueError("compression_level must be between 0 and 9 for zlib compression")
190
+
191
+ # Collect global unique_symbols
192
+ unique_symbols_set = set()
193
+ for a in frames_list:
194
+ unique_symbols_set.update(a.get_chemical_symbols())
195
+ unique_symbols = sorted(list(unique_symbols_set))
196
+ unique_symbols_lookup = {s: i for i, s in enumerate(unique_symbols)}
197
+
198
+ # Check if cell changes across frames
199
+ first_cell = np.array(frames_list[0].get_cell(), dtype=np.float32)
200
+ cell_changes = any(
201
+ not np.allclose(np.array(a.get_cell(), dtype=np.float32), first_cell, rtol=1e-6)
202
+ for a in frames_list[1:20] # Sample first 20 frames
203
+ )
204
+
205
+ # Pre-extract positions as float32 arrays for all frames
206
+ positions_list = [a.get_positions().astype(np.float32) for a in frames_list]
207
+ if cell_changes:
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
270
+
271
+ # Optimized frame serialization - pack only essential per-frame data
272
+ def _pack_frame(i: int) -> bytes:
273
+ # Only pack data that changes between frames
274
+ a = frames_list[i]
275
+ frame_dict = {'positions': positions_list[i]}
276
+ if cell_changes:
277
+ frame_dict['cell'] = cells_list[i]
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))
309
+
310
+ with open(filename, 'wb', buffering=1024*1024) as f:
311
+ frame_offsets: List[Tuple[int, int]] = []
312
+ uncompressed_lengths: List[int] = []
313
+ if compression_mode == 'zlib' or compression_mode == 'lz4':
314
+ # Pre-pack all frames (fast operation)
315
+ packed_frames = [_pack_frame(i) for i in range(len(frames_list))]
316
+
317
+ worker_count = _max_workers(len(packed_frames))
318
+
319
+ def _compress_frame(packed: bytes) -> bytes:
320
+ if compression_mode == 'zlib':
321
+ return zlib.compress(packed, compression_level)
322
+ else: # lz4
323
+ return lz4.block.compress(packed, store_size=True)
324
+
325
+ initial = f.tell()
326
+ current = initial
327
+
328
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
329
+ compressed_frames = list(executor.map(_compress_frame, packed_frames))
330
+
331
+ # Write all compressed frames
332
+ for packed, compressed in zip(packed_frames, compressed_frames):
333
+ f.write(compressed)
334
+ frame_offsets.append((current, len(compressed)))
335
+ uncompressed_lengths.append(len(packed))
336
+ current += len(compressed)
337
+
338
+ else:
339
+ # Write frames directly without intermediate buffer
340
+ initial = f.tell()
341
+ current = initial
342
+ for i in range(len(frames_list)):
343
+ packed = _pack_frame(i)
344
+ l = len(packed)
345
+ f.write(packed)
346
+ frame_offsets.append((current, l))
347
+ current += l
348
+
349
+ # Store static data in header (data that's the same for all frames)
350
+ first_frame = frames_list[0]
351
+ symbols = first_frame.get_chemical_symbols()
352
+ symbols_idx = np.array([unique_symbols_lookup[s] for s in symbols], dtype=np.uint16)
353
+
354
+ # Write header
355
+ header_dict: Dict[str, Any] = {
356
+ 'format_version': 5,
357
+ 'metadata': dict(metadata or {}),
358
+ 'unique_symbols': unique_symbols,
359
+ 'num_frames': len(frames_list),
360
+ 'frame_offsets': frame_offsets,
361
+ # Static frame data stored once in header
362
+ 'static_data': {
363
+ 'n_atoms': len(first_frame),
364
+ 'symbols': symbols_idx,
365
+ 'numbers': first_frame.get_atomic_numbers(),
366
+ 'masses': first_frame.get_masses(),
367
+ 'pbc': first_frame.get_pbc(),
368
+ 'cell': first_cell,
369
+ 'cell_changes': cell_changes,
370
+ }
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
379
+ if compression_mode != 'none':
380
+ comp_dict: Dict[str, Any] = {'type': compression_mode}
381
+ if compression_mode == 'zlib':
382
+ comp_dict['level'] = int(compression_level)
383
+ header_dict['compression'] = comp_dict
384
+ header_dict['frame_uncompressed_lengths'] = uncompressed_lengths
385
+ header_bytes = cast(bytes, msgpack.packb(header_dict, use_bin_type=True))
386
+ header_start = f.tell()
387
+ f.write(header_bytes)
388
+
389
+ # Write header offset
390
+ f.write(header_start.to_bytes(8, 'little'))
391
+
392
+
393
+ def read_tess(filename: str, frames_indices: Optional[List[int]] = None) -> Tuple[List['Atoms'], Dict]:
394
+
395
+ try:
396
+ import msgpack
397
+ import msgpack_numpy as m
398
+ from atomict.io.atoms import dict_to_atoms
399
+ from ase import Atoms
400
+ import mmap
401
+ import zlib
402
+ import lz4.block
403
+ import numpy as np
404
+ from ase.calculators.singlepoint import SinglePointCalculator
405
+ except ImportError:
406
+ raise ImportError("You need to install with `pip install atomict[utils]` to use the newer formats")
407
+
408
+ # Enable numpy array deserialization
409
+ m.patch()
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
+
430
+ with open(filename, 'rb') as f:
431
+ # Use mmap with larger read-ahead hint
432
+ mm = mmap.mmap(f.fileno(), 0, access=mmap.ACCESS_READ)
433
+ try:
434
+ # Advise the kernel we'll read sequentially
435
+ if hasattr(mm, 'madvise'):
436
+ import mmap as mmap_module
437
+ if hasattr(mmap_module, 'MADV_SEQUENTIAL'):
438
+ mm.madvise(mmap_module.MADV_SEQUENTIAL)
439
+
440
+ # Determine which frames to load
441
+ if frames_indices is not None:
442
+ # Validate and normalize indices
443
+ frames_to_load = []
444
+ for idx in frames_indices:
445
+ if idx < 0 or idx >= num_frames:
446
+ raise IndexError(f"Frame index {idx} out of range [0, {num_frames})")
447
+ frames_to_load.append(idx)
448
+ # Filter offsets to only requested frames
449
+ filtered_offsets = [(i, frame_offsets[i]) for i in frames_to_load]
450
+ else:
451
+ frames_to_load = list(range(num_frames))
452
+ filtered_offsets = [(i, offset) for i, offset in enumerate(frame_offsets)]
453
+
454
+ # Pre-allocate the result list based on requested frames
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}:
459
+ static_data = header.get('static_data', {})
460
+ unique_symbols = header['unique_symbols']
461
+ symbols_idx = static_data['symbols']
462
+ symbols = [unique_symbols[i] for i in symbols_idx]
463
+ numbers = static_data['numbers']
464
+ masses = static_data['masses']
465
+ pbc = static_data['pbc']
466
+ static_cell = static_data.get('cell')
467
+ cell_changes = static_data.get('cell_changes', True)
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
+
472
+ # Create a template Atoms object to clone for efficiency
473
+ template_atoms = Atoms(numbers=numbers, pbc=pbc)
474
+ template_atoms.set_masses(masses)
475
+ if static_cell is not None:
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)
483
+ else:
484
+ convert = dict_to_atoms
485
+ static_data = None
486
+ cell_changes = True
487
+
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']:
492
+ orig_idx, (start, length) = idx_offset
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)
495
+
496
+ worker_count = _max_workers(len(filtered_offsets))
497
+ chunk_size = _chunk_size(worker_count)
498
+
499
+ with ThreadPoolExecutor(max_workers=worker_count) as executor:
500
+ for chunk_start in range(0, len(filtered_offsets), chunk_size):
501
+ offset_chunk = filtered_offsets[chunk_start:chunk_start + chunk_size]
502
+ for result_idx, (orig_idx, atoms) in enumerate(
503
+ executor.map(_decode, offset_chunk), start=0
504
+ ):
505
+ atoms_list[chunk_start + result_idx] = atoms
506
+ finally:
507
+ mm.close()
508
+
509
+ return cast(List[Atoms], atoms_list), metadata