Coverage for ase/vibrations/vibrations.py: 89.62%

289 statements  

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

1"""A class for computing vibrational modes""" 

2 

3import sys 

4from collections import namedtuple 

5from collections.abc import Iterator 

6from math import log, pi, sqrt 

7from pathlib import Path 

8 

9import numpy as np 

10 

11import ase.io 

12import ase.units as units 

13from ase.atoms import Atoms 

14from ase.constraints import FixAtoms 

15from ase.parallel import paropen, world 

16from ase.utils.filecache import get_json_cache 

17from ase.vibrations.data import VibrationsData 

18 

19 

20class AtomicDisplacements: 

21 def _disp(self, a, i, step): 

22 if isinstance(i, str): # XXX Simplify by removing this. 

23 i = 'xyz'.index(i) 

24 return Displacement(a, i, np.sign(step), abs(step), self) 

25 

26 def _eq_disp(self): 

27 return self._disp(0, 0, 0) 

28 

29 @property 

30 def ndof(self): 

31 return 3 * len(self.indices) 

32 

33 

34class Displacement( 

35 namedtuple('Displacement', ['a', 'i', 'sign', 'ndisp', 'vib']) 

36): 

37 @property 

38 def name(self): 

39 if self.sign == 0: 

40 return 'eq' 

41 

42 axisname = 'xyz'[self.i] 

43 dispname = self.ndisp * ' +-'[self.sign] 

44 return f'{self.a}{axisname}{dispname}' 

45 

46 @property 

47 def _cached(self): 

48 return self.vib.cache[self.name] 

49 

50 def forces(self): 

51 return self._cached['forces'].copy() 

52 

53 @property 

54 def step(self): 

55 return self.ndisp * self.sign * self.vib.delta 

56 

57 # XXX dipole only valid for infrared 

58 def dipole(self): 

59 return self._cached['dipole'].copy() 

60 

61 # XXX below stuff only valid for TDDFT excitation stuff 

62 def save_ov_nn(self, ov_nn): 

63 np.save(Path(self.vib.exname) / (self.name + '.ov'), ov_nn) 

64 

65 def load_ov_nn(self): 

66 return np.load(Path(self.vib.exname) / (self.name + '.ov.npy')) 

67 

68 @property 

69 def _exname(self): 

70 return Path(self.vib.exname) / f'ex.{self.name}{self.vib.exext}' 

71 

72 def calculate_and_save_static_polarizability(self, atoms): 

73 exobj = self.vib._new_exobj() 

74 excitation_data = exobj(atoms) 

75 np.savetxt(self._exname, excitation_data) 

76 

77 def load_static_polarizability(self): 

78 return np.loadtxt(self._exname) 

79 

80 def read_exobj(self): 

81 # XXX each exobj should allow for self._exname as Path 

82 return self.vib.read_exobj(str(self._exname)) 

83 

84 def calculate_and_save_exlist(self, atoms): 

85 # exo = self.vib._new_exobj() 

86 excalc = self.vib._new_exobj() 

87 exlist = excalc.calculate(atoms) 

88 # XXX each exobj should allow for self._exname as Path 

89 exlist.write(str(self._exname)) 

90 

91 

92class Vibrations(AtomicDisplacements): 

