Ejemplo n.º 1
0
def get_xrd():
    struct = readstructure()
    xrd = XRDCalculator()

    #    xrd_data=xrd.get_xrd_pattern(struct)
    xrd_data = xrd.get_pattern(struct)
    jxrd_data = jsanitize(xrd_data.as_dict())
    fname = 'XRD.json'
    proc_str = "Saving data to " + fname + " File ..."
    procs(proc_str, 1, sp='-->>')
    json_store(jxrd_data, fname)

    data = np.vstack((xrd_data.x, xrd_data.y)).T

    margin = 10.
    ds = xrd_data.x[0] - margin
    de = xrd_data.x[-1] + margin
    tmp_data = [ds] + xrd_data.x.tolist() + [de]
    tmp_data1 = np.diff(tmp_data).tolist()
    tmp_data2 = np.array([0] + np.cumsum(tmp_data1).tolist())
    tmp_data3 = tmp_data2 / tmp_data2[-1]
    x_data = np.linspace(ds, de, 10000)
    y_data = np.zeros((len(x_data)))
    for i in range(1, len(tmp_data3) - 1):
        index = int(tmp_data3[i] * 10000)
        y_data[index] = xrd_data.y[i - 1]

    data = np.vstack((x_data, y_data))
    data = (smear(data, sigma=0.1)).T

    head_line = "#%(key1)+12s %(key2)+12s" % {
        'key1': '2theta',
        'key2': 'Intensity'
    }
    fname = 'XRD.dat'
    proc_str = "Saving data to " + fname + " File ..."
    procs(proc_str, 2, sp='-->>')
    write_col_data(fname, data, head_line)

    check_matplotlib()
    fname = 'XRD.png'
    proc_str = "Saving plot to " + fname + " File ..."
    procs(proc_str, 3, sp='-->>')
    plt = xrd.get_plot(struct)
    plt.savefig(fname, format='png')
