Coverage for ase/atoms.py: 94.41%

1019 statements  

« prev     ^ index     » next       coverage.py v7.16.2, created at 2026-11-27 15:21 +0000

1# Copyright 2008, 2009 CAMd 

2# (see accompanying license files for details). 

3 

4"""Definition of the Atoms class. 

5 

6This module defines the central object in the ASE package: the Atoms 

7object. 

8""" 

9 

10from __future__ import annotations 

11 

12import copy 

13import numbers 

14import warnings 

15from collections.abc import Sequence 

16from math import cos, pi, sin 

17from typing import overload 

18 

19import numpy as np 

20 

21from ase import units 

22from ase.atom import Atom 

23from ase.cell import Cell 

24from ase.data import atomic_masses, atomic_masses_common 

25from ase.stress import full_3x3_to_voigt_6_stress, voigt_6_to_full_3x3_stress 

26from ase.symbols import Symbols, symbols2numbers 

27from ase.utils import deprecated, string2index 

28 

29 

30class _LimitedAtoms: 

31 """Atoms object with limited methods and attributes. 

32 

33 This class is only for smooth transition from ASE3 to ASE4 and not intended 

34 to be used for any other purposes by users. 

35 """ 

36 

37 ase_objtype = 'atoms' # For JSONability 

38 

39 def __init__( 

40 self, 

41 symbols=None, 

42 positions=None, 

43 numbers=None, 

44 tags=None, 

45 momenta=None, 

46 masses=None, 

47 magmoms=None, 

48 charges=None, 

49 scaled_positions=None, 

50 cell=None, 

51 pbc=None, 

52 celldisp=None, 

53 constraint=None, 

54 info=None, 

55 velocities=None, 

56 ): 

57 

58 self._cellobj = Cell.new() 

59 self._pbc = np.zeros(3, bool) 

60 

61 atoms = None 

62 

63 if hasattr(symbols, 'get_positions'): 

64 atoms = symbols 

65 symbols = None 

66 elif ( 

67 isinstance(symbols, (list, tuple)) 

68 and len(symbols) > 0 

69 and isinstance(symbols[0], Atom) 

70 ): 

71 # Get data from a list or tuple of Atom objects: 

72 data = [ 

73 [atom.get_raw(name) for atom in symbols] 

74 for name in [ 

75 'position', 

76 'number', 

77 'tag', 

78 'momentum', 

79 'mass', 

80 'magmom', 

81 'charge', 

82 ] 

83 ] 

84 atoms = self.__class__(None, *data) 

85 symbols = None 

86 

87 if atoms is not None: 

88 # Get data from another Atoms object: 

89 if scaled_positions is not None: 

90 raise NotImplementedError 

91 if symbols is None and numbers is None: 

92 numbers = atoms.get_atomic_numbers() 

93 if positions is None: 

94 positions = atoms.get_positions() 

95 if tags is None and atoms.has('tags'): 

96 tags = atoms.get_tags() 

97 if momenta is None and atoms.has('momenta'): 

98 momenta = atoms.get_momenta() 

99 if magmoms is None and atoms.has('initial_magmoms'): 

100 magmoms = atoms.get_initial_magnetic_moments() 

101 if masses is None and atoms.has('masses'): 

102 masses = atoms.get_masses() 

103 if charges is None and atoms.has('initial_charges'): 

104 charges = atoms.get_initial_charges() 

105 if cell is None: 

106 cell = atoms.get_cell() 

107 if celldisp is None: 

108 celldisp = atoms.get_celldisp() 

109 if pbc is None: 

110 pbc = atoms.get_pbc() 

111 if constraint is None: 

112 constraint = [c.copy() for c in atoms.constraints] 

113 if info is None: 

114 info = copy.deepcopy(atoms.info) 

115 

116 self.arrays: dict[str, np.ndarray] = {} 

117 

118 if symbols is not None and numbers is not None: 

119 raise TypeError('Use only one of "symbols" and "numbers".') 

120 if symbols is not None: 

121 numbers = symbols2numbers(symbols) 

122 elif numbers is None: 

123 if positions is not None: 

124 natoms = len(positions) 

125 elif scaled_positions is not None: 

126 natoms = len(scaled_positions) 

127 else: 

128 natoms = 0 

129 numbers = np.zeros(natoms, int) 

130 self.new_array('numbers', numbers, int) 

131 

132 if self.numbers.ndim != 1: 

133 raise ValueError('"numbers" must be 1-dimensional.') 

134 

135 if cell is None: 

136 cell = np.zeros((3, 3)) 

137 self.set_cell(cell) 

138 

139 if celldisp is None: 

140 celldisp = np.zeros(shape=(3, 1)) 

141 self.set_celldisp(celldisp) 

142 

143 if positions is None: 

144 if scaled_positions is None: 

145 positions = np.zeros((len(self.arrays['numbers']), 3)) 

146 else: 

147 assert self.cell.rank == 3 

148 positions = np.dot(scaled_positions, self.cell) 

149 else: 

150 if scaled_positions is not None: 

151 raise TypeError( 

152 'Use only one of "positions" and "scaled_positions".' 

153 ) 

154 self.new_array('positions', positions, float, (3,)) 

155 

156 self.set_constraint(constraint) 

157 self.set_tags(default(tags, 0)) 

158 self.set_masses(default(masses, None)) 

159 self.set_initial_magnetic_moments(default(magmoms, 0.0)) 

160 self.set_initial_charges(default(charges, 0.0)) 

161 if pbc is None: 

162 pbc = False 

163 self.set_pbc(pbc) 

164 self.set_momenta( 

165 default(momenta, (0.0, 0.0, 0.0)), apply_constraint=False 

166 ) 

167 

168 if velocities is not None: 

169 if momenta is None: 

170 self.set_velocities(velocities) 

171 else: 

172 raise TypeError('Use only one of "momenta" and "velocities".') 

173 

174 if info is None: 

175 self.info = {} 

176 else: 

177 self.info = dict(info) 

178 

179 @property 

180 def symbols(self): 

181 """Get chemical symbols as a :class:`~ase.symbols.Symbols` object. 

182 

183 The object works like ``atoms.numbers`` except its values are strings. 

184 It supports in-place editing. 

185 

186 Examples 

187 -------- 

188 >>> from ase.build import molecule 

189 >>> atoms = molecule('CH3CH2OH') 

190 >>> atoms.symbols 

191 Symbols('C2OH6') 

192 >>> list(atoms.symbols) 

193 ['C', 'C', 'O', 'H', 'H', 'H', 'H', 'H', 'H'] 

194 >>> atoms.symbols == 'C' # doctest: +ELLIPSIS 

195 array([ True, True, False, False, False, False, False, False, False]...) 

196 >>> atoms.symbols.indices() 

197 {'C': array([0, 1]), 'O': array([2]), 'H': array([3, 4, 5, 6, 7, 8])} 

198 >>> list(atoms.symbols.indices()) # unique elements 

199 ['C', 'O', 'H'] 

200 >>> atoms.symbols.species() # doctest: +SKIP 

201 {'C', 'O', 'H'} 

202 """ # noqa 

203 return Symbols(self.numbers) 

204 

205 @symbols.setter 

206 def symbols(self, obj): 

207 new_symbols = Symbols.fromsymbols(obj) 

208 self.numbers[:] = new_symbols.numbers 

209 

210 def get_chemical_symbols(self): 

211 """Get list of chemical symbol strings. 

212 

213 Equivalent to ``list(atoms.symbols)``.""" 

214 return list(self.symbols) 

215 

216 def set_chemical_symbols(self, symbols): 

217 """Set chemical symbols.""" 

218 self.set_array('numbers', symbols2numbers(symbols), int, ()) 

219 

220 @property 

221 def numbers(self): 

222 """Attribute for direct manipulation of the atomic numbers.""" 

223 return self.arrays['numbers'] 

224 

225 @numbers.setter 

226 def numbers(self, numbers): 

227 self.set_atomic_numbers(numbers) 

228 

229 def set_atomic_numbers(self, numbers): 

230 """Set atomic numbers.""" 

231 self.set_array('numbers', numbers, int, ()) 

232 

233 def get_atomic_numbers(self): 

234 """Get integer array of atomic numbers.""" 

235 return self.arrays['numbers'].copy() 

236 

237 @property 

238 def positions(self): 

239 """Attribute for direct manipulation of the positions.""" 

240 return self.arrays['positions'] 

241 

242 @positions.setter 

243 def positions(self, pos): 

244 self.arrays['positions'][:] = pos 

245 

246 def set_positions(self, newpositions, apply_constraint=True): 

247 """Set positions, honoring any constraints. To ignore constraints, 

248 use *apply_constraint=False*.""" 

249 if self.constraints and apply_constraint: 

250 newpositions = np.array(newpositions, float) 

251 for constraint in self.constraints: 

252 constraint.adjust_positions(self, newpositions) 

253 

254 self.set_array('positions', newpositions, shape=(3,)) 

255 

256 def get_positions(self, wrap=False, **wrap_kw): 

257 """Get array of positions. 

258 

259 Parameters 

260 ---------- 

261 

262 wrap: bool 

263 wrap atoms back to the cell before returning positions 

264 wrap_kw: (keyword=value) pairs 

265 optional keywords `pbc`, `center`, `pretty_translation`, `eps`, 

266 see :func:`ase.geometry.wrap_positions` 

267 """ 

268 from ase.geometry import wrap_positions 

269 

270 if wrap: 

271 if 'pbc' not in wrap_kw: 

272 wrap_kw['pbc'] = self.pbc 

273 return wrap_positions(self.positions, self.cell, **wrap_kw) 

274 else: 

275 return self.arrays['positions'].copy() 

276 

277 @property 

278 @deprecated('Please use atoms.cell.rank instead', DeprecationWarning) 

279 def number_of_lattice_vectors(self): 

280 """Number of (non-zero) lattice vectors. 

281 

282 .. deprecated:: 3.21.0 

283 Please use ``atoms.cell.rank`` instead 

284 """ 

285 return self.cell.rank 

286 

287 @property 

288 def constraints(self): 

289 """Constraints.""" 

290 return self._constraints 

291 

292 @constraints.setter 

293 def constraints(self, constraint): 

294 self.set_constraint(constraint) 

295 

296 @constraints.deleter 

297 def constraints(self): 

298 self._constraints = [] 

299 

300 def set_constraint(self, constraint=None): 

301 """Apply one or more constrains. 

302 

303 The *constraint* argument must be one constraint object or a 

304 list of constraint objects.""" 

305 if constraint is None: 

306 self._constraints = [] 

307 else: 

308 if isinstance(constraint, list): 

309 self._constraints = constraint 

310 elif isinstance(constraint, tuple): 

311 self._constraints = list(constraint) 

312 else: 

313 self._constraints = [constraint] 

314 

315 def get_number_of_degrees_of_freedom(self): 

316 """Calculate the number of degrees of freedom in the system.""" 

