Coverage for tbkit/error_handling.py: 100%

1569 statements  

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

1import numpy as np 

2import inspect 

3 

4 

5ATOL = 1e-3 # matches the distance/angle tolerance used throughout tbkit.system 

6TAG_LEN = 8 # longest sublattice tag, in characters (the 'U8' tag field of Lattice.coor) 

7 

8 

9############################### 

10# GENERIC EXCEPTION HANDLING 

11############################### 

12 

13 

14def boolean(var, var_name): 

15 ''' 

16 Check if *var* is a boolean. 

17 

18 Raises 

19 ------ 

20 TypeError 

21 Parameter *var* must be a bool. 

22 ''' 

23 if not isinstance(var, bool): 

24 raise TypeError('\n\nParameter {} must be a bool.\n'.format(var_name)) 

25 

26 

27def positive_int(var, var_name): 

28 ''' 

29 Check if *var* is a positive integer. 

30 

31 Raises 

32 ------ 

33 TypeError 

34 Parameter *var* must be an integer. 

35 ValueError 

36 Parameter *var* must be a positive integer. 

37 ''' 

38 if not isinstance(var, int): 

39 raise TypeError('\n\nParameter {} must be an integer.\n'.format(var_name)) 

40 if var < 1: 

41 raise ValueError('\n\nParameter {} must be a positive integer.\n'.format(var_name)) 

42 

43 

44def positive_int_lim(var, var_name, nmax): 

45 ''' 

46 Check if *var* is a positive integer smaller than nmax. 

47 

48 Raises 

49 ------ 

50 TypeError 

51 Parameter *var* must be an integer. 

52 ValueError 

53 Parameter *var* must be a positive integer. 

54 ValueError 

55 Parameter *var* must be a positive integer 

56 smaller than nmax. 

57 ''' 

58 if not isinstance(var, int): 

59 raise TypeError('\n\nParameter {} must be an integer.\n'.format(var_name)) 

60 if var < 1: 

61 raise ValueError('\n\nParameter {} must be a positive integer.\n'.format(var_name)) 

62 if var > nmax: 

63 raise ValueError('\n\nParameter {} must be a positive integer ' 

64 'smaller than {}.\n'.format(var_name, nmax)) 

65 

66 

67def real_number(var, var_name): 

68 ''' 

69 Check if parameter *var* is a real number. 

70 

71 Raises 

72 ------ 

73 TypeError 

74 Parameter *var* must be a real number. 

75 ''' 

76 if not isinstance(var, (int, float)): 

77 raise TypeError('\n\nParameter {} must be a real number.\n'.format(var_name)) 

78 

79 

80def real_numbers(params): 

81 ''' 

82 Check that every value of the dictionary *params* (name: value) is a 

83 real number. 

84 

85 Raises 

86 ------ 

87 TypeError 

88 Parameter *name* must be a real number. 

89 ''' 

90 for name, var in params.items(): 

91 real_number(var, name) 

92 

93 

94def positive_real(var, var_name): 

95 ''' 

96 Check if parameter *var* is a positive number. 

97 

98 Raises 

99 ------ 

100 TypeError 

101 Parameter *var* must be a real number. 

102 ValueError 

103 Parameter *var* must be a positive number. 

104 ''' 

105 if not isinstance(var, (int, float)): 

106 raise TypeError('\n\nParameter {} must be a real number.\n'.format(var_name)) 

107 if var <= 0: 

108 raise ValueError('\n\nParameter {} must be a positive number.\n'.format(var_name)) 

109 

110 

111def positive_real_zero(var, var_name): 

112 ''' 

113 Check if parameter *var* is a positive number or zero. 

114 

115 Raises 

116 ------ 

117 TypeError 

118 Parameter *var* must be a real number. 

119 ValueError 

120 Parameter *var* must be a positive number or zero. 

121 ''' 

122 if not isinstance(var, (int, float)): 

123 raise TypeError('\n\nParameter {} must be a real number.\n'.format(var_name)) 

124 if var < 0: 

125 raise ValueError('\n\nParameter {} must be a positive number or zero.\n'.format(var_name)) 

126 

127 

128def negative_real(var, var_name): 

129 ''' 

130 Check if parameter *var* is a negative number. 

131 

132 Raises 

133 ------ 

134 TypeError 

135 Parameter *var* must be a real number. 

136 ValueError 

137 Parameter *var* must be a negative number. 

138 ''' 

139 if not isinstance(var, (int, float)): 

140 raise TypeError('\n\nParameter {} must be a real number.\n'.format(var_name)) 

141 if var >= 0: 

142 raise ValueError('\n\nParameter {} must be a negative number.\n'.format(var_name)) 

143 

144 

145def number(var, var_name): 

146 ''' 

147 Check if parameter *var* is a number. 

148 

149 Raises 

150 ------ 

151 TypeError 

152 Parameter *var* must be a real or complex number. 

153 ''' 

154 if not isinstance(var, (int, float, complex)): 

155 raise TypeError('\n\nParameter {} must be a real or complex number.\n'.format(var_name)) 

156 

157 

158def value_params(required, params, func): 

159 ''' 

160 Check that *params* holds every parameter that the value function *func* 

161 needs (see *tbkit.values*). 

162 

163 Raises 

164 ------ 

165 TypeError 

166 The value function needs parameters missing from get_ham. 

167 ''' 

168 missing = [name for name in required if name not in params] 

169 if missing: 

170 raise TypeError('\n\nThe value function {} needs the parameter(s) {}: ' 

171 'pass them to get_ham (or KSpace.set_params).\n'.format( 

172 getattr(func, '__name__', func), ', '.join(missing))) 

173 

174 

175def value_shape(val, size, spin, func): 

176 ''' 

177 Check the values returned by the value function *func* for *size* 

178 bonds or sites: a number or one per entry (or, if *spin*, also a 2x2 

179 matrix or one per entry). 

180 

181 Raises 

182 ------ 

183 ValueError 

184 The value function must return a number or an array of one value per bond/site. 

185 ''' 

186 shapes = [(), (size,)] + ([(2, 2), (size, 2, 2)] if spin else []) 

187 if val.shape not in shapes: 

188 raise ValueError('\n\nThe value function {} returned shape {}: it must return a number, ' 

189 'or one per bond/site (shape ({},)){}.\n'.format( 

190 getattr(func, '__name__', func), val.shape, size, 

191 ', or a 2x2 matrix (one per bond, shape ({}, 2, 2))'.format(size) 

192 if spin else '')) 

193 

194 

195def no_value_functions(model, method): 

196 ''' 

197 Check that *model* has no value functions (callable hoppings or onsite 

198 energies), which *method* cannot represent. 

199 

200 Raises 

201 ------ 

202 ValueError 

203 method does not support value functions. 

204 ''' 

205 if getattr(model, '_hop_values', None) or getattr(model, '_onsite_values', None): 

206 raise ValueError('\n\n{} does not support value functions (callable hoppings or ' 

207 'onsite energies): use plain numbers.\n'.format(method)) 

208 

209 

210def is_callable(var, var_name): 

211 ''' 

212 Check if parameter *var* is callable. 

213 

214 Raises 

215 ------ 

216 TypeError 

217 Parameter *var* must be callable. 

218 ''' 

219 if not callable(var): 

220 raise TypeError('\n\nParameter {} must be callable.\n'.format(var_name)) 

221 

222 

223def larger(var1, var_name1, var2, var_name2): 

224 ''' 

225 Check if *var1* larger than *val*. 

226 

227 Raises 

228 ------ 

229 ValueError 

230 Parameter *var1* larger than *var2*. 

231 ''' 

232 if var1 >= var2: 

233 raise ValueError('\n\n{} must be larger than {}.\n' 

234 .format(var_name1, var_name2)) 

235 

236 

237def smaller(var1, var_name1, var2, var_name2): 

238 ''' 

239 Check if *var1* smaller than *var2*. 

240 

241 Raises 

242 ------ 

243 ValueError 

244 Parameter *var1* must be smaller than *var2*. 

245 ''' 

246 if var1 >= var2: 

247 raise ValueError('\n\n{} must be smaller than {}.\n' 

248 .format(var_name1, var_name2)) 

249 

250 

251def string(var, var_name): 

252 ''' 

253 Check if parameter *var* is a string. 

254 

255 Raises 

256 ------ 

257 TypeError 

258 Parameter *var* must be a string. 

259 ''' 

260 if var is None: 

261 return 

262 if not isinstance(var, str): 

263 raise TypeError('\n\nParameter {} must be a string.\n'.format(var_name)) 

264 

265 

266def ndarray(var, var_name, length): 

267 ''' 

268 Check if parameter *var* is a numpy array. 

269 

270 Raises 

271 ------ 

272 TypeError 

273 Parameter *var* must be a numpy ndarray. 

274 ValueError 

275 length array must be equal to length. 

276 ''' 

277 if not isinstance(var, np.ndarray): 

278 raise TypeError('\n\nParameter {} must be a numpy ndarray.\n'.format(var_name)) 

279 if len(var) != length: 

280 raise ValueError('\n\nParameter {} must be a numpy ndarray of {}\n' 

281 ''.format(var_name, length)) 

282 

283 

284def ndarray_null(var, var_name): 

285 ''' 

286 Check if parameter *var* is not a null numpy array. 

287 

288 Raises 

289 ------ 

290 ValueError 

291 Parameter *var* must not be a null numpy ndarray. 

292 ''' 

293 array_null = np.zeros(len(var)) 

294 if np.allclose(var, array_null): 

295 raise ValueError('\n\nParameter {} must not be a null numpy ndarray.\n'.format(var_name)) 

296 

297 

298def ndarray_empty(var, var_name): 

299 ''' 

300 Check if parameter *var* is not an empty numpy array. 

301 

302 Raises 

303 ------ 

304 ValueError 

305 Parameter *var* must not be an emptynumpy ndarray. 

306 ''' 

307 if var.size == 0: 

308 raise ValueError('\n\nParameter {} must not be an empty numpy ndarray.\n'.format(var_name)) 

309 

310 

311def list_tuple_2elem(var, var_name): 

312 ''' 

313 Check if parameter *var* is a list/tuple with 2 elements. 

314 

315 Raises 

316 ------ 

317 TypeError 

318 Parameter *var* must be a list/tuple. 

319 ValueError 

320 Parameter *var* must contain 2 elements. 

321 ''' 

322 if var is None: 

323 return 

324 if not isinstance(var, (list, tuple)): 

325 raise TypeError('\n\nParameter {} must be a list/tuple.\n'.format(var_name)) 

326 if len(var) != 2: 

327 raise ValueError('\n\nParameter {} must be a list/tuple of length two.\n'.format(var_name)) 

328 

329 

330def tuple_2elem(var, var_name): 

331 ''' 

332 Check if parameter *var* is a tuple with 2 elements. 

333 

334 Raises 

335 ------ 

336 TypeError 

337 Parameter *var* must be a tuple. 

338 ValueError 

339 Parameter *var* must contain 2 elements. 

340 ''' 

341 if var is None: 

342 return 

343 if not isinstance(var, tuple): 

344 raise TypeError('\n\nParameter {} must be a tuple.\n'.format(var_name)) 

345 if len(var) != 2: 

346 raise ValueError('\n\nParameter {} must be a list/tuple of length two.\n'.format(var_name)) 

347 

348 

349############################### 

350# LATTICE EXCEPTION HANDLING 

351############################### 

352 

353 

354def lat(lat): 

355 ''' 

356 Check if parameter is an instance of the *lattice*. 

357 

358 Raises 

359 ------ 

360 TypeError 

361 Parameter must be an instance of the class lattice. 

362 ''' 

363 names = inspect.getmro(lat.__class__) 

364 if str(names).find('lattice') == -1: 

365 raise TypeError('\n\nParameter must be an instance of the class lattice.\n') 

366 

367 

368def unit_cell(unit_cell): 

369 ''' 

370 Check parameter *unit_cell*. 

371 

372 Raises 

373 ------ 

374 TypeError 

375 Parameter unit_cell must be a list. 

376 KeyError 

377 Dictionaries must contain the key "tag". 

378 KeyError 

379 Dictionaries must contain the key "r0". 

380 TypeError 

381 Key "tag" must contain a string. 

382 ValueError 

383 Key "tag" must be a string of 1 to TAG_LEN characters. 

384 ValueError 

385 Key "r0" must contain be a list. 

386 TypeError 

387 Key "r0" must contain be a tuple. 

388 ValueError 

389 Key "r0" must contain a tuple of length two. 

390 ValueError 

391 Key "r0" must contain a tuple of two real numbers. 

392 ''' 

393 if not isinstance(unit_cell, list): 

394 raise TypeError('\n\nParameter unit_cell must be a list.\n') 

395 for dic in unit_cell: 

396 if 'tag' not in dic: 

397 raise KeyError('\n\nDictionaries must contain the key "tag".\n') 

398 if 'r0' not in dic: 

399 raise KeyError('\n\nDictionaries must contain the key "r0".\n') 

400 if not isinstance(dic['tag'], str): 

401 raise TypeError('\n\nKey "tag" must contain a string.\n') 

402 if not 1 <= len(dic['tag']) <= TAG_LEN: 

403 raise ValueError('\n\nKey "tag" must be a string of 1 to {} characters.\n'.format(TAG_LEN)) 

404 if not isinstance(dic['r0'], tuple): 

405 raise TypeError('\n\nKey "r0" must be a tuple.\n') 

406 if len(dic['r0']) not in (2, 3): 

407 raise ValueError('\n\nKey "r0" must contain a tuple of length two (or three, ' 

408 'for a lattice in 3D space).\n') 

409 if not all(isinstance(c, (int, float)) for c in dic['r0']): 

410 raise ValueError('\n\nKey "r0" must contain a tuple of real numbers.\n') 

411 if len({len(dic['r0']) for dic in unit_cell}) > 1: 

412 raise ValueError('\n\nAll "r0" must have the same length.\n') 

413 

414 

415def prim_vec(prim_vec): 

416 ''' 

417 Check parameter *prim_vec*. 

418 

419 Raises 

420 ------ 

421 TypeError 

422 Parameter prim_vec must be a list. 

423 ValueError 

424 Parameter prim_vec must be a list 

425 of length 1 for 1D lattices or length 2 fro 2D lattices. 

426 TypeError 

427 List elements must be tuples. 

428 ValueError 

429 List elements must be 1 or 2 tuples. 

430 ValueError 

431 Tuples must be of length 2. 

432 ValueError 

433 Tuples must containt real numbers. 

434 ValueError 

435 Norm of coor should be larger than 0.1. 

436 ''' 

437 if not isinstance(prim_vec, list): 

438 raise TypeError('\n\nParameter prim_vec must be a list.\n') 

439 if len(prim_vec) not in (1, 2, 3): 

440 raise ValueError('\n\nParameter prim_vec must be a list of length 1 ' 

441 'for 1D lattices, 2 for 2D lattices, or 3 for 3D lattices.\n') 

442 for coor in prim_vec: 

443 if not isinstance(coor, tuple): 

444 raise TypeError('\n\nParameter prim_vec must contain tuples.\n') 

445 if len(coor) not in (2, 3): 

446 raise ValueError('\n\nParameter prim_vec must contain tuples of length 2 ' 

447 '(or 3, for a lattice in 3D space).\n') 

448 if not all(isinstance(c, (int, float)) for c in coor): 

449 raise ValueError('\n\nParameter prim_vec must contain tuples of ' 

450 'real numbers.\n') 

451 if sum(c ** 2 for c in coor) < 0.1: 

452 raise ValueError('\n\nEach primitive vector must have a norm larger ' 

453 'than 0.1.\n') 

454 if len({len(coor) for coor in prim_vec}) > 1: 

455 raise ValueError('\n\nAll primitive vectors must have the same length.\n') 

456 if len(prim_vec) > len(prim_vec[0]): 

457 raise ValueError('\n\nA lattice cannot have more primitive vectors than ' 

458 'space dimensions (use 3-tuples for a 3D lattice).\n') 

459 

460 

461def independent(prim_vec): 

462 ''' 

463 Check that the primitive vectors are linearly independent (needed for 

464 the reciprocal lattice). 

465 

466 Raises 

467 ------ 

468 ValueError 

469 The primitive vectors must be linearly independent. 

470 ''' 

471 if np.linalg.matrix_rank(np.array(prim_vec, dtype='f8'), tol=1e-8) != len(prim_vec): 

472 raise ValueError('\n\nThe primitive vectors must be linearly independent.\n') 

473 

474 

475def space_dim(unit_cell, prim_vec): 

476 ''' 

477 Check that the unit cell positions and the primitive vectors live in the 

478 same space (2D or 3D). 

479 

480 Raises 

481 ------ 

482 ValueError 

483 "r0" and prim_vec tuples must have the same length. 

484 ''' 

485 if unit_cell and len(unit_cell[0]['r0']) != len(prim_vec[0]): 

486 raise ValueError('\n\nThe "r0" positions and the primitive vectors must have ' 

487 'the same number of components.\n') 

488 

489 

490def get_lattice(prim_vec, n1, n2, n3=1): 

491 ''' 

492 Check method *get_lattice*. 

493 

494 Raises 

495 ------ 

496 TypeError 

497 Parameters n1, n2, n3 must be integers. 

498 ValueError 

499 Parameters n1, n2, n3 must be positive integers. 

500 ValueError 

501 n2 (n3) must be 1 with fewer than 2 (3) primitive vectors. 

502 ''' 

503 positive_int(n1, 'n1') 

504 positive_int(n2, 'n2') 

505 positive_int(n3, 'n3') 

506 if len(prim_vec) == 1 and n2 > 1: 

507 raise ValueError('\n\nParameter n2 should be equal to 1\n' 

508 'if one primitive vector is given\n') 

509 if len(prim_vec) < 3 and n3 > 1: 

510 raise ValueError('\n\nParameter n3 should be equal to 1\n' 

511 'if fewer than three primitive vectors are given\n') 

512 

513 

514def coor(coor, dtype=None): 

515 ''' 

516 Check if *coor* is a structured array with 

517 dtype=[('x', 'f8'), ('y', 'f8'), ('tag', 'U8')], or, for a lattice in 3D 

518 space, dtype=[('x', 'f8'), ('y', 'f8'), ('z', 'f8'), ('tag', 'U8')]. A 

519 narrower tag field ('U1' to 'U8') is accepted too. If *dtype* is given, 

520 *coor* must have its position fields. 

521 ''' 

522 tags = ['U{}'.format(n) for n in range(1, TAG_LEN + 1)] 

523 positions = [[('x', 'f8'), ('y', 'f8')], [('x', 'f8'), ('y', 'f8'), ('z', 'f8')]] 

524 if dtype is not None: 

525 positions = [[f for f in np.dtype(dtype).descr if f[0] != 'tag']] 

526 dtypes = [np.dtype(f + [('tag', t)]) for f in positions for t in tags] 

527 if coor.dtype not in dtypes: 

528 raise TypeError('\n\nParameter coor dtype must be\n' 

529 'dtype=[("x", "f8"), ("y", "f8"), ("tag", "U8")]\n' 

530 '(with a ("z", "f8") field after "y" for a lattice in 3D space;\n' 

531 'a tag field from "U1" to "U8").\n') 

532 

533 

534def coor_1d(coor): 

535 ''' 

536 Check if *coor* is 1d (coor['y'] = cst). 

537 

538 Raises 

539 ------ 

540 ValueError 

541 *coor* must be 1d( coor['y'] = cst).. 

542 ''' 

543 if not np.allclose(coor['y'][0], coor['y']): 

544 raise ValueError('\n\ncoor["y"] must be constant.\n') 

545 

546 

547def remove_sites(index, sites): 

548 ''' 

549 Check method *remove_sites*. 

550 

551 Raises 

552 ------ 

553 TypeError 

554 Parameter index must be a list. 

555 ValueError 

556 Parameter index must be a list of integers. 

557 ValueError 

558 Indices must be between 0 and sites -1. 

559 of integers between 0 and sites 

560 ''' 

561 if not isinstance(index, list): 

562 raise TypeError('\n\nParameter index must be a list.\n') 

563 if not all(isinstance(i, int) for i in index): 

564 raise ValueError('\n\nParameter index must be a list of integers.\n') 

565 if not all(-1 < i < sites for i in index): 

566 raise ValueError('\n\nElements of index must be between 0 and sites - 1.\n') 

567 

568 

569def shift(shift): 

570 ''' 

571 Check *shift_x* and *shift_y*. 

572 

573 Raises 

574 ------ 

575 TypeError 

576 Parameter delta must be a real number. 

577 ''' 

578 if not isinstance(shift, (int, float)): 

579 raise TypeError('\n\nParameter shift must be a real number.\n') 

580 

581 

582def boundary_line(cx, cy, co): 

583 ''' 

584 Check *boundary_line*. 

585 

586 Raises 

587 ------ 

588 TypeError 

589 Parameter cx must be a real number. 

590 TypeError 

591 Parameter cy must be a real number. 

592 TypeError 

593 Parameter co must be a real number. 

594 ''' 

595 if not isinstance(cx, (int, float)): 

596 raise TypeError('\n\nParameter cx must be a real number.\n') 

597 if not isinstance(cy, (int, float)): 

598 raise TypeError('\n\nParameter cy must be a real number.\n') 

599 if not isinstance(co, (int, float)): 

600 raise TypeError('\n\nParameter co must be a real number.\n') 

601 

602 

603def space_3d(space_dim): 

604 ''' 

605 Check that the lattice lives in 3D space. 

606 

607 Raises 

608 ------ 

609 ValueError 

610 This method requires a lattice in 3D space. 

611 ''' 

612 if space_dim != 3: 

613 raise ValueError('\n\nThis method requires a lattice in 3D space ' 

614 '(unit_cell and prim_vec given as 3-tuples).\n') 

615 

616 

617def sites(sites): 

618 ''' 

619 Check if *get_lattice* has been called (*coor* not empty). 

620 

621 Raises 

622 ------ 

623 RuntimeError 

624 Run method lat.get_lattice first. 

625 ''' 

626 if sites == 0: 

627 raise RuntimeError('\n\nRun method lat.get_lattice first.\n') 

628 

629 

630#################################### 

631# CLASS SYSTEM EXCEPTION HANDLING 

632#################################### 

633 

634 

635def sys(sys): 

636 ''' 

637 Check if parameter is an instance of the *system*. 

638 

639 Raises 

640 ------ 

641 TypeError 

642 Parameter must be an instance of the class system. 

643 ''' 

644 names = inspect.getmro(sys.__class__) 

645 if str(names).find('system') == -1: 

646 raise TypeError('\n\nParameter must be an instance of the class system.\n') 

647 

648 

649def print_hopping(n, nmax): 

650 ''' 

651 Check method *print_vec_hopping*. 

652 

653 Raises 

654 ------ 

655 TypeError 

656 Parameter *nmax* must be an integer. 

657 ValueError 

658 Parameter *nmax* must be a positive integer. 

659 between 1 and n_max-1. 

660 ''' 

661 if not isinstance(n, int): 

662 raise TypeError('\n\nParameter n_max must be an integer.\n') 

663 if n < 1 or n > nmax-1: 

664 raise ValueError('\n\nParameter n_max must be a positive integer' 

665 'between 1 and n_max-1.\n') 

666 

667 

668def set_onsite(onsite, tags): 

669 ''' 

670 Check method *set_onsite*. 

671 

672 Raises 

673 ------ 

674 TypeError 

675 Parameter onsite must be a dictionary. 

676 ValueError 

677 Parameter onsite keys must be a tag. 

678 ValueError 

679 Parameter onsite values must be 

680 real and/or complex numbers, or value functions. 

681 ''' 

682 if not isinstance(onsite, dict): 

683 raise TypeError('\n\nParameter onsite must be a dictionary.\n') 

684 for tag, val in onsite.items(): 

685 if tag not in tags: 

686 raise ValueError('\n\nParameter onsite keys must be a tag.\n') 

687 if not isinstance(val, (int, float, complex)) and not callable(val): 

688 raise ValueError('\n\nParameter onsite values must be\n'\ 

689 'real and/or complex numbers, or value functions.\n') 

690 

691 

692def set_hopping(list_hop, n_max): 

693 ''' 

694 Check method *set_hopping*. 

695 

696 Raises 

697 ------ 

698 TypeError 

699 Parameter *list_hop* must be a list. 

700 TypeError 

701 Parameter *list_hop* must be a list of dictionary. 

702 KeyError 

703 "n" and "t" must be dictionary keys. 

704 KeyError 

705 "tag" or "ang" must be a key. 

706 KeyError 

707 "tag" and "ang" must be keys. 

708 ValueError 

709 Dictionaries must be of length 2, 3, or 4. 

710 ValueError 

711 "n" must be between 1 and nmax" 

712 ''' 

713 if not isinstance(list_hop, list): 

714 raise TypeError('\n\nParameter *list_hop* must be a list.\n') 

715 for dic in list_hop: 

716 if not isinstance(dic, dict): 

717 raise TypeError('\n\nParameter *list_hop* must be a list of dictionary.\n') 

718 if 'n' not in dic or 't' not in dic: 

719 raise KeyError('\n\n"n" and "t" must be dictionary keys.\n') 

720 if not isinstance(dic['n'], int): 

721 raise TypeError('\n\n"n" value must be an integer.\n') 

722 if not 0 < dic['n'] <= n_max: 

723 raise ValueError('\n\n"n" value must be between 1 and {}.\n'.format(n_max)) 

724 if not isinstance(dic['t'], (int, float, complex)) and not callable(dic['t']): 

725 raise TypeError('\n\n"t" value must be a real or complex number, or a value function.\n') 

726 if len(dic) == 3: 

727 if 'tag' not in dic and 'ang' not in dic: 

728 raise KeyError('\n\n"tag" or "ang" must be a key.\n') 

729 elif len(dic) == 4: 

730 if 'tag' not in dic or 'ang' not in dic: 

731 raise KeyError('\n\n"tag" and "ang" must be keys.\n') 

732 elif len(dic) > 4: 

733 raise ValueError('\n\nDictionaries must be of length 2, 3, or 4.\n') 

734 if 'tag' in dic: 

735 hop_tag(dic['tag']) 

736 if 'ang' in dic: 

737 if not isinstance(dic['ang'], (int, float)): 

738 raise TypeError('\n\n"ang" value must be a real number.\n') 

739 

740 

741def hop_tag(tag): 

742 ''' 

743 Check a bond selector "tag": a string of two one-character tags 

744 ('ab'), or a tuple or list of two tags (('Mo', 'S')). 

745 

746 Raises 

747 ------ 

748 TypeError 

749 "tag" value must be a string or a pair of strings. 

750 ValueError 

751 "tag" value must be a string of length 2 or a pair of tags. 

752 ''' 

753 if isinstance(tag, (tuple, list)): 

