Example #1
0
def object_hook(dct):
    if '__datetime__' in dct:
        return datetime.datetime.strptime(dct['__datetime__'],
                                          '%Y-%m-%dT%H:%M:%S.%f')
    if '__complex_ndarray__' in dct:
        r, i = (np.array(x) for x in dct['__complex_ndarray__'])
        return r + i * 1j

    if '__ase_objtype__' in dct:
        objtype = dct.pop('__ase_objtype__')
        dct = numpyfy(dct)

        # We just try each object type one after another and instantiate
        # them manually, depending on which kind it is.
        # We can formalize this later if it ever becomes necessary.
        if objtype == 'cell':
            from ase.cell import Cell
            obj = Cell(**dct)
        elif objtype == 'bandstructure':
            from ase.dft.band_structure import BandStructure
            obj = BandStructure(**dct)
        elif objtype == 'bandpath':
            from ase.dft.kpoints import BandPath
            obj = BandPath(path=dct.pop('labelseq'), **dct)
        else:
            raise RuntimeError('Do not know how to decode object type {} '
                               'into an actual object'.format(objtype))

        assert obj.ase_objtype == objtype
        return obj

    return dct
Example #2
0
def main(args, parser):
    atoms = read(args.calculation)
    cell = atoms.get_cell()
    calc = atoms.calc
    bzkpts = calc.get_bz_k_points()
    ibzkpts = calc.get_ibz_k_points()
    efermi = calc.get_fermi_level()
    nibz = len(ibzkpts)
    nspins = 1 + int(calc.get_spin_polarized())
    eps = np.array([[calc.get_eigenvalues(kpt=k, spin=s)
                     for k in range(nibz)]
                    for s in range(nspins)])
    if not args.quiet:
        print('Spins, k-points, bands: {}, {}, {}'.format(*eps.shape))
    try:
        size, offset = get_monkhorst_pack_size_and_offset(bzkpts)
    except ValueError:
        path = ibzkpts
    else:
        if not args.quiet:
            print('Interpolating from Monkhorst-Pack grid (size, offset):')
            print(size, offset)
        if args.path is None:
            err = 'Please specify a path!'
            try:
                cs = crystal_structure_from_cell(cell)
            except ValueError:
                err += ('\nGPAW cannot autimatically '
                        'recognize this crystal structure')
            else:
                from ase.dft.kpoints import special_paths
                kptpath = special_paths[cs]
                err += ('\nIt looks like you have a {} crystal structure.'
                        '\nMaybe you want its special path:'
                        ' {}'.format(cs, kptpath))
            parser.error(err)
        bz2ibz = calc.get_bz_to_ibz_map()
        path = bandpath(args.path, atoms.cell, args.points)[0]
        icell = atoms.get_reciprocal_cell()
        eps = monkhorst_pack_interpolate(path, eps.transpose(1, 0, 2),
                                         icell, bz2ibz, size, offset)
        eps = eps.transpose(1, 0, 2)

    emin, emax = (float(e) for e in args.range)
    bs = BandStructure(atoms.cell, path, eps, reference=efermi)
    bs.plot(emin=emin, emax=emax)
Example #3
0
def atoms2bandstructure(atoms, parser, args):
    cell = atoms.get_cell()
    calc = atoms.calc
    bzkpts = calc.get_bz_k_points()
    ibzkpts = calc.get_ibz_k_points()
    efermi = calc.get_fermi_level()
    nibz = len(ibzkpts)
    nspins = 1 + int(calc.get_spin_polarized())

    eps = np.array([[calc.get_eigenvalues(kpt=k, spin=s)
                     for k in range(nibz)]
                    for s in range(nspins)])
    if not args.quiet:
        print('Spins, k-points, bands: {}, {}, {}'.format(*eps.shape))

    if bzkpts is None:
        if ibzkpts is None:
            raise ValueError('Cannot find any k-point data')
        else:
            path_kpts = ibzkpts
    else:
        try:
            size, offset = get_monkhorst_pack_size_and_offset(bzkpts)
        except ValueError:
            path_kpts = ibzkpts
        else:
            if not args.quiet:
                print('Interpolating from Monkhorst-Pack grid (size, offset):')
                print(size, offset)
            if args.path is None:
                err = 'Please specify a path!'
                try:
                    cs = crystal_structure_from_cell(cell)
                except ValueError:
                    err += ('\nASE cannot automatically '
                            'recognize this crystal structure')
                else:
                    from ase.dft.kpoints import special_paths
                    kptpath = special_paths[cs]
                    err += ('\nIt looks like you have a {} crystal structure.'
                            '\nMaybe you want its special path:'
                            ' {}'.format(cs, kptpath))
                parser.error(err)
            bz2ibz = calc.get_bz_to_ibz_map()

            path_kpts = bandpath(args.path, atoms.cell, args.points).kpts

            icell = atoms.get_reciprocal_cell()
            eps = monkhorst_pack_interpolate(path_kpts, eps.transpose(1, 0, 2),
                                             icell, bz2ibz, size, offset)
            eps = eps.transpose(1, 0, 2)

    special_points = get_special_points(cell)
    path = BandPath(atoms.cell, kpts=path_kpts,
                    special_points=special_points)

    return BandStructure(path, eps, reference=efermi)
Example #4
0
    def get_band_structure(self, path, modes=False, born=False, verbose=True):
        omega_kl = self.band_structure(path.scaled_kpts, modes, born, verbose)
        if modes:
            assert 0
            omega_kl, modes = omega_kl

        from ase.dft.band_structure import BandStructure
        bs = BandStructure(path, energies=omega_kl[None])
        return bs
 def band_structure(self):
     self.calculate()
     perm = self.parameters.get('perm', self.label)
     if self.calc.get_spin_polarized():
         alpha = np.loadtxt(os.path.join(perm, self.label + '.alpha_band'))
         beta = np.loadtxt(os.path.join(perm, self.label + '.beta_band'))
         energies = np.array([alpha[:, 1:], beta[:, 1:]]) * Hartree
     else:
         data = np.loadtxt(
             os.path.join(perm, self.label + '.restricted_band'))
         energies = data[np.newaxis, :, 1:] * Hartree
     eref = self.calc.get_fermi_level()
     if eref is None:
         eref = 0.
     return BandStructure(self.parameters.bandpath, energies, eref)
Example #6
0
def create_ase_object(objtype, dct):
    # We just try each object type one after another and instantiate
    # them manually, depending on which kind it is.
    # We can formalize this later if it ever becomes necessary.
    if objtype == 'cell':
        from ase.cell import Cell
        obj = Cell(**dct)
    elif objtype == 'bandstructure':
        from ase.dft.band_structure import BandStructure
        obj = BandStructure(**dct)
    elif objtype == 'bandpath':
        from ase.dft.kpoints import BandPath
        obj = BandPath(path=dct.pop('labelseq'), **dct)
    else:
        raise ValueError('Do not know how to decode object type {} '
                         'into an actual object'.format(objtype))
    assert obj.ase_objtype == objtype
    return obj
def test_bandstructure(plt):
    from ase.build import bulk
    from ase.calculators.test import FreeElectrons
    from ase.dft.kpoints import special_paths
    from ase.dft.band_structure import BandStructure

    a = bulk('Cu')
    path = special_paths['fcc']
    a.calc = FreeElectrons(nvalence=1,
                           kpts={'path': path, 'npoints': 200})
    a.get_potential_energy()
    bs = a.calc.band_structure()
    coords, labelcoords, labels = bs.get_labels()
    print(labels)
    bs.write('hmm.json')
    bs = BandStructure.read('hmm.json')
    coords, labelcoords, labels = bs.get_labels()
    print(labels)
    assert ''.join(labels) == 'GXWKGLUWLKUX'
    bs.plot(emax=10, filename='bs.png')
def test_bandstructure_json():
    from ase.build import bulk
    from ase.dft.band_structure import calculate_band_structure, BandStructure
    from ase.io.jsonio import read_json
    from ase.calculators.test import FreeElectrons

    atoms = bulk('Au')
    lat = atoms.cell.get_bravais_lattice()
    path = lat.bandpath(npoints=100)

    atoms.calc = FreeElectrons()

    bs = calculate_band_structure(atoms, path)
    bs.write('bs.json')
    bs.path.write('path.json')

    bs1 = read_json('bs.json')
    bs2 = BandStructure.read('bs.json')
    path1 = read_json('path.json')
    assert type(bs1) == type(bs)  # noqa
    assert type(bs2) == type(bs)  # noqa
    assert type(path1) == type(bs.path)  # noqa
