Coverage for tbkit/manybody.py: 100%

238 statements  

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

1r''' 

2Exact diagonalization of small interacting clusters: the reference against 

3which the mean-field solvers of :mod:`tbkit.meanfield` are checked. 

4 

5The Hamiltonian is the extended Hubbard model of any single-particle 

6matrix :math:`t_{ij}` (e.g. *System.ham*, or *KSpace.finite_ham* for a 

7torus), 

8 

9.. math:: 

10 

11 H = \sum_{ij\sigma} t_{ij}c^\dagger_{i\sigma}c_{j\sigma} 

12 + \sum_i U_i\,n_{i\uparrow}n_{i\downarrow} 

13 + \sum_{i<j} V_{ij}\,n_i n_j\, ,\qquad n_i = n_{i\uparrow} + n_{i\downarrow}\, , 

14 

15or its spinless version (one species, no *U*). It conserves 

16:math:`N_\uparrow` and :math:`N_\downarrow`, so it is built in one sector 

17at a time (:class:`FockSector`). A basis state is a pair of bit patterns, 

18bit *i* the occupation of site *i*, in increasing order; the fermion 

19operators are ordered by site, all spins up before all spins down, so 

20:math:`c^\dagger_i c_j` carries the sign :math:`(-1)^m`, *m* the number of 

21occupied sites strictly between *i* and *j*. Every hopping is applied to 

22all basis states at once (one vectorized pass per bond), and the lowest 

23states come from ``scipy.sparse.linalg.eigsh``: about 12 sites at half 

24filling (853776 states) take seconds. 

25''' 

26from __future__ import annotations 

27 

28import functools 

29import itertools 

30from math import comb 

31 

32import numpy as np 

33import scipy.linalg as LA 

34import scipy.sparse as sp 

35import scipy.sparse.linalg as sla 

36from numpy.typing import ArrayLike, NDArray 

37 

38import tbkit.error_handling as error_handling 

39 

40#: Largest sector diagonalized densely (all eigenvalues), above it eigsh. 

41DENSE_MAX = 1500 

42 

43_M1 = np.uint64(0x5555555555555555) 

44_M2 = np.uint64(0x3333333333333333) 

45_M4 = np.uint64(0x0F0F0F0F0F0F0F0F) 

46_H01 = np.uint64(0x0101010101010101) 

47 

48 

49def _popcount(x: NDArray) -> NDArray[np.int64]: 

50 ''' 

51 Private function. Number of set bits of every element of an integer array. 

52 ''' 

53 x = x.astype(np.uint64) 

54 x = x - ((x >> np.uint64(1)) & _M1) 

55 x = (x & _M2) + ((x >> np.uint64(2)) & _M2) 

56 x = (x + (x >> np.uint64(4))) & _M4 

57 return ((x * _H01) >> np.uint64(56)).astype(np.int64) 

58 

59 

60@functools.lru_cache(maxsize=8) 

61def _all_patterns(n_sites: int, n_particles: int) -> NDArray[np.int64]: 

62 ''' 

63 Private function. Cached (read-only) result of *_patterns*, reused by 

64 the momentum sectors of one cluster. 

65 ''' 

66 count = comb(n_sites, n_particles) 

67 if n_particles == 0: 

68 out = np.zeros(1, np.int64) 

69 else: 

70 sites = np.fromiter(itertools.chain.from_iterable(itertools.combinations(range(n_sites), n_particles)), 

71 dtype=np.int64, count=count * n_particles).reshape(count, n_particles) 

72 out = np.sort(np.sum(np.left_shift(1, sites), axis=1)) 

73 out.flags.writeable = False 

74 return out 

75 

76 

77def _patterns(n_sites: int, n_particles: int) -> NDArray[np.int64]: 

78 ''' 

79 Private function. Every way to put *n_particles* fermions on *n_sites* 

80 sites, as bit patterns in increasing order. 

81 ''' 

82 return _all_patterns(n_sites, n_particles).copy() 

83 

84 

85def _occupations(patterns: NDArray[np.int64], n_sites: int) -> NDArray[np.float64]: 

86 ''' 

87 Private function. Occupation numbers, shape (len(patterns), n_sites). 

88 ''' 

89 return ((patterns[:, None] >> np.arange(n_sites)[None, :]) & 1).astype('f8') 

90 