754 if len(tag) != 2 or not all(isinstance(t, str) for t in tag): 

755 raise TypeError('\n\n"tag" value must be a string or a pair of strings.\n') 

756 if not all(1 <= len(t) <= TAG_LEN for t in tag): 

757 raise ValueError('\n\n"tag" pair must hold tags of 1 to {} characters.\n'.format(TAG_LEN)) 

758 elif not isinstance(tag, str): 

759 raise TypeError('\n\n"tag" value must be a string.\n') 

760 elif len(tag) != 2: 

761 raise ValueError('\n\n"tag" value must be a string of length 2 (two one-character tags),\n' 

762 'or a pair of tags such as ("Mo", "S").\n') 

763 

764 

765def index(ind, dic): 

766 ''' 

767 check if *ind* not empy. 

768 ''' 

769 if np.sum(ind) == 0: 

770 raise ValueError('\n\nNo hoppings with parameters {}.\n'.format(dic)) 

771 

772 

773def set_hopping_def(hop, hopping_def, sites, var_name='hopping_def', same_site=False): 

774 ''' 

775 Check methods *set_hopping_def* and *set_hopping_manual*. 

776 

777 *hop* is not used (kept for backward compatibility). Indices may be 

778 Python or NumPy integers, values Python or NumPy numbers. If *same_site* 

779 is True, keys :math:`(i, i)` are accepted. 

780 

781 Raises 

782 ------ 

783 TypeError 

784 Parameter *hopping_def* must be a dictionary 

785 TypeError 

786 *hopping_def* keys must be tuples. 

787 TypeError 

788 *hopping_def* keys must be tuples of length 2. 

789 ValueError 

790 *hopping_def* keys must be tuples of integers. 

791 ValueError 

792 *hopping_def* keys must be integers between 0 and sites-1. 

793 ValueError 

794 *hopping_def* keys must be different integers between 0 and sites-1. 

795 TypeError 

796 *hopping_def* values must be numbers. 

797 ''' 

798 if not isinstance(hopping_def, dict): 

799 raise TypeError('\n\nParameter {} must be a dictionary.\n'.format(var_name)) 

800 for key, val in hopping_def.items(): 

801 if not isinstance(key, tuple): 

802 raise TypeError('\n\n{} keys must be tuples.\n'.format(var_name)) 

803 if len(key) != 2: 

804 raise TypeError('\n\n{} keys must be tuples of length 2.\n'.format(var_name)) 

805 if not isinstance(key[0], (int, np.integer)) or not isinstance(key[1], (int, np.integer)): 

806 raise ValueError('\n\n{} keys must be tuples of integers.\n'.format(var_name)) 

807 if key[0] < 0 or key[1] < 0 or key[0] > sites-1 or key[1] > sites-1: 

808 raise ValueError('\n\n{} keys must be integers between 0 and sites-1.\n'.format(var_name)) 

809 if key[0] == key[1] and not same_site: 

810 raise ValueError('\n\n{} keys must be different integers between 0 and sites-1.\n'.format(var_name)) 

811 if not isinstance(val, (int, float, complex, np.number)): 

812 raise TypeError('\n\n{} values must be numbers.\n'.format(var_name)) 

813 

814 

815def set_onsite_def(onsite_def, sites): 

816 ''' 

817 Check method *set_ons_def*. 

818 

819 Raises 

820 ------ 

821 TypeError 

822 Parameter *onsite_def* must be a dictionary. 

823 TypeError 

824 *onsite_def* keys must be integers. 

825 TypeError 

826 *onsite_def* values must be numbers. 

827 ValueError 

828 *onsite_def* keys must be integers between :math:`[0, sites)`. 

829 ''' 

830 if not isinstance(onsite_def, dict): 

831 raise TypeError('\n\nParameter onsite_def must be a dictionary.\n') 

832 for key, val in onsite_def.items(): 

833 if not isinstance(key, int): 

834 raise TypeError('\n\nonsite_def keys must be integers.\n') 

835 if not isinstance(val, (int, float, complex)): 

836 raise TypeError('\n\nonsite_def values must be numbers.\n') 

837 if key < 0 or key > sites-1: 

838 raise ValueError('\n\nonsite_def keys must be integers between 0 and sites-1.\n') 

839 

840 

841def hop_n1(hop): 

842 ''' 

843 Check method if self.hop contains nearest neighbours hoppings. 

844 

845 Raises 

846 ------ 

847 ValueError 

848 self.hop must contain nearest neighbours hoppings. 

849 ''' 

850 if not np.any(hop['n'] == 1): 

851 raise ValueError('\n\nParameter hop must contain nearest neighbours hoppings.\n') 

852 

853 

854def empty_onsite(onsite): 

855 ''' 

856 Check if *onsite* not empty. 

857 

858 Raises 

859 ------ 

860 RuntimeError 

861 Run method set_onsite first. 

862 ''' 

863 if onsite.size == 0: 

864 raise RuntimeError('\n\nRun method set_onsite first\n') 

865 

866 

867def empty_hop(hop): 

868 ''' 

869 Check if *hop* not empty. 

870 

871 Raises 

872 ------ 

873 RuntimeError 

874 Run method set_hopping first. 

875 ''' 

876 if hop.size == 0: 

877 raise RuntimeError('\n\nRun method set_hopping first\n') 

878 

879 

880def hop_sites(hop, sites): 

881 ''' 

882 Check if *hop* indices are smaller than *sites*. 

883 

884 Raises 

885 ------ 

886 ValueError 

887 Run method sys.clear_hopping and redefine the hoppings. 

888 ''' 

889 ind_max = max(np.max(hop[f]) for f in ('i', 'j') if f in hop.dtype.names) 

890 if ind_max >= sites: 

891 raise ValueError('\n\nThe hoppings refer to sites that no longer exist.\n' 

892 'Run method system.clear_hopping ' 

893 'and redefine the hoppings.\n') 

894 

895 

896def empty_coor(coor): 

897 ''' 

898 Check if *coor* not empty. 

899 

900 Raises 

901 ------ 

902 RuntimeError 

903 Run method lattice.get_lattice first. 

904 ''' 

905 if coor.size == 0: 

906 raise RuntimeError('\n\nRun method lattice.get_lattice first.\n') 

907 

908 

909def empty_coor_hop(coor_hop): 

910 ''' 

911 Check if *coor_hop* not empty. 

912 

913 Raises 

914 ------ 

915 RuntimeError 

916 Run method system.get_coor_hop first. 

917 ''' 

918 if coor_hop.size == 0: 

919 raise RuntimeError('\n\nRun method system.get_coor_hop first.\n') 

920 

921 

922def empty_ham(ham): 

923 ''' 

924 Check if Hamiltonian not empty. 

925 

926 Raises 

927 ------ 

928 RuntimeError 

929 Run method system.get_ham first. 

930 ''' 

931 if not ham.nnz: 

932 raise RuntimeError('\n\nRun method system.get_ham first.\n') 

933 

934 

935def empty_en(en): 

936 ''' 

937 Check if *en* not empty. 

938 

939 Raises 

940 ------ 

941 RuntimeError 

942 Run method get_ham first. 

943 ''' 

944 if en.size == 0: 

945 raise RuntimeError('\n\nRun method get_eig first\n') 

946 

947 

948def empty_pola(pola): 

949 ''' 

950 Check if *pola* not empty. 

951 

952 Raises 

953 ------ 

954 RuntimeError 

955 Run method get_eig(eigenvec=True) first. 

956 ''' 

957 if pola.size == 0: 

958 raise RuntimeError('\n\nRun method get_eig(eigenvec=True) first\n') 

959 

960 

961def empty_vn(vn): 

962 ''' 

963 Check if *vn* not empty. 

964 

965 Raises 

966 ------ 

967 RuntimeError 

968 Run method get_eig(eigenvec=True) first. 

969 ''' 

970 if vn.size == 0: 

971 raise RuntimeError('\n\nRun method get_eig(eigenvec=True) first\n') 

972 

973 

974def empty_ipr(ipr): 

975 ''' 

976 Check if *ipr* not empty. 

977 ''' 

978 if ipr.size == 0: 

979 raise RuntimeError('\n\nRun method get_ipr first\n') 

980 

981 

982def empty_ndarray(arr, method): 

983 ''' 

984 Check if *arr* is a not empty np.ndarray. 

985 ''' 

986 if arr.size == 0: 

987 raise RuntimeError('\n\nRun method {} first\n'. format(method)) 

988 

989 

990def tag(tag, tags): 

991 ''' 

992 Check tag. 

993 

994 Raises 

995 ------ 

996 TypeError 

997 Parameter *tag* must be a string. 

998 ValueError 

999 Parameter *tag* is not in tags. 

1000 ''' 

1001 if not isinstance(tag, str): 

1002 raise TypeError('\n\nParameter tag must be a string.\n') 

1003 if tag not in tags: 

1004 raise ValueError('\n\nParameter tag is not in tags.\n') 

1005 

1006 

1007def angle(angle, angles, upper_part): 

1008 ''' 

1009 Check angle. 

1010 

1011 Raises 

1012 ------ 

1013 TypeError 

1014 Parameter *angle* must be 

1015 

1016 * a positive number if *upper_part* is True 

1017 * a negative real if *upper_part* is False. 

1018 ValueError 

1019 Parameter *angle* is not in hop['ang']. 

1020 ''' 

1021 if upper_part: 

1022 positive_real_zero(angle, 'angle, if upper_part=True,') 

1023 else: 

1024 negative_real(angle, 'angle, if upper_part=False,') 

1025 if not np.sum(np.isclose(angle, angles, atol=ATOL)) and \ 

1026 not np.sum(np.isclose(angle, angles - 180, atol=ATOL)): 

1027 raise ValueError('\n\nParameter angle is not in hop["ang"].\n') 

1028 

1029 

1030def lims(lims): 

1031 ''' 

1032 Check parameter *lims*. 

1033 

1034 Raises 

1035 ------ 

1036 TypeError 

1037 Parameter lims must be a list. 

1038 TypeError 

1039 Parameter *lims[0]* must be a real number. 

1040 TypeError 

1041 Parameter *lims[1]* must be a real number. 

1042 ValueError 

1043 *lims* must be a list of length 2. 

1044 ValueError 

1045 *lims[0]* must be smaller than *lims[1]*. 

1046 ''' 

1047 if lims is not None: 

1048 list_tuple_2elem(lims, 'lims') 

1049 real_number(lims[0], 'lims[0]') 

1050 real_number(lims[1], 'lims[1]') 

1051 smaller(lims[0], 'lims[0]', lims[1], 'lims[1]') 

1052 

1053 

1054def lims_positive(lims): 

1055 ''' 

1056 Check parameter *lims*. 

1057 

1058 Raises 

1059 ------ 

1060 TypeError 

1061 Parameter lims must be a list. 

1062 TypeError 

1063 Parameter *lims[0]* must be a positive real number. 

1064 TypeError 

1065 Parameter *lims[1]* must be a positive real number. 

1066 ValueError 

1067 *lims* must be a list of length 2. 

1068 ValueError 

1069 *lims[0]* must be smaller than *lims[1]*. 

1070 ''' 

1071 if lims is not None: 

1072 list_tuple_2elem(lims, 'lims') 

1073 positive_real(lims[0], 'lims[0]') 

1074 positive_real(lims[1], 'lims[1]') 

1075 smaller(lims[0], 'lims[0]', lims[1], 'lims[1]') 

1076 

1077 

1078################################# 

1079# CLASS PLOT EXCEPTION HANDLING 

1080################################# 

1081 

1082 

1083def fig(fig): 

1084 ''' 

1085 Check if fig is an instance of *Figure*. 

1086 

1087 Raises 

1088 ------ 

1089 TypeError 

1090 fig must be an instance of *Figure*. 

1091 ''' 

1092 if not fig.__class__.__name__ == 'Figure': 

1093 raise TypeError('\n\nfig must be an instance of *Figure*.\n') 

1094 

1095 

1096def ani(ani): 

1097 ''' 

1098 Check if ani is an instance of *FuncAnimation*. 

1099 

1100 Raises 

1101 ------ 

1102 TypeError 

1103 ani must be an instance of *FuncAnimation*. 

1104 ''' 

1105 if not ani.__class__.__name__ == 'FuncAnimation': 

1106 raise TypeError('\n\nani must be an instance of *FuncAnimation*.\n') 

1107 

1108 

1109def file_format(file_format): 

1110 ''' 

1111 Check if file_format is a string 'png', 'pdf', 'ps', 'eps', or 'svg'. 

1112 

1113 Raises 

1114 ------ 

1115 TypeError 

1116 file_format must be a string. 

1117 ValueError 

1118 file_format must be a string given by 'png', 'pdf', 'ps', 'eps', or 'svg'. 

1119 ''' 

1120 if not isinstance(file_format, str): 

1121 raise TypeError('\n\nfile_format must be a string.\n') 

1122 if file_format not in ['png', 'pdf', 'ps', 'eps', 'svg']: 

1123 raise ValueError('\n\nfile_format must be a string given by,\n'\ 

1124 ' "png", "pdf", "ps", "eps", or "svg".\n') 

1125 

1126 

1127#################################### 

1128# PROPAGATION 

1129#################################### 

1130 

1131 

1132def get_pump(hams): 

1133 ''' 

1134 Check method *propagation.get_pumping*. 

1135 

1136 Raises 

1137 ------ 

1138 TypeError 

1139 hams must be a non-empty list. 

1140 RuntimeError 

1141 Run method system.get_ham first. 

1142 ''' 

1143 if not isinstance(hams, list) or not hams: 

1144 raise TypeError('\n\nhams must be a non-empty list.\n') 

1145 for ham in hams: 

1146 empty_ham(ham) 

1147 

1148def prop_type(prop_type): 

1149 string(prop_type, 'prop_type') 

1150 if prop_type not in ['real', 'imag', 'norm']: 

1151 raise ValueError('\n\nParameter prop_type must be a string:\n' 

1152 '"real", "imag", "norm".\n') 

1153 

1154 

1155def prop_method(method): 

1156 ''' 

1157 Check the method of *Propagation.get_propagation*. 

1158 

1159 Raises 

1160 ------ 

1161 ValueError 

1162 Parameter method must be "crank-nicolson" or "chebyshev". 

1163 ''' 

1164 if method not in ('crank-nicolson', 'chebyshev'): 

1165 raise ValueError('\n\nParameter method must be "crank-nicolson" or "chebyshev".\n') 

1166 

1167 

1168#################################### 

1169# CLASS KSPACE EXCEPTION HANDLING 

1170#################################### 

1171 

1172 

1173def k_vector(vec, var_name, ndim): 

1174 ''' 

1175 Check that *vec* is a tuple/list of *ndim* real numbers. 

1176 

1177 Raises 

1178 ------ 

1179 TypeError 

1180 Parameter *var_name* must be a tuple/list. 

1181 ValueError 

1182 Parameter *var_name* must be of length *ndim*. 

1183 TypeError 

1184 Parameter *var_name* must contain real numbers. 

1185 ''' 

1186 if not isinstance(vec, (tuple, list, np.ndarray)): 

1187 raise TypeError('\n\nParameter {} must be a tuple, list, or ndarray.\n'.format(var_name)) 

1188 if len(vec) != ndim: 

1189 raise ValueError('\n\nParameter {} must be of length {}.\n'.format(var_name, ndim)) 

1190 for val in vec: 

1191 if not isinstance(val, (int, float, np.integer, np.floating)): 

1192 raise TypeError('\n\nParameter {} must contain real numbers.\n'.format(var_name)) 

1193 

1194 

1195def k_points(k, var_name, ndim): 

1196 ''' 

1197 Check that *k* is one k-point (see *k_vector*) or an array of shape 

1198 (nk, *ndim*) of real numbers. 

1199 

1200 Raises 

1201 ------ 

1202 ValueError 

1203 Parameter *var_name* must be of shape (nk, ndim). 

1204 ''' 

1205 if np.ndim(k) != 2: 

1206 k_vector(k, var_name, ndim) 

1207 return 

1208 k = np.asarray(k) 

1209 if k.shape[1] != ndim or not np.issubdtype(k.dtype, np.number) or np.iscomplexobj(k): 

1210 raise ValueError('\n\nParameter {} must be a real array of shape (nk, {}).\n'.format(var_name, ndim)) 

1211 

1212 

1213def ks(ks, ndim): 

1214 ''' 

1215 Check the k-points passed to *kspace.get_bands*: a 2D array of shape 

1216 (nk, *ndim*). 

1217 

1218 Raises 

1219 ------ 

1220 ValueError 

1221 Parameter ks must be of shape (nk, ndim). 

1222 ''' 

1223 if ks.ndim != 2 or ks.shape[1] != ndim: 

1224 raise ValueError('\n\nParameter ks must be an array of shape (nk, {}).\n'.format(ndim)) 

1225 

1226 

1227def spin_matrix(t, var_name): 

1228 ''' 

1229 Check a spinful "t" or onsite value: either a plain number, or a 2x2 

1230 complex matrix. 

1231 

1232 Raises 

1233 ------ 

1234 TypeError 

1235 Parameter *var_name* must be a number or a 2x2 matrix. 

1236 ''' 

1237 if isinstance(t, (int, float, complex)): 

1238 return 

1239 t = np.asarray(t) 

1240 if t.shape != (2, 2): 

1241 raise TypeError('\n\nParameter {} must be a number or a 2x2 matrix.\n'.format(var_name)) 

1242 

1243 

1244def set_hopping_kspace(list_hop, n_sites, ndim, spin=False, values=False): 

1245 ''' 

1246 Check method *kspace.set_hopping*. With *values*, "t" may also be a 

1247 value function (a callable). 

1248 

1249 Raises 

1250 ------ 

1251 TypeError 

1252 Parameter *list_hop* must be a list of dictionaries. 

1253 KeyError 

1254 "i", "j", "R", and "t" must be dictionary keys. 

1255 ValueError 

1256 "i" and "j" must be site indices between 0 and n_sites-1. 

1257 ValueError 

1258 "R" must be a tuple of *ndim* integers. 

1259 TypeError 

1260 "t" must be a real or complex number (or, if *spin*, 

1261 a 2x2 matrix). 

1262 ''' 

1263 if not isinstance(list_hop, list): 

1264 raise TypeError('\n\nParameter list_hop must be a list.\n') 

1265 for dic in list_hop: 

1266 if not isinstance(dic, dict): 

1267 raise TypeError('\n\nParameter list_hop must be a list of dictionaries.\n') 

1268 if not {'i', 'j', 'R', 't'} <= set(dic): 

1269 raise KeyError('\n\n"i", "j", "R", and "t" must be dictionary keys.\n') 

1270 if not isinstance(dic['i'], int) or not isinstance(dic['j'], int): 

1271 raise TypeError('\n\n"i" and "j" must be integers.\n') 

1272 if not (0 <= dic['i'] < n_sites) or not (0 <= dic['j'] < n_sites): 

1273 raise ValueError('\n\n"i" and "j" must be site indices between 0 and {}.\n'.format(n_sites-1)) 

1274 if not isinstance(dic['R'], tuple) or len(dic['R']) != ndim: 

1275 raise ValueError('\n\n"R" must be a tuple of {} integers.\n'.format(ndim)) 

1276 if not all(isinstance(n, int) for n in dic['R']): 

1277 raise TypeError('\n\n"R" must be a tuple of integers.\n') 

1278 if dic['i'] == dic['j'] and dic['R'] == (0,) * ndim: 

1279 raise ValueError('\n\nUse kspace.set_onsite for i == j and R == 0 ' 

1280 '(it accepts a 2x2 spin matrix when spin=True).\n') 

1281 if values and callable(dic['t']): 

1282 continue 

1283 if spin: 

1284 spin_matrix(dic['t'], '"t"') 

1285 elif not isinstance(dic['t'], (int, float, complex)): 

1286 raise TypeError('\n\n"t" value must be a real or complex number.\n') 

1287 

1288 

1289def set_onsite_kspace(dict_onsite, tags, spin=False): 

1290 ''' 

1291 Check method *kspace.set_onsite*. 

1292 

1293 Raises 

1294 ------ 

1295 TypeError 

1296 Parameter *dict_onsite* must be a dictionary. 

1297 ValueError 

1298 keys must be tags. 

1299 TypeError 

1300 values must be real or complex numbers (or, if 

1301 *spin*, a pair of real/complex numbers, or a 2x2 matrix). 

1302 ''' 

1303 if not isinstance(dict_onsite, dict): 

1304 raise TypeError('\n\nParameter dict_onsite must be a dictionary.\n') 

1305 for tag, val in dict_onsite.items(): 

1306 if tag not in tags: 

1307 raise ValueError('\n\nParameter dict_onsite keys must be a tag.\n') 

1308 if spin and not isinstance(val, (int, float, complex)): 

1309 is_pair = (isinstance(val, (tuple, list)) and len(val) == 2 

1310 and all(isinstance(v, (int, float, complex)) for v in val)) 

1311 is_mat = np.ndim(val) == 2 and np.shape(val) == (2, 2) 

1312 if not (is_pair or is_mat): 

1313 raise TypeError('\n\nParameter dict_onsite values must be a number, or, ' 

1314 'if spin, a pair of numbers (E_up, E_down) or a ' 

1315 '2x2 matrix.\n') 

1316 elif not spin and not isinstance(val, (int, float, complex)): 

1317 raise TypeError('\n\nParameter dict_onsite values must be real and/or complex numbers.\n') 

1318 

1319 

1320def k_path_points(points, ndim): 

1321 ''' 

1322 Check parameter *points* used by *kspace.k_path*. 

1323 

1324 Raises 

1325 ------ 

1326 TypeError 

1327 Parameter points must be a list. 

1328 ValueError 

1329 Parameter points must contain at least two k-points. 

1330 ''' 

1331 if not isinstance(points, list): 

1332 raise TypeError('\n\nParameter points must be a list of k-points.\n') 

1333 if len(points) < 2: 

1334 raise ValueError('\n\nParameter points must contain at least two k-points.\n') 

1335 for i, pt in enumerate(points): 

1336 k_vector(pt, 'points[{}]'.format(i), ndim) 

1337 

1338 

1339#################################### 

1340# DENSITY OF STATES 

1341#################################### 

1342 

1343 

1344def dos_kernel(kernel): 

1345 ''' 

1346 Check parameter *kernel* used by *dos.density_of_states*. 

1347 

1348 Raises 

1349 ------ 

1350 TypeError 

1351 Parameter kernel must be a string. 

1352 ValueError 

1353 Parameter kernel must be "gaussian" or "lorentzian". 

1354 ''' 

1355 string(kernel, 'kernel') 

1356 if kernel not in ['gaussian', 'lorentzian']: 

1357 raise ValueError('\n\nParameter kernel must be a string:\n' 

1358 '"gaussian", "lorentzian".\n') 

1359 

1360 

1361def kspace_dos_kernel(kernel): 

1362 ''' 

1363 Check parameter *kernel* used by *kspace.plot_dos*. 

1364 

1365 Raises 

1366 ------ 

1367 TypeError 

1368 Parameter kernel must be a string. 

1369 ValueError 

1370 Parameter kernel must be "gaussian", "lorentzian" or "tetrahedron". 

1371 ''' 

1372 string(kernel, 'kernel') 

1373 if kernel not in ['gaussian', 'lorentzian', 'tetrahedron']: 

1374 raise ValueError('\n\nParameter kernel must be a string:\n' 

1375 '"gaussian", "lorentzian", "tetrahedron".\n') 

1376 

1377 

1378def mesh_energies(energies): 

1379 ''' 

1380 Check parameter *energies* used by *dos.tetrahedron_dos*: a non-empty 

1381 array of bands on a mesh of 1, 2 or 3 dimensions. 

1382 

1383 Raises 

1384 ------ 

1385 ValueError 

1386 Parameter energies must be of shape (n1, ..., nbands), on a mesh of 1 to 3 dimensions. 

1387 ''' 

1388 energies = np.asarray(energies) 

1389 if energies.ndim not in (2, 3, 4) or energies.size == 0: 

1390 raise ValueError('\n\nParameter energies must be a non-empty array of shape ' 

1391 '(n1, ..., nbands), on a mesh of 1, 2 or 3 dimensions.\n') 

1392 

1393 

1394def increasing_grid(grid, var_name): 

1395 ''' 

1396 Check that *grid* is a 1D real array of at least two increasing values. 

1397 

1398 Raises 

1399 ------ 

1400 ValueError 

1401 Parameter *var_name* must be a 1D array of at least two increasing real values. 

1402 ''' 

1403 grid = np.asarray(grid) 

1404 if grid.ndim != 1 or len(grid) < 2 or np.iscomplexobj(grid) or np.any(np.diff(grid) <= 0): 

1405 raise ValueError('\n\nParameter {} must be a 1D array of at least two increasing ' 

1406 'real values.\n'.format(var_name)) 

1407 

1408 

1409def nk(nk, ndim): 

1410 ''' 

1411 Check parameter *nk* used by *kspace.mesh_bands* / *kspace.berry_curvature*. 

1412 

1413 Raises 

1414 ------ 

1415 TypeError 

1416 Parameter nk must be an integer or a tuple of integers. 

1417 ValueError 

1418 Parameter nk (or each of its elements) must be a 

1419 positive integer. 

1420 ValueError 

1421 Parameter nk must be a tuple of length *ndim*. 

1422 ''' 

1423 if isinstance(nk, int): 

1424 positive_int(nk, 'nk') 

1425 return 

1426 if not isinstance(nk, tuple): 

1427 raise TypeError('\n\nParameter nk must be an integer or a tuple of integers.\n') 

1428 if len(nk) != ndim: 

1429 raise ValueError('\n\nParameter nk must be of length {}.\n'.format(ndim)) 

1430 for n in nk: 

1431 positive_int(n, 'nk') 

1432 

1433 

1434#################################### 

1435# TOPOLOGY 

1436#################################### 

1437 

1438 

1439def dim_2(dim): 

1440 ''' 

1441 Check that the model is 2D. Berry curvature / Chern number are only 

1442 defined for a 2D Brillouin zone. 

1443 

1444 Raises 

1445 ------ 

1446 ValueError 

1447 This calculation requires a 2D lattice. 

1448 ''' 

1449 if dim != 2: 

1450 raise ValueError('\n\nThis calculation requires a 2D lattice ' 

1451 '(two primitive vectors).\n') 

1452 

1453 

1454def dim_min(dim, dmin): 

1455 ''' 

1456 Check that the model has at least *dmin* periodic dimensions. 

1457 

1458 Raises 

1459 ------ 

1460 ValueError 

1461 This calculation requires a lattice with at least dmin primitive vectors. 

1462 ''' 

1463 if dim < dmin: 

1464 raise ValueError('\n\nThis calculation requires a lattice with at least {} ' 

1465 'primitive vectors.\n'.format(dmin)) 

1466 

1467 

1468def plane(plane, dim): 

