Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

103

104

105

106

107

108

109

110

111

112

113

114

115

116

117

118

119

120

121

122

123

124

125

126

127

128

129

130

131

132

133

134

135

136

137

138

139

140

141

142

143

144

145

146

147

148

149

150

151

152

153

154

155

156

157

158

159

160

161

162

163

164

165

166

167

168

169

170

171

172

173

174

175

176

177

178

179

180

181

182

183

184

185

186

187

188

189

190

191

192

193

194

195

196

197

198

199

200

201

202

203

204

205

206

207

208

209

210

211

212

213

214

215

216

217

218

219

220

221

222

223

224

225

226

227

228

229

230

231

232

233

234

235

236

237

238

239

240

241

242

243

244

245

246

247

248

249

250

251

252

253

254

255

256

257

258

259

260

261

262

263

264

265

266

267

268

269

270

271

272

273

274

275

276

277

278

279

280

281

282

283

284

285

286

287

288

289

290

291

292

293

294

295

296

297

298

299

300

301

302

303

304

305

306

307

308

309

310

311

312

313

314

315

316

317

318

319

320

321

322

323

324

325

326

327

328

329

330

331

332

333

334

335

336

337

338

339

340

341

342

343

344

345

346

347

348

349

350

351

352

353

354

355

356

357

358

359

360

361

362

363

364

365

366

367

368

369

370

371

372

373

374

375

376

377

378

379

380

381

382

383

384

385

386

387

388

389

390

391

392

393

394

395

396

397

398

399

400

401

402

403

404

405

406

407

408

409

410

411

412

413

414

415

416

417

418

419

420

421

422

423

424

425

426

427

428

429

430

431

432

433

434

435

436

437

438

439

440

441

442

443

444

445

446

447

448

449

450

451

452

453

454

455

456

457

458

459

460

461

462

463

464

465

466

467

468

469

470

471

472

473

474

475

476

477

478

479

480

481

482

483

484

485

486

487

488

489

490

491

492

493

494

495

496

497

498

499

500

501

502

503

504

505

506

507

508

509

510

511

512

513

514

515

516

517

518

519

520

521

522

523

524

525

526

527

528

529

530

531

532

533

534

535

536

537

538

539

540

541

542

543

544

545

546

547

548

549

550

551

552

553

554

555

556

557

558

559

560

561

562

563

564

565

566

567

568

569

570

571

572

573

574

575

576

577

578

579

580

581

582

583

584

585

586

587

588

589

590

591

592

593

594

595

596

597

598

599

600

601

602

603

604

605

606

607

608

609

610

611

612

613

614

615

616

617

618

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

1865

1866

1867

1868

1869

1870

1871

1872

1873

1874

1875

1876

1877

1878

1879

1880

1881

1882

1883

1884

1885

1886

1887

1888

1889

1890

1891

1892

1893

1894

1895

1896

1897

1898

1899

1900

1901

1902

1903

1904

1905

1906

1907

1908

1909

1910

1911

1912

1913

1914

1915

1916

1917

1918

1919

1920

1921

1922

1923

1924

1925

1926

1927

1928

1929

1930

1931

1932

1933

1934

1935

1936

1937

1938

1939

1940

1941

1942

1943

1944

1945

1946

1947

1948

1949

1950

1951

1952

1953

1954

1955

1956

1957

1958

1959

1960

1961

1962

1963

1964

1965

1966

1967

1968

1969

1970

1971

1972

1973

1974

1975

1976

1977

1978

1979

1980

1981

1982

1983

1984

1985

1986

1987

1988

1989

1990

1991

1992

1993

1994

1995

1996

1997

1998

1999

2000

2001

2002

2003

2004

2005

2006

2007

2008

2009

2010

2011

2012

2013

2014

2015

2016

2017

2018

2019

2020

2021

2022

2023

2024

2025

2026

2027

2028

2029

2030

2031

2032

2033

2034

2035

2036

2037

2038

2039

2040

2041

2042

2043

2044

2045

2046

2047

2048

2049

2050

2051

2052

2053

2054

2055

2056

2057

2058

2059

2060

2061

2062

2063

2064

2065

2066

2067

2068

2069

2070

2071

2072

2073

2074

2075

2076

2077

2078

2079

2080

2081

2082

2083

2084

2085

2086

2087

2088

2089

2090

2091

2092

2093

2094

2095

2096

2097

2098

2099

2100

2101

2102

2103

2104

2105

2106

2107

2108

2109

2110

2111

2112

2113

2114

2115

2116

2117

2118

2119

2120

2121

2122

2123

2124

2125

2126

2127

2128

2129

2130

2131

2132

2133

2134

2135

2136

2137

2138

2139

2140

2141

2142

2143

2144

2145

2146

2147

2148

2149

2150

2151

2152

2153

2154

2155

2156

2157

2158

2159

2160

2161

2162

2163

2164

2165

2166

2167

2168

2169

2170

2171

2172

2173

2174

2175

2176

2177

2178

2179

2180

2181

2182

2183

2184

2185

2186

2187

2188

2189

2190

2191

2192

2193

2194

2195

2196

2197

2198

2199

2200

2201

2202

2203

2204

2205

2206

2207

2208

2209

2210

2211

2212

2213

2214

2215

2216

2217

2218

2219

2220

2221

2222

2223

2224

2225

2226

2227

2228

2229

2230

2231

2232

2233

2234

2235

2236

2237

2238

2239

2240

2241

2242

2243

2244

2245

2246

2247

2248

2249

2250

2251

2252

2253

2254

2255

2256

2257

2258

# -*- coding: utf-8 -*- 

# Copyright 2011-2018 Kwant authors. 

# 

# This file is part of Kwant. It is subject to the license terms in the file 

# LICENSE.rst found in the top-level directory of this distribution and at 

# http://kwant-project.org/license. A list of Kwant authors can be found in 

# the file AUTHORS.rst at the top-level directory of this distribution and at 

# http://kwant-project.org/authors. 

 

"""Plotter module for Kwant. 

 

This module provides iterators useful for any plotter routine, such as a list 

of system sites, their coordinates, lead sites at any lead unit cell, etc. If 

`matplotlib` is available, it also provides simple functions for plotting the 

system in two or three dimensions. 

""" 

 

from collections import defaultdict 

import sys 

import itertools 

import functools 

import warnings 

import cmath 

import numpy as np 

import tinyarray as ta 

from scipy import spatial, interpolate 

from math import cos, sin, pi, sqrt 

 

from . import system, builder, _common 

from ._common import deprecate_args 

 

 

__all__ = ['plot', 'map', 'bands', 'spectrum', 'current', 'density', 

'interpolate_current', 'interpolate_density', 

'streamplot', 'scalarplot', 

'sys_leads_sites', 'sys_leads_hoppings', 'sys_leads_pos', 

'sys_leads_hopping_pos', 'mask_interpolate'] 

 

# All the expensive imports are done in _plotter.py. We lazy load the module 

# to avoid slowing down the initial import of Kwant. 

_p = _common.lazy_import('_plotter') 

 

 

def _sample_array(array, n_samples, rng=None): 

rng = _common.ensure_rng(rng) 

la = len(array) 

return array[rng.choice(range(la), min(n_samples, la), replace=False)] 

 

 

# matplotlib helper functions. 

 

def _color_cycle(): 

"""Infinitely cycle through colors from the matplotlib color cycle.""" 

props = _p.matplotlib.rcParams['axes.prop_cycle'] 

return itertools.cycle(x['color'] for x in props) 

 

 

def _make_figure(dpi, fig_size, use_pyplot=False): 

59 ↛ 60line 59 didn't jump to line 60, because the condition on line 59 was never true if 'matplotlib.backends' not in sys.modules: 

warnings.warn( 

"Kwant's plotting functions have\nthe side effect of " 

"selecting the matplotlib backend. To avoid this " 

"warning,\nimport matplotlib.pyplot, " 

"matplotlib.backends or call matplotlib.use().", 

RuntimeWarning, stacklevel=3 

) 

67 ↛ 72line 67 didn't jump to line 72, because the condition on line 67 was never true if use_pyplot: 

# We import backends and pyplot only at the last possible moment (=now) 

# because this has the side effect of selecting the matplotlib backend 

# for good. Warn if backend has not been set yet. This check is the 

# same as the one performed inside matplotlib.use. 

from matplotlib import pyplot 

fig = pyplot.figure() 

else: 

from matplotlib.backends.backend_agg import FigureCanvasAgg 

fig = _p.Figure() 

fig.canvas = FigureCanvasAgg(fig) 

if dpi is not None: 

fig.set_dpi(dpi) 

if fig_size is not None: 

fig.set_figwidth(fig_size[0]) 

fig.set_figheight(fig_size[1]) 

return fig 

 

 

def _maybe_output_fig(fig, file=None, show=True): 

"""Output a matplotlib figure using a given output mode. 

 

Parameters 

---------- 

fig : matplotlib.figure.Figure instance 

The figure to be output. 

file : string or a file object 

The name of the target file or the target file itself 

(opened for writing). 

show : bool 

Whether to call ``matplotlib.pyplot.show()``. Only has an effect if 

not saving to a file. 

 

Notes 

----- 

The behavior of this function producing a file is different from that of 

matplotlib in that the `dpi` attribute of the figure is used by defaul 

instead of the matplotlib config setting. 

""" 

if fig is None: 

return 

 

109 ↛ 111line 109 didn't jump to line 111, because the condition on line 109 was never false if file is not None: 

fig.canvas.print_figure(file, dpi=fig.dpi) 

elif show: 

# If there was no file provided, pyplot should already be available and 

# we can import it safely without additional warnings. 

from matplotlib import pyplot 

pyplot.show() 

 

 

def set_colors(color, collection, cmap, norm=None): 

"""Process a color specification to a format accepted by collections. 

 

Parameters 

---------- 

color : color specification 

collection : instance of a subclass of ``matplotlib.collections.Collection`` 

Collection to which the color is added. 

cmap : ``matplotlib`` color map specification or None 

Color map to be used if colors are specified as floats. 

norm : ``matplotlib`` color norm 

Norm to be used if colors are specified as floats. 

""" 

 

length = max(len(collection.get_paths()), len(collection.get_offsets())) 

 

# matplotlib gets confused if dtype='object' 

135 ↛ 136line 135 didn't jump to line 136, because the condition on line 135 was never true if (isinstance(color, np.ndarray) and color.dtype == np.dtype('object')): 

color = tuple(color) 

 

138 ↛ 139line 138 didn't jump to line 139, because the condition on line 138 was never true if _p.has3d and isinstance(collection, _p.mplot3d.art3d.Line3DCollection): 

length = len(collection._segments3d) # Once again, matplotlib fault! 

 

if _p.isarray(color) and len(color) == length: 

try: 

# check if it is an array of floats for color mapping 

color = np.asarray(color, dtype=float) 

if color.ndim == 1: 

collection.set_array(color) 

collection.set_cmap(cmap) 

collection.set_norm(norm) 

collection.set_color(None) 

return 

except (TypeError, ValueError): 

pass 

 

colors = _p.matplotlib.colors.colorConverter.to_rgba_array(color) 

collection.set_color(colors) 

 

 

def percentile_bound(data, vmin, vmax, percentile=96, stretch=0.1): 

"""Return the bounds that captures at least 'percentile' of 'data'. 

 

If 'vmin' or 'vmax' are provided, then the corresponding bound is 

exactly 'vmin' or 'vmax'. First we set the bounds such that the 

provided percentile of the data is within them. Then we try to 

extend the bounds to cover all the data, maximally stretching each 

bound by a factor 'stretch'. 

""" 

167 ↛ 168line 167 didn't jump to line 168, because the condition on line 167 was never true if vmin is not None and vmax is not None: 

return vmin, vmax 

 

percentile = (100 - percentile) / 2 

percentiles = (0, percentile, 100 - percentile, 100) 

mn, bound_mn, bound_mx, mx = np.percentile(data.flatten(), percentiles) 

 

bound_mn = bound_mn if vmin is None else vmin 

bound_mx = bound_mx if vmax is None else vmax 

 

