Exemple #1
0
def test_1_graphene_all_ArgumentParser(sisl_files, sisl_tmp):
    pytest.importorskip("matplotlib", reason="matplotlib not available")

    # Local routine to run the collected actions
    def run(ns):
        ns._actions_run = True
        # Run all so-far collected actions
        for A, Aargs, Akwargs in ns._actions:
            A(*Aargs, **Akwargs)
        ns._actions_run = False
        ns._actions = []

    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))

    p, ns = tbt.ArgumentParser()
    p.parse_args([], namespace=ns)

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--energy', ' -1.995:1.995'], namespace=ns)
    assert not out._actions_run
    run(out)

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--kpoint', '1'], namespace=ns)
    assert out._krng
    run(out)
    assert out._krng == 1

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--norm', 'orbital'], namespace=ns)
    run(out)
    assert out._norm == 'orbital'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--norm', 'atom'], namespace=ns)
    run(out)
    assert out._norm == 'atom'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--kpoint', '1', '--norm', 'orbital'], namespace=ns)
    run(out)
    assert out._krng == 1
    assert out._norm == 'orbital'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--atom', '10:11,14'], namespace=ns)
    run(out)
    assert out._Ovalue == '10:11,14'
    # Only atom 14 is in the device region
    assert np.all(out._Orng + 1 == [14])

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--atom', '10:11,12,14:20'], namespace=ns)
    run(out)
    assert out._Ovalue == '10:11,12,14:20'
    # Only 13-48 is in the device
    assert np.all(out._Orng + 1 == [14, 15, 16, 17, 18, 19, 20])

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--transmission', 'Left', 'Right'], namespace=ns)
    run(out)
    assert len(out._data) == 2
    assert out._data_header[0][0] == 'E'
    assert out._data_header[1][0] == 'T'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(
        ['--transmission', 'Left', 'Right', '--transmission-bulk', 'Left'],
        namespace=ns)
    run(out)
    assert len(out._data) == 3
    assert out._data_header[0][0] == 'E'
    assert out._data_header[1][0] == 'T'
    assert out._data_header[2][:2] == 'BT'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--dos', '--dos', 'Left', '--ados', 'Right'],
                       namespace=ns)
    run(out)
    assert len(out._data) == 4
    assert out._data_header[0][0] == 'E'
    assert out._data_header[1][0] == 'D'
    assert out._data_header[2][:2] == 'AD'
    assert out._data_header[3][:2] == 'AD'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--bulk-dos', 'Left', '--ados', 'Right'], namespace=ns)
    run(out)
    assert len(out._data) == 3
    assert out._data_header[0][0] == 'E'
    assert out._data_header[1][:2] == 'BD'
    assert out._data_header[2][:2] == 'AD'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--transmission-eig', 'Left', 'Right'], namespace=ns)
    run(out)
    assert out._data_header[0][0] == 'E'
    for i in range(1, len(out._data)):
        assert out._data_header[i][:4] == 'Teig'

    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--info'], namespace=ns)

    # Test output
    f = sisl_tmp('1_graphene_all.dat', _dir)
    p, ns = tbt.ArgumentParser()
    out = p.parse_args(['--transmission-eig', 'Left', 'Right', '--out', f],
                       namespace=ns)
    assert len(out._data) == 0

    f1 = sisl_tmp('1_graphene_all_1.dat', _dir)
    f2 = sisl_tmp('1_graphene_all_2.dat', _dir)
    p, ns = tbt.ArgumentParser()
    out = p.parse_args([
        '--transmission', 'Left', 'Right', '--out', f1, '--dos', '--atom',
        '12:2:48', '--dos', 'Right', '--ados', 'Left', '--out', f2
    ],
                       namespace=ns)

    d = sisl.io.tableSile(f1).read_data()
    assert len(d) == 2
    d = sisl.io.tableSile(f2).read_data()
    assert len(d) == 4
    assert np.allclose(d[1, :], (d[2, :] + d[3, :]) * 2)
    assert np.allclose(d[2, :], d[3, :])

    f = sisl_tmp('1_graphene_all_T.png', _dir)
    p, ns = tbt.ArgumentParser()
    out = p.parse_args([
        '--transmission', 'Left', 'Right', '--transmission-bulk', 'Left',
        '--plot', f
    ],
                       namespace=ns)
Exemple #2
0
def test_zz_sc_geom(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'zz.gout'))
    sc = si.read_supercell()
    geom = si.read_geometry()
    assert sc == geom.sc