1469 ''' 

1470 Check parameter *plane* of *kspace.berry_curvature*: two distinct 

1471 reciprocal-vector indices below *dim*. 

1472 

1473 Raises 

1474 ------ 

1475 TypeError 

1476 Parameter plane must be a tuple of two integers. 

1477 ValueError 

1478 Parameter plane must contain two distinct indices below dim. 

1479 ''' 

1480 if not isinstance(plane, tuple) or len(plane) != 2 or \ 

1481 not all(isinstance(p, int) for p in plane): 

1482 raise TypeError('\n\nParameter plane must be a tuple of two integers.\n') 

1483 if plane[0] == plane[1] or not all(0 <= p < dim for p in plane): 

1484 raise ValueError('\n\nParameter plane must contain two distinct indices ' 

1485 'between 0 and {}.\n'.format(dim - 1)) 

1486 

1487 

1488def direction(direction, dim=2): 

1489 ''' 

1490 Check parameter *direction* used by *kspace.ribbon* (and the Wilson-loop 

1491 methods): a primitive-vector index below *dim*. 

1492 

1493 Raises 

1494 ------ 

1495 TypeError 

1496 Parameter direction must be an integer. 

1497 ValueError 

1498 Parameter direction must be between 0 and dim-1. 

1499 ''' 

1500 if not isinstance(direction, int): 

1501 raise TypeError('\n\nParameter direction must be an integer.\n') 

1502 if not 0 <= direction < dim: 

1503 raise ValueError('\n\nParameter direction must be between 0 and {}.\n'.format(dim - 1)) 

1504 

1505 

1506def band_indices(bands, norb): 

1507 ''' 

1508 Check parameter *bands* used by *kspace.berry_curvature*. 

1509 

1510 Raises 

1511 ------ 

1512 TypeError 

1513 Parameter bands must be a non-empty list of integers. 

1514 ValueError 

1515 Parameter bands must be a list of distinct band 

1516 indices between 0 and norb-1. 

1517 ''' 

1518 if not isinstance(bands, list) or not bands: 

1519 raise TypeError('\n\nParameter bands must be a non-empty list of integers.\n') 

1520 if not all(isinstance(b, int) for b in bands): 

1521 raise TypeError('\n\nParameter bands must be a non-empty list of integers.\n') 

1522 if len(set(bands)) != len(bands): 

1523 raise ValueError('\n\nParameter bands must be a list of distinct band indices.\n') 

1524 if not all(0 <= b < norb for b in bands): 

1525 raise ValueError('\n\nParameter bands must be integers between 0 and {}.\n'.format(norb-1)) 

1526 

1527 

1528#################################### 

1529# BERRY PHASES, Z2, SYMMETRIES 

1530#################################### 

1531 

1532 

1533def k_perp(k_perp, n): 

1534 ''' 

1535 Check parameter *k_perp* of the Wilson-loop methods: a tuple of *n* real 

1536 numbers (fractional coordinates along the other reciprocal vectors). 

1537 

1538 Raises 

1539 ------ 

1540 ValueError 

1541 Parameter k_perp must contain n real numbers. 

1542 ''' 

1543 if len(k_perp) != n or not all(isinstance(f, (int, float)) for f in k_perp): 

1544 raise ValueError('\n\nParameter k_perp must contain {} real number(s).\n'.format(n)) 

1545 

1546 

1547def flow(flow, direction, dim): 

1548 ''' 

1549 Check parameter *flow* of *kspace.wannier_flow*. 

1550 

1551 Raises 

1552 ------ 

1553 TypeError 

1554 Parameter flow must be an integer. 

1555 ValueError 

1556 Parameter flow must be a direction other than *direction*. 

1557 ''' 

1558 if not isinstance(flow, int): 

1559 raise TypeError('\n\nParameter flow must be an integer.\n') 

1560 if flow == direction or not 0 <= flow < dim: 

1561 raise ValueError('\n\nParameter flow must be a direction between 0 and {}, ' 

1562 'other than direction.\n'.format(dim - 1)) 

1563 

1564 

1565def even_bands(bands): 

1566 ''' 

1567 Check that *bands* is a list of an even number of band indices (Kramers pairs). 

1568 

1569 Raises 

1570 ------ 

1571 TypeError 

1572 Parameter bands must be a list. 

1573 ValueError 

1574 Parameter bands must contain an even number of bands. 

1575 ''' 

1576 if not isinstance(bands, list): 

1577 raise TypeError('\n\nParameter bands must be a list of band indices.\n') 

1578 if len(bands) % 2: 

1579 raise ValueError('\n\nParameter bands must contain an even number of bands ' 

1580 '(Kramers pairs).\n') 

1581 

1582 

1583def operator(mat, norb): 

1584 ''' 

1585 Check a symmetry operator: a (norb, norb) matrix. 

1586 

1587 Raises 

1588 ------ 

1589 ValueError 

1590 The operator must be a (norb, norb) matrix. 

1591 ''' 

1592 if mat.shape != (norb, norb): 

1593 raise ValueError('\n\nThe operator must be a ({0}, {0}) matrix.\n'.format(norb)) 

1594 

1595 

1596def parities(xi, tol=1e-6): 

1597 ''' 

1598 Check that inversion eigenvalues are +-1. 

1599 

1600 Raises 

1601 ------ 

1602 ValueError 

1603 The bands are not an inversion-invariant subspace. 

1604 ''' 

1605 if not np.allclose(np.abs(xi.real), 1., atol=tol) or not np.allclose(xi.imag, 0., atol=tol): 

1606 raise ValueError('\n\nThe parity eigenvalues are not +-1: the operator is not ' 

1607 'an inversion symmetry of these bands (or the bands are ' 

1608 'degenerate with the others at a TRIM).\n') 

1609 if np.sum(xi.real < 0) % 2: 

1610 raise ValueError('\n\nOdd number of negative parities: the bands are not ' 

1611 'Kramers pairs.\n') 

1612 

1613 

1614def k_map(k_map): 

1615 ''' 

1616 Check parameter *k_map* of *kspace.symmetry_error*. 

1617 

1618 Raises 

1619 ------ 

1620 ValueError 

1621 Parameter k_map must be 'minus' or 'identity'. 

1622 ''' 

1623 if k_map not in ('minus', 'identity'): 

1624 raise ValueError('\n\nParameter k_map must be "minus" or "identity".\n') 

1625 

1626 

1627def is_symmetry(err, tol): 

1628 ''' 

1629 Check that a symmetry error is below *tol*. 

1630 

1631 Raises 

1632 ------ 

1633 ValueError 

1634 The operator is not a symmetry of the model. 

1635 ''' 

1636 if err > tol: 

1637 raise ValueError('\n\nThe operator is not a symmetry of the model ' 

1638 '(deviation {:.3g}).\n'.format(err)) 

1639 

1640 

1641def symmetry_algebra(u, v, tol): 

1642 ''' 

1643 Check that two symmetry operators of the same kind agree up to a phase 

1644 (in *kspace.KSpace.non_hermitian_class*, *v* is a product of others). 

1645 

1646 Raises 

1647 ------ 

1648 ValueError 

1649 The symmetry operators leave a unitary symmetry: block-diagonalize it first. 

1650 ''' 

1651 phase = np.trace(u.conj().T @ v) / np.trace(u.conj().T @ u) 

1652 if not np.allclose(v, phase * u, atol=tol): 

1653 raise ValueError('\n\nThe symmetry operators leave a unitary symmetry (two products of ' 

1654 'the same kind differ by more than a phase): block-diagonalize ' 

1655 'the Hamiltonian first.\n') 

1656 

1657 

1658def square(sq, tol): 

1659 ''' 

1660 Check that the square of an antiunitary operator is +-1. 

1661 

1662 Raises 

1663 ------ 

1664 ValueError 

1665 The square of the operator must be +1 or -1. 

1666 ''' 

1667 if not np.allclose(sq, sq[0, 0] * np.eye(len(sq)), atol=tol) or \ 

1668 not np.isclose(abs(sq[0, 0]), 1., atol=tol): 

1669 raise ValueError('\n\nThe square of the antiunitary operator must be +1 or -1.\n') 

1670 

1671 

1672def hermitian(ham): 

1673 ''' 

1674 Check that a (sparse) Hamiltonian is Hermitian. 

1675 

1676 Raises 

1677 ------ 

1678 ValueError 

1679 This calculation requires a Hermitian Hamiltonian. 

1680 ''' 

1681 if (abs(ham - ham.conj().T) > 1e-12).nnz: 

1682 raise ValueError('\n\nThis calculation requires a Hermitian Hamiltonian.\n') 

1683 

1684 

1685def planar_cell(prim_vec): 

1686 ''' 

1687 Check that the lattice has two in-plane primitive vectors (a unit-cell area). 

1688 

1689 Raises 

1690 ------ 

1691 ValueError 

1692 Give the area per site explicitly. 

1693 ''' 

1694 if len(prim_vec) != 2 or len(prim_vec[0]) != 2: 

1695 raise ValueError('\n\nThe unit-cell area needs two in-plane primitive vectors: ' 

1696 'give the area per site explicitly.\n') 

1697 

1698 

1699def integer(var, var_name): 

1700 ''' 

1701 Check if *var* is an integer. 

1702 

1703 Raises 

1704 ------ 

1705 TypeError 

1706 Parameter *var* must be an integer. 

1707 ''' 

1708 if not isinstance(var, int): 

1709 raise TypeError('\n\nParameter {} must be an integer.\n'.format(var_name)) 

1710 

1711 

1712def dim_exact(dim, d): 

1713 ''' 

1714 Check that the model has exactly *d* periodic dimensions. 

1715 

1716 Raises 

1717 ------ 

1718 ValueError 

1719 This calculation requires a lattice with d primitive vectors. 

1720 ''' 

1721 if dim != d: 

1722 raise ValueError('\n\nThis calculation requires a lattice with {} primitive ' 

1723 'vector(s).\n'.format(d)) 

1724 

1725 

1726def nonzero_number(var, var_name): 

1727 ''' 

1728 Check if *var* is a nonzero number. 

1729 

1730 Raises 

1731 ------ 

1732 TypeError 

1733 Parameter *var* must be a number. 

1734 ValueError 

1735 Parameter *var* must be nonzero. 

1736 ''' 

1737 number(var, var_name) 

1738 if var == 0: 

1739 raise ValueError('\n\nParameter {} must be nonzero.\n'.format(var_name)) 

1740 

1741 

1742def gbz_roots(n_roots, p): 

1743 ''' 

1744 Check that det[H(beta) - E] has roots on both sides of the GBZ. 

1745 

1746 Raises 

1747 ------ 

1748 ValueError 

1749 The model has no hoppings in both directions. 

1750 ''' 

1751 if p < 1 or n_roots <= p: 

1752 raise ValueError('\n\nThe generalized Brillouin zone needs hoppings in both ' 

1753 'directions along the chain.\n') 

1754 

1755 

1756#################################### 

1757# EXCEPTIONAL POINTS 

1758#################################### 

1759 

1760 

1761def ham_model(model, cls): 

1762 ''' 

1763 Check the model of *tbkit.exceptional*: a 2D **KSpace** instance, or a 

1764 callable of a point of a 2D parameter plane. 

1765 

1766 Raises 

1767 ------ 

1768 TypeError 

1769 Parameter model must be a KSpace instance or a callable. 

1770 ValueError 

1771 A KSpace model must have two primitive vectors. 

1772 ''' 

1773 if isinstance(model, cls): 

1774 if model.dim != 2: 

1775 raise ValueError('\n\nParameter model must be a KSpace with two primitive ' 

1776 'vectors (a 2D Brillouin zone).\n') 

1777 elif not callable(model): 

1778 raise TypeError('\n\nParameter model must be a KSpace instance, or a callable ' 

1779 'returning a square matrix.\n') 

1780 

1781 

1782def ham_matrix(ham): 

1783 ''' 

1784 Check the matrix returned by the callable model of *tbkit.exceptional*: 

1785 square and finite. 

1786 

1787 Raises 

1788 ------ 

1789 ValueError 

1790 The model must return a finite square matrix. 

1791 ''' 

1792 if ham.ndim != 2 or ham.shape[0] != ham.shape[1] or not np.all(np.isfinite(ham)): 

1793 raise ValueError('\n\nThe model must return a finite square matrix.\n') 

1794 

1795 

1796def loop(loop): 

1797 ''' 

1798 Check a closed loop of *tbkit.exceptional*: a callable of s in [0, 1] 

1799 returning a point of the plane, or the vertices of a polygon. 

1800 

1801 Raises 

1802 ------ 

1803 TypeError 

1804 Parameter loop must be a callable or an array of vertices. 

1805 ValueError 

1806 A polygon needs at least 3 vertices with 2 real coordinates. 

1807 ''' 

1808 if callable(loop): 

1809 return 

1810 try: 

1811 arr = np.asarray(loop, dtype='f8') 

1812 except (TypeError, ValueError): 

1813 arr = np.zeros(()) 

1814 if arr.ndim == 0: 

1815 raise TypeError('\n\nParameter loop must be a callable of s in [0, 1], or an ' 

1816 'array of polygon vertices.\n') 

1817 if arr.ndim != 2 or arr.shape[0] < 3 or arr.shape[1] != 2 or not np.all(np.isfinite(arr)): 

1818 raise ValueError('\n\nParameter loop must hold at least 3 vertices of 2 real ' 

1819 'coordinates, shape (m, 2).\n') 

1820 

1821 

1822def loop_point(point): 

1823 ''' 

1824 Check a point returned by a loop callable: 2 finite real numbers. 

1825 

1826 Raises 

1827 ------ 

1828 ValueError 

1829 The loop must return points of 2 real coordinates. 

1830 ''' 

1831 if point.shape != (2,) or not np.all(np.isfinite(point)): 

1832 raise ValueError('\n\nParameter loop must return points of 2 finite real ' 

1833 'coordinates.\n') 

1834 

1835 

1836def closed_loop(ham_start, ham_end): 

1837 ''' 

1838 Check that a loop is closed: the Hamiltonian at its end is the one at its start. 

1839 

1840 Raises 

1841 ------ 

1842 ValueError 

1843 The loop is not closed. 

1844 ''' 

1845 scale = max(1., float(np.max(np.abs(ham_start)))) 

1846 if np.max(np.abs(ham_end - ham_start)) > 1e-9 * scale: 

1847 raise ValueError('\n\nParameter loop must be closed: H(loop(1)) differs from ' 

1848 'H(loop(0)).\n') 

1849 

1850 

1851def band_pair(bands, norb): 

1852 ''' 

1853 Check a pair of band labels: two distinct integers between 0 and norb-1. 

1854 

1855 Raises 

1856 ------ 

1857 TypeError 

1858 Parameter bands must be a pair of integers. 

1859 ValueError 

1860 Parameter bands must be two distinct band indices. 

1861 ''' 

1862 if not isinstance(bands, (tuple, list)) or len(bands) != 2 or \ 

1863 not all(isinstance(b, int) for b in bands): 

1864 raise TypeError('\n\nParameter bands must be a pair of integers (m, n).\n') 

1865 if bands[0] == bands[1] or not all(0 <= b < norb for b in bands): 

1866 raise ValueError('\n\nParameter bands must be two distinct band indices between 0 ' 

1867 'and {}.\n'.format(norb - 1)) 

1868 

1869 

1870def band_index(band, norb): 

1871 ''' 

1872 Check a band label: an integer between 0 and norb-1. 

1873 

1874 Raises 

1875 ------ 

1876 TypeError 

1877 Parameter band must be an integer. 

1878 ValueError 

1879 Parameter band must be between 0 and norb-1. 

1880 ''' 

1881 integer(band, 'band') 

1882 if not 0 <= band < norb: 

1883 raise ValueError('\n\nParameter band must be between 0 and {}.\n'.format(norb - 1)) 

1884 

1885 

1886def tracking(k): 

1887 ''' 

1888 Eigenvalue continuation failed: the path meets a degeneracy. 

1889 

1890 Raises 

1891 ------ 

1892 ValueError 

1893 Cannot follow the eigenvalues continuously near k. 

1894 ''' 

1895 raise ValueError('\n\nCannot follow the eigenvalues continuously near k = {}: the path ' 

1896 'passes through (or too close to) a degeneracy. Move or ' 

1897 'enlarge the loop.\n'.format(np.round(k, 8))) 

1898 

1899 

1900def winding_path(k): 

1901 ''' 

1902 The discriminant vanishes on the path of a winding number. 

1903 

1904 Raises 

1905 ------ 

1906 ValueError 

1907 The loop passes through a zero of the discriminant. 

1908 ''' 

1909 raise ValueError('\n\nThe discriminant vanishes (to numerical precision) on the path, ' 

1910 'near k = {}: the loop passes through a degeneracy. Move the ' 

1911 'loop, or change nk.\n'.format(np.round(k, 8))) 

1912 

1913 

1914def discriminant_nonzero(scale): 

1915 ''' 

1916 Check that the discriminant does not vanish identically. 

1917 

1918 Raises 

1919 ------ 

1920 ValueError 

1921 The bands are degenerate everywhere. 

1922 ''' 

1923 if scale == 0.: 

1924 raise ValueError('\n\nThe discriminant vanishes everywhere: some bands are ' 

1925 'degenerate over the whole zone.\n') 

1926 

1927 

1928def gap_kind(gap): 

1929 ''' 

1930 Check the kind of line gap: 'real' (Re E) or 'imaginary' (Im E). 

1931 

1932 Raises 

1933 ------ 

1934 ValueError 

1935 Parameter gap must be "real" or "imaginary". 

1936 ''' 

1937 if gap not in ('real', 'imaginary'): 

1938 raise ValueError('\n\nParameter gap must be "real" or "imaginary".\n') 

1939 

1940 

1941def biorthogonal_kind(kind): 

1942 ''' 

1943 Check the kind of Berry connection: 'LR', 'RL', 'RR' or 'LL'. 

1944 

1945 Raises 

1946 ------ 

1947 ValueError 

1948 Parameter kind must be "LR", "RL", "RR" or "LL". 

1949 ''' 

1950 if kind not in ('LR', 'RL', 'RR', 'LL'): 

1951 raise ValueError('\n\nParameter kind must be "LR", "RL", "RR" or "LL".\n') 

1952 

1953 

1954def line_gap(keys, bands, gap): 

1955 ''' 

1956 Check that *bands* are separated from the other bands by a line gap: 

1957 with the bands ordered by *keys* (Re E or Im E, shape (nk, norb)) at 

1958 every k-point, a band inside the group and its neighbour outside it 

1959 never overlap over the whole mesh. 

1960 

1961 Raises 

1962 ------ 

1963 ValueError 

1964 The bands have no line gap. 

1965 ''' 

1966 inside = np.zeros(keys.shape[1], bool) 

1967 inside[bands] = True 

1968 for n in range(keys.shape[1] - 1): 

1969 if inside[n] != inside[n + 1] and np.max(keys[:, n]) >= np.min(keys[:, n + 1]): 

1970 part = 'Re E' if gap == 'real' else 'Im E' 

1971 raise ValueError('\n\nThe bands {} are not separated from the others by a {} line ' 

1972 'gap: sorted by {}, band {} reaches band {} over the ' 

1973 'Brillouin zone, so the band labels are not continuous. ' 

1974 'For a non-Hermitian model, use ' 

1975 'KSpace.biorthogonal_chern_number with the other kind of ' 

1976 'gap, or locate the gap-closing exceptional points with ' 

1977 'tbkit.exceptional.find_exceptional_points.\n' 

1978 .format(bands, gap, part, n, n + 1)) 

1979 

1980 

1981def band_continuity(en, bands): 

1982 ''' 

1983 Check that a group of bands, labelled at every point of a periodic k 

1984 mesh (*en*, complex, shape (n1, n2, norb)), is continuous: matching the 

1985 eigenvalues of neighbouring points by distance maps the group onto 

1986 itself. A line gap measured on the mesh alone can miss a narrow 

1987 crossing between mesh points; this catches the jump of the labels. 

1988 

1989 Raises 

1990 ------ 

1991 ValueError 

1992 The band labels jump between neighbouring k-points. 

1993 ''' 

1994 from scipy.optimize import linear_sum_assignment 

1995 inside = np.zeros(en.shape[2], bool) 

1996 inside[bands] = True 

1997 for axis in (0, 1): 

1998 nxt = np.roll(en, -1, axis=axis) 

1999 for e_a, e_b in zip(en.reshape(-1, en.shape[2]), nxt.reshape(-1, en.shape[2])): 

2000 _, perm = linear_sum_assignment(np.abs(e_a[:, None] - e_b[None, :])) 

2001 if np.any(inside != inside[perm]): 

2002 raise ValueError('\n\nThe bands {} are not separated from the others over the ' 

2003 'Brillouin zone: between neighbouring k-points they ' 

2004 'exchange eigenvalues with the other bands (the line gap ' 

2005 'closes, e.g. at exceptional points, or nk is too small). ' 

2006 'For a non-Hermitian model, try ' 

2007 'KSpace.biorthogonal_chern_number with the other kind of ' 

2008 'gap, or tbkit.exceptional.find_exceptional_points.\n' 

2009 .format(bands)) 

2010 

2011 

2012def no_overlap(overlap): 

2013 ''' 

2014 Check that no overlap matrix is set (non-orthogonal bases are not 

2015 supported by the biorthogonal tools). 

2016 

2017 Raises 

2018 ------ 

2019 ValueError 

2020 Not available with an overlap matrix. 

2021 ''' 

2022 if overlap: 

2023 raise ValueError('\n\nThis method does not support an overlap matrix (set_overlap).\n') 

2024 

2025 

2026def weights(weights, n): 

2027 ''' 

2028 Check the weights of *occupation.fermi_level*: *n* positive numbers. 

2029 

2030 Raises 

2031 ------ 

2032 ValueError 

2033 Parameter weights must contain n positive numbers. 

2034 ''' 

2035 if len(weights) != n or np.any(weights <= 0): 

2036 raise ValueError('\n\nParameter weights must contain {} positive numbers.\n'.format(n)) 

2037 

2038 

2039def electrons(n_electrons, capacity): 

2040 ''' 

2041 Check a number of electrons: between 0 and the total weight of the levels. 

2042 

2043 Raises 

2044 ------ 

2045 TypeError 

2046 Parameter n_electrons must be a real number. 

2047 ValueError 

2048 Parameter n_electrons must be between 0 and capacity. 

2049 ''' 

2050 positive_real_zero(n_electrons, 'n_electrons') 

2051 if n_electrons > capacity * (1 + 1e-12): 

2052 raise ValueError('\n\nParameter n_electrons must be between 0 and {:g} ' 

2053 '(the number of states).\n'.format(capacity)) 

2054 

2055 

2056def n_eig(n_eig, sites): 

2057 ''' 

2058 Check the number of eigenpairs of *system.get_eig_sparse*. 

2059 

2060 Raises 

2061 ------ 

2062 TypeError 

2063 Parameter n_eig must be an integer. 

2064 ValueError 

2065 Parameter n_eig must be between 1 and sites-2. 

2066 ''' 

2067 positive_int(n_eig, 'n_eig') 

2068 if n_eig > sites - 2: 

2069 raise ValueError('\n\nParameter n_eig must be between 1 and {} (use get_eig for ' 

2070 'the full spectrum).\n'.format(sites - 2)) 

2071 

2072 

2073def slice_count(found, expected, lo, hi): 

2074 ''' 

2075 Check that a shift-invert slice of *System.get_eig_window* found as 

2076 many independent eigenvectors as its inertia count. 

2077 

2078 Raises 

2079 ------ 

2080 RuntimeError 

2081 The sparse solver missed eigenvalues of a slice. 

2082 ''' 

2083 if found != expected: 

2084 raise RuntimeError('\n\nThe sparse solver found {} independent eigenvectors in [{:.6g}, {:.6g}) ' 

2085 'instead of {} (Sylvester inertia): use get_eig.\n'.format(found, lo, hi, expected)) 

2086 

2087 

2088#################################### 

2089# TRANSPORT 

2090#################################### 

2091 

2092 

2093def square_matrix(mat, var_name): 

2094 ''' 

2095 Check that *mat* is a square 2D array. 

2096 

2097 Raises 

2098 ------ 

2099 ValueError 

2100 Parameter must be a square matrix. 

2101 ''' 

2102 if mat.ndim != 2 or mat.shape[0] != mat.shape[1]: 

2103 raise ValueError('\n\nParameter {} must be a square matrix.\n'.format(var_name)) 

2104 

2105 

2106def lead(h0, v): 

2107 ''' 

2108 Check a lead: square cell Hamiltonian *h0* and coupling *v* of the same shape. 

2109 

2110 Raises 

2111 ------ 

2112 ValueError 

2113 h0 and v must be square matrices of the same shape. 

2114 ''' 

2115 square_matrix(h0, 'h0') 

2116 if v.shape != h0.shape: 

2117 raise ValueError('\n\nParameters h0 and v must be square matrices of the same shape.\n') 

2118 

2119 

2120def converged(flag, name): 

2121 ''' 

2122 Check that an iteration converged. 

2123 

2124 Raises 

2125 ------ 

2126 RuntimeError 

2127 The iteration did not converge. 

2128 ''' 

2129 if not flag: 

2130 raise RuntimeError('\n\n{} did not converge: increase max_iter.\n'.format(name)) 

2131 

2132 

2133def lead_direction(direction): 

2134 ''' 

2135 Check the direction of a lead: +1 or -1. 

2136 

2137 Raises 

2138 ------ 

2139 ValueError 

2140 Parameter direction must be +1 or -1. 

2141 ''' 

2142 if direction not in (1, -1): 

2143 raise ValueError('\n\nParameter direction must be +1 or -1.\n') 

2144 

2145 

2146def surface_side(side): 

2147 ''' 

2148 Check parameter *side* of *KSpace.surface_spectral_function*: +1 or -1. 

2149 

2150 Raises 

2151 ------ 

2152 ValueError 

2153 Parameter side must be +1 or -1. 

2154 ''' 

2155 if isinstance(side, bool) or side not in (1, -1): 

2156 raise ValueError('\n\nParameter side must be +1 or -1.\n') 

2157 

2158 

2159def nearest_cells(n): 

2160 ''' 

2161 Check that a lead hopping reaches at most the neighbouring cells. 

2162 

2163 Raises 

2164 ------ 

2165 ValueError 

2166 Lead hoppings must connect neighbouring cells only. 

2167 ''' 

2168 if abs(n) > 1: 

2169 raise ValueError('\n\nA lead from a KSpace model needs hoppings between ' 

2170 'neighbouring cells only (use a larger unit cell).\n') 

2171 

2172 

2173def lead_coupling(coupling, sites, m, n_device): 

