Ejemplo n.º 1
0
def test_makebandpath():
    atoms = bulk('Au')
    cell = atoms.cell

    path0 = bandpath('GXL', cell)
    print(path0)
    path1 = bandpath([[0., 0., 0.], [.5, .5, .5]], cell, npoints=50)
    print(path1)
    path2 = bandpath([[0., 0., 0.], [.5, .5, .5], [.1, .2, .3]], cell,
                     npoints=50,
                     special_points={'G': [0., 0., 0.]})
    print(path2)
Ejemplo n.º 2
0
def cubic_kpath(npoints=500, name=True):
    """
    return the kpoint path for cubic
    Parameters:
    ----------------
    npoints: int
        number of points.

    Returns:
    -----------------
    kpts:
        kpoints
    xs:
        x cordinates for plot
    xspecial:
        x cordinates for special k points
    """
    special_path = special_paths['cubic']
    points = special_points['cubic']
    paths = parse_path_string(special_path)
    special_kpts = [points[k] for k in paths[0]]
    kpts, xs, xspecial = bandpath(special_kpts,
                                  cell=np.eye(3),
                                  npoints=npoints)
    if not name:
        return kpts, xs, xspecial
    else:
        return kpts, xs, xspecial, special_path
Ejemplo n.º 3
0
 def plot_phonon_band(self,
                      kvectors=np.array([[0, 0, 0], [0.5, 0, 0],
                                         [0.5, 0.5, 0], [0, 0,
                                                         0], [.5, .5, .5]]),
                      knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
                      supercell_matrix=None,
                      npoints=100,
                      color='red',
                      ax=None):
     if ax is None:
         fig, ax = plt.subplots()
     from ase.dft.kpoints import bandpath
     if supercell_matrix is not None:
         kvectors = [np.dot(k, supercell_matrix) for k in kvectors]
     kpts, x, X = bandpath(kvectors, self.get_cell(), npoints)
     evalues, evecs = self.solve_phonon(kpts)
     for i in range(3 * self.natoms):
         ax.plot(x, evalues[:, i], color=color, alpha=1)
     plt.axhline(0, linestyle='--', color='gray')
     ax.set_xlabel('q-point')
     ax.set_ylabel('Frequency (cm$^{-1}$)')
     #ax.set_ylabel('Energy (eV)')
     ax.set_xlim(x[0], x[-1])
     ax.set_xticks(X)
     ax.set_xticklabels(knames)
     for x in X:
         ax.axvline(x, linewidth=0.6, color='gray')
     return ax
Ejemplo n.º 4
0
def cubic_kpath():
    special_path = special_paths['cubic']
    points = special_points['cubic']
    paths = parse_path_string(special_path)
    special_kpts = [points[k] for k in paths[0]]
    kpts, xs, xspecial = bandpath(special_kpts, cell=np.eye(3), npoints=500)
    return kpts, xs, xspecial
Ejemplo n.º 5
0
def test_makebandpath():
    from ase.dft.kpoints import bandpath
    from ase.build import bulk

    atoms = bulk('Au')
    cell = atoms.cell

    path0 = bandpath('GXL', cell)
    print(path0)
    path1 = bandpath([[0., 0., 0.], [.5, .5, .5]], cell, npoints=50)
    print(path1)
    path2 = bandpath([[0., 0., 0.], [.5, .5, .5], [.1, .2, .3]],
                     cell,
                     npoints=50,
                     special_points={'G': [0., 0., 0.]})
    print(path2)
Ejemplo n.º 6
0
    def plot_band(self,
                  kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],
                                     [0, 0, 0], [.5, .5, .5]]),
                  knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
                  supercell_matrix=None,
                  npoints=100,
                  efermi=None,
                  ax=None):
        if ax is None:
            _fig, ax = plt.subplots()
        if supercell_matrix is not None:
            kvectors = [np.dot(k, supercell_matrix) for k in kvectors]
        kpts, x, X = bandpath(kvectors, self.cell, npoints)
        evalues, _evecs = self.solve_all(kpts=kpts)
        for i in range(evalues.shape[1]):
            ax.plot(x, evalues[:, i], color='blue', alpha=1)

        if efermi is not None:
            plt.axhline(self.get_fermi_level(), linestyle='--', color='gray')
        else:
            try:
                plt.axhline(self.get_fermi_level(),
                            linestyle='--',
                            color='gray')
            except:
                pass
        ax.set_xlabel('k-point')
        ax.set_ylabel('Energy (eV)')
        ax.set_xlim(x[0], x[-1])
        ax.set_xticks(X)
        ax.set_xticklabels(knames)
        for x in X:
            ax.axvline(x, linewidth=0.6, color='gray')
        return ax
Ejemplo n.º 7
0
    def scdmk(self,
              mu,
              sigma,
              nwann,
              ftype='Gauss',
              anchor_only=False,
              anchor_kpoint=[0.0, 0.0, 0.0],
              kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],
                                 [0, 0, 0], [.5, .5, .5]]),
              knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
              supercell_matrix=None,
              npoints=100,
              color='red',
              anchors=None,
              scols=None,
              ax=None):
        from minimulti.scdm.scdmk import SCDMk, occupation_func, Amnk_to_Hk

        if ax is None:
            fig, ax = plt.subplots()
        from ase.dft.kpoints import bandpath
        if supercell_matrix is not None:
            kvectors = [np.dot(k, supercell_matrix) for k in kvectors]
        kpts, x, X = bandpath(kvectors, self.get_cell(), npoints)
        Hks, evalues, evecs = self.solve_phonon(
            kpts, ham=True, add_phase=False)

        scdmk = SCDMk(
            evals=evalues,
            wfn=evecs,
            #positions=self.basis_positions,
            positions=np.zeros_like(self.basis_positions),
            kpts=kpts,
            nwann=nwann,
            occupation_func=occupation_func(ftype=ftype, mu=mu, sigma=sigma),
            anchor_kpoint=anchor_kpoint,
            anchors=anchors,
            change_basis=evecs[0],
            scols=scols)
        Amn = scdmk.get_Amn(anchor_only=anchor_only)
        self.Hkr = np.zeros_like(Hks)
        for i, Hk in enumerate(Hks):
            self.Hkr[i] = rebase_H(Hk, evecs[0])

        Hk_prim = Amnk_to_Hk(Amn, evecs, Hks, kpts)

        evals = []
        for ik, k in enumerate(kpts):
            ev, _ = sl.eigh(Hk_prim[ik], turbo=False)
            evals.append(ev)

        evals = np.array(evals)
        s = np.sign(evals)
        v = np.sqrt(evals * s)
        evals = s * v * 15.633302 * 33

        for i in range(evals.shape[1]):
            ax.plot(x, evals[:, i], marker='.', color='blue', alpha=0.2)
        return ax
Ejemplo n.º 8
0
def plot_band(model,
              kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],
                                 [0, 0, 0], [.5, .5, .5]]),
              knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
              supercell_matrix=None,
              npoints=100,
              efermi=None,
              erange=None,
              color='blue',
              alpha=0.8,
              marker='',
              cell=np.eye(3),
              ax=None):
    if ax is None:
        _fig, ax = plt.subplots()

    if supercell_matrix is None:
        supercell_matrix = np.eye(3)
    kvectors = [np.dot(k, supercell_matrix) for k in kvectors]
    if 'cell' not in model.__dict__:
        band = bandpath(kvectors, cell @ supercell_matrix, npoints)
    else:
        band = bandpath(kvectors, cell @ supercell_matrix, npoints)
    kpts = band.kpts
    x, X, _labels = band.get_linear_kpoint_axis()
    evalues, _evecs = model.solve_all(kpts=kpts)
    for i in range(evalues.shape[1]):
        ax.plot(x, evalues[:, i], color=color, alpha=alpha, marker=marker)

    if efermi is not None:
        ax.axhline(efermi, linestyle='--', color='gray')
    else:
        try:
            plt.axhline(model.get_fermi_level(), linestyle='--', color='gray')
        except AttributeError:
            pass
    ax.set_ylabel('Energy (eV)')
    ax.set_xlim(x[0], x[-1])
    ax.set_xticks(X)
    ax.set_xticklabels(knames)
    if erange is not None:
        ax.set_ylim(erange)
    for x in X:
        ax.axvline(x, linewidth=0.6, color='gray')
    return ax
