示例#1
0
文件: irdeb.py 项目: haoxy97/I-ReaxFF
def g(gen='poscar.gen'):
    atoms = read(gen)
    ir = IRFF(atoms=atoms, libfile='ffield.json', nn=True, autograd=True)
    ir.calculate(atoms)
    print(ir.grad)

    ir_ = IRFF_TF(atoms=atoms, libfile='ffield.json', nn=True)
    ir_.calculate(atoms)
    print(ir_.grad.numpy())
示例#2
0
from ase.optimize import BFGS, FIRE
from irff.md import opt
from irff.irff import IRFF
from ase.io.trajectory import Trajectory
import matplotlib.pyplot as plt

images = Trajectory('pre_opt.traj', mode='r')

ir = IRFF(atoms=images[0], libfile='ffield.json', rcut=None, nn=True)
GPa = 1.60217662 * 1.0e2

v_, p = [], []
v0 = images[0].get_volume()

for atoms_ in images:
    ir.calculate(atoms=atoms_, CalStress=True)
    stress = ir.results['stress']

    nonzero = 0
    stre_ = 0.0
    for _ in range(3):
        if abs(stress[_]) > 0.0000001:
            nonzero += 1
            stre_ += -stress[_]
    pressure = stre_ * GPa / nonzero

    p.append(pressure)
    v = atoms_.get_volume()
    v_.append(v / v0)
    print(' * V/V0', v_[-1], v, pressure)
示例#3
0
文件: irdeb.py 项目: haoxy97/I-ReaxFF
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()
示例#4
0
def e(traj='pre_dft.traj',batch_size=100,nn=True):
    ffield = 'ffield.json' if nn else 'ffield'
    images = Trajectory(traj)
    e,ei,ei_    = [],[],[]

    ir = IRFF(atoms=images[0],
                 libfile=ffield,
                 nn=True)
    ir.get_potential_energy(images[0])

    ir_reax = IRFF(atoms=images[0],
                 libfile='ffield',
                 nn=False)
    ir_reax.get_potential_energy(images[0])

    v_,pdft,pml,preax,diff   = [],[],[],[],[]
    v0  = images[0].get_volume()

    for i,atoms in enumerate(images):
        v=atoms.get_volume()
        e.append(atoms.get_potential_energy())
        stress_ = atoms.get_stress()
        if v/v0 < 0.86:
           pdft.append(calculate_pressure(stress_)) 

           ir.calculate(atoms=atoms,CalStress=True)
           ei.append(ir.E)
           stress  = ir.results['stress']
           pml.append(calculate_pressure(stress)) 

           ir_reax.calculate(atoms=atoms,CalStress=True)
           ei_.append(ir.E)
           stress  = ir_reax.results['stress']
           preax.append(calculate_pressure(stress)) 

           v_.append(v/v0)
           diff.append(abs(pml[-1]-pdft[-1]))
           print(' * V/V0',v_[-1],v,pml[-1],pdft[-1],' diff: ',diff[-1])
     
    print(' * mean error:',np.mean(diff))
    e_min = min(e)
    e_max = max(e)
    e = np.array(e) - e_min
    e_min = min(ei)
    ei = np.array(ei) - e_min

    plt.figure()   
    plt.ylabel(r'$Pressure$ ($GPa$)')
    plt.xlabel(r'$V/V_0$')
    # plt.xlim(0,i)
    # plt.ylim(0,np.max(hist)+0.01)

    ax   = plt.gca()
    pml  = np.array(pml)
    pdft = np.array(pdft)

    plt.plot(v_,pml,alpha=0.9,
             linestyle='-',marker='o',markerfacecolor='none',markersize=7,
             color='b',label='IRFF(MPNN)')

    plt.plot(v_,preax,alpha=0.9,
             linestyle='-',marker='^',markerfacecolor='none',markersize=7,
             color='g',label='ReaxFF(trained)')

    plt.plot(v_,pdft,alpha=0.9,
             linestyle='-',marker='s',markerfacecolor='none',markersize=7,
             color='r',label='DFT(SIESTA)')
    
    pdiff = np.abs(pdft - pml)
    plt.fill_between(v_, pdft - pdiff, pdft + pdiff, color='darkorange',
                     alpha=0.2)

    pdiff = np.abs(pdft - preax)
    plt.fill_between(v_, pdft - pdiff, pdft + pdiff, color='palegreen',
                     alpha=0.2)

    plt.legend(loc='best',edgecolor='yellowgreen') # lower left upper right
    plt.savefig('compare-pv.svg',transparent=True) 
    plt.close() 
