Coverage for tbkit/propagation.py: 100%

201 statements  

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

1from __future__ import annotations 

2 

3import numpy as np 

4from numpy.typing import NDArray 

5import scipy.sparse as sparse 

6import scipy.sparse.linalg as spla 

7import matplotlib.pyplot as plt 

8from matplotlib.figure import Figure 

9from matplotlib.animation import FuncAnimation 

10import os 

11import tbkit.error_handling as error_handling 

12import tbkit.kpm as kpm 

13from tbkit.lattice import Lattice 

14 

15 

16 

17def _crank_nicolson(ham, dz: float): 

18 r''' 

19 Private function. One Crank-Nicolson step, 

20 :math:`\psi \mapsto (i - \tfrac{dz}{2}H)^{-1}(i + \tfrac{dz}{2}H)\psi`, 

21 with :math:`i - \tfrac{dz}{2}H` factorized once (sparse LU). 

22 ''' 

23 ham = sparse.csc_matrix(ham, dtype='c16') 

24 eye = sparse.identity(ham.shape[0], dtype='c16', format='csc') 

25 lu = spla.splu((1j * eye - 0.5 * dz * ham).tocsc()) 

26 rhs = (1j * eye + 0.5 * dz * ham).tocsr() 

27 return lambda psi: lu.solve(rhs @ psi) 

28 

29 

30################################# 

31# CLASS PROPAGATION 

32################################# 

33 

34 

35class Propagation(): 

36 r''' 

37 Get lattice time evolution. The time-dependent Schrodinger equation 

38 :math:`i\,\partial_z\psi = H\psi` is solved by the Crank-Nicolson method, 

39 

40 .. math:: 

41 

42 \psi(z+dz) = \left(1 + \tfrac{i}{2}H\,dz\right)^{-1} 

43 \left(1 - \tfrac{i}{2}H\,dz\right)\psi(z)\, , 

44 

45 unitary for a Hermitian :math:`H`. The matrix 

46 :math:`1 + \tfrac{i}{2}H\,dz` is factorized once per Hamiltonian 

47 (sparse LU, *scipy.sparse.linalg.splu*) and never inverted, so each 

48 step costs one sparse product and two sparse triangular solves. 

49 *get_propagation* also takes ``method='chebyshev'``: the exact evolution 

50 :math:`e^{-iH\,dz}` from its Chebyshev expansion 

51 (*tbkit.kpm.time_evolution*), for Hermitian Hamiltonians, with no 

52 factorization at all and no time-step error. 

53 

54 Parameters 

55 ---------- 

56 lat : **lattice** class instance 

57 ''' 

58 

59 def __init__(self, lat: Lattice) -> None: 

60 error_handling.lat(lat) 

61 self.lat = lat 

62 self.prop = np.array([], 'c16') 

63 

64 def get_propagation( 

65 self, ham: sparse.spmatrix, psi_init: NDArray, steps: int, dz: float, norm: bool = False, 

66 method: str = 'crank-nicolson', 

67 ) -> None: 

68 r''' 

69 Get the time evolution. 

70 

71 Parameters 

72 ---------- 

73 ham : sparse.csr_matrix 

74 Tight-Binding Hamiltonian. 

75 psi_init : np.ndarray 

76 Initial state. 

77 steps : Positive Integer 

78 Number of steps. 

79 dz : Positive number 

80 Step. 

81 norm : Boolean, default False 

82 Renormalize the state to 

83 :math:`\sum_i|\psi_i|^2 = 1` at each step. The Crank-Nicolson 

84 step is unitary, so this only matters for a non-Hermitian 

85 Hamiltonian (gain/loss), where the norm is not conserved. 

86 method : String, default 'crank-nicolson' 

87 'crank-nicolson' (one 

88 sparse LU factorization; any Hamiltonian, Hermitian or not) or 

89 'chebyshev' (the exact :math:`e^{-iH\,dz}` of 

90 *tbkit.kpm.time_evolution*; Hermitian Hamiltonians only). 

91 ''' 

92 error_handling.empty_ham(ham) 

93 error_handling.ndarray(psi_init, 'psi_init', self.lat.sites) 

94 error_handling.positive_int(steps, 'steps') 

95 error_handling.positive_real(dz, 'dz') 

96 error_handling.boolean(norm, 'norm') 

97 error_handling.prop_method(method) 

98 self.steps = steps 

99 self.dz = dz 

100 if method == 'chebyshev': 

101 self.prop = kpm.time_evolution(ham, psi_init, self.dz * np.arange(self.steps)) 

102 if norm: 

103 self.prop /= np.linalg.norm(self.prop, axis=0) 

104 return 

105 self.prop = np.empty((self.lat.sites, self.steps), 'c16') 

