Skip to content
Snippets Groups Projects
Commit fb84570b authored by Christoph Groth's avatar Christoph Groth
Browse files

get rid of backslashes as far as possible (recommended by PEP 8)

parent e39a33f9
Branches
Tags
No related merge requests found
...@@ -16,8 +16,8 @@ from kwant.graph.core cimport CGraph, gintArraySlice ...@@ -16,8 +16,8 @@ from kwant.graph.core cimport CGraph, gintArraySlice
from kwant.graph.defs cimport gint from kwant.graph.defs cimport gint
from .graph.defs import gint_dtype from .graph.defs import gint_dtype
msg = 'Hopping from site {0} to site {1} does not match the ' \ msg = ('Hopping from site {0} to site {1} does not match the '
'dimensions of onsite Hamiltonians of these sites.' 'dimensions of onsite Hamiltonians of these sites.')
@cython.boundscheck(False) @cython.boundscheck(False)
def make_sparse(ham, args, CGraph gr, diag, def make_sparse(ham, args, CGraph gr, diag,
......
...@@ -850,8 +850,8 @@ class Builder(object): ...@@ -850,8 +850,8 @@ class Builder(object):
func = None func = None
for sh in self.expand(key): for sh in self.expand(key):
if func is None: if func is None:
func = self._set_site if isinstance(sh, Site) \ func = (self._set_site if isinstance(sh, Site)
else self._set_hopping else self._set_hopping)
func(sh, value) func(sh, value)
def _del_site(self, site): def _del_site(self, site):
...@@ -899,8 +899,8 @@ class Builder(object): ...@@ -899,8 +899,8 @@ class Builder(object):
func = None func = None
for sh in self.expand(key): for sh in self.expand(key):
if func is None: if func is None:
func = self._del_site if isinstance(sh, Site) \ func = (self._del_site if isinstance(sh, Site)
else self._del_hopping else self._del_hopping)
func(sh) func(sh)
def eradicate_dangling(self): def eradicate_dangling(self):
...@@ -1030,9 +1030,9 @@ class Builder(object): ...@@ -1030,9 +1030,9 @@ class Builder(object):
raise ValueError('Only builders with a 1D symmetry are allowed.') raise ValueError('Only builders with a 1D symmetry are allowed.')
for hopping in lead_builder.hoppings(): for hopping in lead_builder.hoppings():
if not -1 <= sym.which(hopping[1])[0] <= 1: if not -1 <= sym.which(hopping[1])[0] <= 1:
msg = 'Hopping {0} connects non-neighboring lead unit cells.' +\ msg = ('Hopping {0} connects non-neighboring lead unit cells. '
'Only nearest-cell hoppings are allowed ' +\ 'Only nearest-cell hoppings are allowed '
'(consider increasing the lead period).' '(consider increasing the lead period).')
raise ValueError(msg.format(hopping)) raise ValueError(msg.format(hopping))
if not H: if not H:
raise ValueError('Lead to be attached contains no sites.') raise ValueError('Lead to be attached contains no sites.')
...@@ -1046,8 +1046,8 @@ class Builder(object): ...@@ -1046,8 +1046,8 @@ class Builder(object):
if not lead_only_families: if not lead_only_families:
break break
else: else:
msg = 'Sites with site families {0} do not appear in the system, ' \ msg = ('Sites with site families {0} do not appear in the system, '
'hence the system does not interrupt the lead.' 'hence the system does not interrupt the lead.')
raise ValueError(msg.format(tuple(lead_only_families))) raise ValueError(msg.format(tuple(lead_only_families)))
all_doms = set() all_doms = set()
...@@ -1098,8 +1098,8 @@ class Builder(object): ...@@ -1098,8 +1098,8 @@ class Builder(object):
elif new_dom < min_dom: elif new_dom < min_dom:
raise ValueError('Builder does not interrupt the lead,' raise ValueError('Builder does not interrupt the lead,'
' this lead cannot be attached.') ' this lead cannot be attached.')
if site_new not in self \ if (site_new not in self
and sym.which(site_new)[0] != max_dom + 1: and sym.which(site_new)[0] != max_dom + 1):
self[site_new] = lead_builder[site_new] self[site_new] = lead_builder[site_new]
added2.add(site_new) added2.add(site_new)
covered = True covered = True
...@@ -1184,8 +1184,8 @@ class Builder(object): ...@@ -1184,8 +1184,8 @@ class Builder(object):
interface = [id_by_site[isite] for isite in lead.interface] interface = [id_by_site[isite] for isite in lead.interface]
except KeyError, e: except KeyError, e:
t, v, tb = sys.exc_info() t, v, tb = sys.exc_info()
msg = "Lead {0} is attached to a site that does not " \ msg = ("Lead {0} is attached to a site that does not "
"belong to the scattering region:\n {1}" "belong to the scattering region:\n {1}")
raise ValueError(msg.format(lead_nr, v)) raise ValueError(msg.format(lead_nr, v))
lead_interfaces.append(np.array(interface)) lead_interfaces.append(np.array(interface))
...@@ -1293,8 +1293,8 @@ class Builder(object): ...@@ -1293,8 +1293,8 @@ class Builder(object):
# to this one has been added already or will be added. # to this one has been added already or will be added.
fd = sym.which(head)[0] fd = sym.which(head)[0]
if fd != 1: if fd != 1:
msg = 'Further-than-nearest-neighbor cells ' \ msg = ('Further-than-nearest-neighbor cells '
'are connected by hopping\n{0}.' 'are connected by hopping\n{0}.')
raise ValueError(msg.format((tail, head))) raise ValueError(msg.format((tail, head)))
continue continue
if head_id >= cell_size: if head_id >= cell_size:
......
...@@ -10,8 +10,8 @@ from StringIO import StringIO ...@@ -10,8 +10,8 @@ from StringIO import StringIO
from itertools import izip_longest from itertools import izip_longest
import numpy as np import numpy as np
from nose.tools import assert_equal, assert_raises from nose.tools import assert_equal, assert_raises
from kwant.graph.core import \ from kwant.graph.core import (Graph, NodeDoesNotExistError,
Graph, NodeDoesNotExistError, EdgeDoesNotExistError, DisabledFeatureError EdgeDoesNotExistError, DisabledFeatureError)
def test_empty(): def test_empty():
graph = Graph() graph = Graph()
......
...@@ -9,8 +9,8 @@ ...@@ -9,8 +9,8 @@
import numpy as np import numpy as np
from nose.tools import assert_equal, assert_true from nose.tools import assert_equal, assert_true
from kwant.graph import Graph from kwant.graph import Graph
from kwant.graph.utils import \ from kwant.graph.utils import (make_undirected, remove_duplicates,
make_undirected, remove_duplicates, induced_subgraph induced_subgraph)
from kwant.graph.defs import gint_dtype from kwant.graph.defs import gint_dtype
def test_make_undirected(): def test_make_undirected():
......
...@@ -503,8 +503,8 @@ class TranslationalSymmetry(builder.Symmetry): ...@@ -503,8 +503,8 @@ class TranslationalSymmetry(builder.Symmetry):
if self.periods.ndim != 2: if self.periods.ndim != 2:
# TODO: remove the second part of the following message once # TODO: remove the second part of the following message once
# everybody got used to it. # everybody got used to it.
msg = "TranslationalSymmetry takes 1d sequences as parameters.\n" \ msg = ("TranslationalSymmetry takes 1d sequences as parameters.\n"
"See What's new in Kwant 0.2 in the documentation." "See What's new in Kwant 0.2 in the documentation.")
raise ValueError(msg) raise ValueError(msg)
if np.linalg.matrix_rank(periods) < len(periods): if np.linalg.matrix_rank(periods) < len(periods):
raise ValueError("Translational symmetry periods must be " raise ValueError("Translational symmetry periods must be "
...@@ -549,12 +549,12 @@ class TranslationalSymmetry(builder.Symmetry): ...@@ -549,12 +549,12 @@ class TranslationalSymmetry(builder.Symmetry):
bravais_periods = np.dot(self.periods, inv) bravais_periods = np.dot(self.periods, inv)
# Absolute tolerance is correct in the following since we want an error # Absolute tolerance is correct in the following since we want an error
# relative to the closest integer. # relative to the closest integer.
if not np.allclose(bravais_periods, np.round(bravais_periods), if (not np.allclose(bravais_periods, np.round(bravais_periods),
rtol=0, atol=1e-8) or \ rtol=0, atol=1e-8) or
not np.allclose([fam.vec(i) for i in bravais_periods], not np.allclose([fam.vec(i) for i in bravais_periods],
self.periods): self.periods)):
msg = 'Site family {0} does not have commensurate periods with ' +\ msg = ('Site family {0} does not have commensurate periods with '
'symmetry {1}.' 'symmetry {1}.')
raise ValueError(msg.format(fam, self)) raise ValueError(msg.format(fam, self))
bravais_periods = np.array(np.round(bravais_periods), dtype='int') bravais_periods = np.array(np.round(bravais_periods), dtype='int')
(num_dir, lat_dim) = bravais_periods.shape (num_dir, lat_dim) = bravais_periods.shape
...@@ -596,8 +596,7 @@ class TranslationalSymmetry(builder.Symmetry): ...@@ -596,8 +596,7 @@ class TranslationalSymmetry(builder.Symmetry):
print m print m
raise RuntimeError('Adding site family failed.') raise RuntimeError('Adding site family failed.')
det_x_inv_m = \ det_x_inv_m = np.array(np.round(det_m * np.linalg.inv(m)), dtype=int)
np.array(np.round(det_m * np.linalg.inv(m)), dtype=int)
assert (np.dot(m, det_x_inv_m) // det_m == np.identity(lat_dim)).all() assert (np.dot(m, det_x_inv_m) // det_m == np.identity(lat_dim)).all()
det_x_inv_m_part = det_x_inv_m[:num_dir, :] det_x_inv_m_part = det_x_inv_m[:num_dir, :]
...@@ -633,20 +632,20 @@ class TranslationalSymmetry(builder.Symmetry): ...@@ -633,20 +632,20 @@ class TranslationalSymmetry(builder.Symmetry):
if b is None: if b is None:
return builder.Site(a.family, a.tag + delta, True) return builder.Site(a.family, a.tag + delta, True)
elif b.family == a.family: elif b.family == a.family:
return builder.Site(a.family, a.tag + delta, True), \ return (builder.Site(a.family, a.tag + delta, True),
builder.Site(b.family, b.tag + delta, True) builder.Site(b.family, b.tag + delta, True))
else: else:
m_part = self._get_site_family_data(b.family)[0] m_part = self._get_site_family_data(b.family)[0]
try: try:
delta2 = ta.dot(m_part, element) delta2 = ta.dot(m_part, element)
except ValueError: except ValueError:
msg = 'Expecting a {0}-tuple group element, ' + \ msg = ('Expecting a {0}-tuple group element, '
'but got `{1}` instead.' 'but got `{1}` instead.')
raise ValueError(msg.format(self.num_directions, element)) raise ValueError(msg.format(self.num_directions, element))
if self.is_reversed: if self.is_reversed:
delta2 = -delta2 delta2 = -delta2
return builder.Site(a.family, a.tag + delta, True), \ return (builder.Site(a.family, a.tag + delta, True),
builder.Site(b.family, b.tag + delta2, True) builder.Site(b.family, b.tag + delta2, True))
def to_fd(self, a, b=None): def to_fd(self, a, b=None):
return self.act(-self.which(a), a, b) return self.act(-self.which(a), a, b)
......
...@@ -80,8 +80,8 @@ def lll(basis, c=1.34): ...@@ -80,8 +80,8 @@ def lll(basis, c=1.34):
# Main part of LLL algorithm. # Main part of LLL algorithm.
i = 0 i = 0
while i < m-1: while i < m-1:
if np.linalg.norm(vecsstar[i]) ** 2 < \ if (np.linalg.norm(vecsstar[i]) ** 2 <
c * np.linalg.norm(vecsstar[i+1]) ** 2: c * np.linalg.norm(vecsstar[i+1]) ** 2):
i += 1 i += 1
else: else:
vecsstar[i+1] += u[i+1, i] * vecsstar[i] vecsstar[i+1] += u[i+1, i] * vecsstar[i]
......
...@@ -97,18 +97,17 @@ class AnalysisStatistics(object): ...@@ -97,18 +97,17 @@ class AnalysisStatistics(object):
self.time = time self.time = time
def __str__(self): def __str__(self):
string = " estimated memory for in-core factorization: " + \ parts = ["estimated memory for in-core factorization:",
str(self.est_mem_incore) + " mbytes\n" str(self.est_mem_incore), "mbytes\n",
string += " estimated memory for out-of-core factorization: " + \ "estimated memory for out-of-core factorization:",
str(self.est_mem_ooc) + " mbytes\n" str(self.est_mem_ooc), "mbytes\n",
string += " estimated number of nonzeros in factors: " + \ "estimated number of nonzeros in factors:",
str(self.est_nonzeros) + "\n" str(self.est_nonzeros), "\n",
string += " estimated number of flops: " + str(self.est_flops) + "\n" "estimated number of flops:", str(self.est_flops), "\n",
string += " ordering used: " + self.ordering "ordering used:", self.ordering]
if hasattr(self, "time"): if hasattr(self, "time"):
string += "\n analysis time: " + str(self.time) + " secs" parts.extend(["\n analysis time:", str(self.time), "secs"])
return " ".join(parts)
return string
class FactorizationStatistics(object): class FactorizationStatistics(object):
...@@ -131,19 +130,18 @@ class FactorizationStatistics(object): ...@@ -131,19 +130,18 @@ class FactorizationStatistics(object):
self.time = time self.time = time
def __str__(self): def __str__(self):
string = " off-diagonal pivots: " + str(self.offdiag_pivots) + "\n" parts = ["off-diagonal pivots:", str(self.offdiag_pivots), "\n",
string += " delayed pivots: " + str(self.delayed_pivots) + "\n" "delayed pivots:", str(self.delayed_pivots), "\n",
string += " tiny pivots: " + str(self.tiny_pivots) + "\n" "tiny pivots:", str(self.tiny_pivots), "\n"]
if hasattr(self, "ordering"): if hasattr(self, "ordering"):
string += " ordering used: " + self.ordering + "\n" parts.extend(["ordering used:", self.ordering, "\n"])
string += " memory used during factorization : " + str(self.memory) + \ parts.extend(["memory used during factorization:", str(self.memory),
" mbytes\n" "mbytes\n",
string += " nonzeros in factored matrix: " + str(self.nonzeros) + "\n" "nonzeros in factored matrix:", str(self.nonzeros), "\n",
string += " floating point operations: " + str(self.flops) "floating point operations:", str(self.flops)])
if hasattr(self, "time"): if hasattr(self, "time"):
string += "\n factorization time: " + str(self.time) +" secs" parts.extend(["\n factorization time:", str(self.time), "secs"])
return " ".join(parts)
return string
class MUMPSContext(object): class MUMPSContext(object):
...@@ -348,8 +346,8 @@ class MUMPSContext(object): ...@@ -348,8 +346,8 @@ class MUMPSContext(object):
x = np.empty((b.shape[0], b.shape[1]), x = np.empty((b.shape[0], b.shape[1]),
order='F', dtype=self.data.dtype) order='F', dtype=self.data.dtype)
dtype, col_ptr, row_ind, data = \ dtype, col_ptr, row_ind, data = _make_sparse_rhs_from_csc(
_make_sparse_rhs_from_csc(b, self.data.dtype) b, self.data.dtype)
if b.shape[0] != self.n: if b.shape[0] != self.n:
raise ValueError("Right hand side has wrong size") raise ValueError("Right hand side has wrong size")
...@@ -498,9 +496,8 @@ def schur_complement(a, indices, ordering='auto', ooc=False, pivot_tol=0.01, ...@@ -498,9 +496,8 @@ def schur_complement(a, indices, ordering='auto', ooc=False, pivot_tol=0.01,
if not calc_stats: if not calc_stats:
return schur_compl return schur_compl
else: else:
return schur_compl, \ return (schur_compl, FactorizationStatistics(
FactorizationStatistics(mumps_instance, time=t2 - t1, mumps_instance, time=t2 - t1, include_ordering=True))
include_ordering=True)
# Some internal helper functions # Some internal helper functions
......
...@@ -6,9 +6,10 @@ ...@@ -6,9 +6,10 @@
# the AUTHORS file at the top-level directory of this distribution and at # the AUTHORS file at the top-level directory of this distribution and at
# http://kwant-project.org/authors. # http://kwant-project.org/authors.
from kwant.linalg import lu_factor, lu_solve, rcond_from_lu, gen_eig, schur, \ from kwant.linalg import (
convert_r2c_schur, order_schur, evecs_from_schur, gen_schur, \ lu_factor, lu_solve, rcond_from_lu, gen_eig, schur,
convert_r2c_gen_schur, order_gen_schur, evecs_from_gen_schur convert_r2c_schur, order_schur, evecs_from_schur, gen_schur,
convert_r2c_gen_schur, order_gen_schur, evecs_from_gen_schur)
from nose.tools import assert_equal, assert_true from nose.tools import assert_equal, assert_true
import numpy as np import numpy as np
from _test_utils import _Random, assert_array_almost_equal from _test_utils import _Random, assert_array_almost_equal
......
...@@ -263,8 +263,7 @@ def setup_linsys(h_cell, h_hop, tol=1e6, stabilization=None): ...@@ -263,8 +263,7 @@ def setup_linsys(h_cell, h_hop, tol=1e6, stabilization=None):
# the projected one (v^dagger psi lambda^-1, s u^dagger psi). # the projected one (v^dagger psi lambda^-1, s u^dagger psi).
def extract_wf(psi, lmbdainv): def extract_wf(psi, lmbdainv):
wf = - dot(u, psi[: n_nonsing] * lmbdainv) - \ wf = -dot(u, psi[: n_nonsing] * lmbdainv) - dot(v, psi[n_nonsing:])
dot(v, psi[n_nonsing:])
if need_to_stabilize: if need_to_stabilize:
wf += 1j * (dot(v, psi[: n_nonsing]) + wf += 1j * (dot(v, psi[: n_nonsing]) +
dot(u, psi[n_nonsing:] * lmbdainv)) dot(u, psi[n_nonsing:] * lmbdainv))
...@@ -572,14 +571,14 @@ def modes(h_cell, h_hop, tol=1e6, stabilization=None): ...@@ -572,14 +571,14 @@ def modes(h_cell, h_hop, tol=1e6, stabilization=None):
# False if h_hop is purely imaginary # False if h_hop is purely imaginary
if not (np.any(h_hop.real) or np.any(h_hop.imag)): if not (np.any(h_hop.real) or np.any(h_hop.imag)):
v = np.empty((0, m)) v = np.empty((0, m))
return PropagatingModes(np.empty((0, n)), np.empty((0,)), return (PropagatingModes(np.empty((0, n)), np.empty((0,)),
np.empty((0,))), \ np.empty((0,))),
StabilizedModes(np.empty((0, 0)), np.empty((0, 0)), 0, v) StabilizedModes(np.empty((0, 0)), np.empty((0, 0)), 0, v))
# Defer most of the calculation to helper routines. # Defer most of the calculation to helper routines.
matrices, v, extract = setup_linsys(h_cell, h_hop, tol, stabilization) matrices, v, extract = setup_linsys(h_cell, h_hop, tol, stabilization)
ev, evanselect, propselect, vec_gen, ord_schur =\ ev, evanselect, propselect, vec_gen, ord_schur = unified_eigenproblem(
unified_eigenproblem(*(matrices + (tol,))) *(matrices + (tol,)))
if v is not None: if v is not None:
n = v.shape[1] n = v.shape[1]
...@@ -591,8 +590,8 @@ def modes(h_cell, h_hop, tol=1e6, stabilization=None): ...@@ -591,8 +590,8 @@ def modes(h_cell, h_hop, tol=1e6, stabilization=None):
# Compute the propagating eigenvectors. # Compute the propagating eigenvectors.
prop_vecs = vec_gen(propselect) prop_vecs = vec_gen(propselect)
# Compute their velocity, and, if necessary, rotate them # Compute their velocity, and, if necessary, rotate them
prop_vecs, real_space_data = \ prop_vecs, real_space_data = make_proper_modes(
make_proper_modes(ev[propselect], prop_vecs, extract, tol) ev[propselect], prop_vecs, extract, tol)
vecs = np.c_[prop_vecs[n:], evan_vecs[n:]] vecs = np.c_[prop_vecs[n:], evan_vecs[n:]]
vecslmbdainv = np.c_[prop_vecs[:n], evan_vecs[:n]] vecslmbdainv = np.c_[prop_vecs[:n], evan_vecs[:n]]
...@@ -674,6 +673,6 @@ def square_selfenergy(width, hopping, fermi_energy): ...@@ -674,6 +673,6 @@ def square_selfenergy(width, hopping, fermi_energy):
result = np.empty((width, width), dtype=complex) result = np.empty((width, width), dtype=complex)
for i in xrange(width): for i in xrange(width):
for j in xrange(width): for j in xrange(width):
result[i, j] = hopping * \ result[i, j] = hopping * (
(psi_p_i[:, i] * psi_p_i[:, j].conj() * f_p).sum() psi_p_i[:, i] * psi_p_i[:, j].conj() * f_p).sum()
return result return result
...@@ -282,8 +282,8 @@ def test_algorithm_equivalence(): ...@@ -282,8 +282,8 @@ def test_algorithm_equivalence():
for vecs, algo in izip(evan_vecs, algos): for vecs, algo in izip(evan_vecs, algos):
# Evanescent modes must span the same linear space. # Evanescent modes must span the same linear space.
assert np.linalg.matrix_rank(np.c_[vecs, evan_vecs[0]], tol=1e-12) == \ assert (np.linalg.matrix_rank(np.c_[vecs, evan_vecs[0]], tol=1e-12) ==
vecs.shape[1], msg.format(algo) vecs.shape[1]), msg.format(algo)
def test_for_all_evs_equal(): def test_for_all_evs_equal():
...@@ -308,11 +308,11 @@ def test_dtype_linsys(): ...@@ -308,11 +308,11 @@ def test_dtype_linsys():
h_hop) h_hop)
assert lsys.eigenproblem[0].dtype == np.float64 assert lsys.eigenproblem[0].dtype == np.float64
lsys = kwant.physics.leads.setup_linsys(h_cell.astype(np.complex128) lsys = kwant.physics.leads.setup_linsys(h_cell.astype(np.complex128)
- 0.3*np.eye(2), - 0.3*np.eye(2),
h_hop.astype(np.complex128)) h_hop.astype(np.complex128))
assert lsys.eigenproblem[0].dtype == np.float64 assert lsys.eigenproblem[0].dtype == np.float64
# energy=1 is an eigenstate of the isolated cell Hamiltonian, # energy=1 is an eigenstate of the isolated cell Hamiltonian,
# i.e. a complex self-energy stabilization is necessary # i.e. a complex self-energy stabilization is necessary
lsys = kwant.physics.leads.setup_linsys(h_cell - 1*np.eye(2), lsys = kwant.physics.leads.setup_linsys(h_cell - 1*np.eye(2),
......
...@@ -149,7 +149,7 @@ if mpl_enabled: ...@@ -149,7 +149,7 @@ if mpl_enabled:
corners = np.zeros((3, 8, 6), np.float_) corners = np.zeros((3, 8, 6), np.float_)
corners[0, [0, 1, 2, 3], 0] = corners[0, [4, 5, 6, 7], 1] = \ corners[0, [0, 1, 2, 3], 0] = corners[0, [4, 5, 6, 7], 1] = \
corners[0, [0, 1, 4, 5], 2] = corners[0, [2, 3, 6, 7], 3] = \ corners[0, [0, 1, 4, 5], 2] = corners[0, [2, 3, 6, 7], 3] = \
corners[0, [0, 2, 4, 6], 4] = corners[0, [1, 3, 5, 7], 5] = 1. corners[0, [0, 2, 4, 6], 4] = corners[0, [1, 3, 5, 7], 5] = 1.0
class Line3DCollection(mplot3d.art3d.Line3DCollection): class Line3DCollection(mplot3d.art3d.Line3DCollection):
...@@ -624,8 +624,8 @@ def output_fig(fig, output_mode='auto', file=None, savefile_opts=None, ...@@ -624,8 +624,8 @@ def output_fig(fig, output_mode='auto', file=None, savefile_opts=None,
try: try:
fake_fig = matplotlib.pyplot.figure() fake_fig = matplotlib.pyplot.figure()
except AttributeError: except AttributeError:
msg = 'matplotlib.pyplot is unavailable. Execute `import ' \ msg = ('matplotlib.pyplot is unavailable. Execute `import '
'matplotlib.pyplot` or use a different output mode.' 'matplotlib.pyplot` or use a different output mode.')
raise RuntimeError(msg) raise RuntimeError(msg)
fake_fig.canvas.figure = fig fake_fig.canvas.figure = fig
fig.canvas = fake_fig.canvas fig.canvas = fake_fig.canvas
...@@ -699,8 +699,8 @@ def sys_leads_sites(sys, num_lead_cells=2): ...@@ -699,8 +699,8 @@ def sys_leads_sites(sys, num_lead_cells=2):
for leadnr, lead in enumerate(sys.leads): for leadnr, lead in enumerate(sys.leads):
start = len(sites) start = len(sites)
# We will only plot leads with a graph and with a symmetry. # We will only plot leads with a graph and with a symmetry.
if hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and \ if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and
len(sys.lead_interfaces[leadnr]): len(sys.lead_interfaces[leadnr])):
sites.extend(((site, leadnr, i) for site in sites.extend(((site, leadnr, i) for site in
xrange(lead.cell_size) for i in xrange(lead.cell_size) for i in
xrange(num_lead_cells))) xrange(num_lead_cells)))
...@@ -844,8 +844,8 @@ def sys_leads_hoppings(sys, num_lead_cells=2): ...@@ -844,8 +844,8 @@ def sys_leads_hoppings(sys, num_lead_cells=2):
for leadnr, lead in enumerate(sys.leads): for leadnr, lead in enumerate(sys.leads):
start = len(hoppings) start = len(hoppings)
# We will only plot leads with a graph and with a symmetry. # We will only plot leads with a graph and with a symmetry.
if hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and \ if (hasattr(lead, 'graph') and hasattr(lead, 'symmetry') and
len(sys.lead_interfaces[leadnr]): len(sys.lead_interfaces[leadnr])):
hoppings.extend(((hop, leadnr, i) for hop in ll_hoppings(lead) hoppings.extend(((hop, leadnr, i) for hop in ll_hoppings(lead)
for i in xrange(num_lead_cells))) for i in xrange(num_lead_cells)))
lead_cells.append(slice(start, len(hoppings))) lead_cells.append(slice(start, len(hoppings)))
...@@ -1098,8 +1098,8 @@ def plot(sys, num_lead_cells=2, unit='nn', ...@@ -1098,8 +1098,8 @@ def plot(sys, num_lead_cells=2, unit='nn',
def resize_to_dim(array): def resize_to_dim(array):
if array.shape[1] != dim: if array.shape[1] != dim:
ar = np.zeros((len(array), dim), dtype=float) ar = np.zeros((len(array), dim), dtype=float)
ar[:, : min(dim, array.shape[1])] = \ ar[:, : min(dim, array.shape[1])] = array[
array[:, : min(dim, array.shape[1])] :, : min(dim, array.shape[1])]
return ar return ar
else: else:
return array return array
......
...@@ -143,8 +143,8 @@ def gaussian(n, sym='A', v=1.): ...@@ -143,8 +143,8 @@ def gaussian(n, sym='A', v=1.):
elif sym == 'CII': elif sym == 'CII':
sigma_z = np.array((n // 4) * [1, 1, -1, -1]) sigma_z = np.array((n // 4) * [1, 1, -1, -1])
idx_sigma_x = np.arange(n) + 2 * sigma_z idx_sigma_x = np.arange(n) + 2 * sigma_z
h += sigma_z.reshape(-1, 1) * h[idx_sigma_x][:, idx_sigma_x].conj() * \ h += (sigma_z.reshape(-1, 1) * h[idx_sigma_x][:, idx_sigma_x].conj() *
sigma_z sigma_z)
factor /= np.sqrt(2) factor /= np.sqrt(2)
h *= factor h *= factor
......
...@@ -172,8 +172,10 @@ class SparseSolver(object): ...@@ -172,8 +172,10 @@ class SparseSolver(object):
if not realspace: if not realspace:
prop, stab = lead.modes(energy, args) prop, stab = lead.modes(energy, args)
lead_info.append(prop) lead_info.append(prop)
u, ulinv, nprop, svd_v = \ u = stab.vecs
stab.vecs, stab.vecslmbdainv, stab.nmodes, stab.sqrt_hop ulinv = stab.vecslmbdainv
nprop = stab.nmodes
svd_v = stab.sqrt_hop
if len(u) == 0: if len(u) == 0:
rhs.append(None) rhs.append(None)
...@@ -190,11 +192,11 @@ class SparseSolver(object): ...@@ -190,11 +192,11 @@ class SparseSolver(object):
iface_orbs = np.r_[tuple(slice(offsets[i], offsets[i + 1]) iface_orbs = np.r_[tuple(slice(offsets[i], offsets[i + 1])
for i in interface)] for i in interface)]
n_lead_orbs = svd_v.shape[0] if svd_v is not None else \ n_lead_orbs = (svd_v.shape[0] if svd_v is not None
u_out.shape[0] else u_out.shape[0])
if n_lead_orbs != len(iface_orbs): if n_lead_orbs != len(iface_orbs):
msg = 'Lead {0} has hopping with dimensions ' + \ msg = ('Lead {0} has hopping with dimensions '
'incompatible with its interface dimension.' 'incompatible with its interface dimension.')
raise ValueError(msg.format(leadnum)) raise ValueError(msg.format(leadnum))
coords = np.r_[[np.arange(len(iface_orbs))], [iface_orbs]] coords = np.r_[[np.arange(len(iface_orbs))], [iface_orbs]]
...@@ -203,8 +205,8 @@ class SparseSolver(object): ...@@ -203,8 +205,8 @@ class SparseSolver(object):
if svd_v is not None: if svd_v is not None:
v_sp = sp.csc_matrix(svd_v.T.conj()) * transf v_sp = sp.csc_matrix(svd_v.T.conj()) * transf
vdaguout_sp = transf.T * \ vdaguout_sp = (transf.T *
sp.csc_matrix(np.dot(svd_v, u_out)) sp.csc_matrix(np.dot(svd_v, u_out)))
lead_mat = - ulinv_out lead_mat = - ulinv_out
else: else:
v_sp = transf v_sp = transf
...@@ -233,9 +235,9 @@ class SparseSolver(object): ...@@ -233,9 +235,9 @@ class SparseSolver(object):
for i in interface)] for i in interface)]
if sigma.shape != 2 * vars.shape: if sigma.shape != 2 * vars.shape:
msg = 'Self-energy dimension for lead {0} does not ' + \ msg = ('Self-energy dimension for lead {0} does not '
'match the total number of orbitals of the ' + \ 'match the total number of orbitals of the '
'sites for which it is defined.' 'sites for which it is defined.')
raise ValueError(msg.format(leadnum)) raise ValueError(msg.format(leadnum))
y, x = np.meshgrid(vars, vars) y, x = np.meshgrid(vars, vars)
...@@ -326,9 +328,9 @@ class SparseSolver(object): ...@@ -326,9 +328,9 @@ class SparseSolver(object):
in_leads = range(n) in_leads = range(n)
if out_leads is None: if out_leads is None:
out_leads = range(n) out_leads = range(n)
if sorted(in_leads) != in_leads or sorted(out_leads) != out_leads or \ if (sorted(in_leads) != in_leads or sorted(out_leads) != out_leads or
len(set(in_leads)) != len(in_leads) or \ len(set(in_leads)) != len(in_leads) or
len(set(out_leads)) != len(out_leads): len(set(out_leads)) != len(out_leads)):
raise ValueError("Lead lists must be sorted and " raise ValueError("Lead lists must be sorted and "
"with unique entries.") "with unique entries.")
if len(in_leads) == 0 or len(out_leads) == 0: if len(in_leads) == 0 or len(out_leads) == 0:
...@@ -409,9 +411,9 @@ class SparseSolver(object): ...@@ -409,9 +411,9 @@ class SparseSolver(object):
in_leads = range(n) in_leads = range(n)
if out_leads is None: if out_leads is None:
out_leads = range(n) out_leads = range(n)
if sorted(in_leads) != in_leads or sorted(out_leads) != out_leads or \ if (sorted(in_leads) != in_leads or sorted(out_leads) != out_leads or
len(set(in_leads)) != len(in_leads) or \ len(set(in_leads)) != len(in_leads) or
len(set(out_leads)) != len(out_leads): len(set(out_leads)) != len(out_leads)):
raise ValueError("Lead lists must be sorted and " raise ValueError("Lead lists must be sorted and "
"with unique entries.") "with unique entries.")
if len(in_leads) == 0 or len(out_leads) == 0: if len(in_leads) == 0 or len(out_leads) == 0:
...@@ -471,9 +473,8 @@ class SparseSolver(object): ...@@ -471,9 +473,8 @@ class SparseSolver(object):
raise NotImplementedError("ldos for leads with only " raise NotImplementedError("ldos for leads with only "
"self-energy is not implemented yet.") "self-energy is not implemented yet.")
linsys, lead_info = \ linsys, lead_info = self._make_linear_sys(
self._make_linear_sys(sys, xrange(len(sys.leads)), energy, args, sys, xrange(len(sys.leads)), energy, args, check_hermiticity)
check_hermiticity)
ldos = np.zeros(linsys.num_orb, float) ldos = np.zeros(linsys.num_orb, float)
factored = None factored = None
...@@ -532,12 +533,11 @@ class WaveFunction(object): ...@@ -532,12 +533,11 @@ class WaveFunction(object):
for lead in sys.leads: for lead in sys.leads:
if not hasattr(lead, 'modes'): if not hasattr(lead, 'modes'):
# TODO: figure out what to do with self-energies. # TODO: figure out what to do with self-energies.
msg = 'Wave functions for leads with only self-energy' + \ msg = ('Wave functions for leads with only self-energy'
' are not available yet.' ' are not available yet.')
raise NotImplementedError(msg) raise NotImplementedError(msg)
linsys, lead_info = \ linsys, lead_info = solver._make_linear_sys(
solver._make_linear_sys(sys, xrange(len(sys.leads)), energy, args, sys, xrange(len(sys.leads)), energy, args, check_hermiticity)
check_hermiticity)
self.solve = solver._solve_linear_sys self.solve = solver._solve_linear_sys
self.rhs = linsys.rhs self.rhs = linsys.rhs
self.factorized_h = solver._factorized(linsys.lhs) self.factorized_h = solver._factorized(linsys.lhs)
...@@ -630,9 +630,8 @@ class SMatrix(BlockResult): ...@@ -630,9 +630,8 @@ class SMatrix(BlockResult):
return np.linalg.norm(self.submatrix(lead_out, lead_in)) ** 2 return np.linalg.norm(self.submatrix(lead_out, lead_in)) ** 2
def __repr__(self): def __repr__(self):
return "SMatrix(data=%r, lead_info=%r, " \ return ("SMatrix(data=%r, lead_info=%r, out_leads=%r, in_leads=%r)" %
"out_leads=%r, in_leads=%r)" % (self.data, self.lead_info, (self.data, self.lead_info, self.out_leads, self.in_leads))
self.out_leads, self.in_leads)
class GreensFunction(BlockResult): class GreensFunction(BlockResult):
...@@ -709,6 +708,6 @@ class GreensFunction(BlockResult): ...@@ -709,6 +708,6 @@ class GreensFunction(BlockResult):
return result return result
def __repr__(self): def __repr__(self):
return "GreensFunction(data=%r, lead_info=%r, " \ return ("GreensFunction(data=%r, lead_info=%r, "
"out_leads=%r, in_leads=%r)" % (self.data, self.lead_info, "out_leads=%r, in_leads=%r)" %
self.out_leads, self.in_leads) (self.data, self.lead_info, self.out_leads, self.in_leads))
...@@ -9,8 +9,8 @@ ...@@ -9,8 +9,8 @@
#from nose.plugins.skip import Skip, SkipTest #from nose.plugins.skip import Skip, SkipTest
from numpy.testing.decorators import skipif from numpy.testing.decorators import skipif
try: try:
from kwant.solvers.mumps import \ from kwant.solvers.mumps import (
smatrix, greens_function, ldos, wave_function, options, reset_options smatrix, greens_function, ldos, wave_function, options, reset_options)
import _test_sparse import _test_sparse
no_mumps = False no_mumps = False
except ImportError: except ImportError:
......
...@@ -16,8 +16,7 @@ def onsite(site, phi, salt): ...@@ -16,8 +16,7 @@ def onsite(site, phi, salt):
def test_qhe(W=16, L=8): def test_qhe(W=16, L=8):
def central_region(pos): def central_region(pos):
x, y = pos x, y = pos
return -L < x < L and \ return -L < x < L and abs(y) < W - 5.5 * math.exp(-x**2 / 5**2)
abs(y) < W - 5.5 * math.exp(-x**2 / 5**2)
lat = kwant.lattice.square() lat = kwant.lattice.square()
sys = kwant.Builder() sys = kwant.Builder()
......
...@@ -100,8 +100,8 @@ def test_plot(): ...@@ -100,8 +100,8 @@ def test_plot():
for color in color_opts: for color in color_opts:
for sys in (sys2d, sys3d): for sys in (sys2d, sys3d):
fig = plot(sys, site_color=color, cmap='binary', file=out) fig = plot(sys, site_color=color, cmap='binary', file=out)
if color != 'k' and \ if (color != 'k' and
isinstance(color(iter(sys2d.sites()).next()), float): isinstance(color(iter(sys2d.sites()).next()), float)):
assert fig.axes[0].collections[0].get_array() is not None assert fig.axes[0].collections[0].get_array() is not None
assert len(fig.axes[0].collections) == (8 if sys is sys2d else assert len(fig.axes[0].collections) == (8 if sys is sys2d else
6) 6)
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment