Coverage for kwant/lattice.py : 85%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
# Copyright 2011-2013 Kwant authors. # # This file is part of Kwant. It is subject to the license terms in the file # LICENSE.rst found in the top-level directory of this distribution and at # http://kwant-project.org/license. A list of Kwant authors can be found in # the file AUTHORS.rst at the top-level directory of this distribution and at # http://kwant-project.org/authors.
'chain', 'square', 'cubic', 'triangular', 'honeycomb', 'kagome']
""" Create a Bravais lattice of any dimensionality, with any number of sites.
Parameters ---------- prim_vecs : 2d array-like of floats The primitive vectors of the Bravais lattice basis : 2d array-like of floats The coordinates of the basis sites inside the unit cell name : string or sequence of strings Name of the lattice, or sequence of names of all of the sublattices. If the name of the lattice is given, the names of sublattices (if any) are obtained by appending their number to the name of the lattice. norbs : int or sequence of ints, optional The number of orbitals per site on the lattice, or a sequence of the number of orbitals of sites on each of the sublattices.
Returns ------- lattice : either `Monatomic` or `Polyatomic` Resulting lattice.
Notes ----- This function is largely an alias to the constructors of corresponding lattices. """ else:
"""Check constraints to ensure that prim_vecs is correct."""
'the space dimensionality.')
""" A Bravais lattice with an arbitrary number of sites in the basis.
Contains `Monatomic` sublattices. Note that an instance of ``Polyatomic`` is not itself a `~kwant.builder.SiteFamily`, only its sublattices are.
Parameters ---------- prim_vecs : 2d array-like of floats The primitive vectors of the Bravais lattice basis : 2d array-like of floats The coordinates of the basis sites inside the unit cell. name : string or sequence of strings, optional The name of the lattice, or a sequence of the names of all the sublattices. If the name of the lattice is given, the names of sublattices are obtained by appending their number to the name of the lattice. norbs : int or sequence of ints, optional The number of orbitals per site on the lattice, or a sequence of the number of orbitals of sites on each of the sublattices.
Raises ------ ValueError If dimensionalities do not match. """
name = ''
raise ValueError('`basis` must be a 2d array-like object.') raise ValueError('Basis dimensionality does not match ' 'the space dimensionality.')
'the number of basis vectors')
for offset, sname, norb in zip(basis, name, norbs)] # Sequence of primitive vectors of the lattice. # Precalculation of auxiliary arrays for real space calculations.
sl_names = ', '.join(str(sl.name) for sl in self.sublattices) return '<Polyatomic lattice with sublattices {0}>'.format(sl_names)
"""Return a key for all the lattice sites inside a given shape.
The object returned by this method is primarily meant to be used as a key for indexing `~kwant.builder.Builder` instances. See example below.
Parameters ---------- function : callable A function of real space coordinates that returns a truth value: true for coordinates inside the shape, and false otherwise. start : 1d array-like The real-space origin for the flood-fill algorithm.
Returns ------- shape_sites : function
Notes ----- When the function returned by this method is called, a flood-fill algorithm finds and yields all the lattice sites inside the specified shape starting from the specified position.
A `~kwant.builder.Symmetry` or `~kwant.builder.Builder` may be passed as sole argument when calling the function returned by this method. This will restrict the flood-fill to the fundamental domain of the symmetry (or the builder's symmetry). Note that unless the shape function has that symmetry itself, the result may be unexpected.
Examples -------- >>> def circle(pos): ... x, y = pos ... return x**2 + y**2 < 100 ... >>> lat = kwant.lattice.honeycomb() >>> syst = kwant.Builder() >>> syst[lat.shape(circle, (0, 0))] = 0 >>> syst[lat.neighbors()] = 1 """
raise ValueError('Dimensionality of start position does not ' 'match the space dimensionality.')
#### Flood-fill ####
"""Return a key for all the lattice sites inside an infinite cylinder.
This method makes it easy to define cylindrical (2d: rectangular) leads that point in any direction. The object returned by this method is primarily meant to be used as a key for indexing `~kwant.builder.Builder` instances. See example below.
Parameters ---------- center : 1d array-like of floats A point belonging to the axis of the cylinder. radius : float The radius of the cylinder.
Notes ----- The function returned by this method is to be called with a `~kwant.builder.TranslationalSymmetry` instance (or a `~kwant.builder.Builder` instance whose symmetry is used then) as sole argument. All the lattice sites (in the fundamental domain of the symmetry) inside the specified infinite cylinder are yielded. The direction of the cylinder is determined by the symmetry.
Examples -------- >>> lat = kwant.lattice.honeycomb() >>> sym = kwant.TranslationalSymmetry(lat.a.vec((-2, 1))) >>> lead = kwant.Builder(sym) >>> lead[lat.wire((0, -5), 5)] = 0 >>> lead[lat.neighbors()] = 1 """
raise ValueError('wire shape only works with ' 'translational symmetry.') raise ValueError('wire shape only works with one-dimensional ' 'translational symmetry.')
"""Return n-th nearest neighbor hoppings.
Parameters ---------- n : integer Order of the hoppings to return. eps : float Tolerance relative to the length of the shortest lattice vector for when to consider lengths to be approximately equal.
Returns ------- hoppings : list of kwant.builder.HopplingKind objects The n-th nearest neighbor hoppings.
Notes ----- The hoppings are ordered lexicographically according to sublattice from which they originate, sublattice on which they end, and their lattice coordinates. Out of the two equivalent hoppings (a hopping and its reverse) only the lexicographically larger one is returned. """ # This algorithm is not designed to be fast and can be improved, # however there is no real need. sls[0].pos(([0] * sls[0].lattice_dim)), 2)[-1] if sls.index(j) >= sls.index(i)] for i in tag: if i < 0: return False elif i > 0: return True else: continue return True
# Find the correct number of neighbors to calculate on each lattice.
for tag in tags] cutoff += 1
# We now have all the required sites, we need to find n-th. if abs(dist - n_dist) < eps]) # Sort the tags. # Throw away equivalent hoppings if # two sublattices are the same.
def prim_vecs(self): """(sequence of vectors) Primitive vectors
`prim_vecs[i]`` is the `i`-th primitive basis vector of the lattice displacement of the lattice origin from the real space coordinates origin. """
""" Return the coordinates of a Bravais lattice vector in real space.
Parameters ---------- vec : integer vector
Returns ------- output : real vector """
""" A Bravais lattice with a single site in the basis.
Instances of this class provide the `~kwant.builder.SiteFamily` interface. Site tags (see `~kwant.builder.SiteFamily`) are sequences of integers and describe the lattice coordinates of a site.
``Monatomic`` instances are used as site families on their own or as sublattices of `Polyatomic` lattices.
Parameters ---------- prim_vecs : 2d array-like of floats Primitive vectors of the Bravais lattice.
offset : vector of floats Displacement of the lattice origin from the real space coordinates origin.
Attributes ---------- ``offset`` : vector Displacement of the lattice origin from the real space coordinates origin """
name = ''
else: raise ValueError('Dimensionality of offset does not match ' 'that of the space.')
short_array_repr(offset), repr(name), repr(norbs))
# Precalculation of auxiliary arrays for real space calculations.
else: short_array_str(self.offset), orbs)
"""Find n sites closest to position `pos`.
Returns ------- sites : numpy array An array with sites coordinates. """ # TODO (Anton): transform to tinyarrays, once ta indexing is better. self.transf.T)
""" Find the lattice coordinates of the site closest to position ``pos``. """
"""Return the real-space position of the site with a given tag."""
# The following class is designed such that it should avoid floating # point precision issues.
"""A translational symmetry defined in real space.
An alias exists for this common name: ``kwant.TranslationalSymmetry``.
Group elements of this symmetry are integer tuples of appropriate length.
Parameters ---------- p0, p1, p2, ... : sequences of real numbers The symmetry periods in real space.
Notes ----- This symmetry automatically chooses the fundamental domain for each new `SiteFamily` it encounters. If this site family does not correspond to a Bravais lattice, or if it does not have a commensurate period, an error is produced. A certain flexibility in choice of the fundamental domain can be achieved by calling manually the `add_site_family` method and providing it the `other_vectors` parameter.
The fundamental domain for hoppings are all hoppings ``(a, b)`` with site `a` in fundamental domain of sites. """ # TODO: remove the second part of the following message once # everybody got used to it. msg = ("TranslationalSymmetry takes 1d sequences as parameters.\n" "See What's new in Kwant 0.2 in the documentation.") raise ValueError(msg) "linearly independent") # A dictionary containing cached data required for applying the # symmetry to different site families.
"""Return the subgroup generated by a sequence of group elements.
Parameters ---------- *generators: sequence of int Each generator must have length ``self.num_directions``. """
raise ValueError("Unknown symmetry type.")
return False # Mismatch of spatial dimensionalities.
# Absolute tolerance is correct in the following since we want an error # relative to the closest integer. np.allclose(ta.dot(factors, self.periods), other.periods))
""" Select a fundamental domain for site family and cache associated data.
Parameters ---------- fam : `SiteFamily` the site family which has to be processed. Be sure to delete the previously processed site families from `site_family_data` if you want to modify the cache.
other_vectors : 2d array-like of integers Bravais lattice vectors used to complement the periods in forming a basis. The fundamental domain consists of all the lattice sites for which the zero coefficients corresponding to the symmetry periods in the basis formed by the symmetry periods and `other_vectors`. If an insufficient number of `other_vectors` is provided to form a basis, the missing ones are selected automatically.
Raises ------ KeyError If `fam` is already stored in `site_family_data`. ValueError If lattice `fam` is incompatible with given periods. """
raise KeyError('Family already processed, delete it from ' 'site_family_data first.') except ValueError: fam_space_dim = fam.prim_vecs.shape[1] if dim == fam_space_dim: raise msg = ("{0}-d-embedded lattice is incompatible with " "{1}-d translational symmetry.") raise ValueError(msg.format(fam_space_dim, dim)) # Absolute tolerance is correct in the following since we want an error # relative to the closest integer. rtol=0, atol=1e-8) or not np.allclose([fam.vec(i) for i in bravais_periods], self.periods)): 'symmetry {1}.') else: raise ValueError( '`other_vectors` must be a 2d array-like object.') raise ValueError('Only integer other_vectors are allowed.')
raise ValueError('other_vectors and symmetry periods are not ' 'linearly independent.')
# To define the fundamental domain of the new site family we now need to # choose `lat_dim - num_vec` extra lattice vectors that are not # linearly dependent on the vectors we already have. To do so we # continuously add the lattice basis vectors one by one such that they # are not linearly dependent on the existent vectors full_matrices=False)[2]
raise RuntimeError('Adding site family failed.')
ta.array(det_x_inv_m_part), det_m)
def num_directions(self):
except ValueError: msg = 'Expecting a {0}-tuple group element, but got `{1}` instead.' raise ValueError(msg.format(self.num_directions, element)) builder.Site(b.family, b.tag + delta, True)) else: except ValueError: msg = ('Expecting a {0}-tuple group element, ' 'but got `{1}` instead.') raise ValueError(msg.format(self.num_directions, element)) delta2 = -delta2 builder.Site(b.family, b.tag + delta2, True))
"""Return a reversed copy of the symmetry.
The resulting symmetry has all the period vectors opposite to the original and an identical fundamental domain. """
################ Library of lattices
"""Make a one-dimensional lattice."""
"""Make a square lattice."""
"""Make a cubic lattice.""" return Monatomic(((a, 0, 0), (0, a, 0), (0, 0, a)), name=name, norbs=norbs)
"""Make a triangular lattice.""" return Monatomic(a * tri, name=name, norbs=norbs)
"""Make a honeycomb lattice.""" name=name, norbs=norbs)
"""Make a kagome lattice.""" name=name, norbs=norbs)
# TODO (Anton): unhide _prim_vecs, once tinyarray supports indexing of # sub-arrays. |