317 return len(self) * 3 - sum( 

318 c.get_removed_dof(self) for c in self._constraints 

319 ) 

320 

321 def set_cell(self, cell, scale_atoms=False, apply_constraint=True): 

322 """Set unit cell vectors. 

323 

324 Parameters 

325 ---------- 

326 

327 cell: 3x3 matrix or length 3 or 6 vector 

328 Unit cell. A 3x3 matrix (the three unit cell vectors) or 

329 just three numbers for an orthorhombic cell. Another option is 

330 6 numbers, which describes unit cell with lengths of unit cell 

331 vectors and with angles between them (in degrees), in following 

332 order: [len(a), len(b), len(c), angle(b,c), angle(a,c), 

333 angle(a,b)]. First vector will lie in x-direction, second in 

334 xy-plane, and the third one in z-positive subspace. 

335 scale_atoms: bool 

336 Fix atomic positions or move atoms with the unit cell? 

337 Default behavior is to *not* move the atoms (scale_atoms=False). 

338 apply_constraint: bool 

339 Whether to apply constraints to the given cell. 

340 

341 Examples 

342 -------- 

343 

344 Two equivalent ways to define an orthorhombic cell: 

345 

346 >>> atoms = Atoms('He') 

347 >>> a, b, c = 7, 7.5, 8 

348 >>> atoms.set_cell([a, b, c]) 

349 >>> atoms.set_cell([(a, 0, 0), (0, b, 0), (0, 0, c)]) 

350 

351 FCC unit cell: 

352 

353 >>> atoms.set_cell([(0, b, b), (b, 0, b), (b, b, 0)]) 

354 

355 Hexagonal unit cell: 

356 

357 >>> atoms.set_cell([a, a, c, 90, 90, 120]) 

358 

359 Rhombohedral unit cell: 

360 

361 >>> alpha = 77 

362 >>> atoms.set_cell([a, a, a, alpha, alpha, alpha]) 

363 """ 

364 

365 # Override pbcs if and only if given a Cell object: 

366 cell = Cell.new(cell) 

367 

368 # XXX not working well during initialize due to missing _constraints 

369 if apply_constraint and hasattr(self, '_constraints'): 

370 for constraint in self.constraints: 

371 if hasattr(constraint, 'adjust_cell'): 

372 constraint.adjust_cell(self, cell) 

373 

374 if scale_atoms: 

375 M = np.linalg.solve(self.cell.complete(), cell.complete()) 

376 self.positions[:] = np.dot(self.positions, M) 

377 

378 self.cell[:] = cell 

379 

380 def set_celldisp(self, celldisp): 

381 """Set the unit cell displacement vectors.""" 

382 celldisp = np.array(celldisp, float) 

383 self._celldisp = celldisp 

384 

385 def get_celldisp(self): 

386 """Get the unit cell displacement vectors.""" 

387 return self._celldisp.copy() 

388 

389 def get_cell(self, complete=False): 

390 """Get the three unit cell vectors as a `class`:ase.cell.Cell` object. 

391 

392 The Cell object resembles a 3x3 ndarray, and cell[i, j] 

393 is the jth Cartesian coordinate of the ith cell vector.""" 

394 if complete: 

395 cell = self.cell.complete() 

396 else: 

397 cell = self.cell.copy() 

398 

399 return cell 

400 

401 @deprecated('Please use atoms.cell.cellpar() instead', DeprecationWarning) 

402 def get_cell_lengths_and_angles(self): 

403 """Get unit cell parameters. Sequence of 6 numbers. 

404 

405 First three are unit cell vector lengths and second three 

406 are angles between them:: 

407 

408 [len(a), len(b), len(c), angle(b,c), angle(a,c), angle(a,b)] 

409 

410 in degrees. 

411 

412 .. deprecated:: 3.21.0 

413 Please use ``atoms.cell.cellpar()`` instead 

414 """ 

415 return self.cell.cellpar() 

416 

417 @deprecated('Please use atoms.cell.reciprocal()', DeprecationWarning) 

418 def get_reciprocal_cell(self): 

419 """Get the three reciprocal lattice vectors as a 3x3 ndarray. 

420 

421 Note that the commonly used factor of 2 pi for Fourier 

422 transforms is not included here. 

423 

424 .. deprecated:: 3.21.0 

425 Please use ``atoms.cell.reciprocal()`` 

426 """ 

427 return self.cell.reciprocal() 

428 

429 @property 

430 def pbc(self): 

431 """Reference to pbc-flags for in-place manipulations.""" 

432 return self._pbc 

433 

434 @pbc.setter 

435 def pbc(self, pbc): 

436 self._pbc[:] = pbc 

437 

438 def set_pbc(self, pbc): 

439 """Set periodic boundary condition flags.""" 

440 self.pbc = pbc 

441 

442 def get_pbc(self): 

443 """Get periodic boundary condition flags.""" 

444 return self.pbc.copy() 

445 

446 def new_array(self, name, a, dtype=None, shape=None): 

447 """Add new array. 

448 

449 If *shape* is not *None*, the shape of *a* will be checked.""" 

450 

451 if dtype is not None: 

452 a = np.array(a, dtype, order='C') 

453 if len(a) == 0 and shape is not None: 

454 a = a.reshape((-1, *shape)) 

455 else: 

456 if not a.flags['C_CONTIGUOUS']: 

457 a = np.ascontiguousarray(a) 

458 else: 

459 a = a.copy() 

460 

461 if name in self.arrays: 

462 raise RuntimeError(f'Array {name} already present') 

463 

464 for b in self.arrays.values(): 

465 if len(a) != len(b): 

466 raise ValueError( 

467 'Array "%s" has wrong length: %d != %d.' 

468 % (name, len(a), len(b)) 

469 ) 

470 break 

471 

472 if shape is not None and a.shape[1:] != shape: 

473 raise ValueError( 

474 f'Array "{name}" has wrong shape {a.shape} != ' 

475 f'{(a.shape[0:1] + shape)}.' 

476 ) 

477 

478 self.arrays[name] = a 

479 

480 def get_array(self, name, copy=True): 

481 """Get an array. 

482 

483 Returns a copy unless the optional argument copy is false. 

484 """ 

485 if copy: 

486 return self.arrays[name].copy() 

487 else: 

488 return self.arrays[name] 

489 

490 def set_array(self, name, a, dtype=None, shape=None): 

491 """Update array. 

492 

493 If *shape* is not *None*, the shape of *a* will be checked. 

494 If *a* is *None*, then the array is deleted.""" 

495 

496 b = self.arrays.get(name) 

497 if b is None: 

498 if a is not None: 

499 self.new_array(name, a, dtype, shape) 

500 else: 

501 if a is None: 

502 del self.arrays[name] 

503 else: 

504 a = np.asarray(a) 

505 if a.shape != b.shape: 

506 raise ValueError( 

507 f'Array "{name}" has wrong shape ' 

508 f'{a.shape} != {b.shape}.' 

509 ) 

510 b[:] = a 

511 

512 def has(self, name): 

513 """Check for existence of array. 

514 

515 name must be one of: 'tags', 'momenta', 'masses', 'initial_magmoms', 

516 'initial_charges'.""" 

517 # XXX extend has to calculator properties 

518 return name in self.arrays 

519 

520 def get_chemical_formula(self, mode='hill', empirical=False): 

521 """Get the chemical formula as a string based on the chemical symbols. 

522 

523 Parameters 

524 ---------- 

525 

526 mode: str 

527 There are four different modes available: 

528 

529 'all': The list of chemical symbols are contracted to a string, 

530 e.g. ['C', 'H', 'H', 'H', 'O', 'H'] becomes 'CHHHOH'. 

531 

532 'reduce': The same as 'all' where repeated elements are contracted 

533 to a single symbol and a number, e.g. 'CHHHOCHHH' is reduced to 

534 'CH3OCH3'. 

535 

536 'hill': The list of chemical symbols are contracted to a string 

537 following the Hill notation (alphabetical order with C and H 

538 first), e.g. 'CHHHOCHHH' is reduced to 'C2H6O' and 'SOOHOHO' to 

539 'H2O4S'. This is default. 

540 

541 'metal': The list of chemical symbols (alphabetical metals, 

542 and alphabetical non-metals) 

543 

544 empirical, bool (optional, default=False) 

545 Divide the symbol counts by their greatest common divisor to yield 

546 an empirical formula. Only for mode `metal` and `hill`. 

547 """ 

548 return self.symbols.get_chemical_formula(mode, empirical) 

549 

550 def set_tags(self, tags): 

551 """Set tags for all atoms. If only one tag is supplied, it is 

552 applied to all atoms.""" 

553 if isinstance(tags, int): 

554 tags = [tags] * len(self) 

555 self.set_array('tags', tags, int, ()) 

556 

557 def get_tags(self): 

558 """Get integer array of tags.""" 

559 if 'tags' in self.arrays: 

560 return self.arrays['tags'].copy() 

561 else: 

562 return np.zeros(len(self), int) 

563 

564 def set_momenta(self, momenta, apply_constraint=True): 

565 """Set momenta.""" 

566 if ( 

567 apply_constraint 

568 and len(self.constraints) > 0 

569 and momenta is not None 

570 ): 

571 momenta = np.array(momenta) # modify a copy 

572 for constraint in self.constraints: 

573 if hasattr(constraint, 'adjust_momenta'): 

574 constraint.adjust_momenta(self, momenta) 

575 self.set_array('momenta', momenta, float, (3,)) 

576 

577 def get_momenta(self): 

578 """Get array of momenta.""" 

579 if 'momenta' in self.arrays: 

580 return self.arrays['momenta'].copy() 

581 else: 

582 return np.zeros((len(self), 3)) 

583 

584 def get_velocities(self): 

585 """Get array of velocities.""" 

586 momenta = self.get_momenta() 

587 masses = self.get_masses() 

588 return momenta / masses[:, np.newaxis] 

589 

590 def set_velocities(self, velocities): 

591 """Set the momenta by specifying the velocities.""" 

592 self.set_momenta(self.get_masses()[:, np.newaxis] * velocities) 

593 

594 def set_masses(self, masses='defaults'): 

595 """Set atomic masses in atomic mass units. 

596 

597 The array masses should contain a list of masses. In case 

598 the masses argument is not given or for those elements of the 

599 masses list that are None, standard values are set.""" 

600 

601 if isinstance(masses, str): 

602 if masses == 'defaults': 

603 masses = atomic_masses[self.arrays['numbers']] 

604 elif masses == 'most_common': 

605 masses = atomic_masses_common[self.arrays['numbers']] 

606 elif masses is None: 

607 pass 

608 elif not isinstance(masses, np.ndarray): 

609 masses = list(masses) 

610 for i, mass in enumerate(masses): 

611 if mass is None: 

612 masses[i] = atomic_masses[self.numbers[i]] 

613 self.set_array('masses', masses, float, ()) 