93 """Class for calculating vibrational modes using finite difference. 

94 

95 The vibrational modes are calculated from a finite difference 

96 approximation of the Hessian matrix. 

97 

98 The *summary()*, *get_energies()* and *get_frequencies()* methods all take 

99 an optional *method* keyword. Use method='Frederiksen' to use the method 

100 described in: 

101 

102 T. Frederiksen, M. Paulsson, M. Brandbyge, A. P. Jauho: 

103 "Inelastic transport theory from first-principles: methodology and 

104 applications for nanoscale devices", Phys. Rev. B 75, 205413 (2007) 

105 

106 Parameters 

107 ---------- 

108 atoms: :class:`~ase.Atoms` 

109 The atoms to work on. 

110 indices: list[int] | :obj:`None`, default: None 

111 List of indices of atoms to vibrate. Default behavior is 

112 to vibrate all atoms. 

113 name: str 

114 Name to use for files. 

115 delta: float 

116 Magnitude of displacements. 

117 nfree: int 

118 Number of displacements per atom and cartesian coordinate, 2 and 4 are 

119 supported. Default is 2 which will displace each atom +delta and 

120 -delta for each cartesian coordinate. 

121 

122 Examples 

123 -------- 

124 >>> from ase import Atoms 

125 >>> from ase.calculators.emt import EMT 

126 >>> from ase.optimize import BFGS 

127 >>> from ase.vibrations import Vibrations 

128 >>> n2 = Atoms('N2', [(0, 0, 0), (0, 0, 1.1)], 

129 ... calculator=EMT()) 

130 >>> BFGS(n2).run(fmax=0.01) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE 

131 Step Time Energy fmax 

132 BFGS: 0 ... 0.440344 3.251800 

133 BFGS: 1 ... 0.264361 0.347497 

134 BFGS: 2 ... 0.262860 0.080535 

135 BFGS: 3 ... 0.262777 0.001453 

136 ... 

137 >>> vib = Vibrations(n2) 

138 >>> vib.run() 

139 >>> print(vib.description()) # doctest:+ELLIPSIS, +NORMALIZE_WHITESPACE 

140 --------------------- 

141 # meV cm^-1 

142 --------------------- 

143 0 0.0 0.0 

144 1 0.0 0.0 

145 2 0.0 0.0 

146 3 1.4 11.5 

147 4 1.4 11.5 

148 5 152.7 1231.3 

149 --------------------- 

150 Zero-point energy: 0.078 eV 

151 >>> vib.write_mode(-1) # write last mode to trajectory file 

152 

153 """ 

154 

155 def __init__( 

156 self, 

157 atoms: Atoms, 

158 indices: list[int] | None = None, 

159 name: str = 'vib', 

160 delta: float = 0.01, 

161 nfree: int = 2, 

162 ): 

163 assert nfree in [2, 4] 

164 self.atoms = atoms 

165 self.calc = atoms.calc 

166 if indices is None: 

167 fixed_indices = [] 

168 for constr in atoms.constraints: 

169 if isinstance(constr, FixAtoms): 

170 fixed_indices.extend(constr.get_indices()) 

171 fixed_indices = list(set(fixed_indices)) 

172 indices = [i for i in range(len(atoms)) if i not in fixed_indices] 

173 if len(indices) != len(set(indices)): 

174 raise ValueError('one (or more) indices included more than once') 

175 self.indices = np.asarray(indices) 

176 

177 self.delta = delta 

178 self.nfree = nfree 

179 self.H = None 

180 self.ir = None 

181 self._vibrations = None 

182 

183 self.cache = get_json_cache(name) 

184 

185 @property 

186 def name(self): 

187 return str(self.cache.directory) 

188 

189 def run(self): 

190 """Run the vibration calculations. 

191 

192 This will calculate the forces for 6 displacements per atom +/-x, 

193 +/-y, +/-z. Only those calculations that are not already done will be 

194 started. Be aware that an interrupted calculation may produce an empty 

195 file (ending with .json), which must be deleted before restarting the 

196 job. Otherwise the forces will not be calculated for that 

197 displacement. 

198 

199 Note that the calculations for the different displacements can be done 

200 simultaneously by several independent processes. This feature relies 

201 on the existence of files and the subsequent creation of the file in 

202 case it is not found. 

203 

204 If the program you want to use does not have a calculator in ASE, use 

205 ``iterdisplace`` to get all displaced structures and calculate the 

206 forces on your own. 

207 """ 

208 

209 if not self.cache.writable: 

210 raise RuntimeError( 

211 'Cannot run calculation. ' 

212 'Cache must be removed or split in order ' 

213 'to have only one sort of data structure at a time.' 

214 ) 

215 

216 self._check_old_pickles() 

