Coverage for ase/vibrations/raman.py: 89.53%

191 statements  

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

1import numpy as np 

2 

3import ase.units as u 

4from ase.dft import monkhorst_pack 

5from ase.parallel import world 

6from ase.phonons import Phonons 

7from ase.utils import IOContext 

8from ase.vibrations.vibrations import AtomicDisplacements, Vibrations 

9 

10 

11class RamanCalculatorBase(IOContext): 

12 def __init__( 

13 self, 

14 atoms, # XXX do we need atoms at this stage ? 

15 *args, 

16 name='raman', 

17 exext='.alpha', 

18 txt='-', 

19 verbose=False, 

20 comm=world, 

21 **kwargs, 

22 ): 

23 """ 

24 Parameters 

25 ---------- 

26 atoms: ase Atoms object 

27 exext: string 

28 Extension for excitation filenames 

29 txt: 

30 Output stream 

31 verbose: 

32 Verbosity level of output 

33 comm: 

34 Communicator, default world 

35 """ 

36 kwargs['name'] = name 

37 self.exname = kwargs.pop('exname', name) 

38 

39 super().__init__(atoms, *args, **kwargs) 

40 

41 self.exext = exext 

42 

43 self.txt = self.openfile(file=txt, comm=comm) 

44 self.verbose = verbose 

45 

46 self.comm = comm 

47 

48 

49class StaticRamanCalculatorBase(RamanCalculatorBase): 

50 """Base class for Raman intensities derived from 

51 static polarizabilities""" 

52 

53 def __init__(self, atoms, exobj, exkwargs=None, *args, **kwargs): 

54 self.exobj = exobj 

55 if exkwargs is None: 

56 exkwargs = {} 

57 self.exkwargs = exkwargs 

58 super().__init__(atoms, *args, **kwargs) 

59 

60 def _new_exobj(self): 

61 return self.exobj(**self.exkwargs) 

62 

63 def calculate(self, atoms, disp): 

64 returnvalue = super().calculate(atoms, disp) 

65 disp.calculate_and_save_static_polarizability(atoms) 

66 return returnvalue 

67 

68 

69class StaticRamanCalculator(StaticRamanCalculatorBase, Vibrations): 

70 pass 

71 

72 

73class StaticRamanPhononsCalculator(StaticRamanCalculatorBase, Phonons): 

74 pass 

75 

76 

77class RamanBase(AtomicDisplacements, IOContext): 

78 def __init__( 

79 self, 

80 atoms, # XXX do we need atoms at this stage ? 

81 *args, 

82 name='raman', 

83 exname=None, 

84 exext='.alpha', 

85 txt='-', 

86 verbose=False, 

87 comm=world, 

88 **kwargs, 

89 ): 

90 """ 

91 Parameters 

92 ---------- 

93 atoms: ase Atoms object 

94 exext: string 

95 Extension for excitation filenames 

96 txt: 

97 Output stream 

98 verbose: 

99 Verbosity level of output 

100 comm: 

101 Communicator, default world 

102 """ 

103 self.atoms = atoms 

104 

105 self.name = name 

106 if exname is None: 

107 self.exname = name 

108 else: 

109 self.exname = exname 

110 self.exext = exext 

111 

112 self.txt = self.openfile(file=txt, comm=comm) 

113 self.verbose = verbose 

114 

115 self.comm = comm 

116 

117 

118class RamanData(RamanBase): 

119 """Base class to evaluate Raman spectra from pre-computed data""" 

120 

121 def __init__( 

122 self, 

123 atoms, # XXX do we need atoms at this stage ? 

124 *args, 

125 exname=None, # name for excited state calculations 

126 **kwargs, 

127 ): 

128 """ 

129 Parameters 

130 ---------- 

131 atoms: ase Atoms object 

132 exname: string 

133 name for excited state calculations (defaults to name), 

134 used for reading excitations 

135 """ 

136 super().__init__(atoms, *args, **kwargs) 

137 

138 if exname is None: 