Ejemplo n.º 2
0
def twoD_operation():
    #sepline(ch='2D structure operation',sp='=')
    print('your choice ?')
    print('{} >>> {}'.format('1', 'build rippled structure'))
    print('{} >>> {}'.format('2', 'build multi-layered structure'))
    print('{} >>> {}'.format('3', 'split multi-layered structure'))
    print('{} >>> {}'.format('4', 'resize vacuum layer'))
    print('{} >>> {}'.format('5', 'center atomic-layer along z direction'))
    print('{} >>> {}'.format('6', 'apply strain along different direction'))
    print('{} >>> {}'.format('7', 'constrain atom in specific range'))
    print('{} >>> {}'.format('8',
                             'get a substrate for 2D material (online!!!)'))
    wait_sep()

    in_str = ""
    while in_str == "":
        in_str = input().strip()

    choice = int(in_str)
    if choice == 1:
        struct = readstructure()
        margin_dist = 1.0  #
        assert (struct.lattice.is_orthogonal)
        print("input the supercell scaling factor")
        print('for x direction can be: 10 1 1')
        print('for y direction can be: 1 10 1')
        wait_sep()
        scale_str = input()
        scaling = [int(x) for x in scale_str.split()]
        if (len(scaling) != 3):
            print('unknow format')
        else:
            if scaling[0] >= scaling[1]:
                direction = 0  # for x direction
            else:
                direction = 1  # for y direction
        print("input the strain range")
        print("example: 0.02:0.1:10 ")
        wait_sep()
        strain_str = input()
        tmp = [float(x) for x in strain_str.split(":")]
        strain = []
        if len(tmp) == 3:
            strain_range = np.linspace(tmp[0], tmp[1], int(tmp[2]))
        #     print(strain_range)
        else:
            print("unknow format")
            return
        print("input the index of atom need to be fixed")
        print("example: 1 10 11 20 ")
        print("0 means fix the atom automatically")
        wait_sep()
        atom_index_str = input()
        try:
            atom_index = [int(x) for x in strain_str.split("")]
            auto_fix = False
        except:
            atom_index = [int(atom_index_str)]
            auto_fix = True

        struct_sc = struct.copy()
        struct_sc.make_supercell(scaling)
        natom = struct_sc.num_sites
        min_z = np.min(struct_sc.cart_coords[:, 2])
        tmp_coords = np.ones((struct_sc.num_sites, 1)) * min_z
        cart_coords = struct_sc.cart_coords
        cart_coords[:, 2] = cart_coords[:, 2] - tmp_coords.T + 0.01
        frac_coords_new = np.dot(cart_coords,
                                 np.linalg.inv(struct_sc.lattice.matrix))
        for i_strain in strain_range:
            new_lat_matrix = struct_sc.lattice.matrix
            new_lat_matrix[direction, direction] = struct_sc.lattice.matrix[
                direction, direction] * (1 - i_strain)
            fname = "%10.5f" % (
                i_strain
            ) + '_wo.vasp'  # structure only applied with in-plan strain
            struct_wo_ripple = Structure(new_lat_matrix, struct_sc.species,
                                         frac_coords_new)
            struct_wo_ripple.to(filename=fname.strip(), fmt='poscar')
            frac_coords_new_cp = struct_wo_ripple.frac_coords.copy()
            cart_coords_new_cp = struct_wo_ripple.cart_coords.copy()
            nz = 0
            selective_dynamics = [[True for col in range(3)]
                                  for row in range(natom)]
            z_shift = np.zeros((natom, 3))
            for i_atom in range(natom):
                z_shift[i_atom,
                        2] = 40 * (2 * i_strain - 10 * i_strain**2) * np.sin(
                            cart_coords_new_cp[i_atom, direction] * np.pi /
                            new_lat_matrix[direction, direction])
                if cart_coords_new_cp[i_atom,
                                      direction] < nz or cart_coords_new_cp[
                                          i_atom, direction] > new_lat_matrix[
                                              direction, direction] - nz:
                    z_shift[i_atom, 2] = 0.0

                if auto_fix:
                    if struct_wo_ripple[i_atom].coords[direction]<margin_dist or \
                       struct_wo_ripple[i_atom].coords[direction] > new_lat_matrix[direction,direction]-margin_dist:
                        selective_dynamics[i_atom] = [False, False, False]
                else:
                    if i_atom in atom_index:
                        selective_dynamics[i_atom] = [False, False, False]

            struct_w_ripple=Structure(new_lat_matrix,struct_sc.species,cart_coords_new_cp+z_shift,coords_are_cartesian=True,\
                                     site_properties={'selective_dynamics':selective_dynamics})
            fname = "%10.5f" % (
                i_strain
            ) + '_w.vasp'  # structure  applied with in-plan strain  and ripple
            struct_w_ripple.to(filename=fname.strip(), fmt='poscar')
    elif choice == 2:
        struct = readstructure()
        print("input the number of layers")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        layer_number = int(in_str)

        print("input the layer distance")
        wait_sep()
        species = []
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        layer_distance = float(in_str)

        new_struct = move_to_zcenter(struct)
        struct_thickness = np.max(new_struct.cart_coords[:, 2]) - np.min(
            new_struct.cart_coords[:, 2])
        natom = new_struct.num_sites
        new_cart_coords = np.zeros((natom * layer_number, 3))
        for i in range(layer_number):
            new_cart_coords[i * natom:(i + 1) * natom,
                            0:2] = new_struct.cart_coords[:, 0:2]
            new_cart_coords[i * natom:(i + 1) * natom,
                            2] = new_struct.cart_coords[:, 2] + i * (
                                layer_distance + struct_thickness)
            species.extend(new_struct.species)
        new_lat = new_struct.lattice.matrix
        new_lat[2, 2] = new_lat[2, 2] + layer_distance * layer_number
        tmp_struct = Structure(new_lat,
                               species,
                               new_cart_coords,
                               coords_are_cartesian=True)
        tmp1_struct = move_to_zcenter(tmp_struct)
        tmp2_struct = tmp1_struct.get_sorted_structure()
        tmp2_struct.to(filename='layer_' + str(layer_number) + '.vasp',
                       fmt='poscar')

    elif choice == 3:
        ProperDist = 3.5  # Ang
        struct = readstructure()
        (atom_index, in_str) = atom_selection(struct)
        print("input the splitting distance, 10 Ang is enough!")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        SplitDistance = float(in_str)
        print("numbers of splitting site, 50 sites are enough!")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        NumberSplitSite = int(in_str)
        DensityN = int(NumberSplitSite * 0.75)
        SparseN = NumberSplitSite - DensityN + 1
        #        print(DensityN,SparseN)
        dist = ProperDist / (DensityN - 1)
        SplitDistanceArray = np.zeros(NumberSplitSite + 1)
        for Nsite in range(DensityN):
            SplitDistanceArray[Nsite] = (Nsite) * dist

        dist = (SplitDistance - ProperDist) / SparseN
        for Nsite in range(SparseN):
            SplitDistanceArray[Nsite +
                               DensityN] = ProperDist + (Nsite + 1) * dist


