Esempio n. 1
0
def test_symmetry_has_subgroup():
    rng = np.random.RandomState(0)
    ## test whether actual subgroups are detected as such
    vecs = rng.randn(3, 3)
    sym1 = lattice.TranslationalSymmetry(*vecs)
    ns = system.NoSymmetry()
    assert ns.has_subgroup(ns)
    assert sym1.has_subgroup(sym1)
    assert sym1.has_subgroup(ns)
    assert sym1.has_subgroup(
        lattice.TranslationalSymmetry(2 * vecs[0], 3 * vecs[1] + 4 * vecs[2]))
    assert not lattice.TranslationalSymmetry(*(0.8 * vecs)).has_subgroup(sym1)

    ## test subgroup creation
    for dim in range(1, 4):
        generators = rng.randint(10, size=(dim, 3))
        assert sym1.has_subgroup(sym1.subgroup(*generators))

    # generators are not linearly independent
    with raises(ValueError):
        sym1.subgroup(*rng.randint(10, size=(4, 3)))

    # generators are not integer sequences
    with raises(ValueError):
        sym1.subgroup(*rng.rand(1, 3))
Esempio n. 2
0
def test_shape():
    def in_circle(pos):
        return pos[0]**2 + pos[1]**2 < 3

    lat = lattice.honeycomb(norbs=1)
    sites = list(lat.shape(in_circle, (0, 0))())
    sites_alt = list()
    sl0, sl1 = lat.sublattices
    for x in range(-2, 3):
        for y in range(-2, 3):
            tag = (x, y)
            for site in (sl0(*tag), sl1(*tag)):
                if in_circle(site.pos):
                    sites_alt.append(site)
    assert len(sites) == len(sites_alt)
    assert set(sites) == set(sites_alt)
    raises(ValueError, lat.shape(in_circle, (10, 10))().__next__)

    # Check if narrow ribbons work.
    for period in (0, 1), (1, 0), (1, -1):
        vec = lat.vec(period)
        sym = lattice.TranslationalSymmetry(vec)

        def shape(pos):
            return abs(pos[0] * vec[1] - pos[1] * vec[0]) < 10

        sites = list(lat.shape(shape, (0, 0))(sym))
        assert len(sites) > 35
Esempio n. 3
0
def test_wire():
    rng = ensure_rng(5)
    vecs = rng.randn(3, 3)
    vecs[0] = [1, 0, 0]
    center = rng.randn(3)
    lat = lattice.general(vecs, rng.randn(4, 3), norbs=1)
    syst = builder.Builder(lattice.TranslationalSymmetry((2, 0, 0)))
    def wire_shape(pos):
        pos = np.array(pos)
        return np.linalg.norm(pos[1:] - center[1:])**2 <= 8.6**2
    syst[lat.shape(wire_shape, center)] = 0
    sites2 = set(syst.sites())
    syst = builder.Builder(lattice.TranslationalSymmetry((2, 0, 0)))
    syst[lat.wire(center, 8.6)] = 1
    sites1 = set(syst.sites())
    assert sites1 == sites2
Esempio n. 4
0
def test_symmetry_act():
    lat = lattice.square(norbs=1)
    sym = lattice.TranslationalSymmetry((1, 0), (0, 1))
    site = lat(0, 0)
    hopping = (lat(0, 0), lat(1, 0))
    el = (1, 0)

    # Verify that the dtype of tags of sites returned by 'act' is 'int'
    for el in [el, ta.array(el, int)]:
        assert sym.act(el, site).tag.dtype is int
        assert all(s.tag.dtype is int for s in sym.act(el, *hopping))

    for el in [(1.0, 0), (1.5, 0)]:
        with raises(ValueError):
            sym.act(el, site)
        with raises(ValueError):
            sym.act(ta.array(el), site)
Esempio n. 5
0
def test_translational_symmetry_reversed():
    rng = ensure_rng(30)
    lat = lattice.general(np.identity(3), norbs=1)
    sites = [lat(i, j, k) for i in range(-2, 6) for j in range(-2, 6)
                          for k in range(-2, 6)]
    for i in range(4):
            periods = rng.randint(-5, 5, (3, 3))
            try:
                sym = lattice.TranslationalSymmetry(*periods)
                rsym = sym.reversed()
                for site in sites:
                    assert sym.to_fd(site) == rsym.to_fd(site)
                    assert sym.which(site) == -rsym.which(site)
                    vec = np.array([1, 1, 1])
                    assert sym.act(vec, site), rsym.act(-vec == site)
            except ValueError:
                pass
