Coverage for ase/vibrations/infrared.py: 50.39%

127 statements  

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

1"""Infrared intensities""" 

2 

3from math import sqrt 

4from sys import stdout 

5 

6import numpy as np 

7 

8import ase.units as units 

9from ase.parallel import paropen, parprint 

10from ase.vibrations.vibrations import Vibrations 

11 

12 

13class Infrared(Vibrations): 

14 """Class for calculating vibrational modes and infrared intensities 

15 using finite difference. 

16 

17 The vibrational modes are calculated from a finite difference 

18 approximation of the Dynamical matrix and the IR intensities from 

19 a finite difference approximation of the gradient of the dipole 

20 moment. The method is described in: 

21 

22 D. Porezag, M. R. Pederson: 

23 "Infrared intensities and Raman-scattering activities within 

24 density-functional theory", 

25 Phys. Rev. B 54, 7830 (1996) 

26 

27 The calculator object (calc) linked to the Atoms object (atoms) must 

28 have the attribute: 

29 

30 >>> calc.get_dipole_moment(atoms) 

31 

32 In addition to the methods included in the ``Vibrations`` class 

33 the ``Infrared`` class introduces two new methods; 

34 *get_spectrum()* and *write_spectra()*. The *summary()*, *get_energies()*, 

35 *get_frequencies()*, *get_spectrum()* and *write_spectra()* 

36 methods all take an optional *method* keyword. Use 

37 method='Frederiksen' to use the method described in: 

38 

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

40 "Inelastic transport theory from first-principles: methodology 

41 and applications for nanoscale devices", 

42 Phys. Rev. B 75, 205413 (2007) 

43 

44 atoms: Atoms object 

45 The atoms to work on. 

46 indices: list of int 

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

48 to vibrate all atoms. 

49 name: str 

50 Name to use for files. 

51 delta: float 

52 Magnitude of displacements. 

53 nfree: int 

54 Number of displacements per degree of freedom, 2 or 4 are 

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

56 and -delta in each cartesian direction. 

57 directions: list of int 

58 Cartesian coordinates to calculate the gradient 

59 of the dipole moment in. 

60 For example directions = 2 only dipole moment in the z-direction will 

61 be considered, whereas for directions = [0, 1] only the dipole 

62 moment in the xy-plane will be considered. Default behavior is to 

63 use the dipole moment in all directions. 

64 

65 Example: 

66 

67 >>> from ase.io import read 

68 >>> from ase.calculators.vasp import Vasp 

69 >>> from ase.vibrations import Infrared 

70 >>> water = read('water.traj') # read pre-relaxed structure of water 

71 >>> calc = Vasp(prec='Accurate', 

72 ... ediff=1E-8, 

73 ... isym=0, 

74 ... idipol=4, # calculate the total dipole moment 

75 ... dipol=water.get_center_of_mass(scaled=True), 

76 ... ldipol=True) 

77 >>> water.calc = calc 

78 >>> ir = Infrared(water) 

79 >>> ir.run() 

80 >>> ir.summary() 

81 ------------------------------------- 

82 Mode Frequency Intensity 

83 # meV cm^-1 (D/Å)^2 amu^-1 

84 ------------------------------------- 

85 0 16.9i 136.2i 1.6108 

86 1 10.5i 84.9i 2.1682 

87 2 5.1i 41.1i 1.7327 

88 3 0.3i 2.2i 0.0080 

89 4 2.4 19.0 0.1186 

90 5 15.3 123.5 1.4956 

91 6 195.5 1576.7 1.6437 

92 7 458.9 3701.3 0.0284 

93 8 473.0 3814.6 1.1812 

94 ------------------------------------- 

95 Zero-point energy: 0.573 eV 

96 Static dipole moment: 1.833 D 

97 Maximum force on atom in `equilibrium`: 0.0026 eV/Å 

98 

99 

100 

101 This interface now also works for calculator 'siesta', 

102 (added get_dipole_moment for siesta). 

103 

104 Example: 

105 

106 >>> #!/usr/bin/env python3 

107 

108 >>> from ase.io import read 

109 >>> from ase.calculators.siesta import Siesta 

110 >>> from ase.vibrations import Infrared 

111 

112 >>> bud = read('bud1.xyz') 

113 

114 >>> calc = Siesta(label='bud', 

115 ... meshcutoff=250 * Ry, 

116 ... basis='DZP', 

117 ... kpts=[1, 1, 1]) 

118 

119 >>> calc.set_fdf('DM.MixingWeight', 0.08) 

120 >>> calc.set_fdf('DM.NumberPulay', 3) 

121 >>> calc.set_fdf('DM.NumberKick', 20) 

122 >>> calc.set_fdf('DM.KickMixingWeight', 0.15) 

123 >>> calc.set_fdf('SolutionMethod', 'Diagon') 

124 >>> calc.set_fdf('MaxSCFIterations', 500) 

125 >>> calc.set_fdf('PAO.BasisType', 'split') 

126 >>> #50 meV = 0.003674931 * Ry 

127 >>> calc.set_fdf('PAO.EnergyShift', 0.003674931 * Ry ) 

128 >>> calc.set_fdf('LatticeConstant', 1.000000 * Ang) 

129 >>> calc.set_fdf('WriteCoorXmol', 'T') 

130 

131 >>> bud.calc = calc 

132 

133 >>> ir = Infrared(bud) 

134 >>> ir.run() 

135 >>> ir.summary() 

136 

137 """ 

