Coverage for ase/dft/wannier.py: 59.18%

561 statements  

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

1"""Partly occupied Wannier functions 

2 

3Find the set of partly occupied Wannier functions using the method from 

4Thygesen, Hansen and Jacobsen PRB v72 i12 p125119 2005. 

5""" 

6 

7import functools 

8import warnings 

9from math import pi, sqrt 

10from time import time 

11 

12import numpy as np 

13from scipy.linalg import qr 

14 

15from ase.dft.bandgap import bandgap 

16from ase.dft.kpoints import get_monkhorst_pack_size_and_offset 

17from ase.io.jsonio import read_json, write_json 

18from ase.parallel import paropen 

19 

20 

21def dagger(matrix): 

22 return np.conj(matrix.T) 

23 

24 

25def normalize(matrix, S=None): 

26 """Normalize column vectors. 

27 

28 :: 

29 

30 <matrix[:,i]| S |matrix[:,i]> = 1 

31 

32 """ 

33 for col in matrix.T: 

34 if S is None: 

35 col /= np.linalg.norm(col) 

36 else: 

37 col /= np.sqrt(np.dot(col.conj(), np.dot(S, col))) 

38 

39 

40dag = dagger 

41 

42 

43def silent(*args, **kwargs): 

44 """Dummy logging function.""" 

45 

46 

47def gram_schmidt(U): 

48 """Orthonormalize columns of U according to the Gram-Schmidt procedure.""" 

49 for i, col in enumerate(U.T): 

50 for col2 in U.T[:i]: 

51 col -= col2 * (col2.conj() @ col) 

52 col /= np.linalg.norm(col) 

53 

54 

55def lowdin(U, S=None): 

56 """Orthonormalize columns of U according to the symmetric Lowdin procedure. 

57 The implementation uses SVD, like symm. Lowdin it returns the nearest 

58 orthonormal matrix, but is more robust. 

59 """ 

60 

61 L, _s, R = np.linalg.svd(U, full_matrices=False) 

62 U[:] = L @ R 

63 

64 

65def neighbor_k_search(k_c, G_c, kpt_kc, tol=1e-4): 

66 # search for k1 (in kpt_kc) and k0 (in alldir), such that 

67 # k1 - k - G + k0 = 0 

68 alldir_dc = np.array( 

69 [ 

70 [0, 0, 0], 

71 [1, 0, 0], 

72 [0, 1, 0], 

73 [0, 0, 1], 

74 [1, 1, 0], 

75 [1, 0, 1], 

76 [0, 1, 1], 

77 ], 

78 dtype=int, 

79 ) 

80 for k0_c in alldir_dc: 

81 for k1, k1_c in enumerate(kpt_kc): 

82 if np.linalg.norm(k1_c - k_c - G_c + k0_c) < tol: 

83 return k1, k0_c 

84 

85 raise ValueError( 

86 f'Wannier: Did not find matching kpoint for kpt={k_c}. ' 

87 'Probably non-uniform k-point grid' 

88 ) 

89 

90 

91def calculate_weights(cell_cc, normalize=True): 

92 """Weights are used for non-cubic cells, see PRB **61**, 10040 

93 If normalized they lose the physical dimension.""" 

94 alldirs_dc = np.array( 

95 [[1, 0, 0], [0, 1, 0], [0, 0, 1], [1, 1, 0], [1, 0, 1], [0, 1, 1]], 

96 dtype=int, 

97 ) 

98 g = cell_cc @ cell_cc.T 

99 # NOTE: Only first 3 of following 6 weights are presently used: 

100 w = np.zeros(6) 

101 w[0] = g[0, 0] - g[0, 1] - g[0, 2] 

102 w[1] = g[1, 1] - g[0, 1] - g[1, 2] 

103 w[2] = g[2, 2] - g[0, 2] - g[1, 2] 

104 w[3] = g[0, 1] 

105 w[4] = g[0, 2] 

106 w[5] = g[1, 2] 

107 # Make sure that first 3 Gdir vectors are included - 

108 # these are used to calculate Wanniercenters. 

109 Gdir_dc = alldirs_dc[:3] 

110 weight_d = w[:3] 

111 for d in range(3, 6): 

112 if abs(w[d]) > 1e-5: 

113 Gdir_dc = np.concatenate((Gdir_dc, alldirs_dc[d : d + 1])) 

114 weight_d = np.concatenate((weight_d, w[d : d + 1])) 

115 if normalize: 

116 weight_d /= max(abs(weight_d)) 

117 return weight_d, Gdir_dc 

118 

119 

120def steepest_descent(func, step=0.005, tolerance=1e-6, log=silent, **kwargs): 

121 fvalueold = 0.0 

122 fvalue = fvalueold + 10 

123 count = 0 

124 while abs((fvalue - fvalueold) / fvalue) > tolerance: 

125 fvalueold = fvalue 

126 dF = func.get_gradients() 

127 func.step(dF * step, **kwargs) 

128 fvalue = func.get_functional_value() 

129 count += 1 

130 log(f'SteepestDescent: iter={count}, value={fvalue}') 

131 

132 

133def md_min( 

134 func, step=0.25, tolerance=1e-6, max_iter=10000, log=silent, **kwargs 

135): 

136 log('Localize with step =', step, 'and tolerance =', tolerance) 

137 finit = func.get_functional_value() 

138 

139 t = -time() 

140 fvalueold = 0.0 

141 fvalue = fvalueold + 10 

142 count = 0 

143 V = np.zeros(func.get_gradients().shape, dtype=complex) 

144 

145 while abs((fvalue - fvalueold) / fvalue) > tolerance: 

146 fvalueold = fvalue 

147 dF = func.get_gradients() 

148 

149 V *= (dF * V.conj()).real > 0 

150 V += step * dF 

151 func.step(V, **kwargs) 

152 fvalue = func.get_functional_value() 

153 

154 if fvalue < fvalueold: 

155 step *= 0.5 

156 count += 1 

157 log(f'MDmin: iter={count}, step={step}, value={fvalue}') 

158 if count > max_iter: 

159 t += time() 

160 warnings.warn( 

161 'Max iterations reached: ' 

162 'iters=%s, step=%s, seconds=%0.2f, value=%0.4f' 

163 % (count, step, t, fvalue.real) 

164 ) 

165 break 

166 

167 t += time() 

168 log( 

169 '%d iterations in %0.2f seconds (%0.2f ms/iter), endstep = %s' 

170 % (count, t, t * 1000.0 / count, step) 

171 ) 

172 log(f'Initial value={finit}, Final value={fvalue}') 

173 

174 

175def rotation_from_projection(proj_nw, fixed, ortho=True): 

176 """Determine rotation and coefficient matrices from projections 

177 

178 proj_nw = <psi_n|p_w> 

179 psi_n: eigenstates 

180 p_w: localized function 

181 

182 Nb (n) = Number of bands 

183 Nw (w) = Number of wannier functions 

184 M (f) = Number of fixed states 

185 L (l) = Number of extra degrees of freedom 

186 U (u) = Number of non-fixed states 

187 """ 

188 

189 Nb, Nw = proj_nw.shape 

190 M = fixed 

191 L = Nw - M 

192 U = Nb - M 

193 

194 U_ww = np.empty((Nw, Nw), dtype=proj_nw.dtype) 

195 

196 # Set the section of the rotation matrix about the 'fixed' states 

197 U_ww[:M] = proj_nw[:M] 

198 

199 if L > 0: 

200 # If there are extra degrees of freedom we have to select L of them 

201 C_ul = np.empty((U, L), dtype=proj_nw.dtype) 

202 

203 # Get the projections on the 'non fixed' states 

204 proj_uw = proj_nw[M:] 

205 

206 # Obtain eigenvalues and eigevectors matrix 

207 eig_w, C_ww = np.linalg.eigh(dag(proj_uw) @ proj_uw) 

208 

209 # Sort columns of eigenvectors matrix according to the eigenvalues 

210 # magnitude, select only the L largest ones. Then use them to obtain 

211 # the parameter C matrix. 

212 C_ul[:] = proj_uw @ C_ww[:, np.argsort(-eig_w.real)[:L]] 

213 

214 # Compute the section of the rotation matrix about 'non fixed' states 

215 U_ww[M:] = dag(C_ul) @ proj_uw 

216 normalize(C_ul) 

217 else: 

218 # If there are no extra degrees of freedom we do not need any parameter 

219 # matrix C 

220 C_ul = np.empty((U, 0), dtype=proj_nw.dtype) 

221 

222 if ortho: 

223 # Orthogonalize with Lowdin to take the closest orthogonal set 

224 lowdin(U_ww) 

225 else: 

226 normalize(U_ww) 

227 

228 return U_ww, C_ul 

229 

230 

231def search_for_gamma_point(kpts): 

232 """Returns index of Gamma point in a list of k-points.""" 

233 gamma_idx = np.argmin([np.linalg.norm(kpt) for kpt in kpts]) 

234 if np.linalg.norm(kpts[gamma_idx]) >= 1e-14: 

235 gamma_idx = None 

236 return gamma_idx 

237 

238 

239def scdm(pseudo_nkG, kpts, fixed_k, Nw): 

240 """Compute localized orbitals with SCDM method 

241 

242 This method was published by Anil Damle and Lin Lin in Multiscale 

243 Modeling & Simulation 16, 1392–1410 (2018). 

244 For now only the isolated bands algorithm is implemented, because it is 

245 intended as a drop-in replacement for other initial guess methods for 

246 the ASE Wannier class. 

247 

248 pseudo_nkG = pseudo wave-functions on a real grid 

249 Ng (G) = number of real grid points 

250 kpts = List of k-points in the BZ 

251 Nk (k) = Number of k-points 

252 Nb (n) = Number of bands 

253 Nw (w) = Number of wannier functions 

254 fixed_k = Number of fixed states for each k-point 

255 L (l) = Number of extra degrees of freedom 

256 U (u) = Number of non-fixed states 

257 """ 

258 

259 gamma_idx = search_for_gamma_point(kpts) 

260 Nk = len(kpts) 

261 U_kww = [] 

262 C_kul = [] 

263 

264 # compute factorization only at Gamma point 

265 _, _, P = qr( 

266 pseudo_nkG[:, gamma_idx, :], 

267 mode='full', 

268 pivoting=True, 

269 check_finite=True, 

270 ) 

271 

272 for k in range(Nk): 

273 A_nw = pseudo_nkG[:, k, P[:Nw]] 

274 U_ww, C_ul = rotation_from_projection( 

275 proj_nw=A_nw, fixed=fixed_k[k], ortho=True 

276 ) 

277 U_kww.append(U_ww) 

278 C_kul.append(C_ul) 

279 

280 U_kww = np.asarray(U_kww) 

281 

282 return C_kul, U_kww 

283 

284 

285def arbitrary_s_orbitals(atoms, Ns, rng=np.random): 

286 """ 

287 Generate a list of Ns randomly placed s-orbitals close to at least 

288 one atom (< 1.5Å). 

289 The format of the list is the one required by GPAW in initial_wannier(). 

290 """ 

291 # Create dummy copy of the Atoms object and dummy H atom 

292 tmp_atoms = atoms.copy() 

293 tmp_atoms.append('H') 

294 s_pos = tmp_atoms.get_scaled_positions() 

295 

296 orbs = [] 

297 for _ in range(Ns): 

298 fine = False 

299 while not fine: 

300 # Random position 

301 x, y, z = rng.rand(3) 

302 s_pos[-1] = [x, y, z] 

303 tmp_atoms.set_scaled_positions(s_pos) 

304 

305 # Use dummy H atom to measure distance from any other atom 

306 dists = tmp_atoms.get_distances(a=-1, indices=range(len(atoms))) 

307 

308 # Check if it is close to at least one atom 

309 if (dists < 1.5).any(): 

310 fine = True 

311 

312 orbs.append([[x, y, z], 0, 1]) 

313 return orbs 

314 

315 

316def init_orbitals(atoms, ntot, rng=np.random): 

317 """ 

318 Place d-orbitals for every atom that has some in the valence states 

319 and then random s-orbitals close to at least one atom (< 1.5Å). 

320 The orbitals list format is compatible with GPAW.get_initial_wannier(). 

321 'atoms': ASE Atoms object 

322 'ntot': total number of needed orbitals 

323 'rng': generator random numbers 

324 """ 

325 

326 # List all the elements that should have occupied d-orbitals 

327 # in the valence states (according to GPAW setups) 

328 d_metals = set( 

329 list(range(21, 31)) 

330 + list(range(39, 52)) 

331 + list(range(57, 84)) 

332 + list(range(89, 113)) 

333 ) 

334 orbs = [] 

335 

336 # Start with zero orbitals 

337 No = 0 

338 

339 # Add d orbitals to each d-metal 

340 for i, z in enumerate(atoms.get_atomic_numbers()): 

341 if z in d_metals: 

342 No_new = No + 5 

343 if No_new <= ntot: 

344 orbs.append([i, 2, 1]) 

345 No = No_new 

346 

347 if No < ntot: 

348 # Add random s-like orbitals if there are not enough yet 

349 Ns = ntot - No 

350 orbs += arbitrary_s_orbitals(atoms, Ns, rng) 

351 

352 assert sum(orb[1] * 2 + 1 for orb in orbs) == ntot 

353 return orbs 

354 

355 

356def square_modulus_of_Z_diagonal(Z_dww): 

357 """ 

358 Square modulus of the Z matrix diagonal, the diagonal is taken 

359 for the indexes running on the WFs. 

360 """ 

361 return np.abs(Z_dww.diagonal(0, 1, 2)) ** 2 

362 

363 

364def get_kklst(kpt_kc, Gdir_dc): 

365 # Set the list of neighboring k-points k1, and the "wrapping" k0, 

366 # such that k1 - k - G + k0 = 0 

367 # 

368 # Example: kpoints = (-0.375,-0.125,0.125,0.375), dir=0 

369 # G = [0.25,0,0] 

370 # k=0.375, k1= -0.375 : -0.375-0.375-0.25 => k0=[1,0,0] 

371 # 

372 # For a gamma point calculation k1 = k = 0, k0 = [1,0,0] for dir=0 

373 Nk = len(kpt_kc) 

374 Ndir = len(Gdir_dc) 

375 

376 if Nk == 1: 

377 kklst_dk = np.zeros((Ndir, 1), int) 

378 k0_dkc = Gdir_dc.reshape(-1, 1, 3) 

379 else: 

380 kklst_dk = np.empty((Ndir, Nk), int) 

381 k0_dkc = np.empty((Ndir, Nk, 3), int) 

382 

383 # Distance between kpoints 

384 kdist_c = np.empty(3) 

385 for c in range(3): 

386 # make a sorted list of the kpoint values in this direction 

387 slist = np.argsort(kpt_kc[:, c], kind='mergesort') 

388 skpoints_kc = np.take(kpt_kc, slist, axis=0) 

389 kdist_c[c] = max( 

390 skpoints_kc[n + 1, c] - skpoints_kc[n, c] for n in range(Nk - 1) 

391 ) 

392 

393 for d, Gdir_c in enumerate(Gdir_dc): 

394 for k, k_c in enumerate(kpt_kc): 

395 # setup dist vector to next kpoint 

396 G_c = np.where(Gdir_c > 0, kdist_c, 0) 

397 if max(G_c) < 1e-4: 

398 kklst_dk[d, k] = k 

399 k0_dkc[d, k] = Gdir_c 

400 else: 

401 kklst_dk[d, k], k0_dkc[d, k] = neighbor_k_search( 

402 k_c, G_c, kpt_kc 

403 ) 

404 return kklst_dk, k0_dkc 

405 

406 

407def get_invkklst(kklst_dk): 

408 Ndir, Nk = kklst_dk.shape 

409 invkklst_dk = np.empty(kklst_dk.shape, int) 

410 for d in range(Ndir): 

411 for k1 in range(Nk): 

412 invkklst_dk[d, k1] = kklst_dk[d].tolist().index(k1) 

413 return invkklst_dk 

414 

415 

416def choose_states(calcdata, fixedenergy, fixedstates, Nk, nwannier, log, spin): 

417 if fixedenergy is None and fixedstates is not None: 

418 if isinstance(fixedstates, int): 

419 fixedstates = [fixedstates] * Nk 

420 fixedstates_k = np.array(fixedstates, int) 

421 elif fixedenergy is not None and fixedstates is None: 

422 # Setting number of fixed states and EDF from given energy cutoff. 

423 # All states below this energy cutoff are fixed. 

424 # The reference energy is Ef for metals and CBM for insulators. 

425 if calcdata.gap < 0.01 or fixedenergy < 0.01: 

426 cutoff = fixedenergy + calcdata.fermi_level 

427 else: 

428 cutoff = fixedenergy + calcdata.lumo 

429 

430 # Find the states below the energy cutoff at each k-point 

431 tmp_fixedstates_k = [] 

432 for k in range(Nk): 

433 eps_n = calcdata.eps_skn[spin, k] 

434 kindex = eps_n.searchsorted(cutoff) 

435 tmp_fixedstates_k.append(kindex) 

436 fixedstates_k = np.array(tmp_fixedstates_k, int) 

437 elif fixedenergy is not None and fixedstates is not None: 

438 raise RuntimeError('You can not set both fixedenergy and fixedstates') 

439 

440 if nwannier == 'auto': 

441 if fixedenergy is None and fixedstates is None: 

442 # Assume the fixedexergy parameter equal to 0 and 

443 # find the states below the Fermi level at each k-point. 

444 log( 

445 "nwannier=auto but no 'fixedenergy' or 'fixedstates'", 

446 'parameter was provided, using Fermi level as', 

447 'energy cutoff.', 

448 ) 

449 tmp_fixedstates_k = [] 

450 for k in range(Nk): 

451 eps_n = calcdata.eps_skn[spin, k] 

452 kindex = eps_n.searchsorted(calcdata.fermi_level) 

453 tmp_fixedstates_k.append(kindex) 

454 fixedstates_k = np.array(tmp_fixedstates_k, int) 

455 nwannier = np.max(fixedstates_k) 

456 

457 # Without user choice just set nwannier fixed states without EDF 

458 if fixedstates is None and fixedenergy is None: 

459 fixedstates_k = np.array([nwannier] * Nk, int) 

460 

461 return fixedstates_k, nwannier 

462 

463 

464def get_eigenvalues(calc): 

465 nspins = calc.get_number_of_spins() 

466 nkpts = len(calc.get_ibz_k_points()) 

467 nbands = calc.get_number_of_bands() 

468 eps_skn = np.empty((nspins, nkpts, nbands)) 

469 

470 for ispin in range(nspins): 

471 for ikpt in range(nkpts): 

472 eps_skn[ispin, ikpt] = calc.get_eigenvalues(kpt=ikpt, spin=ispin) 

473 return eps_skn 

474 

475 

476class CalcData: 

477 def __init__(self, kpt_kc, atoms, fermi_level, lumo, eps_skn, gap): 

478 self.kpt_kc = kpt_kc 

479 self.atoms = atoms 

480 self.fermi_level = fermi_level 

481 self.lumo = lumo 

482 self.eps_skn = eps_skn 

483 self.gap = gap 

484 

485 @property 

486 def nbands(self): 

487 return self.eps_skn.shape[2] 

488 

489 

490def get_calcdata(calc): 

491 kpt_kc = calc.get_bz_k_points() 

492 # Make sure there is no symmetry reduction 

493 if len(calc.get_ibz_k_points()) != len(kpt_kc): 

494 raise RuntimeError( 

495 'K-point symmetry is not currently supported. ' 

496 "Please re-run your calculator with symmetry='off'." 

497 ) 

498 

499 lumo = calc.get_homo_lumo()[1] 

500 gap = bandgap(calc=calc)[0] 