91 

92def _hop(patterns: NDArray[np.int64], i: int, j: int): 

93 r''' 

94 Private function. :math:`c^\dagger_i c_j` (i != j) on every pattern: the 

95 patterns it acts on (indices), their images (indices) and the signs. 

96 ''' 

97 occ_j = (patterns >> j) & 1 

98 occ_i = (patterns >> i) & 1 

99 cols = np.flatnonzero(occ_j & (1 - occ_i)) 

100 src = patterns[cols] 

101 lo, hi = min(i, j), max(i, j) 

102 between = ((1 << hi) - 1) ^ ((1 << (lo + 1)) - 1) 

103 signs = 1 - 2 * (_popcount(src & between) & 1) 

104 rows = np.searchsorted(patterns, src ^ ((1 << i) | (1 << j))) 

105 return rows, cols, signs 

106 

107 

108def _hopping_matrix(patterns: NDArray[np.int64], h: NDArray, occ: NDArray[np.float64]) -> sp.csr_matrix: 

109 ''' 

110 Private function. One species' kinetic energy in the basis *patterns*. 

111 ''' 

112 dim = len(patterns) 

113 rows, cols, vals = [np.arange(dim)], [np.arange(dim)], [occ @ np.diag(h)] 

114 for i, j in zip(*np.nonzero(h - np.diag(np.diag(h)))): 

115 r, c, s = _hop(patterns, int(i), int(j)) 

116 rows.append(r) 

117 cols.append(c) 

118 vals.append(s * h[i, j]) 

119 return sp.coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), 

120 shape=(dim, dim)).tocsr() 

121 

122 

123def _pair_coefficients(w: NDArray, tol: float = 1e-12): 

124 r''' 

125 Private function. The two-body operator 

126 :math:`\tfrac12\sum W_{abcd}a^\dagger_aa^\dagger_ba_da_c` as 

127 :math:`\sum_{a<b,\,c<d} C_{ab,cd}\,a^\dagger_aa^\dagger_ba_da_c`: the 

128 pairs (c, d) annihilated, and for each the pairs (a, b) created with 

129 their nonzero coefficients. 

130 ''' 

131 c = (w - w.transpose(1, 0, 2, 3) - w.transpose(0, 1, 3, 2) + w.transpose(1, 0, 3, 2)) / 2 

132 n = len(w) 

133 lo, hi = np.triu_indices(n, 1) 

134 block = c[lo[:, None], hi[:, None], lo[None, :], hi[None, :]] # (created pair, annihilated pair) 

135 scale = max(1., float(np.max(np.abs(block)))) if block.size else 1. 

136 out = [] 

137 for q in range(len(lo)): 

138 keep = np.flatnonzero(np.abs(block[:, q]) > tol * scale) 

139 if len(keep): 

140 out.append((int(lo[q]), int(hi[q]), lo[keep], hi[keep], block[keep, q])) 

141 return out 

142 

143 

144def _two_body_matrix(patterns: NDArray[np.int64], w: NDArray) -> sp.csr_matrix: 

145 ''' 

146 Private function. A two-body operator of spinless fermions in the basis 

147 *patterns* (each annihilated pair applied to every state at once). 

148 ''' 

149 dim = len(patterns) 

150 rows, cols, vals = [np.zeros(0, int)], [np.zeros(0, int)], [np.zeros(0, w.dtype)] 

151 for c, d, created_a, created_b, coef in _pair_coefficients(w): 

152 cols0 = np.flatnonzero(((patterns >> c) & 1) & ((patterns >> d) & 1)) 

153 if not len(cols0): 

154 continue 

155 s = patterns[cols0] 

156 # a_d a_c: (-1)^(occupied below c) (-1)^(occupied below d, after removing c) 

157 sign0 = _popcount(s & ((1 << c) - 1)) + _popcount(s & ((1 << d) - 1)) - 1 

158 s2 = s ^ ((1 << c) | (1 << d)) 

159 for a, b, x in zip(created_a, created_b, coef): 

160 empty = np.flatnonzero((((s2 >> a) | (s2 >> b)) & 1) == 0) 

161 if not len(empty): 

162 continue 

163 t = s2[empty] 

164 # a+_a a+_b: (-1)^(occupied below b) (-1)^(occupied below a), a < b 