Exemple #3
0
def test_1_graphene_all_content(sisl_files):
    """ This tests manifolds itself as:

    sisl.geom.graphene(orthogonal=True).tile(3, 0).tile(5, 1)

    All output is enabled:

    ### FDF ###
    # Transmission related quantities
    TBT.T.All T
    TBT.T.Out T
    TBT.T.Eig 2

    # Density of states
    TBT.DOS.Elecs T
    TBT.DOS.Gf T
    TBT.DOS.A T
    TBT.DOS.A.All T

    # Orbital currents and Crystal-Orbital investigations.
    TBT.Symmetry.TimeReversal F
    TBT.Current.Orb T
    TBT.COOP.Gf T
    TBT.COOP.A T
    TBT.COHP.Gf T
    TBT.COHP.A T

    TBT.k [100 1 1]
    ### FDF ###
    """
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    assert tbt.E.min() > -2.
    assert tbt.E.max() < 2.
    # We have 400 energy-points
    ne = len(tbt.E)
    assert ne == 400
    assert tbt.ne == ne

    # We have 100 k-points
    nk = len(tbt.kpt)
    assert nk == 100
    assert tbt.nk == nk
    assert tbt.wk.sum() == pytest.approx(1.)

    for i in range(ne):
        assert tbt.Eindex(i) == i
        assert tbt.Eindex(tbt.E[i]) == i

    # Check raises
    with pytest.warns(sisl.SislWarning):
        tbt.Eindex(tbt.E.min() - 1.)
    with pytest.warns(sisl.SislInfo):
        tbt.Eindex(tbt.E.min() - 2e-3)
    with pytest.warns(sisl.SislWarning):
        tbt.kindex([0, 0, 0.5])
    # Can't hit it
    #with pytest.warns(sisl.SislInfo):
    #    tbt.kindex([0.0106, 0, 0])

    for i in range(nk):
        assert tbt.kindex(i) == i
        assert tbt.kindex(tbt.kpt[i]) == i

    # Get geometry
    geom = tbt.geometry
    geom_c1 = tbt.read_geometry(atoms=sisl.Atoms(sisl.Atom[6], geom.na))
    geom_c2 = tbt.read_geometry(
        atoms=sisl.Atoms(sisl.Atom(6, orbs=2), geom.na))
    assert geom_c1 == geom_c2

    # Check read is the same as the direct query
    assert tbt.na == geom.na
    assert tbt.no == geom.no
    assert tbt.no == geom.na
    assert tbt.na == 3 * 5 * 4
    assert np.allclose(tbt.cell, geom.cell)

    # Check device atoms (1-orbital system)
    assert tbt.na_d == tbt.no_d
    assert tbt.na_d == 36  # 3 * 5 * 4 (and device is without electrodes, so 3 * 3 * 4)
    assert len(
        tbt.pivot()
    ) == 3 * 3 * 4  # 3 * 5 * 4 (and device is without electrodes, so 3 * 3 * 4)
    assert len(tbt.pivot(in_device=True)) == len(tbt.pivot())
    assert np.all(tbt.pivot(in_device=True, sort=True) == np.arange(tbt.no_d))
    assert np.all(tbt.pivot(sort=True) == np.sort(tbt.pivot()))

    # Just check they are there
    assert tbt.n_btd() == len(tbt.btd())

    # Check electrodes
    assert len(tbt.elecs) == 2
    elecs = tbt.elecs[:]
    assert elecs == ['Left', 'Right']
    for i, elec in enumerate(elecs):
        assert tbt._elec(i) == elec

    # Check the chemical potentials
    for elec in elecs:
        assert tbt.n_btd(elec) == len(tbt.btd(elec))
        assert tbt.chemical_potential(elec) == pytest.approx(0.)
        assert tbt.electron_temperature(elec) == pytest.approx(300., abs=1)
        assert tbt.eta(elec) == pytest.approx(1e-4, abs=1e-6)

    # Check electrode relevant stuff
    left = elecs[0]
    right = elecs[1]

    # Assert we have transmission symmetry
    assert np.allclose(tbt.transmission(left, right),
                       tbt.transmission(right, left))
    assert np.allclose(tbt.transmission_eig(left, right),
                       tbt.transmission_eig(right, left))
    # Check that the total transmission is larger than the sum of transmission eigenvalues
    assert np.all(
        tbt.transmission(left, right) +
        1e-7 >= tbt.transmission_eig(left, right).sum(-1))
    assert np.all(
        tbt.transmission(right, left) +
        1e-7 >= tbt.transmission_eig(right, left).sum(-1))

    # Check that we can't retrieve from same to same electrode
    with pytest.raises(ValueError):
        tbt.transmission(left, left)
    with pytest.raises(ValueError):
        tbt.transmission_eig(left, left)

    assert np.allclose(tbt.transmission(left, right, kavg=False),
                       tbt.transmission(right, left, kavg=False))

    # Both methods should be identical for simple bulk systems
    assert np.allclose(tbt.reflection(left),
                       tbt.reflection(left, from_single=True),
                       atol=1e-5)

    # Also check for each k
    for ik in range(nk):
        assert np.allclose(tbt.transmission(left, right, ik),
                           tbt.transmission(right, left, ik))
        assert np.allclose(tbt.transmission_eig(left, right, ik),
                           tbt.transmission_eig(right, left, ik))
        assert np.all(
            tbt.transmission(left, right, ik) +
            1e-7 >= tbt.transmission_eig(left, right, ik).sum(-1))
        assert np.all(
            tbt.transmission(right, left, ik) +
            1e-7 >= tbt.transmission_eig(right, left, ik).sum(-1))
        assert np.allclose(tbt.DOS(kavg=ik),
                           tbt.ADOS(left, kavg=ik) + tbt.ADOS(right, kavg=ik))
        assert np.allclose(
            tbt.DOS(E=0.195, kavg=ik),
            tbt.ADOS(left, E=0.195, kavg=ik) +
            tbt.ADOS(right, E=0.195, kavg=ik))

    # Check that norm returns correct values
    assert tbt.norm() == 1
    assert tbt.norm(norm='all') == tbt.no_d
    assert tbt.norm(norm='atom') == tbt.norm(norm='orbital')

    # Check atom is equivalent to orbital
    for norm in ['atom', 'orbital']:
        assert tbt.norm(0, norm=norm) == 0.
        assert tbt.norm(3 * 4, norm=norm) == 1
        assert tbt.norm(range(3 * 4, 3 * 5), norm=norm) == 3

    # Assert sum(ADOS) == DOS
    assert np.allclose(tbt.DOS(), tbt.ADOS(left) + tbt.ADOS(right))
    assert np.allclose(tbt.DOS(sum=False),
                       tbt.ADOS(left, sum=False) + tbt.ADOS(right, sum=False))

    # Now check orbital resolved DOS
    assert np.allclose(tbt.DOS(sum=False),
                       tbt.ADOS(left, sum=False) + tbt.ADOS(right, sum=False))

    # Current must be 0 when the chemical potentials are equal
    assert tbt.current(left, right) == pytest.approx(0.)
    assert tbt.current(right, left) == pytest.approx(0.)

    high_low = tbt.current_parameter(left, 0.5, 0.0025, right, -0.5, 0.0025)
    low_high = tbt.current_parameter(left, -0.5, 0.0025, right, 0.5, 0.0025)
    assert high_low > 0.
    assert low_high < 0.
    assert -high_low == pytest.approx(low_high)
    with pytest.warns(sisl.SislWarning):
        tbt.current_parameter(left, -10., 0.0025, right, 10., 0.0025)

    with warnings.catch_warnings():
        warnings.simplefilter('ignore')

        # Since this is a perfect system there should be *no* QM shot-noise
        # Also, the shot-noise is related to the applied bias, so NO shot-noise
        assert np.allclose((tbt.shot_noise(left, right, kavg=False) *
                            tbt.wkpt.reshape(-1, 1)).sum(0), 0.)
        assert np.allclose(tbt.shot_noise(left, right), 0.)
        assert np.allclose(tbt.shot_noise(right, left), 0.)
        assert np.allclose(tbt.shot_noise(left, right, kavg=1), 0.)

        # Since the data-file does not contain all T-eigs (only the first two)
        # we can't correctly calculate the fano factors
        # This is a pristine system, hence all fano-factors should be more or less zero
        # All transmissions are step-functions, however close to band-edges there is some
        # smearing.
        # When calculating the Fano factor it is extremely important that the zero_T is *sufficient*
        # I don't now which value is *good*
        assert np.all((tbt.fano(left, right, kavg=False) *
                       tbt.wkpt.reshape(-1, 1)).sum(0) <= 1)
        assert np.all(tbt.fano(left, right) <= 1)
        assert np.all(tbt.fano(right, left) <= 1)
        assert np.all(tbt.fano(left, right, kavg=0) <= 1)

        # Neither should the noise_power exist
        assert (tbt.noise_power(right, left, kavg=False) *
                tbt.wkpt).sum() == pytest.approx(0.)
        assert tbt.noise_power(right, left) == pytest.approx(0.)
        assert tbt.noise_power(right, left, kavg=0) == pytest.approx(0.)

    # Check specific DOS queries
    DOS = tbt.DOS
    ADOS = tbt.ADOS

    assert DOS(2, atoms=True, sum=False).size == geom.names['Device'].size
    assert np.allclose(DOS(2, atoms='Device', sum=False),
                       DOS(2, atoms=True, sum=False))
    assert DOS(2, orbitals=True, sum=False).size == geom.a2o('Device',
                                                             all=True).size
    assert ADOS(left, 2, atoms=True,
                sum=False).size == geom.names['Device'].size
    assert ADOS(left, 2, orbitals=True,
                sum=False).size == geom.a2o('Device', all=True).size
    assert np.allclose(ADOS(left, 2, atoms='Device', sum=False),
                       ADOS(left, 2, atoms=True, sum=False))

    atoms = range(8, 40)  # some in device, some not in device
    for o in ['atoms', 'orbitals']:
        opt = {o: atoms}

        for E in [None, 2, 4]:
            assert np.allclose(DOS(E), ADOS(left, E) + ADOS(right, E))
            assert np.allclose(DOS(E, **opt),
                               ADOS(left, E, **opt) + ADOS(right, E, **opt))

        opt['sum'] = False
        for E in [None, 2, 4]:
            assert np.allclose(DOS(E), ADOS(left, E) + ADOS(right, E))
            assert np.allclose(DOS(E, **opt),
                               ADOS(left, E, **opt) + ADOS(right, E, **opt))

        opt['sum'] = True
        opt['norm'] = o[:-1]
        for E in [None, 2, 4]:
            assert np.allclose(DOS(E), ADOS(left, E) + ADOS(right, E))
            assert np.allclose(DOS(E, **opt),
                               ADOS(left, E, **opt) + ADOS(right, E, **opt))

        opt['sum'] = False
        for E in [None, 2, 4]:
            assert np.allclose(DOS(E), ADOS(left, E) + ADOS(right, E))
            assert np.allclose(DOS(E, **opt),
                               ADOS(left, E, **opt) + ADOS(right, E, **opt))

    # Check orbital currents
    E = 201
    # Sum of orbital current should be 0 (in == out)
    orb_left = tbt.orbital_current(left, E)
    orb_right = tbt.orbital_current(right, E)
    assert orb_left.sum() == pytest.approx(0., abs=1e-7)
    assert orb_right.sum() == pytest.approx(0., abs=1e-7)

    d1 = np.arange(12, 24).reshape(-1, 1)
    d2 = np.arange(24, 36).reshape(-1, 1)
    assert orb_left[d1, d2.T].sum() == pytest.approx(
        tbt.transmission(left, right)[E])
    assert orb_left[d1, d2.T].sum() == pytest.approx(-orb_left[d2, d1.T].sum())
    assert orb_right[d2, d1.T].sum() == pytest.approx(
        tbt.transmission(right, left)[E])
    assert orb_right[d2,
                     d1.T].sum() == pytest.approx(-orb_right[d1, d2.T].sum())

    orb_left.sort_indices()
    atom_left = tbt.bond_current(left, E, only='all')
    atom_left.sort_indices()
    assert np.allclose(orb_left.data, atom_left.data)
    assert np.allclose(
        orb_left.data,
        tbt.bond_current_from_orbital(orb_left, only='all').data)
    orb_right.sort_indices()
    atom_right = tbt.bond_current(right, E, only='all')
    atom_right.sort_indices()
    assert np.allclose(orb_right.data, atom_right.data)
    assert np.allclose(
        orb_right.data,
        tbt.bond_current_from_orbital(orb_right, only='all').data)

    # Calculate the atom current
    # For 1-orbital systems the activity and non-activity are equivalent
    assert np.allclose(tbt.atom_current(left, E),
                       tbt.atom_current(left, E, activity=False))
    tbt.vector_current(left, E)
    assert np.allclose(
        tbt.vector_current_from_bond(atom_left) / 2,
        tbt.vector_current(left, E, only='all'))

    # Check COOP curves
    coop = tbt.orbital_COOP(E)
    coop_l = tbt.orbital_ACOOP(left, E)
    coop_r = tbt.orbital_ACOOP(right, E)
    coop_lr = coop_l + coop_r

    # Ensure aligment
    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    coop = tbt.orbital_COOP(E, isc=[0, 0, 0])
    coop_l = tbt.orbital_ACOOP(left, E, isc=[0, 0, 0])
    coop_r = tbt.orbital_ACOOP(right, E, isc=[0, 0, 0])
    coop_lr = coop_l + coop_r

    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    coop = tbt.atom_COOP(E)
    coop_l = tbt.atom_ACOOP(left, E)
    coop_r = tbt.atom_ACOOP(right, E)
    coop_lr = coop_l + coop_r

    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    coop = tbt.atom_COOP(E, isc=[0, 0, 0])
    coop_l = tbt.atom_ACOOP(left, E, isc=[0, 0, 0])
    coop_r = tbt.atom_ACOOP(right, E, isc=[0, 0, 0])
    coop_lr = coop_l + coop_r

    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    # Check COHP curves
    coop = tbt.orbital_COHP(E)
    coop_l = tbt.orbital_ACOHP(left, E)
    coop_r = tbt.orbital_ACOHP(right, E)
    coop_lr = coop_l + coop_r

    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    coop = tbt.atom_COHP(E)
    coop_l = tbt.atom_ACOHP(left, E)
    coop_r = tbt.atom_ACOHP(right, E)
    coop_lr = coop_l + coop_r

    coop.eliminate_zeros()
    coop.sorted_indices()
    coop_lr.eliminate_zeros()
    coop_lr.sorted_indices()
    assert np.allclose(coop.data, coop_lr.data)

    # Simply print out information
    tbt.info()
    for elec in elecs:
        tbt.info(elec)
