Coverage for ase/calculators/combine_mm.py: 87.92%
207 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
1import copy
3import numpy as np
5from ase import units
6from ase.calculators.calculator import Calculator
7from ase.calculators.qmmm import combine_lj_lorenz_berthelot
9k_c = units.Hartree * units.Bohr
12class CombineMM(Calculator):
13 implemented_properties = ['energy', 'forces']
15 def __init__(
16 self,
17 idx,
18 apm1,
19 apm2,
20 calc1,
21 calc2,
22 sig1,
23 eps1,
24 sig2,
25 eps2,
26 rc=7.0,
27 width=1.0,
28 ):
29 """A calculator that combines two MM calculators
30 (TIPnP, Counterions, ...)
32 parameters
33 ----------
35 idx: List of indices of atoms belonging to calculator 1
36 apm1,2: atoms pr molecule of each subsystem (NB: apm for TIP4P is 3!)
37 calc1,2: calculator objects for each subsystem
38 sig1,2, eps1,2: LJ parameters for each subsystem. Should be a numpy
39 array of length = apm
40 rc = long range cutoff
41 width = width of cutoff region.
43 Currently the interactions are limited to being:
44 - Nonbonded
45 - Hardcoded to two terms:
46 - Coulomb electrostatics
47 - Lennard-Jones
49 It could of course benefit from being more like the EIQMMM class
50 where the interactions are switchable. But this is in princple
51 just meant for adding counter ions to a qmmm simulation to neutralize
52 the charge of the total systemn
54 Maybe it can combine n MM calculators in the future?
55 """
57 self.idx = idx
58 self.apm1 = apm1 # atoms per mol for LJ calculator
59 self.apm2 = apm2
61 self.rc = rc
62 self.width = width
64 self.atoms1 = None
65 self.atoms2 = None
66 self.mask = None
68 self.calc1 = calc1
69 self.calc2 = calc2
71 self.sig1 = sig1
72 self.eps1 = eps1
73 self.sig2 = sig2
74 self.eps2 = eps2
76 Calculator.__init__(self)
78 def initialize(self, atoms):
79 self.mask = np.zeros(len(atoms), bool)
80 self.mask[self.idx] = True
82 constraints = atoms.constraints
83 atoms.constraints = []
84 self.atoms1 = atoms[self.mask]
85 self.atoms2 = atoms[~self.mask]
87 atoms.constraints = constraints
89 self.atoms1.calc = self.calc1
90 self.atoms2.calc = self.calc2
92 self.cell = atoms.cell
93 self.pbc = atoms.pbc
95 self.sigma, self.epsilon = combine_lj_lorenz_berthelot(
96 self.sig1, self.sig2, self.eps1, self.eps2
97 )
99 self.make_virtual_mask()
101 def calculate(self, atoms, properties, system_changes):
102 Calculator.calculate(self, atoms, properties, system_changes)
104 if self.atoms1 is None:
105 self.initialize(atoms)
107 pos1 = atoms.positions[self.mask]
108 pos2 = atoms.positions[~self.mask]
109 self.atoms1.set_positions(pos1)
110 self.atoms2.set_positions(pos2)
112 # positions and charges for the coupling term, which should
113 # include virtual charges and sites:
114 spm1 = self.atoms1.calc.sites_per_mol
115 spm2 = self.atoms2.calc.sites_per_mol
116 xpos1 = self.atoms1.calc.add_virtual_sites(pos1)
117 xpos2 = self.atoms2.calc.add_virtual_sites(pos2)
119 xc1 = self.atoms1.calc.get_virtual_charges(self.atoms1)
120 xc2 = self.atoms2.calc.get_virtual_charges(self.atoms2)
122 xpos1 = xpos1.reshape((-1, spm1, 3))
123 xpos2 = xpos2.reshape((-1, spm2, 3))
125 e_c, f_c = self.coulomb(xpos1, xpos2, xc1, xc2, spm1, spm2)
127 e_lj, f1, f2 = self.lennard_jones(self.atoms1, self.atoms2)
129 f_lj = np.zeros((len(atoms), 3))
130 f_lj[self.mask] += f1
131 f_lj[~self.mask] += f2
133 # internal energy, forces of each subsystem:
134 f12 = np.zeros((len(atoms), 3))
135 e1 = self.atoms1.get_potential_energy()
136 fi1 = self.atoms1.get_forces()
138 e2 = self.atoms2.get_potential_energy()
139 fi2 = self.atoms2.get_forces()
141 f12[self.mask] += fi1
142 f12[~self.mask] += fi2
144 self.results['energy'] = e_c + e_lj + e1 + e2
145 self.results['forces'] = f_c + f_lj + f12
147 def get_virtual_charges(self, atoms):
148 if self.atoms1 is None:
149 self.initialize(atoms)
151 vc1 = self.atoms1.calc.get_virtual_charges(atoms[self.mask])
152 vc2 = self.atoms2.calc.get_virtual_charges(atoms[~self.mask])
153 # Need to expand mask with possible new virtual sites.
154 # Virtual sites should ALWAYS be put AFTER actual atoms, like in
155 # TIP4P: OHHX, OHHX, ...
157 vc = np.zeros(len(vc1) + len(vc2))
158 vc[self.virtual_mask] = vc1
159 vc[~self.virtual_mask] = vc2
161 return vc
163 def add_virtual_sites(self, positions):
164 vs1 = self.atoms1.calc.add_virtual_sites(positions[self.mask])
165 vs2 = self.atoms2.calc.add_virtual_sites(positions[~self.mask])
166 vs = np.zeros((len(vs1) + len(vs2), 3))
168 vs[self.virtual_mask] = vs1
169 vs[~self.virtual_mask] = vs2
171 return vs
173 def make_virtual_mask(self):
174 virtual_mask = []
175 ct1 = 0
176 ct2 = 0
177 for i in range(len(self.mask)):
178 virtual_mask.append(self.mask[i])
179 if self.mask[i]:
180 ct1 += 1
181 if not self.mask[i]:
182 ct2 += 1
183 if (ct2 == self.apm2) & (
184 self.apm2 != self.atoms2.calc.sites_per_mol
185 ):
186 virtual_mask.append(False)
187 ct2 = 0
188 if (ct1 == self.apm1) & (
189 self.apm1 != self.atoms1.calc.sites_per_mol
190 ):
191 virtual_mask.append(True)
192 ct1 = 0
194 self.virtual_mask = np.array(virtual_mask)
196 def coulomb(self, xpos1, xpos2, xc1, xc2, spm1, spm2):
197 energy = 0.0
198 forces = np.zeros((len(xc1) + len(xc2), 3))
200 self.xpos1 = xpos1
201 self.xpos2 = xpos2
203 R1 = xpos1
204 R2 = xpos2
205 F1 = np.zeros_like(R1)
206 F2 = np.zeros_like(R2)
207 C1 = xc1.reshape((-1, np.shape(xpos1)[1]))
208 C2 = xc2.reshape((-1, np.shape(xpos2)[1]))
209 # Vectorized evaluation is not as trivial when spm1 != spm2.
210 # This is pretty inefficient, but for ~1-5 counter ions as region 1
211 # it should not matter much ..
212 # There is definitely room for improvements here.
213 cell = self.cell.diagonal()
214 for m1, (r1, c1) in enumerate(zip(R1, C1)):
215 for m2, (r2, c2) in enumerate(zip(R2, C2)):
216 r00 = r2[0] - r1[0]
217 shift = np.zeros(3)
218 for i, periodic in enumerate(self.pbc):
219 if periodic:
220 L = cell[i]
221 shift[i] = (r00[i] + L / 2.0) % L - L / 2.0 - r00[i]
222 r00 += shift
224 d00 = (r00**2).sum() ** 0.5
225 t = 1
226 dtdd = 0
227 if d00 > self.rc:
228 continue
229 elif d00 > self.rc - self.width:
230 y = (d00 - self.rc + self.width) / self.width
231 t -= y**2 * (3.0 - 2.0 * y)
232 dtdd = r00 * 6 * y * (1.0 - y) / (self.width * d00)
234 for a1 in range(spm1):
235 for a2 in range(spm2):
236 r = r2[a2] - r1[a1] + shift
237 d2 = (r**2).sum()
238 d = d2**0.5
239 e = k_c * c1[a1] * c2[a2] / d
240 energy += t * e
242 F1[m1, a1] -= t * (e / d2) * r
243 F2[m2, a2] += t * (e / d2) * r
245 F1[m1, 0] -= dtdd * e
246 F2[m2, 0] += dtdd * e
248 F1 = F1.reshape((-1, 3))
249 F2 = F2.reshape((-1, 3))
251 # Redist forces but dont save forces in org calculators
252 atoms1 = self.atoms1.copy()
253 atoms1.calc = copy.copy(self.calc1)
254 atoms1.calc.atoms = atoms1
255 F1 = atoms1.calc.redistribute_forces(F1)
256 atoms2 = self.atoms2.copy()
257 atoms2.calc = copy.copy(self.calc2)
258 atoms2.calc.atoms = atoms2
259 F2 = atoms2.calc.redistribute_forces(F2)
261 forces = np.zeros((len(self.atoms), 3))
262 forces[self.mask] = F1
263 forces[~self.mask] = F2
264 return energy, forces
266 def lennard_jones(self, atoms1, atoms2):
267 pos1 = atoms1.get_positions().reshape((-1, self.apm1, 3))
268 pos2 = atoms2.get_positions().reshape((-1, self.apm2, 3))
270 f1 = np.zeros_like(atoms1.positions)
271 f2 = np.zeros_like(atoms2.positions)
272 energy = 0.0
274 cell = self.cell.diagonal()
275 for q, p1 in enumerate(pos1): # molwise loop
276 eps = self.epsilon
277 sig = self.sigma
279 R00 = pos2[:, 0] - p1[0, :]
281 # cutoff from first atom of each mol
282 shift = np.zeros_like(R00)
283 for i, periodic in enumerate(self.pbc):
284 if periodic:
285 L = cell[i]
286 shift[:, i] = (R00[:, i] + L / 2) % L - L / 2 - R00[:, i]
287 R00 += shift
289 d002 = (R00**2).sum(1)
290 d00 = d002**0.5
291 x1 = d00 > self.rc - self.width
292 x2 = d00 < self.rc
293 x12 = np.logical_and(x1, x2)
294 y = (d00[x12] - self.rc + self.width) / self.width
295 t = np.zeros(len(d00))
296 t[x2] = 1.0
297 t[x12] -= y**2 * (3.0 - 2.0 * y)
298 dt = np.zeros(len(d00))
299 dt[x12] -= 6.0 / self.width * y * (1.0 - y)
300 for qa in range(len(p1)):
301 if ~np.any(eps[qa, :]):
302 continue
303 R = pos2 - p1[qa, :] + shift[:, None]
304 d2 = (R**2).sum(2)
305 c6 = (sig[qa, :] ** 2 / d2) ** 3
306 c12 = c6**2
307 e = 4 * eps[qa, :] * (c12 - c6)
308 energy += np.dot(e.sum(1), t)
309 f = (
310 t[:, None, None]
311 * (24 * eps[qa, :] * (2 * c12 - c6) / d2)[:, :, None]
312 * R
313 )
314 f00 = -(e.sum(1) * dt / d00)[:, None] * R00
315 f2 += f.reshape((-1, 3))
316 f1[q * self.apm1 + qa, :] -= f.sum(0).sum(0)
317 f1[q * self.apm1, :] -= f00.sum(0)
318 f2[:: self.apm2, :] += f00
320 return energy, f1, f2
322 def redistribute_forces(self, forces):
323 f1 = self.calc1.redistribute_forces(forces[self.virtual_mask])
324 f2 = self.calc2.redistribute_forces(forces[~self.virtual_mask])
325 # and then they are back on the real atom centers so
326 f = np.zeros((len(self.atoms), 3))
327 f[self.mask] = f1
328 f[~self.mask] = f2
329 return f