示例#5
0
def da(traj='opt.traj', batch_size=50, ef=3, nn=True, frame=44):
    ffield = 'ffield.json' if nn else 'ffield'
    images = Trajectory(traj)
    atoms = images[frame]
    his = TrajectoryWriter('tmp.traj', mode='w')
    his.write(atoms=atoms)
    # his.write(atoms=images[frame+1])
    his.close()

    ir = IRFF(atoms=atoms, libfile=ffield, nn=nn, autograd=False)
    ir.calculate(atoms)

    rn = MPNN(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],
              EnergyFunction=ef,
              pkl=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()

    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]),
                    '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]),
                    'theta: %10.8f' % (theta_[ang][a_][0]),
                    # 'sbo3: %10.8f' %(sbo3_[ang][a_][0]),
                    'theta0: %10.8f' % (theta0_[ang][a_][0]))
    fa.close()
    epen = rn.get_value(rn.epen)
    eang = rn.get_value(rn.eang)
    print(' * penalty energy:', ir.Epen.numpy(), epen[mol][0])
    print(' * angel energy:', ir.Eang.numpy(), eang[mol][0])
示例#6
0
def db(traj='opt.traj', batch_size=50, ef=3, nn=True, frame=40):
    ffield = 'ffield.json' if nn else 'ffield'
    images = Trajectory(traj)
    atoms = images[frame]

    e, ei = [], []
    ir = IRFF(atoms=atoms, libfile=ffield, nn=nn, autograd=False)

    ir.calculate(atoms)

    ei.append(ir.Ebond)
    ebond = ir.ebond  # .numpy()

    rn = MPNN(libfile=ffield,
              direcs={'tmp': traj},
              dft='siesta',
              opt=[],
              optword='nocoul',
              batch_size=batch_size,
              atomic=True,
              clip_op=False,
              InitCheck=False,
              nn=nn,
              bo_layer=[9, 2],
              EnergyFunction=ef,
              pkl=False)
    molecules = rn.initialize()
    rn.session(learning_rate=1.0e-10, method='AdamOptimizer')

    mol = 'tmp'
    er = rn.get_value(rn.ebond[mol])
    blab = rn.lk.bdlab

    bosi = ir.bosi.numpy()
    bopsi = ir.bop_si.numpy()
    boppi = ir.bop_pi.numpy()
    boppp = ir.bop_pp.numpy()

    bopow3 = ir.bopow3.numpy()
    eterm3 = ir.eterm3.numpy()

    bop = ir.bop.numpy()
    bo = ir.bo0.numpy()

    eterm1 = ir.eterm1.numpy()
    bopow1 = ir.bopow1.numpy()
    bodiv1 = ir.bodiv1.numpy()

    r = ir.r.numpy()
    D_ = rn.get_value(rn.Deltap)
    D = ir.Deltap.numpy()

    ebd_ = np.zeros([ir.natom, ir.natom])

    for bd in rn.bonds:
        for nb in range(rn.nbd[bd]):
            ebd = rn.get_value(rn.EBD[bd])
            mol_, i, j = blab[bd][nb]
            bosi_ = rn.get_value(rn.bosi[bd])
            bopsi_ = rn.get_value(rn.bop_si[bd])
            boppi_ = rn.get_value(rn.bop_pi[bd])
            boppp_ = rn.get_value(rn.bop_pp[bd])

            bopow3_ = rn.get_value(rn.bopow3[bd])
            eterm3_ = rn.get_value(rn.eterm3[bd])

            bop_ = rn.get_value(rn.bop[bd])
            bo_ = rn.get_value(rn.bo0[bd])

            eterm1_ = rn.get_value(rn.eterm1[bd])
            bopow1_ = rn.get_value(rn.bopow1[bd])
            bodiv1_ = rn.get_value(rn.bodiv1[bd])

            rbd = rn.get_value(rn.rbd[bd])

            ebd_[i][j] = ebd[nb][frame]
            ebd_[j][i] = ebd[nb][frame]
            # if abs(bo_[nb][0]-bo[i][j])>0.00001:
            print('-  %s %2d %2d:' % (bd, i, j),
                  'rbd %10.7f %10.7f' % (rbd[nb][frame], r[i][j]),
                  'bop %10.7f %10.7f' % (bop_[nb][frame], bop[i][j]),
                  'Di %10.7f %10.7f' % (D_[i][frame], D[i]),
                  'Dj %10.7f %10.7f' % (D_[j][frame], D[j]),
                  'bo %10.7f %10.7f' % (bo_[nb][frame], bo[i][j]),
                  'ebond %10.7f %10.7f' % (ebd[nb][frame], ebond[i][j]))

    rcbo = rn.get_value(rn.rc_bo)
    eb = rn.get_value(rn.ebond[mol])
    print('\n-  bond energy:', ir.Ebond.numpy(), eb[frame], end='\n')

    for i in range(ir.natom):
        for j in range(ir.natom):
            if abs(ebd_[i][j] - ebond[i][j]) > 0.00001:
                print('-  %s %2d %2d:' % (bd, i, j), 'rbd %10.7f' % (r[i][j]),
                      'bop %10.7f' % (bop[i][j]),
                      'Di %10.7f %10.7f' % (D_[i][frame], D[i]),
                      'Dj %10.7f %10.7f' % (D_[j][frame], D[j]),
                      'bo %10.7f' % (bo[i][j]),
                      'ebond %10.7f %10.7f' % (ebd_[i][j], ebond[i][j]))

    # print(rcbo)
    print('\n-  bond energy:', ir.Ebond.numpy(), eb[frame], end='\n')
