Commit 195e4249 authored by Christoph Groth's avatar Christoph Groth
Browse files

Merge branch 'python3'

parents 2de760a3 0f3068d1
......@@ -6,10 +6,10 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from __future__ import division
from math import sin, cos, sqrt, pi, copysign
from collections import namedtuple
from itertools import izip
import numpy as np
import numpy.linalg as npl
import scipy.linalg as la
......@@ -434,7 +434,7 @@ def make_proper_modes(lmbdainv, psi, extract, tol=1e6):
if boundaries.shape == (0,) and len(angles):
boundaries = np.array([0, len(angles)])
for interval in izip(boundaries[:-1], boundaries[1:]):
for interval in zip(boundaries[:-1], boundaries[1:]):
if interval[1] > boundaries[0] + len(angles):
break
......@@ -661,8 +661,8 @@ def square_selfenergy(width, hopping, fermi_energy):
psi_p_i = np.empty((width, width))
factor = pi / (width + 1)
prefactor = sqrt(2 / (width + 1))
for p in xrange(width):
for i in xrange(width):
for p in range(width):
for i in range(width):
psi_p_i[p, i] = prefactor * sin(factor * (p + 1) * (i + 1))
# Precalculate the integrals of the longitudinal wave functions.
......@@ -672,15 +672,15 @@ def square_selfenergy(width, hopping, fermi_energy):
else:
return q/2 - copysign(sqrt((q / 2) ** 2 - 1), q)
f_p = np.empty((width,), dtype=complex)
for p in xrange(width):
for p in range(width):
e = 2 * hopping * (1 - cos(factor * (p + 1)))
q = (fermi_energy - e) / hopping - 2
f_p[p] = f(q)
# Put everything together into the self energy and return it.
result = np.empty((width, width), dtype=complex)
for i in xrange(width):
for j in xrange(width):
for i in range(width):
for j in range(width):
result[i, j] = hopping * (
psi_p_i[:, i] * psi_p_i[:, j].conj() * f_p).sum()
return result
......@@ -6,9 +6,9 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from __future__ import division
import numpy as np
from itertools import product, izip
from itertools import product
from numpy.testing import assert_almost_equal
from kwant.physics import leads
import kwant
......@@ -273,14 +273,14 @@ def test_algorithm_equivalence():
evan_vecs.append(full_vecs[:, 2 * result.nmodes :])
msg = 'Stabilization {0} failed.'
for vecs, algo in izip(prop_vecs, algos):
for vecs, algo in zip(prop_vecs, algos):
# Propagating modes should have identical ordering, and only vary
# By a phase
np.testing.assert_allclose(np.abs(np.sum(vecs/prop_vecs[0],
axis=0)), vecs.shape[0],
err_msg=msg.format(algo))
for vecs, algo in izip(evan_vecs, algos):
for vecs, algo in zip(evan_vecs, algos):
# Evanescent modes must span the same linear space.
assert (np.linalg.matrix_rank(np.c_[vecs, evan_vecs[0]], tol=1e-12) ==
vecs.shape[1]), msg.format(algo)
......
......@@ -69,7 +69,7 @@ if mpl_enabled:
# Collections that allow for symbols and linewiths to be given in data space
# (not for general use, only implement what's needed for plotter)
def isarray(var):
if hasattr(var, '__getitem__') and not isinstance(var, basestring):
if hasattr(var, '__getitem__') and not isinstance(var, str):
return True
else:
return False
......@@ -717,18 +717,18 @@ def sys_leads_sites(sys, num_lead_cells=2):
if hasattr(lead, 'builder') and len(lead.interface):
sites.extend(((site, leadnr, i) for site in
lead.builder.sites() for i in
xrange(num_lead_cells)))
range(num_lead_cells)))
lead_cells.append(slice(start, len(sites)))
elif isinstance(sys, system.FiniteSystem):
sites = [(i, None, 0) for i in xrange(sys.graph.num_nodes)]
sites = [(i, None, 0) for i in range(sys.graph.num_nodes)]
for leadnr, lead in enumerate(sys.leads):
start = len(sites)
# We will only plot leads with a graph and with a symmetry.
if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and
len(sys.lead_interfaces[leadnr])):
sites.extend(((site, leadnr, i) for site in
xrange(lead.cell_size) for i in
xrange(num_lead_cells)))
range(lead.cell_size) for i in
range(num_lead_cells)))
lead_cells.append(slice(start, len(sites)))
else:
raise TypeError('Unrecognized system type.')
......@@ -796,10 +796,10 @@ def sys_leads_pos(sys, site_lead_nr):
# 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 xrange(len(sys.leads)))
vecs_doms = dict((i, get_vec_domain(i)) for i in range(len(sys.leads)))
vecs_doms[None] = np.zeros((dim,)), 0
for k, v in vecs_doms.iteritems():
vecs_doms[k] = [v[0] * i for i in xrange(v[1], v[1] + num_lead_cells)]
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
......@@ -856,11 +856,11 @@ def sys_leads_hoppings(sys, num_lead_cells=2):
if hasattr(lead, 'builder') and len(lead.interface):
hoppings.extend(((hop, leadnr, i) for hop in
lead_hoppings(lead.builder) for i in
xrange(num_lead_cells)))
range(num_lead_cells)))
lead_cells.append(slice(start, len(hoppings)))
elif isinstance(sys, system.System):
def ll_hoppings(sys):
for i in xrange(sys.graph.num_nodes):
for i in range(sys.graph.num_nodes):
for j in sys.graph.out_neighbors(i):
if i < j:
yield i, j
......@@ -872,7 +872,7 @@ def sys_leads_hoppings(sys, num_lead_cells=2):
if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and
len(sys.lead_interfaces[leadnr])):
hoppings.extend(((hop, leadnr, i) for hop in ll_hoppings(lead)
for i in xrange(num_lead_cells)))
for i in range(num_lead_cells)))
lead_cells.append(slice(start, len(hoppings)))
else:
raise TypeError('Unrecognized system type.')
......@@ -942,12 +942,12 @@ def sys_leads_hopping_pos(sys, hop_lead_nr):
vec = np.array(sym.periods)[0]
return np.r_[vec, vec], dom
vecs_doms = dict((i, get_vec_domain(i)) for i in xrange(len(sys.leads)))
vecs_doms = dict((i, get_vec_domain(i)) for i in range(len(sys.leads)))
vecs_doms[None] = np.zeros((dim,)), 0
for k, v in vecs_doms.iteritems():
vecs_doms[k] = [v[0] * i for i in xrange(v[1], v[1] + num_lead_cells)]
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:])
return np.copy(pos[:, : dim // 2]), np.copy(pos[:, dim // 2:])
# Useful plot functions (to be extended).
......@@ -1136,7 +1136,7 @@ def plot(sys, num_lead_cells=2, unit='nn',
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, (basestring, tuple)):
if isinstance(value, (str, tuple)):
return
try:
if len(value) != n_sys_sites:
......@@ -1226,7 +1226,7 @@ def plot(sys, num_lead_cells=2, unit='nn',
for i, symbol in enumerate(site_symbol):
symbol_dict[symbol].append(i)
symbol_slcs = []
for symbol, indx in symbol_dict.iteritems():
for symbol, indx in symbol_dict.items():
symbol_slcs.append((symbol, np.array(indx)))
fancy_indexing = True
else:
......@@ -1285,7 +1285,7 @@ def plot(sys, num_lead_cells=2, unit='nn',
else defaults['hop_lw'][dim])
hop_cmap = None
if not isinstance(cmap, basestring):
if not isinstance(cmap, str):
try:
cmap, hop_cmap = cmap
except TypeError:
......
......@@ -6,8 +6,6 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from __future__ import division
__all__ = ['gaussian', 'circular']
import numpy as np
......
......@@ -15,6 +15,7 @@ import numpy as np
import scipy.sparse as sp
from .._common import ensure_isinstance
from .. import system
from functools import reduce
# Currently, scipy.sparse does not support matrices with one dimension being
# zero: http://projects.scipy.org/scipy/ticket/1602 We use NumPy dense matrices
......@@ -28,7 +29,7 @@ from .. import system
LinearSys = namedtuple('LinearSys', ['lhs', 'rhs', 'indices', 'num_orb'])
class SparseSolver(object):
class SparseSolver(object, metaclass=abc.ABCMeta):
"""Solver class for computing physical quantities based on solving
a liner system of equations.
......@@ -51,7 +52,6 @@ class SparseSolver(object):
too avoid excessive memory usage, but for some solvers not too small for
performance reasons.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def _factorized(self, a):
......@@ -333,11 +333,11 @@ class SparseSolver(object):
n = len(sys.lead_interfaces)
if in_leads is None:
in_leads = range(n)
in_leads = list(range(n))
else:
in_leads = list(in_leads)
if out_leads is None:
out_leads = range(n)
out_leads = list(range(n))
else:
out_leads = list(out_leads)
if (np.any(np.diff(in_leads) <= 0) or np.any(np.diff(out_leads) <= 0)):
......@@ -420,11 +420,11 @@ class SparseSolver(object):
n = len(sys.lead_interfaces)
if in_leads is None:
in_leads = range(n)
in_leads = list(range(n))
else:
in_leads = list(in_leads)
if out_leads is None:
out_leads = range(n)
out_leads = list(range(n))
else:
out_leads = list(out_leads)
if (np.any(np.diff(in_leads) <= 0) or np.any(np.diff(out_leads) <= 0)):
......@@ -489,7 +489,7 @@ class SparseSolver(object):
raise NotImplementedError("ldos for leads with only "
"self-energy is not implemented yet.")
linsys = self._make_linear_sys(sys, xrange(len(sys.leads)), energy,
linsys = self._make_linear_sys(sys, range(len(sys.leads)), energy,
args, check_hermiticity)[0]
ldos = np.zeros(linsys.num_orb, float)
......@@ -503,7 +503,7 @@ class SparseSolver(object):
# See comment about zero-shaped sparse matrices at the top of common.py.
rhs = sp.bmat([[i for i in linsys.rhs if i.shape[1]]],
format=self.rhsformat)
for j in xrange(0, rhs.shape[1], self.nrhs):
for j in range(0, rhs.shape[1], self.nrhs):
jend = min(j + self.nrhs, rhs.shape[1])
psi = self._solve_linear_sys(factored, rhs[:, j:jend],
slice(linsys.num_orb))
......@@ -555,7 +555,7 @@ class WaveFunction(object):
msg = ('Wave functions for leads with only self-energy'
' are not available yet.')
raise NotImplementedError(msg)
linsys = solver._make_linear_sys(sys, xrange(len(sys.leads)), energy,
linsys = solver._make_linear_sys(sys, range(len(sys.leads)), energy,
args, check_hermiticity)[0]
self.solve = solver._solve_linear_sys
self.rhs = linsys.rhs
......@@ -568,11 +568,10 @@ class WaveFunction(object):
return result.transpose()
class BlockResult(object):
class BlockResult(object, metaclass=abc.ABCMeta):
"""
ABC for a linear system solution with variable grouping.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, data, lead_info, out_leads, in_leads, sizes,
current_conserving=False):
......@@ -676,7 +675,7 @@ class BlockResult(object):
Section 2.4 of the book by S. Datta.
"""
n = len(self.lead_info)
rn = xrange(n)
rn = range(n)
result = np.array([[-self.transmission(i, j) if i != j else 0
for j in rn] for i in rn])
# Set the diagonal elements such that the sums of columns are zero.
......
......@@ -84,14 +84,14 @@ class Solver(common.SparseSolver):
self.nrhs = nrhs
if ordering is not None:
if ordering not in mumps.orderings.keys() + ['kwant_decides']:
raise ValueError("Invalid ordering: " + ordering)
if ordering == 'kwant_decides':
# Choose what is considered to be the best ordering.
sorted_orderings = [order
for order in ['metis', 'scotch', 'auto']
if order in mumps.possible_orderings()]
ordering = sorted_orderings[0]
elif ordering not in mumps.orderings:
raise ValueError("Invalid ordering: " + ordering)
self.ordering = ordering
if sparse_rhs is not None:
......@@ -111,7 +111,7 @@ class Solver(common.SparseSolver):
solve = factorized_a.solve
sols = []
for j in xrange(0, b.shape[1], self.nrhs):
for j in range(0, b.shape[1], self.nrhs):
tmprhs = b[:, j:min(j + self.nrhs, b.shape[1])]
if not self.sparse_rhs:
......
......@@ -110,7 +110,7 @@ class Solver(common.SparseSolver):
sols = []
vec = np.empty(b.shape[0], complex)
for j in xrange(b.shape[1]):
for j in range(b.shape[1]):
vec[:] = b[:, j].todense().flatten()
sols.append(factorized_a(vec)[kept_vars])
......
......@@ -6,7 +6,7 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from __future__ import division
from math import cos, sin
import numpy as np
from nose.tools import assert_raises
......@@ -263,18 +263,18 @@ def test_tricky_singular_hopping(smatrix):
lead = kwant.Builder(kwant.TranslationalSymmetry((4, 0)))
interface = []
for i in xrange(n):
for i in range(n):
site = sq(-1, i)
interface.append(site)
system[site] = 0
for j in xrange(4):
for j in range(4):
lead[sq(j, i)] = 0
for i in xrange(n-1):
for i in range(n-1):
system[sq(-1, i), sq(-1, i+1)] = -1
for j in xrange(4):
for j in range(4):
lead[sq(j, i), sq(j, i+1)] = -1
for i in xrange(n):
for j in xrange(4):
for i in range(n):
for j in range(4):
lead[sq(j, i), sq(j+1, i)] = -1
del lead[sq(1, 0), sq(2, 0)]
......@@ -300,10 +300,10 @@ def test_many_leads(*factories):
# Build a square system with four leads and a hole in the center.
sys = kwant.Builder()
sys[(sq(x, y) for x in xrange(-4, 4) for y in xrange(-4, 4)
sys[(sq(x, y) for x in range(-4, 4) for y in range(-4, 4)
if x**2 + y**2 >= 2)] = 3
sys[sq.neighbors()] = phase
for r in [xrange(-4, -1), xrange(4)]:
for r in [range(-4, -1), range(4)]:
lead = kwant.Builder(kwant.TranslationalSymmetry([-1, 0]))
lead[(sq(0, y) for y in r)] = 4
lead[sq.neighbors()] = phase
......@@ -311,7 +311,7 @@ def test_many_leads(*factories):
sys.attach_lead(lead.reversed())
sys = sys.finalized()
r4 = range(4)
r4 = list(range(4))
br = factories[0](sys, E, out_leads=r4, in_leads=r4)
trans = np.array([[br._transmission(i, j) for j in r4] for i in r4])
cmat = br.conductance_matrix()
......@@ -480,7 +480,7 @@ def test_wavefunc_ldos_consistency(wave_function, ldos):
for energy in [0, 1000]:
wf = wave_function(sys, energy)
ldos2 = np.zeros(wf.num_orb, float)
for lead in xrange(len(sys.leads)):
for lead in range(len(sys.leads)):
temp = abs(wf(lead))
temp **= 2
ldos2 += temp.sum(axis=0)
......
......@@ -11,7 +11,7 @@ from numpy.testing.decorators import skipif
try:
from kwant.solvers.mumps import (
smatrix, greens_function, ldos, wave_function, options, reset_options)
import _test_sparse
from . import _test_sparse
no_mumps = False
except ImportError:
no_mumps = True
......
......@@ -9,7 +9,7 @@
from nose.plugins.skip import SkipTest
from kwant.solvers.sparse import smatrix, greens_function, ldos, wave_function
import kwant.solvers.sparse
import _test_sparse
from . import _test_sparse
def test_output():
_test_sparse.test_output(smatrix)
......
......@@ -8,7 +8,6 @@
"""Low-level interface of systems"""
from __future__ import division
__all__ = ['System', 'FiniteSystem', 'InfiniteSystem']
import abc
......@@ -17,7 +16,7 @@ from copy import copy
from . import _system
class System(object):
class System(object, metaclass=abc.ABCMeta):
"""Abstract general low-level system.
Attributes
......@@ -33,7 +32,6 @@ class System(object):
Optionally, a class derived from `System` can provide a method `pos` which
is assumed to return the real-space position of a site given its index.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def hamiltonian(self, i, j, *args):
......@@ -49,11 +47,10 @@ class System(object):
pass
# Add a C-implemented function as an unbound method to class System.
System.hamiltonian_submatrix = types.MethodType(
_system.hamiltonian_submatrix, None, System)
System.hamiltonian_submatrix = _system.HamiltonianSubmatrix()
class FiniteSystem(System):
class FiniteSystem(System, metaclass=abc.ABCMeta):
"""Abstract finite low-level system, possibly with leads.
Attributes
......@@ -80,7 +77,6 @@ class FiniteSystem(System):
the first ``len(lead_interfaces[n])`` sites of the InfiniteSystem.
"""
__metaclass__ = abc.ABCMeta
def precalculate(self, energy=0, args=(), leads=None,
what='modes'):
......@@ -123,7 +119,7 @@ class FiniteSystem(System):
result = copy(self)
if leads is None:
leads = range(len(self.leads))
leads = list(range(len(self.leads)))
new_leads = []
for nr, lead in enumerate(self.leads):
if nr not in leads:
......@@ -141,7 +137,7 @@ class FiniteSystem(System):
result.leads = new_leads
return result
class InfiniteSystem(System):
class InfiniteSystem(System, metaclass=abc.ABCMeta):
"""
Abstract infinite low-level system.
......@@ -183,18 +179,17 @@ class InfiniteSystem(System):
infinite system. The other scheme has the numbers of site 0 and 1
exchanged, as well as of site 3 and 4.
"""
__metaclass__ = abc.ABCMeta
def cell_hamiltonian(self, args=(), sparse=False):
"""Hamiltonian of a single cell of the infinite system."""
cell_sites = xrange(self.cell_size)
cell_sites = range(self.cell_size)
return self.hamiltonian_submatrix(args, cell_sites, cell_sites,
sparse=sparse)
def inter_cell_hopping(self, args=(), sparse=False):
"""Hopping Hamiltonian between two cells of the infinite system."""
cell_sites = xrange(self.cell_size)
interface_sites = xrange(self.cell_size, self.graph.num_nodes)
cell_sites = range(self.cell_size)
interface_sites = range(self.cell_size, self.graph.num_nodes)
return self.hamiltonian_submatrix(args, cell_sites, interface_sites,
sparse=sparse)
......
......@@ -6,7 +6,6 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from __future__ import division
import warnings
from random import Random
from nose.tools import assert_raises
......@@ -84,7 +83,7 @@ def test_bad_keys():
try:
assert_raises(error, func, key)
except AssertionError:
print func, error, key
print(func, error, key)
raise
......@@ -259,14 +258,14 @@ def random_hopping_integral(rng):
def check_onsite(fsys, sites, subset=False, check_values=True):
freq = {}
for node in xrange(fsys.graph.num_nodes):
for node in range(fsys.graph.num_nodes):
site = fsys.sites[node].tag
freq[site] = freq.get(site, 0) + 1
if check_values and site in sites:
assert fsys.onsite_hamiltonians[node] is sites[site]
if not subset:
# Check that all sites of `fsys` are in `sites`.
for site in freq.iterkeys():
for site in freq.keys():
assert site in sites
# Check that all sites of `sites` are in `fsys`.
for site in sites:
......@@ -302,7 +301,7 @@ def test_finalization():
def set_hops(dest, sites):
while len(dest) < n_hops:
a, b = rng.sample(sites, 2)
a, b = rng.sample(list(sites), 2)
if (a, b) not in dest and (b, a) not in dest:
dest[a, b] = random_hopping_integral(rng)
......@@ -327,7 +326,7 @@ def test_finalization():
set_hops(lead_hops, lead_sites)
lead_sites_list = list(lead_sites)
neighbors = set()
for i in xrange(n_hops):
for i in range(n_hops):
while True:
a = rng.choice(lead_sites_list)
b = rng.choice(possible_neighbors)
......@@ -343,9 +342,9 @@ def test_finalization():
# Build scattering region from blueprint and test it.
sys = builder.Builder()
fam = kwant.lattice.general(ta.identity(2))
for site, value in sr_sites.iteritems():
for site, value in sr_sites.items():
sys[fam(*site)] = value
for hop, value in sr_hops.iteritems():
for hop, value in sr_hops.items():
sys[fam(*hop[0]), fam(*hop[1])] = value
fsys = sys.finalized()
check_onsite(fsys, sr_sites)
......@@ -353,7 +352,7 @@ def test_finalization():
# Build lead from blueprint and test it.
lead = builder.Builder(kwant.TranslationalSymmetry((size, 0)))
for site, value in lead_sites.iteritems():
for site, value in lead_sites.items():
shift = rng.randrange(-5, 6) * size
site = site[0] + shift, site[1]
lead[fam(*site)] = value
......@@ -363,7 +362,7 @@ def test_finalization():
assert_equal(len(w), 1)
assert issubclass(w[0].category, RuntimeWarning)
assert "disconnected" in str(w[0].message)
for (a, b), value in lead_hops.iteritems():
for (a, b), value in lead_hops.items():
shift = rng.randrange(-5, 6) * size
a = a[0] + shift, a[1]
b = b[0] + shift, b[1]
......@@ -645,21 +644,21 @@ def test_ModesLead_and_SelfEnergyLead():
energies = [0.9, 1.7]
sys = builder.Builder()
for x in xrange(L):
for y in xrange(L):
for x in range(L):
for y in range(L):
sys[lat(x, y)] = 4 * t + rng.random() - 0.5
sys[hoppings] = -t
# Attach a lead from the left.
lead = builder.Builder(VerySimpleSymmetry(-1))
for y in xrange(L):
for y in range(L):
lead[lat(0, y)] = 4 * t
lead[hoppings] = -t
sys.attach_lead(lead)
# Make the right lead and attach it.
lead = builder.Builder(VerySimpleSymmetry(1))
for y in xrange(L):
for y in range(L):
lead[lat(0, y)] = 4 * t