#        print(SplitDistanceArray)
        coords = struct.cart_coords
        for Nsite in range(NumberSplitSite + 1):
            coords = struct.cart_coords
            for atom in atom_index:
                coords[atom, 2] = coords[atom, 2] + SplitDistanceArray[Nsite]
            tmp_struct = Structure(struct.lattice,
                                   struct.species,
                                   coords,
                                   coords_are_cartesian=True)
            fname = str(Nsite) + '.vasp'
            tmp_struct.to(filename=fname, fmt='poscar')
        data = np.zeros((NumberSplitSite + 1, 2))
        for i, j in enumerate(SplitDistanceArray):
            data[i][0] = i
            data[i][1] = j
        head_line = "#%(key1)+12s  %(key2)+12s" % {
            'key1': 'index',
            'key2': 'distance/Ang'
        }
        fmt = "%12d %12.6f" + '\n'
        write_col_data('split.dat', data, head_line, sp_fmt=fmt)
        return

    elif choice == 4:
        struct = readstructure()
        new_struct = move_to_zcenter(struct)
        struct_thickness = np.max(new_struct.cart_coords[:, 2]) - np.min(
            new_struct.cart_coords[:, 2])
        vac_layer_thickness = new_struct.lattice.c - struct_thickness
        print("current vacuum layer thickness is %6.3f Ang" %
              (vac_layer_thickness))
        print("input the new value of vacuum layer thickness")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        nvac_layer_thickness = float(in_str)

        assert (nvac_layer_thickness > struct_thickness)
        new_lat = new_struct.lattice.matrix
        new_lat[2, 2] = nvac_layer_thickness
        tmp_struct = Structure(new_lat,
                               new_struct.species,
                               new_struct.cart_coords,
                               coords_are_cartesian=True)
        center_struct = move_to_zcenter(tmp_struct)
        center_struct.to(filename='new_vacuum.vasp', fmt='poscar')
        return

    elif choice == 5:
        struct = readstructure()
        new_struct = move_to_zcenter(struct)
        new_struct.to(filename='z-center.vasp', fmt='poscar')
        return

    elif choice == 6:
        struct = readstructure()
        assert (struct.lattice.is_orthogonal)
        try:
            import sympy
        except:
            print("you must install sympy module")
            return

        new_struct = move_to_zcenter(struct)
        print("input the elastic of material by order : C11 C12 C22 C66")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip().split()
        elastic_constant = [float(x) for x in in_str]
        if len(elastic_constant) != 4:
            print("you must input C11 C12 C22 C66")
            return
        C11 = elastic_constant[0]
        C12 = elastic_constant[1]
        C22 = elastic_constant[2]
        C66 = elastic_constant[3]
        print("input applied force: e.x. 1.0 GPa nm")
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        sigma = float(in_str)
        orig_struct = new_struct.copy()
        new_struct = new_struct.copy()
        natom = orig_struct.num_sites
        lat = orig_struct.lattice.matrix
        pos = orig_struct.frac_coords
        nps = 37
        phi = np.linspace(0, 360, nps) * np.pi / 180
        vzz = C12 / C22
        temp_num = (C11 * C22 - C12**2) / (C22 * C66)
        d1 = C11 / C22 + 1.0 - temp_num
        d2 = -(2.0 * C12 / C22 - temp_num)
        d3 = C11 / C22
        F = sigma * C22 / (C11 * C22 - C12**2.0)
        Poisson=(vzz*(np.cos(phi))**4.0-d1*(np.cos(phi))**2.0*(np.sin(phi))**2.0+vzz*(np.sin(phi))**4.0)/\
                ((np.cos(phi))**4.0+d2*(np.cos(phi))**2.0*(np.sin(phi))**2.0+d3*(np.sin(phi))**4.0)

        eps_theta = F * ((np.cos(phi))**4 + d2 * (np.cos(phi))**2.0 *
                         (np.sin(phi))**2.0 + d3 * (np.sin(phi))**4.0)
        t = sympy.Symbol('t', real=True)
        e = sympy.Symbol('e', real=True)
        v = sympy.Symbol('v', real=True)
        eprim = sympy.Matrix([[e + 1, 0], [0, 1 - e * v]])
        R = sympy.Matrix([[sympy.cos(t), -sympy.sin(t)],
                          [sympy.sin(t), sympy.cos(t)]])
        eps_mat = R * eprim * R.adjugate()
        for k in range(len(phi)):
            cur__phi = phi[k] * 180 / np.pi
            Rot = eps_mat.subs({e: eps_theta[k], v: Poisson[k], t: phi[k]})
            fname = str(k) + '.vasp'
            final_lat = np.matrix(np.eye(3))
            final_lat[0, 0] = Rot[0, 0]
            final_lat[0, 1] = Rot[0, 1]
            final_lat[1, 0] = Rot[1, 0]
            final_lat[1, 1] = Rot[1, 1]
            lat_new = lat * final_lat
            tmp_struct = Structure(lat_new, new_struct.species, pos)
            tmp_struct.to(filename=fname, fmt='poscar')
        return

    elif choice == 7:
        struct = readstructure()
        natom = struct.num_sites
        atom_index, in_str = atom_selection(struct)
        selective_dynamics = [[True for col in range(3)]
                              for row in range(natom)]
        for i in range(natom):
            if i in atom_index:
                selective_dynamics[i] = [False, False, False]
        tmp_struct = Structure(
            struct.lattice,
            struct.species,
            struct.frac_coords,
            site_properties={'selective_dynamics': selective_dynamics})
        poscar = Poscar(tmp_struct)
        poscar.comment = poscar.comment + ' |--> ' + in_str
        poscar.write_file('Fixed.vasp')
        return

    elif choice == 8:
        print('your choice ?')
        print('{} >>> {}'.format('1', 'input 2D structure from local disk'))
        print('{} >>> {}'.format('2', 'get 2D structure online'))
        wait_sep()
        in_str = ""
        while in_str == "":
            in_str = input().strip()
        choice = int(in_str)

        if choice == 1:
            mpid = None
            struct = readstructure()
        else:
            print("input the mp-id for your structure")
            wait_sep()
            in_str = ""
            while in_str == "":
                in_str = input().strip()
            mpid = in_str
            struct = None

        film, substrates = make_connect(mpid=mpid, struct=struct)
        df = get_subs(film, substrates)
        df.to_csv('substrate.csv', sep=',', header=True, index=True)
        return
    else:
        print("unkonw choice")
        return