501 return CalcData( 

502 kpt_kc=kpt_kc, 

503 atoms=calc.get_atoms(), 

504 fermi_level=calc.get_fermi_level(), 

505 lumo=lumo, 

506 eps_skn=get_eigenvalues(calc), 

507 gap=gap, 

508 ) 

509 

510 

511class Wannier: 

512 """Partly occupied Wannier functions 

513 

514 Find the set of partly occupied Wannier functions according to 

515 Thygesen, Hansen and Jacobsen PRB v72 i12 p125119 2005. 

516 """ 

517 

518 def __init__( 

519 self, 

520 nwannier, 

521 calc, 

522 file=None, 

523 nbands=None, 

524 fixedenergy=None, 

525 fixedstates=None, 

526 spin=0, 

527 initialwannier='orbitals', 

528 functional='std', 

529 rng=np.random, 

530 log=silent, 

531 ): 

532 """ 

533 Required arguments: 

534 

535 ``nwannier``: The number of Wannier functions you wish to construct. 

536 This must be at least half the number of electrons in the system 

537 and at most equal to the number of bands in the calculation. 

538 It can also be set to 'auto' in order to automatically choose the 

539 minimum number of needed Wannier function based on the 

540 ``fixedenergy`` / ``fixedstates`` parameter. 

541 

542 ``calc``: A converged DFT calculator class. 

543 If ``file`` arg. is not provided, the calculator *must* provide the 

544 method ``get_wannier_localization_matrix``, and contain the 

545 wavefunctions (save files with only the density is not enough). 

546 If the localization matrix is read from file, this is not needed, 

547 unless ``get_function`` or ``write_cube`` is called. 

548 

549 Optional arguments: 

550 

551 ``nbands``: Bands to include in localization. 

552 The number of bands considered by Wannier can be smaller than the 

553 number of bands in the calculator. This is useful if the highest 

554 bands of the DFT calculation are not well converged. 

555 

556 ``spin``: The spin channel to be considered. 

557 The Wannier code treats each spin channel independently. 

558 

559 ``fixedenergy`` / ``fixedstates``: Fixed part of Hilbert space. 

560 Determine the fixed part of Hilbert space by either a maximal 

561 energy *or* a number of bands (possibly a list for multiple 

562 k-points). 

563 Default is None meaning that the number of fixed states is equated 

564 to ``nwannier``. 

565 The maximal energy is relative to the CBM if there is a finite 

566 bandgap or to the Fermi level if there is none. 

567 

568 ``file``: Read localization and rotation matrices from this file. 

569 

570 ``initialwannier``: Initial guess for Wannier rotation matrix. 

571 Can be 'bloch' to start from the Bloch states, 'random' to be 

572 randomized, 'orbitals' to start from atom-centered d-orbitals and 

573 randomly placed gaussian centers (see init_orbitals()), 

574 'scdm' to start from localized state selected with SCDM 

575 or a list passed to calc.get_initial_wannier. 

576 

577 ``functional``: The functional used to measure the localization. 

578 Can be 'std' for the standard quadratic functional from the PRB 

579 paper, 'var' to add a variance minimizing term. 

580 

581 ``rng``: Random number generator for ``initialwannier``. 

582 

583 ``log``: Function which logs, such as print(). 

584 """ 

585 # Bloch phase sign convention. 

586 # May require special cases depending on which code is used. 

587 sign = -1 

588 

589 self.log = log 

590 self.calc = calc 

591 

592 self.spin = spin 

593 self.functional = functional 

594 self.initialwannier = initialwannier 

595 self.log('Using functional:', functional) 

596 

597 self.calcdata = get_calcdata(calc) 

598 

599 self.kptgrid = get_monkhorst_pack_size_and_offset(self.kpt_kc)[0] 

600 self.calcdata.kpt_kc *= sign 

601 

602 self.largeunitcell_cc = (self.unitcell_cc.T * self.kptgrid).T 

603 self.weight_d, self.Gdir_dc = calculate_weights(self.largeunitcell_cc) 

604 assert len(self.weight_d) == len(self.Gdir_dc) 

605 

606 if nbands is None: 

607 # XXX Can work with other number of bands than calculator. 

608 # Is this case properly tested, lest we confuse them? 

609 nbands = self.calcdata.nbands 

610 self.nbands = nbands 

611 

612 self.fixedstates_k, self.nwannier = choose_states( 

613 self.calcdata, 

614 fixedenergy, 

615 fixedstates, 

616 self.Nk, 

617 nwannier, 

618 log, 

619 spin, 

620 ) 

621 

622 # Compute the number of extra degrees of freedom (EDF) 

623 self.edf_k = self.nwannier - self.fixedstates_k 

624 

625 self.log(f'Wannier: Fixed states : {self.fixedstates_k}') 

626 self.log(f'Wannier: Extra degrees of freedom: {self.edf_k}') 

627 

628 self.kklst_dk, k0_dkc = get_kklst(self.kpt_kc, self.Gdir_dc) 

629 

630 # Set the inverse list of neighboring k-points 

631 self.invkklst_dk = get_invkklst(self.kklst_dk) 

632 

633 Nw = self.nwannier 

634 Nb = self.nbands 

635 self.Z_dkww = np.empty((self.Ndir, self.Nk, Nw, Nw), complex) 

636 self.V_knw = np.zeros((self.Nk, Nb, Nw), complex) 

637 

638 if file is None: 

639 self.Z_dknn = self.new_Z(calc, k0_dkc) 

640 self.initialize(file=file, initialwannier=initialwannier, rng=rng) 

641 

642 @property 

643 def atoms(self): 

644 return self.calcdata.atoms 

645 

646 @property 

647 def kpt_kc(self): 

648 return self.calcdata.kpt_kc 

649 

650 @property 

651 def Ndir(self): 

652 return len(self.weight_d) # Number of directions 

653 

654 @property 

655 def Nk(self): 

656 return len(self.kpt_kc) 

657 

658 def new_Z(self, calc, k0_dkc): 

659 Nb = self.nbands 

660 Z_dknn = np.empty((self.Ndir, self.Nk, Nb, Nb), complex) 

661 for d, dirG in enumerate(self.Gdir_dc): 

662 for k in range(self.Nk): 

663 k1 = self.kklst_dk[d, k] 

664 k0_c = k0_dkc[d, k] 

665 Z_dknn[d, k] = calc.get_wannier_localization_matrix( 

666 nbands=Nb, 

667 dirG=dirG, 

668 kpoint=k, 

669 nextkpoint=k1, 

670 G_I=k0_c, 

671 spin=self.spin, 

672 ) 

673 return Z_dknn 

674 

675 @property 

676 def unitcell_cc(self): 

677 return self.atoms.cell 

678 

679 @property 

680 def U_kww(self): 