Example #9
0
def get_band_structure(atoms=None, calc=None, ref=0):
    """
    Create band structure object from Atoms or calculator.

    This functions is rewritten here to allow the user to set the reference energy level.
    (The method calc.get_fermi_level() can fail in some cases as for insulators or for non-scf calculations)
    """

    atoms = atoms if atoms is not None else calc.atoms
    calc = calc if calc is not None else atoms.calc

    kpts = calc.get_k_points()

    energies = []
    for s in range(calc.get_number_of_spins()):
        energies.append(
            [calc.get_eigenvalues(kpt=k, spin=s) for k in range(len(kpts))])
    energies = np.array(energies)

    return BandStructure(cell=atoms.cell,
                         kpts=kpts,
                         energies=energies,
                         reference=ref)
                          28.6214, 29.1794, 29.1794, 29.6229, 30.5584, 32.8451
                      ],
                      [
                          -3.0876, -0.8863, 3.0037, 3.0037, 6.2623, 6.7765,
                          14.7728, 14.7728, 17.1201, 17.4077, 17.8504, 17.8504,
                          19.3349, 19.8627, 22.8644, 23.6249, 23.6249, 24.7429,
                          27.5978, 27.9651, 27.9651, 29.0422, 30.4427, 32.3347
                      ],
                      [
                          -2.5785, -1.4744, 2.9437, 2.9437, 6.3021, 6.5565,
                          15.41, 15.41, 17.2036, 17.2036, 17.7555, 18.0538,
                          19.0775, 19.1146, 23.7456, 24.5645, 24.5645, 24.9649,
                          26.8166, 26.8167, 26.9285, 27.9975, 30.8961, 31.8679
                      ],
                      [
                          -2.0397, -2.0397, 2.9235, 2.9235, 6.399, 6.3991,
                          15.775, 15.775, 16.8298, 16.8298, 18.4119, 18.4119,
                          18.6257, 18.6257, 24.5738, 24.5739, 25.3583, 25.3583,
                          25.9521, 25.9521, 27.1466, 27.1466, 31.3822, 31.3825
                      ]]])

# Update to new band structure stuff
lattice = atoms.cell.get_bravais_lattice()
bandpath = lattice.bandpath('WGX', npoints=30)
maxerr = np.abs(bandpath.kpts - kpts).max()
assert maxerr < 1e-5

bs = BandStructure(bandpath, energies=energies, reference=ref)

bs.plot(emin=-13, filename='vasp_si_bandstructure.png')
Example #11
0
                          -3.5642, -0.2784, 3.1042, 3.1042, 6.2793, 7.064,
                          14.1111, 14.1111, 16.5581, 16.7126, 18.5182, 18.5182,
                          19.3103, 20.6566, 22.0339, 22.8057, 22.8057, 24.5452,
                          28.6214, 29.1794, 29.1794, 29.6229, 30.5584, 32.8451
                      ],
                      [
                          -3.0876, -0.8863, 3.0037, 3.0037, 6.2623, 6.7765,
                          14.7728, 14.7728, 17.1201, 17.4077, 17.8504, 17.8504,
                          19.3349, 19.8627, 22.8644, 23.6249, 23.6249, 24.7429,
                          27.5978, 27.9651, 27.9651, 29.0422, 30.4427, 32.3347
                      ],
                      [
                          -2.5785, -1.4744, 2.9437, 2.9437, 6.3021, 6.5565,
                          15.41, 15.41, 17.2036, 17.2036, 17.7555, 18.0538,
                          19.0775, 19.1146, 23.7456, 24.5645, 24.5645, 24.9649,
                          26.8166, 26.8167, 26.9285, 27.9975, 30.8961, 31.8679
                      ],
                      [
                          -2.0397, -2.0397, 2.9235, 2.9235, 6.399, 6.3991,
                          15.775, 15.775, 16.8298, 16.8298, 18.4119, 18.4119,
                          18.6257, 18.6257, 24.5738, 24.5739, 25.3583, 25.3583,
                          25.9521, 25.9521, 27.1466, 27.1466, 31.3822, 31.3825
                      ]]])

