Coverage for ase/vibrations/albrecht.py: 89.82%

285 statements  

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

1import sys 

2from itertools import combinations_with_replacement 

3 

4import numpy as np 

5 

6import ase.units as u 

7from ase.parallel import paropen, parprint 

8from ase.vibrations.franck_condon import ( 

9 FranckCondonOverlap, 

10 FranckCondonRecursive, 

11) 

12from ase.vibrations.resonant_raman import ResonantRaman 

13 

14 

15class Albrecht(ResonantRaman): 

16 def __init__(self, *args, **kwargs): 

17 """ 

18 Parameters 

19 ---------- 

20 all from ResonantRaman.__init__ 

21 combinations: int 

22 Combinations to consider for multiple excitations. 

23 Default is 1, possible 2 

24 skip: int 

25 Number of first transitions to exclude. Default 0, 

26 recommended: 5 for linear molecules, 6 for other molecules 

27 nm: int 

28 Number of intermediate m levels to consider, default 20 

29 """ 

30 self.combinations = kwargs.pop('combinations', 1) 

31 self.skip = kwargs.pop('skip', 0) 

32 self.nm = kwargs.pop('nm', 20) 

33 approximation = kwargs.pop('approximation', 'Albrecht') 

34 

35 ResonantRaman.__init__(self, *args, **kwargs) 

36 

37 self.set_approximation(approximation) 

38 

39 def set_approximation(self, value): 

40 approx = value.lower() 

41 if approx in ['albrecht', 'albrecht b', 'albrecht c', 'albrecht bc']: 

42 if not self.overlap: 

43 raise ValueError('Overlaps are needed') 

44 elif approx != 'albrecht a': 

45 raise ValueError('Please use "Albrecht" or "Albrecht A/B/C/BC"') 

46 self._approx = value 

47 

48 def calculate_energies_and_modes(self): 

49 if hasattr(self, 'im_r'): 

50 return 

51 

52 ResonantRaman.calculate_energies_and_modes(self) 

53 

54 # single transitions and their occupation 

55 om_Q = self.om_Q[self.skip :] 

56 om_v = om_Q 

57 ndof = len(om_Q) 

58 n_vQ = np.eye(ndof, dtype=int) 

59 

60 l_Q = range(ndof) 

61 ind_v = list(combinations_with_replacement(l_Q, 1)) 

62 

63 if self.combinations > 1: 

64 if self.combinations != 2: 

65 raise NotImplementedError 

66 

67 for c in range(2, self.combinations + 1): 

68 ind_v += list(combinations_with_replacement(l_Q, c)) 

69 

70 nv = len(ind_v) 

71 n_vQ = np.zeros((nv, ndof), dtype=int) 

72 om_v = np.zeros((nv), dtype=float) 

73 for j, wt in enumerate(ind_v): 

74 for i in wt: 

75 n_vQ[j, i] += 1 

76 om_v = n_vQ.dot(om_Q) 

77 

78 self.ind_v = ind_v 

79 self.om_v = om_v 

80 self.n_vQ = n_vQ # how many of each 

81 self.d_vQ = np.where(n_vQ > 0, 1, 0) # do we have them ? 

82 

83 def get_energies(self): 

84 self.calculate_energies_and_modes() 

85 return self.om_v 

86 

87 def _collect_r(self, arr_ro, oshape, dtype): 

88 """Collect an array that is distributed.""" 

89 if len(self.myr) == self.ndof: # serial 

90 return arr_ro 

91 data_ro = np.zeros([self.ndof] + oshape, dtype) 

92 if len(arr_ro): 

93 data_ro[self.slize] = arr_ro 

94 self.comm.sum(data_ro) 

95 return data_ro 

96 

97 def Huang_Rhys_factors(self, forces_r): 

98 """Evaluate Huang-Rhys factors derived from forces.""" 

99 return 0.5 * self.unitless_displacements(forces_r) ** 2 

100 

101 def unitless_displacements(self, forces_r, mineigv=1e-12): 

102 """Evaluate unitless displacements from forces 

103 

104 Parameters 

105 ---------- 

106 forces_r: array 

107 Forces in cartesian coordinates 

108 mineigv: float 

109 Minimal Eigenvalue to consider in matrix inversion to handle 

110 numerical noise. Default 1e-12 

111 

112 Returns 

113 ------- 

114 Unitless displacements in Eigenmode coordinates 

115 """ 