Ejemplo n.º 3
0
def chg_locp_average():
    chg = False
    print("which file would like to average: CHG or LOCPOT ?")
    wait_sep()
    in_str = ""
    while in_str == "":
        in_str = input().strip()
    if in_str.lower() == 'chg':
        filename = 'CHG'
        check_file(filename)
        grid_data = CHGCAR.from_file(filename)
        head_line = "#%(key1)+s %(key2)+s" % {
            'key1': 'Distance/Ang',
            'key2': 'Average Charge/(e/Ang**3)'
        }
        chg = True
    elif in_str.lower() == 'locpot':
        filename = 'LOCPOT'
        check_file(filename)
        grid_data = Locpot.from_file(filename)
        head_line = "#%(key1)+s %(key2)+s" % {
            'key1': 'Distance/Ang',
            'key2': 'Average Potential/(eV)'
        }
    else:
        print('unknown file file: ' + in_str)
        os._exit()

    step_count = 1
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    volume = grid_data.structure.volume
    print("which direction would like to average: x y or z ?")
    wait_sep()
    in_str = ""
    while in_str == "":
        in_str = input().strip().lower()
    if in_str == "x":
        selected_dir = 0
    elif in_str == 'y':
        selected_dir = 1
    elif in_str == 'z':
        selected_dir = 2
    else:
        print("Unknow Direction!")
        return

    axis_grid = grid_data.get_axis_grid(selected_dir)
    if chg:
        aver_grid = grid_data.get_average_along_axis(selected_dir) / volume
    else:
        aver_grid = grid_data.get_average_along_axis(selected_dir)

    data = np.vstack((axis_grid, aver_grid)).T

    step_count += 1
    if chg:
        filename = "average_CHG_" + in_str + '.dat'
    else:
        filename = "average_LOCPOT_" + in_str + '.dat'

    proc_str = "Writting Average Data to " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    write_col_data(filename, data, head_line)
Ejemplo n.º 4
0
def optics_analysis():

    filename = 'vasprun.xml'
    step_count = 1
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    vsr = Vasprun(filename, parse_eigen=False)
    try:
        energy = np.array(vsr.dielectric[0])
        freq = energy / H
        real = np.array(vsr.dielectric[1])
        imag = np.array(vsr.dielectric[2])
    except:
        print('extracing data failed ')
        return

    head_line="#%(key1)+12s%(key2)+12s%(key3)+12s%(key4)+12s%(key5)+12s%(key6)+12s%(key7)+12s"%\
     {'key1':'Energy','key2':'xx','key3':'yy','key4':'zz','key5':'xy','key6':'yz','key7':'zx'}
    step_count += 1
    filename = "AbsorbSpectrum.dat"
    proc_str = "Writing Data To " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    Absorb = np.zeros((len(freq), 6))
    for i in range(6):
        Absorb[:, i] = 1.4142 * freq * (np.sqrt(-real[:, i] + np.sqrt(
            imag[:, i] * imag[:, i] + real[:, i] * real[:, i]))) / (C0 * 100)
    data = np.vstack((energy, Absorb.T)).T
    write_col_data(filename, data, head_line, e_fmt=True)

    step_count += 1
    filename = "RefractiveSpectrum.dat"
    proc_str = "Writing Data To " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    Refrac = np.zeros((len(freq), 6))
    for i in range(6):
        Refrac[:, i] = (np.sqrt(real[:, i] +
                                np.sqrt(imag[:, i] * imag[:, i] +
                                        real[:, i] * real[:, i]))) / 1.4142
    data = np.vstack((energy, Refrac.T)).T
    write_col_data(filename, data, head_line, e_fmt=True)

    step_count += 1
    filename = "EnergyLossSpectrum.dat"
    proc_str = "Writing Data To " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    EnergyLoss = np.zeros((len(freq), 6))
    for i in range(6):
        EnergyLoss[:, i] = imag[:, i] / (imag[:, i] * imag[:, i] +
                                         real[:, i] * real[:, i])
    data = np.vstack((energy, EnergyLoss.T)).T
    write_col_data(filename, data, head_line, e_fmt=True)

    step_count += 1
    filename = "ExtictionSpectrum.dat"
    proc_str = "Writing Data To " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    Extic = np.zeros((len(freq), 6))
    for i in range(6):
        Extic[:, i] = (np.sqrt(-real[:, i] +
                               np.sqrt(imag[:, i] * imag[:, i] +
                                       real[:, i] * real[:, i]))) / 1.4142
    data = np.vstack((energy, Extic.T)).T
    write_col_data(filename, data, head_line, e_fmt=True)

    step_count += 1
    filename = "ReflectivitySpectrum.dat"
    proc_str = "Writing Data To " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    Reflect = np.zeros((len(freq), 6))
    for i in range(6):
        Reflect[:, i] = ((Refrac[:, i] - 1) *
                         (Refrac[:, i] - 1) + Extic[:, i] * Extic[:, i]) / (
                             (Refrac[:, i] + 1) *
                             (Refrac[:, i] + 1) + Extic[:, i] * Extic[:, i])
    data = np.vstack((energy, Reflect.T)).T
    write_col_data(filename, data, head_line, e_fmt=True)
