Exemplo n.º 1
0
def test_complex_multiorbital_hamiltonian():
    def checkerboard_lattice(delta, t):
        lat = pb.Lattice(a1=[1, 0], a2=[0, 1])
        lat.add_sublattices(('A', [0, 0], -delta),
                            ('B', [1 / 2, 1 / 2], delta))
        lat.add_hoppings(
            ([0, 0], 'A', 'B', t),
            ([0, -1], 'A', 'B', t),
            ([-1, 0], 'A', 'B', t),
            ([-1, -1], 'A', 'B', t),
        )
        return lat

    hopp_t = np.array([[2 + 2j, 3 + 3j], [4 + 4j,
                                          5 + 5j]])  # multi-orbital hopping
    onsite_en = np.array([[1, 1j], [-1j, 1]])  # onsite energy

    model = pb.Model(checkerboard_lattice(onsite_en, hopp_t),
                     pb.translational_symmetry(True, True))
    h = model.hamiltonian.toarray()

    assert model.system.num_sites == 2
    assert h.shape[0] == 4
    assert pytest.fuzzy_equal(h, h.T.conjugate())  # check if Hermitian
    assert pytest.fuzzy_equal(
        h[:2, :2], -h[-2:, -2:])  # onsite energy on A and B is opposite
    assert pytest.fuzzy_equal(h[:2, 2:4],
                              4 * hopp_t)  # hopping A <-> B is 4 * hopp_t
Exemplo n.º 2
0
 def assert_state(name, **kwargs):
     state, x, y, z, nearest = capture[name]
     assert state.shape == kwargs["shape"]
     assert pytest.fuzzy_equal(state, kwargs["state"])
     assert x.shape == kwargs["shape"]
     assert pytest.fuzzy_equal(x, kwargs["x"])
     assert pytest.fuzzy_equal(y, kwargs["y"])
     assert pytest.fuzzy_equal(z, kwargs["z"])
     assert np.all(nearest == kwargs["nearest"])
Exemplo n.º 3
0
 def assert_positions(name, **kwargs):
     x, y, z, nearest = capture[name]
     assert x.shape == kwargs["shape"]
     assert y.shape == kwargs["shape"]
     assert z.shape == kwargs["shape"]
     assert pytest.fuzzy_equal(x, kwargs["x"])
     assert pytest.fuzzy_equal(y, kwargs["y"])
     assert pytest.fuzzy_equal(z, kwargs["z"])
     assert np.all(nearest == kwargs["nearest"])
Exemplo n.º 4
0
def test_builder():
    """Builder pattern methods"""
    lattice = pb.Lattice([1, 0], [0, 1])

    copy = lattice.with_offset([0, 0.5])
    assert pytest.fuzzy_equal(copy.offset, [0, 0.5, 0])
    assert pytest.fuzzy_equal(lattice.offset, [0, 0, 0])

    copy = lattice.with_min_neighbors(5)
    assert copy.min_neighbors == 5
    assert lattice.min_neighbors == 1
Exemplo n.º 5
0
    def assert_onsite(name, **expected):
        energy, x, y, z = capture[name]
        assert energy.shape == expected["shape"]

        expected_energy = np.array(expected["energy"])
        for index in np.ndindex(*expected_energy.shape):
            expected_slice = np.full(energy.shape[-1], expected_energy[index])
            assert pytest.fuzzy_equal(energy[index], expected_slice)

        assert pytest.fuzzy_equal(x, expected["x"])
        assert pytest.fuzzy_equal(y, expected["y"])
        assert pytest.fuzzy_equal(z, expected["z"])
Exemplo n.º 6
0
def test_ldos(kpm, baseline, plot_if_fails):
    energy = np.linspace(0, 2, 25)
    results = [k.calc_ldos(energy, broadening=0.15, position=(0, 0)) for k in kpm]

    expected = pb.results.LDOS(energy, baseline(results[0].ldos.astype(np.float32)))
    for i in range(len(results)):
        plot_if_fails(results[i], expected, 'plot', label=i)

    assert pytest.fuzzy_equal(results[0], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[1], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[2], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[3], expected, rtol=1e-4, atol=1e-6)