681 return self.wannier_state.U_kww 

682 

683 @property 

684 def C_kul(self): 

685 return self.wannier_state.C_kul 

686 

687 def initialize(self, file=None, initialwannier='random', rng=np.random): 

688 """Re-initialize current rotation matrix. 

689 

690 Keywords are identical to those of the constructor. 

691 """ 

692 from ase.dft.wannierstate import WannierSpec, WannierState 

693 

694 spec = WannierSpec( 

695 self.Nk, self.nwannier, self.nbands, self.fixedstates_k 

696 ) 

697 

698 if file is not None: 

699 with paropen(file, 'r') as fd: 

700 Z_dknn, U_kww, C_kul = read_json(fd, always_array=False) 

701 self.Z_dknn = Z_dknn 

702 wannier_state = WannierState(C_kul, U_kww) 

703 elif initialwannier == 'bloch': 

704 # Set U and C to pick the lowest Bloch states 

705 wannier_state = spec.bloch(self.edf_k) 

706 elif initialwannier == 'random': 

707 wannier_state = spec.random(rng, self.edf_k) 

708 elif initialwannier == 'orbitals': 

709 orbitals = init_orbitals(self.atoms, self.nwannier, rng) 

710 wannier_state = spec.initial_orbitals( 

711 self.calc, orbitals, self.kptgrid, self.edf_k, self.spin 

712 ) 

713 elif initialwannier == 'scdm': 

714 wannier_state = spec.scdm(self.calc, self.kpt_kc, self.spin) 

715 else: 

716 wannier_state = spec.initial_wannier( 

717 self.calc, initialwannier, self.kptgrid, self.edf_k, self.spin 

718 ) 

719 

720 self.wannier_state = wannier_state 

721 self.update() 

722 

723 def save(self, file): 

724 """Save information on localization and rotation matrices to file.""" 

725 with paropen(file, 'w') as fd: 

726 write_json(fd, (self.Z_dknn, self.U_kww, self.C_kul)) 

727 

728 def update(self): 

729 # Update large rotation matrix V (from rotation U and coeff C) 

730 for k, M in enumerate(self.fixedstates_k): 

731 self.V_knw[k, :M] = self.U_kww[k, :M] 

732 if M < self.nwannier: 

733 self.V_knw[k, M:] = self.C_kul[k] @ self.U_kww[k, M:] 

734 # else: self.V_knw[k, M:] = 0.0 

735 

736 # Calculate the Zk matrix from the large rotation matrix: 

737 # Zk = V^d[k] Zbloch V[k1] 

738 for d in range(self.Ndir): 

739 for k in range(self.Nk): 

740 k1 = self.kklst_dk[d, k] 

741 self.Z_dkww[d, k] = dag(self.V_knw[k]) @ ( 

742 self.Z_dknn[d, k] @ self.V_knw[k1] 

743 ) 

744 

745 # Update the new Z matrix 

746 self.Z_dww = self.Z_dkww.sum(axis=1) / self.Nk 

747 

748 def get_optimal_nwannier(self, nwrange=5, random_reps=5, tolerance=1e-6): 

749 """ 

750 The optimal value for 'nwannier', maybe. 

751 

752 The optimal value is the one that gives the lowest average value for 

753 the spread of the most delocalized Wannier function in the set. 

754 

755 ``nwrange``: number of different values to try for 'nwannier', the 

756 values will span a symmetric range around ``nwannier`` if possible. 

757 

758 ``random_reps``: number of repetitions with random seed, the value is 

759 then an average over these repetitions. 

760 

761 ``tolerance``: tolerance for the gradient descent algorithm, can be 

762 useful to increase the speed, with a cost in accuracy. 

763 """ 

764 

765 # Define the range of values to try based on the maximum number of fixed 

766 # states (that is the minimum number of WFs we need) and the number of 

767 # available bands we have. 

768 max_number_fixedstates = np.max(self.fixedstates_k) 

769 

770 min_range_value = max( 

771 self.nwannier - int(np.floor(nwrange / 2)), max_number_fixedstates 

772 ) 

773 max_range_value = min(min_range_value + nwrange, self.nbands + 1) 

774 Nws = np.arange(min_range_value, max_range_value) 

775 

776 # If there is no randomness, there is no need to repeat 

777 random_initials = ['random', 'orbitals'] 

778 if self.initialwannier not in random_initials: 

779 random_reps = 1 

780 

781 t = -time() 

782 avg_max_spreads = np.zeros(len(Nws)) 

783 for j, Nw in enumerate(Nws): 

784 self.log('Trying with Nw =', Nw) 

785 

786 # Define once with the fastest 'initialwannier', 

787 # then initialize with random seeds in the for loop 

788 wan = Wannier( 

789 nwannier=int(Nw), 

790 calc=self.calc, 

791 nbands=self.nbands, 

792 spin=self.spin, 

793 functional=self.functional, 

794 initialwannier='bloch', 

795 log=self.log, 

796 rng=self.rng, 

797 ) 

798 wan.fixedstates_k = self.fixedstates_k 

799 wan.edf_k = wan.nwannier - wan.fixedstates_k 

800 

801 max_spreads = np.zeros(random_reps) 

802 for i in range(random_reps): 

803 wan.initialize(initialwannier=self.initialwannier) 

804 wan.localize(tolerance=tolerance) 

805 max_spreads[i] = np.max(wan.get_spreads()) 

806 

807 avg_max_spreads[j] = max_spreads.mean() 

808 

809 self.log('Average spreads: ', avg_max_spreads) 

810 t += time() 

811 self.log(f'Execution time: {t:.1f}s') 

812 

813 return Nws[np.argmin(avg_max_spreads)] 

814 

815 def get_centers(self, scaled=False): 

816 """Calculate the Wannier centers 

817 

818 :: 

819 

820 pos = L / 2pi * phase(diag(Z)) 

821 """ 

822 coord_wc = np.angle(self.Z_dww[:3].diagonal(0, 1, 2)).T / (2 * pi) % 1 

823 if not scaled: 

824 coord_wc = coord_wc @ self.largeunitcell_cc 

825 return coord_wc 

826 

827 def get_radii(self): 

828 r"""Calculate the spread of the Wannier functions. 

829 

830 :: 

831 

832 -- / L \ 2 2 

833 radius**2 = - > | --- | ln |Z| 

834 --d \ 2pi / 

835 

836 Note that this function can fail with some Bravais lattices, 

837 see `get_spreads()` for a more robust alternative. 

838 """ 

839 r2 = -(self.largeunitcell_cc.diagonal() ** 2 / (2 * pi) ** 2) @ np.log( 

840 abs(self.Z_dww[:3].diagonal(0, 1, 2)) ** 2 

841 ) 

842 return np.sqrt(r2) 

843 

844 def get_spreads(self): 

845 r"""Calculate the spread of the Wannier functions in Ų. 

846 The definition is based on eq. 13 in PRB61-15 by Berghold and Mundy. 

847 

848 :: 

849 

850 / 1 \ 2 -- 2 

851 spread = - |----| > W_d ln |Z_dw| 

852 \2 pi/ --d 

853 

854 

855 """ 

856 # compute weights without normalization, to keep physical dimension 

857 weight_d, _ = calculate_weights(self.largeunitcell_cc, normalize=False) 

858 Z2_dw = square_modulus_of_Z_diagonal(self.Z_dww) 

859 spread_w = -(np.log(Z2_dw).T @ weight_d).real / (2 * np.pi) ** 2 

860 return spread_w 

861 

862 def get_spectral_weight(self, w): 

863 return abs(self.V_knw[:, :, w]) ** 2 / self.Nk 

864 

865 def get_pdos(self, w, energies, width): 

866 """Projected density of states (PDOS). 

867 

868 Returns the (PDOS) for Wannier function ``w``. The calculation 

869 is performed over the energy grid specified in energies. The 

870 PDOS is produced as a sum of Gaussians centered at the points 

871 of the energy grid and with the specified width. 

872 """ 

873 spec_kn = self.get_spectral_weight(w) 

874 dos = np.zeros(len(energies)) 

875 for k, spec_n in enumerate(spec_kn): 

876 eig_n = self.calcdata.eps_skn[self.spin, k] 

877 for weight, eig in zip(spec_n, eig_n): 

878 # Add gaussian centered at the eigenvalue 

879 x = ((energies - eig) / width) ** 2 

880 dos += weight * np.exp(-x.clip(0.0, 40.0)) / (sqrt(pi) * width) 

881 return dos 

882 

883 def translate(self, w, R): 

884 """Translate the w'th Wannier function 

885 

886 The distance vector R = [n1, n2, n3], is in units of the basis 

887 vectors of the small cell. 

888 """ 

889 for kpt_c, U_ww in zip(self.kpt_kc, self.U_kww): 

890 U_ww[:, w] *= np.exp(2.0j * pi * (np.array(R) @ kpt_c)) 

891 self.update() 

892 

893 def translate_to_cell(self, w, cell): 

894 """Translate the w'th Wannier function to specified cell""" 

895 scaled_c = np.angle(self.Z_dww[:3, w, w]) * self.kptgrid / (2 * pi) 

896 trans = np.array(cell) - np.floor(scaled_c) 

897 self.translate(w, trans) 

898 

899 def translate_all_to_cell(self, cell=(0, 0, 0)): 

900 r"""Translate all Wannier functions to specified cell. 

901 

902 Move all Wannier orbitals to a specific unit cell. There 

903 exists an arbitrariness in the positions of the Wannier 

904 orbitals relative to the unit cell. This method can move all 

905 orbitals to the unit cell specified by ``cell``. For a 

906 `\Gamma`-point calculation, this has no effect. For a 

907 **k**-point calculation the periodicity of the orbitals are 

908 given by the large unit cell defined by repeating the original 

909 unitcell by the number of **k**-points in each direction. In 

910 this case it is useful to move the orbitals away from the 

911 boundaries of the large cell before plotting them. For a bulk 

912 calculation with, say 10x10x10 **k** points, one could move 

913 the orbitals to the cell [2,2,2]. In this way the pbc 

914 boundary conditions will not be noticed. 

915 """ 

916 scaled_wc = ( 

917 np.angle(self.Z_dww[:3].diagonal(0, 1, 2)).T 

918 * self.kptgrid 

919 / (2 * pi) 

920 ) 

921 trans_wc = np.array(cell)[None] - np.floor(scaled_wc) 

922 for kpt_c, U_ww in zip(self.kpt_kc, self.U_kww): 

923 U_ww *= np.exp(2.0j * pi * (trans_wc @ kpt_c)) 

924 self.update() 

925 

926 def distances(self, R): 

927 """Relative distances between centers. 

928 

929 Returns a matrix with the distances between different Wannier centers. 

930 R = [n1, n2, n3] is in units of the basis vectors of the small cell 

931 and allows one to measure the distance with centers moved to a 

932 different small cell. 

933 The dimension of the matrix is [Nw, Nw]. 

934 """ 

935 Nw = self.nwannier 

936 cen = self.get_centers() 

937 r1 = cen.repeat(Nw, axis=0).reshape(Nw, Nw, 3) 

938 r2 = cen.copy() 

939 for i in range(3): 

940 r2 += self.unitcell_cc[i] * R[i] 

941 

942 r2 = np.swapaxes(r2.repeat(Nw, axis=0).reshape(Nw, Nw, 3), 0, 1) 

943 return np.sqrt(np.sum((r1 - r2) ** 2, axis=-1)) 

944 

945 @functools.lru_cache(maxsize=10000) 

946 def _get_hopping(self, n1, n2, n3): 

947 """Returns the matrix H(R)_nm=<0,n|H|R,m>. 

948 

949 :: 

950 

951 1 _ -ik.R 

952 H(R) = <0,n|H|R,m> = --- >_ e H(k) 

953 Nk k 

954 

955 where R = (n1, n2, n3) is the cell-distance (in units of the basis 

956 vectors of the small cell) and n,m are indices of the Wannier functions. 

957 This function caches up to 'maxsize' results. 

958 """ 

959 R = np.array([n1, n2, n3], float) 

960 H_ww = np.zeros([self.nwannier, self.nwannier], complex) 

961 for k, kpt_c in enumerate(self.kpt_kc): 

962 phase = np.exp(-2.0j * pi * (np.array(R) @ kpt_c)) 

963 H_ww += self.get_hamiltonian(k) * phase 

964 return H_ww / self.Nk 

965 

966 def get_hopping(self, R): 

967 """Returns the matrix H(R)_nm=<0,n|H|R,m>. 

968 

969 :: 

970 

971 1 _ -ik.R 

972 H(R) = <0,n|H|R,m> = --- >_ e H(k) 

973 Nk k 

974 

975 where R is the cell-distance (in units of the basis vectors of 

976 the small cell) and n,m are indices of the Wannier functions. 

977 """ 

978 return self._get_hopping(R[0], R[1], R[2]) 

979 

980 def get_hamiltonian(self, k): 

981 """Get Hamiltonian at existing k-vector of index k 

982 

983 :: 

984 

985 dag 

986 H(k) = V diag(eps ) V 

987 k k k 

988 """ 

989 eps_n = self.calcdata.eps_skn[self.spin, k, : self.nbands] 

990 V_nw = self.V_knw[k] 

991 return (dag(V_nw) * eps_n) @ V_nw 