# Stretch the lower and upper bounds to cover all the data, if 

# we stretch the bound by less than a factor 'stretch'. 

stretch = (bound_mx - bound_mn) * stretch 

out_mn = max(bound_mn - stretch, mn) if vmin is None else vmin 

out_mx = min(bound_mx + stretch, mx) if vmax is None else vmax 

 

return (out_mn, out_mx) 

 

 

symbol_dict = {'O': 'o', 's': ('p', 4, 45), 'S': ('P', 4, 45)} 

 

def get_symbol(symbols): 

"""Return the path corresponding to the description in ``symbols``""" 

# Figure out if list of symbols or single symbol. 

191 ↛ 192line 191 didn't jump to line 192, because the condition on line 191 was never true if not hasattr(symbols, '__getitem__'): 

symbols = [symbols] 

193 ↛ 196line 193 didn't jump to line 196, because the condition on line 193 was never true elif len(symbols) == 3 and symbols[0] in ('p', 'P'): 

# Most likely a polygon specification (at least not a valid other 

# symbol). 

symbols = [symbols] 

 

symbols = [symbol_dict[symbol] if symbol in symbol_dict else symbol for 

symbol in symbols] 

 

paths = [] 

for symbol in symbols: 

203 ↛ 204line 203 didn't jump to line 204, because the condition on line 203 was never true if isinstance(symbol, _p.matplotlib.path.Path): 

return symbol 

205 ↛ 206line 205 didn't jump to line 206, because the condition on line 205 was never true elif hasattr(symbol, '__getitem__') and len(symbol) == 3: 

kind, n, angle = symbol 

 

if kind in ['p', 'P']: 

if kind == 'p': 

radius = 1. / cos(pi / n) 

else: 

# make the polygon such that it has area equal 

# to a unit circle 

radius = sqrt(2 * pi / (n * sin(2 * pi / n))) 

 

angle = pi * angle / 180 

patch = _p.matplotlib.patches.RegularPolygon((0, 0), n, 

radius=radius, 

orientation=angle) 

else: 

raise ValueError("Unknown symbol definition " + str(symbol)) 

222 ↛ 225line 222 didn't jump to line 225, because the condition on line 222 was never false elif symbol == 'o': 

patch = _p.matplotlib.patches.Circle((0, 0), 1) 

 

paths.append(patch.get_path().transformed(patch.get_transform())) 

 

return paths 

 

 

def symbols(axes, pos, symbol='o', size=1, reflen=None, facecolor='k', 

edgecolor='k', linewidth=None, cmap=None, norm=None, zorder=0, 

**kwargs): 

"""Add a collection of symbols (2D or 3D) to an axes instance. 

 

Parameters 

---------- 

axes : matplotlib.axes.Axes instance 

Axes to which the lines have to be added. 

pos0 : 2d or 3d array_like 

Coordinates of each symbol. 

symbol: symbol definition. 

TODO To be written. 

size: float or 1d array 

Size(s) of the symbols. Defaults to 1. 

reflen: float or None, optional 

If ``reflen`` is ``None``, the symbol sizes and linewidths are 

given in points (absolute size in the figure space). If 

``reflen`` is a number, the symbol sizes and linewidths are 

given in units of ``reflen`` in data space (i.e. scales with the 

scale of the plot). Defaults to ``None``. 

facecolor: color definition, optional 

edgecolor: color definition, optional 

Defines the fill and edge color of the symbol, repsectively. 

Either a single object that is a proper matplotlib color 

definition or a sequence of such objects of appropriate 

length. Defaults to all black. 

cmap : ``matplotlib`` color map specification or None 

Color map to be used if colors are specified as floats. 

norm : ``matplotlib`` color norm 

Norm to be used if colors are specified as floats. 

zorder: int 

Order in which different collections are drawn: larger 

``zorder`` means the collection is drawn over collections with 

smaller ``zorder`` values. 

**kwargs : dict keyword arguments to 

pass to `PathCollection` or `Path3DCollection`, respectively. 

 

Returns 

------- 

`PathCollection` or `Path3DCollection` instance containing all the 

symbols that were added. 

""" 

 

dim = pos.shape[1] 

assert dim == 2 or dim == 3 

 

#internally, size must be array_like 

try: 

size[0] 

except TypeError: 

size = (size, ) 

 

if dim == 2: 

Collection = _p.PathCollection 

else: 

Collection = _p.Path3DCollection 

 

288 ↛ 289line 288 didn't jump to line 289, because the condition on line 288 was never true if len(pos) == 0 or np.all(symbol == 'no symbol') or np.all(size == 0): 

paths = [] 

pos = np.empty((0, dim)) 

else: 

paths = get_symbol(symbol) 

 

coll = Collection(paths, sizes=size, reflen=reflen, linewidths=linewidth, 

offsets=pos, transOffset=axes.transData, zorder=zorder) 

 

set_colors(facecolor, coll, cmap, norm) 

coll.set_edgecolors(edgecolor) 

 

coll.update(kwargs) 

 

if dim == 2: 

axes.add_collection(coll) 

else: 

axes.add_collection3d(coll) 

 

return coll 

 

 

def lines(axes, pos0, pos1, reflen=None, colors='k', linestyles='solid', 

cmap=None, norm=None, zorder=0, **kwargs): 

"""Add a collection of line segments (2D or 3D) to an axes instance. 

 

Parameters 

---------- 

axes : matplotlib.axes.Axes instance 

Axes to which the lines have to be added. 

pos0 : 2d or 3d array_like 

Starting coordinates of each line segment 

pos1 : 2d or 3d array_like 

Ending coordinates of each line segment 

reflen: float or None, optional 

If `reflen` is `None`, the linewidths are given in points (absolute 

size in the figure space). If `reflen` is a number, the linewidths 

are given in units of `reflen` in data space (i.e. scales with 

the scale of the plot). Defaults to `None`. 

colors : color definition, optional 

Either a single object that is a proper matplotlib color definition 

or a sequence of such objects of appropriate length. Defaults to all 

segments black. 

linestyles :linestyle definition, optional 

Either a single object that is a proper matplotlib line style 

definition or a sequence of such objects of appropriate length. 

Defaults to all segments solid. 

cmap : ``matplotlib`` color map specification or None 

Color map to be used if colors are specified as floats. 

norm : ``matplotlib`` color norm 

Norm to be used if colors are specified as floats. 

zorder: int 

Order in which different collections are drawn: larger 

`zorder` means the collection is drawn over collections with 

smaller `zorder` values. 

**kwargs : dict keyword arguments to 

pass to `LineCollection` or `Line3DCollection`, respectively. 

 

Returns 

------- 

`LineCollection` or `Line3DCollection` instance containing all the 

segments that were added. 

""" 

 

352 ↛ 353line 352 didn't jump to line 353, because the condition on line 352 was never true if not pos0.shape == pos1.shape: 

raise ValueError('Incompatible lengths of coordinate arrays.') 

 

dim = pos0.shape[1] 

assert dim == 2 or dim == 3 

if dim == 2: 

Collection = _p.LineCollection 

else: 

Collection = _p.Line3DCollection 

 

if (len(pos0) == 0 or 

('linewidths' in kwargs and kwargs['linewidths'] == 0)): 

coll = Collection([], reflen=reflen, linestyles=linestyles, 

zorder=zorder) 

coll.update(kwargs) 

if dim == 2: 

axes.add_collection(coll) 

else: 

axes.add_collection3d(coll) 

return coll 

 

segments = np.c_[pos0, pos1].reshape(pos0.shape[0], 2, dim) 

 

coll = Collection(segments, reflen=reflen, linestyles=linestyles, 

zorder=zorder) 

set_colors(colors, coll, cmap, norm) 

coll.update(kwargs) 

 

380 ↛ 383line 380 didn't jump to line 383, because the condition on line 380 was never false if dim == 2: 

axes.add_collection(coll) 

else: 

axes.add_collection3d(coll) 

 

return coll 

 

 

# Extracting necessary data from the system. 

 

def sys_leads_sites(sys, num_lead_cells=2): 

"""Return all the sites of the system and of the leads as a list. 

 

Parameters 

---------- 

sys : kwant.builder.Builder or kwant.system.System instance 

The system, sites of which should be returned. 

num_lead_cells : integer 

The number of times lead sites from each lead should be returned. 

This is useful for showing several unit cells of the lead next to the 

system. 

 

Returns 

------- 

sites : list of (site, lead_number, copy_number) tuples 

A site is a `~kwant.builder.Site` instance if the system is not finalized, 

and an integer otherwise. For system sites `lead_number` is `None` and 

`copy_number` is `0`, for leads both are integers. 

lead_cells : list of slices 

`lead_cells[i]` gives the position of all the coordinates of lead 

`i` within `sites`. 

 

Notes 

----- 

Leads are only supported if they are of the same type as the original 

system, i.e. sites of `~kwant.builder.BuilderLead` leads are returned with an 

unfinalized system, and sites of ``system.InfiniteSystem`` leads are 

returned with a finalized system. 

""" 

syst = sys # for naming consistency within function bodies 

lead_cells = [] 

if isinstance(syst, builder.Builder): 

sites = [(site, None, 0) for site in syst.sites()] 

for leadnr, lead in enumerate(syst.leads): 

start = len(sites) 

425 ↛ 429line 425 didn't jump to line 429, because the condition on line 425 was never false if hasattr(lead, 'builder') and len(lead.interface): 

sites.extend(((site, leadnr, i) for site in 

lead.builder.sites() for i in 

range(num_lead_cells))) 

lead_cells.append(slice(start, len(sites))) 

430 ↛ 442line 430 didn't jump to line 442, because the condition on line 430 was never false elif isinstance(syst, system.FiniteSystem): 

sites = [(i, None, 0) for i in range(syst.graph.num_nodes)] 

for leadnr, lead in enumerate(syst.leads): 

start = len(sites) 

# We will only plot leads with a graph and with a symmetry. 

435 ↛ 440line 435 didn't jump to line 440, because the condition on line 435 was never false if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and 

len(syst.lead_interfaces[leadnr])): 

sites.extend(((site, leadnr, i) for site in 

range(lead.cell_size) for i in 

range(num_lead_cells))) 

lead_cells.append(slice(start, len(sites))) 

else: 

raise TypeError('Unrecognized system type.') 

return sites, lead_cells 

 

 

def sys_leads_pos(sys, site_lead_nr): 

"""Return an array of positions of sites in a system. 

 

Parameters 

---------- 

sys : `kwant.builder.Builder` or `kwant.system.System` instance 

The system, coordinates of sites of which should be returned. 

site_lead_nr : list of `(site, leadnr, copynr)` tuples 

Output of `sys_leads_sites` applied to the system. 

 

Returns 

------- 

coords : numpy.ndarray of floats 

Array of coordinates of the sites. 

 

Notes 

----- 

This function uses `site.pos` property to get the position of a builder 

site and `sys.pos(sitenr)` for finalized systems. This function requires 

that all the positions of all the sites have the same dimensionality. 

""" 

 

# Note about efficiency (also applies to sys_leads_hoppings_pos) 

# NumPy is really slow when making a NumPy array from a tinyarray 

# (buffer interface seems very slow). It's much faster to first 

# convert to a tuple and then to convert to numpy array ... 

 

syst = sys # for naming consistency inside function bodies 

is_builder = isinstance(syst, builder.Builder) 

num_lead_cells = site_lead_nr[-1][2] + 1 

if is_builder: 

pos = np.array(ta.array([i[0].pos for i in site_lead_nr])) 

else: 

syst_from_lead = lambda lead: (syst if (lead is None) 

else syst.leads[lead]) 

pos = np.array(ta.array([syst_from_lead(i[1]).pos(i[0]) 

for i in site_lead_nr])) 

483 ↛ 484line 483 didn't jump to line 484, because the condition on line 483 was never true if pos.dtype == object: # Happens if not all the pos are same length. 

raise ValueError("pos attribute of the sites does not have consistent" 

" values.") 

dim = pos.shape[1] 

 

def get_vec_domain(lead_nr): 

489 ↛ 490line 489 didn't jump to line 490, because the condition on line 489 was never true if lead_nr is None: 

return np.zeros((dim,)), 0 

if is_builder: 

sym = syst.leads[lead_nr].builder.symmetry 

try: 

site = syst.leads[lead_nr].interface[0] 

except IndexError: 

return (0, 0) 

else: 

try: 

sym = syst.leads[lead_nr].symmetry 

site = syst.sites[syst.lead_interfaces[lead_nr][0]] 

except (AttributeError, IndexError): 

# empty leads, or leads without symmetry aren't drawn anyways 

return (0, 0) 

dom = sym.which(site)[0] + 1 

# Conversion to numpy array here useful for efficiency 

vec = np.array(sym.periods)[0] 

return vec, dom 

vecs_doms = dict((i, get_vec_domain(i)) for i in range(len(syst.leads))) 

vecs_doms[None] = np.zeros((dim,)), 0 

for k, v in vecs_doms.items(): 

vecs_doms[k] = [v[0] * i for i in range(v[1], v[1] + num_lead_cells)] 

pos += [vecs_doms[i[1]][i[2]] for i in site_lead_nr] 

return pos 

 

 

def sys_leads_hoppings(sys, num_lead_cells=2): 

"""Return all the hoppings of the system and of the leads as an iterator. 

 

Parameters 

---------- 

sys : kwant.builder.Builder or kwant.system.System instance 

The system, sites of which should be returned. 

num_lead_cells : integer 

The number of times lead sites from each lead should be returned. 

This is useful for showing several unit cells of the lead next to the 

system. 

 

Returns 

------- 

hoppings : list of (hopping, lead_number, copy_number) tuples 

A site is a `~kwant.builder.Site` instance if the system is not finalized, 

and an integer otherwise. For system sites `lead_number` is `None` and 

`copy_number` is `0`, for leads both are integers. 

lead_cells : list of slices 

`lead_cells[i]` gives the position of all the coordinates of lead 

`i` within `hoppings`. 

 

Notes 

----- 

Leads are only supported if they are of the same type as the original 

system, i.e. hoppings of `~kwant.builder.BuilderLead` leads are returned with an 

unfinalized system, and hoppings of `~kwant.system.InfiniteSystem` leads are 

returned with a finalized system. 

""" 

 

syst = sys # for naming consistency inside function bodies 

hoppings = [] 

lead_cells = [] 

if isinstance(syst, builder.Builder): 

hoppings.extend(((hop, None, 0) for hop in syst.hoppings())) 

 

def lead_hoppings(lead): 

sym = lead.symmetry 

for site2, site1 in lead.hoppings(): 

shift1 = sym.which(site1)[0] 

shift2 = sym.which(site2)[0] 

# We need to make sure that the hopping is between a site in a 

# fundamental domain and a site with a negative domain. The 

# direction of the hopping is chosen arbitrarily 

# NOTE(Anton): This may need to be revisited with the future 

# builder format changes. 

shift = max(shift1, shift2) 

yield sym.act([-shift], site2), sym.act([-shift], site1) 

 

for leadnr, lead in enumerate(syst.leads): 

start = len(hoppings) 

567 ↛ 571line 567 didn't jump to line 571, because the condition on line 567 was never false if hasattr(lead, 'builder') and len(lead.interface): 

hoppings.extend(((hop, leadnr, i) for hop in 

lead_hoppings(lead.builder) for i in 

range(num_lead_cells))) 

lead_cells.append(slice(start, len(hoppings))) 

572 ↛ 589line 572 didn't jump to line 589, because the condition on line 572 was never false elif isinstance(syst, system.System): 

def ll_hoppings(syst): 

for i in range(syst.graph.num_nodes): 

575 ↛ 576line 575 didn't jump to line 576, because the loop on line 575 never started for j in syst.graph.out_neighbors(i): 

if i < j: 

yield i, j 

 

hoppings.extend(((hop, None, 0) for hop in ll_hoppings(syst))) 

580 ↛ 581line 580 didn't jump to line 581, because the loop on line 580 never started for leadnr, lead in enumerate(syst.leads): 

start = len(hoppings) 

# We will only plot leads with a graph and with a symmetry. 

if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and 

len(syst.lead_interfaces[leadnr])): 

hoppings.extend(((hop, leadnr, i) for hop in ll_hoppings(lead) 

for i in range(num_lead_cells))) 

lead_cells.append(slice(start, len(hoppings))) 

else: 

raise TypeError('Unrecognized system type.') 

return hoppings, lead_cells 

 

 

def sys_leads_hopping_pos(sys, hop_lead_nr): 

"""Return arrays of coordinates of all hoppings in a system. 

 

Parameters 

---------- 

sys : ``~kwant.builder.Builder`` or ``~kwant.system.System`` instance 

The system, coordinates of sites of which should be returned. 

hoppings : list of ``(hopping, leadnr, copynr)`` tuples 

Output of `sys_leads_hoppings` applied to the system. 

 

Returns 

------- 

coords : (end_site, start_site): tuple of NumPy arrays of floats 

Array of coordinates of the hoppings. The first half of coordinates 

in each array entry are those of the first site in the hopping, the 

last half are those of the second site. 

 

Notes 

----- 

This function uses ``site.pos`` property to get the position of a builder 

site and ``sys.pos(sitenr)`` for finalized systems. This function requires 

that all the positions of all the sites have the same dimensionality. 

""" 

 

syst = sys # for naming consistency inside function bodies 

is_builder = isinstance(syst, builder.Builder) 

if len(hop_lead_nr) == 0: 

return np.empty((0, 3)), np.empty((0, 3)) 

num_lead_cells = hop_lead_nr[-1][2] + 1 

622 ↛ 627line 622 didn't jump to line 627, because the condition on line 622 was never false if is_builder: 

pos = np.array(ta.array([ta.array(tuple(i[0][0].pos) + 

tuple(i[0][1].pos)) for i in 

hop_lead_nr])) 

else: 

syst_from_lead = lambda lead: (syst if (lead is None) else 

syst.leads[lead]) 

pos = ta.array([ta.array(tuple(syst_from_lead(i[1]).pos(i[0][0])) + 

tuple(syst_from_lead(i[1]).pos(i[0][1]))) for i 

in hop_lead_nr]) 

pos = np.array(pos) 

633 ↛ 634line 633 didn't jump to line 634, because the condition on line 633 was never true if pos.dtype == object: # Happens if not all the pos are same length. 

raise ValueError("pos attribute of the sites does not have consistent" 

" values.") 

dim = pos.shape[1] 

 

def get_vec_domain(lead_nr): 

639 ↛ 640line 639 didn't jump to line 640, because the condition on line 639 was never true if lead_nr is None: 

return np.zeros((dim,)), 0 

641 ↛ 648line 641 didn't jump to line 648, because the condition on line 641 was never false if is_builder: 

sym = syst.leads[lead_nr].builder.symmetry 

try: 

site = syst.leads[lead_nr].interface[0] 

except IndexError: 

return (0, 0) 

else: 

try: 

sym = syst.leads[lead_nr].symmetry 

site = syst.sites[syst.lead_interfaces[lead_nr][0]] 

except (AttributeError, IndexError): 

# empyt leads or leads without symmetry are not drawn anyways 

return (0, 0) 

dom = sym.which(site)[0] + 1 

vec = np.array(sym.periods)[0] 

return np.r_[vec, vec], dom 

 

vecs_doms = dict((i, get_vec_domain(i)) for i in range(len(syst.leads))) 

vecs_doms[None] = np.zeros((dim,)), 0 

for k, v in vecs_doms.items(): 

vecs_doms[k] = [v[0] * i for i in range(v[1], v[1] + num_lead_cells)] 

pos += [vecs_doms[i[1]][i[2]] for i in hop_lead_nr] 

