Unverified Commit 1051acbd authored by peastman's avatar peastman Committed by GitHub
Browse files

Merge pull request #1982 from peastman/rmsd

Created RMSDForce
parents f481bd0a 107f4580
/* Portions copyright (c) 2018 Stanford University and Simbios.
* Contributors: Peter Eastman
*
* 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.
*/
#ifndef __ReferenceRMSDForce_H__
#define __ReferenceRMSDForce_H__
#include "openmm/RMSDForce.h"
#include <vector>
namespace OpenMM {
class ReferenceRMSDForce {
private:
std::vector<OpenMM::Vec3> referencePos;
std::vector<int> particles;
public:
/**
* Constructor
*/
ReferenceRMSDForce(std::vector<OpenMM::Vec3>& referencePos, std::vector<int>& particles);
/**
* Destructor
*/
~ReferenceRMSDForce();
/**
* Calculate the interaction.
*
* @param atomCoordinates atom coordinates
* @param forces the forces are added to this
* @return the energy of the interaction
*/
double calculateIxn(std::vector<OpenMM::Vec3>& atomCoordinates, std::vector<OpenMM::Vec3>& forces) const;
};
} // namespace OpenMM
#endif // __ReferenceRMSDForce_H__
......@@ -80,6 +80,8 @@ KernelImpl* ReferenceKernelFactory::createKernelImpl(std::string name, const Pla
return new ReferenceCalcCustomCompoundBondForceKernel(name, platform);
if (name == CalcCustomCVForceKernel::Name())
return new ReferenceCalcCustomCVForceKernel(name, platform);
if (name == CalcRMSDForceKernel::Name())
return new ReferenceCalcRMSDForceKernel(name, platform);
if (name == CalcCustomManyParticleForceKernel::Name())
return new ReferenceCalcCustomManyParticleForceKernel(name, platform);
if (name == CalcGayBerneForceKernel::Name())
......
......@@ -57,6 +57,7 @@
#include "ReferenceMonteCarloBarostat.h"
#include "ReferenceProperDihedralBond.h"
#include "ReferenceRbDihedralBond.h"
#include "ReferenceRMSDForce.h"
#include "ReferenceStochasticDynamics.h"
#include "ReferenceTabulatedFunction.h"
#include "ReferenceVariableStochasticDynamics.h"
......@@ -2055,6 +2056,43 @@ void ReferenceCalcCustomCVForceKernel::copyState(ContextImpl& context, ContextIm
innerContext.setParameter(param.first, context.getParameter(param.first));
}
void ReferenceCalcRMSDForceKernel::initialize(const System& system, const RMSDForce& force) {
particles = force.getParticles();
if (particles.size() == 0)
for (int i = 0; i < system.getNumParticles(); i++)
particles.push_back(i);
referencePos = force.getReferencePositions();
Vec3 center;
for (int i : particles)
center += referencePos[i];
center /= particles.size();
for (Vec3& p : referencePos)
p -= center;
}
double ReferenceCalcRMSDForceKernel::execute(ContextImpl& context, bool includeForces, bool includeEnergy) {
vector<Vec3>& posData = extractPositions(context);
vector<Vec3>& forceData = extractForces(context);
ReferenceRMSDForce rmsd(referencePos, particles);
return rmsd.calculateIxn(posData, forceData);
}
void ReferenceCalcRMSDForceKernel::copyParametersToContext(ContextImpl& context, const RMSDForce& force) {
if (referencePos.size() != force.getReferencePositions().size())
throw OpenMMException("updateParametersInContext: The number of reference positions has changed");
particles = force.getParticles();
if (particles.size() == 0)
for (int i = 0; i < referencePos.size(); i++)
particles.push_back(i);
referencePos = force.getReferencePositions();
Vec3 center;
for (int i : particles)
center += referencePos[i];
center /= particles.size();
for (Vec3& p : referencePos)
p -= center;
}
ReferenceIntegrateVerletStepKernel::~ReferenceIntegrateVerletStepKernel() {
if (dynamics)
delete dynamics;
......
......@@ -65,6 +65,7 @@ ReferencePlatform::ReferencePlatform() {
registerKernelFactory(CalcCustomCentroidBondForceKernel::Name(), factory);
registerKernelFactory(CalcCustomCompoundBondForceKernel::Name(), factory);
registerKernelFactory(CalcCustomCVForceKernel::Name(), factory);
registerKernelFactory(CalcRMSDForceKernel::Name(), factory);
registerKernelFactory(CalcCustomManyParticleForceKernel::Name(), factory);
registerKernelFactory(CalcGayBerneForceKernel::Name(), factory);
registerKernelFactory(IntegrateVerletStepKernel::Name(), factory);
......
/* Portions copyright (c) 2018 Stanford University and Simbios.
* Contributors: Peter Eastman
*
* 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.
*/
#include "ReferenceRMSDForce.h"
#include "jama_eig.h"
using namespace OpenMM;
using namespace std;
ReferenceRMSDForce::ReferenceRMSDForce(vector<Vec3>& referencePos, vector<int>& particles) :
referencePos(referencePos), particles(particles) {
}
ReferenceRMSDForce::~ReferenceRMSDForce() {
}
double ReferenceRMSDForce::calculateIxn(vector<Vec3>& atomCoordinates, vector<Vec3>& forces) const {
// Compute the RMSD and its gradient using the algorithm described in Coutsias et al,
// "Using quaternions to calculate RMSD" (doi: 10.1002/jcc.20110). First subtract
// the centroid from the atom positions. The reference positions have already been centered.
int numParticles = particles.size();
Vec3 center;
for (int i : particles)
center += atomCoordinates[i];
center /= numParticles;
vector<Vec3> positions(numParticles);
for (int i = 0; i < numParticles; i++)
positions[i] = atomCoordinates[particles[i]]-center;
// Compute the correlation matrix.
double R[3][3] = {{0, 0, 0}, {0, 0, 0}, {0, 0, 0}};
for (int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
for (int k = 0; k < numParticles; k++) {
int index = particles[k];
R[i][j] += positions[k][i]*referencePos[index][j];
}
// Compute the F matrix.
Array2D<double> F(4, 4);
F[0][0] = R[0][0] + R[1][1] + R[2][2];
F[1][0] = R[1][2] - R[2][1];
F[2][0] = R[2][0] - R[0][2];
F[3][0] = R[0][1] - R[1][0];
F[0][1] = R[1][2] - R[2][1];
F[1][1] = R[0][0] - R[1][1] - R[2][2];
F[2][1] = R[0][1] + R[1][0];
F[3][1] = R[0][2] + R[2][0];
F[0][2] = R[2][0] - R[0][2];
F[1][2] = R[0][1] + R[1][0];
F[2][2] = -R[0][0] + R[1][1] - R[2][2];
F[3][2] = R[1][2] + R[2][1];
F[0][3] = R[0][1] - R[1][0];
F[1][3] = R[0][2] + R[2][0];
F[2][3] = R[1][2] + R[2][1];
F[3][3] = -R[0][0] - R[1][1] + R[2][2];
// Find the maximum eigenvalue and eigenvector.
JAMA::Eigenvalue<double> eigen(F);
Array1D<double> values;
eigen.getRealEigenvalues(values);
Array2D<double> vectors;
eigen.getV(vectors);
// Compute the RMSD.
double sum = 0.0;
for (int i = 0; i < numParticles; i++) {
int index = particles[i];
sum += positions[i].dot(positions[i]) + referencePos[index].dot(referencePos[index]);
}
double msd = (sum-2*values[3])/numParticles;
if (msd < 1e-20) {
// The particles are perfectly aligned, so all the forces should be zero.
// Numerical error can lead to NaNs, so just return 0 now.
return 0.0;
}
double rmsd = sqrt(msd);
// Compute the rotation matrix.
double q[] = {vectors[0][3], vectors[1][3], vectors[2][3], vectors[3][3]};
double q00 = q[0]*q[0], q01 = q[0]*q[1], q02 = q[0]*q[2], q03 = q[0]*q[3];
double q11 = q[1]*q[1], q12 = q[1]*q[2], q13 = q[1]*q[3];
double q22 = q[2]*q[2], q23 = q[2]*q[3];
double q33 = q[3]*q[3];
double U[3][3] = {{q00+q11-q22-q33, 2*(q12-q03), 2*(q13+q02)},
{2*(q12+q03), q00-q11+q22-q33, 2*(q23-q01)},
{2*(q13-q02), 2*(q23+q01), q00-q11-q22+q33}};
// Rotate the reference positions and compute the forces.
for (int i = 0; i < numParticles; i++) {
const Vec3& p = referencePos[particles[i]];
Vec3 rotatedRef(U[0][0]*p[0] + U[1][0]*p[1] + U[2][0]*p[2],
U[0][1]*p[0] + U[1][1]*p[1] + U[2][1]*p[2],
U[0][2]*p[0] + U[1][2]*p[1] + U[2][2]*p[2]);
forces[particles[i]] -= (positions[i]-rotatedRef) / (rmsd*numParticles);
}
return rmsd;
}
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2018 Stanford University and the Authors. *
* Authors: Peter Eastman *
* 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. *
* -------------------------------------------------------------------------- */
#include "ReferenceTests.h"
#include "TestRMSDForce.h"
void runPlatformTests() {
}
#ifndef OPENMM_RMSDFORCE_PROXY_H_
#define OPENMM_RMSDFORCE_PROXY_H_
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2018 Stanford University and the Authors. *
* Authors: Peter Eastman *
* 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. *
* -------------------------------------------------------------------------- */
#include "openmm/internal/windowsExport.h"
#include "openmm/serialization/SerializationProxy.h"
namespace OpenMM {
/**
* This is a proxy for serializing RMSDForce objects.
*/
class OPENMM_EXPORT RMSDForceProxy : public SerializationProxy {
public:
RMSDForceProxy();
void serialize(const void* object, SerializationNode& node) const;
void* deserialize(const SerializationNode& node) const;
};
} // namespace OpenMM
#endif /*OPENMM_RMSDFORCE_PROXY_H_*/
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2018 Stanford University and the Authors. *
* Authors: Peter Eastman *
* 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. *
* -------------------------------------------------------------------------- */
#include "openmm/serialization/RMSDForceProxy.h"
#include "openmm/serialization/SerializationNode.h"
#include "openmm/Force.h"
#include "openmm/RMSDForce.h"
#include <sstream>
using namespace OpenMM;
using namespace std;
RMSDForceProxy::RMSDForceProxy() : SerializationProxy("RMSDForce") {
}
void RMSDForceProxy::serialize(const void* object, SerializationNode& node) const {
node.setIntProperty("version", 0);
const RMSDForce& force = *reinterpret_cast<const RMSDForce*>(object);
node.setIntProperty("forceGroup", force.getForceGroup());
SerializationNode& positionsNode = node.createChildNode("ReferencePositions");
for (const Vec3& pos : force.getReferencePositions())
positionsNode.createChildNode("Position").setDoubleProperty("x", pos[0]).setDoubleProperty("y", pos[1]).setDoubleProperty("z", pos[2]);
SerializationNode& particlesNode = node.createChildNode("Particles");
for (int i : force.getParticles())
particlesNode.createChildNode("Particle").setIntProperty("index", i);
}
void* RMSDForceProxy::deserialize(const SerializationNode& node) const {
int version = node.getIntProperty("version");
if (version != 0)
throw OpenMMException("Unsupported version number");
RMSDForce* force = NULL;
try {
vector<Vec3> positions;
for (auto& pos : node.getChildNode("ReferencePositions").getChildren())
positions.push_back(Vec3(pos.getDoubleProperty("x"), pos.getDoubleProperty("y"), pos.getDoubleProperty("z")));
vector<int> particles;
for (auto& particle : node.getChildNode("Particles").getChildren())
particles.push_back(particle.getIntProperty("index"));
force = new RMSDForce(positions, particles);
force->setForceGroup(node.getIntProperty("forceGroup", 0));
return force;
}
catch (...) {
if (force != NULL)
delete force;
throw;
}
}
......@@ -57,6 +57,7 @@
#include "openmm/NonbondedForce.h"
#include "openmm/PeriodicTorsionForce.h"
#include "openmm/RBTorsionForce.h"
#include "openmm/RMSDForce.h"
#include "openmm/System.h"
#include "openmm/TabulatedFunction.h"
#include "openmm/VariableLangevinIntegrator.h"
......@@ -92,6 +93,7 @@
#include "openmm/serialization/NonbondedForceProxy.h"
#include "openmm/serialization/PeriodicTorsionForceProxy.h"
#include "openmm/serialization/RBTorsionForceProxy.h"
#include "openmm/serialization/RMSDForceProxy.h"
#include "openmm/serialization/StateProxy.h"
#include "openmm/serialization/SystemProxy.h"
#include "openmm/serialization/TabulatedFunctionProxies.h"
......@@ -148,6 +150,7 @@ extern "C" void registerSerializationProxies() {
SerializationProxy::registerProxy(typeid(NonbondedForce), new NonbondedForceProxy());
SerializationProxy::registerProxy(typeid(PeriodicTorsionForce), new PeriodicTorsionForceProxy());
SerializationProxy::registerProxy(typeid(RBTorsionForce), new RBTorsionForceProxy());
SerializationProxy::registerProxy(typeid(RMSDForce), new RMSDForceProxy());
SerializationProxy::registerProxy(typeid(System), new SystemProxy());
SerializationProxy::registerProxy(typeid(State), new StateProxy());
SerializationProxy::registerProxy(typeid(VariableLangevinIntegrator), new VariableLangevinIntegratorProxy());
......
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2018 Stanford University and the Authors. *
* Authors: Peter Eastman *
* 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. *
* -------------------------------------------------------------------------- */
#include "openmm/internal/AssertionUtilities.h"
#include "openmm/RMSDForce.h"
#include "openmm/serialization/XmlSerializer.h"
#include <iostream>
#include <sstream>
using namespace OpenMM;
using namespace std;
void testSerialization() {
// Create a Force.
vector<Vec3> refPos;
for (int i = 0; i < 10; i++)
refPos.push_back(Vec3(i/5.0, i*1.2, i*i/3.5));
vector<int> particles;
for (int i = 0; i < 5; i++)
particles.push_back(i*i);
RMSDForce force(refPos, particles);
force.setForceGroup(3);
// Serialize and then deserialize it.
stringstream buffer;
XmlSerializer::serialize<RMSDForce>(&force, "Force", buffer);
RMSDForce* copy = XmlSerializer::deserialize<RMSDForce>(buffer);
// Compare the two forces to see if they are identical.
RMSDForce& force2 = *copy;
ASSERT_EQUAL(force.getForceGroup(), force2.getForceGroup());
ASSERT_EQUAL(force.getReferencePositions().size(), force2.getReferencePositions().size());
for (int i = 0; i < force.getReferencePositions().size(); i++)
ASSERT_EQUAL_VEC(force.getReferencePositions()[i], force2.getReferencePositions()[i], 0.0);
ASSERT_EQUAL(force.getParticles().size(), force2.getParticles().size());
for (int i = 0; i < force.getParticles().size(); i++)
ASSERT_EQUAL(force.getParticles()[i], force2.getParticles()[i]);
}
int main() {
try {
testSerialization();
}
catch(const exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
/* -------------------------------------------------------------------------- *
* OpenMM *
* -------------------------------------------------------------------------- *
* This is part of the OpenMM molecular simulation toolkit originating from *
* Simbios, the NIH National Center for Physics-Based Simulation of *
* Biological Structures at Stanford, funded under the NIH Roadmap for *
* Medical Research, grant U54 GM072970. See https://simtk.org. *
* *
* Portions copyright (c) 2018 Stanford University and the Authors. *
* Authors: Peter Eastman *
* 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. *
* -------------------------------------------------------------------------- */
#include "openmm/internal/AssertionUtilities.h"
#include "openmm/RMSDForce.h"
#include "openmm/Context.h"
#include "openmm/System.h"
#include "openmm/VerletIntegrator.h"
#include "sfmt/SFMT.h"
#include <cmath>
#include <iostream>
#include <vector>
using namespace OpenMM;
using namespace std;
double estimateRMSD(vector<Vec3>& positions, vector<Vec3>& referencePos, vector<int>& particles) {
// Estimate the RMSD. For simplicity we omit the orientation alignment, but they should
// already be almost perfectly aligned.
Vec3 center1, center2;
for (int i : particles) {
center1 += referencePos[i];
center2 += positions[i];
}
center1 /= particles.size();
center2 /= particles.size();
double estimate = 0.0;
for (int i : particles) {
Vec3 delta = (referencePos[i]-center1) - (positions[i]-center2);
estimate += delta.dot(delta);
}
return sqrt(estimate/particles.size());
}
void testRMSD() {
const int numParticles = 20;
System system;
vector<Vec3> referencePos(numParticles);
vector<Vec3> positions(numParticles);
vector<int> particles;
OpenMM_SFMT::SFMT sfmt;
init_gen_rand(0, sfmt);
for (int i = 0; i < numParticles; ++i) {
system.addParticle(1.0);
referencePos[i] = Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt))*10;
positions[i] = referencePos[i] + Vec3(genrand_real2(sfmt), genrand_real2(sfmt), genrand_real2(sfmt))*0.2;
if (i%5 != 0)
particles.push_back(i);
}
RMSDForce* force = new RMSDForce(referencePos, particles);
system.addForce(force);
VerletIntegrator integrator(0.001);
Context context(system, integrator, platform);
context.setPositions(positions);
double estimate = estimateRMSD(positions, referencePos, particles);
// Have the force compute the RMSD. It should be very slightly less than
// what we calculated above (since that omitted the rotation).
State state1 = context.getState(State::Energy);
double rmsd = state1.getPotentialEnergy();
ASSERT(rmsd <= estimate);
ASSERT(rmsd > 0.9*estimate);
// Translate and rotate all the particles. This should have no effect on the RMSD.
vector<Vec3> transformedPos(numParticles);
double cs = cos(1.1), sn = sin(1.1);
for (int i = 0; i < numParticles; i++) {
Vec3 p = positions[i];
transformedPos[i] = Vec3( cs*p[0] + sn*p[1] + 0.1,
-sn*p[0] + cs*p[1] - 11.3,
p[2] + 1.5);
}
context.setPositions(transformedPos);
state1 = context.getState(State::Energy | State::Forces);
ASSERT_EQUAL_TOL(rmsd, state1.getPotentialEnergy(), 1e-4);
// Take a small step in the direction of the energy gradient and see whether the potential energy changes by the expected amount.
const vector<Vec3>& forces = state1.getForces();
double norm = 0.0;
for (int i = 0; i < (int) forces.size(); ++i)
norm += forces[i].dot(forces[i]);
norm = std::sqrt(norm);
const double stepSize = 0.1;
double step = 0.5*stepSize/norm;
vector<Vec3> positions2(numParticles), positions3(numParticles);
for (int i = 0; i < (int) positions.size(); ++i) {
Vec3 p = transformedPos[i];
Vec3 f = forces[i];
positions2[i] = Vec3(p[0]-f[0]*step, p[1]-f[1]*step, p[2]-f[2]*step);
positions3[i] = Vec3(p[0]+f[0]*step, p[1]+f[1]*step, p[2]+f[2]*step);
}
context.setPositions(positions2);
State state2 = context.getState(State::Energy);
context.setPositions(positions3);
State state3 = context.getState(State::Energy);
ASSERT_EQUAL_TOL(norm, (state2.getPotentialEnergy()-state3.getPotentialEnergy())/stepSize, 1e-3);
// Check that updateParametersInContext() works correctly.
context.setPositions(transformedPos);
force->setReferencePositions(transformedPos);
force->updateParametersInContext(context);
ASSERT_EQUAL_TOL(0.0, context.getState(State::Energy).getPotentialEnergy(), 1e-2);
context.setPositions(referencePos);
ASSERT_EQUAL_TOL(rmsd, context.getState(State::Energy).getPotentialEnergy(), 1e-4);
// Verify that giving an empty list of particles is interpreted to mean all particles.
vector<int> allParticles;
for (int i = 0; i < numParticles; i++)
allParticles.push_back(i);
estimate = estimateRMSD(positions, referencePos, allParticles);
force->setParticles(allParticles);
force->setReferencePositions(referencePos);
force->updateParametersInContext(context);
context.setPositions(positions);
double rmsd1 = context.getState(State::Energy).getPotentialEnergy();
force->setParticles(vector<int>());
force->updateParametersInContext(context);
double rmsd2 = context.getState(State::Energy).getPotentialEnergy();
ASSERT_EQUAL_TOL(rmsd1, rmsd2, 1e-4);
ASSERT(rmsd1 <= estimate);
ASSERT(rmsd1 > 0.9*estimate);
}
void runPlatformTests();
int main(int argc, char* argv[]) {
try {
initializeTests(argc, argv);
testRMSD();
runPlatformTests();
}
catch(const exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
......@@ -453,5 +453,7 @@ UNITS = {
("DrudeSCFIntegrator", "getMinimizationErrorTolerance") : ("unit.kilojoules_per_mole/unit.nanometer", ()),
("RPMDIntegrator", "getContractions") : (None, ()),
("RPMDIntegrator", "getTotalEnergy") : ("unit.kilojoules_per_mole", ()),
("RMSDForce", "getReferencePositions") : ("unit.nanometer", ()),
("RMSDForce", "getParticles") : (None, ()),
}
......@@ -415,11 +415,14 @@ int Py_SequenceToVecVecVecDouble(PyObject* obj, std::vector<std::vector<std::vec
$1 = &v;
}
%typemap(typecheck, precedence=SWIG_TYPECHECK_DOUBLE_ARRAY, fragment="Py_SequenceToVecVec3") const std::vector<Vec3>& {
std::vector<double> v;
std::vector<Vec3> v;
int res=0;
res = Py_SequenceToVecVec3($input, v);
$1 = SWIG_IsOK(res);
}
%typemap(out) const std::vector<Vec3>& {
$result = copyVVec3ToList(*$1);
}
// typemap for const vector<double>
......
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