Ejemplo n.º 5
0
def select_one_band_structure():
    check_matplotlib()
    step_count = 1
    filename = 'vasprun.xml'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    vsr = Vasprun(filename)

    step_count += 1
    filename = 'KPOINTS'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    bands = vsr.get_band_structure(filename, line_mode=True, efermi=vsr.efermi)
    nelect = vsr.parameters['NELECT']
    nbands = bands.nb_bands
    if vsr.is_spin:
        proc_str = "This Is a Spin-polarized Calculation."
        procs(proc_str, 0, sp='-->>')
        ISPIN = 2
    else:
        if vsr.parameters['LNONCOLLINEAR']:
            proc_str = "This Is a Non-Collinear Calculation."
            procs(proc_str, 0, sp='-->>')
            ISPIN = 3
        else:
            proc_str = "This Is a Non-Spin Calculation."
            procs(proc_str, 0, sp='-->>')
            ISPIN = 1
    proc_str = "Total band number is " + str(nbands)
    procs(proc_str, 0, sp='-->>')
    proc_str = "Total electron number is " + str(nelect)
    procs(proc_str, 0, sp='-->>')

    print("which band would like to select ?")
    wait_sep()
    in_str = ""
    while in_str == "":
        in_str = input().strip()
    selected_band = int(in_str)

    step_count += 1
    filename = "BAND_" + str(selected_band) + '.dat'
    proc_str = "Writting Selected Band Structure Data to " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    if ISPIN == 1 or ISPIN == 3:
        band_data = bands.bands[Spin.up][selected_band - 1] - vsr.efermi
        data = np.vstack((bands.distance, band_data)).T
        head_line = "#%(key1)+12s%(key2)+13s" % {
            'key1': 'K-Distance',
            'key2': 'Energy(ev)'
        }
        write_col_data(filename, data, head_line, len(band_data))
    else:
        band_data_up = bands.bands[Spin.up][selected_band - 1] - vsr.efermi
        band_data_down = bands.bands[Spin.down][selected_band - 1] - vsr.efermi
        data = np.vstack((bands.distance, band_data_up, band_data_down)).T
        head_line = "#%(key1)+12s%(key2)+13s%(key3)+15s" % {
            'key1': 'K-Distance',
            'key2': 'UpEnergy(ev)',
            'key3': 'DownEnergy(ev)'
        }
        write_col_data(filename, data, head_line, len(band_data_up))
    return
Ejemplo n.º 6
0
def projected_band_structure():
    step_count = 1
    filename = 'vasprun.xml'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    vsr = Vasprun(filename)

    filename = 'PROCAR'
    check_file(filename)
    step_count += 1
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    procar = Procar(filename)
    nbands = procar.nbands
    nions = procar.nions
    norbitals = len(procar.orbitals)
    nkpoints = procar.nkpoints

    step_count += 1
    filename = 'KPOINTS'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    bands = vsr.get_band_structure(filename, line_mode=True, efermi=vsr.efermi)
    struct = vsr.final_structure
    (atom_index, in_str) = atom_selection(struct)

    if len(atom_index) == 0:
        print("No atoms selected!")
        return
#   print(atom_index)

    if vsr.is_spin:
        proc_str = "This Is a Spin-polarized Calculation."
        procs(proc_str, 0, sp='-->>')
        ISPIN = 2
        contrib = np.zeros((nkpoints, nbands, norbitals, 2))
        for i in atom_index:
            contrib[:, :, :,
                    0] = contrib[:, :, :, 0] + procar.data[Spin.up][:, :, i, :]
            contrib[:, :, :,
                    1] = contrib[:, :, :, 1] + procar.data[Spin.down][:, :,
                                                                      i, :]

        for ispin in range(2):
            proj_band = contrib[:, :, :,
                                ispin].reshape(nkpoints * nbands, norbitals)
            step_count += 1
            if ispin == 0:
                filename = "PBAND_Up.dat"
            else:
                filename = "PBAND_Down.dat"
            proc_str = "Writting Projected Band Structure Data to " + filename + " File ..."
            procs(proc_str, step_count, sp='-->>')
            band_data = bands.bands[Spin.up]
            y_data = band_data.reshape(
                1, nbands * nkpoints)[0] - vsr.efermi  #shift fermi level to 0
            x_data = np.array(bands.distance * nbands)
            data = np.vstack((x_data, y_data, proj_band.T)).T
            tmp1_str = "#%(key1)+12s%(key2)+12s"
            tmp2_dic = {'key1': 'K-Distance', 'key2': 'Energy(ev)'}
            for i in range(norbitals):
                tmp1_str += "%(key" + str(i + 3) + ")+12s"
                tmp2_dic["key" + str(i + 3)] = procar.orbitals[i]

#          print(tmp1_str)
            atom_index_str = [str(x + 1) for x in atom_index]
            head_line1 = "#String: " + in_str + '\n#Selected atom: ' + ' '.join(
                atom_index_str) + '\n'
            head_line2 = tmp1_str % tmp2_dic
            head_line = head_line1 + head_line2
            write_col_data(filename, data, head_line, nkpoints)

    else:
        if vsr.parameters['LNONCOLLINEAR']:
            proc_str = "This Is a Non-Collinear Calculation."
            procs(proc_str, 0, sp='-->>')
            ISPIN = 3
        else:
            proc_str = "This Is a Non-Spin Calculation."
            procs(proc_str, 0, sp='-->>')
            ISPIN = 1

        contrib = np.zeros((nkpoints, nbands, norbitals))
        for i in atom_index:
            contrib[:, :, :] = contrib[:, :, :] + procar.data[Spin.up][:, :,
                                                                       i, :]

        proj_band = contrib.reshape(nkpoints * nbands, norbitals)
        step_count += 1
        filename = "PBAND.dat"
        proc_str = "Writting Projected Band Structure Data to " + filename + " File ..."
        procs(proc_str, step_count, sp='-->>')
        band_data = bands.bands[Spin.up]
        y_data = band_data.reshape(
            1, nbands * nkpoints)[0] - vsr.efermi  #shift fermi level to 0
        x_data = np.array(bands.distance * nbands)
        data = np.vstack((x_data, y_data, proj_band.T)).T
        tmp1_str = "#%(key1)+12s%(key2)+12s"
        tmp2_dic = {'key1': 'K-Distance', 'key2': 'Energy(ev)'}
        for i in range(norbitals):
            tmp1_str += "%(key" + str(i + 3) + ")+12s"
            tmp2_dic["key" + str(i + 3)] = procar.orbitals[i]