614 

615 def get_masses(self) -> np.ndarray: 

616 """Get masses of atoms. 

617 

618 Returns 

619 ------- 

620 masses : np.ndarray 

621 Atomic masses in dalton (unified atomic mass units). 

622 

623 Examples 

624 -------- 

625 >>> from ase.build import molecule 

626 >>> atoms = molecule('CH4') 

627 >>> atoms.get_masses() 

628 array([12.011, 1.008, 1.008, 1.008, 1.008]) 

629 >>> total_mass = atoms.get_masses().sum() 

630 >>> print(f'{total_mass:f}') 

631 16.043000 

632 """ 

633 if 'masses' in self.arrays: 

634 return self.arrays['masses'].copy() 

635 return atomic_masses[self.arrays['numbers']] 

636 

637 def set_initial_magnetic_moments(self, magmoms=None): 

638 """Set the initial magnetic moments. 

639 

640 Use either one or three numbers for every atom (collinear 

641 or non-collinear spins).""" 

642 

643 if magmoms is None: 

644 self.set_array('initial_magmoms', None) 

645 else: 

646 magmoms = np.asarray(magmoms) 

647 self.set_array('initial_magmoms', magmoms, float, magmoms.shape[1:]) 

648 

649 def get_initial_magnetic_moments(self): 

650 """Get array of initial magnetic moments.""" 

651 if 'initial_magmoms' in self.arrays: 

652 return self.arrays['initial_magmoms'].copy() 

653 else: 

654 return np.zeros(len(self)) 

655 

656 def set_initial_charges(self, charges=None): 

657 """Set the initial charges.""" 

658 

659 if charges is None: 

660 self.set_array('initial_charges', None) 

661 else: 

662 self.set_array('initial_charges', charges, float, ()) 

663 

664 def get_initial_charges(self): 

665 """Get array of initial charges.""" 

666 if 'initial_charges' in self.arrays: 

667 return self.arrays['initial_charges'].copy() 

668 else: 

669 return np.zeros(len(self)) 

670 

671 def get_kinetic_energy(self): 

672 """Get the kinetic energy.""" 

673 momenta = self.arrays.get('momenta') 

674 if momenta is None: 

675 return 0.0 

676 return 0.5 * np.vdot(momenta, self.get_velocities()) 

677 

678 def get_kinetic_stress(self, voigt=True): 

679 """Calculate the kinetic part of the Virial stress tensor.""" 

680 stress = np.zeros(6) # Voigt notation 

681 stresscomp = np.array([[0, 5, 4], [5, 1, 3], [4, 3, 2]]) 

682 p = self.get_momenta() 

683 masses = self.get_masses() 

684 invmass = 1.0 / masses 

685 invvol = 1.0 / self.get_volume() 

686 for alpha in range(3): 

687 for beta in range(alpha, 3): 

688 stress[stresscomp[alpha, beta]] -= ( 

689 p[:, alpha] * p[:, beta] * invmass 

690 ).sum() * invvol 

691 

692 if voigt: 

693 return stress 

694 else: 

695 return voigt_6_to_full_3x3_stress(stress) 

696 

697 def copy(self): 

698 """Return a copy.""" 

699 atoms = self.__class__( 

700 cell=self.cell, 

701 pbc=self.pbc, 

702 info=copy.deepcopy(self.info), 

703 celldisp=self._celldisp.copy(), 

704 ) 

705 

706 atoms.arrays = {} 

707 for name, a in self.arrays.items(): 

708 atoms.arrays[name] = a.copy() 

709 atoms.constraints = copy.deepcopy(self.constraints) 

710 return atoms 

711 

712 def todict(self): 

713 """For basic JSON (non-database) support.""" 

714 d = dict(self.arrays) 

715 d['cell'] = np.asarray(self.cell) 

716 d['pbc'] = self.pbc 

717 if self._celldisp.any(): 

718 d['celldisp'] = self._celldisp 

719 if self.constraints: 

720 d['constraints'] = self.constraints 

721 if self.info: 

722 d['info'] = self.info 

723 # Calculator... trouble. 

724 return d 

725 

726 @classmethod 

727 def fromdict(cls, dct): 

728 """Rebuild atoms object from dictionary representation (todict).""" 

729 dct = dct.copy() 

730 kw = { 

731 name: dct.pop(name) 

732 for name in ['numbers', 'positions', 'cell', 'pbc'] 

733 } 

734 constraints = dct.pop('constraints', None) 

735 if constraints: 

736 from ase.constraints import dict2constraint 

737 

738 constraints = [dict2constraint(d) for d in constraints] 

739 

740 info = dct.pop('info', None) 

741 

742 atoms = cls( 

743 constraint=constraints, 

744 celldisp=dct.pop('celldisp', None), 

745 info=info, 

746 **kw, 

747 ) 

748 natoms = len(atoms) 

749 

750 # Some arrays are named differently from the atoms __init__ keywords. 

751 # Also, there may be custom arrays. Hence we set them directly: 

752 for name, arr in dct.items(): 

753 assert len(arr) == natoms, name 

754 assert isinstance(arr, np.ndarray) 

755 atoms.arrays[name] = arr 

756 return atoms 

757 

758 def __len__(self): 

759 return len(self.arrays['positions']) 

760 

761 @deprecated( 

762 'Please use len(self) or, if your atoms are distributed, ' 

763 'self.get_global_number_of_atoms.', 

764 category=FutureWarning, 

765 ) 

766 def get_number_of_atoms(self): 

767 """ 

768 .. deprecated:: 3.18.1 

769 You probably want ``len(atoms)``. Or if your atoms are distributed, 

770 use (and see) :func:`get_global_number_of_atoms()`. 

771 """ 

772 return len(self) 

773 

774 def get_global_number_of_atoms(self): 

775 """Returns the global number of atoms in a distributed-atoms parallel 

776 simulation. 

777 

778 DO NOT USE UNLESS YOU KNOW WHAT YOU ARE DOING! 

779 

780 Equivalent to len(atoms) in the standard ASE Atoms class. You should 

781 normally use len(atoms) instead. This function's only purpose is to 

782 make compatibility between ASE and Asap easier to maintain by having a 

783 few places in ASE use this function instead. It is typically only 

784 when counting the global number of degrees of freedom or in similar 

785 situations. 

786 """ 

787 return len(self) 

788 

789 def _get_tokens_for_repr(self) -> list[str]: 

790 tokens = [] 

791 

792 N = len(self) 

793 if N <= 60: 

794 symbols = self.get_chemical_formula('reduce') 

795 else: 

796 symbols = self.get_chemical_formula('hill') 

797 tokens.append(f"symbols='{symbols}'") 

798 

799 if self.pbc.any() and not self.pbc.all(): 

800 tokens.append(f'pbc={self.pbc.tolist()}') 

801 else: 

802 tokens.append(f'pbc={self.pbc[0]}') 

803 

804 cell = self.cell 

805 if cell: 

806 if cell.orthorhombic: 

807 cell = cell.lengths().tolist() 

808 else: 

809 cell = cell.tolist() 

810 tokens.append(f'cell={cell}') 

811 

812 for name in sorted(self.arrays): 

813 if name in ['numbers', 'positions']: 

814 continue 

815 tokens.append(f'{name}=...') 

816 

817 if self.constraints: 

818 if len(self.constraints) == 1: 

819 constraint = self.constraints[0] 

820 else: 

821 constraint = self.constraints 

822 tokens.append(f'constraint={constraint!r}') 

823 

824 return tokens 

825 

826 def __repr__(self) -> str: 

827 tokens = self._get_tokens_for_repr() 

828 return '{}({})'.format(self.__class__.__name__, ', '.join(tokens)) 

829 

830 def __add__(self, other): 

831 atoms = self.copy() 

832 atoms += other 

833 return atoms 

834 

835 def extend(self, other): 

836 """Extend atoms object by appending atoms from *other*.""" 

837 if isinstance(other, Atom): 

838 other = self.__class__([other]) 

839 

840 n1 = len(self) 

841 n2 = len(other) 

842 

843 for name, a1 in self.arrays.items(): 

844 a = np.zeros((n1 + n2,) + a1.shape[1:], a1.dtype) 

845 a[:n1] = a1 

846 if name == 'masses': 

847 a2 = other.get_masses() 

848 else: 

849 a2 = other.arrays.get(name) 

850 if a2 is not None: 

851 a[n1:] = a2 

852 self.arrays[name] = a 

853 

854 for name, a2 in other.arrays.items(): 

855 if name in self.arrays: 

856 continue 

857 a = np.empty((n1 + n2,) + a2.shape[1:], a2.dtype) 

858 a[n1:] = a2 

859 if name == 'masses': 

860 a[:n1] = self.get_masses()[:n1] 

861 else: 

862 a[:n1] = 0 

863 

864 self.set_array(name, a) 

865 

866 def __iadd__(self, other): 

867 self.extend(other) 

868 return self 

869 

870 def append(self, atom): 

871 """Append atom to end.""" 

872 self.extend(self.__class__([atom])) 

873 

874 def __iter__(self): 

875 for i in range(len(self)): 

876 yield self[i] 

877 

878 @overload 

879 def __getitem__(self, i: int | np.integer) -> Atom: ... 

880 

881 @overload 

882 def __getitem__(self, i: Sequence | slice | np.ndarray) -> Atoms: ... 

883 

884 def __getitem__(self, i): 

885 """Return a subset of the atoms. 

886 

887 i -- scalar integer, list of integers, or slice object 

888 describing which atoms to return. 

889 

890 If i is a scalar, return an Atom object. If i is a list or a 

891 slice, return an Atoms object with the same cell, pbc, and 

892 other associated info as the original Atoms object. The 

893 indices of the constraints will be shuffled so that they match 

894 the indexing in the subset returned. 

895 

896 """ 

897 

898 if isinstance(i, numbers.Integral): 

899 natoms = len(self) 

900 if i < -natoms or i >= natoms: 

901 raise IndexError('Index out of range.') 

902 

903 return Atom(atoms=self, index=i) 

904 elif not isinstance(i, slice): 

905 i = np.array(i) 

906 if len(i) == 0: 

907 i = np.array([], dtype=int) 

908 # if i is a mask 

909 if i.dtype == bool: 

910 if len(i) != len(self): 

911 raise IndexError( 

912 'Length of mask {} must equal ' 

913 'number of atoms {}'.format(len(i), len(self)) 

914 ) 

915 i = np.arange(len(self))[i] 

916 

917 import copy 

918 

919 conadd = [] 

920 # Constraints need to be deepcopied, but only the relevant ones. 

921 for con in copy.deepcopy(self.constraints): 

922 try: 

923 con.index_shuffle(self, i) 

924 except (IndexError, NotImplementedError): 

925 pass 

926 else: 

927 conadd.append(con) 

928 