Exemple #4
0
def test_1_graphene_all_fail_kavg(sisl_files, sisl_tmp):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    with pytest.raises(ValueError):
        tbt.transmission(kavg=[0, 1])
Exemple #5
0
def test_h2o_dipole_hsx_hs_no_geometry(sisl_files, sisl_tmp):
    HSX = sisl.get_sile(sisl_files(_dir, "h2o_dipole.HSX"))
    HS = HSX.read_hamiltonian()
    S = HSX.read_overlap()
Exemple #6
0
        action="append",
        default=None,
        help=
        "Output file to store the resulting Poisson solution. It *has* to have TSV.nc file ending to make the file conforming with TranSiesta."
    )

    # Parse args
    args = p.parse_args()

    if args.out is None:
        print(
            f">\n>\n>{_script}: No out-files has been specified, work will be carried out but not saved!\n>\n>\n"
        )

    # Read in geometry
    geometry = si.get_sile(args.geometry).read_geometry()

    # Figure out the electrodes
    elecs_V = {}
    if len(args.elec_V) == 0:
        print(geometry.names)
        raise ValueError(
            "{}: Please specify the electrode potentials using --elec-V")

    for name, V in args.elec_V:
        elecs_V[name] = float(V)

    if args.dtype == "f":
        dtype = np.float32
    elif args.dtype == "d":
        dtype = np.float64