Exemplo n.º 7
0
def test_site_position():
    @pb.site_position_modifier
    def mod(x, y, z):
        return x + 1, y + 1, z + 1

    assert (one, ) * 3 == mod(zero, zero, zero)
    assert (one, ) * 3 == mod.apply(zero, zero, zero, one)

    capture = {}

    @pb.site_position_modifier
    def check_args(x, y, z, sub_id, sites):
        capture[sub_id] = [v.copy() for v in (x, y, z)]
        capture[sub_id].append(sites.argsort_nearest([0, graphene.a_cc / 2]))
        return x, y, z

    def assert_positions(name, **kwargs):
        x, y, z, nearest = capture[name]
        assert x.shape == kwargs["shape"]
        assert y.shape == kwargs["shape"]
        assert z.shape == kwargs["shape"]
        assert pytest.fuzzy_equal(x, kwargs["x"])
        assert pytest.fuzzy_equal(y, kwargs["y"])
        assert pytest.fuzzy_equal(z, kwargs["z"])
        assert np.all(nearest == kwargs["nearest"])

    model = build_model(check_args, pb.primitive(1, 2))
    assert model.hamiltonian.dtype == np.float32

    assert_positions("A",
                     shape=(2, ),
                     nearest=[1, 0],
                     x=[-graphene.a / 2, 0],
                     y=[-2 * graphene.a_cc, -graphene.a_cc / 2],
                     z=[0, 0])
    assert_positions("B",
                     shape=(2, ),
                     nearest=[1, 0],
                     x=[-graphene.a / 2, 0],
                     y=[-graphene.a_cc, graphene.a_cc / 2],
                     z=[0, 0])

    @pb.site_position_modifier
    def shift(x, y, z):
        return x + 1, y + 1, z + 1

    model = build_model(check_args, shift)
    assert pytest.fuzzy_equal(model.system.x, [1, 1])
    assert pytest.fuzzy_equal(model.system.y,
                              [1 - graphene.a_cc / 2, 1 + graphene.a_cc / 2])
    assert pytest.fuzzy_equal(model.system.z, [1, 1])
Exemplo n.º 8
0
def test_lapack(baseline, plot_if_fails):
    model = pb.Model(graphene.monolayer(), pb.translational_symmetry())
    solver = pb.solver.lapack(model)
    assert pytest.fuzzy_equal(solver.eigenvalues, [-3*abs(graphene.t), 3*abs(graphene.t)])

    from math import pi, sqrt
    g = [0, 0]
    k1 = [-4*pi / (3*sqrt(3) * graphene.a_cc), 0]
    m = [0, 2*pi / (3 * graphene.a_cc)]
    k2 = [2*pi / (3*sqrt(3) * graphene.a_cc), 2*pi / (3 * graphene.a_cc)]

    bands = solver.calc_bands(k1, g, m, k2, step=3)
    expected = baseline(bands)
    plot_if_fails(bands, expected, 'plot')
    assert pytest.fuzzy_equal(bands, expected, 2.e-2, 1.e-6)
Exemplo n.º 9
0
def test_ldos(kpm, baseline, plot_if_fails):
    energy = np.linspace(0, 2, 25)
    results = [
        k.calc_ldos(energy, broadening=0.15, position=(0, 0)) for k in kpm
    ]

    expected = pb.results.LDOS(energy,
                               baseline(results[0].ldos.astype(np.float32)))
    for i in range(len(results)):
        plot_if_fails(results[i], expected, 'plot', label=i)

    assert pytest.fuzzy_equal(results[0], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[1], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[2], expected, rtol=1e-4, atol=1e-6)
    assert pytest.fuzzy_equal(results[3], expected, rtol=1e-4, atol=1e-6)
Exemplo n.º 10
0
def test_structure_map(model):
    system = model.system
    zeros = np.zeros_like(system.x)

    spatial_map = pb.results.SpatialMap(zeros, system.positions, system.sublattices)
    structure_map = system.with_data(zeros)

    assert pytest.fuzzy_equal(spatial_map.data, structure_map.spatial_map.data)
    assert pytest.fuzzy_equal(spatial_map.positions, structure_map.spatial_map.positions)
    assert pytest.fuzzy_equal(spatial_map.sublattices, structure_map.spatial_map.sublattices)

    tmp = structure_map[structure_map.x < 0.05]
    assert structure_map.hoppings.nnz == 41
    assert tmp.hoppings.nnz == 21
    assert tmp.hoppings.tocsr().data.mapping == model.lattice.impl.hop_name_map
Exemplo n.º 11
0
def test_site_generator():
    """Generated some disordered sites"""
    @pb.site_generator("New", energy=0.4)
    def site_gen():
        x = [10, 20, 30]
        y = [1, 2, 3]
        z = [0, -1, -2]
        return x, y, z

    model = pb.Model(graphene.monolayer(), graphene.hexagon_ac(1), site_gen)
    s = model.system[model.system.x >= 10]
    assert s.num_sites == 3
    assert pytest.fuzzy_equal(s.x, [10, 20, 30])
    assert pytest.fuzzy_equal(s.y, [1, 2, 3])
    assert pytest.fuzzy_equal(s.z, [0, -1, -2])