116 assert len(forces_r.flat) == self.ndof 

117 

118 if not hasattr(self, 'Dm1_q'): 

119 self.eigv_q, self.eigw_rq = np.linalg.eigh( 

120 self.im_r[:, None] * self.H * self.im_r 

121 ) 

122 # there might be zero or nearly zero eigenvalues 

123 self.Dm1_q = np.divide( 

124 1, 

125 self.eigv_q, 

126 out=np.zeros_like(self.eigv_q), 

127 where=np.abs(self.eigv_q) > mineigv, 

128 ) 

129 X_r = ( 

130 self.eigw_rq 

131 @ np.diag(self.Dm1_q) 

132 @ self.eigw_rq.T 

133 @ (forces_r.flat * self.im_r) 

134 ) 

135 

136 d_Q = np.dot(self.modes_Qq, X_r) 

137 s = 1.0e-20 / u.kg / u.C / u._hbar**2 

138 d_Q *= np.sqrt(s * self.om_Q) 

139 

140 return d_Q 

141 

142 def omegaLS(self, omega, gamma): 

143 omL = omega + 1j * gamma 

144 omS_Q = omL - self.om_Q 

145 return omL, omS_Q 

146 

147 def init_parallel_excitations(self): 

148 """Init for paralellization over excitations.""" 

149 n_p = len(self.ex0E_p) 

150 

151 # collect excited state forces 

152 exF_pr = self._collect_r(self.exF_rp, [n_p], self.ex0E_p.dtype).T 

153 

154 # select your work load 