929 atoms = self.__class__( 

930 cell=self.cell, 

931 pbc=self.pbc, 

932 info=copy.deepcopy(self.info), 

933 # should be communicated to the slice as well 

934 celldisp=self._celldisp, 

935 ) 

936 # TODO: Do we need to shuffle indices in adsorbate_info too? 

937 

938 atoms.arrays = {} 

939 for name, a in self.arrays.items(): 

940 atoms.arrays[name] = a[i].copy() 

941 

942 atoms.constraints = conadd 

943 return atoms 

944 

945 def __delitem__(self, i): 

946 from ase.constraints import FixAtoms 

947 

948 for c in self._constraints: 

949 if not isinstance(c, FixAtoms): 

950 raise RuntimeError( 

951 'Remove constraint using set_constraint() ' 

952 'before deleting atoms.' 

953 ) 

954 

955 if isinstance(i, list) and len(i) > 0: 

956 # Make sure a list of booleans will work correctly and not be 

957 # interpreted at 0 and 1 indices. 

958 i = np.array(i) 

959 

960 if len(self._constraints) > 0: 

961 n = len(self) 

962 i = np.arange(n)[i] 

963 if isinstance(i, int): 

964 i = [i] 

965 constraints = [] 

966 for c in self._constraints: 

967 c = c.delete_atoms(i, n) 

968 if c is not None: 

969 constraints.append(c) 

970 self.constraints = constraints 

971 

972 mask = np.ones(len(self), bool) 

973 mask[i] = False 

974 for name, a in self.arrays.items(): 

975 self.arrays[name] = a[mask] 

976 

977 def pop(self, i=-1): 

978 """Remove and return atom at index *i* (default last).""" 

979 atom = self[i] 

980 atom.cut_reference_to_atoms() 

981 del self[i] 

982 return atom 

983 

984 def __imul__(self, m): 

985 """In-place repeat of atoms.""" 

986 if isinstance(m, int): 

987 m = (m, m, m) 

988 

989 for x, vec in zip(m, self.cell): 

990 if x != 1 and not vec.any(): 

991 raise ValueError('Cannot repeat along undefined lattice vector') 

992 

993 M = np.prod(m) 

994 n = len(self) 

995 

996 for name, a in self.arrays.items(): 

997 self.arrays[name] = np.tile(a, (M,) + (1,) * (len(a.shape) - 1)) 

998 

999 positions = self.arrays['positions'] 

1000 i0 = 0 

1001 for m0 in range(m[0]): 

1002 for m1 in range(m[1]): 

1003 for m2 in range(m[2]): 

1004 i1 = i0 + n 

1005 positions[i0:i1] += np.dot((m0, m1, m2), self.cell) 

1006 i0 = i1 

1007 

1008 if self.constraints is not None: 

1009 self.constraints = [c.repeat(m, n) for c in self.constraints] 

1010 

1011 self.cell = np.array([m[c] * self.cell[c] for c in range(3)]) 

1012 

1013 return self 

1014 

1015 def repeat(self, rep): 

1016 """Create new repeated atoms object. 

1017 

1018 The *rep* argument should be a sequence of three positive 

1019 integers like *(2,3,1)* or a single integer (*r*) equivalent 

1020 to *(r,r,r)*.""" 

1021 

1022 atoms = self.copy() 

1023 atoms *= rep 

1024 return atoms 

1025 

1026 def __mul__(self, rep): 

1027 return self.repeat(rep) 

1028 

1029 def translate(self, displacement): 

1030 """Translate atomic positions. 

1031 

1032 The displacement argument can be a float an xyz vector or an 

1033 nx3 array (where n is the number of atoms).""" 

1034 

1035 self.arrays['positions'] += np.array(displacement) 

1036 

1037 def center(self, vacuum=None, axis=(0, 1, 2), about=None): 

1038 """Center atoms in unit cell. 

1039 

1040 Centers the atoms in the unit cell, so there is the same 

1041 amount of vacuum on all sides. 

1042 

1043 Parameters 

1044 ---------- 

1045 vacuum: float, default: None 

1046 If specified adjust the amount of vacuum when centering. 

1047 If vacuum=10.0 there will thus be 10 Angstrom of vacuum 

1048 on each side. 

1049 axis: int | Sequence[int], default: (0, 1, 2) 

1050 Axis or axes to act on. Default: Act on all axes. 

1051 about: float | Sequence[float] | None, default: None 

1052 If specified, center the atoms about the given point. 

1053 

1054 .. versionadded:: 3.30.0 

1055 A float value is accepted, which is applied to all the axes 

1056 selected by `axis`. 

1057 

1058 """ 

1059 

1060 # Find the orientations of the faces of the unit cell 

1061 cell = self.cell.complete() 

1062 dirs = np.zeros_like(cell) 

1063 

1064 lengths = cell.lengths() 

1065 for i in range(3): 

1066 dirs[i] = np.cross(cell[i - 1], cell[i - 2]) 

1067 dirs[i] /= np.linalg.norm(dirs[i]) 

1068 if dirs[i] @ cell[i] < 0.0: 

1069 dirs[i] *= -1 

1070 

1071 if isinstance(axis, int): 

1072 axes = (axis,) 

1073 else: 

1074 axes = axis 

1075 

1076 # Now, decide how much each basis vector should be made longer 

1077 pos = self.positions 

1078 longer = np.zeros(3) 

1079 shift = np.zeros(3) 

1080 for i in axes: 

1081 if len(pos): 

1082 scalarprod = pos @ dirs[i] 

1083 p0 = scalarprod.min() 

1084 p1 = scalarprod.max() 

1085 else: 

1086 p0 = 0 

1087 p1 = 0 

1088 height = cell[i] @ dirs[i] 

1089 if vacuum is not None: 

1090 lng = (p1 - p0 + 2 * vacuum) - height 

1091 else: 

1092 lng = 0.0 # Do not change unit cell size! 

1093 top = lng + height - p1 

1094 shf = 0.5 * (top - p0) 

1095 cosphi = cell[i] @ dirs[i] / lengths[i] 

1096 longer[i] = lng / cosphi 

1097 shift[i] = shf / cosphi 

1098 

1099 # Now, do it! 

1100 translation = np.zeros(3) 

1101 for i in axes: 

1102 nowlen = lengths[i] 

1103 if vacuum is not None: 

1104 self.cell[i] = cell[i] * (1 + longer[i] / nowlen) 

1105 translation += shift[i] * cell[i] / nowlen 

1106 

1107 # We calculated translations using the completed cell, 

1108 # so directions without cell vectors will have been centered 

1109 # along a "fake" vector of length 1. 

1110 # Therefore, we adjust by -0.5: 

1111 if not any(self.cell[i]): 

1112 translation[i] -= 0.5 

1113 

1114 # Optionally, translate to center about a point in space. 

1115 if about is not None: 

1116 # Convert scalar to a 3-element array to prevent subscriptable error 

1117 if np.isscalar(about): 

1118 about = [about] * 3 

1119 for n, vector in enumerate(self.cell): 

1120 if n in axes: 

1121 translation -= vector / 2.0 

1122 translation[n] += about[n] 

1123 

1124 self.positions += translation 

1125 

1126 def get_center_of_mass(self, scaled=False, indices=None): 

1127 """Get the center of mass. 

1128 

1129 Parameters 

1130 ---------- 

1131 scaled : bool 

1132 If True, the center of mass in scaled coordinates is returned. 

1133 indices : list | slice | str, default: None 

1134 If specified, the center of mass of a subset of atoms is returned. 

1135 """ 

1136 if indices is None: 

1137 indices = slice(None) 

1138 elif isinstance(indices, str): 

1139 indices = string2index(indices) 

1140 

1141 masses = self.get_masses()[indices] 

1142 com = masses @ self.positions[indices] / masses.sum() 

1143 if scaled: 

1144 return self.cell.scaled_positions(com) 

1145 return com # Cartesian coordinates 

1146 

1147 def set_center_of_mass(self, com, scaled=False): 

1148 """Set the center of mass. 

1149 

1150 If scaled=True the center of mass is expected in scaled coordinates. 

1151 Constraints are considered for scaled=False. 

1152 """ 

1153 old_com = self.get_center_of_mass(scaled=scaled) 

1154 difference = com - old_com 

1155 if scaled: 

1156 self.set_scaled_positions(self.get_scaled_positions() + difference) 

1157 else: 

1158 self.set_positions(self.get_positions() + difference) 

1159 

1160 def get_moments_of_inertia(self, vectors=False): 

1161 """Get the moments of inertia along the principal axes. 

1162 

1163 The three principal moments of inertia are computed from the 

1164 eigenvalues of the symmetric inertial tensor. Note that the result 

1165 can be "wrong" if a molecule is crossing periodic boundaries. 

1166 Units of the moments of inertia are amu*angstrom**2. 

1167 

1168 Parameters 

1169 ---------- 

1170 vectors : bool 

1171 If true, also return the principal axes as rows in a 3x3 

1172 matrix. 

1173 """ 

1174 

1175 if self.pbc.any(): 

1176 # raise a user warning that PBC are ignored 

1177 warnings.warn( 

1178 'Periodic boundary conditions are ignored ' 

1179 'when calculating the inertial tensor.', 

1180 UserWarning, 

1181 ) 

1182 

1183 com = self.get_center_of_mass() 

1184 positions = self.get_positions() 

1185 positions -= com # translate center of mass to origin 

1186 masses = self.get_masses() 

1187 

1188 # Initialize elements of the inertial tensor 

1189 I11 = I22 = I33 = I12 = I13 = I23 = 0.0 

1190 for i in range(len(self)): 

1191 x, y, z = positions[i] 

1192 m = masses[i] 

1193 

1194 I11 += m * (y**2 + z**2) 

1195 I22 += m * (x**2 + z**2) 

1196 I33 += m * (x**2 + y**2) 

1197 I12 += -m * x * y 

1198 I13 += -m * x * z 

1199 I23 += -m * y * z 

1200 

1201 Itensor = np.array([[I11, I12, I13], [I12, I22, I23], [I13, I23, I33]]) 

1202 

1203 evals, evecs = np.linalg.eigh(Itensor) 

1204 if vectors: 

1205 return evals, evecs.transpose() 

1206 else: 

1207 return evals 

1208 

1209 def get_angular_momentum(self): 

1210 """Get total angular momentum with respect to the center of mass.""" 

1211 com = self.get_center_of_mass() 

1212 positions = self.get_positions() 

1213 positions -= com # translate center of mass to origin 

1214 return np.cross(positions, self.get_momenta()).sum(0) 

1215 

1216 def rotate(self, a, v, center=(0, 0, 0), rotate_cell=False): 

