Ejemplo n.º 1
0
def standardize_poscar(ibrav, spg, poscar='POSCAR'):
    struct = parse.parse_poscar(poscar)
    if abs(ibrav) == 9 and spg.split()[0] == "A":
        sc = np.matrix(([[0, 1, 0], [0, 0, 1], [1, 0, 0]]), float)
    elif ibrav == 13 and latt['beta'] != 90:
        sc = np.matrix(([[1, 0, 0], [0, 0, 1], [0, -1, 0]]), float)
    else:
        sc = np.matrix(([1, 0, 0], [0, 1, 0], [0, 0, 1]), float)
    struct_std = struct.build_supercell(sc)
    write.write_poscar_head(1,
                            struct_std._cell,
                            system='standardized poscar',
                            filename='POSCAR_standardized')
    write.write_poscar_atoms(struct_std, filename='POSCAR_standardized')
Ejemplo n.º 2
0
 def _get_kpts(self):
     try:
         import parse
         struct = parse.parse_poscar('POSCAR')
     except:
         struct = parse_outcar_struct()
     get_kpt = os.popen('grep k-point PROCAR').readlines()[1:self._nkpt + 1]
     kpt = np.matrix([[
         float(item.split()[3]),
         float(item.split()[4]),
         float(item.split()[5])
     ] for item in get_kpt])
     rec_cell = struct._reciprocal_cell()
     kpt = np.matrix(kpt, float) * rec_cell
     return kpt
#!/usr/bin/python

#===========================================================================#
#                                                                           #
#  File:       v2openmx.py                                                  #
#  Dependence: parse.py,write.py                                            #
#  Usage:      convert the POSCAR file to the dat file for openmx           #
#  Author:     Shunhong Zhang <*****@*****.**>               #
#  Date:       Apr 21, 2017                                                 #
#                                                                           #
#===========================================================================#

import os
import parse
import argparse
import write

if __name__ == '__main__':
    desc_str = 'convert the POSCAR to the dat file for OPENMX'
    parser = argparse.ArgumentParser(prog='readdos.py', description=desc_str)
    parser.add_argument('--prefix',
                        type=str,
                        default='system',
                        help='the prefix for the input file')
    args = parser.parse_args()

    datapath = os.popen('locate DFT_DATA13').readlines()[0].rstrip('\n')
    print 'find DATA.PATH: ', datapath, '\nplease confirm that the PAO and VPS files are in this directory!\n'
    struct = parse.parse_poscar('POSCAR')
    write.write_openmx_dat(args.prefix, struct, datapath)
Ejemplo n.º 4
0
                        default=".pbe-mt_fhi.UPF",
                        help="type of pseudopotentail")
    parser.add_argument('--kmesh',
                        type=str,
                        default="5 5 5",
                        help='k point mesh using the Monkhorst Pack scheme')
    parser.add_argument('--kshift',
                        type=str,
                        default="0 0 0",
                        help='k point mesh shift from the Gamma point')
    args = parser.parse_args()
    print colored(Note, 'blue')
    print colored(Usage, 'blue')
    print colored(Alert, "red")

    struct = parse.parse_poscar(args.poscar)
    spg, spg_no = struct._find_symmetry()
    ibrav, brav, center = struct._get_ibrav()
    print "space group:", spg, ", No.", spg_no, ", Lattice type:", brav, center

    print colored(crystal_structure.def_ibrav, 'green')
    print colored("ibrav=", "red"), ibrav
    print colored(
        "Please be cautious with the space group and ibrav found by this code if you are dealing with the following systems",
        'red')
    print colored(
        "Low dimensional materials: The periodicity in the vacuum direction(s) are inrealistic, so the 'spacegroup' may be wrong.",
        "green")
    print colored(
        "Magnetic materials: The spin polarization may adds extra properties to the atoms, so the magnetic unit cell may differs from the chemical primitive cell.",
        "green")