Exemple #7
0
def NC_init_func(sisl_files, **kwargs):
    H = sisl.get_sile(sisl_files("fe_clust_noncollinear.TSHS")).read_hamiltonian()
    bz = sisl.BandStructure(H, [[0, 0, 0], [0.5, 0, 0]], 3, ["Gamma", "X"])

    return bz.plot.fatbands(**kwargs)
Exemple #8
0
def test_si_pdos_kgrid_hsx_H_no_geometry(sisl_files, sisl_tmp):
    si = sisl.get_sile(sisl_files(_dir, "si_pdos_kgrid.HSX"))
    H0 = si.read_hamiltonian()
    H1 = si.read_hamiltonian(geometry=si_pdos_kgrid_geom())
    assert H0._csr.spsame(H1._csr)
Exemple #9
0
from hubbard import HubbardHamiltonian, sp2, density, plot
import numpy as np
import sisl
"""
For this system we get an open-shell solution for U>3 eV
This test obtaines the closed-shell solution for U=2 eV for both a spin-polarized and unpolarized situation
"""

# Build sisl Geometry object
molecule = sisl.get_sile('mol-ref/mol-ref.XV').read_geometry()
molecule.sc.set_nsc([1, 1, 1])

Hsp2 = sp2(molecule)

H = HubbardHamiltonian(Hsp2, U=2.0)
H.set_polarization([36], [77])
dn = H.converge(density.calc_n_insulator,
                mixer=sisl.mixing.LinearMixer(),
                tol=1e-7)
