Coverage for ase/calculators/counterions.py: 96.72%

61 statements  

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

1import numpy as np 

2 

3from ase import units 

4from ase.calculators.calculator import Calculator 

5 

6k_c = units.Hartree * units.Bohr 

7 

8 

9class AtomicCounterIon(Calculator): 

10 implemented_properties = ['energy', 'forces'] 

11 

12 def __init__( 

13 self, charge, epsilon, sigma, sites_per_mol=1, rc=7.0, width=1.0 

14 ): 

15 """Counter Ion Calculator. 

16 

17 A very simple, nonbonded (Coulumb and LJ) 

18 interaction calculator meant for single atom ions 

19 to charge neutralize systems (and nothing else)... 

20 """ 

21 self.rc = rc 

22 self.width = width 

23 self.sites_per_mol = sites_per_mol 

24 self.epsilon = epsilon 

25 self.sigma = sigma 

26 self.charge = charge 

27 Calculator.__init__(self) 

28 

29 def add_virtual_sites(self, positions): 

30 return positions 

31 

32 def get_virtual_charges(self, atoms): 

33 charges = np.tile(self.charge, len(atoms) // self.sites_per_mol) 

34 return charges 

35 

36 def redistribute_forces(self, forces): 

37 return forces 

38 

39 def calculate(self, atoms, properties, system_changes): 

40 Calculator.calculate(self, atoms, properties, system_changes) 

41 

42 R = atoms.get_positions() 

43 charges = self.get_virtual_charges(atoms) 

44 pbc = atoms.pbc 

45 

46 energy = 0.0 

47 forces = np.zeros_like(atoms.get_positions()) 

48 

49 for m in range(len(atoms)): 

50 D = R[m + 1 :] - R[m] 

51 shift = np.zeros_like(D) 

52 for i, periodic in enumerate(pbc): 

53 if periodic: 

54 L = atoms.cell.diagonal()[i] 

55 shift[:, i] = (D[:, i] + L / 2) % L - L / 2 - D[:, i] 

56 D += shift 

57 d2 = (D**2).sum(1) 

58 d = d2**0.5 

59 

60 x1 = d > self.rc - self.width 

61 x2 = d < self.rc 

62 x12 = np.logical_and(x1, x2) 

63 y = (d[x12] - self.rc + self.width) / self.width 

64 t = np.zeros(len(d)) # cutoff function 

65 t[x2] = 1.0 

66 t[x12] -= y**2 * (3.0 - 2.0 * y) 

67 dtdd = np.zeros(len(d)) 

68 dtdd[x12] -= 6.0 / self.width * y * (1.0 - y) 

69 

70 c6 = (self.sigma**2 / d2) ** 3 

71 c12 = c6**2 

72 e_lj = 4 * self.epsilon * (c12 - c6) 

73 e_c = k_c * charges[m + 1 :] * charges[m] / d 

74 

75 energy += np.dot(t, e_lj) 

76 energy += np.dot(t, e_c) 

77 

78 F = (24 * self.epsilon * (2 * c12 - c6) / d2 * t - e_lj * dtdd / d)[ 

79 :, None 

80 ] * D 

81 

82 forces[m] -= F.sum(0) 

83 forces[m + 1 :] += F 

84 

85 F = (e_c / d2 * t)[:, None] * D - (e_c * dtdd / d)[:, None] * D 

86 

87 forces[m] -= F.sum(0) 

88 forces[m + 1 :] += F 

89 

90 self.results['energy'] = energy 

91 self.results['forces'] = forces