138 

139 def __init__( 

140 self, 

141 atoms, 

142 indices=None, 

143 name='ir', 

144 delta=0.01, 

145 nfree=2, 

146 directions=None, 

147 ): 

148 Vibrations.__init__( 

149 self, atoms, indices=indices, name=name, delta=delta, nfree=nfree 

150 ) 

151 if atoms.constraints: 

152 print( 

153 'WARNING! \n Your Atoms object is constrained. ' 

154 'Some forces may be unintended set to zero. \n' 

155 ) 

156 if directions is None: 

157 self.directions = np.asarray([0, 1, 2]) 

158 else: 

159 self.directions = np.asarray(directions) 

160 self.ir = True 

161 

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

163 self.method = method.lower() 

164 self.direction = direction.lower() 

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

166 

167 if direction != 'central': 

168 raise NotImplementedError( 

169 'Only central difference is implemented at the moment.' 

170 ) 

171 

172 disp = self._eq_disp() 

173 forces_zero = disp.forces() 

174 dipole_zero = disp.dipole() 

175 self.dipole_zero = (sum(dipole_zero**2) ** 0.5) / units.Debye 

176 self.force_zero = max( 

177 sum((forces_zero[j]) ** 2) ** 0.5 for j in self.indices 

178 ) 

179 

180 ndof = 3 * len(self.indices) 

181 H = np.empty((ndof, ndof)) 

182 dpdx = np.empty((ndof, 3)) 

183 for r, (a, i) in enumerate(self._iter_ai()): 

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

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

186 

187 fminus = disp_minus.forces() 

188 dminus = disp_minus.dipole() 

189 

190 fplus = disp_plus.forces() 

191 dplus = disp_plus.dipole() 

192 

193 if self.nfree == 4: 

194 disp_mm = self._disp(a, i, -2) 

195 disp_pp = self._disp(a, i, 2) 

196 fminusminus = disp_mm.forces() 

197 dminusminus = disp_mm.dipole() 

198 

199 fplusplus = disp_pp.forces() 

200 dplusplus = disp_pp.dipole() 

201 if self.method == 'frederiksen': 

202 fminus[a] += -fminus.sum(0) 

203 fplus[a] += -fplus.sum(0) 

204 if self.nfree == 4: 

205 fminusminus[a] += -fminus.sum(0) 

206 fplusplus[a] += -fplus.sum(0) 

207 if self.nfree == 2: 

208 H[r] = (fminus - fplus)[self.indices].ravel() / 2.0 

209 dpdx[r] = dminus - dplus 

210 if self.nfree == 4: 

211 H[r] = (-fminusminus + 8 * fminus - 8 * fplus + fplusplus)[ 

212 self.indices 

213 ].ravel() / 12.0 

214 dpdx[r] = ( 

215 -dplusplus + 8 * dplus - 8 * dminus + dminusminus 

216 ) / 6.0 

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

218 dpdx[r] /= 2 * self.delta 

219 for n in range(3): 

220 if n not in self.directions: 

221 dpdx[r][n] = 0 

222 dpdx[r][n] = 0 

223 # Calculate eigenfrequencies and eigenvectors 

224 masses = self.atoms.get_masses() 

225 H += H.copy().T 

226 self.H = H 

227 

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

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

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

231 

232 # Calculate intensities 