Ejemplo n.º 5
0
def main():
    desc_str = 'Unfold bands calculated by VASP. For this, phase '\
               'information needs to be present in the PROCAR file '\
               'which means that bands need to be calculated with '\
               'the option LORBIT=12 specified in the INCAR file. '\
               'The required input consists of POSCAR file, PROCAR '\
               'file and a set of up to three fractional translations. '\
               'There is no need to specify all translations, just the '\
               'generators. The programs will generate all distinct '\
               'translations from the generators and generate all irreps. '\
               'NOTE: In cas of non-collinear spin-polarized calculations ' \
               'mx, my and mz components of orbital weights are not ' \
               'unfolded, only spin up and spin down totals.'
               
               
    parser = argparse.ArgumentParser(prog='vasp_unfold', description = desc_str)

    parser.add_argument('poscar', type=str, help='POSCAR file')     
    parser.add_argument('procar', type=str, help='PROCAR file')

    parser.add_argument('--tgen', type=translation, action='append',
                        metavar='SX,SY,SZ', help='Fractional translation '
                        'generator. No whitespaces are allowed between the '
                        'components! SX, SY and SZ can be either 0 or 1/n, '
                        'where n is an integer. Up to three linearly '
                        'independant generators can be specified.')

    parser.add_argument('--out', type=str, help='Output filename. If left '
                        'unspecified  output is writen to PROCAR.irrep.n '
                        'where PROCAR is location of the input PROCAR file. '
                        'If specified, output is written to OUT.irrep.n.')
    
    parser.add_argument('--eps', type=float, default=1e-6, help='Numerical '
                        'precision. When building permutation representation '
                        'of the fractional translations this parameter is used '
                        'to determine whether two fractional positions are '
                        'identical. For irregular structures, it may need to '
                        'be increased. If this does not help, try to tweak '
                        'the atomic positions in POSCAR to make the structure '
                        'more regular. Default is 1e-6.')
    
    parser.add_argument('--all-irreps', default=False, action='store_true',
                        help='Flag specifying that all irreps from the unfolding '
                        'will be written to the output. By default, only irrep 0 '
                        '(unit irrep) is written out.')
                        
    parser.add_argument('--check-mapping', action='store_true', default=False,
                        help='Specifies to check if supplied translation '
                        'generators generate fractional translations which are '
                        'one-to-one, ie. map every atom on exactly one other atom '
                        'in the unit cell. This MUST not be enabled for the cases '
                        'where vacancies or excess atoms are present.')
                                                                     
    args = parser.parse_args()
    
    tgens = args.tgen
    
    trans, irreps = build_translations(tgens)
    
    try:
        cell, spos, symbols = parse_poscar(args.poscar)
    except:
        post_error('Unable to parse the input POSCAR file. Please '
            'check if the file exists and is formatted properly')
    
    ops = build_operators(spos, trans, args.check_mapping, args.eps)
    
    try:
        data = parse_procar(args.procar)
    except:
        post_error(errors.poscar_parse_error)
    
    if data[-1] is None:
        post_error('Phase information has to be present in the PROCAR '
            'file. Please repeat the calculation with LORBIT=12.')

    phases = np.copy(data[-1])
    
    norbs = phases.shape[1]/len(spos)
    
    projs = build_projectors(irreps, ops, norbs)
    
    if args.out is None:
        output = args.procar
    else:
        output = args.out
    
    if args.all_irreps:
        nirrep = len(projs)
    else:
        nirrep = 1
        
    for i, p in enumerate(projs[:nirrep]):
        for s in xrange(data[-1].shape[-1]):
            try:
                data[-1][:,:,:,s] = np.dot(p, phases[:,:,:,s]).swapaxes(0, 1)
            except:
                post_error('Unable to apply projectors. Are you sure '
                    'that specified POSCAR and PROCAR file belong to '
                    'the same crystal structure?')
        
        # We update total absolute weights to correspond to
        # unfolded phases (by multiplying them by the magnitude
        # ratio of unfolded and folded phases 
        phase_ratio = np.abs(data[-1])/(np.abs(phases)+1e-4)
        
        for idim in xrange(data[-2].shape[3]):
            data[-2][:,:,:,idim,:] *= phase_ratio

        write_procar('{0}.irrep.{1}'.format(output, i), *data)