return np.copy(pos[:, : dim // 2]), np.copy(pos[:, dim // 2:]) 

 

 

# Useful plot functions (to be extended). 

 

defaults = {'site_symbol': {2: 'o', 3: 'o'}, 

'site_size': {2: 0.25, 3: 0.5}, 

'site_color': {2: 'black', 3: 'white'}, 

'site_edgecolor': {2: 'black', 3: 'black'}, 

'site_lw': {2: 0, 3: 0.1}, 

'hop_color': {2: 'black', 3: 'black'}, 

'hop_lw': {2: 0.1, 3: 0}, 

'lead_color': {2: 'red', 3: 'red'}} 

 

 

def plot(sys, num_lead_cells=2, unit='nn', 

site_symbol=None, site_size=None, 

site_color=None, site_edgecolor=None, site_lw=None, 

hop_color=None, hop_lw=None, 

lead_site_symbol=None, lead_site_size=None, lead_color=None, 

lead_site_edgecolor=None, lead_site_lw=None, 

lead_hop_lw=None, pos_transform=None, 

cmap='gray', colorbar=True, file=None, 

show=True, dpi=None, fig_size=None, ax=None): 

"""Plot a system in 2 or 3 dimensions. 

 

An alias exists for this common name: ``kwant.plot``. 

 

Parameters 

---------- 

sys : kwant.builder.Builder or kwant.system.FiniteSystem 

A system to be plotted. 

num_lead_cells : int 

Number of lead copies to be shown with the system. 

unit : 'nn', 'pt', or float 

The unit used to specify symbol sizes and linewidths. 

Possible choices are: 

 

- 'nn': unit is the shortest hopping or a typical nearst neighbor 

distance in the system if there are no hoppings. This means that 

symbol sizes/linewidths will scale as the zoom level of the figure is 

changed. Very short distances are discarded before searching for the 

shortest. This choice means that the symbols will scale if the 

figure is zoomed. 

- 'pt': unit is points (point = 1/72 inch) in figure space. This means 

that symbols and linewidths will always be drawn with the same size 

independent of zoom level of the plot. 

- float: sizes are given in units of this value in real (system) space, 

and will accordingly scale as the plot is zoomed. 

 

The default value is 'nn', which allows to ensure that the images 

neighboring sites do not overlap. 

 

site_symbol : symbol specification, function, array, or `None` 

Symbol used for representing a site in the plot. Can be specified as 

 

- 'o': circle with radius of 1 unit. 

- 's': square with inner circle radius of 1 unit. 

- ``('p', nvert, angle)``: regular polygon with ``nvert`` vertices, 

rotated by ``angle``. ``angle`` is given in degrees, and ``angle=0`` 

corresponds to one edge of the polygon pointing upward. The 

radius of the inner circle is 1 unit. 

- 'no symbol': no symbol is plotted. 

- 'S', `('P', nvert, angle)`: as the lower-case variants described 

above, but with an area equal to a circle of radius 1. (Makes 

the visual size of the symbol equal to the size of a circle with 

radius 1). 

- matplotlib.path.Path instance. 

 

Instead of a single symbol, different symbols can be specified 

for different sites by passing a function that returns a valid 

symbol specification for each site, or by passing an array of 

symbols specifications (only for kwant.system.FiniteSystem). 

site_size : number, function, array, or `None` 

Relative (linear) size of the site symbol. 

An array may not be used when 'syst' is a kwant.Builder. 

site_color : ``matplotlib`` color description, function, array, or `None` 

A color used for plotting a site in the system. If a colormap is used, 

it should be a function returning single floats or a one-dimensional 

array of floats. By default sites are colored by their site family, 

using the current matplotlib color cycle. 

An array of colors may not be used when 'syst' is a kwant.Builder. 

site_edgecolor : ``matplotlib`` color description, function, array, or `None` 

Color used for plotting the edges of the site symbols. Only 

valid matplotlib color descriptions are allowed (and no 

combination of floats and colormap as for site_color). 

An array of colors may not be used when 'syst' is a kwant.Builder. 

site_lw : number, function, array, or `None` 

Linewidth of the site symbol edges. 

An array may not be used when 'syst' is a kwant.Builder. 

hop_color : ``matplotlib`` color description or a function 

Same as `site_color`, but for hoppings. A function is passed two sites 

in this case. (arrays are not allowed in this case). 

hop_lw : number, function, or `None` 

Linewidth of the hoppings. 

lead_site_symbol : symbol specification or `None` 

Symbol to be used for the leads. See `site_symbol` for allowed 

specifications. Note that for leads, only constants 

(i.e. no functions or arrays) are allowed. If None, then 

`site_symbol` is used if it is constant (i.e. no function or array), 

the default otherwise. The same holds for the other lead properties 

below. 

lead_site_size : number or `None` 

Relative (linear) size of the lead symbol 

lead_color : ``matplotlib`` color description or `None` 

For the leads, `num_lead_cells` copies of the lead unit cell 

are plotted. They are plotted in color fading from `lead_color` 

to white (alpha values in `lead_color` are supported) when moving 

from the system into the lead. Is also applied to the 

hoppings. 

lead_site_edgecolor : ``matplotlib`` color description or `None` 

Color of the symbol edges (no fading done). 

lead_site_lw : number or `None` 

Linewidth of the lead symbols. 

lead_hop_lw : number or `None` 

Linewidth of the lead hoppings. 

cmap : ``matplotlib`` color map or a sequence of two color maps or `None` 

The color map used for sites and optionally hoppings. 

pos_transform : function or `None` 

Transformation to be applied to the site position. 

colorbar : bool 

Whether to show a colorbar if colormap is used. Ignored if `ax` is 

provided. 

file : string or file object or `None` 

The output file. If `None`, output will be shown instead. 

show : bool 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. Defaults to `True`. 

dpi : float or `None` 

Number of pixels per inch. If not set the ``matplotlib`` default is 

used. 

fig_size : tuple or `None` 

Figure size `(width, height)` in inches. If not set, the default 

``matplotlib`` value is used. 

ax : ``matplotlib.axes.Axes`` instance or `None` 

If `ax` is not `None`, no new figure is created, but the plot is done 

within the existing Axes `ax`. in this case, `file`, `show`, `dpi` 

and `fig_size` are ignored. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if `ax` is not set, else None. 

 

Notes 

----- 

- If `None` is passed for a plot property, a default value depending on 

the dimension is chosen. Typically, the default values result in 

acceptable plots. 

 

- The meaning of "site" depends on whether the system to be plotted is a 

builder or a low level system. For builders, a site is a 

kwant.builder.Site object. For low level systems, a site is an integer 

-- the site number. 

 

- color and symbol definitions may be tuples, but not lists or arrays. 

Arrays of values (linewidths, colors, sizes) may not be tuples. 

 

- The dimensionality of the plot (2D vs 3D) is inferred from the coordinate 

array. If there are more than three coordinates, only the first three 

are used. If there is just one coordinate, the second one is padded with 

zeros. 

 

- The system is scaled to fit the smaller dimension of the figure, given 

its aspect ratio. 

 

""" 

830 ↛ 831line 830 didn't jump to line 831, because the condition on line 830 was never true if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for plot()") 

 

syst = sys # for naming consistency inside function bodies 

# Generate data. 

sites, lead_sites_slcs = sys_leads_sites(syst, num_lead_cells) 

n_syst_sites = sum(i[1] is None for i in sites) 

sites_pos = sys_leads_pos(syst, sites) 

hops, lead_hops_slcs = sys_leads_hoppings(syst, num_lead_cells) 

n_syst_hops = sum(i[1] is None for i in hops) 

end_pos, start_pos = sys_leads_hopping_pos(syst, hops) 

 

# Choose plot type. 

def resize_to_dim(array): 

if array.shape[1] != dim: 

ar = np.zeros((len(array), dim), dtype=float) 

ar[:, : min(dim, array.shape[1])] = array[ 

:, : min(dim, array.shape[1])] 

return ar 

else: 

return array 

 

loc = locals() 

 

def check_length(name): 

value = loc[name] 

857 ↛ 858line 857 didn't jump to line 858, because the condition on line 857 was never true if name in ('site_size', 'site_lw') and isinstance(value, tuple): 

raise TypeError('{0} may not be a tuple, use list or ' 

'array instead.'.format(name)) 

if isinstance(value, (str, tuple)): 

return 

try: 

863 ↛ 864line 863 didn't jump to line 864, because the condition on line 863 was never true if len(value) != n_syst_sites: 

raise ValueError('Length of {0} is not equal to number of ' 

'system sites.'.format(name)) 

except TypeError: 

pass 

 

for name in ['site_symbol', 'site_size', 'site_color', 'site_edgecolor', 

'site_lw']: 

check_length(name) 

 

# Apply transformations to the data 

if pos_transform is not None: 

sites_pos = np.apply_along_axis(pos_transform, 1, sites_pos) 

end_pos = np.apply_along_axis(pos_transform, 1, end_pos) 

start_pos = np.apply_along_axis(pos_transform, 1, start_pos) 

 

dim = 3 if (sites_pos.shape[1] == 3) else 2 

880 ↛ 881line 880 didn't jump to line 881, because the condition on line 880 was never true if dim == 3 and not _p.has3d: 

raise RuntimeError("Installed matplotlib does not support 3d plotting") 

sites_pos = resize_to_dim(sites_pos) 

end_pos = resize_to_dim(end_pos) 

start_pos = resize_to_dim(start_pos) 

 

# Determine the reference length. 

887 ↛ 888line 887 didn't jump to line 888, because the condition on line 887 was never true if unit == 'pt': 

reflen = None 

889 ↛ 912line 889 didn't jump to line 912, because the condition on line 889 was never false elif unit == 'nn': 

if n_syst_hops: 

# If hoppings are present use their lengths to determine the 

# minimal one. 

distances = end_pos - start_pos 

else: 

# If no hoppings are present, use for the same purpose distances 

# from ten randomly selected points to the remaining points in the 

# system. 

points = _sample_array(sites_pos, 10).T 

distances = (sites_pos.reshape(1, -1, dim) - 

points.reshape(-1, 1, dim)).reshape(-1, dim) 

distances = np.sort(np.sum(distances**2, axis=1)) 

# Then check if distances are present that are way shorter than the 

# longest one. Then take first distance longer than these short 

# ones. This heuristic will fail for too large systems, or systems with 

# hoppings that vary by orders and orders of magnitude, but for sane 

# cases it will work. 

long_dist_coord = np.searchsorted(distances, 1e-16 * distances[-1]) 

reflen = sqrt(distances[long_dist_coord]) 

 

else: 

# The last allowed value is float-compatible. 

try: 

reflen = float(unit) 

except: 

raise ValueError('Invalid value of unit argument.') 

 

# make all specs proper: either constant or lists/np.arrays: 

def make_proper_site_spec(spec_name, spec, fancy_indexing=False): 

if _p.isarray(spec) and isinstance(syst, builder.Builder): 

raise TypeError('{} cannot be an array when plotting' 

' a Builder; use a function instead.' 

.format(spec_name)) 

if callable(spec): 

spec = [spec(i[0]) for i in sites if i[1] is None] 

925 ↛ 927line 925 didn't jump to line 927, because the condition on line 925 was never true if (fancy_indexing and _p.isarray(spec) 

and not isinstance(spec, np.ndarray)): 

try: 

spec = np.asarray(spec) 

except: 

spec = np.asarray(spec, dtype='object') 

return spec 

 

def make_proper_hop_spec(spec, fancy_indexing=False): 

if callable(spec): 

spec = [spec(*i[0]) for i in hops if i[1] is None] 

936 ↛ 938line 936 didn't jump to line 938, because the condition on line 936 was never true if (fancy_indexing and _p.isarray(spec) 

and not isinstance(spec, np.ndarray)): 

try: 

spec = np.asarray(spec) 

except: 

spec = np.asarray(spec, dtype='object') 

return spec 

 

 

site_symbol = make_proper_site_spec('site_symbol', site_symbol) 

if site_symbol is None: site_symbol = defaults['site_symbol'][dim] 

# separate different symbols (not done in 3D, the separation 

# would mess up sorting) 

949 ↛ 951line 949 didn't jump to line 951, because the condition on line 949 was never true if (_p.isarray(site_symbol) and dim != 3 and 

(len(site_symbol) != 3 or site_symbol[0] not in ('p', 'P'))): 

symbol_dict = defaultdict(list) 

for i, symbol in enumerate(site_symbol): 

symbol_dict[symbol].append(i) 

symbol_slcs = [] 

for symbol, indx in symbol_dict.items(): 

symbol_slcs.append((symbol, np.array(indx))) 

fancy_indexing = True 

else: 

symbol_slcs = [(site_symbol, slice(n_syst_sites))] 

fancy_indexing = False 

 

if site_color is None: 

cycle = _color_cycle() 

if isinstance(syst, (builder.FiniteSystem, builder.InfiniteSystem)): 

# Skipping the leads for brevity. 

families = sorted({site.family for site in syst.sites}) 

color_mapping = dict(zip(families, cycle)) 

def site_color(site): 

return color_mapping[syst.sites[site].family] 

970 ↛ 977line 970 didn't jump to line 977, because the condition on line 970 was never false elif isinstance(syst, builder.Builder): 

families = sorted({site[0].family for site in sites}) 

color_mapping = dict(zip(families, cycle)) 

def site_color(site): 

return color_mapping[site.family] 

else: 

# Unknown finalized system, no sites access. 

site_color = defaults['site_color'][dim] 

 

site_size = make_proper_site_spec('site_size', site_size, fancy_indexing) 

site_color = make_proper_site_spec('site_color', site_color, fancy_indexing) 

site_edgecolor = make_proper_site_spec('site_edgecolor', site_edgecolor, fancy_indexing) 

site_lw = make_proper_site_spec('site_lw', site_lw, fancy_indexing) 

 

hop_color = make_proper_hop_spec(hop_color) 

hop_lw = make_proper_hop_spec(hop_lw) 

 

# Choose defaults depending on dimension, if None was given 

if site_size is None: site_size = defaults['site_size'][dim] 

989 ↛ 991line 989 didn't jump to line 991, because the condition on line 989 was never false if site_edgecolor is None: 

site_edgecolor = defaults['site_edgecolor'][dim] 

if site_lw is None: site_lw = defaults['site_lw'][dim] 

 

if hop_color is None: hop_color = defaults['hop_color'][dim] 

if hop_lw is None: hop_lw = defaults['hop_lw'][dim] 

 

# if symbols are split up into different collections, 

# the colormapping will fail without normalization 

norm = None 

999 ↛ 1000line 999 didn't jump to line 1000, because the condition on line 999 was never true if len(symbol_slcs) > 1: 

try: 

if site_color.ndim == 1 and len(site_color) == n_syst_sites: 

site_color = np.asarray(site_color, dtype=float) 

norm = _p.matplotlib.colors.Normalize(site_color.min(), 

site_color.max()) 

except: 

pass 

 

# take spec also for lead, if it's not a list/array, default, otherwise 

1009 ↛ 1012line 1009 didn't jump to line 1012, because the condition on line 1009 was never false if lead_site_symbol is None: 

lead_site_symbol = (site_symbol if not _p.isarray(site_symbol) 

else defaults['site_symbol'][dim]) 

1012 ↛ 1015line 1012 didn't jump to line 1015, because the condition on line 1012 was never false if lead_site_size is None: 

lead_site_size = (site_size if not _p.isarray(site_size) 

else defaults['site_size'][dim]) 

1015 ↛ 1017line 1015 didn't jump to line 1017, because the condition on line 1015 was never false if lead_color is None: 

lead_color = defaults['lead_color'][dim] 

lead_color = _p.matplotlib.colors.colorConverter.to_rgba(lead_color) 

 

1019 ↛ 1022line 1019 didn't jump to line 1022, because the condition on line 1019 was never false if lead_site_edgecolor is None: 

lead_site_edgecolor = (site_edgecolor if not _p.isarray(site_edgecolor) 

else defaults['site_edgecolor'][dim]) 

1022 ↛ 1025line 1022 didn't jump to line 1025, because the condition on line 1022 was never false if lead_site_lw is None: 

lead_site_lw = (site_lw if not _p.isarray(site_lw) 

else defaults['site_lw'][dim]) 

1025 ↛ 1029line 1025 didn't jump to line 1029, because the condition on line 1025 was never false if lead_hop_lw is None: 