106 self.prop[:, 0] = psi_init 

107 step = _crank_nicolson(ham, self.dz) 

108 for i in range(1, self.steps): 

109 self.prop[:, i] = step(self.prop[:, i-1]) 

110 if norm: 

111 self.prop[:, i] /= np.linalg.norm(self.prop[:, i]) 

112 

113 def get_pumping( 

114 self, hams: list[sparse.spmatrix], psi_init: NDArray, steps: int, dz: float, norm: bool = True, 

115 ) -> None: 

116 r''' 

117 Get the time evolution with adiabatic pumpings. 

118 

119 Parameters 

120 ---------- 

121 hams : List of sparse.csr_matrices 

122 Tight-Binding Hamiltonians. 

123 psi_init : np.ndarray 

124 Initial state. 

125 steps : Positive integer 

126 Number of steps. 

127 dz : Positive number 

128 Step. 

129 norm : Boolean, default True 

130 Renormalize the state to 

131 :math:`\sum_i|\psi_i|^2 = 1` at each step. 

132 

133 Notes 

134 ----- 

135 The *steps* are split into ``len(hams) + 1`` equal stages: evolution 

136 under ``hams[0]``, then ``len(hams) - 1`` stages each interpolating 

137 linearly from ``hams[j]`` to ``hams[j+1]``, then evolution under 

138 ``hams[-1]`` for the remaining steps. With fewer than 

139 ``len(hams) + 1`` steps the stages are empty: the state evolves under 

140 ``hams[-1]`` from the first step on. 

141 ''' 

142 error_handling.get_pump(hams) 

143 error_handling.ndarray(psi_init, 'psi_init', self.lat.sites) 

144 error_handling.positive_int(steps, 'steps') 

145 error_handling.positive_real(dz, 'dz') 

146 error_handling.boolean(norm, 'norm') 

147 self.steps = steps 

148 self.dz = dz 

149 no = len(hams) 

150 self.prop = np.empty((self.lat.sites, self.steps), 'c16') 

151 self.prop[:, 0] = psi_init 

152 

153 def advance(i, step): 

154 self.prop[:, i] = step(self.prop[:, i-1]) 

155 if norm: 

156 self.prop[:, i] /= np.linalg.norm(self.prop[:, i]) 

157 

158 delta = self.steps // (1 + no) 

159 # before pumping 

160 step = _crank_nicolson(hams[0], self.dz) 

161 for i in range(1, delta): 

162 advance(i, step) 

163 # pumping: one factorization per interpolated Hamiltonian 

164 c = np.linspace(0, 1, delta) 

165 for j in range(0, no-1): 

166 for i in range(0, delta): 

167 advance((j+1)*delta+i, _crank_nicolson((1-c[i])*hams[j]+c[i]*hams[j+1], self.dz)) 

168 # after pumping, under hams[-1] (what the last pumping step ends on). 

169 # Start at 1 at least: with delta == 0 there were no stages, and 

170 # index no*delta - 1 = -1 would overwrite the initial state. 

171 step = _crank_nicolson(hams[-1], self.dz) 

172 for i in range(max(no*delta, 1), self.steps): 

173 advance(i, step) 

174 

175 def plt_propagation_1d( 

176 self, prop_type: str = 'real', fs: float = 20, figsize: tuple[float, float] | None = None, 

177 ) -> Figure: 

178 ''' 

179 Plot time evolution for 1D systems. 

180 

181 Parameters 

182 ---------- 

183 prop_type : String, default 'real' 

184 Plot the real part 

185 ('real'), the imaginary part ('imag'), or the intensity ('norm'). 

186 fs : Positive number, default 20 

187 Fontsize. 

188 figsize : Tuple, default None 

189 Figure size. 

190 

191 Returns 

192 ------- 

193 fig : Figure 

194 ''' 

195 error_handling.empty_ndarray(self.prop, 'get_propagation or get_pumping') 

196 error_handling.positive_real(fs, 'fs') 

197 error_handling.prop_type(prop_type) 

198 error_handling.tuple_2elem(figsize, 'figsize') 

199 fig, ax = plt.subplots(figsize=figsize) 

200 plt.ylabel('n', fontsize=fs) 

201 plt.xlabel('z', fontsize=fs) 

202 if prop_type == 'real': 

203 color = self.prop_smooth_1d(self.prop.real) 

204 max_val = max(np.max(color), -np.min(color)) 

205 ticks = [-max_val, max_val] 

206 cmap = 'seismic' 

207 elif prop_type == 'imag': 

208 color = self.prop_smooth_1d(self.prop.imag) 

209 max_val = max(np.max(color), -np.min(color)) 

210 ticks = [-max_val, max_val] 

211 cmap = 'seismic' 

212 else: 