print('Closed-shell spin-polarized calculation:')
print('dn: {}, Etot: {}\n'.format(dn, H.Etot))

p = plot.Plot()
for i in range(2):
    ev = H.eigh(spin=i) - H.find_midgap()
    ev = ev[abs(ev) < 2]
    p.axes.plot(ev,
                np.zeros_like(ev), ['or', 'xg'][i],
                label=[r'$\sigma=\uparrow$', r'$\sigma=\downarrow$'][i])

# Compute same system with spin degeneracy
Exemple #10
0
from hubbard import HubbardHamiltonian, sp2, plot, density
import sys
import numpy as np
import sisl

# Build sisl Geometry object
mol_file = '3-anthracene'
mol = sisl.get_sile(mol_file+'.XV').read_geometry()
mol.sc.set_nsc([1, 1, 1])
mol = mol.move(-mol.center(what='xyz'))

# 3NN tight-binding model
Hsp2 = sp2(mol, t1=2.7, t2=0.2, t3=.18, dim=2)
H = HubbardHamiltonian(Hsp2)

# Output file to collect the energy difference between
# FM and AFM solutions
f = open('FM-AFM.dat', 'w')

mixer = sisl.mixing.PulayMixer(0.7, history=7)

for u in np.linspace(0.0, 4.0, 5):
    # We approach the solutions from above, starting at U=4eV
    H.U = 4.0-u

    # AFM case first
    success = H.read_density(mol_file+'.nc') # Try reading, if we already have density on file
    if not success:
        H.random_density()
        H.set_polarization([1, 6, 15]) # polarize lower zigzag edge
    mixer.clear()
Exemple #11
0
def test_si_pdos_kgrid_grid_fdf(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'si_pdos_kgrid.fdf'))
    VT = si.read_grid("VT", order='bin')
    TotPot = si.read_grid("totalpotential", order='bin')
    assert np.allclose(VT.grid, TotPot.grid)
Exemple #12
0
def test_si_pdos_kgrid_grid_fractions(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'si_pdos_kgrid.VT'))
    grid = si.read_grid()
    grid_halve = si.read_grid(index=[0.5])
    assert np.allclose(grid.grid * 0.5, grid_halve.grid)
Exemple #13
0
def test_si_pdos_kgrid_grid_cell(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'si_pdos_kgrid.VT'))
    si.read_supercell()
Exemple #14
0
def test_si_pdos_kgrid_grid(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'si_pdos_kgrid.VT'))
    si.read_grid()
    assert si.grid_unit == pytest.approx(sisl.unit.siesta.unit_convert('Ry', 'eV'))
Exemple #15
0
from hubbard import HubbardHamiltonian, density, plot, sp2
import sys
import numpy as np
import sisl

# Build sisl Geometry object
mol = sisl.get_sile('junction-2-2.XV').read_geometry()
mol.sc.set_nsc([1, 1, 1])
# 3NN tight-binding model
Hsp2 = sp2(mol, t1=2.7, t2=0.2, t3=.18)

H = HubbardHamiltonian(Hsp2)

# Output file to collect the energy difference between
# FM and AFM solutions
f = open('FM-AFM.dat', 'w')

mixer = sisl.mixing.PulayMixer(0.7, history=7)
H.set_polarization([77], dn=[23])
for u in np.linspace(0.0, 1.4, 15):
    # We approach the solutions from above, starting at U=4eV
    H.U = 4.4 - u
    # AFM case first
    success = H.read_density(
        'fig_S15.nc')  # Try reading, if we already have density on file

    mixer.clear()
    dn = H.converge(density.calc_n_insulator, mixer=mixer, tol=1e-6)
    eAFM = H.Etot
    H.write_density('fig_S15.nc')
Exemple #16
0
def test_si_pdos_kgrid_hsx_H(sisl_files, sisl_tmp):
    si = sisl.get_sile(sisl_files(_dir, "si_pdos_kgrid.fdf"))
    si.read_hamiltonian(order="HSX")
