Coverage for ase/vibrations/resonant_raman.py: 65.27%
311 statements
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
« prev ^ index » next coverage.py v7.16.2, created at 2026-11-27 15:21 +0000
1"""Resonant Raman intensities"""
3import sys
4from pathlib import Path
6import numpy as np
8import ase.units as u
9from ase.parallel import paropen, parprint, world
10from ase.vibrations import Vibrations
11from ase.vibrations.raman import Raman, RamanCalculatorBase
14class ResonantRamanCalculator(RamanCalculatorBase, Vibrations):
15 """Base class for resonant Raman calculators using finite differences."""
17 def __init__(
18 self,
19 atoms,
20 ExcitationsCalculator,
21 *args,
22 exkwargs=None,
23 exext='.ex.gz',
24 overlap=False,
25 **kwargs,
26 ):
27 """
28 Parameters
29 ----------
30 atoms: Atoms
31 The Atoms object
32 ExcitationsCalculator: object
33 Calculator for excited states
34 exkwargs: dict
35 Arguments given to the ExcitationsCalculator object
36 exext: string
37 Extension for filenames of Excitation lists (results of
38 the ExcitationsCalculator).
39 overlap : function or False
40 Function to calculate overlaps between excitation at
41 equilibrium and at a displaced position. Calculators are
42 given as first and second argument, respectively.
44 Example
45 -------
47 >>> from ase.calculators.h2morse import (H2Morse,
48 ... H2MorseExcitedStatesCalculator)
49 >>> from ase.vibrations.resonant_raman import ResonantRamanCalculator
50 >>>
51 >>> atoms = H2Morse()
52 >>> rmc = ResonantRamanCalculator(atoms, H2MorseExcitedStatesCalculator)
53 >>> rmc.run()
55 This produces all necessary data for further analysis.
56 """
57 self.exobj = ExcitationsCalculator
58 if exkwargs is None:
59 exkwargs = {}
60 self.exkwargs = exkwargs
61 self.overlap = overlap
63 super().__init__(atoms, *args, exext=exext, **kwargs)
65 def _new_exobj(self):
66 # XXXX I have to duplicate this because there are two objects
67 # which have exkwargs, why are they not unified?
68 return self.exobj(**self.exkwargs)
70 def calculate(self, atoms, disp):
71 """Call ground and excited state calculation"""
72 assert atoms == self.atoms # XXX action required
73 forces = self.atoms.get_forces()
75 if self.overlap:
76 """Overlap is determined as
78 ov_ij = int dr displaced*_i(r) eqilibrium_j(r)
79 """
80 ov_nn = self.overlap(self.atoms.calc, self.eq_calculator)
81 if world.rank == 0:
82 disp.save_ov_nn(ov_nn)
84 disp.calculate_and_save_exlist(atoms)
85 return {'forces': forces}
87 def run(self):
88 if self.overlap:
89 # XXXX stupid way to make a copy
90 self.atoms.get_potential_energy()
91 self.eq_calculator = self.atoms.calc
92 Path(self.name).mkdir(parents=True, exist_ok=True)
93 fname = Path(self.name) / 'tmp.gpw'
94 self.eq_calculator.write(fname, 'all')
95 self.eq_calculator = self.eq_calculator.__class__(restart=fname)
96 try:
97 # XXX GPAW specific
98 self.eq_calculator.converge_wave_functions()
99 except AttributeError:
100 pass
101 Vibrations.run(self)
104class ResonantRaman(Raman):
105 """Base Class for resonant Raman intensities using finite differences."""
107 def __init__(
108 self,
109 atoms,
110 Excitations,
111 *args,
112 observation=None,
113 form='v', # form of the dipole operator
114 exkwargs=None, # kwargs to be passed to Excitations
115 exext='.ex.gz', # extension for Excitation names
116 overlap=False,
117 minoverlap=0.02,
118 minrep=0.8,
119 comm=world,
120 **kwargs,
121 ):
122 """
123 Parameters
124 ----------
125 atoms: ase Atoms object
126 Excitations: class
127 Type of the excitation list object. The class object is
128 initialized as::
130 Excitations(atoms.calc)
132 or by reading form a file as::
134 Excitations('filename', **exkwargs)
136 The file is written by calling the method
137 Excitations.write('filename').
139 Excitations should work like a list of ex obejects, where:
140 ex.get_dipole_me(form='v'):
141 gives the velocity form dipole matrix element in
142 units |e| * Angstrom
143 ex.energy:
144 is the transition energy in Hartrees
145 approximation: string
146 Level of approximation used.
147 observation: dict
148 Polarization settings
149 form: string
150 Form of the dipole operator, 'v' for velocity form (default)
151 and 'r' for length form.
152 overlap: bool or function
153 Use wavefunction overlaps.
154 minoverlap: float ord dict
155 Minimal absolute overlap to consider. Defaults to 0.02 to avoid
156 numerical garbage.
157 minrep: float
158 Minimal representation to consider derivative, defaults to 0.8
159 """
161 if observation is None:
162 observation = {'geometry': '-Z(XX)Z'}
164 kwargs['exext'] = exext
165 Raman.__init__(self, atoms, *args, **kwargs)
166 assert self.vibrations.nfree == 2
168 self.exobj = Excitations
169 if exkwargs is None:
170 exkwargs = {}
171 self.exkwargs = exkwargs
172 self.observation = observation
173 self.dipole_form = form
175 self.overlap = overlap
176 if not isinstance(minoverlap, dict):
177 # assume it's a number
178 self.minoverlap = {
179 'orbitals': minoverlap,
180 'excitations': minoverlap,
181 }
182 else:
183 self.minoverlap = minoverlap
184 self.minrep = minrep
186 def read_exobj(self, filename):
187 return self.exobj.read(filename, **self.exkwargs)
189 def get_absolute_intensities(self, omega, gamma=0.1, delta=0, **kwargs):
190 """Absolute Raman intensity or Raman scattering factor
192 Parameter
193 ---------
194 omega: float
195 incoming laser energy, unit eV
196 gamma: float
197 width (imaginary energy), unit eV
198 delta: float
199 pre-factor for asymmetric anisotropy, default 0
201 References
202 ----------
203 Porezag and Pederson, PRB 54 (1996) 7830-7836 (delta=0)
204 Baiardi and Barone, JCTC 11 (2015) 3267-3280 (delta=5)
206 Returns
207 -------
208 raman intensity, unit Ang**4/amu
209 """
210 alpha2_r, gamma2_r, delta2_r = self._invariants(
211 self.electronic_me_Qcc(omega, gamma, **kwargs)
212 )
213 return 45 * alpha2_r + delta * delta2_r + 7 * gamma2_r
215 @property
216 def approximation(self):
217 return self._approx
219 @approximation.setter
220 def approximation(self, value):
221 self.set_approximation(value)
223 def read_excitations(self):
224 """Read all finite difference excitations and select matching."""
225 if self.overlap:
226 return self.read_excitations_overlap()
228 disp = self._eq_disp()
229 ex0_object = disp.read_exobj()
230 eu = ex0_object.energy_to_eV_scale
231 matching = frozenset(ex0_object)
233 def append(lst, disp, matching):
234 exo = disp.read_exobj()
235 lst.append(exo)
236 matching = matching.intersection(exo)
237 return matching
239 exm_object_list = []
240 exp_object_list = []
241 for a, i in zip(self.myindices, self.myxyz):
242 mdisp = self._disp(a, i, -1)
243 pdisp = self._disp(a, i, 1)
244 matching = append(exm_object_list, mdisp, matching)
245 matching = append(exp_object_list, pdisp, matching)
247 def select(exl, matching):
248 mlst = [ex for ex in exl if ex in matching]
249 assert len(mlst) == len(matching)
250 return mlst
252 ex0 = select(ex0_object, matching)
253 exm = []
254 exp = []
255 r = 0
256 for a, i in zip(self.myindices, self.myxyz):
257 exm.append(select(exm_object_list[r], matching))
258 exp.append(select(exp_object_list[r], matching))
259 r += 1
261 self.ex0E_p = np.array([ex.energy * eu for ex in ex0])
262 self.ex0m_pc = (
263 np.array([ex.get_dipole_me(form=self.dipole_form) for ex in ex0])
264 * u.Bohr
265 )
266 exmE_rp = []
267 expE_rp = []
268 exF_rp = []
269 exmm_rpc = []
270 expm_rpc = []
271 r = 0
272 for a, i in zip(self.myindices, self.myxyz):
273 exmE_rp.append([em.energy for em in exm[r]])
274 expE_rp.append([ep.energy for ep in exp[r]])
275 exF_rp.append(
276 [(em.energy - ep.energy) for ep, em in zip(exp[r], exm[r])]
277 )
278 exmm_rpc.append(
279 [ex.get_dipole_me(form=self.dipole_form) for ex in exm[r]]
280 )
281 expm_rpc.append(
282 [ex.get_dipole_me(form=self.dipole_form) for ex in exp[r]]
283 )
284 r += 1
285 # indicees: r=coordinate, p=excitation
286 # energies in eV
287 self.exmE_rp = np.array(exmE_rp) * eu
288 self.expE_rp = np.array(expE_rp) * eu
289 # forces in eV / Angstrom
290 self.exF_rp = np.array(exF_rp) * eu / 2 / self.delta
291 # matrix elements in e * Angstrom
292 self.exmm_rpc = np.array(exmm_rpc) * u.Bohr
293 self.expm_rpc = np.array(expm_rpc) * u.Bohr
295 def read_excitations_overlap(self):
296 """Read all finite difference excitations and wf overlaps.
298 We assume that the wave function overlaps are determined as
300 ov_ij = int dr displaced*_i(r) eqilibrium_j(r)
301 """
302 ex0 = self._eq_disp().read_exobj()
303 eu = ex0.energy_to_eV_scale
304 rep0_p = np.ones((len(ex0)), dtype=float)
306 def load(disp, rep0_p):
307 ex_p = disp.read_exobj()
308 ov_nn = disp.load_ov_nn()
309 # remove numerical garbage
310 ov_nn = np.where(
311 np.abs(ov_nn) > self.minoverlap['orbitals'], ov_nn, 0
312 )
313 ov_pp = ex_p.overlap(ov_nn, ex0)
314 ov_pp = np.where(
315 np.abs(ov_pp) > self.minoverlap['excitations'], ov_pp, 0
316 )
317 rep0_p *= (ov_pp.real**2 + ov_pp.imag**2).sum(axis=0)
318 return ex_p, ov_pp
320 def rotate(ex_p, ov_pp):
321 e_p = np.array([ex.energy for ex in ex_p])
322 m_pc = np.array(
323 [ex.get_dipole_me(form=self.dipole_form) for ex in ex_p]
324 )
325 r_pp = ov_pp.T
326 return ((r_pp.real**2 + r_pp.imag**2).dot(e_p), r_pp.dot(m_pc))
328 exmE_rp = []
329 expE_rp = []
330 exF_rp = []
331 exmm_rpc = []
332 expm_rpc = []
333 exdmdr_rpc = []
334 for a, i in zip(self.myindices, self.myxyz):
335 mdisp = self._disp(a, i, -1)
336 pdisp = self._disp(a, i, 1)
337 ex, ov = load(mdisp, rep0_p)
338 exmE_p, exmm_pc = rotate(ex, ov)
339 ex, ov = load(pdisp, rep0_p)
340 expE_p, expm_pc = rotate(ex, ov)
341 exmE_rp.append(exmE_p)
342 expE_rp.append(expE_p)
343 exF_rp.append(exmE_p - expE_p)
344 exmm_rpc.append(exmm_pc)
345 expm_rpc.append(expm_pc)
346 exdmdr_rpc.append(expm_pc - exmm_pc)
348 # select only excitations that are sufficiently represented
349 self.comm.product(rep0_p)
350 select = np.where(rep0_p > self.minrep)[0]
352 self.ex0E_p = np.array([ex.energy * eu for ex in ex0])[select]
353 self.ex0m_pc = (
354 np.array([ex.get_dipole_me(form=self.dipole_form) for ex in ex0])[
355 select
356 ]
357 * u.Bohr
358 )
360 if len(self.myr):
361 # indicees: r=coordinate, p=excitation
362 # energies in eV
363 self.exmE_rp = np.array(exmE_rp)[:, select] * eu
364 self.expE_rp = np.array(expE_rp)[:, select] * eu
365 # forces in eV / Angstrom
366 self.exF_rp = np.array(exF_rp)[:, select] * eu / 2 / self.delta
367 # matrix elements in e * Angstrom
368 self.exmm_rpc = np.array(exmm_rpc)[:, select, :] * u.Bohr
369 self.expm_rpc = np.array(expm_rpc)[:, select, :] * u.Bohr
370 # matrix element derivatives in e
371 self.exdmdr_rpc = (
372 np.array(exdmdr_rpc)[:, select, :] * u.Bohr / 2 / self.delta
373 )
374 else:
375 # did not read
376 self.exmE_rp = self.expE_rp = self.exF_rp = np.empty(0)
377 self.exmm_rpc = self.expm_rpc = self.exdmdr_rpc = np.empty(0)
379 def read(self, *args, **kwargs):
380 """Read data from a pre-performed calculation."""
381 self.vibrations.read(*args, **kwargs)
382 self.init_parallel_read()
383 if not hasattr(self, 'ex0E_p'):
384 if self.overlap:
385 self.read_excitations_overlap()
386 else:
387 self.read_excitations()
389 self._already_read = True
391 def get_cross_sections(self, omega, gamma):
392 """Returns Raman cross sections for each vibration."""
393 I_v = self.intensity(omega, gamma)
394 pre = 1.0 / 16 / np.pi**2 / u._eps0**2 / u._c**4
395 # frequency of scattered light
396 omS_v = omega - self.om_Q
397 return pre * omega * omS_v**3 * I_v
399 def get_spectrum(
400 self,
401 omega,
402 gamma=0.1,
403 start=None,
404 end=None,
405 npts=None,
406 width=20,
407 type='Gaussian',
408 intensity_unit='????',
409 normalize=False,
410 ):
411 """Get resonant Raman spectrum.
413 The method returns wavenumbers in cm^-1 with corresponding
414 Raman cross section.
415 Start and end point, and width of the Gaussian/Lorentzian should
416 be given in cm^-1.
417 """
419 self.type = type.lower()
420 assert self.type in ['gaussian', 'lorentzian']
422 frequencies = self.get_energies().real / u.invcm
423 intensities = self.get_cross_sections(omega, gamma)
424 if width is None:
425 return [frequencies, intensities]
427 if start is None:
428 start = min(self.om_Q) / u.invcm - 3 * width
429 if end is None:
430 end = max(self.om_Q) / u.invcm + 3 * width
432 if not npts:
433 npts = int((end - start) / width * 10 + 1)
435 prefactor = 1
436 if self.type == 'lorentzian':
437 intensities = intensities * width * np.pi / 2.0
438 if normalize:
439 prefactor = 2.0 / width / np.pi
440 else:
441 sigma = width / 2.0 / np.sqrt(2.0 * np.log(2.0))
442 if normalize:
443 prefactor = 1.0 / sigma / np.sqrt(2 * np.pi)
444 # Make array with spectrum data
445 spectrum = np.empty(npts)
446 energies = np.linspace(start, end, npts)
447 for i, energy in enumerate(energies):
448 energies[i] = energy
449 if self.type == 'lorentzian':
450 spectrum[i] = (
451 intensities
452 * 0.5
453 * width
454 / np.pi
455 / ((frequencies - energy) ** 2 + 0.25 * width**2)
456 ).sum()
457 else:
458 spectrum[i] = (
459 intensities
460 * np.exp(-((frequencies - energy) ** 2) / 2.0 / sigma**2)
461 ).sum()
462 return [energies, prefactor * spectrum]
464 def write_spectrum(
465 self,
466 omega,
467 gamma,
468 out='resonant-raman-spectra.dat',
469 start=200,
470 end=4000,
471 npts=None,
472 width=10,
473 type='Gaussian',
474 ):
475 """Write out spectrum to file.
477 Start and end
478 point, and width of the Gaussian/Lorentzian should be given
479 in cm^-1."""
480 energies, spectrum = self.get_spectrum(
481 omega, gamma, start, end, npts, width, type
482 )
484 # Write out spectrum in file. First column is absolute intensities.
485 outdata = np.empty([len(energies), 3])
486 outdata.T[0] = energies
487 outdata.T[1] = spectrum
489 with paropen(out, 'w') as fd:
490 fd.write('# Resonant Raman spectrum\n')
491 if hasattr(self, '_approx'):
492 fd.write(f'# approximation: {self._approx}\n')
493 for key in self.observation:
494 fd.write(f'# {key}: {self.observation[key]}\n')
495 fd.write('# omega={:g} eV, gamma={:g} eV\n'.format(omega, gamma))
496 if width is not None:
497 fd.write(
498 '# %s folded, width=%g cm^-1\n' % (type.title(), width)
499 )
500 fd.write('# [cm^-1] [a.u.]\n')
502 for row in outdata:
503 fd.write('%.3f %15.5g\n' % (row[0], row[1]))
505 def summary(
506 self,
507 omega,
508 gamma=0.1,
509 method='standard',
510 direction='central',
511 log=sys.stdout,
512 ):
513 """Print summary for given omega [eV]"""
514 self.read(method, direction)
515 hnu = self.get_energies()
516 intensities = self.get_absolute_intensities(omega, gamma)
517 te = int(np.log10(intensities.max())) - 2
518 scale = 10 ** (-te)
519 if not te:
520 ts = ''
521 elif te > -2 and te < 3:
522 ts = str(10**te)
523 else:
524 ts = f'10^{te}'
526 if isinstance(log, str):
527 log = paropen(log, 'a')
529 parprint('-------------------------------------', file=log)
530 parprint(' excitation at ' + str(omega) + ' eV', file=log)
531 parprint(' gamma ' + str(gamma) + ' eV', file=log)
532 parprint(' method:', self.vibrations.method, file=log)
533 parprint(' approximation:', self.approximation, file=log)
534 parprint(' Mode Frequency Intensity', file=log)
535 parprint(f' # meV cm^-1 [{ts}A^4/amu]', file=log)
536 parprint('-------------------------------------', file=log)
537 for n, e in enumerate(hnu):
538 if e.imag != 0:
539 c = 'i'
540 e = e.imag
541 else:
542 c = ' '
543 e = e.real
544 parprint(
545 '%3d %6.1f%s %7.1f%s %9.2f'
546 % (n, 1000 * e, c, e / u.invcm, c, intensities[n] * scale),
547 file=log,
548 )
549 parprint('-------------------------------------', file=log)
550 parprint(
551 'Zero-point energy: %.3f eV'
552 % self.vibrations.get_zero_point_energy(),
553 file=log,
554 )
557class LrResonantRaman(ResonantRaman):
558 """Resonant Raman for linear response
560 Quick and dirty approach to enable loading of LrTDDFT calculations
561 """
563 def read_excitations(self):
564 eq_disp = self._eq_disp()
565 ex0_object = eq_disp.read_exobj()
566 eu = ex0_object.energy_to_eV_scale
567 matching = frozenset(ex0_object.kss)
569 def append(lst, disp, matching):
570 exo = disp.read_exobj()
571 lst.append(exo)
572 matching = matching.intersection(exo.kss)
573 return matching
575 exm_object_list = []
576 exp_object_list = []
577 for a in self.indices:
578 for i in 'xyz':
579 disp1 = self._disp(a, i, -1)
580 disp2 = self._disp(a, i, 1)
582 matching = append(exm_object_list, disp1, matching)
583 matching = append(exp_object_list, disp2, matching)
585 def select(exl, matching):
586 exl.diagonalize(**self.exkwargs)
587 mlist = list(exl)
588 # mlst = [ex for ex in exl if ex in matching]
589 # assert(len(mlst) == len(matching))
590 return mlist
592 ex0 = select(ex0_object, matching)
593 exm = []
594 exp = []
595 r = 0
596 for a in self.indices:
597 for i in 'xyz':
598 exm.append(select(exm_object_list[r], matching))
599 exp.append(select(exp_object_list[r], matching))
600 r += 1
602 self.ex0E_p = np.array([ex.energy * eu for ex in ex0])
603 # self.exmE_p = np.array([ex.energy * eu for ex in exm])
604 # self.expE_p = np.array([ex.energy * eu for ex in exp])
605 self.ex0m_pc = (
606 np.array([ex.get_dipole_me(form=self.dipole_form) for ex in ex0])
607 * u.Bohr
608 )
609 self.exF_rp = []
610 exmE_rp = []
611 expE_rp = []
612 exmm_rpc = []
613 expm_rpc = []
614 r = 0
615 for a in self.indices:
616 for i in 'xyz':
617 exmE_rp.append([em.energy for em in exm[r]])
618 expE_rp.append([ep.energy for ep in exp[r]])
619 self.exF_rp.append(
620 [(em.energy - ep.energy) for ep, em in zip(exp[r], exm[r])]
621 )
622 exmm_rpc.append(
623 [ex.get_dipole_me(form=self.dipole_form) for ex in exm[r]]
624 )
625 expm_rpc.append(
626 [ex.get_dipole_me(form=self.dipole_form) for ex in exp[r]]
627 )
628 r += 1
629 self.exmE_rp = np.array(exmE_rp) * eu
630 self.expE_rp = np.array(expE_rp) * eu
631 self.exF_rp = np.array(self.exF_rp) * eu / 2 / self.delta
632 self.exmm_rpc = np.array(exmm_rpc) * u.Bohr
633 self.expm_rpc = np.array(expm_rpc) * u.Bohr