def read_from_pickle(file, ts_est, geo_dict): from pts.tools.pathtools import unpickle_path, PathTools from ase import Atoms from ase.io import write from pts.ui.read_COS import set_atoms from pts.searcher import new_abscissa from numpy import savetxt coord_b, energy_b, gradients_b, __, __, symbols, funcart = unpickle_path(file) # v2 mt.setup_metric(funcart) startx = new_abscissa(coord_b, mt.metric) pt2 = PathTools(coord_b, energy_b, gradients_b, startx) if ts_est == "spline": ts_int = pt2.ts_spl() if len(ts_int) == 0: print >> stderr, "Transition state estimate did not provide any results" print >> stderr, "Aborting!" exit() est = ts_int[-1] elif ts_est == "spl_avg": ts_int = pt2.ts_splavg() if len(ts_int) == 0: print >> stderr, "Transition state estimate did not provide any results" print >> stderr, "Aborting!" exit() est = ts_int[-1] elif ts_est == "cubic": ts_int = pt2.ts_splcub() if len(ts_int) == 0: print >> stderr, "Transition state estimate did not provide any results" print >> stderr, "Aborting!" exit() est = ts_int[-1] elif ts_est == "highest": est = pt2.ts_highest()[-1] elif ts_est == "bell": ts_int = pt2.ts_bell() if len(ts_int) == 0: print >> stderr, "Transition state estimate did not provide any results" print >> stderr, "Aborting!" exit() est = ts_int[-1] else: print >> stderr, "Transition state estimate not found", ts_est print >> stderr, "Make sure that the name is written correctly" exit() energy, start_geo, __, __,s_ts, __, __ = est init_mode = pt2.xs.fprime(s_ts) atoms = Atoms(symbols) atoms.set_positions(funcart(start_geo)) atoms = set_atoms(atoms, geo_dict) write("start.xyz", atoms) savetxt("mode.start", init_mode) return start_geo, init_mode, funcart, atoms
def update_atoms(self): write(self.filename, self.atoms) # initialize OBMolecule self.mol = openbabel.OBMol() # read atoms from file: conv = openbabel.OBConversion() #format = conv.FormatFromExt(self.filename) conv.SetInAndOutFormats(self.file_format, self.file_format) conv.ReadFile(self.mol, self.filename) # attach OBmolecule to OBforcefield if self.ff.Setup( self.mol ) == 0: print('Could not setup forcefield') # log changes in topology: natoms = self.mol.NumAtoms() if (self.natoms != natoms): if self.natoms > 0: if not(self.logfile is None): self.logfile.write('WARNING! Changed number of atoms!\n') else: print('WARNING: changed number of atoms!\n') self.natoms = natoms if not(self.logfile is None): self.logfile.write('OB> Number of atoms:\t%i\n' % natoms) nbonds = self.mol.NumBonds() if (self.nbonds != nbonds): self.nbonds = nbonds if not(self.logfile is None): self.logfile.write( 'OB> Number of bonds:\t%i\n' % nbonds) self.logfile.flush()
def main(argv=[]): kwargs = getArgs(argv) nam = kwargs['file'] fix = kwargs['layers'] pad = kwargs['pad'] v = kwargs['v'] format = kwargs['format'] if format: atoms = read(nam, format=format) elif "vasp" in nam or "POSCAR" in nam or "CONTCAR" in nam: atoms = read(nam, format="vasp") else: atoms = read(nam) if v: print "-file loaded." # TODO: ameliorate layerz = {round(a.z, 2): None for a in atoms} layerz_list = [None] + [z for z in sorted(layerz)] if v: print "layerz list:", layerz_list n_layers = len(layerz) atoms.set_tags([layerz_list.index(round(a.z, 2)) for a in atoms]) if v: print "-tags set." constraint = FixAtoms(mask=[a.tag <= fix for a in atoms]) atoms.set_constraint(constraint) if v: print "-constraints set." write('POSCAR' + pad, atoms, format='vasp', direct=True)
def get_e_h_density(self, lamda=None, filename=None): if filename is not None: self.load(filename) self.initialize() gd = self.gd w_S = self.w_S v_SS = self.v_SS A_S = v_SS[:, lamda] kq_k = self.kq_k kd = self.kd # Electron density nte_R = gd.zeros() for iS in range(self.nS_start, self.nS_end): print 'electron density:', iS k1, n1, m1 = self.Sindex_S3[iS] ibzkpt1 = kd.kibz_k[k1] psitold_g = self.get_wavefunction(ibzkpt1, n1) psit1_g = kd.transform_wave_function(psitold_g, k1) for jS in range(self.nS): k2, n2, m2 = self.Sindex_S3[jS] if m1 == m2 and k1 == k2: psitold_g = self.get_wavefunction(ibzkpt1, n2) psit2_g = kd.transform_wave_function(psitold_g, k1) nte_R += A_S[iS] * A_S[jS].conj() * psit1_g.conj() * psit2_g # Hole density nth_R = gd.zeros() for iS in range(self.nS_start, self.nS_end): print 'hole density:', iS k1, n1, m1 = self.Sindex_S3[iS] ibzkpt1 = kd.kibz_k[kq_k[k1]] psitold_g = self.get_wavefunction(ibzkpt1, m1) psit1_g = kd.transform_wave_function(psitold_g, kq_k[k1]) for jS in range(self.nS): k2, n2, m2 = self.Sindex_S3[jS] if n1 == n2 and k1 == k2: psitold_g = self.get_wavefunction(ibzkpt1, m2) psit2_g = kd.transform_wave_function(psitold_g, kq_k[k1]) nth_R += A_S[iS] * A_S[jS].conj() * psit1_g * psit2_g.conj() self.Scomm.sum(nte_R) self.Scomm.sum(nth_R) if rank == 0: write('rho_e.cube',self.calc.atoms, format='cube', data=nte_R) write('rho_h.cube',self.calc.atoms, format='cube', data=nth_R) world.barrier() return
def __call__(self, calc): if calc.wfs.world.rank > 0: return from ase.io import write name = os.path.join(self.dir, ''.join(random.sample('gpaw' * 3, 12))) write(name + '.traj', calc.atoms.copy()) fd = open(name + '.gkw', 'w') fd.write('%r\n' % dict(calc.input_parameters)) fd.close() fd = open(name + '.txt', 'w') txt = calc.txt calc.txt = fd calc.print_logo() calc.print_cell_and_parameters() calc.print_positions() fd.close() calc.txt = txt os.chmod(name + '.traj', 0666) os.chmod(name + '.gkw', 0666) os.chmod(name + '.txt', 0666)
def insert_atom_document(name, ase_object, time=None): if time is None: time = ttime.time() # at some level, you dont actually care where this thing is on disk file_uid = str(uuid4()) is_trajectory = False if isinstance(ase_object, list): is_trajectory = True # create the filename file_name = os.path.join(simdb.ATOM_PATH, file_uid + '.traj') # save the object aseio.write(file_name, ase_object) # do the filestore magic resource = fsc.insert_resource('ase', file_name) fsc.insert_datum(resource, file_uid, datum_kwargs={'is_trajectory': is_trajectory}) # create an instance of a mongo document (metadata) a = AtomicConfig(name=name, file_uid=file_uid, time=time) # save the document a.save() return a
def run_single(self, name): try: atoms = self.create_system(name) except Exception: self.log(name, "FAILED") traceback.print_exc(file=self.logfile) return atoms.calc = self.calcfactory(self.get_filename(name), atoms) tstart = time() try: data = self.calculate(name, atoms) except KeyboardInterrupt: raise except Exception: self.log(name, "FAILED") traceback.print_exc(file=self.logfile) return tstop = time() data["time"] = tstop - tstart for write in self.write_funcs: filenamebase = self.get_filename(name) write(filenamebase, atoms, data) return atoms
def main(args): from pts.ui.read_inp_dimer import read_dimer_input from pts.trajectories import empty_traj, traj_every, traj_long, traj_last from ase.io import write pes, start_geo, __, params, atoms, funcart = read_dimer_input(args[1:], args[0] ) metric = Default() if "trajectory" in params: if params["trajectory"] in ["empty", "None", "False"]: params["trajectory"] = empty_traj elif params["trajectory"] == "every": params["trajectory"] = traj_every(atoms, funcart) elif params["trajectory"] == "one_file": params["trajectory"] = traj_long(atoms, funcart, ["grads"]) else: params["trajectory"] = traj_last(atoms, funcart) else: params["trajectory"] = traj_last(atoms, funcart) geo, res = qn(pes, start_geo, metric, **params) print "" print "" print "Results as given back from Quasi Newton routine" print geo print res print "" print "Results Quasi Newton calculation:" print "Quasi Newton converged: ", res["convergence"] print "Forces left (RMS):", res["abs_force"] print "Final geometry:" atoms.set_positions(funcart(geo)) write("-", atoms)
def write(self, filename=None, format=None, repeat=None): """Write the structure to file. Parameters ---------- format: string can be given or it will be guessed from the filename repeat: array, eg.: [1,0,1] can be used to repeat the structure """ if filename is None: if format is None: raise RuntimeError('Please specify either filename or format.') else: filename = self.get_name() + '.' + format out = self if repeat is None: out = self else: out = Cluster([]) cell = self.get_cell().diagonal() for i in range(repeat[0] + 1): for j in range(repeat[1] + 1): for k in range(repeat[2] + 1): copy = self.copy() copy.translate(np.array([i, j, k]) * cell) out += copy write(filename, out, format)
def output_for_fitpot(atoms,keep_const,dirname='./',specorder=[]): if not keep_const: try: del atoms.constraints except: print('del atoms.constraints for ',type(atoms),' failed.') #write(dirname+'/POSCAR',images=atoms,format='vasp',direct=True,vasp5=True) try: epot = atoms.get_potential_energy() except: print(' Failed to get_potential_energy(), so skip it.') return None with open(dirname+'/erg.ref','w') as f: f.write("{0:12.7f}\n".format(epot)) with open(dirname+'/frc.ref','w') as f: f.write("{0:6d}\n".format(len(atoms))) frcs= atoms.get_forces() for frc in frcs: f.write("{0:12.7f} {1:12.7f} {2:12.7f}\n".format(frc[0],frc[1],frc[2])) write_pos(atoms,fname=dirname+'/pos',specorder=specorder) if not os.path.exists(dirname+'/POSCAR'): write(dirname+'/POSCAR',images=atoms,format='vasp', direct=True,vasp5=True,sort=False) try: strs = atoms.get_stress() except: with open(dirname+'/WARNING','w') as f: f.write(' Since failed to get stress tensor, put 0.0s into strs.ref file.\n') strs = [ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0] with open(dirname+'/strs.ref','w') as f: for s in strs: f.write(" {0:15.7f}".format(s*_kb2gpa)) # converting from kBar to GPa f.write('\n') return None
def build_calculation(count, i, sub, film, min_ratio, initial_INCAR, initial_QSUB, INCAR_inputs, KMETHOD, KGRID, POTCAR_type, POTCAR_array, make_input_files): count += 1 base_dir = "./Films/Substrate_" + sub.name + "/Film_" + film.name new_name = sub.name + "on" + film.name + "_" + str(int(i[4])) + "_on_" + str(int(i[5])) end_dir = str(int(i[4])) + "_on_" + str(int(i[5])) + "/magnitude-" + str(round(i[3], 3)) + "/dialation-" + str(round(i[9], 3)) + "/" if round(i[6], 4) == round(min_ratio, 4): dir = base_dir + "/Ratio_" + str(round(i[6], 4)) + "____min_ratio/" + end_dir else: dir = base_dir + "/Ratio_" + str(round(i[6], 4)) + "/" + end_dir try: os.makedirs(dir) except: return text_file = open(dir + "cell_summary", "a") txt = info_end(i, sub, film) new_file = make_sub(i, sub.atoms, film.atoms, buffer, translate, site, vacuum=10) text_file.write(info_intro(i, sub, film)) text_file.write(txt) text_file.close() write(dir + "POSCAR", new_file, "vasp") write(dir + "Trajectory", new_file, "traj") if make_input_files: INCAR = open(dir + "INCAR", "a") qs_vasp = open(dir + "qs_vasp", "a") KPOINTS = open(dir + "KPOINTS", "a") POTCAR = open(dir + "POTCAR", "a") INCAR.write(write_incar(new_file, INCAR_inputs, initial_INCAR)) qs_vasp.write(write_qsub(new_file, new_name, initial_QSUB)) KPOINTS.write(write_kpoints(new_file, KMETHOD, KGRID)) POTCAR.write(write_potcar(new_file, POTCAR_type, POTCAR_array))
def view(atoms, data=None, viewer='ag', repeat=None, block=False): # Ignore for parallel calculations: if parallel.size != 1: return if hasattr(atoms, 'GetUnitCell'): # Convert old ASE ListOfAtoms to new style. atoms = OldASEListOfAtomsWrapper(atoms).copy() vwr = viewer.lower() if vwr == 'ag': format = 'traj' if repeat is None: command = 'ag' else: command = 'ag --repeat=%d,%d,%d' % tuple(repeat) repeat = None elif vwr == 'vmd': format = 'cube' command = 'vmd' elif vwr == 'rasmol': format = 'pdb' command = 'rasmol -pdb' elif vwr == 'xmakemol': format = 'xyz' command = 'xmakemol -f' elif vwr == 'gopenmol': format = 'xyz' command = 'rungOpenMol' elif vwr == 'avogadro': format = 'cube' command = 'avogadro' elif vwr == 'sage': from ase.visualize.sage import view_sage_jmol view_sage_jmol(atoms) return else: raise RuntimeError('Unknown viewer: ' + viewer) fd, filename = tempfile.mkstemp('.' + format, 'ase-') fd = os.fdopen(fd, 'w') if repeat is not None: atoms = atoms.repeat() if data is None: write(fd, atoms, format=format) else: write(fd, atoms, format=format, data=data) fd.close() if block: os.system('%s %s' % (command, filename)) os.remove(filename) else: if os.name in ['ce', 'nt']: # Win # XXX: how to make it non-blocking? os.system('%s %s' % (command, filename)) os.remove(filename) else: os.system('%s %s & ' % (command, filename)) os.system('(sleep 60; rm %s) &' % filename)
def write_input(self, atoms, properties=None, system_changes=None): # self.Ham_AtomsDependProp(atoms) from ase.io import write FileIOCalculator.write_input(\ self, atoms, properties, system_changes) self.write_dftb_in() write('geo_end.gen', atoms)
def make_1disp_poscars(atoms0,rtype='uniform',dis=0.03, offset=0,idatom=0, xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0, zmin=0.0,zmax=1.0): """ Make displaced POSCARs, in which only one atom is displaced, from non-displaced POSCAR file. *atoms0* ASE's atoms object whose atom to be displaced. *dis* = 0.03 (float) Maximum displacement. *offset* = 0 (int) Offset of the sequential POSCAR file names. *idatom* = 0 (int) ID of an atom to be displaced. """ nd= 3 # poscar= POSCAR() # poscar.read(fname=fname) # #...original a vectors # ho= poscar.h *poscar.afac # hi= np.linalg.inv(ho) ho = atoms0.get_cell() hi = np.linalg.inv(ho) inc= offset # default constraints cdefault = copy.deepcopy(atoms0.constraints) # constraints object of every atoms being able to move from ase.constraints import FixScaled atmlist= [ i for i in range(len(atoms0))] atoms0.set_constraint(FixScaled(ho,atmlist,[0,0,0])) dd= np.zeros(3,dtype=float) d= dis/nd for ixyz in range(3): dd[:]= 0.0 for i in range(-nd,nd+1): atoms= copy.deepcopy(atoms0) if i == 0: continue dd[ixyz]= i*d #ddh= np.dot(hi,dd) pos = atoms.get_positions() #poscar.pos[idatom]= poscar.pos[idatom] +ddh pos[idatom] = pos[idatom] + dd inc += 1 atoms.set_positions(pos) atoms.wrap() # reset constraint atoms.set_constraint(cdefault) #poscar.write(fname=fname+'-{0:03d}'.format(inc)) write(fname+'-{0:03d}'.format(inc), images=atoms,format="vasp",vasp5=True, direct=True,sort=False)
def make_random_poscars(atoms0,rtype='uniform',dis=0.03, nout=10,offset=0, xmin=0.0,xmax=1.0,ymin=0.0,ymax=1.0, zmin=0.0,zmax=1.0): """ Make displaced POSCARs from non-displaced POSCAR file. *atoms0* ASE's atoms object whose atoms to be displaced. *dis* = 0.03 (float) Characteristic displacement. *nout* = 10 (int) Number of displaced POSCAR files to be created. *offset* = 0 (int) Offset of the sequential POSCAR file names. """ # poscar= POSCAR() # poscar.read(fname=fname) # #...original a vectors # ho= poscar.h *poscar.afac # hi= np.linalg.inv(ho) ho = atoms0.get_cell() hi = np.linalg.inv(ho) inc= offset # default constraints cdefault = copy.deepcopy(atoms0.constraints) # constraints object of every atoms being able to move from ase.constraints import FixScaled atmlist= [ i for i in range(len(atoms0))] atoms0.set_constraint(FixScaled(ho,atmlist,[0,0,0])) for i in range(nout): atoms = copy.deepcopy(atoms0) pos = atoms.get_positions() spos = atoms.get_scaled_positions() for ia in range(1,len(pos)): sp = spos[ia] if sp[0] < xmin or sp[0] > xmax \ or sp[1] < ymin or sp[1] > ymax \ or sp[2] < zmin or sp[2] > zmax: continue r= abs(dis* myrand(rtype)) theta= pi*random() phi= 2.0*pi*random() dr= get_displacement(r,theta,phi) #drh= np.dot(hi,dr) pos[ia] = pos[ia] +dr inc += 1 atoms.set_positions(pos) atoms.wrap() # reset constraint atoms.set_constraint(cdefault) write(fname+'-{0:03d}'.format(inc), images=atoms,format="vasp",vasp5=True, direct=True,sort=False)
def save_trajectory(confid, trajectory, folder): """ Saves traj files to the database folder. This method should never be used directly, but only through the DataConnection object. """ fname = os.path.join(folder, 'traj%05d.traj' % confid) write(fname, trajectory) return fname
def save_cfg(self, name=None): """Save the current structure as a .cfg file to the /cfgs folder under the working wrk_dir. Parameter: name: string Name of the file. The .cfg postfix is automatically appended. """ write(self.cfg_dir+'/'+name+".cfg", self.atoms)
def test_compression_read_write_multiple(ext='gz'): """Re-reading a compressed file with multiple configurations.""" filename = 'multiple.xyz.{ext}'.format(ext=ext) io.write(filename, multiple) assert os.path.exists(filename) reread = io.read(filename, ':') assert len(reread) == len(multiple) assert np.allclose(reread[-1].positions, multiple[-1].positions) os.unlink(filename)
def __call__(self, geo, iter, adds_files, adds_only_pickle): self.atoms.set_positions(self.fun(geo)) write("actual_geo", self.atoms, format = "xyz") for item in adds_files: val, name, text = item savetxt("actual_" + name, val) self.logger([(geo, None, "Center")] + adds_files + adds_only_pickle)
def get_excitation_wavefunction(self, lamda=None,filename=None, re_c=None, rh_c=None): if filename is not None: self.load(filename) self.initialize() gd = self.gd w_S = self.w_S v_SS = self.v_SS A_S = v_SS[:, lamda] kq_k = self.kq_k kd = self.kd if re_c is not None: psith_R = gd.zeros(dtype=complex) elif rh_c is not None: psite_R = gd.zeros(dtype=complex) else: self.printtxt('No wavefunction output !') return for iS in range(self.nS_start, self.nS_end): print 'hole wavefunction', iS k, n, m = self.Sindex_S3[iS] ibzkpt1 = kd.kibz_k[k] ibzkpt2 = kd.kibz_k[kq_k[k]] psitold_g = self.get_wavefunction(ibzkpt1, n) psit1_g = kd.transform_wave_function(psitold_g, k) psitold_g = self.get_wavefunction(ibzkpt2, m) psit2_g = kd.transform_wave_function(psitold_g, kq_k[k]) if re_c is not None: # given electron position, plot hole wavefunction psith_R += A_S[iS] * psit1_g[re_c].conj() * psit2_g elif rh_c is not None: # given hole position, plot electron wavefunction psite_R += A_S[iS] * psit1_g.conj() * psit2_g[rh_c] else: pass if re_c is not None: self.Scomm.sum(psith_R) if rank == 0: write('psit_h.cube',self.calc.atoms, format='cube', data=psith_R) elif rh_c is not None: self.Scomm.sum(psite_R) if rank == 0: write('psit_e.cube',self.calc.atoms, format='cube', data=psite_R) else: pass world.barrier() return
def relax(self, a): """Relax the atoms object a by submitting the relaxation to the pool of cpus.""" self.dc.mark_as_queued(a) fname = '{0}/cand{1}.traj'.format(self.tmp_folder, a.info['confid']) write(fname, a) self.results.append(self.pool.apply_async(self.relax_function, [fname])) self._cleanup()
def main(argv=None): args = getArgs(argv) atoms = read(args.file, format=args.f) if args.f else struct = read(args.file) atoms = correct_z(atoms) kw = {"format": args.format} if args.format == 'vasp': kw['sort'] = True kw['vasp5'] = True kw['direct'] = True write(args.nam, atoms, **kw)
def main(argv=[]): args = getArgs(argv) atoms = read(args.file, format=args.format) if args.format else read(args.file) atoms = correct_z(atoms) atoms = fix_layers(atoms, args.fix, args.n_layers) kw = {'format': 'vasp', 'direct': True, 'vasp5': True, 'sort':True} write('POSCAR' + args.pad, atoms, **kw)
def test_compression_read_write_single(ext='gz'): """Re-reading a compressed file.""" # Use xsf filetype as it needs to check the 'magic' # filetype guessing when reading filename = 'single.xsf.{ext}'.format(ext=ext) io.write(filename, single) assert os.path.exists(filename) reread = io.read(filename) assert reread.get_chemical_symbols() == single.get_chemical_symbols() assert np.allclose(reread.positions, single.positions) os.unlink(filename)
def write_xyz_animation(curve_pickle, filename): """ This function takes a curve object that has been pickled and writes out an XYZ animation file to use with JMol. Args: curve_pickle (str): The location of a pickled curve object. filename (str): The location of where to write the XYZ animation. """ # Unpickle the curve object curve = pickle.load(open(curve_pickle, "rb")) # Extract the trajectories points trajectory = curve.get_points() # Reparameterise to determine physical times times = get_times(curve) # Index to determine correct time i = 0 # Extract the curves molecular configuration as described by an ASE atoms object molecule = curve.configuration['molecule'] # Create a new file for the animation to be stored animation_file = open(filename, 'w') # For each node along the curve... for state in trajectory: # Determine the molecular configuration in ASE molecule.set_positions(convert_vector_to_atoms(state)) # Produce a snapshot XYZ file of the configuration at that point in time write('current_state.xyz', molecule, format='xyz') # Increase index i += 1 # Open the newly produced XYZ file current_state = open('current_state.xyz', 'r') # Append the snapshot XYZ file into the animation file for line in current_state: animation_file.write(line) current_state.close() # Once finished close the file so that other programs can access it animation_file.close() # Delete the temporary file used to store current snapshots os.remove('current_state.xyz')
def h2(name, par): h2 = molecule('H2', pbc=par.pop('pbc', False)) h2.center(vacuum=2.0) h2.calc = get_calculator(name)(**par) e = h2.get_potential_energy() f = h2.get_forces() assert not h2.calc.calculation_required(h2, ['energy', 'forces']) write('h2.traj', h2) h2 = read('h2.traj') assert abs(e - h2.get_potential_energy()) < 1e-12 assert abs(f - h2.get_forces()).max() < 1e-12
def write_input(self, atoms, properties=None, system_changes=None): from ase.io import write FileIOCalculator.write_input( self, atoms, properties, system_changes) self.write_dftb_in(os.path.join(self.directory, 'dftb_in.hsd')) write(os.path.join(self.directory, 'geo_end.gen'), atoms) # self.atoms is none until results are read out, # then it is set to the ones at writing input self.atoms_input = atoms self.atoms = None if self.pcpot: self.pcpot.write_mmcharges('dftb_external_charges.dat')
def optimize(system): c = FixAtoms(indices=[atom.index for atom in system if atom.symbol == 'C']) system.set_constraint(c) hop = MinimaHopping(system, temperature=298.15 * units.kB, dr=0.1, fmax=0.00001, trajectory='lowestMin.traj', ) traj = Trajectory("lowestMin.traj") atoms = traj[-1] write('finalMin.pdb', atoms)
def main(argv=[]): args = getArgs(argv) # create slab kw = dict(vars(args)) del kw['pad'] atoms = bulk(**kw) # write POSCAR kw = {'format': 'vasp', 'sort': True, 'vasp5': True, 'direct': True} nam = 'POSCAR' + args.pad write(nam, atoms, **kw)
def write_inputs(self): #fragments os.mkdir("frag1") os.mkdir("frag2") self.frag1.calc.write_control(self.frag1, "frag1/control.in") self.frag1.calc.write_species(self.frag1, "frag1/control.in") write("frag1/geometry.in", self.frag1, format="aims") self.frag2.calc.write_control(self.frag2, "frag2/control.in") self.frag2.calc.write_species(self.frag2, "frag2/control.in") if self.embedding == ".false.": write("frag2/geometry.in", self.frag2, format="aims") else: self.__write_aims_empty__("frag1/geometry.in", self.frag2) self.__write_species_empty__(self.frag2, "frag1/control.in") write("frag2/tmp_geometry.in", self.frag2, format="aims") self.__write_aims_empty__("frag2/geometry.in", self.frag1) self.__write_species_empty__(self.frag1, "frag2/control.in") with open('frag2/geometry.in', 'a') as outfile: with open("frag2/tmp_geometry.in") as infile: outfile.write(infile.read()) os.remove("frag2/tmp_geometry.in") # final step self.dimer.calc.write_control(self.dimer, "control.in") self.dimer.calc.write_species(self.dimer, "control.in") write("geometry.in", self.frag1+self.frag2, format="aims")
def save_zeolites(folder_path: str, zeotype_list: Iterable[PerfectZeolite], ase_ext: str = '.traj', zip: bool = True) -> None: """ This saves a list of Zeotypes to a .zeo file :param folder_path: path and name of the zeo file without the zeo extension :type folder_path: str :param zeotype_list: an iterable collection of Zeotype objects (or subclasses) :type zeotype_list: Iterable[PerfectZeolite] :param ase_ext: extension to save the Zeotype files (default .traj) :type ase_ext: str :return: None :rtype: None """ assert '.' not in folder_path, 'do not add file extension when saving zeolites' my_path = Path(folder_path) my_path.mkdir(parents=True, exist_ok=True) name_list = [] for z in zeotype_list: name_list.append(z.name) for names in z.additions.values(): name_list.extend(names) assert "parent" in name_list, 'parent must be in zeolite list' new_index_mapper = copy.deepcopy(zeotype_list[0].index_mapper) for z in zeotype_list: assert z.index_mapper is zeotype_list[ 0].index_mapper, 'index mappers must match' # save index mapper index_mapper_path = os.path.join(my_path, 'index_mapper.json') for name in zeotype_list[0].index_mapper.names: if name not in name_list: new_index_mapper.delete_name(name) save_index_mapper(index_mapper_path, new_index_mapper) for z in zeotype_list: zeotype_folder = os.path.join(my_path, z.name) Path(zeotype_folder).mkdir(parents=True, exist_ok=True) dict_json = { 'name': z.name, 'type': str(type(z)), 'additions': z.additions, 'additions_map': z.build_additions_map() } if z.name == 'parent': additional_params = { 'site_to_atom_indices': z.site_to_atom_indices, 'atom_indices_to_site': z.atom_indices_to_sites } dict_json.update(additional_params) binary_path = os.path.join(zeotype_folder, z.name + ase_ext) dict_path = os.path.join(zeotype_folder, z.name + '.json') try: z.retag_self() except AttributeError: pass # is a Perfect Zeolite or Atoms object write(binary_path, z) with open(dict_path, 'w') as f: json.dump(dict_json, f, indent=4, ensure_ascii=True) if zip: make_folder_to_zeo(folder_path) delete_folder(folder_path)
else: file = 'OUTCAR' if (len(sys.argv) > 2): element = sys.argv[2] atoms = read(file) energy = subprocess.check_output( "grep py= OUTCAR | tail -1 | gawk '{print $7}' ", shell=True) energy = float(energy) print(energy) traj2 = Trajectory('moments.traj', 'w') traj2.write(atoms, energy=energy) write('optimized.cif', atoms) moments = [] moments2 = [] moms = atoms.get_magnetic_moments() forces = atoms.get_forces() sum = 0.0 largest = 0.0 for a in range(len(atoms)): # #if(atoms[a].symbol=='Co'): # # moments.append(moms[a]) if (np.abs(moms[a]) > 0.1): moments.append([atoms[a].symbol, a, moms[a]]) if (len(sys.argv) > 2): if (atoms[a].symbol == element): moments2.append(moms[a]) force = np.sqrt(forces[a][0]**2 + forces[a][1]**2 + forces[a][2]**2)
r0 = 2.866 alpha = 1.3588 atoms = FaceCenteredCubic(latticeconstant=1.5, symbol='Cu', pbc=False, size=(3, 3, 3)) atoms.center(vacuum=100) atoms.set_calculator(MorsePotential(D=D, alpha=alpha, r0=r0)) dyn = FIRE(atoms, trajectory='relax.traj') dyn.run(fmax=0.01) write('relax.xyz', read('relax.traj@:')) # uncomment this line for Task 2 open('langevin_friction.log', 'w').close() # clean current log file # dyn = VelocityVerlet(atoms, dt=1 * units.fs, # trajectory='md.traj', logfile='md.log') # dyn.run(1000) # write('md.xyz', read('md.traj@:')) dyn = Langevin(atoms, timestep=5 * units.fs, temperature=2500 * units.kB, friction=0.002, trajectory='langevin_friction.traj', logfile='langevin_friction.log')
def add_mol(cml): arg = parse_cml_args(cml) slab = read(arg.slab) assert arg.molecule is not None, "Please specify the name of the adsorbates." mol = molecule(arg.molecule, pbc=slab.pbc, cell=slab.cell) mol.center() print(' '.join(mol.get_chemical_symbols())) if arg.rot: for za in arg.rot: if za[0].lower() in 'xyz': axis = za[0].lower() angle = za[1:] else: axis = 'z' angle = za try: angle = float(angle) except: print("Please enter valid rotation parameter, e.g. z90!") raise mol.rotate(angle, axis) if arg.rotx: mol.rotate(arg.rotx, 'x') if arg.roty: mol.rotate(arg.roty, 'y') if arg.rotz: mol.rotate(arg.rotz, 'z') mol.positions += slab.positions[arg.atom_index] - mol.positions[ arg.mol_index] mol.positions += [arg.offset[0], arg.offset[1], arg.height] new = slab + mol # add vacuum if arg.vacuum: if arg.xvacuum == 'a': axis = (0, 1, 2) else: axis = 'xyz'.index(arg.xvacuum) new.center(vacuum=arg.vacuum / 2., axis=axis) else: # By default, center the slab in the z direction and keep the original vacuum # length. new.center(axis=2) org_atom_index = np.arange(len(new), dtype=int) # Sort first by z-coordinates then by y and x. if arg.sort_pos: rpos = np.round(new.positions, 4) new_atom_index = np.lexsort((rpos[:, 0], rpos[:, 1], rpos[:, 2])) new = new[new_atom_index] # Just stick to the original order. chem_sym_order = [] for ss in slab.get_chemical_symbols() + mol.get_chemical_symbols(): if not ss in chem_sym_order: chem_sym_order.append(ss) # Re-arrange the atoms according to the new order of chemical symbols new_atom_index = [ ii for ss in chem_sym_order for ii in org_atom_index[new.symbols == ss] ] new = new[new_atom_index] write(arg.out, new, vasp5=True, direct=True, label=open(arg.slab).readline().strip())
#print(vars(ase_input_data)) spg_input = ase_to_spglib(ase_input_data) print("Number of atoms in input", len(spg_input[2])) # Reduce to primitive cell find_primitive = True if find_primitive: print(" Find primitive of conventional structure") lattice, positions, numbers = spglib.find_primitive(spg_input, symprec=1e-1) show_cell(lattice, positions, numbers) print("Number of atoms in primitive: ", len(numbers)) spg_molecule = (lattice, positions, numbers) ase_primitive_cell = spglib_to_ase(spg_molecule) ase_primitive_cell.set_pbc((1, 1, 1)) write('aei_primtive_cell.xyz', ase_primitive_cell) else: spg_molecule = spg_input # Get and print symmetry data dataset = spglib.get_symmetry_dataset(spg_molecule) print_spg_symmetry_info(dataset, equivalent_atoms=False, wyckoff=False) # Reduce cell/primitive cell to asymmetric cell of irreducible atomic positions neighbouring_atoms = True if neighbouring_atoms: irreducible_atom_indices = nearest_neighbour_asymmetric_cell_atom_indices( dataset, spg_molecule) else: irreducible_atom_indices = asymmetric_cell_atom_indices(dataset)
import warnings import numpy as np from ase.io import read, write from ase.calculators.emt import EMT from ase.build import bulk at = bulk("Cu") at.rattle() at.set_calculator(EMT()) f = at.get_forces() write("tmp.xyz", at) at2 = read("tmp.xyz") f2 = at.get_forces() assert np.abs(f - f2).max() < 1e-6 with warnings.catch_warnings(record=True) as w: # Cause all warnings to always be triggered. warnings.simplefilter("always") write("tmp2.xyz", at2) assert len(w) == 1 assert ('overwriting array' in str(w[0].message)) at3 = read("tmp2.xyz") f3 = at3.get_forces() assert np.abs(f - f3).max() < 1e-6
idx = [a.index for a in atoms if a.symbol == 'Pt'] Nbulk = len(idx) multiples = [0, 1, -1] for i in multiples: for j in multiples: if i == j == 0: continue chunk = atoms[idx] chunk.translate(i * cell[0] + j * cell[1]) atoms += chunk transmittances += [0.8] * Nbulk textures += ['pale'] * Nbulk bbox = [-30, 10, 5, 25] renderer = write('o2pt100.pov', atoms, rotation='90z,-75x', bbox=bbox, show_unit_cell=0, povray_settings=dict(pause=False, canvas_width=1024, bondatoms=bonded_atoms, camera_type='perspective', transmittances=transmittances, textures=textures)) renderer.render()
""" Creating (7 0, 6 6 ) Cu(111) surface """ from ase.build import fcc111 from ase.io import write from dlePy.supercell import create_matrix_surface primitive_cell = fcc111('Au', (1, 1, 5), vacuum=7.5) matrix = (7, 0, 6, 6) system = create_matrix_surface(primitive_cell, matrix) write('POSCAR', system, format='vasp', direct=True, vasp5=True)
a = 4.0 from ase import Atoms Pt3Rh = Atoms('Pt3Rh', scaled_positions=[(0, 0, 0), (0.5, 0.5, 0), (0.5, 0, 0.5), (0, 0.5, 0.5)], cell=[a, a, a], pbc=True) s3 = surface(Pt3Rh, (2, 1, 1), 9) s3.center(vacuum=10, axis=2) Pt3Rh.set_chemical_symbols('PtRhPt2') s4 = surface(Pt3Rh, (2, 1, 1), 9) s4.center(vacuum=10, axis=2) from ase.io import write for atoms, name in [(s1, 's1'), (s2, 's2'), (s3, 's3'), (s4, 's4')]: write(name + '.pov', atoms, rotation='-90x', show_unit_cell=2, transparent=False, display=False, run_povray=True) import os for i in range(2): error = os.system('pdflatex -interaction=nonstopmode general_surface ' + '> /dev/null') assert error == 0, 'pdflatex failed'
# creates: C2H4.png from ase.build.molecule import molecule from ase.io import write from ase.io.pov import get_bondpairs, set_high_bondorder_pairs C2H4 = molecule('C2H4') r = [{'C': 0.4, 'H': 0.2}[at.symbol] for at in C2H4] bondpairs = get_bondpairs(C2H4, radius=1.1) high_bondorder_pairs = {} # This defines offset, bond order, and bond_offset of the bond between 0 and 1 high_bondorder_pairs[(0, 1)] = ((0, 0, 0), 2, (0.17, 0.17, 0)) bondpairs = set_high_bondorder_pairs(bondpairs, high_bondorder_pairs) renderer = write('C2H4.pov', C2H4, format='pov', radii=r, rotation='90y', povray_settings=dict(canvas_width=200, bondatoms=bondpairs)) renderer.render()
disp = (ts.get_positions() - rs.get_positions()) / float(n_image) for i in range(n_image): configs.append(rs.copy()) c = FixAtoms(fix_atoms) for i in range(0, n_image): configs[i].set_positions(rs.get_positions() + disp * i) for j in reacting_center: configs[i][j].position = rs[j].position configs[i].set_constraint(c) # diff_area.append(find_area(configs[i], fix_atoms)-rs_area) # diff_area.append(poly_area(np.array([configs[i][j].position for j in fix_atoms[0:4:]])) + poly_area(np.array([configs[i][j].position for j in fix_atoms[2:6:]])) -rs_area) # diff_area.append(poly_area(np.array([configs[i][j].position for j in fix_atoms])) -rs_area) diff_area.append(find_area(configs[i], fix_atoms) - rs_area) write(str(i) + '.con', configs[i]) ds = np.linalg.norm(disp[18]) print ds energy = [] e_out = open(workdir + '/e_strain.dat', 'w') for i in range(n_image): os.chdir(workdir) if os.path.exists(str(i)): os.system('rm -rf ' + str(i)) os.makedirs(str(i)) inputfile = open(str(i) + '.con', 'r') output = open(str(i) + '/pos.con', 'w') n_line = 0 pd = []
e[i] = atoms.get_potential_energy() v[i] = atoms.get_volume() # Write outputs atoms.calc.write("c"+str(c[i])+".gpw") # Fit EOS eos_c = EquationOfState(v,e,eos='birchmurnaghan') v0, e0, B = eos_c.fit() c_scaling = v0/(volume*ab_scaling*ab_scaling) # Set atoms to optimized cell parameters atoms = read(input_structure) calc = GPAW(xc='PBE', gpts=gpoints, kpts=kpoints) atoms.set_calculator(calc) cell = atoms.get_cell() cell[0][:] = ab_scaling*cell[0][:] cell[1][:] = ab_scaling*cell[1][:] cell[2][:] = c_scaling*cell[2][:] atoms.set_cell(cell,scale_atoms=True) # Do atom relax and write outputs write(output_structure,atoms) name = atoms.get_chemical_formula(mode='hill') atoms.calc.set(txt=name+'.txt') atoms.calc.attach(atoms.calc.write, 5, name+'.gpw') dyn=BFGS(atoms=atoms, trajectory=name+'.traj', logfile = 'qn.log', maxstep=maxstep) dyn.run(fmax=fmaxx)
def write_input(self, atoms, properties=None, system_changes=None): FileIOCalculator.write_input(self, atoms, properties, system_changes) io.write(self.label + '.pwi', atoms, **self.parameters)
relax = PatchedOptimizer( sf, precon=precon, trajectory=args.trajectory, logfile=args.logfile, use_armijo=args.armijo, ) else: relax = PatchedOptimizer( mol, precon=precon, trajectory=args.trajectory, logfile=args.logfile, use_armijo=args.armijo, ) try: relax.run(econv=args.econv, fconv=args.fconv) except KeyboardInterrupt: print("User got impatient") except RuntimeError: print("Optimization terminated due to internal error") e = mol.get_potential_energy() print("Final energy: eV, Eh", e, e / Hartree) if mol.pbc.any(): write("xtbopt.POSCAR", mol, format="vasp") else: write("xtbopt.xyz", mol, format="xyz")
old = large.cell.copy() large *= (1, 1, 3) large.set_cell(old) #view(large) colors = np.zeros((len(large), 3)) colors[:] = [1., 1., .75] pr = [.7, .1, .1] H = [1, 1, 1] C = [.3, .3, .3] Pt = [.7, .7, .9] colors[164:218] = pr # principal layer colors[289:316] = pr # principal layer colors[218:289] = Pt # Central region Pt colors[316:322] = C # Molecule C colors[322:328] = H # Molecule H #write('test.png', large, rotation='-90x,-13y', radii=.9, show_unit_cell=0, colors=colors) write('transport_setup.pov', large, rotation='-90x,-13y', radii=1.06, show_unit_cell=0, colors=colors, display=False, transparent=False, run_povray=True)
]) # Relax all unrelaxed structures (e.g. the starting population) while (da.get_number_of_unrelaxed_candidates() > 0 and not pbs_run.enough_jobs_running()): a = da.get_an_unrelaxed_candidate() pbs_run.relax(a) # create the population population = Population(data_connection=da, population_size=population_size, comparator=comp) # Submit new candidates until enough are running while (not pbs_run.enough_jobs_running() and len(population.get_current_population()) > 2): a1, a2 = population.get_two_candidates() a3, desc = pairing.get_new_individual([a1, a2]) if a3 is None: continue da.add_unrelaxed_candidate(a3, description=desc) if random() < mutation_probability: a3_mut, desc = mutations.get_new_individual([a3]) if a3_mut is not None: da.add_unrelaxed_step(a3_mut, desc) a3 = a3_mut pbs_run.relax(a3) write('all_candidates.traj', da.get_all_relaxed_candidates())
sublattice_structure = read(cif_filename + '.cif') view(sublattice_structure) ######## Model Simulation Example - Cu NP ######## ase_xyz_filename = "Cu_NP_example.xyz" prismatic_xyz_filename = "Cu_NP_example_pris.xyz" surfaces = [(1, 0, 0), (1, 1, 0), (1, 1, 1)] layers = [6, 9, 5] lc = 3.61000 Cu_NP = FaceCenteredCubic('Cu', surfaces, layers, latticeconstant=lc) view(Cu_NP) write(filename=ase_xyz_filename, images=Cu_NP) prismatic_xyz = tml.convert_vesta_xyz_to_prismatic_xyz( vesta_xyz_filename=ase_xyz_filename, prismatic_xyz_filename=prismatic_xyz_filename, edge_padding=(2, 2, 1), delimiter=' | | ') tml.simulate_with_prismatic(xyz_filename=prismatic_xyz_filename, filename=prismatic_xyz_filename, reference_image=None, probeStep=0.1, E0=60e3, integrationAngleMin=0.085, integrationAngleMax=0.186, detectorAngleStep=0.001,
from ase import io t = io.read('mytrajectory.traj') for i, s in enumerate(t): # rotate to the desired direction s.rotate('z', 'x', rotate_cell=True) # repeat with keeping old cell cell = s.get_cell() s = s.repeat((1, 3, 3)) s.set_cell(cell) ofname = str(i) + '.png' print('writing', ofname) io.write(ofname, s, show_unit_cell=True, bbox=[-3, -5, 50, 22]) # set bbox by hand, try and error
# creates: a1.png, a2.png, a3.png, cnt1.png, cnt2.png, gnr1.png, gnr2.png from ase.io import write from ase.build import bulk from ase.build import nanotube, graphene_nanoribbon for i, a in enumerate([ bulk('Cu', 'fcc', a=3.6), bulk('Cu', 'fcc', a=3.6, orthorhombic=True), bulk('Cu', 'fcc', a=3.6, cubic=True) ]): write('a%d.pov' % (i + 1), a, display=False, run_povray=True) cnt1 = nanotube(6, 0, length=4, vacuum=2.5) cnt1.rotate('x', 'z', rotate_cell=True) cnt2 = nanotube(3, 3, length=6, bond=1.4, symbol='Si', vacuum=2.5) cnt2.rotate('x', 'z', rotate_cell=True) for i, a in enumerate([cnt1, cnt2]): write('cnt%d.pov' % (i + 1), a, display=False, run_povray=True) gnr1 = graphene_nanoribbon(3, 4, type='armchair', saturated=True, vacuum=2.5) gnr2 = graphene_nanoribbon(2, 6, type='zigzag', saturated=True, C_H=1.1, C_C=1.4, vacuum=3.0, magnetic=True, initial_mag=1.12)
def cluster_GA( nPool, eleNames, eleNums, eleRadii, generations, calc, filename, log_file, CXPB=0.5, singleTypeCluster=False, use_dask=False, use_vasp=False, al_method=None, al_learner_params=None, train_config=None, optimizer=BFGS, use_vasp_inter=False, restart=False, gen_num=None, ): """ DEAP Implementation of the GIGA Geneting Algorithm for nanoclusters nPool : Total number of clusters present in the initial pool eleNames : List of element symbols present in the cluster eleNums : List of the number of atoms of each element present in the cluster eleRadii : List of radii of each element present in the cluster generations : Total number of generations to run the genetic algorithm calc : The calculator used to perform relaxations (must be an ase calculator object) filename : Name of the file to be used to generate ase traj and db files log_file : Name of the log file CXPB : probability of a crossover operation in a given generation singleTypeCluster : Default = False, set to True if only 1 element is present in cluster use_Dask : Default = False, set to True if using dask (Refer examples on using dask) use_vasp : Default = False, set to True if using inbuilt vasp optimizer to run GA code (not supported with active learning) al_method : Default = None, accepts values 'online' or 'offline' al_learner_params : Default = None, refer examples or https://github.com/ulissigroup/al_mlp for sample set up trainer_config : Default = None, refer examples or https://github.com/ulissigroup/al_mlp for sample set up optimizer : Default = BFGS, ase optimizer to be used use_vasp_inter : Default = False, whether to use vasp interactive mode or not """ def calculate(atoms): """ Support function to assign the type of minimization to e performed (pure vasp, using ase optimizer or using active learning) """ if al_method is not None: atoms_min, parent_calls = minimize_al( atoms, calc, eleNames, al_learner_params, train_config, dataset_parent, optimizer, al_method, ) else: if use_vasp == True: atoms_min = minimize_vasp(atoms, calc) else: atoms_min = minimize(atoms, calc, optimizer, use_vasp_inter) return atoms_min, parent_calls if al_method is not None: al_method = al_method.lower() # Creating DEAP types creator.create("FitnessMax", base.Fitness, weights=(1.0, )) creator.create("Individual", list, fitness=creator.FitnessMax) # Registration of the evolutionary tools in the toolbox toolbox = base.Toolbox() toolbox.register("poolfill", fillPool, eleNames, eleNums, eleRadii, calc) toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.poolfill, 1) toolbox.register("evaluate", fitness_func) toolbox.register("population", tools.initRepeat, list, toolbox.individual) # Registering mutations and crossover operators toolbox.register("mate", mate) toolbox.register("mutate_homotop", homotop) toolbox.register("mutate_rattle", rattle_mut) toolbox.register("mutate_rotate", rotate_mut) toolbox.register("mutate_twist", twist) toolbox.register("mutate_tunnel", tunnel) toolbox.register("mutate_partialinv", partialInversion) toolbox.register("mutate_skin", skin) toolbox.register("mutate_changecore", changeCore) # Registering selection operator toolbox.register("select", tools.selTournament) #Initialize the parent dataset dataset_parent = [] # Creating a list of cluster atom objects from population if not restart: population = toolbox.population(n=nPool) pop_list = [] for individual in population: pop_list.append(individual[0]) write('init_pop_before_relax.traj', pop_list) if use_dask == True: # distribute and run the calculations (requires dask and needs to be set up correctly) clus_bag = db.from_sequence(pop_list, partition_size=1) clus_bag_computed = clus_bag.map(calculate) lst_clus_min = clus_bag_computed.compute() else: lst_clus_min = list(map(calculate, pop_list)) for i, p in enumerate(population): p[0] = lst_clus_min[i][0] init_pop_list_after_relax = [] for individual in population: init_pop_list_after_relax.append(individual[0]) write('init_pop_after_relax.traj', init_pop_list_after_relax) with open(log_file, "a+") as fh: fh.write( f'Total clusters in the intital pool after relaxationi: {len(population)}' "\n") #parent_calls list if online learner total_parent_calls = [] parent_calls_initial_pool = [] for i in range(len(lst_clus_min)): parent_calls_initial_pool.append(lst_clus_min[i][1]) total_parent_calls.extend(parent_calls_initial_pool) with open(log_file, "a+") as fh: fh.write( f'parent calls after initial pool relaxation: {parent_calls_initial_pool}' '\n') fh.write( f'Total parent calls after initial pool relaxation: {sum(parent_calls_initial_pool)}' '\n') # Fitnesses (or Energy) values of the initial random population fitnesses = list(map(toolbox.evaluate, population)) for ind, fit in zip(population, fitnesses): ind.fitness.values = fit #Removing bad geometries population_filter = [] for i, p in enumerate(population): if checkBonded(p[0]) == True: if checkOverlap(p[0]) == False: population_filter.append(p) population = copy.deepcopy(population_filter) init_pop_list_after_filter = [] for individual in population: init_pop_list_after_filter.append(individual[0]) write('init_pop_after_filter.traj', init_pop_list_after_filter) with open(log_file, "a+") as fh: fh.write( f'Total clusters in the intital pool after filtering: {len(population)}' "\n") fitnesses_init_pool = list(map(toolbox.evaluate, population)) with open(log_file, "a+") as fh: fh.write("Energies (fitnesses) of the initial pool" "\n") for value in fitnesses_init_pool: fh.write("{} \n".format(value[0])) # Evolution of the Genetic Algorithm with open(log_file, "a+") as fh: fh.write("\n") fh.write("Starting Evolution" "\n") g = 0 # Generation counter init_pop_db = ase.db.connect("init_pop_{}.db".format(filename)) for cl in population: write_to_db(init_pop_db, cl[0]) bi = [] else: population = toolbox.population(n=nPool) restart_gen = 'best_n_clus_after_gen' + str(gen_num) + '.traj' restart_traj = Trajectory(restart_gen) for i, p in enumerate(population): p[0] = restart_traj[i] # Fitnesses (or Energy) values of the restart population from the gen_num fitnesses = list(map(toolbox.evaluate, population)) for ind, fit in zip(population, fitnesses): ind.fitness.values = fit fitnesses_restart_pool = list(map(toolbox.evaluate, population)) # Restarting the Evolution of the Genetic Algorithm from Restart Trajectory with open(log_file, "a+") as fh: fh.write("\n") fh.write("Restarting Evolution" "\n") fh.write("Energies (fitnesses) of the Restarted pool" "\n") for value in fitnesses_restart_pool: fh.write("{} \n".format(value[0])) fh.write("\n") g = gen_num # Generation counter -Restart gen number #parent_calls list if online learner total_parent_calls = [] bi = [] old_final_pop_db = "./final_pop_{}.db".format(filename) copy_final_pop_db = "final_pop_{}_{}.db".format(filename, gen_num) if os.path.exists(old_final_pop_db): subprocess.call( ['mv', old_final_pop_db, 'old_' + copy_final_pop_db]) ##### Evolution of Generations ###### while g < generations: mutType = None muttype_list = [] g = g + 1 with open(log_file, "a+") as fh: fh.write("{} {} \n".format("Generation", g)) cm_pop = [] if random.random() < CXPB: # Crossover Operation mutType = "crossover" with open(log_file, "a+") as fh: fh.write("{} {} \n".format("mutType", mutType)) # Crossover operation step. # The child clusters will be checked for bonding and similarity # between other child clusters. loop_count = 0 while ( loop_count != 200 ): # Perform 200 possible crossovers or until unique crossovers match pool size clusters = toolbox.select(population, 2, 1) muttype_list.append(mutType) parent1 = copy.deepcopy(clusters[0]) parent2 = copy.deepcopy(clusters[1]) fit1 = clusters[0].fitness.values (f1, ) = fit1 fit2 = clusters[1].fitness.values (f2, ) = fit2 child_clus = toolbox.mate(parent1[0], parent2[0], f1, f2) parent1[0] = child_clus diff_list = [] if checkBonded(parent1[0]) == True: if loop_count == 0: cm_pop.append(parent1) else: for c, cluster in enumerate(cm_pop): diff = checkSimilar(cluster[0], parent1[0]) diff_list.append(diff) if all(diff_list) == True: cm_pop.append(parent1) loop_count = loop_count + 1 if len(cm_pop) == nPool: break else: # Mutation Operation mutType = "mutations" with open(log_file, "a+") as fh: fh.write("{} {} \n".format("mutType", mutType)) # Mutation opeation step # Each cluster in the population will undergo a randomly chosen mutation step # Mutated new clusters will be checked for bonding and similarity with other new clusters for m, mut in enumerate(population): mutant = copy.deepcopy(mut) if singleTypeCluster: mutType = random.choice([ "rattle", "rotate", "twist", "partialinv", "tunnel", "skin", "changecore", ]) else: mutType = random.choice([ "rattle", "rotate", "homotop", "twist", "partialinv", "tunnel", "skin", "changecore", ]) muttype_list.append(mutType) if mutType == "homotop": mutant[0] = toolbox.mutate_homotop(mutant[0]) if mutType == "rattle": mutant[0] = toolbox.mutate_rattle(mutant[0]) if mutType == "rotate": mutant[0] = toolbox.mutate_rotate(mutant[0]) if mutType == "twist": mutant[0] = toolbox.mutate_twist(mutant[0]) if mutType == "tunnel": mutant[0] = toolbox.mutate_tunnel(mutant[0]) if mutType == "partialinv": mutant[0] = toolbox.mutate_partialinv(mutant[0]) if mutType == "skin": mutant[0] = toolbox.mutate_skin(mutant[0]) if mutType == "changecore": mutant[0] = toolbox.mutate_changecore(mutant[0]) diff_list = [] if checkBonded(mutant[0]) == True: for c, cluster in enumerate(cm_pop): diff = checkSimilar(cluster[0], mutant[0]) diff_list.append(diff) if all(diff_list) == True: cm_pop.append(mutant) with open(log_file, "a+") as fh: fh.write("{} {} \n".format("mutType_list", muttype_list)) mut_new_lst = [] for mut in cm_pop: mut_new_lst.append(mut[0]) write('mut_before_relax_gen' + str(g) + '.traj', mut_new_lst) # DASK Parallel relaxation of the crossover child/mutated clusters if use_dask == True: mut_bag = db.from_sequence(mut_new_lst, partition_size=1) mut_bag_computed = mut_bag.map(calculate) mut_new_lst_min = mut_bag_computed.compute() else: mut_new_lst_min = list(map(calculate, mut_new_lst)) for i, mm in enumerate(cm_pop): mm[0] = mut_new_lst_min[i][0] mut_list_after_relax = [] for individual in cm_pop: mut_list_after_relax.append(individual[0]) write('mut_after_relax_gen' + str(g) + '.traj', mut_list_after_relax) with open(log_file, "a+") as fh: fh.write( f'Total clusters relaxed in Generation {g}: {len(cm_pop)}' "\n") #parent calls list if online learner parent_calls_mut_list = [] for i in range(len(mut_new_lst_min)): parent_calls_mut_list.append(mut_new_lst_min[i][1]) total_parent_calls.extend(parent_calls_mut_list) with open(log_file, "a+") as fh: fh.write( f'Parent calls list after relaxtions in this generation: {parent_calls_mut_list} ' '\n') fh.write( f'Total Parent calls specific to this generation: {sum(parent_calls_mut_list)} ' '\n') fh.write( f'Total Parent calls up to this generation: {sum(total_parent_calls)} ' '\n') fitnesses_mut = list(map(toolbox.evaluate, cm_pop)) for ind, fit in zip(cm_pop, fitnesses_mut): ind.fitness.values = fit new_population = copy.deepcopy(population) # Relaxed clusters will be checked for bonded and similarity with the other # clusters in the population. If dissimilar, they will be added to the new population. for cm1, cmut1 in enumerate(cm_pop): new_diff_list = [] if checkBonded(cmut1[0]) == True: if checkOverlap(cmut1[0]) == False: for c2, cluster1 in enumerate(population): diff = checkSimilar(cluster1[0], cmut1[0]) new_diff_list.append(diff) if all(new_diff_list) == True: new_population.append(cmut1) else: pass mut_list_after_filter = [] for individual in new_population: mut_list_after_filter.append(individual[0]) write('mut_after_filter_gen' + str(g) + '.traj', mut_list_after_filter) with open(log_file, "a+") as fh: fh.write( f'Total clusters flitered out in Generation {g}: {len(cm_pop) + len(population) - len(new_population)}' "\n") fh.write( f'Total clusters in the pool after filtering in Generation {g}: {len(new_population)}' "\n") fitnesses_pool = list(map(toolbox.evaluate, new_population)) with open(log_file, "a+") as fh: fh.write( "Energies (fitnesses) of the present pool before best 10 are selected" "\n") for value in fitnesses_pool: fh.write("{} \n".format(value[0])) # Selecting the lowest energy npool clusters from the new_population len_new_pop = len(new_population) if len_new_pop > nPool: best_n_clus = tools.selWorst(new_population, nPool) else: best_n_clus = new_population best_n_clus_list = [] for individual in best_n_clus: best_n_clus_list.append(individual[0]) write('best_n_clus_after_gen' + str(g) + '.traj', best_n_clus_list) population = best_n_clus best_clus = tools.selWorst(population, 1)[0] with open(log_file, "a+") as fh: fh.write("{} {} \n".format("Lowest energy for this generation is", best_clus.fitness.values[0])) fh.write("\n Best cluster in this generation: \n") for atom in best_clus[0]: fh.write("{} {:12.8f} {:12.8f} {:12.8f} \n".format( atom.symbol, atom.x, atom.y, atom.z)) fh.write("\n") bi.append(best_clus[0]) if g == 1: writer = TrajectoryWriter(filename + "_best.traj", mode="w", atoms=best_clus[0]) writer.write() else: writer = TrajectoryWriter(filename + "_best.traj", mode="a", atoms=best_clus[0]) writer.write() final_pop_db = ase.db.connect("final_pop_{}.db".format(filename)) for clus in population: write_to_db(final_pop_db, clus[0]) with open(log_file, "a+") as fh: fh.write("Global Minimum after {} Generations \n".format(g)) for atom in best_clus[0]: fh.write("{} {:12.8f} {:12.8f} {:12.8f} \n".format( atom.symbol, atom.x, atom.y, atom.z)) # Return the list of best clusters in every generations and the overall best cluster return bi, best_clus[0]
# Exception("CMR is not configured properly. Please create the settings file with cmr --create-settings.") try: import cmr except (Exception, ImportError): raise NotAvailable('CMR is required') from ase.calculators.emt import EMT from ase.io import read, write from ase.structure import molecule m1 = molecule('O2') m1.center(2.0) write("O2.cmr", images=m1) m1.set_calculator(EMT()) e1 = m1.get_potential_energy() f1 = m1.get_forces() m2 = read("O2.cmr") m2.set_calculator(EMT()) e2 = m2.get_potential_energy() f2 = m1.get_forces() # assume atoms definitions are the same if energy/forces are the same: can we do better? assert abs(e1 - e2) < 1.e-6, str(e1) + ' ' + str(e2) assert array_almost_equal(f1, f2, tol=1.e-6)
# -*- coding: utf-8 -*- # creates: diffusion-I.png, diffusion-T.png, diffusion-F.png # creates: diffusion-barrier.png from ase.io import read, write from ase.neb import NEBTools if 1: exec(compile(open('diffusion1.py').read(), 'diffusion1.py', 'exec')) exec(compile(open('diffusion2.py').read(), 'diffusion2.py', 'exec')) exec(compile(open('diffusion4.py').read(), 'diffusion4.py', 'exec')) exec(compile(open('diffusion5.py').read(), 'diffusion5.py', 'exec')) images = read('neb.traj@-5:') for name, a in zip('ITF', images[::2]): cell = a.get_cell() del a.constraints a = a * (2, 2, 1) a.set_cell(cell) write('diffusion-%s.pov' % name, a, show_unit_cell=True, transparent=False, display=False, run_povray=True) nebtools = NEBTools(images) assert abs(nebtools.get_barrier()[0] - 0.374) < 1e-3
def main(): parser = optparse.OptionParser( usage='%prog [options] name/input-file [output-file]') add = parser.add_option add('-M', '--magnetic-moment', metavar='M1,M2,...', help='Magnetic moment(s). ' + 'Use "-M 1" or "-M 2.3,-2.3".') add('--modify', metavar='...', help='Modify atoms with Python statement. ' + 'Example: --modify="atoms.positions[-1,2]+=0.1".') add('-v', '--vacuum', type=float, default=3.0, help='Amount of vacuum to add around isolated atoms ' '(in Angstrom).') add('--unit-cell', help='Unit cell. Examples: "10.0" or "9,10,11" ' + '(in Angstrom).') add('--bond-length', type=float, help='Bond length of dimer in Angstrom.') add('-x', '--crystal-structure', help='Crystal structure.', choices=[ 'sc', 'fcc', 'bcc', 'hcp', 'diamond', 'zincblende', 'rocksalt', 'cesiumchloride', 'fluorite' ]) add('-a', '--lattice-constant', default='', help='Lattice constant(s) in Angstrom.') add('--orthorhombic', action='store_true', help='Use orthorhombic unit cell.') add('--cubic', action='store_true', help='Use cubic unit cell.') add('-r', '--repeat', help='Repeat unit cell. Use "-r 2" or "-r 2,3,1".') add('-g', '--gui', action='store_true') opts, args = parser.parse_args() if len(args) == 0 or len(args) > 2: parser.error('Wrong number of arguments!') name = args.pop(0) if '.' in name: # Read from file: atoms = read(name) elif opts.crystal_structure: atoms = build_bulk(name, opts) else: atoms = build_molecule(name, opts) if opts.magnetic_moment: magmoms = np.array([float(m) for m in opts.magnetic_moment.split(',')]) atoms.set_initial_magnetic_moments( np.tile(magmoms, len(atoms) // len(magmoms))) if opts.modify: exec opts.modify in {'atoms': atoms} if opts.repeat is not None: r = opts.repeat.split(',') if len(r) == 1: r = 3 * r atoms = atoms.repeat([int(c) for c in r]) if args: write(args[0], atoms) elif sys.stdout.isatty(): write(name + '.json', atoms) else: con = connect(sys.stdout, type='json') con.write(name, atoms)
# 0 0 ax = plt.subplot(gs[0, 0]) image = image * (2,1,1) img = image.copy() plot_conf(ax, img) ax.set_xlim([-6.2, 13.5]) ax.set_ylim([10.7, 20.0]) ax.set_yticks([]) ax.set_xticks([]) ax.set(aspect=1) # 0 1 ax = plt.subplot(gs[1, 0]) image = image * (1,2,1) write('newimage.traj',image) cell = image.get_cell() img = image.copy() plot_conf(ax, img, rot=True) ax.set_xlim([-6.2, 13.50]) ax.set_ylim([0.0, 14.0]) ax.set_yticks([]) ax.set_xticks([]) ax.set(aspect=1) gs.update(wspace=0.00,hspace=0.00) plt.tight_layout() name ='Pt10_3O2_Al2O3_0001_DFTopt_g{}'.format(j) savefig(name,bbox_inches='tight')
# Make a mask of zeros and ones that select fixed atoms (the # two bottom layers): mask = initial.positions[:, 2] - min(initial.positions[:, 2]) < 1.5 * h constraint = FixAtoms(mask=mask) print(mask) for image in images: # Let all images use an EMT calculator: image.calc = EMT() image.set_constraint(constraint) # Relax the initial and final states: QuasiNewton(initial).run(fmax=0.05) QuasiNewton(final).run(fmax=0.05) # Create a Nudged Elastic Band: neb = NEB(images) # Make a starting guess for the minimum energy path (a straight line # from the initial to the final state): neb.interpolate() # Relax the NEB path: minimizer = MDMin(neb) minimizer.run(fmax=0.05) # Write the path to a trajectory: view(images) # 564 meV write('jump2.traj', images)
#cut away periodic image planes u = nx - 1 v = ny - 1 w = nz - 1 cd2 = np.empty((u, v, w), np.float) for i in range(u): for j in range(v): cd2[i][j][:] = cd[i][j][:w] bohr = 0.52917721092 integral = np.sum(cd2.flat) * atoms.get_volume() / (u * v * w) / bohr**3 print "total electrons" print integral io.write('density.cube', atoms, data=cd2) xyzname = 'qn.xyz' #name.split('.')[0]+'.xyz' io.write(xyzname, atoms) os.system( '/nfs/slac/g/suncatfs/sw/external/bader-0.27c/bader density.cube' ) # see http://theory.cm.utexas.edu/henkelman/code/bader/ for print options atoms = io.read('density.cube') attach_charges(atoms) os.system('rm Bv*.cube AtIndex.cube') dos = calc.calc_pdos(nscf=True, kpts=(8, 8, 1), Emin=-50.0, Emax=50.0, tetrahedra=False, sigma=0.08)
def test(format): if format in ['abinit', 'castep-cell', 'dftb', 'eon', 'gaussian']: # Someone should do something ... return if format in ['v-sim', 'mustem']: # Standalone test used as not compatible with 1D periodicity return if format in ['mustem']: # Standalone test used as specific arguments are required return if format in ['dmol-arc', 'dmol-car', 'dmol-incoor']: # We have a standalone dmol test return if format in ['gif', 'mp4']: # Complex dependencies; see animate.py test return if format in ['postgresql', 'trj', 'vti', 'vtu']: # Let's not worry about these. return if not matplotlib and format in ['eps', 'png']: return if not etree and format == 'exciting': return if not Scientific and format == 'etsf': return if not netCDF4 and format == 'netcdftrajectory': return atoms = get_atoms() images = [atoms, atoms] io = get_ioformat(format) print('{0:20}{1}{2}{3}{4}'.format(format, ' R'[bool(io.read)], ' W'[bool(io.write)], '+1'[io.single], 'SF'[io.acceptsfd])) fname1 = '{}/io-test.1.{}'.format(testdir, format) fname2 = '{}/io-test.2.{}'.format(testdir, format) if io.write: write(fname1, atoms, format=format) if not io.single: write(fname2, images, format=format) if io.read: for a in [read(fname1, format=format), read(fname1)]: check(a, atoms, format) if not io.single: if format in ['json', 'db']: aa = read(fname2 + '@id=1') + read(fname2 + '@id=2') else: aa = [read(fname2), read(fname2, 0)] aa += read(fname2, ':') for a in iread(fname2, format=format): aa.append(a) assert len(aa) == 6, aa for a in aa: check(a, atoms, format)
else: atoms = io.read('InitialGeom.xyz') cell = ([18.21500974, 0, 0], [-7.2860039, 8.92349591, 0], [0, 0, 34.94966576]) atoms.set_cell(cell) atoms.set_pbc([1, 1, 1]) constraint_s = " ".join( [str(i + 1) for i in range(len(atoms)) if atoms[i].position[2] < 9]) print constraint_s constraint = FixAtoms( indices=[atom.index for atom in atoms if atom.position[2] < 9]) c = FixBondLength(274, 276) atoms.set_constraint([constraint, c]) io.write('InitialGeom.traj', atoms) SYSNAME = 'MgAl2O4' calc = CP2K(label=SYSNAME, xc='PBE', cutoff=None, basis_set_file=None, potential_file=None, basis_set=None, pseudo_potential=None, stress_tensor=False, max_scf=None, inp=inp, print_level='LOW')
if name.endswith('corrected'): n = 6 # get the vacuum level 6 grid-points from the boundary plt.plot([0.2, 0.2], [efermi, v[n]], 'r:') plt.text(0.23, (efermi + v[n]) / 2, '$\phi$ = %.2f eV' % (v[n] - efermi), va='center') plt.plot([z[-1] - 0.2, z[-1] - 0.2], [efermi, v[-n]], 'r:') plt.text(z[-1] - 0.23, (efermi + v[-n]) / 2, '$\phi$ = %.2f eV' % (v[-n] - efermi), va='center', ha='right') plt.xlabel('$z$, $\AA$') plt.ylabel('(Pseudo) electrostatic potential, V') plt.xlim([0., z[-1]]) if name == 'pwcorrected': title = 'PW-mode corrected' else: title = name.title() plt.title(title + ' boundary conditions') plt.savefig(name + '.png') write('slab.pov', calc.atoms, rotation='-90x', show_unit_cell=2, transparent=False, display=False, run_povray=True)
def run(self, names=None): """Run task for all names. The task will be one of these four: * Open ASE's GUI * Write configuration to file * Write summary * Do the actual calculation """ if self.lock is None: # Create lock object: self.lock = Lock(self.get_filename(ext='lock')) if self.clean: self.clean_json_file(names) return if names is None or len(names) == 0: names = self.collection.keys() names = self.expand(names) names = names[self.slice] names = self.exclude(names) if self.gui: for name in names: view(self.create_system(name)) return if self.write_to_file: if self.write_to_file[0] == '.': for name in names: filename = self.get_filename(name, self.write_to_file) write(filename, self.create_system(name)) else: assert len(names) == 1 write(self.write_to_file, self.create_system(names[0])) return if self.write_summary: self.read() self.analyse() self.summarize(names) return atoms = None for name in names: if self.use_lock_files: try: filename = self.get_filename(ext='json') self.lock.acquire() if os.path.isfile(filename): data = read_json(filename) if name not in data: data[name] = {} write_json(filename, data) else: self.log('Skipping', name) continue else: write_json(filename, {name: {}}) finally: self.lock.release() if atoms is not None: del atoms.calc atoms = self.run_single(name) return atoms