1217 """Rotate atoms based on a vector and an angle, or two vectors. 

1218 

1219 Parameters 

1220 ---------- 

1221 

1222 a = None: 

1223 Angle that the atoms is rotated around the vector 'v'. 'a' 

1224 can also be a vector and then 'a' is rotated 

1225 into 'v'. 

1226 

1227 v: 

1228 Vector to rotate the atoms around. Vectors can be given as 

1229 strings: 'x', '-x', 'y', ... . 

1230 

1231 center = (0, 0, 0): 

1232 The center is kept fixed under the rotation. Use 'COM' to fix 

1233 the center of mass, 'COP' to fix the center of positions or 

1234 'COU' to fix the center of cell. 

1235 

1236 rotate_cell = False: 

1237 If true the cell is also rotated. 

1238 

1239 Examples 

1240 -------- 

1241 

1242 Rotate 90 degrees around the z-axis, so that the x-axis is 

1243 rotated into the y-axis: 

1244 

1245 >>> atoms = Atoms() 

1246 >>> atoms.rotate(90, 'z') 

1247 >>> atoms.rotate(90, (0, 0, 1)) 

1248 >>> atoms.rotate(-90, '-z') 

1249 >>> atoms.rotate('x', 'y') 

1250 >>> atoms.rotate((1, 0, 0), (0, 1, 0)) 

1251 """ 

1252 

1253 if not isinstance(a, numbers.Real): 

1254 a, v = v, a 

1255 

1256 norm = np.linalg.norm 

1257 v = string2vector(v) 

1258 

1259 normv = norm(v) 

1260 

1261 if normv == 0.0: 

1262 raise ZeroDivisionError('Cannot rotate: norm(v) == 0') 

1263 

1264 if isinstance(a, numbers.Real): 

1265 a *= pi / 180 

1266 v /= normv 

1267 c = cos(a) 

1268 s = sin(a) 

1269 else: 

1270 v2 = string2vector(a) 

1271 v /= normv 

1272 normv2 = np.linalg.norm(v2) 

1273 if normv2 == 0: 

1274 raise ZeroDivisionError('Cannot rotate: norm(a) == 0') 

1275 v2 /= norm(v2) 

1276 c = np.dot(v, v2) 

1277 v = np.cross(v, v2) 

1278 s = norm(v) 

1279 # In case *v* and *a* are parallel, np.cross(v, v2) vanish 

1280 # and can't be used as a rotation axis. However, in this 

1281 # case any rotation axis perpendicular to v2 will do. 

1282 eps = 1e-7 

1283 if s < eps: 

1284 v = np.cross((0, 0, 1), v2) 

1285 if norm(v) < eps: 

1286 v = np.cross((1, 0, 0), v2) 

1287 assert norm(v) >= eps 

1288 elif s > 0: 

1289 v /= s 

1290 

1291 center = self._centering_as_array(center) 

1292 

1293 p = self.arrays['positions'] - center 

1294 self.arrays['positions'][:] = ( 

1295 c * p 

1296 - np.cross(p, s * v) 

1297 + np.outer(np.dot(p, v), (1.0 - c) * v) 

1298 + center 

1299 ) 

1300 if rotate_cell: 

1301 rotcell = self.get_cell() 

1302 rotcell[:] = ( 

1303 c * rotcell 

1304 - np.cross(rotcell, s * v) 

1305 + np.outer(np.dot(rotcell, v), (1.0 - c) * v) 

1306 ) 

1307 self.set_cell(rotcell) 

1308 

1309 def _centering_as_array(self, center): 

1310 if isinstance(center, str): 

1311 if center.lower() == 'com': 

1312 center = self.get_center_of_mass() 

1313 elif center.lower() == 'cop': 

1314 center = self.get_positions().mean(axis=0) 

1315 elif center.lower() == 'cou': 

1316 center = self.get_cell().sum(axis=0) / 2 

1317 else: 

1318 raise ValueError('Cannot interpret center') 

1319 else: 

1320 center = np.array(center, float) 

1321 return center 

1322 

1323 def euler_rotate( 

1324 self, 

1325 phi: float = 0.0, 

1326 theta: float = 0.0, 

1327 psi: float = 0.0, 

1328 center: Sequence[float] = (0.0, 0.0, 0.0), 

1329 ) -> None: 

1330 """Rotate atoms via Euler angles (in degrees). 

1331 

1332 See e.g https://mathworld.wolfram.com/EulerAngles.html for explanation. 

1333 

1334 Note that the rotations in this method are passive and applied **not** 

1335 to the atomic coordinates in the present frame **but** the frame itself. 

1336 

1337 Parameters 

1338 ---------- 

1339 phi : float 

1340 The 1st rotation angle around the z axis. 

1341 theta : float 

1342 Rotation around the x axis. 

1343 psi : float 

1344 2nd rotation around the z axis. 

1345 center : Sequence[float], default = (0.0, 0.0, 0.0) 

1346 The point to rotate about. A sequence of length 3 with the 

1347 coordinates, or 'COM' to select the center of mass, 'COP' to 

1348 select center of positions or 'COU' to select center of cell. 

1349 

1350 """ 

1351 from scipy.spatial.transform import Rotation as R 

1352 

1353 center = self._centering_as_array(center) 

1354 

1355 # passive rotations (negative angles) for backward compatibility 

1356 rotation = R.from_euler('zxz', (-phi, -theta, -psi), degrees=True) 

1357 

1358 self.positions = rotation.apply(self.positions - center) + center 

1359 

1360 def get_dihedral(self, a0, a1, a2, a3, mic=False): 

1361 """Calculate dihedral angle. 

1362 

1363 Calculate dihedral angle (in degrees) between the vectors a0->a1 

1364 and a2->a3. 

1365 

1366 Use mic=True to use the Minimum Image Convention and calculate the 

1367 angle across periodic boundaries. 

1368 """ 

1369 return self.get_dihedrals([[a0, a1, a2, a3]], mic=mic)[0] 

1370 

1371 def get_dihedrals(self, indices, mic=False): 

1372 """Calculate dihedral angles. 

1373 

1374 Calculate dihedral angles (in degrees) between the list of vectors 

1375 a0->a1 and a2->a3, where a0, a1, a2 and a3 are in each row of indices. 

1376 

1377 Use mic=True to use the Minimum Image Convention and calculate the 

1378 angles across periodic boundaries. 

1379 """ 

1380 from ase.geometry import get_dihedrals 

1381 

1382 indices = np.array(indices) 

1383 assert indices.shape[1] == 4 

1384 

1385 a0s = self.positions[indices[:, 0]] 

1386 a1s = self.positions[indices[:, 1]] 

1387 a2s = self.positions[indices[:, 2]] 

1388 a3s = self.positions[indices[:, 3]] 

1389 

1390 # vectors 0->1, 1->2, 2->3 

1391 v0 = a1s - a0s 

1392 v1 = a2s - a1s 

1393 v2 = a3s - a2s 

1394 

1395 cell = None 

1396 pbc = None 

1397 

1398 if mic: 

1399 cell = self.cell 

1400 pbc = self.pbc 

1401 

1402 return get_dihedrals(v0, v1, v2, cell=cell, pbc=pbc) 

1403 

1404 def _masked_rotate(self, center, axis, diff, mask): 

1405 # do rotation of subgroup by copying it to temporary atoms object 

1406 # and then rotating that 

1407 # 

1408 # recursive object definition might not be the most elegant thing, 

1409 # more generally useful might be a rotation function with a mask? 

1410 group = self.__class__() 

1411 for i in range(len(self)): 

1412 if mask[i]: 

1413 group += self[i] 

1414 group.translate(-center) 

1415 group.rotate(diff * 180 / pi, axis) 

1416 group.translate(center) 

1417 # set positions in original atoms object 

1418 j = 0 

1419 for i in range(len(self)): 

1420 if mask[i]: 

1421 self.positions[i] = group[j].position 

1422 j += 1 

1423 

1424 def set_dihedral(self, a1, a2, a3, a4, angle, mask=None, indices=None): 

1425 """Set the dihedral angle (degrees) between vectors a1->a2 and 

1426 a3->a4 by changing the atom indexed by a4. 

1427 

1428 If mask is not None, all the atoms described in mask 

1429 (read: the entire subgroup) are moved. Alternatively to the mask, 

1430 the indices of the atoms to be rotated can be supplied. If both 

1431 *mask* and *indices* are given, *indices* overwrites *mask*. 

1432 

1433 **Important**: If *mask* or *indices* is given and does not contain 

1434 *a4*, *a4* will NOT be moved. In most cases you therefore want 

1435 to include *a4* in *mask*/*indices*. 

1436 

1437 Example: the following defines a very crude 

1438 ethane-like molecule and twists one half of it by 30 degrees. 

1439 

1440 >>> atoms = Atoms('HHCCHH', [[-1, 1, 0], [-1, -1, 0], [0, 0, 0], 

1441 ... [1, 0, 0], [2, 1, 0], [2, -1, 0]]) 

1442 >>> atoms.set_dihedral(1, 2, 3, 4, 210, mask=[0, 0, 0, 1, 1, 1]) 

1443 """ 

1444 

1445 angle *= pi / 180 

1446 

1447 # if not provided, set mask to the last atom in the 

1448 # dihedral description 

1449 if mask is None and indices is None: 

1450 mask = np.zeros(len(self)) 

1451 mask[a4] = 1 

1452 elif indices is not None: 

1453 mask = [index in indices for index in range(len(self))] 

1454 

1455 # compute necessary in dihedral change, from current value 

1456 current = self.get_dihedral(a1, a2, a3, a4) * pi / 180 

1457 diff = angle - current 

1458 axis = self.positions[a3] - self.positions[a2] 

1459 center = self.positions[a3] 

1460 self._masked_rotate(center, axis, diff, mask) 

1461 

1462 def rotate_dihedral(self, a1, a2, a3, a4, angle, mask=None, indices=None): 

1463 """Rotate dihedral angle. 

1464 

1465 Same usage as in :meth:`ase.Atoms.set_dihedral`: Rotate a group by a 

1466 predefined dihedral angle, starting from its current configuration. 

1467 """ 

1468 start = self.get_dihedral(a1, a2, a3, a4) 

1469 self.set_dihedral(a1, a2, a3, a4, angle + start, mask, indices) 

1470 

1471 def get_angle(self, a1, a2, a3, mic=False): 

1472 """Get angle formed by three atoms. 

1473 

1474 Calculate angle in degrees between the vectors a2->a1 and 

1475 a2->a3. 

1476 

1477 Use mic=True to use the Minimum Image Convention and calculate the 

1478 angle across periodic boundaries. 

1479 """ 

1480 return self.get_angles([[a1, a2, a3]], mic=mic)[0] 

1481 

1482 def get_angles(self, indices, mic=False): 

1483 """Get angle formed by three atoms for multiple groupings. 

1484 

1485 Calculate angle in degrees between vectors between atoms a2->a1 

1486 and a2->a3, where a1, a2, and a3 are in each row of indices. 

1487 

1488 Use mic=True to use the Minimum Image Convention and calculate 

1489 the angle across periodic boundaries. 

1490 """ 

1491 from ase.geometry import get_angles 

1492 