2174 ''' 

2175 Check the coupling of a lead to the device. 

2176 

2177 Raises 

2178 ------ 

2179 TypeError 

2180 Parameter sites must be a list of integers. 

2181 ValueError 

2182 sites must be distinct device indices, coupling of shape (len(sites), m). 

2183 ''' 

2184 if not isinstance(sites, list) or not all(isinstance(s, (int, np.integer)) for s in sites): 

2185 raise TypeError('\n\nParameter sites must be a list of integers.\n') 

2186 if len(set(sites)) != len(sites) or not all(0 <= s < n_device for s in sites): 

2187 raise ValueError('\n\nParameter sites must contain distinct device indices ' 

2188 'between 0 and {}.\n'.format(n_device - 1)) 

2189 if coupling.shape != (len(sites), m): 

2190 raise ValueError('\n\nParameter coupling must be of shape (len(sites), len(h0)) ' 

2191 '= ({}, {}).\n'.format(len(sites), m)) 

2192 

2193 

2194def lead_device_size(sites, n_device): 

2195 ''' 

2196 Check that a System has one site per row of the device Hamiltonian. 

2197 

2198 Raises 

2199 ------ 

2200 ValueError 

2201 The System must have as many sites as the device Hamiltonian has rows. 

2202 ''' 

2203 if sites != n_device: 

2204 raise ValueError('\n\nThe System has {} sites but the device Hamiltonian has {} ' 

2205 'rows.\n'.format(sites, n_device)) 

2206 

2207 

2208def lead_space_dim(lead_dim, device_dim): 

2209 ''' 

2210 Check that a lead and the device have positions of the same dimension. 

2211 

2212 Raises 

2213 ------ 

2214 ValueError 

2215 The lead and the device must have the same space dimension. 

2216 ''' 

2217 if lead_dim != device_dim: 

2218 raise ValueError('\n\nThe lead has {}D positions but the device {}D ' 

2219 'ones.\n'.format(lead_dim, device_dim)) 

2220 

2221 

2222def lead_overlap(found): 

2223 ''' 

2224 Check that some device site lies on the lattice of a lead. 

2225 

2226 Raises 

2227 ------ 

2228 ValueError 

2229 No device site matches a lead orbital. 

2230 ''' 

2231 if not found: 

2232 raise ValueError('\n\nNo device site sits at the position (and tag) of a lead ' 

2233 'orbital: place the lead unit cell in the coordinates of the device.\n') 

2234 

2235 

2236def lead_interface(missing): 

2237 ''' 

2238 Check that the interface cell of a lead is complete (*missing*: the lead 

2239 orbitals coupled to the next cell but absent from the device). 

2240 

2241 Raises 

2242 ------ 

2243 ValueError 

2244 The interface between the device and the lead is incomplete. 

2245 ''' 

2246 if missing: 

2247 raise ValueError('\n\nThe device lacks lead orbitals {} in its outermost lead cell: ' 

2248 'extend the device so that it ends with a complete lead ' 

2249 'cell (or pass extend=True).\n'.format([int(o) for o in missing])) 

2250 

2251 

2252def lead_extension(inside): 

2253 ''' 

2254 Check that the lead sites added to complete an interface stay within the 

2255 device's extent along the lead (*inside* False when they would pass the 

2256 innermost lead cell holding a device site). 

2257 

2258 Raises 

2259 ------ 

2260 ValueError 

2261 The lead cannot be closed against the device. 

2262 ''' 

2263 if not inside: 

2264 raise ValueError('\n\nThe lead sites missing from the device reach past its far end: ' 

2265 'the lead is not closed off by the device (wider than it, or ' 

2266 'off its edge).\n') 

2267 

2268 

2269def lead_index(lead, n_leads): 

2270 ''' 

2271 Check a lead index. 

2272 

2273 Raises 

2274 ------ 

2275 TypeError 

2276 The lead index must be an integer. 

2277 ValueError 

2278 No such lead. 

2279 ''' 

2280 if not isinstance(lead, int): 

2281 raise TypeError('\n\nThe lead index must be an integer.\n') 

2282 if not 0 <= lead < n_leads: 

2283 raise ValueError('\n\nNo lead {} ({} lead(s) attached with add_lead).\n'.format(lead, n_leads)) 

2284 

2285 

2286def transport_solver(solver): 

2287 ''' 

2288 Check the sparse solver of *Transport* (*Transport.solver*). 

2289 

2290 Raises 

2291 ------ 

2292 ValueError 

2293 Transport.solver must be "auto", "mumps" or "superlu". 

2294 ''' 

2295 if solver not in ('auto', 'mumps', 'superlu'): 

2296 raise ValueError('\n\nTransport.solver must be "auto", "mumps" or "superlu".\n') 

2297 

2298 

2299def lead_band_edge(flag, energy): 

2300 ''' 

2301 Check that the modes of a lead are well defined: the energy is not at a 

2302 band edge, where a propagating mode has zero velocity. 

2303 

2304 Raises 

2305 ------ 

2306 ValueError 

2307 Energy at a band edge of a lead. 

2308 ''' 

2309 if not flag: 

2310 raise ValueError('\n\nEnergy {} is at a band edge of a lead (a mode with zero velocity): ' 

2311 'shift it slightly.\n'.format(energy)) 

2312 

2313 

2314def conservation_law(law, h0, v, tol=1e-10): 

2315 ''' 

2316 Check the conservation law of a lead: a Hermitian matrix of the shape 

2317 of *h0* that commutes with *h0* and *v*. 

2318 

2319 Raises 

2320 ------ 

2321 ValueError 

2322 Wrong shape, not Hermitian, or not conserved by the lead. 

2323 ''' 

2324 if law.shape != h0.shape: 

2325 raise ValueError('\n\nParameter conservation_law must have the shape of h0, {}.\n'.format(h0.shape)) 

2326 hermitian_operator(law, tol) 

2327 scale = max(1., np.max(np.abs(h0)), np.max(np.abs(v))) 

2328 if max(np.max(np.abs(law @ h0 - h0 @ law)), np.max(np.abs(law @ v - v @ law))) > tol * scale: 

2329 raise ValueError('\n\nThe conservation law must commute with the lead\'s h0 and v.\n') 

2330 

2331 

2332def lead_block(lead, n_blocks): 

2333 ''' 

2334 Check a lead of a scattering matrix: a lead index, or a tuple 

2335 (lead, block) with a block of that lead's conservation law. 

2336 

2337 Raises 

2338 ------ 

2339 TypeError 

2340 Not an integer or a tuple of two integers. 

2341 ValueError 

2342 No such lead or block. 

2343 ''' 

2344 if isinstance(lead, tuple): 

2345 if len(lead) != 2 or not all(isinstance(x, (int, np.integer)) for x in lead): 

2346 raise TypeError('\n\nA lead block must be a tuple (lead, block) of two integers.\n') 

2347 lead_index(int(lead[0]), len(n_blocks)) 

2348 if not 0 <= lead[1] < n_blocks[lead[0]]: 

2349 raise ValueError('\n\nLead {} has {} block(s) (its conservation law).\n'.format( 

2350 lead[0], n_blocks[lead[0]])) 

2351 else: 

2352 lead_index(lead, len(n_blocks)) 

2353 

2354 

2355 

2356#################################### 

2357# KERNEL POLYNOMIAL METHOD 

2358#################################### 

2359 

2360 

2361def kpm_kernel(kernel): 

2362 ''' 

2363 Check the KPM kernel name. 

2364 

2365 Raises 

2366 ------ 

2367 ValueError 

2368 Parameter kernel must be "jackson" or "lorentz". 

2369 ''' 

2370 if kernel not in ('jackson', 'lorentz'): 

2371 raise ValueError('\n\nParameter kernel must be "jackson" or "lorentz".\n') 

2372 

2373 

2374def kpm_grid(eps, var_name='e_grid'): 

2375 ''' 

2376 Check that the KPM energies lie inside the (scaled) spectral bounds. 

2377 

2378 Raises 

2379 ------ 

2380 ValueError 

2381 e_grid must lie inside the spectral bounds. 

2382 ''' 

2383 if np.any(np.abs(eps) >= 1.): 

2384 raise ValueError('\n\nParameter {} must lie strictly inside the spectral ' 

2385 'bounds.\n'.format(var_name)) 

2386 

2387 

2388def kpm_times(times): 

2389 ''' 

2390 Check the times of *kpm.time_evolution*: a non-empty, finite and 

2391 non-decreasing array. 

2392 

2393 Raises 

2394 ------ 

2395 ValueError 

2396 Parameter times must be a non-empty, finite, non-decreasing array. 

2397 ''' 

2398 if times.size == 0 or times.ndim != 1 or not np.all(np.isfinite(times)) \ 

2399 or np.any(np.diff(times) < 0): 

2400 raise ValueError('\n\nParameter times must be a non-empty, finite, non-decreasing ' 

2401 '1D array.\n') 

2402 

2403 

2404def positive_frequencies(omega): 

2405 ''' 

2406 Check that photon energies are positive. 

2407 

2408 Raises 

2409 ------ 

2410 ValueError 

2411 Parameter omega must be positive. 

2412 ''' 

2413 if np.any(omega <= 0): 

2414 raise ValueError('\n\nParameter omega must be positive.\n') 

2415 

2416 

2417def site_index(site, n): 

2418 ''' 

2419 Check a site (row) index. 

2420 

2421 Raises 

2422 ------ 

2423 TypeError 

2424 Parameter site must be an integer. 

2425 ValueError 

2426 Parameter site must be between 0 and n-1. 

2427 ''' 

2428 if not isinstance(site, (int, np.integer)): 

2429 raise TypeError('\n\nParameter site must be an integer.\n') 

2430 if not 0 <= site < n: 

2431 raise ValueError('\n\nParameter site must be between 0 and {}.\n'.format(n - 1)) 

2432 

2433 

2434def max_order(list_hop): 

2435 ''' 

2436 Largest neighbour order 'n' requested by a (possibly malformed) list of 

2437 hoppings; 1 if there is none (the list is validated afterwards). 

2438 ''' 

2439 try: 

2440 orders = [dic['n'] for dic in list_hop if isinstance(dic['n'], int)] 

2441 except (TypeError, KeyError): 

2442 return 1 

2443 return max([n for n in orders if n > 0] + [1]) 

2444 

2445 

2446#################################### 

2447# ORBITALS, SLATER-KOSTER, SPIN 

2448#################################### 

2449 

2450 

2451def orbitals(orbs): 

2452 ''' 

2453 Check a list of orbital names. 

2454 

2455 Raises 

2456 ------ 

2457 TypeError 

2458 The orbitals must be a list of names. 

2459 ValueError 

2460 Unknown or repeated orbital. 

2461 ''' 

2462 from tbkit.slater_koster import ORBITALS 

2463 if not isinstance(orbs, list) or not orbs: 

2464 raise TypeError('\n\nThe orbitals must be a non-empty list of names.\n') 

2465 for o in orbs: 

2466 if o not in ORBITALS: 

2467 raise ValueError('\n\nUnknown orbital {!r}: use one of {}.\n'.format(o, list(ORBITALS))) 

2468 if len(set(orbs)) != len(orbs): 

2469 raise ValueError('\n\nRepeated orbital in {}.\n'.format(orbs)) 

2470 

2471 

2472def orbital_dict(orbital_dict, tags): 

2473 ''' 

2474 Check the orbitals of *OrbitalSystem*: a list of orbitals for every tag. 

2475 

2476 Raises 

2477 ------ 

2478 TypeError 

2479 Parameter orbitals must be a dictionary. 

2480 ValueError 

2481 Every tag needs its orbitals. 

2482 ''' 

2483 if not isinstance(orbital_dict, dict): 

2484 raise TypeError('\n\nParameter orbitals must be a dictionary {tag: list of orbitals}.\n') 

2485 for tag in tags: 

2486 if tag not in orbital_dict: 

2487 raise ValueError('\n\nParameter orbitals has no entry for tag {!r}.\n'.format(tag)) 

2488 for orbs in orbital_dict.values(): 

2489 orbitals(orbs) 

2490 

2491 

2492def sk_params(params): 

2493 ''' 

2494 Check a dictionary of Slater-Koster bond integrals. 

2495 

2496 Raises 

2497 ------ 

2498 TypeError 

2499 Parameter params must be a dictionary of numbers. 

2500 ValueError 

2501 Unknown bond integral. 

2502 ''' 

2503 from tbkit.slater_koster import PARAMS 

2504 if not isinstance(params, dict): 

2505 raise TypeError('\n\nThe bond integrals must be a dictionary.\n') 

2506 for key, val in params.items(): 

2507 if key not in PARAMS: 

2508 raise ValueError('\n\nUnknown bond integral {!r}: use {}.\n'.format(key, PARAMS)) 

2509 if not isinstance(val, (int, float)): 

2510 raise TypeError('\n\nBond integral {!r} must be a real number.\n'.format(key)) 

2511 

2512 

2513def sk_pair_params(params, tags_i, tags_j): 

2514 ''' 

2515 Check the bond integrals of *set_slater_koster*: one dictionary, or one 

2516 per tag pair of the bonds (keys ``'ab'`` or ``('Mo', 'S')``). 

2517 

2518 Returns 

2519 ------- 

2520 bool 

2521 True if keyed by tag pair. 

2522 

2523 Raises 

2524 ------ 

2525 ValueError 

2526 A tag pair of the bonds has no bond integrals. 

2527 ''' 

2528 from tbkit.slater_koster import PARAMS 

2529 if not isinstance(params, dict): 

2530 raise TypeError('\n\nThe bond integrals must be a dictionary.\n') 

2531 by_pair = bool(params) and all(k not in PARAMS for k in params) 

2532 if not by_pair: 

2533 sk_params(params) 

2534 return False 

2535 for a, b in set(zip(tags_i, tags_j)): 

2536 if (a, b) not in params and a + b not in params: 

2537 raise ValueError('\n\nNo bond integrals for the tag pair {!r}.\n'.format(a + b)) 

2538 sk_params(params[(a, b) if (a, b) in params else a + b]) 

2539 return True 

2540 

2541 

2542def bond_vector(d): 

2543 ''' 

2544 Check a bond vector: 2 or 3 reals, nonzero. 

2545 

2546 Raises 

2547 ------ 

2548 ValueError 

2549 The bond vector must have 2 or 3 components and be nonzero. 

2550 ''' 

2551 if d.ndim != 1 or len(d) not in (2, 3) or not np.any(d): 

2552 raise ValueError('\n\nThe bond vector must have 2 or 3 components, not all zero.\n') 

2553 

2554 

2555def orbital_of_site(orbital, orbs): 

2556 ''' 

2557 Check that a site carries an orbital. 

2558 

2559 Raises 

2560 ------ 

2561 ValueError 

2562 The site has no such orbital. 

2563 ''' 

2564 if orbital not in orbs: 

2565 raise ValueError('\n\nThe site has no orbital {!r} (it has {}).\n'.format(orbital, orbs)) 

2566 

2567 

2568def spin_index(spin, ns): 

2569 ''' 

2570 Check a spin index: 0, or 0/1 with spin. 

2571 

2572 Raises 

2573 ------ 

2574 ValueError 

2575 Parameter spin must be 0 (or 1 with spin). 

2576 ''' 

2577 if spin not in range(ns): 

2578 raise ValueError('\n\nParameter spin must be {}.\n'.format('0 or 1' if ns == 2 else '0')) 

2579 

2580 

2581def set_onsite_orb(dict_onsite, tags, orbital_dict): 

2582 ''' 

2583 Check *OrbitalSystem.set_onsite*: numbers, or {orbital: number} dictionaries. 

2584 

2585 Raises 

2586 ------ 

2587 TypeError 

2588 Onsite energies must be numbers or dictionaries. 

2589 ValueError 

2590 Unknown tag or orbital. 

2591 ''' 

2592 if not isinstance(dict_onsite, dict): 

2593 raise TypeError('\n\nParameter onsite must be a dictionary.\n') 

2594 for tag, val in dict_onsite.items(): 

2595 if tag not in tags: 

2596 raise ValueError('\n\nParameter onsite keys must be a tag.\n') 

2597 if isinstance(val, dict): 

2598 for o, e in val.items(): 

2599 orbital_of_site(o, orbital_dict[tag]) 

2600 if not isinstance(e, (int, float, complex)): 

2601 raise TypeError('\n\nOnsite energies must be numbers.\n') 

2602 elif not isinstance(val, (int, float, complex)): 

2603 raise TypeError('\n\nOnsite energies must be numbers or {orbital: number} dictionaries.\n') 

2604 

2605 

2606def spinful(spin): 

2607 ''' 

2608 Check that the model has spin. 

2609 

2610 Raises 

2611 ------ 

2612 ValueError 

2613 This term needs spin=True. 

2614 ''' 

2615 if not spin: 

2616 raise ValueError('\n\nThis term needs a spinful model (spin=True).\n') 

2617 

2618 

2619def vector3(vec, var_name): 

2620 ''' 

2621 Check a tuple of three real numbers. 

2622 

2623 Raises 

2624 ------ 

2625 ValueError 

2626 Parameter must be a tuple of three real numbers. 

2627 ''' 

2628 if not isinstance(vec, (tuple, list)) or len(vec) != 3 or \ 

2629 not all(isinstance(c, (int, float)) for c in vec): 

2630 raise ValueError('\n\nParameter {} must be a tuple of three real numbers.\n'.format(var_name)) 

2631 

2632 

2633def p_shell(tags, orbital_dict): 

2634 ''' 

2635 Check that the tags carry the three p orbitals. 

2636 

2637 Raises 

2638 ------ 

2639 ValueError 

2640 The tags must carry px, py and pz. 

2641 ''' 

2642 if not isinstance(tags, list) or not tags: 

2643 raise ValueError('\n\nParameter tags must be a non-empty list of tags with p orbitals.\n') 

2644 for tag in tags: 

2645 if tag not in orbital_dict or not {'px', 'py', 'pz'} <= set(orbital_dict[tag]): 

2646 raise ValueError('\n\nTag {!r} must carry the orbitals px, py and pz.\n'.format(tag)) 

2647 

2648 

2649def block_shape(mat, shape): 

2650 ''' 

2651 Check the shape of a hopping block. 

2652 

2653 Raises 

2654 ------ 

2655 ValueError 

2656 The block must have the given shape. 

2657 ''' 

2658 if mat.shape != shape: 

2659 raise ValueError('\n\nThe hopping block must have shape {}.\n'.format(shape)) 

2660 

2661 

2662def orbital_terms(hop, blocks): 

2663 ''' 

2664 Check that an *OrbitalSystem* has hoppings. 

2665 

2666 Raises 

2667 ------ 

2668 RuntimeError 

2669 Run set_hopping or set_slater_koster first. 

2670 ''' 

2671 if not hop.size and not any(blocks.values()): 

2672 raise RuntimeError('\n\nRun method set_hopping or set_slater_koster first.\n') 

2673 

2674 

2675def no_left(left): 

2676 ''' 

2677 Check that left eigenvectors are not asked for with an overlap matrix. 

2678 

2679 Raises 

2680 ------ 

2681 ValueError 

2682 left=True needs an orthogonal basis. 

2683 ''' 

2684 if left: 

2685 raise ValueError('\n\nleft=True needs an orthogonal basis (no overlap).\n') 

2686 

2687 

2688def orthogonal(overlap): 

2689 ''' 

2690 Check that the basis is orthogonal. 

2691 

2692 Raises 

2693 ------ 

2694 ValueError 

2695 This calculation needs an orthogonal basis. 

2696 ''' 

2697 if overlap is not None: 

2698 raise ValueError('\n\nThis calculation needs an orthogonal basis (no overlap matrix).\n') 

2699 

2700 

2701#################################### 

2702# MEAN FIELD, SUPERCONDUCTIVITY 

2703#################################### 

2704 

2705 

2706def hermitian_dense(ham): 

2707 ''' 

2708 Check that a dense matrix is Hermitian. 

2709 

2710 Raises 

2711 ------ 

2712 ValueError 

2713 This calculation requires a Hermitian Hamiltonian. 

2714 ''' 

2715 if not np.allclose(ham, ham.conj().T, atol=1e-12): 

2716 raise ValueError('\n\nThis calculation requires a Hermitian Hamiltonian.\n') 

2717 

2718 

2719def integer_electrons(n_electrons): 

2720 ''' 

2721 Check that the number of electrons is an integer (zero temperature). 

2722 

2723 Raises 

2724 ------ 

2725 ValueError 

2726 At zero temperature, n_electrons must be an integer. 

2727 ''' 

2728 if abs(n_electrons - round(n_electrons)) > 1e-12: 

2729 raise ValueError('\n\nAt zero temperature, n_electrons must be an integer ' 

2730 '(use a small temperature for a fractional filling).\n') 

2731 

2732 

2733def mixing(mixing): 

2734 ''' 

2735 Check the density mixing: a real in (0, 1]. 

2736 

2737 Raises 

2738 ------ 

2739 ValueError 

2740 Parameter mixing must be in (0, 1]. 

2741 ''' 

2742 positive_real(mixing, 'mixing') 

2743 if mixing > 1: 

2744 raise ValueError('\n\nParameter mixing must be in (0, 1].\n') 

2745 

2746 

2747def pairing(delta, n): 

2748 ''' 

2749 Check a BdG pairing matrix: (n, n), antisymmetric. 

2750 

2751 Raises 

2752 ------ 

2753 ValueError 

2754 The pairing matrix must be (n, n) and antisymmetric. 

2755 ''' 

2756 if delta.shape != (n, n): 

2757 raise ValueError('\n\nThe pairing matrix must have the shape ({0}, {0}) of ham.\n'.format(n)) 

2758 if (abs(delta + delta.T) > 1e-12).nnz: 

2759 raise ValueError('\n\nThe pairing matrix must be antisymmetric (Delta^T = -Delta).\n') 

2760 

2761 

2762def hermitian_kspace(hermitian, overlap): 

2763 ''' 

2764 Check that a KSpace model is Hermitian, with an orthogonal basis. 

2765 

2766 Raises 

2767 ------ 

2768 ValueError 

2769 The model must be Hermitian, without overlap. 

2770 ''' 

2771 if not hermitian or overlap: 

2772 raise ValueError('\n\nThe model must be Hermitian, with an orthogonal basis.\n') 

2773 

2774 

2775def pairing_kspace(pairing, norb, ndim): 

2776 ''' 

2777 Check the pairings of *bdg.bdg_kspace*. 

2778 

2779 Raises 

2780 ------ 

2781 TypeError 

2782 Parameter pairing must be a list of dictionaries. 

2783 KeyError 

2784 "i", "j", "R" and "delta" must be keys. 

2785 ValueError 

2786 Orbital indices below norb; R a tuple of ndim integers. 

2787 ''' 

2788 if not isinstance(pairing, list): 

2789 raise TypeError('\n\nParameter pairing must be a list of dictionaries.\n') 

2790 for dic in pairing: 

2791 if not isinstance(dic, dict): 

2792 raise TypeError('\n\nParameter pairing must be a list of dictionaries.\n') 

2793 if not {'i', 'j', 'R', 'delta'} <= set(dic): 

2794 raise KeyError('\n\n"i", "j", "R" and "delta" must be dictionary keys.\n') 

2795 if not all(isinstance(dic[k], int) and 0 <= dic[k] < norb for k in ('i', 'j')): 

2796 raise ValueError('\n\n"i" and "j" must be orbital indices between 0 and {}.\n'.format(norb - 1)) 

2797 if not isinstance(dic['R'], tuple) or len(dic['R']) != ndim or \ 

2798 not all(isinstance(n, int) for n in dic['R']): 

2799 raise ValueError('\n\n"R" must be a tuple of {} integers.\n'.format(ndim)) 

2800 number(dic['delta'], '"delta"') 

2801 

2802 

2803#################################### 

2804# FLOQUET 

2805#################################### 

2806 

2807 

2808def positive_int_zero(var, var_name): 

2809 ''' 

2810 Check if *var* is a positive integer or zero. 

2811 

2812 Raises 

2813 ------ 

2814 TypeError 

2815 Parameter *var* must be an integer. 

2816 ValueError 

2817 Parameter *var* must be a positive integer or zero. 

2818 ''' 

2819 if not isinstance(var, int): 

2820 raise TypeError('\n\nParameter {} must be an integer.\n'.format(var_name)) 

2821 if var < 0: 

2822 raise ValueError('\n\nParameter {} must be a positive integer or zero.\n'.format(var_name)) 

2823 

2824 

2825def harmonics(harm): 

2826 ''' 

2827 Check the harmonics of *floquet.sambe_hamiltonian*: a dictionary with (at least) m = 0. 

2828 

2829 Raises 

2830 ------ 

2831 TypeError 

2832 The harmonics must be a dictionary {m: matrix}. 

2833 ValueError 

2834 The harmonics must contain m = 0 and square matrices of one shape. 

2835 ''' 

2836 if not isinstance(harm, dict): 

2837 raise TypeError('\n\nThe harmonics must be a dictionary {m: matrix}.\n') 

2838 if 0 not in harm: 

2839 raise ValueError('\n\nThe harmonics must contain the static part, m = 0.\n') 

2840 shapes = {np.shape(h) for h in harm.values()} 

2841 if len(shapes) != 1 or len(shapes.pop()) != 2: 

2842 raise ValueError('\n\nThe harmonics must be square matrices of one shape.\n') 

2843 

2844 

2845def kspace(ks, cls): 

2846 ''' 

2847 Check that *ks* is a KSpace instance. 

2848 

2849 Raises 

2850 ------ 

2851 TypeError 

2852 Parameter ks must be a KSpace instance. 

2853 ''' 

2854 if not isinstance(ks, cls): 

2855 raise TypeError('\n\nParameter ks must be a KSpace instance.\n') 

2856 

2857 

2858def not_floquet(): 

2859 ''' 

2860 

2861 Raises 

2862 ------ 

2863 ValueError 

2864 Not available for a Floquet (driven) model. 

2865 ''' 

2866 raise ValueError('\n\nThis method needs the static hoppings: it is not available ' 

2867 'for a Floquet (driven) model.\n') 

2868 

2869 

2870def sk_bonds(bonds): 

2871 ''' 

2872 Check the bonds of *slater_koster.sk_kspace*: {n: bond integrals}. 

2873 

2874 Raises 

2875 ------ 

2876 TypeError 

2877 Parameter bonds must be a dictionary {n: bond integrals}. 

2878 ''' 

2879 if not isinstance(bonds, dict) or not all(isinstance(n, int) and n > 0 for n in bonds): 

2880 raise TypeError('\n\nParameter bonds must be a dictionary {n: bond integrals}, ' 

2881 'n a positive integer.\n') 

2882 for params in bonds.values(): 

2883 sk_params(params) 

2884 

2885 

2886#################################### 

2887# HALL CONDUCTIVITIES 

2888#################################### 

2889 

2890 

2891def fermi_energies(e_fermi): 