bs = BandStructure(cell=atoms.cell,
                   kpts=kpts,
                   energies=energies,
                   reference=ref)

bs.plot(emin=-13, filename='vasp_si_bandstructure.png')
Example #12
0
for i, k in enumerate(kpts):
    # Restart from ground state and fix potential:
    calc = GPAW(
        datapath + 'graphene_bilayer_sc_' + str(RRA) + '.gpw',
        fixdensity=True,
        kpts=[k],
        symmetry='off',
        txt=datapath + 'graphene_bilayer_bs_' + str(RRA) + '.txt',
        parallel=dict(
            band=5,  # band parallelization
            augment_grids=True,  # use all cores for XC/Poisson
            sl_auto=True)  # enable parallel ScaLAPACK
    )

    grap_bilayer.calc = calc
    en2 = calc.get_potential_energy()
    bs = get_band_structure(grap_bilayer, _bandpath=path).todict()

    ref.append(bs['reference'])
    energies.append(bs['energies'][0][0])

    parprint(i, end=' ', flush=True)

parprint('\nFinished band structure calculation.')
parprint('Energy self-consistent:', en1, '\nEnergy band structure:', en2)

bs = BandStructure(path, [energies], reference=ref[0])
bs.write(datapath + 'bandstructure_rot' + str(RRA) + '.json')
path.write(datapath + 'bandpath_rot' + str(RRA) + '.json')
parprint('Saved band structure file.')
Example #13
0
import matplotlib
from ase.build import bulk
from ase.calculators.test import FreeElectrons
from ase.dft.kpoints import special_paths
from ase.dft.band_structure import BandStructure

a = bulk('Cu')
path = special_paths['fcc']
a.calc = FreeElectrons(nvalence=1, kpts={'path': path, 'npoints': 200})
a.get_potential_energy()
bs = a.calc.band_structure()
coords, labelcoords, labels = bs.get_labels()
print(labels)
bs.write('hmm.json')
bs = BandStructure.read('hmm.json')
coords, labelcoords, labels = bs.get_labels()
print(labels)
assert ''.join(labels) == 'GXWKGLUWLKUX'
matplotlib.use('Agg', warn=False)
bs.plot(emax=10, filename='bs.png')
Example #14
0
from ase.build import bulk
from ase.calculators.test import FreeElectrons
from ase.dft.kpoints import special_paths
from ase.dft.band_structure import BandStructure

a = bulk('Cu')
path = special_paths['fcc']
a.calc = FreeElectrons(nvalence=1,
                       kpts={'path': path, 'npoints': 200})
a.get_potential_energy()
bs = a.calc.band_structure()
coords, labelcoords, labels = bs.get_labels()
print(labels)
bs.write('hmm.json')
bs = BandStructure.read('hmm.json')
coords, labelcoords, labels = bs.get_labels()
print(labels)
assert ''.join(labels) == 'GXWKGLUWLKUX'
import matplotlib
matplotlib.use('Agg', warn=False)
bs.plot(emax=10, filename='bs.png')
Example #15
0
from ase.build import bulk
from ase.calculators.test import FreeElectrons
from ase.dft.kpoints import special_paths
from ase.dft.band_structure import BandStructure

a = bulk("Cu")
path = special_paths["fcc"]
a.calc = FreeElectrons(nvalence=1, kpts={"path": path, "npoints": 200})
a.get_potential_energy()
bs = a.calc.band_structure()
print(bs.labels)
bs.write("hmm.json")
bs = BandStructure(filename="hmm.json")
print(bs.labels)
assert "".join(bs.labels) == "GXWKGLUWLKUX"
import matplotlib

matplotlib.use("Agg", warn=False)
bs.plot(emax=10, filename="bs.png")
Example #16
0
import numpy
import os
import matplotlib.pyplot as plt
from ase.dft.band_structure import BandStructure, BandStructurePlot


data = numpy.load("./PBE-gap.npz")

bs = BandStructure(cell=data["cell"],
                   kpts=data["kpts"],
                   energies=data["energies"],
                   reference=data["reference"])
print(bs)
bsp = BandStructurePlot(bs)
bsp.plot(emin=-8, emax=8, filename="bs.png")