Exemplo n.º 12
0
def test_expected(lattice, baseline, plot_if_fails):
    expected = baseline(lattice)
    plot_if_fails(lattice, expected, 'plot')

    assert lattice.sub_name_map == expected.sub_name_map
    assert lattice.hop_name_map == expected.hop_name_map
    assert pytest.fuzzy_equal(lattice, expected)
Exemplo n.º 13
0
def test_dos(params, baseline, plot_if_fails):
    configurations = [
        {
            'matrix_format': "ELL",
            'optimal_size': False,
            'interleaved': False
        },
        {
            'matrix_format': "ELL",
            'optimal_size': True,
            'interleaved': True
        },
    ]
    model = pb.Model(*params)

    kernel = pb.lorentz_kernel()
    strategies = [
        pb.kpm(model, kernel=kernel, silent=True, **c) for c in configurations
    ]

    energy = np.linspace(0, 2, 25)
    results = [kpm.calc_dos(energy, broadening=0.15) for kpm in strategies]

    expected = results[0].with_data(
        baseline(results[0].data.astype(np.float32)))
    for i in range(len(results)):
        plot_if_fails(results[i], expected, 'plot', label=i)

    for result in results:
        assert pytest.fuzzy_equal(result, expected, rtol=1e-3, atol=1e-6)
Exemplo n.º 14
0
def test_brillouin_zone():
    from math import pi, sqrt

    lat = pb.Lattice(a1=1)
    assert pytest.fuzzy_equal(lat.brillouin_zone(), [-pi, pi])

    lat = pb.Lattice(a1=[0, 1], a2=[0.5, 0.5])
    assert pytest.fuzzy_equal(
        lat.brillouin_zone(),
        [[0, -2 * pi], [2 * pi, 0], [0, 2 * pi], [-2 * pi, 0]])

    # Identical lattices represented using acute and obtuse angles between primitive vectors
    acute = pb.Lattice(a1=[1, 0], a2=[1 / 2, 1 / 2 * sqrt(3)])
    obtuse = pb.Lattice(a1=[1 / 2, 1 / 2 * sqrt(3)],
                        a2=[1 / 2, -1 / 2 * sqrt(3)])
    assert pytest.fuzzy_equal(acute.brillouin_zone(), obtuse.brillouin_zone())
Exemplo n.º 15
0
def test_hopping_generator():
    """Generated next-nearest hoppings should produce the same result as the builtin lattice"""
    from scipy.spatial import cKDTree

    @pb.hopping_generator("tnn_test", energy=graphene.t_nn)
    def next_nearest(x, y, z):
        pos = np.stack([x, y, z], axis=1)
        dmin = graphene.a * 0.95
        dmax = graphene.a * 1.05
        kdtree = cKDTree(pos)
        coo = kdtree.sparse_distance_matrix(kdtree, dmax).tocoo()
        idx = coo.data > dmin
        return coo.row[idx], coo.col[idx]

    @pb.onsite_energy_modifier
    def onsite_offset(energy):
        return energy + 3 * graphene.t_nn

    model = pb.Model(graphene.monolayer(), next_nearest, onsite_offset,
                     graphene.hexagon_ac(1))
    expected = pb.Model(graphene.monolayer(2), graphene.hexagon_ac(1))
    assert pytest.fuzzy_equal(model.hamiltonian, expected.hamiltonian)

    @pb.hopping_generator("t_new", energy=1.0)
    def bad_generator():
        """Different array lengths"""
        return [0, 1, 2], [0, 1]

    model = pb.Model(graphene.monolayer(), pb.primitive(3, 3), bad_generator)
    with pytest.raises(RuntimeError) as excinfo:
        model.eval()
    assert "the number of `from` and `to` indices must be equal" in str(
        excinfo.value)
Exemplo n.º 16
0
def test_ldos_sublattice():
    """LDOS for A and B sublattices should be antisymmetric for graphene with a mass term"""
    model = pb.Model(graphene.monolayer(), graphene.hexagon_ac(10), graphene.mass_term(1))
    kpm = pb.greens.kpm(model)

    a, b = (kpm.calc_ldos(np.linspace(-5, 5, 50), 0.1, [0, 0], sub) for sub in ('A', 'B'))
    assert pytest.fuzzy_equal(a.ldos, b.ldos[::-1], rtol=1e-3, atol=1e-6)