2892 ''' 

2893 Check the Fermi energies of the Hall conductivities: a real number, or a 

2894 non-empty array of finite real numbers. 

2895 

2896 Raises 

2897 ------ 

2898 TypeError 

2899 Parameter e_fermi must be a real number or an array of real numbers. 

2900 ValueError 

2901 Parameter e_fermi must be non-empty and finite. 

2902 ''' 

2903 arr = np.asarray(e_fermi) 

2904 if arr.dtype.kind not in 'iuf': 

2905 raise TypeError('\n\nParameter e_fermi must be a real number or an array ' 

2906 'of real numbers.\n') 

2907 if arr.size == 0 or not np.all(np.isfinite(arr)): 

2908 raise ValueError('\n\nParameter e_fermi must contain at least one finite number.\n') 

2909 

2910 

2911def hermitian_model(hermitian): 

2912 ''' 

2913 Check that a KSpace model is Hermitian (a Kubo conductivity needs real 

2914 bands and orthonormal eigenstates). 

2915 

2916 Raises 

2917 ------ 

2918 ValueError 

2919 This calculation requires a Hermitian model. 

2920 ''' 

2921 if not hermitian: 

2922 raise ValueError('\n\nThis calculation requires a Hermitian model (no gain/loss, ' 

2923 'no hermitian=False hopping).\n') 

2924 

2925 

2926def k_fixed_hall(k_fixed, dim, full_allowed=True): 

2927 ''' 

2928 Check parameter *k_fixed* of the Hall conductivities: None (the whole 

2929 Brillouin zone) or a real number (a plane of a 3D model). 

2930 

2931 Raises 

2932 ------ 

2933 TypeError 

2934 Parameter k_fixed must be None or a real number. 

2935 ValueError 

2936 A 3D spin Hall conductivity needs a plane (k_fixed). 

2937 ''' 

2938 if k_fixed is not None: 

2939 real_number(k_fixed, 'k_fixed') 

2940 elif dim == 3 and not full_allowed: 

2941 raise ValueError('\n\nIn 3D, give the plane of the spin Hall conductivity: ' 

2942 'k_fixed must be a real number.\n') 

2943 

2944 

2945def spin_axis(axis): 

2946 ''' 

2947 Check the spin quantization axis: 'x', 'y' or 'z'. 

2948 

2949 Raises 

2950 ------ 

2951 ValueError 

2952 Parameter spin_axis must be "x", "y" or "z". 

2953 ''' 

2954 if axis not in ('x', 'y', 'z'): 

2955 raise ValueError('\n\nParameter spin_axis must be "x", "y" or "z".\n') 

2956 

2957 

2958def refine_fraction(fraction): 

2959 ''' 

2960 Check the fraction of mesh points refined by the adaptive mesh: a real in (0, 1]. 

2961 

2962 Raises 

2963 ------ 

2964 TypeError 

2965 Parameter refine_fraction must be a real number. 

2966 ValueError 

2967 Parameter refine_fraction must be in (0, 1]. 

2968 ''' 

2969 positive_real(fraction, 'refine_fraction') 

2970 if fraction > 1: 

2971 raise ValueError('\n\nParameter refine_fraction must be in (0, 1].\n') 

2972 

2973 

2974def path_parameter(param): 

2975 ''' 

2976 Check the parameter that a path varies (*KSpace.axion_angle*): a string. 

2977 

2978 Raises 

2979 ------ 

2980 TypeError 

2981 Parameter param must be a string (the name of a value-function parameter). 

2982 ''' 

2983 if not isinstance(param, str): 

2984 raise TypeError('\n\nParameter param must be a string (the name of a ' 

2985 'value-function parameter).\n') 

2986 

2987 

2988def path_values(values): 

2989 ''' 

2990 Check the parameter values of a path: a 1D array of at least two finite 

2991 real numbers, strictly increasing or strictly decreasing. 

2992 

2993 Raises 

2994 ------ 

2995 TypeError 

2996 Parameter values must be a 1D array of real numbers. 

2997 ValueError 

2998 Parameter values must hold at least two finite, strictly monotonic values. 

2999 ''' 

3000 arr = np.asarray(values) 

3001 if arr.ndim != 1 or arr.dtype.kind not in 'iuf': 

3002 raise TypeError('\n\nParameter values must be a 1D array of real numbers.\n') 

3003 step = np.diff(arr) 

3004 if len(arr) < 2 or not np.all(np.isfinite(arr)) or not (np.all(step > 0) or np.all(step < 0)): 

3005 raise ValueError('\n\nParameter values must hold at least two finite values, ' 

3006 'strictly increasing or strictly decreasing.\n') 

3007 

3008 

3009def path_gap(gap, param, value, tol=1e-6): 

3010 ''' 

3011 Check that the bands stay separated from the others along a path. 

3012 

3013 Raises 

3014 ------ 

3015 ValueError 

3016 The bands touch the others at param = value. 

3017 ''' 

3018 if gap < tol: 

3019 raise ValueError('\n\nThe bands touch the other bands at {} = {} (gap {:.1e}): ' 

3020 'the path must stay gapped.\n'.format(param, value, gap)) 

3021 

3022 

3023def velocity(vel, n, var_name): 

3024 ''' 

3025 Check a velocity operator: a square (sparse or dense) matrix of the 

3026 Hamiltonian's shape. 

3027 

3028 Raises 

3029 ------ 

3030 ValueError 

3031 The velocity must be a (n, n) matrix. 

3032 ''' 

3033 if getattr(vel, 'shape', None) != (n, n): 

3034 raise ValueError('\n\nParameter {} must be a ({}, {}) matrix, like ham.\n'.format(var_name, n, n)) 

3035 

3036 

3037def positive_overlap(s_min): 

3038 ''' 

3039 Check that the overlap matrix S(k) is positive definite. 

3040 

3041 Raises 

3042 ------ 

3043 ValueError 

3044 The overlap matrix must be positive definite. 

3045 ''' 

3046 if s_min <= 0: 

3047 raise ValueError('\n\nThe overlap matrix S(k) must be positive definite ' 

3048 '(smallest eigenvalue {:.3g}).\n'.format(s_min)) 

3049 

3050 

3051#################################### 

3052# FLOQUET: STEP DRIVES, WINDING NUMBER 

3053#################################### 

3054 

3055 

3056def branch_cut(epsilon): 

3057 ''' 

3058 Check the branch cut of a Floquet Hamiltonian: None or a real number. 

3059 

3060 Raises 

3061 ------ 

3062 TypeError 

3063 Parameter epsilon must be None or a real number. 

3064 ''' 

3065 if epsilon is not None and (isinstance(epsilon, bool) 

3066 or not isinstance(epsilon, (int, float, np.integer, np.floating))): 

3067 raise TypeError('\n\nParameter epsilon must be None or a real number.\n') 

3068 

3069 

3070def durations(durations, n): 

3071 ''' 

3072 Check the step durations of a step drive: n positive reals. 

3073 

3074 Raises 

3075 ------ 

3076 TypeError 

3077 Parameter durations must be a list of real numbers. 

3078 ValueError 

3079 Parameter durations must hold one positive number per step. 

3080 ''' 

3081 if not isinstance(durations, (list, tuple, np.ndarray)): 

3082 raise TypeError('\n\nParameter durations must be a list of real numbers.\n') 

3083 if len(durations) != n: 

3084 raise ValueError('\n\nParameter durations must hold one duration per step ({}).\n'.format(n)) 

3085 for d in durations: 

3086 if isinstance(d, bool) or not isinstance(d, (int, float, np.integer, np.floating)): 

3087 raise TypeError('\n\nParameter durations must be a list of real numbers.\n') 

3088 if d <= 0: 

3089 raise ValueError('\n\nParameter durations must be positive numbers.\n') 

3090 

3091 

3092def step_models(models, kspace_cls, system_cls): 

3093 ''' 

3094 Check the models of a step drive: a non-empty list, either of KSpace 

3095 instances (Hermitian, orthogonal basis, one lattice size) or of System 

3096 instances and square matrices. Returns 'kspace' or 'matrix'. 

3097 

3098 Raises 

3099 ------ 

3100 TypeError 

3101 Parameter models must be a non-empty list of KSpace, System or matrices. 

3102 ValueError 

3103 The KSpace models must be Hermitian, with no overlap, of one size. 

3104 ''' 

3105 if not isinstance(models, (list, tuple)) or len(models) == 0: 

3106 raise TypeError('\n\nParameter models must be a non-empty list of KSpace instances, ' 

3107 'or of System instances and matrices.\n') 

3108 if all(isinstance(m, kspace_cls) for m in models): 

3109 for m in models: 

3110 if (m.norb, m.dim) != (models[0].norb, models[0].dim): 

3111 raise ValueError('\n\nThe KSpace models must have the same orbitals and dimension.\n') 

3112 if not m.is_hermitian(): 

3113 raise ValueError('\n\nThe KSpace models must be Hermitian.\n') 

3114 if m._overlap_hop: 

3115 raise ValueError('\n\nThe KSpace models need an orthogonal basis (no overlap).\n') 

3116 return 'kspace' 

3117 for m in models: 

3118 if not isinstance(m, system_cls) and getattr(m, 'ndim', None) != 2: 

3119 raise TypeError('\n\nParameter models must be a list of KSpace instances only, ' 

3120 'or of System instances and square matrices.\n') 

3121 return 'matrix' 

3122 

3123 

3124def step_matrices(hams): 

3125 ''' 

3126 Check the Hamiltonians of a real-space step drive: Hermitian square 

3127 matrices of one shape. 

3128 

3129 Raises 

3130 ------ 

3131 TypeError 

3132 Parameter hams must be a non-empty list of matrices. 

3133 ValueError 

3134 The matrices must be square, Hermitian and of one shape. 

3135 ''' 

3136 if not isinstance(hams, (list, tuple)) or len(hams) == 0: 

3137 raise TypeError('\n\nParameter hams must be a non-empty list of matrices.\n') 

3138 shape = np.shape(hams[0]) 

3139 for h in hams: 

3140 h = np.asarray(h) 

3141 if h.ndim != 2 or h.shape[0] != h.shape[1] or h.shape != shape: 

3142 raise ValueError('\n\nThe step Hamiltonians must be square matrices of one shape.\n') 

3143 hermitian_dense(h) 

3144 

3145 

3146def drive_matrix(ham, norb): 

3147 ''' 

3148 Check the output of a Bloch drive ham_kt(k, t): a Hermitian (norb, norb) matrix. 

3149 

3150 Raises 

3151 ------ 

3152 ValueError 

3153 ham_kt(k, t) must return a Hermitian (norb, norb) matrix. 

3154 ''' 

3155 if np.shape(ham) != (norb, norb): 

3156 raise ValueError('\n\nham_kt(k, t) must return a ({}, {}) matrix.\n'.format(norb, norb)) 

3157 hermitian_dense(np.asarray(ham)) 

3158 

3159 

3160def time_in_period(t, period): 

3161 ''' 

3162 Check a time within the period: None or a real in [0, period]. 

3163 

3164 Raises 

3165 ------ 

3166 TypeError 

3167 Parameter t must be None or a real number. 

3168 ValueError 

3169 Parameter t must be in [0, period]. 

3170 ''' 

3171 if t is None: 

3172 return 

3173 real_number(t, 't') 

3174 if not 0 <= t <= period: 

3175 raise ValueError('\n\nParameter t must be in [0, {}].\n'.format(period)) 

3176 

3177 

3178def nk_min(nk, n_min): 

3179 ''' 

3180 Check that every k-mesh size is at least n_min. 

3181 

3182 Raises 

3183 ------ 

3184 ValueError 

3185 Parameter nk must be at least n_min. 

3186 ''' 

3187 if min(nk) < n_min: 

3188 raise ValueError('\n\nParameter nk must be at least {}.\n'.format(n_min)) 

3189 

3190 

3191#################################### 

3192# MODEL BUILDING, BRIDGES AND I/O 

3193# (neighbour-order hoppings in k-space, System <-> KSpace, tbkit.io) 

3194#################################### 

3195 

3196 

3197def hopping_form(list_hop): 

3198 ''' 

3199 Tell the two forms of *KSpace.set_hopping* apart: the explicit one 

3200 (keys 'i', 'j', 'R', 't') and the neighbour-order one of 

3201 *System.set_hopping* (keys 'n', 't', and optionally 'ang', 'tag'). 

3202 

3203 Returns 

3204 ------- 

3205 neighbour : Boolean 

3206 True for the neighbour-order form. 

3207 

3208 Raises 

3209 ------ 

3210 TypeError 

3211 Parameter list_hop must be a list of dictionaries. 

3212 ValueError 

3213 list_hop mixes the two forms. 

3214 ''' 

3215 if not isinstance(list_hop, list): 

3216 raise TypeError('\n\nParameter list_hop must be a list.\n') 

3217 if not all(isinstance(dic, dict) for dic in list_hop): 

3218 raise TypeError('\n\nParameter list_hop must be a list of dictionaries.\n') 

3219 by_order = ['n' in dic for dic in list_hop] 

3220 if any(by_order) and not all(by_order): 

3221 raise ValueError('\n\nParameter list_hop mixes explicit hoppings (keys "i", "j", "R", "t") ' 

3222 'and neighbour-order ones (keys "n", "t", "ang", "tag"): ' 

3223 'make one call per form.\n') 

3224 return bool(list_hop) and all(by_order) 

3225 

3226 

3227def set_hopping_neighbours(list_hop, spin=False): 

3228 ''' 

3229 Check the neighbour-order form of *KSpace.set_hopping*. 

3230 

3231 Raises 

3232 ------ 

3233 KeyError 

3234 "n" and "t" must be keys, and only "ang" and "tag" may be added. 

3235 TypeError 

3236 "n" must be an integer, "t" a number (or, if *spin*, 

3237 a 2x2 matrix) or a value function, "ang" a real number and "tag" a string. 

3238 ValueError 

3239 "n" must be positive, "ang" in [-180, 180), "tag" of length 2 or a pair of tags. 

3240 ''' 

3241 hopping_form(list_hop) 

3242 for dic in list_hop: 

3243 if 'n' not in dic or 't' not in dic: 

3244 raise KeyError('\n\n"n" and "t" must be dictionary keys.\n') 

3245 if not set(dic) <= {'n', 't', 'ang', 'tag'}: 

3246 raise KeyError('\n\nOnly the keys "n", "t", "ang" and "tag" are allowed.\n') 

3247 if isinstance(dic['n'], bool) or not isinstance(dic['n'], int): 

3248 raise TypeError('\n\n"n" value must be an integer.\n') 

3249 if dic['n'] < 1: 

3250 raise ValueError('\n\n"n" value must be a positive integer.\n') 

3251 if callable(dic['t']): 

3252 pass 

3253 elif spin: 

3254 spin_matrix(dic['t'], '"t"') 

3255 elif not isinstance(dic['t'], (int, float, complex)): 

3256 raise TypeError('\n\n"t" value must be a real or complex number.\n') 

3257 if 'ang' in dic: 

3258 if not isinstance(dic['ang'], (int, float)): 

3259 raise TypeError('\n\n"ang" value must be a real number.\n') 

3260 if not -180. <= dic['ang'] < 180.: 

3261 raise ValueError('\n\n"ang" value must be in [-180, 180).\n') 

3262 if 'tag' in dic: 

3263 hop_tag(dic['tag']) 

3264 

3265 

3266def shell_angle(ang, angles): 

3267 ''' 

3268 Check that a neighbour shell has bonds along the angle *ang* (in 

3269 degrees, either orientation: *angles* are those in [0, 180)). 

3270 

3271 Raises 

3272 ------ 

3273 ValueError 

3274 No bond of the shell points along *ang*. 

3275 ''' 

3276 if not np.any(np.isclose(ang, angles, atol=ATOL)) and \ 

3277 not np.any(np.isclose(ang, angles - 180., atol=ATOL)): 

3278 raise ValueError('\n\nNo bond of this neighbour shell has angle {} (angles: {}).\n' 

3279 .format(ang, np.unique(angles.round(4)))) 

3280 

3281 

3282def not_orbital_system(sys, orbital_cls): 

3283 ''' 

3284 Check that a System is not an *OrbitalSystem* (several rows per site). 

3285 

3286 Raises 

3287 ------ 

3288 TypeError 

3289 An OrbitalSystem is not supported. 

3290 ''' 

3291 if isinstance(sys, orbital_cls): 

3292 raise TypeError('\n\nAn OrbitalSystem (several orbitals per site) is not supported: ' 

3293 'build its KSpace with tbkit.slater_koster.sk_kspace.\n') 

3294 

3295 

3296def lattice_sites(matches): 

3297 ''' 

3298 Check that every site of a finite lattice is a copy of exactly one 

3299 orbital of *unit_cell*, translated by a lattice vector (*matches*: the 

3300 number of such orbitals, per site). 

3301 

3302 Raises 

3303 ------ 

3304 ValueError 

3305 A site is not on the periodic lattice. 

3306 ''' 

3307 bad = np.flatnonzero(np.asarray(matches) != 1) 

3308 if len(bad): 

3309 raise ValueError('\n\nSite {} is not a translate of exactly one unit-cell site (same tag, ' 

3310 'position r0 + n1 a1 + ...): was the lattice rotated, strained ' 

3311 'or shifted?\n'.format(int(bad[0]))) 

3312 

3313 

3314def translation_invariant(dev, tol): 

3315 ''' 

3316 Check that equivalent matrix elements (same orbitals, same lattice 

3317 vector) are equal in every cell, within *tol*. 

3318 

3319 Raises 

3320 ------ 

3321 ValueError 

3322 The model is not translation invariant. 

3323 ''' 

3324 if dev > tol: 

3325 raise ValueError('\n\nThe Hamiltonian is not translation invariant: equivalent hoppings ' 

3326 'or onsite energies differ by {:.3g} (> tol = {:.3g}), e.g. after ' 

3327 'disorder, defects or a magnetic field.\n'.format(dev, tol)) 

3328 

3329 

3330def torus_range(R, sizes): 

3331 ''' 

3332 Check that the lattice vectors of a torus's bonds (shortest images, in 

3333 [-N/2, N/2)) are unambiguous: at least 3 cells along every direction, 

3334 and no bond reaching half-way around. 

3335 

3336 Raises 

3337 ------ 

3338 ValueError 

3339 The torus is too small for the range of the model. 

3340 ''' 

3341 if np.any(sizes < 3) or np.any(2 * R == -sizes[None, :]): 

3342 raise ValueError('\n\nThe torus ({} cells) is too small for the range of the model: ' 

3343 'a bond reaches half-way around it.\n'.format(tuple(int(n) for n in sizes))) 

3344 

3345 

3346def saveable_model(model, lattice_cls, system_cls, kspace_cls, orbital_cls): 

3347 ''' 

3348 Check that *tbkit.io.save_model* can store *model*. 

3349 

3350 Raises 

3351 ------ 

3352 TypeError 

3353 model must be a Lattice, System or KSpace instance 

3354 (not an OrbitalSystem). 

3355 ''' 

3356 if isinstance(model, orbital_cls) or not isinstance(model, (lattice_cls, system_cls, kspace_cls)): 

3357 raise TypeError('\n\nParameter model must be a Lattice, System or KSpace instance ' 

3358 '(an OrbitalSystem or a driven model cannot be saved).\n') 

3359 

3360 

3361def file_path(path, var_name): 

3362 ''' 

3363 Check a file name. 

3364 

3365 Raises 

3366 ------ 

3367 TypeError 

3368 Parameter var_name must be a string or a path. 

3369 ''' 

3370 if not (isinstance(path, str) or hasattr(path, "__fspath__")): 

3371 raise TypeError('\n\nParameter {} must be a string or a path.\n'.format(var_name)) 

3372 

3373 

3374def model_archive(data, fmt, version): 

3375 ''' 

3376 Check an archive read by *tbkit.io.load_model*. 

3377 

3378 Raises 

3379 ------ 

3380 ValueError 

3381 Not a tbkit model archive, or a newer version. 

3382 ''' 

3383 if 'format' not in data.files or str(data['format']) != fmt: 

3384 raise ValueError('\n\nThis file is not a tbkit model archive (format {}).\n'.format(fmt)) 

3385 if int(data['version']) > version: 

3386 raise ValueError('\n\nThis archive has version {}; this tbkit reads versions up to {}: ' 

3387 'upgrade tbkit.\n'.format(int(data['version']), version)) 

3388 

3389 

3390def hr_header(tokens, name='_hr.dat'): 

3391 ''' 

3392 Check the header of a Wannier90 ``_hr.dat`` (or *name*) file: num_wann, 

3393 nrpts and the nrpts degeneracy weights, as positive integers. 

3394 

3395 Raises 

3396 ------ 

3397 ValueError 

3398 Not a Wannier90 _hr.dat file. 

3399 ''' 

3400 try: 

3401 num_wann, nrpts = int(tokens[0]), int(tokens[1]) 

3402 weights = [int(w) for w in tokens[2:2 + nrpts]] 

3403 except (IndexError, ValueError): 

3404 raise ValueError('\n\nNot a Wannier90 {} file: expected num_wann, nrpts and ' 

3405 'the degeneracy weights after the header.\n'.format(name)) from None 

3406 if num_wann < 1 or nrpts < 1 or len(weights) != nrpts or min(weights) < 1: 

3407 raise ValueError('\n\nNot a Wannier90 {} file: num_wann, nrpts and the ' 

3408 'degeneracy weights must be positive integers.\n'.format(name)) 

3409 

3410 

3411def hr_body(n_tokens, nrpts, num_wann): 

3412 ''' 

3413 Check the number of entries of a Wannier90 ``_hr.dat`` file. 

3414 

3415 Raises 

3416 ------ 

3417 ValueError 

3418 The file must have nrpts * num_wann**2 lines of 7 numbers. 

3419 ''' 

3420 if n_tokens != 7 * nrpts * num_wann ** 2: 

3421 raise ValueError('\n\nThe _hr.dat file must have nrpts * num_wann**2 = {} lines ' 

3422 '"R1 R2 R3 m n Re Im" after the weights.\n'.format(nrpts * num_wann ** 2)) 

3423 

3424 

3425def hr_blocks(ok): 

3426 ''' 

3427 Check that the lines of a ``_hr.dat`` file come in blocks of num_wann**2 

3428 with the same lattice vector. 

3429 

3430 Raises 

3431 ------ 

3432 ValueError 

3433 Lines of a lattice vector must be consecutive. 

3434 ''' 

3435 if not ok: 

3436 raise ValueError('\n\nThe _hr.dat lines of each lattice vector R must be consecutive ' 

3437 '(num_wann**2 lines per R).\n') 

3438 

3439 

3440def win_block(found): 

3441 ''' 

3442 Check that a ``.win`` file has a ``unit_cell_cart`` block. 

3443 

3444 Raises 

3445 ------ 

3446 ValueError 

3447 No unit_cell_cart block. 

3448 ''' 

3449 if not found: 

3450 raise ValueError('\n\nThe .win file has no "begin unit_cell_cart ... end unit_cell_cart" block.\n') 

3451 

3452 

3453def win_cell(cell, what='The unit_cell_cart block'): 

3454 ''' 

3455 Check the ``unit_cell_cart`` block of a ``.win`` file (or the cell of 

3456 a ``_tb.dat`` file, *what*): three lines of three real numbers. 

3457 

3458 Raises 

3459 ------ 

3460 ValueError 

3461 unit_cell_cart must hold three vectors of three numbers. 

3462 ''' 

3463 try: 

3464 ok = len(cell) == 3 and all(len(v) == 3 for v in cell) and \ 

3465 all(np.isfinite([float(c) for v in cell for c in v])) 

3466 except ValueError: 

3467 ok = False 

3468 if not ok: 

3469 raise ValueError('\n\n{} must hold three vectors of three real numbers.\n'.format(what)) 

3470 

3471 

3472def centres_count(n, num_wann): 

3473 ''' 

3474 Check that a ``_centres.xyz`` file lists num_wann Wannier centres (X). 

3475 

3476 Raises 

3477 ------ 

3478 ValueError 

3479 Too few Wannier centres. 

3480 ''' 

3481 if n < num_wann: 

3482 raise ValueError('\n\nThe _centres.xyz file lists {} Wannier centres ("X"), ' 

3483 'not {}.\n'.format(n, num_wann)) 

3484 

3485 

3486def wannier_dim(dim): 

3487 ''' 

3488 Check the dimension of a Wannier90 model. 

3489 

3490 Raises 

3491 ------ 

3492 ValueError 

3493 dim must be 2 or 3. 

3494 ''' 

3495 if isinstance(dim, bool) or dim not in (2, 3): 

3496 raise ValueError('\n\nParameter dim must be 2 or 3.\n') 

3497 

3498 

3499def win_given(win): 

3500 ''' 

3501 Check that the lattice vectors can be found. 

3502 

3503 Raises 

3504 ------ 

3505 ValueError 

3506 Give prim_vec or win. 

3507 ''' 

3508 if win is None: 

3509 raise ValueError('\n\nGive the primitive vectors: prim_vec, or the .win file (win).\n') 

3510 

3511 

3512def layer_cell(cell, dim): 

3513 ''' 

3514 Check that, for a 2D model, a1 and a2 lie in the (x, y) plane. 

3515 

3516 Raises 

3517 ------ 

3518 ValueError 

3519 a1 and a2 must have no z component. 

3520 ''' 

3521 if dim == 2 and np.any(np.abs(cell[:2, 2]) > 1e-8): 

3522 raise ValueError('\n\nFor dim=2, the first two lattice vectors must lie in the (x, y) plane.\n') 

3523 

3524 

3525def wannier_prim_vec(prim_vec, dim): 

3526 ''' 

3527 Check that the primitive vectors are *dim* vectors of *dim* components. 

3528 

3529 Raises 

3530 ------ 

3531 ValueError 

3532 prim_vec must hold dim vectors of dim components. 

3533 ''' 

3534 if len(prim_vec) != dim or len(prim_vec[0]) != dim: 

3535 raise ValueError('\n\nParameter prim_vec must hold {0} vectors of {0} components.\n'.format(dim)) 

3536 independent(prim_vec) 

3537 

3538 

3539def wannier_positions(shape, num_wann, dim): 

3540 ''' 

3541 Check the orbital positions of a Wannier90 model. 

3542 

3543 Raises 

3544 ------ 

3545 ValueError 

3546 positions must have shape (num_wann, dim) or (num_wann, 3). 

3547 ''' 

3548 if len(shape) != 2 or shape[0] != num_wann or shape[1] not in (dim, 3): 

3549 raise ValueError('\n\nParameter positions must have shape ({0}, {1}) or ({0}, 3).\n' 

3550 .format(num_wann, dim)) 

3551 

3552 

3553def wannier_tags(tags, num_wann): 