165 sign = sign0[empty] + _popcount(t & ((1 << int(b)) - 1)) + _popcount(t & ((1 << int(a)) - 1)) 

166 rows.append(np.searchsorted(patterns, t | (1 << int(a)) | (1 << int(b)))) 

167 cols.append(cols0[empty]) 

168 vals.append((1 - 2 * (sign & 1)) * x) 

169 return sp.coo_matrix((np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), 

170 shape=(dim, dim)).tocsr() 

171 

172 

173def project_interaction(states: ArrayLike, V) -> NDArray[np.complex128]: 

174 r''' 

175 Get a density-density interaction projected onto a set of 

176 single-particle states :math:`\phi_a` (e.g. the Bloch states of one 

177 band of a torus): with :math:`c_r \to \sum_a\phi_a(r)\,a_a`, 

178 

179 .. math:: 

180 

181 \sum_{r<r'}V_{rr'}n_rn_{r'} \to \frac12\sum_{abcd}W_{abcd}\, 

182 a^\dagger_aa^\dagger_ba_da_c\, ,\qquad 

183 W_{abcd} = \sum_{rr'}V_{rr'}\,\phi^*_a(r)\phi^*_b(r')\phi_c(r)\phi_d(r')\, . 

184 

185 Pass *W* to *exact_diagonalization*, with the projected one-body 

186 Hamiltonian (``diag`` of the band energies) as *ham*. This is how a 

187 partially filled flat band is studied on clusters too large for the 

188 full Fock space (e.g. a fractional Chern insulator). 

189 

190 Parameters 

191 ---------- 

192 states : Complex array, shape (N, n) 

193 Orthonormal single-particle states (columns) on the N sites. 

194 V : Real symmetric (N, N) matrix with zero diagonal 

195 Density-density interaction on the sites. 

196 

197 Returns 

198 ------- 

199 W : Complex ndarray, shape (n, n, n, n) 

200 ''' 

201 phi = np.asarray(states, dtype='c16') 

202 error_handling.orthonormal_states(phi) 

203 v = V.toarray() if hasattr(V, 'toarray') else np.asarray(V) 

204 error_handling.density_interaction(v, len(phi)) 

205 v = v.astype('f8') 

206 n = phi.shape[1] 

207 pair = (phi.conj()[:, :, None] * phi[:, None, :]).reshape(len(phi), n * n) # (r, (a, c)) 

208 w = (pair.T @ v @ pair).reshape(n, n, n, n) # (a, c, b, d) 

209 return w.transpose(0, 2, 1, 3) 

210 

211 

212class FockSector(): 

213 r''' 

214 Basis of the many-body states with :math:`N_\uparrow` spin-up and 

215 :math:`N_\downarrow` spin-down fermions on *n_sites* sites (or 

216 :math:`N_\uparrow` spinless ones, with ``n_dn=None``). 

217 

218 The state of index ``a * len(dn) + b`` has spin-up pattern ``up[a]`` 

219 and spin-down pattern ``dn[b]``: a wave function reshaped to 

220 ``(len(up), len(dn))`` has the spin-up configurations along its rows. 

221 

222 Parameters 

223 ---------- 

224 n_sites : Positive integer, at most 62 

225 n_up : Integer from 0 to *n_sites* 

226 Spin-up fermions (or spinless ones). 

227 n_dn : Integer from 0 to *n_sites*, or None, default None 

228 Spin-down fermions; None for spinless fermions. 

229 momentum : Tuple (labels, n_cells, total), or None, default None 

230 Spinless fermions only: keep the states of one total crystal 

231 momentum. *labels* (integers, shape (n_sites, d)) is the momentum 

232 :math:`(m_1, \dots)` of each orbital, in units of 

233 :math:`\mathbf{b}_\alpha/N_\alpha`, *n_cells* the 

234 :math:`(N_1, \dots)` of the torus and *total* the sector 

235 :math:`\sum m \bmod N`. The orbitals are then Bloch states (see 

236 *project_interaction*), and the Hamiltonian must conserve momentum. 

237 

238 Attributes 

239 ---------- 

240 up : Integer ndarray 

241 Spin-up (or spinless) occupation patterns, bit *i* for site *i*, 

242 in increasing order. 

243 dn : Integer ndarray 

244 Spin-down patterns (the single empty pattern ``[0]`` when spinless). 

245 dim : Integer 

246 Number of basis states. 

247 spinless : Boolean 

248 ''' 