Ejemplo n.º 9
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)
Ejemplo n.º 10
0
    def plot_magnon_band(
        self,
        kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0, 0],
                           [.5, .5, .5]]),
        knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
        supercell_matrix=None,
        npoints=50,
        color='red',
        kpath_fname=None,
        Jq=False,
        ax=None,
    ):
        if ax is None:
            fig, ax = plt.subplots()
        kptlist = kvectors
        if knames is None and kvectors is None:
            # fully automatic k-path
            bp = Cell(self.cell).bandpath(npoints=npoints)
            spk = bp.special_points
            xlist, kptlist, Xs, knames = group_band_path(bp)
        elif knames is not None and kvectors is None:
            # user specified kpath by name
            bp = Cell(self.cell).bandpath(knames, npoints=npoints)
            spk = bp.special_points
            kpts = bp.kpts
            xlist, kptlist, Xs, knames = group_band_path(bp)
        else:
            # user spcified kpath and kvector.
            kpts, x, Xs = bandpath(kvectors, self.cell, npoints)
            spk = dict(zip(knames, kvectors))
            xlist = [x]
            kptlist = [kpts]

        if supercell_matrix is not None:
            kptlist = [np.dot(k, supercell_matrix) for k in kptlist]
        print("High symmetry k-points:")
        for name, k in spk.items():
            if name == 'G':
                name = 'Gamma'
            print(f"{name}: {k}")

        for kpts, xs in zip(kptlist, xlist):
            evals, evecs = self.solve_k(kpts, Jq=Jq)
            # Plot band structure
            nbands = evals.shape[1]
            emin = np.min(evals[:, 0])
            for i in range(nbands):
                ax.plot(xs, (evals[:, i]) / 1.6e-22, color=color)

        ax.set_ylabel('Energy (meV)')
        ax.set_xlim(xlist[0][0], xlist[-1][-1])
        ax.set_xticks(Xs)
        knames = [x if x != 'G' else '$\Gamma$' for x in knames]
        ax.set_xticklabels(knames)
        for x in Xs:
            ax.axvline(x, linewidth=0.6, color='gray')
        return ax
def kpath():
    #DDB = abilab.abiopen('out_DDB')
    #struct = DDB.structure
    #atoms = DDB.structure.to_ase_atoms()
    atoms = bulk('Cu', 'fcc')
    points = get_special_points('fcc', atoms.cell, eps=0.01)
    GXW = [points[k] for k in 'GXWGL']
    kpts, x, X = bandpath(GXW, atoms.cell, 700)
    names = ['$\Gamma$', 'X', 'W', '$\Gamma$', 'L']
    return kpts, x, X, names, GXW
Ejemplo n.º 12
0
def phonon_run(runID, save_to_db=False, plot_bands=False):
    print("Running ID %d" % (runID))
    db = connect(db_name)
    atoms = db.get_atoms(id=runID)
    #view(atoms)
    #atoms = bulk("Al")
    #atoms = atoms*(2,1,1)
    #calc = EAM(potential="/home/davidkl/Documents/EAM/Al-LEA.eam.alloy")
    calc = EAM(potential="/home/davidkl/Documents/EAM/mg-al-set.eam.alloy")
    atoms.set_calculator(calc)
    #calc = gp.GPAW( mode=gp.PW(600), xc="PBE", kpts=(4,4,4), nbands="120%", symmetry="off" )
    #atoms.set_calculator(calc)
    ph = Phonons(atoms,
                 calc,
                 supercell=(3, 3, 3),
                 name=wrk + "/phonon_files/phonon%d" % (runID))
    ph.run()
    #return
    ph.read(acoustic=True)
    omega_e, dos_e = ph.dos(kpts=(30, 30, 30), npts=1000, delta=5E-4)
    if (plot_bands):
        points = ibz_points['fcc']
        G = points['Gamma']
        X = points['X']
        W = points['W']
        K = points['K']
        L = points['L']
        U = points['U']
        point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K']
        path = [G, X, U, L, G, K]

        path_kc, q, Q = bandpath(path, atoms.cell, 100)
        omega_kn = 1000.0 * ph.band_structure(path_kc)

        figb = plt.figure()
        axb = figb.add_subplot(1, 1, 1)
        for n in range(len(omega_kn[0])):
            omega_n = omega_kn[:, n]
            axb.plot(q, omega_n)
        plt.show()

    if (save_to_db):
        # Store the results in the database
        db.update(runID, has_dos=True)

        manager = cpd.PhononDOS_DB(db_name)

        # Extract relevant information from the atoms database
        row = db.get(id=runID)
        name = row.name
        atID = row.id
        manager.save(name=name, atID=atID, omega_e=omega_e, dos_e=dos_e)