1493 indices = np.array(indices) 

1494 assert indices.shape[1] == 3 

1495 

1496 a1s = self.positions[indices[:, 0]] 

1497 a2s = self.positions[indices[:, 1]] 

1498 a3s = self.positions[indices[:, 2]] 

1499 

1500 v12 = a1s - a2s 

1501 v32 = a3s - a2s 

1502 

1503 cell = None 

1504 pbc = None 

1505 

1506 if mic: 

1507 cell = self.cell 

1508 pbc = self.pbc 

1509 

1510 return get_angles(v12, v32, cell=cell, pbc=pbc) 

1511 

1512 def set_angle( 

1513 self, 

1514 a1, 

1515 a2=None, 

1516 a3=None, 

1517 angle=None, 

1518 mask=None, 

1519 indices=None, 

1520 add=False, 

1521 ): 

1522 """Set angle (in degrees) formed by three atoms. 

1523 

1524 Sets the angle between vectors *a2*->*a1* and *a2*->*a3*. 

1525 

1526 If *add* is `True`, the angle will be changed by the value given. 

1527 

1528 Same usage as in :meth:`ase.Atoms.set_dihedral`. 

1529 If *mask* and *indices* 

1530 are given, *indices* overwrites *mask*. If *mask* and *indices* 

1531 are not set, only *a3* is moved.""" 

1532 

1533 if any(a is None for a in [a2, a3, angle]): 

1534 raise ValueError('a2, a3, and angle must not be None') 

1535 

1536 # If not provided, set mask to the last atom in the angle description 

1537 if mask is None and indices is None: 

1538 mask = np.zeros(len(self)) 

1539 mask[a3] = 1 

1540 elif indices is not None: 

1541 mask = [index in indices for index in range(len(self))] 

1542 

1543 if add: 

1544 diff = angle 

1545 else: 

1546 # Compute necessary in angle change, from current value 

1547 diff = angle - self.get_angle(a1, a2, a3) 

1548 

1549 diff *= pi / 180 

1550 # Do rotation of subgroup by copying it to temporary atoms object and 

1551 # then rotating that 

1552 v10 = self.positions[a1] - self.positions[a2] 

1553 v12 = self.positions[a3] - self.positions[a2] 

1554 v10 /= np.linalg.norm(v10) 

1555 v12 /= np.linalg.norm(v12) 

1556 axis = np.cross(v10, v12) 

1557 center = self.positions[a2] 

1558 self._masked_rotate(center, axis, diff, mask) 

1559 

1560 def mirror(self, v, center=None, indices=None, mirror_cell=False): 

1561 """Reflect atoms across a plane. 

1562 

1563 Parameters 

1564 ---------- 

1565 

1566 v : array_like or {'x', 'y', 'z'} 

1567 Normal vector of the plane of reflection, i.e. the direction in 

1568 which the atoms are mirrored. Vectors can be specified numerically 

1569 e.g.: (1, 0, 0); or as one of the strings 'x', 'y', or 'z'. 

1570 

1571 center : array_like or {'COM', 'COP', 'COU'} or None, default: None 

1572 The plane of reflection is shifted to include the center point. Use 

1573 'COM' to fix the center of mass (of all atoms), 'COP' to fix the 

1574 center of positions (all atoms) or 'COU' to fix the center of the 

1575 cell (or origin if cell is not defined). Has no effect, if 

1576 mirror_cell is True. 

1577 

1578 indices : array_like or None, default: None 

1579 Select which atoms are moved using an array of indices (or a 

1580 boolean mask). If None, then all atoms are affected. 

1581 

1582 mirror_cell : bool, default: False 

1583 If True, transform the cell with its contents. Can not be used 

1584 together with 'center'. 

1585 """ 

1586 v = string2vector(v) 

1587 v = v / np.linalg.norm(v) 

1588 if mirror_cell: 

1589 if center is not None: 

1590 raise ValueError( 

1591 "The 'center' keyword can't be used when mirroring cell." 

1592 ) 

1593 center = (0.0, 0.0, 0.0) 

1594 elif center is None: 

1595 center = 'COU' 

1596 center = self._centering_as_array(center) 

1597 

1598 if indices is None: 

1599 indices = np.ones(len(self), dtype=bool) 

1600 

1601 tmp_pos = self.positions.copy() 

1602 tmp_pos -= center 

1603 tmp_pos[indices, :] = self._mirror_array(tmp_pos[indices, :], v) 

1604 tmp_pos += center 

1605 self.set_positions(tmp_pos) 

1606 

1607 if mirror_cell: 

1608 self.set_cell(self._mirror_array(self.get_cell(), v)) 

1609 

1610 def _mirror_array(self, a, v): 

1611 """Mirror given array of coordinates across v, relative to origin 

1612 

1613 Following Ref_b(w) = w - 2 * (w·b)/(b·b) * b 

1614 """ 

1615 vdota = (a * v).sum(1, keepdims=True) 

1616 return a - vdota / np.dot(v, v) * 2 * v.reshape(1, 3) 

1617 

1618 def rattle(self, stdev=0.001, seed=None, rng=None): 

1619 """Randomly displace atoms. 

1620 

1621 This method adds random displacements to the atomic positions, 

1622 taking a possible constraint into account. The random numbers are 

1623 drawn from a normal distribution of standard deviation stdev. 

1624 

1625 By default, the random number generator always uses the same seed (42) 

1626 for repeatability. You can provide your own seed (an integer), or if you 

1627 want the randomness to be different each time you run a script, then 

1628 provide `rng=numpy.random`. For a parallel calculation, it is important 

1629 to use the same seed on all processors!""" 

1630 

1631 if seed is not None and rng is not None: 

1632 raise ValueError('Please do not provide both seed and rng.') 

1633 

1634 if rng is None: 

1635 if seed is None: 

1636 seed = 42 

1637 rng = np.random.RandomState(seed) 

1638 positions = self.arrays['positions'] 

1639 self.set_positions( 

1640 positions + rng.normal(scale=stdev, size=positions.shape) 

1641 ) 

1642 

1643 def get_distance(self, a0, a1, mic=False, vector=False): 

1644 """Return distance between two atoms. 

1645 

1646 Use mic=True to use the Minimum Image Convention. 

1647 vector=True gives the distance vector (from a0 to a1). 

1648 """ 

1649 return self.get_distances(a0, [a1], mic=mic, vector=vector)[0] 

1650 

1651 def get_distances(self, a, indices, mic=False, vector=False): 

1652 """Return distances of atom No.i with a list of atoms. 

1653 

1654 Use mic=True to use the Minimum Image Convention. 

1655 vector=True gives the distance vector (from a to self[indices]). 

1656 """ 

1657 from ase.geometry import get_distances 

1658 

1659 R = self.arrays['positions'] 

1660 p1 = [R[a]] 

1661 p2 = R[indices] 

1662 

1663 cell = None 

1664 pbc = None 

1665 

1666 if mic: 

1667 cell = self.cell 

1668 pbc = self.pbc 

1669 

1670 D, D_len = get_distances(p1, p2, cell=cell, pbc=pbc) 

1671 

1672 if vector: 

1673 return D.reshape((-1, 3)) 

1674 else: 

1675 return D_len.ravel() 

1676 

1677 def get_all_distances(self, mic=False, vector=False): 

1678 """Return distances of all of the atoms with all of the atoms. 

1679 

1680 Use mic=True to use the Minimum Image Convention. 

1681 """ 

1682 from ase.geometry import get_distances 

1683 

1684 R = self.arrays['positions'] 

1685 

1686 cell = None 

1687 pbc = None 

1688 

1689 if mic: 

1690 cell = self.cell 

1691 pbc = self.pbc 

1692 

1693 D, D_len = get_distances(R, cell=cell, pbc=pbc) 

1694 

1695 if vector: 

1696 return D 

1697 else: 

1698 return D_len 

1699 

1700 def set_distance( 

1701 self, 

1702 a0, 

1703 a1, 

1704 distance, 

1705 fix=0.5, 

1706 mic=False, 

1707 mask=None, 

1708 indices=None, 

1709 add=False, 

1710 factor=False, 

1711 ): 

1712 """Set the distance between two atoms. 

1713 

1714 Set the distance between atoms *a0* and *a1* to *distance*. 

1715 By default, the center of the two atoms will be fixed. Use 

1716 *fix=0* to fix the first atom, *fix=1* to fix the second 

1717 atom and *fix=0.5* (default) to fix the center of the bond. 

1718 

1719 If *mask* or *indices* are set (*mask* overwrites *indices*), 

1720 only the atoms defined there are moved 

1721 (see :meth:`ase.Atoms.set_dihedral`). 

1722 

1723 When *add* is true, the distance is changed by the value given. 

1724 In combination 

1725 with *factor* True, the value given is a factor scaling the distance. 

1726 

1727 It is assumed that the atoms in *mask*/*indices* move together 

1728 with *a1*. If *fix=1*, only *a0* will therefore be moved.""" 

1729 from ase.geometry import find_mic 

1730 

1731 if a0 % len(self) == a1 % len(self): 

1732 raise ValueError('a0 and a1 must not be the same') 

1733 

1734 if add: 

1735 oldDist = self.get_distance(a0, a1, mic=mic) 

1736 if factor: 

1737 newDist = oldDist * distance 

1738 else: 

1739 newDist = oldDist + distance 

1740 self.set_distance( 

1741 a0, 

1742 a1, 

1743 newDist, 

1744 fix=fix, 

1745 mic=mic, 

1746 mask=mask, 

1747 indices=indices, 

1748 add=False, 

1749 factor=False, 

1750 ) 

1751 return 

1752 

1753 R = self.arrays['positions'] 

1754 D = np.array([R[a1] - R[a0]]) 

1755 

1756 if mic: 

1757 D, D_len = find_mic(D, self.cell, self.pbc) 

1758 else: 

1759 D_len = np.array([np.sqrt((D**2).sum())]) 

1760 x = 1.0 - distance / D_len[0] 

1761 

1762 if mask is None and indices is None: 

1763 indices = [a0, a1] 

1764 elif mask: 

1765 indices = [i for i in range(len(self)) if mask[i]] 

1766 

1767 for i in indices: 

1768 if i == a0: 

1769 R[a0] += (x * fix) * D[0] 

1770 else: 

1771 R[i] -= (x * (1.0 - fix)) * D[0] 

1772 

1773 def get_scaled_positions(self, wrap=True): 

1774 """Get positions relative to unit cell. 

1775 

1776 If wrap is True, atoms outside the unit cell will be wrapped into 

1777 the cell in those directions with periodic boundary conditions 

1778 so that the scaled coordinates are between zero and one. 

1779 

1780 If any cell vectors are zero, the corresponding coordinates 

1781 are evaluated as if the cell were completed using 

1782 ``cell.complete()``. This means coordinates will be Cartesian 

1783 as long as the non-zero cell vectors span a Cartesian axis or 

1784 plane.""" 