249 

250 def __init__(self, n_sites: int, n_up: int, n_dn: int | None = None, momentum: tuple | None = None) -> None: 

251 if isinstance(n_up, np.integer): 

252 n_up = int(n_up) 

253 if isinstance(n_dn, np.integer): 

254 n_dn = int(n_dn) 

255 error_handling.fock_sector(n_sites, n_up, n_dn) 

256 self.n_sites, self.n_up = n_sites, n_up 

257 self.n_dn: int | None = n_dn 

258 self.spinless = n_dn is None 

259 self.up = _patterns(n_sites, n_up) 

260 self.dn = _patterns(n_sites, 0 if n_dn is None else n_dn) 

261 self.momentum = None 

262 if momentum is not None: 

263 error_handling.momentum_sector(momentum, n_sites, self.spinless) 

264 labels = np.asarray(momentum[0], dtype=np.int64).reshape(n_sites, -1) 

265 cells = np.broadcast_to(np.asarray(momentum[1], dtype=np.int64), labels.shape[1:]) 

266 total = np.broadcast_to(np.asarray(momentum[2], dtype=np.int64), labels.shape[1:]) 

267 self.momentum = (labels, cells, total % cells) 

268 k = (_occupations(self.up, n_sites) @ labels).astype(np.int64) % cells 

269 self.up = self.up[np.all(k == total % cells, axis=1)] 

270 self.dim = len(self.up) * len(self.dn) 

271 

272 @property 

273 def sz(self) -> float: 

274 r''' 

275 :math:`S_z = (N_\uparrow - N_\downarrow)/2` (0 when spinless). 

276 ''' 

277 return 0. if self.n_dn is None else (self.n_up - self.n_dn) / 2 

278 

279 def occupations(self) -> tuple[NDArray[np.float64], NDArray[np.float64]]: 

280 ''' 

281 Occupation numbers of the spin-up and spin-down patterns. 

282 

283 Returns 

284 ------- 

285 occ_up, occ_dn 

286 Real ndarrays, shapes (len(up), n_sites) and (len(dn), n_sites). 

287 ''' 

288 return _occupations(self.up, self.n_sites), _occupations(self.dn, self.n_sites) 

289 

290 def hamiltonian(self, ham, U: float | ArrayLike = 0., V=None, W: ArrayLike | None = None) -> sp.csr_matrix: 

291 r''' 

292 Get the sparse Hamiltonian of the sector. 

293 

294 Parameters 

295 ---------- 

296 ham 

297 Hermitian (N, N) matrix, sparse or dense: the hoppings 

298 :math:`t_{ij}` and onsite energies :math:`t_{ii}`, the same 

299 for both spins. 

300 U : Real number, or array of one per site, default 0 

301 Onsite repulsion :math:`U_i n_{i\uparrow}n_{i\downarrow}` 

302 (must be 0 for spinless fermions). 

303 V : Real symmetric (N, N) matrix with zero diagonal, or None, default None 

304 Density-density interaction :math:`\sum_{i<j}V_{ij}n_in_j` 

305 (e.g. a constant on the nearest-neighbour bonds). 

306 W : Complex array, shape (N, N, N, N), or None, default None 

307 Spinless fermions only: a general two-body interaction 

308 :math:`\tfrac12\sum_{abcd}W_{abcd}c^\dagger_ac^\dagger_bc_dc_c`, 

309 Hermitian (:math:`W_{abcd} = W^*_{cdab}`), e.g. from 

310 *project_interaction*. 

311 

312 Returns 

313 ------- 

314 ham : CSR matrix 

315 Of shape (dim, dim). Real when *ham* and *W* are real, else complex. 

316 ''' 

317 h, u, v = self._interactions(ham, U, V) 

318 occ_up, occ_dn = self.occupations() 

319 h_up = _hopping_matrix(self.up, h, occ_up) 

320 diag_up = 0.5 * np.sum((occ_up @ v) * occ_up, axis=1) 

321 if self.spinless: 

322 mat = h_up + sp.diags(diag_up) 

323 if W is not None: 

324 w = np.asarray(W) 

325 error_handling.two_body(w, self.n_sites) 

326 if self.momentum is not None: 

327 error_handling.conserves_momentum(h, w, *self.momentum) 