Ejemplo n.º 13
0
def kpts2ndarray(kpts, atoms=None):
    """Convert kpts keyword to 2-d ndarray of scaled k-points."""

    if kpts is None:
        return np.zeros((1, 3))

    if isinstance(kpts, dict):
        if 'path' in kpts:
            return bandpath(cell=atoms.cell, **kpts)[0]
        size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts)
        return monkhorst_pack(size) + offsets

    if isinstance(kpts[0], int):
        return monkhorst_pack(kpts)

    return np.array(kpts)
Ejemplo n.º 14
0
def kpts2ndarray(kpts, atoms=None):
    """Convert kpts keyword to 2-d ndarray of scaled k-points."""

    if kpts is None:
        return np.zeros((1, 3))

    if isinstance(kpts, dict):
        if 'path' in kpts:
            return bandpath(cell=atoms.cell, **kpts)[0]
        size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts)
        return monkhorst_pack(size) + offsets

    if isinstance(kpts[0], int):
        return monkhorst_pack(kpts)

    return np.array(kpts)
Ejemplo n.º 15
0
    def plot_unfolded_band(self,
                           kvectors=np.array([[0, 0, 0], [0.5, 0,
                                                          0], [0.5, 0.5, 0],
                                              [0, 0, 0], [.5, .5, .5]]),
                           knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
                           supercell_matrix=None,
                           npoints=300,
                           color='red',
                           ax=None):
        """
        plot the projection of the band to the basis
        """
        if ax is None:
            fig, ax = plt.subplots()
        from ase.dft.kpoints import bandpath
        kvectors = [np.dot(k, supercell_matrix) for k in kvectors]
        kpts, x, X = bandpath(kvectors, self.ref_atoms.cell, npoints)
        kslist = np.array([x] * (self.natoms * 3))
        evals, wkslist = self.unfold_phonon(
            kpts, supercell_matrix)  #.T * 0.98 + 0.01
        wkslist = wkslist * 0.98 + 0.02
        ekslist = evals

        ax = plot_band_weight(
            kslist,
            ekslist.T,
            wkslist=wkslist.T,
            efermi=None,
            yrange=None,
            output=None,
            style='alpha',
            color='blue',
            axis=ax,
            width=20,
            xticks=None)
        for i in range(3 * self.natom):
            ax.plot(x, evals[:, i], color='gray', alpha=1, linewidth=0.1)
        ax.axhline(0.0, linestyle='--', color='gray')
        ax.set_ylabel('Frequency (THz)')
        ax.set_xlim(x[0], x[-1])
        ax.set_xticks(X)
        ax.set_xticklabels(knames)
        for x in X:
            ax.axvline(x, linewidth=0.6, color='gray')
        return ax

        pass