#      print(tmp1_str)
        atom_index_str = [str(x + 1) for x in atom_index]
        head_line1 = "#String: " + in_str + '\n#Selected atom: ' + ' '.join(
            atom_index_str) + '\n'
        head_line2 = tmp1_str % tmp2_dic
        head_line = head_line1 + head_line2
        write_col_data(filename, data, head_line, nkpoints)

    step_count += 1
    bsp = BSPlotter(bands)
    filename = "HighSymmetricPoints.dat"
    proc_str = "Writting Label infomation to " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    head_line = "#%(key1)+12s%(key2)+12s%(key3)+12s" % {
        'key1': 'index',
        'key2': 'label',
        'key3': 'position'
    }
    line = head_line + '\n'
    for i, label in enumerate(bsp.get_ticks()['label']):
        new_line = "%(key1)12d%(key2)+12s%(key3)12f\n" % {
            'key1': i,
            'key2': label,
            'key3': bsp.get_ticks()['distance'][i]
        }
        line += new_line
    write_col_data(filename, line, '', str_data=True)
Ejemplo n.º 7
0
def total_dos():
    check_matplotlib()
    filename = 'vasprun.xml'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, 1, sp='-->>')
    vsr = Vasprun(filename, parse_eigen=False)
    tdos = vsr.tdos
    idos = vsr.idos
    E = tdos.energies - tdos.efermi
    if vsr.is_spin:
        proc_str = "This Is a Spin-polarized Calculation."
        procs(proc_str, 0, sp='-->>')
        proc_str = "Writting TDOS.dat File ..."
        TDOSUP = tdos.densities[Spin.up]
        TDOSDOWN = tdos.densities[Spin.down]
        ETDOS = np.vstack((E, TDOSUP, TDOSDOWN))
        head_line = "#%(key1)+12s%(key2)+12s%(key3)+12s" % {
            'key1': 'Energy(eV)',
            'key2': 'SpinUp',
            'key3': 'SpinDown'
        }
        write_col_data('TDOS.dat', ETDOS.T, head_line)

        proc_str = "Writting IDOS.dat File ..."
        procs(proc_str, 3, sp='-->>')
        IDOSUP = idos.densities[Spin.up]
        IDOSDOWN = idos.densities[Spin.down]
        EIDOS = np.vstack((E, IDOSUP, IDOSDOWN))
        head_line = "#%(key1)+12s%(key2)+12s%(key3)+12s" % {
            'key1': 'Energy(eV)',
            'key2': 'IntSpinUp',
            'key3': 'IntSpinDown'
        }
        write_col_data('IDOS.dat', EIDOS.T, head_line)

        plt1 = DosPlotter()
        plt2 = DosPlotter()
        plt1.add_dos('Total DOS', tdos)
        plt2.add_dos('Total DOS', idos)
        try:
            # plt1.show()
            plt1.save_plot('TotalDOS.png', img_format="png")
            # plt2.show()
            plt2.save_plot('IntegratedDOS.png', img_format="png")
        except:
            print("pls use gnuplot to plot TDOS.dat and IDOS.dat")
    else:
        if vsr.parameters['LNONCOLLINEAR']:
            proc_str = "This Is a Non-Collinear Calculation."
        else:
            proc_str = "This Is a Non-Spin Calculation."
        procs(proc_str, 0, sp='-->>')
        proc_str = "Writting TDOS.dat File ..."
        procs(proc_str, 2, sp='-->>')

        TDOS = tdos.densities[Spin.up]
        ETDOS = np.vstack((E, TDOS))
        head_line = "#%(key1)+12s%(key2)+12s" % {
            'key1': 'Energy(eV)',
            'key2': 'TotalDOS'
        }
        write_col_data('TDOS.dat', ETDOS.T, head_line)

        proc_str = "Writting IDOS.dat File ..."
        procs(proc_str, 3, sp='-->>')
        IDOS = idos.densities[Spin.up]
        EIDOS = np.vstack((E, IDOS))
        head_line = "#%(key1)+12s%(key2)+13s" % {
            'key1': 'Energy(eV)',
            'key2': 'IntegratedDOS'
        }
        write_col_data('IDOS.dat', EIDOS.T, head_line)

        plt1 = DosPlotter()
        plt2 = DosPlotter()
        plt1.add_dos('Total DOS', tdos)
        plt2.add_dos('Integrated DOS', idos)
        filename4 = "TotalDOS.png IntegratedDOS.png"
        proc_str = "Saving Plot to " + filename4 + " File ..."
        procs(proc_str, 4, sp='-->>')

        try:
            # plt1.show()
            plt1.save_plot('TotalDOS.png', img_format="png")
            # plt2.show()
            plt2.save_plot('IntegratedDOS.png', img_format="png")
        except:
            print("pls use gnuplot to plot TDOS.dat and IDOS.dat")