1785 

1786 fractional = self.cell.scaled_positions(self.positions) 

1787 

1788 if wrap: 

1789 for i, periodic in enumerate(self.pbc): 

1790 if periodic: 

1791 # Yes, we need to do it twice. 

1792 # See the scaled_positions.py test. 

1793 fractional[:, i] %= 1.0 

1794 fractional[:, i] %= 1.0 

1795 

1796 return fractional 

1797 

1798 def set_scaled_positions(self, scaled): 

1799 """Set positions relative to unit cell.""" 

1800 self.positions[:] = self.cell.cartesian_positions(scaled) 

1801 

1802 def wrap(self, **wrap_kw): 

1803 """Wrap positions to unit cell. 

1804 

1805 Parameters 

1806 ---------- 

1807 

1808 wrap_kw: (keyword=value) pairs 

1809 optional keywords `pbc`, `center`, `pretty_translation`, `eps`, 

1810 see :func:`ase.geometry.wrap_positions` 

1811 """ 

1812 

1813 if 'pbc' not in wrap_kw: 

1814 wrap_kw['pbc'] = self.pbc 

1815 

1816 self.positions[:] = self.get_positions(wrap=True, **wrap_kw) 

1817 

1818 def get_temperature(self): 

1819 """Get the temperature in Kelvin.""" 

1820 ekin = self.get_kinetic_energy() 

1821 return 2 * ekin / (self.get_number_of_degrees_of_freedom() * units.kB) 

1822 

1823 def __eq__(self, other): 

1824 """Check for identity of two atoms objects. 

1825 

1826 Identity means: same positions, atomic numbers, unit cell and 

1827 periodic boundary conditions.""" 

1828 if not isinstance(other, Atoms): 

1829 return False 

1830 a = self.arrays 

1831 b = other.arrays 

1832 return ( 

1833 len(self) == len(other) 

1834 and (a['positions'] == b['positions']).all() 

1835 and (a['numbers'] == b['numbers']).all() 

1836 and (self.cell == other.cell).all() 

1837 and (self.pbc == other.pbc).all() 

1838 ) 

1839 

1840 def __ne__(self, other): 

1841 """Check if two atoms objects are not equal. 

1842 

1843 Any differences in positions, atomic numbers, unit cell or 

1844 periodic boundary condtions make atoms objects not equal. 

1845 """ 

1846 eq = self.__eq__(other) 

1847 if eq is NotImplemented: 

1848 return eq 

1849 else: 

1850 return not eq 

1851 

1852 # @deprecated('Please use atoms.cell.volume') 

1853 # We kind of want to deprecate this, but the ValueError behaviour 

1854 # might be desirable. Should we do this? 

1855 def get_volume(self): 

1856 """Get volume of unit cell.""" 

1857 if self.cell.rank != 3: 

1858 raise ValueError( 

1859 'You have {} lattice vectors: volume not defined'.format( 

1860 self.cell.rank 

1861 ) 

1862 ) 

1863 return self.cell.volume 

1864 

1865 @property 

1866 def cell(self): 

1867 """The :class:`ase.cell.Cell` for direct manipulation.""" 

1868 return self._cellobj 

1869 

1870 @cell.setter 

1871 def cell(self, cell): 

1872 cell = Cell.ascell(cell) 

1873 self._cellobj[:] = cell 

1874 

1875 def write(self, filename, format=None, **kwargs): 

1876 """Write atoms object to a file. 

1877 

1878 see ase.io.write for formats. 

1879 kwargs are passed to ase.io.write. 

1880 """ 

1881 from ase.io import write 

1882 

1883 write(filename, self, format, **kwargs) 

1884 

1885 def iterimages(self): 

1886 yield self 

1887 

1888 def __ase_optimizable__(self): 

1889 from ase.optimize.optimize import OptimizableAtoms 

1890 

1891 return OptimizableAtoms(self) 

1892 

1893 def edit(self): 

1894 """Modify atoms interactively through ASE's GUI viewer. 

1895 

1896 Conflicts leading to undesirable behaviour might arise 

1897 when matplotlib has been pre-imported with certain 

1898 incompatible backends and while trying to use the 

1899 plot feature inside the interactive GUI. To circumvent, 

1900 please set matplotlib.use('gtk') before calling this 

1901 method. 

1902 """ 

1903 from ase.gui.gui import GUI 

1904 from ase.gui.images import Images 

1905 

1906 images = Images([self]) 

1907 gui = GUI(images) 

1908 gui.run() 

1909 

1910 

1911class Atoms(_LimitedAtoms): 

1912 """Atoms object. 

1913 

1914 The Atoms object can represent an isolated molecule, or a 

1915 periodically repeated structure. It has a unit cell and 

1916 there may be periodic boundary conditions along any of the three 

1917 unit cell axes. 

1918 Information about the atoms (atomic numbers and position) is 

1919 stored in ndarrays. Optionally, there can be information about 

1920 tags, momenta, masses, magnetic moments and charges. 

1921 

1922 In order to calculate energies, forces and stresses, a calculator 

1923 object has to attached to the atoms object. 

1924 

1925 Parameters 

1926 ---------- 

1927 symbols : str | list[str] | list[Atom] 

1928 Chemical formula, a list of chemical symbols, or list of 

1929 :class:`~ase.Atom` objects (mutually exclusive with ``numbers``). 

1930 

1931 - ``'H2O'`` 

1932 - ``'COPt12'`` 

1933 - ``['H', 'H', 'O']`` 

1934 - ``[Atom('Ne', (x, y, z)), ...]`` 

1935 

1936 positions : list[tuple[float, float, float]] 

1937 Atomic positions in Cartesian coordinates 

1938 (mutually exclusive with ``scaled_positions``). 

1939 Anything that can be converted to an ndarray of shape (n, 3) works: 

1940 [(x0, y0, z0), (x1, y1, z1), ...]. 

1941 scaled_positions : list[tuple[float, float, float]] 

1942 Atomic positions in units of the unit cell 

1943 (mutually exclusive with ``positions``). 

1944 numbers : list[int] 

1945 Atomic numbers (mutually exclusive with ``symbols``). 

1946 tags : list[int] 

1947 Special purpose tags. 

1948 momenta : list[tuple[float, float, float]] 

1949 Momenta for all atoms in Cartesian coordinates 

1950 (mutually exclusive with ``velocities``). 

1951 velocities : list[tuple[float, float, float]] 

1952 Velocities for all atoms in Cartesian coordinates 

1953 (mutually exclusive with ``momenta``). 

1954 masses : list[float] 

1955 Atomic masses in atomic units. 

1956 magmoms : list[float] | list[tuple[float, float, float]] 

1957 Magnetic moments. Can be either a single value for each atom 

1958 for collinear calculations or three numbers for each atom for 

1959 non-collinear calculations. 

1960 charges : list[float] 

1961 Initial atomic charges. 

1962 cell : 3x3 matrix or length 3 or 6 vector, default: (0, 0, 0) 

1963 Unit cell vectors. Can also be given as just three 

1964 numbers for orthorhombic cells, or 6 numbers, where 

1965 first three are lengths of unit cell vectors, and the 

1966 other three are angles between them (in degrees), in following order: 

1967 [len(a), len(b), len(c), angle(b,c), angle(a,c), angle(a,b)]. 

1968 First vector will lie in x-direction, second in xy-plane, 

1969 and the third one in z-positive subspace. 

1970 celldisp : tuple[float, float, float], default: (0, 0, 0) 

1971 Unit cell displacement vector. To visualize a displaced cell 

1972 around the center of mass of a Systems of atoms. 

1973 pbc : bool | tuple[bool, bool, bool], default: False 

1974 Periodic boundary conditions flags. 

1975 

1976 - ``True`` 

1977 - ``False`` 

1978 - ``0`` 

1979 - ``1`` 

1980 - ``(1, 1, 0)`` 

1981 - ``(True, False, False)`` 

1982 

1983 constraint : constraint object(s) 

1984 One or more ASE constraints applied during structure optimization. 

1985 calculator : :class:`~ase.calculators.calculator.BaseCalculator` 

1986 ASE calculator to obtain energies and atomic forces. 

1987 info : dict | None, default: None 

1988 Dictionary with additional information about the system. 

1989 The following keys may be used by ASE: 

1990 

1991 - spacegroup: :class:`~ase.spacegroup.Spacegroup` instance 

1992 - unit_cell: 'conventional' | 'primitive' | int | 3 ints 

1993 - adsorbate_info: Information about special adsorption sites 

1994 

1995 Items in the info attribute survives copy and slicing and can 

1996 be stored in and retrieved from trajectory files given that the 

1997 key is a string, the value is JSON-compatible and, if the value is a 

1998 user-defined object, its base class is importable. One should 

1999 not make any assumptions about the existence of keys. 

2000 

2001 Examples 

2002 -------- 

2003 >>> from ase import Atom 

2004 

2005 N2 molecule (These three are equivalent): 

2006 

2007 >>> d = 1.104 # N2 bondlength 

2008 >>> a = Atoms('N2', [(0, 0, 0), (0, 0, d)]) 

2009 >>> a = Atoms(numbers=[7, 7], positions=[(0, 0, 0), (0, 0, d)]) 

2010 >>> a = Atoms([Atom('N', (0, 0, 0)), Atom('N', (0, 0, d))]) 

2011 

2012 FCC gold: 

2013 

2014 >>> a = 4.05 # Gold lattice constant 

2015 >>> b = a / 2 

2016 >>> fcc = Atoms('Au', 

2017 ... cell=[(0, b, b), (b, 0, b), (b, b, 0)], 

2018 ... pbc=True) 

2019 

2020 Hydrogen wire: 

2021 

2022 >>> d = 0.9 # H-H distance 

2023 >>> h = Atoms('H', positions=[(0, 0, 0)], 

2024 ... cell=(d, 0, 0), 

2025 ... pbc=(1, 0, 0)) 

2026 """ 

2027 

2028 def __init__(self, symbols=None, *args, calculator=None, **kwargs) -> None: 

2029 super().__init__(symbols, *args, **kwargs) 

2030 if hasattr(symbols, 'get_positions'): 

2031 atoms = symbols 

2032 if atoms is not None: 

2033 if calculator is None: 

2034 calculator = atoms.calc 

2035 self.calc = calculator 

2036 

2037 @deprecated('Please use atoms.calc = calc', FutureWarning) 

2038 def set_calculator(self, calc=None): 

2039 """Attach calculator object. 

2040 

2041 .. deprecated:: 3.20.0 

2042 Please use the equivalent ``atoms.calc = calc`` instead of this 

2043 method. 

2044 """ 

2045 

2046 self.calc = calc 

2047 

2048 @deprecated('Please use atoms.calc', FutureWarning) 

2049 def get_calculator(self): 

