Coverage for ase/dft/stm.py: 82.93%
164 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 numpy as np
3from ase.io.jsonio import read_json, write_json
6class STM:
7 def __init__(self, atoms, symmetries=None, use_density=False):
8 """Scanning tunneling microscope.
10 atoms: Atoms object or filename
11 Atoms to scan or name of file to read LDOS from.
12 symmetries: list of int
13 List of integers 0, 1, and/or 2 indicating which surface
14 symmetries have been used to reduce the number of k-points
15 for the DFT calculation. The three integers correspond to
16 the following three symmetry operations::
18 [-1 0] [ 1 0] [ 0 1]
19 [ 0 1] [ 0 -1] [ 1 0]
21 use_density: bool
22 Use the electron density instead of the LDOS.
23 """
25 self.use_density = use_density
27 if isinstance(atoms, str):
28 with open(atoms) as fd:
29 self.ldos, self.bias, self.cell = read_json(
30 fd, always_array=False
31 )
32 self.atoms = None
33 else:
34 self.atoms = atoms
35 self.cell = atoms.cell
36 self.bias = None
37 self.ldos = None
38 assert not self.cell[2, :2].any() and not self.cell[:2, 2].any()
40 self.symmetries = symmetries or []
42 def calculate_ldos(self, bias):
43 """Calculate local density of states for given bias."""
44 if self.ldos is not None and bias == self.bias:
45 return
47 self.bias = bias
49 calc = self.atoms.calc
51 if self.use_density:
52 self.ldos = calc.get_pseudo_density()
53 return
55 if bias < 0:
56 emin = bias
57 emax = 0.0
58 else:
59 emin = 0
60 emax = bias
62 nbands = calc.get_number_of_bands()
63 weights = calc.get_k_point_weights()
64 nkpts = len(weights)
65 nspins = calc.get_number_of_spins()
66 eigs = np.array(
67 [
68 [calc.get_eigenvalues(k, s) for k in range(nkpts)]
69 for s in range(nspins)
70 ]
71 )
72 eigs -= calc.get_fermi_level()
73 ldos = np.zeros(calc.get_pseudo_wave_function(0, 0, 0).shape)
75 for s in range(nspins):
76 for k in range(nkpts):
77 for n in range(nbands):
78 e = eigs[s, k, n]
79 if emin < e < emax:
80 psi = calc.get_pseudo_wave_function(n, k, s)
81 ldos += weights[k] * (psi * np.conj(psi)).real
83 if 0 in self.symmetries:
84 # (x,y) -> (-x,y)
85 ldos[1:] += ldos[:0:-1].copy()
86 ldos[1:] *= 0.5
88 if 1 in self.symmetries:
89 # (x,y) -> (x,-y)
90 ldos[:, 1:] += ldos[:, :0:-1].copy()
91 ldos[:, 1:] *= 0.5
93 if 2 in self.symmetries:
94 # (x,y) -> (y,x)
95 ldos += ldos.transpose((1, 0, 2)).copy()
96 ldos *= 0.5
98 self.ldos = ldos
100 def write(self, filename):
101 """Write local density of states to JSON file."""
102 write_json(filename, (self.ldos, self.bias, self.cell))
104 def get_averaged_current(self, bias, z):
105 """Calculate avarage current at height z (in Angstrom).
107 Use this to get an idea of what current to use when scanning."""
109 self.calculate_ldos(bias)
110 nz = self.ldos.shape[2]
112 # Find grid point:
113 n = z / self.cell[2, 2] * nz
114 dn = n - np.floor(n)
115 n = int(n) % nz
117 # Average and do linear interpolation:
118 return (1 - dn) * self.ldos[:, :, n].mean() + dn * self.ldos[
119 :, :, (n + 1) % nz
120 ].mean()
122 def scan(self, bias, current, z0=None, repeat=(1, 1)):
123 """Constant current 2-d scan.
125 Returns three 2-d arrays (x, y, z) containing x-coordinates,
126 y-coordinates and heights. These three arrays can be passed to
127 matplotlibs contourf() function like this:
128 >>> x, y, z = stm.scan(bias, current) # doctest: +SKIP
129 >>> import matplotlib.pyplot as plt # doctest: +SKIP
130 >>> plt.contourf(x, y, z) # doctest: +SKIP
131 >>> plt.show() # doctest: +SKIP
133 """
135 self.calculate_ldos(bias)
137 L = self.cell[2, 2]
138 nz = self.ldos.shape[2]
139 h = L / nz
141 ldos = self.ldos.reshape((-1, nz))
143 heights = np.empty(ldos.shape[0])
144 for i, a in enumerate(ldos):
145 heights[i] = find_height(a, current, h, z0)
147 s0 = self.ldos.shape[:2]
148 heights = heights.reshape(s0)
149 heights = np.tile(heights, repeat)
150 s = heights.shape
152 ij = np.indices(s, dtype=float).reshape((2, -1)).T
153 x, y = np.dot(ij / s0, self.cell[:2, :2]).T.reshape((2,) + s)
155 return x, y, heights
157 def scan2(self, bias, z, repeat=(1, 1)):
158 """Constant height 2-d scan.
160 Returns three 2-d arrays (x, y, I) containing x-coordinates,
161 y-coordinates and currents. These three arrays can be passed to
162 matplotlibs contourf() function like this:
164 >>> import matplotlib.pyplot as plt # doctest: +SKIP
165 >>> plt.contourf(x, y, I) # doctest: +SKIP
166 >>> plt.show() # doctest: +SKIP
168 """
170 self.calculate_ldos(bias)
172 nz = self.ldos.shape[2]
173 ldos = self.ldos.reshape((-1, nz))
175 current = np.empty(ldos.shape[0])
177 zp = z / self.cell[2, 2] * nz
178 zp = int(zp) % nz
180 for i, a in enumerate(ldos):
181 current[i] = self.find_current(a, zp)
183 s0 = self.ldos.shape[:2]
184 current = current.reshape(s0)
185 current = np.tile(current, repeat)
186 s = current.shape
188 ij = np.indices(s, dtype=float).reshape((2, -1)).T
189 x, y = np.dot(ij / s0, self.cell[:2, :2]).T.reshape((2,) + s)
191 # Returing scan with axes in Angstrom.
192 return x, y, current
194 def linescan(self, bias, current, p1, p2, npoints=50, z0=None):
195 """Constant current line scan.
197 Example::
199 stm = STM(...)
200 z = ... # tip position
201 c = stm.get_averaged_current(-1.0, z)
202 stm.linescan(-1.0, c, (1.2, 0.0), (1.2, 3.0))
203 """
205 heights = self.scan(bias, current, z0)[2]
207 p1 = np.asarray(p1, float)
208 p2 = np.asarray(p2, float)
209 d = p2 - p1
210 s = np.dot(d, d) ** 0.5
212 cell = self.cell[:2, :2]
213 shape = np.array(heights.shape, float)
214 M = np.linalg.inv(cell)
215 line = np.empty(npoints)
216 for i in range(npoints):
217 p = p1 + i * d / (npoints - 1)
218 q = np.dot(p, M) * shape
219 line[i] = interpolate(q, heights)
220 return np.linspace(0, s, npoints), line
222 def pointcurrent(self, bias, x, y, z):
223 """Current for a single x, y, z position for a given bias."""
225 self.calculate_ldos(bias)
227 nx = self.ldos.shape[0]
228 ny = self.ldos.shape[1]
229 nz = self.ldos.shape[2]
231 # Find grid point:
232 xp = x / np.linalg.norm(self.cell[0]) * nx
233 dx = xp - np.floor(xp)
234 xp = int(xp) % nx
236 yp = y / np.linalg.norm(self.cell[1]) * ny
237 dy = yp - np.floor(yp)
238 yp = int(yp) % ny
240 zp = z / np.linalg.norm(self.cell[2]) * nz
241 dz = zp - np.floor(zp)
242 zp = int(zp) % nz
244 # 3D interpolation of the LDOS at point (x,y,z) at given bias.
245 xyzldos = (
246 ((1 - dx) + (1 - dy) + (1 - dz)) * self.ldos[xp, yp, zp]
247 + dx * self.ldos[(xp + 1) % nx, yp, zp]
248 + dy * self.ldos[xp, (yp + 1) % ny, zp]
249 + dz * self.ldos[xp, yp, (zp + 1) % nz]
250 )
252 return dos2current(bias, xyzldos)
254 def sts(self, x, y, z, bias0, bias1, biasstep):
255 """Returns the dI/dV curve for position x, y at height z (in Angstrom),
256 for bias from bias0 to bias1 with step biasstep."""
258 biases = np.arange(bias0, bias1 + biasstep, biasstep)
259 current = np.zeros(biases.shape)
261 for b in np.arange(len(biases)):
262 print(b, biases[b])
263 current[b] = self.pointcurrent(biases[b], x, y, z)
265 dIdV = np.gradient(current, biasstep)
267 return biases, current, dIdV
269 def find_current(self, ldos, z):
270 """Finds current for given LDOS at height z."""
271 nz = self.ldos.shape[2]
273 zp = z / self.cell[2, 2] * nz
274 dz = zp - np.floor(zp)
275 zp = int(zp) % nz
277 ldosz = (1 - dz) * ldos[zp] + dz * ldos[(zp + 1) % nz]
279 return dos2current(self.bias, ldosz)
282def dos2current(bias, dos):
283 # Borrowed from gpaw/analyse/simple_stm.py:
284 # The connection between density n and current I
285 # n [e/Angstrom^3] = 0.0002 sqrt(I [nA])
286 # as given in Hofer et al., RevModPhys 75 (2003) 1287
287 return 5000.0 * dos**2 * (1 if bias > 0 else -1)
290def interpolate(q, heights):
291 qi = q.astype(int)
292 f = q - qi
293 g = 1 - f
294 qi %= heights.shape
295 n0, m0 = qi
296 n1, m1 = (qi + 1) % heights.shape
297 z = (
298 g[0] * g[1] * heights[n0, m0]
299 + f[0] * g[1] * heights[n1, m0]
300 + g[0] * f[1] * heights[n0, m1]
301 + f[0] * f[1] * heights[n1, m1]
302 )
303 return z
306def find_height(ldos, current, h, z0=None):
307 if z0 is None:
308 n = len(ldos) - 2
309 else:
310 n = int(z0 / h)
311 while n >= 0:
312 if ldos[n] > current:
313 break
314 n -= 1
315 else:
316 return 0.0
318 c2, c1 = ldos[n : n + 2]
319 return (n + 1 - (current - c1) / (c2 - c1)) * h
322def delta(biases, bias, width):
323 """Return a delta-function centered at 'bias'"""
324 x = -(((biases - bias) / width) ** 2)
325 return np.exp(x) / (np.sqrt(np.pi) * width)