Ejemplo n.º 8
0
def band_structure():
    check_matplotlib()
    step_count = 1

    filename = 'vasprun.xml'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    vsr = Vasprun(filename)

    step_count += 1
    filename = 'KPOINTS'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    bands = vsr.get_band_structure(filename, line_mode=True, efermi=vsr.efermi)

    step_count += 1
    filename = 'OUTCAR'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    outcar = Outcar('OUTCAR')
    mag = outcar.as_dict()['total_magnetization']

    if vsr.is_spin:
        proc_str = "This Is a Spin-polarized Calculation."
        procs(proc_str, 0, sp='-->>')
        tdos = vsr.tdos
        SpinUp_gap = tdos.get_gap(spin=Spin.up)
        cbm_vbm_up = tdos.get_cbm_vbm(spin=Spin.up)
        SpinDown_gap = tdos.get_gap(spin=Spin.down)
        cbm_vbm_down = tdos.get_cbm_vbm(spin=Spin.up)

        if SpinUp_gap > min_gap and SpinDown_gap > min_gap:
            is_metal = False
            is_semimetal = False
        elif SpinUp_gap > min_gap and SpinDown_gap < min_gap:
            is_metal = False
            is_semimetal = True
        elif SpinUp_gap < min_gap and SpinDown_gap > min_gap:
            is_metal = False
            is_semimetal = True
        elif SpinUp_gap < min_gap and SpinDown_gap < min_gap:
            is_metal = True
            is_semimetal = False

        if is_metal:
            proc_str = "This Material Is a Metal."
            procs(proc_str, 0, sp='-->>')
        if not is_metal and is_semimetal:
            proc_str = "This Material Is a Semimetal."
            procs(proc_str, 0, sp='-->>')
        else:
            proc_str = "This Material Is a Semiconductor."
            procs(proc_str, 0, sp='-->>')
            proc_str = "Total magnetization is " + str(mag)
            procs(proc_str, 0, sp='-->>')
            if mag > min_mag:
                proc_str = "SpinUp  : vbm=%f eV cbm=%f eV gap=%f eV" % (
                    cbm_vbm_up[1], cbm_vbm_up[0], SpinUp_gap)
                procs(proc_str, 0, sp='-->>')
                proc_str = "SpinDown: vbm=%f eV cbm=%f eV gap=%f eV" % (
                    cbm_vbm_down[1], cbm_vbm_down[0], SpinUp_gap)
                procs(proc_str, 0, sp='-->>')
            else:
                proc_str = "SpinUp  : vbm=%f eV cbm=%f eV gap=%f eV" % (
                    cbm_vbm_up[1], cbm_vbm_up[0], SpinUp_gap)
                procs(proc_str, 0, sp='-->>')
        step_count += 1
        filename = "BAND.dat"
        proc_str = "Writting Band Structure Data to " + filename + " File ..."
        procs(proc_str, step_count, sp='-->>')
        band_data_up = bands.bands[Spin.up]
        band_data_down = bands.bands[Spin.down]
        y_data_up = band_data_up.reshape(
            1, band_data_up.shape[0] *
            band_data_up.shape[1])[0] - vsr.efermi  #shift fermi level to 0
        y_data_down = band_data_down.reshape(
            1, band_data_down.shape[0] *
            band_data_down.shape[1])[0] - vsr.efermi  #shift fermi level to 0
        x_data = np.array(bands.distance * band_data_up.shape[0])
        data = np.vstack((x_data, y_data_up, y_data_down)).T
        head_line = "#%(key1)+12s%(key2)+13s%(key3)+15s" % {
            'key1': 'K-Distance',
            'key2': 'UpEnergy(ev)',
            'key3': 'DownEnergy(ev)'
        }
        write_col_data(filename, data, head_line, band_data_up.shape[1])

    else:
        if vsr.parameters['LNONCOLLINEAR']:
            proc_str = "This Is a Non-Collinear Calculation."
        else:
            proc_str = "This Is a Non-Spin Calculation."
        procs(proc_str, 0, sp='-->>')
        cbm = bands.get_cbm()['energy']
        vbm = bands.get_vbm()['energy']
        gap = bands.get_band_gap()['energy']
        if not bands.is_metal():
            proc_str = "This Material Is a Semiconductor."
            procs(proc_str, 0, sp='-->>')
            proc_str = "vbm=%f eV cbm=%f eV gap=%f eV" % (vbm, cbm, gap)
            procs(proc_str, 0, sp='-->>')
        else:
            proc_str = "This Material Is a Metal."
            procs(proc_str, 0, sp='-->>')

        step_count += 1
        filename3 = "BAND.dat"
        proc_str = "Writting Band Structure Data to " + filename3 + " File ..."
        procs(proc_str, step_count, sp='-->>')
        band_data = bands.bands[Spin.up]
        y_data = band_data.reshape(
            1, band_data.shape[0] *
            band_data.shape[1])[0] - vsr.efermi  #shift fermi level to 0
        x_data = np.array(bands.distance * band_data.shape[0])
        data = np.vstack((x_data, y_data)).T
        head_line = "#%(key1)+12s%(key2)+13s" % {
            'key1': 'K-Distance',
            'key2': 'Energy(ev)'
        }
        write_col_data(filename3, data, head_line, band_data.shape[1])
        step_count += 1
        bsp = BSPlotter(bands)
        filename4 = "HighSymmetricPoints.dat"
        proc_str = "Writting Label infomation to " + filename4 + " File ..."
        procs(proc_str, step_count, sp='-->>')
        head_line = "#%(key1)+12s%(key2)+12s%(key3)+12s" % {
            'key1': 'index',
            'key2': 'label',
            'key3': 'position'
        }
        line = head_line + '\n'
        for i, label in enumerate(bsp.get_ticks()['label']):
            new_line = "%(key1)12d%(key2)+12s%(key3)12f\n" % {
                'key1': i,
                'key2': label,
                'key3': bsp.get_ticks()['distance'][i]
            }
            line += new_line
        line += '\n'
        write_col_data(filename4, line, '', str_data=True)
    try:
        step_count += 1
        filename5 = "BAND.png"
        proc_str = "Saving Plot to " + filename5 + " File ..."
        procs(proc_str, step_count, sp='-->>')
        bsp.save_plot(filename5, img_format="png")
    except:
        print("Figure output fails !!!")
