def plev(): atoms = Atoms('H2', positions=[(0, 0, 0), (r, 0, 0)], cell=[10.0, 10.0, 10.0], pbc=[1, 1, 1]) ao = AtomDance(atoms) pairs = [0, 1] images = ao.stretch(pairs, nbin=50, st=0.6, ed=5.0, scale=1.25, traj='evdw.traj') ao.close() # view(images) ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) ev_, r_ = [], [] for atoms in images: ir.calculate(atoms) r_.append(ir.r[0][1]) ev_.append(ir.Evdw) fig, ax = plt.subplots() plt.plot(r_, ev_, label=r'$Evdw$ VS $r$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('Evdw.eps') plt.close()
def bde(ffield='ffield.json', nn='T', gen='poscar.gen', traj='C2H4.traj'): images = Trajectory(traj) 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_ = [], [] for atoms in images: ir.calculate(atoms) Empnn.append(ir.E) Esiesta.append(atoms.get_potential_energy()) # eb.append(ir.ebond[i][j]) fig, ax = plt.subplots() plt.plot(Empnn[0:14], label=r'$E_{MPNN}$', color='blue', linewidth=2, linestyle='-.') plt.plot(Esiesta[0:14], label=r'$E_{SIESTA}$', color='r', linewidth=2, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('Ecompare.pdf') plt.show() plt.close()
def plot_bondorder(): #atoms = structure('HMX') atoms = read('poscar.gen', index=-1) # atoms = atoms*[2,2,2] # view(atoms) # atoms = read('md.traj',index=-1) atom_name = atoms.get_chemical_symbols() ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) ir.calculate_Delta(atoms) fig = plt.figure() # set figure information # plt.set_title("Bond-Order") plt.xlabel("Atom ID") plt.ylabel("Atom ID") plt.imshow(ir.bop, cmap='jet') # atom conection matrix plt.colorbar() # plt.grid() plt.savefig('bop.eps') plt.close() fig = plt.figure() plt.xlabel("Atom ID") plt.ylabel("Atom ID") plt.imshow(ir.bo0, cmap='jet') # atom conection matrix plt.colorbar() # plt.grid() plt.savefig('bo.eps') plt.close()
def pltf(atomi, atomj, gen): atoms = read(gen) ao = AtomOP(atoms) # pairs = [[1,2],[13,7],[5,26]] pairs = [[0, 1]] images = ao.stretch(pairs, nbin=50, wtraj=True) ao.close() # view(images) ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) e_, r_ = [], [] b_, f_ = [], [] for atoms in images: ir.calculate(atoms) # positions = atoms.get_positions() # r = np.sqrt(np.sum(np.square(positions[1]-positions[0]))) r_.append(ir.r[atomi][atomj]) e_.append(atoms.get_potential_energy()) b_.append(ir.H[0][atomi][atomj]) f_.append(ir.F[-1][atomi][atomj]) fig, ax = plt.subplots() plt.plot(r_, f_, label=r'$f_{NN}$ vs $BO^t=0$', color='blue', linewidth=2, linestyle='-') # plt.plot(b_,f_,label=r'$f_{NN}$ vs $BO^{t=0}$', color='blue', # linewidth=2, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('Estretch.svg') # plt.show() plt.close()
def ple(traj='md.traj'): images = Trajectory(traj) ir = IRFF_NP(atoms=images[0], libfile='ffield.json', rcut=None, nn=True) e, e_, r_ = [], [], [] for atoms in images: # for i in range(62): # atoms = images[i] e.append(atoms.get_potential_energy()) ir.calculate(atoms) # r_.append(ir.r[atomi][atomj]) e_.append(ir.E) fig, ax = plt.subplots() plt.plot(e, label=r'$DFT$ ($SIESTA$)', color='red', markeredgewidth=1, ms=5, alpha=0.8, linewidth=2, linestyle='-') # plt.plot(e,label=r'$Potential$ $Energy$', color='red', # marker='^',markerfacecolor='none', # markeredgewidth=1, # ms=5,alpha=0.8, # linewidth=1, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('popeng.svg', transparent=True) plt.close()
def get_theta(atoms, figsize=(8, 6)): ir = IRFF_NP(atoms=atoms, libfile='ffield.json', nn=True) ir.calculate(atoms) for a, angle in enumerate(ir.angs): i, j, k = angle print( '{:3d} {:3d} {:3d} {:3d} {:6.4f} {:6.4f} Dpi: {:6.4f} SBO: {:6.4f} pbo: {:6.4f} SBO3: {:6.4f}' .format(a, i, j, k, ir.thet0[a], ir.theta[a], ir.sbo[a], ir.SBO[a], ir.pbo[a], ir.SBO3[a])) # self.thet0-self.theta
def pleo(atomi,traj='md.traj'): images = Trajectory(traj) ir = IRFF_NP(atoms=images[0], libfile='ffield.json', rcut=None, nn=True) el_,eu_,eo_,r_ = [],[],[],[] delta = [] for atoms in images: ir.calculate(atoms) # r_.append(ir.r[atomi][atomj]) eo_.append(ir.eover[atomi]) eu_.append(ir.eunder[atomi]) el_.append(ir.elone[atomi]) delta.append(ir.Delta[atomi]) print('Delta_e:',ir.Delta_e[atomi],'Delta_lp:',ir.Delta_lp[atomi], 'Delta_lpcorr:',ir.Delta_lpcorr[atomi]) fig, ax = plt.subplots() plt.plot(delta,eo_,label=r'$E_{over}$ VS $Radius$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best',edgecolor='yellowgreen') plt.savefig('Eover.pdf') plt.close() fig, ax = plt.subplots() plt.plot(delta,eo_,label=r'$E_{over}$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best',edgecolor='yellowgreen') plt.savefig('Eover.pdf') plt.close() fig, ax = plt.subplots() plt.plot(delta,eu_,label=r'$E_{under}$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best',edgecolor='yellowgreen') plt.savefig('Eunder.pdf') plt.close() fig, ax = plt.subplots() plt.plot(el_,label=r'$E_{lone}$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best',edgecolor='yellowgreen') plt.savefig('Elone.pdf') plt.close()
def __init__(self, atoms=None, poscar=None, nn=True, rtole=0.5, bondTole=1.25, botol=0.0): self.rtole = rtole self.bondTole = bondTole self.botol = botol self.BondDistrubed = [] if atoms is None: if poscar is None: atoms = read('poscar.gen') else: atoms = read(poscar) self.ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=nn) self.natom = self.ir.natom self.atom_name = self.ir.atom_name spec = self.ir.spec self.mass = atoms.get_masses() label_dic = {} for sp in self.atom_name: if sp in label_dic: label_dic[sp] += 1 else: label_dic[sp] = 1 self.label = '' for sp in spec: self.label += sp + str(label_dic[sp]) self.ir.calculate_Delta(atoms) self.InitBonds = getBonds(self.natom, self.ir.r, self.bondTole * self.ir.re, self.ir.bo0, botol=self.botol) self.neighbors = getNeighbor(self.natom, self.ir.r, self.bondTole * self.ir.re, self.ir.bo0, botol=self.botol)
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 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 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 pleb(atomi=0,atomj=1,traj='md.traj'): images = Trajectory(traj) ir = IRFF_NP(atoms=images[0], libfile='ffield.json', rcut=None, nn=True) e_,r_ = [],[] for atoms in images: ir.calculate(atoms) r_.append(ir.r[atomi][atomj]) e_.append(ir.ebond[atomi][atomj]) fig, ax = plt.subplots() plt.plot(r_,e_,label=r'$E_{Bond}$ VS $Radius$', color='blue', linewidth=2, linestyle='-') plt.legend(loc='best',edgecolor='yellowgreen') plt.savefig('Ebond.eps') plt.close()
def deb_energy(images, debframe=[], i=6, j=8, show=False): ir = IRFF_NP(atoms=images[0], libfile='ffield.json', nn=True) ir.calculate_Delta(images[0]) Eb, Ea, e = [], [], [] Ehb, Eo, Ev, Eu, El = [], [], [], [], [] Etor, Ef, Ep, Et = [], [], [], [] for i_, atoms in enumerate(images): ir.calculate(images[i_]) # print('%d Energies: ' %i_,'%12.4f ' %ir.E, 'Ebd: %8.4f' %ir.ebond[0][1],'Ebd: %8.4f' %ir.ebond[2][3] ) Eb.append(ir.Ebond) Ea.append(ir.Eang) Eo.append(ir.Eover) Ev.append(ir.Evdw) Eu.append(ir.Eunder) El.append(ir.Elone) Ep.append(ir.Epen) Et.append(ir.Etcon) Ef.append(ir.Efcon) Etor.append(ir.Etor) Ehb.append(ir.Ehb) e.append(ir.E) plot(e, Eb, Eu, Eo, El, Ea, Et, Ep, Etor, Ef, Ev, Ehb, show=show) return e
def get_mole(traj='nm-0.traj'): images = Trajectory(traj) tframe = len(images) x_ = [i for i in range(tframe)] e,e_ = [],[] mol_ = traj.split('.')[0] mol = mol_.split('-')[0] ir = IRFF_NP(atoms=images[0], libfile='ffield.json', rcut=None, nn=True,vdwnn=True) for i,atoms in enumerate(images): energy = atoms.get_potential_energy() ir.calculate(atoms) e_.append(ir.E) e.append(energy) emol = np.mean(e) - np.mean(e_) print('- recommended molecular energy for %s is :' %mol,emol) return emol
def __init__(self, atoms=None, rtole=0.5): self.rtole = rtole if atoms is None: gen_ = 'md.traj' if isfile('md.traj') else 'poscar.gen' atoms = read(gen_, index=-1) self.ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) self.natom = self.ir.natom self.atom_name = self.ir.atom_name spec = self.ir.spec label_dic = {} for sp in self.atom_name: if sp in label_dic: label_dic[sp] += 1 else: label_dic[sp] = 1 self.label = '' for sp in spec: self.label += sp + str(label_dic[sp])
def deb_vdw(images, i=0, j=1, show=False): ir = IRFF_NP(atoms=images[0], libfile='ffield.json', nn=True) ir.calculate_Delta(images[0]) Eb, Ea, e = [], [], [] Ehb, Eo, Ev, Eu, El = [], [], [], [], [] Etor, Ef, Ep, Et = [], [], [], [] for i_, atoms in enumerate(images): ir.calculate(images[i_]) # print('%d Energies: ' %i_,'%12.4f ' %ir.E, 'Ebd: %8.4f' %ir.ebond[0][1],'Ebd: %8.4f' %ir.ebond[2][3] ) Eb.append(ir.Ebond) Ea.append(ir.Eang) Eo.append(ir.Eover) Ev.append(ir.Evdw) Eu.append(ir.Eunder) El.append(ir.Elone) Ep.append(ir.Epen) Et.append(ir.Etcon) Ef.append(ir.Efcon) Etor.append(ir.Etor) Ehb.append(ir.Ehb) e.append(ir.E) emin_ = np.min(Eb) eb = np.array(Eb) - emin_ # )/emin_ vmin_ = np.min(Ev) ev = np.array(EV) - vmin_ # )/emin_ plt.figure(figsize=figsize) # plt.plot(bopsi,alpha=0.8,linewidth=2,linestyle=':',color='k',label=r'$BO_p^{\sigma}$') # plt.plot(boppi,alpha=0.8,linewidth=2,linestyle='-.',color='k',label=r'$BO_p^{\pi}$') # plt.plot(boppp,alpha=0.8,linewidth=2,linestyle='--',color='k',label=r'$BO_p^{\pi\pi}$') # plt.plot(bo0,alpha=0.8,linewidth=2,linestyle='-',color='g',label=r'$BO^{t=0}$') plt.plot(ev, alpha=0.8, linewidth=2, linestyle='-', color='y', label=r'$E_{vdw}$') plt.plot(eb, alpha=0.8, linewidth=2, linestyle='-', color='r', label=r'$E_{bond}$') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('deb_bo.pdf') if show: plt.show() plt.close() return eb, ev
def eover(i=0, j=1, ffield='ffield.json', nn='T', traj='md.traj'): # atoms = read(traj) # ao = AtomDance(atoms) # images = ao.stretch([[i,j]],nbin=50,traj=False) images = Trajectory(traj) atoms = images[0] nn_ = True if nn == 'T' else False ir = IRFF_NP(atoms=atoms, libfile=ffield, rcut=None, nn=nn_) ir.calculate_Delta(atoms) natom = ir.natom r_,eb,bosi,bop_si,bop,bop_pi,bop_pp,bo = [],[],[],[],[],[],[],[] eba, eo, dlpi, dlpj, ev, boe = [], [], [], [], [], [] esi, epi, epp = [], [], [] Di, Dj = [], [] Dpi = [] for atoms in images: positions = atoms.positions v = positions[j] - positions[i] r = np.sqrt(np.sum(np.square(v))) ir.calculate(atoms) r_.append(ir.r[i][j]) eb.append(ir.ebond[i][j]) eba.append(ir.ebond[i][j] + ir.eover[i] + ir.Evdw) ev.append(ir.Evdw) eo.append(ir.Eover) # print(ir.so[j],ir.eover[j]) dlpi.append(ir.Delta_lpcorr[i]) dlpj.append(ir.Delta_lpcorr[j]) Di.append(ir.Delta[i]) Dj.append(ir.Delta[j]) Dpi.append(ir.Dpil[j]) fig, ax = plt.subplots() ax.plot(eo, label=r'$E_{over}$', color='r', linewidth=2, linestyle='-') # fig, ax = plt.subplots(2,1,2) # plt.plot(r_,dlpj,label=r'$\Delta_{lp}$(%s%d)' %(ir.atom_name[j],j), # color='b', linewidth=2, linestyle='-') # Dpil plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('Eover.pdf') # plt.show() plt.close()
def deb_eang(images, ang=[0, 1, 2], figsize=(8, 6), show=False, print_=False): i, j, k = ang ang_ = [k, j, i] a = 0 found = False eang, ecoa, epen = [], [], [] ir = IRFF_NP(atoms=images[0], libfile='ffield.json', nn=True) ir.calculate_Delta(images[0]) for na, angle in enumerate(ir.angs): i_, j_, k_ = angle if (i_ == i and j_ == j and k_ == k) or (i_ == k and j_ == j and k_ == i): a = na found = True if not found: print('Error: no angle found for', ang, angle) for i_, atoms in enumerate(images): ir.calculate(atoms) eang.append(ir.Eang) ecoa.append(ir.Etcon) epen.append(ir.Epen) if print_: # for a,angle in enumerate(ir.angs): #i_,j_,k_ = angle print( '{:3d} {:6.4f} {:6.4f} Dpi: {:6.4f} pbo: {:6.4f} N: {:6.4f} SBO3: {:6.4f}' .format(i_, ir.thet0[a], ir.theta[a], ir.sbo[a], ir.pbo[a], ir.nlp[j], ir.SBO3[a])) # self.thet0-self.theta plt.figure(figsize=figsize) plt.plot(eang, alpha=0.8, linewidth=2, linestyle='-', color='r', label=r'$E_{ang}$') # ($-E_{ang}/{:4.2f}$)'.format(ang_m)) # plt.plot(ecoa,alpha=0.8,linewidth=2,linestyle='-',color='indigo',label=r'$E_{coa}$') # ($E_{coa}/%4.2f$)' %emx) # plt.plot(epen,alpha=0.8,linewidth=2,linestyle='-',color='b',label=r'$E_{pen}$') # ($E_{pen}/%4.2f$)' %eox) plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('deb_ang.pdf') if show: plt.show() plt.close()
def ple(traj='md.traj', dE=0.15, d2E=0.05, Etole=0.1): images = Trajectory(traj) tframe = len(images) x_ = [i for i in range(tframe)] ir = IRFF_NP(atoms=images[0], libfile='ffield.json', rcut=None, nn=True) energies, e_ = [], [] dEs, d2Es = [], [] ind_, labels = [], [] dE_ = 0.0 d2E_ = 0.0 fig, ax = plt.subplots() with open('SinglePointEnergies.log', 'r') as fs: in_, edft = [], [] for line in fs.readlines(): l = line.split() i_ = int(l[0]) e = float(l[2]) e_ = float(l[4]) dE = float(l[8]) d2E = float(l[10]) in_.append(i_) edft.append(e_) for i, atoms in enumerate(images): energy = atoms.get_potential_energy() ir.calculate(atoms) # e_.append(ir.E) 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) if i in in_: ########### ind_.append(i) labels.append(energy) energies.append(energy) dEs.append(dE_) d2Es.append(d2E_) print(' * differential:', dE_, d2E_) i_, edft_, labels_ = [], [], [] for _, i in enumerate(ind_): if abs(edft[_] - labels[_]) > Etole: i_.append(i) edft_.append(edft[_]) labels_.append(labels[_]) le = (len(energies) - 1) * 0.1 dle = le / 100.0 plt.xlim(-dle, le + dle) emin = np.min(energies) edft_ = np.array(edft_) edft = np.array(edft) labels_ = np.array(labels_) labels = np.array(labels) energies = np.array(energies) in_ = np.array(in_) i_ = np.array(i_) x_ = np.array(x_) plt.ylabel('Energy (unit: eV)') plt.xlabel('Time (unit: fs)') plt.scatter(i_ * 0.1, labels_ - emin, color='none', edgecolors='red', linewidths=2, marker='*', s=150, label=r'$Labeled$ $Data$', alpha=1.0) err = edft - labels plt.errorbar(in_ * 0.1, edft - emin, yerr=err, fmt='s', ecolor='red', color='none', ms=7, markerfacecolor='none', mec='red', elinewidth=2, capsize=2, label=r'$True$ $Value(DFT)$') plt.plot(x_ * 0.1, energies - emin, label=r'$IRFF$($MPNN$) $Predictions$', color='blue', marker='o', markerfacecolor='none', markeredgewidth=1, ms=3, alpha=0.8, linewidth=1, linestyle='-') plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('popeng.eps', transparents=True) plt.close()
class AtomOP(object): def __init__(self, atoms=None, rtole=0.5): self.rtole = rtole if atoms is None: gen_ = 'md.traj' if isfile('md.traj') else 'poscar.gen' atoms = read(gen_, index=-1) self.ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) self.natom = self.ir.natom self.atom_name = self.ir.atom_name spec = self.ir.spec label_dic = {} for sp in self.atom_name: if sp in label_dic: label_dic[sp] += 1 else: label_dic[sp] = 1 self.label = '' for sp in spec: self.label += sp + str(label_dic[sp]) def check(self, wcheck=2, i=0, atoms=None, rtole=None): if atoms is None: atoms = self.ir.atoms if not rtole is None: self.rtole = rtole self.ir.calculate_Delta(atoms, updateP=True) fc = open('check.log', 'w') if i % wcheck == 0: atoms = self.checkLoneAtoms(atoms, fc) else: atoms = self.checkLoneAtom(atoms, fc) atoms = self.checkClosedAtom(atoms, fc) fc.close() return atoms def checkLoneAtom(self, atoms, fc): for i in range(self.natom): if self.ir.Delta[i] <= self.ir.atol: print('- find an lone atom', i, self.atom_name[i], file=fc) sid = np.argsort(self.ir.r[i]) for j in sid: if self.ir.r[i][j] > 0.0001: print(' move lone atom to nearest neighbor: %d' % j, file=fc) vr = self.ir.vr[i][j] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ j] + u * 0.64 * self.ir.r_cuta[i][j] break self.ir.calculate_Delta(atoms) return atoms def checkLoneAtoms(self, atoms, fc): for i in range(self.natom): if self.ir.Delta[i] <= self.ir.atol: print('- find an lone atom', i, self.atom_name[i], file=fc) mid = np.argmin(self.ir.ND) if mid == i: continue print('- find the most atractive atom:', mid, file=fc) print('\n- neighors of atom %d %s:' % (i, self.atom_name[i]), end='', file=fc) neighs = [] for j, bo in enumerate(self.ir.bo0[mid]): if bo > self.ir.botol: neighs.append(j) print(j, self.atom_name[j], end='', file=fc) print(' ', file=fc) if len(neighs) == 0: vr = self.ir.vr[mid][i] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 1: j = neighs[0] vr = self.ir.vr[mid][j] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 2: i_, j_ = neighs xj = atoms.positions[mid] xi = 0.5 * (atoms.positions[i_] + atoms.positions[j_]) vr = xj - xi u = vr / np.sqrt(np.sum(np.square(vr))) vij = atoms.positions[j_] - atoms.positions[i_] rij = np.sqrt(np.sum(np.square(vij))) r_ = np.dot(vij, u) if r_ != rij: atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 3: i_, j_, k_ = neighs vi = atoms.positions[i_] - atoms.positions[j_] vj = atoms.positions[i_] - atoms.positions[k_] # cross product vr = np.cross(vi, vj) c = (atoms.positions[i_] + atoms.positions[j_] + atoms.positions[k_]) / 3 v = atoms.positions[mid] - c u = vr / np.sqrt(np.sum(np.square(vr))) # dot product dot = np.dot(v, u) if dot <= 0: u = -u atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] self.ir.calculate_Delta(atoms) return atoms def checkClosedAtom(self, atoms, fc): self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, self.ir.r_cuta) for i in range(self.natom - 1): for j in range(i + 1, self.natom): if self.ir.r[i][j] < self.rtole * self.ir.r_cuta[i][j]: print('- atoms %d and %d too closed' % (i, j), file=fc) moveDirection = self.ir.vr[j][i] / self.ir.r[i][j] moveD = self.ir.r_cuta[i][j] * (self.rtole + 0.01) - self.ir.r[i][j] moveV = moveD * moveDirection ToBeMove = [] ToBeMove = getAtomsToMove(i, j, ToBeMove, neighbors) print(' atoms to to be moved:', ToBeMove, file=fc) for m in ToBeMove: newPos = atoms.positions[m] + moveV r = np.sqrt( np.sum(np.square(newPos - atoms.positions[i]))) if r > self.ir.r[i][m]: atoms.positions[m] = newPos self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, self.ir.r_cuta) return atoms 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 close(self): self.ir = None self.atom_name = None
def nxp(gen='C2H4.gen', ffield='ffield.json', nn='T', threshold=0.1): atoms = read(gen) atom_name = atoms.get_chemical_symbols() nn_ = True if nn == 'T' else False ir = IRFF_NP(atoms=atoms, libfile=ffield, rcut=None, nn=nn_) # ir.get_pot_energy(atoms) # ir.logout() ir.calculate_Delta(atoms) natom = ir.natom g = nx.Graph() g.clear() color = {'C': 'grey', 'H': 'yellow', 'O': 'red', 'N': 'blue'} size = {'C': 400, 'H': 150, 'O': 300, 'N': 300} nodeColor = [] nodeSize = [] labels0, labels1 = {}, {} for i in range(natom): c = color[atom_name[i]] s = size[atom_name[i]] nodeColor.append(c) nodeSize.append(s) g.add_node(atom_name[i] + str(i)) labels0[atom_name[i] + str(i)] = atom_name[i] + str(i) + ':%4.3f' % ir.Deltap[i] labels1[atom_name[i] + str(i)] = atom_name[i] + str(i) + ':%4.3f' % ir.Delta[i] edgew = [] for i in range(natom - 1): for j in range(i + 1, natom): if ir.r[i][j] < ir.r_cut[i][j]: if ir.bop[i][j] >= threshold: g.add_edge(atom_name[i] + str(i), atom_name[j] + str(j), BO0='%5.4f' % ir.bop[i][j]) edgew.append(2.0 * ir.bop[i][j]) pos = {} # pos = nx.spring_layout(g) for i, a in enumerate(atoms): pos[atom_name[i] + str(i)] = [a.x, a.y] nx.draw(g, pos, node_color=nodeColor, node_size=nodeSize, width=edgew, with_labels=False) edge_labels = nx.get_edge_attributes(g, 'BO0') nx.draw_networkx_edge_labels(g, pos, labels=edge_labels, font_size=8) # nx.draw_networkx_labels(g,pos,labels=labels0,font_size=8) plt.savefig('%s_bo0.eps' % gen.split('.')[0]) plt.close() g = nx.Graph() g.clear() for i in range(natom): g.add_node(atom_name[i] + str(i)) edgew = [] for i in range(natom - 1): for j in range(i + 1, natom): if ir.r[i][j] < ir.r_cut[i][j]: if ir.bo0[i][j] >= threshold: g.add_edge(atom_name[i] + str(i), atom_name[j] + str(j), BO1='%5.4f' % ir.bo0[i][j]) edgew.append(2.0 * ir.bo0[i][j]) nx.draw(g, pos, node_color=nodeColor, node_size=nodeSize, width=edgew, with_labels=False) edge_labels = nx.get_edge_attributes(g, 'BO1') nx.draw_networkx_edge_labels(g, pos, labels=edge_labels, font_size=8) # nx.draw_networkx_labels(g,pos,labels=labels1,font_size=8) plt.savefig('%s_bo1.eps' % gen.split('.')[0]) plt.close() ir.close()
class AtomDance(object): def __init__(self, atoms=None, poscar=None, nn=True, rtole=0.5, bondTole=1.25, botol=0.0): self.rtole = rtole self.bondTole = bondTole self.botol = botol self.BondDistrubed = [] if atoms is None: if poscar is None: atoms = read('poscar.gen') else: atoms = read(poscar) self.ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=nn) self.natom = self.ir.natom self.atom_name = self.ir.atom_name spec = self.ir.spec self.mass = atoms.get_masses() label_dic = {} for sp in self.atom_name: if sp in label_dic: label_dic[sp] += 1 else: label_dic[sp] = 1 self.label = '' for sp in spec: self.label += sp + str(label_dic[sp]) self.ir.calculate_Delta(atoms) self.InitBonds = getBonds(self.natom, self.ir.r, self.bondTole * self.ir.re, self.ir.bo0, botol=self.botol) self.neighbors = getNeighbor(self.natom, self.ir.r, self.bondTole * self.ir.re, self.ir.bo0, botol=self.botol) def bond_momenta_bigest(self, atoms): ratio = [] s = [] for bd in self.InitBonds: i, j = bd ratio_ = self.ir.r[i][j] / self.ir.re[i][j] s_ = ratio_ - 1.0 s.append(s_) ratio.append(abs(s_)) m_ = np.argmax(ratio) i, j = self.InitBonds[m_] s_ = s[m_] if s_ >= 0.0: sign = 1.0 else: sign = -1.0 atoms = self.set_bond_momenta(i, j, atoms, sign=sign) return atoms def bond_momenta(self, atoms): ratio = [] for bd in self.InitBonds: i, j = bd if bd not in self.BondDistrubed: s_ = self.ir.r[i][j] / self.ir.re[i][j] - 1.0 if s_ >= 0.0: sign = 1.0 else: sign = -1.0 self.BondDistrubed.append(bd) atoms = self.set_bond_momenta(i, j, atoms, sign=sign) return atoms, True return atoms, False def set_bond_momenta(self, i, j, atoms, sign=1.0): ha = int(0.5 * self.natom) # x = atoms.get_positions() v = np.zeros([self.natom, 3]) group_j = [] group_j, ring = getAtomsToMove(i, j, j, group_j, self.neighbors) jg = len(group_j) group_i = [] group_i, ring = getAtomsToMove(j, i, i, group_i, self.neighbors) ig = len(group_i) if ring: group_i = [i] group_j = [j] vij = self.ir.vr[j][i] / self.ir.r[i][j] massi = 0.0 massj = 0.0 for a in group_i: massi += self.mass[a] for a in group_j: massj += self.mass[a] vi = 1.0 / massi vj = 1.0 / massj for a in group_i: v[a] = sign * vi * vij for a in group_j: v[a] = -sign * vj * vij atoms.set_velocities(v) return atoms def check_bond(self, atoms=None, mdtraj=None, bondTole=1.3): if atoms is None: atoms = self.ir.atoms if not bondTole is None: self.bondTole = bondTole self.ir.calculate_Delta(atoms, updateP=True) bkbd = None bB_ = 0 bondBroken = False bondTole_ = self.bondTole - 0.015 bonds = getBonds(self.natom, self.ir.r, bondTole_ * self.ir.re, self.ir.bo0, botol=self.botol * 0.5) if len(bonds) == len(self.InitBonds): for bd in self.InitBonds: bd_ = (bd[1], bd[0]) if (bd not in bonds) and (bd_ not in bonds): bkbd = bd bondBroken = True break else: bondBroken = True if bondBroken: bB_ += 1 bondBroken = False bondTole_ = self.bondTole bonds = getBonds(self.natom, self.ir.r, bondTole_ * self.ir.re, self.ir.bo0, botol=self.botol) if len(bonds) == len(self.InitBonds): for bd in self.InitBonds: bd_ = (bd[1], bd[0]) if (bd not in bonds) and (bd_ not in bonds): bondBroken = True break else: bondBroken = True if bondBroken: bB_ += 1 return bB_, bkbd def check(self, wcheck=2, i=0, atoms=None, rtole=None): if atoms is None: atoms = self.ir.atoms if not rtole is None: self.rtole = rtole self.ir.calculate_Delta(atoms, updateP=True) fc = open('check.log', 'w') if i % wcheck == 0: atoms = self.checkLoneAtoms(atoms, fc) else: atoms = self.checkLoneAtom(atoms, fc) atoms = self.checkClosedAtom(atoms, fc) fc.close() return atoms def checkLoneAtom(self, atoms, fc): for i in range(self.natom): if self.ir.Delta[i] <= self.ir.atol: print('- find an lone atom', i, self.atom_name[i], file=fc) sid = np.argsort(self.ir.r[i]) for j in sid: if self.ir.r[i][j] > 0.0001: print(' move lone atom to nearest neighbor: %d' % j, file=fc) vr = self.ir.vr[i][j] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ j] + u * 0.64 * self.ir.r_cuta[i][j] break self.ir.calculate_Delta(atoms) return atoms def checkLoneAtoms(self, atoms, fc): for i in range(self.natom): if self.ir.Delta[i] <= self.ir.atol: print('- find an lone atom', i, self.atom_name[i], file=fc) mid = np.argmin(self.ir.ND) if mid == i: continue print('- find the most atractive atom:', mid, file=fc) print('\n- neighors of atom %d %s:' % (i, self.atom_name[i]), end='', file=fc) neighs = [] for j, bo in enumerate(self.ir.bo0[mid]): if bo > self.ir.botol: neighs.append(j) print(j, self.atom_name[j], end='', file=fc) print(' ', file=fc) if len(neighs) == 0: vr = self.ir.vr[mid][i] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 1: j = neighs[0] vr = self.ir.vr[mid][j] u = vr / np.sqrt(np.sum(np.square(vr))) atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 2: i_, j_ = neighs xj = atoms.positions[mid] xi = 0.5 * (atoms.positions[i_] + atoms.positions[j_]) vr = xj - xi u = vr / np.sqrt(np.sum(np.square(vr))) vij = atoms.positions[j_] - atoms.positions[i_] rij = np.sqrt(np.sum(np.square(vij))) r_ = np.dot(vij, u) if r_ != rij: atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] elif len(neighs) == 3: i_, j_, k_ = neighs vi = atoms.positions[i_] - atoms.positions[j_] vj = atoms.positions[i_] - atoms.positions[k_] # cross product vr = np.cross(vi, vj) c = (atoms.positions[i_] + atoms.positions[j_] + atoms.positions[k_]) / 3 v = atoms.positions[mid] - c u = vr / np.sqrt(np.sum(np.square(vr))) # dot product dot = np.dot(v, u) if dot <= 0: u = -u atoms.positions[i] = atoms.positions[ mid] + u * 0.64 * self.ir.r_cuta[i][mid] self.ir.calculate_Delta(atoms) return atoms def checkClosedAtom(self, atoms, fc): self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, self.ir.r_cuta, self.ir.bo0) for i in range(self.natom - 1): for j in range(i + 1, self.natom): if self.ir.r[i][j] < self.rtole * self.ir.r_cuta[i][j]: print('- atoms %d and %d too closed' % (i, j), file=fc) moveDirection = self.ir.vr[j][i] / self.ir.r[i][j] moveD = self.ir.r_cuta[i][j] * (self.rtole + 0.01) - self.ir.r[i][j] moveV = moveD * moveDirection ToBeMove = [] ToBeMove, ring = getAtomsToMove(i, j, j, ToBeMove, neighbors) print(' atoms to to be moved:', ToBeMove, file=fc) for m in ToBeMove: newPos = atoms.positions[m] + moveV r = np.sqrt( np.sum(np.square(newPos - atoms.positions[i]))) if r > self.ir.r[i][m]: atoms.positions[m] = newPos self.ir.calculate_Delta(atoms) neighbors = getNeighbor(self.natom, self.ir.r, self.ir.r_cuta, self.ir.bo0) return atoms def bend(self, ang=None, rang=20.0, nbin=10, scale=1.2, wtraj=False): i, j, k = ang axis = [i, k] images = self.rotate(atms=[i, k], axis=axis, o=j, rang=rang, nbin=nbin, wtraj=wtraj, scale=scale) return images def bend_axis(self, axis=None, group=None, rang=20, nbin=30, scale=1.2, wtraj=False): images = self.rotate(atms=group, axis=axis, o=axis[0], rang=rang, nbin=nbin, wtraj=wtraj, scale=scale) return images def swing_group(self, ang=None, group=None, rang=20, nbin=30, scale=1.2, wtraj=False): i, j, k = ang atoms = self.ir.atoms self.ir.calculate_Delta(atoms) 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 images = self.rotate(atms=group, axis_vector=uk, o=j, rang=rang, nbin=nbin, wtraj=wtraj, scale=scale) return images 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 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 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 def close(self): self.ir = None self.atom_name = None
from ase.io.trajectory import Trajectory from ase.visualize import view from irff.prep_data import prep_data import matplotlib.pyplot as plt import matplotlib.mlab as mlab from mpl_toolkits.mplot3d import Axes3D from matplotlib import cm import matplotlib.colors as col import numpy as np get_ipython().run_line_magic('matplotlib', 'inline') images = Trajectory('md.traj') view(images) atoms = images[-1] ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) # ir.get_pot_energy(atoms) # ir.logout() ir.calculate_Delta(atoms) # print(ir.ebond) fig = plt.figure() ax = fig.gca(projection='3d') # set figure information ax.set_title("Bond Energy") ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z") mine = np.min(ir.ebond)
def messagePassing(atoms, color={ 'C': 'dimgray', 'H': 'silver', 'O': 'crimson', 'N': 'dodgerblue' }, size={ 'C': 320, 'H': 90, 'O': 180, 'N': 320 }, bondColor='darkgoldenrod', boxColor='steelblue', bondWidth=1, latticeWidth=2, bocut=0.0001, elev=45, azim=45, Axis=True, Box=True, t=0, text='edge', labelnode=False, ball_scale=20, ray_scale=100, n_ray_steps=10, show=False, show_element=False, figname='messagepassing.svg'): ''' avilable colors: ghostwhite whitesmoke olive ''' positions = atoms.get_positions() sym = atoms.get_chemical_symbols() ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) ir.calculate(atoms) normalized_charges = ir.q.copy() normalized_charges[np.isnan(normalized_charges)] = 0 max_charge = np.max(np.abs(normalized_charges)) normalized_charges /= max_charge normalized_charges = (normalized_charges + 1) / 2 color_map = plt.get_cmap("bwr_r") colors = color_map(normalized_charges) ball_sizes = np.array([ir.p['rvdw_' + e] for e in ir.atom_name]) * ball_scale ray_full_sizes = ball_sizes + np.abs(ir.q) * ray_scale ray_sizes = np.array([ np.linspace(ray_full_sizes[i], ball_sizes[i], n_ray_steps, endpoint=False) for i in range(ir.natom) ]).T # plot scatter points # fig, ax = plt.subplots() fig = plt.figure(figsize=(8.0, 6.0)) ax = fig.add_subplot(111, projection="3d") bonds = [] bondColors = [] #color_map(0.5) bWs = [] for i in range(ir.natom - 1): for j in range(i + 1, ir.natom): if ir.H[t][i][j] > bocut: bonds.append((atoms.positions[i], atoms.positions[j])) ax.text(0.5 * (atoms.positions[i][0] + atoms.positions[j][0]), 0.5 * (atoms.positions[i][1] + atoms.positions[j][1]), 0.5 * (atoms.positions[i][2] + atoms.positions[j][2]), r'$%3.3f$' % ir.H[t][i][j], ha="center", va="center", zorder=100, fontsize=16, color='k') bondColors.append( color_map(0.5 * (normalized_charges[i] + normalized_charges[j]))) bWs.append(ir.H[t][i][j]) sticks = Line3DCollection(bonds, color=bondColors, linewidths=bondWidth * np.array(bWs), alpha=0.8) ax.add_collection(sticks) if show_element: for i, atom in enumerate(atoms): ax.text(atom.x, atom.y, atom.z, ir.atom_name[i] + str(i), color="black", ha="center", va="center", zorder=100, fontsize=16) ax.scatter(*atoms.positions.T, c=colors, s=ball_sizes**2, alpha=1.0) ax.set_facecolor((0.05, 0.05, 0.05)) ax.get_figure().set_facecolor((0.05, 0.05, 0.05)) # Plots the rays for i in range(n_ray_steps): ax.scatter(*atoms.positions.T, s=ray_sizes[i]**2, c=colors, linewidth=0, alpha=0.05) # ymin_ =min( ymin,yl+0.1*yr) # ax.text(xmin,ymin_,zmin_,r'$BO^{t=%d}$' %t,fontsize=16) if Box: # plot lattice cell = atoms.get_cell() crystalVetexes = [np.zeros(3), cell[0], cell[1], cell[2]] crystalVetexes.append(cell[0] + cell[1]) crystalVetexes.append(cell[0] + cell[2]) crystalVetexes.append(cell[1] + cell[2]) crystalVetexes.append(crystalVetexes[4] + cell[2]) edges = [[0, 1], [0, 2], [0, 3], [1, 4], [1, 5], [2, 6], [2, 4], [3, 5], [3, 6], [4, 7], [5, 7], [6, 7]] for e in edges: i, j = e x = [crystalVetexes[i][0], crystalVetexes[j][0]] y = [crystalVetexes[i][1], crystalVetexes[j][1]] z = [crystalVetexes[i][2], crystalVetexes[j][2]] ax.plot(x, y, z, c=boxColor, linewidth=latticeWidth, alpha=0.9) fig.tight_layout() ax.azim = azim ax.elev = elev ax.axis("off") # Remove frame plt.savefig(figname, transparent=True) if show: plt.show() plt.close()
def MessagePassing(atoms, color={ 'C': 'dimgray', 'H': 'silver', 'O': 'crimson', 'N': 'dodgerblue' }, size={ 'C': 320, 'H': 90, 'O': 180, 'N': 320 }, bondColor='darkgoldenrod', boxColor='steelblue', bondWidth=2, elev=45, azim=45, Axis=True, Box=True, t=0, text='edge', labelnode=False): ''' avilable colors: ghostwhite whitesmoke olive ''' positions = atoms.get_positions() sym = atoms.get_chemical_symbols() ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) ir.calculate_Delta(atoms) # plot scatter points fig, ax = plt.subplots() # ax.set_xlim([0,5]) # ax.set_ylim([0,5]) x_, y_, z_ = [], [], [] # circ=plt.Circle((1.5, 0.5),radius=0.2,color=(58/255,94/255,148/255)) # ax.add_patch(circ) for i, atom in enumerate(atoms): x_.append(atom.x) y_.append(atom.y) z_.append(atom.z) plt.scatter(atom.y, atom.z, c=color[sym[i]], marker='o', s=size[sym[i]], label=sym[i], alpha=1) if text == 'node': plt.text(atom.y - 0.15, atom.z, r'$%3.2f$' % ir.Delta[i], fontsize=20) else: if labelnode: plt.text(atom.y - 0.11, atom.z, r'$%s%d$' % (ir.atom_name[i], i), fontsize=20) xmin, ymin = np.min(atoms.positions[:, 1]), np.min(atoms.positions[:, 2]) yl, yh = ax.get_ylim() yr = yh - yl xl, xh = ax.get_xlim() xr = xh - xl for i in range(ir.natom - 1): for j in range(i + 1, ir.natom): if ir.bo0[i][j] > 0.05: x = [atoms.positions[i][0], atoms.positions[j][0]] y = [atoms.positions[i][1], atoms.positions[j][1]] z = [atoms.positions[i][2], atoms.positions[j][2]] # plt.plot(y,z,c=bondColor,linewidth=5,alpha=0.8) line = mlines.Line2D(y, z, lw=bondWidth * ir.bop[i][j], ls='-', alpha=1, color=bondColor) line.set_zorder(0) ax.add_line(line) if text == 'edge': # if ir.atom_name[i]=='C' and ir.atom_name[j]=='C': # plt.text(0.5*(y[0]+y[1])-0.05*xr,0.5*(z[0]+z[1]), # r'$BO=%3.2f$' %ir.H[t][i][j], # fontsize=16) # eb = ir.ebond[i][j] # si = ir.Hsi[t][i][j] # pi = ir.Hpi[t][i][j] # pp = ir.Hpp[t][i][j] # plt.text(0.5*(y[0]+y[1])-0.05*xr,0.5*(z[0]+z[1])+0.3*yr, # r'$BO^{\sigma}=%3.2f$' %si,fontsize=16) # plt.text(0.5*(y[0]+y[1])-0.05*xr,0.5*(z[0]+z[1])+0.2*yr, # r'$BO^{\pi}=%3.2f$' %pi,fontsize=16) # plt.text(0.5*(y[0]+y[1])-0.05*xr,0.5*(z[0]+z[1])+0.1*yr, # r'$BO^{\pi\pi}=%3.2f$' %pp,fontsize=16) # print('f_Ebond(%5.3f,%5.3f,%5.3f)=%5.3f' %(si,pi,pp,eb)) # Di = ir.Delta[i]-ir.bo0[i][j] # Dj = ir.Delta[j]-ir.bo0[i][j] # if t>0: # plt.text(xmin+0.45,0.5*(z[0]+z[1])-0.1*yr, # r'$f_{Message}^{t=1}(%3.2f,%3.2f,%3.2f)=%3.2f$' %(Di,Dj,ir.bo0[i][j],ir.F[-1][i][j]), # fontsize=16) # print('f_BO(%5.3f,%5.3f,%5.3f)=%5.3f' %(Di,Dj,ir.bo0[i][j],ir.F[-1][i][j])) # else: plt.text( 0.5 * (y[0] + y[1]) - 0.15 * xr, 0.5 * (z[0] + z[1]), r'$(%3.2f,%3.2f,%3.2f)$' % (ir.Hsi[t][i][j], ir.Hpi[t][i][j], ir.Hpp[t][i][j]), fontsize=16) ymin_ = min(ymin, yl + 0.1 * yr) plt.text(xmin, ymin_, r'$BO^{t=%d}$' % t, fontsize=16) plt.savefig('MessagePassing.svg', transparent=True)
def deb_eover(images, i=0, j=1, figsize=(16, 10), show=False, print_=True): bopsi, boppi, boppp, bo0, bo1, eb = [], [], [], [], [], [] eo, eu, el, esi, r = [], [], [], [], [] eo_, eu_, eb_ = [], [], [] ir = IRFF_NP(atoms=images[0], libfile='ffield.json', nn=True) ir.calculate_Delta(images[0]) for i_, atoms in enumerate(images): ir.calculate(atoms) bo0.append(ir.bop[i][j]) bo1.append(ir.bo0[i][j]) eb.append(ir.ebond[i][j]) eo.append(ir.Eover) eu.append(ir.Eunder) r.append(ir.r[i][j]) if print_: print('r: {:6.4f} bo: {:6.4f} eu: {:6.4f} ev: {:6.4f} eb: {:6.4f}'. format(ir.r[i][j], ir.bo0[i][j], ir.Eunder, ir.Eover, ir.ebond[i][j])) ebx = np.max(np.abs(eb)) eb = np.array(eb) / ebx + 1.0 eox = np.max(np.abs(eo)) if eox < 0.0001: eox = 1.0 eo = np.array(eo) / eox + 1.0 eux = np.max(np.abs(eu)) eu = np.array(eu) / eux + 1.0 plt.figure(figsize=figsize) # plt.plot(r,bo0,alpha=0.8,linewidth=2,linestyle='-',color='g',label=r'$BO^{t=0}$') # plt.plot(r,bo1,alpha=0.8,linewidth=2,linestyle='-',color='y',label=r'$BO^{t=1}$') plt.plot(r, eb, alpha=0.8, linewidth=2, linestyle='-', color='r', label=r'$E_{bond}$') plt.plot(r, eo, alpha=0.8, linewidth=2, linestyle='-', color='indigo', label=r'$E_{over}$ ($E_{over}/%4.2f$)' % eox) plt.plot(r, eu, alpha=0.8, linewidth=2, linestyle='-', color='b', label=r'$E_{under}$ ($E_{under}/%4.2f$)' % eux) plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('deb_bo.pdf') if show: plt.show() plt.close()
def deb_bo(images, i=0, j=1, figsize=(16, 10), print_=False, show=False): r, bopsi, boppi, boppp, bo0, bo1, eb, esi = [], [], [], [], [], [], [], [] ir = IRFF_NP(atoms=images[0], libfile='ffield.json', nn=True) ir.calculate_Delta(images[0]) for i_, atoms in enumerate(images): ir.calculate(atoms) bopsi.append(ir.eterm1[i][j]) boppi.append(ir.eterm2[i][j]) boppp.append(ir.eterm3[i][j]) bo0.append(ir.bop[i][j]) bo1.append(ir.bo0[i][j]) eb.append(ir.ebond[i][j]) esi.append(ir.esi[i][j]) r.append(ir.r[i][j]) if print_: print( '{:3d} r: {:6.4f} bo: {:6.4f} Delta: {:6.4f} {:6.4f}'.format( i_, ir.r[i][j], ir.bo0[i][j], ir.Delta[i], ir.Delta[j])) # self.thet0-self.theta emin_ = np.min(eb) eb = (emin_ - np.array(eb)) / emin_ ems = np.min(esi) emx = np.max(esi) esi = (np.array(esi) - ems) / emx plt.figure(figsize=figsize) plt.plot(r, bopsi, alpha=0.8, linewidth=2, linestyle=':', color='k', label=r'$BO_p^{\sigma}$') plt.plot(r, boppi, alpha=0.8, linewidth=2, linestyle='-.', color='k', label=r'$BO_p^{\pi}$') plt.plot(r, boppp, alpha=0.8, linewidth=2, linestyle='--', color='k', label=r'$BO_p^{\pi\pi}$') plt.plot(r, bo0, alpha=0.8, linewidth=2, linestyle='-', color='g', label=r'$BO^{t=0}$') plt.plot(r, bo1, alpha=0.8, linewidth=2, linestyle='-', color='y', label=r'$BO^{t=1}$') plt.plot(r, eb, alpha=0.8, linewidth=2, linestyle='-', color='r', label=r'$E_{bond}$ ($-E_{bond}/%4.2f$)' % -emin_) plt.plot(r, esi, alpha=0.8, linewidth=2, linestyle='-', color='indigo', label=r'$E_{esi}$ ($E_{si}/%4.2f$)' % emx) plt.legend(loc='best', edgecolor='yellowgreen') plt.savefig('deb_bo.pdf') if show: plt.show() plt.close() return r, eb
def e(traj='md.traj', nn=True): ffield = 'ffield.json' if nn else 'ffield' images = Trajectory(traj) atoms = images[0] e, e_ = [], [] eb, el, eo, eu = [], [], [], [] ea, ep, etc = [], [], [] et, ef = [], [] ev, eh, ec = [], [], [] eb_, el_, eo_, eu_ = [], [], [], [] ea_, ep_, etc_ = [], [], [] et_, ef_ = [], [] ev_, eh_, ec_ = [], [], [] ir = IRFF(atoms=atoms, libfile=ffield, nn=nn, autograd=False) for i, atoms in enumerate(images): ir.calculate(atoms) e.append(ir.E) eb.append(ir.Ebond.numpy()) el.append(ir.Elone.numpy()) eo.append(ir.Eover.numpy()) eu.append(ir.Eunder.numpy()) ea.append(ir.Eang.numpy()) ep.append(ir.Epen.numpy()) et.append(ir.Etor.numpy()) ef.append(ir.Efcon.numpy()) etc.append(ir.Etcon.numpy()) ev.append(ir.Evdw.numpy()) eh.append(ir.Ehb.numpy()) ec.append(ir.Ecoul.numpy()) ir_ = IRFF_NP(atoms=atoms, libfile=ffield, nn=nn) for i, atoms in enumerate(images): ir_.calculate(atoms) e_.append(ir_.E) eb_.append(ir_.Ebond) el_.append(ir_.Elone) eo_.append(ir_.Eover) eu_.append(ir_.Eunder) ea_.append(ir_.Eang) ep_.append(ir_.Epen) et_.append(ir_.Etor) ef_.append(ir_.Efcon) etc_.append(ir_.Etcon) ev_.append(ir_.Evdw) eh_.append(ir_.Ehb) ec_.append(ir_.Ecoul) e_irffnp = { 'Energy': e, 'Ebond': eb, 'Eunger': eu, 'Eover': eo, 'Eang': ea, 'Epen': ep, 'Elone': el, 'Etcon': etc, 'Etor': et, 'Efcon': ef, 'Evdw': ev, 'Ecoul': ec, 'Ehbond': eh } e_irff = { 'Energy': e_, 'Ebond': eb_, 'Eunger': eu_, 'Eover': eo_, 'Eang': ea_, 'Epen': ep_, 'Elone': el_, 'Etcon': etc_, 'Etor': et_, 'Efcon': ef_, 'Evdw': ev_, 'Ecoul': ec_, 'Ehbond': eh_ } for key in e_irffnp: plt.figure() plt.ylabel('%s (eV)' % key) plt.xlabel('Step') plt.plot(e_irffnp[key], alpha=0.01, linestyle='-.', marker='o', markerfacecolor='none', markeredgewidth=1, markeredgecolor='b', markersize=4, color='blue', label='IRFF_NP') plt.plot(e_irff[key], alpha=0.01, linestyle=':', marker='^', markerfacecolor='none', markeredgewidth=1, markeredgecolor='red', markersize=4, color='red', label='IRFF') plt.legend(loc='best', edgecolor='yellowgreen') # lower left upper right plt.savefig('%s.eps' % key) plt.close()
def pam(traj, color={ 'C': 'grey', 'H': 'steelblue', 'O': 'crimson', 'N': 'dodgerblue' }, size={ 'C': 8000, 'H': 1200, 'O': 7000, 'N': 7000 }, bondColor='olive', boxColor='steelblue', bondWidth=20, elev=10, azim=120, Axis=True, Box=True, t=1, text='edge', labelnode=False): images = Trajectory(traj) atoms = images[0] sym = atoms.get_chemical_symbols() ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) ir.calculate_Delta(atoms) # plot scatter points fig, ax = plt.subplots(figsize=(8, 8)) plt.axis('off') mid = int(0.5 * len(images)) for i_ in [0, -1]: atoms = images[i_] ir.calculate_Delta(atoms) if i_ == 0: alp = 0.9 else: alp = 0.3 for i, atom in enumerate(atoms): x_, y_, z_ = [], [], [] x_.append(atom.x) y_.append(atom.y) z_.append(atom.z) plt.scatter(atom.y, atom.z, c=color[sym[i]], marker='o', s=size[sym[i]], label=sym[i], alpha=alp) for i in range(ir.natom - 1): for j in range(i + 1, ir.natom): if ir.r[i][j] < ir.re[i][j] * 1.25 and ir.ebond[i][j] < -0.01: x = [atoms.positions[i][0], atoms.positions[j][0]] y = [atoms.positions[i][1], atoms.positions[j][1]] z = [atoms.positions[i][2], atoms.positions[j][2]] # plt.plot(y,z,c=bondColor,linewidth=5,alpha=0.8) line = mlines.Line2D(y, z, lw=bondWidth * ir.bo0[i][j], ls='-', alpha=alp, color=bondColor) line.set_zorder(0) ax.add_line(line) # ax.ylabel('Y', fontdict={'size': 15, 'color': 'b'}) # ax.xlabel('X', fontdict={'size': 15, 'color': 'b'}) svg = traj.replace('.traj', '.svg') plt.savefig(svg, transparent=True)
def plf3d(atomi, atomj, traj, bo_=2.11): images = Trajectory(traj) atoms = images[0] # positions = atoms.get_positions() sym = atoms.get_chemical_symbols() with open('ffield.json', 'r') as lf: j = js.load(lf) m = j['m'] ir = IRFF_NP(atoms=atoms, libfile='ffield.json', rcut=None, nn=True) Di_, Dj_, F_, BO_ = [], [], [], [] for _, atoms in enumerate(images): ir.calculate(atoms) Di_.append(ir.D[0][atomi] - ir.H[0][atomi][atomj]) Dj_.append(ir.D[0][atomj] - ir.H[0][atomi][atomj]) BO_.append(ir.H[0][atomi][atomj]) F_.append(ir.F[-1][atomi][atomj]) for _, d in enumerate(Di_): print(Di_[_], Dj_[_], F_[_]) Di_ = Dj_ = np.arange(1.54, 1.62, 0.0001) Di, Dj = np.meshgrid(Di_, Dj_) i_, j_ = Di.shape F = np.zeros([i_, i_]) # di_= np.expand_dims(ir.D[0],axis=0)-ir.H[0] # dj_= np.expand_dims(ir.D[0],axis=1)-ir.H[0] # bo_= ir.H[0] wi = np.array(m['f1wi_C-C']) bi = np.array(m['f1bi_C-C']) w = np.array(m['f1w_C-C']) b = np.array(m['f1b_C-C']) wo = np.array(m['f1wo_C-C']) bo = np.array(m['f1bo_C-C']) for i in range(i_): for j in range(i, i_): di_ = Di[i][j] dj_ = Dj[i][j] Fi = f_nn([dj_, di_, bo_], wi, bi, w, b, wo, bo, layer=ir.bo_layer[1]) F_ = 2.0 * Fi * Fi # print(F_) F[i][j] = F_ F[j][i] = F_ fig = plt.figure() ax = Axes3D(fig) # plt.xlabel("Delta'") ax = plt.subplot(111, projection='3d') # ax.plot_surface(Di,Dj,F, cmap=plt.get_cmap('rainbow')) ax.contourf(Di, Dj, F, zdir='z', cmap=plt.get_cmap('rainbow')) plt.savefig('F.svg') plt.close()