3554 ''' 

3555 Check the sublattice tags of a Wannier90 model. 

3556 

3557 Raises 

3558 ------ 

3559 TypeError 

3560 tags must be a list of strings of 1 to TAG_LEN characters. 

3561 ValueError 

3562 tags must have num_wann elements. 

3563 ''' 

3564 if not isinstance(tags, list) or not all(isinstance(t, str) and 1 <= len(t) <= TAG_LEN for t in tags): 

3565 raise TypeError('\n\nParameter tags must be a list of strings of 1 to {} characters.\n' 

3566 .format(TAG_LEN)) 

3567 if len(tags) != num_wann: 

3568 raise ValueError('\n\nParameter tags must have {} elements.\n'.format(num_wann)) 

3569 

3570 

3571def layer_hoppings(h_max, tol): 

3572 ''' 

3573 Check that a 2D model has no hopping between layers (R3 != 0). 

3574 

3575 Raises 

3576 ------ 

3577 ValueError 

3578 Hoppings with R3 != 0 must vanish for dim=2. 

3579 ''' 

3580 if h_max > tol: 

3581 raise ValueError('\n\nFor dim=2, the matrix elements with R3 != 0 must vanish ' 

3582 '(largest: {:.3g}).\n'.format(h_max)) 

3583 

3584 

3585def tb_body(n_tokens, nrpts, num_wann): 

3586 ''' 

3587 Check the number of entries of a Wannier90 ``_tb.dat`` file. 

3588 

3589 Raises 

3590 ------ 

3591 ValueError 

3592 The file must have nrpts blocks of the Hamiltonian, then nrpts of positions. 

3593 ''' 

3594 if n_tokens != nrpts * (6 + 12 * num_wann ** 2): 

3595 raise ValueError('\n\nThe _tb.dat file must hold, after the weights, nrpts = {0} blocks ' 

3596 '"R1 R2 R3" followed by num_wann**2 = {1} lines "m n Re Im", then ' 

3597 'nrpts blocks "R1 R2 R3" followed by {1} lines of 2 + 6 numbers.\n' 

3598 .format(nrpts, num_wann ** 2)) 

3599 

3600 

3601def tb_vectors(ok): 

3602 ''' 

3603 Check that the position blocks of a ``_tb.dat`` file come in the order 

3604 of its Hamiltonian blocks. 

3605 

3606 Raises 

3607 ------ 

3608 ValueError 

3609 The two lists of lattice vectors differ. 

3610 ''' 

3611 if not ok: 

3612 raise ValueError('\n\nThe position blocks of the _tb.dat file must list the lattice ' 

3613 'vectors R in the order of the Hamiltonian blocks.\n') 

3614 

3615 

3616def tb_origin(n): 

3617 ''' 

3618 Check that a ``_tb.dat`` file lists the lattice vector R = 0 once. 

3619 

3620 Raises 

3621 ------ 

3622 ValueError 

3623 R = 0 must appear once. 

3624 ''' 

3625 if n != 1: 

3626 raise ValueError('\n\nThe _tb.dat file must list the lattice vector R = (0, 0, 0) once ' 

3627 '(it holds the Wannier centres); it does {} times.\n'.format(n)) 

3628 

3629 

3630def wannier_export_dim(dim, space_dim): 

3631 ''' 

3632 Check that a KSpace can be written in the Wannier90 formats: a 2D 

3633 lattice in the plane or a 3D lattice. 

3634 

3635 Raises 

3636 ------ 

3637 ValueError 

3638 Only 2D models in the plane and 3D models. 

3639 ''' 

3640 if dim not in (2, 3) or dim != space_dim: 

3641 raise ValueError('\n\nOnly a 2D model in the plane (dim = space_dim = 2) or a 3D model ' 

3642 'can be written in the Wannier90 formats (dim = {}, space_dim = {}).\n' 

3643 .format(dim, space_dim)) 

3644 

3645 

3646def no_position_elements(present, method): 

3647 ''' 

3648 Check that a response which knows only the orbital positions is not 

3649 asked to use the position matrix elements of a ``_tb.dat`` model. 

3650 

3651 Raises 

3652 ------ 

3653 ValueError 

3654 *method* does not use the position matrix elements. 

3655 ''' 

3656 if present: 

3657 raise ValueError('\n\n{} does not use the position matrix elements of a _tb.dat model ' 

3658 'besides the Wannier centres: read the model with ' 

3659 'read_wannier90_tb(..., elements=False) to keep the centres only, ' 

3660 'or pass positions=False.\n'.format(method)) 

3661 

3662 

3663#################################### 

3664# INTEROPERABILITY (tbkit.interop) 

3665#################################### 

3666 

3667 

3668def site_tags(tags, n): 

3669 ''' 

3670 Check a list of *n* sublattice tags (strings of 1 to TAG_LEN characters). 

3671 

3672 Raises 

3673 ------ 

3674 TypeError 

3675 tags must be a list of strings. 

3676 ValueError 

3677 One tag per site, of 1 to TAG_LEN characters. 

3678 ''' 

3679 if not isinstance(tags, list) or not all(isinstance(t, str) for t in tags): 

3680 raise TypeError('\n\nParameter tags must be a list of strings.\n') 

3681 if len(tags) != n or not all(1 <= len(t) <= TAG_LEN for t in tags): 

3682 raise ValueError('\n\nParameter tags must hold {} strings (one per site) of 1 to {} ' 

3683 'characters.\n'.format(n, TAG_LEN)) 

3684 

3685 

3686def ase_periodic(pbc): 

3687 ''' 

3688 Check that an ASE Atoms object has a periodic direction. 

3689 

3690 Raises 

3691 ------ 

3692 ValueError 

3693 At least one periodic direction. 

3694 ''' 

3695 if not np.any(pbc): 

3696 raise ValueError('\n\nThe Atoms object needs at least one periodic direction (pbc).\n') 

3697 

3698 

3699def ase_space_dim(space_dim, planar): 

3700 ''' 

3701 Check the space dimension asked of *lattice_from_ase*. 

3702 

3703 Raises 

3704 ------ 

3705 ValueError 

3706 space_dim must be 2 or 3, and 2 only for a planar structure. 

3707 ''' 

3708 if space_dim not in (2, 3): 

3709 raise ValueError('\n\nParameter space_dim must be 2, 3 or None.\n') 

3710 if space_dim == 2 and not planar: 

3711 raise ValueError('\n\nspace_dim=2 needs at most two periodic vectors in the (x, y) plane ' 

3712 'and every atom at the same height.\n') 

3713 

3714 

3715def chemical_symbols(names, known): 

3716 ''' 

3717 Check that every name is a chemical symbol of ASE. 

3718 

3719 Raises 

3720 ------ 

3721 ValueError 

3722 Not a chemical symbol: give a dictionary symbols={tag: symbol}. 

3723 ''' 

3724 unknown = sorted({n for n in names if n not in known}) 

3725 if unknown: 

3726 raise ValueError('\n\n{} are not chemical symbols: map the tags to symbols with ' 

3727 'symbols={{tag: symbol}}.\n'.format(unknown)) 

3728 

3729 

3730def pythtb_periodic(n_per): 

3731 ''' 

3732 Check that a PythTB model has a periodic direction. 

3733 

3734 Raises 

3735 ------ 

3736 ValueError 

3737 A finite PythTB model has no KSpace. 

3738 ''' 

3739 if n_per < 1: 

3740 raise ValueError('\n\nThe PythTB model has no periodic direction: a KSpace needs one.\n') 

3741 

3742 

3743def numeric_terms(values, code): 

3744 ''' 

3745 Check that the onsite energies and hoppings of a model of *code* are 

3746 numbers (or matrices of numbers). 

3747 

3748 Raises 

3749 ------ 

3750 ValueError 

3751 Parametric terms are not supported. 

3752 ''' 

3753 for v in values: 

3754 if callable(v) or np.asarray(v).dtype.kind not in 'biufc': 

3755 raise ValueError('\n\nThe {} model has parametric terms (strings or functions): ' 

3756 'give them numbers before importing it.\n'.format(code)) 

3757 

3758 

3759def pybinding_aliases(unique): 

3760 ''' 

3761 Check that a pybinding lattice has no sublattice aliases. 

3762 

3763 Raises 

3764 ------ 

3765 ValueError 

3766 Sublattice aliases are not supported. 

3767 ''' 

3768 if not all(unique): 

3769 raise ValueError('\n\nThe pybinding lattice has sublattice aliases, which tbkit does ' 

3770 'not import.\n') 

3771 

3772 

3773def pybinding_spin(sizes): 

3774 ''' 

3775 Check that every sublattice has two orbitals, for spin=True. 

3776 

3777 Raises 

3778 ------ 

3779 ValueError 

3780 spin=True needs two orbitals per sublattice. 

3781 ''' 

3782 if any(n != 2 for n in sizes): 

3783 raise ValueError('\n\nspin=True needs every sublattice to have 2 orbitals ' 

3784 '(they have {}).\n'.format(sizes)) 

3785 

3786 

3787def kwant_ham(n_ham, n_sites): 

3788 ''' 

3789 Check that a System's Hamiltonian is built, before exporting it. 

3790 

3791 Raises 

3792 ------ 

3793 ValueError 

3794 Call get_ham first. 

3795 ''' 

3796 if n_ham != n_sites: 

3797 raise ValueError('\n\nThe System has no Hamiltonian of its {} sites: call get_ham first.\n' 

3798 .format(n_sites)) 

3799 

3800 

3801def hermitian_matrix(ham, leads=(), tol=1e-12): 

3802 ''' 

3803 Check that a sparse Hamiltonian, and the leads (h0, v, coupling, 

3804 sites) attached to it, are Hermitian. 

3805 

3806 Raises 

3807 ------ 

3808 ValueError 

3809 The Hamiltonian must be Hermitian. 

3810 ''' 

3811 dev = abs(ham - ham.conj().T).max() if ham.nnz else 0. 

3812 dev = max([dev] + [float(np.abs(h0 - h0.conj().T).max()) for h0, *_ in leads]) 

3813 if dev > tol: 

3814 raise ValueError('\n\nKwant needs a Hermitian Hamiltonian (largest deviation {:.3g}).\n' 

3815 .format(dev)) 

3816 

3817 

3818def kwant_finite(fsys): 

3819 ''' 

3820 Check that an object is a finalized, finite Kwant system. 

3821 

3822 Raises 

3823 ------ 

3824 TypeError 

3825 Not a finalized finite Kwant system. 

3826 ''' 

3827 if not (hasattr(fsys, 'hamiltonian_submatrix') and hasattr(fsys, 'sites')) \ 

3828 or hasattr(fsys, 'cell_size'): 

3829 raise TypeError('\n\nExpected a finalized, finite Kwant system ' 

3830 '(builder.finalized(), not a lead).\n') 

3831 

3832 

3833def kwant_orbitals(n_orbitals, n_ham): 

3834 ''' 

3835 Check that the orbitals of a Kwant system match its Hamiltonian. 

3836 

3837 Raises 

3838 ------ 

3839 ValueError 

3840 Set norbs on the site families. 

3841 ''' 

3842 if n_orbitals != n_ham: 

3843 raise ValueError('\n\nThe Kwant system has {} orbitals for {} sites: set norbs on its ' 

3844 'site families.\n'.format(n_ham, n_orbitals)) 

3845 

3846 

3847def spinless(spin): 

3848 ''' 

3849 Check that a KSpace model has no spin. 

3850 

3851 Raises 

3852 ------ 

3853 ValueError 

3854 This needs a spinless model. 

3855 ''' 

3856 if spin: 

3857 raise ValueError('\n\nThis needs a spinless model (spin=False): a System has one ' 

3858 'orbital per site; use bridges.finite_model for spinful models.\n') 

3859# HIGHER-ORDER TOPOLOGY, MOIRE SUPERCELLS, SELF-CONSISTENT INTERACTIONS 

3860#################################### 

3861 

3862 

3863def wannier_gap(nu, sector, tol=1e-4): 

3864 ''' 

3865 Check that a Wannier sector is separated from the other Wannier bands 

3866 over the mesh (*nu*, shape (n1, n2, nb), sorted at each k): at every k, 

3867 the smallest distance on the circle between a Wannier band of the 

3868 sector and one outside it (the Wannier gap) exceeds *tol*, and the 

3869 Wannier bands of the sector change between neighbouring k-points by 

3870 less than the smallest gap (otherwise two Wannier bands crossed between 

3871 them, or the sector wrapped around the circle). 

3872 

3873 Raises 

3874 ------ 

3875 ValueError 

3876 The Wannier sector is not separated by a Wannier gap. 

3877 ''' 

3878 nu = np.asarray(nu) 

3879 rest = [n for n in range(nu.shape[-1]) if n not in sector] 

3880 if not rest: 

3881 return 

3882 

3883 def circ(d): 

3884 d = np.abs(d) % 1. 

3885 return np.minimum(d, 1. - d) 

3886 gap = np.min(circ(nu[..., sector][..., :, None] - nu[..., rest][..., None, :])) 

3887 jump = max(np.max(circ(nu[..., sector] - np.roll(nu[..., sector], 1, axis=a))) 

3888 for a in range(nu.ndim - 1)) 

3889 if gap < tol or jump >= gap: 

3890 raise ValueError('\n\nThe Wannier sector is not separated from the other Wannier ' 

3891 'bands by a Wannier gap (smallest distance {:.2e}, largest ' 

3892 'step {:.2e}).\n'.format(gap, jump)) 

3893 

3894 

3895def supercell_matrix(mat, dim): 

3896 ''' 

3897 Check a supercell matrix: integers, shape (dim, dim), nonzero determinant. 

3898 

3899 Raises 

3900 ------ 

3901 TypeError 

3902 The supercell matrix must contain integers. 

3903 ValueError 

3904 The supercell matrix must be (dim, dim), with a nonzero determinant. 

3905 ''' 

3906 if mat.shape != (dim, dim): 

3907 raise ValueError('\n\nThe supercell matrix must have the shape ({0}, {0}).\n'.format(dim)) 

3908 if not np.issubdtype(mat.dtype, np.integer): 

3909 raise TypeError('\n\nThe supercell matrix must contain integers.\n') 

3910 if round(abs(np.linalg.det(mat))) == 0: 

3911 raise ValueError('\n\nThe supercell matrix must have a nonzero determinant.\n') 

3912 

3913 

3914def supercell_model(sc, cls): 

3915 ''' 

3916 Check that *sc* is a supercell (made by *moire.supercell*). 

3917 

3918 Raises 

3919 ------ 

3920 TypeError 

3921 Parameter sc must be a SupercellKSpace instance. 

3922 ''' 

3923 if not isinstance(sc, cls): 

3924 raise TypeError('\n\nParameter sc must be a SupercellKSpace instance ' 

3925 '(see tbkit.moire.supercell).\n') 

3926 

3927 

3928def bond_vectors(d): 

3929 ''' 

3930 Check bond vectors: shape (n, 3), none of zero length. 

3931 

3932 Raises 

3933 ------ 

3934 ValueError 

3935 Bond vectors must have the shape (n, 3) and a nonzero length. 

3936 ''' 

3937 if d.ndim != 2 or d.shape[1] != 3: 

3938 raise ValueError('\n\nThe bond vectors must have the shape (n, 3).\n') 

3939 if np.any(np.linalg.norm(d, axis=1) == 0): 

3940 raise ValueError('\n\nThe bond vectors must have a nonzero length.\n') 

3941 

3942 

3943def twist_lattice(lattice): 

3944 ''' 

3945 Check the layer lattice of a twisted bilayer. 

3946 

3947 Raises 

3948 ------ 

3949 ValueError 

3950 Parameter lattice must be "honeycomb" or "square". 

3951 ''' 

3952 if lattice not in ('honeycomb', 'square'): 

3953 raise ValueError('\n\nParameter lattice must be "honeycomb" or "square".\n') 

3954 

3955 

3956def commensurate(moire_1, moire_2): 

3957 ''' 

3958 Check that the moire vectors of the two layers coincide. 

3959 

3960 Raises 

3961 ------ 

3962 ValueError 

3963 The two layers do not share the moire cell. 

3964 ''' 

3965 if not np.allclose(moire_1, moire_2, atol=1e-9 * max(1., np.abs(moire_1).max())): 

3966 raise ValueError('\n\nThe two layers do not share the moire cell.\n') 

3967 

3968 

3969def hopping_values(t, n): 

3970 ''' 

3971 Check the output of a hopping function: n values. 

3972 

3973 Raises 

3974 ------ 

3975 ValueError 

3976 The hopping function must return one value per bond vector. 

3977 ''' 

3978 if np.shape(t) != (n,): 

3979 raise ValueError('\n\nThe hopping function must return one value per bond vector, ' 

3980 'shape ({},).\n'.format(n)) 

3981 

3982 

3983def even_dimension(n): 

3984 ''' 

3985 Check that a spinful matrix has an even dimension (two spins per site). 

3986 

3987 Raises 

3988 ------ 

3989 ValueError 

3990 A spinful Hamiltonian must have an even dimension. 

3991 ''' 

3992 if n % 2: 

3993 raise ValueError('\n\nA spinful Hamiltonian must have an even dimension ' 

3994 '(rows site-major, spin up then down).\n') 

3995 

3996 

3997def magnetization(mag, n): 

3998 ''' 

3999 Check initial moments: a real array of shape (n, 3). 

4000 

4001 Raises 

4002 ------ 

4003 ValueError 

4004 Parameter magnetization must have the shape (n, 3). 

4005 ''' 

4006 if mag.shape != (n, 3): 

4007 raise ValueError('\n\nParameter magnetization must have the shape ({}, 3).\n'.format(n)) 

4008 

4009 

4010def interaction(V, n): 

4011 ''' 

4012 Check an attractive interaction: a positive number, or n non-negative numbers. 

4013 

4014 Raises 

4015 ------ 

4016 ValueError 

4017 The interaction must be positive (or n non-negative values). 

4018 ''' 

4019 V = np.asarray(V, dtype='f8') 

4020 if V.ndim == 0: 

4021 positive_real(float(V), 'V') 

4022 return 

4023 if V.shape != (n,) or np.any(V < 0): 

4024 raise ValueError('\n\nParameter V must be a positive number, or {} non-negative ' 

4025 'numbers (one per site).\n'.format(n)) 

4026 

4027 

4028def pairing_amplitudes(delta, n, var_name='delta0'): 

4029 ''' 

4030 Check pairing amplitudes: a number, or n numbers. 

4031 

4032 Raises 

4033 ------ 

4034 ValueError 

4035 Parameter *var_name* must be a number or n numbers. 

4036 ''' 

4037 if np.ndim(delta) == 0: 

4038 number(delta, var_name) 

4039 return 

4040 if np.shape(delta) != (n,): 

4041 raise ValueError('\n\nParameter {} must be a number, or {} numbers ' 

4042 '(one per site).\n'.format(var_name, n)) 

4043 

4044 

4045def spin_up_model(spin): 

4046 ''' 

4047 Check that a KSpace model is spinless (the spin-up electrons). 

4048 

4049 Raises 

4050 ------ 

4051 ValueError 

4052 This needs the spinless spin-up model. 

4053 ''' 

4054 if spin: 

4055 raise ValueError('\n\nThis needs a spinless model (spin=False): the spin-up ' 

4056 'electrons, whose time-reversed partners are the spin-down ones.\n') 

4057# OPTICAL RESPONSE AND TRANSPORT (tbkit.optics, tbkit.transport) 

4058#################################### 

4059 

4060 

4061def frequencies(omega, var_name): 

4062 ''' 

4063 Check photon energies (or energies): a real number, or a non-empty 

4064 array of finite real numbers. 

4065 

4066 Raises 

4067 ------ 

4068 TypeError 

4069 Parameter must be a real number or an array of real numbers. 

4070 ValueError 

4071 Parameter must contain at least one finite number. 

4072 ''' 

4073 arr = np.asarray(omega) 

4074 if arr.dtype.kind not in 'iuf': 

4075 raise TypeError('\n\nParameter {} must be a real number or an array ' 

4076 'of real numbers.\n'.format(var_name)) 

4077 if arr.size == 0 or not np.all(np.isfinite(arr)): 

4078 raise ValueError('\n\nParameter {} must contain at least one finite ' 

4079 'number.\n'.format(var_name)) 

4080 

4081 

4082def optical_part(part): 

4083 ''' 

4084 Check the part of *kpm.optical_conductivity* to return. 

4085 

4086 Raises 

4087 ------ 

4088 ValueError 

4089 Parameter part must be "real", "imag" or "complex". 

4090 ''' 

4091 if part not in ('real', 'imag', 'complex'): 

4092 raise ValueError('\n\nParameter part must be "real", "imag" or "complex".\n') 

4093 

4094 

4095def cartesian_axes(axes, space_dim, var_name='component', length=None): 

4096 ''' 

4097 Check a string of Cartesian axes ('x', 'y', 'z', within the space 

4098 dimension), for the derivatives of *KSpace.finite_derivatives* and the 

4099 components of *kpm.nonlinear_optical_conductivity*. 

4100 

4101 Raises 

4102 ------ 

4103 TypeError 

4104 Parameter must be a string. 

4105 ValueError 

4106 Parameter must be letters among the axes (*length* of them if given). 

4107 ''' 

4108 if not isinstance(axes, str): 

4109 raise TypeError('\n\nParameter {} must be a string.\n'.format(var_name)) 

4110 letters = 'xyz'[:space_dim] 

4111 if not axes or any(c not in letters for c in axes) or (length is not None and len(axes) != length): 

4112 raise ValueError('\n\nParameter {} must be a string of {} letters among ' 

4113 "'{}'.\n".format(var_name, length or 'one or more', letters)) 

4114 

4115 

4116def nonlinear_derivatives(derivatives, keys, n): 

4117 ''' 

4118 Check the derivatives of the Hamiltonian given to 

4119 *kpm.nonlinear_optical_conductivity*: a dict holding every key in 

4120 *keys*, each a (n, n) matrix. 

4121 

4122 Raises 

4123 ------ 

4124 TypeError 

4125 Parameter derivatives must be a dict. 

4126 ValueError 

4127 Parameter derivatives must hold the derivative along each key. 

4128 ''' 

4129 if not isinstance(derivatives, dict): 

4130 raise TypeError('\n\nParameter derivatives must be a dict (see KSpace.finite_derivatives).\n') 

4131 missing = [k for k in keys if k not in derivatives] 

4132 if missing: 

4133 raise ValueError('\n\nParameter derivatives lacks the derivatives {} (see ' 

4134 'KSpace.finite_derivatives).\n'.format(missing)) 

4135 for k in keys: 

4136 velocity(derivatives[k], n, "derivatives['{}']".format(k)) 

4137 

4138 

4139def nonzero_frequencies(omega, var_name): 

4140 ''' 

4141 Check that the frequencies of a nonlinear response are finite and 

4142 nonzero (the velocity gauge divides by them). 

4143 

4144 Raises 

4145 ------ 

4146 ValueError 

4147 Parameter must be nonzero. 

4148 ''' 

4149 frequencies(omega, var_name) 

4150 if np.any(np.asarray(omega) == 0): 

4151 raise ValueError('\n\nParameter {} must be nonzero.\n'.format(var_name)) 

4152 

4153 

4154def tensor_component(component, order): 

4155 ''' 

4156 Check a Cartesian tensor component of a 2D response: a string of 

4157 *order* letters among 'x' and 'y'. Returns the axis indices. 

4158 

4159 Raises 

4160 ------ 

4161 TypeError 

4162 Parameter component must be a string. 

4163 ValueError 

4164 Parameter component must have order letters among x, y. 

4165 ''' 

4166 if not isinstance(component, str): 

4167 raise TypeError('\n\nParameter component must be a string.\n') 

4168 if len(component) != order or any(c not in 'xy' for c in component): 

4169 raise ValueError('\n\nParameter component must be {} letters among ' 

4170 "'x' and 'y'.\n".format(order)) 

4171 return tuple('xy'.index(c) for c in component) 

4172 

4173 

4174def band_derivatives(en, vel, w): 

4175 ''' 

4176 Check the band energies (nk, n), velocities (2, nk, n, n) and second 

4177 derivatives (2, 2, nk, n, n) of *optics.generalized_derivative*. 

4178 

4179 Raises 

4180 ------ 

4181 ValueError 

4182 Inconsistent shapes. 

4183 ''' 

4184 if en.ndim != 2 or vel.shape != (2,) + en.shape + en.shape[-1:] or \ 

4185 w.shape != (2,) + vel.shape: 

4186 raise ValueError('\n\nThe shapes must be en (nk, n), vel (2, nk, n, n) and ' 

4187 'w (2, 2, nk, n, n).\n') 

4188 

4189 

4190def lead_pair(pair, n_leads, var_name, distinct): 

4191 ''' 

4192 Check a pair of lead indices (and, with *distinct*, that they differ). 

4193 

4194 Raises 

4195 ------ 

4196 TypeError 

4197 Parameter must be a tuple/list of two lead indices. 

4198 ValueError 

4199 No such lead, or the two leads must differ. 

4200 ''' 

4201 if not isinstance(pair, (tuple, list)) or len(pair) != 2: 

4202 raise TypeError('\n\nParameter {} must be a tuple of two lead indices.\n'.format(var_name)) 

4203 for lead in pair: 

4204 lead_index(lead, n_leads) 

4205 if distinct and pair[0] == pair[1]: 

4206 raise ValueError('\n\nThe two leads of parameter {} must differ.\n'.format(var_name)) 

4207 

4208 

4209def site_positions(positions, n_sites): 

4210 ''' 

4211 Check site positions: a real array of shape (n_sites, d). 

4212 

4213 Raises 

4214 ------ 

4215 ValueError 

4216 Parameter positions must have shape (n_sites, d). 

4217 ''' 

4218 if positions.ndim != 2 or len(positions) != n_sites: 

4219 raise ValueError('\n\nParameter positions must have shape ({}, d).\n'.format(n_sites)) 

4220 

4221 

4222def slices(slices, n_sites): 

4223 ''' 

4224 Check a partition of the device sites into non-empty slices. 

4225 

4226 Raises 

4227 ------ 

4228 TypeError 

4229 Parameter slices must be a list of lists of integers. 

4230 ValueError 

4231 The slices must contain every site exactly once. 

4232 ''' 

4233 if not isinstance(slices, list) or not all( 

4234 isinstance(s, (list, tuple)) and len(s) > 0 

4235 and all(isinstance(i, (int, np.integer)) for i in s) for s in slices): 

4236 raise TypeError('\n\nParameter slices must be a list of non-empty lists of integers.\n') 

4237 flat = sorted(int(i) for s in slices for i in s) 

4238 if flat != list(range(n_sites)): 

4239 raise ValueError('\n\nThe slices must contain every site (0 to {}) exactly ' 

4240 'once.\n'.format(n_sites - 1)) 

4241 

4242 

4243def block_tridiagonal(max_distance): 