217 

218 for disp, atoms in self.iterdisplace(inplace=True): 

219 with self.cache.lock(disp.name) as handle: 

220 if handle is None: 

221 continue 

222 

223 result = self.calculate(atoms, disp) 

224 

225 if world.rank == 0: 

226 handle.save(result) 

227 

228 def _check_old_pickles(self): 

229 eq_pickle_path = Path(f'{self.name}.eq.pckl') 

230 pickle2json_instructions = f"""\ 

231Found old pickle files such as {eq_pickle_path}. \ 

232Please remove them and recalculate or run \ 

233"python -m ase.vibrations.pickle2json --help".""" 

234 if len(self.cache) == 0 and eq_pickle_path.exists(): 

235 raise RuntimeError(pickle2json_instructions) 

236 

237 def iterdisplace( 

238 self, 

239 inplace: bool = False, 

240 ) -> Iterator[tuple[Displacement, Atoms]]: 

241 """Iterate over initial and displaced structures. 

242 

243 Use this to export the structures for each single-point calculation 

244 to an external program instead of using ``run()``. Then save the 

245 calculated gradients to <name>.json and continue using this instance. 

246 

247 Parameters 

248 ---------- 

249 inplace: bool, default: :obj:`False` 

250 If True, the atoms object will be modified in-place. Otherwise a 

251 copy will be made. 

252 

253 Yields 

254 ------ 

255 disp: :class:`Displacement` 

256 Displacement object with information about the displacement. 

257 atoms: :class:`~ase.Atoms` 

258 Atoms object with the displaced structure. 

259 

260 """ 

261 # XXX change of type of disp 

262 atoms = self.atoms if inplace else self.atoms.copy() 

263 displacements = self.displacements() 

264 eq_disp = next(displacements) 

265 assert eq_disp.name == 'eq' 

266 yield eq_disp, atoms 

267 

268 for disp in displacements: 

269 if not inplace: 

270 atoms = self.atoms.copy() 

271 pos0 = atoms.positions[disp.a, disp.i] 

272 atoms.positions[disp.a, disp.i] += disp.step 

273 yield disp, atoms 

274 

275 if inplace: 

276 atoms.positions[disp.a, disp.i] = pos0 

277 

278 def iterimages(self): 

279 """Yield initial and displaced structures.""" 

280 for name, atoms in self.iterdisplace(): 

281 yield atoms 

282 

283 def _iter_ai(self): 

284 for a in self.indices: 

285 for i in range(3): 

286 yield a, i 

287 

288 def displacements(self): 

289 yield self._eq_disp() 

290 

291 for a, i in self._iter_ai(): 

292 for sign in [-1, 1]: 