233 dpdq = np.array( 

234 [ 

235 dpdx[j] 

236 / sqrt(masses[self.indices[j // 3]] * units._amu / units._me) 

237 for j in range(ndof) 

238 ] 

239 ) 

240 dpdQ = np.dot(dpdq.T, modes) 

241 dpdQ = dpdQ.T 

242 intensities = np.array([sum(dpdQ[j] ** 2) for j in range(ndof)]) 

243 # Conversion factor: 

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

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

246 # Conversion factor from atomic units to (D/Angstrom)^2/amu. 

247 conv = (1.0 / units.Debye) ** 2 * units._amu / units._me 

248 self.intensities = intensities * conv 

249 

250 def intensity_prefactor(self, intensity_unit): 

251 if intensity_unit == '(D/A)2/amu': 

252 return 1.0, '(D/Å)^2 amu^-1' 

253 elif intensity_unit == 'km/mol': 

254 # conversion factor from Porezag PRB 54 (1996) 7830 

255 return 42.255, 'km/mol' 

256 else: 

257 raise RuntimeError( 

258 'Intensity unit >' + intensity_unit + '< unknown.' 

259 ) 

260 

261 def summary( 

262 self, 

263 method='standard', 

264 direction='central', 

265 intensity_unit='(D/A)2/amu', 

266 log=stdout, 

267 ): 

268 hnu = self.get_energies(method, direction) 

269 s = 0.01 * units._e / units._c / units._hplanck 

270 iu, iu_string = self.intensity_prefactor(intensity_unit) 

271 if intensity_unit == '(D/A)2/amu': 

272 iu_format = '%9.4f' 

273 elif intensity_unit == 'km/mol': 

274 iu_string = ' ' + iu_string 

275 iu_format = ' %7.1f' 

276 if isinstance(log, str): 

277 log = paropen(log, 'a') 

278 

279 parprint('-------------------------------------', file=log) 

280 parprint(' Mode Frequency Intensity', file=log) 

281 parprint(' # meV cm^-1 ' + iu_string, file=log) 

282 parprint('-------------------------------------', file=log) 

283 for n, e in enumerate(hnu): 

284 if e.imag != 0: 

285 c = 'i' 

286 e = e.imag 

287 else: 

288 c = ' ' 

289 e = e.real 

290 parprint( 

291 ('%3d %6.1f%s %7.1f%s ' + iu_format) 

292 % (n, 1000 * e, c, s * e, c, iu * self.intensities[n]), 

293 file=log, 

294 ) 

295 parprint('-------------------------------------', file=log) 

296 parprint( 

297 'Zero-point energy: %.3f eV' % self.get_zero_point_energy(), 

298 file=log, 

299 ) 

300 parprint('Static dipole moment: %.3f D' % self.dipole_zero, file=log) 

301 parprint( 

302 'Maximum force on atom in `equilibrium`: %.4f eV/Å' 

303 % self.force_zero, 

304 file=log, 

305 ) 

306 parprint(file=log) 

307 

308 def get_spectrum( 

309 self, 

310 start=800, 

311 end=4000, 

312 npts=None, 

313 width=4, 

314 type='Gaussian', 

315 method='standard', 

316 direction='central', 

317 intensity_unit='(D/A)2/amu', 

318 normalize=False, 

319 ): 

320 """Get infrared spectrum. 

321 

322 The method returns wavenumbers in cm^-1 with corresponding 

323 absolute infrared intensity. 

324 Start and end point, and width of the Gaussian/Lorentzian should 

325 be given in cm^-1. 

326 normalize=True ensures the integral over the peaks to give the 

327 intensity. 

328 """ 

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

330 intensities = self.intensities 

331 return self.fold( 

332 frequencies, intensities, start, end, npts, width, type, normalize 

333 ) 

334 

335 def write_spectra( 

336 self, 

337 out='ir-spectra.dat', 

338 start=800, 

339 end=4000, 

340 npts=None, 

341 width=10, 

342 type='Gaussian', 

343 method='standard', 

344 direction='central', 

345 intensity_unit='(D/A)2/amu', 

346 normalize=False, 

347 ): 

348 """Write out infrared spectrum to file. 

349 

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

351 absolute infrared intensities, and 

352 the third column the absorbance scaled so that data runs 

353 from 1 to 0. Start and end 

354 point, and width of the Gaussian/Lorentzian should be given 

355 in cm^-1.""" 

356 energies, spectrum = self.get_spectrum( 

357 start, end, npts, width, type, method, direction, normalize 

358 ) 

359 

360 # Write out spectrum in file. First column is absolute intensities. 

361 # Second column is absorbance scaled so that data runs from 1 to 0 

362 spectrum2 = 1.0 - spectrum / spectrum.max() 

363 outdata = np.empty([len(energies), 3]) 

364 outdata.T[0] = energies 

365 outdata.T[1] = spectrum 

366 outdata.T[2] = spectrum2 

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

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

369 iu, iu_string = self.intensity_prefactor(intensity_unit) 

370 if normalize: 

371 iu_string = 'cm ' + iu_string 

372 fd.write('# [cm^-1] %14s\n' % ('[' + iu_string + ']')) 

373 for row in outdata: 

374 fd.write( 

375 '%.3f %15.5e %15.5e \n' % (row[0], iu * row[1], row[2]) 

376 )