Ejemplo n.º 9
0
def projected_dos():
    step_count = 1
    filename = 'vasprun.xml'
    check_file(filename)
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    vsr = Vasprun(filename)
    nedos = vsr.parameters['NEDOS']
    struct = vsr.final_structure
    pdos = vsr.pdos

    filename = 'PROCAR'
    check_file(filename)
    step_count += 1
    proc_str = "Reading Data From " + filename + " File ..."
    procs(proc_str, step_count, sp='-->>')
    procar = Procar(filename)
    nbands = procar.nbands
    nions = procar.nions
    norbitals = len(procar.orbitals)
    nkpoints = procar.nkpoints

    (atom_index, in_str) = atom_selection(struct)

    if len(atom_index) == 0:
        print("No atoms selected!")
        return
#   print(atom_index)

    if vsr.is_spin:
        proc_str = "This Is a Spin-polarized Calculation."
        procs(proc_str, 0, sp='-->>')

        contrib = np.zeros((nedos, norbitals + 1, 2))
        energies = vsr.tdos.energies - vsr.efermi
        for ispin in [0, 1]:
            if ispin == 0:
                spin = Spin.up
                s_name = 'Up'
            else:
                spin = Spin.down
                s_name = 'Down'

            contrib[:, 0, ispin] = energies
            for i in atom_index:
                for j in range(norbitals):
                    contrib[:, j + 1,
                            ispin] = contrib[:, j + 1,
                                             ispin] + pdos[i][Orbital(j)][spin]

            step_count += 1
            filename = "PDOS_" + s_name + ".dat"
            proc_str = "Writting Projected DOS Data to " + filename + " File ..."
            procs(proc_str, step_count, sp='-->>')
            tmp1_str = "#%%(key1)+12s"
            tmp2_dic = {'key1': 'Energy(ev)'}
            for i in range(norbitals):
                tmp1_str += "%(key" + str(i + 2) + ")+12s"
                tmp2_dic["key" + str(i + 2)] = procar.orbitals[i]

#          print(tmp1_str)
            atom_index_str = [str(x + 1) for x in atom_index]
            head_line1 = "#String: " + in_str + '\n#Selected atom: ' + ' '.join(
                atom_index_str) + '\n'
            head_line2 = tmp1_str % tmp2_dic
            head_line = head_line1 + head_line2
            write_col_data(filename, contrib[:, :, ispin], head_line)

    else:
        if vsr.parameters['LNONCOLLINEAR']:
            proc_str = "This Is a Non-Collinear Calculation."
            procs(proc_str, 0, sp='-->>')
        else:
            proc_str = "This Is a Non-Spin Calculation."
            procs(proc_str, 0, sp='-->>')

        contrib = np.zeros((nedos, norbitals + 1))
        energies = vsr.tdos.energies - vsr.efermi
        contrib[:, 0] = energies
        for i in atom_index:
            for j in range(norbitals):
                contrib[:, j +
                        1] = contrib[:, j + 1] + pdos[i][Orbital(j)][Spin.up]

        step_count += 1
        filename = "PDOS.dat"
        proc_str = "Writting Projected DOS Data to " + filename + " File ..."
        procs(proc_str, step_count, sp='-->>')
        tmp1_str = "#%(key1)+12s%(key2)+12s"
        tmp2_dic = {'key1': 'K-Distance', 'key2': 'Energy(ev)'}
        for i in range(norbitals):
            tmp1_str += "%(key" + str(i + 3) + ")+12s"
            tmp2_dic["key" + str(i + 3)] = procar.orbitals[i]


#      print(tmp1_str)
        atom_index_str = [str(x + 1) for x in atom_index]
        head_line1 = "#String: " + in_str + '\n#Selected atom: ' + ' '.join(
            atom_index_str) + '\n'
        head_line2 = tmp1_str % tmp2_dic
        head_line = head_line1 + head_line2
        write_col_data(filename, contrib, head_line)