Coverage for kwant/continuum/discretizer.py : 93%

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-2017 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.
monomials)
"""A builder that is made from a discretized model and knows how to pretty-print itself."""
raise ValueError("Cannot pretty-print _DiscretizedBuilder: " "must contain a single site.") raise ValueError("Cannot pretty-print _DiscretizedBuilder: " "site must be located at origin.")
" ".join(self._coords), "\n\n"])
self.hopping_value_pairs()): else: str(tuple(b.tag)), ":\n"])
# Enable human-readable rendering in Jupyter notebooks: return self.__str__()
################ Interface functions
locals=None): """Construct a tight-binding model from a continuum Hamiltonian.
If necessary, the given Hamiltonian is sympified using `kwant.continuum.sympify`. It is then discretized symbolically and turned into a `~kwant.builder.Builder` instance that may be used with `~kwant.builder.Builder.fill`.
This is a convenience function that is equivalent to first calling `~kwant.continuum.discretize_symbolic` and feeding its result into `~kwant.continuum.build_discretized`.
.. warning:: This function uses ``eval`` (because it calls ``sympy.sympify``), and thus should not be used on unsanitized input.
Parameters ---------- hamiltonian : str or SymPy expression Symbolic representation of a continuous Hamiltonian. It is converted to a SymPy expression using `kwant.continuum.sympify`. coords : sequence of strings, or ``None`` (default) The coordinates for which momentum operators will be treated as differential operators. May contain only "x", "y" and "z" and must be sorted. If not provided, `coords` will be obtained from the input Hamiltonian by reading the present coordinates and momentum operators. grid_spacing : int or float, default: 1 Spacing of the (quadratic or cubic) discretization grid. locals : dict or ``None`` (default) Additional namespace entries for `~kwant.continuum.sympify`. May be used to simplify input of matrices or modify input before proceeding further. For example: ``locals={'k': 'k_x + I * k_y'}`` or ``locals={'sigma_plus': [[0, 2], [0, 0]]}``.
Returns ------- model : `~kwant.builder.Builder` The translationally symmetric builder that corresponds to the provided Hamiltonian. This builder instance belongs to a subclass of the standard builder that may be printed to obtain the source code of the value functions. It also holds the discretization lattice (a `~kwant.lattice.Monatomic` instance with lattice constant `grid_spacing`) in the ``lattice`` attribute. """
"""Discretize a continuous Hamiltonian into a tight-binding representation.
If necessary, the given Hamiltonian is sympified using `kwant.continuum.sympify`. It is then discretized symbolically.
The two return values may be used directly as the first two arguments for `~kwant.continuum.build_discretized`.
.. warning:: This function uses ``eval`` (because it calls ``sympy.sympify``), and thus should not be used on unsanitized input.
Parameters ---------- hamiltonian : str or SymPy expression Symbolic representation of a continuous Hamiltonian. It is converted to a SymPy expression using `kwant.continuum.sympify`. coords : sequence of strings, or ``None`` (default) The coordinates for which momentum operators will be treated as differential operators. May contain only "x", "y" and "z" and must be sorted. If not provided, `coords` will be obtained from the input Hamiltonian by reading the present coordinates and momentum operators. locals : dict or ``None`` (default) Additional namespace entries for `~kwant.continuum.sympify`. May be used to simplify input of matrices or modify input before proceeding further. For example: ``locals={'k': 'k_x + I * k_y'}`` or ``locals={'sigma_plus': [[0, 2], [0, 0]]}``.
Returns ------- tb_hamiltonian : dict Keys are tuples of integers; the offsets of the hoppings ((0, 0, 0) for the onsite). Values are symbolic expressions for the hoppings/onsite. coords : list of strings The coordinates that have been discretized.
"""
raise TypeError("'a' is a symbol used internally to represent " "grid spacing; please use a different symbol.")
else: raise ValueError("The argument 'coords' must be sorted.") raise ValueError("The argument 'coords' may only contain " "'x', 'y', or 'z'.")
raise ValueError("Failed to read any discrete coordinates. This is " "probably due to a lack of momentum operators in " "your input. You can use the 'coords' " "parameter to provide them.")
else:
# do not include Hermitian conjugates of hoppings
"""Create a template builder from a symbolic tight-binding Hamiltonian.
The provided symbolic tight-binding Hamiltonian is put on a (hyper) square lattice and turned into Python functions. These functions are used to create a `~kwant.builder.Builder` instance that may be used with `~kwant.builder.Builder.fill` to construct a system of a desired shape.
The return values of `~kwant.continuum.discretize_symbolic` may be used directly for the first two arguments of this function.
.. warning:: This function uses ``eval`` (because it calls ``sympy.sympify``), and thus should not be used on unsanitized input.
Parameters ---------- tb_hamiltonian : dict Keys must be the offsets of the hoppings, represented by tuples of integers ((0, 0, 0) for onsite). Values must be symbolic expressions for the hoppings/onsite or expressions that can by sympified with `kwant.continuum.sympify`. coords : sequence of strings The coordinates for which momentum operators will be treated as differential operators. May contain only "x", "y" and "z" and must be sorted. grid_spacing : int or float, default: 1 Spacing of the (quadratic or cubic) discretization grid. locals : dict, defaults to empty Additional namespace entries for the calls of `~kwant.continuum.sympify` on the values of `tb_hamiltonian`. May be used to simplify input of matrices or modify input before proceeding further. For example: ``locals={'k': 'k_x + I * k_y'}`` or ``locals={'sigma_plus': [[0, 2], [0, 0]]}``.
Returns ------- model : `~kwant.builder.Builder` The translationally symmetric builder that corresponds to the provided Hamiltonian. This builder instance belongs to a subclass of the standard builder that may be printed to obtain the source code of the value functions. It also holds the discretization lattice (a `~kwant.lattice.Monatomic` instance with lattice constant `grid_spacing`) in the ``lattice`` attribute.
""" raise ValueError('Discrete coordinates cannot be empty.')
raise ValueError("The argument 'coords' must be sorted.")
else:
grid_spacing, onsite, name)
else random_element.shape[0])
# 'delta' parameter to HoppingKind is the negative of the 'hopping offset' for d, val in tb.items()}
lattice.TranslationalSymmetry(*prim_vecs))
"""Calculate derivative of an expression for given coordinate.
Parameters: ----------- expression : sympy.Expr Sympy expression containing function to be derivated. coordinate_name : string Coordinate over which derivative is calculated.
Returns ------- sympy.Expr """
"""Discretize a product of factors.
Parameters ---------- summand : sympy.Expr coords : sequence of strings Must be a subset of ``{'x', 'y', 'z'}``.
Returns ------- sympy.Expr """
# apply momentum as differential operator '-i d/dx' else:
"""Discretize an expression into a discrete (tight-binding) representation.
Parameters ---------- expression : sympy.Expr coords : sequence of strings Must be a subset of ``{'x', 'y', 'z'}``.
Returns ------- dict Keys are tuples of integers; the offsets of the hoppings ((0, 0, 0) for the onsite). Values are symbolic expressions for the hoppings/onsite. """ # e.g. wf(x + h, y, z + h) -> (1, 0, 1)
"""Read hoppings and perform shortening operation."""
# rescale the offsets for each coordinate by their greatest # common divisor across the summands. e.g: # wf(x+2h) + wf(x+4h) --> wf(x+h) + wf(x+2h) and a_x //= 2 # apply the rescaling to the hoppings
# if there are no momenta in the expression, then it is an onsite
# make sure we have list of summands
# discretize every summand
################ string processing
settings = {'allow_unknown_functions': True} else: # We're on Sympy without "allow_unknown_functions" setting
# prevent sympy from printing 'I' for imaginary unit
# copied from sympy's StrPrinter with the code paths # to print 'sqrt' removed.
return '1/%s' % self.parenthesize(expr.base, PREC)
expr.exp.is_Rational and expr.exp.q != 1): if e.startswith('(Rational'): return '%s**%s' % (self.parenthesize(expr.base, PREC), e[1:-1])
"""Process a sympy expression into an evaluatable Python return statement.
Parameters ---------- expr : sympy.Expr
Returns ------- output : string A return string that can be used to assemble a Kwant value function. map_func_calls : dict mapping of function calls to assigned constants. const_symbols : sequance of sympy.Symbol All constants that appear in the expression. _cache: dict mapping of cache symbols to cached matrices. """
if s.name not in blacklisted}
# functions will be evaluated within the function body and the # result assigned to a symbol '_const_<n>', so we replace all # function calls by these symbols in the return statement. for n, s in enumerate(map_func_calls)}
# express matrix return values in terms of sums of known matrices, # which will be assigned to '_cache_n' in the function body. for k, v in mons.items()] else:
coords, onsite): """Generate a series of assignments.
Parameters ---------- map_func_calls : dict mapping of function calls to assigned constants. grid_spacing : int or float Used to get site.pos from site.tag coords : sequence of strings If left as None coordinates will not be read from a site. onsite : bool True if function is called for onsite, false for hoppings
Returns ------- assignments : list of strings List of lines used for including in a function. """
name='_anonymous_func'): """Generate a builder value from a sympy expression.
Parameters ---------- expr : sympy.Expr or sympy.matrix Expr that from which value function will be generated. coords : sequence of strings List of coodinates present in the system. grid_spacing : int or float Lattice spacing of the system
Returns ------- `expr` transformed into an object that can be used as a `kwant.builder.Builder` value. Either a numerical value (``tinyarray.array`` instance or complex number) or a value function. In the case of a function, the source code is available in its `_source` attribute. """ expr, coords=coords)
# first check if value function needs to read coordinates
# constants and functions in the sympy input will be passed # as arguments to the value function {str(k.func) for k in map_func_calls})
# check if all argument names are valid python identifiers "Names of symbols used in Hamiltonian " "must be valid Python identifiers and " "may not be keywords".format(arg_name))
# we can just use a constant value instead of a value function return ta.array(expr.tolist(), complex) else:
grid_spacing=grid_spacing, coords=coords)
# 'site_string' is tightly coupled to the symbols used in '_assign_symbol' else:
# Add "I" to namespace just in case sympy again would miss to replace it # with Python's 1j as it was the case with SymPy 1.2 when I was argument # of some function.
|