992 

993 def get_hamiltonian_kpoint(self, kpt_c): 

994 """Get Hamiltonian at some new arbitrary k-vector 

995 

996 :: 

997 

998 _ ik.R 

999 H(k) = >_ e H(R) 

1000 R 

1001 

1002 Warning: This method moves all Wannier functions to cell (0, 0, 0) 

1003 """ 

1004 self.log('Translating all Wannier functions to cell (0, 0, 0)') 

1005 self.translate_all_to_cell() 

1006 max = (self.kptgrid - 1) // 2 

1007 N1, N2, N3 = max 

1008 Hk = np.zeros([self.nwannier, self.nwannier], complex) 

1009 for n1 in range(-N1, N1 + 1): 

1010 for n2 in range(-N2, N2 + 1): 

1011 for n3 in range(-N3, N3 + 1): 

1012 R = np.array([n1, n2, n3], float) 

1013 hop_ww = self.get_hopping(R) 

1014 phase = np.exp(+2.0j * pi * (R @ kpt_c)) 

1015 Hk += hop_ww * phase 

1016 return Hk 

1017 

1018 def get_function(self, index, repeat=None): 

1019 r"""Get Wannier function on grid. 

1020 

1021 Returns an array with the funcion values of the indicated Wannier 

1022 function on a grid with the size of the *repeated* unit cell. 

1023 

1024 For a calculation using **k**-points the relevant unit cell for 

1025 eg. visualization of the Wannier orbitals is not the original unit 

1026 cell, but rather a larger unit cell defined by repeating the 

1027 original unit cell by the number of **k**-points in each direction. 

1028 Note that for a `\Gamma`-point calculation the large unit cell 

1029 coinsides with the original unit cell. 

1030 The large unitcell also defines the periodicity of the Wannier 

1031 orbitals. 

1032 

1033 ``index`` can be either a single WF or a coordinate vector in terms 

1034 of the WFs. 

1035 """ 

1036 

1037 # Default size of plotting cell is the one corresponding to k-points. 

1038 if repeat is None: 

1039 repeat = self.kptgrid 

1040 N1, N2, N3 = repeat 

1041 

1042 dim = self.calc.get_number_of_grid_points() 

1043 largedim = dim * [N1, N2, N3] 

1044 

1045 wanniergrid = np.zeros(largedim, dtype=complex) 

1046 for k, kpt_c in enumerate(self.kpt_kc): 

1047 # The coordinate vector of wannier functions 

1048 if isinstance(index, int): 

1049 vec_n = self.V_knw[k, :, index] 

1050 else: 

1051 vec_n = self.V_knw[k] @ index 

1052 

1053 wan_G = np.zeros(dim, complex) 

1054 for n, coeff in enumerate(vec_n): 

1055 wan_G += coeff * self.calc.get_pseudo_wave_function( 

1056 n, k, self.spin, pad=True 

1057 ) 

1058 

1059 # Distribute the small wavefunction over large cell: 

1060 for n1 in range(N1): 

1061 for n2 in range(N2): 

1062 for n3 in range(N3): # sign? 

1063 e = np.exp(-2.0j * pi * np.array([n1, n2, n3]) @ kpt_c) 

1064 wanniergrid[ 

1065 n1 * dim[0] : (n1 + 1) * dim[0], 

1066 n2 * dim[1] : (n2 + 1) * dim[1], 

1067 n3 * dim[2] : (n3 + 1) * dim[2], 

1068 ] += e * wan_G 

1069 

1070 # Normalization 

1071 wanniergrid /= np.sqrt(self.Nk) 

1072 return wanniergrid 

1073 

1074 def write_cube(self, index, fname, repeat=None, angle=False): 

1075 """ 

1076 Dump specified Wannier function to a cube file. 

1077 

1078 Arguments: 

1079 

1080 ``index``: Integer, index of the Wannier function to save. 

1081 

1082 ``repeat``: Array of integer, repeat supercell and Wannier function. 

1083 

1084 ``fname``: Name of the cube file. 

1085 

1086 ``angle``: If False, save the absolute value. If True, save 

1087 the complex phase of the Wannier function. 

1088 """ 

1089 from ase.io import write 

1090 

1091 # Default size of plotting cell is the one corresponding to k-points. 

1092 if repeat is None: 

1093 repeat = self.kptgrid 

1094 

1095 # Remove constraints, some are not compatible with repeat() 

1096 atoms = self.atoms.copy() 

1097 atoms.set_constraint() 

1098 atoms = atoms * repeat 

1099 func = self.get_function(index, repeat) 

1100 

1101 # Compute absolute value or complex angle 

1102 if angle: 

1103 data = np.angle(func) 

1104 else: 

1105 if self.Nk == 1: 

1106 func *= np.exp(-1.0j * np.angle(func.max())) 

1107 func = abs(func) 

1108 data = func 

1109 

1110 write(fname, atoms, data=data, format='cube') 

1111 

1112 def localize( 

1113 self, step=0.25, tolerance=1e-08, updaterot=True, updatecoeff=True 

1114 ): 

1115 """Optimize rotation to give maximal localization""" 

1116 md_min( 

1117 self, 

1118 step=step, 

1119 tolerance=tolerance, 

1120 log=self.log, 

1121 updaterot=updaterot, 

1122 updatecoeff=updatecoeff, 

1123 ) 

1124 

1125 def get_functional_value(self): 

1126 """Calculate the value of the spread functional. 

1127 

1128 :: 

1129 

1130 Tr[|ZI|^2]=sum(I)sum(n) w_i|Z_(i)_nn|^2, 

1131 

1132 where w_i are weights. 

1133 

1134 If the functional is set to 'var' it subtracts a variance term 

1135 

1136 :: 

1137 

1138 Nw * var(sum(n) w_i|Z_(i)_nn|^2), 

1139 

1140 where Nw is the number of WFs ``nwannier``. 

1141 """ 

1142 a_w = self._spread_contributions() 

1143 if self.functional == 'std': 

1144 fun = np.sum(a_w) 

1145 elif self.functional == 'var': 

1146 fun = np.sum(a_w) - self.nwannier * np.var(a_w) 

1147 self.log( 

1148 f'std: {np.sum(a_w):.4f}', 

1149 f'\tvar: {self.nwannier * np.var(a_w):.4f}', 

1150 ) 

1151 return fun 

1152 

1153 def get_gradients(self): 

1154 # Determine gradient of the spread functional. 

1155 # 

1156 # The gradient for a rotation A_kij is:: 

1157 # 

1158 # dU = dRho/dA_{k,i,j} = sum(I) sum(k') 

1159 # + Z_jj Z_kk',ij^* - Z_ii Z_k'k,ij^* 

