Commit d8fa9e94 authored by Joseph Weston's avatar Joseph Weston Committed by Joseph Weston
Browse files

run 2to3 on Kwant codebase

parent 2de760a3
......@@ -29,7 +29,7 @@ __all__.append('KwantDeprecationWarning')
from ._common import version as __version__
for module in ['system', 'builder', 'lattice', 'solvers', 'digest', 'rmt']:
exec 'from . import {0}'.format(module)
exec('from . import {0}'.format(module))
__all__.append(module)
# Make selected functionality available directly in the root namespace.
......@@ -38,7 +38,7 @@ available = [('builder', ['Builder', 'HoppingKind']),
('solvers.default',
['smatrix', 'greens_function', 'ldos', 'wave_function'])]
for module, names in available:
exec 'from .{0} import {1}'.format(module, ', '.join(names))
exec('from .{0} import {1}'.format(module, ', '.join(names)))
__all__.extend(names)
# Importing plotter might not work, but this does not have to be a problem --
......
......@@ -42,7 +42,7 @@ def get_version_from_git():
break
else:
return
description = p.communicate()[0].strip('v').rstrip('\n')
description = p.communicate()[0].decode().strip('v').rstrip('\n')
release, dev, git = description.rsplit('-', 2)
version = [release]
......
......@@ -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
__all__ = ['Builder', 'Site', 'SiteFamily', 'SimpleSiteFamily', 'Symmetry',
'HoppingKind', 'Lead', 'BuilderLead', 'SelfEnergyLead', 'ModesLead']
......@@ -14,11 +14,12 @@ __all__ = ['Builder', 'Site', 'SiteFamily', 'SimpleSiteFamily', 'Symmetry',
import abc
import warnings
import operator
from itertools import izip, islice, chain
from itertools import islice, chain
import tinyarray as ta
import numpy as np
from . import system, graph, KwantDeprecationWarning
from ._common import ensure_isinstance
import collections
......@@ -84,7 +85,7 @@ class Site(tuple):
return self.family.pos(self.tag)
class SiteFamily(object):
class SiteFamily(object, metaclass=abc.ABCMeta):
"""Abstract base class for site families.
Site families are the 'type' of `Site` objects. Within a family, individual
......@@ -107,7 +108,6 @@ class SiteFamily(object):
site belonging to this family with a given tag.
"""
__metaclass__ = abc.ABCMeta
def __init__(self, canonical_repr, name):
self.canonical_repr = canonical_repr
......@@ -224,7 +224,7 @@ def validate_hopping(hopping):
################ Symmetries
class Symmetry(object):
class Symmetry(object, metaclass=abc.ABCMeta):
"""Abstract base class for spatial symmetries.
Many physical systems possess a discrete spatial symmetry, which results in
......@@ -249,7 +249,6 @@ class Symmetry(object):
typical example of this is when the vector defining a translational
symmetry is not a lattice vector.
"""
__metaclass__ = abc.ABCMeta
@abc.abstractproperty
def num_directions(self):
......@@ -430,7 +429,7 @@ class HermConjOfFunc(object):
################ Leads
class Lead(object):
class Lead(object, metaclass=abc.ABCMeta):
"""Abstract base class for leads that can be attached to a `Builder`.
To attach a lead to a builder, append it to the builder's `~Builder.leads`
......@@ -442,7 +441,6 @@ class Lead(object):
interface : sequence of sites
"""
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def finalized(self):
......@@ -567,7 +565,7 @@ def edges(seq):
# izip, when given the same iterator twice, turns a sequence into a
# sequence of pairs.
seq_iter = iter(seq)
result = izip(seq_iter, seq_iter)
result = zip(seq_iter, seq_iter)
next(result) # Skip the special loop edge.
return result
......@@ -766,7 +764,7 @@ class Builder(object):
result.H = self.H
return result
def __nonzero__(self):
def __bool__(self):
return bool(self.H)
def expand(self, key):
......@@ -797,7 +795,7 @@ class Builder(object):
iter_stack = [None]
while iter_stack:
for key in itr:
while callable(key):
while isinstance(key, collections.Callable):
key = key(self)
if isinstance(key, tuple):
# Site instances are also tuples.
......@@ -828,7 +826,7 @@ class Builder(object):
b, a = sym.to_fd(b, a)
assert not sym.in_fd(a)
value = self._get_edge(b, a)
if callable(value):
if isinstance(value, collections.Callable):
assert not isinstance(value, HermConjOfFunc)
value = HermConjOfFunc(value)
else:
......@@ -974,13 +972,13 @@ class Builder(object):
initially (but always the equivalent ones).
"""
try:
return self.H.viewkeys()
return self.H.keys()
except AttributeError:
return frozenset(self.H)
def site_value_pairs(self):
"""Return an iterator over all (site, value) pairs."""
for site, hvhv in self.H.iteritems():
for site, hvhv in self.H.items():
yield site, hvhv[1]
def hoppings(self):
......@@ -990,7 +988,7 @@ class Builder(object):
`Builder` symmetry, and are not necessarily the ones that were set
initially (but always the equivalent ones).
"""
for tail, hvhv in self.H.iteritems():
for tail, hvhv in self.H.items():
for head, value in edges(hvhv):
if value is Other:
continue
......@@ -998,7 +996,7 @@ class Builder(object):
def hopping_value_pairs(self):
"""Return an iterator over all (hopping, value) pairs."""
for tail, hvhv in self.H.iteritems():
for tail, hvhv in self.H.items():
for head, value in edges(hvhv):
if value is Other:
continue
......@@ -1201,7 +1199,7 @@ class Builder(object):
#### Make graph.
g = graph.Graph()
g.num_nodes = len(sites) # Some sites could not appear in any edge.
for tail, hvhv in self.H.iteritems():
for tail, hvhv in self.H.items():
for head in islice(hvhv, 2, None, 2):
if tail == head:
continue
......@@ -1225,7 +1223,7 @@ class Builder(object):
msg = 'When finalizing lead {0}:'.format(lead_nr)
warnings.warn(w.__class__(' '.join((msg,) + w.args)),
stacklevel=3)
except ValueError, e:
except ValueError as e:
# Re-raise the exception with an additional message.
msg = 'Problem finalizing lead {0}:'.format(lead_nr)
e.args = (' '.join((msg,) + e.args),)
......@@ -1387,7 +1385,7 @@ class FiniteSystem(system.FiniteSystem):
def hamiltonian(self, i, j, *args):
if i == j:
value = self.onsite_hamiltonians[i]
if callable(value):
if isinstance(value, collections.Callable):
value = value(self.sites[i], *args)
else:
edge_id = self.graph.first_edge_id(i, j)
......@@ -1397,7 +1395,7 @@ class FiniteSystem(system.FiniteSystem):
i, j = j, i
edge_id = self.graph.first_edge_id(i, j)
value = self.hoppings[edge_id]
if callable(value):
if isinstance(value, collections.Callable):
sites = self.sites
value = value(sites[i], sites[j], *args)
if conj:
......@@ -1421,7 +1419,7 @@ class InfiniteSystem(system.InfiniteSystem):
if i >= self.cell_size:
i -= self.cell_size
value = self.onsite_hamiltonians[i]
if callable(value):
if isinstance(value, collections.Callable):
value = value(self.symmetry.to_fd(self.sites[i]), *args)
else:
edge_id = self.graph.first_edge_id(i, j)
......@@ -1431,7 +1429,7 @@ class InfiniteSystem(system.InfiniteSystem):
i, j = j, i
edge_id = self.graph.first_edge_id(i, j)
value = self.hoppings[edge_id]
if callable(value):
if isinstance(value, collections.Callable):
sites = self.sites
site_i = sites[i]
site_j = sites[j]
......
......@@ -19,7 +19,7 @@ good enough to pass the "dieharder" battery of tests: see the function `test` of
this module.
"""
from __future__ import division
from math import pi, log, sqrt, cos
from hashlib import md5
......@@ -96,8 +96,8 @@ def test(n=20000):
f = tempfile.NamedTemporaryFile(delete=False)
try:
for x in xrange(n):
for y in xrange(n):
for x in range(n):
for y in range(n):
a = array((x, y))
i = int(2**32 * uniform(a))
f.write(pack('I', i))
......
......@@ -11,6 +11,6 @@
# Merge the public interface of all submodules.
__all__ = []
for module in ['core', 'defs', 'slicer', 'utils']:
exec 'from . import {0}'.format(module)
exec 'from .{0} import *'.format(module)
exec '__all__.extend({0}.__all__)'.format(module)
exec('from . import {0}'.format(module))
exec('from .{0} import *'.format(module))
exec('__all__.extend({0}.__all__)'.format(module))
......@@ -6,8 +6,8 @@
# the file AUTHORS.rst at the top-level directory of this distribution and at
# http://kwant-project.org/authors.
from StringIO import StringIO
from itertools import izip_longest
from io import StringIO
from itertools import zip_longest
import numpy as np
from nose.tools import assert_equal, assert_raises
from kwant.graph.core import (Graph, NodeDoesNotExistError,
......@@ -41,12 +41,12 @@ def test_num_nodes():
def test_large():
num_edges = 1000
graph = Graph()
for i in xrange(num_edges):
for i in range(num_edges):
graph.add_edge(i, i + 1)
g = graph.compressed()
g2 = graph.compressed(twoway=True)
assert_equal(num_edges, g.num_nodes - 1)
for i in xrange(num_edges):
for i in range(num_edges):
assert_equal(tuple(g.out_neighbors(i)), (i + 1,))
assert_equal(tuple(g2.in_neighbors(i + 1)), (i,))
......@@ -71,7 +71,7 @@ def test_small():
check_dot(dot_expect, g)
g = g.compressed(twoway=True)
for edge_should, edge_is in izip_longest(edges, g):
for edge_should, edge_is in zip_longest(edges, g):
assert_equal(edge_should, edge_is)
edge_ids = []
......
......@@ -19,13 +19,13 @@ def _DISABLED_test_edge_dissection():
size = 5
graph = Graph()
for i in xrange(size - 1):
for i in range(size - 1):
offset = i * size
for j in xrange(size - 1):
for j in range(size - 1):
graph.add_edge(offset + j, offset + j + 1)
graph.add_edge(offset + j + 1, offset + j)
if i > 0:
for j in xrange(size):
for j in range(size):
graph.add_edge(offset + j, offset + j - size)
graph.add_edge(offset + j - size, offset + j)
g = graph.compressed()
......
......@@ -17,32 +17,32 @@ def _DISABLED_test_bisect():
size = 5
graph = Graph()
for i in xrange(size-1):
for i in range(size-1):
offset = i * size
for j in xrange(size-1):
for j in range(size-1):
graph.add_edge(offset + j, offset + j + 1)
graph.add_edge(offset + j + 1, offset + j)
if i > 0:
for j in xrange(size):
for j in range(size):
graph.add_edge(offset + j, offset + j - size)
graph.add_edge(offset + j - size, offset + j)
g = graph.compressed()
parts = bisect(g)
for i in xrange(g.num_nodes):
for i in range(g.num_nodes):
assert_true(parts[i] == 0 or parts[i] == 1)
def _DISABLED_test_reset():
size = 5
graph = Graph()
for i in xrange(size-1):
for i in range(size-1):
offset = i * size
for j in xrange(size-1):
for j in range(size-1):
graph.add_edge(offset + j, offset + j + 1)
graph.add_edge(offset + j + 1, offset + j)
if i > 0:
for j in xrange(size):
for j in range(size):
graph.add_edge(offset + j, offset + j - size)
graph.add_edge(offset + j - size, offset + j)
g = graph.compressed()
......
......@@ -11,13 +11,13 @@ from kwant.graph import slicer
def assert_sanity(graph, slices):
# Slices must comprise all of the graph.
slclist = [slices[j][i] for j in xrange(len(slices))
for i in xrange(len(slices[j]))]
slclist = [slices[j][i] for j in range(len(slices))
for i in range(len(slices[j]))]
slclist.sort()
assert slclist == [i for i in xrange(graph.num_nodes)]
assert slclist == [i for i in range(graph.num_nodes)]
# Nodes may only have neighbors in neighboring slices.
for j in xrange(len(slices)):
for j in range(len(slices)):
for node in slices[j]:
for neigh in graph.out_neighbors(node):
if j > 0 and j < len(slices) - 1:
......@@ -39,8 +39,8 @@ def test_rectangle():
sys = kwant.Builder()
lead = kwant.Builder(kwant.TranslationalSymmetry((-1, 0)))
lat = kwant.lattice.square()
lead[(lat(0, i) for i in xrange(w))] = 0
sys[(lat(j, i) for j in xrange(l) for i in xrange(w))] = 0
lead[(lat(0, i) for i in range(w))] = 0
sys[(lat(j, i) for j in range(l) for i in range(w))] = 0
for s in [lead, sys]:
for kind in [kwant.builder.HoppingKind((1, 0), lat),
kwant.builder.HoppingKind((0, 1), lat)]:
......@@ -57,7 +57,7 @@ def test_rectangle():
# we know that all slices must have the same shape.
assert len(slices) == l
for j in xrange(l):
for j in range(l):
assert len(slices[j]) == w
assert_sanity(fsys.graph, slices)
......@@ -83,7 +83,7 @@ def test_induced_subgraph():
num_nodes = 6
graph = Graph()
for i in xrange(num_nodes-1):
for i in range(num_nodes-1):
graph.add_edge(i, i + 1)
graph.add_edge(1, 0)
g = graph.compressed()
......
......@@ -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
__all__ = ['TranslationalSymmetry', 'general', 'Polyatomic', 'Monatomic',
'chain', 'square', 'triangular', 'honeycomb', 'kagome']
......@@ -617,7 +617,7 @@ class TranslationalSymmetry(builder.Symmetry):
det_m = int(round(np.linalg.det(m)))
if det_m == 0:
print m
print(m)
raise RuntimeError('Adding site family failed.')
det_x_inv_m = np.array(np.round(det_m * np.linalg.inv(m)), dtype=int)
......
......@@ -11,6 +11,6 @@ from . import lapack
# Merge the public interface of the other submodules.
for module in ['decomp_lu', 'decomp_ev', 'decomp_schur']:
exec 'from . import {0}'.format(module)
exec 'from .{0} import *'.format(module)
exec '__all__.extend({0}.__all__)'.format(module)
exec('from . import {0}'.format(module))
exec('from .{0} import *'.format(module))
exec('__all__.extend({0}.__all__)'.format(module))
......@@ -61,7 +61,7 @@ def lu_factor(a, overwrite_a=False):
return lapack.cgetrf(a)
def lu_solve((lu, ipiv, singular), b):
def lu_solve(xxx_todo_changeme, b):
"""Solve a linear system of equations, a x = b, given the LU
factorization of a
......@@ -77,7 +77,7 @@ def lu_solve((lu, ipiv, singular), b):
x : array (vector or matrix)
Solution to the system
"""
(lu, ipiv, singular) = xxx_todo_changeme
if singular:
raise RuntimeWarning("In lu_solve: the flag singular indicates "
"a singular matrix. Result of solve step "
......@@ -102,7 +102,7 @@ def lu_solve((lu, ipiv, singular), b):
return lapack.cgetrs(lu, ipiv, b)
def rcond_from_lu((lu, ipiv, singular), norm_a, norm="1"):
def rcond_from_lu(xxx_todo_changeme1, norm_a, norm="1"):
"""Compute the reciprocal condition number from the LU decomposition as
returned from lu_factor(), given additionally the norm of the matrix a in
norm_a.
......@@ -126,7 +126,7 @@ def rcond_from_lu((lu, ipiv, singular), norm_a, norm="1"):
reciprocal condition number of a with respect to the type of matrix
norm specified in norm
"""
(lu, ipiv, singular) = xxx_todo_changeme1
if not norm in ("1", "I"):
raise ValueError("norm in rcond_from_lu must be either '1' or 'I'")
......
......@@ -36,7 +36,7 @@ def prepare_for_fortran(overwrite, *args):
# Make sure we have NumPy arrays
mats = [None]*len(args)
for i in xrange(len(args)):
for i in range(len(args)):
if args[i] is not None:
arr = np.asanyarray(args[i])
if not np.issubdtype(arr.dtype, np.number):
......
......@@ -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
__all__ = ['lll', 'cvp', 'voronoi']
......@@ -68,7 +68,7 @@ def lll(basis, c=1.34):
m = vecs.shape[0]
u = np.identity(m)
def ll_reduce(i):
for j in reversed(range(i)):
for j in reversed(list(range(i))):
vecs[i] -= np.round(u[i, j]) * vecs[j]
u[i] -= np.round(u[i, j]) * u[j]
......
......@@ -219,7 +219,7 @@ class MUMPSContext(object):
if a.ndim != 2 or a.shape[0] != a.shape[1]:
raise ValueError("Input matrix must be square!")
if not ordering in orderings.keys():
if not ordering in list(orderings.keys()):
raise ValueError("Unknown ordering '"+ordering+"'!")
dtype, row, col, data = _make_assembled_from_coo(a, overwrite_a)
......@@ -470,7 +470,7 @@ def schur_complement(a, indices, ordering='auto', ooc=False, pivot_tol=0.01,
if indices.ndim != 1:
raise ValueError("Schur indices must be specified in a 1d array!")
if not ordering in orderings.keys():
if not ordering in list(orderings.keys()):
raise ValueError("Unknown ordering '"+ordering+"'!")
dtype, row, col, data = _make_assembled_from_coo(a, overwrite_a)
......
......@@ -43,16 +43,16 @@ class _Random:
mat = np.empty((n, m), dtype = dtype)
if issubclass(dtype, np.complexfloating):
for i in xrange(n):
for j in xrange(m):
for i in range(n):
for j in range(m):
mat[i,j] = self._randf() + 1j * self._randf()
elif issubclass(dtype, np.floating):
for i in xrange(n):
for j in xrange(m):
for i in range(n):
for j in range(m):
mat[i,j] = self._randf()
elif issubclass(dtype, np.integer):
for i in xrange(n):
for j in xrange(m):
for i in range(n):
for j in range(m):
mat[i,j] = self._randi()
return mat
......@@ -61,13 +61,13 @@ class _Random:
vec = np.empty(n, dtype = dtype)
if issubclass(dtype, np.complexfloating):
for i in xrange(n):
for i in range(n):
vec[i] = self._randf() + 1j * self._randf()
elif issubclass(dtype, np.floating):
for i in xrange(n):
for i in range(n):
vec[i] = self._randf()
elif issubclass(dtype, np.integer):
for i in xrange(n):
for i in range(n):
vec[i] = self._randi()
return vec
......
......@@ -12,7 +12,7 @@ from kwant.linalg import (
convert_r2c_gen_schur, order_gen_schur, evecs_from_gen_schur)
from nose.tools import assert_equal, assert_true
import numpy as np
from _test_utils import _Random, assert_array_almost_equal
from ._test_utils import _Random, assert_array_almost_equal
def test_gen_eig():
def _test_gen_eig(dtype):
......
......@@ -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
import numpy as np
from kwant.linalg import lll
......
......@@ -17,7 +17,7 @@ from kwant.builder import Builder, HoppingKind
from numpy.testing.decorators import skipif
import numpy as np
import scipy.sparse as sp
from _test_utils import _Random, assert_array_almost_equal
from ._test_utils import _Random, assert_array_almost_equal
@skipif(no_mumps)
def test_lu_with_dense():
......@@ -53,7 +53,7 @@ def test_schur_complement_with_dense():
def _test_schur_complement_with_dense(dtype):
rand = _Random()
a = rand.randmat(10, 10, dtype)
s = schur_complement(sp.coo_matrix(a), range(3))
s = schur_complement(sp.coo_matrix(a), list(range(3)))
assert_array_almost_equal(dtype, np.linalg.inv(s),
np.linalg.inv(a)[:3, :3])
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment