def gen_forceconstants(species, index, cart, displacement=0.1, hour=5, np=48, template_dir='templates'): """ generate directory and POSCAR perturbation Args: species(str): Name of perturbed atom. """ target_dir = "{spec}_{index}_{cart}_disp".format(spec=species, index=index, cart=cart[1]) dir_util.copy_tree(template_dir, target_dir) with pushd(target_dir) as ctx0: #Fix the pbs string with open('vasp.sh', 'r') as f: pbs_str = f.read() pbs_str = pbs_str.format(hour=hour, index=index, np=np, species=species) with open('vasp.sh', 'w') as f: print >> f, pbs_str ats = vasp.read_vasp('POSCAR') print "before pert", ats[index].position[:] ats[index].position[cart[0]] += displacement print "after pert", ats[index].position[:] vasp.write_vasp("POSCAR", ats)
def write(self): self.atoms.write("CN.xyz") write_vasp("POSCAR", self.atoms, sort="True", direct=True, vasp5=True) poscar = open("POSCAR") unit_cell = UnitCell(poscar) unit_cell.num_atom_types = len(self.elements) tools.write(unit_cell.output_lammps(), "structure")
def write_poscar(self, fname=None): """Write the POSCAR file.""" if fname is None: fname = os.path.join(self.directory, 'POSCAR') from ase.io.vasp import write_vasp write_vasp(fname, self.atoms_sorted, symbol_count=self.symbol_count)
def calc_stress(pos_optimized, cell_strain, method_stress_statistics, stress_set_dict, num_last_samples, up, cwd): pos_strain = deepcopy(pos_optimized) pos_strain.set_cell(cell_strain, scale_atoms=True) if method_stress_statistics == 'dynamic': #pos_supercell = pos_strain.repeat((int(indict['repeat_num'][0]),int(indict['repeat_num'][1]),int(indict['repeat_num'][2]))) step = 'NVT-MD' tag = 'Total+kin.' kpoints_file_name = 'KPOINTS-dynamic' #vasp.write_vasp('POSCAR', pos_supercell, vasp5=True, direct=True) vasp.write_vasp('POSCAR', pos_strain, vasp5=True, sort=True, direct=True) else: vasp.write_vasp('POSCAR', pos_strain, vasp5=True, sort=True, direct=True) step = 'fixed-volume-opt' tag = 'in kB' kpoints_file_name = 'KPOINTS-static' # calculate stresses via static or molecular dynamics at fixed pressure and/or temperature vasp_run(step, kpoints_file_name, cwd) run_mode = int(indict['run_mode'][0]) if run_mode == 1 or run_mode == 3: stress = mean_stress('OUTCAR', num_last_samples, tag) stress_set_dict[up].append(stress) return stress_set_dict
def write_interstitials(ats, ttol=0.5): vasp_args = dict(xc='PBE', amix=0.01, amin=0.001, bmix=0.001, amix_mag=0.01, bmix_mag=0.001, kpts=[3, 3, 3], kpar=6, lreal='auto', ibrion=1, nsw=50, nelmdl=-15, ispin=2, prec='High', nelm=100, algo='VeryFast', npar=24, lplane=False, lwave=False, lcharg=False, istart=0, voskown=0, ismear=1, sigma=0.1, isym=2) vasp = Vasp(**vasp_args) vasp.initialize(ats) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5=True)
def write_input_files(self, at, label): global _chdir_lock # For LOTF Simulations active number of quantum # atoms vary and must wait to this stage in order for # magnetic moments to be set properly. If magnetic moments # not set defaults to 0. self.vasp_args['magmom'] = at.get_initial_magnetic_moments() vasp = Vasp(**self.vasp_args) vasp.initialize(at) # chdir not thread safe, so acquire global lock before using it orig_dir = os.getcwd() try: _chdir_lock.acquire() os.chdir(self.subdir) if os.path.exists('OUTCAR'): n = 1 while os.path.exists('OUTCAR.%d' % n): n += 1 shutil.copyfile('OUTCAR', 'OUTCAR.%d' % n) shutil.copyfile('POSCAR', 'POSCAR.%d' % n) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5='5' in self.exe) vasp.write_incar(at) vasp.write_potcar() vasp.write_kpoints() finally: os.chdir(orig_dir) _chdir_lock.release()
def prepare_wannier_gamma(self, band=0): hamk_gamma = self.model.make_hamk([0, 0, 0]) hamk_gamma = (hamk_gamma + hamk_gamma.conj().T) / 2 red_hamk_gamma = hamk_gamma[1::3, 1::3] red_hamk_gamma = asr(red_hamk_gamma) #print("Freqs: ", dym_to_freq(red_hamk_gamma)[band]) freqs, evecs = dym_to_freq(red_hamk_gamma) masses = self.atoms.get_masses() disp = eig_vec_to_eig_disp(evecs[:, band], masses, dimension=1) disp = np.real(disp) #print disp disp = np.kron(disp, [0, 0, 1]) disp.resize([5, 3]) # print disp for amp in [0.0, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2]: disp_atoms = copy.copy(self.atoms) disp_atoms.translate(disp * amp) disp_dir = os.path.join( './Wannier', self.atoms.get_chemical_formula(mode='reduce'), 'Gamma_%s' % amp) # print disp_dir # print disp * amp if not os.path.exists(disp_dir): os.makedirs(disp_dir) write_vasp(os.path.join(disp_dir, 'POSCAR_disp.vasp'), disp_atoms, vasp5=True)
def write(self): self.atoms.write("CN.xyz") write_vasp("POSCAR",self.atoms,sort="True",direct=True,vasp5=True) poscar = open("POSCAR") unit_cell = UnitCell(poscar) unit_cell.num_atom_types=len(self.elements) tools.write(unit_cell.output_lammps(),"structure")
def write_input(self, atoms, directory='./'): from ase.io.vasp import write_vasp write_vasp(join(directory, 'POSCAR'), self.atoms_sorted, symbol_count=self.symbol_count) self.write_incar(atoms, directory=directory) self.write_potcar(directory=directory) self.write_kpoints(directory=directory) self.write_sort_file(directory=directory)
def get_poscar_from_atoms(atoms): poscar = io.StringIO() write_vasp(file=poscar, atoms=atoms, vasp5=True, long_format=False, direct=True) return poscar.getvalue()
def calculate(self, atoms): """Generate necessary files in the working directory. If the directory does not exist it will be created. """ positions = atoms.get_positions() from ase.io.vasp import write_vasp write_vasp('POSCAR', self.atoms_sorted, symbol_count = self.symbol_count) self.write_incar(atoms) self.write_potcar() self.write_kpoints() self.write_sort_file() stderr = sys.stderr p=self.input_parameters if p['txt'] is None: sys.stderr = devnull elif p['txt'] == '-': pass elif isinstance(p['txt'], str): sys.stderr = open(p['txt'], 'w') if os.environ.has_key('VASP_COMMAND'): vasp = os.environ['VASP_COMMAND'] exitcode = os.system(vasp) elif os.environ.has_key('VASP_SCRIPT'): vasp = os.environ['VASP_SCRIPT'] locals={} execfile(vasp, {}, locals) exitcode = locals['exitcode'] else: raise RuntimeError('Please set either VASP_COMMAND or VASP_SCRIPT environment variable') sys.stderr = stderr if exitcode != 0: raise RuntimeError('Vasp exited with exit code: %d. ' % exitcode) atoms_sorted = ase.io.read('CONTCAR', format='vasp') p=self.incar_parameters if p['ibrion']>-1 and p['nsw']>0: atoms.set_positions(atoms_sorted.get_positions()[self.resort]) self.positions = atoms.get_positions() self.energy_free, self.energy_zero = self.read_energy() self.forces = self.read_forces(atoms) self.dipole = self.read_dipole() self.fermi = self.read_fermi() self.atoms = atoms.copy() self.nbands = self.read_nbands() if self.spinpol: self.magnetic_moment = self.read_magnetic_moment() if p['lorbit']>=10 or (p['lorbit']!=None and p['rwigs']): self.magnetic_moments = self.read_magnetic_moments(atoms) self.old_incar_parameters = self.incar_parameters.copy() self.old_input_parameters = self.input_parameters.copy() self.converged = self.read_convergence()
def data_write(self, filename): if filename.endswith(".con"): tsase.io.write_con(filename, self.get_frame_atoms()) elif filename.endswith(".bx"): tsase.io.write_bopfox(filename, self.get_frame_atoms()) else: if '.' not in filename: vasp.write_vasp(filename, self.get_frame_atoms()) else: ase.io.write(filename, self.get_frame_atoms()) self.set_title(os.path.abspath(filename))
def write_poscar(self, inputdict, dst): ''' converts from structures node (StructureData) to POSCAR format and writes to dst :param inputdict: required by baseclass :param dst: absolute path of the file to write to ''' from ase.io.vasp import write_vasp with open(dst, 'w') as poscar: write_vasp(poscar, self.inp.structure.get_ase(), vasp5=True)
def relax_poscar(poscar_file, calc, fmax=1e-4): atoms = read(poscar_file) atoms.set_calculator(calc) ecf = ExpCellFilter(atoms) opt = BFGS(ecf) opt.run(fmax=fmax) write_vasp('POSCAR-opt', atoms, vasp5=True) return
def prepare_input_files(self): # Initialize calculations atoms = self.get_atoms() self.initialize(atoms) # Write input from ase.io.vasp import write_vasp write_vasp('POSCAR', self.atoms_sorted, symbol_count=self.symbol_count) self.write_incar(atoms) self.write_potcar() self.write_kpoints() self.write_sort_file() self.create_metadata()
def generate_vaspinput(ele1="Ti", ele2="O", a_ref=5.05): # C1 CaF2 a = a_ref atoms = crystal([ele1, ele2], [(0.0, 0.5, 0.5), (0.25, 0.25, 0.25)], spacegroup=225, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("C1"): os.mkdir("C1") os.chdir("C1") write_vasp("POSCAR", atoms, label="C1", direct=True, long_format=True, vasp5=True) os.chdir("..") # C2 FeS2 a = a_ref atoms = crystal( [ele1, ele2], [(0.0, 0.0, 0.0), (0.38504, 0.38504, 0.38504)], spacegroup=205, cellpar=[a, a, a, 90, 90, 90] ) if not os.path.exists("C2"): os.mkdir("C2") os.chdir("C2") write_vasp("POSCAR", atoms, label="C2", direct=True, long_format=True, vasp5=True) os.chdir("..") # C3 Cu2O a = a_ref * 0.917 atoms = crystal([ele1, ele2], [(0.0, 0.0, 0.0), (0.25, 0.25, 0.25)], spacegroup=224, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("C3"): os.mkdir("C3") os.chdir("C3") write_vasp("POSCAR", atoms, label="C3", direct=True, long_format=True, vasp5=True) os.chdir("..") # C4 TiO2 (rutile) a = a_ref * 0.9278 c = a * 0.6440 atoms = crystal( [ele1, ele2], [(0.0, 0.0, 0.0), (0.3057, 0.3057, 0.0)], spacegroup=136, cellpar=[a, a, c, 90, 90, 90] ) if not os.path.exists("C4"): os.mkdir("C4") os.chdir("C4") write_vasp("POSCAR", atoms, label="C4", direct=True, long_format=True, vasp5=True) os.chdir("..") # C5 TiO2 (anatase) a = a_ref * 0.7798 c = a * 2.514 atoms = crystal([ele1, ele2], [(0.0, 0.0, 0.0), (0.0, 0.0, 0.2081)], spacegroup=141, cellpar=[a, a, c, 90, 90, 90]) if not os.path.exists("C5"): os.mkdir("C5") os.chdir("C5") write_vasp("POSCAR", atoms, label="C5", direct=True, long_format=True, vasp5=True) os.chdir("..")
def gen_orient(mol,frm,N_images): i = 0 while i < N_images: #np.random.seed(i) #Create copy of atoms object 'mol'. mol_cp = mol.copy() #Randomly generate rotation about COM axis for gas mol placement. rot_gen = np.multiply(np.random.random_sample([3]),np.array([180,180,180])) mol_cp.euler_rotate(phi=rot_gen[0],theta=rot_gen[1],psi=rot_gen[2],center=('COM')) #Randomly generate center of mass position for gas mol to be placed. com_gen = np.random.random_sample([3]) #Replicate com_gen vector along axis= 0 to form array. com_gen = np.tile(com_gen,(len(mol_cp.get_chemical_symbols()),1)) #Translate gas mol to new com position and wrap atoms outstanding from unit cell. mol_cp.set_scaled_positions(np.add(mol_cp.get_scaled_positions(),com_gen)) mol_cp.wrap() #Create system 'frm_mol' by appending mol atoms object to framework atoms object. mol_frm = mol_cp+frm #Generate POTCAR file. make_POTCAR(mol_frm) #Generate INCAR file. (Just pull it from bin for now- FIX LATER) subprocess.call("cp ~/bin/INCARS_other_functionals/DFT-D2/INCAR .",shell=True) #Generate submission script, again just pull from bin for now. subprocess.call("cp ~/bin/submit_vasp_gam.sh .",shell=True) #Generate KPOINTS file, again just pull from bin for now. subprocess.call("cp ~/bin/KPOINTS .",shell=True) #Ensure new com position does not overlap with framework atoms. atoms_far_enough_criteria = 0 for j,atom in enumerate(mol_frm[0:mol.get_global_number_of_atoms()]): dist = mol_frm.get_distances(j,range(mol.get_global_number_of_atoms(),mol_frm.get_global_number_of_atoms())) if np.amin(dist) > 1.0:#Adjust this for molecule placement. Helps avoid overlap! atoms_far_enough_criteria += 1 if atoms_far_enough_criteria == mol.get_global_number_of_atoms(): f_out_dir = ('CONTCAR_%s' % str(i)) f_out = ('POSCAR') vasp.write_vasp(f_out,mol_cp+frm) #view(mol_frm) #uncomment to view formed CONTCARs within ASE gui. subprocess.call("mkdir "+f_out_dir,shell=True) subprocess.call("mv KPOINTS POTCAR submit_vasp_gam.sh INCAR POSCAR "+f_out_dir,shell=True) i += 1 continue
def optimize_initial_str(pos_conv, cwd, tag): if not isdir('OPT'): mkdir('OPT') chdir('OPT') vasp.write_vasp('POSCAR', pos_conv, vasp5=True, direct=True) kpoints_file_name = 'KPOINTS-static' pos_optimized = vasp_run(tag, kpoints_file_name, cwd) chdir('..') return pos_optimized
def main(filename, source, x=1, y=1, z=1): temp = list(xyz.read_xyz(filename))[0] if source == "NA": temp.cell = Cell([[x, 0, 0], [0, y, 0], [0, 0, z]]) else: try: temp.cell = vasp.read_vasp(source).cell except: raise Exception("source is neither valid POSCAR nor NA") vasp.write_vasp("../POSCAR_ec", temp, sort=True, vasp5=True)
def calculate(self, atoms): """Generate necessary files in the working directory and run VASP. The method first write VASP input files, then calls the method which executes VASP. When the VASP run is finished energy, forces, etc. are read from the VASP output. """ cwd = os.getcwd() if os.path.exists('/data') and self.tempdir is None: self.tempdir = tempfile.mkdtemp(prefix='vasptmp_', dir='/data') with open('./syncpath.txt', 'w') as myfile: myfile.write('%s:%s\n' % (socket.gethostname(), self.tempdir)) if self.tempdir is not None: print(('rsync -a ./* %s' % self.tempdir)) os.system('rsync -a ./* %s' % self.tempdir) os.chdir(self.tempdir) print(("Changing path to %s" % self.tempdir)) # Initialize calculations self.initialize(atoms) # Write input from ase.io.vasp import write_vasp write_vasp('POSCAR', self.atoms_sorted, symbol_count=self.symbol_count) self.write_incar(atoms) self.write_potcar() self.write_kpoints() self.write_sort_file() # Execute VASP if not self.force_no_calc: self.run() # Read output atoms_sorted = ase.io.read('CONTCAR', format='vasp') if (not (self.int_params['ibrion'] is None or self.int_params['nsw'] is None)) and (self.int_params['ibrion'] > -1 and self.int_params['nsw'] > 0): # Update atomic positions and unit cell with the ones read # from CONTCAR. atoms.positions = atoms_sorted[self.resort].positions atoms.cell = atoms_sorted.cell self.converged = self.read_convergence() self.set_results(atoms) if self.tempdir is not None: print("Sync back") print(('rsync -a %s/* %s' % (self.tempdir, cwd))) os.system('rsync -a %s/* %s' % (self.tempdir, cwd)) os.chdir(cwd)
def randomGrid(adsorbate, slab, h=2, outputDir="tempout/", numDirs=10, runsPerDir=17, shallow=False, kind='gen'): """ Produces a collection of structures with adsorbate randomly placed on given slab. Writes (.gen or vasp) outputs to desired directory Args: adsorbate: Atoms obj of adsorbate slab: Atoms obj of slab h: height of adsorbate (above max slab position) outputDir: Path (str) for desired output location. numDirs: Number of batches. Defaults to 10. runsPerDir: Number of sims per batch. Defaults to 17. shallow: If all runs to be at one directory level. Defaults to False. kind: output desired, from (gen, vasp). Defaults to gen. Returns: None """ np.random.seed(429) for d in range(numDirs): for run in range(runsPerDir): s = slab.copy() # generate random positions with dummy z required (3) p = s.cell.cartesian_positions(np.random.random(3)) # construct and write add_adsorbate(s, adsorbate, height=h, position=p[:2]) if kind == 'gen': outname = "input{}-{}.gen".format( d, run) if not shallow else "input{}.gen".format( d * runsPerDir + run) gen.write_gen(outputDir + outname, s) elif kind == 'vasp': outname = "POSCAR{}-{}".format( d, run) if not shallow else "POSCAR{}".format(d * runsPerDir + run) vasp.write_vasp(outputDir + outname, s, sort=True, vasp5=True) else: raise AssertionError("kind should be from (vasp, gen)")
def gen_orient(mol, frm, N_images): i = 0 while i < N_images: #np.random.seed(i) #Create copy of atoms object 'mol'. mol_cp = mol.copy() #Randomly generate rotation about x,y,z axis for gas mol placement. rot_gen = np.multiply(np.random.random_sample([3]), np.array([180, 180, 180])) mol_cp.euler_rotate(phi=rot_gen[0], theta=rot_gen[1], psi=rot_gen[2], center=(0, 0, 0)) #Randomly generate center of mass position for gas mol to be placed. com_gen = np.random.random_sample([3]) #Replicate com_gen vector along axis= 0 to form array. com_gen = np.tile(com_gen, (len(mol.get_chemical_symbols()), 1)) #Translate gas mol to new com position and wrap atoms outstanding from unit cell. mol_cp.set_scaled_positions(np.add(mol.get_scaled_positions(), com_gen)) mol_cp.wrap() #Create system 'frm_mol' by appending mol atoms object to framework atoms object. mol_frm = mol_cp + frm #Ensure new com position does not overlap with framework atoms. atoms_far_enough_criteria = 0 for j, atom in enumerate(mol_frm[0:mol.get_global_number_of_atoms()]): dist = mol_frm.get_distances( j, range(mol.get_global_number_of_atoms(), mol_frm.get_global_number_of_atoms())) if np.amin( dist ) > 5.0: #Adjust this for molecule placement. Helps avoid overlap! atoms_far_enough_criteria += 1 if atoms_far_enough_criteria == mol.get_global_number_of_atoms(): f_out = ('CONTCAR_%s' % str(i)) vasp.write_vasp(f_out, mol_cp + frm) view(mol_frm) i += 1 continue
def write(self, filename, format=None): """Write VASP charge density in CHG format. filename: str Name of file to write to. format: str String specifying whether to write in CHGCAR or CHG format. """ import ase.io.vasp as aiv if format is None: if filename.lower().find('chgcar') != -1: format = 'chgcar' elif filename.lower().find('chg') != -1: format = 'chg' elif len(self.chg) == 1: format = 'chgcar' else: format = 'chg' with open(filename, 'w') as f: for ii, chg in enumerate(self.chg): if format == 'chgcar' and ii != len(self.chg) - 1: continue # Write only the last image for CHGCAR aiv.write_vasp(f, self.atoms[ii], direct=True, long_format=False) f.write('\n') for dim in chg.shape: f.write(' %4i' % dim) f.write('\n') vol = self.atoms[ii].get_volume() self._write_chg(f, chg, vol, format) if format == 'chgcar': f.write(self.aug) if self.is_spin_polarized(): if format == 'chg': f.write('\n') for dim in chg.shape: f.write(' %4i' % dim) f.write('\n') # a new line after dim is required self._write_chg(f, self.chgdiff[ii], vol, format) if format == 'chgcar': # a new line is always provided self._write_chg f.write(self.augdiff) if format == 'chg' and len(self.chg) > 1: f.write('\n')
def slice(poscar, indices, vacuum, layer=1, name=''): ''' :param poscar: poscar'name :param indices: Miller indices :param vacuum: vacuum's length (A) :param layer: Number of equivalent layers of the slab :return: new poscar ''' if name == '': name = '%s_slab%s' % (poscar, str(indices)) else: pass POSCAR = poscar Atom = read(POSCAR) slab = surface(Atom, indices=indices, layers=layer, vacuum=vacuum) write_vasp(name, slab)
def generate_vaspinput(element="Li", a_ref=3.05): # HCP a = a_ref c = 1.62 * a_ref atoms = crystal(element, [(1.0 / 3.0, 2.0 / 3.0, 3.0 / 4.0)], spacegroup=194, cellpar=[a, a, c, 90, 90, 120]) if not os.path.exists("HCP"): os.mkdir("HCP") os.chdir("HCP") write_vasp("POSCAR", atoms, label="HCP", direct=True, long_format=True, vasp5=True) os.chdir("..") # FCC structure a = a_ref * 1.42 atoms = crystal(element, [(0, 0, 0)], spacegroup=225, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("FCC"): os.mkdir("FCC") os.chdir("FCC") write_vasp("POSCAR", atoms, label="FCC", direct=True, long_format=True, vasp5=True) os.chdir("..") # BCC structure a = a_ref * 1.13 atoms = crystal(element, [(0, 0, 0)], spacegroup=229, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("BCC"): os.mkdir("BCC") os.chdir("BCC") write_vasp("POSCAR", atoms, label="BCC", direct=True, long_format=True, vasp5=True) os.chdir("..") # SCC structure a = a_ref * 0.90 atoms = crystal(element, [(0, 0, 0)], spacegroup=221, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("SCC"): os.mkdir("SCC") os.chdir("SCC") write_vasp("POSCAR", atoms, label="SCC", direct=True, long_format=True, vasp5=True) os.chdir("..") # Diamond a = a_ref * 1.93 atoms = crystal(element, [(0, 0, 0)], spacegroup=227, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("DIAMOND"): os.mkdir("DIAMOND") os.chdir("DIAMOND") write_vasp("POSCAR", atoms, label="DIAMOND", direct=True, long_format=True, vasp5=True) os.chdir("..")
def prepare_input_files(self): """Prepares input files for a calculation. POSCAR, INCAR, POTCAR, KPOINTS, METADATA, and ase-sort.dat. """ # Initialize calculations atoms = self.get_atoms() self.initialize(atoms) # Write input from ase.io.vasp import write_vasp write_vasp('POSCAR', self.atoms_sorted, symbol_count=self.symbol_count) self.write_incar(atoms) self.write_potcar() self.write_kpoints() self.write_sort_file() self.create_metadata()
def scale_iso_cell(atoms, start, end, step, out_name): """ creat the scaling cell for vasp atoms: the Atoms object from ase start: starting fraction end: ending fraction step: the step from start to end out_name: the name for out file, it can be a path. """ cell_list = np.arange(start, end, step) old_cell_vector = atoms.get_cell() new_atoms = atoms.copy() for scale in cell_list: new_atoms.set_cell(old_cell_vector * scale, scale_atoms = True) vasp.write_vasp(out_name + "_{0:.3f}".format(scale), new_atoms, \ direct=True, sort=True) printtbox("create POSCAR for {0:.3f} scaling".format(scale))
def get_almin(self): m = self.m m.atoms = io.read('POSCAR') atoms = m.atoms.repeat(m.supercell) general = """&general \tPREFIX = alm \tMODE = suggest \tNAT = %s; NKD = %s \tKD = %s / """ % (len(atoms), len(m.elements), m.toString(m.elements)) interaction = """&interaction \tNORDER = 2 / """ cell = """&cell \t1.889726 \t%s / """ % ('\n '.join([m.toString(atoms.cell[i]) for i in range(3)])) cutoff = """&cutoff \t*-* None %f / """ % (self.m.shengcut * 1.889726) pos = ' \n'.join([ '\t%s ' % (m.elements.index(a.symbol) + 1) + m.toString(atoms.get_scaled_positions()[i]) for i, a in enumerate(atoms) ]) position = """&position %s / """ % pos s = tl.headtrim(general + interaction + cell + cutoff + position) tl.write(s, 'alm.in') write_vasp('POSCAR-supercell', atoms, sort="True", direct=True, vasp5=True)
def write(self, filename='CHG', format=None): """Write VASP charge density in CHG format. filename: str Name of file to write to. format: str String specifying whether to write in CHGCAR or CHG format. """ import ase.io.vasp as aiv if format is None: if filename.lower().find('chgcar') != -1: format = 'chgcar' elif filename.lower().find('chg') != -1: format = 'chg' elif len(self.chg) == 1: format = 'chgcar' else: format = 'chg' f = open(filename, 'w') for ii, chg in enumerate(self.chg): if format == 'chgcar' and ii != len(self.chg) - 1: continue # Write only the last image for CHGCAR aiv.write_vasp(f, self.atoms[ii], direct=True, long_format=False) f.write('\n') for dim in chg.shape: f.write(' %4i' % dim) f.write('\n') vol = self.atoms[ii].get_volume() self._write_chg(f, chg, vol, format) if format == 'chgcar': f.write(self.aug) if self.is_spin_polarized(): if format == 'chg': f.write('\n') for dim in chg.shape: f.write(' %4i' % dim) self._write_chg(f, self.chgdiff[ii], vol, format) if format == 'chgcar': f.write('\n') f.write(self.augdiff) if format == 'chg' and len(self.chg) > 1: f.write('\n') f.close()
def relax_atoms_pos(pos_optimized, cell_strain, cwd): if not isdir('RELAX'): mkdir('RELAX') chdir('RELAX') #print() #print(cell_strain) pos_strain = deepcopy(pos_optimized) pos_strain.set_cell(cell_strain, scale_atoms=True) vasp.write_vasp('POSCAR', pos_strain, vasp5=True, direct=True) # relax atoms positions under fixed strains kpoints_file_name = 'KPOINTS-static' pos_conv_strain = vasp_run('relax', kpoints_file_name, cwd) chdir('..') return pos_conv_strain
def get_almin(self): m = self.m m.atoms = io.read('POSCAR') atoms = m.atoms.repeat(m.supercell) general = """&general \tPREFIX = alm \tMODE = suggest \tNAT = %s; NKD = %s \tKD = %s / """ % (len(atoms), len(m.elements), m.toString(m.elements)) interaction = """&interaction \tNORDER = 2 / """ cell = """&cell \t1.889726 \t%s / """ % ('\n '.join([m.toString(atoms.cell[i]) for i in range(3)])) cutoff = """&cutoff \t*-* None %f / """ % (self.m.shengcut * 1.889726) pos = ' \n'.join([ '\t%s ' % (m.elements.index(a.symbol) + 1) + m.toString(atoms.get_scaled_positions()[i]) for i, a in enumerate(atoms) ]) position = """&position %s / """ % pos s = tl.headtrim(general + interaction + cell + cutoff + position) tl.write(s, 'alm.in') write_vasp( 'POSCAR-supercell', atoms, sort="True", direct=True, vasp5=True)
def relax_calculation(self, atoms, pre_relax=False, **kwargs): self.set(ionmov=2, ecutsm=0.5, dilatmx=1.1, optcell=2, ntime=50) if kwargs: self.set(**kwargs) self.calculate(atoms=atoms, properties=[]) self.set(ntime=0, toldfe=0.0) newatoms = read_output(fname='abinit.txt', afterend=True) write_vasp('CONTCAR', newatoms, vasp5=True) print(newatoms) scaled_positions = newatoms.get_scaled_positions() cell = newatoms.get_cell() atoms.set_cell(cell) atoms.set_scaled_positions(scaled_positions) if not os.path.exists('RELAX'): os.mkdir('RELAX') for fname in [ 'abinit.in', 'abinit.txt', 'abinit.log', 'abinit.ase', 'CONTCAR' ]: if os.path.exists(fname): shutil.copy(fname, 'RELAX') return atoms
def my_write_vasp(atoms_in, filename='POSCAR', vasp5=True): from ase.io.vasp import write_vasp atoms = copy.deepcopy(atoms_in) pos_a0 = atoms.pos_a0 atoms.set_cell(atoms.get_cell() / pos_a0) atoms.set_positions( atoms.get_positions()/pos_a0, \ apply_constraint=False ) write_vasp('POSCAR_temp', atoms, label='system_name', direct=False, vasp5=vasp5) with open('POSCAR_temp', 'r') as f: lines = f.readlines() lines[1] = ' %.16f \n' % (pos_a0) with open(filename, "w") as f: f.writelines(lines) os.remove('POSCAR_temp')
def equil_md(pos_optimized, cwd): if not isdir('NO_STRAIN_MD'): mkdir('NO_STRAIN_MD') chdir('NO_STRAIN_MD') repeat = [ int(indict['repeat_num'][0]), int(indict['repeat_num'][1]), int(indict['repeat_num'][2]) ] #pos_supercell = make_supercell(pos_optimized, repeat, wrap=True, tol=1e-5) pos_supercell = pos_optimized.repeat(repeat) #vasp.write_vasp('POSCAR', pos_supercell, vasp5=True, direct=True, sort=True) vasp.write_vasp('POSCAR', pos_supercell, direct=True, sort=True, vasp5=True) kpoints_file_name = 'KPOINTS-dynamic' pos_optimized = vasp_run('NPT-MD', kpoints_file_name, cwd) chdir('..') return pos_optimized
def gridVasp(adsorbate, slab, directory='tempout/', spacing=0.2): """ Takes in slab, adsorbate, and desired output directory. Writes numbered POSCAR files to output directory with adsorbate placed in grid pattern Args: adsorbate: either path (str) for POS/CONTCAR or Atoms obj slab: either path (str) for POS/CONTCAR or Atoms obj directory: path (str) for desired output location spacing: spacing between grid points (eg, 0.2 is a 5x5 grid) Returns: None """ if type(adsorbate) == str: adsorbate = vasp.read_vasp(adsorbate) if type(slab) == str: slab = vasp.read_vasp(slab) # TODO: make this work with path objects? i = 0 # 0 index written POSCAR{i} files for _x in np.arange(0, 1 - spacing, spacing): for _y in np.arange(0, 1 - spacing, spacing): s = slab.copy() x, y, z = slab.cell.cartesian_positions([_x, _y, 0]) add_adsorbate(s, adsorbate, height=2, position=(x, y)) s = Atoms(sorted(s, key=lambda x: x.symbol)) s.cell = slab.cell vasp.write_vasp(directory + "POSCAR" + str(i), s, label='{} on {}'.format( adsorbate.get_chemical_formula(), slab.get_chemical_formula()), vasp5=True) i += 1
def write_input_files(self, at, label): global _chdir_lock vasp = Vasp(**self.vasp_args) vasp.initialize(at) # chdir not thread safe, so acquire global lock before using it orig_dir = os.getcwd() try: _chdir_lock.acquire() os.chdir(self.subdir) if os.path.exists('OUTCAR'): n = 1 while os.path.exists('OUTCAR.%d' % n): n += 1 shutil.copyfile('OUTCAR', 'OUTCAR.%d' % n) shutil.copyfile('POSCAR', 'POSCAR.%d' % n) write_vasp('POSCAR', vasp.atoms_sorted, symbol_count=vasp.symbol_count, vasp5='5' in self.exe) vasp.write_incar(at) vasp.write_potcar() vasp.write_kpoints() finally: os.chdir(orig_dir) _chdir_lock.release()
def generate_vaspinput(ele1="Ca", ele2="O", a_ref=3.05): # B1 NaCl a = a_ref atoms = crystal([ele1, ele2], [(0, 0, 0), (0.5, 0.5, 0.5)], spacegroup=225, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("B1"): os.mkdir("B1") os.chdir("B1") write_vasp("POSCAR", atoms, label="B1", direct=True, long_format=True, vasp5=True) os.chdir("..") # B2 CsCl a = a_ref * 0.6975 atoms = crystal([ele1, ele2], [(0, 0, 0), (0.5, 0.5, 0.5)], spacegroup=221, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("B2"): os.mkdir("B2") os.chdir("B2") write_vasp("POSCAR", atoms, label="B2", direct=True, long_format=True, vasp5=True) os.chdir("..") # B3 ZnS Sphalerite (F43m) a = a_ref * 1.086 atoms = crystal([ele1, ele2], [(0, 0, 0), (0.25, 0.25, 0.25)], spacegroup=216, cellpar=[a, a, a, 90, 90, 90]) if not os.path.exists("B3"): os.mkdir("B3") os.chdir("B3") write_vasp("POSCAR", atoms, label="B3", direct=True, long_format=True, vasp5=True) os.chdir("..") # B4 ZnS Wurtzite (p6mc) a = a_ref * 0.8272 c = a * 1.635 atoms = crystal([ele1, ele2], [(0.3333, 0.6667, 0), (0.3333, 0.6667, 0.3748)], spacegroup=186, cellpar=[a, a, c, 90, 90, 120]) if not os.path.exists("B4"): os.mkdir("B4") os.chdir("B4") write_vasp("POSCAR", atoms, label="B4", direct=True, long_format=True, vasp5=True) os.chdir("..")
def evaluate_indiv(self, Optimizer, individ, relax): logger = logging.getLogger(Optimizer.loggername) logger.info('Setting up MAST input for individual evaluation with VASP') self.setup_mast_inp(Optimizer, individ, self.args, relax) num = 0 for ind in individ: totalsol = compose_structure(Optimizer,ind) write_vasp('POSCAR_Indiv%s'%num, totalsol, direct=True, vasp5=True) num += 1 #try: # os.mkdir('scratch') # os.mkdir('archive') #except OSError: # pass cwd = os.getcwd() #scratch = os.path.join(cwd,'scratch') #archive = os.path.join(cwd,'archive') #os.environ['MAST_SCRATCH'] = scratch #os.environ['MAST_ARCHIVE'] = archive scratch = os.getenv('MAST_SCRATCH') archive = os.getenv('MAST_ARCHIVE') #proc = Popen(['mast','-i','my_mast.inp']) #proc.wait() mast = MASTInput(inputfile="my_mast.inp") ind_folders = mast.check_independent_loops() for files in glob.glob("loop_*.inp"): os.remove(files) logger.info('Completed setting up MAST jobs for individual evaluation of generation #%s'%Optimizer.generation) logger.info("Type 'mast' to manually submit VASP jobs or wait for crontab for submission.") while True: #proc = Popen(['mast']) #proc.wait() stats = 'VASP jobs stats:' finished = 'Finished jobs: ' complete = 0 for d in ind_folders: if d in os.listdir(archive): finished += '%s, '%d complete += 1 running = 'Running jobs: ' for d in ind_folders: if d in os.listdir(scratch): running += '%s, '%d logger.info(stats) logger.info(finished) logger.info(running) if complete == len(individ): logger.info('Finished VASP jobs for all individuals of generation #%s'%Optimizer.generation) break time.sleep(60) stro = [] energies = [] for i in range(len(ind_folders)): ingred = os.path.join(archive,ind_folders[i],'Individual') energy_output = check_output(['tail','-n1',os.path.join(ingred, 'OSZICAR')]) individ[i].energy = float(energy_output.split()[4]) energies.append(individ[i].energy) if relax: stro.append('Relaxed structure of individual %s\n'%individ[i].history_index) else: stro.append('Evaluated energy of individual %s to be %s\n'%(individ[i].history_index,individ[i].energy)) totalsol = read_vasp(os.path.join(ingred, 'CONTCAR')) individ[i], bul = decompose_structure(Optimizer,totalsol,individ[i]) shutil.rmtree(os.path.join(archive,ind_folders[i])) # either remove or zip ?? if relax: return individ, stro return energies, stro
def get_required_memory(self): ''' Returns the recommended memory needed for a VASP calculation Code retrieves memory estimate based on the following priority: 1) METADATA 2) existing OUTCAR 3) run diagnostic calculation The final method determines the memory requirements from KPOINT calculations run locally before submission to the queue ''' import json def get_memory(): ''' Retrieves the recommended memory from the OUTCAR ''' if os.path.exists('OUTCAR'): with open('OUTCAR') as f: lines = f.readlines() else: return None for line in lines: # There can be multiple instances of this, # but they all seem to be identical if 'memory' in line: # Read the memory usage required_mem = float(line.split()[-2]) / 1e6 return required_mem # Attempt to get the recommended memory from METADATA # JASP automatically generates a METADATA file when # run, so there should be no instances where it does not exist with open('METADATA', 'r') as f: data = json.load(f) try: memory = data['recommended.memory'] except(KeyError): # Check if an OUTCAR exists from a previous run if os.path.exists('OUTCAR'): memory = get_memory() # Write the recommended memory to the METADATA file with open('METADATA', 'r+') as f: data = json.load(f) data['recommended.memory'] = memory f.seek(0) json.dump(data, f) # If no OUTCAR exists, we run a 'dummy' calculation else: original_ialgo = self.int_params.get('ialgo') self.int_params['ialgo'] = -1 # Generate the base files needed for VASP calculation atoms = self.get_atoms() self.initialize(atoms) from ase.io.vasp import write_vasp write_vasp('POSCAR', self.atoms_sorted, symbol_count=self.symbol_count) self.write_incar(atoms) self.write_potcar() self.write_kpoints() self.write_sort_file() # We only need the memory estimate, so we can greatly # accelerate the process by terminating after we have it process = Popen(JASPRC['vasp.executable.serial'], stdout=PIPE) from threading import Timer timer = Timer(15.0, process.kill()) timer.start() while True: if timer.is_alive(): memory = get_memory() if memory: timer.cancel() process.terminate() break else: raise RuntimeError('Memory estimate timed out') # return to original settings self.int_params['ialgo'] = original_ialgo self.write_incar(atoms) # Write the recommended memory to the METADATA file with open('METADATA', 'r+') as f: data = json.load(f) data['recommended.memory'] = memory f.seek(0) json.dump(data, f) # Remove all non-initialization files files = ['CHG', 'CHGCAR', 'CONTCAR', 'DOSCAR', 'EIGENVAL', 'IBZKPT', 'OSZICAR', 'PCDAT', 'vasprun.xml', 'OUTCAR', 'WAVECAR', 'XDATCAR'] for f in files: os.unlink(f) # Each node will require the memory read from the OUTCAR nodes = JASPRC['queue.nodes'] ppn = JASPRC['queue.ppn'] # Return an integer import math total_memory = int(math.ceil(nodes * ppn * memory)) JASPRC['queue.mem'] = '{0}GB'.format(total_memory) # return the memory as read from the OUTCAR return memory
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties=properties, system_changes=system_changes) # dftd3 can either do fully 3D periodic or non-periodic calculations. # It cannot do calculations that are only periodic in 1 or 2 # dimensions. If the atoms object is periodic in only 1 or 2 # dimensions, then treat it as a fully 3D periodic system, but warn # the user. pbc = False if any(atoms.pbc): if not all(atoms.pbc): warn('WARNING! dftd3 can only calculate the dispersion energy ' 'of non-periodic or 3D-periodic systems. We will treat ' 'this system as 3D-periodic!') pbc = True if pbc: fname = os.path.join(self.directory, '{}.POSCAR'.format(self.label)) write_vasp(fname, atoms) else: fname = os.path.join(self.directory, '{}.xyz'.format(self.label)) write_xyz(fname, atoms, plain=True) # Generate custom damping parameters file. This is kind of ugly, but # I don't know of a better way of doing this. if self.custom_damp: damppars = [] # s6 is always first damppars.append(str(float(self.parameters['s6']))) # sr6 is the second value for zero{,m} damping, a1 for bj{,m} if self.parameters['damping'] in ['zero', 'zerom']: damppars.append(str(float(self.parameters['sr6']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a1']))) # s8 is always third damppars.append(str(float(self.parameters['s8']))) # sr8 is fourth for zero, a2 for bj{,m}, beta for zerom if self.parameters['damping'] == 'zero': damppars.append(str(float(self.parameters['sr8']))) elif self.parameters['damping'] in ['bj', 'bjm']: damppars.append(str(float(self.parameters['a2']))) elif self.parameters['damping'] == 'zerom': damppars.append(str(float(self.parameters['beta']))) # alpha6 is always fifth damppars.append(str(int(self.parameters['alpha6']))) # last is the version number if self.parameters['old']: damppars.append('2') elif self.parameters['damping'] == 'zero': damppars.append('3') elif self.parameters['damping'] == 'bj': damppars.append('4') elif self.parameters['damping'] == 'zerom': damppars.append('5') elif self.parameters['damping'] == 'bjm': damppars.append('6') damp_fname = os.path.join(self.directory, '.dftd3par.local') with open(damp_fname, 'w') as f: f.write(' '.join(damppars))
def get_neb(self, npi=1): """Returns images, energies if available or runs the job. npi = cores per image for running the calculations. Default=1 show: if True show an NEB plot """ if self.in_queue(): return self.neb, [None for a in self.neb] calc_required = False # check for OUTCAR in each image dir for i in range(1, len(self.neb) - 1): wf = '{0}/OUTCAR'.format(str(i).zfill(2)) wf = os.path.join(self.directory, wf) if not os.path.exists(wf): calc_required = True break else: # there was an OUTCAR, now we need to check for # convergence. done = False with open(wf) as f: for line in f: if ('reached required accuracy - stopping structural' ' energy minimisation') in line: done = True break if not done: calc_required = True break if calc_required: # this creates the directories and files if needed. write out # all the images, including initial and final if not os.path.isdir(self.directory): os.makedirs(self.directory) self.set(images=len(self.neb) - 2) self.write_incar() self.write_kpoints() self.write_potcar() self.write_db() for i, atoms in enumerate(self.neb): # zero-padded directory name image_dir = os.path.join(self.directory, str(i).zfill(2)) if not os.path.isdir(image_dir): # create if needed. os.makedirs(image_dir) write_vasp('{0}/POSCAR'.format(image_dir), atoms[self.resort], symbol_count=self.symbol_count) # The first and last images need to have real calculators on # them so we can write out a DB entry. We need this so we can # get the energies on the end-points. Otherwise, there doesn't # seem to be a way to do that short of cloning the whole # calculation into the end-point directories. self.write_db(os.path.join(self.directory, '00/DB.db'), self.neb[0]) # print(self.neb) # import sys # sys.exit() self.write_db(os.path.join(self.directory, '{:02}/DB.db'.format(len(self.neb) - 1)), self.neb[-1]) VASPRC['queue.ppn'] = npi * (len(self.neb) - 2) log.debug('Running on %i cores', VASPRC['queue.ppn']) self.calculate() # this will raise VaspSubmitted return self.neb, [None for a in self.neb] ############################################# # now we are just retrieving results energies = [] import ase.io atoms0 = ase.io.read(os.path.join(self.directory, '00', 'DB.db')) energies += [atoms0.get_potential_energy()] for i in range(1, len(self.neb) - 1): atoms = ase.io.read(os.path.join(self.directory, str(i).zfill(2), 'CONTCAR'))[self.resort] self.neb[i].positions = atoms.positions self.neb[i].cell = atoms.cell energy = None with open(os.path.join(self.directory, str(i).zfill(2), 'OUTCAR')) as f: for line in f: if 'free energy TOTEN =' in line: energy = float(line.split()[4]) energies += [energy] fname = os.path.join(self.directory, '0{}/DB.db'.format(len(self.neb) - 1)) atoms_end = ase.io.read(fname) energies += [atoms_end.get_potential_energy()] energies = np.array(energies) energies -= energies[0] return (self.neb, np.array(energies))
#!/usr/bin/env python # -*- coding: utf-8; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- # vim:fenc=utf-8:et:sw=4:ts=4:sts=4:tw=0 from ase.io.vasp import read_vasp, write_vasp atoms = read_vasp('POSCAR') transvec = atoms.get_cell().diagonal() / -1. atoms.translate(transvec) supercell = atoms.repeat((3,3,3)) write_vasp('POSCAR.3',supercell) # import numpy as np # from oppvasp.vasp.parsers import PoscarParser # # pp = PoscarParser('POSCAR') # unit_pos = pp.get_positions( coordinates = 'direct' ) # unit_natoms = pos.shape[0] # print "Num atoms:",num_atoms # super_size = [2,2,2] # natoms = np.prod(super_size)*num_atoms # pos = np.array((natoms,3)) # pos[0:unit_natoms] = unit_pos # # # add atoms in x dir: # for i = range(unit_natoms): # for j = range(1,super_size[0]): # pos[unit_natoms+i*j] = pos[i]*[j,1,1] # f = open('movie.xyz','w')
def get_neb(self, npi=1): '''Returns images, energies if available or runs the job. npi = nodes per image for running the calculations. Default=1 ''' # how do we know if we need to run jobs? if jobid exists that means # it is or was queued # # if no jobid, and no OUTCAR for each image, then calculation # required. # # It is also possible a keyword has changed, and that a calculation # is required. calc_required = False if self.job_in_queue(): from jasp import VaspQueued raise VaspQueued else: if os.path.exists('jobid'): os.unlink('jobid') # check for OUTCAR in each image dir for i in range(1, len(self.neb_images)-1): wf = '{0}/OUTCAR'.format(str(i).zfill(2)) if not os.path.exists(wf): log.debug('calc_required in {0}'.format(wf)) calc_required = True break else: # there was an OUTCAR, now we need to check for # convergence. def subdir_converged(fname): f = open(fname) for line in f: if 'reached required accuracy - stopping structural energy minimisation' in line: return True f.close() return False converged = subdir_converged('{0}/OUTCAR'.format(str(i).zfill(2))) if not converged: print '{0} does not appear converged'.format(str(i).zfill(2)) # make sure no keywords have changed if not ((self.float_params == self.old_float_params) and (self.exp_params == self.old_exp_params) and (self.string_params == self.old_string_params) and (self.int_params == self.old_int_params) and (self.bool_params == self.old_bool_params) and (self.list_params == self.old_list_params) and (self.input_params == self.old_input_params) and (self.dict_params == self.old_dict_params)): calc_required = True log.debug('Calculation is required') log.debug(self.vaspdir) if calc_required: ''' this creates the directories and files if needed. write out the poscar for all the images. write out the kpoints and potcar. ''' if os.path.exists('jobid'): raise VaspQueued # write out all the images, including initial and final for i, atoms in enumerate(self.neb_images): image_dir = str(i).zfill(2) if not os.path.isdir(image_dir): # create if needed. os.makedirs(image_dir) # this code is copied from # ase.calculators.vasp.initialize to get the sorting # correct. p = self.input_params self.all_symbols = atoms.get_chemical_symbols() self.natoms = len(atoms) self.spinpol = atoms.get_initial_magnetic_moments().any() atomtypes = atoms.get_chemical_symbols() # Determine the number of atoms of each atomic species # sorted after atomic species special_setups = [] symbols = [] symbolcount = {} if self.input_params['setups']: for m in self.input_params['setups']: try: special_setups.append(int(m)) except ValueError: continue for m, atom in enumerate(atoms): symbol = atom.symbol if m in special_setups: pass else: if symbol not in symbols: symbols.append(symbol) symbolcount[symbol] = 1 else: symbolcount[symbol] += 1 # Build the sorting list self.sort = [] self.sort.extend(special_setups) for symbol in symbols: for m, atom in enumerate(atoms): if m in special_setups: pass else: if atom.symbol == symbol: self.sort.append(m) self.resort = range(len(self.sort)) for n in range(len(self.resort)): self.resort[self.sort[n]] = n self.atoms_sorted = atoms[self.sort] # Check if the necessary POTCAR files exists and # create a list of their paths. self.symbol_count = [] for m in special_setups: self.symbol_count.append([atomtypes[m], 1]) for m in symbols: self.symbol_count.append([m, symbolcount[m]]) write_vasp('{0}/POSCAR'.format(image_dir), self.atoms_sorted, symbol_count = self.symbol_count) cwd = os.getcwd() os.chdir(image_dir) self.write_sort_file() os.chdir(cwd) f = open('00/energy', 'w') f.write(str(self.neb_initial_energy)) f.close() f = open('{0}/energy'.format(str(len(self.neb_images) - 1).zfill(2)), 'w') f.write(str(self.neb_final_energy)) f.close() # originally I only created these if they did not exist. that # doesn't modfiy the incar if you add variables though. I am # too lazy right now to write code that checks if a change was # made, and we just write it out here. self.write_kpoints() self.initialize(self.neb_images[0]) self.write_potcar() self.write_incar(self.neb_images[0]) JASPRC['queue.nodes'] = npi * self.neb_nimages log.debug('Running on %i nodes',JASPRC['queue.nodes']) self.run() # this will raise VaspSubmitted ############################################# # now we are just retrieving results images = [self.neb_images[0]] energies = [self.neb_initial_energy] # this is a tricky point. unless # the calc stores an absolute # path, it may be tricky to call # get_potential energy log.debug('self.neb_nimages = %i', self.neb_nimages) for i in range(1, self.neb_nimages + 1): log.debug(self.neb_images[i].numbers) nebd = str(i).zfill(2) try: os.chdir(nebd) log.debug('in %s' % nebd) log.debug(os.listdir('.')) energies += [self.read_energy()[1]] atoms = read('CONTCAR') # I do not understand why this is needed to resort the # atoms! If I don't do it, the calculations are wrong. If # I do it here, it is wrong somewhere else. f = open('ase-sort.dat') sort, resort = [], [] for line in f: s, r = [int(x) for x in line.split()] sort.append(s) resort.append(r) log.debug('read %i: %s', i, str(atoms.numbers)) log.debug('read %i: %s', i, str(atoms.get_chemical_symbols())) images += [atoms[resort]] finally: os.chdir('..') images += [self.neb_images[-1]] energies += [self.neb_final_energy] return (images, np.array(energies))
from ase.constraints import FixAtoms from ase.constraints import FixedLine from ase.visualize import view from ase.io import read from ase.io.vasp import write_vasp #Read in previous CONTCAR slab = read('CONTCAR',format='vasp') slab.center() #Freeze all atoms except NN and adsorbate. Freeze in all directions but one atomIndex = [36, 27, 28, 30] constraint1 = FixAtoms(indices=[atom.index for atom in slab if atom.index not in atomIndex]) constraint2 = FixedLine(36,[0, 0, 1]) constraint3 = FixedLine(27,[0, 0, 1]) constraint4 = FixedLine(28,[0, 0, 1]) constraint5 = FixedLine(30,[0, 0, 1]) slab.set_constraint([constraint1,constraint2,constraint3,constraint4,constraint5]) view(slab) # View the slab, frozen atoms will be marked with a "X" write_vasp('POSCAR', slab, direct=False, long_format=True, vasp5=True)
and only along the first unit cell vector $ repeat.py filename n1 """ from ase.io.vasp import read_vasp, write_vasp import sys nargs = len(sys.argv) if not nargs in [3, 4, 5]: raise SyntaxError('Must specify name of input file and \ direction on command line, e.g. \n \ $ repeat.py POSCAR 2 2 2') file = sys.argv[1] n1 = int(sys.argv[2]) if nargs > 3: n2 = int(sys.argv[3]) if nargs > 4: n3 = int(sys.argv[4]) else: n3 = 1 else: n2 = n3 = 1 atoms = read_vasp(file) atoms.constraints = [] atoms = atoms.repeat([n1, n2, n3]) write_vasp(file+'-%dx%dx%d' % (n1, n2, n3), atoms)