213 color = self.prop_smooth_1d(np.abs(self.prop) ** 2) 

214 ticks = [0., np.max(color[:, -1])] 

215 cmap = 'hot' 

216 extent = (-0, self.steps*self.dz, self.lat.sites-.5, -.5) 

217 interpolation = 'nearest' 

218 im = plt.imshow(color, cmap=cmap, aspect='auto', 

219 interpolation=interpolation, extent=extent, 

220 vmin=ticks[0], vmax=ticks[-1]) 

221 for label in ax.xaxis.get_majorticklabels(): 

222 label.set_fontsize(fs) 

223 for label in ax.yaxis.get_majorticklabels(): 

224 label.set_fontsize(fs) 

225 ax.get_yaxis().set_major_locator(plt.MaxNLocator(integer=True)) 

226 if prop_type == 'norm': 

227 cbar = fig.colorbar(im, ticks=ticks) 

228 cbar.ax.set_yticklabels(['0','max']) 

229 else: 

230 cbar = fig.colorbar(im, ticks=[ticks[0], 0, ticks[1]]) 

231 cbar.ax.set_yticklabels(['min', '0','max']) 

232 cbar.ax.tick_params(labelsize=fs) 

233 return fig 

234 

235 def prop_smooth_1d(self, prop: NDArray, a: float = 10, no: int = 40) -> NDArray: 

236 r''' 

237 Private function. Used in *plt_propagation_1d*. 

238 Smooth propagation for 1D systems. 

239 Perform Gaussian interpolation :math:`e^{-a(x-x_i)^2}`, 

240 

241 Parameters 

242 ---------- 

243 prop 

244 Propagation. 

245 a 

246 Default value 10. Gaussian Parameter. 

247 no 

248 Default value 40. Number of points of each Gaussian. 

249 

250 Returns 

251 ------- 

252 smooth 

253 Smoothed propagation. 

254 ''' 

255 func = np.exp(- a * np.linspace(-0.5, 0.5, no) ** 2) 

256 smooth = np.empty((self.lat.sites * no, self.steps)) 

257 for iz in range(0, self.steps): 

258 for i in range(self.lat.sites): 

259 smooth[i*no: (i+1)*no, iz] = prop[i, iz] * func 

260 return smooth 

261 

262 def get_animation( 

263 self, s: float = 300., fs: float = 20., prop_type: str = 'real', 

264 figsize: tuple[float, float] | None = None, 

265 ) -> FuncAnimation: 

266 ''' 

267 Get time evolution animation. 

268 

269 Parameters 

270 ---------- 

271 s 

272 Default value 300. Circle size. 

273 fs 

274 Default value 20. Fontsize. 

275 prop_type : String, default 'real' 

276 Plot the real part 

277 ('real'), the imaginary part ('imag'), or the intensity ('norm'). 

278 figsize : Tuple, default None 

279 Figsize. 

280 

281 Returns 

282 ------- 

283 ani 

284 Animation. 

285 ''' 

286 error_handling.empty_ndarray(self.prop, 'get_propagation or get_pumping') 

287 error_handling.positive_real(s, 's') 

288 error_handling.positive_real(fs, 'fs') 

289 error_handling.prop_type(prop_type) 

290 error_handling.tuple_2elem(figsize, 'figsize') 

291 if os.name == 'posix': 

292 blit = False 

293 else: 

294 blit = True 

295 if prop_type == 'real': 

296 color = self.prop.real 

297 max_val = max(np.max(color), -np.min(color)) 

298 ticks = [-max_val, max_val] 

299 cmap = 'seismic' 

300 elif prop_type == 'imag': 

301 color = self.prop.imag 

302 max_val = max(np.max(color), -np.min(color)) 

303 ticks = [-max_val, max_val] 

304 cmap = 'seismic' 

305 else: 

306 color = np.abs(self.prop) ** 2 

307 ticks = [0., np.max(color)] 

308 cmap = 'Reds' 

309 fig, ax = plt.subplots(figsize=figsize) 

310 plt.xlim(np.min(self.lat.coor['x'])-1., np.max(self.lat.coor['x'])+1.) 

311 plt.ylim(np.min(self.lat.coor['y'])-1., np.max(self.lat.coor['y'])+1.) 

312 scat = plt.scatter(self.lat.coor['x'], self.lat.coor['y'], c=color[:, 0], 

313 s=s, vmin=ticks[0], vmax=ticks[1], 

314 cmap=plt.get_cmap(cmap)) 

315 frame = plt.gca() 

316 frame.get_xaxis().set_ticks([]) 

317 frame.get_yaxis().set_ticks([]) 

318 ax.set_aspect('equal') 

319 if prop_type == 'norm': 