4244 ''' 

4245 Check that hoppings only couple a slice to itself or to its neighbours. 

4246 

4247 Raises 

4248 ------ 

4249 ValueError 

4250 Hoppings must connect neighbouring slices only. 

4251 ''' 

4252 if max_distance > 1: 

4253 raise ValueError('\n\nThe Hamiltonian couples slices that are not neighbours: ' 

4254 'use thicker slices.\n') 

4255 

4256 

4257def lead_tuple(lead): 

4258 ''' 

4259 Check a lead given as a tuple (h0, v, coupling). 

4260 

4261 Raises 

4262 ------ 

4263 TypeError 

4264 A lead must be a tuple (h0, v, coupling). 

4265 ''' 

4266 if not isinstance(lead, (tuple, list)) or len(lead) != 3: 

4267 raise TypeError('\n\nA lead must be a tuple (h0, v, coupling).\n') 

4268 

4269 

4270#################################### 

4271# SECTOR CHERN NUMBERS, BDG, BOTT, WEYL 

4272#################################### 

4273 

4274 

4275def hermitian_operator(ops, tol=1e-10): 

4276 ''' 

4277 Check that an operator (shape (..., norb, norb)) is Hermitian. 

4278 

4279 Raises 

4280 ------ 

4281 ValueError 

4282 The operator must be Hermitian. 

4283 ''' 

4284 if np.max(np.abs(ops - ops.conj().swapaxes(-1, -2))) > tol: 

4285 raise ValueError('\n\nThe operator must be Hermitian.\n') 

4286 

4287 

4288def projected_gap(w, tol=1e-6): 

4289 ''' 

4290 Check that the projected operator POP (eigenvalues *w*, shape (nk, n), 

4291 sorted) has no eigenvalue near zero, and the same number of negative 

4292 eigenvalues at every k-point; return that number. 

4293 

4294 Raises 

4295 ------ 

4296 ValueError 

4297 The spectrum of POP must have a gap around zero. 

4298 ''' 

4299 n_minus = np.sum(w < 0., axis=1) 

4300 if np.min(np.abs(w)) < tol or np.any(n_minus != n_minus[0]): 

4301 raise ValueError('\n\nThe spectrum of the projected operator POP closes around zero ' 

4302 '(smallest |eigenvalue| {:.3g}): the two sectors are not ' 

4303 'defined.\n'.format(float(np.min(np.abs(w))))) 

4304 return int(n_minus[0]) 

4305 

4306 

4307def mirror_square(squares, tol): 

4308 ''' 

4309 Check that a mirror operator squares to +1 or -1 (*squares*, shape 

4310 (..., norb, norb)); return the sign. 

4311 

4312 Raises 

4313 ------ 

4314 ValueError 

4315 The mirror operator must square to +1 or -1. 

4316 ''' 

4317 sign = np.sign(squares[0, 0, 0].real) 

4318 eye = np.eye(squares.shape[-1]) 

4319 if sign == 0 or np.max(np.abs(squares - sign * eye)) > tol: 

4320 raise ValueError('\n\nThe mirror operator must be unitary and square to +1 or -1.\n') 

4321 return int(sign) 

4322 

4323 

4324def commutes(err, tol): 

4325 ''' 

4326 Check that an operator commutes with H(k) on the plane (*err*: largest 

4327 entry of the commutator). 

4328 

4329 Raises 

4330 ------ 

4331 ValueError 

4332 The operator does not commute with H(k) on this plane. 

4333 ''' 

4334 if err > tol: 

4335 raise ValueError('\n\nThe mirror operator does not commute with H(k) on this plane ' 

4336 '(largest commutator entry {:.3g}): choose a ' 

4337 'mirror-invariant plane.\n'.format(err)) 

4338 

4339 

4340def strong_index(strong): 

4341 ''' 

4342 Check that the strong Z2 index comes out the same from the three pairs 

4343 of time-reversal-invariant planes. 

4344 

4345 Raises 

4346 ------ 

4347 ValueError 

4348 The six Z2 invariants are inconsistent. 

4349 ''' 

4350 if len(set(int(s) for s in strong)) != 1: 

4351 raise ValueError('\n\nThe six planar Z2 invariants give different strong indices: ' 

4352 'increase nk or nk_perp (or the bands are not gapped).\n') 

4353 

4354 

4355def region(region, n): 

4356 ''' 

4357 Check a region: a non-empty list of distinct indices between 0 and n-1. 

4358 

4359 Raises 

4360 ------ 

4361 TypeError 

4362 Parameter region must be a non-empty list of integers. 

4363 ValueError 

4364 Parameter region must hold distinct indices between 0 and n-1. 

4365 ''' 

4366 if not isinstance(region, list) or not region or \ 

4367 not all(isinstance(i, (int, np.integer)) for i in region): 

4368 raise TypeError('\n\nParameter region must be a non-empty list of integers.\n') 

4369 if len(set(region)) != len(region) or not all(0 <= i < n for i in region): 

4370 raise ValueError('\n\nParameter region must hold distinct indices between 0 and ' 

4371 '{}.\n'.format(n - 1)) 

4372 

4373 

4374def torus_cell(cell, d): 

4375 ''' 

4376 Check the two vectors spanning a torus: shape (2, d), linearly independent. 

4377 

4378 Raises 

4379 ------ 

4380 ValueError 

4381 Parameter cell must hold two independent vectors of d components. 

4382 ''' 

4383 if cell.shape != (2, d) or np.linalg.matrix_rank(cell) < 2: 

4384 raise ValueError('\n\nParameter cell must hold two linearly independent vectors ' 

4385 'of {} components.\n'.format(d)) 

4386 

4387 

4388def band_below_top(n, norb): 

4389 ''' 

4390 Check that a band has a band above it. 

4391 

4392 Raises 

4393 ------ 

4394 ValueError 

4395 The highest band of bands must not be the top band. 

4396 ''' 

4397 if n >= norb - 1: 

4398 raise ValueError('\n\nThe highest band of bands must have a band above it.\n') 

4399 

4400 

4401def antisymmetric(a, tol=1e-10): 

4402 ''' 

4403 Check that a matrix is antisymmetric. 

4404 

4405 Raises 

4406 ------ 

4407 ValueError 

4408 The matrix must be antisymmetric. 

4409 ''' 

4410 if np.max(np.abs(a + a.T), initial=0.) > tol: 

4411 raise ValueError('\n\nThe matrix must be antisymmetric.\n') 

4412 

4413 

4414def bdg_orbitals(norb): 

4415 ''' 

4416 Check that a BdG model has an even number of orbitals (particles, then holes). 

4417 

4418 Raises 

4419 ------ 

4420 ValueError 

4421 A BdG model must have an even number of orbitals. 

4422 ''' 

4423 if norb % 2: 

4424 raise ValueError('\n\nA BdG model must have an even number of orbitals ' 

4425 '(particles, then holes).\n') 

4426 

4427 

4428def majorana_form(a, tol=1e-8): 

4429 ''' 

4430 Check that the Majorana form -i U H U^dagger of a BdG Hamiltonian at a 

4431 time-reversal-invariant momentum is real (particle-hole symmetry). 

4432 

4433 Raises 

4434 ------ 

4435 ValueError 

4436 The model is not particle-hole symmetric. 

4437 ''' 

4438 if np.max(np.abs(a.imag)) > tol: 

4439 raise ValueError('\n\nThe model is not particle-hole symmetric in the BdG basis ' 

4440 '(particles, then holes; see bdg.bdg_kspace).\n') 

4441 

4442 

4443def gapped_trim(pf, tol=1e-12): 

4444 ''' 

4445 Check that a Pfaffian is nonzero (the BdG gap is open at the momentum). 

4446 

4447 Raises 

4448 ------ 

4449 ValueError 

4450 The gap closes at a time-reversal-invariant momentum. 

4451 ''' 

4452 if abs(pf) < tol: 

4453 raise ValueError('\n\nThe gap closes at a time-reversal-invariant momentum: the ' 

4454 'Majorana number is not defined.\n') 

4455 

4456 

4457#################################### 

4458# PERIODIC BOUNDARIES (SYSTEM) 

4459#################################### 

4460 

4461 

4462def periodic(periodic, dim): 

4463 ''' 

4464 Check parameter *periodic* of *System*: a boolean, or a tuple of *dim* 

4465 booleans (one per primitive vector); return the tuple. 

4466 

4467 Raises 

4468 ------ 

4469 TypeError 

4470 Parameter periodic must be a bool or a tuple of bools. 

4471 ValueError 

4472 Parameter periodic must have one entry per primitive vector. 

4473 ''' 

4474 if isinstance(periodic, bool): 

4475 return (periodic,) * dim 

4476 if not isinstance(periodic, tuple) or not all(isinstance(p, bool) for p in periodic): 

4477 raise TypeError('\n\nParameter periodic must be a bool or a tuple of bools.\n') 

4478 if len(periodic) != dim: 

4479 raise ValueError('\n\nParameter periodic must have one entry per primitive vector ' 

4480 '({}).\n'.format(dim)) 

4481 return periodic 

4482 

4483 

4484def torus_lattice(n1): 

4485 ''' 

4486 Check that the lattice of a periodic System comes from *get_lattice*. 

4487 

4488 Raises 

4489 ------ 

4490 ValueError 

4491 Periodic boundaries need lat.get_lattice first. 

4492 ''' 

4493 if n1 == 0: 

4494 raise ValueError('\n\nPeriodic boundaries wrap the n1 x n2 (x n3) cells of ' 

4495 'lat.get_lattice: call it first.\n') 

4496 

4497 

4498def torus_size(dist, period, n): 

4499 ''' 

4500 Check that bonds of length *dist* (order *n*) reach less than half-way 

4501 around the torus (shortest period *period*), so that each one has a 

4502 single shortest image. 

4503 

4504 Raises 

4505 ------ 

4506 ValueError 

4507 The torus is too small for this neighbour order. 

4508 ''' 

4509 if 2 * dist >= period - ATOL: 

4510 raise ValueError('\n\nThe torus is too small for the neighbours of order {}: their ' 

4511 'length {:.3f} reaches half-way around it (shortest period ' 

4512 '{:.3f}). Use more cells.\n'.format(n, dist, period)) 

4513 

4514 

4515def not_periodic(periodic, method): 

4516 ''' 

4517 Check that a System has open boundaries. 

4518 

4519 Raises 

4520 ------ 

4521 ValueError 

4522 The method needs open boundaries. 

4523 ''' 

4524 if any(periodic): 

4525 raise ValueError('\n\n{} needs open boundaries (periodic=False); on a torus, see ' 

4526 'System.get_bott_index and set_peierls_phase.\n'.format(method)) 

4527 

4528 

4529def torus_2d(periodic): 

4530 ''' 

4531 Check that a System is a 2D torus (periodic along two primitive vectors). 

4532 

4533 Raises 

4534 ------ 

4535 ValueError 

4536 This calculation needs a 2D lattice periodic along both vectors. 

4537 ''' 

4538 if len(periodic) != 2 or not all(periodic): 

4539 raise ValueError('\n\nThis calculation needs a 2D lattice with periodic boundaries ' 

4540 'along both primitive vectors (periodic=True).\n') 

4541 

4542 

4543#################################### 

4544# ANALYSIS AND PLOTTING (projections, contours, k-paths) 

4545#################################### 

4546 

4547 

4548def projector(proj, norb, tags): 

4549 ''' 

4550 Check parameter *projector* of *kspace.band_weights*: an orbital index, 

4551 a non-empty list of distinct orbital indices, a sublattice tag, or a 

4552 (norb, norb) Hermitian matrix. 

4553 

4554 Raises 

4555 ------ 

4556 TypeError 

4557 Parameter projector must be an orbital index, a list of them, a tag or a matrix. 

4558 ValueError 

4559 Orbital indices must be distinct and between 0 and norb-1. 

4560 ValueError 

4561 Parameter projector must be a tag of the unit cell. 

4562 ValueError 

4563 The operator must be a (norb, norb) Hermitian matrix. 

4564 ''' 

4565 if isinstance(proj, str): 

4566 if proj not in tags: 

4567 raise ValueError('\n\nParameter projector must be a tag of the unit cell: ' 

4568 '{}.\n'.format(sorted(set(tags)))) 

4569 return 

4570 if isinstance(proj, np.ndarray) and proj.ndim == 2: 

4571 operator(proj, norb) 

4572 hermitian_operator(proj) 

4573 return 

4574 if isinstance(proj, int): 

4575 proj = [proj] 

4576 if not isinstance(proj, list) or not proj or not all(isinstance(p, int) for p in proj): 

4577 raise TypeError('\n\nParameter projector must be an orbital index, a list of ' 

4578 'orbital indices, a sublattice tag or a (norb, norb) matrix.\n') 

4579 if len(set(proj)) != len(proj) or not all(0 <= p < norb for p in proj): 

4580 raise ValueError('\n\nOrbital indices must be distinct and between 0 and ' 

4581 '{}.\n'.format(norb - 1)) 

4582 

4583 

4584def band_weights(weights, shape): 

4585 ''' 

4586 Check parameter *weights* of *kspace.plot_bands*: real values, one per 

4587 band and k-point of the stored band structure. 

4588 

4589 Raises 

4590 ------ 

4591 ValueError 

4592 Parameter weights must be a real array of the shape of the bands. 

4593 ''' 

4594 weights = np.asarray(weights) 

4595 if weights.shape != shape or np.iscomplexobj(weights) or not np.all(np.isfinite(weights)): 

4596 raise ValueError('\n\nParameter weights must be a finite real array of shape {}, ' 

4597 'the shape of the bands (see band_weights).\n'.format(shape)) 

4598 

4599 

4600def weight_style(style): 

4601 ''' 

4602 Check parameter *style* of *kspace.plot_bands*. 

4603 

4604 Raises 

4605 ------ 

4606 ValueError 

4607 Parameter style must be "color" or "size". 

4608 ''' 

4609 if style not in ('color', 'size'): 

4610 raise ValueError('\n\nParameter style must be "color" or "size".\n') 

4611 

4612 

4613def contour_found(n_elements, energy): 

4614 ''' 

4615 Check that a band crosses the energy of a constant-energy contour. 

4616 

4617 Raises 

4618 ------ 

4619 ValueError 

4620 The band does not cross the energy. 

4621 ''' 

4622 if n_elements == 0: 

4623 raise ValueError('\n\nThe band does not cross the energy {}: there is no ' 

4624 'constant-energy contour.\n'.format(energy)) 

4625 

4626 

4627def cubic_path(points, names, axes): 

4628 ''' 

4629 Check the parameters of *kspace.cubic_path*. 

4630 

4631 Raises 

4632 ------ 

4633 TypeError 

4634 Parameter points must be a dictionary. 

4635 ValueError 

4636 Each point must have 3 real coordinates. 

4637 ValueError 

4638 Parameter names must list at least two keys of points. 

4639 ValueError 

4640 Parameter axes must be 3 orthonormal rows. 

4641 ''' 

4642 if not isinstance(points, dict): 

4643 raise TypeError('\n\nParameter points must be a dictionary (label: point).\n') 

4644 for key, point in points.items(): 

4645 point = np.asarray(point) 

4646 if point.shape != (3,) or not np.isrealobj(point) or not np.all(np.isfinite(point)): 

4647 raise ValueError('\n\nPoint {} must have 3 real coordinates.\n'.format(key)) 

4648 if (not isinstance(names, (list, tuple)) or len(names) < 2 

4649 or any(n not in points for n in names)): 

4650 raise ValueError('\n\nParameter names must list at least two keys of points.\n') 

4651 if axes is not None: 

4652 axes = np.asarray(axes) 

4653 if axes.shape != (3, 3) or not np.isrealobj(axes) or not np.allclose(axes @ axes.T, np.eye(3)): 

4654 raise ValueError('\n\nParameter axes must be 3 orthonormal rows (shape (3, 3)).\n') 

4655 

4656 

4657def bravais_lattice(kind, dim): 

4658 ''' 

4659 Check that *kspace.high_symmetry_path* recognized the Bravais lattice. 

4660 

4661 Raises 

4662 ------ 

4663 ValueError 

4664 No standard path for this lattice. 

4665 ''' 

4666 if kind is None: 

4667 raise ValueError('\n\nNo standard high-symmetry path for this {}D lattice: ' 

4668 'high_symmetry_path knows the 1D and 2D Bravais lattices, ' 

4669 'and the simple cubic, fcc, bcc, simple tetragonal and ' 

4670 'hexagonal ones in 3D. Pass the k-points to k_path ' 

4671 'directly.\n'.format(dim)) 

4672 

4673 

4674############################### 

4675# CONTINUUM DISCRETIZATION 

4676############################### 

4677 

4678 

4679def sympy_module(module): 

4680 ''' 

4681 Check that sympy, the optional dependency of *tbkit.continuum*, is installed. 

4682 

4683 Raises 

4684 ------ 

4685 ImportError 

4686 sympy is not installed. 

4687 ''' 

4688 if module is None: 

4689 raise ImportError('\n\ntbkit.continuum needs sympy: pip install tbkit[continuum].\n') 

4690 

4691 

4692def continuum_type(ham, types): 

4693 ''' 

4694 Check the type of the Hamiltonian of *continuum.discretize*. 

4695 

4696 Raises 

4697 ------ 

4698 TypeError 

4699 The Hamiltonian must be a string, a sympy expression 

4700 or a sympy Matrix. 

4701 ''' 

4702 if not isinstance(ham, types): 

4703 raise TypeError('\n\nParameter hamiltonian must be a string, a sympy expression ' 

4704 'or a sympy Matrix.\n') 

4705 

4706 

4707def continuum_parsed(error, string): 

4708 ''' 

4709 Check that the string Hamiltonian of *continuum.discretize* was parsed. 

4710 

4711 Raises 

4712 ------ 

4713 ValueError 

4714 The string is not a valid expression. 

4715 ''' 

4716 if error is not None: 

4717 raise ValueError('\n\nParameter hamiltonian {!r} is not a valid sympy expression ' 

4718 '({}: {}).\n'.format(string, type(error).__name__, error)) 

4719 

4720 

4721def continuum_square(shape): 

4722 ''' 

4723 Check that the Hamiltonian of *continuum.discretize* is a square matrix. 

4724 

4725 Raises 

4726 ------ 

4727 ValueError 

4728 The Hamiltonian must be a square matrix. 

4729 ''' 

4730 if len(shape) != 2 or shape[0] != shape[1] or shape[0] == 0: 

4731 raise ValueError('\n\nParameter hamiltonian must be a scalar or a square matrix ' 

4732 '(shape {}).\n'.format(shape)) 

4733 

4734 

4735def continuum_symbols(names): 

4736 ''' 

4737 Check the free symbols of the Hamiltonian of *continuum.discretize*: 

4738 no position (the model is translation invariant), no symbol named 

4739 like the grid spacing *a*, and parameter names that can be passed as 

4740 keyword arguments. 

4741 

4742 Raises 

4743 ------ 

4744 ValueError 

4745 x, y, z are not supported. 

4746 ValueError 

4747 a is reserved for the grid spacing. 

4748 ValueError 

4749 Parameter names must be Python identifiers. 

4750 ''' 

4751 position = sorted(names & {'x', 'y', 'z'}) 

4752 if position: 

4753 raise ValueError('\n\nThe Hamiltonian depends on the position ({}): only translation-' 

4754 'invariant continuum models (constant coefficients) can be ' 

4755 'discretized into a KSpace.\n'.format(', '.join(position))) 

4756 if 'a' in names: 

4757 raise ValueError('\n\nThe symbol a is reserved for the grid spacing: rename the ' 

4758 'parameter.\n') 

4759 bad = sorted(n for n in names if not n.isidentifier() or n in ('site_i', 'site_j')) 

4760 if bad: 

4761 raise ValueError('\n\nParameter names must be Python identifiers (other than site_i, ' 

4762 'site_j), to be passed to get_ham: {}.\n'.format(', '.join(bad))) 

4763 

4764 

4765def continuum_dim(dim, used): 

4766 ''' 

4767 Check the dimension of *continuum.discretize*, given the momenta 

4768 k_x, k_y, k_z (axes 0, 1, 2) used by the Hamiltonian. 

4769 

4770 Raises 

4771 ------ 

4772 TypeError 

4773 Parameter dim must be an integer. 

4774 ValueError 

4775 Parameter dim must be 1, 2 or 3. 

4776 ValueError 

4777 The Hamiltonian uses a momentum beyond dim. 

4778 ''' 

4779 if not isinstance(dim, int): 

4780 raise TypeError('\n\nParameter dim must be an integer.\n') 

4781 if dim not in (1, 2, 3): 

4782 raise ValueError('\n\nParameter dim must be 1, 2 or 3.\n') 

4783 if used and max(used) >= dim: 

4784 raise ValueError('\n\nThe Hamiltonian uses {} in dimension {}.\n'.format( 

4785 ('k_x', 'k_y', 'k_z')[max(used)], dim)) 

4786 

4787 

4788def continuum_polynomial(entry, is_polynomial): 

4789 ''' 

4790 Check that a matrix element of *continuum.discretize* is a polynomial 

4791 in the momenta. 

4792 

4793 Raises 

4794 ------ 

4795 ValueError 

4796 The Hamiltonian must be a polynomial in k_x, k_y, k_z. 

4797 ''' 

4798 if not is_polynomial: 

4799 raise ValueError('\n\nThe Hamiltonian must be a polynomial in k_x, k_y, k_z ' 

4800 '(matrix element {}).\n'.format(entry)) 

4801 

4802 

4803def continuum_tags(tags, norb): 

4804 ''' 

4805 Check the orbital tags of *continuum.discretize*. 

4806 

4807 Raises 

4808 ------ 

4809 ValueError 

4810 More than 52 orbitals need explicit tags. 

4811 TypeError 

4812 Parameter tags must be a string or a list of strings. 

4813 ValueError 

4814 Parameter tags must hold one tag (1 to TAG_LEN characters) per orbital. 

4815 ''' 

4816 if tags is None: 

4817 if norb > 52: 

4818 raise ValueError('\n\nThe Hamiltonian has {} orbitals: pass their tags (default ' 

4819 'tags are the 52 letters).\n'.format(norb)) 

4820 return 

4821 if not isinstance(tags, (str, list, tuple)) or not all(isinstance(t, str) for t in tags): 

4822 raise TypeError('\n\nParameter tags must be a string or a list of strings.\n') 

4823 if len(tags) != norb or not all(1 <= len(t) <= TAG_LEN for t in tags): 

4824 raise ValueError('\n\nParameter tags must hold {} tags of 1 to {} characters, one per ' 

4825 'orbital.\n'.format(norb, TAG_LEN)) 

4826 

4827 

4828def continuum_spacing(a): 

4829 ''' 

4830 Check the grid spacing of *continuum.discretize*: a **Lattice** 

4831 refuses primitive vectors whose squared norm is below 0.1. 

4832 

4833 Raises 

4834 ------ 

4835 ValueError 

4836 Parameter a must be at least sqrt(0.1). 

4837 ''' 

4838 if a * a < 0.1: 

4839 raise ValueError('\n\nParameter a must be at least sqrt(0.1) = 0.316 (the shortest ' 

4840 'primitive vector of a Lattice): measure lengths in a smaller ' 

4841 'unit, and scale the coefficients of the Hamiltonian ' 

4842 'accordingly.\n') 

4843 

4844 

4845#################################### 

4846# WANNIER FUNCTIONS 

4847#################################### 

4848 

4849 

4850def trial_orbitals(trial, norb, n_bands): 

4851 ''' 

4852 Check the trial orbitals of *wannier.wannierize*: a list of orbital 

4853 indices, or an array of shape (norb, n_wann), with at most *n_bands* 

4854 trial orbitals (one per Wannier function; fewer than the bands 

4855 disentangles them). 

4856 

4857 Raises 

4858 ------ 

4859 TypeError 

4860 Parameter trial must be a list of orbital indices or an array. 

4861 ValueError 

4862 Parameter trial must hold between 1 and n_bands trial orbitals. 

4863 ''' 

4864 if isinstance(trial, list) and trial and all(isinstance(o, int) for o in trial): 

4865 if len(trial) > n_bands or not all(0 <= o < norb for o in trial): 

4866 raise ValueError('\n\nParameter trial must hold at most {} orbital indices (one per ' 

4867 'Wannier function, at most one per band) between 0 and {}.\n' 

4868 .format(n_bands, norb - 1)) 

4869 return 

4870 try: 

4871 g = np.asarray(trial, dtype='c16') 

4872 except (TypeError, ValueError): 

4873 raise TypeError('\n\nParameter trial must be a list of orbital indices or a complex ' 

4874 'array of shape (norb, n_wann).\n') from None 

4875 if g.ndim != 2 or g.shape[0] != norb or not 1 <= g.shape[1] <= n_bands: 

4876 raise ValueError('\n\nParameter trial must be an array of shape ({}, n_wann), with ' 

4877 '1 <= n_wann <= {}: one column (trial orbital) per Wannier ' 

4878 'function, at most one per band.\n'.format(norb, n_bands)) 

4879 

4880 

4881def energy_window(window, var_name): 

4882 ''' 

4883 Check an energy window of *wannier.wannierize*: a tuple of two 

4884 increasing real numbers. 

4885 

4886 Raises 

4887 ------ 

4888 TypeError 

4889 Parameter var_name must be a tuple of two real numbers. 

4890 ValueError 

4891 Parameter var_name must be increasing. 

4892 ''' 

4893 if not isinstance(window, tuple) or len(window) != 2 or \ 

4894 not all(isinstance(e, (int, float)) and not isinstance(e, bool) for e in window): 

4895 raise TypeError('\n\nParameter {} must be a tuple (E_min, E_max) of two real ' 

4896 'numbers.\n'.format(var_name)) 

4897 if window[0] >= window[1]: 

4898 raise ValueError('\n\nParameter {} must satisfy E_min < E_max.\n'.format(var_name)) 

4899 

4900 

4901def frozen_window(frozen, window): 

4902 ''' 

4903 Check that the frozen (inner) window of *wannier.wannierize* lies 

4904 inside the outer window. 

4905 

4906 Raises 

4907 ------ 

4908 ValueError 

4909 The frozen window must lie inside the outer window. 

4910 ''' 

4911 if frozen[0] < window[0] or frozen[1] > window[1]: 

4912 raise ValueError('\n\nParameter frozen {} must lie inside the outer window {}.\n' 

4913 .format(frozen, window)) 

4914 

4915 

4916def window_states(n_inside, n_frozen, n_wann): 

4917 ''' 

4918 Check the number of states of the disentanglement windows at every 

4919 k-point: at least *n_wann* in the outer window, at most *n_wann* in the 

4920 frozen window. 

4921 

4922 Raises 

4923 ------ 

4924 ValueError 

4925 The outer window holds fewer than n_wann states at some k-point. 

4926 ValueError 

4927 The frozen window holds more than n_wann states at some k-point. 

4928 ''' 

4929 if n_inside < n_wann: 

4930 raise ValueError('\n\nThe outer window holds only {} of the bands at some k-point, ' 

4931 'fewer than the {} Wannier functions: widen it, or add bands.\n' 

4932 .format(n_inside, n_wann)) 

4933 if n_frozen > n_wann: 

4934 raise ValueError('\n\nThe frozen window holds {} bands at some k-point, more than the ' 

4935 '{} Wannier functions: narrow it.\n'.format(n_frozen, n_wann)) 

4936 

4937 

4938def isolated_bands(en, bands, tol=1e-8): 

4939 ''' 

4940 Check that a group of bands is separated in energy from the other bands 

4941 at every point of the mesh (*en*, shape (nk, norb), sorted). 

4942 

4943 Raises 

4944 ------ 

4945 ValueError 

4946 The bands are not isolated. 

4947 ''' 

4948 inside = np.zeros(en.shape[1], bool) 

4949 inside[bands] = True 

4950 for n in range(en.shape[1] - 1): 

4951 if inside[n] != inside[n + 1] and np.min(en[:, n + 1] - en[:, n]) < tol: 

4952 raise ValueError('\n\nThe bands {} touch band {} on the k-mesh: Wannier functions ' 

4953 'need an isolated group of bands: add the bands they touch to the group, ' 

4954 'or disentangle them (more bands than trial orbitals).\n' 

4955 .format(bands, n + 1 if inside[n] else n)) 

4956 

4957 

4958def projection(s_min, tol=1e-10): 

4959 ''' 

4960 Check that the projection of the bands onto the trial orbitals has full 

4961 rank at every k-point. 

4962 

4963 Raises 

4964 ------ 

4965 ValueError 

4966 The trial orbitals miss the bands at some k-point. 

4967 ''' 

4968 if s_min < tol: 

4969 raise ValueError('\n\nThe trial orbitals have no overlap with the bands at some ' 

4970 'k-point (singular projection): choose other trial orbitals, or ' 

4971 'another mesh. A band group with a nonzero Chern number has no ' 

4972 'localized Wannier functions, and any projection vanishes ' 

4973 'somewhere.\n') 

4974 

4975 

4976 

4977def invertible_coupling(v, cond_max=1e12): 

4978 ''' 

4979 Check that the coupling to the farthest slice of a strip is invertible, 

4980 as the transfer matrix needs. 

4981 

4982 Raises 

4983 ------ 

4984 ValueError 

4985 The last coupling is singular. 

4986 ''' 

4987 if np.linalg.cond(v) > cond_max: 

4988 raise ValueError('\n\nThe coupling to the farthest slice is singular, so the transfer matrix ' 

4989 'does not exist: group several cells into one slice (e.g. two cells of a ' 

4990 'zigzag ribbon), or pass the couplings to more slices.\n') 

4991 

4992 

4993def transfer_chunks(n_chunks, n_slices, qr_every): 

4994 ''' 

4995 Check the number of pieces of a strip for the error of its Lyapunov 

4996 exponents: an integer of at least 2, each piece holding at least 

4997 *qr_every* slices. 

4998 

4999 Raises 

5000 ------ 

5001 TypeError 

5002 Parameter n_chunks must be an integer. 

5003 ValueError 

5004 Parameter n_chunks must be at least 2. 

5005 ValueError 

5006 Each chunk needs at least qr_every slices. 

5007 ''' 

5008 if not isinstance(n_chunks, int): 

5009 raise TypeError('\n\nParameter n_chunks must be an integer.\n') 

5010 if n_chunks < 2: 

5011 raise ValueError('\n\nParameter n_chunks must be at least 2.\n') 

5012 if n_slices < n_chunks * qr_every: 

5013 raise ValueError('\n\nParameter n_slices must be at least n_chunks * qr_every ' 

5014 '({}).\n'.format(n_chunks * qr_every)) 

5015 

5016 

5017#################################### 

5018# EXACT DIAGONALIZATION (tbkit.manybody, twisted tori) 

5019#################################### 

5020 

5021 

5022def twist(twist, dim, periodic): 

5023 ''' 

5024 Check the twist angles of *KSpace.finite_ham*: one real angle per 

5025 dimension, on a periodic sample. 

5026 

5027 Raises 

5028 ------ 

5029 ValueError 

5030 Parameter twist must hold dim real angles. 

5031 ValueError 

5032 Twisted boundary conditions need periodic=True. 

5033 ''' 

5034 if twist.shape != (dim,) or not np.all(np.isfinite(twist)): 

5035 raise ValueError('\n\nParameter twist must hold {} real angles.\n'.format(dim)) 

5036 if not periodic: 

5037 raise ValueError('\n\nTwisted boundary conditions need periodic=True.\n') 

5038 

5039 

5040def fock_sector(n_sites, n_up, n_dn): 

5041 ''' 

5042 Check a sector of fixed particle numbers: at most 62 sites (the bit 

5043 patterns are 64-bit integers), and between 0 and *n_sites* fermions of 

5044 each spin (*n_dn* None for spinless fermions). 

5045 

5046 Raises 

5047 ------ 

5048 TypeError 

5049 Parameters must be integers. 

5050 ValueError 

5051 Parameter n_sites must be at most 62. 

5052 ValueError 

5053 The numbers of fermions must be between 0 and n_sites. 

5054 ''' 

5055 positive_int(n_sites, 'n_sites') 

5056 if n_sites > 62: 

5057 raise ValueError('\n\nParameter n_sites must be at most 62.\n') 

5058 for var, name in ((n_up, 'n_up'), (n_dn, 'n_dn')): 

5059 if name == 'n_dn' and var is None: 

5060 continue 

5061 positive_int_zero(var, name) 

5062 if var > n_sites: 

5063 raise ValueError('\n\nParameter {} must be at most the number of sites ({}).\n' 

5064 ''.format(name, n_sites)) 

5065 

5066 

5067def spinless_onsite(u, spinless): 

5068 ''' 

5069 Check that spinless fermions get no onsite repulsion. 

5070 

5071 Raises 

5072 ------ 

5073 ValueError 

5074 Spinless fermions have no onsite interaction U. 

5075 ''' 

5076 if spinless and np.any(u != 0): 

5077 raise ValueError('\n\nSpinless fermions have no onsite interaction U: use V.\n') 

5078 

5079 

5080def density_interaction(v, n_sites): 

5081 ''' 

5082 Check a density-density interaction: a real symmetric (N, N) matrix 

5083 with zero diagonal. 

5084 

5085 Raises 

5086 ------ 

5087 ValueError 

5088 Parameter V must be a real symmetric (N, N) matrix with zero diagonal. 

5089 ''' 

5090 if (v.shape != (n_sites, n_sites) or np.iscomplexobj(v) or not np.allclose(v, v.T) 

5091 or np.any(np.diag(v) != 0)): 

5092 raise ValueError('\n\nParameter V must be a real symmetric ({0}, {0}) matrix with zero ' 

5093 'diagonal (the onsite term is U).\n'.format(n_sites)) 

5094 

5095 

5096def n_states(n_states, dim): 

5097 ''' 

5098 Check the number of eigenstates asked of a sector of dimension *dim*. 

5099 

5100 Raises 

5101 ------ 

5102 ValueError 

5103 Parameter n_states must be at most the dimension of the sector. 

5104 ''' 

5105 if n_states > dim: 

5106 raise ValueError('\n\nParameter n_states must be at most the dimension of the ' 

5107 'sector ({}).\n'.format(dim)) 

5108 

5109 

5110def state_index(state, n_states): 

5111 ''' 

5112 Check the index of an eigenstate of *exact_diagonalization*. 

5113 

5114 Raises 

5115 ------ 

5116 TypeError 

5117 Parameter state must be an integer. 

5118 ValueError 

5119 Parameter state must be between 0 and n_states - 1. 

5120 ''' 

5121 positive_int_zero(state, 'state') 

5122 if state >= n_states: 

5123 raise ValueError('\n\nParameter state must be smaller than the number of states ' 

5124 'computed ({}).\n'.format(n_states)) 

5125 

5126 

5127def spinful_sector(spinless): 

5128 ''' 

5129 Check that a spin observable is asked of spinful fermions. 

5130 

5131 Raises 

5132 ------ 

5133 ValueError 

5134 Spinless fermions have no spin. 

5135 ''' 

5136 if spinless: 

5137 raise ValueError('\n\nSpinless fermions have no spin: pass n_dn.\n') 

5138 

5139 

5140def orthonormal_states(phi): 

5141 ''' 

5142 Check single-particle states for a projection: a 2D array of 

5143 orthonormal columns. 

5144 

5145 Raises 

5146 ------ 

5147 ValueError 

5148 Parameter states must be a 2D array of orthonormal columns. 

5149 ''' 

5150 if phi.ndim != 2 or not np.allclose(phi.conj().T @ phi, np.eye(phi.shape[1]), atol=1e-8): 

5151 raise ValueError('\n\nParameter states must be a 2D array of orthonormal columns ' 

5152 '(one single-particle state each).\n') 

5153 

5154 

5155def two_body(w, n_sites): 

5156 ''' 

5157 Check a two-body interaction W: shape (N, N, N, N), Hermitian 

5158 (W_abcd = conj(W_cdab)). 

5159 

5160 Raises 

5161 ------ 

5162 ValueError 

5163 Parameter W must have shape (N, N, N, N). 

5164 ValueError 

5165 Parameter W must be Hermitian. 

5166 ''' 

5167 if w.shape != (n_sites,) * 4: 

5168 raise ValueError('\n\nParameter W must have shape ({0}, {0}, {0}, {0}).\n'.format(n_sites)) 

5169 if not np.allclose(w, w.transpose(2, 3, 0, 1).conj(), atol=1e-10): 

5170 raise ValueError('\n\nParameter W must be Hermitian: W[a, b, c, d] = conj(W[c, d, a, b]).\n') 

5171 

5172 

5173def spinless_two_body(w): 

5174 ''' 

5175 Check that a general two-body interaction is given for spinless fermions. 

5176 

5177 Raises 

5178 ------ 

5179 ValueError 

5180 Parameter W needs spinless fermions. 

5181 ''' 

5182 if w is not None: 

5183 raise ValueError('\n\nParameter W needs spinless fermions (n_dn=None): put the spin ' 

5184 'in the orbitals.\n') 

5185 

5186 

5187def momentum_sector(momentum, n_sites, spinless): 

5188 ''' 

5189 Check a momentum sector (labels, n_cells, total) of *FockSector*. 

5190 

5191 Raises 

5192 ------ 

5193 ValueError 

5194 A momentum sector needs spinless fermions. 

5195 ValueError 

5196 Parameter momentum must be a tuple (labels, n_cells, total). 

5197 ValueError 

5198 The labels must be integers, one row per orbital. 

5199 ValueError 

5200 n_cells must be positive and total must have one entry per dimension. 

5201 ''' 

5202 if not spinless: 

5203 raise ValueError('\n\nA momentum sector needs spinless fermions (n_dn=None).\n') 

5204 if not isinstance(momentum, tuple) or len(momentum) != 3: 

5205 raise ValueError('\n\nParameter momentum must be a tuple (labels, n_cells, total).\n') 

5206 labels = np.asarray(momentum[0]) 

5207 if labels.dtype.kind not in 'iu' or len(labels) != n_sites or labels.ndim not in (1, 2): 

5208 raise ValueError('\n\nThe momentum labels must be integers, one row per orbital ' 

5209 '({} rows).\n'.format(n_sites)) 

5210 d = 1 if labels.ndim == 1 else labels.shape[1] 

5211 cells, total = np.asarray(momentum[1]), np.asarray(momentum[2]) 

5212 if (cells.dtype.kind not in 'iu' or total.dtype.kind not in 'iu' or cells.size not in (1, d) 

5213 or total.size not in (1, d) or np.any(cells < 1)): 

5214 raise ValueError('\n\nThe n_cells (positive) and total of a momentum sector must be ' 

5215 'integers, one per dimension ({}).\n'.format(d)) 

5216 

5217 

5218def conserves_momentum(h, w, labels, cells, total): 

5219 ''' 

5220 Check that the one-body matrix *h* (and the two-body *w*, if given) 

5221 conserve the crystal momentum of the orbitals. 

5222 

5223 Raises 

5224 ------ 

5225 ValueError 

5226 The Hamiltonian mixes momentum sectors. 

5227 ''' 

5228 def differ(*pairs): 

5229 out = 0 

5230 for sign, lab in pairs: 

5231 out = out + sign * lab 

5232 return np.any(out % cells != 0, axis=-1) 

5233 

5234 a = labels 

5235 tol = 1e-10 * max(1., float(np.max(np.abs(h)))) 

5236 bad = np.any((np.abs(h) > tol) & differ((1, a[:, None]), (-1, a[None, :]))) 

5237 if w is not None: 

5238 tol = 1e-10 * max(1., float(np.max(np.abs(w)))) 

5239 moved = differ((1, a[:, None, None, None]), (1, a[None, :, None, None]), 

5240 (-1, a[None, None, :, None]), (-1, a[None, None, None, :])) 

5241 bad = bad or np.any((np.abs(w) > tol) & moved) 

5242 if bad: 

5243 raise ValueError('\n\nThe Hamiltonian mixes momentum sectors: check the momentum ' 

5244 'labels of the orbitals.\n') 

5245 

5246 

5247#################################### 

5248# CRYSTAL SYMMETRY (tbkit.symmetry) 

5249#################################### 

5250 

5251 

5252def operation(rotation, translation, orbitals, antiunitary, name): 

5253 ''' 

5254 Check the parameters of *symmetry.Operation*. 

5255 

5256 Raises 

5257 ------ 

5258 ValueError 

5259 Parameter rotation must be an orthogonal (d, d) matrix, d = 1, 2 or 3. 

5260 ValueError 

5261 Parameter translation must be a vector of d real numbers. 

5262 ValueError 

5263 Parameter orbitals must be a square unitary matrix. 

5264 TypeError 

5265 Parameter antiunitary must be a bool; parameter name a string. 

5266 ''' 

5267 rot = np.asarray(rotation) 

5268 if (rot.ndim != 2 or rot.shape[0] != rot.shape[1] or rot.shape[0] not in (1, 2, 3) 

5269 or not np.isrealobj(rot) or not np.allclose(rot @ rot.T, np.eye(len(rot)), atol=1e-6)): 

5270 raise ValueError('\n\nParameter rotation must be an orthogonal (d, d) real matrix, ' 

5271 'd = 1, 2 or 3.\n') 

5272 if translation is not None: 

5273 t = np.asarray(translation) 

5274 if t.shape != (len(rot),) or not np.isrealobj(t): 

5275 raise ValueError('\n\nParameter translation must be a vector of {} real numbers.\n' 

5276 ''.format(len(rot))) 

5277 if orbitals is not None: 

5278 d = np.asarray(orbitals) 

5279 if (d.ndim != 2 or d.shape[0] != d.shape[1] 

5280 or not np.allclose(d.conj().T @ d, np.eye(len(d)), atol=1e-6)): 

5281 raise ValueError('\n\nParameter orbitals must be a square unitary matrix.\n') 

5282 boolean(antiunitary, 'antiunitary') 

5283 if name is not None and not isinstance(name, str): 

5284 raise TypeError('\n\nParameter name must be a string.\n') 

5285 

5286 

5287def is_operation(op): 

5288 ''' 

5289 Check that *op* is a *symmetry.Operation*. 

5290 

5291 Raises 

5292 ------ 

5293 TypeError 

5294 The operation must be a tbkit.symmetry.Operation. 

5295 ''' 

5296 from tbkit.symmetry import Operation 

5297 if not isinstance(op, Operation): 

5298 raise TypeError('\n\nThe operation must be a tbkit.symmetry.Operation.\n') 

5299 

5300 

5301def operations(ops): 

5302 ''' 

5303 Check a non-empty list of *symmetry.Operation*. 

5304 

5305 Raises 

5306 ------ 

5307 TypeError 

5308 Parameter ops must be a non-empty list of Operation. 

5309 ''' 

5310 if not isinstance(ops, list) or not ops: 

5311 raise TypeError('\n\nParameter ops must be a non-empty list of tbkit.symmetry.Operation.\n') 

5312 for op in ops: 

5313 is_operation(op) 

5314 

5315 

5316def compose(a, b): 

5317 ''' 

5318 Check that two operations can be multiplied: same dimension, and both 

5319 or neither with an orbital matrix (of the same size). 

5320 

5321 Raises 

5322 ------ 

5323 ValueError 

5324 The operations act in different dimensions, or on different orbitals. 

5325 ''' 

5326 is_operation(b) 

5327 if len(a.rotation) != len(b.rotation): 

5328 raise ValueError('\n\nThe two operations act in different dimensions.\n') 

5329 if (a.orbitals is None) != (b.orbitals is None) or ( 

5330 a.orbitals is not None and a.orbitals.shape != b.orbitals.shape): 

5331 raise ValueError('\n\nThe two operations must both give orbital matrices of the same ' 

5332 'size, or neither.\n') 

5333 

5334 

5335def nonzero_vector(vec, var_name): 

5336 ''' 

5337 Check that *vec* is a nonzero vector. 

5338 

5339 Raises 

5340 ------ 

5341 ValueError 

5342 Parameter var_name must be a nonzero vector. 

5343 ''' 

5344 if not np.any(vec): 

5345 raise ValueError('\n\nParameter {} must be a nonzero vector.\n'.format(var_name)) 

5346 

5347 

5348def operation_space(op, space_dim): 

5349 ''' 

5350 Check that an operation acts in the space of the model. 

5351 

5352 Raises 

5353 ------ 

5354 ValueError 

5355 The operation must be a (space_dim, space_dim) rotation. 

5356 ''' 

5357 if len(op.rotation) != space_dim: 

5358 raise ValueError('\n\nThe operation must act in {} dimensions (that of the ' 

5359 'positions of the model).\n'.format(space_dim)) 

5360 

5361 

5362def maps_lattice(ok): 

5363 ''' 

5364 Check that an operation sends every position of the unit cell onto a 

5365 position of the crystal (*ok*: (n, n) booleans, source by target). 

5366 

5367 Raises 

5368 ------ 

5369 ValueError 

5370 The operation does not map the orbitals onto orbitals of the crystal. 

5371 ''' 

5372 if not np.all(ok.sum(axis=1) == 1) or not np.all(ok.sum(axis=0) == 1): 

5373 raise ValueError('\n\nThe operation does not map the orbital positions onto ' 

5374 'orbital positions of the crystal.\n') 

5375 

5376 

5377def block_sizes(sizes, perm, m): 

5378 ''' 

5379 Check that an operation maps every position onto one with as many 

5380 orbitals, and that its orbital matrix (size *m*, or None) fits them. 

5381 

5382 Raises 

5383 ------ 

5384 ValueError 

5385 The positions exchanged carry different numbers of orbitals. 

5386 ValueError 

5387 The orbital matrix does not match the orbitals of a position. 

5388 ''' 

5389 if any(sizes[p] != s for s, p in zip(sizes, perm)): 

5390 raise ValueError('\n\nThe operation exchanges positions with different numbers of ' 

5391 'orbitals.\n') 

5392 if m is not None and any(s != m for s in sizes): 

5393 raise ValueError('\n\nThe orbital matrix must be ({0}, {0}): one row per orbital at ' 

5394 'each position.\n'.format(sizes[0])) 

5395 

5396 

5397def full_dim(dim, space_dim): 

5398 ''' 

5399 Check that the lattice fills its space (as many primitive vectors as 

5400 coordinates). 

5401 

5402 Raises 

5403 ------ 

5404 ValueError 

5405 This needs a lattice that fills its space. 

5406 ''' 

5407 if dim != space_dim: 

5408 raise ValueError('\n\nThis needs a lattice with as many primitive vectors as ' 

5409 'coordinates.\n') 

5410 

5411 

5412def callable_or_none(func, var_name): 

5413 ''' 

5414 Check that *func* is callable or None. 

5415 

5416 Raises 

5417 ------ 

5418 TypeError 

5419 Parameter var_name must be callable or None. 

5420 ''' 

5421 if func is not None and not callable(func): 

5422 raise TypeError('\n\nParameter {} must be callable or None.\n'.format(var_name)) 

5423 

5424 

5425def spinless_irreps(spin): 

5426 ''' 

5427 Check that the model has no spin (the double groups are not tabulated). 

5428 

5429 Raises 

5430 ------ 

5431 ValueError 

5432 This needs a spinless model. 

5433 ''' 

5434 if spin: 

5435 raise ValueError('\n\nThis needs a spinless model (the double groups of spin 1/2 ' 

5436 'are not tabulated).\n') 

5437 

5438 

5439def dim_irreps(dim): 

5440 ''' 

5441 Check that the model is 2D or 3D. 

5442 

5443 Raises 

5444 ------ 

5445 ValueError 

5446 Irreps are tabulated in 2D and 3D. 

5447 ''' 

5448 if dim not in (2, 3): 

5449 raise ValueError('\n\nThe point groups are tabulated in 2D and 3D only.\n') 

5450 

5451 

5452def symmorphic(residual): 

5453 ''' 

5454 Check that the little group is made of rotations about one point. 

5455 

5456 Raises 

5457 ------ 

5458 ValueError 

5459 The little group is not symmorphic about one point. 

5460 ''' 

5461 if residual > 1e-6: 

5462 raise ValueError('\n\nThe operations are not rotations about one common point: ' 

5463 'nonsymmorphic groups are not covered, and a rotation about c needs ' 

5464 'translation c - R c exactly (see Operation.about).\n') 

5465 

5466 

5467def tabulated(res): 

5468 ''' 

5469 Check that the point group of a little group is tabulated. 

5470 

5471 Raises 

5472 ------ 

5473 ValueError 

5474 Point group not tabulated. 

5475 ''' 

5476 if res is None: 

5477 raise ValueError('\n\nThis point group is not tabulated (in 3D, only the cubic ' 

5478 'groups T, Th, O, Td, Oh are).\n') 

5479 

5480 

5481def multiplicities(mult): 

5482 ''' 

5483 Check that the irrep multiplicities are non-negative integers. 

5484 

5485 Raises 

5486 ------ 

5487 ValueError 

5488 The characters do not decompose into irreps. 

5489 ''' 

5490 if np.any(np.abs(mult - np.round(mult.real)) > 1e-3) or np.any(np.round(mult.real) < 0): 

5491 raise ValueError('\n\nThe characters do not decompose into irreps: a level is not ' 

5492 'invariant (raise deg_tol), or an operation is not a symmetry.\n') 

5493 

5494 

5495def proper_rotation(op): 

5496 ''' 

5497 Check that an operation is a unitary 2D rotation C_n, n = 2, 3, 4 or 6. 

5498 

5499 Raises 

5500 ------ 

5501 ValueError 

5502 The operation must be a unitary rotation C_n (n = 2, 3, 4, 6). 

5503 ''' 

5504 rot = op.rotation 

5505 ok = len(rot) == 2 and not op.antiunitary and np.linalg.det(rot) > 0 

5506 if ok: 

5507 theta = abs(np.arctan2(rot[1, 0], rot[0, 0])) 

5508 ok = theta > 1e-6 and any(abs(theta - 2 * np.pi / n) < 1e-6 for n in (2, 3, 4, 6)) 

5509 if not ok: 

5510 raise ValueError('\n\nThe operation must be a unitary 2D rotation C_n, n = 2, 3, 4 or 6.\n') 

5511 

5512 

5513def corner_rotation(n): 

5514 ''' 

5515 Check that the rotation of *corner_charge* is C_4. 

5516 

5517 Raises 

5518 ------ 

5519 ValueError 

5520 The corner charge is given for C_4. 

5521 ''' 

5522 if n != 4: 

5523 raise ValueError('\n\nThe corner charge is given for a C_4 rotation.\n') 

5524 

5525 

5526def cell_rotation(L): 

5527 ''' 

5528 Check that an operation maps the orbitals of the unit cell onto 

5529 themselves (no lattice vector L_s): a rotation about the cell centre. 

5530 

5531 Raises 

5532 ------ 

5533 ValueError 

5534 The rotation must be about the centre of the unit cell. 

5535 ''' 

5536 if np.any(L): 

5537 raise ValueError('\n\nThe rotation must be about the centre of the unit cell: it must ' 

5538 'map the orbitals of the unit cell onto themselves.\n') 

5539 

5540 

5541def inversion_operation(op): 

5542 ''' 

5543 Check that an operation is the (unitary) inversion. 

5544 

5545 Raises 

5546 ------ 

5547 ValueError 

5548 The operation must be the inversion. 

5549 ''' 

5550 if op.antiunitary or not np.allclose(op.rotation, -np.eye(len(op.rotation))): 

5551 raise ValueError('\n\nThe operation must be the inversion (rotation -1, unitary).\n') 

5552 

5553 

5554def invariant_bands(singular_values, tol=1e-6): 

5555 ''' 

5556 Check that the bands are an invariant subspace of an operation. 

5557 

5558 Raises 

5559 ------ 

5560 ValueError 

5561 The bands are not invariant under the operation. 

5562 ''' 

5563 if not np.allclose(singular_values, 1., atol=tol): 

5564 raise ValueError('\n\nThe bands are not invariant under the operation: they touch ' 

5565 'other bands at a rotation-invariant point.\n') 

5566 

5567 

5568def rotation_power(u_n, tol=1e-6): 

5569 ''' 

5570 Check that the n-th power of a C_n rotation is +1 or -1 (spin 1/2), 

5571 and return that sign. 

5572 

5573 Raises 

5574 ------ 

5575 ValueError 

5576 U^n must be +1 or -1. 

5577 ''' 

5578 for sign in (1, -1): 

5579 if np.allclose(u_n, sign * np.eye(len(u_n)), atol=tol): 

5580 return sign 

5581 raise ValueError('\n\nThe n-th power of the rotation C_n must be +1 or -1 on the orbitals.\n') 

5582 

5583 

5584def quantized(x, what, tol=1e-3): 

5585 ''' 

5586 Check that *x* is close to an integer. 

5587 

5588 Raises 

5589 ------ 

5590 ValueError 

5591 The product of the eigenvalues is not quantized. 

5592 ''' 

5593 if abs(x - round(x)) > tol: 

5594 raise ValueError('\n\nThe {} do not give a quantized result.\n'.format(what)) 

5595 

5596 

5597def group_size(n, nmax=192): 

5598 ''' 

5599 Check the size of a group being generated. 

5600 

5601 Raises 

5602 ------ 

5603 ValueError 

5604 The operations generate more than nmax elements. 

5605 ''' 

5606 if n > nmax: 

5607 raise ValueError('\n\nThe operations generate more than {} elements: they are not a ' 

5608 'crystallographic group of the model.\n'.format(nmax))