Ejemplo n.º 16
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)
Ejemplo n.º 17
0
    def plot_magnon_band(
        self,
        kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0], [0, 0, 0],
                           [.5, .5, .5]]),
        knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
        supercell_matrix=None,
        npoints=100,
        color='red',
        kpath_fname=None,
        Jq=False,
        ax=None,
    ):
        if ax is None:
            fig, ax = plt.subplots()
        if knames is None and kvectors is None:
            bp = Cell(self.cell).bandpath(npoints=npoints)
            kpts = bp.kpts
            x, X, knames = bp.get_linear_kpoint_axis()
            spk = bp.special_points
        elif knames is not None:
            bp = Cell(self.cell).bandpath(knames, npoints=npoints)
            kpts = bp.kpts
            x, X, knames = bp.get_linear_kpoint_axis()
        else:
            kpts, x, X = bandpath(kvectors, self.cell, npoints)
            spk = dict(zip(knames, kvectors))

        if supercell_matrix is not None:
            kvectors = [np.dot(k, supercell_matrix) for k in kvectors]

        evals, evecs = self.solve_k(kpts, Jq=Jq)
        # Plot band structure
        nbands = evals.shape[1]
        emin = np.min(evals[:, 0])
        for i in range(nbands):
            ax.plot(x, (evals[:, i]) / 1.6e-22, color=color)
        ax.set_ylabel('Energy (meV)')
        ax.set_xlim(x[0], x[-1])
        #ax.set_ylim(0)
        ax.set_xticks(X)
        knames = [x if x != 'G' else '$\Gamma$' for x in knames]
        ax.set_xticklabels(knames)
        for x in X:
            ax.axvline(x, linewidth=0.6, color='gray')
        return ax
    def plot_unfolded_band(
            self,
            kvectors=np.array([[0, 0, 0], [0.5, 0, 0], [0.5, 0.5, 0],
                               [0, 0, 0], [.5, .5, .5]]),
            knames=['$\Gamma$', 'X', 'M', '$\Gamma$', 'R'],
            npoints=200,
            ax=None, ):
        """
        plot the projection of the band to the basis
        """
        if ax is None:
            fig, ax = plt.subplots()
        from ase.dft.kpoints import bandpath
        kvectors = [np.dot(k, self.sc_matrix) for k in kvectors]
        kpts, x, X = bandpath(kvectors, self.cell, npoints)
        kslist = [x] * len(self.positions)
        efermi = 0.0
        wkslist=self.unfold(kpts).T * 0.98 +0.01
        ekslist = self.evals
        #wkslist = np.abs(self.get_projection(orb, spin=spin, eigenvecs=evecs))
        ax = plot_band_weight(
                kslist,
                ekslist,
                wkslist=wkslist,
                efermi=None,
                yrange=None,
                output=None,
                style='alpha',
                color='blue',
                axis=ax,
                width=20,
                xticks=None)
        for i in range(len(self.positions)):
            ax.plot(x, self.evals[i, :], color='gray', alpha=1, linewidth=0.1)

        #ax.axhline(self.get_fermi_level(), linestyle='--', color='gray')
        ax.set_xlabel('k-point')
        ax.set_ylabel('Energy (eV)')
        ax.set_xlim(x[0], x[-1])
        ax.set_xticks(X)
        ax.set_xticklabels(knames)
        for x in X:
            ax.axvline(x, linewidth=0.6, color='gray')
        return ax
Ejemplo n.º 19
0
def plot_spinwave(ham,
                  qnames=['$\Gamma$', 'X'],
                  qvectors=[(0, 0, 0), (0.5, 0, 0)]):
    fig = plt.figure()
    from ase.build import bulk
    from ase.dft.kpoints import get_special_points
    from ase.dft.kpoints import bandpath
    kpts, x, X = bandpath(qvectors, ham.cell, 300)
    qsolver = QSolver(hamiltonian=ham)
    evals, evecs = qsolver.solve_all(kpts, eigen_vectors=True)
    nbands = evals.shape[1]
    for i in range(nbands):
        plt.plot(x, evals[:, i] / 1.6e-21)
    plt.xlabel('Q-point (2$\pi$)')
    plt.ylabel('Energy (meV)')
    plt.xlim(x[0], x[-1])
    plt.xticks(X, qnames)
    for x in X:
        plt.axvline(x, linewidth=0.6, color='gray')
    plt.show()
Ejemplo n.º 20
0
def kpts2kpts(kpts, atoms=None):
    if kpts is None:
        return KPoints()

    if hasattr(kpts, 'kpts'):
        return kpts

    if isinstance(kpts, dict):
        if 'kpts' in kpts:
            return KPoints(kpts['kpts'])
        if 'path' in kpts:
            path = bandpath(cell=atoms.cell, **kpts)
            return path
        size, offsets = kpts2sizeandoffsets(atoms=atoms, **kpts)
        return KPoints(monkhorst_pack(size) + offsets)

    if isinstance(kpts[0], int):
        return KPoints(monkhorst_pack(kpts))

    return KPoints(np.array(kpts))
Ejemplo n.º 21
0
def construct_kpoint_path(path: str, cell: Cell, bands_point_num: int) -> BandPath:
    path_lengths = _path_lengths(path, cell, bands_point_num)
    special_points = cell.bandpath().special_points

    path_list = path_str_to_list(path, special_points)

    kpts = []
    for start, end, npoints in zip(path_list[:-1], path_list[1:], path_lengths):
        if start == ',':
            pass
        elif end == ',':
            kpts.append(special_points[start].tolist())
        else:
            bp = bandpath(start + end, cell, npoints + 1)
            kpts += bp.kpts[:-1].tolist()
    # Don't forget about the final kpoint
    kpts.append(bp.kpts[-1].tolist())

    if len(kpts) != sum(path_lengths) + 1:
        raise AssertionError(
            'Did not get the expected number of kpoints; this suggests there is a bug in the code')

    return BandPath(cell=cell, kpts=kpts, path=path, special_points=special_points)