1160 # - Z_ii^* Z_kk',ji + Z_jj^* Z_k'k,ji 

1161 # 

1162 # The gradient for a change of coefficients is:: 

1163 # 

1164 # dRho/da^*_{k,i,j} = sum(I) [[(Z_0)_{k} V_{k'} diag(Z^*) + 

1165 # (Z_0_{k''})^d V_{k''} diag(Z)] * 

1166 # U_k^d]_{N+i,N+j} 

1167 # 

1168 # where diag(Z) is a square,diagonal matrix with Z_nn in the diagonal, 

1169 # k' = k + dk and k = k'' + dk. 

1170 # 

1171 # The extra degrees of freedom chould be kept orthonormal to the fixed 

1172 # space, thus we introduce lagrange multipliers, and minimize instead:: 

1173 # 

1174 # Rho_L = Rho - sum_{k,n,m} lambda_{k,nm} <c_{kn}|c_{km}> 

1175 # 

1176 # for this reason the coefficient gradients should be multiplied 

1177 # by (1 - c c^dag). 

1178 

1179 Nb = self.nbands 

1180 Nw = self.nwannier 

1181 

1182 if self.functional == 'var': 

1183 O_w = self._spread_contributions() 

1184 O_sum = np.sum(O_w) 

1185 

1186 dU = [] 

1187 dC = [] 

1188 for k in range(self.Nk): 

1189 M = self.fixedstates_k[k] 

1190 L = self.edf_k[k] 

1191 U_ww = self.U_kww[k] 

1192 C_ul = self.C_kul[k] 

1193 Utemp_ww = np.zeros((Nw, Nw), complex) 

1194 Ctemp_nw = np.zeros((Nb, Nw), complex) 

1195 

1196 for d, weight in enumerate(self.weight_d): 

1197 if abs(weight) < 1.0e-6: 

1198 continue 

1199 

1200 Z_knn = self.Z_dknn[d] 

1201 diagZ_w = self.Z_dww[d].diagonal() 

1202 Zii_ww = np.repeat(diagZ_w, Nw).reshape(Nw, Nw) 

1203 if self.functional == 'var': 

1204 diagOZ_w = O_w * diagZ_w 

1205 OZii_ww = np.repeat(diagOZ_w, Nw).reshape(Nw, Nw) 

1206 

1207 k1 = self.kklst_dk[d, k] 

1208 k2 = self.invkklst_dk[d, k] 

1209 V_knw = self.V_knw 

1210 Z_kww = self.Z_dkww[d] 

1211 

1212 if L > 0: 

1213 Ctemp_nw += weight * ( 

1214 ( 

1215 (Z_knn[k] @ V_knw[k1]) * diagZ_w.conj() 

1216 + (dag(Z_knn[k2]) @ V_knw[k2]) * diagZ_w 

1217 ) 

1218 @ dag(U_ww) 

1219 ) 

1220 

1221 if self.functional == 'var': 

1222 # Gradient of the variance term, split in two terms 

1223 def variance_term_computer(factor): 

1224 result = ( 

1225 self.nwannier 

1226 * 2 

1227 * weight 

1228 * ( 

1229 ( 

1230 (Z_knn[k] @ V_knw[k1]) * factor.conj() 

1231 + (dag(Z_knn[k2]) @ V_knw[k2]) * factor 

1232 ) 

1233 @ dag(U_ww) 

1234 ) 

1235 / Nw**2 

1236 ) 

1237 return result 

1238 

1239 first_term = ( 

1240 O_sum * variance_term_computer(diagZ_w) / Nw**2 

1241 ) 

1242 

1243 second_term = -variance_term_computer(diagOZ_w) / Nw 

1244 

1245 Ctemp_nw += first_term + second_term 

1246 

1247 temp = Zii_ww.T * Z_kww[k].conj() - Zii_ww * Z_kww[k2].conj() 

1248 Utemp_ww += weight * (temp - dag(temp)) 

1249 

1250 if self.functional == 'var': 

1251 Utemp_ww += ( 

1252 self.nwannier 

1253 * 2 

1254 * O_sum 

1255 * weight 

1256 * (temp - dag(temp)) 

1257 / Nw**2 

1258 ) 

1259 

1260 temp = ( 

1261 OZii_ww.T * Z_kww[k].conj() - OZii_ww * Z_kww[k2].conj() 

1262 ) 

1263 Utemp_ww -= ( 

1264 self.nwannier * 2 * weight * (temp - dag(temp)) / Nw 

1265 ) 

1266 

1267 dU.append(Utemp_ww.ravel()) 

1268 

1269 if L > 0: 

1270 # Ctemp now has same dimension as V, the gradient is in the 

1271 # lower-right (Nb-M) x L block 

1272 Ctemp_ul = Ctemp_nw[M:, M:] 

1273 G_ul = Ctemp_ul - ((C_ul @ dag(C_ul)) @ Ctemp_ul) 

1274 dC.append(G_ul.ravel()) 

1275 

1276 return np.concatenate(dU + dC) 

1277 

1278 def _spread_contributions(self): 

1279 """ 

1280 Compute the contribution of each WF to the spread functional. 

1281 """ 

1282 return (square_modulus_of_Z_diagonal(self.Z_dww).T @ self.weight_d).real 

1283 

1284 def step(self, dX, updaterot=True, updatecoeff=True): 

1285 # dX is (A, dC) where U->Uexp(-A) and C->C+dC 

1286 Nw = self.nwannier 

1287 Nk = self.Nk 

1288 M_k = self.fixedstates_k 

1289 L_k = self.edf_k 

1290 if updaterot: 

1291 A_kww = dX[: Nk * Nw**2].reshape(Nk, Nw, Nw) 

1292 for U, A in zip(self.U_kww, A_kww): 

1293 H = -1.0j * A.conj() 

1294 epsilon, Z = np.linalg.eigh(H) 

1295 # Z contains the eigenvectors as COLUMNS. 

1296 # Since H = iA, dU = exp(-A) = exp(iH) = ZDZ^d 

1297 dU = Z * np.exp(1.0j * epsilon) @ dag(Z) 

1298 if U.dtype == float: 

1299 U[:] = (U @ dU).real 

1300 else: 

1301 U[:] = U @ dU 

1302 

1303 if updatecoeff: 

1304 start = 0 

1305 for C, unocc, L in zip(self.C_kul, self.nbands - M_k, L_k): 

1306 if L == 0 or unocc == 0: 

1307 continue 

1308 Ncoeff = L * unocc 

1309 deltaC = dX[Nk * Nw**2 + start : Nk * Nw**2 + start + Ncoeff] 

1310 C += deltaC.reshape(unocc, L) 

1311 gram_schmidt(C) 

1312 start += Ncoeff 

1313 

1314 self.update()