Coverage for ase/calculators/test.py: 89.34%
122 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 math import pi
3import numpy as np
5from ase.atoms import Atoms
6from ase.calculators.calculator import Calculator, kpts2ndarray
7from ase.calculators.fd import calculate_numerical_forces
8from ase.units import Bohr, Ha
11def make_test_dft_calculation():
12 a = b = 2.0
13 c = 6.0
14 atoms = Atoms(
15 positions=[(0, 0, c / 2)],
16 symbols='H',
17 pbc=(1, 1, 0),
18 cell=(a, b, c),
19 calculator=TestCalculator(),
20 )
21 return atoms
24class TestCalculator:
25 def __init__(self, nk=8):
26 assert nk % 2 == 0
27 bzk = []
28 weights = []
29 ibzk = []
30 w = 1.0 / nk**2
31 for i in range(-nk + 1, nk, 2):
32 for j in range(-nk + 1, nk, 2):
33 k = (0.5 * i / nk, 0.5 * j / nk, 0)
34 bzk.append(k)
35 if i >= j > 0:
36 ibzk.append(k)
37 if i == j:
38 weights.append(4 * w)
39 else:
40 weights.append(8 * w)
41 assert abs(sum(weights) - 1.0) < 1e-12
42 self.bzk = np.array(bzk)
43 self.ibzk = np.array(ibzk)
44 self.weights = np.array(weights)
46 # Calculate eigenvalues and wave functions:
47 self.init()
49 def init(self):
50 nibzk = len(self.weights)
51 nbands = 1
53 V = -1.0
54 self.eps = (
55 2
56 * V
57 * (
58 np.cos(2 * pi * self.ibzk[:, 0])
59 + np.cos(2 * pi * self.ibzk[:, 1])
60 )
61 ).reshape((nibzk, nbands))
63 self.psi = np.zeros((nibzk, 20, 20, 60), complex)
64 phi = np.empty((2, 2, 20, 20, 60))
65 z = np.linspace(-1.5, 1.5, 60, endpoint=False)
66 for i in range(2):
67 x = np.linspace(0, 1, 20, endpoint=False) - i
68 for j in range(2):
69 y = np.linspace(0, 1, 20, endpoint=False) - j
70 r = (((x[:, None] ** 2 + y**2)[:, :, None] + z**2) ** 0.5).clip(
71 0, 1
72 )
73 phi = 1.0 - r**2 * (3.0 - 2.0 * r)
74 phase = np.exp(pi * 2j * np.dot(self.ibzk, (i, j, 0)))
75 self.psi += phase[:, None, None, None] * phi
77 def get_pseudo_wave_function(self, band=0, kpt=0, spin=0):
78 assert spin == 0 and band == 0
79 return self.psi[kpt]
81 def get_eigenvalues(self, kpt=0, spin=0):
82 assert spin == 0
83 return self.eps[kpt]
85 def get_number_of_bands(self):
86 return 1
88 def get_k_point_weights(self):
89 return self.weights
91 def get_number_of_spins(self):
92 return 1
94 def get_fermi_level(self):
95 return 0.0
97 def get_pseudo_density(self):
98 n = 0.0
99 for w, eps, psi in zip(self.weights, self.eps[:, 0], self.psi):
100 if eps >= 0.0:
101 continue
102 n += w * (psi * psi.conj()).real
104 n[1:] += n[:0:-1].copy()
105 n[:, 1:] += n[:, :0:-1].copy()
106 n += n.transpose((1, 0, 2)).copy()
107 n /= 8
108 return n
111class TestPotential(Calculator):
112 implemented_properties = ['energy', 'forces']
114 def calculate(self, atoms, properties, system_changes):
115 Calculator.calculate(self, atoms, properties, system_changes)
116 E = 0.0
117 R = atoms.positions
118 F = np.zeros_like(R)
119 for a, r in enumerate(R):
120 D = R - r
121 d = (D**2).sum(1) ** 0.5
122 x = d - 1.0
123 E += np.vdot(x, x)
124 d[a] = 1
125 F -= (x / d)[:, None] * D
126 energy = 0.25 * E
127 self.results = {'energy': energy, 'forces': F}
130class FreeElectrons(Calculator):
131 """Free-electron band calculator.
133 Parameters
134 ----------
136 nvalence: int
137 Number of electrons
138 kpts: dict
139 K-point specification.
141 Example:
142 >>> from ase.calculators.test import FreeElectrons
143 >>> calc = FreeElectrons(nvalence=1, kpts={'path': 'GXL'})
144 """
146 implemented_properties = ['energy']
147 default_parameters = {
148 'kpts': np.zeros((1, 3)),
149 'nvalence': 0.0,
150 'nbands': 20,
151 'gridsize': 7,
152 }
154 def calculate(self, atoms, properties, system_changes):
155 Calculator.calculate(self, atoms)
156 self.kpts = kpts2ndarray(self.parameters.kpts, atoms)
157 icell = atoms.cell.reciprocal() * 2 * np.pi * Bohr
158 n = self.parameters.gridsize
159 offsets = np.indices((n, n, n)).T.reshape((n**3, 1, 3)) - n // 2
160 eps = 0.5 * (np.dot(self.kpts + offsets, icell) ** 2).sum(2).T
161 eps.sort()
162 self.eigenvalues = eps[:, : self.parameters.nbands] * Ha
163 self.results = {'energy': 0.0}
165 def get_eigenvalues(self, kpt, spin=0):
166 assert spin == 0
167 return self.eigenvalues[kpt].copy()
169 def get_fermi_level(self):
170 v = self.atoms.cell.complete().volume / Bohr**3
171 kF = (self.parameters.nvalence / v * 3 * np.pi**2) ** (1 / 3)
172 return 0.5 * kF**2 * Ha
174 def get_ibz_k_points(self):
175 return self.kpts.copy()
177 def get_number_of_spins(self):
178 return 1
181def gradient_test(atoms, indices=None):
182 """
183 Use numeric_force to compare analytical and numerical forces on atoms
185 If indices is None, test is done on all atoms.
186 """
187 if indices is None:
188 indices = range(len(atoms))
189 f = atoms.get_forces()[indices]
190 print('{:>16} {:>20}'.format('eps', 'max(abs(df))'))
191 for eps in np.logspace(-1, -8, 8):
192 fn = calculate_numerical_forces(atoms, eps, indices)
193 print(f'{eps:16.12f} {abs(fn - f).max():20.12f}')
194 return f, fn