Coverage for ase/calculators/h2morse.py: 100.00%
125 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
1from itertools import count
3import numpy as np
5from ase import Atoms
6from ase.calculators.calculator import all_changes
7from ase.calculators.excitation_list import Excitation, ExcitationList
8from ase.calculators.morse import MorsePotential
9from ase.data import atomic_masses
10from ase.units import Ha, invcm
12"""The H2 molecule represented by Morse-Potentials for
13gound and first 3 excited singlet states B + C(doubly degenerate)"""
15npa = np.array
16# data from:
17# https://webbook.nist.gov/cgi/cbook.cgi?ID=C1333740&Mask=1000#Diatomic
18# X B C C
19Re = npa([0.74144, 1.2928, 1.0327, 1.0327]) # eq. bond length
20ome = npa([4401.21, 1358.09, 2443.77, 2443.77]) # vibrational frequency
21# electronic transition energy
22Etrans = npa([0, 91700.0, 100089.9, 100089.9]) * invcm
24# dissociation energy
25# GS: https://aip.scitation.org/doi/10.1063/1.3120443
26De = np.ones(4) * 36118.069 * invcm
27# B, C separated energy E(1s) - E(2p)
28De[1:] += Ha / 2 - Ha / 8
29De -= Etrans
31# Morse parameter
32m = atomic_masses[1] * 0.5 # reduced mass
33# XXX find scaling factor
34rho0 = Re * ome * invcm * np.sqrt(m / 2 / De) * 4401.21 / 284.55677429605862
37def H2Morse(state=0):
38 """Return H2 as a Morse-Potential with calculator attached."""
39 atoms = Atoms('H2', positions=np.zeros((2, 3)))
40 atoms[1].position[2] = Re[state]
41 atoms.calc = H2MorseCalculator(state=state)
42 atoms.get_potential_energy()
43 return atoms
46class H2MorseCalculator(MorsePotential):
47 """H2 ground or excited state as Morse potential"""
49 _count = count(0)
51 def __init__(self, restart=None, state=0, rng=np.random):
52 self.rng = rng
53 MorsePotential.__init__(
54 self,
55 restart=restart,
56 epsilon=De[state],
57 r0=Re[state],
58 rho0=rho0[state],
59 )
61 def calculate(
62 self, atoms=None, properties=None, system_changes=all_changes
63 ):
64 if properties is None:
65 properties = ['energy']
66 if atoms is not None:
67 assert len(atoms) == 2
68 MorsePotential.calculate(self, atoms, properties, system_changes)
70 # determine 'wave functions' including
71 # Berry phase (arbitrary sign) and
72 # random orientation of wave functions perpendicular
73 # to the molecular axis
75 # molecular axis
76 vr = atoms[1].position - atoms[0].position
77 r = np.linalg.norm(vr)
78 hr = vr / r
79 # perpendicular axes
80 vrand = self.rng.random(3)
81 hx = np.cross(hr, vrand)
82 hx /= np.linalg.norm(hx)
83 hy = np.cross(hr, hx)
84 hy /= np.linalg.norm(hy)
85 wfs = [1, hr, hx, hy]
86 # Berry phase
87 berry = (-1) ** self.rng.randint(0, 2, 4)
88 self.wfs = [wf * b for wf, b in zip(wfs, berry)]
90 def read(self, filename):
91 ms = self
92 with open(filename) as fd:
93 ms.wfs = [int(fd.readline().split()[0])]
94 for _ in range(1, 4):
95 ms.wfs.append(
96 np.array([float(x) for x in fd.readline().split()[:4]])
97 )
98 ms.filename = filename
99 return ms
101 def write(self, filename, option=None):
102 """write calculated state to a file"""
103 with open(filename, 'w') as fd:
104 fd.write(f'{self.wfs[0]}\n')
105 for wf in self.wfs[1:]:
106 fd.write('{:g} {:g} {:g}\n'.format(*wf))
108 def overlap(self, other):
109 ov = np.zeros((4, 4))
110 ov[0, 0] = self.wfs[0] * other.wfs[0]
111 wfs = np.array(self.wfs[1:])
112 owfs = np.array(other.wfs[1:])
113 ov[1:, 1:] = np.dot(wfs, owfs.T)
114 return ov
117class H2MorseExcitedStatesCalculator:
118 """First singlet excited states of H2 from Morse potentials"""
120 def __init__(self, nstates=3):
121 """
122 Parameters
123 ----------
124 nstates: int
125 Numer of states to calculate 0 < nstates < 4, default 3
126 """
127 assert nstates > 0 and nstates < 4
128 self.nstates = nstates
130 def calculate(self, atoms):
131 """Calculate excitation spectrum
133 Parameters
134 ----------
135 atoms: Ase atoms object
136 """
137 # central me value and rise, unit Bohr
138 # from DOI: 10.1021/acs.jctc.9b00584
139 mc = [0, 0.8, 0.7, 0.7]
140 mr = [0, 1.0, 0.5, 0.5]
142 cgs = atoms.calc
143 r = atoms.get_distance(0, 1)
144 E0 = cgs.get_potential_energy(atoms)
146 exl = H2MorseExcitedStates()
147 for i in range(1, self.nstates + 1):
148 hvec = cgs.wfs[0] * cgs.wfs[i]
149 energy = Ha * (0.5 - 1.0 / 8) - E0
150 calc = H2MorseCalculator(state=i)
151 calc.calculate(atoms)
152 energy += calc.get_potential_energy()
154 mur = hvec * (mc[i] + (r - Re[0]) * mr[i])
155 muv = mur
157 exl.append(H2Excitation(energy, i, mur, muv))
158 return exl
161class H2MorseExcitedStates(ExcitationList):
162 """First singlet excited states of H2"""
164 def __init__(self, nstates=3):
165 """
166 Parameters
167 ----------
168 nstates: int, 1 <= nstates <= 3
169 Number of excited states to consider, default 3
170 """
171 self.nstates = nstates
172 super().__init__()
174 def overlap(self, ov_nn, other):
175 return ov_nn[1 : len(self) + 1, 1 : len(self) + 1] * ov_nn[0, 0]
177 @classmethod
178 def read(cls, filename, nstates=3):
179 """Read myself from a file"""
180 exl = cls(nstates)
181 with open(filename) as fd:
182 exl.filename = filename
183 n = int(fd.readline().split()[0])
184 for _ in range(min(n, exl.nstates)):
185 exl.append(H2Excitation.fromstring(fd.readline()))
186 return exl
188 def write(self, fname):
189 with open(fname, 'w') as fd:
190 fd.write(f'{len(self)}\n')
191 for ex in self:
192 fd.write(ex.outstring())
195class H2Excitation(Excitation):
196 def __eq__(self, other):
197 """Considered to be equal when their indices are equal."""
198 return self.index == other.index
200 def __hash__(self):
201 """Hash similar to __eq__"""
202 if not hasattr(self, 'hash'):
203 self.hash = hash(self.index)
204 return self.hash
207class H2MorseExcitedStatesAndCalculator(
208 H2MorseExcitedStatesCalculator, H2MorseExcitedStates
209):
210 """Traditional joined object for backward compatibility only"""
212 def __init__(self, calculator, nstates=3):
213 if isinstance(calculator, str):
214 exlist = H2MorseExcitedStates.read(calculator, nstates)
215 else:
216 atoms = calculator.atoms
217 atoms.calc = calculator
218 excalc = H2MorseExcitedStatesCalculator(nstates)
219 exlist = excalc.calculate(atoms)
220 H2MorseExcitedStates.__init__(self, nstates=nstates)
221 for ex in exlist:
222 self.append(ex)