Ejemplo n.º 6
0
    def _plot_kpdos(self, args):
        import matplotlib
        matplotlib.use('Agg')
        import matplotlib.pyplot as plot
        import matplotlib.patches as mpatches
        import matplotlib.gridspec as gridspec

        try:
            import parse
            struct = parse.parse_poscar('POSCAR')
        except:
            struct = parse_outcar_struct()
        dk = [
            np.linalg.norm(self._kpt_cart[ikpt] - self._kpt_cart[ikpt - 1])
            for ikpt in range(1, len(self._kpt))
        ]
        path = np.concatenate(
            ([0], [np.cumsum(dk)[i] for i in range(len(np.cumsum(dk)))]),
            axis=0)
        xsym = [path[0]] + [x for n, x in enumerate(path) if x in path[:n]
                            ] + [path[-1]]
        xticks, xlabels = refine_xsym_xlabels(xsym, args.label_k.split(),
                                              args.xlabel_thr)
        print '\n---------high symmetry k points-----------\n'
        print '{0:13s} {1:12s}'.format('xticks'.center(13),
                                       'xlabels'.center(20))
        print '\n'.join([
            '{0:12.6f} {1:20s}'.format(tick,
                                       label.strip('$').center(20))
            for tick, label in zip(xticks, xlabels)
        ])
        print '\n---------high symmetry k points-----------\n'
        print 'plot kpdos, proj_type=', args.proj_type, ', proj_index=', args.proj_index
        if args.shift_fermi == True:
            self._energy += -self._efermi

        projections = args.proj_index.split(',')
        for proj in projections:
            if '_d' in proj or '_p' in proj:
                idx = projections.index(proj)
                head = proj.split('_')[0]
                projections.remove(proj)
                if '_p' in proj:
                    for i in range(1, 4):
                        projections.insert(idx + i - 1, head + '_' + str(i))
                if '_d' in proj:
                    for i in range(4, 9):
                        projections.insert(idx + i - 4, head + '_' + str(i))

        cc = np.concatenate((np.array([0]), np.cumsum(struct._counts)), axis=0)
        if args.proj_type == 'species':
            #print [int(ispec) for ispec in args.proj_index.split(',')]
            #print [[iat for iat in range(cc[int(ispec)],cc[int(ispec)+1])] for ispec in args.proj_index.split(',')]
            weights_list = [
                sum([
                    self._get_kpdos(iat)
                    for iat in range(cc[int(ispec)], cc[int(ispec) + 1])
                ]) for ispec in args.proj_index.split(',')
            ]
            legend_list = [
                struct._symbols[cc[int(ispec)]]
                for ispec in args.proj_index.split(',')
            ]
        elif args.proj_type == 'atom':
            weights_list = [
                self._get_kpdos(int(iat)) for iat in args.proj_index.split(',')
            ]
            legend_list = [
                struct._symbols[int(iat)] + str(
                    filter(lambda x: x >= 0, [int(iat) - ic
                                              for ic in cc])[-1] + 1)
                for iat in args.proj_index.split(',')
            ]
        elif args.proj_type == 'atom_subshell':

            def start_orb(isubshell):
                if isubshell == 's': return 0
                if isubshell == 'p': return 1
                if isubshell == 'd': return 4

            def last_orb(isubshell):
                if isubshell == 's': return 0
                if isubshell == 'p': return 3
                if isubshell == 'd': return 8

            at_list = [
                int(projection.split("_")[0]) for projection in projections
            ]
            subshell_list = [
                int(projection.split("_")[1]) for projection in projections
            ]
            weights_list = [
                sum(self._get_kpdos_orb(
                    int(iat))[start_orb(isubshell):last_orb(isubshell) + 1],
                    axis=3) for iat, isubshell in zip(at_list, subshell_list)
            ]
            legend_list = [
                struct._symbols[int(iat)] + str(
                    filter(lambda x: x >= 0, [int(iat) - ic
                                              for ic in cc])[-1] + 1) +
                isubshell for iat, isubshell in zip(at_list, subshell_list)
            ]
        elif args.proj_type == 'orbital':
            at_list = [
                int(projection.split('_')[0]) for projection in projections
            ]
            orb_list = [
                int(projection.split('_')[1]) for projection in projections
            ]
            weights_list = [
                self._get_kpdos_orb(iat)[:, :, :, iorb]
                for iat, iorb in zip(at_list, orb_list)
            ]
            legend_list = [
                struct._symbols[iat] + str(iat) + '_$' + orb_dic[iorb] + '$'
                for iat, iorb in zip(at_list, orb_list)
            ]
        elif args.proj_type == 'species_orbital':
            cc = np.concatenate((np.array([0]), np.cumsum(struct._counts)),
                                axis=0)
            spec_list = [
                int(projection.split("_")[0]) for projection in projections
            ]
            orb_list = [
                int(projection.split("_")[1]) for projection in projections
            ]
            weights_list = [
                sum([
                    self._get_kpdos_orb(iat)[:, :, :, iorb]
                    for iat in range(cc[int(ispec)], cc[int(ispec) + 1])
                ]) for ispec, iorb in zip(spec_list, orb_list)
            ]
            legend_list = [
                struct._species[ispec] + '_$' + orb_dic[iorb] + '$'
                for ispec, iorb in zip(spec_list, orb_list)
            ]
        elif args.proj_type == 'None':
            plot_band(args,
                      path,
                      self._energy,
                      xsym,
                      label_k=None,
                      output='band_structure')
            exit('band structure without weights plotted')

        def plot_color_band(ax, ispin, weights_list, legend_list, args):
            color_patch = []
            fw = open('kpdos.dat', 'w')
            for icolor, (weights,
                         legend) in enumerate(zip(weights_list, legend_list)):
                print '{0:20s}, spin {1}'.format(
                    legend,
                    spin_dic[ispin]), ', nspin,nkpt,nband=', weights.shape
                if args.pow != 1: weights = np.power(weights, args.pow)
                for bi, wi in zip(self._energy[ispin, :, :].T,
                                  weights[ispin, :, :].T):
                    print >> fw, '\n'.join(
                        '{0:10.7f} {1:10.7f} {2:10.7f}'.format(
                            path[ikpt], bi[ikpt], wi[ikpt])
                        for ikpt in range(self._nkpt, self._startk))
                    scolor = args.color.split()[icolor]
                    if args.spin_color:
                        scolor = args.color.split()[icolor * 2 + ispin]
                    ax.scatter(path,
                               bi,
                               s=args.markersize * wi,
                               marker=args.marker,
                               facecolor='none',
                               edgecolor=scolor,
                               lw=args.linewidth,
                               alpha=0.7)
                color_patch.append(mpatches.Patch(color=scolor, label=legend))

            fw.close()
            ax.set_xticks(xticks)
            if args.yticks:
                ax.set_yticks(args.yticks)
            [
                ax.plot([xi, xi], [args.elim[0], args.elim[1]],
                        color='gray',
                        zorder=-1) for xi in xsym
            ]
            ax.set_xticklabels(['$' + ilabel + '$' for ilabel in xlabels],
                               fontsize=args.label_fontsize,
                               visible=(args.nplot[0] == 1
                                        or (not args.merge_spin
                                            or not (self._nspin - ispin - 1))))
            ax.plot([np.min(path), np.max(path)],
                    [(args.shift_fermi == False) * self._efermi,
                     (args.shift_fermi == False) * self._efermi],
                    ls='--',
                    color='grey',
                    zorder=-1)
            ax.set_xlim(np.min(path), np.max(path))
            ax.set_ylim(args.elim)
            ax.tick_params(top='off', right='off', direction='out')
            if args.yticks:
                ax.set_yticks(args.yticks)
            [
                label.set_fontsize(args.label_fontsize)
                for label in ax.get_yticklabels()
            ]
            ax.get_yaxis().set_tick_params(direction='out')
            ax.get_xaxis().set_tick_params(length=0.0)
            #ax.set_ylabel(args.ylabel,fontsize=14,visible=not args.merge_spin)
            if args.subtitles:
                ax.set_title(args.subtitles.split(',')[ispin])
            return color_patch

        if args.legend_content:
            legend_list = [item for item in args.legend_content.split(',')]

        if args.merge_spin == False or self._nspin == 1:
            print 'plot each spin band in a single file'
            for ispin in range(self._nspin):
                fig = plot.figure(figsize=args.figsize)
                ax = fig.add_subplot(111)
                color_patch = plot_color_band(ax, ispin, weights_list,
                                              legend_list, args)
                if args.legend_switch == 'on':
                    plot.legend(bbox_to_anchor=(args.legend_pos),
                                handles=[item for item in color_patch],
                                prop={'size': args.legend_fontsize})
                ax.set_ylabel(args.ylabel, fontsize=args.label_fontsize)
                output = args.proj_type + '_projected_bands'
                if self._nspin > 1:
                    output = output + '_{0}'.format(spin_dic[ispin])
                plot.tight_layout(pad=0.7, w_pad=1.5, h_pad=1.2)
                plot.savefig(output, dpi=args.dpi, bbox_inches='tight')
        elif args.merge_spin == True and self._nspin > 1:
            print 'merge spin bands in one plot'
            fig = plot.figure(figsize=args.figsize)
            nrow, ncol = args.nplot
            gs = gridspec.GridSpec(
                nrow,
                ncol,
                height_ratios=[item for item in args.hratio],
                width_ratios=[item for item in args.wratio])
            ax = []
            for ispin in range(self._nspin):
                if nrow == 1 and ispin > 0:
                    ax.append(fig.add_subplot(gs[ispin], sharey=ax[0]))
                else:
                    ax.append(fig.add_subplot(gs[ispin]))
                color_patch = plot_color_band(ax[ispin], ispin, weights_list,
                                              legend_list, args)
                ax[ispin].set_ylim(args.elim[0], args.elim[1])
            ax[0].set_ylabel(args.ylabel)
            for label in ax[1].get_yticklabels():
                label.set_visible(args.nplot[0] != 1)

            #if nrow>1:
            #   plot.text(args.ylabel_pos[0],args.ylabel_pos[1],args.ylabel,fontsize=14,ha='center',va='center',rotation='vertical')
            if args.legend_switch == 'on':
                plot.legend(bbox_to_anchor=(args.legend_pos),
                            handles=[item for item in color_patch],
                            prop={'size': args.legend_fontsize})

            output = args.proj_type + '_projected_bands'
            plot.tight_layout(pad=0.7, w_pad=1.5, h_pad=1.2)
            plot.savefig(output, dpi=args.dpi, bbox_inches='tight')
        print "Done"
            print "metallic!"


