Commit 8df54762 authored by Lee-Ping Wang's avatar Lee-Ping Wang
Browse files

Merge branch 'master' of github.com:leeping/openmm

parents 3cb25ad8 59854c5e
......@@ -47,6 +47,9 @@ namespace OpenMM {
* springs to form a ring. This allows certain quantum mechanical effects to be efficiently
* simulated.
*
* By default this Integrator applies a PILE thermostat to the system to simulate constant
* temperature dynamics. You can disable the thermostat by calling setApplyThermostat(false).
*
* Because this Integrator simulates many copies of the System at once, it must be used
* differently from other Integrators. Instead of setting positions and velocities by
* calling methods of the Context, you should use the corresponding methods of the Integrator
......@@ -127,6 +130,18 @@ public:
void setFriction(double coeff) {
friction = coeff;
}
/**
* Get whether a thermostat is applied to the system.
*/
bool getApplyThermostat() const {
return applyThermostat;
}
/**
* Set whether a thermostat is applied to the system.
*/
void setApplyThermostat(bool apply) {
applyThermostat = apply;
}
/**
* Get the random number seed. See setRandomNumberSeed() for details.
*/
......@@ -213,6 +228,7 @@ protected:
private:
double temperature, friction;
int numCopies, randomNumberSeed;
bool applyThermostat;
std::map<int, int> contractions;
bool forcesAreValid, hasSetPosition, hasSetVelocity, isFirstStep;
Kernel kernel;
......
......@@ -42,7 +42,7 @@ using namespace OpenMM;
using namespace std;
RPMDIntegrator::RPMDIntegrator(int numCopies, double temperature, double frictionCoeff, double stepSize, const map<int, int>& contractions) :
numCopies(numCopies), contractions(contractions), forcesAreValid(false), hasSetPosition(false), hasSetVelocity(false), isFirstStep(true) {
numCopies(numCopies), applyThermostat(true), contractions(contractions), forcesAreValid(false), hasSetPosition(false), hasSetVelocity(false), isFirstStep(true) {
setTemperature(temperature);
setFriction(frictionCoeff);
setStepSize(stepSize);
......@@ -51,7 +51,7 @@ RPMDIntegrator::RPMDIntegrator(int numCopies, double temperature, double frictio
}
RPMDIntegrator::RPMDIntegrator(int numCopies, double temperature, double frictionCoeff, double stepSize) :
numCopies(numCopies), forcesAreValid(false), hasSetPosition(false), hasSetVelocity(false), isFirstStep(true) {
numCopies(numCopies), applyThermostat(true), forcesAreValid(false), hasSetPosition(false), hasSetVelocity(false), isFirstStep(true) {
setTemperature(temperature);
setFriction(frictionCoeff);
setStepSize(stepSize);
......
......@@ -128,12 +128,12 @@ void CudaIntegrateRPMDStepKernel::initialize(const System& system, const RPMDInt
if (copies != numCopies) {
if (groupsByCopies.find(copies) == groupsByCopies.end()) {
groupsByCopies[copies] = 1<<group;
groupsNotContracted -= 1<<group;
if (copies > maxContractedCopies)
maxContractedCopies = copies;
}
else
groupsByCopies[copies] |= 1<<group;
groupsNotContracted -= 1<<group;
}
}
if (maxContractedCopies > 0) {
......@@ -205,7 +205,8 @@ void CudaIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDIntegr
void* frictionPtr = (useDoublePrecision ? (void*) &friction : (void*) &frictionFloat);
int randomIndex = integration.prepareRandomNumbers(numParticles*numCopies);
void* pileArgs[] = {&velocities->getDevicePointer(), &integration.getRandom().getDevicePointer(), &randomIndex, dtPtr, kTPtr, frictionPtr};
cu.executeKernel(pileKernel, pileArgs, numParticles*numCopies, workgroupSize);
if (integrator.getApplyThermostat())
cu.executeKernel(pileKernel, pileArgs, numParticles*numCopies, workgroupSize);
// Update positions and velocities.
......@@ -223,8 +224,10 @@ void CudaIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDIntegr
// Apply the PILE-L thermostat again.
randomIndex = integration.prepareRandomNumbers(numParticles*numCopies);
cu.executeKernel(pileKernel, pileArgs, numParticles*numCopies, workgroupSize);
if (integrator.getApplyThermostat()) {
randomIndex = integration.prepareRandomNumbers(numParticles*numCopies);
cu.executeKernel(pileKernel, pileArgs, numParticles*numCopies, workgroupSize);
}
// Update the time and step count.
......@@ -285,6 +288,14 @@ void CudaIntegrateRPMDStepKernel::computeForces(ContextImpl& context) {
void* contractForceArgs[] = {&forces->getDevicePointer(), &contractedForces->getDevicePointer()};
cu.executeKernel(forceContractionKernels[copies], contractForceArgs, numParticles*numCopies, workgroupSize);
}
if (groupsByCopies.size() > 0) {
// Ensure the Context contains the positions from the last copy, since we'll assume that later.
int i = numCopies-1;
void* copyToContextArgs[] = {&velocities->getDevicePointer(), &cu.getVelm().getDevicePointer(), &positions->getDevicePointer(),
&cu.getPosq().getDevicePointer(), &cu.getAtomIndexArray().getDevicePointer(), &i};
cu.executeKernel(copyToContextKernel, copyToContextArgs, cu.getNumAtoms());
}
}
double CudaIntegrateRPMDStepKernel::computeKineticEnergy(ContextImpl& context, const RPMDIntegrator& integrator) {
......@@ -374,7 +385,6 @@ void CudaIntegrateRPMDStepKernel::copyToContext(int copy, ContextImpl& context)
string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable, bool forward) {
stringstream source;
int unfactored = size;
int stage = 0;
int L = size;
int m = 1;
......@@ -390,16 +400,27 @@ string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable,
// Factor size, generating an appropriate block of code for each factor.
while (unfactored > 1) {
while (L > 1) {
int input = stage%2;
int output = 1-input;
int radix;
if (L%5 == 0)
radix = 5;
else if (L%4 == 0)
radix = 4;
else if (L%3 == 0)
radix = 3;
else if (L%2 == 0)
radix = 2;
else
throw OpenMMException("Illegal size for FFT: "+cu.intToString(size));
source<<"{\n";
if (unfactored%5 == 0) {
L = L/5;
source<<"// Pass "<<(stage+1)<<" (radix 5)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
L = L/radix;
source<<"// Pass "<<(stage+1)<<" (radix "<<radix<<")\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
if (radix == 5) {
source<<"mixed3 c0r = real"<<input<<"[i];\n";
source<<"mixed3 c0i = imag"<<input<<"[i];\n";
source<<"mixed3 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -443,16 +464,8 @@ string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable,
source<<"imag"<<output<<"[i+(4*j+3)*"<<m<<"] = "<<multImag<<"(w[j*"<<(3*size)<<"/"<<(5*L)<<"], d8r-d10r, d8i-d10i);\n";
source<<"real"<<output<<"[i+(4*j+4)*"<<m<<"] = "<<multReal<<"(w[j*"<<(4*size)<<"/"<<(5*L)<<"], d7r-d9r, d7i-d9i);\n";
source<<"imag"<<output<<"[i+(4*j+4)*"<<m<<"] = "<<multImag<<"(w[j*"<<(4*size)<<"/"<<(5*L)<<"], d7r-d9r, d7i-d9i);\n";
source<<"}\n";
m = m*5;
unfactored /= 5;
}
else if (unfactored%4 == 0) {
L = L/4;
source<<"// Pass "<<(stage+1)<<" (radix 4)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 4) {
source<<"mixed3 c0r = real"<<input<<"[i];\n";
source<<"mixed3 c0i = imag"<<input<<"[i];\n";
source<<"mixed3 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -477,16 +490,8 @@ string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable,
source<<"imag"<<output<<"[i+(3*j+2)*"<<m<<"] = "<<multImag<<"(w[j*"<<(2*size)<<"/"<<(4*L)<<"], d0r-d2r, d0i-d2i);\n";
source<<"real"<<output<<"[i+(3*j+3)*"<<m<<"] = "<<multReal<<"(w[j*"<<(3*size)<<"/"<<(4*L)<<"], d1r-d3r, d1i-d3i);\n";
source<<"imag"<<output<<"[i+(3*j+3)*"<<m<<"] = "<<multImag<<"(w[j*"<<(3*size)<<"/"<<(4*L)<<"], d1r-d3r, d1i-d3i);\n";
source<<"}\n";
m = m*4;
unfactored /= 4;
}
else if (unfactored%3 == 0) {
L = L/3;
source<<"// Pass "<<(stage+1)<<" (radix 3)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 3) {
source<<"mixed3 c0r = real"<<input<<"[i];\n";
source<<"mixed3 c0i = imag"<<input<<"[i];\n";
source<<"mixed3 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -505,16 +510,8 @@ string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable,
source<<"imag"<<output<<"[i+(2*j+1)*"<<m<<"] = "<<multImag<<"(w[j*"<<size<<"/"<<(3*L)<<"], d1r+d2r, d1i+d2i);\n";
source<<"real"<<output<<"[i+(2*j+2)*"<<m<<"] = "<<multReal<<"(w[j*"<<(2*size)<<"/"<<(3*L)<<"], d1r-d2r, d1i-d2i);\n";
source<<"imag"<<output<<"[i+(2*j+2)*"<<m<<"] = "<<multImag<<"(w[j*"<<(2*size)<<"/"<<(3*L)<<"], d1r-d2r, d1i-d2i);\n";
source<<"}\n";
m = m*3;
unfactored /= 3;
}
else if (unfactored%2 == 0) {
L = L/2;
source<<"// Pass "<<(stage+1)<<" (radix 2)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 2) {
source<<"mixed3 c0r = real"<<input<<"[i];\n";
source<<"mixed3 c0i = imag"<<input<<"[i];\n";
source<<"mixed3 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -523,12 +520,9 @@ string CudaIntegrateRPMDStepKernel::createFFT(int size, const string& variable,
source<<"imag"<<output<<"[i+j*"<<m<<"] = c0i+c1i;\n";
source<<"real"<<output<<"[i+(j+1)*"<<m<<"] = "<<multReal<<"(w[j*"<<size<<"/"<<(2*L)<<"], c0r-c1r, c0i-c1i);\n";
source<<"imag"<<output<<"[i+(j+1)*"<<m<<"] = "<<multImag<<"(w[j*"<<size<<"/"<<(2*L)<<"], c0r-c1r, c0i-c1i);\n";
source<<"}\n";
m = m*2;
unfactored /= 2;
}
else
throw OpenMMException("Illegal size for FFT: "+cu.intToString(size));
source<<"}\n";
m = m*radix;
source<<"__syncthreads();\n";
source<<"}\n";
++stage;
......
......@@ -431,6 +431,71 @@ void testContractions() {
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("CUDA");
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 argc, char* argv[]) {
try {
registerRPMDCudaKernelFactories();
......@@ -441,6 +506,7 @@ int main(int argc, char* argv[]) {
testCMMotionRemoval();
testVirtualSites();
testContractions();
testWithoutThermostat();
}
catch(const std::exception& e) {
std::cout << "exception: " << e.what() << std::endl;
......
......@@ -108,12 +108,12 @@ void OpenCLIntegrateRPMDStepKernel::initialize(const System& system, const RPMDI
if (copies != numCopies) {
if (groupsByCopies.find(copies) == groupsByCopies.end()) {
groupsByCopies[copies] = 1<<group;
groupsNotContracted -= 1<<group;
if (copies > maxContractedCopies)
maxContractedCopies = copies;
}
else
groupsByCopies[copies] |= 1<<group;
groupsNotContracted -= 1<<group;
}
}
if (maxContractedCopies > 0) {
......@@ -223,7 +223,8 @@ void OpenCLIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDInte
stepKernel.setArg<cl_float>(4, (cl_float) (integrator.getTemperature()*BOLTZ));
velocitiesKernel.setArg<cl_float>(2, (cl_float) dt);
}
cl.executeKernel(pileKernel, numParticles*numCopies, workgroupSize);
if (integrator.getApplyThermostat())
cl.executeKernel(pileKernel, numParticles*numCopies, workgroupSize);
// Update positions and velocities.
......@@ -238,8 +239,10 @@ void OpenCLIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDInte
// Apply the PILE-L thermostat again.
pileKernel.setArg<cl_uint>(2, integration.prepareRandomNumbers(numParticles*numCopies));
cl.executeKernel(pileKernel, numParticles*numCopies, workgroupSize);
if (integrator.getApplyThermostat()) {
pileKernel.setArg<cl_uint>(2, integration.prepareRandomNumbers(numParticles*numCopies));
cl.executeKernel(pileKernel, numParticles*numCopies, workgroupSize);
}
// Update the time and step count.
......@@ -301,6 +304,13 @@ void OpenCLIntegrateRPMDStepKernel::computeForces(ContextImpl& context) {
cl.executeKernel(forceContractionKernels[copies], numParticles*numCopies, workgroupSize);
}
}
if (groupsByCopies.size() > 0) {
// Ensure the Context contains the positions from the last copy, since we'll assume that later.
copyToContextKernel.setArg<cl::Buffer>(2, positions->getDeviceBuffer());
copyToContextKernel.setArg<cl_int>(5, numCopies-1);
cl.executeKernel(copyToContextKernel, cl.getNumAtoms());
}
}
double OpenCLIntegrateRPMDStepKernel::computeKineticEnergy(ContextImpl& context, const RPMDIntegrator& integrator) {
......@@ -380,7 +390,6 @@ void OpenCLIntegrateRPMDStepKernel::copyToContext(int copy, ContextImpl& context
string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable, bool forward) {
stringstream source;
int unfactored = size;
int stage = 0;
int L = size;
int m = 1;
......@@ -396,16 +405,27 @@ string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable
// Factor size, generating an appropriate block of code for each factor.
while (unfactored > 1) {
while (L > 1) {
int input = stage%2;
int output = 1-input;
int radix;
if (L%5 == 0)
radix = 5;
else if (L%4 == 0)
radix = 4;
else if (L%3 == 0)
radix = 3;
else if (L%2 == 0)
radix = 2;
else
throw OpenMMException("Illegal size for FFT: "+cl.intToString(size));
source<<"{\n";
if (unfactored%5 == 0) {
L = L/5;
source<<"// Pass "<<(stage+1)<<" (radix 5)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
L = L/radix;
source<<"// Pass "<<(stage+1)<<" (radix "<<radix<<")\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
if (radix == 5) {
source<<"mixed4 c0r = real"<<input<<"[i];\n";
source<<"mixed4 c0i = imag"<<input<<"[i];\n";
source<<"mixed4 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -449,16 +469,8 @@ string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable
source<<"imag"<<output<<"[i+(4*j+3)*"<<m<<"] = "<<multImag<<"(w[j*"<<(3*size)<<"/"<<(5*L)<<"], d8r-d10r, d8i-d10i);\n";
source<<"real"<<output<<"[i+(4*j+4)*"<<m<<"] = "<<multReal<<"(w[j*"<<(4*size)<<"/"<<(5*L)<<"], d7r-d9r, d7i-d9i);\n";
source<<"imag"<<output<<"[i+(4*j+4)*"<<m<<"] = "<<multImag<<"(w[j*"<<(4*size)<<"/"<<(5*L)<<"], d7r-d9r, d7i-d9i);\n";
source<<"}\n";
m = m*5;
unfactored /= 5;
}
else if (unfactored%4 == 0) {
L = L/4;
source<<"// Pass "<<(stage+1)<<" (radix 4)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 4) {
source<<"mixed4 c0r = real"<<input<<"[i];\n";
source<<"mixed4 c0i = imag"<<input<<"[i];\n";
source<<"mixed4 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -483,16 +495,8 @@ string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable
source<<"imag"<<output<<"[i+(3*j+2)*"<<m<<"] = "<<multImag<<"(w[j*"<<(2*size)<<"/"<<(4*L)<<"], d0r-d2r, d0i-d2i);\n";
source<<"real"<<output<<"[i+(3*j+3)*"<<m<<"] = "<<multReal<<"(w[j*"<<(3*size)<<"/"<<(4*L)<<"], d1r-d3r, d1i-d3i);\n";
source<<"imag"<<output<<"[i+(3*j+3)*"<<m<<"] = "<<multImag<<"(w[j*"<<(3*size)<<"/"<<(4*L)<<"], d1r-d3r, d1i-d3i);\n";
source<<"}\n";
m = m*4;
unfactored /= 4;
}
else if (unfactored%3 == 0) {
L = L/3;
source<<"// Pass "<<(stage+1)<<" (radix 3)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 3) {
source<<"mixed4 c0r = real"<<input<<"[i];\n";
source<<"mixed4 c0i = imag"<<input<<"[i];\n";
source<<"mixed4 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -511,16 +515,8 @@ string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable
source<<"imag"<<output<<"[i+(2*j+1)*"<<m<<"] = "<<multImag<<"(w[j*"<<size<<"/"<<(3*L)<<"], d1r+d2r, d1i+d2i);\n";
source<<"real"<<output<<"[i+(2*j+2)*"<<m<<"] = "<<multReal<<"(w[j*"<<(2*size)<<"/"<<(3*L)<<"], d1r-d2r, d1i-d2i);\n";
source<<"imag"<<output<<"[i+(2*j+2)*"<<m<<"] = "<<multImag<<"(w[j*"<<(2*size)<<"/"<<(3*L)<<"], d1r-d2r, d1i-d2i);\n";
source<<"}\n";
m = m*3;
unfactored /= 3;
}
else if (unfactored%2 == 0) {
L = L/2;
source<<"// Pass "<<(stage+1)<<" (radix 2)\n";
source<<"if (indexInBlock < "<<(L*m)<<") {\n";
source<<"int i = indexInBlock;\n";
source<<"int j = i/"<<m<<";\n";
else if (radix == 2) {
source<<"mixed4 c0r = real"<<input<<"[i];\n";
source<<"mixed4 c0i = imag"<<input<<"[i];\n";
source<<"mixed4 c1r = real"<<input<<"[i+"<<(L*m)<<"];\n";
......@@ -529,12 +525,9 @@ string OpenCLIntegrateRPMDStepKernel::createFFT(int size, const string& variable
source<<"imag"<<output<<"[i+j*"<<m<<"] = c0i+c1i;\n";
source<<"real"<<output<<"[i+(j+1)*"<<m<<"] = "<<multReal<<"(w[j*"<<size<<"/"<<(2*L)<<"], c0r-c1r, c0i-c1i);\n";
source<<"imag"<<output<<"[i+(j+1)*"<<m<<"] = "<<multImag<<"(w[j*"<<size<<"/"<<(2*L)<<"], c0r-c1r, c0i-c1i);\n";
source<<"}\n";
m = m*2;
unfactored /= 2;
}
else
throw OpenMMException("Illegal size for FFT: "+cl.intToString(size));
source<<"}\n";
m = m*radix;
source<<"barrier(CLK_LOCAL_MEM_FENCE);\n";
source<<"}\n";
++stage;
......
......@@ -432,6 +432,71 @@ void testContractions() {
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("OpenCL");
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 argc, char* argv[]) {
try {
registerRPMDOpenCLKernelFactories();
......@@ -442,6 +507,7 @@ int main(int argc, char* argv[]) {
testCMMotionRemoval();
testVirtualSites();
testContractions();
testWithoutThermostat();
}
catch(const std::exception& e) {
std::cout << "exception: " << e.what() << std::endl;
......
......@@ -89,7 +89,6 @@ void ReferenceIntegrateRPMDStepKernel::initialize(const System& system, const RP
if (copies != numCopies) {
if (groupsByCopies.find(copies) == groupsByCopies.end()) {
groupsByCopies[copies] = 1<<group;
groupsNotContracted -= 1<<group;
contractionFFT[copies] = NULL;
fftpack_init_1d(&contractionFFT[copies], copies);
if (copies > maxContractedCopies)
......@@ -97,6 +96,7 @@ void ReferenceIntegrateRPMDStepKernel::initialize(const System& system, const RP
}
else
groupsByCopies[copies] |= 1<<group;
groupsNotContracted -= 1<<group;
}
}
......@@ -135,36 +135,38 @@ void ReferenceIntegrateRPMDStepKernel::execute(ContextImpl& context, const RPMDI
const RealOpenMM twown = 2.0*nkT/hbar;
const RealOpenMM c1_0 = exp(-halfdt*integrator.getFriction());
const RealOpenMM c2_0 = sqrt(1.0-c1_0*c1_0);
for (int particle = 0; particle < numParticles; particle++) {
if (system.getParticleMass(particle) == 0.0)
continue;
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int component = 0; component < 3; component++) {
for (int k = 0; k < numCopies; k++)
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.
if (integrator.getApplyThermostat()) {
for (int particle = 0; particle < numParticles; particle++) {
if (system.getParticleMass(particle) == 0.0)
continue;
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int component = 0; component < 3; component++) {
for (int k = 0; k < numCopies; k++)
v[k] = t_complex(scale*velocities[k][particle][component], 0.0);
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]);
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.
for (int k = 1; k <= numCopies/2; k++) {
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c1 = exp(-2.0*wk*halfdt);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
v[k] = v[k]*c1 + t_complex(rand1, rand2);
if (k < numCopies-k)
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2);
v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
// Use critical damping white noise for the remaining modes.
for (int k = 1; k <= numCopies/2; k++) {
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c1 = exp(-2.0*wk*halfdt);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
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
// Apply the PILE-L thermostat again.
for (int particle = 0; particle < numParticles; particle++) {
if (system.getParticleMass(particle) == 0.0)
continue;
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int component = 0; component < 3; component++) {
for (int k = 0; k < numCopies; k++)
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.
if (integrator.getApplyThermostat()) {
for (int particle = 0; particle < numParticles; particle++) {
if (system.getParticleMass(particle) == 0.0)
continue;
const RealOpenMM c3_0 = c2_0*sqrt(nkT/system.getParticleMass(particle));
for (int component = 0; component < 3; component++) {
for (int k = 0; k < numCopies; k++)
v[k] = t_complex(scale*velocities[k][particle][component], 0.0);
fftpack_exec_1d(fft, FFTPACK_FORWARD, &v[0], &v[0]);
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.
for (int k = 1; k <= numCopies/2; k++) {
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c1 = exp(-2.0*wk*halfdt);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
v[k] = v[k]*c1 + t_complex(rand1, rand2);
if (k < numCopies-k)
v[numCopies-k] = v[numCopies-k]*c1 + t_complex(rand1, -rand2);
v[0].re = v[0].re*c1_0 + c3_0*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
// Use critical damping white noise for the remaining modes.
for (int k = 1; k <= numCopies/2; k++) {
const bool isCenter = (numCopies%2 == 0 && k == numCopies/2);
const RealOpenMM wk = twown*sin(k*M_PI/numCopies);
const RealOpenMM c1 = exp(-2.0*wk*halfdt);
const RealOpenMM c2 = sqrt((1.0-c1*c1)/2) * (isCenter ? sqrt(2.0) : 1.0);
const RealOpenMM c3 = c2*sqrt(nkT/system.getParticleMass(particle));
RealOpenMM rand1 = c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
RealOpenMM rand2 = (isCenter ? 0.0 : c3*SimTKOpenMMUtilities::getNormallyDistributedRandomNumber());
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() {
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() {
try {
testFreeParticles();
testCMMotionRemoval();
testVirtualSites();
testContractions();
testWithoutThermostat();
}
catch(const std::exception& e) {
std::cout << "exception: " << e.what() << std::endl;
......
......@@ -56,6 +56,12 @@ void verifyEvaluation(const string& expression, double expectedValue) {
ExpressionProgram program = parsed.createProgram();
value = program.evaluate();
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
value = program.evaluate(variables);
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.
variables.clear();
......
......@@ -78,6 +78,10 @@ MODULE OpenMM_Types
integer*8 :: handle = 0
end type
type OpenMM_IntSet
integer*8 :: handle = 0
end type
! Enumerations
integer*4, parameter :: OpenMM_False = 0
......
......@@ -85,6 +85,7 @@ version = '%(version)s'
full_version = '%(full_version)s'
git_revision = '%(git_revision)s'
release = %(isrelease)s
openmm_library_path = '%(path)s'
if not release:
version = full_version
......@@ -113,7 +114,8 @@ if not release:
a.write(cnt % {'version': version,
'full_version' : full_version,
'git_revision' : git_revision,
'isrelease': str(IS_RELEASED)})
'isrelease': str(IS_RELEASED),
'path': os.getenv('OPENMM_LIB_PATH')})
finally:
a.close()
......@@ -197,7 +199,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM,
macVersion = [int(x) for x in platform.mac_ver()[0].split('.')]
if tuple(macVersion) < (10, 6):
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]
......@@ -209,6 +211,7 @@ def buildKeywordDictionary(major_version_num=MAJOR_VERSION_NUM,
include_dirs = include_dirs,
define_macros = define_macros,
library_dirs = library_dirs,
runtime_library_dirs = library_dirs,
libraries = libraries,
extra_compile_args=extra_compile_args,
extra_link_args=extra_link_args,
......@@ -238,8 +241,8 @@ def main():
uninstall()
except:
pass
writeVersionPy()
setupKeywords=buildKeywordDictionary()
writeVersionPy()
setup(**setupKeywords)
if __name__ == '__main__':
......
......@@ -13,7 +13,7 @@ It also tries to load any plugin modules it can find.
__author__ = "Randall J. Radmer"
import os, sys, glob
import os, sys, glob, os.path
if sys.platform == "win32":
libPrefix=""
libExt="dll"
......@@ -34,5 +34,9 @@ else:
from simtk.openmm.openmm import *
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()
......@@ -24,6 +24,7 @@ from dcdreporter import DCDReporter
from modeller import Modeller
from statedatareporter import StateDataReporter
from element import Element
from desmonddmsfile import DesmondDMSFile
# Enumerated values
......
......@@ -61,6 +61,11 @@ class GBn(object):
return 'GBn'
GBn = GBn()
class GBn2(object):
def __repr__(self):
return 'GBn2'
GBn2 = GBn2()
class AmberPrmtopFile(object):
"""AmberPrmtopFile parses an AMBER prmtop file and constructs a Topology and (optionally) an OpenMM System from it."""
......@@ -69,6 +74,7 @@ class AmberPrmtopFile(object):
top = Topology()
## The Topology read from the prmtop file
self.topology = top
self.elements = []
# Load the prmtop file
......@@ -96,21 +102,30 @@ class AmberPrmtopFile(object):
if atomName in atomReplacements:
atomName = atomReplacements[atomName]
# Try to guess the element.
upper = atomName.upper()
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
element = elem.magnesium
else:
# Get the element from the prmtop file if available
if prmtop.has_atomic_number:
try:
element = elem.get_by_symbol(atomName[0])
element = elem.Element.getByAtomicNumber(int(prmtop._raw_data['ATOMIC_NUMBER'][index]))
except KeyError:
element = None
else:
# Try to guess the element from the atom name.
upper = atomName.upper()
if upper.startswith('CL'):
element = elem.chlorine
elif upper.startswith('NA'):
element = elem.sodium
elif upper.startswith('MG'):
element = elem.magnesium
else:
try:
element = elem.get_by_symbol(atomName[0])
except KeyError:
element = None
top.addAtom(atomName, element, r)
self.elements.append(element)
# Add bonds to the topology
......@@ -127,7 +142,7 @@ class AmberPrmtopFile(object):
def createSystem(self, nonbondedMethod=ff.NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
constraints=None, rigidWater=True, implicitSolvent=None, soluteDielectric=1.0, solventDielectric=78.5, removeCMMotion=True,
ewaldErrorTolerance=0.0005):
hydrogenMass=None, ewaldErrorTolerance=0.0005):
"""Construct an OpenMM System representing the topology described by this prmtop file.
Parameters:
......@@ -137,10 +152,12 @@ class AmberPrmtopFile(object):
- constraints (object=None) Specifies which bonds angles should be implemented with constraints.
Allowed values are None, HBonds, AllBonds, or HAngles.
- rigidWater (boolean=True) If true, water molecules will be fully rigid regardless of the value passed for the constraints argument
- implicitSolvent (object=None) If not None, the implicit solvent model to use. Allowed values are HCT, OBC1, OBC2, or GBn.
- implicitSolvent (object=None) If not None, the implicit solvent model to use. Allowed values are HCT, OBC1, OBC2, GBn, or GBn2.
- soluteDielectric (float=1.0) The solute dielectric constant to use in the implicit solvent model.
- solventDielectric (float=78.5) The solvent dielectric constant to use in the implicit solvent model.
- 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.
- ewaldErrorTolerance (float=0.0005) The error tolerance to use if nonbondedMethod is Ewald or PME.
Returns: the newly created System
"""
......@@ -165,19 +182,30 @@ class AmberPrmtopFile(object):
raise ValueError('Illegal value for constraints')
if implicitSolvent is None:
implicitString = None
elif implicitSolvent == HCT:
elif implicitSolvent is HCT:
implicitString = 'HCT'
elif implicitSolvent == OBC1:
elif implicitSolvent is OBC1:
implicitString = 'OBC1'
elif implicitSolvent == OBC2:
elif implicitSolvent is OBC2:
implicitString = 'OBC2'
elif implicitSolvent == GBn:
elif implicitSolvent is GBn:
implicitString = 'GBn'
elif implicitSolvent is GBn2:
implicitString = 'GBn2'
else:
raise ValueError('Illegal value for implicit solvent model')
sys = amber_file_parser.readAmberSystem(prmtop_loader=self._prmtop, shake=constraintString, nonbondedCutoff=nonbondedCutoff,
nonbondedMethod=methodMap[nonbondedMethod], flexibleConstraints=False, gbmodel=implicitString,
soluteDielectric=soluteDielectric, solventDielectric=solventDielectric, rigidWater=rigidWater)
soluteDielectric=soluteDielectric, solventDielectric=solventDielectric, rigidWater=rigidWater,
elements=self.elements)
if hydrogenMass is not None:
for atom1, atom2 in self.topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transferMass = hydrogenMass-sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
sys.setParticleMass(atom1.index, sys.getParticleMass(atom1.index)-transferMass)
for force in sys.getForces():
if isinstance(force, mm.NonbondedForce):
force.setEwaldErrorTolerance(ewaldErrorTolerance)
......
<Residues>
<Residue name="A">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2" parent="C2"/>
<H name="H2'" parent="C2'"/>
......@@ -11,9 +12,7 @@
<H name="H62" parent="N6"/>
<H name="H8" parent="C8"/>
<H name="HO2'" parent="O2'"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="ACE">
<H name="H" parent="C" terminal="C"/>
......@@ -80,6 +79,7 @@
<H name="HD2" parent="OD2" maxph="4.4" variant="ASH"/>
</Residue>
<Residue name="C">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
<H name="H3'" parent="C3'"/>
......@@ -91,9 +91,7 @@
<H name="H5''" parent="C5'"/>
<H name="H6" parent="C6"/>
<H name="HO2'" parent="O2'"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="CYS">
<Variant name="CYS"/>
......@@ -107,6 +105,7 @@
<H name="HG" parent="SG" maxph="8.5" variant="CYS"/>
</Residue>
<Residue name="DA">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2" parent="C2"/>
<H name="H2'" parent="C2'"/>
......@@ -118,11 +117,10 @@
<H name="H61" parent="N6"/>
<H name="H62" parent="N6"/>
<H name="H8" parent="C8"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="DC">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
<H name="H2''" parent="C2'"/>
......@@ -134,11 +132,10 @@
<H name="H5'" parent="C5'"/>
<H name="H5''" parent="C5'"/>
<H name="H6" parent="C6"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="DG">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1" parent="N1"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
......@@ -150,11 +147,10 @@
<H name="H5'" parent="C5'"/>
<H name="H5''" parent="C5'"/>
<H name="H8" parent="C8"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="DT">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
<H name="H2''" parent="C2'"/>
......@@ -167,15 +163,14 @@
<H name="H71" parent="C7"/>
<H name="H72" parent="C7"/>
<H name="H73" parent="C7"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="FOR">
<H name="H1" parent="C"/>
<H name="H2" parent="C"/>
</Residue>
<Residue name="G">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1" parent="N1"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
......@@ -187,9 +182,7 @@
<H name="H5''" parent="C5'"/>
<H name="H8" parent="C8"/>
<H name="HO2'" parent="O2'"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="GLN">
<H name="H" parent="N"/>
......@@ -409,6 +402,7 @@
<H name="HH" parent="OH"/>
</Residue>
<Residue name="U">
<H name="HO5'" parent="O5'" terminal="N"/>
<H name="H1'" parent="C1'"/>
<H name="H2'" parent="C2'"/>
<H name="H3" parent="N3"/>
......@@ -419,9 +413,7 @@
<H name="H5''" parent="C5'"/>
<H name="H6" parent="C6"/>
<H name="HO2'" parent="O2'"/>
<H name="HO3'" parent="O3'"/>
<H name="HOP2" parent="OP2"/>
<H name="HOP3" parent="OP3"/>
<H name="HO3'" parent="O3'" terminal="C"/>
</Residue>
<Residue name="UNK">
<H name="H" parent="N"/>
......
......@@ -718,6 +718,7 @@
<Bond from="CG" to="HG2"/>
<Bond from="CG" to="HG3"/>
<Bond from="H" to="N"/>
<Bond from="H2" to="N"/>
<Bond from="H3" to="N"/>
<Bond from="HXT" to="OXT"/>
</Residue>
......
'''
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:
look up the Element with a particular chemical symbol."""
_elements_by_symbol = {}
_elements_by_atomic_number = {}
def __init__(self, number, name, symbol, mass):
## The atomic number of the element
......@@ -58,6 +59,16 @@ class Element:
s = symbol.strip().upper()
assert s not in Element._elements_by_symbol
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
def getBySymbol(symbol):
......@@ -65,6 +76,10 @@ class Element:
s = symbol.strip().upper()
return Element._elements_by_symbol[s]
@staticmethod
def getByAtomicNumber(atomic_number):
return Element._elements_by_atomic_number[atomic_number]
# This is for backward compatibility.
def get_by_symbol(symbol):
s = symbol.strip().upper()
......@@ -188,3 +203,8 @@ ununtrium = Element(113, "ununtrium", "Uut", 284*daltons)
ununquadium = Element(114, "ununquadium", "Uuq", 289*daltons)
ununpentium = Element(115, "ununpentium", "Uup", 288*daltons)
ununhexium = Element(116, "ununhexium", "Uuh", 292*daltons)
# Aliases to recognize common alternative spellings. Both the '==' and 'is'
# relational operators will work with any chosen name
sulphur = sulfur
aluminium = aluminum
......@@ -272,7 +272,7 @@ class ForceField(object):
self.atoms = [x-self.index for x in self.atoms]
def createSystem(self, topology, nonbondedMethod=NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
constraints=None, rigidWater=True, removeCMMotion=True, **args):
constraints=None, rigidWater=True, removeCMMotion=True, hydrogenMass=None, **args):
"""Construct an OpenMM System representing a Topology with this force field.
Parameters:
......@@ -284,6 +284,8 @@ class ForceField(object):
Allowed values are None, HBonds, AllBonds, or HAngles.
- rigidWater (boolean=True) If true, water molecules will be fully rigid regardless of the value passed for the constraints argument
- 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.
- args Arbitrary additional keyword arguments may also be specified. This allows extra parameters to be specified that are specific to
particular force fields.
Returns: the newly created System
......@@ -335,6 +337,17 @@ class ForceField(object):
sys = mm.System()
for atom in topology.atoms():
sys.addParticle(self._atomTypes[data.atomType[atom]][1])
# Adjust masses.
if hydrogenMass is not None:
for atom1, atom2 in topology.bonds():
if atom1.element == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.hydrogen, None):
transferMass = hydrogenMass-sys.getParticleMass(atom2.index)
sys.setParticleMass(atom2.index, hydrogenMass)
sys.setParticleMass(atom1.index, sys.getParticleMass(atom1.index)-transferMass)
# Set periodic boundary conditions.
......@@ -516,6 +529,27 @@ def _matchResidue(res, template, bondedToAtom):
bonds = [renumberAtoms[x] for x in bondedToAtom[atom.index] if x in renumberAtoms]
bondedTo.append(bonds)
externalBonds.append(len([x for x in bondedToAtom[atom.index] if x not in renumberAtoms]))
# For each unique combination of element and number of bonds, make sure the residue and
# template have the same number of atoms.
residueTypeCount = {}
for i, atom in enumerate(atoms):
key = (atom.element, len(bondedTo[i]), externalBonds[i])
if key not in residueTypeCount:
residueTypeCount[key] = 1
residueTypeCount[key] += 1
templateTypeCount = {}
for i, atom in enumerate(template.atoms):
key = (atom.element, len(atom.bondedTo), atom.externalBonds)
if key not in templateTypeCount:
templateTypeCount[key] = 1
templateTypeCount[key] += 1
if residueTypeCount != templateTypeCount:
return None
# Recursively match atoms.
if _findAtomMatches(atoms, template, bondedTo, externalBonds, matches, hasMatch, 0):
return matches
return None
......@@ -590,8 +624,8 @@ def _findMatchErrors(forcefield, res):
# Return an appropriate error message.
if numBestMatchAtoms == numResidueAtoms:
chainLength = len(list(res.chain.residues()))
if chainLength > 1 and (res.index == 0 or res.index == chainLength-1):
chainResidues = list(res.chain.residues())
if len(chainResidues) > 1 and (res == chainResidues[0] or res == chainResidues[-1]):
return 'The set of atoms matches %s, but the bonds are different. Perhaps the chain is missing a terminal group?' % bestMatchName
return 'The set of atoms matches %s, but the bonds are different.' % bestMatchName
if bestMatchName is not None:
......
......@@ -40,6 +40,7 @@ import simtk.unit as unit
import simtk.openmm as mm
import math
import os
import distutils.spawn
HBonds = ff.HBonds
AllBonds = ff.AllBonds
......@@ -90,6 +91,9 @@ class GromacsTopFile(object):
# A preprocessor command.
fields = stripped.split()
command = fields[0]
if len(self._ifStack) != len(self._elseStack):
raise RuntimeError('#if/#else stack out of sync')
if command == '#include' and not ignore:
# Locate the file to include
name = stripped[len(command):].strip(' \t"<>')
......@@ -116,17 +120,29 @@ class GromacsTopFile(object):
raise ValueError('Illegal line in .top file: '+line)
name = fields[1]
self._ifStack.append(name in self._defines)
self._elseStack.append(False)
elif command == '#ifndef':
# See whether this block should be ignored.
if len(fields) < 2:
raise ValueError('Illegal line in .top file: '+line)
name = fields[1]
self._ifStack.append(name not in self._defines)
self._elseStack.append(False)
elif command == '#endif':
# Pop an entry off the if stack.
if len(self._ifStack) == 0:
raise ValueError('Unexpected line in .top file: '+line)
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:
# A line of data for the current category
......@@ -342,23 +358,34 @@ class GromacsTopFile(object):
raise ValueError('Unsupported function type in [ cmaptypes ] line: '+line);
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=None):
"""Load a top file.
Parameters:
- file (string) the name of the file to load
- 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
included from the top file
- defines (map={}) preprocessor definitions that should be predefined when parsing the file
- includeDir (string=None) A directory in which to look for other files
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 (dict={}) preprocessor definitions that should be predefined when parsing the file
"""
if includeDir is None:
includeDir = _defaultGromacsIncludeDir()
self._includeDirs = (os.path.dirname(file), includeDir)
self._defines = defines
# Most of the gromacs water itp files for different forcefields,
# unless the preprocessor #define FLEXIBLE is given, don't define
# bonds between the water hydrogen and oxygens, but only give the
# constraint distances and exclusions.
self._defines = {'FLEXIBLE': True}
if defines is not None:
self._defines.update(defines)
# Parse the file.
self._currentCategory = None
self._ifStack = []
self._elseStack = []
self._moleculeTypes = {}
self._molecules = []
self._currentMoleculeType = None
......@@ -427,7 +454,7 @@ class GromacsTopFile(object):
top.addBond(atoms[int(fields[0])-1], atoms[int(fields[1])-1])
def createSystem(self, nonbondedMethod=ff.NoCutoff, nonbondedCutoff=1.0*unit.nanometer,
constraints=None, rigidWater=True, implicitSolvent=None, soluteDielectric=1.0, solventDielectric=78.5, ewaldErrorTolerance=0.0005, removeCMMotion=True):
constraints=None, rigidWater=True, implicitSolvent=None, soluteDielectric=1.0, solventDielectric=78.5, ewaldErrorTolerance=0.0005, removeCMMotion=True, hydrogenMass=None):
"""Construct an OpenMM System representing the topology described by this prmtop file.
Parameters:
......@@ -442,6 +469,8 @@ class GromacsTopFile(object):
- solventDielectric (float=78.5) The solvent dielectric constant to use in the implicit solvent model.
- 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.
Returns: the newly created System
"""
# Create the System.
......@@ -733,9 +762,36 @@ class GromacsTopFile(object):
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 == elem.hydrogen:
(atom1, atom2) = (atom2, atom1)
if atom2.element == elem.hydrogen and atom1.element not in (elem.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 _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'
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