Exemplo n.º 17
0
def test_ldos_sublattice():
    """LDOS for A and B sublattices should be antisymmetric for graphene with a mass term"""
    model = pb.Model(graphene.monolayer(), graphene.hexagon_ac(10), graphene.mass_term(1))
    kpm = pb.chebyshev.kpm(model)

    a, b = (kpm.calc_ldos(np.linspace(-5, 5, 50), 0.1, [0, 0], sub) for sub in ('A', 'B'))
    assert pytest.fuzzy_equal(a.ldos, b.ldos[::-1], rtol=1e-3, atol=1e-6)
Exemplo n.º 18
0
def test_expected(lattice, baseline, plot_if_fails):
    expected = baseline(lattice)
    plot_if_fails(lattice, expected, 'plot')

    assert lattice.sub_name_map == expected.sub_name_map
    assert lattice.hop_name_map == expected.hop_name_map
    assert pytest.fuzzy_equal(lattice, expected)
Exemplo n.º 19
0
def test_pickle_round_trip(lattice, tmpdir):
    file_name = str(tmpdir.join('file.npz'))
    pb.save(lattice, file_name)
    from_file = pb.load(file_name)

    assert lattice.sub_name_map == from_file.sub_name_map
    assert lattice.hop_name_map == from_file.hop_name_map
    assert pytest.fuzzy_equal(lattice, from_file)
Exemplo n.º 20
0
def test_dos(solver, baseline, plot_if_fails):
    energy = np.linspace(0, 0.075, 15)
    result = solver.calc_dos(energy, 0.01)

    expected = pb.results.DOS(energy, baseline(result.dos))
    plot_if_fails(result, expected, 'plot')

    assert pytest.fuzzy_equal(result, expected, rtol=2e-2, atol=1e-5)
Exemplo n.º 21
0
def test_pickle_round_trip(lattice, tmpdir):
    file_name = str(tmpdir.join('file.npz'))
    pb.save(lattice, file_name)
    from_file = pb.load(file_name)

    assert lattice.sub_name_map == from_file.sub_name_map
    assert lattice.hop_name_map == from_file.hop_name_map
    assert pytest.fuzzy_equal(lattice, from_file)