328 mat = mat + _two_body_matrix(self.up, w.real if np.allclose(w.imag, 0.) else w) 

329 return mat.tocsr() 

330 error_handling.spinless_two_body(W) 

331 h_dn = _hopping_matrix(self.dn, h, occ_dn) 

332 diag_dn = 0.5 * np.sum((occ_dn @ v) * occ_dn, axis=1) 

333 diag = (diag_up[:, None] + diag_dn[None, :] + (occ_up * u) @ occ_dn.T + occ_up @ v @ occ_dn.T) 

334 n_up, n_dn = len(self.up), len(self.dn) 

335 return (sp.kron(h_up, sp.identity(n_dn), format='csr') + sp.kron(sp.identity(n_up), h_dn, format='csr') 

336 + sp.diags(diag.ravel())).tocsr() 

337 

338 def _interactions(self, ham, U, V): 

339 ''' 

340 Private method. Check and densify the hoppings and interactions. 

341 ''' 

342 h = ham.toarray() if hasattr(ham, 'toarray') else np.asarray(ham) 

343 error_handling.square_matrix(h, 'ham') 

344 error_handling.ndarray(h, 'ham', self.n_sites) 

345 error_handling.hermitian_dense(h) 

346 if np.allclose(h.imag, 0.): 

347 h = h.real.astype('f8') 

348 if self.momentum is not None: 

349 error_handling.conserves_momentum(h, None, *self.momentum) 

350 u = np.broadcast_to(np.asarray(U, dtype='f8'), (self.n_sites,)).copy() if np.ndim(U) == 0 \ 

351 else np.asarray(U, dtype='f8') 

352 error_handling.ndarray(u, 'U', self.n_sites) 

353 error_handling.spinless_onsite(u, self.spinless) 

354 if V is None: 

355 v = np.zeros((self.n_sites, self.n_sites)) 

356 else: 

357 v = V.toarray() if hasattr(V, 'toarray') else np.asarray(V) 

358 error_handling.density_interaction(v, self.n_sites) 

359 return h, u, v.astype('f8') 

360 

361 

362class ExactResult(): 

363 r''' 

364 Lowest eigenstates of a sector, from *exact_diagonalization*. 

365 

366 Attributes 

367 ---------- 

368 energies : Real ndarray 

369 The lowest energies, in increasing order. 

370 states : ndarray 

371 The eigenvectors (columns, shape (dim, n_states)), in the basis of 

372 *sector*. 

373 sector : :class:`FockSector` 

374 ''' 

375 

376 def __init__(self, energies, states, sector) -> None: 

377 self.energies, self.states, self.sector = energies, states, sector 

378 self._occ = sector.occupations() 

379 

380 def _psi(self, state): 

381 ''' 

382 Private method. Wave function *state*, shape (len(up), len(dn)). 

383 ''' 

384 error_handling.state_index(state, len(self.energies)) 

385 return self.states[:, state].reshape(len(self.sector.up), len(self.sector.dn)) 

386 

387 def densities(self, state: int = 0): 

388 r''' 

389 Get the densities :math:`\langle n_{i\uparrow}\rangle` and 

390 :math:`\langle n_{i\downarrow}\rangle` of an eigenstate. 

391 

392 Parameters 

393 ---------- 

394 state : Integer, default 0 

395 Index of the eigenstate (0 the lowest). 

396 

397 Returns 

398 ------- 

399 n_up, n_dn : Real ndarrays 

400 The densities on every site (*n_dn* all zero when spinless). 

401 ''' 

402 p = np.abs(self._psi(state)) ** 2 

403 return p.sum(axis=1) @ self._occ[0], p.sum(axis=0) @ self._occ[1] 

404 

405 def density_correlation(self, state: int = 0) -> NDArray[np.float64]: 

406 r''' 

407 Get :math:`\langle n_in_j\rangle` (:math:`n_i` summed over spin). 

408 

409 Parameters 

410 ---------- 

411 state : Integer, default 0 

412 

413 Returns 

414 ------- 

415 corr : Real ndarray, shape (N, N) 

416 ''' 

417 p = np.abs(self._psi(state)) ** 2 

418 occ_up, occ_dn = self._occ 

419 uu = occ_up.T @ (p.sum(axis=1)[:, None] * occ_up) 