Ejemplo n.º 22
0
def parse_plotbands(args):
    """Parse command-line arguments for the plotbands subcommand."""
    # Try and load the data from the interpolation step
    data, equivalences, coeffs, metadata = (
        BoltzTraP2.serialization.load_calculation(args.bt2_file))
    lattvec = data.get_lattvec()
    info("sucessfully loaded " + args.bt2_file)
    # The second position alargument is first interpreted as a Python literal,
    # and after parsing it is cast to a NumPy array, which must have the right
    # dimensions. The special value None directs the parser to split the path
    # in several parts.
    try:
        kpaths = ast.literal_eval(args.kpath)
    except ValueError:
        lexit("'{}' cannot be parsed as a Python literal".format(kpaths))
    if not isinstance(kpaths, list):
        lexit("'{}' cannot be parsed as a Python list".format(kpaths))
    kpaths = [
        list(group)
        for k, group in itertools.groupby(
            kpaths, key=lambda x: x is not None) if k
    ]
    try:
        kpaths = [np.array(i, dtype=np.float64) for i in kpaths]
        for i in kpaths:
            if i.shape[0] < 2 or i.shape[1] != 3:
                raise ValueError
    except ValueError:
        lexit("the path cannot be interpreted as a set of N x 3"
              " arrays (with N >= 2")

    plt.figure()
    ax = plt.gca()
    ticks = []
    dividers = []
    offset = 0.
    for ikpath, kpath in enumerate(kpaths):
        ax.set_prop_cycle(
            color=matplotlib.rcParams["axes.prop_cycle"].by_key()["color"])
        info("k path #{}".format(i + 1))
        # Generate the explicit point list.
        kp, dkp, dcl = asekp.bandpath(kpath, data.atoms.cell, args.nkpoints)
        dkp += offset
        dcl += offset
        # Compute the band energies.
        with TimerContext() as timer:
            egrid = BoltzTraP2.fite.getBands(kp, equivalences,
                                             data.get_lattvec(), coeffs)[0]
            deltat = timer.get_deltat()
            info("rebuilding the bands took {:.3g} s".format(deltat))
        egrid -= data.fermi
        # Create the plot
        nbands = egrid.shape[0]
        for i in range(nbands):
            plt.plot(dkp, egrid[i, :], lw=2.)
        ticks += dcl.tolist()
        dividers += [dcl[0], dcl[-1]]
        offset = dkp[-1]
    ax.set_xticks(ticks)
    ax.set_xticklabels([])
    for d in ticks:
        plt.axvline(x=d, color=PSEUDO_BLACK, ls="--", lw=.5)
    for d in dividers:
        plt.axvline(x=d, color=PSEUDO_BLACK, ls="-", lw=2.)
    plt.axhline(y=0., color=PSEUDO_BLACK, lw=1.)
    plt.ylabel(r"$\varepsilon - \varepsilon_F\;\left[\mathrm{Ha}\right]$")
    plt.tight_layout()
    plt.show()
Ejemplo n.º 23
0
from ase.dft.kpoints import bandpath
import numpy as np
print(bandpath('GX,GX', np.eye(3), 6))
Ejemplo n.º 24
0
from __future__ import print_function
from ase.dft.kpoints import bandpath
from ase.parallel import paropen
from gpaw import GPAW

layer = GPAW('WS2_gs.gpw', txt=None).atoms

G = [0, 0, 0]
K = [1 / 3., 1 / 3., 0]
M = [0.5, 0, 0]
M_ = [-0.5, 0, 0]
K_ = [-1 / 3., -1 / 3., 0]
kpts, x, X = bandpath([M, K, G, K_, M_], layer.cell, npoints=1000)

calc = GPAW('WS2_gs.gpw', kpts=kpts, symmetry='off')
calc.diagonalize_full_hamiltonian(nbands=100)

calc.write('WS2_bands.gpw', mode='all')

f = paropen('WS2_kpath.dat', 'w')
for k in x:
    print(k, file=f)
f.close()

f = paropen('WS2_highsym.dat', 'w')
for k in X:
    print(k, file=f)
f.close()
Ejemplo n.º 25
0
from ase.dft.kpoints import bandpath
from ase.build import bulk

atoms = bulk('Au')
cell = atoms.cell