desc_str = '''Simple program used to quickly plot the orbital weights
of the band structure contained in the specified PROCAR file.
'''

parser = argparse.ArgumentParser(prog='plotprocar', description=desc_str)

arguments.add_io_arguments(parser)
arguments.add_fig_arguments(parser)
arguments.add_plot_arguments(parser)

args = parser.parse_args()

struct = parse.parse_poscar(args.poscar)
orbitals, kpt, kweights, energy, occupancies, weights, phases = parse.parse_procar(
    args.procar)
kpt = np.matrix(kpt)
kpt = kpt * struct._reciprocal_cell()

nspin = int(os.popen('grep ISPIN OUTCAR').readline().split()[2])
if os.popen('grep LNONCOLLINEAR OUTCAR').readline().split()[2] == 'T':
    print 'noncollinear spin polarized calculations'
    nspin = 2
nelect = float(os.popen('grep NELECT OUTCAR').readline().split()[2])
nelect = int(nelect)
print 'energy.shape:', energy.shape
print 'weights.shape:', weights.shape
#get_bandgap(nspin,energy,nelect)
Ejemplo n.º 8
0
      write.write_band(path,segment_nkpt,energy,nelect)
      write.write_specified_band(kpt,kweight,path,energy,nelect)
   else:
      print "K points specified explicitly in the KPINTS file"
      kp_mode="specified"
      write.write_specified_band(kpt_cart,kweight,path,energy,nelect)
else:
   print "Monkhort Pack k points grid"
   kp_mode='mp'
   grid=[int(item) for item in open("KPOINTS","r").readlines()[3].split()]
   #write.write_specified_band(kpt_cart,energy,nspin,nelect)
   write.write_mesh_band(kpt_cart,energy,nspin,nelect,grid,isoenergy=-0.7)


if kp_mode=='line':
   struct=parse.parse_poscar()
   ibrav,brav,center=struct._get_ibrav()
   label_k = bzkpt.get_label_k(4,kpt)
   print label_k
   struct._is_slab()
   xplot.plot_band(args,path,energy,xsym)
elif kp_mode == 'specified':
   for ikpt in range(nkpt):
       if kweight[ikpt]!=0:
          ikpt+=1
       else:
          start_kpt=ikpt
          break
   path = bzkpt.get_path(kpt_cart)
   xsym = bzkpt.guess_xsym(path)
   kpt=kpt[start_kpt:,:]