def generate_restricted_gs(): traj = TrajectoryWriter("data/restricted_gs_5x1x1.traj", mode='a') N = 400 for i in range(N): print("{} of {}".format(i, N)) atoms = get_gs() traj.write(atoms)
def main(): db_name = "data/almgsicu.db" traj = TrajectoryWriter("data/almgsicu_data.traj") db = connect(db_name) groups = set() for row in db.select(): g = row.get('group', None) if g is not None and g not in exclude_groups: groups.add(g) structures = [] for g in groups: row = db.get(group=g, struct_type='initial') init = row.toatoms() if init.get_chemical_formula() in ignore_formulas: continue try: final = db.get(group=g, struct_type='relaxed') except: continue energy = 0.0 if final is not None: energy = final.energy calc = SinglePointCalculator(init, energy=energy) init.calc = calc structures.append(init) for idx in sorted(equiv_from_atat, reverse=True): del structures[idx] for s in structures: traj.write(s)
def __init__(self, trajfile="default.traj", atoms=None): super(Snapshot, self).__init__() self.name = "Snapshot" if not trajfile.endswith(".traj"): msg = "This object stores all images in a trajectory file. " msg += "File extension should be .traj" raise ValueError(msg) if atoms is None: raise ValueError("No atoms object given!") self.atoms = atoms self.traj = TrajectoryWriter(trajfile, mode="a") self.fname = trajfile
def rotate(self, atms=None, axis=None, axis_vector=None, o=None, rang=20.0, nbin=10, wtraj=False, scale=1.2): da = 2.0 * rang / nbin atoms = self.ir.atoms self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, scale * self.ir.re, self.ir.bo0) images = [] if wtraj: his = TrajectoryWriter('rotate.traj', mode='a') if axis_vector is None: i, j = axis vaxis = atoms.positions[j] - atoms.positions[i] uk = vaxis / self.ir.r[i][j] else: uk = axis_vector a_ = -rang while a_ < rang: atoms_ = atoms.copy() for atomk in atms: vo = atoms.positions[atomk] - atoms.positions[o] r_ = np.dot(vo, uk) o_ = atoms.positions[o] + r_ * uk vi = atoms.positions[atomk] - o_ r = np.sqrt(np.sum(np.square(vi))) ui = vi / r uj = np.cross(uk, ui) a = a_ * 3.14159 / 180.0 p = r * np.cos(a) * ui + r * np.sin(a) * uj atoms_.positions[atomk] = o_ + p self.ir.calculate(atoms_) calc = SinglePointCalculator(atoms_, energy=self.ir.E) atoms_.set_calculator(calc) images.append(atoms_) if wtraj: his.write(atoms=atoms_) a_ += da return images
def stretch(self,pair,atoms=None,nbin=20,rst=0.7,red=1.3,scale=1.25,traj=None, ToBeMoved=None,neighbors=None): if atoms is None: atoms = self.ir.atoms if neighbors is None: self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom,self.ir.r,scale*self.ir.re,self.ir.bo0) images = [] if not traj is None: his = TrajectoryWriter(traj,mode='w') #for pair in pairs: i,j = pair if ToBeMoved is None: ToBeMove = [] ToBeMove,ring = getAtomsToMove(i,j,j,ToBeMove,neighbors) else: ToBeMove = ToBeMoved ring = False if ring: # return None ToBeMove = [j] bin_ = (red - rst)/nbin moveDirection = self.ir.vr[j][i]/self.ir.r[i][j] for n in range(nbin+1): atoms_ = atoms.copy() moveV = atoms.positions[i] + moveDirection*(rst+bin_*n)-atoms.positions[j] # print(self.ir.re[i][j]*self.rmin+bin_*n) for m in ToBeMove: # sPos = atoms.positions[i] + self.ir.re[i][m]*self.rmin*moveDirection newPos = atoms.positions[m] + moveV r = np.sqrt(np.sum(np.square(newPos-atoms.positions[i]))) atoms_.positions[m] = newPos self.ir.calculate(atoms_) i_= np.where(np.logical_and(self.ir.r<self.ir.re[i][j]*self.rmin-bin_,self.ir.r>0.0001)) n = len(i_[0]) try: assert n==0,'Atoms too closed!' except: print('Atoms too closed.') break calc = SinglePointCalculator(atoms_,energy=self.ir.E) atoms_.set_calculator(calc) images.append(atoms_) if not traj is None: his.write(atoms=atoms_) return images
def store_trajectory_neb(self): # Evaluated images. TrajectoryWriter(atoms=self.ase_ini, filename='./evaluated_structures.traj', mode='a').write() # Last path. write('last_predicted_path.traj', self.images) # All paths. for i in self.images: TrajectoryWriter(atoms=i, filename='all_predicted_paths.traj', mode='a').write()
def query_func(self): """ Default random query strategy. """ # queries_db = ase.db.connect("queried_images.db") if len(self.sample_candidates) <= self.samples_to_retrain: print( "Number of sample candidates is less than or equal to the requested samples to retrain, defaulting to all samples but the initial and final" ) query_idx = [*range(1, len(self.sample_candidates) - 1)] if query_idx == []: query_idx = [ 0 ] # EDGE CASE WHEN samples = 2 (need a better way to do it) else: query_idx = random.sample( range(1, len(self.sample_candidates) - 1), self.samples_to_retrain - 1, ) # query_idx = np.append(query_idx, [len(self.sample_candidates) - 1]) queried_images = [self.sample_candidates[idx] for idx in query_idx] # write_to_db(queries_db, queried_images) if self.iterations == 1: writer = TrajectoryWriter("queried_images.traj", mode="w") for i in queried_images: writer.write(i) else: writer = TrajectoryWriter("queried_images.traj", mode="a") for i in queried_images: writer.write(i) self.parent_calls += len(queried_images) return queried_images
def do_after_train(self): """ Executes after training the trainer in every active learning loop. """ trainer_calc = self.make_trainer_calc() self.trained_calc = DeltaCalc([trainer_calc, self.base_calc], "add", self.refs) self.atomistic_method.run(calc=self.trained_calc, filename=self.fn_label) self.sample_candidates = list( self.atomistic_method.get_trajectory(filename=self.fn_label) ) final_point_image = [self.sample_candidates[-1]] # print(final_point_image[0].get_positions()) final_point_evA = compute_with_calc(final_point_image, self.parent_calc) self.final_point_force = np.max(np.abs(final_point_evA[0].get_forces())) self.training_data += subtract_deltas( final_point_evA, self.base_calc, self.refs ) self.parent_calls += 1 # final_queries_db = ase.db.connect("final_queried_images.db") random.seed(self.query_seeds[self.iterations - 1] + 1) # write_to_db(final_queries_db, final_point_image) if self.iterations == 0: writer = TrajectoryWriter("final_images.traj", mode="w") writer.write(final_point_image[0]) else: writer = TrajectoryWriter("final_images.traj", mode="a") writer.write(final_point_image[0]) self.terminate = self.check_terminate() self.iterations += 1
class SnapshotNoAl(MCObserver): def __init__(self, fname, atoms): self.tw = TrajectoryWriter(fname) self.atoms = atoms def __call__(self, change): at = self.atoms.copy() for i in range(len(at), 0, -1): if at[i - 1].symbol == 'Al': del at[i - 1] self.tw.write(at) def close(self): self.tw.close()
def path2trajectory( self, fname="relaxed_path.traj" ): """ Writes the path to a trajectory file """ traj = TrajectoryWriter(fname,'w') for energy,state in zip(self.init_path["energy"], self.init_path["symbols"]): self.nuc_mc.network.reset() self.nuc_mc.set_state(state) self.nuc_mc.network(None) atoms = self.nuc_mc.network.get_atoms_with_largest_cluster( prohibited_symbols=["Al","Mg"] ) if atoms is None: atoms = self.nuc_mc.atoms calc = SinglePointCalculator(atoms, energy=energy) traj.write(atoms) self.log( "Trajectory written to {}".format(fname))
def _relax_with_vasp(atoms, vasp_flags): ''' Perform a DFT relaxation with VASP and then write the trajectory to the 'all.traj' file and save the log file. Args: atoms `ase.Atoms` object of the structure we want to relax vasp_flags A dictionary of settings we want to pass to the `Vasp2` calculator Returns: atoms The relaxed `ase.Atoms` structure ''' # Run the calculation calc = Vasp2(**vasp_flags) atoms.set_calculator(calc) atoms.get_potential_energy() # Read the trajectory from the output file images = [] for atoms in ase.io.read('vasprun.xml', ':'): image = atoms.copy() image = image[calc.resort] image.set_calculator(SPC(image, energy=atoms.get_potential_energy(), forces=atoms.get_forces()[calc.resort])) images += [image] # Write the trajectory with TrajectoryWriter('all.traj', 'a') as tj: for atoms in images: tj.write(atoms) return images[-1]
def main(): a = 4.05 atoms = bulk('Al', cubic=True, a=a) * (N, N, N) tags, _ = get_layers(atoms, (0, 0, 1)) pos = atoms.get_positions().copy() center = np.mean(pos, axis=0) + np.array([a / 4, a / 4, 0.0]) pos -= center radii = np.sqrt(np.sum(pos[:, :2]**2, axis=1)) indices = np.argsort(radii) num_per_layer = 5 all_indices = [] for layer in range(2, 12): symbol = 'Mg' if layer % 2 == 0 else 'Si' num_inserted = 0 for i in indices: if tags[i] == layer and num_inserted < num_per_layer: atoms[i].symbol = symbol num_inserted += 1 all_indices.append(i) # Extract all items in the 2 layers above indices_si = [] indices_mg = [] num_si = 4 num_mg = 5 for layer in range(12, 14): num_extracted = 0 num_to_extract = num_mg if layer % 2 == 0 else num_si for i in indices: if tags[i] == layer and num_extracted < num_to_extract: if layer % 2 == 0: indices_mg.append(i) else: indices_si.append(i) num_extracted += 1 print(len(indices_mg), len(indices_si)) traj = TrajectoryWriter("data/specialMgSiClusters.traj") for symbMg in product(['Al', 'Mg'], repeat=len(indices_mg)): for symbSi in product(['Al', 'Si'], repeat=len(indices_si)): atoms_cpy = atoms.copy() for i in range(len(indices_mg)): atoms_cpy[indices_mg[i]].symbol = symbMg[i] for j in range(len(indices_si)): atoms_cpy[indices_si[j]].symbol = symbSi[j] traj.write(atoms_cpy)
def LearningResult_angel(ffield='ffield.json', nn='T', gen='poscar.gen', traj='C1N1O2H30.traj'): images = Trajectory(traj) traj_ = TrajectoryWriter(traj[:-5] + '_.traj', mode='w') atoms = images[0] nn_ = True if nn == 'T' else False ir = IRFF_NP(atoms=atoms, libfile=ffield, rcut=None, nn=nn_) natom = ir.natom Empnn, Esiesta = [], [] eb, eb_ = [], [] eang_ = [] theta0 = [] l = len(images) for _ in range(l - 10, l): atoms = images[_] ir.calculate(atoms) Empnn.append(ir.E) Esiesta.append(atoms.get_potential_energy()) atoms_ = atoms.copy() atoms_.set_initial_charges(charges=ir.q) calc = SinglePointCalculator(atoms_, energy=ir.E) atoms_.set_calculator(calc) traj_.write(atoms=atoms_) eang_.append(ir.Eang) # print(ir.Eang) # print(ir.SBO3) for a, ang in enumerate(ir.angi): th0 = ir.thet0[a] #*180.0/3.14159 th = ir.theta[a] # *180.0/3.14159 i, j, k = ir.angi[a][0], ir.angj[a][0], ir.angk[a][0] print( '%s-%s-%s' % (ir.atom_name[i], ir.atom_name[j], ir.atom_name[k]), 'thet0: %8.6f' % th0, 'thet: %f8.6' % th, 'sbo3 %8.6f:' % ir.SBO3[a], 'Dpi: %8.6f' % ir.Dpi[ir.angj[a][0]], 'pbo: %8.6f' % ir.PBO[ir.angj[a][0]], 'nlp: %8.6f' % ir.nlp[ir.angj[a][0]], 'Dang: %8.6f' % ir.Dang[ir.angj[a][0]], # 'eang:',ir.eang[a],'expang:',ir.expang[a], )
def get_cpmd_data(self): fe = open('ENERGIES', 'r') lines = fe.readlines() fe.close() nl = len(lines) xs = [] self.energy_nw = [] if isfile('inp-nve'): inp = 'inp-nve' elif isfile('inp-nvt'): inp = 'inp-nvt' else: print('- error: inp-nvt or inp-nve file not found!') exit() cell = get_lattice(inp=inp) # surpose the cell is orthogonal self.cell = np.array(cell) for nf in range(nl): l = lines[nf].split() self.energy_nw.append(float(l[3]) * 27.211396) ### a.u. to eV fg = open('GEOMETRY.xyz', 'r') lines = fg.readlines() fg.close() self.natom = len(lines) - 2 for na in range(2, self.natom + 2): self.atom_name.append(lines[na].split()[0]) ft = open('TRAJECTORY', 'r') lines = ft.readlines() ft.close() if self.traj: his = TrajectoryWriter(self.structure + '.traj', mode='w') ii = 0 for nf in range(nl): x = [] for na in range(self.natom): l = lines[nf * self.natom + na].split() x.append([ float(l[1]) * 0.52917721067, float(l[2]) * 0.52917721067, float(l[3]) * 0.52917721067 ]) xs.append(x) if self.traj: if nf in self.indexs: A = Atoms(self.atom_name, x, cell=self.cell, pbc=[True, True, True]) his.write(atoms=A) if self.traj: his.close() return xs
def SinglePointEnergies(traj, label='aimd', frame=50, cpu=4): his = TrajectoryWriter(label + '.traj', mode='w') images = Trajectory(traj) tframe = len(images) E = [] if tframe > frame: ind_ = np.linspace(0, tframe, num=frame, dtype=np.int32) for i in range(tframe): if tframe > frame: if i in ind_: atoms = images[i] else: continue else: atoms = images[i] e_ = atoms.get_potential_energy() atoms_ = single_point(atoms, cpu=cpu) e = atoms_.get_potential_energy() his.write(atoms=atoms_) print('- Energies from MLP: %9.5f DFT: %9.5f' % (e_, e)) E.append(e) his.close() images = None return E
def decompostion(gen='rdx.gen', ncpu=12): ''' decompostion energy of N-NO2 ''' traj = TrajectoryWriter('stretch.traj', mode='w') ncfg = 20 A = read(gen) s = stretch(A, shrink=0.8, enlarge=2.6, fix_end=3, move_end=18, move_atoms=[18, 19, 20], nconfig=ncfg) for i in range(ncfg): atoms = s.move(i) write_nwchem_inp(atoms, struc=gen.split('.')[0], task='dft gradient', xc='b3lyp', basis='6-311G*') system('mpirun -n %d nwchem inp-nw > nw.out' % (ncpu)) e, grad_ = get_nw_gradient(out='nw.out') system('cp nw.out nw_%s.out' % str(i)) system('rm QMD-*') print('- energy(NWchem):', e) calc = SinglePointCalculator(atoms, energy=e) atoms.set_calculator(calc) traj.write(atoms=atoms) traj.close()
def amp_data(lab='amp', dft='siesta', dic='/home/gfeng/siesta/train/ethane', batch=800,sort=False): ''' prepare data for AMP ''' md = MDtoData(dft=dft,direc=dic, batch=batch,sort=sort) if len(md.energy_nw)<batch: batch = len(md.energy_nw) box = [md.cell[0][0],md.cell[1][1],md.cell[2][2]] his = TrajectoryWriter(lab+'.traj',mode='w') for i in range(batch): md.energy_nw[i] x = np.mod(md.x[i],box) A = Atoms(md.atom_name,x,cell=md.cell,pbc=[True,True,True]) e = float(md.energy_nw[i]) calc = SinglePointCalculator(A,energy=e, free_energy=float(md.max_e), forces=md.forces[i]) A.set_calculator(calc) his.write(atoms=A) del A his.close()
def get_traj(self): self.uc= np.linalg.inv(self.cell) images = [] his = TrajectoryWriter(self.structure+'.traj',mode='w') indexs = np.array(self.indexs) ind = indexs.argsort() batch_ = self.batch if self.nframe>self.batch else self.nframe for i in range(batch_): ii = ind[i] xf = np.dot(self.x[ii],self.uc) xf = np.mod(xf,1.0) self.x[ii] = np.dot(xf,self.cell) if self.qs is None: c = None else: c = self.qs[i] A = Atoms(self.atom_name,self.x[ii], charges=c, cell=self.cells[ii],pbc=[True,True,True]) if self.checkMol: A = press_mol(A) calc = SinglePointCalculator(A,energy=float(self.energy_nw[ii])) A.set_calculator(calc) his.write(atoms=A) images.append(A) his.close() return images
class Snapshot(MCObserver): """ Store a snapshot in a trajectory file :param str trajfile: Filename of the trajectory file :param Atoms atoms: Instance of the atoms objected modofied by the MC object """ def __init__(self, trajfile="default.traj", atoms=None): super(Snapshot, self).__init__() self.name = "Snapshot" if not trajfile.endswith(".traj"): msg = "This object stores all images in a trajectory file. " msg += "File extension should be .traj" raise ValueError(msg) if atoms is None: raise ValueError("No atoms object given!") self.atoms = atoms self.traj = TrajectoryWriter(trajfile, mode="a") self.fname = trajfile def __call__(self, system_changes): self.traj.write(self.atoms)
def merge(t1='O7H20C2.traj', t2='O7H20C2opt.traj'): his = TrajectoryWriter('merged.traj', mode='w') trajs = [t1, t2] for traj in trajs: images = Trajectory(traj) for atoms in images: his.write(atoms=atoms) his.close()
def zmat_relax(self,atoms,nbin=10,relax_step=None, zmat_variable=None,zvlo=None,zvhi=None, traj='zmat.traj',relaxlog = ''): zmatrix = np.array(self.get_zmatrix(atoms)) initz = np.array(self.InitZmat) # target relax_step_ = nbin if relax_step is None else relax_step if not zmat_variable is None: i,j = zmat_variable initz = zmatrix.copy() initz[i][j] = initz[i][j] + zvhi # target zmatrix[i][j] = zmatrix[i][j] + zvlo # starting point: current configration relaxlog += ' ---------------------------\n' relaxlog += ' %d-%d-%d-%d (%d,%d) \n' %(self.zmat_id[i],self.zmat_index[i][0], self.zmat_index[i][1],self.zmat_index[i][2],i,j) relaxlog += ' ---------------------------\n' relaxlog += 'varied from: %8.4f to %8.4f,\n' %(zmatrix[i][j],initz[i][j]) else: relaxlog += 'relax the structure to %d/%d of the initial value ...\n' %(relax_step_,nbin) dz_ = (initz - zmatrix) dz_ = np.where(dz_>180.0,dz_-360.0,dz_) dz = np.where(dz_<-180.0,dz_+360.0,dz_) dz = dz/nbin his = TrajectoryWriter(traj,mode='w') images = [] nb_ = 0 for i_ in range(relax_step_): zmat_ = zmatrix+dz*(i_+1) zmat_ = np.where(zmat_>180.0,zmat_-360.0,zmat_) # scale to a reasonalbale range zmat_ = np.where(zmat_==-180.0,zmat_+0.000001,zmat_) zmat_ = np.where(zmat_==180.0,zmat_-0.000001,zmat_) zmat_ = np.where(zmat_<-180.0,zmat_+360.0,zmat_) # scale to a reasonalbale range atoms = self.zmat_to_cartation(atoms,zmat_) self.ir.calculate(atoms) calc = SinglePointCalculator(atoms,energy=self.ir.E) atoms.set_calculator(calc) his.write(atoms=atoms) images.append(atoms) bonds = getBonds(self.natom,self.ir.r,self.rmax*self.ir.re,self.ir.bo0) newbond,nbd = self.checkBond(bonds) if newbond: iatom,jatom = nbd if nb_ == 0: nbd_ = nbd r_ = self.ir.r[iatom][jatom] else: if nbd==nbd_: if self.ir.r[iatom][jatom]<r_: relaxlog += 'stop at %d/%d because new bond formed ...\n' %(i_,nbin) break r_ = self.ir.r[iatom][jatom] else: relaxlog += 'stop at %d/%d because new bond formed ...\n' %(i_,nbin) break nb_ += 1 his.close() return images,relaxlog
def sel(traj='md.traj',m=3): newt= traj.replace('.traj','_.traj') images = Trajectory(traj) his = TrajectoryWriter(newt,mode='w') images = Trajectory(traj) for i,atoms in enumerate(images): if i%m==0: his.write(atoms=atoms) his.close()
def sortraj(traj='siesta.traj'): newt = traj[:-5] + '_.traj' images = Trajectory(traj) his = TrajectoryWriter(newt, mode='w') images = Trajectory(traj) for i in range(50): atoms = images[i] his.write(atoms=atoms) his.close()
def readposcars(poscars,energies='goodStructures'): ''' read POSCARS generated by USPEX''' f = open(poscars,'r') lines = f.readlines() f.close() f = open(energies,'r') linee = f.readlines() f.close() e = [] for i,le in enumerate(linee): if i>1: e.append(float(le.split()[-4])) l = lines[6].split() natom = 0 for i in l: natom += int(i) nstru = len(lines)/(natom+8) traj = TrajectoryWriter('strucs.traj',mode='w') for i in range(nstru): nl = i*(natom+8) cl1 = lines[nl+2].split() cl2 = lines[nl+3].split() cl3 = lines[nl+4].split() cell = [[float(cl1[0]),float(cl1[1]),float(cl1[2])], [float(cl2[0]),float(cl2[1]),float(cl2[2])], [float(cl3[0]),float(cl3[1]),float(cl3[2])]] cell = np.array(cell) anl = lines[nl+5].split() nsl = lines[nl+6].split() atom_name = [] for i_,sp in enumerate(anl): atom_name.extend([sp]*int(nsl[i_])) xf = [] for na in range(natom): xl = lines[nl+8+na].split() xf.append([float(xl[0]),float(xl[1]),float(xl[2])]) xf = np.array(xf) x = np.dot(xf,cell) A = Atoms(atom_name,x,cell=cell,pbc=[True,True,True]) calc = SinglePointCalculator(A,energy=e[i]) # print(e[i]) A.set_calculator(calc) traj.write(atoms=A) traj.close()
def col(traj='siesta.traj', start=0, end=20): newt = traj.replace('.traj', '_.traj') images = Trajectory(traj) his = TrajectoryWriter(newt, mode='w') images = Trajectory(traj) for i in range(start, end): atoms = images[i] his.write(atoms=atoms) his.close()
def stretch(self, pairs, nbin=20, scale=1.2, wtraj=False): atoms = self.ir.atoms self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, scale * self.ir.re) images = [] if wtraj: his = TrajectoryWriter('stretch.traj', mode='w') for pair in pairs: i, j = pair ToBeMove = [] ToBeMove = getAtomsToMove(i, j, ToBeMove, neighbors) bin_ = (self.ir.r_cuta[i][j] - self.ir.re[i][j] * self.rtole) / nbin moveDirection = self.ir.vr[j][i] / self.ir.r[i][j] for n in range(nbin): atoms_ = atoms.copy() moveV = atoms.positions[i] + moveDirection * ( self.ir.re[i][j] * self.rtole + bin_ * n) - atoms.positions[j] # print(self.ir.re[i][j]*self.rtole+bin_*n) for m in ToBeMove: # sPos = atoms.positions[i] + self.ir.re[i][m]*self.rtole*moveDirection newPos = atoms.positions[m] + moveV r = np.sqrt(np.sum(np.square(newPos - atoms.positions[i]))) atoms_.positions[m] = newPos self.ir.calculate(atoms_) i_ = np.where( np.logical_and( self.ir.r < self.ir.re[i][j] * self.rtole - bin_, self.ir.r > 0.0001)) n = len(i_[0]) try: assert n == 0, 'Atoms too closed!' except: print('Atoms too closed.') break calc = SinglePointCalculator(atoms_, energy=self.ir.E) atoms_.set_calculator(calc) images.append(atoms_) if wtraj: his.write(atoms=atoms_) if wtraj: his.close() return images
def LearningResultAngel(ffield='ffield.json', nn='T', gen='poscar.gen', traj='C2H4-1.traj'): images = Trajectory(traj) traj_ = TrajectoryWriter(traj[:-5] + '_.traj', mode='w') atoms = images[0] nn_ = True if nn == 'T' else False ir = IRFF_NP(atoms=atoms, libfile=ffield, rcut=None, nn=nn_) natom = ir.natom Empnn, Esiesta = [], [] eb, eb_ = [], [] # images_= [] # for _ in range(0,50): eang_ = [] for _, atoms in enumerate(images): # atoms = images[_] ir.calculate(atoms) Empnn.append(ir.E) Esiesta.append(atoms.get_potential_energy()) atoms_ = atoms.copy() atoms_.set_initial_charges(charges=ir.q) calc = SinglePointCalculator(atoms_, energy=ir.E) atoms_.set_calculator(calc) traj_.write(atoms=atoms_) # print(ir.Eang) eang_.append(ir.Eang) traj_.close() fig, ax = plt.subplots() plt.plot(eang_, label=r'$E_{Angle}$', color='blue', linewidth=2, linestyle='-.') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('Eang-%s.eps' % traj[:-4]) # plt.show() plt.close()
def pes(self,i,atoms,neighbor=None,nbin=[5],scandr=[0.2],traj=None): images = [] r = {} if neighbor is None: neighbor = self.neighbors[i] for j_ in neighbor: r[j_] = self.ir.r[i][j_] images = self.scan_pes(i,0,neighbor,atoms,images,r,nbin=nbin,dr=scandr) if not traj is None: his = TrajectoryWriter(traj,mode='w') for atoms in images: his.write(atoms=atoms) his.close() return images
def collect(traj='siesta.traj', start=0, end=20): newt = traj[:-5] + '_.traj' # images = Trajectory(traj) his = TrajectoryWriter(newt, mode='w') cdir = getcwd() trajs = listdir(cdir) for traj in trajs: if traj.find('.traj') > 0 and traj != 'siesta_.traj': print('- reading file %s ...' % traj) images = Trajectory(traj) for i in range(start, end): atoms = images[i] his.write(atoms=atoms) his.close()
def learning_result(ffield='ffield.json', nn='T', gen='poscar.gen', traj='C2H4.traj'): images = Trajectory(traj) traj_ = TrajectoryWriter(traj[:-5] + '_.traj', mode='w') atoms = images[0] nn_ = True if nn == 'T' else False ir = IRFF_NP(atoms=atoms, libfile=ffield, rcut=None, nn=nn_) natom = ir.natom Empnn, Esiesta = [], [] eb, eb_ = [], [] # images_= [] # for _ in range(10,11): for atoms in images: ir.calculate(atoms) Empnn.append(ir.E) Esiesta.append(atoms.get_potential_energy()) atoms_ = atoms.copy() atoms_.set_initial_charges(charges=ir.q) calc = SinglePointCalculator(atoms_, energy=ir.E) atoms_.set_calculator(calc) traj_.write(atoms=atoms_) traj_.close() fig, ax = plt.subplots() plt.plot(Empnn, label=r'$E_{MPNN}$', color='blue', linewidth=2, linestyle='-.') plt.plot(Esiesta, label=r'$E_{SIESTA}$', color='r', linewidth=2, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('result-%s.pdf' % traj[:-4]) plt.show() plt.close()