path0 = bandpath('GXL', cell)
print(path0)
path1 = bandpath([[0., 0., 0.], [.5, .5, .5]], cell, npoints=50)
print(path1)
path2 = bandpath([[0., 0., 0.], [.5, .5, .5], [.1, .2, .3]], cell, npoints=50,
                 special_points={'G': [0., 0., 0.]})
print(path2)
Ejemplo n.º 26
0
# Read forces and assemble the dynamical matrix
ph.read(acoustic=True)

# High-symmetry points in the Brillouin zone
points = ibz_points['fcc']
G = points['Gamma']
X = points['X']
W = points['W']
K = points['K']
L = points['L']
U = points['U']

point_names = ['$\Gamma$', 'X', 'U', 'L', '$\Gamma$', 'K']
path = [G, X, U, L, G, K]
path_kc, q, Q = bandpath(path, atoms.cell, 100)
omega_kn = 1000 * ph.band_structure(path_kc)

# DOS
omega_e, dos_e = ph.dos(kpts=(50, 50, 50), npts=5000, delta=1e-4)
omega_e *= 1000

# Plot phonon dispersion
plt.figure(1, (8, 6))
plt.axes([.1, .07, .67, .85])
for n in range(len(omega_kn[0])):
    omega_n = omega_kn[:, n]
    plt.plot(q, omega_n, 'k-', lw=2)

plt.xticks(Q, point_names, fontsize=18)
plt.yticks(fontsize=18)
Ejemplo n.º 27
0
    evbm = np.max(eigval[eigval < efermi])

    calc.set(
        nbands=8,  # 4 occupied and 4 unoccupied bands
        fixdensity=True,
        eigensolver=CG(niter=5),
        symmetry='off',
        kpts={
            'path': 'WGKL',
            'npoints': 20
        },
        convergence={'bands': 'all'},
    )
    calc.get_potential_energy()

    path = bandpath('WGKL', atoms.get_cell(), npoints=20)
    bs_dft = get_band_structure(atoms=atoms,
                                calc=calc,
                                path=path,
                                reference=evbm)
    write_json('bs_dft.json', bs_dft)

bs_dft = read_json('bs_dft.json')
bs_dft.plot(filename='bs_dft.png',
            show=False,
            emax=bs_dft.reference + 10,
            emin=bs_dft.reference - 20)

dpbs = DftbPlusBandStructure(Hamiltonian_SCC='Yes',
                             Hamiltonian_OrbitalResolvedSCC='No',
                             Hamiltonian_MaxAngularMomentum_='',
Ejemplo n.º 28
0
from __future__ import print_function
from ase.dft.kpoints import ibz_points, bandpath
from ase.parallel import paropen
from gpaw import GPAW

layer = GPAW('Fe_gs.gpw', txt=None).atoms

points = ibz_points['bcc']
G = points['Gamma']
H = points['H']
P = points['P']
N = points['N']
H_z = [H[0], -H[1], -H[2]]
G_yz = [2 * H[0], 0.0, 0.0]

kpts, x, X = bandpath([G, H, G_yz], layer.cell, npoints=1000)
calc = GPAW('Fe_gs.gpw',
            kpts=kpts,
            fixdensity=True,
            symmetry='off',
            txt='Fe_bands.txt',
            parallel={'band': 1})
calc.get_potential_energy()

calc.write('Fe_bands.gpw')

f = paropen('Fe_kpath.dat', 'w')
for k in x:
    print(k, file=f)
f.close()
Ejemplo n.º 29
0
    txt=datapath + 'graphene_bilayer_sc_' + str(RRA) + '.txt',
    parallel=dict(
        band=2,  # band parallelization
        augment_grids=True,  # use all cores for XC/Poisson
        sl_auto=True)  # enable parallel ScaLAPACK
)

grap_bilayer.calc = calc
en1 = grap_bilayer.get_potential_energy()
parprint('Finished self-consistent calculation.')
calc.write(datapath + 'graphene_bilayer_sc_' + str(RRA) + '.gpw')

# Build path in BZ for bandstructure calculation.
# Temporarily change the cell height to workaround an ASE problem.
super_cell[2][2] = v_norm
path = bandpath('MKG', super_cell, 50)
kpts = path.kpts
super_cell[2][2] = vacuum

# Compute band path with a sequential approach, one kpt at a time,
#  to use less memory.
parprint('Calculation on', len(kpts), 'k points:')
ref, energies = [], []
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',
Ejemplo n.º 30
0
from __future__ import print_function
from ase.dft.kpoints import bandpath
from ase.io import read
from ase.parallel import paropen
from gpaw import GPAW

