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 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
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 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 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 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 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()
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 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 rotate(self,atms=None,axis=None,axis_vector=None,o=None,rang=20.0, nbin=10,traj=None,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 not traj is None: his = TrajectoryWriter(traj,mode='w') 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 for i in range(nbin+1): 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.141593/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 not traj is None: his.write(atoms=atoms_) a_ += da if not traj is None: 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 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 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 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()
def xyztotraj(fxyz, gen='poscar.gen', mode='w'): A = read(gen) atom_name, positions, velocities, frames = reaxyz(fxyz) e, p, t = get_dftb_energy(out='dftb.out') cell = A.get_cell() # box = [cell[0][0],cell[1][1],cell[2][2]] his = TrajectoryWriter('dftb.traj', mode=mode) for i, p_ in enumerate(positions): # pos = np.mod(positions[i],box) # aplling simple pbc conditions A = Atoms(atom_name, positions[i], cell=cell, pbc=[True, True, True]) # print(i,len(e),len(positions),e[frames[i]]) calc = SinglePointCalculator(A, energy=e[frames[i]]) A.set_calculator(calc) A.set_velocities(velocities[i]) his.write(atoms=A) del A his.close() return e[frames], p[frames], t[frames]
def swing(self, ang, st=60.0, ed=180.0, nbin=50, scale=1.2, wtraj=False): da = (ed - st) / nbin i, j, k = ang 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('swing.traj', mode='w') vij = atoms.positions[i] - atoms.positions[j] vjk = atoms.positions[k] - atoms.positions[j] r = self.ir.r[j][k] ujk = vjk / r ui = vij / self.ir.r[i][j] uk = np.cross(ui, ujk) rk = np.sqrt(np.sum(uk * uk)) if rk < 0.0000001: uk = np.array([1.0, 0.0, 0.0]) else: uk = uk / rk uj = np.cross(uk, ui) a_ = st while a_ < ed: atoms_ = atoms.copy() a = a_ * 3.14159 / 180.0 p = r * np.cos(a) * ui + r * np.sin(a) * uj atoms_.positions[k] = atoms_.positions[j] + 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 if wtraj: his.close() return images
def LammpsHistory(traj='ase.lammpstrj', frame=0, atomType=['C', 'H', 'O', 'N']): fl = open(traj, 'r') lines = fl.readlines() nl = len(lines) fl.close() natom = int(lines[3]) his = TrajectoryWriter(traj.split('.')[0] + '.traj', mode='w') n = 0 block = natom + 9 atomName = [' ' for i in range(natom)] cell = np.zeros([3, 3]) line = lines[block * frame + 5].split() cell[0][0] = float(line[1]) - float(line[0]) line = lines[block * frame + 6].split() cell[1][1] = float(line[1]) - float(line[0]) line = lines[block * frame + 7].split() cell[2][2] = float(line[1]) - float(line[0]) positions = np.zeros([natom, 3]) while n <= nl: for i in range(natom): n = block * frame + i + 9 line = lines[n].split() id_ = int(line[0]) - 1 atomName[id_] = atomType[int(line[1]) - 1] positions[id_][0] = float(line[2]) positions[id_][1] = float(line[3]) positions[id_][2] = float(line[4]) atoms = Atoms(atomName, positions, cell=cell, pbc=[True, True, True]) his.write(atoms=atoms) frame += 1 n = block * frame + 9 his.close() lines = None return atoms
def xyztotraj(fxyz,checkMol=False,mode='w'): atom_name,positions,e = reaxyz(fxyz) cell = get_lattice() u = np.linalg.inv(cell) his = TrajectoryWriter('gulp.traj',mode=mode) for i,e_ in enumerate(e): pos_ = np.dot(positions[i],u) posf = np.mod(pos_,1.0) # aplling simple pbc conditions pos = np.dot(posf,cell) A = Atoms(atom_name,pos,cell=cell,pbc=[True,True,True]) if checkMol: A = press_mol(A) calc = SinglePointCalculator(A,energy=e[i]) A.set_calculator(calc) his.write(atoms=A) del A his.close()
def to_traj(): traj_init = 'structures_initial3.traj' traj_final = 'structures_final3.traj' if os.path.exists(traj_init): os.remove(traj_init) if os.path.exists(traj_final): os.remove(traj_final) init = TrajectoryWriter(traj_init) final = TrajectoryWriter(traj_final) db_server = connect(mysql_url) groups = set() for row in db_server.select(project=project): gr = row.get('group', None) if gr is not None: groups.add(gr) for gr in groups: print(gr) try: atoms_init = list( db_server.select(group=gr, type='initial', project=project))[0].toatoms() atoms_final = list( db_server.select(group=gr, type=relax_type, project=project))[0].toatoms() init.write(atoms_init) final.write(atoms_final) except (KeyError, IndexError): pass init.close() final.close()
def SinglePointEnergies(traj, label='aimd', xcf='VDW', xca='DRSLL', basistype='DZP', EngTole=0.0000001, frame=50, cpu=4, dE=0.2, d2E=0.1, select=False): ''' get single point energy and labeling data ''' images = Trajectory(traj) tframe = len(images) E, E_, dEs = [], [], [] if tframe > frame: if frame > 1: ind_ = list(np.linspace(0, tframe - 1, num=frame, dtype=np.int32)) else: ind_ = [tframe - 1] else: ind_ = [i for i in range(tframe)] if len(ind_) > 1 and 0 in ind_: ind_.pop(0) his = TrajectoryWriter(label + '.traj', mode='w') # print(frame,ind_) energies = [] d2Es = [] dE_ = 0.0 d2E_ = 0.0 for i, atoms in enumerate(images): energy = atoms.get_potential_energy() if i > 0: if i < (tframe - 1): deltEl = energy - energies[-1] deltEr = images[i + 1].get_potential_energy() - energy dE_ = abs(deltEl) d2E_ = abs(deltEr - deltEl) else: deltEl = energy - energies[-1] dE_ = abs(deltEl) energies.append(energy) dEs.append(dE_) d2Es.append(d2E_) if select: if dE_ > dE or d2E_ > d2E: if i not in ind_: ind_.append(i) ide = np.argmax(dEs) id2e = np.argmax(d2Es) if (ide not in ind_) and (ide + 1 not in ind_) and (ide - 1 not in ind_): ind_.append(ide) if id2e not in ind_ and (id2e + 1 not in ind_) and (id2e - 1 not in ind_): ind_.append(id2e) ind_.sort() for i in ind_: atoms = images[i] e_ = atoms.get_potential_energy() dE_ = dEs[i] d2E_ = d2Es[i] atoms_ = single_point(atoms, xcf=xcf, xca=xca, basistype=basistype, cpu=cpu) e = atoms_.get_potential_energy() E.append(e) E_.append(e_) diff_ = abs(e - e_) print( ' * %d Energies from MLP: %9.5f DFT: %9.5f Diff: %6.6f dE: %5.4f d2E: %5.4f' % (i, e_, e, diff_, dE_, d2E_)) with open('SinglePointEnergies.log', 'a') as fs: fs.write( '%d MLP: %9.5f DFT: %9.5f Diff: %6.6f dE: %5.4f d2E: %5.4f\n' % (i, e_, e, diff_, dE_, d2E_)) if diff_ > EngTole: # or i==ind_[-1] his.write(atoms=atoms_) his.close() images = None dEmax = dEs[ide] d2Emax = d2Es[id2e] return E, E_, dEmax, d2Emax
def stretch(self, pair, atoms=None, nbin=20, st=0.7, ed=1.3, scale=1.25, traj=None, ToBeMoved=None): if atoms is None: 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 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 bin_ = (self.ir.re[i][j] * ed - self.ir.re[i][j] * st) / nbin moveDirection = self.ir.vr[j][i] / self.ir.r[i][j] if ring: return None for n in range(nbin): atoms_ = atoms.copy() moveV = atoms.positions[i] + moveDirection * ( self.ir.re[i][j] * st + 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 not traj is None: his.write(atoms=atoms_) if not traj is None: his.close() return images
command = "mkdir "+path os.system(command) writer = TrajectoryWriter(path+'/initial.traj','a') latprm = read(filename).get_cell_lengths_and_angles() for i in range(nstep+1): atoms = read(filename) scaled_pos = atoms.get_scaled_positions() sym = atoms.get_chemical_symbols() for j in range(len(sym)): if sym[j]!='C': scaled_pos[j][0] = scaled_pos[j][0]+i*index[0]/nstep scaled_pos[j][1] = scaled_pos[j][1]+i*index[1]/nstep scaled_pos[j][2] = scaled_pos[j][2]+i*index[2]/nstep atoms.set_scaled_positions(scaled_pos) writer.write(atoms) command = "mkdir "+path+"/"+str(i) os.system(command) write(path+'/'+str(i)+'/str.cif',atoms) command = "cp job.sh relax.py "+path+"/"+str(i)+"/." os.system(command) # Edit job.sh job name newjobname = path+'_'+str(i) command = 'sed -i \'s/jobname/'+newjobname+'/g\' ./'+path+'/'+str(i)+'/job.sh ' os.system(command) writer.close()
def prep_data(label=None,direcs=None,split_batch=100,frame=50,max_batch=50,dft='siesta'): ''' To sort data must have same atom number and atom types images: contains all atom image in all directions frame : collect this number to images split_batch: split images evergy split_batch In the end, all data stored in label-i.traj file: collect number (frame=5) in energy directory, split the frame to traj file evergy (split_batch=1000) ''' images = [] for key in direcs: direc=direcs[key] if direc.endswith('.traj'): try: images_ = Trajectory(direc) except: images_ = [] else: d = MDtoData(structure=key,dft=dft,direc=direc,batch=frame) images_ = d.get_images() d.close() # print('- the number of frames in dir %s:' %key,len(images_)) if len(images_)>frame: images.extend(images_[0:frame]) else: images.extend(images_) # traj = TrajectoryWriter('all.traj',mode='w') # for atoms in images: # traj.write(atoms=atoms) nframe = len(images) # get batch size to split if nframe>split_batch : nb_ = float(int(nframe/split_batch)) spb_ = int(ceil(nframe/nb_)) if nb_>max_batch: nb_ = max_batch spb_= int(ceil(nframe/max_batch)) else: nb_ = 1 spb_ = split_batch n = int(nb_) if n*split_batch<nframe: pool = np.array(nframe) ind_ = np.linspace(0,nframe-1,num=n*split_batch,dtype=np.int32) images = [images[_] for _ in ind_] if not exists('data'): mkdir('data') trajs = {} for i in range(n): sf = i*split_batch ef = (i+1)*split_batch if sf<nframe: if ef>nframe: ef = nframe # print(i,sf,ef) images_ = images[sf:ef] tn = label+'-'+str(i) tn_ = 'data/'+tn +'.traj' traj = TrajectoryWriter(tn_,mode='w') for atoms in images_: traj.write(atoms=atoms) traj.close() trajs[tn] = tn_ return trajs
def dh(traj='siesta.traj', batch_size=1, nn=True, frame=7): ffield = 'ffield.json' if nn else 'ffield' images = Trajectory(traj) atoms = images[frame] his = TrajectoryWriter('tmp.traj', mode='w') his.write(atoms=atoms) his.close() from irff.irff import IRFF ir = IRFF(atoms=atoms, libfile=ffield, nn=nn, bo_layer=[9, 2]) ir.get_potential_energy(atoms) from irff.reax import ReaxFF rn = ReaxFF(libfile=ffield, direcs={'tmp': 'tmp.traj'}, dft='siesta', opt=[], optword='nocoul', batch_size=batch_size, atomic=True, clip_op=False, InitCheck=False, nn=nn, pkl=False, to_train=False) molecules = rn.initialize() rn.session(learning_rate=1.0e-10, method='AdamOptimizer') mol = 'tmp' hblab = rn.lk.hblab hbs = [] for hb in ir.hbs: hbs.append(list(hb)) eh_ = rn.get_value(rn.EHB) # eh = ir.ehb.numpy() rhb_ = rn.get_value(rn.rhb) # rhb = ir.rhb.numpy() frhb_ = rn.get_value(rn.frhb) # frhb = ir.frhb.numpy() sin4_ = rn.get_value(rn.sin4) # sin4 = ir.sin4.numpy() # exphb1_= rn.get_value(rn.exphb1) # exphb2_= rn.get_value(rn.exphb2) # exphb1 = ir.exphb1.numpy() # exphb2 = ir.exphb2.numpy() # hbsum_ = rn.get_value(rn.hbsum) # hbsum = ir.hbsum.numpy() for hb in rn.hbs: for a_ in range(rn.nhb[hb]): a = hblab[hb][a_][1:] i, j, k = a if a in hbs: ai = hbs.index(a) # if eh_[hb][a_][0]<-0.000001: print( '- %2d%s-%2d%s-%2d%s:' % (i, ir.atom_name[i], j, ir.atom_name[j], k, ir.atom_name[k]), 'ehb: %10.8f' % (eh_[hb][a_][0]), 'rhb: %10.8f' % (rhb_[hb][a_][0]), 'frhb: %10.8f' % (frhb_[hb][a_][0]), 'sin4: %10.8f' % (sin4_[hb][a_][0]))
def dt(traj='siesta.traj', batch_size=1, nn=True, frame=0): ffield = 'ffield.json' if nn else 'ffield' images = Trajectory(traj) atoms = images[frame] his = TrajectoryWriter('tmp.traj', mode='w') his.write(atoms=atoms) his.close() from irff.irff import IRFF ir = IRFF(atoms=atoms, libfile=ffield, nn=nn) ir.get_potential_energy(atoms) eb = ir.Ebond.numpy() et = ir.etor.numpy() ef = ir.efcon.numpy() f10 = ir.f_10.numpy() f11 = ir.f_11.numpy() sijk = ir.s_ijk.numpy() sjkl = ir.s_jkl.numpy() f = ir.fijkl.numpy() v1 = ir.v1.numpy() v2 = ir.v2.numpy() v3 = ir.v3.numpy() expv2 = ir.expv2.numpy() boij = ir.botij.numpy() bojk = ir.botjk.numpy() bokl = ir.botkl.numpy() cosw = ir.cos_w.numpy() cos2w = ir.cos2w.numpy() w = ir.w.numpy() Etor = ir.Etor.numpy() del IRFF from irff.reax import ReaxFF rn = ReaxFF(libfile=ffield, direcs={'tmp': 'tmp.traj'}, dft='siesta', opt=[], optword='nocoul', batch_size=batch_size, atomic=True, clip_op=False, InitCheck=False, nn=nn, bo_layer=[9, 2], pkl=False, to_train=False) molecules = rn.initialize() # rn.calculate(rn.p,rn.m) rn.session(learning_rate=3.0 - 4, method='AdamOptimizer') mol = 'tmp' torlab = rn.lk.torlab tors = [] for tor in ir.tors: tors.append(list(tor)) print(tor) eb_ = rn.get_value(rn.ebond[mol]) et_ = rn.get_value(rn.ETOR) ef_ = rn.get_value(rn.Efcon) f10_ = rn.get_value(rn.f_10) f11_ = rn.get_value(rn.f_11) sijk_ = rn.get_value(rn.s_ijk) sjkl_ = rn.get_value(rn.s_jkl) f_ = rn.get_value(rn.fijkl) boij_ = rn.get_value(rn.BOtij) bojk_ = rn.get_value(rn.BOtjk) bokl_ = rn.get_value(rn.BOtkl) v1_ = rn.get_value(rn.v1) v2_ = rn.get_value(rn.v2) v3_ = rn.get_value(rn.v3) expv2_ = rn.get_value(rn.expv2) cosw_ = rn.get_value(rn.cos_w) cos2w_ = rn.get_value(rn.cos2w) w_ = rn.get_value(rn.w) for tor in rn.tors: for a_ in range(rn.ntor[tor]): a = torlab[tor][a_][1:] if a not in tors: a.reverse() i, j, k, l = a if a in tors: ai = tors.index(a) # if abs(et_[tor][a_][0]-et[ai])>0.0001: print( '- %2d%s-%2d%s-%2d%s-%2d%s:' % (i, ir.atom_name[i], j, ir.atom_name[j], k, ir.atom_name[k], l, ir.atom_name[l]), 'etor: %10.8f %10.8f' % (et_[tor][a_][0], et[ai]), 'sijk: %10.8f %10.8f' % (sijk_[tor][a_][0], sijk[ai]), 'sjkl: %10.8f %10.8f' % (sjkl_[tor][a_][0], sjkl[ai]), 'boij: %10.8f %10.8f' % (boij_[tor][a_][0], boij[ai]), 'bojk: %10.8f %10.8f' % (bojk_[tor][a_][0], bojk[ai]), 'bokl: %10.8f %10.8f' % (bokl_[tor][a_][0], bokl[ai]), 'fijkl: %10.8f %10.8f' % (f_[tor][a_][0], f[ai]), 'v1: %10.8f %10.8f' % (v1_[tor][a_][0], v1[ai]), 'v2: %10.8f %10.8f' % (v2_[tor][a_][0], v2[ai]), 'v3: %10.8f %10.8f' % (v3_[tor][a_][0], v3[ai]), 'expv2: %10.8f %10.8f' % (expv2_[tor][a_][0], expv2[ai]), 'ptor1: %10.8f %10.8f' % (rn.p_['tor1_' + tor], ir.P['tor1'][ai]), # 'cosw: %10.8f %10.8f' %(cosw_[tor][a_][0],cosw[ai]), # 'cos2w: %10.8f %10.8f' %(cos2w_[tor][a_][0],cos2w[ai]), # 'v1: %10.8f %10.8f' %(0.5*rn.p_['V1_'+tor]*(1.0+cosw_[tor][a_][0]), # 0.5*ir.P['V1'][ai]*(1.0+cosw[ai])), # 'w: %10.8f %10.8f' %(w_[tor][a_][0],w[ai]), # 'efcon: %10.8f %10.8f' %(ef_[tor][a_][0],ef[ai]), # 'f_10: %10.8f %10.8f' %(f10_[tor][a_][0],f10[ai]), # 'f_11: %10.8f %10.8f' %(f11_[tor][a_][0],f11[ai]), ) Etor_ = rn.get_value(rn.etor) print('\n- torsion energy:', Etor, Etor_[mol][0], end='\n') print('\n- Bond energy:', eb, eb_, end='\n') del ReaxFF
def da(traj='siesta.traj', batch_size=1, nn=False, frame=0): ffield = 'ffield.json' if nn else 'ffield' images = Trajectory(traj) atoms = images[frame] his = TrajectoryWriter('tmp.traj', mode='w') his.write(atoms=atoms) his.close() ir = IRFF(atoms=atoms, libfile=ffield, nn=False, bo_layer=[8, 4]) ir.get_potential_energy(atoms) rn = ReaxFF(libfile=ffield, direcs={'tmp': 'tmp.traj'}, dft='siesta', opt=[], optword='nocoul', batch_size=batch_size, atomic=True, clip_op=False, InitCheck=False, nn=nn, pkl=False, to_train=False) molecules = rn.initialize() rn.session(learning_rate=1.0e-10, method='AdamOptimizer') mol = 'tmp' anglab = rn.lk.anglab angs = [] for ang in ir.angs: angs.append(list(ang)) ea_ = rn.get_value(rn.EANG) ea = ir.eang.numpy() f7_ = rn.get_value(rn.f_7) f7 = ir.f_7.numpy() f8_ = rn.get_value(rn.f_8) f8 = ir.f_8.numpy() expang_ = rn.get_value(rn.expang) expang = ir.expang.numpy() expaij_ = rn.get_value(rn.expaij) expaij = ir.expaij.numpy() expajk_ = rn.get_value(rn.expajk) expajk = ir.expajk.numpy() theta_ = rn.get_value(rn.theta) theta = ir.theta.numpy() theta0_ = rn.get_value(rn.theta0) theta0 = ir.thet0.numpy() sbo3_ = rn.get_value(rn.SBO3) sbo3 = ir.SBO3.numpy() fa = open('ang.txt', 'w') for ang in rn.angs: for a_ in range(rn.nang[ang]): a = anglab[ang][a_][1:] if a not in angs: a.reverse() i, j, k = a if a in angs: ai = angs.index(a) print('- %2d%s-%2d%s-%2d%s:' % (i, ir.atom_name[i], j, ir.atom_name[j], k, ir.atom_name[k]), 'eang: %10.8f %10.8f' % (ea_[ang][a_][0], ea[ai]), 'f7: %10.8f %10.8f' % (f7_[ang][a_][0], f7[ai]), 'f8: %10.8f %10.8f' % (f8_[ang][a_][0], f8[ai]), 'expang: %10.8f %10.8f' % (expang_[ang][a_][0], expang[ai]), 'expaij: %10.8f %10.8f' % (expaij_[ang][a_][0], expaij[ai]), 'expajk: %10.8f %10.8f' % (expajk_[ang][a_][0], expajk[ai]), 'theta: %10.8f %10.8f' % (theta_[ang][a_][0], theta[ai]), 'sbo3: %10.8f %10.8f' % (sbo3_[ang][a_][0], sbo3[ai]), 'theta0: %10.8f %10.8f' % (theta0_[ang][a_][0], theta0[ai]), file=fa) else: print( '- %2d%s-%2d%s-%2d%s:' % (i, ir.atom_name[i], j, ir.atom_name[j], k, ir.atom_name[k]), 'eang: %10.8f' % (ea_[ang][a_][0]), 'f7: %10.8f' % (f7_[ang][a_][0]), 'f8: %10.8f' % (f8_[ang][a_][0]), 'expang: %10.8f' % (expang_[ang][a_][0]), 'expang: %10.8f' % (expang_[ang][a_][0]), 'expaij: %10.8f' % (expaij_[ang][a_][0]), 'expajk: %10.8f' % (expajk_[ang][a_][0]), 'theta: %10.8f' % (theta_[ang][a_][0]), 'sbo3: %10.8f' % (sbo3_[ang][a_][0]), 'theta0: %10.8f' % (theta0_[ang][a_][0])) fa.close() print('\n- angel energy:', ir.Eang.numpy(), rn.eang[mol].numpy()[0], end='\n')