420 dd = occ_dn.T @ (p.sum(axis=0)[:, None] * occ_dn) 

421 ud = occ_up.T @ p @ occ_dn 

422 return uu + dd + ud + ud.T 

423 

424 def double_occupancy(self, state: int = 0) -> NDArray[np.float64]: 

425 r''' 

426 Get :math:`\langle n_{i\uparrow}n_{i\downarrow}\rangle` on every site. 

427 The local moment is 

428 :math:`\langle (n_{i\uparrow} - n_{i\downarrow})^2\rangle = \langle n_i\rangle - 2\langle n_{i\uparrow}n_{i\downarrow}\rangle`. 

429 

430 Parameters 

431 ---------- 

432 state : Integer, default 0 

433 

434 Returns 

435 ------- 

436 d : Real ndarray 

437 ''' 

438 error_handling.spinful_sector(self.sector.spinless) 

439 p = np.abs(self._psi(state)) ** 2 

440 return np.sum((p @ self._occ[1]) * self._occ[0], axis=0) 

441 

442 def spin_correlation(self, state: int = 0) -> NDArray[np.float64]: 

443 r''' 

444 Get :math:`\langle\mathbf{S}_i\cdot\mathbf{S}_j\rangle`. The sum of 

445 all its elements is :math:`S(S+1)`; its diagonal is 

446 :math:`\tfrac34\langle(n_{i\uparrow} - n_{i\downarrow})^2\rangle`. 

447 

448 Parameters 

449 ---------- 

450 state : Integer, default 0 

451 

452 Returns 

453 ------- 

454 corr : Real ndarray, shape (N, N) 

455 ''' 

456 error_handling.spinful_sector(self.sector.spinless) 

457 psi = self._psi(state) 

458 p = np.abs(psi) ** 2 

459 occ_up, occ_dn = self._occ 

460 uu = occ_up.T @ (p.sum(axis=1)[:, None] * occ_up) 

461 dd = occ_dn.T @ (p.sum(axis=0)[:, None] * occ_dn) 

462 ud = occ_up.T @ p @ occ_dn 

463 corr = (uu + dd - ud - ud.T) / 4 

464 n = self.sector.n_sites 

465 for i in range(n): 

466 for j in range(i + 1, n): 

467 # S+_i S-_j = -(c+_{i up} c_{j up})(c+_{j dn} c_{i dn}) 

468 ru, cu, su = _hop(self.sector.up, i, j) 

469 rd, cd, sd = _hop(self.sector.dn, j, i) 

470 if not (len(ru) and len(rd)): 

471 continue 

472 moved = (su[:, None] * sd[None, :]) * psi[np.ix_(cu, cd)] 

473 x = -np.vdot(psi[np.ix_(ru, rd)], moved) 

474 # <S_i.S_j> gets (<S+_i S-_j> + <S-_i S+_j>)/2 = Re <S+_i S-_j> 

475 corr[i, j] += x.real 

476 corr[j, i] += x.real 

477 occ = self.densities(state) 

478 corr[np.diag_indices(n)] = 0.75 * (occ[0] + occ[1] - 2 * self.double_occupancy(state)) 

479 return corr 

480 

481 def total_spin(self, state: int = 0) -> float: 

482 r''' 

483 Get the total spin *S*, from 

484 :math:`S(S+1) = \|S^+\psi\|^2 + S_z(S_z+1)`. Within a degenerate 

485 multiplet the eigensolver may return a mixture of spins, whose *S* 

486 is then not a half-integer. 

487 

488 Parameters 

489 ---------- 

490 state : Integer, default 0 

491 

492 Returns 

493 ------- 

494 S : Real number 

495 ''' 

496 error_handling.spinful_sector(self.sector.spinless) 

497 psi = self._psi(state) 

498 sec = self.sector 

499 sz = sec.sz 

500 norm = 0. 

501 if sec.n_dn and sec.n_up < sec.n_sites: 

502 up2, dn2 = _patterns(sec.n_sites, sec.n_up + 1), _patterns(sec.n_sites, sec.n_dn - 1) 

503 target = np.zeros((len(up2), len(dn2)), dtype=psi.dtype) 

504 for i in range(sec.n_sites): 

505 cu = np.flatnonzero(((sec.up >> i) & 1) == 0) 