a = read('gs_Bi2Se3.gpw')

G = [0.0, 0.0, 0.0]
L = [0.5, 0.0, 0.0]
F = [0.5, 0.5, 0.0]
Z = [0.5, 0.5, 0.5]
kpts, x, X = bandpath([G, Z, F, G, L], a.cell, npoints=200)

calc = GPAW('gs_Bi2Se3.gpw',
            kpts=kpts,
            symmetry='off',
            parallel={'band': 16},
            txt='Bi2Se3_bands.txt')
calc.diagonalize_full_hamiltonian(nbands=48, scalapack=(4, 4, 32))

calc.write('Bi2Se3_bands.gpw', mode='all')

with paropen('kpath.dat', 'w') as f:
    for k in x:
        print(k, file=f)

with paropen('highsym.dat', 'w') as f:
    for k in X:
        print(k, file=f)
Ejemplo n.º 31
0
calc = GPAW(mode='pw', #changed from LCAO with dbz basis set
            xc='PBE',
            kpts=(4, 4, 1),
            occupations=FermiDirac(0.01),
            txt='gs_3x3_defect.txt')

structure.set_calculator(calc)
structure.get_potential_energy()
calc.write('gs_3x3_defect.gpw', 'all')


a = 3.184
PC = mx2(a=a).get_cell(complete=True)
path = [special_points['hexagonal'][k] for k in 'MKG']
kpts, x, X = bandpath(path, PC, 48)
    
M = [[3, 0, 0], [0, 3, 0], [0, 0, 1]]

Kpts = []
for k in kpts:
    K = find_K_from_k(k, M)[0]
    Kpts.append(K)

calc_bands = GPAW('gs_3x3_defect.gpw',
                  fixdensity=True,
                  kpts=Kpts,
                  symmetry='off',
                  nbands=220,
                  convergence={'bands': 200})
Ejemplo n.º 32
0
# Creates: Pt_bands.png
import numpy as np
import matplotlib.pyplot as plt
from gpaw import GPAW
from ase.dft.kpoints import bandpath
from gpaw.spinorbit import get_spinorbit_eigenvalues

calc = GPAW('Pt_bands.gpw', txt=None)
ef = GPAW('Pt_gs.gpw').get_fermi_level()

kpts, x, X = bandpath('GXWLGKX', calc.atoms.cell, npoints=200)

e_kn = np.array([
    calc.get_eigenvalues(kpt=k)[:20]
    for k in range(len(calc.get_ibz_k_points()))
])
e_nk = e_kn.T
e_nk -= ef

for e_k in e_nk:
    plt.plot(x, e_k, '--', c='0.5')

e_mk = get_spinorbit_eigenvalues(calc)
e_mk -= ef

plt.xticks(X, [r'$\Gamma$', 'X', 'W', 'L', r'$\Gamma$', 'K', 'X'], size=20)
plt.yticks(size=20)
for i in range(len(X))[1:-1]:
    plt.plot(2 * [X[i]], [-11, 13], c='0.5', linewidth=0.5)

for e_k in e_mk[::2]:
Ejemplo n.º 33
0
# Read forces and assemble the dynamical matrix
ph.read()

# High-symmetry points in the Brillouin zone
points = ibz_points['bcc']
G = points['Gamma']
H = points['H']
N = points['N']
P = points['P']

point_names = ['$\Gamma$', 'H', 'P', '$\Gamma$', 'N']
path = [G, H, P, G, N]

# Band structure in meV
path_kc, q, Q = bandpath(path, atoms.cell, 100)
omega_kn = 1000 * ph.band_structure(path_kc)

# Calculate phonon DOS
omega_e, dos_e = ph.dos(kpts=(50, 50, 50), npts=5000, delta=5e-4)
omega_e *= 1000
save_atoms(atoms, q, Q, omega_kn, point_names, dos_e, omega_e)
# Plot the band structure and DOS
# import matplotlib.pyplot as plt
# plt.figure(1, (8, 6))
# plt.axes([.1, .07, .67, .85])
# for n in range(len(omega_kn[0])):
#     omega_n = omega_kn[:, n]
#     plt.plot(q, omega_n, 'k-', lw=2)
#
# plt.xticks(Q, point_names, fontsize=18)