Exemplo n.º 22
0
def test_add_multiorbital_sublattice():
    lat = pb.Lattice([1, 0], [0, 1])
    lat.add_one_sublattice("A", [0, 0])
    assert lat.nsub == 1

    lat.add_one_sublattice("B", [0, 0], [1, 2, 3])
    assert pytest.fuzzy_equal(lat.sublattices["B"].energy,
                              [[1, 0, 0], [0, 2, 0], [0, 0, 3]])

    lat.add_one_sublattice("C", [0, 0], [[1, 2, 3], [0, 4, 5], [0, 0, 6]])
    assert pytest.fuzzy_equal(lat.sublattices["C"].energy,
                              [[1, 2, 3], [2, 4, 5], [3, 5, 6]])

    lat.add_one_sublattice("D", [0, 0], [[1, 2j, 3], [0, 4, 5j], [0, 0, 6]])
    assert pytest.fuzzy_equal(lat.sublattices["D"].energy,
                              [[1, 2j, 3], [-2j, 4, 5j], [3, -5j, 6]])

    lat.add_one_sublattice("E", [0, 0], [[1, 2, 3], [2, 4, 5], [3, 5, 6]])
    assert pytest.fuzzy_equal(lat.sublattices["E"].energy,
                              [[1, 2, 3], [2, 4, 5], [3, 5, 6]])
    assert lat.nsub == 5

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("zero-dimensional", [0, 0], [])
    assert "can't be zero-dimensional" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("complex onsite energy", [0, 0], [1j, 2j, 3j])
    assert "must be a real vector or a square matrix" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("not square", [0, 0], [[1, 2, 3], [4, 5, 6]])
    assert "must be a real vector or a square matrix" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("not square", [0, 0],
                               [[1j, 2, 3], [2, 4j, 5], [3, 5, 6j]])
    assert "The main diagonal of the onsite hopping term must be real" in str(
        excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("not Hermitian", [0, 0],
                               [[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    assert "The onsite hopping matrix must be upper triangular or Hermitian" in str(
        excinfo.value)
Exemplo n.º 23
0
def test_expected(model, baseline):
    model.attach_lead(1, [0, -1], [0, 1])
    model.attach_lead(-1, [0, -1], [0, 1])
    model.attach_lead(2, [-1, -5], [1, -5])
    model.attach_lead(-2, [-1, 5], [1, 5])

    ports = model.system.ports
    expected = baseline(ports)
    assert pytest.fuzzy_equal(ports, expected, 1.e-4, 1.e-6)
Exemplo n.º 24
0
def test_expected(model, baseline):
    model.attach_lead(1, [0, -1], [0, 1])
    model.attach_lead(-1, [0, -1], [0, 1])
    model.attach_lead(2, [-1, -5], [1, -5])
    model.attach_lead(-2, [-1, 5], [1, 5])

    ports = model.system.ports
    expected = baseline(ports)
    assert pytest.fuzzy_equal(ports, expected, 1.e-4, 1.e-6)
Exemplo n.º 25
0
    def test_kwant():
        """Create the same model using kwant and pybinding and solve with kwant.smatrix"""
        energy = 1
        vs = np.linspace(-2, 0, 5)

        system = make_wire_with_flat_potential()
        kwant_result = np.array([calc_transmission(system, energy, v) for v in vs])
        pb_result = np.array([calc_transmission(pb_model(v).tokwant(), energy) for v in vs])

        assert pytest.fuzzy_equal(pb_result, kwant_result)
Exemplo n.º 26
0
def test_freeform(baseline, plot_if_fails):
    def donut(inner_radius, outer_radius):
        def contains(x, y, _):
            r = np.sqrt(x**2 + y**2)
            return np.logical_and(inner_radius < r, r < outer_radius)

        return pb.FreeformShape(contains,
                                width=[2 * outer_radius, 2 * outer_radius])

    assert pytest.fuzzy_equal(
        donut(0.5, 1).vertices,
        [[-1, -1, 0], [1, -1, 0], [-1, 1, 0], [1, 1, 0]] * 2)

    shape = donut(0.6, 1.1)
    model = pb.Model(graphene.monolayer(), shape)
    expected = baseline(model.system)
    plot_if_fails(model.system, expected, 'plot')
    plot_if_fails(shape, shape, 'plot')
    assert pytest.fuzzy_equal(model.system, expected, 1.e-4, 1.e-6)
Exemplo n.º 27
0
def test_hamiltonian(model):
    """Must be in the correct format and point to memory allocated in C++ (no copies)"""
    h = model.hamiltonian
    assert isinstance(h, csr_matrix)
    assert h.dtype == np.float32
    assert h.shape == (2, 2)
    assert pytest.fuzzy_equal(h.data, [graphene.t] * 2)
    assert pytest.fuzzy_equal(h.indices, [1, 0])
    assert pytest.fuzzy_equal(h.indptr, [0, 1, 2])

    assert h.data.flags['OWNDATA'] is False
    assert h.data.flags['WRITEABLE'] is False

    with pytest.raises(ValueError) as excinfo:
        h.data += 1
    assert "read-only" in str(excinfo.value)

    h2 = model.hamiltonian
    assert h2.data is not h.data
    assert point_to_same_memory(h2.data, h.data)
Exemplo n.º 28
0
def test_kpm_reuse():
    """KPM should return the same result when a single object is used for multiple calculations"""
    model = pb.Model(graphene.monolayer(), graphene.hexagon_ac(10))
    kpm = pb.chebyshev.kpm(model)
    energy = np.linspace(-5, 5, 50)
    broadening = 0.1

    for position in [0, 0], [6, 0]:
        actual = kpm.calc_ldos(energy, broadening, position)
        expected = pb.chebyshev.kpm(model).calc_ldos(energy, broadening, position)
        assert pytest.fuzzy_equal(actual, expected, rtol=1e-3, atol=1e-6)
Exemplo n.º 29
0
def test_kpm_reuse():
    """KPM should return the same result when a single object is used for multiple calculations"""
    model = pb.Model(graphene.monolayer(), graphene.hexagon_ac(10))
    kpm = pb.greens.kpm(model)
    energy = np.linspace(-5, 5, 50)
    broadening = 0.1

    for position in [0, 0], [6, 0]:
        actual = kpm.calc_ldos(energy, broadening, position)
        expected = pb.greens.kpm(model).calc_ldos(energy, broadening, position)
        assert pytest.fuzzy_equal(actual, expected, rtol=1e-3, atol=1e-6)
Exemplo n.º 30
0
def test_freeform(baseline, plot_if_fails):
    def donut(inner_radius, outer_radius):
        def contains(x, y, _):
            r = np.sqrt(x**2 + y**2)
            return np.logical_and(inner_radius < r, r < outer_radius)

        return pb.FreeformShape(contains, width=[2 * outer_radius, 2 * outer_radius])

    assert pytest.fuzzy_equal(
        donut(0.5, 1).vertices,
        [[ 1, 1, 0], [ 1, 1, 0], [ 1, -1, 0], [ 1, -1, 0],
         [-1, 1, 0], [-1, 1, 0], [-1, -1, 0], [-1, -1, 0]]
    )

    shape = donut(0.6, 1.1)
    model = pb.Model(graphene.monolayer(), shape)
    expected = baseline(model.system)
    plot_if_fails(model.system, expected, 'plot')
    plot_if_fails(shape, shape, 'plot')
    assert pytest.fuzzy_equal(model.system, expected, 1.e-4, 1.e-6)
Exemplo n.º 31
0
def test_hamiltonian(model):
    """Must be in the correct format and point to memory allocated in C++ (no copies)"""
    h = model.hamiltonian
    assert isinstance(h, csr_matrix)
    assert h.dtype == np.float32
    assert h.shape == (2, 2)
    assert pytest.fuzzy_equal(h.data, [graphene.t] * 2)
    assert pytest.fuzzy_equal(h.indices, [1, 0])
    assert pytest.fuzzy_equal(h.indptr, [0, 1, 2])

    assert h.data.flags['OWNDATA'] is False
    assert h.data.flags['WRITEABLE'] is False

    with pytest.raises(ValueError) as excinfo:
        h.data += 1
    assert "read-only" in str(excinfo.value)

    h2 = model.hamiltonian
    assert h2.data is not h.data
    assert point_to_same_memory(h2.data, h.data)
Exemplo n.º 32
0
def test_spatial_ldos(solver, baseline, plot_if_fails):
    ldos_map = solver.calc_spatial_ldos(energy=0.05, broadening=0.01)

    x_max = solver.system.x.max()
    y_max = solver.system.y.max()
    ldos_map = ldos_map.cropped(x=(x_max - 1, x_max + 1), y=(y_max - 1, y_max + 1))

    expected = ldos_map.with_data(baseline(ldos_map.data))
    plot_if_fails(ldos_map, expected, "plot")

    assert pytest.fuzzy_equal(ldos_map, expected, rtol=1e-2, atol=1e-5)
Exemplo n.º 33
0
def test_ldos(solver, plot_if_fails):
    """Compare an LDOS sum at every position with directly calculated DOS"""
    energy = np.linspace(0, 0.075, 15)
    broadening = 0.01
    expected = solver.calc_dos(energy, broadening)

    ldos = np.stack([solver.calc_ldos(energy, broadening, position).ldos
                     for position in zip(*solver.system.positions)])
    result = pb.results.DOS(energy, np.sum(ldos, axis=0))

    plot_if_fails(result, expected, 'plot')
    assert pytest.fuzzy_equal(result, expected)
Exemplo n.º 34
0
    def test_kwant():
        """Create the same model using kwant and pybinding and solve with kwant.smatrix"""
        energy = 1
        vs = np.linspace(-2, 0, 5)

        system = make_wire_with_flat_potential()
        kwant_result = np.array(
            [calc_transmission(system, energy, v) for v in vs])
        pb_result = np.array(
            [calc_transmission(pb_model(v).tokwant(), energy) for v in vs])

        assert pytest.fuzzy_equal(pb_result, kwant_result)
Exemplo n.º 35
0
def test_add_sublattice(capsys):
    lat = pb.Lattice(1)
    assert lat.nsub == 0

    lat.add_one_sublattice("A", 0.0)
    assert lat.nsub == 1

    lat.add_sublattices(("B", 0.1), ("C", 0.2))
    assert lat.nsub == 3

    subs = lat.sublattices
    assert len(subs) == 3
    assert all(v in subs for v in ("A", "B", "C"))

    assert pytest.fuzzy_equal(subs["A"].position, [0, 0, 0])
    assert subs["A"].energy == 0
    assert subs["A"].unique_id == 0
    assert subs["A"].alias_id == 0

    assert pytest.fuzzy_equal(subs["B"].position, [0.1, 0, 0])
    assert subs["B"].energy == 0
    assert subs["B"].unique_id == 1
    assert subs["B"].alias_id == 1

    assert pytest.fuzzy_equal(subs["C"].position, [0.2, 0, 0])
    assert subs["C"].energy == 0
    assert subs["C"].unique_id == 2
    assert subs["C"].alias_id == 2

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("", 0)
    assert "Sublattice name can't be blank" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("A", 0)
    assert "Sublattice 'A' already exists" in str(excinfo.value)

    with pytest.warns(LoudDeprecationWarning):
        assert lat["A"] == "A"
    capsys.readouterr()
Exemplo n.º 36
0
def test_structure_map(model):
    system = model.system
    zeros = np.zeros_like(system.x)

    spatial_map = pb.results.SpatialMap.from_system(zeros, system)
    structure_map = pb.results.StructureMap.from_system(zeros, system)

    assert pytest.fuzzy_equal(spatial_map, structure_map.spatial_map)

    tmp = structure_map[structure_map.x < 0.05]
    assert structure_map.hoppings.nnz == 41
    assert tmp.hoppings.nnz == 21
    assert tmp.hoppings.data.mapping == model.lattice.impl.hop_name_map
Exemplo n.º 37
0
def test_structure_map(model):
    system = model.system
    zeros = np.zeros_like(system.positions.x)

    spatial_map = pb.results.SpatialMap.from_system(zeros, system)
    structure_map = pb.results.StructureMap.from_system(zeros, system)

    assert pytest.fuzzy_equal(spatial_map, structure_map.spatial_map)

    tmp = structure_map.copy()
    tmp.filter(tmp.pos.x < 0.05)
    assert structure_map.hoppings.nnz == 41
    assert tmp.hoppings.nnz == 21
Exemplo n.º 38
0
def test_add_sublattice():
    lat = pb.Lattice(1)
    assert lat.nsub == 0

    lat.add_one_sublattice("A", 0.0)
    assert lat.nsub == 1

    lat.add_sublattices(("B", 0.1), ("C", 0.2))
    assert lat.nsub == 3

    subs = lat.sublattices
    assert len(subs) == 3
    assert all(v in subs for v in ("A", "B", "C"))

    assert pytest.fuzzy_equal(subs["A"].position, [0, 0, 0])
    assert subs["A"].energy == 0
    assert subs["A"].unique_id == 0
    assert subs["A"].alias_id == 0

    assert pytest.fuzzy_equal(subs["B"].position, [0.1, 0, 0])
    assert subs["B"].energy == 0
    assert subs["B"].unique_id == 1
    assert subs["B"].alias_id == 1

    assert pytest.fuzzy_equal(subs["C"].position, [0.2, 0, 0])
    assert subs["C"].energy == 0
    assert subs["C"].unique_id == 2
    assert subs["C"].alias_id == 2

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("", 0)
    assert "Sublattice name can't be blank" in str(excinfo.value)

    with pytest.raises(RuntimeError) as excinfo:
        lat.add_one_sublattice("A", 0)
    assert "Sublattice 'A' already exists" in str(excinfo.value)

    pytest.deprecated_call(lat.__getitem__, "A")
Exemplo n.º 39
0
    def assert_positions(name, **expected):
        _, x1, y1, z1, x2, y2, z2 = capture[name]

        assert pytest.fuzzy_equal(x1.squeeze(), expected["x1"])
        assert pytest.fuzzy_equal(y1.squeeze(), expected["y1"])
        assert pytest.fuzzy_equal(z1.squeeze(), expected["z1"])
        assert pytest.fuzzy_equal(x2.squeeze(), expected["x2"])
        assert pytest.fuzzy_equal(y2.squeeze(), expected["y2"])
        assert pytest.fuzzy_equal(z1.squeeze(), expected["z2"])
Exemplo n.º 40
0
def test_kpm_multiple_indices(model):
    """KPM can take a vector of column indices and return the Green's function for all of them"""
    kpm = pb.greens.kpm(model)

    num_sites = model.system.num_sites
    i, j = num_sites // 2, num_sites // 4
    energy = np.linspace(-0.3, 0.3, 10)
    broadening = 0.8

    cols = [j, j + 1, j + 2]
    gs = kpm(i, cols, energy, broadening)
    assert len(gs) == len(cols)

    g = kpm(j, i, energy, broadening)
    assert pytest.fuzzy_equal(gs[0], g)
Exemplo n.º 41
0
def test_wrapper_return():
    """Make sure the boost python wrapper return type conversion is working"""
    @pb.hopping_energy_modifier
    def mul(energy):
        """Returning a non-contiguous view will force the wrapper to create a copy"""
        energy = np.concatenate([energy, energy])
        energy *= 3
        return energy[::2]

    lattice = pb.Lattice([1, 0])
    lattice.add_sublattices(("A", [0, 0]), ("B", [0, 0]))
    lattice.add_one_hopping([0], "A", "B", 1.0)

    model = pb.Model(lattice, mul, pb.primitive(2))
    assert pytest.fuzzy_equal(model.hamiltonian.data, [3, 3, 3, 3])
Exemplo n.º 42
0
def test_make_lattice():
    a, t = 1, 1

    lat1 = pb.Lattice([a, 0], [0, a])
    lat1.add_one_sublattice('s', (0, 0))
    lat1.add_hoppings([(0,  1), 's', 's', t],
                      [(1,  0), 's', 's', t])
    lat1.min_neighbors = 2

    lat2 = pb.make_lattice(
        vectors=[[a, 0], [0, a]],
        sublattices=[['s', (0, 0)]],
        hoppings=[[(0, 1), 's', 's', t],
                  [(1, 0), 's', 's', t]],
        min_neighbors=2
    )

    assert pytest.fuzzy_equal(lat1, lat2)
Exemplo n.º 43
0
def test_ndsweep(baseline):
    @pb.parallelize(v1=np.linspace(0, 0.1, 5), v2=np.linspace(-0.2, 0.2, 4))
    def factory(v1, v2, energy=np.linspace(0, 0.1, 10)):
        model = pb.Model(
            graphene.monolayer(),
            graphene.hexagon_ac(side_width=15),
            pb.constant_potential(v1),
            pb.constant_potential(v2)
        )

        kpm = pb.greens.kpm(model)
        return kpm.deferred_ldos(energy, broadening=0.15, position=[0, 0])

    silence_parallel_output(factory)
    result = pb.parallel.ndsweep(factory)

    expected = baseline(result)
    assert pytest.fuzzy_equal(result, expected, rtol=1e-4, atol=1e-6)
Exemplo n.º 44
0
def test_sweep(baseline, plot_if_fails):
    @pb.parallelize(v=np.linspace(0, 0.1, 10))
    def factory(v, energy=np.linspace(0, 0.1, 10)):
        model = pb.Model(
            graphene.monolayer(),
            graphene.hexagon_ac(side_width=15),
            pb.constant_potential(v)
        )

        kpm = pb.greens.kpm(model)
        return kpm.deferred_ldos(energy, broadening=0.15, position=[0, 0])

    silence_parallel_output(factory)
    labels = dict(title="test sweep", x="V (eV)", y="E (eV)", data="LDOS")
    result = pb.parallel.sweep(factory, labels=labels)

    expected = baseline(result)
    plot_if_fails(result, expected, 'plot')
    assert pytest.fuzzy_equal(result, expected, rtol=1e-4, atol=1e-6)
Exemplo n.º 45
0
def test_hopping_generator():
    """Generated next-nearest hoppings should produce the same result as the builtin lattice"""
    from scipy.spatial import cKDTree

    @pb.hopping_generator("tnn_test", energy=graphene.t_nn)
    def next_nearest(x, y, z):
        pos = np.stack([x, y, z], axis=1)
        dmin = graphene.a * 0.95
        dmax = graphene.a * 1.05
        kdtree = cKDTree(pos)
        coo = kdtree.sparse_distance_matrix(kdtree, dmax).tocoo()
        idx = coo.data > dmin
        return coo.row[idx], coo.col[idx]

    @pb.onsite_energy_modifier
    def onsite_offset(energy):
        return energy + 3 * graphene.t_nn

    model = pb.Model(graphene.monolayer(), next_nearest, onsite_offset, graphene.hexagon_ac(1))
    expected = pb.Model(graphene.monolayer(2), graphene.hexagon_ac(1))
    assert pytest.fuzzy_equal(model.hamiltonian, expected.hamiltonian)
Exemplo n.º 46
0
def test_expected(model, baseline, plot_if_fails):
    system = model.system
    expected = baseline(system)
    plot_if_fails(system, expected, 'plot')
    assert pytest.fuzzy_equal(system, expected, 1.e-4, 1.e-6)
Exemplo n.º 47
0
def test_pickle_round_trip(model, tmpdir):
    file_name = str(tmpdir.join('file.npz'))
    pb.save(model.system, file_name)
    from_file = pb.load(file_name)

    assert pytest.fuzzy_equal(model.system, from_file)
Exemplo n.º 48
0
def test_polygon(polygon, baseline, plot_if_fails):
    model = pb.Model(graphene.monolayer(), polygon)
    expected = baseline(model.system)
    plot_if_fails(model.system, expected, 'plot')
    plot_if_fails(polygon, polygon, 'plot')
    assert pytest.fuzzy_equal(model.system, expected, 1.e-4, 1.e-6)