155 myn = -(-n_p // self.comm.size) # ceil divide 

156 rank = self.comm.rank 

157 s = slice(myn * rank, myn * (rank + 1)) 

158 return n_p, range(n_p)[s], exF_pr 

159 

160 def meA(self, omega, gamma=0.1): 

161 """Evaluate Albrecht A term. 

162 

163 Returns 

164 ------- 

165 Full Albrecht A matrix element. Unit: e^2 Angstrom^2 / eV 

166 """ 

167 self.read() 

168 

169 if not hasattr(self, 'fcr'): 

170 self.fcr = FranckCondonRecursive() 

171 

172 omL = omega + 1j * gamma 

173 omS_Q = omL - self.om_Q 

174 

175 _n_p, myp, exF_pr = self.init_parallel_excitations() 

176 exF_pr = np.where(np.abs(exF_pr) > 1e-2, exF_pr, 0) 

177 

178 m_Qcc = np.zeros((self.ndof, 3, 3), dtype=complex) 

179 for p in myp: 

180 energy = self.ex0E_p[p] 

181 d_Q = self.unitless_displacements(exF_pr[p]) 

182 energy_Q = energy - self.om_Q * d_Q**2 / 2.0 

183 me_cc = np.outer(self.ex0m_pc[p], self.ex0m_pc[p].conj()) 

184 

185 wm_Q = np.zeros((self.ndof), dtype=complex) 

186 wp_Q = np.zeros((self.ndof), dtype=complex) 

187 for m in range(self.nm): 

188 fco_Q = self.fcr.direct0mm1(m, d_Q) 

189 e_Q = energy_Q + m * self.om_Q 

190 wm_Q += fco_Q / (e_Q - omL) 

191 wp_Q += fco_Q / (e_Q + omS_Q) 

192 m_Qcc += np.einsum('a,bc->abc', wm_Q, me_cc) 

193 m_Qcc += np.einsum('a,bc->abc', wp_Q, me_cc.conj()) 

194 self.comm.sum(m_Qcc) 

195 

196 return m_Qcc # e^2 Angstrom^2 / eV 

197 

198 def meAmult(self, omega, gamma=0.1): 

199 """Evaluate Albrecht A term. 

200 

201 Returns 

202 ------- 

203 Full Albrecht A matrix element. Unit: e^2 Angstrom^2 / eV 

204 """ 

205 self.read() 

206 

207 if not hasattr(self, 'fcr'): 

208 self.fcr = FranckCondonRecursive() 

209 

210 omL = omega + 1j * gamma 

211 omS_v = omL - self.om_v 

212 nv = len(self.om_v) 

213 om_Q = self.om_Q[self.skip :] 

214 nQ = len(om_Q) 

215 

216 # n_v: 

217 # how many FC factors are involved 

218 # nvib_ov: 

219 # delta functions to switch contributions depending on order o 

220 # ind_ov: 

221 # Q indicees 

222 # n_ov: 

223 # # of vibrational excitations 

224 n_v = self.d_vQ.sum(axis=1) # multiplicity 

225 

226 nvib_ov = np.empty((self.combinations, nv), dtype=int) 

227 om_ov = np.zeros((self.combinations, nv), dtype=float) 

228 n_ov = np.zeros((self.combinations, nv), dtype=int) 

229 d_ovQ = np.zeros((self.combinations, nv, nQ), dtype=int) 

230 for o in range(self.combinations): 

231 nvib_ov[o] = np.array(n_v == (o + 1)) 

232 for v in range(nv): 

233 try: 

234 om_ov[o, v] = om_Q[self.ind_v[v][o]] 

235 d_ovQ[o, v, self.ind_v[v][o]] = 1 

236 except IndexError: 

237 pass 

238 # XXXX change ???? 

239 n_ov[0] = self.n_vQ.max(axis=1) 

240 n_ov[1] = nvib_ov[1] 

241 

242 _n_p, myp, exF_pr = self.init_parallel_excitations() 

243 

244 m_vcc = np.zeros((nv, 3, 3), dtype=complex) 

245 for p in myp: 

246 energy = self.ex0E_p[p] 

247 d_Q = self.unitless_displacements(exF_pr[p])[self.skip :] 

248 S_Q = d_Q**2 / 2.0 

249 energy_v = energy - self.d_vQ.dot(om_Q * S_Q) 

250 me_cc = np.outer(self.ex0m_pc[p], self.ex0m_pc[p].conj()) 

251 

252 fco1_mQ = np.empty((self.nm, nQ), dtype=float) 

253 fco2_mQ = np.empty((self.nm, nQ), dtype=float) 

254 for m in range(self.nm): 

255 fco1_mQ[m] = self.fcr.direct0mm1(m, d_Q) 

256 fco2_mQ[m] = self.fcr.direct0mm2(m, d_Q) 

257 

258 wm_v = np.zeros((nv), dtype=complex) 

259 wp_v = np.zeros((nv), dtype=complex) 

260 for m in range(self.nm): 

261 fco1_v = np.where( 

262 n_ov[0] == 2, 

263 d_ovQ[0].dot(fco2_mQ[m]), 

264 d_ovQ[0].dot(fco1_mQ[m]), 

265 ) 

266 

267 em_v = energy_v + m * om_ov[0] 

268 # multiples of same kind 

269 fco_v = nvib_ov[0] * fco1_v 

270 wm_v += fco_v / (em_v - omL) 

271 wp_v += fco_v / (em_v + omS_v) 

272 if nvib_ov[1].any(): 

273 # multiples of mixed type 

274 for n in range(self.nm): 

275 fco2_v = d_ovQ[1].dot(fco1_mQ[n]) 

276 e_v = em_v + n * om_ov[1] 

277 fco_v = nvib_ov[1] * fco1_v * fco2_v 

278 wm_v += fco_v / (e_v - omL) 

279 wp_v += fco_v / (e_v + omS_v) 

280 

281 m_vcc += np.einsum('a,bc->abc', wm_v, me_cc) 

282 m_vcc += np.einsum('a,bc->abc', wp_v, me_cc.conj()) 

283 self.comm.sum(m_vcc) 

284 

285 return m_vcc # e^2 Angstrom^2 / eV 

286 

287 def meBC(self, omega, gamma=0.1, term='BC'): 

288 """Evaluate Albrecht BC term. 

289 

290 Returns 

291 ------- 

292 Full Albrecht BC matrix element. 

293 Unit: e^2 Angstrom / eV / sqrt(amu) 

294 """ 

295 self.read() 

296 

297 if not hasattr(self, 'fco'): 

298 self.fco = FranckCondonOverlap() 

299 

300 omL = omega + 1j * gamma 

301 omS_Q = omL - self.om_Q 

302 

303 # excited state forces 

304 n_p, myp, exF_pr = self.init_parallel_excitations() 

305 # derivatives after normal coordinates 

306 exdmdr_rpc = self._collect_r( 

307 self.exdmdr_rpc, [n_p, 3], self.ex0m_pc.dtype 

308 ) 

309 dmdq_qpc = (exdmdr_rpc.T * self.im_r).T # unit e / sqrt(amu) 

310 dmdQ_Qpc = np.dot(dmdq_qpc.T, self.modes_Qq.T).T # unit e / sqrt(amu) 

311 

312 me_Qcc = np.zeros((self.ndof, 3, 3), dtype=complex) 

313 for p in myp: 

314 energy = self.ex0E_p[p] 

315 S_Q = self.Huang_Rhys_factors(exF_pr[p]) 

316 # relaxed excited state energy 

317 # # n_vQ = np.where(self.n_vQ > 0, 1, 0) 

318 # # energy_v = energy - n_vQ.dot(self.om_Q * S_Q) 

319 energy_Q = energy - self.om_Q * S_Q 

320 

321 # # me_cc = np.outer(self.ex0m_pc[p], self.ex0m_pc[p].conj()) 

322 m_c = self.ex0m_pc[p] # e Angstrom 

323 dmdQ_Qc = dmdQ_Qpc[:, p] # e / sqrt(amu) 

324 

325 wBLS_Q = np.zeros((self.ndof), dtype=complex) 

326 wBSL_Q = np.zeros((self.ndof), dtype=complex) 

327 wCLS_Q = np.zeros((self.ndof), dtype=complex) 

328 wCSL_Q = np.zeros((self.ndof), dtype=complex) 

329 for m in range(self.nm): 

330 f0mmQ1_Q = self.fco.directT0(m, S_Q) + np.sqrt( 

331 2 

332 ) * self.fco.direct0mm2(m, S_Q) 

333 f0Qmm1_Q = self.fco.direct(1, m, S_Q) 

334 

335 em_Q = energy_Q + m * self.om_Q 

336 wBLS_Q += f0mmQ1_Q / (em_Q - omL) 

337 wBSL_Q += f0Qmm1_Q / (em_Q - omL) 

338 wCLS_Q += f0mmQ1_Q / (em_Q + omS_Q) 

339 wCSL_Q += f0Qmm1_Q / (em_Q + omS_Q) 

340 

341 # unit e^2 Angstrom / sqrt(amu) 

342 mdmdQ_Qcc = np.einsum('a,bc->bac', m_c, dmdQ_Qc.conj()) 

343 dmdQm_Qcc = np.einsum('ab,c->abc', dmdQ_Qc, m_c.conj()) 

344 if 'B' in term: 

345 me_Qcc += np.multiply(wBLS_Q, mdmdQ_Qcc.T).T 

346 me_Qcc += np.multiply(wBSL_Q, dmdQm_Qcc.T).T 

347 if 'C' in term: 

348 me_Qcc += np.multiply(wCLS_Q, mdmdQ_Qcc.T).T 

349 me_Qcc += np.multiply(wCSL_Q, dmdQm_Qcc.T).T 

350 

351 self.comm.sum(me_Qcc) 

352 return me_Qcc # unit e^2 Angstrom / eV / sqrt(amu) 

353 

354 def electronic_me_Qcc(self, omega, gamma): 

355 self.calculate_energies_and_modes() 

356 

357 approx = self.approximation.lower() 

358 assert self.combinations == 1 

359 Vel_Qcc = np.zeros((len(self.om_Q), 3, 3), dtype=complex) 

360 if approx == 'albrecht a' or approx == 'albrecht': 

361 Vel_Qcc += self.meA(omega, gamma) # e^2 Angstrom^2 / eV 

362 # divide through pre-factor 

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

364 Vel_Qcc *= np.where(self.vib01_Q > 0, 1.0 / self.vib01_Q, 0)[ 

365 :, None, None 

366 ] 

367 # -> e^2 Angstrom / eV / sqrt(amu) 

368 if approx == 'albrecht bc' or approx == 'albrecht': 

369 Vel_Qcc += self.meBC(omega, gamma) # e^2 Angstrom / eV / sqrt(amu) 

370 if approx == 'albrecht b': 

371 Vel_Qcc += self.meBC(omega, gamma, term='B') 

372 if approx == 'albrecht c': 

373 Vel_Qcc = self.meBC(omega, gamma, term='C') 

374 

375 Vel_Qcc *= u.Hartree * u.Bohr # e^2 Angstrom^2 / eV -> Angstrom^3 

376 

377 return Vel_Qcc # Angstrom^2 / sqrt(amu) 

378 

379 def me_Qcc(self, omega, gamma): 

380 """Full matrix element""" 

381 self.read() 

382 approx = self.approximation.lower() 

383 nv = len(self.om_v) 

384 V_vcc = np.zeros((nv, 3, 3), dtype=complex) 

385 if approx == 'albrecht a' or approx == 'albrecht': 

386 if self.combinations == 1: 

387 # e^2 Angstrom^2 / eV 

388 V_vcc += self.meA(omega, gamma)[self.skip :] 

389 else: 

390 V_vcc += self.meAmult(omega, gamma) 

391 if approx == 'albrecht bc' or approx == 'albrecht': 

392 if self.combinations == 1: 

393 vel_vcc = self.meBC(omega, gamma) 

394 V_vcc += vel_vcc * self.vib01_Q[:, None, None] 

395 else: 

396 vel_vcc = self.meBCmult(omega, gamma) 

397 V_vcc = 0 

398 elif approx == 'albrecht b': 

399 assert self.combinations == 1 

400 vel_vcc = self.meBC(omega, gamma, term='B') 

401 V_vcc = vel_vcc * self.vib01_Q[:, None, None] 

402 if approx == 'albrecht c': 

403 assert self.combinations == 1 

404 vel_vcc = self.meBC(omega, gamma, term='C') 

405 V_vcc = vel_vcc * self.vib01_Q[:, None, None] 

406 

407 return V_vcc # e^2 Angstrom^2 / eV 

408 

409 def summary( 

410 self, 

411 omega=0, 

412 gamma=0, 

413 method='standard', 

414 direction='central', 

415 log=sys.stdout, 

416 ): 

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

418 if self.combinations > 1: 

419 return self.extended_summary() 

420 

421 om_v = self.get_energies() 

422 intensities = self.get_absolute_intensities(omega, gamma)[self.skip :] 

423 

424 if isinstance(log, str): 

425 log = paropen(log, 'a') 

426 

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

428 parprint(' excitation at ' + str(omega) + ' eV', file=log) 

429 parprint(' gamma ' + str(gamma) + ' eV', file=log) 

430 parprint(' approximation:', self.approximation, file=log) 

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

432 parprint(' # meV cm^-1 [A^4/amu]', file=log) 

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

434 for n, e in enumerate(om_v): 

435 if e.imag != 0: 

436 c = 'i' 

437 e = e.imag 

438 else: 

439 c = ' ' 

440 e = e.real 

441 parprint( 

442 '%3d %6.1f %7.1f%s %9.1f' 

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

444 file=log, 

445 ) 

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

447 parprint( 

448 'Zero-point energy: %.3f eV' 

449 % self.vibrations.get_zero_point_energy(), 

450 file=log, 

451 ) 

452 

453 def extended_summary( 

454 self, 

455 omega=0, 

456 gamma=0, 

457 method='standard', 

458 direction='central', 

459 log=sys.stdout, 

460 ): 

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

462 self.read(method, direction) 

463 om_v = self.get_energies() 

464 intens_v = self.intensity(omega, gamma) 

465 

466 if isinstance(log, str): 

467 log = paropen(log, 'a') 

468 

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

470 parprint(' excitation at ' + str(omega) + ' eV', file=log) 

471 parprint(' gamma ' + str(gamma) + ' eV', file=log) 

472 parprint(' approximation:', self.approximation, file=log) 

473 parprint(' observation:', self.observation, file=log) 

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

475 parprint(' # meV cm^-1 [e^4A^4/eV^2]', file=log) 

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

477 for v, e in enumerate(om_v): 

478 parprint( 

479 self.ind_v[v], 

480 '{:6.1f} {:7.1f} {:9.1f}'.format( 

481 1000 * e, e / u.invcm, 1e9 * intens_v[v] 

482 ), 

483 file=log, 

484 ) 

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

486 parprint( 

487 'Zero-point energy: %.3f eV' 

488 % self.vibrations.get_zero_point_energy(), 

489 file=log, 

490 )