lead_hop_lw = (hop_lw if not _p.isarray(hop_lw) 

else defaults['hop_lw'][dim]) 

 

hop_cmap = None 

1030 ↛ 1031line 1030 didn't jump to line 1031, because the condition on line 1030 was never true if not isinstance(cmap, str): 

try: 

cmap, hop_cmap = cmap 

except TypeError: 

pass 

 

# make a new figure unless axes specified 

1037 ↛ 1048line 1037 didn't jump to line 1048, because the condition on line 1037 was never false if not ax: 

fig = _make_figure(dpi, fig_size, use_pyplot=(file is None)) 

if dim == 2: 

ax = fig.add_subplot(1, 1, 1, aspect='equal') 

ax.set_xmargin(0.05) 

ax.set_ymargin(0.05) 

else: 

warnings.filterwarnings('ignore', message=r'.*rotation.*') 

ax = fig.add_subplot(1, 1, 1, projection='3d') 

warnings.resetwarnings() 

else: 

fig = None 

 

# plot system sites and hoppings 

for symbol, slc in symbol_slcs: 

size = site_size[slc] if _p.isarray(site_size) else site_size 

col = site_color[slc] if _p.isarray(site_color) else site_color 

edgecol = (site_edgecolor[slc] if _p.isarray(site_edgecolor) else 

site_edgecolor) 

lw = site_lw[slc] if _p.isarray(site_lw) else site_lw 

 

symbol_coll = symbols(ax, sites_pos[slc], size=size, 

reflen=reflen, symbol=symbol, 

facecolor=col, edgecolor=edgecol, 

linewidth=lw, cmap=cmap, norm=norm, zorder=2) 

 

end, start = end_pos[: n_syst_hops], start_pos[: n_syst_hops] 

line_coll = lines(ax, end, start, reflen, hop_color, linewidths=hop_lw, 

zorder=1, cmap=hop_cmap) 

 

# plot lead sites and hoppings 

norm = _p.matplotlib.colors.Normalize(-0.5, num_lead_cells - 0.5) 

cmap_from_list = _p.matplotlib.colors.LinearSegmentedColormap.from_list 

lead_cmap = cmap_from_list(None, [lead_color, (1, 1, 1, lead_color[3])]) 

 

for sites_slc, hops_slc in zip(lead_sites_slcs, lead_hops_slcs): 

lead_site_colors = np.array([i[2] for i in sites[sites_slc]], 

dtype=float) 

 

# Note: the previous version of the code had in addition this 

# line in the 3D case: 

# lead_site_colors = 1 / np.sqrt(1. + lead_site_colors) 

symbols(ax, sites_pos[sites_slc], size=lead_site_size, reflen=reflen, 

symbol=lead_site_symbol, facecolor=lead_site_colors, 

edgecolor=lead_site_edgecolor, linewidth=lead_site_lw, 

cmap=lead_cmap, zorder=2, norm=norm) 

 

lead_hop_colors = np.array([i[2] for i in hops[hops_slc]], dtype=float) 

 

# Note: the previous version of the code had in addition this 

# line in the 3D case: 

# lead_hop_colors = 1 / np.sqrt(1. + lead_hop_colors) 

end, start = end_pos[hops_slc], start_pos[hops_slc] 

lines(ax, end, start, reflen, lead_hop_colors, linewidths=lead_hop_lw, 

cmap=lead_cmap, norm=norm, zorder=1) 

 

min_ = np.min(sites_pos, 0) 

max_ = np.max(sites_pos, 0) 

m = (min_ + max_) / 2 

if dim == 2: 

w = np.max([(max_ - min_) / 2, (reflen, reflen)], axis=0) 

ax.update_datalim((m - w, m + w)) 

ax.autoscale_view(tight=True) 

else: 

# make axis limits the same in all directions 

# (3D only works decently for equal aspect ratio. Since 

# this doesn't work out of the box in mplot3d, this is a 

# workaround) 

w = np.max(max_ - min_) / 2 

ax.auto_scale_xyz(*[(i - w, i + w) for i in m], had_data=True) 

 

# add separate colorbars for symbols and hoppings if ncessary 

if symbol_coll.get_array() is not None and colorbar and fig is not None: 

fig.colorbar(symbol_coll) 

if line_coll.get_array() is not None and colorbar and fig is not None: 

fig.colorbar(line_coll) 

 

_maybe_output_fig(fig, file=file, show=show) 

 

return fig 

 

 

def mask_interpolate(coords, values, a=None, method='nearest', oversampling=3): 

"""Interpolate a scalar function in vicinity of given points. 

 

Create a masked array corresponding to interpolated values of the function 

at points lying not further than a certain distance from the original 

data points provided. 

 

Parameters 

---------- 

coords : np.ndarray 

An array with site coordinates. 

values : np.ndarray 

An array with the values from which the interpolation should be built. 

a : float, optional 

Reference length. If not given, it is determined as a typical 

nearest neighbor distance. 

method : string, optional 

Passed to ``scipy.interpolate.griddata``: "nearest" (default), "linear", 

or "cubic" 

oversampling : integer, optional 

Number of pixels per reference length. Defaults to 3. 

 

Returns 

------- 

array : 2d NumPy array 

The interpolated values. 

min, max : vectors 

The real-space coordinates of the two extreme ([0, 0] and [-1, -1]) 

points of ``array``. 

 

Notes 

----- 

- `min` and `max` are chosen such that when plotting a system on a square 

lattice and `oversampling` is set to an odd integer, each site will lie 

exactly at the center of a pixel of the output array. 

 

- When plotting a system on a square lattice and `method` is "nearest", it 

makes sense to set `oversampling` to ``1``. Then, each site will 

correspond to exactly one pixel in the resulting array. 

""" 

# Build the bounding box. 

cmin, cmax = coords.min(0), coords.max(0) 

 

tree = spatial.cKDTree(coords) 

 

# Select 10 sites to compare -- comparing them all is too costly. 

points = _sample_array(coords, 10) 

min_dist = np.min(tree.query(points, 2)[0][:, 1]) 

if min_dist < 1e-6 * np.linalg.norm(cmax - cmin): 

warnings.warn("Some sites have nearly coinciding positions, " 

"interpolation may be confusing.", 

RuntimeWarning, stacklevel=2) 

 

if a is None: 

a = min_dist 

 

if a < 1e-6 * np.linalg.norm(cmax - cmin): 

raise ValueError("The reference distance a is too small.") 

 

1178 ↛ 1179line 1178 didn't jump to line 1179, because the condition on line 1178 was never true if len(coords) != len(values): 

raise ValueError("The number of sites doesn't match the number of " 

"provided values.") 

 

shape = (((cmax - cmin) / a + 1) * oversampling).round() 

delta = 0.5 * (oversampling - 1) * a / oversampling 

cmin -= delta 

cmax += delta 

dims = tuple(slice(cmin[i], cmax[i], 1j * shape[i]) for i in 

range(len(cmin))) 

grid = tuple(np.ogrid[dims]) 

img = interpolate.griddata(coords, values, grid, method) 

mask = np.mgrid[dims].reshape(len(cmin), -1).T 

# The numerical values in the following line are optimized for the common 

# case of a square lattice: 

# * 0.99 makes sure that non-masked pixels and sites correspond 1-by-1 to 

# each other when oversampling == 1. 

# * 0.4 (which is just below sqrt(2) - 1) makes tree.query() exact. 

mask = tree.query(mask, eps=0.4)[0] > 0.99 * a 

 

return np.ma.masked_array(img, mask), cmin, cmax 

 

 

def map(sys, value, colorbar=True, cmap=None, vmin=None, vmax=None, a=None, 

method='nearest', oversampling=3, num_lead_cells=0, file=None, 

show=True, dpi=None, fig_size=None, ax=None, pos_transform=None, 

background='#e0e0e0'): 

"""Show interpolated map of a function defined for the sites of a system. 

 

Create a pixmap representation of a function of the sites of a system by 

calling `~kwant.plotter.mask_interpolate` and show this pixmap using 

matplotlib. 

 

This function is similar to `~kwant.plotter.density`, but is more suited 

to the case where you want site-level resolution of the quantity that 

you are plotting. If your system has many sites you may get more appealing 

plots by using `~kwant.plotter.density`. 

 

Parameters 

---------- 

sys : kwant.system.FiniteSystem or kwant.builder.Builder 

The system for whose sites `value` is to be plotted. 

value : function or list 

Function which takes a site and returns a value if the system is a 

builder, or a list of function values for each system site of the 

finalized system. 

colorbar : bool, optional 

Whether to show a color bar if numerical data has to be plotted. 

Defaults to `True`. If `ax` is provided, the colorbar is never plotted. 

cmap : ``matplotlib`` color map or `None` 

The color map used for sites and optionally hoppings, if `None`, 

``matplotlib`` default is used. 

vmin : float, optional 

The lower saturation limit for the colormap; values returned by 

`value` which are smaller than this will saturate 

vmax : float, optional 

The upper saturation limit for the colormap; valued returned by 

`value` which are larger than this will saturate 

a : float, optional 

Reference length. If not given, it is determined as a typical 

nearest neighbor distance. 

method : string, optional 

Passed to ``scipy.interpolate.griddata``: "nearest" (default), "linear", 

or "cubic" 

oversampling : integer, optional 

Number of pixels per reference length. Defaults to 3. 

num_lead_cells : integer, optional 

number of lead unit cells that should be plotted to indicate 

the position of leads. Defaults to 0. 

file : string or file object or `None` 

The output file. If `None`, output will be shown instead. 

show : bool 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. Defaults to `True`. 

ax : ``matplotlib.axes.Axes`` instance or `None` 

If `ax` is not `None`, no new figure is created, but the plot is done 

within the existing Axes `ax`. in this case, `file`, `show`, `dpi` 

and `fig_size` are ignored. 

pos_transform : function or `None` 

Transformation to be applied to the site position. 

background : matplotlib color spec 

Areas without sites are filled with this color. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if `ax` is not set, else None. 

 

Notes 

----- 

- When plotting a system on a square lattice and `method` is "nearest", it 

makes sense to set `oversampling` to ``1``. Then, each site will 

correspond to exactly one pixel. 

 

See Also 

-------- 

kwant.plotter.density 

""" 

 

1277 ↛ 1278line 1277 didn't jump to line 1278, because the condition on line 1277 was never true if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for map()") 

 

syst = sys # for naming consistency inside function bodies 

sites = sys_leads_sites(syst, 0)[0] 

coords = sys_leads_pos(syst, sites) 

 

if pos_transform is not None: 

coords = np.apply_along_axis(pos_transform, 1, coords) 

 

if coords.shape[1] != 2: 

raise ValueError('Only 2D systems can be plotted this way.') 

 

if callable(value): 

value = [value(site[0]) for site in sites] 

else: 

if not isinstance(syst, system.FiniteSystem): 

raise ValueError('List of values is only allowed as input ' 

'for finalized systems.') 

value = np.array(value) 

with _common.reraise_warnings(): 

img, min, max = mask_interpolate(coords, value, a, method, oversampling) 

border = 0.5 * (max - min) / (np.asarray(img.shape) - 1) 

min -= border 

max += border 

1303 ↛ 1307line 1303 didn't jump to line 1307, because the condition on line 1303 was never false if ax is None: 

fig = _make_figure(dpi, fig_size, use_pyplot=(file is None)) 

ax = fig.add_subplot(1, 1, 1, aspect='equal') 

else: 

fig = None 

 

if cmap is None: 

cmap = _p._colormaps.kwant_red 

 

# Calculate the min/max bounds for the colormap. 

# User-provided values take precedence. 

unmasked_data = img[~img.mask].data.flatten() 

unmasked_data = unmasked_data[~np.isnan(unmasked_data)] 

new_vmin, new_vmax = percentile_bound(unmasked_data, vmin, vmax) 

overflow_pct = 100 * np.sum(unmasked_data > new_vmax) / len(unmasked_data) 

underflow_pct = 100 * np.sum(unmasked_data < new_vmin) / len(unmasked_data) 