320 cbar = fig.colorbar(scat, ticks=ticks) 

321 cbar.ax.set_yticklabels(['0','max']) 

322 else: 

323 cbar = fig.colorbar(scat, ticks=[ticks[0], 0, ticks[1]]) 

324 cbar.ax.set_yticklabels(['min', '0','max']) 

325 

326 def update(i, color, scat): 

327 scat.set_array(color[:, i]) 

328 return scat, 

329 

330 ani = FuncAnimation(fig, update, frames=self.steps, 

331 fargs=(color, scat), blit=blit, repeat=False) 

332 return ani 

333 

334 def get_animation_nb( 

335 self, s: float = 300., fs: float = 20., prop_type: str = 'real', 

336 figsize: tuple[float, float] | None = None, 

337 ) -> FuncAnimation: 

338 ''' 

339 Get time evolution animation for iPython notebooks. 

340 

341 Parameters 

342 ---------- 

343 s 

344 Default value 300. Circle size. 

345 fs 

346 Default value 20. Fontsize. 

347 prop_type : String, default 'real' 

348 Plot the real part 

349 ('real'), the imaginary part ('imag'), or the intensity ('norm'). 

350 figsize : Tuple, default None 

351 Figsize. 

352 

353 Returns 

354 ------- 

355 ani 

356 Animation. 

357 ''' 

358 error_handling.empty_ndarray(self.prop, 'get_propagation or get_pumping') 

359 error_handling.positive_real(s, 's') 

360 error_handling.positive_real(fs, 'fs') 

361 error_handling.prop_type(prop_type) 

362 error_handling.tuple_2elem(figsize, 'figsize') 

363 if prop_type == 'real' or prop_type == 'imag': 

364 color = self.prop.real if prop_type == 'real' else self.prop.imag 

365 max_val = max(np.max(color), -np.min(color)) 

366 ticks = [-max_val, max_val] 

367 cmap = 'seismic' 

368 else: 

369 color = np.abs(self.prop) ** 2 

370 ticks = [0., np.max(color)] 

371 cmap = 'Reds' 

372 fig = plt.figure(figsize=figsize) 

373 ax = plt.axes(xlim=(np.min(self.lat.coor['x']-.5), np.max(self.lat.coor['x']+.5)), 

374 ylim=(np.min(self.lat.coor['y']-.5), np.max(self.lat.coor['y']+.5))) 

375 ax.set_aspect('equal') 

376 frame = plt.gca() 

377 frame.get_xaxis().set_ticks([]) 

378 frame.get_yaxis().set_ticks([]) 

379 scat = plt.scatter(self.lat.coor['x'], self.lat.coor['y'], c=color[:, 0], 

380 s=s, vmin=ticks[0], vmax=ticks[1], 

381 cmap=cmap) 

382 if prop_type == 'real' or prop_type == 'imag': 

383 cbar = fig.colorbar(scat, ticks=[ticks[0], 0, ticks[1]]) 

384 cbar.ax.set_yticklabels(['min', '0','max']) 

385 else: 

386 cbar = fig.colorbar(scat, ticks=[0, ticks[1]]) 

387 cbar.ax.set_yticklabels(['0','max']) 

388 

389 def init(): 

390 scat.set_array(color[:, 0]) 

391 return scat, 

392 

393 def animate(i): 

394 scat.set_array(color[:, i]) 

395 return scat, 

396 

397 return FuncAnimation(fig, animate, init_func=init, 

398 frames=self.steps, interval=120, blit=True) 

399 

400 def plt_prop_dimer(self, lw: float = 5, fs: float = 20) -> Figure: 

401 ''' 

402 Plot time evolution for dimers. 

403 

404 Parameters 

405 ---------- 

406 lw : Positive number, default 5 

407 Linewidth. 

408 fs : Positive number, default 20 

409 Fontsize. 

410 

411 Returns 

412 ------- 

413 fig : Figure 

414 ''' 

415 error_handling.empty_ndarray(self.prop, 'get_propagation or get_pumping') 

416 error_handling.positive_real(lw, 'lw') 

417 error_handling.positive_real(fs, 'fs') 

418 color = ['b', 'r'] 

419 fig, ax = plt.subplots() 

420 z = self.dz * np.arange(self.steps) 

421 for i, c in zip([0, 1], color): 

422 plt.plot(z, np.abs(self.prop[i, :])**2, c, lw=lw) 

423 plt.title('Intensity', fontsize=fs) 

424 plt.xlabel('$z$', fontsize=fs) 

425 plt.ylabel(r'$|\psi_j|^2$', fontsize=fs) 

426 plt.xlim(0, z[-1]) 

427 return fig 

428 

429 

430# Backward-compatible lowercase alias (pre-0.2 API). 

431propagation = Propagation