506 cd = np.flatnonzero((sec.dn >> i) & 1) 

507 below = (1 << i) - 1 

508 su = 1 - 2 * (_popcount(sec.up[cu] & below) & 1) 

509 sd = 1 - 2 * (_popcount(sec.dn[cd] & below) & 1) 

510 ru = np.searchsorted(up2, sec.up[cu] | (1 << i)) 

511 rd = np.searchsorted(dn2, sec.dn[cd] ^ (1 << i)) 

512 target[np.ix_(ru, rd)] += (su[:, None] * sd[None, :]) * psi[np.ix_(cu, cd)] 

513 norm = float(np.sum(np.abs(target) ** 2)) 

514 s_s1 = norm + sz * (sz + 1) 

515 return float((np.sqrt(1 + 4 * s_s1) - 1) / 2) 

516 

517 

518def exact_diagonalization( 

519 ham, n_up: int, n_dn: int | None = None, U: float | ArrayLike = 0., V=None, n_states: int = 1, 

520 W: ArrayLike | None = None, momentum: tuple | None = None, 

521) -> ExactResult: 

522 r''' 

523 Get the lowest eigenstates of the (extended) Hubbard model of a small 

524 cluster, exactly, in the sector of :math:`N_\uparrow` and 

525 :math:`N_\downarrow` electrons (see :mod:`tbkit.manybody`). 

526 

527 The spin-up and spin-down hoppings are those of *ham*, so this is the 

528 exact counterpart of :func:`tbkit.meanfield.hubbard_mean_field` on the 

529 same matrix and *U*. Sectors of up to :data:`DENSE_MAX` states are 

530 diagonalized densely; larger ones by ``eigsh`` (Lanczos), from a fixed 

531 starting vector so that results are reproducible. 

532 

533 Parameters 

534 ---------- 

535 ham 

536 Hermitian (N, N) matrix, sparse or dense, e.g. *System.ham*. 

537 n_up : Integer from 0 to N 

538 Spin-up electrons (or spinless fermions, with ``n_dn=None``). 

539 n_dn : Integer from 0 to N, or None, default None 

540 Spin-down electrons; None for spinless fermions. 

541 U : Real number, or array of one per site, default 0 

542 Onsite repulsion (0 for spinless fermions). 

543 V : Real symmetric (N, N) matrix with zero diagonal, or None, default None 

544 Density-density interaction :math:`\sum_{i<j}V_{ij}n_in_j`. 

545 n_states : Positive integer, default 1 

546 Number of lowest states, at most the dimension of the sector. 

547 W : Complex array, shape (N, N, N, N), or None, default None 

548 Spinless fermions only: a general two-body interaction (see 

549 *FockSector.hamiltonian*), e.g. from *project_interaction*. 

550 momentum : Tuple (labels, n_cells, total), or None, default None 

551 Spinless fermions only: the sector of one total crystal momentum 

552 (see :class:`FockSector`). 

553 

554 Returns 

555 ------- 

556 result : :class:`ExactResult` 

557 

558 Examples 

559 -------- 

560 The Hubbard dimer at half filling:: 

561 

562 res = exact_diagonalization([[0., -1.], [-1., 0.]], 1, 1, U=4.) 

563 res.energies[0] # (U - sqrt(U^2 + 16 t^2)) / 2 = -0.828 

564 res.total_spin() # 0, a singlet 

565 ''' 

566 h = ham.toarray() if hasattr(ham, 'toarray') else np.asarray(ham) 

567 error_handling.square_matrix(h, 'ham') 

568 sector = FockSector(len(h), n_up, n_dn, momentum) 

569 error_handling.positive_int(n_states, 'n_states') 

570 error_handling.n_states(n_states, sector.dim) 

571 mat = sector.hamiltonian(h, U, V, W) 

572 if sector.dim <= DENSE_MAX or n_states >= sector.dim - 1: 

573 energies, states = LA.eigh(mat.toarray(), subset_by_index=(0, n_states - 1)) 

574 else: 

575 v0 = np.random.default_rng(0).standard_normal(sector.dim).astype(mat.dtype) 

576 energies, states = sla.eigsh(mat, k=n_states, which='SA', v0=v0, tol=1e-12) 

577 order = np.argsort(energies) 

578 energies, states = energies[order], states[:, order] 

579 return ExactResult(energies, states, sector)