Exemple #17
0
    def init_func_and_attrs(self, request, siesta_test_files):
        name = request.param

        if name == "siesta_output":
            # From a siesta .bands file
            init_func = sisl.get_sile(siesta_test_files("SrTiO3.bands")).plot
            attrs = {
                "bands_shape": (150, 72),
                "ticklabels": ('Gamma', 'X', 'M', 'Gamma', 'R', 'X'),
                "tickvals":
                [0.0, 0.429132, 0.858265, 1.465149, 2.208428, 2.815313],
                "gap": 1.677,
                "spin_texture": False,
                "spin": sisl.Spin("")
            }
        elif name.startswith("sisl_H"):
            gr = sisl.geom.graphene()
            H = sisl.Hamiltonian(gr)
            H.construct([(0.1, 1.44), (0, -2.7)])

            spin_type = name.split("_")[-1]
            n_spin, H = {
                "unpolarized": (0, H),
                "polarized": (2, H.transform(spin=sisl.Spin.POLARIZED)),
                "noncolinear": (0, H.transform(spin=sisl.Spin.NONCOLINEAR)),
                "spinorbit": (0, H.transform(spin=sisl.Spin.SPINORBIT))
            }.get(spin_type)

            n_states = 2
            if not H.spin.is_diagonal:
                n_states *= 2

            # Let's create the same graphene bands plot using the hamiltonian
            # from two different prespectives
            if name.startswith("sisl_H_path"):
                # Passing a list of points (as if we were interacting from a GUI)
                path = [{
                    "active": True,
                    "x": x,
                    "y": y,
                    "z": z,
                    "divisions": 3,
                    "name": tick
                } for tick, (x, y, z) in zip(
                    ["Gamma", "M", "K"], [[0, 0, 0], [2 / 3, 1 /
                                                      3, 0], [1 / 2, 0, 0]])]

                init_func = partial(H.plot.bands, band_structure=path)
            else:
                # Directly creating a BandStructure object
                bz = sisl.BandStructure(
                    H, [[0, 0, 0], [2 / 3, 1 / 3, 0], [1 / 2, 0, 0]], 6,
                    ["Gamma", "M", "K"])
                init_func = bz.plot

            attrs = {
                "bands_shape": (6, n_spin, n_states) if n_spin != 0 else
                (6, n_states),
                "ticklabels": ["Gamma", "M", "K"],
                "tickvals": [0., 1.70309799, 2.55464699],
                "gap":
                0,
                "spin_texture":
                not H.spin.is_diagonal,
                "spin":
                H.spin
            }

        return init_func, attrs
Exemple #18
0
def test_si_pdos_kgrid_hsx_H_fix_orbitals(sisl_files, sisl_tmp):
    si = sisl.get_sile(sisl_files(_dir, "si_pdos_kgrid.HSX"))
    si.read_hamiltonian(geometry=si_pdos_kgrid_geom(False))
Exemple #19
0
def gen_exchange_siesta(
    fdf_fname,
    magnetic_elements=[],
    kmesh=[4, 4, 4],
    emin=-12.0,
    emax=0.0,
    nz=50,
    #height=0.2,
    #nz1=50,
    #nz2=200,
    #nz3=50,
    exclude_orbs=[],
    Rcut=None,
    ne=None,
    use_cache=False,
    description=''):

    try:
        import sisl
    except:
        raise ImportError(
            "sisl cannot be imported. Please install sisl first.")
    fdf = sisl.get_sile(fdf_fname)
    H = fdf.read_hamiltonian()
    if H.spin.is_colinear and True:
        print("Reading Siesta hamiltonian: colinear spin.")
        tbmodel_up = SislWrapper(H, spin=0)
        tbmodel_dn = SislWrapper(H, spin=1)
        basis = dict(zip(tbmodel_up.orbs, list(range(tbmodel_up.norb))))
        print("Starting to calculate exchange.")
        description = f""" Input from collinear Siesta data.
 working directory: {os.getcwd()}
 fdf_fname: {fdf_fname}.
\n"""
        exchange = ExchangeCL2(
            tbmodels=(tbmodel_up, tbmodel_dn),
            atoms=tbmodel_up.atoms,
            basis=basis,
            efermi=0.0,
            magnetic_elements=magnetic_elements,
            kmesh=kmesh,
            emin=emin,
            emax=emax,
            nz=nz,
            #height=height,
            #nz1=nz1,
            #nz2=nz2,
            #nz3=nz3,
            exclude_orbs=exclude_orbs,
            Rcut=Rcut,
            ne=ne,
            use_cache=use_cache,
            description=description)
        exchange.run()
        print("\n")
        print(
            "All calculation finsihed. The results are in TB2J_results directory."
        )

    elif H.spin.is_colinear:
        print(
            "Reading Siesta hamiltonian: colinear spin. Treat as non-colinear")
        tbmodel = SislWrapper(H, spin='merge')
        basis = dict(zip(tbmodel.orbs, list(range(tbmodel.nbasis))))
        print("Starting to calculate exchange.")
        description = f""" Input from collinear Siesta data.
 working directory: {os.getcwd()}
 fdf_fname: {fdf_fname}.
\n"""
        exchange = ExchangeNCL(
            tbmodels=tbmodel,
            atoms=tbmodel.atoms,
            basis=basis,
            efermi=0.0,
            magnetic_elements=magnetic_elements,
            kmesh=kmesh,
            emin=emin,
            emax=emax,
            nz=nz,
            #height=height,
            #nz1=nz1,
            #nz2=nz2,
            #nz3=nz3,
            exclude_orbs=exclude_orbs,
            Rcut=Rcut,
            ne=ne,
            use_cache=use_cache,
            description=description)
        exchange.run()
        print("\n")
        print(
            "All calculation finsihed. The results are in TB2J_results directory."
        )

    elif H.spin.is_spinorbit:

        print("Reading Siesta hamiltonian: non-colinear spin.")
        tbmodel = SislWrapper(H, spin=None)
        basis = dict(zip(tbmodel.orbs, list(range(tbmodel.nbasis))))
        print("Starting to calculate exchange.")
        description = f""" Input from non-collinear Siesta data.
 working directory: {os.getcwd()}
 fdf_fname: {fdf_fname}.
Warning: The DMI component parallel to the spin orientation, the Jani which has the component of that orientation should be disregarded
 e.g. if the spins are along z, the xz, yz, zz, zx, zy components and the z component of DMI.
 If you need these component, try to do three calculations with spin along x, y, z,  or use structure with z rotated to x, y and z. And then use TB2J_merge.py to get the full set of parameters.
\n"""
        exchange = ExchangeNCL(tbmodels=tbmodel,
                               atoms=tbmodel.atoms,
                               basis=basis,
                               efermi=0.0,
                               magnetic_elements=magnetic_elements,
                               kmesh=kmesh,
                               emin=emin,
                               emax=emax,
                               nz=nz,
                               exclude_orbs=exclude_orbs,
                               Rcut=Rcut,
                               ne=ne,
                               use_cache=use_cache,
                               description=description)
        exchange.run()
        print("\n")
        print(
            "All calculation finsihed. The results are in TB2J_results directory."
        )
