"wrappers/python/vscode:/vscode.git/clone" did not exist on "ce46b9b0f91f99951e6bb48099470e061cf7ff80"
Commit 855ece90 authored by leeping's avatar leeping
Browse files

Merge branch 'master' of https://github.com/SimTk/openmm

parents 471bea82 a42c55ad
...@@ -135,36 +135,38 @@ void ReferenceIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDI ...@@ -135,36 +135,38 @@ void ReferenceIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDI
const RealOpenMM twown = 2.0*nkT/hbar; const RealOpenMM twown = 2.0*nkT/hbar;
const RealOpenMM c1_0 = exp(-halfdt*integrator.getFriction()); const RealOpenMM c1_0 = exp(-halfdt*integrator.getFriction());
const RealOpenMM c2_0 = sqrt(1.0-c1_0*c1_0); const RealOpenMM c2_0 = sqrt(1.0-c1_0*c1_0);
for (int particle = 0; particle < numParticles; particle++) { if (integrator.getApplyThermostat()) {
if (system.getParticleMass(particle) == 0.0) for (int particle = 0; particle < numParticles; particle++) {
continue; if (system.getParticleMass(particle) == 0.0)
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle)); continue;
for (int component = 0; component < 3; component++) { const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int k = 0; k < numCopies; k++) for (int component = 0; component < 3; component++) {
v[k] = t_complex(scale*velocities[k][particle][component], 0.0); for (int k = 0; k < numCopies; k++)
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]); v[k] = t_complex(scale*velocities[k][particle][component], 0.0);
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]);
// Apply a local Langevin thermostat to the centroid mode.
v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber(); // Apply a local Langevin thermostat to the centroid mode.
// Use critical damping white noise for the remaining modes. v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
for (int k = 1; k <= numCopies/2; k++) { // Use critical damping white noise for the remaining modes.
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies); for (int k = 1; k <= numCopies/2; k++) {
const RealOpenMM c1 = exp(-2.0*wk*halfdt); const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0); const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle)); const RealOpenMM c1 = exp(-2.0*wk*halfdt);
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber(); const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber()); const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
v[k] = v[k]*c1 + t_complex(rand1, rand2); RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
if (k < numCopies-k) RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2); v[k] = v[k]*c1 + t_complex(rand1, rand2);
if (k < numCopies-k)
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2);
}
fftpack_exec_1d(fft, FFTPACK_BACKWARD, &v[0], &v[0]);
for (int k = 0; k < numCopies; k++)
velocities[k][particle][component] = scale*v[k].re;
} }
fftpack_exec_1d(fft, FFTPACK_BACKWARD, &v[0], &v[0]);
for (int k = 0; k < numCopies; k++)
velocities[k][particle][component] = scale*v[k].re;
} }
} }
...@@ -220,36 +222,38 @@ void ReferenceIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDI ...@@ -220,36 +222,38 @@ void ReferenceIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDI
// Apply the PILE-L thermostat again. // Apply the PILE-L thermostat again.
for (int particle = 0; particle < numParticles; particle++) { if (integrator.getApplyThermostat()) {
if (system.getParticleMass(particle) == 0.0) for (int particle = 0; particle < numParticles; particle++) {
continue; if (system.getParticleMass(particle) == 0.0)
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle)); continue;
for (int component = 0; component < 3; component++) { const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int k = 0; k < numCopies; k++) for (int component = 0; component < 3; component++) {
v[k] = t_complex(scale*velocities[k][particle][component], 0.0); for (int k = 0; k < numCopies; k++)
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]); v[k] = t_complex(scale*velocities[k][particle][component], 0.0);
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]);
// Apply a local Langevin thermostat to the centroid mode.
v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber(); // Apply a local Langevin thermostat to the centroid mode.
// Use critical damping white noise for the remaining modes. v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
for (int k = 1; k <= numCopies/2; k++) { // Use critical damping white noise for the remaining modes.
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies); for (int k = 1; k <= numCopies/2; k++) {
const RealOpenMM c1 = exp(-2.0*wk*halfdt); const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0); const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle)); const RealOpenMM c1 = exp(-2.0*wk*halfdt);
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber(); const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber()); const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
v[k] = v[k]*c1 + t_complex(rand1, rand2); RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
if (k < numCopies-k) RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2); v[k] = v[k]*c1 + t_complex(rand1, rand2);
if (k < numCopies-k)
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2);
}
fftpack_exec_1d(fft, FFTPACK_BACKWARD, &v[0], &v[0]);
for (int k = 0; k < numCopies; k++)
velocities[k][particle][component] = scale*v[k].re;
} }
fftpack_exec_1d(fft, FFTPACK_BACKWARD, &v[0], &v[0]);
for (int k = 0; k < numCopies; k++)
velocities[k][particle][component] = scale*v[k].re;
} }
} }
......
...@@ -313,12 +313,78 @@ void testContractions() { ...@@ -313,12 +313,78 @@ void testContractions() {
ASSERT_USUALLY_EQUAL_TOL(expectedKE, meanKE, 1e-2); ASSERT_USUALLY_EQUAL_TOL(expectedKE, meanKE, 1e-2);
} }
void testWithoutThermostat() {
const int numParticles = 20;
const int numCopies = 10;
const double temperature = 300.0;
const double mass = 2.0;
// Create a chain of particles.
System system;
HarmonicBondForce* bonds = new HarmonicBondForce();
system.addForce(bonds);
for (int i = 0; i < numParticles; i++) {
system.addParticle(mass);
if (i > 0)
bonds->addBond(i-1, i, 1.0, 1000.0);
}
RPMDIntegrator integ(numCopies, temperature, 1.0, 0.001);
integ.setApplyThermostat(false);
Platform& platform = Platform::getPlatformByName("Reference");
Context context(system, integ, platform);
OpenMM_SFMT::SFMT sfmt;
init_gen_rand(0, sfmt);
vector<vector<Vec3> > positions(numCopies);
for (int i = 0; i < numCopies; i++) {
positions[i].resize(numParticles);
for (int j = 0; j < numParticles; j++)
positions[i][j] = Vec3(0.95*j, 0.01*genrand_real2(sfmt), 0.01*genrand_real2(sfmt));
integ.setPositions(i, positions[i]);
}
// Simulate it and see if the energy remains constant.
double initialEnergy;
int numSteps = 100;
const double hbar = 1.054571628e-34*AVOGADRO/(1000*1e-12);
const double wn = numCopies*BOLTZ*temperature/hbar;
const double springConstant = mass*wn*wn;
for (int i = 0; i < numSteps; i++) {
integ.step(1);
// Sum the energies of all the copies.
double energy = 0.0;
for (int j = 0; j < numCopies; j++) {
State state = integ.getState(j, State::Positions | State::Energy);
positions[j] = state.getPositions();
energy += state.getPotentialEnergy()+state.getKineticEnergy();
}
// Add the energy from the springs connecting copies.
for (int j = 0; j < numCopies; j++) {
int previous = (j == 0 ? numCopies-1 : j-1);
for (int k = 0; k < numParticles; k++) {
Vec3 delta = positions[j][k]-positions[previous][k];
energy += 0.5*springConstant*delta.dot(delta);
}
}
if (i == 0)
initialEnergy = energy;
else
ASSERT_EQUAL_TOL(initialEnergy, energy, 1e-4);
}
}
int main() { int main() {
try { try {
testFreeParticles(); testFreeParticles();
testCMMotionRemoval(); testCMMotionRemoval();
testVirtualSites(); testVirtualSites();
testContractions(); testContractions();
testWithoutThermostat();
} }
catch(const std::exception& e) { catch(const std::exception& e) {
std::cout << "exception: " << e.what() << std::endl; std::cout << "exception: " << e.what() << std::endl;
......
...@@ -56,6 +56,12 @@ void verifyEvaluation(const string& expression, double expectedValue) { ...@@ -56,6 +56,12 @@ void verifyEvaluation(const string& expression, double expectedValue) {
ExpressionProgram program = parsed.createProgram(); ExpressionProgram program = parsed.createProgram();
value = program.evaluate(); value = program.evaluate();
ASSERT_EQUAL_TOL(expectedValue, value, 1e-10); ASSERT_EQUAL_TOL(expectedValue, value, 1e-10);
// Create a CompiledExpression and see if that also gives the same result.
CompiledExpression compiled = parsed.createCompiledExpression();
value = compiled.evaluate();
ASSERT_EQUAL_TOL(expectedValue, value, 1e-10);
} }
/** /**
...@@ -86,6 +92,16 @@ void verifyEvaluation(const string& expression, double x, double y, double expec ...@@ -86,6 +92,16 @@ void verifyEvaluation(const string& expression, double x, double y, double expec
value = program.evaluate(variables); value = program.evaluate(variables);
ASSERT_EQUAL_TOL(expectedValue, value, 1e-10); ASSERT_EQUAL_TOL(expectedValue, value, 1e-10);
// Create a CompiledExpression and see if that also gives the same result.
CompiledExpression compiled = parsed.createCompiledExpression();
if (compiled.getVariables().find("x") != compiled.getVariables().end())
compiled.getVariableReference("x") = x;
if (compiled.getVariables().find("y") != compiled.getVariables().end())
compiled.getVariableReference("y") = y;
value = compiled.evaluate();
ASSERT_EQUAL_TOL(expectedValue, value, 1e-10);
// Make sure that variable renaming works. // Make sure that variable renaming works.
variables.clear(); variables.clear();
......
...@@ -85,6 +85,7 @@ version = '%(version)s' ...@@ -85,6 +85,7 @@ version = '%(version)s'
full_version = '%(full_version)s' full_version = '%(full_version)s'
git_revision = '%(git_revision)s' git_revision = '%(git_revision)s'
release = %(isrelease)s release = %(isrelease)s
openmm_library_path = '%(path)s'
if not release: if not release:
version = full_version version = full_version
...@@ -113,7 +114,8 @@ if not release: ...@@ -113,7 +114,8 @@ if not release:
a.write(cnt % {'version': version, a.write(cnt % {'version': version,
'full_version' : full_version, 'full_version' : full_version,
'git_revision' : git_revision, 'git_revision' : git_revision,
'isrelease': str(IS_RELEASED)}) 'isrelease': str(IS_RELEASED),
'path': os.getenv('OPENMM_LIB_PATH')})
finally: finally:
a.close() a.close()
...@@ -197,7 +199,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM, ...@@ -197,7 +199,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM,
macVersion = [int(x) for x in platform.mac_ver()[0].split('.')] macVersion = [int(x) for x in platform.mac_ver()[0].split('.')]
if tuple(macVersion) < (10, 6): if tuple(macVersion) < (10, 6):
os.environ['MACOSX_DEPLOYMENT_TARGET']='10.5' os.environ['MACOSX_DEPLOYMENT_TARGET']='10.5'
extra_link_args.append('-Wl,-rpath,@loader_path/OpenMM') extra_link_args.append('-Wl,-rpath,'+openmm_lib_path)
library_dirs=[openmm_lib_path] library_dirs=[openmm_lib_path]
...@@ -209,6 +211,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM, ...@@ -209,6 +211,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM,
include_dirs = include_dirs, include_dirs = include_dirs,
define_macros = define_macros, define_macros = define_macros,
library_dirs = library_dirs, library_dirs = library_dirs,
runtime_library_dirs = library_dirs,
libraries = libraries, libraries = libraries,
extra_compile_args=extra_compile_args, extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args, extra_link_args=extra_link_args,
...@@ -238,8 +241,8 @@ def main(): ...@@ -238,8 +241,8 @@ def main():
uninstall() uninstall()
except: except:
pass pass
writeVersionPy()
setupKeywords=buildKeywordDictionary() setupKeywords=buildKeywordDictionary()
writeVersionPy()
setup(**setupKeywords) setup(**setupKeywords)
if __name__ == '__main__': if __name__ == '__main__':
......
...@@ -13,7 +13,7 @@ It also tries to load any plugin modules it can find. ...@@ -13,7 +13,7 @@ It also tries to load any plugin modules it can find.
__author__ = "Randall J. Radmer" __author__ = "Randall J. Radmer"
import os, sys, glob import os, sys, glob, os.path
if sys.platform == "win32": if sys.platform == "win32":
libPrefix="" libPrefix=""
libExt="dll" libExt="dll"
...@@ -34,5 +34,9 @@ else: ...@@ -34,5 +34,9 @@ else:
from simtk.openmm.openmm import * from simtk.openmm.openmm import *
from simtk.openmm.vec3 import Vec3 from simtk.openmm.vec3 import Vec3
pluginLoadedLibNames = Platform.loadPluginsFromDirectory(Platform.getDefaultPluginsDirectory()) from simtk.openmm import version
if os.getenv('OPENMM_PLUGIN_DIR') is None and os.path.isdir(version.openmm_library_path):
pluginLoadedLibNames = Platform.loadPluginsFromDirectory(os.path.join(version.openmm_library_path, 'plugins'))
else:
pluginLoadedLibNames = Platform.loadPluginsFromDirectory(Platform.getDefaultPluginsDirectory())
__version__ = Platform.getOpenMMVersion() __version__ = Platform.getOpenMMVersion()
...@@ -24,6 +24,7 @@ from dcdreporter import DCDReporter ...@@ -24,6 +24,7 @@ from dcdreporter import DCDReporter
from modeller import Modeller from modeller import Modeller
from statedatareporter import StateDataReporter from statedatareporter import StateDataReporter
from element import Element from element import Element
from desmonddmsfile import DesmondDMSFile
# Enumerated values # Enumerated values
......
'''
desmonddmsfile.py: Load Desmond dms files
Portions copyright (c) 2013 Stanford University and the Authors
Authors: Robert McGibbon
Contributors:
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
THE AUTHORS, CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
USE OR OTHER DEALINGS IN THE SOFTWARE.
'''
import os
import math
from simtk import openmm as mm
from simtk.openmm.app import forcefield as ff
from simtk.openmm.app import Element, Topology, PDBFile
from simtk.openmm.app.element import hydrogen
from simtk.unit import (nanometer, angstrom, dalton, radian,
kilocalorie_per_mole, kilojoule_per_mole,
degree, elementary_charge)
class DesmondDMSFile(object):
'''DesmondDMSFile parses a Desmond DMS (desmond molecular system) and
constructs a topology and (optionally) an OpenMM System from it
'''
def __init__(self, file):
'''Load a DMS file
Parameters:
- file (string) the name of the file to load
'''
# sqlite3 is included in the standard lib, but at python
# compile time, you can disable support (I think), so it's
# not *guarenteed* to be available. Doing the import here
# means we only raise an ImportError if people try to use
# this class, so the module can be safely imported
import sqlite3
self._open = False
self._tables = None
if not os.path.exists(str(file)):
raise IOError("No such file or directory: '%s'" % str(file))
self._conn = sqlite3.connect(file)
self._open = True
self._readSchemas()
if len(self._tables) == 0:
raise IOError('DMS file was not loaded sucessfully. No tables found')
if 'nbtype' not in self._tables['particle']:
raise ValueError('No nonbonded parameters associated with this '
'DMS file. You can add a forcefield with the '
'viparr command line tool distributed with desmond')
# build the provenance string
provenance = []
q = '''SELECT id, user, timestamp, version, workdir, cmdline, executable
FROM provenance'''
#for id, user, timestamp, version, workdir, cmdline, executable in self._conn.execute(q):
for row in self._conn.execute('SELECT * FROM provenance'):
rowdict = dict(zip(self._tables['provenance'], row))
provenance.append('%(id)d) %(timestamp)s: %(user)s\n version: %(version)s\n '
'cmdline: %(cmdline)s\n executable: %(executable)s\n' % rowdict)
self.provenance = ''.join(provenance)
# Build the topology
self.topology, self.positions = self._createTopology()
self._topologyAtoms = list(self.topology.atoms())
self._atomBonds = [{} for x in range(len(self._topologyAtoms))]
self._angleConstraints = [{} for x in range(len(self._topologyAtoms))]
def getPositions(self):
'''Get the positions of each atom in the system
'''
return self.positions
def getTopology(self):
'''Get the topology of the system
'''
return self.topology
def getProvenance(self):
'''Get the provenance string of this system
'''
return self.provenance
def _createTopology(self):
'''Build the topology of the system
'''
top = Topology()
positions = []
boxVectors = []
for x, y, z in self._conn.execute('SELECT x, y, z FROM global_cell'):
boxVectors.append(mm.Vec3(x, y, z))
unitCellDimensions = [boxVectors[0][0], boxVectors[1][1], boxVectors[2][2]]
top.setUnitCellDimensions(unitCellDimensions*angstrom)
atoms = {}
lastChain = None
lastResId = None
c = top.addChain()
q = '''SELECT id, name, anum, resname, resid, chain, x, y, z
FROM particle'''
for (atomId, atomName, atomNumber, resName, resId, chain, x, y, z) in self._conn.execute(q):
newChain = False
if chain != lastChain:
lastChain = chain
c = top.addChain()
newChain = True
if resId != lastResId or newChain:
lastResId = resId
if resName in PDBFile._residueNameReplacements:
resName = PDBFile._residueNameReplacements[resName]
r = top.addResidue(resName, c)
if resName in PDBFile._atomNameReplacements:
atomReplacements = PDBFile._atomNameReplacements[resName]
else:
atomReplacements = {}
if atomNumber == 0 and atomName.startswith('Vrt'):
elem = None
else:
elem = Element.getByAtomicNumber(atomNumber)
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
atoms[atomId] = top.addAtom(atomName, elem, r)
positions.append(mm.Vec3(x, y, z))
for p0, p1 in self._conn.execute('SELECT p0, p1 FROM bond'):
top.addBond(atoms[p0], atoms[p1])
positions = positions*angstrom
return top, positions
def createSystem(self, nonbondedMethod=ff.NoCutoff, nonbondedCutoff=1.0*nanometer,
ewaldErrorTolerance=0.0005, removeCMMotion=True, hydrogenMass=None):
'''Construct an OpenMM System representing the topology described by this dms file
Parameters:
- nonbondedMethod (object=NoCutoff) The method to use for nonbonded interactions. Allowed values are
NoCutoff, CutoffNonPeriodic, CutoffPeriodic, Ewald, or PME.
- nonbondedCutoff (distance=1*nanometer) The cutoff distance to use for nonbonded interactions
- ewaldErrorTolerance (float=0.0005) The error tolerance to use if nonbondedMethod is Ewald or PME.
- removeCMMotion (boolean=True) If true, a CMMotionRemover will be added to the System
- hydrogenMass (mass=None) The mass to use for hydrogen atoms bound to heavy atoms. Any mass added to a hydrogen is
subtracted from the heavy atom to keep their total mass the same.
'''
self._checkForUnsupportedTerms()
sys = mm.System()
# Buld the box dimensions
sys = mm.System()
boxSize = self.topology.getUnitCellDimensions()
if boxSize is not None:
sys.setDefaultPeriodicBoxVectors((boxSize[0], 0, 0), (0, boxSize[1], 0), (0, 0, boxSize[2]))
elif nonbondedMethod in (ff.CutoffPeriodic, ff.Ewald, ff.PME):
raise ValueError('Illegal nonbonded method for a non-periodic system')
# Create all of the particles
for mass in self._conn.execute('SELECT mass from particle'):
sys.addParticle(mass[0]*dalton)
# Add all of the forces
self._addBondsToSystem(sys)
self._addAnglesToSystem(sys)
self._addConstraintsToSystem(sys)
self._addPeriodicTorsionsToSystem(sys)
self._addImproperHarmonicTorsionsToSystem(sys)
self._addCMAPToSystem(sys)
self._addVirtualSitesToSystem(sys)
nb = self._addNonbondedForceToSystem(sys)
# Finish configuring the NonbondedForce.
methodMap = {ff.NoCutoff:mm.NonbondedForce.NoCutoff,
ff.CutoffNonPeriodic:mm.NonbondedForce.CutoffNonPeriodic,
ff.CutoffPeriodic:mm.NonbondedForce.CutoffPeriodic,
ff.Ewald:mm.NonbondedForce.Ewald,
ff.PME:mm.NonbondedForce.PME}
nb.setNonbondedMethod(methodMap[nonbondedMethod])
nb.setCutoffDistance(nonbondedCutoff)
nb.setEwaldErrorTolerance(ewaldErrorTolerance)
# Adjust masses.
if hydrogenMass is not None:
for atom1, atom2 in self.topology.bonds():
if atom1.element == hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == hydrogen and atom1.element not in (hydrogen, None):
transferMass = hydrogenMass-sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
sys.setParticleMass(atom1.index, sys.getParticleMass(atom1.index)-transferMass)
# Add a CMMotionRemover.
if removeCMMotion:
sys.addForce(mm.CMMotionRemover())
return sys
def _addBondsToSystem(self, sys):
'''Create the harmonic bonds
'''
bonds = mm.HarmonicBondForce()
sys.addForce(bonds)
q = '''SELECT p0, p1, r0, fc, constrained
FROM stretch_harm_term INNER JOIN stretch_harm_param
ON stretch_harm_term.param=stretch_harm_param.id'''
for p0, p1, r0, fc, constrained in self._conn.execute(q):
if constrained:
sys.addConstraint(p0, p1, r0*angstrom)
else:
# Desmond writes the harmonic bond force without 1/2
# so we need to to double the force constant
bonds.addBond(p0, p1, r0*angstrom, 2*fc*kilocalorie_per_mole/angstrom**2)
# Record information that will be needed for constraining angles.
self._atomBonds[p0][p1] = r0*angstrom
self._atomBonds[p1][p0] = r0*angstrom
return bonds
def _addAnglesToSystem(self, sys):
'''Create the harmonic angles
'''
angles = mm.HarmonicAngleForce()
sys.addForce(angles)
degToRad = math.pi/180
q = '''SELECT p0, p1, p2, theta0, fc, constrained
FROM angle_harm_term INNER JOIN angle_harm_param
ON angle_harm_term.param=angle_harm_param.id'''
for p0, p1, p2, theta0, fc, constrained in self._conn.execute(q):
if constrained:
l1 = self._atomBonds[p1][p0]
l2 = self._atomBonds[p1][p2]
length = (l1*l1 + l2*l2 - 2*l1*l2*math.cos(theta0*degToRad)).sqrt()
sys.addConstraint(p0, p2, length)
self._angleConstraints[p1][p0] = p2
self._angleConstraints[p1][p2] = p0
else:
# Desmond writes the harmonic angle force without 1/2
# so we need to to double the force constant
angles.addAngle(p0, p1, p2, theta0*degToRad, 2*fc*kilocalorie_per_mole/radian**2)
return angles
def _addConstraintsToSystem(self, sys):
'''Add constraints to system. Normally these should already be
added by the bonds table, but we want to make sure that there's
no extra information in the constraints table that we're not
including in the system'''
for term_table in [n for n in self._tables.keys() if n.startswith('constraint_a') and n.endswith('term')]:
param_table = term_table.replace('term', 'param')
q = '''SELECT p0, p1, r1
FROM %(term)s INNER JOIN %(param)s
ON %(term)s.param=%(param)s.id''' % \
{'term': term_table, 'param': param_table}
for p0, p1, r1 in self._conn.execute(q):
if not p1 in self._atomBonds[p0]:
sys.addConstraint(p0, p1, r1*angstrom)
self._atomBonds[p0][p1] = r1*angstrom
self._atomBonds[p1][p0] = r1*angstrom
if 'constraint_hoh_term' in self._tables:
degToRad = math.pi/180
q = '''SELECT p0, p1, p2, r1, r2, theta
FROM constraint_hoh_term INNER JOIN constraint_hoh_param
ON constraint_hoh_term.param=constraint_hoh_param.id'''
for p0, p1, p2, r1, r2, theta in self._conn.execute(q):
# Here, p0 is the heavy atom and p1 and p2 are the H1 and H2
# wihth O-H1 and O-H2 distances r1 and r2
if not (self._angleConstraints[p0].get(p1, None) == p2):
length = (r1*r1 + r2*r2 - 2*r1*r2*math.cos(theta*degToRad)).sqrt()
sys.addConstraint(p1, p2, length)
def _addPeriodicTorsionsToSystem(self, sys):
'''Create the torsion terms
'''
periodic = mm.PeriodicTorsionForce()
sys.addForce(periodic)
q = '''SELECT p0, p1, p2, p3, phi0, fc0, fc1, fc2, fc3, fc4, fc5, fc6
FROM dihedral_trig_term INNER JOIN dihedral_trig_param
ON dihedral_trig_term.param=dihedral_trig_param.id'''
for p0, p1, p2, p3, phi0, fc0, fc1, fc2, fc3, fc4, fc5, fc6 in self._conn.execute(q):
for order, fc in enumerate([fc0, fc1, fc2, fc3, fc4, fc5, fc6]):
if fc == 0:
continue
periodic.addTorsion(p0, p1, p2, p3, order, phi0*degree, fc*kilocalorie_per_mole)
def _addImproperHarmonicTorsionsToSystem(self, sys):
'''Create the improper harmonic torsion terms
'''
if not self._hasTable('improper_harm_term'):
return
harmonicTorsion = mm.CustomTorsionForce('k*(theta-theta0)^2')
harmonicTorsion.addPerTorsionParameter('theta0')
harmonicTorsion.addPerTorsionParameter('k')
sys.addForce(harmonicTorsion)
q = '''SELECT p0, p1, p2, p3, phi0, fc
FROM improper_harm_term INNER JOIN improper_harm_param
ON improper_harm_term.param=improper_harm_param.id'''
for p0, p1, p2, p3, phi0, fc in self._conn.execute(q):
harmonicTorsion.addTorsion(p0, p1, p2, p3, [phi0*degree, fc*kilocalorie_per_mole])
def _addCMAPToSystem(self, sys):
'''Create the CMAP terms
'''
if not self._hasTable('torsiontorsion_cmap_term'):
return
# Create CMAP torsion terms
cmap = mm.CMAPTorsionForce()
sys.addForce(cmap)
cmap_indices = {}
for name in [k for k in self._tables.keys() if k.startswith('cmap')]:
size2 = self._conn.execute('SELECT COUNT(*) FROM %s' % name).fetchone()[0]
fsize = math.sqrt(size2)
if fsize != int(fsize):
raise ValueError('Non-square CMAPs are not supported')
size = int(fsize)
map = [0 for i in range(size2)]
for phi, psi, energy in self._conn.execute("SELECT phi, psi, energy FROM %s" % name):
i = int((phi % 360) / (360.0 / size))
j = int((psi % 360) / (360.0 / size))
map[i+size*j] = energy
index = cmap.addMap(size, map*kilocalorie_per_mole)
cmap_indices[name] = index
q = '''SELECT p0, p1, p2, p3, p4, p5, p6, p7, cmapid
FROM torsiontorsion_cmap_term INNER JOIN torsiontorsion_cmap_param
ON torsiontorsion_cmap_term.param=torsiontorsion_cmap_param.id'''
for p0, p1, p2, p3, p4, p5, p6, p7, cmapid in self._conn.execute(q):
cmap.addTorsion(cmap_indices[cmapid], p0, p1, p2, p3, p4, p5, p6, p7)
def _addNonbondedForceToSystem(self, sys):
'''Create the nonbonded force
'''
nb = mm.NonbondedForce()
sys.addForce(nb)
q = '''SELECT charge, sigma, epsilon
FROM particle INNER JOIN nonbonded_param
ON particle.nbtype=nonbonded_param.id'''
for charge, sigma, epsilon in self._conn.execute(q):
nb.addParticle(charge, sigma*angstrom, epsilon*kilocalorie_per_mole)
for p0, p1 in self._conn.execute('SELECT p0, p1 FROM exclusion'):
nb.addException(p0, p1, 0.0, 1.0, 0.0)
q = '''SELECT p0, p1, aij, bij, qij
FROM pair_12_6_es_term INNER JOIN pair_12_6_es_param
ON pair_12_6_es_term.param=pair_12_6_es_param.id;'''
for p0, p1, a_ij, b_ij, q_ij in self._conn.execute(q):
a_ij = (a_ij*kilocalorie_per_mole*(angstrom**12)).in_units_of(kilojoule_per_mole*(nanometer**12))
b_ij = (b_ij*kilocalorie_per_mole*(angstrom**6)).in_units_of(kilojoule_per_mole*(nanometer**6))
q_ij = q_ij*elementary_charge**2
if (b_ij._value == 0.0) or (a_ij._value == 0.0):
new_epsilon = 0
new_sigma = 1
else:
new_epsilon = b_ij**2/(4*a_ij)
new_sigma = (a_ij / b_ij)**(1.0/6.0)
nb.addException(p0, p1, q_ij, new_sigma, new_epsilon, True)
n_total = self._conn.execute('''SELECT COUNT(*) FROM pair_12_6_es_term''').fetchone()
n_in_exclusions = self._conn.execute('''SELECT COUNT(*)
FROM exclusion INNER JOIN pair_12_6_es_term
ON exclusion.p0==pair_12_6_es_term.p0 AND exclusion.p1==pair_12_6_es_term.p1''').fetchone()
if not n_total == n_in_exclusions:
raise NotImplementedError('All pair_12_6_es_terms must have a corresponding exclusion')
return nb
def _addVirtualSitesToSystem(self, sys):
'''Create any virtual sites in the systempy
'''
if not any(t.startswith('virtual_') for t in self._tables.keys()):
return
if 'virtual_lc2_term' in self._tables:
q = '''SELECT p0, p1, p2, c1
FROM virtual_lc2_term INNER JOIN virtual_lc2_param
ON virtual_lc2_term.param=virtual_lc2_param.id'''
for p0, p1, p2, c1 in self._conn.execute(q):
vsite = mm.TwoParticleAverageSite(p1, p2, (1-c1), c1)
sys.setVirtualSite(p0, vsite)
if 'virtual_lc3_term' in self._tables:
q = '''SELECT p0, p1, p2, p3, c1, c2
FROM virtual_lc3_term INNER JOIN virtual_lc3_param
ON virtual_lc3_term.param=virtual_lc3_param.id'''
for p0, p1, p2, p3, c1, c2 in self._conn.execute(q):
vsite = mm.ThreeParticleAverageSite(p1, p2, p3, (1-c1-c2), c1, c2)
sys.setVirtualSite(p0, vsite)
if 'virtual_out3_term' in self._tables:
q = '''SELECT p0, p1, p2, p3, c1, c2, c3
FROM virtual_out3_term INNER JOIN virtual_out3_param
ON virtual_out3_term.param=virtual_out3_param.id'''
for p0, p1, p2, p3, c1, c2, c3 in self._conn.execute(q):
vsite = mm.OutOfPlaneSite(p1, p2, p3, c1, c2, c3)
sys.setVirtualSite(p0, vsite)
if 'virtual_fdat3_term' in self._tables:
raise NotImplementedError('OpenMM does not currently support '
'fdat3-style virtual sites')
def _hasTable(self, table_name):
'''Does our DMS file contain this table?
'''
return table_name in self._tables
def _readSchemas(self):
'''Read the schemas of each of the tables in the dms file, populating
the `_tables` instance attribute
'''
tables = {}
for table in self._conn.execute("SELECT name FROM sqlite_master WHERE type='table'"):
names = []
for e in self._conn.execute('PRAGMA table_info(%s)' % table):
names.append(str(e[1]))
tables[str(table[0])] = names
self._tables = tables
def _checkForUnsupportedTerms(self):
'''Check the file for forcefield terms that are not currenty supported,
raising a NotImplementedError
'''
if 'posre_harm_term' in self._tables:
raise NotImplementedError('Position restraints are not implemented.')
flat_bottom_potential_terms = ['stretch_fbhw_term', 'angle_fbhw_term',
'improper_fbhw_term', 'posre_fbhw_term']
if any((t in self._tables) for t in flat_bottom_potential_terms):
raise NotImplementedError('Flat bottom potential terms '
'are not implemeneted')
nbinfo = dict(zip(self._tables['nonbonded_info'],
self._conn.execute('SELECT * FROM nonbonded_info').fetchone()))
if nbinfo['vdw_funct'] != u'vdw_12_6':
raise NotImplementedError('Only Leonard-Jones van der Waals '
'interactions are currently supported')
if nbinfo['vdw_rule'] != u'arithmetic/geometric':
raise NotImplementedError('Only Lorentz-Berthelot nonbonded '
'combining rules are currently supported')
if 'nonbonded_combined_param' in self._tables:
raise NotImplementedError('nonbonded_combined_param interactions '
'are not currently supported')
if 'alchemical_particle' in self._tables:
raise NotImplementedError('Alchemical particles are not supported')
if 'alchemical_stretch_harm' in self._tables:
raise NotImplementedError('Alchemical bonds are not supported')
if 'polar_term' in self._tables:
if self._conn.execute("SELECT COUNT(*) FROM polar_term").fetchone()[0] != 0:
raise NotImplementedError('Drude particles are not currently supported')
def close(self):
'''Close the SQL connection
'''
if self._open:
self._conn.close()
def __del__(self):
self.close()
...@@ -44,6 +44,7 @@ class Element: ...@@ -44,6 +44,7 @@ class Element:
look up the Element with a particular chemical symbol.""" look up the Element with a particular chemical symbol."""
_elements_by_symbol = {} _elements_by_symbol = {}
_elements_by_atomic_number = {}
def __init__(self, number, name, symbol, mass): def __init__(self, number, name, symbol, mass):
## The atomic number of the element ## The atomic number of the element
...@@ -58,6 +59,16 @@ class Element: ...@@ -58,6 +59,16 @@ class Element:
s = symbol.strip().upper() s = symbol.strip().upper()
assert s not in Element._elements_by_symbol assert s not in Element._elements_by_symbol
Element._elements_by_symbol[s] = self Element._elements_by_symbol[s] = self
if number in Element._elements_by_atomic_number:
other_element = Element._elements_by_atomic_number[number]
if mass < other_element.mass:
# If two "elements" share the same atomic number, they're
# probably hydrogen and deuterium, and we want to choose
# the lighter one to put in the table by atomic_number,
# since it's the "canonical" element.
Element._elements_by_atomic_number[number] = self
else:
Element._elements_by_atomic_number[number] = self
@staticmethod @staticmethod
def getBySymbol(symbol): def getBySymbol(symbol):
...@@ -65,6 +76,10 @@ class Element: ...@@ -65,6 +76,10 @@ class Element:
s = symbol.strip().upper() s = symbol.strip().upper()
return Element._elements_by_symbol[s] return Element._elements_by_symbol[s]
@staticmethod
def getByAtomicNumber(atomic_number):
return Element._elements_by_atomic_number[atomic_number]
# This is for backward compatibility. # This is for backward compatibility.
def get_by_symbol(symbol): def get_by_symbol(symbol):
s = symbol.strip().upper() s = symbol.strip().upper()
......
...@@ -40,6 +40,7 @@ import simtk.unit as unit ...@@ -40,6 +40,7 @@ import simtk.unit as unit
import simtk.openmm as mm import simtk.openmm as mm
import math import math
import os import os
import distutils
HBonds = ff.HBonds HBonds = ff.HBonds
AllBonds = ff.AllBonds AllBonds = ff.AllBonds
...@@ -90,6 +91,9 @@ class GromacsTopFile(object): ...@@ -90,6 +91,9 @@ class GromacsTopFile(object):
# A preprocessor command. # A preprocessor command.
fields = stripped.split() fields = stripped.split()
command = fields[0] command = fields[0]
if len(self._ifStack) != len(self._elseStack):
raise RuntimeError('#if/#else stack out of sync')
if command == '#include' and not ignore: if command == '#include' and not ignore:
# Locate the file to include # Locate the file to include
name = stripped[len(command):].strip(' \t"<>') name = stripped[len(command):].strip(' \t"<>')
...@@ -116,17 +120,29 @@ class GromacsTopFile(object): ...@@ -116,17 +120,29 @@ class GromacsTopFile(object):
raise ValueError('Illegal line in .top file: '+line) raise ValueError('Illegal line in .top file: '+line)
name = fields[1] name = fields[1]
self._ifStack.append(name in self._defines) self._ifStack.append(name in self._defines)
self._elseStack.append(False)
elif command == '#ifndef': elif command == '#ifndef':
# See whether this block should be ignored. # See whether this block should be ignored.
if len(fields) < 2: if len(fields) < 2:
raise ValueError('Illegal line in .top file: '+line) raise ValueError('Illegal line in .top file: '+line)
name = fields[1] name = fields[1]
self._ifStack.append(name not in self._defines) self._ifStack.append(name not in self._defines)
self._elseStack.append(False)
elif command == '#endif': elif command == '#endif':
# Pop an entry off the if stack. # Pop an entry off the if stack.
if len(self._ifStack) == 0: if len(self._ifStack) == 0:
raise ValueError('Unexpected line in .top file: '+line) raise ValueError('Unexpected line in .top file: '+line)
del(self._ifStack[-1]) del(self._ifStack[-1])
del(self._elseStack[-1])
elif command == '#else':
# Reverse the last entry on the if stack
if len(self._ifStack) == 0:
raise ValueError('Unexpected line in .top file: '+line)
if self._elseStack[-1]:
raise ValueError('Unexpected line in .top file: '
'#else has already been used ' + line)
self._ifStack[-1] = (not self._ifStack[-1])
self._elseStack[-1] = True
elif not ignore: elif not ignore:
# A line of data for the current category # A line of data for the current category
...@@ -342,16 +358,20 @@ class GromacsTopFile(object): ...@@ -342,16 +358,20 @@ class GromacsTopFile(object):
raise ValueError('Unsupported function type in [ cmaptypes ] line: '+line); raise ValueError('Unsupported function type in [ cmaptypes ] line: '+line);
self._cmapTypes[tuple(fields[:5])] = fields self._cmapTypes[tuple(fields[:5])] = fields
def __init__(self, file, unitCellDimensions=None, includeDir='/usr/local/gromacs/share/gromacs/top', defines={}): def __init__(self, file, unitCellDimensions=None, includeDir=None, defines={}):
"""Load a top file. """Load a top file.
Parameters: Parameters:
- file (string) the name of the file to load - file (string) the name of the file to load
- unitCellDimensions (Vec3=None) the dimensions of the crystallographic unit cell - unitCellDimensions (Vec3=None) the dimensions of the crystallographic unit cell
- includeDir (string=/usr/local/gromacs/share/gromacs/top) a directory in which to look for other files - includeDir (string=None) A directory in which to look for other files
included from the top file included from the top file. If not specified, we will attempt to locate a gromacs
installation on your system. When gromacs is installed in /usr/local, this will resolve
to /usr/local/gromacs/share/gromacs/top
- defines (map={}) preprocessor definitions that should be predefined when parsing the file - defines (map={}) preprocessor definitions that should be predefined when parsing the file
""" """
if includeDir is None:
includeDir = _defaultGromacsIncludeDir()
self._includeDirs = (os.path.dirname(file), includeDir) self._includeDirs = (os.path.dirname(file), includeDir)
self._defines = defines self._defines = defines
...@@ -359,6 +379,7 @@ class GromacsTopFile(object): ...@@ -359,6 +379,7 @@ class GromacsTopFile(object):
self._currentCategory = None self._currentCategory = None
self._ifStack = [] self._ifStack = []
self._elseStack = []
self._moleculeTypes = {} self._moleculeTypes = {}
self._molecules = [] self._molecules = []
self._currentMoleculeType = None self._currentMoleculeType = None
...@@ -752,3 +773,19 @@ class GromacsTopFile(object): ...@@ -752,3 +773,19 @@ class GromacsTopFile(object):
if removeCMMotion: if removeCMMotion:
sys.addForce(mm.CMMotionRemover()) sys.addForce(mm.CMMotionRemover())
return sys return sys
def _defaultGromacsIncludeDir():
"""Find the location where gromacs #include files are referenced from, by
searching for (1) gromacs environment variables, (2) for the gromacs binary
'pdb2gmx' in the PATH, or (3) just using the default gromacs install
location, /usr/local/gromacs/share/gromacs/top """
if 'GMXDATA' in os.environ:
return os.path.join(os.environ['GMXDATA'], 'top')
if 'GMXBIN' in os.environ:
return os.path.abspath(os.path.join(os.environ['GMXBIN'], '..', 'share', 'gromacs', 'top'))
pdb2gmx_path = distutils.spawn.find_executable('pdb2gmx')
if pdb2gmx_path is not None:
return os.path.abspath(os.path.join(os.path.dirname(pdb2gmx_path), '..', 'share', 'gromacs', 'top'))
return '/usr/local/gromacs/share/gromacs/top'
...@@ -41,9 +41,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE. ...@@ -41,9 +41,9 @@ USE OR OTHER DEALINGS IN THE SOFTWARE.
import os import os
import os.path import os.path
import copy
import re import re
import math import math
import warnings
try: try:
import numpy import numpy
...@@ -428,15 +428,25 @@ class PrmtopLoader(object): ...@@ -428,15 +428,25 @@ class PrmtopLoader(object):
charges=self.getCharges() charges=self.getCharges()
nonbondTerms = self.getNonbondTerms() nonbondTerms = self.getNonbondTerms()
for ii in range(0,len(dihedralPointers),5): for ii in range(0,len(dihedralPointers),5):
if int(dihedralPointers[ii+2])>0 and int(dihedralPointers[ii+3])>0: if int(dihedralPointers[ii+2])>0 and int(dihedralPointers[ii+3])>0:
iAtom = int(dihedralPointers[ii])//3 iAtom = int(dihedralPointers[ii])//3
lAtom = int(dihedralPointers[ii+3])//3 lAtom = int(dihedralPointers[ii+3])//3
chargeProd = charges[iAtom]*charges[lAtom] iidx = int(dihedralPointers[ii+4]) - 1
(rVdwI, epsilonI) = nonbondTerms[iAtom] chargeProd = charges[iAtom]*charges[lAtom]
(rVdwL, epsilonL) = nonbondTerms[lAtom] (rVdwI, epsilonI) = nonbondTerms[iAtom]
rMin = (rVdwI+rVdwL) (rVdwL, epsilonL) = nonbondTerms[lAtom]
epsilon = math.sqrt(epsilonI*epsilonL) rMin = (rVdwI+rVdwL)
returnList.append((iAtom, lAtom, chargeProd, rMin, epsilon)) epsilon = math.sqrt(epsilonI*epsilonL)
try:
iScee = float(self._raw_data["SCEE_SCALE_FACTOR"][iidx])
except KeyError:
iScee = 1.2
try:
iScnb = float(self._raw_data["SCNB_SCALE_FACTOR"][iidx])
except KeyError:
iScnb = 2.0
returnList.append((iAtom, lAtom, chargeProd, rMin, epsilon, iScee, iScnb))
return returnList return returnList
def getExcludedAtoms(self): def getExcludedAtoms(self):
...@@ -474,15 +484,15 @@ class PrmtopLoader(object): ...@@ -474,15 +484,15 @@ class PrmtopLoader(object):
# Update screening parameters for GBn if specified # Update screening parameters for GBn if specified
if symbls: if symbls:
for (i, symbl) in enumerate(symbls): for (i, symbl) in enumerate(symbls):
if symbl[0] == ('c' or 'C'): if symbl[0] in ('c', 'C'):
screen[i] = 0.48435382330 screen[i] = 0.48435382330
elif symbl[0] == ('h' or 'H'): elif symbl[0] in ('h', 'H'):
screen[i] = 1.09085413633 screen[i] = 1.09085413633
elif symbl[0] == ('n' or 'N'): elif symbl[0] in ('n', 'N'):
screen[i] = 0.700147318409 screen[i] = 0.700147318409
elif symbl[0] == ('o' or 'O'): elif symbl[0] in ('o', 'O'):
screen[i] = 1.06557401132 screen[i] = 1.06557401132
elif symbl[0] == ('s' or 'S'): elif symbl[0] in ('s', 'S'):
screen[i] = 0.602256336067 screen[i] = 0.602256336067
else: else:
screen[i] = 0.5 screen[i] = 0.5
...@@ -502,11 +512,15 @@ class PrmtopLoader(object): ...@@ -502,11 +512,15 @@ class PrmtopLoader(object):
units.Quantity(y, units.angstrom), units.Quantity(y, units.angstrom),
units.Quantity(z, units.angstrom)) units.Quantity(z, units.angstrom))
@property
def has_scee_scnb(self):
return ("SCEE_SCALE_FACTOR" in self._raw_data and "SCNB_SCALE_FACTOR" in self._raw_data)
#============================================================================================= #=============================================================================================
# AMBER System builder (based on, but not identical to, systemManager from 'zander') # AMBER System builder (based on, but not identical to, systemManager from 'zander')
#============================================================================================= #=============================================================================================
def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmodel=None, soluteDielectric=1.0, solventDielectric=78.5, nonbondedCutoff=None, nonbondedMethod='NoCutoff', scee=1.2, scnb=2.0, mm=None, verbose=False, EwaldErrorTolerance=None, flexibleConstraints=True, rigidWater=True): def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmodel=None, soluteDielectric=1.0, solventDielectric=78.5, nonbondedCutoff=None, nonbondedMethod='NoCutoff', scee=None, scnb=None, mm=None, verbose=False, EwaldErrorTolerance=None, flexibleConstraints=True, rigidWater=True):
""" """
Create an OpenMM System from an Amber prmtop file. Create an OpenMM System from an Amber prmtop file.
...@@ -520,8 +534,8 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode ...@@ -520,8 +534,8 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode
soluteDielectric (float) - The solute dielectric constant to use in the implicit solvent model (default: 1.0) soluteDielectric (float) - The solute dielectric constant to use in the implicit solvent model (default: 1.0)
solventDielectric (float) - The solvent dielectric constant to use in the implicit solvent model (default: 78.5) solventDielectric (float) - The solvent dielectric constant to use in the implicit solvent model (default: 78.5)
nonbondedCutoff (float) - if specified, will set nonbondedCutoff (default: None) nonbondedCutoff (float) - if specified, will set nonbondedCutoff (default: None)
scnb (float) - 1-4 Lennard-Jones scaling factor (default: 1.2) scnb (float) - 1-4 Lennard-Jones scaling factor (default: taken from prmtop or 1.2 if not present there)
scee (float) - 1-4 electrostatics scaling factor (default: 2.0) scee (float) - 1-4 electrostatics scaling factor (default: taken from prmtop or 2.0 if not present there)
mm - if specified, this module will be used in place of pyopenmm (default: None) mm - if specified, this module will be used in place of pyopenmm (default: None)
verbose (boolean) - if True, print out information on progress (default: False) verbose (boolean) - if True, print out information on progress (default: False)
flexibleConstraints (boolean) - if True, flexible bonds will be added in addition ot constrained bonds flexibleConstraints (boolean) - if True, flexible bonds will be added in addition ot constrained bonds
...@@ -571,6 +585,10 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode ...@@ -571,6 +585,10 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode
if prmtop.getIfBox()>1: if prmtop.getIfBox()>1:
raise Exception("only standard periodic boxes are currently supported") raise Exception("only standard periodic boxes are currently supported")
if prmtop.has_scee_scnb and (scee is not None or scnb is not None):
warnings.warn("1-4 scaling parameters in topology file are being ignored. "
"This is not recommended unless you know what you are doing.")
# Use pyopenmm implementation of OpenMM by default. # Use pyopenmm implementation of OpenMM by default.
if mm is None: if mm is None:
mm = simtk.openmm mm = simtk.openmm
...@@ -615,7 +633,7 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode ...@@ -615,7 +633,7 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode
if shake == 'h-angles': if shake == 'h-angles':
numConstrainedBonds = system.getNumConstraints() numConstrainedBonds = system.getNumConstraints()
atomConstraints = [[]]*system.getNumParticles() atomConstraints = [[]]*system.getNumParticles()
for i in range(system.getNumConstraints()): for i in range(numConstrainedBonds):
c = system.getConstraintParameters(i) c = system.getConstraintParameters(i)
distance = c[2].value_in_unit(units.nanometer) distance = c[2].value_in_unit(units.nanometer)
atomConstraints[c[0]].append((c[1], distance)) atomConstraints[c[0]].append((c[1], distance))
...@@ -712,9 +730,12 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode ...@@ -712,9 +730,12 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode
# Add 1-4 Interactions # Add 1-4 Interactions
excludedAtomPairs = set() excludedAtomPairs = set()
sigmaScale = 2**(-1./6.) sigmaScale = 2**(-1./6.)
for (iAtom, lAtom, chargeProd, rMin, epsilon) in prmtop.get14Interactions(): _scee, _scnb = scee, scnb
chargeProd /= scee for (iAtom, lAtom, chargeProd, rMin, epsilon, iScee, iScnb) in prmtop.get14Interactions():
epsilon /= scnb if scee is None: _scee = iScee
if scnb is None: _scnb = iScnb
chargeProd /= _scee
epsilon /= _scnb
sigma = rMin * sigmaScale sigma = rMin * sigmaScale
force.addException(iAtom, lAtom, chargeProd, sigma, epsilon) force.addException(iAtom, lAtom, chargeProd, sigma, epsilon)
excludedAtomPairs.add(min((iAtom, lAtom), (lAtom, iAtom))) excludedAtomPairs.add(min((iAtom, lAtom), (lAtom, iAtom)))
...@@ -829,6 +850,8 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode ...@@ -829,6 +850,8 @@ def readAmberSystem(prmtop_filename=None, prmtop_loader=None, shake=None, gbmode
gb.setCutoffDistance(nonbondedCutoff) gb.setCutoffDistance(nonbondedCutoff)
else: else:
raise Exception("Illegal nonbonded method for use with GBSA") raise Exception("Illegal nonbonded method for use with GBSA")
# This applies the reaction field dielectric to the NonbondedForce
# created above. Do not bind force to another name before this!
force.setReactionFieldDielectric(1.0) force.setReactionFieldDielectric(1.0)
# TODO: Add GBVI terms? # TODO: Add GBVI terms?
......
...@@ -287,11 +287,15 @@ class PDBFile(object): ...@@ -287,11 +287,15 @@ class PDBFile(object):
else: else:
atomName = atom.name atomName = atom.name
coords = positions[posIndex] coords = positions[posIndex]
line = "ATOM %5d %-4s %3s %s%4d %s%s%s 1.00 0.00" % ( if atom.element is not None:
symbol = atom.element.symbol
else:
symbol = ' '
line = "ATOM %5d %-4s %3s %s%4d %s%s%s 1.00 0.00 %2s " % (
atomIndex%100000, atomName, resName, chainName, atomIndex%100000, atomName, resName, chainName,
(resIndex+1)%10000, _format_83(coords[0]), (resIndex+1)%10000, _format_83(coords[0]),
_format_83(coords[1]), _format_83(coords[2])) _format_83(coords[1]), _format_83(coords[2]), symbol)
assert len(line) == 66, 'Fixed width overflow detected' assert len(line) == 80, 'Fixed width overflow detected'
print >>file, line print >>file, line
posIndex += 1 posIndex += 1
atomIndex += 1 atomIndex += 1
...@@ -309,6 +313,56 @@ class PDBFile(object): ...@@ -309,6 +313,56 @@ class PDBFile(object):
- topology (Topology) The Topology defining the molecular system being written - topology (Topology) The Topology defining the molecular system being written
- file (file=stdout) A file to write the file to - file (file=stdout) A file to write the file to
""" """
# Identify bonds that should be listed as CONECT records.
standardResidues = ['ALA', 'ASN', 'CYS', 'GLU', 'HIS', 'LEU', 'MET', 'PRO', 'THR', 'TYR',
'ARG', 'ASP', 'GLN', 'GLY', 'ILE', 'LYS', 'PHE', 'SER', 'TRP', 'VAL',
'A', 'G', 'C', 'U', 'I', 'DA', 'DG', 'DC', 'DT', 'DI', 'HOH']
conectBonds = []
for atom1, atom2 in topology.bonds():
if atom1.residue.name not in standardResidues or atom2.residue.name not in standardResidues:
conectBonds.append((atom1, atom2))
elif atom1.name == 'SG' and atom2.name == 'SG' and atom1.residue.name == 'CYS' and atom2.residue.name == 'CYS':
conectBonds.append((atom1, atom2))
if len(conectBonds) > 0:
# Work out the index used in the PDB file for each atom.
atomIndex = {}
nextAtomIndex = 0
prevChain = None
for chain in topology.chains():
for atom in chain.atoms():
if atom.residue.chain != prevChain:
nextAtomIndex += 1
prevChain = atom.residue.chain
atomIndex[atom] = nextAtomIndex
nextAtomIndex += 1
# Record which other atoms each atom is bonded to.
atomBonds = {}
for atom1, atom2 in conectBonds:
index1 = atomIndex[atom1]
index2 = atomIndex[atom2]
if index1 not in atomBonds:
atomBonds[index1] = []
if index2 not in atomBonds:
atomBonds[index2] = []
atomBonds[index1].append(index2)
atomBonds[index2].append(index1)
# Write the CONECT records.
for index1 in sorted(atomBonds):
bonded = atomBonds[index1]
while len(bonded) > 4:
print >>file, "CONECT%5d%5d%5d%5d" % (index1, bonded[0], bonded[1], bonded[2])
del bonded[:4]
line = "CONECT%5d" % index1
for index2 in bonded:
line = "%s%5d" % (line, index2)
print >>file, line
print >>file, "END" print >>file, "END"
......
...@@ -79,5 +79,6 @@ class PDBReporter(object): ...@@ -79,5 +79,6 @@ class PDBReporter(object):
self._nextModel += 1 self._nextModel += 1
def __del__(self): def __del__(self):
PDBFile.writeFooter(self._topology, self._out) if self._topology is not None:
PDBFile.writeFooter(self._topology, self._out)
self._out.close() self._out.close()
import os
import unittest
from simtk.openmm.app import *
from simtk.openmm import *
from simtk.unit import *
import simtk.openmm.app.element as elem
class TestDesmondDMSFile(unittest.TestCase):
def setUp(self):
"""Set up the tests by loading the input files."""
# alanine dipeptide with explicit water
path = os.path.join(os.path.dirname(__file__), 'systems/alanine-dipeptide-explicit-amber99SBILDN-tip3p.dms')
self.dms = DesmondDMSFile(path)
def test_NonbondedMethod(self):
"""Test all five options for the nonbondedMethod parameter."""
methodMap = {NoCutoff:NonbondedForce.NoCutoff,
CutoffNonPeriodic:NonbondedForce.CutoffNonPeriodic,
CutoffPeriodic:NonbondedForce.CutoffPeriodic,
Ewald:NonbondedForce.Ewald, PME: NonbondedForce.PME}
for method in methodMap:
system = self.dms.createSystem(nonbondedMethod=method)
forces = system.getForces()
self.assertTrue(any(isinstance(f, NonbondedForce) and
f.getNonbondedMethod()==methodMap[method]
for f in forces))
def test_Cutoff(self):
"""Test to make sure the nonbondedCutoff parameter is passed correctly."""
for method in [CutoffNonPeriodic, CutoffPeriodic, Ewald, PME]:
system = self.dms.createSystem(nonbondedMethod=method,
nonbondedCutoff=2*nanometer)
cutoff_distance = 0.0*nanometer
cutoff_check = 2.0*nanometer
for force in system.getForces():
if isinstance(force, NonbondedForce):
cutoff_distance = force.getCutoffDistance()
self.assertEqual(cutoff_distance, cutoff_check)
def test_EwaldErrorTolerance(self):
"""Test to make sure the ewaldErrorTolerance parameter is passed correctly."""
for method in [Ewald, PME]:
system = self.dms.createSystem(nonbondedMethod=method,
ewaldErrorTolerance=1e-6)
tolerance = 0
tolerance_check = 1e-6
for force in system.getForces():
if isinstance(force, NonbondedForce):
tolerance = force.getEwaldErrorTolerance()
self.assertEqual(tolerance, tolerance_check)
def test_RemoveCMMotion(self):
"""Test both options (True and False) for the removeCMMotion parameter."""
for b in [True, False]:
system = self.dms.createSystem(removeCMMotion=b)
self.assertEqual(any(isinstance(f, CMMotionRemover) for f in system.getForces()), b)
def test_HydrogenMass(self):
"""Test that altering the mass of hydrogens works correctly."""
topology = self.dms.topology
hydrogenMass = 4*amu
system1 = self.dms.createSystem()
system2 = self.dms.createSystem(hydrogenMass=hydrogenMass)
for atom in topology.atoms():
if atom.element == elem.hydrogen:
self.assertNotEqual(hydrogenMass, system1.getParticleMass(atom.index))
self.assertEqual(hydrogenMass, system2.getParticleMass(atom.index))
totalMass1 = sum([system1.getParticleMass(i) for i in range(system1.getNumParticles())]).value_in_unit(amu)
totalMass2 = sum([system2.getParticleMass(i) for i in range(system2.getNumParticles())]).value_in_unit(amu)
self.assertAlmostEqual(totalMass1, totalMass2)
This source diff could not be displayed because it is too large. You can view the blob instead.
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment