Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • kwant/kwant
  • jbweston/kwant
  • anton-akhmerov/kwant
  • cwg/kwant
  • Mathieu/kwant
  • slavoutich/kwant
  • pacome/kwant
  • behrmann/kwant
  • michaelwimmer/kwant
  • albeercik/kwant
  • eunjongkim/kwant
  • basnijholt/kwant
  • r-j-skolasinski/kwant
  • sahmed95/kwant
  • pablopiskunow/kwant
  • mare/kwant
  • dvarjas/kwant
  • Paul/kwant
  • bbuijtendorp/kwant
  • tkloss/kwant
  • torosdahl/kwant
  • kel85uk/kwant
  • kpoyhonen/kwant
  • Fromeworld/kwant
  • quaeritis/kwant
  • marwahaha/kwant
  • fernandodfufrpe/kwant
  • oly/kwant
  • jiamingh/kwant
  • mehdi2369/kwant
  • ValFadeev/kwant
  • Kostas/kwant
  • chelseabaptiste03/kwant
33 results
Show changes
......@@ -19,7 +19,7 @@ from pytest import raises, warns
from numpy.testing import assert_almost_equal
import kwant
from kwant import builder
from kwant import builder, system
from kwant._common import ensure_rng
......@@ -28,7 +28,7 @@ def test_bad_keys():
def setitem(key):
syst[key] = None
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
syst = builder.Builder()
failures = [
......@@ -97,9 +97,9 @@ def test_bad_keys():
def test_site_families():
syst = builder.Builder()
fam = builder.SimpleSiteFamily()
ofam = builder.SimpleSiteFamily()
yafam = builder.SimpleSiteFamily('another_name')
fam = builder.SimpleSiteFamily(norbs=1)
ofam = builder.SimpleSiteFamily(norbs=1)
yafam = builder.SimpleSiteFamily('another_name', norbs=1)
syst[fam(0)] = 7
assert syst[fam(0)] == 7
......@@ -162,7 +162,7 @@ class VerySimpleSymmetry(builder.Symmetry):
# made.
def check_construction_and_indexing(sites, sites_fd, hoppings, hoppings_fd,
unknown_hoppings, sym=None):
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
syst = builder.Builder(sym)
t, V = 1.0j, 0.0
syst[sites] = V
......@@ -212,7 +212,7 @@ def check_construction_and_indexing(sites, sites_fd, hoppings, hoppings_fd,
def test_construction_and_indexing():
# Without symmetry
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
sites = [fam(0, 0), fam(0, 1), fam(1, 0)]
hoppings = [(fam(0, 0), fam(0, 1)),
(fam(0, 1), fam(1, 0)),
......@@ -250,7 +250,7 @@ def test_hermitian_conjugation():
raise ValueError
syst = builder.Builder()
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
syst[fam(0)] = syst[fam(1)] = ta.identity(2)
syst[fam(0), fam(1)] = f
......@@ -266,7 +266,7 @@ def test_hermitian_conjugation():
def test_value_equality_and_identity():
m = ta.array([[1, 2], [3j, 4j]])
syst = builder.Builder()
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
syst[fam(0)] = m
syst[fam(1)] = m
......@@ -378,7 +378,7 @@ def test_finalization():
# Build scattering region from blueprint and test it.
syst = builder.Builder()
fam = kwant.lattice.general(ta.identity(2))
fam = kwant.lattice.general(ta.identity(2), norbs=1)
for site, value in sr_sites.items():
syst[fam(*site)] = value
for hop, value in sr_hops.items():
......@@ -421,12 +421,12 @@ def test_finalization():
# Attach lead with improper interface.
syst.leads[-1] = builder.BuilderLead(
lead, 2 * tuple(builder.Site(fam, n) for n in neighbors))
lead, 2 * tuple(system.Site(fam, n) for n in neighbors))
raises(ValueError, syst.finalized)
# Attach lead properly.
syst.leads[-1] = builder.BuilderLead(
lead, (builder.Site(fam, n) for n in neighbors))
lead, (system.Site(fam, n) for n in neighbors))
fsyst = syst.finalized()
assert len(fsyst.lead_interfaces) == 1
assert ([fsyst.sites[i].tag for i in fsyst.lead_interfaces[0]] ==
......@@ -434,15 +434,15 @@ def test_finalization():
# test that we cannot finalize a system with a badly sorted interface order
raises(ValueError, builder.InfiniteSystem, lead,
[builder.Site(fam, n) for n in reversed(neighbors)])
[system.Site(fam, n) for n in reversed(neighbors)])
# site ordering independent of whether interface was specified
flead_order = builder.InfiniteSystem(lead, [builder.Site(fam, n)
flead_order = builder.InfiniteSystem(lead, [system.Site(fam, n)
for n in neighbors])
assert flead.sites == flead_order.sites
syst.leads[-1] = builder.BuilderLead(
lead, (builder.Site(fam, n) for n in neighbors))
lead, (system.Site(fam, n) for n in neighbors))
fsyst = syst.finalized()
assert len(fsyst.lead_interfaces) == 1
assert ([fsyst.sites[i].tag for i in fsyst.lead_interfaces[0]] ==
......@@ -488,8 +488,11 @@ def test_site_ranges():
ranges = syst.finalized().site_ranges
expected = [(0, lat.norbs, 0), (10, 0, 10 * lat.norbs)]
assert ranges == expected
# poison system with a single site with no norbs defined
syst[kwant.lattice.chain()(0)] = 1
# poison system with a single site with no norbs defined.
# Also catch the deprecation warning.
with warnings.catch_warnings():
warnings.simplefilter("ignore")
syst[kwant.lattice.chain(norbs=None)(0)] = 1
ranges = syst.finalized().site_ranges
assert ranges == None
......@@ -506,7 +509,7 @@ def test_hamiltonian_evaluation():
edges = [(0, 1), (0, 2), (0, 3), (1, 2)]
syst = builder.Builder()
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
sites = [fam(*tag) for tag in tags]
syst[(fam(*tag) for tag in tags)] = f_onsite
syst[((fam(*tags[i]), fam(*tags[j])) for (i, j) in edges)] = f_hopping
......@@ -570,7 +573,7 @@ def test_dangling():
# / \
# 3-0---2-4-5 6-7 8
syst = builder.Builder()
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
syst[(fam(i) for i in range(9))] = None
syst[[(fam(0), fam(1)), (fam(1), fam(2)), (fam(2), fam(0))]] = None
syst[[(fam(0), fam(3)), (fam(2), fam(4)), (fam(4), fam(5))]] = None
......@@ -596,7 +599,7 @@ def test_dangling():
def test_builder_with_symmetry():
g = kwant.lattice.general(ta.identity(3))
g = kwant.lattice.general(ta.identity(3), norbs=1)
sym = kwant.TranslationalSymmetry((0, 0, 3), (0, 2, 0))
syst = builder.Builder(sym)
......@@ -642,7 +645,7 @@ def test_builder_with_symmetry():
def test_fill():
g = kwant.lattice.square()
g = kwant.lattice.square(norbs=1)
sym_x = kwant.TranslationalSymmetry((-1, 0))
sym_xy = kwant.TranslationalSymmetry((-1, 0), (0, 1))
......@@ -658,7 +661,7 @@ def test_fill():
lambda pos: True),
(builder.NoSymmetry(),
lambda pos: ta.dot(pos, pos) < 17)]:
cubic = kwant.lattice.general(ta.identity(3))
cubic = kwant.lattice.general(ta.identity(3), norbs=1)
# Make a weird system.
orig = kwant.Builder(sym)
......@@ -769,7 +772,7 @@ def test_fill():
assert sorted(target.hoppings()) == sorted(should_be_syst.hoppings())
## test that 'fill' respects the symmetry of the target builder
lat = kwant.lattice.chain(a=1)
lat = kwant.lattice.chain(a=1, norbs=1)
template = builder.Builder(kwant.TranslationalSymmetry((-1,)))
template[lat(0)] = 2
template[lat.neighbors()] = -1
......@@ -796,7 +799,7 @@ def test_fill():
target.fill(template, lambda x: True, lat(0))
# Test for warning when one of the starting sites is outside the template
lat = kwant.lattice.square()
lat = kwant.lattice.square(norbs=1)
template = builder.Builder(kwant.TranslationalSymmetry((-1, 0)))
template[lat(0, 0)] = None
template[lat.neighbors()] = None
......@@ -811,7 +814,7 @@ def test_fill_sticky():
separately.
"""
# Generate model template.
lat = kwant.lattice.kagome()
lat = kwant.lattice.kagome(norbs=1)
template = kwant.Builder(kwant.TranslationalSymmetry(
lat.vec((1, 0)), lat.vec((0, 1))))
for i, sl in enumerate(lat.sublattices):
......@@ -844,7 +847,7 @@ def test_fill_sticky():
def test_attach_lead():
fam = builder.SimpleSiteFamily(norbs=1)
fam_noncommensurate = builder.SimpleSiteFamily(name='other')
fam_noncommensurate = builder.SimpleSiteFamily(name='other', norbs=1)
syst = builder.Builder()
syst[fam(1)] = 0
......@@ -901,7 +904,7 @@ def test_attach_lead():
def test_attach_lead_incomplete_unit_cell():
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
syst = kwant.Builder()
lead = kwant.Builder(kwant.TranslationalSymmetry((2,)))
syst[lat(1)] = lead[lat(0)] = lead[lat(1)] = 0
......@@ -912,7 +915,7 @@ def test_attach_lead_incomplete_unit_cell():
def test_neighbors_not_in_single_domain():
sr = builder.Builder()
lead = builder.Builder(VerySimpleSymmetry(-1))
fam = builder.SimpleSiteFamily()
fam = builder.SimpleSiteFamily(norbs=1)
sr[(fam(x, y) for x in range(3) for y in range(3) if x >= y)] = 0
sr[builder.HoppingKind((1, 0), fam)] = 1
sr[builder.HoppingKind((0, 1), fam)] = 1
......@@ -935,7 +938,7 @@ def test_closest():
rng = ensure_rng(10)
for sym_dim in range(1, 4):
for space_dim in range(sym_dim, 4):
lat = kwant.lattice.general(ta.identity(space_dim))
lat = kwant.lattice.general(ta.identity(space_dim), norbs=1)
# Choose random periods.
while True:
......@@ -967,7 +970,7 @@ def test_closest():
def test_update():
lat = builder.SimpleSiteFamily()
lat = builder.SimpleSiteFamily(norbs=1)
syst = builder.Builder()
syst[[lat(0,), lat(1,)]] = 1
......@@ -1006,8 +1009,8 @@ def test_update():
# ghgh hhgh
#
def test_HoppingKind():
g = kwant.lattice.general(ta.identity(3), name='some_lattice')
h = kwant.lattice.general(ta.identity(3), name='another_lattice')
g = kwant.lattice.general(ta.identity(3), name='some_lattice', norbs=1)
h = kwant.lattice.general(ta.identity(3), name='another_lattice', norbs=1)
sym = kwant.TranslationalSymmetry((0, 2, 0))
syst = builder.Builder(sym)
syst[((h if max(x, y, z) % 2 else g)(x, y, z)
......@@ -1047,8 +1050,8 @@ def test_HoppingKind():
def test_invalid_HoppingKind():
g = kwant.lattice.general(ta.identity(3))
h = kwant.lattice.general(np.identity(3)[:-1]) # 2D lattice in 3D
g = kwant.lattice.general(ta.identity(3), norbs=1)
h = kwant.lattice.general(np.identity(3)[:-1], norbs=1) # 2D lattice in 3D
delta = (1, 0, 0)
......@@ -1062,7 +1065,7 @@ def test_invalid_HoppingKind():
def test_ModesLead_and_SelfEnergyLead():
lat = builder.SimpleSiteFamily()
lat = builder.SimpleSiteFamily(norbs=1)
hoppings = [builder.HoppingKind((1, 0), lat),
builder.HoppingKind((0, 1), lat)]
rng = Random(123)
......@@ -1139,7 +1142,7 @@ def test_ModesLead_and_SelfEnergyLead():
def test_site_pickle():
site = kwant.lattice.square()(0, 0)
site = kwant.lattice.square(norbs=1)(0, 0)
assert pickle.loads(pickle.dumps(site)) == site
......@@ -1202,7 +1205,7 @@ def test_discrete_symmetries():
# all the deprecation warnings in the test logs
@pytest.mark.filterwarnings("ignore:.*'args' parameter")
def test_argument_passing():
chain = kwant.lattice.chain()
chain = kwant.lattice.chain(norbs=1)
# Test for passing parameters to hamiltonian matrix elements
def onsite(site, p1, p2):
......@@ -1272,7 +1275,7 @@ def test_argument_passing():
# Some common, some different args for value functions
def onsite2(site, a, b):
return site.pos + a + b
return site.pos[0] + a + b
def hopping2(site1, site2, a, c, b):
return a + b + c
......@@ -1336,7 +1339,7 @@ def test_subs():
salt = str(b) + str(c)
return kwant.digest.uniform(ta.array((sitea.tag, siteb.tag)), salt=salt)
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
def make_system(sym=kwant.builder.NoSymmetry(), n=3):
syst = kwant.Builder(sym)
......@@ -1389,7 +1392,7 @@ def test_subs():
assert lead.parameters == {'lead_a', 'lead_b', 'lead_c'}
def test_attach_stores_padding():
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
syst = kwant.Builder()
syst[lat(0)] = 0
lead = kwant.Builder(kwant.TranslationalSymmetry(lat.prim_vecs[0]))
......@@ -1400,7 +1403,7 @@ def test_attach_stores_padding():
def test_finalization_preserves_padding():
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
syst = kwant.Builder()
for i in range(10):
syst[lat(i)] = 0
......@@ -1416,3 +1419,28 @@ def test_finalization_preserves_padding():
syst = syst.finalized()
# The order is guaranteed because the paddings are sorted.
assert [syst.sites[i] for i in syst.lead_paddings[0]] == padding[:-1]
def test_add_peierls_phase():
lat = kwant.lattice.square(norbs=1)
syst = kwant.Builder()
syst[(lat(i, j) for i in range(5) for j in range(5))] = 4
syst[lat.neighbors()] = lambda a, b, t: -t
lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)))
lead[(lat(0, j) for j in range(5))] = 4
lead[lat.neighbors()] = -1
syst.attach_lead(lead)
syst.attach_lead(lead.reversed())
syst, phase = builder.add_peierls_phase(syst)
assert isinstance(syst, builder.FiniteSystem)
params = phase(1, 0, 0)
assert all(p in params for p in ('phi', 'phi_lead0', 'phi_lead1'))
kwant.smatrix(syst, energy=0.1, params=dict(t=-1, **params))
......@@ -18,7 +18,7 @@ def test_qhe(W=16, L=8):
x, y = pos
return -L < x < L and abs(y) < W - 5.5 * math.exp(-x**2 / 5**2)
lat = kwant.lattice.square()
lat = kwant.lattice.square(norbs=1)
syst = kwant.Builder()
syst[lat.shape(central_region, (0, 0))] = onsite
......
......@@ -6,6 +6,7 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
import warnings
from math import sqrt
import numpy as np
import tinyarray as ta
......@@ -17,40 +18,42 @@ import pytest
def test_closest():
rng = ensure_rng(4)
lat = lattice.general(((1, 0), (0.5, sqrt(3)/2)))
lat = lattice.general(((1, 0), (0.5, sqrt(3)/2)), norbs=1)
for i in range(50):
point = 20 * rng.random_sample(2)
closest = lat(*lat.closest(point)).pos
assert np.linalg.norm(point - closest) <= 1 / sqrt(3)
lat = lattice.general(rng.randn(3, 3))
lat = lattice.general(rng.randn(3, 3), norbs=1)
for i in range(50):
tag = rng.randint(10, size=(3,))
assert lat.closest(lat(*tag).pos) == tag
def test_general():
for lat in (lattice.general(((1, 0), (0.5, 0.5))),
for lat in (lattice.general(((1, 0), (0.5, 0.5)), norbs=1),
lattice.general(((1, 0), (0.5, sqrt(3)/2)),
((0, 0), (0, 1/sqrt(3))))):
((0, 0), (0, 1/sqrt(3))),
norbs=1,
)):
for sl in lat.sublattices:
tag = (-5, 33)
site = sl(*tag)
assert tag == sl.closest(site.pos)
# Test 2D lattice with 1 vector.
lat = lattice.general([[1, 0]])
lat = lattice.general([[1, 0]], norbs=1)
site = lat(0)
raises(ValueError, lat, 0, 1)
def test_neighbors():
lat = lattice.honeycomb(1e-10)
lat = lattice.honeycomb(1e-10, norbs=1)
num_nth_nearest = [len(lat.neighbors(n)) for n in range(5)]
assert num_nth_nearest == [2, 3, 6, 3, 6]
lat = lattice.general([(0, 1e8, 0, 0), (0, 0, 1e8, 0)])
lat = lattice.general([(0, 1e8, 0, 0), (0, 0, 1e8, 0)], norbs=1)
num_nth_nearest = [len(lat.neighbors(n)) for n in range(5)]
assert num_nth_nearest == [1, 2, 2, 2, 4]
lat = lattice.chain(1e-10)
lat = lattice.chain(1e-10, norbs=1)
num_nth_nearest = [len(lat.neighbors(n)) for n in range(5)]
assert num_nth_nearest == 5 * [1]
......@@ -59,7 +62,7 @@ def test_shape():
def in_circle(pos):
return pos[0] ** 2 + pos[1] ** 2 < 3
lat = lattice.honeycomb()
lat = lattice.honeycomb(norbs=1)
sites = list(lat.shape(in_circle, (0, 0))())
sites_alt = list()
sl0, sl1 = lat.sublattices
......@@ -88,7 +91,7 @@ def test_wire():
vecs = rng.randn(3, 3)
vecs[0] = [1, 0, 0]
center = rng.randn(3)
lat = lattice.general(vecs, rng.randn(4, 3))
lat = lattice.general(vecs, rng.randn(4, 3), norbs=1)
syst = builder.Builder(lattice.TranslationalSymmetry((2, 0, 0)))
def wire_shape(pos):
pos = np.array(pos)
......@@ -103,8 +106,8 @@ def test_wire():
def test_translational_symmetry():
ts = lattice.TranslationalSymmetry
f2 = lattice.general(np.identity(2))
f3 = lattice.general(np.identity(3))
f2 = lattice.general(np.identity(2), norbs=1)
f3 = lattice.general(np.identity(3), norbs=1)
shifted = lambda site, delta: site.family(*ta.add(site.tag, delta))
raises(ValueError, ts, (0, 0, 4), (0, 5, 0), (0, 0, 2))
......@@ -112,7 +115,7 @@ def test_translational_symmetry():
raises(ValueError, sym.add_site_family, f2)
# Test lattices with dimension smaller than dimension of space.
f2in3 = lattice.general([[4, 4, 0], [4, -4, 0]])
f2in3 = lattice.general([[4, 4, 0], [4, -4, 0]], norbs=1)
sym = ts((8, 0, 0))
sym.add_site_family(f2in3)
sym = ts((8, 0, 1))
......@@ -150,7 +153,7 @@ def test_translational_symmetry():
(site, shifted(site, hop)))
# Test act for hoppings belonging to different lattices.
f2p = lattice.general(2 * np.identity(2))
f2p = lattice.general(2 * np.identity(2), norbs=1)
sym = ts(*(2 * np.identity(2)))
assert sym.act((1, 1), f2(0, 0), f2p(0, 0)) == (f2(2, 2), f2p(1, 1))
assert sym.act((1, 1), f2p(0, 0), f2(0, 0)) == (f2p(1, 1), f2(2, 2))
......@@ -160,7 +163,7 @@ def test_translational_symmetry():
# generated symmetry with proper vectors.
rng = ensure_rng(30)
vec = rng.randn(3, 5)
lat = lattice.general(vec)
lat = lattice.general(vec, norbs=1)
total = 0
for k in range(1, 4):
for i in range(10):
......@@ -176,7 +179,7 @@ def test_translational_symmetry():
def test_translational_symmetry_reversed():
rng = ensure_rng(30)
lat = lattice.general(np.identity(3))
lat = lattice.general(np.identity(3), norbs=1)
sites = [lat(i, j, k) for i in range(-2, 6) for j in range(-2, 6)
for k in range(-2, 6)]
for i in range(4):
......@@ -194,9 +197,9 @@ def test_translational_symmetry_reversed():
def test_monatomic_lattice():
lat = lattice.square()
lat2 = lattice.general(np.identity(2))
lat3 = lattice.square(name='no')
lat = lattice.square(norbs=1)
lat2 = lattice.general(np.identity(2), norbs=1)
lat3 = lattice.square(name='no', norbs=1)
assert len(set([lat, lat2, lat3, lat(0, 0), lat2(0, 0), lat3(0, 0)])) == 4
@pytest.mark.parametrize('prim_vecs, basis', [
......@@ -210,16 +213,22 @@ def test_monatomic_lattice():
])
def test_lattice_constraints(prim_vecs, basis):
with pytest.raises(ValueError):
lattice.general(prim_vecs, basis)
lattice.general(prim_vecs, basis, norbs=1)
def test_norbs():
id_mat = np.identity(2)
# Monatomic lattices
assert lattice.general(id_mat).norbs == None
# Catch deprecation warning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
assert lattice.general(id_mat).norbs == None
assert lattice.general(id_mat, norbs=2).norbs == 2
# Polyatomic lattices
lat = lattice.general(id_mat, basis=id_mat, norbs=None)
# Catch deprecation warning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
lat = lattice.general(id_mat, basis=id_mat, norbs=None)
for l in lat.sublattices:
assert l.norbs == None
lat = lattice.general(id_mat, basis=id_mat, norbs=2)
......@@ -237,8 +246,14 @@ def test_norbs():
raises(ValueError, lattice.general, id_mat, norbs=1.5)
raises(ValueError, lattice.general, id_mat, id_mat, norbs=1.5)
raises(ValueError, lattice.general, id_mat, id_mat, norbs=[1.5, 1.5])
# should raise ValueError if norbs is <= 0
raises(ValueError, lattice.general, id_mat, norbs=0)
raises(ValueError, lattice.general, id_mat, norbs=-1)
# test that lattices with different norbs are compared `not equal`
lat = lattice.general(id_mat, basis=id_mat, norbs=None)
# Catch deprecation warning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
lat = lattice.general(id_mat, basis=id_mat, norbs=None)
lat1 = lattice.general(id_mat, basis=id_mat, norbs=1)
lat2 = lattice.general(id_mat, basis=id_mat, norbs=2)
assert lat != lat1
......@@ -247,7 +262,7 @@ def test_norbs():
def test_symmetry_act():
lat = lattice.square()
lat = lattice.square(norbs=1)
sym = lattice.TranslationalSymmetry((1, 0), (0, 1))
site = lat(0, 0)
hopping = (lat(0, 0), lat(1, 0))
......
......@@ -6,6 +6,7 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
import warnings
import functools as ft
from collections import deque
import pickle
......@@ -59,7 +60,10 @@ def test_operator_construction():
N = len(fsyst.sites)
# test construction failure if norbs not given
latnone = kwant.lattice.chain()
# Catch deprecation warning
with warnings.catch_warnings():
warnings.simplefilter("ignore")
latnone = kwant.lattice.chain()
syst[latnone(0)] = 1
for A in opservables:
raises(ValueError, A, syst.finalized())
......@@ -128,12 +132,35 @@ def test_operator_construction():
fwhere = tuple(fsyst.id_by_site[s] for s in where)
A = ops.Density(fsyst, where=where)
assert np.all(np.asarray(A.where).reshape(-1) == fwhere)
# Test for passing integers as 'where'
A = ops.Density(fsyst, where=fwhere)
assert np.all(np.asarray(A.where).reshape(-1) == fwhere)
# Test passing invalid sites
with raises(ValueError):
ops.Density(fsyst, where=[lat(100)])
with raises(ValueError):
ops.Density(fsyst, where=[-1])
with raises(ValueError):
ops.Density(fsyst, where=[10000])
where = [(lat(2, 2), lat(1, 2)), (lat(0, 0), lat(0, 1))]
fwhere = np.asarray([(fsyst.id_by_site[a], fsyst.id_by_site[b])
for a, b in where])
A = ops.Current(fsyst, where=where)
assert np.all(np.asarray(A.where) == fwhere)
# Test for passing integers as 'where'
A = ops.Current(fsyst, where=fwhere)
assert np.all(np.asarray(A.where) == fwhere)
# Test passing invalid hoppings
with raises(ValueError):
ops.Current(fsyst, where=[(lat(2, 2), lat(0, 0))])
with raises(ValueError):
ops.Current(fsyst, where=[(-1, 1)])
with raises(ValueError):
ops.Current(fsyst, where=[(len(fsyst.sites), 1)])
with raises(ValueError):
ops.Current(fsyst, where=[(fsyst.id_by_site[lat(2, 2)],
fsyst.id_by_site[lat(0, 0)])])
# test construction with `where` given by a function
tag_list = [(1, 0), (1, 1), (1, 2)]
......@@ -304,7 +331,7 @@ def test_opservables_spin():
down, up = kwant.wave_function(fsyst, energy=1., params=params)(0)
x_hoppings = kwant.builder.HoppingKind((1,), lat)
spin_current_z = ops.Current(fsyst, sigmaz, where=x_hoppings(syst))
spin_current_z = ops.Current(fsyst, sigmaz, where=list(x_hoppings(syst)))
_test(spin_current_z, up, params=params, per_el_val=1)
_test(spin_current_z, down, params=params, per_el_val=-1)
......@@ -366,12 +393,14 @@ def test_opservables_gauged():
(Us[i], sigmaz, Us[i].conjugate().transpose()))
x_hoppings = kwant.builder.HoppingKind((1,), lat)
spin_current_gauge = ops.Current(fsyst, M_a, where=x_hoppings(syst))
spin_current_gauge = ops.Current(fsyst, M_a,
where=list(x_hoppings(syst)))
_test(spin_current_gauge, up, per_el_val=1)
_test(spin_current_gauge, down, per_el_val=-1)
# check the reverse is also true
minus_x_hoppings = kwant.builder.HoppingKind((-1,), lat)
spin_current_gauge = ops.Current(fsyst, M_a, where=minus_x_hoppings(syst))
spin_current_gauge = ops.Current(fsyst, M_a,
where=list(minus_x_hoppings(syst)))
_test(spin_current_gauge, up, per_el_val=-1)
_test(spin_current_gauge, down, per_el_val=1)
......@@ -416,7 +445,7 @@ def test_arg_passing(A):
lat1 = kwant.lattice.chain(norbs=1)
syst = kwant.Builder()
syst[lat1(0)] = syst[lat1(1)] = lambda s0, a, b: s0.pos + a + b
syst[lat1(0)] = syst[lat1(1)] = lambda s0, a, b: s0.pos[0] + a + b
syst[lat1.neighbors()] = lambda s0, s1, a, b: a - b
fsyst = syst.finalized()
......
......@@ -91,7 +91,7 @@ def syst_2d(W=3, r1=3, r2=8):
def syst_3d(W=3, r1=2, r2=4, a=1, t=1.0):
lat = kwant.lattice.general(((a, 0, 0), (0, a, 0), (0, 0, a)))
lat = kwant.lattice.general(((a, 0, 0), (0, a, 0), (0, 0, a)), norbs=1)
syst = kwant.Builder()
def ring(pos):
......@@ -162,13 +162,29 @@ def test_plot_more_site_families_than_colors():
# https://gitlab.kwant-project.org/kwant/kwant/issues/257
ncolors = len(pyplot.rcParams['axes.prop_cycle'])
syst = kwant.Builder()
lattices = [kwant.lattice.square(name=i) for i in range(ncolors + 1)]
lattices = [kwant.lattice.square(name=i, norbs=1)
for i in range(ncolors + 1)]
for i, lat in enumerate(lattices):
syst[lat(i, 0)] = None
with tempfile.TemporaryFile('w+b') as out:
plotter.plot(syst, file=out)
@pytest.mark.skipif(not _plotter.mpl_available, reason="Matplotlib unavailable.")
def test_plot_raises_on_bad_site_spec():
syst = kwant.Builder()
lat = kwant.lattice.square(norbs=1)
syst[(lat(i, j) for i in range(5) for j in range(5))] = None
# Cannot provide site_size as an array when syst is a Builder
with pytest.raises(TypeError):
plotter.plot(syst, site_size=[1] * 25)
# Cannot provide site_size as an array when syst is a Builder
with pytest.raises(TypeError):
plotter.plot(syst, site_symbol=['o'] * 25)
def good_transform(pos):
x, y = pos
return y, x
......@@ -237,7 +253,7 @@ def test_spectrum():
def ham_2d(a, b, c):
return np.eye(2) * (a**2 + b**2 + c**2)
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
syst = kwant.Builder()
syst[(lat(i) for i in range(3))] = lambda site, a, b: a + b
syst[lat.neighbors()] = lambda site1, site2, c: c
......@@ -361,7 +377,7 @@ def _border_is_0(field):
def _test_border_0(interpolator):
## Test that current is always identically zero at box boundaries
syst = kwant.Builder()
lat = kwant.lattice.square()
lat = kwant.lattice.square(norbs=1)
syst[[lat(0, 0), lat(1, 0)]] = None
syst[(lat(0, 0), lat(1, 0))] = None
syst = syst.finalized()
......@@ -488,7 +504,7 @@ def test_current_interpolation():
### Tests on a divergence-free current (closed system)
lat = kwant.lattice.general([(1, 0), (0.5, np.sqrt(3) / 2)])
lat = kwant.lattice.general([(1, 0), (0.5, np.sqrt(3) / 2)], norbs=1)
syst = kwant.Builder()
sites = [lat(0, 0), lat(1, 0), lat(0, 1), lat(2, 2)]
syst[sites] = None
......
......@@ -17,7 +17,7 @@ from kwant._common import ensure_rng
def test_hamiltonian_submatrix():
syst = kwant.Builder()
chain = kwant.lattice.chain()
chain = kwant.lattice.chain(norbs=1)
for i in range(3):
syst[chain(i)] = 0.5 * i
for i in range(2):
......@@ -87,7 +87,7 @@ def test_hamiltonian_submatrix():
def test_pickling():
syst = kwant.Builder()
lead = kwant.Builder(symmetry=kwant.TranslationalSymmetry([1.]))
lat = kwant.lattice.chain()
lat = kwant.lattice.chain(norbs=1)
syst[lat(0)] = syst[lat(1)] = 0
syst[lat(0), lat(1)] = 1
lead[lat(0)] = syst[lat(1)] = 0
......
......@@ -37,7 +37,8 @@ def _simple_syst(lat, E=0, t=1+1j, sym=None):
def test_consistence_with_bands(kx=1.9, nkys=31):
kys = np.linspace(-np.pi, np.pi, nkys)
for lat in [kwant.lattice.honeycomb(), kwant.lattice.square()]:
for lat in [kwant.lattice.honeycomb(norbs=1),
kwant.lattice.square(norbs=1)]:
syst = _simple_syst(lat)
wa_keep_1 = wraparound(syst, keep=1).finalized()
wa_keep_none = wraparound(syst).finalized()
......@@ -56,7 +57,7 @@ def test_consistence_with_bands(kx=1.9, nkys=31):
def test_opposite_hoppings():
lat = kwant.lattice.square()
lat = kwant.lattice.square(norbs=1)
for val in [1j, lambda a, b: 1j]:
syst = kwant.Builder(kwant.TranslationalSymmetry((1, 1)))
......@@ -74,7 +75,8 @@ def test_opposite_hoppings():
def test_value_types(k=(-1.1, 0.5), E=2, t=1):
k = dict(zip(('k_x', 'k_y', 'k_z'), k))
sym_extents = [1, 2, 3]
lattices = [kwant.lattice.honeycomb(), kwant.lattice.square()]
lattices = [kwant.lattice.honeycomb(norbs=1),
kwant.lattice.square(norbs=1)]
lat_syms = [
(lat, kwant.TranslationalSymmetry(lat.vec((n, 0)), lat.vec((0, n))))
for n, lat in itertools.product(sym_extents, lattices)
......@@ -112,7 +114,7 @@ def test_value_types(k=(-1.1, 0.5), E=2, t=1):
def test_signatures():
lat = kwant.lattice.square()
lat = kwant.lattice.square(norbs=1)
syst = kwant.Builder(kwant.TranslationalSymmetry((-3, 0), (0, 1)))
# onsites and hoppings that will be bound as sites
syst[lat(-2, 0)] = 4
......@@ -162,7 +164,7 @@ def test_signatures():
def test_symmetry():
syst = _simple_syst(kwant.lattice.square())
syst = _simple_syst(kwant.lattice.square(norbs=1))
matrices = [np.random.rand(2, 2) for i in range(4)]
laws = (matrices, [(lambda a: m) for m in matrices])
......@@ -190,10 +192,10 @@ def test_symmetry():
@pytest.mark.skipif(not _plotter.mpl_available, reason="Matplotlib unavailable.")
def test_plot_2d_bands():
chain = kwant.lattice.chain()
square = kwant.lattice.square()
cube = kwant.lattice.general([(1, 0, 0), (0, 1, 0), (0, 0, 1)])
hc = kwant.lattice.honeycomb()
chain = kwant.lattice.chain(norbs=1)
square = kwant.lattice.square(norbs=1)
cube = kwant.lattice.general([(1, 0, 0), (0, 1, 0), (0, 0, 1)], norbs=1)
hc = kwant.lattice.honeycomb(norbs=1)
syst_1d = kwant.Builder(kwant.TranslationalSymmetry(*chain._prim_vecs))
syst_1d[chain(0)] = 2
......@@ -245,7 +247,7 @@ def test_fd_mismatch():
# around in all directions, but could not be wrapped around when 'keep' is
# provided.
sqrt3 = np.sqrt(3)
lat = kwant.lattice.general([(sqrt3, 0), (-sqrt3/2, 1.5)])
lat = kwant.lattice.general([(sqrt3, 0), (-sqrt3/2, 1.5)], norbs=1)
T = kwant.TranslationalSymmetry((sqrt3, 0), (0, 3))
syst1 = kwant.Builder(T)
......@@ -269,7 +271,8 @@ def test_fd_mismatch():
## Test that spectrum of non-trivial system (including above cases)
## is the same, regardless of the way in which it is wrapped around
lat = kwant.lattice.general([(sqrt3, 0), (-sqrt3/2, 1.5)],
[(sqrt3 / 2, 0.5), (0, 1)])
[(sqrt3 / 2, 0.5), (0, 1)],
norbs=1)
a, b = lat.sublattices
T = kwant.TranslationalSymmetry((3 * sqrt3, 0), (0, 3))
syst = kwant.Builder(T)
......@@ -302,7 +305,7 @@ def test_fd_mismatch():
assert all(np.allclose(E, E[0]) for E in E_k)
# Test square lattice with oblique unit cell
lat = kwant.lattice.general(np.eye(2))
lat = kwant.lattice.general(np.eye(2), norbs=1)
translations = kwant.lattice.TranslationalSymmetry([2, 2], [0, 2])
syst = kwant.Builder(symmetry=translations)
syst[lat.shape(lambda site: True, [0, 0])] = 1
......@@ -314,7 +317,7 @@ def test_fd_mismatch():
# Test Rocksalt structure
# cubic lattice that contains both sublattices
lat = kwant.lattice.general(np.eye(3))
lat = kwant.lattice.general(np.eye(3), norbs=1)
# Builder with FCC translational symmetries.
translations = kwant.lattice.TranslationalSymmetry([1, 1, 0], [1, 0, 1], [0, 1, 1])
syst = kwant.Builder(symmetry=translations)
......@@ -341,7 +344,7 @@ def test_fd_mismatch():
def shape(site):
return abs(site.tag[2]) < 4
lat = kwant.lattice.general(np.eye(3))
lat = kwant.lattice.general(np.eye(3), norbs=1)
# First choice: primitive UC
translations = kwant.lattice.TranslationalSymmetry([1, 1, 0], [1, -1, 0], [1, 0, 1])
syst = kwant.Builder(symmetry=translations)
......
......@@ -20,36 +20,12 @@ from . import builder, system, plotter
from .linalg import lll
from .builder import herm_conj, HermConjOfFunc
from .lattice import TranslationalSymmetry
from ._common import get_parameters
from ._common import get_parameters, memoize
__all__ = ['wraparound', 'plot_2d_bands']
def _hashable(obj):
return isinstance(obj, collections.abc.Hashable)
def _memoize(f):
"""Decorator to memoize a function that works even with unhashable args.
This decorator will even work with functions whose args are not hashable.
The cache key is made up by the hashable arguments and the ids of the
non-hashable args. It is up to the user to make sure that non-hashable
args do not change during the lifetime of the decorator.
This decorator will keep reevaluating functions that return None.
"""
def lookup(*args):
key = tuple(arg if _hashable(arg) else id(arg) for arg in args)
result = cache.get(key)
if result is None:
cache[key] = result = f(*args)
return result
cache = {}
return lookup
def _set_signature(func, params):
"""Set the signature of 'func'.
......@@ -103,7 +79,7 @@ def wraparound(builder, keep=None, *, coordinate_names='xyz'):
format. It will be deprecated in the 2.0 release of Kwant.
"""
@_memoize
@memoize
def bind_site(val):
def f(*args):
a, *args = args
......@@ -113,7 +89,7 @@ def wraparound(builder, keep=None, *, coordinate_names='xyz'):
_set_signature(f, get_parameters(val) + momenta)
return f
@_memoize
@memoize
def bind_hopping_as_site(elem, val):
def f(*args):
a, *args = args
......@@ -128,7 +104,7 @@ def wraparound(builder, keep=None, *, coordinate_names='xyz'):
_set_signature(f, params + momenta)
return f
@_memoize
@memoize
def bind_hopping(elem, val):
def f(*args):
a, b, *args = args
......@@ -142,7 +118,7 @@ def wraparound(builder, keep=None, *, coordinate_names='xyz'):
_set_signature(f, params + momenta)
return f
@_memoize
@memoize
def bind_sum(num_sites, *vals):
"""Construct joint signature for all 'vals'."""
......@@ -386,10 +362,14 @@ def plot_2d_bands(syst, k_x=31, k_y=31, params=None,
if not hasattr(syst, '_wrapped_symmetry'):
raise TypeError("Expecting a system that was produced by "
"'kwant.wraparound.wraparound'.")
if not isinstance(syst, system.FiniteSystem):
if isinstance(syst, system.InfiniteSystem):
msg = ("All symmetry directions must be wrapped around: specify "
"'keep=None' when calling 'kwant.wraparound.wraparound'.")
raise TypeError(msg)
if isinstance(syst, builder.Builder):
msg = ("Expecting a finalized system: remember to finalize your "
"system with 'syst.finalized()'.")
raise TypeError(msg)
params = params or {}
lat_ndim, space_ndim = syst._wrapped_symmetry.periods.shape
......
[pytest]
testpaths = kwant
flakes-ignore =
__init__.py UnusedImport
__init__.py UnusedImport ImportStarUsed ImportStarUsage
kwant/_plotter.py UnusedImport
graph/tests/test_scotch.py UndefinedName
graph/tests/test_dissection.py UndefinedName
......@@ -517,7 +517,7 @@ def maybe_add_numpy_include(exts):
def main():
check_python_version((3, 5))
check_python_version((3, 6))
check_versions()
exts = collections.OrderedDict([
......@@ -581,12 +581,12 @@ def main():
'build_ext': build_ext,
'test': test},
ext_modules=exts,
install_requires=['numpy >= 1.11.0', 'scipy >= 0.17.0',
install_requires=['numpy >= 1.13.3', 'scipy >= 0.19.1',
'tinyarray >= 1.2'],
extras_require={
# The oldest versions between: Debian stable, Ubuntu LTS
'plotting': 'matplotlib >= 1.5.1',
'continuum': 'sympy >= 0.7.6',
'plotting': 'matplotlib >= 2.1.1',
'continuum': 'sympy >= 1.1.1',
# qsymm is only packaged on PyPI
'qsymm': 'qsymm >= 1.2.6',
},
......