Exemple #20
0
def test_h2o_dipole_hsx_no_ef(sisl_files, sisl_tmp):
    HSX = sisl.get_sile(sisl_files(_dir, "h2o_dipole.HSX"))
    with pytest.warns(sisl.SislWarning) as warns:
        Ef = HSX.read_fermi_level()
    assert len(warns) == 1
                        type=str,
                        nargs='*',
                        help="labels for corner points of k-path",
                        default=None)

    parser.add_argument("--hsx",
                        action='store_true',
                        help="shift fermi level when reading from HSX")

    return parser.parse_args()


if __name__ == '__main__':
    args = parse_args()

    sile = sisl.get_sile(args.infile)
    geom = sile.read_geometry()
    H = sile.read_hamiltonian(geometry=geom)

    assert H is not None, "Could not read Hamiltonian."

    if len(args.division) == 1: args.division = args.division[0]
    kpath = sisl.BandStructure(
        H,
        point=args.kpoints,
        division=args.division,
        name=args.klabels,
    )

    def wrap(es, parent, k, weight):
        return np.concatenate(
Exemple #22
0
def test_fe(sisl_files):
    si = sisl.get_sile(sisl_files(_dir, 'fe.bands'))
    labels, k, eig = si.read_data()
    assert k.shape == (131, )
    assert eig.shape == (131, 2, 15)
    assert len(labels[0]) == 5
Exemple #23
0
def test_1_graphene_all_fail_kavg(sisl_files, sisl_tmp):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    tbt.transmission(kavg=[0, 1])
Exemple #24
0
def test_1_graphene_all_tbtav(sisl_files, sisl_tmp):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    f = sisl_tmp('1_graphene_all.TBT.AV.nc', _dir)
    tbt.write_tbtav(f)
Exemple #25
0
def test_1_graphene_all_fail_kavg_E(sisl_files, sisl_tmp):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    tbt.orbital_COOP(kavg=[0, 1], E=0.1)
Exemple #26
0
def test_1_graphene_all_fail_kavg_E(sisl_files, sisl_tmp):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    with pytest.raises(ValueError):
        tbt.orbital_COOP(kavg=[0, 1], E=0.1)
Exemple #27
0
    def init_func_and_attrs(self, request, siesta_test_files):
        name = request.param

        if name.startswith("sisl_H"):
            gr = sisl.geom.graphene()
            H = sisl.Hamiltonian(gr)
            H.construct([(0.1, 1.44), (0, -2.7)])

            spin_type = name.split("_")[2]
            n_spin, H = {
                "unpolarized": (1, H),
                "polarized": (2, H.transform(spin=sisl.Spin.POLARIZED)),
                "noncolinear": (1, H.transform(spin=sisl.Spin.NONCOLINEAR)),
                "spinorbit": (1, H.transform(spin=sisl.Spin.SPINORBIT))
            }.get(spin_type)

            n_states = 2
            if H.spin.is_spinorbit or H.spin.is_noncolinear:
                n_states *= 2

            # Directly creating a BandStructure object
            if name.endswith("jump"):
                names = ["Gamma", "M", "M", "K"]
                bz = sisl.BandStructure(H, [[0, 0, 0], [2 / 3, 1 / 3, 0], None,
                                            [2 / 3, 1 / 3, 0], [1 / 2, 0, 0]],
                                        6, names)
                nk = 7
                tickvals = [0., 1.70309799, 1.83083034, 2.68237934]
            else:
                names = ["Gamma", "M", "K"]
                bz = sisl.BandStructure(
                    H, [[0, 0, 0], [2 / 3, 1 / 3, 0], [1 / 2, 0, 0]], 6, names)
                nk = 6
                tickvals = [0., 1.70309799, 2.55464699]
            init_func = bz.plot.fatbands

            attrs = {
                "bands_shape":
                (nk, n_spin, n_states) if H.spin.is_polarized else
                (nk, n_states),
                "weights_shape":
                (n_spin, nk, n_states, 2) if H.spin.is_polarized else
                (nk, n_states, 2),
                "ticklabels":
                names,
                "tickvals":
                tickvals,
                "gap":
                0,
                "spin_texture":
                not H.spin.is_diagonal,
                "spin":
                H.spin
            }
        elif name == "wfsx file":
            # From a siesta bands.WFSX file
            # Since there is no hamiltonian for bi2se3_3ql.fdf, we create a dummy one
            wfsx = sisl.get_sile(siesta_test_files("bi2se3_3ql.bands.WFSX"))

            geometry = sisl.get_sile(
                siesta_test_files("bi2se3_3ql.fdf")).read_geometry()
            geometry = sisl.Geometry(geometry.xyz, atoms=wfsx.read_basis())

            H = sisl.Hamiltonian(geometry, dim=4)

            init_func = partial(H.plot.fatbands,
                                wfsx_file=wfsx,
                                E0=-51.68,
                                entry_points_order=["wfsx file"])
            attrs = {
                "bands_shape": (16, 8),
                "weights_shape": (16, 8, 195),
                "ticklabels": None,
                "tickvals": None,
                "gap": 0.0575,
                "spin_texture": False,
                "spin": sisl.Spin("nc")
            }

        return init_func, attrs
Exemple #28
0
def test_1_graphene_all_warn_atom(sisl_files):
    tbt = sisl.get_sile(sisl_files(_dir, '1_graphene_all.TBT.nc'))
    with pytest.warns(sisl.SislWarning):
        tbt.a2p(1)
                     tol=0.1)