139 exname = kwargs.get('name', self.name) 

140 self.exname = exname 

141 self._already_read = False 

142 

143 def get_energies(self): 

144 self.calculate_energies_and_modes() 

145 return self.om_Q 

146 

147 def init_parallel_read(self): 

148 """Initialize variables for parallel read""" 

149 rank = self.comm.rank 

150 indices = self.indices 

151 myn = -(-self.ndof // self.comm.size) # ceil divide 

152 self.slize = s = slice(myn * rank, myn * (rank + 1)) 

153 self.myindices = np.repeat(indices, 3)[s] 

154 self.myxyz = ('xyz' * len(indices))[s] 

155 self.myr = range(self.ndof)[s] 

156 self.mynd = len(self.myr) 

157 

158 def read(self, *args, **kwargs): 

159 """Read data from a pre-performed calculation.""" 

160 if self._already_read: 

161 return 

162 

163 self.vibrations.read(*args, **kwargs) 

164 self.init_parallel_read() 

165 self.read_excitations() 

166 

167 self._already_read = True 

168 

169 @staticmethod 

170 def m2(z): 

171 return (z * z.conj()).real 

172 

173 def map_to_modes(self, V_rcc): 

174 V_qcc = (V_rcc.T * self.im_r).T # units Angstrom^2 / sqrt(amu) 

175 V_Qcc = np.dot(V_qcc.T, self.modes_Qq.T).T 

176 return V_Qcc 

177 

178 def me_Qcc(self, *args, **kwargs): 

179 """Full matrix element 

180 

181 Returns 

182 ------- 

183 Matrix element in e^2 Angstrom^2 / eV 

184 """ 

185 # Angstrom^2 / sqrt(amu) 

186 elme_Qcc = self.electronic_me_Qcc(*args, **kwargs) 

187 # Angstrom^3 -> e^2 Angstrom^2 / eV 

188 elme_Qcc /= u.Hartree * u.Bohr # e^2 Angstrom / eV / sqrt(amu) 

189 return elme_Qcc * self.vib01_Q[:, None, None] 

190 

191 def get_absolute_intensities(self, delta=0, **kwargs): 

192 """Absolute Raman intensity or Raman scattering factor 

193 

194 Parameter 

195 --------- 

196 delta: float 

197 pre-factor for asymmetric anisotropy, default 0 

198 

199 References 

200 ---------- 

201 Porezag and Pederson, PRB 54 (1996) 7830-7836 (delta=0) 

202 Baiardi and Barone, JCTC 11 (2015) 3267-3280 (delta=5) 

203 

204 Returns 

205 ------- 

206 raman intensity, unit Ang**4/amu 

207 """ 

208 alpha2_r, gamma2_r, delta2_r = self._invariants( 

209 self.electronic_me_Qcc(**kwargs) 

210 ) 

211 return 45 * alpha2_r + delta * delta2_r + 7 * gamma2_r 

212 

213 def intensity(self, *args, **kwargs): 

214 """Raman intensity 

215 

216 Returns 

217 ------- 

218 unit e^4 Angstrom^4 / eV^2 

219 """ 

220 self.calculate_energies_and_modes() 

221 

222 m2 = Raman.m2 

223 alpha_Qcc = self.me_Qcc(*args, **kwargs) 

224 if not self.observation: # XXXX remove 

225 """Simple sum, maybe too simple""" 

226 return m2(alpha_Qcc).sum(axis=1).sum(axis=1) 

227 # XXX enable when appropriate 

228 # if self.observation['orientation'].lower() != 'random': 

229 # raise NotImplementedError('not yet') 

230 

231 # random orientation of the molecular frame 

232 # Woodward & Long, 

233 # Guthmuller, J. J. Chem. Phys. 2016, 144 (6), 64106 

234 alpha2_r, gamma2_r, delta2_r = self._invariants(alpha_Qcc) 

235 

236 if self.observation['geometry'] == '-Z(XX)Z': # Porto's notation 

237 return (45 * alpha2_r + 5 * delta2_r + 4 * gamma2_r) / 45.0 

238 elif self.observation['geometry'] == '-Z(XY)Z': # Porto's notation 

239 return gamma2_r / 15.0 

240 elif self.observation['scattered'] == 'Z': 

241 # scattered light in direction of incoming light 

242 return (45 * alpha2_r + 5 * delta2_r + 7 * gamma2_r) / 45.0 

243 elif self.observation['scattered'] == 'parallel': 

244 # scattered light perendicular and 

245 # polarization in plane 

246 return 6 * gamma2_r / 45.0 

247 elif self.observation['scattered'] == 'perpendicular': 

248 # scattered light perendicular and 

249 # polarization out of plane 

250 return (45 * alpha2_r + 5 * delta2_r + 7 * gamma2_r) / 45.0 

251 else: 

252 raise NotImplementedError 

253 

254 def _invariants(self, alpha_Qcc): 

255 """Raman invariants 

256 

257 Parameter 

258 --------- 

259 alpha_Qcc: array 

260 Matrix element or polarizability tensor 

261 

262 Reference 

263 --------- 

264 Derek A. Long, The Raman Effect, ISBN 0-471-49028-8 

265 

266 Returns 

267 ------- 

268 mean polarizability, anisotropy, asymmetric anisotropy 

269 """ 

270 m2 = Raman.m2 

271 alpha2_r = ( 

272 m2(alpha_Qcc[:, 0, 0] + alpha_Qcc[:, 1, 1] + alpha_Qcc[:, 2, 2]) 

273 / 9.0 

274 ) 

275 delta2_r = ( 

276 3 

277 / 4.0 

278 * ( 

279 m2(alpha_Qcc[:, 0, 1] - alpha_Qcc[:, 1, 0]) 

280 + m2(alpha_Qcc[:, 0, 2] - alpha_Qcc[:, 2, 0]) 

281 + m2(alpha_Qcc[:, 1, 2] - alpha_Qcc[:, 2, 1]) 

282 ) 

283 ) 

284 gamma2_r = ( 

285 3 

286 / 4.0 

287 * ( 

288 m2(alpha_Qcc[:, 0, 1] + alpha_Qcc[:, 1, 0]) 

289 + m2(alpha_Qcc[:, 0, 2] + alpha_Qcc[:, 2, 0]) 

290 + m2(alpha_Qcc[:, 1, 2] + alpha_Qcc[:, 2, 1]) 

291 ) 

292 + ( 

293 m2(alpha_Qcc[:, 0, 0] - alpha_Qcc[:, 1, 1]) 

294 + m2(alpha_Qcc[:, 0, 0] - alpha_Qcc[:, 2, 2]) 

295 + m2(alpha_Qcc[:, 1, 1] - alpha_Qcc[:, 2, 2]) 

296 ) 

297 / 2 

298 ) 

299 return alpha2_r, gamma2_r, delta2_r 

300 

301 def summary(self, log='-'): 

302 """Print summary for given omega [eV]""" 

303 with IOContext() as io: 

304 log = io.openfile(file=log, mode='a', comm=self.comm) 

305 return self._summary(log) 

306 

307 def _summary(self, log): 

308 hnu = self.get_energies() 

309 intensities = self.get_absolute_intensities() 

310 te = int(np.log10(intensities.max())) - 2 

311 scale = 10 ** (-te) 

312 

313 if not te: 

314 ts = '' 

315 elif te > -2 and te < 3: 

316 ts = str(10**te) 

317 else: 

318 ts = f'10^{te}' 

319 

320 print('-------------------------------------', file=log) 

321 print(' Mode Frequency Intensity', file=log) 

322 print(f' # meV cm^-1 [{ts}A^4/amu]', file=log) 

323 print('-------------------------------------', file=log) 

324 for n, e in enumerate(hnu): 

325 if e.imag != 0: 

326 c = 'i' 

327 e = e.imag 

328 else: 

329 c = ' ' 

330 e = e.real 

331 print( 

332 '%3d %6.1f%s %7.1f%s %9.2f' 

333 % (n, 1000 * e, c, e / u.invcm, c, intensities[n] * scale), 

334 file=log, 

335 ) 

336 print('-------------------------------------', file=log) 

337 # XXX enable this in phonons 

338 # parprint('Zero-point energy: %.3f eV' % 

339 # self.vibrations.get_zero_point_energy(), 

340 # file=log) 

341 

342 

343class Raman(RamanData): 

344 def __init__(self, atoms, *args, **kwargs): 

345 super().__init__(atoms, *args, **kwargs) 

346 

347 for key in ['txt', 'exext', 'exname']: 

348 kwargs.pop(key, None) 

349 kwargs['name'] = kwargs.get('name', self.name) 

350 self.vibrations = Vibrations(atoms, *args, **kwargs) 

351 

352 self.delta = self.vibrations.delta 

353 self.indices = self.vibrations.indices 

354 

355 def calculate_energies_and_modes(self): 

356 if hasattr(self, 'im_r'): 

357 return 

358 

359 self.read() 

360 

361 self.im_r = self.vibrations.im 

362 self.modes_Qq = self.vibrations.modes 

363 self.om_Q = self.vibrations.hnu.real # energies in eV 

364 self.H = self.vibrations.H # XXX used in albrecht.py 

365 # pre-factors for one vibrational excitation 

366 with np.errstate(divide='ignore'): 

367 self.vib01_Q = np.where( 

368 self.om_Q > 0, 1.0 / np.sqrt(2 * self.om_Q), 0 

369 ) 

370 # -> sqrt(amu) * Angstrom 

371 self.vib01_Q *= np.sqrt(u.Ha * u._me / u._amu) * u.Bohr 

372 

373 

374class RamanPhonons(RamanData): 

375 def __init__(self, atoms, *args, **kwargs): 

376 RamanData.__init__(self, atoms, *args, **kwargs) 

377 

378 for key in ['txt', 'exext', 'exname']: 

379 kwargs.pop(key, None) 

380 kwargs['name'] = kwargs.get('name', self.name) 

381 self.vibrations = Phonons(atoms, *args, **kwargs) 

382 

383 self.delta = self.vibrations.delta 

384 self.indices = self.vibrations.indices 

385 

386 self.kpts = (1, 1, 1) 

387 

388 @property 

389 def kpts(self): 

390 return self._kpts 

391 

392 @kpts.setter 

393 def kpts(self, kpts): 

394 if not hasattr(self, '_kpts') or kpts != self._kpts: 

395 self._kpts = kpts 

396 self.kpts_kc = monkhorst_pack(self.kpts) 

397 if hasattr(self, 'im_r'): 

398 del self.im_r # we'll have to recalculate 

399 

400 def calculate_energies_and_modes(self): 

401 if not self._already_read: 

402 if hasattr(self, 'im_r'): 

403 del self.im_r 

404 self.read() 

405 

406 if not hasattr(self, 'im_r'): 

407 omega_kl, u_kl = self.vibrations.band_structure( 

408 self.kpts_kc, modes=True, verbose=self.verbose 

409 ) 

410 

411 m_inv_a = self.atoms.get_masses()[self.indices] ** -0.5 

412 self.im_r = np.repeat(m_inv_a, 3) 

413 self.om_Q = omega_kl.ravel().real # energies in eV 

414 self.modes_Qq = u_kl.reshape(len(self.om_Q), 3 * len(self.atoms)) 

415 self.modes_Qq /= self.im_r 

416 self.om_v = self.om_Q 

417 

418 # pre-factors for one vibrational excitation 

419 with np.errstate(divide='ignore', invalid='ignore'): 

420 self.vib01_Q = np.where( 

421 self.om_Q > 0, 1.0 / np.sqrt(2 * self.om_Q), 0 

422 ) 

423 # -> sqrt(amu) * Angstrom 

424 self.vib01_Q *= np.sqrt(u.Ha * u._me / u._amu) * u.Bohr