2050 """Get currently attached calculator object. 

2051 

2052 .. deprecated:: 3.20.0 

2053 Please use the equivalent ``atoms.calc`` instead of 

2054 ``atoms.get_calculator()``. 

2055 """ 

2056 

2057 return self.calc 

2058 

2059 @property 

2060 def calc(self): 

2061 """Calculator object.""" 

2062 return self._calc 

2063 

2064 @calc.setter 

2065 def calc(self, calc): 

2066 self._calc = calc 

2067 if hasattr(calc, 'set_atoms'): 

2068 calc.set_atoms(self) 

2069 

2070 @calc.deleter 

2071 @deprecated('Please use atoms.calc = None', FutureWarning) 

2072 def calc(self): 

2073 """Delete calculator 

2074 

2075 .. deprecated:: 3.20.0 

2076 Please use ``atoms.calc = None`` 

2077 """ 

2078 self._calc = None 

2079 

2080 def get_magnetic_moments(self): 

2081 """Get calculated local magnetic moments.""" 

2082 if self._calc is None: 

2083 raise RuntimeError('Atoms object has no calculator.') 

2084 return self._calc.get_magnetic_moments(self) 

2085 

2086 def get_magnetic_moment(self): 

2087 """Get calculated total magnetic moment.""" 

2088 if self._calc is None: 

2089 raise RuntimeError('Atoms object has no calculator.') 

2090 return self._calc.get_magnetic_moment(self) 

2091 

2092 def get_charges(self): 

2093 """Get calculated charges.""" 

2094 if self._calc is None: 

2095 raise RuntimeError('Atoms object has no calculator.') 

2096 try: 

2097 return self._calc.get_charges(self) 

2098 except AttributeError: 

2099 from ase.calculators.calculator import PropertyNotImplementedError 

2100 

2101 raise PropertyNotImplementedError 

2102 

2103 def get_potential_energy( 

2104 self, force_consistent=False, apply_constraint=True 

2105 ): 

2106 """Calculate potential energy. 

2107 

2108 Ask the attached calculator to calculate the potential energy and 

2109 apply constraints. Use *apply_constraint=False* to get the raw 

2110 forces. 

2111 

2112 When supported by the calculator, either the energy extrapolated 

2113 to zero Kelvin or the energy consistent with the forces (the free 

2114 energy) can be returned. 

2115 """ 

2116 if self._calc is None: 

2117 raise RuntimeError('Atoms object has no calculator.') 

2118 if force_consistent: 

2119 energy = self._calc.get_potential_energy( 

2120 self, force_consistent=force_consistent 

2121 ) 

2122 else: 

2123 energy = self._calc.get_potential_energy(self) 

2124 if apply_constraint: 

2125 for constraint in self.constraints: 

2126 if hasattr(constraint, 'adjust_potential_energy'): 

2127 energy += constraint.adjust_potential_energy(self) 

2128 return energy 

2129 

2130 def get_properties(self, properties): 

2131 """This method is experimental; currently for internal use.""" 

2132 # XXX Something about constraints. 

2133 if self._calc is None: 

2134 raise RuntimeError('Atoms object has no calculator.') 

2135 return self._calc.calculate_properties(self, properties) 

2136 

2137 def get_potential_energies(self): 

2138 """Calculate the potential energies of all the atoms. 

2139 

2140 Only available with calculators supporting per-atom energies 

2141 (e.g. classical potentials). 

2142 """ 

2143 if self._calc is None: 

2144 raise RuntimeError('Atoms object has no calculator.') 

2145 return self._calc.get_potential_energies(self) 

2146 

2147 def get_total_energy(self): 

2148 """Get the total energy - potential plus kinetic energy.""" 

2149 return self.get_potential_energy() + self.get_kinetic_energy() 

2150 

2151 def get_forces(self, apply_constraint=True, md=False): 

2152 """Calculate atomic forces. 

2153 

2154 Ask the attached calculator to calculate the forces and apply 

2155 constraints. Use *apply_constraint=False* to get the raw 

2156 forces. 

2157 

2158 For molecular dynamics (md=True) we don't apply the constraint 

2159 to the forces but to the momenta. When holonomic constraints for 

2160 rigid linear triatomic molecules are present, ask the constraints 

2161 to redistribute the forces within each triple defined in the 

2162 constraints (required for molecular dynamics with this type of 

2163 constraints).""" 

2164 

2165 if self._calc is None: 

2166 raise RuntimeError('Atoms object has no calculator.') 

2167 forces = self._calc.get_forces(self) 

2168 

2169 if apply_constraint: 

2170 # We need a special md flag here because for MD we want 

2171 # to skip real constraints but include special "constraints" 

2172 # Like Hookean. 

2173 for constraint in self.constraints: 

2174 if md and hasattr(constraint, 'redistribute_forces_md'): 

2175 constraint.redistribute_forces_md(self, forces) 

2176 # Always adjust forces if no MD. In the case of MD, 

2177 # forces only need adjustment if a term is added to the 

2178 # potential energy by the constraint. 

2179 if not md or hasattr(constraint, 'adjust_potential_energy'): 

2180 constraint.adjust_forces(self, forces) 

2181 return forces 

2182 

2183 # Informs calculators (e.g. Asap) that ideal gas contribution is added here. 

2184 _ase_handles_dynamic_stress = True 

2185 

2186 def get_stress( 

2187 self, voigt=True, apply_constraint=True, include_ideal_gas=False 

2188 ): 

2189 """Calculate stress tensor. 

2190 

2191 Returns an array of the six independent components of the 

2192 symmetric stress tensor, in the traditional Voigt order 

2193 (xx, yy, zz, yz, xz, xy) or as a 3x3 matrix. Default is Voigt 

2194 order. 

2195 

2196 The ideal gas contribution to the stresses is added if the 

2197 atoms have momenta and ``include_ideal_gas`` is set to True. 

2198 """ 

2199 

2200 if self._calc is None: 

2201 raise RuntimeError('Atoms object has no calculator.') 

2202 

2203 stress = self._calc.get_stress(self) 

2204 shape = stress.shape 

2205 

2206 if shape == (3, 3): 

2207 # Convert to the Voigt form before possibly applying 

2208 # constraints and adding the dynamic part of the stress 

2209 # (the "ideal gas contribution"). 

2210 stress = full_3x3_to_voigt_6_stress(stress) 

2211 else: 

2212 assert shape == (6,) 

2213 

2214 if apply_constraint: 

2215 for constraint in self.constraints: 

2216 if hasattr(constraint, 'adjust_stress'): 

2217 constraint.adjust_stress(self, stress) 

2218 

2219 # Add ideal gas contribution, if applicable 

2220 if include_ideal_gas and self.has('momenta'): 

2221 stress += self.get_kinetic_stress() 

2222 

2223 if voigt: 

2224 return stress 

2225 else: 

2226 return voigt_6_to_full_3x3_stress(stress) 

2227 

2228 def get_stresses(self, include_ideal_gas=False, voigt=True): 

2229 """Calculate the stress-tensor of all the atoms. 

2230 

2231 Only available with calculators supporting per-atom energies and 

2232 stresses (e.g. classical potentials). Even for such calculators 

2233 there is a certain arbitrariness in defining per-atom stresses. 

2234 

2235 The ideal gas contribution to the stresses is added if the 

2236 atoms have momenta and ``include_ideal_gas`` is set to True. 

2237 """ 

2238 if self._calc is None: 

2239 raise RuntimeError('Atoms object has no calculator.') 

2240 stresses = self._calc.get_stresses(self) 

2241 

2242 # make sure `stresses` are in voigt form 

2243 if np.shape(stresses)[1:] == (3, 3): 

2244 stresses_voigt = [full_3x3_to_voigt_6_stress(s) for s in stresses] 

2245 stresses = np.array(stresses_voigt) 

2246 

2247 # REMARK: The ideal gas contribution is intensive, i.e., the volume 

2248 # is divided out. We currently don't check if `stresses` are intensive 

2249 # as well, i.e., if `a.get_stresses.sum(axis=0) == a.get_stress()`. 

2250 # It might be good to check this here, but adds computational overhead. 

2251 

2252 if include_ideal_gas and self.has('momenta'): 

2253 stresses += self.get_kinetic_stresses() 

2254 

2255 if voigt: 

2256 return stresses 

2257 else: 

2258 stresses_3x3 = [voigt_6_to_full_3x3_stress(s) for s in stresses] 

2259 return np.array(stresses_3x3) 

2260 

2261 def get_kinetic_stresses(self, voigt=True): 

2262 """Calculate the kinetic part of the Virial stress of all the atoms.""" 

2263 stresses = np.zeros((len(self), 6)) # Voigt notation 

2264 stresscomp = np.array([[0, 5, 4], [5, 1, 3], [4, 3, 2]]) 

2265 if hasattr(self._calc, 'get_atomic_volumes'): 

2266 invvol = 1.0 / self._calc.get_atomic_volumes() 

2267 else: 

2268 invvol = self.get_global_number_of_atoms() / self.get_volume() 

2269 p = self.get_momenta() 

2270 invmass = 1.0 / self.get_masses() 

2271 for alpha in range(3): 

2272 for beta in range(alpha, 3): 

2273 stresses[:, stresscomp[alpha, beta]] -= ( 

2274 p[:, alpha] * p[:, beta] * invmass * invvol 

2275 ) 

2276 

2277 if voigt: 

2278 return stresses 

2279 else: 

2280 stresses_3x3 = [voigt_6_to_full_3x3_stress(s) for s in stresses] 

2281 return np.array(stresses_3x3) 

2282 

2283 def get_dipole_moment(self): 

2284 """Calculate the electric dipole moment for the atoms object. 

2285 

2286 Only available for calculators which has a get_dipole_moment() 

2287 method.""" 

2288 

2289 if self._calc is None: 

2290 raise RuntimeError('Atoms object has no calculator.') 

2291 return self._calc.get_dipole_moment(self) 

2292 

2293 def _get_tokens_for_repr(self) -> list[str]: 

2294 tokens = super()._get_tokens_for_repr() 

2295 if self._calc is not None: 

2296 tokens.append(f'calculator={self._calc.__class__.__name__}(...)') 

2297 return tokens 

2298 

2299 

2300def string2vector(v): 

2301 if isinstance(v, str): 

2302 if v[0] == '-': 

2303 return -string2vector(v[1:]) 

2304 w = np.zeros(3) 

2305 w['xyz'.index(v)] = 1.0 

2306 return w 

2307 return np.array(v, float) 

2308 

2309 

2310def default(data, dflt): 

2311 """Helper function for setting default values.""" 

2312 if data is None: 

2313 return None 

2314 elif isinstance(data, (list, tuple)): 

2315 newdata = [] 

2316 allnone = True 

2317 for x in data: 

2318 if x is None: 

2319 newdata.append(dflt) 

2320 else: 

2321 newdata.append(x) 

2322 allnone = False 

2323 if allnone: 

2324 return None 

2325 return newdata 

2326 else: 

2327 return data