Exemplo n.º 1
0
def main_func(mpid='',mat=None,parameters={}):
    if mpid !='':
       json_dat=parameters['json_dat']
       data = loadfn(json_dat, cls=MontyDecoder)
       for d in data:
            mmpid= str(d['mpid'])
            if mmpid==mpid:
               fin= (d['structure'])

               break

       strt = fin#mp.get_structure_by_material_id(mpid)
       sg_mat = SpacegroupAnalyzer(strt)
       mat_cvn = sg_mat.get_conventional_standard_structure()
       mat_cvn.sort()
       if int(strt.composition._natoms)==int(mat_cvn.composition._natoms):
               mat= Poscar(mat_cvn)
       else:
                mat=Poscar(strt)



       mpid=mpid.replace('-','_')
       mpid=str('bulk@')+str(mpid)
       mat.comment=mpid





    main(p=mat,parameters=parameters)
Exemplo n.º 2
0
def do_phonons(strt=None, parameters=None, c_size=25):
    """
    Setting up phonopy job using LAMMPS

    Args:
        strt: Structure object
        parameters: LAMMPS input file parameters
        c_size: cell-size 
    
    """

    p = get_phonopy_atoms(mat=strt)
    bulk = p

    dim1 = int((float(c_size) / float(max(abs(strt.lattice.matrix[0]))))) + 1
    dim2 = int(float(c_size) / float(max(abs(strt.lattice.matrix[1])))) + 1
    dim3 = int(float(c_size) / float(max(abs(strt.lattice.matrix[2])))) + 1
    Poscar(strt).write_file("POSCAR")
    tmp = strt.copy()
    tmp.make_supercell([dim1, dim2, dim3])
    Poscar(tmp).write_file("POSCAR-Super.vasp")

    phonon = Phonopy(bulk, [[dim1, 0, 0], [0, dim2, 0], [0, 0, dim3]])  # ,
    print("[Phonopy] Atomic displacements:")
    disps = phonon.get_displacements()
    for d in disps:
        print("[Phonopy]", d[0], d[1:])
    supercells = phonon.get_supercells_with_displacements()

    # Force calculations by calculator
    set_of_forces = []
    disp = 0
    for scell in supercells:
        cell = Atoms(
            symbols=scell.get_chemical_symbols(),
            scaled_positions=scell.get_scaled_positions(),
            cell=scell.get_cell(),
            pbc=True,
        )
        disp = disp + 1

    mat = Poscar(AseAtomsAdaptor().get_structure(cell))
    mat.comment = str("disp-") + str(disp)
    parameters["min"] = "skip"
    parameters["control_file"] = "/users/knc6/in.phonon"
    # a,b,forces=run_job(mat=mat,parameters={'min':'skip','pair_coeff': '/data/knc6/JARVIS-FF-NEW/ALLOY4/Mishin-Ni-Al-2009.eam.alloy', 'control_file': '/users/knc6/in.phonon', 'pair_style': 'eam/alloy', 'atom_style': 'charge'})
    a, b, forces = run_job(mat=mat, parameters=parameters)
    print("forces=", forces)
    drift_force = forces.sum(axis=0)
    print("drift forces=", drift_force)
    print("[Phonopy] Drift force:", "%11.5f" * 3 % tuple(drift_force))
    # Simple translational invariance
    for force in forces:
        force -= drift_force / forces.shape[0]
    set_of_forces.append(forces)
    phonon.produce_force_constants(forces=set_of_forces)

    write_FORCE_CONSTANTS(phonon.get_force_constants(), filename="FORCE_CONSTANTS")
    print()
    print("[Phonopy] Phonon frequencies at Gamma:")
Exemplo n.º 3
0
def dyna(inputfile, surfaceorbulk, layersrelaxed=3, tol=0.01):
    # TODO - This feature may be buggy - as of current the tolerance on the layers is uhhh to be said lightly. someone
    #  smarter than me can figure it out
    from pymatgen.io.vasp.inputs import Poscar
    from pymatgen import Structure

    obby = Structure.from_file(inputfile)

    if surfaceorbulk == 'surface':
        print(' okay will dyn' + layersrelaxed +
              ' surface layers on either side')
        subspos = []
        for n__ in range(
                0, len(obby)):  # pretty much cpaste from the subs stuff above
            subspos.append(n__)
        eucdis = []
        for n__ in subspos:  # array-tiest the results of which is closest to center.
            eucdis = np.append(eucdis, [
                np.linalg.norm(np.array(0.5) - obby.frac_coords[n__][2]), n__
            ])

        eucdis = np.reshape(eucdis,
                            (len(subspos), 2))  # restruc into a x2 array
        eucdis = eucdis[eucdis[:, 0].argsort(
        )]  # make the array measure based on c distance from center
        # TODO - need to fiddle with this cause as of current the 'stepping process is f****d and may think all 1 layer
        v = 0
        k = 0
        lofleucdis = [[]]
        while v < len(eucdis[:, 1]) - 1:
            if np.isclose(eucdis[v], eucdis[v + 1], atol=tol)[0]:
                print(str(eucdis[v][0]) + ' is near ' + str(eucdis[v + 1][0]))
                lofleucdis[k].append(eucdis[v][1])
            else:
                # print(str(eucdis[v][0]) + ' is not near ' + str(eucdis[v + 1][0]))
                lofleucdis.append([])
                k += 1
            v += 1
        boolatoms = []
        booldyn = np.ones([len(obby), 3])  # Premaking the boolean input
        for elem in range(0,
                          int(layersrelaxed) -
                          1):  # Takes the surface layers as defined
            boolatoms = boolatoms + lofleucdis[elem]
        for elem in boolatoms:
            booldyn[int(elem)] = [0, 0, 0]
        boollist = booldyn.tolist()  # Convert to list
        possy = Poscar(
            obby, selective_dynamics=boollist)  # write as poscar structure
        possy.structure.to(filename=inputfile)
    else:
        print('okay bulk system found will relax all atoms')
        booldyn = np.ones([len(obby), 3])  # makes an array of 1's
        boollist = booldyn.tolist(
        )  # for some reason p.m.g doesnt accept np.arrays - weird!
        possy = Poscar(obby, selective_dynamics=boollist)
        possy.structure.to(filename=inputfile)
    print(
        "your input poscar has been updated - dynamic - sorry if this isn't what you wanted </3"
    )
Exemplo n.º 4
0
 def test_unsymmetric_model_generation(self):
     """
     Test for generating unsymmetric model.
     """
     random.seed(0)
     gen.modify_unsymmetrical(modify_shape=True, cell_min=-0.01, cell_max=0.01)
     struct = pymatgen.Structure.from_str(
         open("tests/samples/POSCAR_unsym").read(), fmt="poscar"
     )
     assert str(Poscar(gen.get_struct())) == str(Poscar(struct))
Exemplo n.º 5
0
def do_phonons(strt=None,parameters=None):

        p= get_phonopy_atoms(mat=strt)
        bulk =p
        c_size=parameters['phon_size']
        dim1=int((float(c_size)/float( max(abs(strt.lattice.matrix[0])))))+1
        dim2=int(float(c_size)/float( max(abs(strt.lattice.matrix[1]))))+1
        dim3=int(float(c_size)/float( max(abs(strt.lattice.matrix[2]))))+1
        Poscar(strt).write_file("POSCAR")
        tmp=strt.copy()
        tmp.make_supercell([dim1,dim2,dim3])
        Poscar(tmp).write_file("POSCAR-Super.vasp")
    
        print ('supercells',dim1,dim2,dim3)
        phonon = Phonopy(bulk,[[dim1,0,0],[0,dim2,0],[0,0,dim3]]) 
        print ("[Phonopy] Atomic displacements:")
        disps = phonon.get_displacements()

        for d in disps:
            print ("[Phonopy]", d[0], d[1:])
        supercells = phonon.get_supercells_with_displacements()

        # Force calculations by calculator
        set_of_forces = []
        disp=0
        for scell in supercells:
            cell = Atoms(symbols=scell.get_chemical_symbols(),
                         scaled_positions=scell.get_scaled_positions(),
                         cell=scell.get_cell(),
                         pbc=True)
            disp=disp+1

            mat = Poscar(AseAtomsAdaptor().get_structure(cell))
            mat.comment=str("disp-")+str(disp)
            parameters['min']='skip'
            parameters['control_file']= parameters['phonon_control_file']  #'/users/knc6/in.phonon'
            #a,b,forces=run_job(mat=mat,parameters={'min':'skip','pair_coeff': '/data/knc6/JARVIS-FF-NEW/ALLOY4/Mishin-Ni-Al-2009.eam.alloy', 'control_file': '/users/knc6/in.phonon', 'pair_style': 'eam/alloy', 'atom_style': 'charge'})
            a,b,forces=run_job(mat=mat,parameters=parameters)
            #print "forces=",forces
            drift_force = forces.sum(axis=0)
            #print "drift forces=",drift_force
            #print "[Phonopy] Drift force:", "%11.5f"*3 % tuple(drift_force)
            # Simple translational invariance
            for force in forces:
                force -= drift_force / forces.shape[0]
            set_of_forces.append(forces)
        phonon.produce_force_constants(forces=set_of_forces)

        write_FORCE_CONSTANTS(phonon.get_force_constants(),
                              filename="FORCE_CONSTANTS")
        #print
        #print "[Phonopy] Phonon frequencies at Gamma:"
        for i, freq in enumerate(phonon.get_frequencies((0, 0, 0))):
            print ("[Phonopy] %3d: %10.5f THz" %  (i + 1, freq)) # THz
Exemplo n.º 6
0
    def write_all_structures(self):
        """
        Write all of the structures relevant for
        the interface calculation to VASP POSCAR files.
        """

        _poscar = Poscar(self.original_substrate_structure)
        _poscar.write_file('bulk_substrate_POSCAR')

        _poscar = Poscar(self.original_film_structure)
        _poscar.write_file('bulk_film_POSCAR')

        _poscar = Poscar(self.strained_substrate)
        _poscar.write_file('strained_substrate_POSCAR')

        _poscar = Poscar(self.strained_film)
        _poscar.write_file('strained_film_POSCAR')

        for i, interface in enumerate(self.modified_substrate_structures):
            _poscar = Poscar(interface)
            _poscar.write_file('slab_substrate_%d_POSCAR' % i)

        for i, interface in enumerate(self.modified_film_structures):
            _poscar = Poscar(interface)
            _poscar.write_file('slab_film_%d_POSCAR' % i)

        for i, interface in enumerate(self.film_structures):
            _poscar = Poscar(interface)
            _poscar.write_file('slab_unit_film_%d_POSCAR' % i)

        for label, interface in zip(self.interface_labels, self.interfaces):
            _poscar = Poscar(interface)
            _poscar.write_file('interface_%s_POSCAR' % label.replace("/", "-"))
        return
    def get_init_fin(self,
                     i_file,
                     f_file,
                     disp_range=np.linspace(-1, 1, 11),
                     output_dir='disp_dir'):
        '''
        '''
        # A. Alkauskas, Q. Yan, and C. G. Van de Walle, Physical Review B 90, 27 (2014)
        struct_i, sorted_symbols = self.read_poscar(i_file, True)
        struct_f, sorted_symbols = self.read_poscar(f_file, True)
        delta_R = struct_f.frac_coords - struct_i.frac_coords
        delta_R = (delta_R + 0.5) % 1 - 0.5

        lattice = struct_i.lattice.matrix  #[None,:,:]
        delta_R = np.dot(delta_R, lattice)

        if not os.path.exists(output_dir):
            os.makedirs(output_dir)

        masses = np.array([spc.atomic_mass for spc in struct_i.species])
        delta_Q2 = masses[:, None] * delta_R**2

        print('Delta_Q^2', np.sqrt(delta_Q2.sum()))

        for frac in disp_range:
            disp = frac * delta_R
            print(disp[0][0])
            struct = Structure(struct_i.lattice, struct_i.species, \
                            struct_i.cart_coords + disp, \
                            coords_are_cartesian=True)
            Poscar(struct).write_file('{0}/POSCAR_{1:03d}'.format(
                output_dir, int(np.rint(frac * 10))))
Exemplo n.º 8
0
def write_lammps_data(structure=None, file=''):
        """
        write lammps structure data
        from ase with custom modifications
        """
        structure.sort()
        structure.to(fmt= "poscar", filename= "new_pymatgen_slab.vasp")
        atoms = AseAtomsAdaptor().get_atoms(structure)

        f=open(file,"w")
        f.write( 'datafile (written by JARVIS-FF) \n\n')
        symbols = atoms.get_chemical_symbols()
        import ase.io.vasp
        n_atoms = len(symbols)
        f.write('%d \t atoms \n' % n_atoms)
        species = [tos for tos in Poscar(structure).site_symbols]
        n_atom_types = len(species)
        #print ("species",species)
        f.write('%d  atom types\n' % n_atom_types)
        p = Prism(atoms.get_cell())
        xhi, yhi, zhi, xy, xz, yz = p.get_lammps_prism_str()
        f.write('0.0 %s  xlo xhi\n' % xhi)
        f.write('0.0 %s  ylo yhi\n' % yhi)
        f.write('0.0 %s  zlo zhi\n' % zhi)
        f.write('%s %s %s  xy xz yz\n' % (xy, xz, yz))
        f.write('\n\n')
        f.write('Atoms \n\n')
        for i, r in enumerate(map(p.pos_to_lammps_str,
                                  atoms.get_positions())):
            c = 0.0
            s = species.index(symbols[i]) + 1
                    
            f.write('%6d %3d %6f %s %s %s\n' %
                            ((i+1, s, c)+tuple(r)) )
        f.close()
Exemplo n.º 9
0
    def test_velocities(self):
        si = 14
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])

        # Silicon structure for testing.
        latt = [[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00],
                [0.00, -2.2171384943, 3.1355090603]]
        struct = Structure(latt, [si, si], coords)
        poscar = Poscar(struct)
        poscar.set_temperature(900)

        v = np.array(poscar.velocities)

        for x in np.sum(v, axis=0):
            self.assertAlmostEqual(x, 0, 7)

        temperature = struct[0].specie.atomic_mass.to("kg") * \
                      np.sum(v ** 2) / (3 * const.k) * 1e10
        self.assertAlmostEqual(temperature, 900, 4,
                               'Temperature instantiated incorrectly')

        poscar.set_temperature(700)
        v = np.array(poscar.velocities)
        for x in np.sum(v, axis=0):
            self.assertAlmostEqual(
                x, 0, 7, 'Velocities initialized with a net momentum')

        temperature = struct[0].specie.atomic_mass.to("kg") * \
                      np.sum(v ** 2) / (3 * const.k) * 1e10
        self.assertAlmostEqual(temperature, 700, 4,
                               'Temperature instantiated incorrectly')