示例#7
0
def static_compress():
    traj = TrajectoryWriter('pre_opt.traj', mode='w')
    atoms = read('nm.gen')
    cell = atoms.get_cell()
    atoms_ = atoms.copy()
    configs = []

    GPa = 1.60217662 * 1.0e2
    s = 1.0
    i = 0
    ir = IRFF(atoms=atoms_, libfile='ffield.json', nn=True)

    v_, p = [], []
    v0 = atoms.get_volume()

    while s > 0.66:
        print(' * lattice step:', i)
        f = s**(1.0 / 3.0)
        cell_ = cell.copy()
        cell_ = cell * f
        ir.CalStress = False
        atoms_.set_cell(cell_)
        atoms_ = opt(atoms=atoms_, fmax=0.02, step=120, optimizer=FIRE)
        configs.append(atoms_)
        traj.write(atoms=atoms_)
        ir.CalStress = True
        ir.calculate(atoms=atoms_)
        stress = ir.results['stress']

        nonzero = 0
        stre_ = 0.0
        for _ in range(3):
            if abs(stress[_]) > 0.0000001:
                nonzero += 1
                stre_ += -stress[_]
        pressure = stre_ * GPa / nonzero

        p.append(pressure)
        v = atoms_.get_volume()
        v_.append(v / v0)
        print(' * V/V0', v_[-1], v, pressure)

        s = s * 0.98
        i += 1

    fig, ax = plt.subplots()
    plt.ylabel(r'$Pressure$ ($GPa$)')
    plt.xlabel(r'$V/V_0$')
    plt.plot(v_,
             p,
             label=r'$IRFF-MPNN$',
             color='blue',
             marker='o',
             markerfacecolor='none',
             markeredgewidth=1,
             ms=5,
             alpha=0.8,
             linewidth=1,
             linestyle='-')

    plt.legend(loc='best', edgecolor='yellowgreen')
    plt.savefig('pv.pdf')
    plt.close()