atomict 1.2.6__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/ase/atatoms.py ADDED
@@ -0,0 +1,715 @@
1
+ import uuid
2
+ import time
3
+ import numpy as np
4
+ import json
5
+ import datetime
6
+ import os
7
+ import sys
8
+ import hashlib
9
+ import threading
10
+ import queue
11
+ from typing import Optional, Dict, Any
12
+ import logging
13
+
14
+ from ase.atoms import Atoms
15
+ from deepdiff import DeepDiff
16
+
17
+ from atomict.api import patch, post
18
+
19
+
20
+ logger = logging.getLogger(__name__)
21
+ handler = logging.StreamHandler(sys.stdout)
22
+ formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
23
+ handler.setFormatter(formatter)
24
+ logger.addHandler(handler)
25
+ logger.setLevel(logging.INFO)
26
+
27
+
28
+ class ATAtomsError(Exception):
29
+ pass
30
+
31
+
32
+ class ATAtomsServerError(ATAtomsError):
33
+ """Raised when server operations fail"""
34
+ pass
35
+
36
+
37
+ class ATAtomsInitializationError(ATAtomsServerError):
38
+ """Raised when server initialization fails"""
39
+ pass
40
+
41
+
42
+ class QueueWorker:
43
+ """Handles network operations in a separate thread"""
44
+ def __init__(self):
45
+ self._queue = queue.Queue(maxsize=100_000)
46
+ self._thread = threading.Thread(target=self._process_queue, daemon=True)
47
+ self._thread.start()
48
+
49
+ def _process_queue(self):
50
+ """Process network operations from the queue"""
51
+ while True:
52
+ try:
53
+ operation = self._queue.get()
54
+ if operation is None:
55
+ break
56
+
57
+ func, args, kwargs = operation
58
+ try:
59
+ func(*args, **kwargs)
60
+ except Exception as e:
61
+ logger.error(f"Network operation failed: {e}")
62
+ finally:
63
+ self._queue.task_done()
64
+ except Exception as e:
65
+ logger.error(f"Error processing network queue: {e}")
66
+
67
+ def enqueue(self, func, *args, **kwargs):
68
+ """Add a request to the queue without blocking"""
69
+ try:
70
+ self._queue.put((func, args, kwargs), block=False)
71
+ except queue.Full:
72
+ logger.warning("Network operation queue is full, operation dropped")
73
+
74
+
75
+ class ATAtoms:
76
+ """
77
+ A wrapper around ASE Atoms that transparently tracks modifications
78
+ and tracks diffs between Atoms states. An ATAtoms run is a collection of diffs.
79
+ """
80
+
81
+ def __init__(self, atoms: Atoms, batch_size: int = 20, sync_interval: float = 10.0,
82
+ project_id: Optional[str] = '', batch_diffs: bool = False):
83
+ """
84
+ atoms: ASE Atoms object to wrap
85
+ batch_size: Number of diffs to accumulate before sending to server in a single request
86
+ sync_interval: Maximum time in seconds between syncs to server
87
+ project_id: ID of the project to associate with the atoms
88
+ batch_diffs: Whether to batch diffs
89
+ """
90
+ if not isinstance(atoms, Atoms):
91
+ raise TypeError(f"Expected ASE Atoms object, got {type(atoms).__name__}: {atoms}")
92
+
93
+ self._atoms = atoms
94
+ self._project_id = project_id
95
+ self._object_id = str(uuid.uuid4())
96
+ self._batch_size = batch_size
97
+ self._sync_interval = sync_interval
98
+ self._worker = self._create_worker()
99
+ self._diffs = []
100
+ self._last_sync_time = time.time()
101
+ self._seq_num = 0
102
+ self.atomic_state_id = None
103
+ self._run_id = None
104
+ self._initialized = False
105
+ self._batch_diffs = batch_diffs
106
+ self._initial_state = self._get_current_state()
107
+ self._previous_state = self._serialize_state(self._initial_state)
108
+ self._structure_id = self._hash_state(self._previous_state)
109
+ self._capture_state_diff()
110
+
111
+ def _create_worker(self) -> QueueWorker:
112
+ """Create and return a new QueueWorker instance.
113
+
114
+ This method is separated out to allow for easier testing and mocking.
115
+ """
116
+ return QueueWorker()
117
+
118
+ def _hash_state(self, state_data):
119
+ """Generate a SHA-256 hash of the state data"""
120
+ state_json = json.dumps(state_data, sort_keys=True)
121
+ _hash = hashlib.sha256(state_json.encode('utf-8')).hexdigest()
122
+ logger.info(f"Created structure id: {_hash}")
123
+ return _hash
124
+
125
+ def _initialize_on_server(self):
126
+ """Send the initial state to create an object on the server"""
127
+ # If no server URL is set, skip the server initialization and run offline
128
+
129
+ try:
130
+ state_data = {
131
+ 'id': self._object_id,
132
+ 'structure_id': self._structure_id,
133
+ 'numbers': self._previous_state.get('numbers'),
134
+ 'positions': self._previous_state.get('positions'),
135
+ 'cell': self._previous_state.get('cell'),
136
+ 'pbc': self._previous_state.get('pbc'),
137
+ 'energy': self._previous_state.get('energy'),
138
+ 'symbols': self._previous_state.get('symbols'),
139
+ 'forces': self._previous_state.get('forces'),
140
+ 'stress': self._previous_state.get('stress'),
141
+ 'info': self._previous_state.get('info', {}),
142
+ 'scaled_positions': self._previous_state.get('scaled_positions'),
143
+ 'tags': self._previous_state.get('tags'),
144
+ 'momenta': self._previous_state.get('momenta'),
145
+ 'velocities': self._previous_state.get('velocities'),
146
+ 'masses': self._previous_state.get('masses'),
147
+ 'magmoms': self._previous_state.get('magmoms'),
148
+ 'charges': self._previous_state.get('charges'),
149
+ 'celldisp': self._previous_state.get('celldisp'),
150
+ 'constraints': self._previous_state.get('constraints')
151
+ }
152
+ response = post(
153
+ 'api/atatoms-states/',
154
+ state_data,
155
+ extra_headers={'Content-Type': 'application/json'}
156
+ )
157
+ if response and 'id' in response:
158
+ self.atomic_state_id = response['id']
159
+ logger.info(f"Successfully initialized state on server with ID: {self.atomic_state_id}")
160
+ if self.atomic_state_id:
161
+ self._initialize_run_on_server()
162
+ else:
163
+ logger.warning(f"Server response did not contain expected 'id' field: {response}")
164
+
165
+ except Exception as e:
166
+ logger.error(f"Failed to queue initialization on server: {e}")
167
+
168
+ def _initialize_run_on_server(self):
169
+ """Create an AtomicRun object on the server using the initial state"""
170
+ # If no server URL is set, skip the run initialization and run offline
171
+
172
+ if not self.atomic_state_id:
173
+ logger.warning("Cannot initialize run without a valid state ID")
174
+ return
175
+
176
+ try:
177
+ run_data = {
178
+ 'id': str(uuid.uuid4()),
179
+ 'name': f"ATAtomsRun-{datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}",
180
+ 'starting_state': self.atomic_state_id,
181
+ 'end_state': self.atomic_state_id,
182
+ 'project': self._project_id,
183
+ 'metadata': json.dumps({
184
+ 'created_by': 'ATAtoms',
185
+ 'initial_structure_id': self._structure_id,
186
+ 'timestamp': datetime.datetime.now().isoformat()
187
+ })
188
+ }
189
+ response = post(
190
+ 'api/atatoms-runs/',
191
+ run_data,
192
+ )
193
+ if response and 'id' in response:
194
+ self._run_id = response['id']
195
+ logger.info(f"Successfully initialized run on server with ID: {self._run_id}")
196
+ else:
197
+ logger.warning(f"Server response did not contain expected 'id' field: {response}")
198
+
199
+ except Exception as e:
200
+ logger.error(f"Failed to queue run initialization on server: {e}")
201
+
202
+ def _capture_state_diff(self):
203
+ """
204
+ Capture differences between current and previous state
205
+ """
206
+
207
+ current_state = self._get_current_state()
208
+ serialized_current = self._serialize_state(current_state)
209
+ new_atomic_state_id = self._hash_state(serialized_current)
210
+ if self._structure_id == new_atomic_state_id:
211
+ logger.info("New state hash matches current")
212
+ return
213
+
214
+ if not self._initialized:
215
+ logger.info("Initializing on server (first state)")
216
+ self._initialize_on_server()
217
+ self._initialized = True
218
+ return None
219
+
220
+ diff = DeepDiff(self._previous_state, serialized_current, verbose_level=1)
221
+
222
+ if diff:
223
+ timestamp = datetime.datetime.now().isoformat()
224
+ current_seq = self._seq_num
225
+ logger.info(f"State change detected, creating diff with seq_num={current_seq}")
226
+ diff_item = {
227
+ 'timestamp': timestamp,
228
+ 'sequence': current_seq,
229
+ 'diff': diff
230
+ }
231
+
232
+ self._previous_state = serialized_current
233
+ self._structure_id = self._hash_state(self._previous_state)
234
+
235
+ if self._batch_diffs:
236
+ logger.info(f"Adding diff to batch queue (queue size now: {len(self._diffs)+1})")
237
+ self._diffs.append(diff_item)
238
+ current_time = time.time()
239
+ if (len(self._diffs) >= self._batch_size or
240
+ current_time - self._last_sync_time >= self._sync_interval):
241
+ logger.info(f"Batch threshold reached, syncing {len(self._diffs)} diffs")
242
+ self._sync_diffs()
243
+ else:
244
+ self._send_diff(diff)
245
+
246
+ self._seq_num += 1
247
+ logger.info(f"Incremented internal seq_num to {self._seq_num}")
248
+ else:
249
+ logger.info("No state change detected")
250
+
251
+ @property
252
+ def calc(self):
253
+ return self._atoms.calc
254
+
255
+ @calc.setter
256
+ def calc(self, calculator):
257
+ self._atoms.calc = calculator
258
+ self._capture_state_diff()
259
+
260
+ def _get_current_state(self) -> Dict[str, Any]:
261
+ """Get the complete state of the atoms object"""
262
+ state = self._atoms.todict()
263
+
264
+ if 'symbols' not in state:
265
+ state['symbols'] = self._atoms.get_chemical_symbols()
266
+
267
+ if hasattr(self._atoms, 'get_potential_energy'):
268
+ try:
269
+ state['energy'] = self._atoms.get_potential_energy()
270
+ except:
271
+ pass
272
+
273
+ if hasattr(self._atoms, 'get_forces'):
274
+ try:
275
+ state['forces'] = self._atoms.get_forces()
276
+ except:
277
+ pass
278
+
279
+ if hasattr(self._atoms, 'get_stress'):
280
+ try:
281
+ state['stress'] = self._atoms.get_stress()
282
+ except:
283
+ pass
284
+
285
+ if hasattr(self._atoms, 'info') and self._atoms.info:
286
+ state['info'] = self._atoms.info.copy()
287
+
288
+ for name in self._atoms.arrays:
289
+ if name not in ['positions', 'numbers']:
290
+ state[name] = self._atoms.arrays[name].copy()
291
+
292
+ return state
293
+
294
+ def _recursive_serialize(self, obj):
295
+ """Recursively convert non-serializable objects to serializable forms."""
296
+ import numpy as np
297
+ # Handle numpy arrays
298
+ if isinstance(obj, np.ndarray):
299
+ return obj.tolist()
300
+ # Handle numpy scalars
301
+ elif isinstance(obj, (np.integer, np.floating)):
302
+ return float(obj) if isinstance(obj, np.floating) else int(obj)
303
+ # Handle dicts
304
+ elif isinstance(obj, dict):
305
+ return {k: self._recursive_serialize(v) for k, v in obj.items()}
306
+ # Handle lists/tuples
307
+ elif isinstance(obj, (list, tuple)):
308
+ return [self._recursive_serialize(v) for v in obj]
309
+ # Handle objects with .todict() (e.g., Spacegroup)
310
+ elif hasattr(obj, 'todict') and callable(getattr(obj, 'todict')):
311
+ return self._recursive_serialize(obj.todict())
312
+ # Handle objects with __dict__ (as a fallback, but avoid recursion on builtins)
313
+ elif hasattr(obj, '__dict__') and not isinstance(obj, type):
314
+ return {k: self._recursive_serialize(v) for k, v in obj.__dict__.items() if not k.startswith('__')}
315
+ # Handle basic types
316
+ elif isinstance(obj, (str, int, float, bool)) or obj is None:
317
+ return obj
318
+ # Fallback: string representation
319
+ else:
320
+ return str(obj)
321
+
322
+ def _serialize_state(self, state: Dict[str, Any]) -> Dict[str, Any]:
323
+ """Convert all non-serializable objects in the state to serializable forms recursively."""
324
+ return self._recursive_serialize(state)
325
+
326
+ def _serialize_diff(self, diff):
327
+ """Convert DeepDiff output to JSON serializable format"""
328
+ if not diff:
329
+ return diff
330
+
331
+ serialized_diff = {}
332
+
333
+ for diff_type, values in diff.items():
334
+ if hasattr(values, 'items'):
335
+ serialized_diff[diff_type] = dict(values)
336
+ elif isinstance(values, (list, tuple)):
337
+ serialized_diff[diff_type] = list(values)
338
+ elif hasattr(values, '__iter__') and not isinstance(values, str):
339
+ serialized_diff[diff_type] = list(values)
340
+ else:
341
+ serialized_diff[diff_type] = values
342
+
343
+ return serialized_diff
344
+
345
+ # Handle individual atom access with change tracking
346
+ def __getitem__(self, index):
347
+ if isinstance(index, slice):
348
+ # Get the sliced atoms
349
+ new_atoms = self._atoms[index]
350
+ # Instead of creating a new ATAtoms instance, create a copy of self
351
+ # and update its _atoms attribute to the sliced atoms
352
+ if new_atoms is self._atoms: # If the slice didn't change anything
353
+ return self
354
+ else:
355
+ # Update internal atoms but preserve all tracking state
356
+ self._atoms = new_atoms
357
+ self._capture_state_diff()
358
+ return self
359
+ else:
360
+ return _AtomProxy(self, index)
361
+
362
+ def __setitem__(self, index, value):
363
+ self._atoms[index] = value
364
+ self._capture_state_diff()
365
+
366
+ def __delitem__(self, index):
367
+ del self._atoms[index]
368
+ self._capture_state_diff()
369
+
370
+ def __iadd__(self, other):
371
+ self._atoms += other
372
+ self._capture_state_diff()
373
+ return self
374
+
375
+ def __len__(self):
376
+ return len(self._atoms)
377
+
378
+ def __getattr__(self, name):
379
+ # First check if the attribute exists directly on the class or instance
380
+ if name in dir(self.__class__) or name in self.__dict__:
381
+ return object.__getattribute__(self, name)
382
+
383
+ # If not found on self, try to get it from the wrapped atoms object
384
+ try:
385
+ attr = getattr(self._atoms, name)
386
+ except AttributeError:
387
+ raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
388
+
389
+ if callable(attr):
390
+ def wrapped_method(*args, **kwargs):
391
+ result = attr(*args, **kwargs)
392
+ if result is self._atoms:
393
+ self._capture_state_diff()
394
+ return self
395
+ elif isinstance(result, Atoms):
396
+ self._atoms = result
397
+ self._capture_state_diff()
398
+ return self
399
+
400
+ self._capture_state_diff()
401
+ return result
402
+
403
+ return wrapped_method
404
+ else:
405
+ return attr
406
+
407
+ def __dir__(self):
408
+ return list(set(dir(self.__class__)) | set(dir(self._atoms)))
409
+
410
+ def __del__(self):
411
+ """Ensure any remaining diffs are synced before garbage collection"""
412
+ if hasattr(self, '_diffs') and self._diffs:
413
+ try:
414
+ self._sync_diffs()
415
+ self._worker._queue.join(timeout=5.0)
416
+ except:
417
+ pass
418
+
419
+ def __enter__(self):
420
+ """Context manager entry point"""
421
+ return self
422
+
423
+ def __exit__(self, exc_type, exc_val, exc_tb):
424
+ """Context manager exit point - syncs diffs and cleans up worker thread"""
425
+ try:
426
+ if hasattr(self, '_diffs') and self._diffs:
427
+ self._sync_diffs()
428
+
429
+ if hasattr(self, '_worker'):
430
+ self._worker._queue.join()
431
+
432
+ if hasattr(self, '_worker'):
433
+ self._worker._queue.put(None)
434
+ self._worker._thread.join(timeout=1.0)
435
+
436
+ except Exception as e:
437
+ logger.error(f"Error during ATAtoms cleanup: {e}")
438
+ return False
439
+
440
+ return False
441
+
442
+ def _send_diff(self, diff):
443
+ """
444
+ Send a diff to the server at /api/atatoms-diffs
445
+ """
446
+
447
+ if not self.atomic_state_id:
448
+ logger.warning("Cannot send diff without state_id. Attempting to initialize on server first.")
449
+ self._initialize_on_server()
450
+ if not self.atomic_state_id:
451
+ raise ATAtomsInitializationError("Failed to initialize ATAtoms state on server after retry attempt")
452
+
453
+ try:
454
+ serialized_diff = self._serialize_diff(diff)
455
+ current_seq = self._seq_num
456
+ diff_data = {
457
+ 'atoms_id': self._object_id,
458
+ 'sequence': current_seq,
459
+ 'timestamp': datetime.datetime.now().isoformat(),
460
+ 'data': serialized_diff,
461
+ 'run': self._run_id
462
+ }
463
+
464
+ logger.info(f"Queueing diff to server with sequence={current_seq}")
465
+
466
+ def _do_send_diff(diff_data):
467
+ response = post(
468
+ 'api/atatoms-diffs/',
469
+ diff_data,
470
+ extra_headers={'Content-Type': 'application/json'}
471
+ )
472
+
473
+ if not response:
474
+ logger.warning("Empty response when sending diff to server")
475
+
476
+ self._worker.enqueue(_do_send_diff, diff_data)
477
+
478
+ except Exception as e:
479
+ logger.error(f"Failed to queue diff send to server: {e}")
480
+ return None
481
+
482
+ def save_current_state(self) -> Dict[str, Any]:
483
+ """
484
+ Get current state, serialize it, hash it, and send it to server.
485
+
486
+ Returns:
487
+ --------
488
+ Dict with server response data
489
+ """
490
+
491
+ current_state = self._get_current_state()
492
+ serialized_state = self._serialize_state(current_state)
493
+ structure_id = self._hash_state(serialized_state)
494
+ state_data = {
495
+ 'structure_id': structure_id,
496
+ 'numbers': serialized_state.get('numbers'),
497
+ 'positions': serialized_state.get('positions'),
498
+ 'cell': serialized_state.get('cell'),
499
+ 'pbc': serialized_state.get('pbc'),
500
+ 'energy': serialized_state.get('energy'),
501
+ 'symbols': serialized_state.get('symbols'),
502
+ 'forces': serialized_state.get('forces'),
503
+ 'stress': serialized_state.get('stress'),
504
+ 'info': serialized_state.get('info', {}),
505
+ 'scaled_positions': serialized_state.get('scaled_positions'),
506
+ 'tags': serialized_state.get('tags'),
507
+ 'momenta': serialized_state.get('momenta'),
508
+ 'velocities': serialized_state.get('velocities'),
509
+ 'masses': serialized_state.get('masses'),
510
+ 'magmoms': serialized_state.get('magmoms'),
511
+ 'charges': serialized_state.get('charges'),
512
+ 'celldisp': serialized_state.get('celldisp'),
513
+ 'constraints': serialized_state.get('constraints')
514
+ }
515
+
516
+ try:
517
+ logger.info(f"Saving current state with structure_id: {structure_id}")
518
+ response = post(
519
+ 'api/atatoms-states/',
520
+ state_data,
521
+ extra_headers={'Content-Type': 'application/json'}
522
+ )
523
+
524
+ if response and 'id' in response:
525
+ logger.info(f"Successfully saved state on server with ID: {response['id']}")
526
+ if self._run_id:
527
+ self.update_run_end_state(response['id'])
528
+
529
+ return response
530
+ else:
531
+ logger.warning(f"Server response did not contain expected 'id' field: {response}")
532
+ return response
533
+
534
+ except Exception as e:
535
+ logger.error(f"Failed to save state on server: {e}")
536
+ return {"error": str(e)}
537
+
538
+ def update_run_end_state(self, state_id):
539
+ """Update the end state of the current run"""
540
+
541
+ if not self._run_id:
542
+ logger.warning("Cannot update run end state: no run ID available")
543
+ return
544
+
545
+ try:
546
+ update_data = {
547
+ 'end_state': state_id,
548
+ 'updated_at': datetime.datetime.now().isoformat()
549
+ }
550
+
551
+ def _do_update_run():
552
+ response = patch(
553
+ f'api/atatoms-runs/{self._run_id}/',
554
+ update_data,
555
+ )
556
+
557
+ if response and 'id' in response:
558
+ logger.info(f"Successfully updated run end state to {state_id}")
559
+ else:
560
+ logger.warning(f"Failed to update run end state: {response}")
561
+
562
+ self._worker.enqueue(_do_update_run)
563
+
564
+ except Exception as e:
565
+ logger.error(f"Failed to queue run end state update: {e}")
566
+
567
+ @classmethod
568
+ def from_known_state(cls, state_id: str) -> 'ATAtoms':
569
+ """Retrieves a state from the server and initializes an ATAtoms object with it."""
570
+ raise NotImplementedError
571
+
572
+ def _sync_diffs(self):
573
+ """Send accumulated diffs to the server in a single request and clear the queue"""
574
+ # offline mode
575
+
576
+ if not self._diffs:
577
+ return
578
+
579
+ if not self.atomic_state_id:
580
+ self._initialize_on_server()
581
+ if not self.atomic_state_id:
582
+ return
583
+
584
+ try:
585
+ batch_data = {
586
+ 'run': self._run_id,
587
+ 'diffs': []
588
+ }
589
+ for diff_item in self._diffs:
590
+ serialized_diff = self._serialize_diff(diff_item['diff'])
591
+
592
+ batch_data['diffs'].append({
593
+ 'sequence': diff_item['sequence'],
594
+ 'timestamp': diff_item['timestamp'],
595
+ 'data': serialized_diff
596
+ })
597
+
598
+ self._diffs = []
599
+ self._last_sync_time = time.time()
600
+
601
+ def _do_sync_diffs(batch_data):
602
+ _ = post(
603
+ 'api/atatoms-diffs/batch/',
604
+ batch_data,
605
+ extra_headers={'Content-Type': 'application/json'}
606
+ )
607
+ logger.info(f"Sent batch of {len(batch_data['diffs'])} diffs to server")
608
+
609
+ self._worker.enqueue(_do_sync_diffs, batch_data)
610
+
611
+ except Exception as e:
612
+ logger.error(f"Failed to queue diff batch sync: {e}")
613
+
614
+
615
+ class _AtomProxy:
616
+ """Proxy for individual atom access that tracks position changes"""
617
+
618
+ def __init__(self, parent, index):
619
+ self._parent = parent
620
+ self._index = index
621
+
622
+ @property
623
+ def position(self):
624
+ # Return a position proxy that tracks changes
625
+ return _PositionProxy(self._parent, self._index)
626
+
627
+ @position.setter
628
+ def position(self, value):
629
+ logger.info(f"Setting position for atom {self._index}")
630
+ self._parent._atoms.positions[self._index] = value
631
+ self._parent._capture_state_diff()
632
+
633
+ def __getattr__(self, name):
634
+ # Forward all other attributes to the actual atom
635
+ return getattr(self._parent._atoms[self._index], name)
636
+
637
+ def __setattr__(self, name, value):
638
+ if name.startswith('_'):
639
+ # Set private attributes directly on this proxy
640
+ object.__setattr__(self, name, value)
641
+ else:
642
+ # Apply changes to the atom and record diff
643
+ logger.info(f"Setting attribute {name} for atom {self._index}")
644
+ setattr(self._parent._atoms[self._index], name, value)
645
+ self._parent._capture_state_diff()
646
+
647
+
648
+ class _PositionProxy:
649
+ """Proxy for atom position that tracks changes"""
650
+
651
+ def __init__(self, parent, index):
652
+ self._parent = parent
653
+ self._index = index
654
+ self._array = parent._atoms.positions[index].copy()
655
+
656
+ def _capture_and_send_diff(self):
657
+ """Helper method to capture and send diffs"""
658
+ logger.info(f"Capturing diff from position proxy for atom {self._index}")
659
+ self._parent._capture_state_diff()
660
+
661
+ def __array__(self, dtype=None):
662
+ """Make this behave like a numpy array"""
663
+ if dtype is not None:
664
+ return np.array(self._array, dtype=dtype)
665
+ return self._array
666
+
667
+ def __getitem__(self, i):
668
+ return self._parent._atoms.positions[self._index][i]
669
+
670
+ def __setitem__(self, i, value):
671
+ # Update both the local array and the actual atom position
672
+ self._array[i] = value
673
+ self._parent._atoms.positions[self._index][i] = value
674
+ self._capture_and_send_diff()
675
+
676
+ def __iadd__(self, other):
677
+ # Handle += operation
678
+ new_pos = self._parent._atoms.positions[self._index] + other
679
+ self._parent._atoms.positions[self._index] = new_pos
680
+ self._array = new_pos.copy()
681
+ self._capture_and_send_diff()
682
+ return self
683
+
684
+ def __isub__(self, other):
685
+ # Handle -= operation
686
+ new_pos = self._parent._atoms.positions[self._index] - other
687
+ self._parent._atoms.positions[self._index] = new_pos
688
+ self._array = new_pos.copy()
689
+ self._capture_and_send_diff()
690
+ return self
691
+
692
+ def __imul__(self, other):
693
+ # Handle *= operation
694
+ new_pos = self._parent._atoms.positions[self._index] * other
695
+ self._parent._atoms.positions[self._index] = new_pos
696
+ self._array = new_pos.copy()
697
+ self._capture_and_send_diff()
698
+ return self
699
+
700
+ def __itruediv__(self, other):
701
+ # Handle /= operation
702
+ new_pos = self._parent._atoms.positions[self._index] / other
703
+ self._parent._atoms.positions[self._index] = new_pos
704
+ self._array = new_pos.copy()
705
+ self._capture_and_send_diff()
706
+ return self
707
+
708
+ def __len__(self):
709
+ return 3 # Positions are always 3D
710
+
711
+ def copy(self):
712
+ return self._parent._atoms.positions[self._index].copy()
713
+
714
+ def tolist(self):
715
+ return self._parent._atoms.positions[self._index].tolist()