def test_PME_QMMM(self): # compare to saved test: PME + QMMM topfile = os.path.join(amberhome, "test/qmmm2/MechEm_nma-spcfwbox/prmtop") rstfile = os.path.join(amberhome, "test/qmmm2/MechEm_nma-spcfwbox/inpcrd") traj = pt.load(rstfile, topfile) options = sander.pme_input() options.cut = 8.0 options.ifqnt = 1 options.jfastw = 4 qm_options = sander.QmInputOptions() qm_options.qm_theory = "PDDG-PM3" qm_options.qmmask = ":1-2" qm_options.qmcharge = 0 qm_options.scfconv = 1e-10 qmmm_tight_p_conv = 1 qm_options.qmmm_int = 5 edict = pt.energy_decomposition(traj=traj, mm_options=options, qm_options=qm_options) assert_close(edict['bond'][0], 605.7349, tol=3E-4) assert_close(edict['vdw_14'][0], 0.0000, tol=3E-4) assert_close(edict['elec_14'][0], 0.0000, tol=3E-4) assert_close(edict['elec'][0], -7409.7167, tol=3E-1) assert_close(edict['scf'][0], -37.1277, tol=3E-4)
def minimize(parm, igb, saltcon, cutoff, tol, maxcyc): """ Minimizes a snapshot. Use the existing System if it exists """ if not HAS_SANDER: raise SimulationError('Could not import sander') if not HAS_SCIPY: raise SimulationError('Could not import scipy') if parm.box is None: if not igb in (0, 1, 2, 5, 6, 7, 8): raise SimulationError('Bad igb value. Must be 0, 1, 2, 5, ' '6, 7, or 8') if cutoff is None: cutoff = 999.0 inp = sander.gas_input(igb) inp.saltcon = saltcon inp.cut = cutoff else: if cutoff is None: cutoff = 8.0 inp = sander.pme_input() inp.cut = cutoff # Define the objective function to minimize def energy_function(xyz): sander.set_positions(xyz) e, f = sander.energy_forces() return e.tot, -np.array(f) with sander.setup(parm, parm.coordinates, parm.box, inp): options = dict(maxiter=maxcyc, disp=True, gtol=tol) results = optimize.minimize(energy_function, parm.coordinates, method='L-BFGS-B', jac=True, options=options) parm.coordinates = results.x if not results.success: print('Problem minimizing structure with scipy and sander:', file=sys.stderr) print('\t' + results.message)
def minimize(parm, igb, saltcon, cutoff, tol, maxcyc, disp=True, callback=None): """ Minimizes a snapshot. Use the existing System if it exists """ if not HAS_SANDER: raise SimulationError('Could not import sander') if not HAS_SCIPY: raise SimulationError('Could not import scipy') if parm.box is None: if not igb in {0, 1, 2, 5, 6, 7, 8}: raise SimulationError('Bad igb value. Must be 0, 1, 2, 5, 6, 7, or 8') if cutoff is None: cutoff = 999.0 inp = sander.gas_input(igb) inp.saltcon = saltcon inp.cut = cutoff else: if cutoff is None: cutoff = 8.0 inp = sander.pme_input() inp.cut = cutoff # Define the objective function to minimize def energy_function(xyz): sander.set_positions(xyz) e, f = sander.energy_forces() return e.tot, -np.array(f) with sander.setup(parm, parm.coordinates, parm.box, inp): options = dict(maxiter=maxcyc, disp=disp, gtol=tol) more_options = dict() if callable(callback): more_options['callback'] = callback results = optimize.minimize(energy_function, parm.coordinates, method='L-BFGS-B', jac=True, options=options, **more_options) parm.coordinates = results.x if not results.success: LOGGER.error(f'Problem minimizing structure with scipy and sander: {results.message}')
def test_PME(self): # compare to saved test: PME topfile = os.path.join(amberhome, "test/4096wat/prmtop") rstfile = os.path.join(amberhome, "test/4096wat/eq1.x") traj = pt.iterload(rstfile, topfile) options = sander.pme_input() options.cut = 8.0 edict = pt.energy_decomposition(traj=traj, mm_options=options) assert_close(edict['bond'][0], 0., tol=3E-4) assert_close(edict['vdw'][0], 6028.9517, tol=3E-4) assert_close(edict['elec'][0], -45371.5995, tol=3E-4)
def sanderforce(self,parmstr,atmlst,boxflag=False,pmeflag=False): """Calculates energy and forces for a provided Amber parm string and set of coordinates using the Sander API. Also takes box dimensions and a flag for use of PME. Currently uses standard simulation options for gas phase or pme based on pmeflag. Only returns forces on first 2 atoms in atmlst Returns a sander energy object and a 3 x 2 x traj length array of forces with units""" self.forces=[] self.energies=[] # sander.APPLY_UNITS = True # More bugs/inconsistencies in pysander in amber15, may be fixed later indices = [a.idx for a in atmlst[:2]] if pmeflag is True: # These default options will be suitable in most cases # PME,cut=8.0,ntb=1,ntf=1,ntc=1 # Should be adapted if shake is required (not important here for ele) inp = sander.pme_input() else: inp = sander.gas_input() for i in range(0,self.traj.frame): coord = self.traj.coordinates[i] if boxflag is True: box = self.traj.box[i] # print box else: box = None with sander.setup(parmstr,coord,box=box,mm_options=inp): #Pass a string, else a temp parmfile is created that fills up tmp directory! ene,frc = sander.energy_forces(as_numpy=False) # pysander __init__ bug/inconsistency, can't use as_numpy! frc = np.asarray(frc) frc = np.reshape(frc,((len(frc)/3.),3)) frcslice = frc[indices] # Add units for forces: kcal mol-1 A-1 frcslice = frcslice * u.kilocalorie / (u.mole * u.angstroms) self.forces.append(frcslice) self.energies.append(ene)
def test_eneregy_and_force(): path = os.path.dirname(__file__) prmtop = path + '/vAla3.prmtop' rst7 = path + '/vAla3.rst7' with mdgx.setup(prmtop, rst7) as context: mdgx_energies, mdgx_forces = context.energy_forces() pme_input = sander.pme_input() parm = pmd.load_file(prmtop, rst7) with sander.setup(prmtop, rst7, box=parm.box, mm_options=pme_input): ene, sander_forces = sander.energy_forces() sander_enegies = dict((att, getattr(ene, att)) for att in dir(ene) if not att.startswith('_')) print("") print("potential energy") print("sander_enegies") print(sander_enegies['tot']) print("mdgx_energies") print(mdgx_energies['eptot']) print("") print('forces') print('sander_forces, first 5 atoms') print(sander_forces[:15]) print("") print('mdgx_forces, first 5 atoms') print(mdgx_forces.tolist()[:15]) aa_eq([sander_enegies['tot'],], [mdgx_energies['eptot'],], decimal=4)
group.add_argument('--cutoff', dest='cutoff', type=float, default=8, help='''Cutoff for nonbonded forces in Angstroms. Cutoff is always infinite for non-periodic systems''') group.add_argument('--platform', dest='platform', default='Reference', help='OpenMM platform to use. Default is %(default)s') args = parser.parse_args() # Get the Amber forces and energies if args.pbc: inp = sander.pme_input() inp.cut = args.cutoff inp.ntc = inp.ntf = 1 else: inp = sander.gas_input(args.igb) inp.cut = 1000 inp.rgbmax = 1000 with sander.setup(args.prmtop, args.inpcrd, None, inp) as context: e, f = sander.energy_forces() f = np.array(f).reshape((context.natom, 3)) # Get the OpenMM forces and energies parm = app.AmberPrmtopFile(args.prmtop) inpcrd = app.AmberInpcrdFile(args.inpcrd)
#! /usr/bin/env python import sander from chemistry.amber.readparm import AmberParm, Rst7 import numpy as np pdb = '3stl' parm = AmberParm('4amber_%s.prmtop' % pdb) #topo rst = Rst7.open('4amber_%s.rst7' % pdb) #box sander.setup(parm, rst.coordinates, rst.box, sander.pme_input()) ene, frc = sander.energy_forces() print ene.tot print max(frc) import code code.interact(local=dict(globals(), **locals())) sander.cleanup()
def energy(parm, args, output=sys.stdout): """ Compute a single-point energy using sander and print the result to the desired output Parameters ---------- parm : Structure args : ArgumentList output : file handler, default sys.stdout """ global HAS_SANDER if not HAS_SANDER: raise SimulationError('Could not import sander') cutoff = args.get_key_float('cutoff', None) igb = args.get_key_int('igb', 5) saltcon = args.get_key_float('saltcon', 0.0) do_ewald = args.has_key('Ewald') vdw_longrange = not args.has_key('nodisper') has_1264 = 'LENNARD_JONES_CCOEF' in parm.parm_data # Get any unmarked arguments unmarked_cmds = args.unmarked() if len(unmarked_cmds) > 0: warnings.warn("Un-handled arguments: " + ' '.join(unmarked_cmds), UnhandledArgumentWarning) if parm.ptr('ifbox') == 0: if not igb in (0, 1, 2, 5, 6, 7, 8): raise SimulationError('Bad igb value. Must be 0, 1, 2, 5, ' '6, 7, or 8') # Force vacuum electrostatics down the GB code path if igb == 0: igb = 6 inp = sander.gas_input(igb) if cutoff is None: cutoff = 1000.0 if cutoff <= 0: raise SimulationError('cutoff must be > 0') inp.cut = cutoff if saltcon < 0: raise SimulationError('salt concentration must be >= 0') inp.saltcon = saltcon elif parm.ptr('ifbox') > 0: inp = sander.pme_input() if cutoff is None: cutoff = 8.0 elif cutoff <= 0: raise SimulationError('cutoff must be > 0') inp.cut = cutoff inp.ew_type = int(do_ewald) inp.vdwmeth = int(vdw_longrange) inp.lj1264 = int(has_1264) if parm.coordinates is None: raise SimulationError('No coordinates are loaded') # Time to set up sander with sander.setup(parm, parm.coordinates, parm.box, inp): e, f = sander.energy_forces() if parm.chamber: output.write('Bond = %20.7f Angle = %20.7f\n' 'Dihedral = %20.7f Urey-Bradley = %20.7f\n' 'Improper = %20.7f ' % (e.bond, e.angle, e.dihedral, e.angle_ub, e.imp)) if parm.has_cmap: output.write('CMAP = %20.7f\n' % e.cmap) output.write('1-4 vdW = %20.7f 1-4 Elec. = %20.7f\n' 'Lennard-Jones = %20.7f Electrostatic = %20.7f\n' 'TOTAL = %20.7f\n' % (e.vdw_14, e.elec_14, e.vdw, e.elec, e.tot)) else: output.write( 'Bond = %20.7f Angle = %20.7f\n' 'Dihedral = %20.7f 1-4 vdW = %20.7f\n' '1-4 Elec = %20.7f vdWaals = %20.7f\n' 'Elec. = %20.7f' % (e.bond, e.angle, e.dihedral, e.vdw_14, e.elec_14, e.vdw, e.elec)) if igb != 0 and inp.ntb == 0: output.write(' Egb = %20.7f' % e.gb) elif e.hbond != 0: output.write(' EHbond = %20.7f' % e.hbond) output.write('\nTOTAL = %20.7f\n' % e.tot)
def energy(parm, args, output=sys.stdout): """ Compute a single-point energy using sander and print the result to the desired output """ global HAS_SANDER if not HAS_SANDER: raise SimulationError('Could not import sander') cutoff = args.get_key_float('cutoff', None) igb = args.get_key_int('igb', 5) saltcon = args.get_key_float('saltcon', 0.0) do_ewald = args.has_key('Ewald') vdw_longrange = not args.has_key('nodisper') has_1264 = 'LENNARD_JONES_CCOEF' in parm.parm_data # Get any unmarked arguments unmarked_cmds = args.unmarked() if len(unmarked_cmds) > 0: warnings.warn("Un-handled arguments: " + ' '.join(unmarked_cmds), UnhandledArgumentWarning) if parm.ptr('ifbox') == 0: if not igb in (0, 1, 2, 5, 6, 7, 8): raise SimulationError('Bad igb value. Must be 0, 1, 2, 5, ' '6, 7, or 8') # Force vacuum electrostatics down the GB code path if igb == 0: igb = 6 inp = sander.gas_input(igb) if cutoff is None: cutoff = 1000.0 if cutoff <= 0: raise SimulationError('cutoff must be > 0') inp.cut = cutoff if saltcon < 0: raise SimulationError('salt concentration must be >= 0') inp.saltcon = saltcon elif parm.ptr('ifbox') > 0: inp = sander.pme_input() if cutoff is None: cutoff = 8.0 elif cutoff <= 0: raise SimulationError('cutoff must be > 0') inp.cut = cutoff inp.ew_type = int(do_ewald) inp.vdwmeth = int(vdw_longrange) inp.lj1264 = int(has_1264) if parm.coordinates is None: raise SimulationError('No coordinates are loaded') # Time to set up sander with sander.setup(parm, parm.coordinates, parm.box, inp): e, f = sander.energy_forces() if parm.chamber: output.write('Bond = %20.7f Angle = %20.7f\n' 'Dihedral = %20.7f Urey-Bradley = %20.7f\n' 'Improper = %20.7f ' % (e.bond, e.angle, e.dihedral, e.angle_ub, e.imp)) if parm.has_cmap: output.write('CMAP = %20.7f\n' % e.cmap) output.write('1-4 vdW = %20.7f 1-4 Elec. = %20.7f\n' 'Lennard-Jones = %20.7f Electrostatic = %20.7f\n' 'TOTAL = %20.7f\n' % (e.vdw_14, e.elec_14, e.vdw, e.elec, e.tot)) else: output.write('Bond = %20.7f Angle = %20.7f\n' 'Dihedral = %20.7f 1-4 vdW = %20.7f\n' '1-4 Elec = %20.7f vdWaals = %20.7f\n' 'Elec. = %20.7f' % (e.bond, e.angle, e.dihedral, e.vdw_14, e.elec_14, e.vdw, e.elec)) if igb != 0 and inp.ntb == 0: output.write(' Egb = %20.7f' % e.gb) elif e.hbond != 0: output.write(' EHbond = %20.7f' % e.hbond) output.write('\nTOTAL = %20.7f\n' % e.tot)
import sander from parmed.amber.readparm import AmberParm, Rst7 import numpy as np import os, sys import pickle base = '1nie' # parm = AmberParm('4amber_%s.prmtop' %base) #topo rst = Rst7.open('4amber_%s.rst7' %base) #box coords1 = rst.coordinates coords2 = np.around( np.array(pickle.load(open('tmp2','rb') ) ), 3) #2nd coordinate set print coords1, coords1.shape print coords2, coords2.shape sander.setup('4amber_%s.prmtop' %base, rst.coordinates, rst.box, sander.pme_input()) ene, frc = sander.energy_forces() print frc[0] sander.set_positions(coords1) ene, frc = sander.energy_forces() print frc[0] sander.set_positions(coords2) ene, frc = sander.energy_forces() print frc[0] print max(frc) print ene.tot, ene.elec, ene.vdw # import code; code.interact(local=dict(globals(), **locals())) import boost.python
group.add_argument('--pbc', dest='pbc', default=False, action='store_true', help='Specify the use of periodic boundary conditions') group.add_argument('-g', '--igb', dest='igb', default=0, type=int, help='''GB model to use (see Amber manual). Default is %(default)s''') group.add_argument('--cutoff', dest='cutoff', type=float, default=8, help='''Cutoff for nonbonded forces in Angstroms. Cutoff is always infinite for non-periodic systems''') group.add_argument('--platform', dest='platform', default='Reference', help='OpenMM platform to use. Default is %(default)s') args = parser.parse_args() # Get the Amber forces and energies if args.pbc: inp = sander.pme_input() inp.cut = args.cutoff else: inp = sander.gas_input(args.igb) inp.cut = 1000 with sander.setup(args.prmtop, args.inpcrd, None, inp) as context: e, f = sander.energy_forces() f = np.array(f).reshape((context.natom, 3)) # Get the OpenMM forces and energies parm = app.AmberPrmtopFile(args.prmtop) inpcrd = app.AmberInpcrdFile(args.inpcrd) gbmap = collections.defaultdict(lambda: None) gbmap[1] = app.HCT
#! /usr/bin/env python import sander from chemistry.amber.readparm import AmberParm, Rst7 import numpy as np pdb ='3stl' parm = AmberParm('4amber_%s.prmtop' %pdb) #topo rst = Rst7.open('4amber_%s.rst7' %pdb) #box sander.setup(parm, rst.coordinates, rst.box, sander.pme_input()) ene, frc = sander.energy_forces() print ene.tot print max(frc) import code; code.interact(local=dict(globals(), **locals())) sander.cleanup()
#! /usr/bin/env python import sander from chemistry.amber.readparm import AmberParm, Rst7 from chemistry.structure import Structure, read_PDB, write_PDB import numpy as np parm = AmberParm('4amber_1cby.prmtop') pdb = read_PDB('new.pdb') rst = Rst7.open('4amber_1cby.rst7') xyz = pdb.pdbxyz[0] sander.setup(parm,xyz, rst.box, sander.pme_input()) sander.set_positions(xyz) ene, frc = sander.energy_forces() #~ import code; code.interact(local=dict(globals(), **locals())) sander.cleanup()