Coverage for ase/transport/calculators.py: 60.61%
264 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
2from numpy import linalg
3from scipy.integrate import trapezoid
5from ase.transport.greenfunction import GreenFunction, asetransport_deprecated
6from ase.transport.selfenergy import LeadSelfEnergy
7from ase.transport.tools import (
8 cutcoupling,
9 dagger,
10 fermidistribution,
11 rotate_matrix,
12 subdiagonalize,
13)
14from ase.units import kB
17class TransportCalculator:
18 """Determine transport properties of a device sandwiched between
19 two semi-infinite leads using a Green function method.
20 """
22 @asetransport_deprecated
23 def __init__(self, **kwargs):
24 """Create the transport calculator.
26 .. deprecated:: ase-3.30.0
27 The :mod:`ase.transport` package will be removed in a future
28 release unless users express interest in keeping it e.g.
29 on the issue tracker.
31 Parameters
32 ----------
34 h : (N, N) ndarray
35 Hamiltonian matrix for the central region.
36 s : {None, (N, N) ndarray}, optional
37 Overlap matrix for the central region.
38 Use None for an orthonormal basis.
39 h1 : (N1, N1) ndarray
40 Hamiltonian matrix for lead1.
41 h2 : {None, (N2, N2) ndarray}, optional
42 Hamiltonian matrix for lead2. You may use None if lead1 and lead2
43 are identical.
44 s1 : {None, (N1, N1) ndarray}, optional
45 Overlap matrix for lead1. Use None for an orthonormal basis.
46 hc1 : {None, (N1, N) ndarray}, optional
47 Hamiltonian coupling matrix between the first principal
48 layer in lead1 and the central region.
49 hc2 : {None, (N2, N} ndarray), optional
50 Hamiltonian coupling matrix between the first principal
51 layer in lead2 and the central region.
52 sc1 : {None, (N1, N) ndarray}, optional
53 Overlap coupling matrix between the first principal
54 layer in lead1 and the central region.
55 sc2 : {None, (N2, N) ndarray}, optional
56 Overlap coupling matrix between the first principal
57 layer in lead2 and the central region.
58 energies : {None, array_like}, optional
59 Energy points for which calculated transport properties are
60 evaluated.
61 eta : {1.0e-5, float}, optional
62 Infinitesimal for the central region Green function.
63 eta1/eta2 : {1.0e-5, float}, optional
64 Infinitesimal for lead1/lead2 Green function.
65 align_bf : {None, int}, optional
66 Use align_bf=m to shift the central region
67 by a constant potential such that the m'th onsite element
68 in the central region is aligned to the m'th onsite element
69 in lead1 principal layer.
70 logfile : {None, str}, optional
71 Write a logfile to file with name `logfile`.
72 Use '-' to write to std out.
73 eigenchannels: {0, int}, optional
74 Number of eigenchannel transmission coefficients to
75 calculate.
76 pdos : {None, (N,) array_like}, optional
77 Specify which basis functions to calculate the
78 projected density of states for.
79 dos : {False, bool}, optional
80 The total density of states of the central region.
82 If hc1/hc2 are None, they are assumed to be identical to
83 the coupling matrix elements between nearest neighbor
84 principal layers in lead1/lead2.
86 Examples
87 --------
89 >>> import numpy as np
90 >>> h = np.array((0,)).reshape((1,1))
91 >>> h1 = np.array((0, -1, -1, 0)).reshape(2,2)
92 >>> energies = np.arange(-3, 3, 0.1)
93 >>> calc = TransportCalculator(h=h, h1=h1, energies=energies)
94 >>> T = calc.get_transmission()
96 """
98 # The default values for all extra keywords
99 self.input_parameters = {
100 'energies': None,
101 'h': None,
102 'h1': None,
103 'h2': None,
104 's': None,
105 's1': None,
106 's2': None,
107 'hc1': None,
108 'hc2': None,
109 'sc1': None,
110 'sc2': None,
111 'align_bf': None,
112 'eta1': 1e-5,
113 'eta2': 1e-5,
114 'eta': 1e-5,
115 'logfile': None,
116 'eigenchannels': 0,
117 'dos': False,
118 'pdos': [],
119 }
121 self.initialized = False # Changed Hamiltonians?
122 self.uptodate = False # Changed energy grid?
123 self.set(**kwargs)
125 def set(self, **kwargs):
126 for key in kwargs:
127 if key in [
128 'h',
129 'h1',
130 'h2',
131 'hc1',
132 'hc2',
133 's',
134 's1',
135 's2',
136 'sc1',
137 'sc2',
138 'eta',
139 'eta1',
140 'eta2',
141 'align_bf',
142 ]:
143 self.initialized = False
144 self.uptodate = False
145 break
146 elif key in ['energies', 'eigenchannels', 'dos', 'pdos']:
147 self.uptodate = False
148 elif key not in self.input_parameters:
149 raise KeyError('%r not a vaild keyword' % key)
151 self.input_parameters.update(kwargs)
152 log = self.input_parameters['logfile']
153 if log is None:
155 class Trash:
156 def write(self, s):
157 pass
159 def flush(self):
160 pass
162 self.log = Trash()
163 elif log == '-':
164 from sys import stdout
166 self.log = stdout
167 elif 'logfile' in kwargs:
168 self.log = open(log, 'w')
170 def initialize(self):
171 if self.initialized:
172 return
174 print('# Initializing calculator...', file=self.log)
176 p = self.input_parameters
177 if p['s'] is None:
178 p['s'] = np.identity(len(p['h']))
180 identical_leads = False
181 if p['h2'] is None:
182 p['h2'] = p['h1'] # Lead2 is idendical to lead1
183 identical_leads = True
185 if p['s1'] is None:
186 p['s1'] = np.identity(len(p['h1']))
188 if identical_leads:
189 p['s2'] = p['s1']
190 else:
191 if p['s2'] is None:
192 p['s2'] = np.identity(len(p['h2']))
194 h_mm = p['h']
195 s_mm = p['s']
196 pl1 = len(p['h1']) // 2
197 pl2 = len(p['h2']) // 2
198 h1_ii = p['h1'][:pl1, :pl1]
199 h1_ij = p['h1'][:pl1, pl1 : 2 * pl1]
200 s1_ii = p['s1'][:pl1, :pl1]
201 s1_ij = p['s1'][:pl1, pl1 : 2 * pl1]
202 h2_ii = p['h2'][:pl2, :pl2]
203 h2_ij = p['h2'][pl2 : 2 * pl2, :pl2]
204 s2_ii = p['s2'][:pl2, :pl2]
205 s2_ij = p['s2'][pl2 : 2 * pl2, :pl2]
207 if p['hc1'] is None:
208 nbf = len(h_mm)
209 h1_im = np.zeros((pl1, nbf), complex)
210 s1_im = np.zeros((pl1, nbf), complex)
211 h1_im[:pl1, :pl1] = h1_ij
212 s1_im[:pl1, :pl1] = s1_ij
213 p['hc1'] = h1_im
214 p['sc1'] = s1_im
215 else:
216 h1_im = p['hc1']
217 if p['sc1'] is not None:
218 s1_im = p['sc1']
219 else:
220 s1_im = np.zeros(h1_im.shape, complex)
221 p['sc1'] = s1_im
223 if p['hc2'] is None:
224 h2_im = np.zeros((pl2, nbf), complex)
225 s2_im = np.zeros((pl2, nbf), complex)
226 h2_im[-pl2:, -pl2:] = h2_ij
227 s2_im[-pl2:, -pl2:] = s2_ij
228 p['hc2'] = h2_im
229 p['sc2'] = s2_im
230 else:
231 h2_im = p['hc2']
232 if p['sc2'] is not None:
233 s2_im = p['sc2']
234 else:
235 s2_im = np.zeros(h2_im.shape, complex)
236 p['sc2'] = s2_im
238 align_bf = p['align_bf']
239 if align_bf is not None:
240 diff = (
241 h_mm[align_bf, align_bf] - h1_ii[align_bf, align_bf]
242 ) / s_mm[align_bf, align_bf]
243 print(
244 '# Aligning scat. H to left lead H. diff=', diff, file=self.log
245 )
246 h_mm -= diff * s_mm
248 # Setup lead self-energies
249 # All infinitesimals must be > 0
250 assert np.all(np.array((p['eta'], p['eta1'], p['eta2'])) > 0.0)
251 self.selfenergies = [
252 LeadSelfEnergy(
253 (h1_ii, s1_ii), (h1_ij, s1_ij), (h1_im, s1_im), p['eta1']
254 ),
255 LeadSelfEnergy(
256 (h2_ii, s2_ii), (h2_ij, s2_ij), (h2_im, s2_im), p['eta2']
257 ),
258 ]
260 # setup scattering green function
261 self.greenfunction = GreenFunction(
262 selfenergies=self.selfenergies, H=h_mm, S=s_mm, eta=p['eta']
263 )
265 self.initialized = True
267 def update(self):
268 if self.uptodate:
269 return
271 p = self.input_parameters
272 self.energies = p['energies']
273 nepts = len(self.energies)
274 nchan = p['eigenchannels']
275 pdos = p['pdos']
276 self.T_e = np.empty(nepts)
277 if p['dos']:
278 self.dos_e = np.empty(nepts)
279 if pdos != []:
280 self.pdos_ne = np.empty((len(pdos), nepts))
281 if nchan > 0:
282 self.eigenchannels_ne = np.empty((nchan, nepts))
284 for e, energy in enumerate(self.energies):
285 Ginv_mm = self.greenfunction.retarded(energy, inverse=True)
286 lambda1_mm = self.selfenergies[0].get_lambda(energy)
287 lambda2_mm = self.selfenergies[1].get_lambda(energy)
288 a_mm = linalg.solve(Ginv_mm, lambda1_mm)
289 b_mm = linalg.solve(dagger(Ginv_mm), lambda2_mm)
290 T_mm = np.dot(a_mm, b_mm)
291 if nchan > 0:
292 t_n = linalg.eigvals(T_mm).real
293 self.eigenchannels_ne[:, e] = np.sort(t_n)[-nchan:]
294 self.T_e[e] = np.sum(t_n)
295 else:
296 self.T_e[e] = np.trace(T_mm).real
298 print(energy, self.T_e[e], file=self.log)
299 self.log.flush()
301 if p['dos']:
302 self.dos_e[e] = self.greenfunction.dos(energy)
304 if pdos != []:
305 self.pdos_ne[:, e] = np.take(
306 self.greenfunction.pdos(energy), pdos
307 )
309 self.uptodate = True
311 def print_pl_convergence(self):
312 self.initialize()
313 pl1 = len(self.input_parameters['h1']) // 2
315 h_ii = self.selfenergies[0].h_ii
316 s_ii = self.selfenergies[0].s_ii
317 ha_ii = self.greenfunction.H[:pl1, :pl1]
318 sa_ii = self.greenfunction.S[:pl1, :pl1]
319 c1 = np.abs(h_ii - ha_ii).max()
320 c2 = np.abs(s_ii - sa_ii).max()
321 print(f'Conv (h,s)={c1:.2e}, {c2:2.e}')
323 def plot_pl_convergence(self):
324 self.initialize()
325 pl1 = len(self.input_parameters['h1']) // 2
326 hlead = self.selfenergies[0].h_ii.real.diagonal()
327 hprincipal = self.greenfunction.H.real.diagonal[:pl1]
329 import pylab as pl
331 pl.plot(hlead, label='lead')
332 pl.plot(hprincipal, label='principal layer')
333 pl.axis('tight')
334 pl.show()
336 def get_current(self, bias, T=0.0, E=None, T_e=None, spinpol=False):
337 """Returns the current as a function of the
338 bias voltage.
340 **Parameters:**
341 bias : {float, (M,) ndarray}, units: V
342 Specifies the bias voltage.
343 T : {float}, units: K, optional
344 Specifies the temperature.
345 E : {(N,) ndarray}, units: eV, optional
346 Contains energy grid of the transmission function.
347 T_e {(N,) ndarray}, units: unitless, optional
348 Contains the transmission function.
349 spinpol: {bool}, optional
350 Specifies whether the current should be
351 calculated assuming degenerate spins
353 **Returns:**
354 I : {float, (M,) ndarray}, units: 2e/h*eV
355 Contains the electric current.
357 Examples
358 --------
360 >> import numpy as np
361 >> import pylab as plt
362 >> from ase import units
363 >>
364 >> bias = np.arange(0, 2, .1)
365 >> current = calc.get_current(bias, T = 0.)
366 >> plt.plot(bias, 2.*units._e**2/units._hplanck*current)
367 >> plt.xlabel('U [V]')
368 >> plt.ylabel('I [A]')
369 >> plt.show()
371 """
372 if E is not None:
373 if T_e is None:
374 self.energies = E
375 self.uptodate = False
376 T_e = self.get_transmission().copy()
377 else:
378 assert self.uptodate, (
379 'Energy grid and transmission function not defined.'
380 )
381 E = self.energies.copy()
382 T_e = self.T_e.copy()
384 if not isinstance(bias, (int, float)):
385 bias = bias[np.newaxis]
386 E = E[:, np.newaxis]
387 T_e = T_e[:, np.newaxis]
389 fl = fermidistribution(E - bias / 2.0, kB * T)
390 fr = fermidistribution(E + bias / 2.0, kB * T)
392 if spinpol:
393 return 0.5 * trapezoid((fl - fr) * T_e, x=E, axis=0)
394 else:
395 return trapezoid((fl - fr) * T_e, x=E, axis=0)
397 def get_transmission(self):
398 self.initialize()
399 self.update()
400 return self.T_e
402 def get_dos(self):
403 self.initialize()
404 self.update()
405 return self.dos_e
407 def get_eigenchannels(self, n=None):
408 """Get ``n`` first eigenchannels."""
409 self.initialize()
410 self.update()
411 if n is None:
412 n = self.input_parameters['eigenchannels']
413 return self.eigenchannels_ne[:n]
415 def get_pdos(self):
416 self.initialize()
417 self.update()
418 return self.pdos_ne
420 def subdiagonalize_bfs(self, bfs, apply=False):
421 self.initialize()
422 bfs = np.array(bfs)
423 p = self.input_parameters
424 h_mm = p['h']
425 s_mm = p['s']
426 ht_mm, st_mm, c_mm, e_m = subdiagonalize(h_mm, s_mm, bfs)
427 if apply:
428 self.uptodate = False
429 h_mm[:] = ht_mm.real
430 s_mm[:] = st_mm.real
431 # Rotate coupling between lead and central region
432 for alpha, sigma in enumerate(self.selfenergies):
433 sigma.h_im[:] = np.dot(sigma.h_im, c_mm)
434 sigma.s_im[:] = np.dot(sigma.s_im, c_mm)
436 c_mm = np.take(c_mm, bfs, axis=0)
437 c_mm = np.take(c_mm, bfs, axis=1)
438 return ht_mm, st_mm, e_m.real, c_mm
440 def cutcoupling_bfs(self, bfs, apply=False):
441 self.initialize()
442 bfs = np.array(bfs)
443 p = self.input_parameters
444 h_pp = p['h'].copy()
445 s_pp = p['s'].copy()
446 cutcoupling(h_pp, s_pp, bfs)
447 if apply:
448 self.uptodate = False
449 p['h'][:] = h_pp
450 p['s'][:] = s_pp
451 for alpha, sigma in enumerate(self.selfenergies):
452 for m in bfs:
453 sigma.h_im[:, m] = 0.0
454 sigma.s_im[:, m] = 0.0
455 return h_pp, s_pp
457 def lowdin_rotation(self, apply=False):
458 p = self.input_parameters
459 h_mm = p['h']
460 s_mm = p['s']
461 eig, rot_mm = linalg.eigh(s_mm)
462 eig = np.abs(eig)
463 rot_mm = np.dot(rot_mm / np.sqrt(eig), dagger(rot_mm))
464 if apply:
465 self.uptodate = False
466 h_mm[:] = rotate_matrix(h_mm, rot_mm) # rotate C region
467 s_mm[:] = rotate_matrix(s_mm, rot_mm)
468 for alpha, sigma in enumerate(self.selfenergies):
469 sigma.h_im[:] = np.dot(sigma.h_im, rot_mm) # rotate L-C coupl.
470 sigma.s_im[:] = np.dot(sigma.s_im, rot_mm)
472 return rot_mm
474 def get_left_channels(self, energy, nchan=1):
475 self.initialize()
476 g_s_ii = self.greenfunction.retarded(energy)
477 lambda_l_ii = self.selfenergies[0].get_lambda(energy)
478 lambda_r_ii = self.selfenergies[1].get_lambda(energy)
480 if self.greenfunction.S is not None:
481 s_mm = self.greenfunction.S
482 s_s_i, s_s_ii = linalg.eig(s_mm)
483 s_s_i = np.abs(s_s_i)
484 s_s_sqrt_i = np.sqrt(s_s_i) # sqrt of eigenvalues
485 s_s_sqrt_ii = np.dot(s_s_ii * s_s_sqrt_i, dagger(s_s_ii))
486 s_s_isqrt_ii = np.dot(s_s_ii / s_s_sqrt_i, dagger(s_s_ii))
488 lambdab_r_ii = np.dot(np.dot(s_s_isqrt_ii, lambda_r_ii), s_s_isqrt_ii)
489 a_l_ii = np.dot(np.dot(g_s_ii, lambda_l_ii), dagger(g_s_ii))
490 ab_l_ii = np.dot(np.dot(s_s_sqrt_ii, a_l_ii), s_s_sqrt_ii)
491 lambda_i, u_ii = linalg.eig(ab_l_ii)
492 ut_ii = np.sqrt(lambda_i / (2.0 * np.pi)) * u_ii
493 m_ii = 2 * np.pi * np.dot(np.dot(dagger(ut_ii), lambdab_r_ii), ut_ii)
494 T_i, c_in = linalg.eig(m_ii)
495 T_i = np.abs(T_i)
497 channels = np.argsort(-T_i)[:nchan]
498 c_in = np.take(c_in, channels, axis=1)
499 T_n = np.take(T_i, channels)
500 v_in = np.dot(np.dot(s_s_isqrt_ii, ut_ii), c_in)
502 return T_n, v_in