293 for ndisp in range(1, self.nfree // 2 + 1): 

294 yield self._disp(a, i, sign * ndisp) 

295 

296 def calculate(self, atoms, disp): 

297 results = {} 

298 results['forces'] = self.calc.get_forces(atoms) 

299 

300 if self.ir: 

301 results['dipole'] = self.calc.get_dipole_moment(atoms) 

302 

303 return results 

304 

305 def clean(self, empty_files=False, combined=True): 

306 """Remove json-files. 

307 

308 Use empty_files=True to remove only empty files and 

309 combined=False to not remove the combined file. 

310 

311 """ 

312 

313 if world.rank != 0: 

314 return 0 

315 

316 if empty_files: 

317 return self.cache.strip_empties() # XXX Fails on combined cache 

318 

319 nfiles = self.cache.filecount() 

320 self.cache.clear() 

321 return nfiles 

322 

323 def combine(self): 

324 """Combine json-files to one file ending with '.all.json'. 

325 

326 The other json-files will be removed in order to have only one sort 

327 of data structure at a time. 

328 

329 """ 

330 nelements_before = self.cache.filecount() 

331 self.cache = self.cache.combine() 

332 return nelements_before 

333 

334 def split(self): 

335 """Split combined json-file. 

336 

337 The combined json-file will be removed in order to have only one 

338 sort of data structure at a time. 

339 

340 """ 

341 count = self.cache.filecount() 

342 self.cache = self.cache.split() 

343 return count 

344 

345 def read(self, method='standard', direction='central'): 

346 self.method = method.lower() 

347 self.direction = direction.lower() 

348 assert self.method in ['standard', 'frederiksen'] 

349 assert self.direction in ['central', 'forward', 'backward'] 

350 

351 n = 3 * len(self.indices) 

352 H = np.empty((n, n)) 

353 r = 0 

354 

355 eq_disp = self._eq_disp() 

356 

357 if direction != 'central': 

358 feq = eq_disp.forces() 

359 

360 for a, i in self._iter_ai(): 

361 disp_minus = self._disp(a, i, -1) 

362 disp_plus = self._disp(a, i, 1) 

363 

364 fminus = disp_minus.forces() 

365 fplus = disp_plus.forces() 

366 if self.method == 'frederiksen': 

367 fminus[a] -= fminus.sum(0) 

368 fplus[a] -= fplus.sum(0) 

369 if self.nfree == 4: 

370 fminusminus = self._disp(a, i, -2).forces() 

371 fplusplus = self._disp(a, i, 2).forces() 

372 if self.method == 'frederiksen': 

373 fminusminus[a] -= fminusminus.sum(0) 

374 fplusplus[a] -= fplusplus.sum(0) 

375 if self.direction == 'central': 

376 if self.nfree == 2: 

377 H[r] = 0.5 * (fminus - fplus)[self.indices].ravel() 

378 else: 

379 assert self.nfree == 4 

380 H[r] = H[r] = ( 

381 -fminusminus + 8 * fminus - 8 * fplus + fplusplus 

382 )[self.indices].ravel() / 12.0 

383 elif self.direction == 'forward': 

384 H[r] = (feq - fplus)[self.indices].ravel() 

385 else: 

386 assert self.direction == 'backward' 

387 H[r] = (fminus - feq)[self.indices].ravel() 

388 H[r] /= 2 * self.delta 

389 r += 1 

390 H += H.copy().T 

391 self.H = H 

392 masses = self.atoms.get_masses() 

393 if any(masses[self.indices] == 0): 

394 raise RuntimeError( 

395 'Zero mass encountered in one or more of ' 

396 'the vibrated atoms. Use Atoms.set_masses()' 

397 ' to set all masses to non-zero values.' 

398 ) 

399 

400 self.im = np.repeat(masses[self.indices] ** -0.5, 3) 

401 self._vibrations = self.get_vibrations( 

402 read_cache=False, method=self.method, direction=self.direction 

403 ) 

404 

405 omega2, modes = np.linalg.eigh(self.im[:, None] * H * self.im) 

406 self.modes = modes.T.copy() 

407 

408 # Conversion factor: 

409 s = units._hbar * 1e10 / sqrt(units._e * units._amu) 

410 self.hnu = s * omega2.astype(complex) ** 0.5 

411 

412 def get_vibrations( 

413 self, 

414 method='standard', 

415 direction='central', 

416 read_cache=True, 

417 **kw, 

418 ): 

419 """Get vibrations as VibrationsData object 

420 

421 If read() has not yet been called, this will be called to assemble data 

422 from the outputs of run(). Most of the arguments to this function are 

423 options to be passed to read() in this case. 

424 

425 Parameters 

426 ---------- 

427 method : str 

428 Calculation method passed to read() 

429 direction : str 

430 Finite-difference scheme passed to read() 

431 read_cache : bool 

432 The :class:`VibrationsData` object will be cached for quick access. 

433 Set :obj:`False` to force regeneration of the cache with the 

434 current atoms/Hessian/indices data. 

435 **kw : dict 

436 Any remaining keyword arguments are passed to read() 

437 

438 Returns 

439 ------- 

440 :class:`VibrationsData` 

441 

442 """ 

443 if read_cache and (self._vibrations is not None): 

444 return self._vibrations 

445 

446 else: 

447 if ( 

448 self.H is None 

449 or method.lower() != self.method 

450 or direction.lower() != self.direction 

451 ): 

452 self.read(method, direction, **kw) 

453 

454 return VibrationsData.from_2d( 

455 self.atoms, 

456 self.H, 

457 indices=self.indices, 

458 ) 

459 

460 def get_energies( 

461 self, 

462 method: str = 'standard', 

463 direction: str = 'central', 

464 **kw, 

465 ): 

466 """Get vibration energies in eV.""" 

467 return self.get_vibrations( 

468 method=method, direction=direction, **kw 

469 ).get_energies() 

470 

471 def get_frequencies( 

472 self, 

473 method: str = 'standard', 

474 direction: str = 'central', 

475 ): 

476 """Get vibration frequencies in cm^-1.""" 

477 return self.get_vibrations( 

478 method=method, direction=direction 

479 ).get_frequencies() 

480 

481 def description( 

482 self, method: str = 'standard', direction: str = 'central', freq=None 

483 ) -> str: 

484 if freq is not None: 

485 energies = freq * units.invcm 

486 else: 

487 energies = self.get_energies(method=method, direction=direction) 

488 

489 summary_lines = VibrationsData._tabulate_from_energies(energies) 

490 return '\n'.join(summary_lines) + '\n' 

491 

492 def summary( 

493 self, 

494 method: str = 'standard', 

495 direction: str = 'central', 

496 freq=None, 

497 log=sys.stdout, 

498 ): 

499 log_text = self.description(method, direction, freq) 

500 

501 if isinstance(log, str): 

502 with paropen(log, 'a') as log_file: 

503 log_file.write(log_text) 

504 else: 

505 log.write(log_text) 

506 

507 def get_zero_point_energy(self, freq=None): 

508 if freq: 

509 raise NotImplementedError 

510 return self.get_vibrations().get_zero_point_energy() 

511 

512 def get_mode(self, n): 

513 """Get mode number .""" 

514 return self.get_vibrations().get_modes(all_atoms=True)[n] 

515 

516 def write_mode( 

517 self, 

518 n: int | None = None, 

519 kT: float = units.kB * 300.0, 

520 nimages: int = 30, 

521 ) -> None: 

522 """Write mode number n to trajectory file. 

523 

524 If n is not specified, writes all non-zero modes. 

525 """ 

526 if n is None: 

527 for index, energy in enumerate(self.get_energies()): 

528 if abs(energy) > 1e-5: 

529 self.write_mode(n=index, kT=kT, nimages=nimages) 

530 return 

531 

532 else: 

533 n %= len(self.get_energies()) 

534 

535 with ase.io.Trajectory('%s.%d.traj' % (self.name, n), 'w') as traj: 

536 for image in self.get_vibrations().iter_animated_mode( 

537 n, temperature=kT, frames=nimages 

538 ): 

539 traj.write(image) 

540 

541 def show_as_force(self, n: int, scale: float = 0.2, show: bool = True): 

542 return self.get_vibrations().show_as_force(n, scale=scale, show=show) 

543 

544 def write_jmol(self): 

545 """Writes file for viewing of the modes with jmol.""" 

546 

547 with open(self.name + '.xyz', 'w') as fd: 

548 self._write_jmol(fd) 

549 

550 def _write_jmol(self, fd): 

551 symbols = self.atoms.get_chemical_symbols() 

552 freq = self.get_frequencies() 

553 for n in range(3 * len(self.indices)): 

554 fd.write('%6d\n' % len(self.atoms)) 

555 

556 if freq[n].imag != 0: 

557 c = 'i' 

558 freq[n] = freq[n].imag 

559 

560 else: 

561 freq[n] = freq[n].real 

562 c = ' ' 

563 

564 fd.write('Mode #%d, f = %.1f%s cm^-1' % (n, float(freq[n].real), c)) 

565 

566 if self.ir: 

567 fd.write(', I = %.4f (D/Å)^2 amu^-1.\n' % self.intensities[n]) 

568 else: 

569 fd.write('.\n') 

570 

571 mode = self.get_mode(n) 

572 for i, pos in enumerate(self.atoms.positions): 

573 fd.write( 

574 '%2s %12.5f %12.5f %12.5f %12.5f %12.5f %12.5f\n' 

575 % ( 

576 symbols[i], 

577 pos[0], 

578 pos[1], 

579 pos[2], 

580 mode[i, 0], 

581 mode[i, 1], 

582 mode[i, 2], 

583 ) 

584 ) 

585 

586 def fold( 

587 self, 

588 frequencies, 

589 intensities, 

590 start: float = 800.0, 

591 end: float = 4000.0, 

592 npts: int | None = None, 

593 width: float = 4.0, 

594 type: str = 'Gaussian', 

595 normalize: bool = False, 

596 ): 

597 """Fold frequencies and intensities within the given range 

598 and folding method (Gaussian/Lorentzian). 

599 The energy unit is cm^-1. 

600 

601 Parameters 

602 --------- 

603 normalize : bool, default: False 

604 If :obj:`True`, the integral over the peaks gives the intensity. 

605 

606 """ 

607 

608 lctype = type.lower() 

609 assert lctype in ['gaussian', 'lorentzian'] 

610 if not npts: 

611 npts = int((end - start) / width * 10 + 1) 

612 prefactor = 1.0 

613 if lctype == 'lorentzian': 

614 intensities = intensities * width * pi / 2.0 

615 if normalize: 

616 prefactor = 2.0 / width / pi 

617 else: 

618 sigma = width / 2.0 / sqrt(2.0 * log(2.0)) 

619 if normalize: 

620 prefactor = 1.0 / sigma / sqrt(2 * pi) 

621 

622 # Make array with spectrum data 

623 spectrum = np.empty(npts) 

624 energies = np.linspace(start, end, npts) 

625 for i, energy in enumerate(energies): 

626 energies[i] = energy 

627 if lctype == 'lorentzian': 

628 spectrum[i] = ( 

629 intensities 

630 * 0.5 

631 * width 

632 / pi 

633 / ((frequencies - energy) ** 2 + 0.25 * width**2) 

634 ).sum() 

635 else: 

636 spectrum[i] = ( 

637 intensities 

638 * np.exp(-((frequencies - energy) ** 2) / 2.0 / sigma**2) 

639 ).sum() 

640 return [energies, prefactor * spectrum] 

641 

642 def write_dos( 

643 self, 

644 out: str = 'vib-dos.dat', 

645 start: float = 800.0, 

646 end: float = 4000.0, 

647 npts: int | None = None, 

648 width: float = 10.0, 

649 type: str = 'Gaussian', 

650 method: str = 'standard', 

651 direction: str = 'central', 

652 ) -> None: 

653 """Write out the vibrational density of states to file. 

654 

655 First column is the wavenumber in cm^-1, the second column the 

656 folded vibrational density of states. 

657 

658 Parameters 

659 ---------- 

660 start : float 

661 Start points in cm^-1. 

662 end : float 

663 End points in cm^-1. 

664 width : float 

665 Width of the Gaussian/Lorentzian in cm^-1. 

666 

667 """ 

668 frequencies = self.get_frequencies(method, direction).real 

669 intensities = np.ones(len(frequencies)) 

670 energies, spectrum = self.fold( 

671 frequencies, intensities, start, end, npts, width, type 

672 ) 

673 

674 # Write out spectrum in file. 

675 outdata = np.empty([len(energies), 2]) 

676 outdata.T[0] = energies 

677 outdata.T[1] = spectrum 

678 

679 with open(out, 'w') as fd: 

680 fd.write(f'# {type.title()} folded, width={width:g} cm^-1\n') 

681 fd.write('# [cm^-1] arbitrary\n') 

682 for row in outdata: 

683 fd.write('%.3f %15.5e\n' % (row[0], row[1]))