Exemplo n.º 1
0
    def bareSurface(self):
        """
		Creates bare pymatgen slab object and scales to correct size
		"""
        slab = self.trajToMG()
        slab.make_supercell([self.scale[0], self.scale[1], 1])
        return reorient_z(slab)
Exemplo n.º 2
0
def makeSlab(a, facList, lay, sym, xy, vac):
    pmg_a = AseAtomsAdaptor.get_structure(a)
    unit = SpacegroupAnalyzer(
        pmg_a, symprec=0.1,
        angle_tolerance=5).get_conventional_standard_structure()
    gen = SlabGenerator(unit,
                        facList,
                        findHeight(unit, facList, lay, sym),
                        vac,
                        center_slab=sym,
                        primitive=True,
                        lll_reduce=True)
    slabs = gen.get_slabs()
    if len(slabs) > 1: print "Warning, multiple slabs generated..."
    slab = slabs[0]
    slab.make_supercell([xy[0], xy[1], 1])
    return reorient_z(slab)
Exemplo n.º 3
0
def plot_slab(slab, ax, scale=0.8, repeat=3, window=1, decay=0.2):
    """
	Function that helps visualize the slab in a 2-D plot, for
	convenient viewing of output of AdsorbateSiteFinder.
	Args:
		slab (slab): 	Slab object to be visualized
		ax (axes): 		matplotlib axes with which to visualize
		scale (float): 	radius scaling for sites
		repeat (int): 	number of repeating unit cells to visualize
		window (float): window for setting the axes limits, is essentially a fraction of the unit cell limits
		decay (float): 	how the alpha-value decays along the z-axis
	"""

    orig_slab = slab.copy()
    slab = reorient_z(slab)
    orig_cell = slab.lattice.matrix.copy()
    if repeat: slab.make_supercell([repeat, repeat, 1])
    coords = np.array(sorted(slab.cart_coords, key=lambda x: x[2]))
    sites = sorted(slab.sites, key=lambda x: x.coords[2])
    alphas = 1 - decay * (np.max(coords[:, 2]) - coords[:, 2])
    alphas = alphas.clip(min=0)
    corner = [0, 0, cart_to_frac(slab.lattice, coords[-1])[-1]]
    corner = frac_to_cart(slab.lattice, corner)[:2]
    verts = orig_cell[:2, :2]
    lattsum = verts[0] + verts[1]
    # Draw circles at sites and stack them accordingly
    for n, coord in enumerate(coords):
        r = sites[n].specie.atomic_radius * scale
        ax.add_patch(
            patches.Circle(coord[:2] - lattsum * (repeat // 2),
                           r,
                           color='w',
                           zorder=2 * n))
        color = color_dict[sites[n].species_string]
        ax.add_patch(
            patches.Circle(coord[:2] - lattsum * (repeat // 2),
                           r,
                           facecolor=color,
                           alpha=alphas[n],
                           edgecolor='k',
                           lw=0.3,
                           zorder=2 * n + 1))
    # Adsorption sites
    asf = AdsorbateSiteFinder(orig_slab)
    ads_sites = asf.find_adsorption_sites(symm_reduce=0)['all']
    sop = get_rot(orig_slab)
    ads_sites = [sop.operate(ads_site)[:2].tolist() for ads_site in ads_sites]

    b_sites = asf.find_adsorption_sites(symm_reduce=0)['bridge']
    b_sites = [(sop.operate(ads_site)[:2].tolist(), 'B' + str(i))
               for i, ads_site in enumerate(b_sites)]
    o_sites = asf.find_adsorption_sites(symm_reduce=0)['ontop']
    o_sites = [(sop.operate(ads_site)[:2].tolist(), 'O' + str(i))
               for i, ads_site in enumerate(o_sites)]
    h_sites = asf.find_adsorption_sites(symm_reduce=0)['hollow']
    h_sites = [(sop.operate(ads_site)[:2].tolist(), 'H' + str(i))
               for i, ads_site in enumerate(h_sites)]

    for site in b_sites + o_sites + h_sites:
        ax.text(site[0][0],
                site[0][1],
                site[1],
                zorder=10000,
                ha='center',
                va='center')

    # Draw unit cell
    verts = np.insert(verts, 1, lattsum, axis=0).tolist()
    verts += [[0., 0.]]
    verts = [[0., 0.]] + verts
    codes = [
        Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY
    ]
    verts = [(np.array(vert) + corner).tolist() for vert in verts]
    path = Path(verts, codes)
    patch = patches.PathPatch(path,
                              facecolor='none',
                              lw=2,
                              alpha=0.5,
                              zorder=2 * n + 2)
    ax.add_patch(patch)

    ax.set_aspect("equal")
    center = corner + lattsum / 2.
    extent = np.max(lattsum)
    lim_array = [center - extent * window, center + extent * window]
    x_lim = [ele[0] for ele in lim_array]
    y_lim = [ele[1] for ele in lim_array]
    ax.set_xlim(x_lim)
    ax.set_ylim(y_lim)
    return ax
Exemplo n.º 4
0
    def fix_absorbed(self,
                     need_miller_index,
                     mole,
                     num,
                     selective_dynamic,
                     min_slab_size_1=8.0,
                     min_vacuum_size_1=15,
                     judge='fuchdi',
                     appendage=""):
        from pymatgen import Structure, Lattice, MPRester, Molecule
        import pymatgen.core.structure

        import pymatgen.core.sites
        from pymatgen.analysis.adsorption import AdsorbateSiteFinder, reorient_z, plot_slab
        from pymatgen.core.surface import generate_all_slabs
        from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
        from matplotlib import pyplot as plt
        from pymatgen.ext.matproj import MPRester
        from pymatgen.io.vasp.inputs import Poscar
        from pymatgen.io.vasp.sets import MVLSlabSet
        from pymatgen.io.cif import CifWriter
        import os
        import shutil
        from openbabel import openbabel
        from pymatgen.core.surface import Slab, SlabGenerator, generate_all_slabs, Structure, Lattice, ReconstructionGenerator
        mp_id = self.mp_id
        os.chdir(r"F:\VASP practical\Input")
        print(os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        mpr = MPRester()
        struct = mpr.get_structure_by_material_id(mp_id)
        struct = SpacegroupAnalyzer(
            struct).get_conventional_standard_structure()
        # fcc_ni = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.5), ["Ni", "Ni"],
        # [[0, 0, 0], [0.5, 0.5, 0.5]])
        slab = SlabGenerator(struct,
                             miller_index=need_miller_index,
                             min_slab_size=min_slab_size_1,
                             min_vacuum_size=min_vacuum_size_1,
                             center_slab=True)

        for n, slabs in enumerate(slab.get_slabs()):
            if str(n) in str(num):
                slabs_bak = slabs.copy()  #可能的晶面
                slabs.make_supercell(self.supercell)
                print(n)
                #晶胞扩充

                asf_ni_111 = AdsorbateSiteFinder(
                    slabs, selective_dynamics=selective_dynamic)
                ads_sites = asf_ni_111.find_adsorption_sites()

                # print(ads_sites)
                assert len(ads_sites) == 4

                fig0 = plt.figure()
                ax = fig0.add_subplot(111)
                plot_slab(slabs, ax, adsorption_sites=False)

                fig1 = plt.figure()
                ax = fig1.add_subplot(111)
                os.chdir(r"D:\Desktop\VASP practical\Cif library")
                print(os.getcwd())
                obConversion = openbabel.OBConversion()
                obConversion.SetInAndOutFormats("pdb", "gjf")
                mol = openbabel.OBMol()
                print(mol)
                c = obConversion.ReadFile(mol, "CH3OH.pdb")
                obConversion.WriteFile(mol, "CH3OH.pdb" + '1.gjf')
                adsorbate = Molecule.from_file("CH3OH.pdb" + '.gjf')
                os.chdir(r"F:\VASP practical\Input")
                print(os.getcwd())

                print(adsorbate.sites)
                ads_structs = asf_ni_111.add_adsorbate(
                    adsorbate,
                    (20, 20, 20),
                    translate=False,
                )
                # ads_structs = asf_ni_111.generate_adsorption_structures(adsorbate,
                # repeat=[1, 1, 1])
                # A = Poscar(ads_structs[0])
                A = Poscar(reorient_z(ads_structs))  #将切面转换为Poscar
                open('POSCAR', 'w').write(str(A))
                p = Poscar.from_file('POSCAR')
                # w = CifWriter(A.struct)
                # w.write_file('mystructure.cif')
                path = r'F:\VASP practical\Input\POSCAR'  # 文件路径
                if os.path.exists(path):  # 如果文件存在
                    # 删除文件,可使用以下两种方法。
                    os.remove(path)
                #os.unlink(path)
                else:
                    print('no such file:%s' % my_file)  # 则返回文件不存在
                # w = CifWriter(A.struct)
                # w.write_file('mystructure.cif')

                relax = p.structure  #将Poscar 转换为结构信息
                custom_settings = {"NPAR": 4}  # 用户的INCAR 设置
                relaxs = MVLSlabSet(relax, user_incar_settings=custom_settings)
                # Vasp输入文件生成器
                dire = str(mp_id) + str(selective_dynamic) + str(mole) + str(
                    need_miller_index).replace(" ", "") + str(n)
                # print (relax)
                relaxs.write_input(dire)
                os.chdir("./" + dire)
                print(os.getcwd())
                fig0.savefig('slab.png',
                             bbox_inches='tight',
                             transparent=True,
                             dpi=600,
                             format='png')
                plot_slab(ads_structs, ax, adsorption_sites=False, decay=0.09)
                fig1.savefig('slab_adsobate.png',
                             bbox_inches='tight',
                             transparent=True,
                             dpi=600,
                             format='png')
                #定义一个更改当前目录的变量
                dire2 = './vaspstd_sub'
                #确立脚本名称
                shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

                eb = appendage  #添加其他INCAR参数

                with open('INCAR', 'r') as f1:
                    lines = f1.readlines()

                with open('INCAR', 'w') as f2:
                    for line in lines:
                        if judge in line:
                            continue
                        f2.write(line)

                with open('INCAR', 'a') as f3:
                    f3.write(eb)

                # open('POSCAR001', 'w').write(str(Poscar(reorient_z(ads_structs[0]))))

                os.chdir(r"D:\Desktop\VASP practical\workdir")
                print(os.getcwd())
                print('finished')


# my_lattace = Lattace('mp-698074')#半水石膏
# # my_lattace.phase_out()#生成晶胞优化的输入文件
# go = my_lattace.phase_sol(66,judge='LWAVE',  appendage= '\nLWAVE = Ture')
# print('yoo')
Exemplo n.º 5
0
def main():
    asedb = connect('/scratch/users/ksb/db/ase.db')
    initialQuestion = (
        '\n%d relaxed bulk structure(s) passed filters+constraints.' %
        (nBulk) + '\nDo you want to create %d slabs?\n(y/n)--> ' % (ncombo))

    if raw_input(initialQuestion).lower() in ['y', 'yes']:

        for combo in domainProduct:
            ind, fac, xy, l, c, sym, vac, vacancy = combo

            a = asedb.get_atoms(id=ind)
            pmg_a = AseAtomsAdaptor.get_structure(a)
            unit = SpacegroupAnalyzer(
                pmg_a, symprec=0.1,
                angle_tolerance=5).get_conventional_standard_structure()

            gen = SlabGenerator(unit,
                                fac,
                                findHeight(unit, fac, l, sym),
                                vac,
                                center_slab=sym,
                                primitive=True,
                                lll_reduce=True)

            slabs = gen.get_slabs()

            if len(slabs) > 1: print "Warning, multiple slabs generated..."

            slab = slabs[0]
            slab.make_supercell(list(xy) + [1])
            bare = reorient_z(slab)
            img = plot(bare)

            aseAtoms = AseAtomsAdaptor.get_atoms(bare)
            taggedAtoms = tag_atoms(aseAtoms)
            taggedAtoms.set_constraint(
                FixAtoms(indices=constrainAtoms(taggedAtoms, c, sym)))

            magmoms = [
                magmomInit if (magmomInit and e in magElems) else 0
                for e in taggedAtoms.get_chemical_symbols()
            ]

            taggedAtoms.set_initial_magnetic_moments(magmoms)
            taggedAtoms.set_calculator(EMT())
            taggedAtoms.wrap()

            for i in vacancy:
                del taggedAtoms[i]

            info = {
                'name':
                '%s_%s_%s' % (asedb.get(ind).get('name'), '-'.join(
                    [str(x) for x in fac]), 'x'.join([str(x) for x in xy])),
                'kind':
                'surface',
                'structure':
                asedb.get(ind).get('structure'),
                'sites':
                img,
                'bare':
                True,
                'parent':
                ind  #ase object surface was generated from
                ,
                'facet':
                str(fac),
                'xy':
                str(xy),
                'layers':
                l,
                'constrained':
                c,
                'symmetric':
                sym,
                'vacuum':
                vac,
                'vacancies':
                str(vacancy),
                'surfcomments':
                'Autogenerated by initializeBareSurf',
                'emt':
                taggedAtoms.get_potential_energy(),
                'relaxed':
                False
            }

            if USER_APPROVAL:
                view(taggedAtoms)
                question = (
                    'Does this structure look right?\nfacet= %s\nlayers = %d\nfixed = %d\n'
                    % ('-'.join([str(x) for x in fac]), l, c) +
                    'vacuum = %d\nxy = %s\n(y/n) --> ' %
                    (vac, 'x'.join([str(x) for x in xy])))

                if raw_input(question).lower() in ['y', 'yes']:
                    asedb.write(taggedAtoms, key_value_pairs=info)
            else:
                asedb.write(taggedAtoms, key_value_pairs=info)
Exemplo n.º 6
0
 def test_functions(self):
     slab = self.slab_dict["111"]
     get_rot(slab)
     reorient_z(slab)
Exemplo n.º 7
0
    def absorbed(self,
                 millerindex_1,
                 absorbate_1,
                 absorba,
                 judge='',
                 appendage=""):

        from pymatgen import Structure, Lattice, MPRester, Molecule
        import pymatgen.core.structure

        import pymatgen.core.sites
        from pymatgen.analysis.adsorption import AdsorbateSiteFinder, reorient_z, plot_slab
        from pymatgen.core.surface import generate_all_slabs
        from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
        from matplotlib import pyplot as plt
        from pymatgen.io.cif import CifParser
        from pymatgen.io.vasp.inputs import Poscar
        from pymatgen.io.vasp.sets import MVLSlabSet
        from pymatgen.io.cif import CifWriter
        import os
        import shutil

        ass = self.cif_route
        print(ass)
        # os.chdir(r"E:\VASP practical\Input")
        # print (os.getcwd())

        # Note that you must provide your own API Key, which can
        # be accessed via the Dashboard at materialsproject.org
        #mpr = MPRester()#密钥
        struct = CifParser(ass)
        structure = struct.get_structures()[0]
        print(structure)

        os.chdir(r"E:\VASP practical\Input")
        print(os.getcwd())
        # fcc_ni = Structure.from_spacegroup("Fm-3m", Lattice.cubic(3.5), ["Ni", "Ni"],
        # [[0, 0, 0], [0.5, 0.5, 0.5]])
        slabs = generate_all_slabs(structure,
                                   max_index=1,
                                   min_slab_size=8.0,
                                   min_vacuum_size=10.0)

        millerindex = millerindex_1
        struct_111 = [
            slab for slab in slabs if slab.miller_index == millerindex_1
        ][0]

        asf_ni_111 = AdsorbateSiteFinder(struct_111)
        ads_sites = asf_ni_111.find_adsorption_sites()

        # print(ads_sites)
        assert len(ads_sites) == 4

        fig = plt.figure()
        ax = fig.add_subplot(111)
        plot_slab(struct_111, ax, adsorption_sites=True)

        fig = plt.figure()
        ax = fig.add_subplot(111)

        adsorbate = Molecule(absorbate_1, absorba)
        ads_structs = asf_ni_111.generate_adsorption_structures(
            adsorbate, repeat=[1, 1, 1])
        A = Poscar(reorient_z(ads_structs[0]))  #将切面转换为Poscar
        open('POSCAR', 'w').write(str(A))
        p = Poscar.from_file('POSCAR')
        # w = CifWriter(A.struct)
        # w.write_file('mystructure.cif')
        path = r'E:\VASP practical\Input\POSCAR'  # 文件路径
        if os.path.exists(path):  # 如果文件存在
            # 删除文件,可使用以下两种方法。
            os.remove(path)
        #os.unlink(path)
        else:
            print('no such file:%s' % my_file)  # 则返回文件不存在
        # w = CifWriter(A.struct)
        # w.write_file('mystructure.cif')

        relax = p.structure  #将Poscar 转换为结构信息
        custom_settings = {"NPAR": 4}  # 用户的INCAR 设置
        relaxs = MVLSlabSet(relax, user_incar_settings=custom_settings)
        # Vasp输入文件生成器
        dire = str(ass) + "---" + str(absorbate_1) + str(millerindex_1)
        # print (relax)
        relaxs.write_input(dire)
        os.chdir("./" + dire)
        print(os.getcwd())
        #定义一个更改当前目录的变量
        dire2 = './vaspstd_sub'
        #确立脚本名称
        shutil.copy(r"C:\Users\41958\.spyder-py3\vaspstd_sub", dire2)

        eb = appendage  #添加其他INCAR参数

        with open('INCAR', 'r') as f1:
            lines = f1.readlines()

        with open('INCAR', 'w') as f2:
            for line in lines:
                if judge in line:
                    continue
                f2.write(line)

        with open('INCAR', 'a') as f3:
            f3.write(eb)

        plot_slab(ads_structs[0], ax, adsorption_sites=False, decay=0.09)
        # open('POSCAR001', 'w').write(str(Poscar(reorient_z(ads_structs[0]))))

        os.chdir(r"D:\Desktop\VASP practical\workdir")
        print(os.getcwd())
        print('finished')


# my_lattace = Lattace('mp-698074')#半水石膏
# # my_lattace.phase_out()#生成晶胞优化的输入文件
# go = my_lattace.phase_sol(66,judge='LWAVE',  appendage= '\nLWAVE = Ture')
# print('yoo')