Exemplo n.º 10
0
def get_chem_pot(s1=None,s2=None,parameters= {}):
#def get_chem_pot(s1=None,s2=None,parameters= {'pair_style':'eam/alloy','pair_coeff':'/scratch/lfs/kamal/POSMAT/Automatic2/Al03.eam.alloy','atom_style': 'charge' ,'control_file':'/home/kamal/inelast.mod'}):
    s1.sort() 
    s2.sort() 
    s3=(set(s2)).symmetric_difference(set(s1))#list(set(s1)-set(s2))
    #s3=[]
    #for el1 in s1:
    #     for el2 in s2:
    #         if el1 !=el2 and el1 not in s3:
    #            s3.append(el1)
    #         if el1 !=el2 and el2 not in s3:
    #            s3.append(el2)
    #             
    #from pymatgen.analysis.structure_matcher import StructureMatcher
    #print "Mather",StructureMatcher().fit(s1, s2)
    print "s3   is   ",type(s1),type(s2),s3
    uniq=[]
    for q in s3:
        el=q._species.elements 
        for j in el:
           print   "j is ",j
           if j not in uniq:   
              uniq.append(j)
              a,b= get_struct_from_mp(j)
              p=Poscar(b)
              p.comment=str(a)
              enp,strt,forces=run_job(mat=p,parameters = parameters)
    if len(uniq)>1:
        print "uniq problem",uniq
    print "uniqqqqqqqqqqqqqqqqqqq=",uniq
    return enp
Exemplo n.º 11
0
def write_rho_vasp(structure, species, sigma, mesh, filename):
    frac_coor_grid = np.array(
        np.meshgrid(
            range(mesh[0]), range(mesh[1]), range(
                mesh[2]), indexing="ij")).T.reshape(-1, 3) / np.array(mesh)

    # np.array(list(np.ndindex(mesh[0],mesh[1],mesh[2])))/np.array(mesh)
    structure1 = structure.copy()
    structure1.sort(key=lambda site: site.species_string)
    poscar = Poscar(structure1)
    outfi = open(filename, "w")
    print(frac_coor_grid)
    rho = rho_gauss(frac_coor_grid, structure, species, sigma)
    outfi.write("rho_vasp\n")
    outfi.write("\t1.00\n")
    latticevecs = structure.lattice.matrix
    outfi.write("\t".join([str(l) for l in latticevecs[0]]) + "\n")
    outfi.write("\t".join([str(l) for l in latticevecs[1]]) + "\n")
    outfi.write("\t".join([str(l) for l in latticevecs[2]]) + "\n")
    outfi.write("\t".join(poscar.site_symbols) + "\n")
    outfi.write("\t".join([str(l) for l in poscar.natoms]) + "\n")
    outfi.write("Direct\n")
    for site in poscar.structure:
        coords = site.frac_coords
        outfi.write("\t".join([str(l) for l in coords]) + "\n")
    outfi.write("\n")
    outfi.write("\t".join(str(l) for l in mesh) + "\n")
    for i in range(len(rho) // 5 + 1):
        outfi.write(" ".join(str(x) for x in rho[i * 5:(i + 1) * 5]) + "\n")
Exemplo n.º 12
0
    def _convert_to_vasp_volumetric(self, filename, dim):
        """
		Utility function to convert pawpyseed volumetric
		output to VASP volumetric output.
		"""

        #from pymatgen VolumetricData class
        p = Poscar(self.structure)
        lines = filename + '\n'
        lines += "   1.00000000000000\n"
        latt = self.structure.lattice.matrix
        lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[0, :])
        lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[1, :])
        lines += " %12.6f%12.6f%12.6f\n" % tuple(latt[2, :])
        lines += "".join(["%5s" % s for s in p.site_symbols]) + "\n"
        lines += "".join(["%6d" % x for x in p.natoms]) + "\n"
        lines += "Direct\n"
        for site in self.structure:
            lines += "%10.6f%10.6f%10.6f\n" % tuple(site.frac_coords)
        lines += " \n"

        f = open(filename, 'r')
        nums = f.read()
        f.close()
        f = open(filename, 'w')
        dimstr = '%d %d %d\n' % (dim[0], dim[1], dim[2])
        #pos = Poscar(self.structure, velocities = None)
        #posstr = pos.get_string() + '\n'
        f.write(lines + dimstr + nums)
        f.close()
Exemplo n.º 13
0
def set_sd_flags(poscar_input=None,
                 n_layers=2,
                 top=True,
                 bottom=True,
                 poscar_output='POSCAR2'):
    """
    set the relaxation flags for top and bottom layers of interface.
    The upper and lower bounds of the z coordinate are determined
    based on the slab.
    Args:
         poscar_input: input poscar file name
         n_layers: number of layers to be relaxed
         top: whether n_layers from top are be relaxed
         bottom: whether n_layers from bottom are be relaxed
         poscar_output: output poscar file name
    Returns:
         None
         writes the modified poscar file
    """
    poscar1 = Poscar.from_file(poscar_input)
    sd_flags = np.zeros_like(poscar1.structure.frac_coords)
    z_coords = poscar1.structure.frac_coords[:, 2]
    z_lower_bound, z_upper_bound = None, None
    if bottom:
        z_lower_bound = np.unique(z_coords)[n_layers - 1]
        sd_flags[np.where(z_coords <= z_lower_bound)] = np.ones((1, 3))
    if top:
        z_upper_bound = np.unique(z_coords)[-n_layers]
        sd_flags[np.where(z_coords >= z_upper_bound)] = np.ones((1, 3))
    poscar2 = Poscar(poscar1.structure, selective_dynamics=sd_flags.tolist())
    poscar2.write_file(filename=poscar_output)
Exemplo n.º 14
0
def main(p=None,vac_cal=True,surf_cal=True,phon_cal=True, parameters={}):

    #p=Poscar.from_file("POSCAR")
    c_size=parameters['c_size']
    vac_size=parameters['vac_size']
    surf_size=parameters['surf_size']
    phon_size=parameters['phon_size']
    sg_mat = SpacegroupAnalyzer(p.structure)
    mat_cvn = sg_mat.get_conventional_standard_structure()
    dim1=int((float(c_size)/float( max(abs(mat_cvn.lattice.matrix[0])))))+1
    dim2=int(float(c_size)/float( max(abs(mat_cvn.lattice.matrix[1]))))+1
    dim3=int(float(c_size)/float( max(abs(mat_cvn.lattice.matrix[2]))))+1
    cellmax=max(dim1,dim2,dim3)
    tmp=mat_cvn.copy()
    mat_cvn.make_supercell([dim1,dim2,dim3])
    #print "dim1 dim2 dim3",dim1,dim2,dim3
    #mat_cvn.make_supercell([dim1,dim2,dim3])
    mat_pos=Poscar(mat_cvn)
    mat_pos.comment=str(p.comment)
    #print ('execcccccc',parameters['exec'])
    #print mat_pos
    #toten,final_str,forces=run_job(mat=mat_pos,parameters = parameters)
    #do_phonons(strt=final_str,parameters=parameters)
    try:
       print ('in elastic calc')
       toten,final_str,forces=run_job(mat=mat_pos,parameters = parameters)
       print ('done elastic calc')
    except:
       pass
    vac=vac_antisite_def_struct_gen(c_size=vac_size,struct=final_str)
    def_list,header_list=def_energy(vac=vac,parameters = parameters)
    #print def_list,header_list
    try:
     if vac_cal==True:
       print ('in defect calc')
       vac=vac_antisite_def_struct_gen(c_size=vac_size,struct=final_str)
       def_list,header_list=def_energy(vac=vac,parameters = parameters)
       print ('done defect calc',def_list,header_list)
    except:
       pass
    try:
     if surf_cal==True:
        print ('in surf calc')
        surf=pmg_surfer(mat=final_str, min_slab_size=surf_size,vacuum=25,max_index=3)
        surf_list,surf_header_list=surf_energy(surf=surf,parameters = parameters)
        print ('done surf calc',surf_list,surf_header_list)
    except:
       pass
    try:
     if phon_cal==True:
       print ('in phon calc')
       cwd=str(os.getcwd())
       if not os.path.exists("Phonon"):
          os.mkdir("Phonon")
       os.chdir("Phonon")
       do_phonons(strt=final_str,parameters=parameters)
       print ('done phon calc')
       os.chdir(cwd)
    except:
       pass
Exemplo n.º 15
0
    def create_slab(self, vacuum=12, thickness=10):
        """
        set the vacuum spacing, slab thickness and call sd_flags
        for top 2 layers

        returns the poscar corresponding to the modified structure
        """
        strt_structure = self.input_structure.copy()
        if self.from_ase:
            slab_struct = get_ase_slab(strt_structure,
                                       hkl=self.system['hkl'],
                                       min_thick=thickness,
                                       min_vac=vacuum)
        else:
            slab_struct = SlabGenerator(initial_structure=strt_structure,
                                        miller_index=self.system['hkl'],
                                        min_slab_size=thickness,
                                        min_vacuum_size=vacuum,
                                        lll_reduce=False,
                                        center_slab=True,
                                        primitive=False).get_slab()
        slab_struct.sort()
        sd = self.set_sd_flags(slab_struct)
        comment = 'VAC' + str(vacuum) + 'THICK' + str(thickness)
        return Poscar(slab_struct, comment=comment, selective_dynamics=sd)
Exemplo n.º 16
0
def get_magmom_afm(poscar, database=None):
    """
    returns the magmom string which is an N length list
    """

    afm_magmom = []
    orig_structure_name = poscar.comment

    if len(poscar.structure) % 2 != 0:

        if database == 'twod':
            # no need for more vacuum spacing
            poscar.structure.make_supercell([2, 2, 1])
        else:
            # for bulk structure
            poscar.structure.make_supercell([2, 2, 2])

    sites_dict = poscar.as_dict()['structure']['sites']

    for n, s in enumerate(sites_dict):

        if Element(s['label']).is_transition_metal:
            if n % 2 == 0:
                afm_magmom.append(6.0)
            else:
                afm_magmom.append(-6.0)

        else:
            if n % 2 == 0:
                afm_magmom.append(0.5)
            else:
                afm_magmom.append(-0.5)

    return afm_magmom, Poscar(structure=poscar.structure,
                              comment=orig_structure_name)
Exemplo n.º 17
0
    def convert_computed_entry_to_job(self,entry):
        """
        Convert ComputedStructureEntry into VaspJob object

        Parameters
        ----------
        entry : 
            ComputedStructureEntry.

        Returns
        -------
        vaspjob : 
            VaspJob object.
        """
        e = entry
        path = e.data['dir_name']
        
        inp = e.data['calculations'][0]['input']           
        incar = Incar(inp['incar'])
        kpoints = Kpoints.from_dict(inp['kpoints'])
        poscar = Poscar(e.structure)
        potcar = Potcar(inp['potcar'])
        
        inputs = VaspInput(incar, kpoints, poscar, potcar)
        job_settings = e.data['job_settings']
        job_script_filename = e.data['job_script_filename']
        name = e.data['job_name']
        
        outputs = {'ComputedStructureEntry':e}
        
        vaspjob =  VaspJob(path,inputs,job_settings,outputs,job_script_filename,name)
        vaspjob._is_converged = e.data['is_converged']
        vaspjob._band_structure = None
            
        return vaspjob            
Exemplo n.º 18
0
    def test_significant_figures(self):
        si = 14
        coords = list()
        coords.append([0, 0, 0])
        coords.append([0.75, 0.5, 0.75])

        # Silicon structure for testing.
        latt = [[3.8401979337, 0.00, 0.00], [1.9200989668, 3.3257101909, 0.00],
                [0.00, -2.2171384943, 3.1355090603]]
        struct = Structure(latt, [si, si], coords)
        poscar = Poscar(struct)
        expected_str = '''Si2
1.0
3.84 0.00 0.00
1.92 3.33 0.00
0.00 -2.22 3.14
Si
2
direct
0.00 0.00 0.00 Si
0.75 0.50 0.75 Si
'''

        actual_str = poscar.get_string(significant_figures=2)
        self.assertEqual(actual_str, expected_str, "Wrong POSCAR output!")
Exemplo n.º 19
0
    def get_vaspjob(self,setname='',pathname=''):
        """
        Generate VaspJob object from the input settings of the class.

        Parameters
        ----------
        setname : (str), optional
            String to be added to 'name' key in job_settings dictionary and to name attribute of VaspJob. The default is ''.
        pathname : (str), optional
            String to be added to self.path. The complete path will be input in 'path' arg of VaspJob. The default is ''.

        Returns
        -------
        vaspjob : (VaspJob object)
        """        
        incar_settings = self.incar_settings.copy()
        job_settings = self.job_settings.copy()
        
        incar = Incar(incar_settings)
        kpoints = self.kpoints
        poscar = Poscar(self.structure)
        potcar = self.potcar
        vaspinput = VaspInput(incar,kpoints,poscar,potcar)
        job_settings['name'] = '_'.join([self.job_settings['name'],setname])
        
        jobname = '_'.join([self.name,setname])
        jobpath = op.join(self.path,pathname)
        job_script_filename = job_settings['filename'] if 'filename' in job_settings.keys() else None
        vaspjob = VaspJob(path=jobpath,inputs=vaspinput,job_settings=job_settings,job_script_filename=job_script_filename,name=jobname)
        
        return vaspjob  
Exemplo n.º 20
0
def write_vasp_input(structure: IStructure,
                     kpath_division: int,
                     write_dir: str = "."):
    vasp_input = VaspInput(
        Incar.from_file("INCAR"),
        Kpoints.automatic_linemode(kpath_division, HighSymmKpath(structure)),
        Poscar(structure), Potcar.from_file("POTCAR"))
    vasp_input.write_input(write_dir)
Exemplo n.º 21
0
def test_get_poscar_method(minimal_pymatgen_structure):
    from pymatgen.io.vasp.inputs import Poscar
    poscar = VaspPoscarData(structure=minimal_pymatgen_structure)
    # assert retrieved poscar equals reference
    reference_poscar = Poscar(structure=minimal_pymatgen_structure)
    retrieved_poscar = poscar.get_poscar()
    assert isinstance(retrieved_poscar, Poscar) is True
    assert str(retrieved_poscar) == str(reference_poscar)
Exemplo n.º 22
0
def create_surface2(st,
                    miller_index,
                    min_slab_size=10,
                    min_vacuum_size=10,
                    surface_i=0,
                    oxidation=None,
                    suf='',
                    primitive=None,
                    symmetrize=False):
    """
    INPUT:
        st (Structure) - Initial input structure. Note that to
                ensure that the miller indices correspond to usual
                crystallographic definitions, you should supply a conventional
                unit cell structure.

        miller_index ([h, k, l]): Miller index of plane parallel to
                        surface. Note that this is referenced to the input structure. If
                        you need this to be based on the conventional cell,
                        you should supply the conventional structure.


        oxidation (dic) - dictionary of effective oxidation states, e. g. {'Y':'Y3+', 'Ba':'Ba2+', 'Co':'Co2.25+', 'O':'O2-'}
                          allows to calculate dipole moment

        surface_i (int) - choose particular surface 

        min_slab_size (float) - minimum slab size

        min_vacuum_size (float) - vacuum thicknes in A

    """

    from pymatgen.core.surface import SlabGenerator
    from pymatgen.io.vasp.inputs import Poscar
    from geo import replic

    pm = st.convert2pymatgen(oxidation=oxidation)
    # pm = st.convert2pymatgen()

    slabgen = SlabGenerator(pm,
                            miller_index,
                            min_slab_size,
                            min_vacuum_size,
                            primitive=primitive)
    # print(slabgen.oriented_unit_cell)
    slabs = slabgen.get_slabs(symmetrize=symmetrize)

    printlog(
        len(slabs),
        'surfaces were generated, choose required surface using *surface_i* argument\nWriting POSCARs to xyz',
        imp='y')

    for i, slab in enumerate(slabs):
        pos = Poscar(slab)
        pos.write_file('xyz/POSCAR_suf' + str(i) + str(suf))

    return slabs
Exemplo n.º 23
0
    def poscar(self):
        """
        Similar to the standard POSCAR, but with selective dynamics added.

        Returns:
            :class: pymatgen.io.vasp.inputs.Poscar
        """
        return Poscar(self.structure,
                      selective_dynamics=self.selective_dynamics)
Exemplo n.º 24
0
def test_init_from_structure_types(minimal_pymatgen_structure):
    pymatgen_structure = minimal_pymatgen_structure
    pymatgen_poscar = Poscar(minimal_pymatgen_structure)
    aiida_structure = StructureData(pymatgen_structure=pymatgen_structure)
    reference_poscar = pymatgen_poscar
    # initialize poscar using different structure types
    for struct in [pymatgen_structure, pymatgen_poscar, aiida_structure]:
        poscar = VaspPoscarData(structure=struct)
        assert str(poscar.get_poscar()) == str(reference_poscar)
Exemplo n.º 25
0
def run_aconvasp_command(command, structure):
    """
    Helper function for calling aconvasp with different arguments
    """
    poscar = Poscar(structure)
    p = subprocess.Popen(command, stdout=subprocess.PIPE,
                         stdin=subprocess.PIPE,
                         stderr=subprocess.PIPE)
    output = p.communicate(input=poscar.get_string())
    return output
Exemplo n.º 26
0
def remove_half(st, el, sg=None):
    """
    # works only for 

    sg - required space group

    TODO
    1. Take care about matching the initial cell and supercell from primitive
    Now the manual shift is done

    2. Make full conversion from pymat structure to mine

    """

    from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
    from pymatgen.io.vasp.inputs import Poscar
    from calc_manage import smart_structure_read
    st_ohne_el = st.remove_atoms([el])

    st_only_el = st.leave_only(el)

    st_mp = st_only_el.convert2pymatgen()

    sf = SpacegroupAnalyzer(st_mp)

    st_mp_prim = sf.find_primitive()  # find primitive based only on element el

    #convert back to my format! please improve!!!
    p = Poscar(st_mp_prim)
    p.write_file('xyz/POSCAR')
    st_prim = smart_structure_read('xyz/POSCAR')

    sts = remove_half_based_on_symmetry(st_prim, sg)

    st_only_el_half = sts[
        0]  # now only first configuration is taken, they could be different

    mul_matrix_float = np.dot(st.rprimd, np.linalg.inv(st_prim.rprimd))
    mul_matrix = np.array(mul_matrix_float)
    mul_matrix = mul_matrix.round(0)
    mul_matrix = mul_matrix.astype(int)

    sc_only_el_half = create_supercell(st_only_el_half, mul_matrix=mul_matrix)

    sc_only_el_half = sc_only_el_half.shift_atoms([0.125, 0.125, 0.125])
    sc_only_el_half = sc_only_el_half.return_atoms_to_cell()

    # st_only_el.write_poscar('xyz/POSCAR1')
    # sc_only_el_half.write_poscar('xyz/POSCAR2')

    st_half = st_ohne_el.add_atoms(sc_only_el_half.xcart, el)

    st_half.name += '_half' + str(sg)

    return st_half
Exemplo n.º 27
0
def main_func(mpid='', jid='', mat=None, enforc_cvn=False):
    """
    Main function to carry out property calculations

    Args:
        mpid: materialsproject id
        jid: jarvis-dft id
        mat: Poscar object
        enforc_cvn:  whether or not enforce conventional cell input structure
    Returns:
       en: final energy
       final: final structure
    """

    if mpid != '' or jid != '':
        data = loadfn(json_dat, cls=MontyDecoder)
        for d in data:
            mmpid = str(d['mpid'])
            jjid = str(d['mpid'])
            if mmpid == mpid:
                fin = (d['structure'])
                break
            if jjpid == jid:
                fin = (d['structure'])
                break

        strt = fin
        sg_mat = SpacegroupAnalyzer(strt)
        mat_cvn = sg_mat.get_conventional_standard_structure()
        mat_cvn.sort()
        if int(strt.composition._natoms) == int(
                mat_cvn.composition._natoms) and enforc_cvn == True:
            mat = Poscar(mat_cvn)
        else:
            mat = Poscar(strt)

        mpid = mpid.replace('-', '_')
        mpid = str('bulk@') + str(mpid)
        mat.comment = mpid

    en, final = smart_converge(mat=mat)
    print(en, final)
Exemplo n.º 28
0
def write_deformed_poscars(deformed_structures, directory=None):
    if not directory:
        directory = "."
    directory = Path(directory)
    n_deformations = len(deformed_structures)
    n_digits = int(np.floor(np.log10(n_deformations)) + 2)
    for i, deformed_structure in enumerate(deformed_structures):
        # pad with leading zeros so the files are sorted correctly
        filename = "POSCAR-{0:0{1}}".format(i + 1, n_digits)
        deform_poscar = Poscar(deformed_structure)
        deform_poscar.write_file(directory / filename, significant_figures=16)
Exemplo n.º 29
0
 def _write_poscar(self, struct):
     """
     Writes POSCAR file.
     
     Arguments
     ---------
     struct: pymatgen.Strucuture
         Atomic structure itself.
     """
     with open("POSCAR", mode="w") as file:
         file.writelines(str(Poscar(struct)))
Exemplo n.º 30
0
def convert(bulk, slab, index, output, generate=True, print_M=True):
    primitiveCell = mg.Structure.from_file(bulk)
    refSlab = mg.Structure.from_file(slab)
    sa = SpacegroupAnalyzer(primitiveCell)
    conventionalCell = sa.get_conventional_standard_structure()
    conventionalCell.to(filename='POSCAR.conventional')
    bulk = read('POSCAR.conventional')
    os.remove('POSCAR.conventional')
    slab = surface(bulk, index, layers=2, vacuum=10)
    lattice, _, _ = spglib.standardize_cell(cell=(slab.get_cell(),
                                                  slab.get_scaled_positions(),
                                                  slab.get_atomic_numbers()),
                                            no_idealize=True)
    lattice_params = np.sort(np.linalg.norm(lattice, axis=1))[:2]
    scales = np.round(
        np.array([refSlab.lattice.a, refSlab.lattice.b] / lattice_params), 2)
    newLattice = []
    oldLattice = refSlab.lattice
    for length, scale in zip([oldLattice.a, oldLattice.b], scales):
        for j in range(len(lattice)):
            if abs((np.linalg.norm(lattice[j]) * scale) - length) < 1e-1:
                newLattice.append(copy.copy(scale * lattice[j][:]))
                lattice[j] = [0, 0, 0]
                break
    for i in range(len(lattice)):
        norm = np.linalg.norm(lattice[i])
        if norm > 1e-1:
            newLattice.append(lattice[i] / norm * oldLattice.c)
            break
    newLattice = Lattice(np.array(newLattice))
    for x, y in zip(oldLattice.angles, newLattice.angles):
        assert abs(
            x - y
        ) < 1e-2, "The converted lattice has incorrect angles: {} compared with reference slab: {}".format(
            " ".join(str(x) for x in newLattice.angles),
            " ".join(str(x) for x in oldLattice.angles))
    newSlab = Structure(newLattice, [], [])
    for atom in refSlab:
        newSlab.append(atom.specie, atom.frac_coords[:])

    if generate:
        Poscar(newSlab.get_sorted_structure()).write_file(output, direct=True)

    transformMat = newSlab.lattice.matrix.dot(
        np.linalg.inv(primitiveCell.lattice.matrix))
    transformMat = transformMat.round().astype(int)
    if print_M:
        print('-------------------------------------------')
        print('Your Transformtaion Matrix is:')
        print(' ')
        print(transformMat)
        print('-------------------------------------------')

    return transformMat