Esempio n. 6
0
def test_act_sites_array():
    lat = lattice.square(norbs=1)

    tags = [(i, j) for i in range(4) for j in range(5)]
    sites = [lat(*tag) for tag in tags]
    site_array = builder.SiteArray(lat, tags=tags)

    for vectors in ([(1, 0)], [(1, 0), (0, 1)]):
        symm = lattice.TranslationalSymmetry(*vectors)
        element = [np.random.randint(5, 10) for _ in range(len(vectors))]
        trans_sites = [symm.act(element, site) for site in sites]

        # these two sites array should be the equal
        trans_sites_array = builder._make_site_arrays(trans_sites)
        new_site_array = symm.act(element, site_array)

        trans_tags_dict = {sa.family.name: sa.tags for sa in trans_sites_array}
        new_tags_dict = {sa.family.name: sa.tags for sa in [new_site_array]}
        for name in trans_tags_dict:
            assert np.all(trans_tags_dict[name] == new_tags_dict[name])
Esempio n. 7
0
def model_to_builder(model, norbs, lat_vecs, atom_coords, *, coeffs=None):
    """Make a `~kwant.builder.Builder` out of qsymm.Models or qsymm.BlochModels.

    Parameters
    ----------
    model : qsymm.Model, qsymm.BlochModel, or an iterable thereof
        The Hamiltonian (or terms of the Hamiltonian) to convert to a
        Builder.
    norbs : OrderedDict or sequence of pairs
        Maps sites to the number of orbitals per site in a unit cell.
    lat_vecs : list of arrays
        Lattice vectors of the underlying tight binding lattice.
    atom_coords : list of arrays
        Positions of the sites (or atoms) within a unit cell.
        The ordering of the atoms is the same as in norbs.
    coeffs : list of sympy.Symbol, default None.
        Constant prefactors for the individual terms in model, if model
        is a list of multiple objects. If model is a single Model or BlochModel
        object, this argument is ignored. By default assigns the coefficient
        c_n to element model[n].

    Returns
    -------
    syst : `~kwant.builder.Builder`
        The unfinalized Kwant system representing the qsymm Model(s).

    Notes
    -----
    Onsite terms that are not provided in the input model are set
    to zero by default.

    The input model(s) representing the tight binding Hamiltonian in
    Bloch form should follow the convention where the difference in the real
    space atomic positions appear in the Bloch factors.
    """

    def make_int(R):
        # If close to an integer array convert to integer tinyarray, else
        # return None
        R_int = ta.array(np.round(R), int)
        if qsymm.linalg.allclose(R, R_int):
            return R_int
        else:
            return None

    def term_onsite(onsites_dict, hopping_dict, hop_mat, atoms,
                    sublattices, coords_dict):
        """Find the Kwant onsites and hoppings in a qsymm.BlochModel term
        that has no lattice translation in the Bloch factor.
        """
        for atom1, atom2 in it.product(atoms, atoms):
            # Subblock within the same sublattice is onsite
            hop = hop_mat[ranges[atom1], ranges[atom2]]
            if sublattices[atom1] == sublattices[atom2]:
                onsites_dict[atom1] += Model({coeff: hop}, momenta=momenta)
            # Blocks between sublattices are hoppings between sublattices
            # at the same position.
            # Only include nonzero hoppings
            elif not allclose(hop, 0):
                if not allclose(np.array(coords_dict[atom1]),
                                np.array(coords_dict[atom2])):
                    raise ValueError(
                        "Position of sites not compatible with qsymm model.")
                lat_basis = np.array(zer)
                hop = Model({coeff: hop}, momenta=momenta)
                hop_dir = builder.HoppingKind(-lat_basis, sublattices[atom1],
                                              sublattices[atom2])
                hopping_dict[hop_dir] += hop
        return onsites_dict, hopping_dict

    def term_hopping(hopping_dict, hop_mat, atoms,
                     sublattices, coords_dict):
        """Find Kwant hoppings in a qsymm.BlochModel term that has a lattice
        translation in the Bloch factor.
        """
        # Iterate over combinations of atoms, set hoppings between each
        for atom1, atom2 in it.product(atoms, atoms):
            # Take the block from atom1 to atom2
            hop = hop_mat[ranges[atom1], ranges[atom2]]
            # Only include nonzero hoppings
            if allclose(hop, 0):
                continue
            # Adjust hopping vector to Bloch form basis
            r_lattice = (
                r_vec
                + np.array(coords_dict[atom1])
                - np.array(coords_dict[atom2])
            )
            # Bring vector to basis of lattice vectors
            lat_basis = np.linalg.solve(np.vstack(lat_vecs).T, r_lattice)
            lat_basis = make_int(lat_basis)
            # Should only have hoppings that are integer multiples of
            # lattice vectors
            if lat_basis is not None:
                hop_dir = builder.HoppingKind(-lat_basis,
                                              sublattices[atom1],
                                              sublattices[atom2])
                # Set the hopping as the matrix times the hopping amplitude
                hopping_dict[hop_dir] += Model({coeff: hop}, momenta=momenta)
            else:
                raise RuntimeError('A nonzero hopping not matching a '
                                   'lattice vector was found.')
        return hopping_dict

    # Disambiguate single model instances from iterables thereof. Because
    # Model is itself iterable (subclasses dict) this is a bit cumbersome.
    if isinstance(model, Model):
        # BlochModel can't yet handle getting a Blochmodel as input
        if not isinstance(model, BlochModel):
            model = BlochModel(model)
    else:
        model = BlochModel(hamiltonian_from_family(
            model, coeffs=coeffs, nsimplify=False, tosympy=False))


    # 'momentum' and 'zer' are used in the closures defined above, so don't
    # move these declarations down.
    momenta = model.momenta
    if len(momenta) != len(lat_vecs):
        raise ValueError("Dimension of the lattice and number of "
                         "momenta do not match.")
    zer = [0] * len(momenta)


    # Subblocks of the Hamiltonian for different atoms.
    N = 0
    if not any([isinstance(norbs, OrderedDict), isinstance(norbs, list),
                isinstance(norbs, tuple)]):
        raise ValueError('norbs must be OrderedDict, tuple, or list.')
    else:
        norbs = OrderedDict(norbs)
    ranges = dict()
    for a, n in norbs.items():
        ranges[a] = slice(N, N + n)
        N += n

    # Extract atoms and number of orbitals per atom,
    # store the position of each atom
    atoms, orbs = zip(*norbs.items())
    coords_dict = dict(zip(atoms, atom_coords))

    # Make the kwant lattice
    lat = lattice.general(lat_vecs, atom_coords, norbs=orbs)
    # Store sublattices by name
    sublattices = dict(zip(atoms, lat.sublattices))

    # Keep track of the hoppings and onsites by storing those
    # which have already been set.
    hopping_dict = defaultdict(dict)
    onsites_dict = defaultdict(dict)

    # Iterate over all terms in the model.
    for key, hop_mat in model.items():
        # Determine whether this term is an onsite or a hopping, extract
        # overall symbolic coefficient if any, extract the exponential
        # part describing the hopping if present.
        r_vec, coeff = key
        # Onsite term; modifies onsites_dict and hopping_dict in-place
        if allclose(r_vec, 0):
            term_onsite(
                onsites_dict, hopping_dict, hop_mat,
                atoms, sublattices, coords_dict)
        # Hopping term; modifies hopping_dict in-place
        else:
            term_hopping(hopping_dict, hop_mat, atoms,
                         sublattices, coords_dict)

    # If some onsite terms are not set, we set them to zero.
    for atom in atoms:
        if atom not in onsites_dict:
            onsites_dict[atom] = Model(
                {sympy.numbers.One(): np.zeros((norbs[atom], norbs[atom]))},
                momenta=momenta)

    # Make the Kwant system, and set all onsites and hoppings.

    sym = lattice.TranslationalSymmetry(*lat_vecs)
    syst = builder.Builder(sym)

    # Iterate over all onsites and set them
    for atom, onsite in onsites_dict.items():
        syst[sublattices[atom](*zer)] = onsite.lambdify(onsite=True)

    # Finally, iterate over all the hoppings and set them
    for direction, hopping in hopping_dict.items():
        syst[direction] = hopping.lambdify(hopping=True)

    return syst