1319 ↛ 1320line 1319 didn't jump to line 1320 if (vmin is None and underflow_pct) or (vmax is None and overflow_pct): 

msg = ( 

'The plotted data contains ', 

'{:.2f}% of values overflowing upper limit {:g} ' 

.format(overflow_pct, new_vmax) 

if overflow_pct > 0 else '', 

'and ' if overflow_pct > 0 and underflow_pct > 0 else '', 

'{:.2f}% of values underflowing lower limit {:g} ' 

.format(underflow_pct, new_vmin) 

if underflow_pct > 0 else '', 

) 

warnings.warn(''.join(msg), RuntimeWarning, stacklevel=2) 

vmin, vmax = new_vmin, new_vmax 

 

# Note that we tell imshow to show the array created by mask_interpolate 

# faithfully and not to interpolate by itself another time. 

image = ax.imshow(img.T, extent=(min[0], max[0], min[1], max[1]), 

origin='lower', interpolation='none', cmap=cmap, 

vmin=vmin, vmax=vmax) 

1338 ↛ 1339line 1338 didn't jump to line 1339, because the condition on line 1338 was never true if num_lead_cells: 

plot(syst, num_lead_cells, site_symbol='no symbol', hop_lw=0, 

lead_site_symbol='s', lead_site_size=0.501, lead_site_lw=0, 

lead_hop_lw=0, lead_color='black', colorbar=False, ax=ax) 

 

ax.patch.set_facecolor(background) 

 

1345 ↛ 1356line 1345 didn't jump to line 1356, because the condition on line 1345 was never false if colorbar and fig is not None: 

# Make the colorbar ends pointy if we saturate the colormap 

extend = 'neither' 

1348 ↛ 1349line 1348 didn't jump to line 1349, because the condition on line 1348 was never true if underflow_pct > 0 and overflow_pct > 0: 

extend = 'both' 

1350 ↛ 1351line 1350 didn't jump to line 1351, because the condition on line 1350 was never true elif underflow_pct > 0: 

extend = 'min' 

1352 ↛ 1353line 1352 didn't jump to line 1353, because the condition on line 1352 was never true elif overflow_pct > 0: 

extend = 'max' 

fig.colorbar(image, extend=extend) 

 

_maybe_output_fig(fig, file=file, show=show) 

 

return fig 

 

 

@deprecate_args 

def bands(sys, args=(), momenta=65, file=None, show=True, dpi=None, 

fig_size=None, ax=None, *, params=None): 

"""Plot band structure of a translationally invariant 1D system. 

 

Parameters 

---------- 

sys : kwant.system.InfiniteSystem 

A system bands of which are to be plotted. 

args : tuple, defaults to empty 

Positional arguments to pass to the ``hamiltonian`` method. 

Deprecated in favor of 'params' (and mutually exclusive with it). 

momenta : int or 1D array-like 

Either a number of sampling points on the interval [-pi, pi], or an 

array of points at which the band structure has to be evaluated. 

file : string or file object or `None` 

The output file. If `None`, output will be shown instead. 

show : bool 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. Defaults to `True`. 

dpi : float 

Number of pixels per inch. If not set the ``matplotlib`` default is 

used. 

fig_size : tuple 

Figure size `(width, height)` in inches. If not set, the default 

``matplotlib`` value is used. 

ax : ``matplotlib.axes.Axes`` instance or `None` 

If `ax` is not `None`, no new figure is created, but the plot is done 

within the existing Axes `ax`. in this case, `file`, `show`, `dpi` 

and `fig_size` are ignored. 

params : dict, optional 

Dictionary of parameter names and their values. Mutually exclusive 

with 'args'. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if `ax` is not set, else None. 

 

Notes 

----- 

See `~kwant.physics.Bands` for the calculation of dispersion without plotting. 

""" 

 

1405 ↛ 1406line 1405 didn't jump to line 1406, because the condition on line 1405 was never true if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for bands()") 

 

syst = sys # for naming consistency inside function bodies 

_common.ensure_isinstance(syst, system.InfiniteSystem) 

 

momenta = np.array(momenta) 

if momenta.ndim != 1: 

momenta = np.linspace(-np.pi, np.pi, momenta) 

 

# expand out the contents of 'physics.Bands' to get the H(k), 

# because 'spectrum' already does the diagonalisation. 

ham = syst.cell_hamiltonian(args, params=params) 

1419 ↛ 1420line 1419 didn't jump to line 1420, because the condition on line 1419 was never true if not np.allclose(ham, ham.conjugate().transpose()): 

raise ValueError('The cell Hamiltonian is not Hermitian.') 

_hop = syst.inter_cell_hopping(args, params=params) 

hop = np.empty(ham.shape, dtype=complex) 

hop[:, :_hop.shape[1]] = _hop 

hop[:, _hop.shape[1]:] = 0 

 

def h_k(k): 

# H_k = H_0 + V e^-ik + V^\dagger e^ik 

mat = hop * cmath.exp(-1j * k) 

mat += mat.conjugate().transpose() + ham 

return mat 

 

return spectrum(h_k, ('k', momenta), file=file, show=show, dpi=dpi, 

fig_size=fig_size, ax=ax) 

 

 

def spectrum(syst, x, y=None, params=None, mask=None, file=None, 

show=True, dpi=None, fig_size=None, ax=None): 

"""Plot the spectrum of a Hamiltonian as a function of 1 or 2 parameters 

 

Parameters 

---------- 

syst : `kwant.system.FiniteSystem` or callable 

If a function, then it must take named parameters and return the 

Hamiltonian as a dense matrix. 

x : pair ``(name, values)`` 

Parameter to ``ham`` that will be varied. Consists of the 

parameter name, and a sequence of parameter values. 

y : pair ``(name, values)``, optional 

Used for 3D plots (same as ``x``). If provided, then the cartesian 

product of the ``x`` values and these values will be used as a grid 

over which to evaluate the spectrum. 

params : dict, optional 

The rest of the parameters to ``ham``, which will be kept constant. 

mask : callable, optional 

Takes the parameters specified by ``x`` and ``y`` and returns True 

if the spectrum should not be calculated for the given parameter 

values. 

file : string or file object or `None` 

The output file. If `None`, output will be shown instead. 

show : bool 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. Defaults to `True`. 

dpi : float 

Number of pixels per inch. If not set the ``matplotlib`` default is 

used. 

fig_size : tuple 

Figure size `(width, height)` in inches. If not set, the default 

``matplotlib`` value is used. 

ax : ``matplotlib.axes.Axes`` instance or `None` 

If `ax` is not `None`, no new figure is created, but the plot is done 

within the existing Axes `ax`. in this case, `file`, `show`, `dpi` 

and `fig_size` are ignored. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if `ax` is not set, else None. 

""" 

 

1480 ↛ 1481line 1480 didn't jump to line 1481, because the condition on line 1480 was never true if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for plot_spectrum()") 

1483 ↛ 1484line 1483 didn't jump to line 1484, because the condition on line 1483 was never true if y is not None and not _p.has3d: 

raise RuntimeError("Installed matplotlib does not support 3d plotting") 

 

if isinstance(syst, system.FiniteSystem): 

def ham(**kwargs): 

return syst.hamiltonian_submatrix(params=kwargs, sparse=False) 

1489 ↛ 1492line 1489 didn't jump to line 1492, because the condition on line 1489 was never false elif callable(syst): 

ham = syst 

else: 

raise TypeError("Expected 'syst' to be a finite Kwant system " 

"or a function.") 

 

params = params or dict() 

keys = (x[0],) if y is None else (x[0], y[0]) 

array_values = (x[1],) if y is None else (x[1], y[1]) 

 

# calculate spectrum on the grid of points 

spectrum = [] 

bound_ham = functools.partial(ham, **params) 

for point in itertools.product(*array_values): 

p = dict(zip(keys, point)) 

if mask and mask(**p): 

spectrum.append(None) 

else: 

h_p = np.atleast_2d(bound_ham(**p)) 

spectrum.append(np.linalg.eigvalsh(h_p)) 

# massage masked grid points into a list of NaNs of the appropriate length 

n_eigvals = len(next(filter(lambda s: s is not None, spectrum))) 

nan_list = [np.nan] * n_eigvals 

spectrum = [nan_list if s is None else s for s in spectrum] 

# make into a numpy array and reshape 

new_shape = [len(v) for v in array_values] + [-1] 

spectrum = np.array(spectrum).reshape(new_shape) 

 

# set up axes 

if ax is None: 

fig = _make_figure(dpi, fig_size, use_pyplot=(file is None)) 

if y is None: 

ax = fig.add_subplot(1, 1, 1) 

else: 

warnings.filterwarnings('ignore', 

message=r'.*mouse rotation disabled.*') 

ax = fig.add_subplot(1, 1, 1, projection='3d') 

warnings.resetwarnings() 

ax.set_xlabel(keys[0]) 

if y is None: 

ax.set_ylabel('Energy') 

else: 

ax.set_ylabel(keys[1]) 

ax.set_zlabel('Energy') 

ax.set_title( 

', '.join( 

'{} = {}'.format(key, value) 

for key, value in params.items() 

if not callable(value) 

) 

) 

else: 

fig = None 

 

# actually do the plot 

if y is None: 

ax.plot(array_values[0], spectrum) 

else: 

if not hasattr(ax, 'plot_surface'): 

msg = ("When providing an axis for plotting over a 2D domain the " 

"axis should be created with 'projection=\"3d\"") 

raise TypeError(msg) 

# plot_surface cannot directly handle rank-3 values, so we 

# explicitly loop over the last axis 

grid = np.meshgrid(*array_values) 

for i in range(spectrum.shape[-1]): 

spec = spectrum[:, :, i].transpose() # row-major to x-y ordering 

ax.plot_surface(*(grid + [spec]), cstride=1, rstride=1) 

 

_maybe_output_fig(fig, file=file, show=show) 

 

return fig 

 

 

# Smoothing functions used with 'interpolate_current'. 

 

# Convolution kernel with finite support: 

# f(r) = (1-r^2)^2 Θ(1-r^2) 

def _bump(r): 

r[r > 1] = 1 

m = 1 - r * r 

return m * m 

 

 

# We generate the smoothing function by convolving the current 

# defined on a line between the two sites with 

# f(ρ, z) = (1 - ρ^2 - z^2)^2 Θ(1 - ρ^2 - z^2), where ρ and z are 

# cylindrical coords defined with respect to the hopping. 

# 'F' is the result of the convolution. 

def _smoothing(rho, z): 

r = 1 - rho * rho 

r[r < 0] = 0 

r = np.sqrt(r) 

m = np.clip(z, -r, r) 

rr = r * r 

rrrr = rr * rr 

mm = m * m 

return m * (mm * (mm/5 - (2/3) * rr) + rrrr) + (8 / 15) * rrrr * r 

 

 

# We need to normalize the smoothing function so that it has unit cross 

# section in the plane perpendicular to the hopping. This is equivalent 

# to normalizing the integral of 'f' over the unit hypersphere to 1. 

# The smoothing function goes as F(ρ) = (16/15) (1 - ρ^2)^(5/2) in the 

# plane perpendicular to the hopping, so the cross section is: 

# A_n = (16 / 15) * σ_n * ∫_0^1 ρ^(n-1) (1 - ρ^2)^(5/2) dρ 

# where σ_n is the surface element prefactor (2 in 2D, 2π in 3D). Rather 

# that calculate A_n every time, we hard code its value for 1, 2 and 3D. 

_smoothing_cross_sections = [16 / 15, np.pi / 3, 32 * np.pi / 105] 

 

 

# Determine the optimal bump function width from the absolute and 

# relative widths provided, and the lengths of all the hoppings in the system 

def _optimal_width(lens, abswidth, relwidth, bbox_size): 

if abswidth is None: 

if relwidth is None: 

unique_lens = np.unique(lens) 

longest = unique_lens[-1] 

1607 ↛ 1610line 1607 didn't jump to line 1610, because the loop on line 1607 didn't complete for shortest_nonzero in unique_lens: 

1608 ↛ 1607line 1608 didn't jump to line 1607, because the condition on line 1608 was never false if shortest_nonzero / longest > 1e-3: 

break 

width = 4 * shortest_nonzero 

else: 

width = relwidth * np.max(bbox_size) 

else: 

width = abswidth 

 

return width 

 

 

# Create empty field array that covers the bounding box plus 

# some additional padding 

def _create_field(dim, bbox_size, width, n, is_current): 

field_shape = np.zeros(dim + 1, int) 

field_shape[dim] = dim if is_current else 1 

for d in range(dim): 

field_shape[d] = int(bbox_size[d] * n / width + n) 

if field_shape[d] % 2: 

field_shape[d] += 1 

field = np.zeros(field_shape) 

# padding is width / 2 

return field, width / 2 

 

 

def density_kernel(coords): 

r = np.sqrt(np.sum(coords * coords)) 

return _bump(r)[..., None] 

 

 

def current_kernel(coords, direction, length): 

z = np.dot(coords, direction) 

rho = np.sqrt(np.abs(np.sum(coords * coords) - z * z)) 

magn = (_smoothing(rho, z) - _smoothing(rho, z - length)) 

return direction * magn[..., None] 

 

 

# interpolate a discrete scalar or vector field. 

def _interpolate_field(dim, elements, discrete_field, bbox, width, 

padding, field_out): 

 

field_shape = np.array(field_out.shape) 

bbox_min, bbox_max = bbox 

 

scale = 2 / width 

 

# if density elements is shape (nsites, dim) 

# if current elements is shape (nhops, 2, dim) 

assert elements.shape[-1] == dim 

is_current = len(elements.shape) == 3 

if is_current: 

assert elements.shape[1] == 2 

dirs = elements[:, 1] - elements[:, 0] 

lens = np.sqrt(np.sum(dirs * dirs, axis=-1)) 

dirs /= lens[:, None] 

lens = lens * scale 

 

if is_current: 

pos_offsets = elements[:, 0] # first site in hopping 

kernel = current_kernel 

else: 

pos_offsets = elements # sites themselves 

kernel = density_kernel 

 

region = [np.linspace(bbox_min[d] - padding, 

bbox_max[d] + padding, 

field_shape[d]) 

for d in range(dim)] 

 

grid_density = (field_shape[:dim] - 1) / (bbox_max + 2*padding - bbox_min) 

 

# slices for indexing 'field' and 'region' array 

slices = np.empty((len(discrete_field), dim, 2), int) 

if is_current: 

mn = np.min(elements, 1) 

mx = np.max(elements, 1) 

else: 

mn = mx = elements 

slices[:, :, 0] = np.floor((mn - bbox_min) * grid_density) 

slices[:, :, 1] = np.ceil((mx + 2*padding - bbox_min) * grid_density) 

 

for i in range(len(discrete_field)): 

 

1691 ↛ 1693line 1691 didn't jump to line 1693, because the condition on line 1691 was never true if not np.diff(slices[i]).all() or not discrete_field[i]: 

# Zero volume or zero field: nothing to do. 

continue 

 

field_slice = tuple([slice(*slices[i, d]) for d in range(dim)]) 

 

# Coordinates of the grid points that are within range of the current 

# hopping. 

coords = np.meshgrid(*[region[d][field_slice[d]] for d in range(dim)], 

sparse=True, indexing='ij') 

 

# Convert "coords" into scaled distances from pos_offset 

coords -= pos_offsets[i] 

coords *= scale 

magns = kernel(coords, dirs[i], lens[i]) if is_current else kernel(coords) 

magns *= discrete_field[i] 

 

field_out[field_slice] += magns 

 

field_out *= scale / _smoothing_cross_sections[dim - 1] 

 

 

def interpolate_current(syst, current, relwidth=None, abswidth=None, n=9): 

"""Interpolate currents in a system onto a regular grid. 

 

The system graph together with current intensities defines a "discrete" 

current density field where the current density is non-zero only on the 

straight lines that connect sites that are coupled by a hopping term. 

 

To make this vector field easier to visualize and interpret at different 

length scales, it is smoothed by convoluting it with the bell-shaped bump 

function ``f(r) = max(1 - (2*r / width)**2, 0)**2``. The bump width is 

determined by the `relwidth` and `abswidth` parameters. 

 

This routine samples the smoothed field on a regular (square or cubic) 

grid. 

 

Parameters 

---------- 

syst : A finalized system 

The system on which we are going to calculate the field. 

current : '1D array of float' 

Must contain the intensity on each hoppings in the same order that they 

appear in syst.graph. 

relwidth : float or `None` 

Relative width of the bumps used to generate the field, as a fraction 

of the length of the longest side of the bounding box. This argument 

is only used if `abswidth` is not given. 

abswidth : float or `None` 

Absolute width of the bumps used to generate the field. Takes 

precedence over `relwidth`. If neither is given, the bump width is set 

to four times the length of the shortest hopping. 

n : int 

Number of points the grid must have over the width of the bump. 

 

Returns 

------- 

field : n-d arraylike of float 

n-d array of n-d vectors. 

box : sequence of 2-sequences of float 

the extents of `field`: ((x0, x1), (y0, y1), ...) 

 

""" 

if not isinstance(syst, builder.FiniteSystem): 

raise TypeError("The system needs to be finalized.") 

 

1757 ↛ 1758line 1757 didn't jump to line 1758, because the condition on line 1757 was never true if len(current) != syst.graph.num_edges: 

raise ValueError("Current and hoppings arrays do not have the same" 

" length.") 

 

# hops: hoppings (pairs of points) 

dim = len(syst.sites[0].pos) 