dn = MFH_HC.converge(negf.calc_n_open,
                     steps=1,
                     mixer=sisl.mixing.PulayMixer(weight=1., history=7),
                     tol=1e-6,
                     print_info=True)
print('Nup, Ndn: ', MFH_HC.n.sum(axis=1))

# Shift device with its Fermi level and write nc file
MFH_HC.H.write('MFH_HC.nc', Ef=negf.Ef)

# TBtrans RUN and plot transmission
import os
print('Clean TBtrans output from previous run')
os.system('rm device.TBT*')
os.system('rm fdf*')
print('Runing TBtrans')
os.system('tbtrans RUN.fdf > RUN.out')

tbt_up = sisl.get_sile('device.TBT_UP.nc')
tbt_dn = sisl.get_sile('device.TBT_DN.nc')

p = plot.Plot()
p.axes.plot(tbt_up.E, tbt_up.transmission(0, 1), label=r'$\sigma=\uparrow$')
p.axes.plot(tbt_dn.E, tbt_dn.transmission(0, 1), label=r'$\sigma=\downarrow$')
p.axes.legend()
p.set_xlim(-10, 10)
p.set_xlabel('Energy [eV]')
p.set_ylabel('Transmission [a.u.]')
p.savefig('transmission.pdf')
Exemple #30
0
def collect_arguments(argv, input=False,
                      argumentparser=None,
                      namespace=None):
    """
    Function for returning the actual arguments depending on the input options.

    This function will create a fake `ArgumentParser` which then
    will pass through the input figuring out which options
    that should be given to the final `ArgumentParser`.

    Parameters
    ----------
    argv : ``list`` of ``str``
       the argument list that comprise the arguments

    input : ``bool``, ``False``
       whether or not the arguments should also gather
       from the input file.
    argumentparser : ``argparse.ArgumentParser``
       the argument parser that should add the options that we find from
       the output and input files.
    namespace : ``Namespace``
       the namespace for the argument parser.
    """

    # First we figure out the input file, and the output file
    import argparse
    import sisl
    import sys, os, os.path as osp


    # Create the default namespace in case there is none
    if namespace is None:
        namespace = default_namespace()

    if input:
        # Grap input-file
        p = argparse.ArgumentParser('Parser for input file', add_help=False)
        # Now add the input and output file
        p.add_argument('input_file',nargs='?',default=None)
        # Retrieve the input file
        # (return the remaining options)
        args, argv = p.parse_known_args(argv)
        input_file = args.input_file
    else:
        input_file = None

        
    # Grap output-file
    p = argparse.ArgumentParser('Parser for output file', add_help=False)
    p.add_argument('--out','-o',nargs=1, default=None)

    # Parse the passed args to sort out the input file and
    # the output file
    args, _ = p.parse_known_args(argv)

    if input_file is not None:
        try:
            obj = sisl.get_sile(input_file)
            argumentparser, namespace = obj.ArgumentParser(argumentparser, namespace=namespace,
                                                           **obj._ArgumentParser_args_single())
            # Be sure to add the input file
            setattr(namespace, '_input_file', input_file)
        except Exception as e:
            print(e)
            raise ValueError("File: '"+input_file+"' cannot be found. Please supply a readable file!")


    if args.out is not None:
        try:
            obj = sisl.get_sile(args.out[0], mode='r')
            obj.ArgumentParser_out(argumentparser, namespace=namespace)
        except Exception as e:
            pass
    
    return argumentparser, namespace, argv
Exemple #31
0
import matplotlib
matplotlib.use('Agg')
from matplotlib import pyplot as plt
from pylab import *
import sisl as si
import numpy as np

###########################
# Input TSHS file
H_dft = si.get_sile('../../single_point15_51/RUN.fdf').read_hamiltonian()

# Atoms whose orbitals will be extracted from DFT
C_list = (H_dft.atoms.Z == 6).nonzero()[0]
O_list = (H_dft.atoms.Z == 8).nonzero()[0]
#print(C_list)
# Here we consider both C and O atoms
C_O_list = np.concatenate((C_list, O_list))
#C_O_list = np.sort(C_O_list)
#He = H_dft.sub(C_list); He.reduce()

# Purging C orbitals --> only taking Pz
H_h_o_cpz = H_dft.sub_orbital(H_dft.geometry.atoms[C_list[0]], orbital=[2])
# Purging O orbitals --> only taking Pz
H_h_opz_cpz = H_h_o_cpz.sub_orbital(H_h_o_cpz.geometry.atoms[O_list[0]],
                                    orbital=[2])
# Removing unnecessary H atoms
H_TB = H_h_opz_cpz.sub(C_O_list)
H_TB.reduce()

#print(H_TB)