hops = np.empty((syst.graph.num_edges // 2, 2, dim)) 

# Take the average of the current flowing each way along the hoppings 

current_one_way = np.empty(syst.graph.num_edges // 2) 

seen_hoppings = dict() 

kprime = 0 

for k, (i, j) in enumerate(syst.graph): 

if (j, i) in seen_hoppings: 

current_one_way[seen_hoppings[j, i]] -= current[k] 

else: 

current_one_way[kprime] = current[k] 

hops[kprime][0] = syst.sites[j].pos 

hops[kprime][1] = syst.sites[i].pos 

seen_hoppings[i, j] = kprime 

kprime += 1 

current = current_one_way / 2 

 

min_hops = np.min(hops, 1) 

max_hops = np.max(hops, 1) 

bbox_min = np.min(min_hops, 0) 

bbox_max = np.max(max_hops, 0) 

bbox_size = bbox_max - bbox_min 

 

# lens: scaled lengths of hoppings 

# dirs: normalized directions of hoppings 

dirs = hops[:, 1] - hops[:, 0] 

lens = np.sqrt(np.sum(dirs * dirs, -1)) 

dirs /= lens[:, None] 

width = _optimal_width(lens, abswidth, relwidth, bbox_size) 

 

 

field, padding = _create_field(dim, bbox_size, width, n, is_current=True) 

boundaries = tuple((bbox_min[d] - padding, bbox_max[d] + padding) 

for d in range(dim)) 

_interpolate_field(dim, hops, current, 

(bbox_min, bbox_max), width, padding, field) 

 

return field, boundaries 

 

 

def interpolate_density(syst, density, relwidth=None, abswidth=None, n=9, 

mask=True): 

"""Interpolate density in a system onto a regular grid. 

 

The system sites together with a scalar for each site defines a "discrete" 

density field where the density is non-zero only at the site positions. 

 

To make this vector field easier to visualize and interpret at different 

length scales, it is smoothed by convoluting it with the bell-shaped bump 

function ``f(r) = max(1 - (2*r / width)**2, 0)**2``. The bump width is 

determined by the `relwidth` and `abswidth` parameters. 

 

This routine samples the smoothed field on a regular (square or cubic) 

grid. 

 

Parameters 

---------- 

syst : A finalized system 

The system on which we are going to calculate the field. 

density : 1D array of float 

Must contain the intensity on each site in the same order that they 

appear in syst.sites. 

relwidth : float, optional 

Relative width of the bumps used to smooth the field, as a fraction 

of the length of the longest side of the bounding box. This argument 

is only used if ``abswidth`` is not given. 

abswidth : float, optional 

Absolute width of the bumps used to smooth the field. Takes 

precedence over ``relwidth``. If neither is given, the bump width is set 

to four times the length of the shortest hopping. 

n : int 

Number of points the grid must have over the width of the bump. 

mask : Bool 

If True, this function returns a masked array that masks positions that 

are too far away from any sites. This is useful for showing an approximate 

outline of the system when the field is plotted. 

 

Returns 

------- 

field : n-d arraylike of float 

n-d array of n-d vectors. 

box : sequence of 2-sequences of float 

the extents of ``field``: ((x0, x1), (y0, y1), ...) 

 

""" 

if not isinstance(syst, builder.FiniteSystem): 

raise TypeError("The system needs to be finalized.") 

 

1850 ↛ 1851line 1850 didn't jump to line 1851, because the condition on line 1850 was never true if len(density) != len(syst.sites): 

raise ValueError("Density and sites arrays do not have the same" 

" length.") 

 

dim = len(syst.sites[0].pos) 

sites = np.array([s.pos for s in syst.sites]) 

 

bbox_min = np.min(sites, axis=0) 

bbox_max = np.max(sites, axis=0) 

bbox_size = bbox_max - bbox_min 

 

# Determine the optimal width for the bump function 

dirs = np.array([syst.sites[i].pos - syst.sites[j].pos 

for i, j in syst.graph]) 

lens = np.sqrt(np.sum(dirs * dirs, -1)) 

width = _optimal_width(lens, abswidth, relwidth, bbox_size) 

 

field, padding = _create_field(dim, bbox_size, width, n, is_current=False) 

boundaries = tuple((bbox_min[d] - padding, bbox_max[d] + padding) 

for d in range(dim)) 

_interpolate_field(dim, sites, density, 

(bbox_min, bbox_max), width, padding, field) 

 

1873 ↛ 1881line 1873 didn't jump to line 1881, because the condition on line 1873 was never false if mask: 

# Field is zero when we are > 0.5*width from any site (as bump has 

# finite support), so we mask positions a little further than this. 

field = _mask(field, 

box=boundaries, 

coords=np.array([s.pos for s in syst.sites]), 

cutoff=0.6*width) 

 

return field, boundaries 

 

 

def _gamma_compress(linear): 

"""Compress linear sRGB into sRGB.""" 

if linear <= 0.0031308: 

return 12.92 * linear 

else: 

a = 0.055 

return (1 + a) * linear ** (1 / 2.4) - a 

 

_gamma_compress = np.vectorize(_gamma_compress, otypes=[float]) 

 

 

def _gamma_expand(corrected): 

"""Expand sRGB into linear sRGB.""" 

if corrected <= 0.04045: 

return corrected / 12.92 

else: 

a = 0.055 

return ((corrected + a) / (1 + a))**2.4 

 

_gamma_expand = np.vectorize(_gamma_expand, otypes=[float]) 

 

 

def _linear_cmap(a, b): 

"""Make a colormap that linearly interpolates between the colors a and b.""" 

a = _p.matplotlib.colors.colorConverter.to_rgb(a) 

b = _p.matplotlib.colors.colorConverter.to_rgb(b) 

a_linear = _gamma_expand(a) 

b_linear = _gamma_expand(b) 

color_diff = a_linear - b_linear 

palette = (np.linspace(0, 1, 256).reshape((-1, 1)) 

* color_diff.reshape((1, -1))) 

palette += b_linear 

palette = _gamma_compress(palette) 

return _p.matplotlib.colors.ListedColormap(palette) 

 

 

def streamplot(field, box, cmap=None, bgcolor=None, linecolor='k', 

max_linewidth=3, min_linewidth=1, density=2/9, 

colorbar=True, file=None, 

show=True, dpi=None, fig_size=None, ax=None, 

vmax=None): 

"""Draw streamlines of a flow field in Kwant style 

 

Solid colored streamlines are drawn, superimposed on a color plot of 

the flow speed that may be disabled by setting `bgcolor`. The width 

of the streamlines is proportional to the flow speed. Lines that 

would be thinner than `min_linewidth` are blended in a perceptually 

correct way into the background color in order to create the 

illusion of arbitrarily thin lines. (This is done because some plot 

backends like PDF do not support lines of arbitrarily thin width.) 

 

Internally, this routine uses matplotlib's streamplot. 

 

Parameters 

---------- 

field : 3d arraylike of float 

2d array of 2d vectors. 

box : 2-sequence of 2-sequences of float 

the extents of `field`: ((x0, x1), (y0, y1)) 

cmap : colormap, optional 

Colormap for the background color plot. When not set the colormap 

"kwant_red" is used by default, unless `bgcolor` is set. 

bgcolor : color definition, optional 

The solid color of the background. Mutually exclusive with `cmap`. 

linecolor : color definition 

Color of the flow lines. 

max_linewidth : float 

Width of lines at maximum flow speed. 

min_linewidth : float 

Minimum width of lines before blending into the background color begins. 

density : float 

Number of flow lines per point of the field. The default value 

of 2/9 is chosen to show two lines per default width of the 

interpolation bump of `~kwant.plotter.interpolate_current`. 

colorbar : bool 

Whether to show a colorbar if a colormap is used. Ignored if `ax` is 

provided. 

file : string or file object or `None` 

The output file. If `None`, output will be shown instead. 

show : bool 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. Defaults to `True`. 

dpi : float or `None` 

Number of pixels per inch. If not set the ``matplotlib`` default is 

used. 

fig_size : tuple or `None` 

Figure size `(width, height)` in inches. If not set, the default 

``matplotlib`` value is used. 

ax : ``matplotlib.axes.Axes`` instance or `None` 

If `ax` is not `None`, no new figure is created, but the plot is done 

within the existing Axes `ax`. in this case, `file`, `show`, `dpi` 

and `fig_size` are ignored. 

vmax : float or `None` 

The upper saturation limit for the colormap; flows higher than 

this will saturate. Note that there is no corresponding vmin 

option, vmin being fixed at zero. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if `ax` is not set, else None. 

""" 

1986 ↛ 1987line 1986 didn't jump to line 1987, because the condition on line 1986 was never true if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for current()") 

 

# Matplotlib's "density" is in units of 30 streamlines... 

density *= 1 / 30 * ta.array(field.shape[:2], int) 

 

# Matplotlib plots images like matrices: image[y, x]. We use the opposite 

# convention: image[x, y]. Hence, it is necessary to transpose. 

field = field.transpose(1, 0, 2) 

 

1997 ↛ 1998line 1997 didn't jump to line 1998, because the condition on line 1997 was never true if field.shape[-1] != 2 or field.ndim != 3: 

raise ValueError("Only 2D field can be plotted.") 

 

2000 ↛ 2005line 2000 didn't jump to line 2005, because the condition on line 2000 was never false if bgcolor is None: 

2001 ↛ 2003line 2001 didn't jump to line 2003, because the condition on line 2001 was never false if cmap is None: 

cmap = _p._colormaps.kwant_red 

cmap = _p.matplotlib.cm.get_cmap(cmap) 

bgcolor = cmap(0)[:3] 

elif cmap is not None: 

raise ValueError("The parameters 'cmap' and 'bgcolor' are " 

"mutually exclusive.") 

 

if ax is None: 

fig = _make_figure(dpi, fig_size, use_pyplot=(file is None)) 

ax = fig.add_subplot(1, 1, 1, aspect='equal') 

else: 

fig = None 

 

X = np.linspace(*box[0], num=field.shape[1]) 

Y = np.linspace(*box[1], num=field.shape[0]) 

 

speed = np.linalg.norm(field, axis=-1) 

2019 ↛ 2022line 2019 didn't jump to line 2022, because the condition on line 2019 was never false if vmax is None: 

vmax = np.max(speed) or 1 

 

2022 ↛ 2023line 2022 didn't jump to line 2023, because the condition on line 2022 was never true if cmap is None: 

ax.set_axis_bgcolor(bgcolor) 

else: 

image = ax.imshow(speed, cmap=cmap, 

interpolation='bicubic', 

extent=[e for c in box for e in c], 

origin='lower', vmin=0, vmax=vmax) 

 

linewidth = max_linewidth / vmax * speed 

color = linewidth / min_linewidth 

thin = linewidth < min_linewidth 

linewidth[thin] = min_linewidth 

color[~ thin] = 1 

 

line_cmap = _linear_cmap(linecolor, bgcolor) 

 

ax.streamplot(X, Y, field[:,:,0], field[:,:,1], 

density=density, linewidth=linewidth, 

color=color, cmap=line_cmap, arrowstyle='->', 

norm=_p.matplotlib.colors.Normalize(0, 1)) 

 

ax.set_xlim(*box[0]) 

ax.set_ylim(*box[1]) 

 

if colorbar and cmap and fig is not None: 

fig.colorbar(image) 

 

_maybe_output_fig(fig, file=file, show=show) 

 

return fig 

 

 

def scalarplot(field, box, 

cmap=None, colorbar=True, file=None, show=True, 

dpi=None, fig_size=None, ax=None, vmin=None, vmax=None, 

background='#e0e0e0'): 

"""Draw a scalar field in Kwant style 

 

Internally, this routine uses matplotlib's imshow. 

 

Parameters 

---------- 

field : 2d arraylike of float 

2d scalar field to plot. 

box : pair of pair of float 

the realspace extents of ``field``: ((x0, x1), (y0, y1)) 

cmap : colormap, optional 

Colormap for the background color plot. When not set the colormap 

"kwant_red" is used by default. 

colorbar : bool, default: True 

Whether to show a colorbar if a colormap is used. Ignored if `ax` is 

provided. 

file : string or file object, optional 

The output file. If not provided, output will be shown instead. 

show : bool, default: True 

Whether ``matplotlib.pyplot.show()`` is to be called, and the output is 

to be shown immediately. 

dpi : float, optional 

Number of pixels per inch. If not set the ``matplotlib`` default is 

used. 

fig_size : tuple, optional 

Figure size ``(width, height)`` in inches. If not set, the default 

``matplotlib`` value is used. 

ax : ``matplotlib.axes.Axes`` instance, optional 

If ``ax`` is provided, no new figure is created, but the plot is done 

within the existing Axes ``ax``. in this case, ``file``, ``show``, 

``dpi`` and ``fig_size`` are ignored. 

vmin, vmax : float, optional 

The lower/upper saturation limit for the colormap. 

background : matplotlib color spec 

Areas outside the system are filled with this color. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if ``ax`` is not set, else None. 

""" 

if not _p.mpl_available: 

raise RuntimeError("matplotlib was not found, but is required " 

"for current()") 

 

# Matplotlib plots images like matrices: image[y, x]. We use the opposite 

# convention: image[x, y]. Hence, it is necessary to transpose. 

# Also squeeze out the last axis as it is just a scalar field 

field = field.squeeze(axis=-1).transpose() 

 

if field.ndim != 2: 

raise ValueError("Only 2D field can be plotted.") 

 

if cmap is None: 

cmap = _p._colormaps.kwant_red 

cmap = _p.matplotlib.cm.get_cmap(cmap) 

 

if ax is None: 

fig = _make_figure(dpi, fig_size, use_pyplot=(file is None)) 

ax = fig.add_subplot(1, 1, 1, aspect='equal') 

else: 

fig = None 

 

if vmin is None: 

vmin = np.min(field) 

if vmax is None: 

vmax = np.max(field) 

 

image = ax.imshow(field, cmap=cmap, 

interpolation='bicubic', 

extent=[e for c in box for e in c], 

origin='lower', vmin=vmin, vmax=vmax) 

 

ax.set_xlim(*box[0]) 

ax.set_ylim(*box[1]) 

ax.patch.set_facecolor(background) 

 

if colorbar and cmap and fig is not None: 

fig.colorbar(image) 

 

_maybe_output_fig(fig, file=file, show=show) 

 

return fig 

 

 

def current(syst, current, relwidth=0.05, **kwargs): 

"""Show an interpolated current defined for the hoppings of a system. 

 

The system graph together with current intensities defines a "discrete" 

current density field where the current density is non-zero only on the 

straight lines that connect sites that are coupled by a hopping term. 

 

To make this scalar field easier to visualize and interpret at different 

length scales, it is smoothed by convoluting it with the bell-shaped bump 

function ``f(r) = max(1 - (2*r / width)**2, 0)**2``. The bump width is 

determined by the ``relwidth`` parameter. 

 

This routine samples the smoothed field on a regular (square or cubic) grid 

and displays it using an enhanced variant of matplotlib's streamplot. 

 

This is a convenience function that is equivalent to 

``streamplot(*interpolate_current(syst, current, relwidth), **kwargs)``. 

The longer form makes it possible to tweak additional options of 

`~kwant.plotter.interpolate_current`. 

 

Parameters 

---------- 

syst : `kwant.system.FiniteSystem` 

The system for which to plot the ``current``. 

current : sequence of float 

Sequence of values defining currents on each hopping of the system. 

Ordered in the same way as ``syst.graph``. This typically will be 

the result of evaluating a `~kwant.operator.Current` operator. 

relwidth : float or `None` 

Relative width of the bumps used to smooth the field, as a fraction 

of the length of the longest side of the bounding box. 

**kwargs : various 

Keyword args to be passed verbatim to `kwant.plotter.streamplot`. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if ``ax`` is not set, else None. 

 

See Also 

-------- 

kwant.plotter.density 

""" 

with _common.reraise_warnings(4): 

return streamplot(*interpolate_current(syst, current, relwidth), 

**kwargs) 

 

 

def _mask(field, box, coords, cutoff): 

tree = spatial.cKDTree(coords) 

 

# Build the mask initially as a 2D array 

dims = tuple(slice(boxmin, boxmax, 1j * shape) 

for (boxmin, boxmax), shape in zip(box, field.shape)) 

mask = np.mgrid[dims].reshape(len(box), -1).T 

 

mask = tree.query(mask, distance_upper_bound=cutoff)[0] == np.inf 

return np.ma.masked_array(field, mask) 

 

 

def density(syst, density, relwidth=0.05, **kwargs): 

"""Show an interpolated density defined on the sites of a system. 

 

The system sites, together with a scalar per site defines a "discrete" 

density field that is non-zero only on the sites. 

 

To make this scalar field easier to visualize and interpret at different 

length scales, it is smoothed by convoluting it with the bell-shaped bump 

function ``f(r) = max(1 - (2*r / width)**2, 0)**2``. The bump width is 

determined by the ``relwidth`` parameter. 

 

This routine samples the smoothed field on a regular (square or cubic) grid 

and displays it using matplotlib's imshow. 

 

This function is similar to `~kwant.plotter.map`, but generally gives more 

appealing visual results when used on systems with many sites. If you want 

site-level resolution you may be better off using `~kwant.plotter.map`. 

 

This is a convenience function that is equivalent to 

``scalarplot(*interpolate_density(syst, density, relwidth), **kwargs)``. 

The longer form makes it possible to tweak additional options of 

`~kwant.plotter.interpolate_density`. 

 

Parameters 

---------- 

syst : `kwant.system.FiniteSystem` 

The system for which to plot ``density``. 

density : sequence of float 

Sequence of values defining density on each site of the system. 

Ordered in the same way as ``syst.sites``. This typically will be 

the result of evaluating a `~kwant.operator.Density` operator. 

relwidth : float or `None` 

Relative width of the bumps used to smooth the field, as a fraction 

of the length of the longest side of the bounding box. 

**kwargs : various 

Keyword args to be passed verbatim to `~kwant.plotter.scalarplot`. 

 

Returns 

------- 

fig : matplotlib figure 

A figure with the output if ``ax`` is not set, else None. 

 

See Also 

-------- 

kwant.plotter.current 

kwant.plotter.map 

""" 

with _common.reraise_warnings(4): 

return scalarplot(*interpolate_density(syst, density, relwidth), 

**kwargs) 

 

 

# TODO (Anton): Fix plotting of parts of the system using color = np.nan. 

# Not plotting sites currently works, not plotting hoppings does not. 

# TODO (Anton): Allow a more flexible treatment of position than pos_transform 

# (an interface for user-defined pos).