Commit 70cfae96 authored by peastman's avatar peastman
Browse files

Reference implementation of CustomCVForce

parent 74b4d450
...@@ -32,10 +32,11 @@ ...@@ -32,10 +32,11 @@
* USE OR OTHER DEALINGS IN THE SOFTWARE. * * USE OR OTHER DEALINGS IN THE SOFTWARE. *
* -------------------------------------------------------------------------- */ * -------------------------------------------------------------------------- */
#include "TabulatedFunction.h"
#include "Force.h" #include "Force.h"
#include <vector> #include "TabulatedFunction.h"
#include "internal/windowsExport.h" #include "internal/windowsExport.h"
#include <string>
#include <vector>
namespace OpenMM { namespace OpenMM {
...@@ -236,6 +237,22 @@ public: ...@@ -236,6 +237,22 @@ public:
* stored into this * stored into this
*/ */
void getCollectiveVariableValues(Context& context, std::vector<double>& values); void getCollectiveVariableValues(Context& context, std::vector<double>& values);
/**
* Get the inner Context used for evaluating collective variables.
*
* When you create a Context for a System that contains a CustomCVForce, internally
* it creates a new System, adds the Forces that define the CVs to it, creates a new
* Context for that System, and uses it to evaluate the variables. In most cases you
* can ignore all of this. It is just an implementation detail. However, there are
* a few cases where you need to directly access that internal Context. For example,
* if you want to modify one of the Forces that defines a collective variable and
* call updateParametersInContext() on it, you need to pass that inner Context to it.
* This method returns a reference to it.
*
* @param context the Context containing the CustomCVForce
* @return the inner Context used to evaluate the collective variables
*/
Context& getInnerContext(Context& context);
/** /**
* Returns whether or not this force makes use of periodic boundary * Returns whether or not this force makes use of periodic boundary
* conditions. * conditions.
......
...@@ -63,6 +63,7 @@ public: ...@@ -63,6 +63,7 @@ public:
std::map<std::string, double> getDefaultParameters(); std::map<std::string, double> getDefaultParameters();
std::vector<std::string> getKernelNames(); std::vector<std::string> getKernelNames();
void getCollectiveVariableValues(ContextImpl& context, std::vector<double>& values); void getCollectiveVariableValues(ContextImpl& context, std::vector<double>& values);
Context& getInnerContext();
private: private:
const CustomCVForce& owner; const CustomCVForce& owner;
Kernel kernel; Kernel kernel;
......
...@@ -119,8 +119,6 @@ ContextImpl::ContextImpl(Context& owner, const System& system, Integrator& integ ...@@ -119,8 +119,6 @@ ContextImpl::ContextImpl(Context& owner, const System& system, Integrator& integ
kernelNames.push_back(VirtualSitesKernel::Name()); kernelNames.push_back(VirtualSitesKernel::Name());
for (int i = 0; i < system.getNumForces(); ++i) { for (int i = 0; i < system.getNumForces(); ++i) {
forceImpls.push_back(system.getForce(i).createImpl()); forceImpls.push_back(system.getForce(i).createImpl());
map<string, double> forceParameters = forceImpls[forceImpls.size()-1]->getDefaultParameters();
parameters.insert(forceParameters.begin(), forceParameters.end());
vector<string> forceKernels = forceImpls[forceImpls.size()-1]->getKernelNames(); vector<string> forceKernels = forceImpls[forceImpls.size()-1]->getKernelNames();
kernelNames.insert(kernelNames.begin(), forceKernels.begin(), forceKernels.end()); kernelNames.insert(kernelNames.begin(), forceKernels.begin(), forceKernels.end());
} }
...@@ -177,8 +175,11 @@ ContextImpl::ContextImpl(Context& owner, const System& system, Integrator& integ ...@@ -177,8 +175,11 @@ ContextImpl::ContextImpl(Context& owner, const System& system, Integrator& integ
Vec3 periodicBoxVectors[3]; Vec3 periodicBoxVectors[3];
system.getDefaultPeriodicBoxVectors(periodicBoxVectors[0], periodicBoxVectors[1], periodicBoxVectors[2]); system.getDefaultPeriodicBoxVectors(periodicBoxVectors[0], periodicBoxVectors[1], periodicBoxVectors[2]);
updateStateDataKernel.getAs<UpdateStateDataKernel>().setPeriodicBoxVectors(*this, periodicBoxVectors[0], periodicBoxVectors[1], periodicBoxVectors[2]); updateStateDataKernel.getAs<UpdateStateDataKernel>().setPeriodicBoxVectors(*this, periodicBoxVectors[0], periodicBoxVectors[1], periodicBoxVectors[2]);
for (size_t i = 0; i < forceImpls.size(); ++i) for (size_t i = 0; i < forceImpls.size(); ++i) {
forceImpls[i]->initialize(*this); forceImpls[i]->initialize(*this);
map<string, double> forceParameters = forceImpls[i]->getDefaultParameters();
parameters.insert(forceParameters.begin(), forceParameters.end());
}
integrator.initialize(*this); integrator.initialize(*this);
updateStateDataKernel.getAs<UpdateStateDataKernel>().setVelocities(*this, vector<Vec3>(numParticles)); updateStateDataKernel.getAs<UpdateStateDataKernel>().setVelocities(*this, vector<Vec3>(numParticles));
} }
......
...@@ -148,6 +148,10 @@ ForceImpl* CustomCVForce::createImpl() const { ...@@ -148,6 +148,10 @@ ForceImpl* CustomCVForce::createImpl() const {
return new CustomCVForceImpl(*this); return new CustomCVForceImpl(*this);
} }
Context& CustomCVForce::getInnerContext(Context& context) {
return dynamic_cast<CustomCVForceImpl&>(getImplInContext(context)).getInnerContext();
}
bool CustomCVForce::usesPeriodicBoundaryConditions() const { bool CustomCVForce::usesPeriodicBoundaryConditions() const {
for (auto& variable : variables) for (auto& variable : variables)
if (variable.variable->usesPeriodicBoundaryConditions()) if (variable.variable->usesPeriodicBoundaryConditions())
......
...@@ -71,6 +71,8 @@ void CustomCVForceImpl::initialize(ContextImpl& context) { ...@@ -71,6 +71,8 @@ void CustomCVForceImpl::initialize(ContextImpl& context) {
for (auto& name : platform.getPropertyNames()) for (auto& name : platform.getPropertyNames())
properties[name] = platform.getPropertyValue(context.getOwner(), name); properties[name] = platform.getPropertyValue(context.getOwner(), name);
innerContext = new Context(innerSystem, innerIntegrator, platform, properties); innerContext = new Context(innerSystem, innerIntegrator, platform, properties);
vector<Vec3> positions(system.getNumParticles(), Vec3());
innerContext->setPositions(positions);
// Create the kernel. // Create the kernel.
...@@ -92,6 +94,7 @@ vector<string> CustomCVForceImpl::getKernelNames() { ...@@ -92,6 +94,7 @@ vector<string> CustomCVForceImpl::getKernelNames() {
map<string, double> CustomCVForceImpl::getDefaultParameters() { map<string, double> CustomCVForceImpl::getDefaultParameters() {
map<string, double> parameters; map<string, double> parameters;
parameters.insert(innerContext->getParameters().begin(), innerContext->getParameters().end());
for (int i = 0; i < owner.getNumGlobalParameters(); i++) for (int i = 0; i < owner.getNumGlobalParameters(); i++)
parameters[owner.getGlobalParameterName(i)] = owner.getGlobalParameterDefaultValue(i); parameters[owner.getGlobalParameterName(i)] = owner.getGlobalParameterDefaultValue(i);
return parameters; return parameters;
...@@ -101,7 +104,11 @@ void CustomCVForceImpl::getCollectiveVariableValues(ContextImpl& context, vector ...@@ -101,7 +104,11 @@ void CustomCVForceImpl::getCollectiveVariableValues(ContextImpl& context, vector
kernel.getAs<CalcCustomCVForceKernel>().copyState(context, getContextImpl(*innerContext)); kernel.getAs<CalcCustomCVForceKernel>().copyState(context, getContextImpl(*innerContext));
values.clear(); values.clear();
for (int i = 0; i < innerSystem.getNumForces(); i++) { for (int i = 0; i < innerSystem.getNumForces(); i++) {
double value = innerContext->getState(State::Energy).getPotentialEnergy(); double value = innerContext->getState(State::Energy, false, 1<<i).getPotentialEnergy();
values.push_back(value); values.push_back(value);
} }
} }
Context& CustomCVForceImpl::getInnerContext() {
return *innerContext;
}
/* Portions copyright (c) 2017 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 __ReferenceCustomCVForce_H__
#define __ReferenceCustomCVForce_H__
#include "openmm/CustomCVForce.h"
#include "openmm/internal/ContextImpl.h"
#include "lepton/ExpressionProgram.h"
#include <map>
#include <string>
#include <vector>
namespace OpenMM {
class ReferenceCustomCVForce {
private:
Lepton::ExpressionProgram energyExpression;
std::vector<std::string> variableNames, paramDerivNames;
std::vector<Lepton::ExpressionProgram> variableDerivExpressions;
std::vector<Lepton::ExpressionProgram> paramDerivExpressions;
public:
/**
* Constructor
*/
ReferenceCustomCVForce(const OpenMM::CustomCVForce& force);
/**
* Destructor
*/
~ReferenceCustomCVForce();
/**
* Calculate the interaction.
*
* @param innerContext the context created by the force for evaluating collective variables
* @param atomCoordinates atom coordinates
* @param globalParameters the values of global parameters
* @param forces the forces are added to this
* @param totalEnergy the energy is added to this
* @param energyParamDerivs parameter derivatives are added to this
*/
void calculateIxn(ContextImpl& innerContext, std::vector<OpenMM::Vec3>& atomCoordinates,
const std::map<std::string, double>& globalParameters,
std::vector<OpenMM::Vec3>& forces, double* totalEnergy, std::map<std::string, double>& energyParamDerivs) const;
};
} // namespace OpenMM
#endif // __ReferenceCustomCVForce_H__
...@@ -45,6 +45,7 @@ class ReferenceObc; ...@@ -45,6 +45,7 @@ class ReferenceObc;
class ReferenceAndersenThermostat; class ReferenceAndersenThermostat;
class ReferenceCustomCentroidBondIxn; class ReferenceCustomCentroidBondIxn;
class ReferenceCustomCompoundBondIxn; class ReferenceCustomCompoundBondIxn;
class ReferenceCustomCVForce;
class ReferenceCustomHbondIxn; class ReferenceCustomHbondIxn;
class ReferenceCustomManyParticleIxn; class ReferenceCustomManyParticleIxn;
class ReferenceGayBerneForce; class ReferenceGayBerneForce;
...@@ -1006,6 +1007,43 @@ private: ...@@ -1006,6 +1007,43 @@ private:
ReferenceGayBerneForce* ixn; ReferenceGayBerneForce* ixn;
}; };
/**
* This kernel is invoked by CustomCVForce to calculate the forces acting on the system and the energy of the system.
*/
class ReferenceCalcCustomCVForceKernel : public CalcCustomCVForceKernel {
public:
ReferenceCalcCustomCVForceKernel(std::string name, const Platform& platform) : CalcCustomCVForceKernel(name, platform), ixn(NULL) {
}
~ReferenceCalcCustomCVForceKernel();
/**
* Initialize the kernel.
*
* @param system the System this kernel will be applied to
* @param force the CustomCVForce this kernel will be used for
*/
void initialize(const System& system, const CustomCVForce& force);
/**
* Execute the kernel to calculate the forces and/or energy.
*
* @param context the context in which to execute this kernel
* @param innerContext the context created by the CustomCVForce for computing collective variables
* @param includeForces true if forces should be calculated
* @param includeEnergy true if the energy should be calculated
* @return the potential energy due to the force
*/
double execute(ContextImpl& context, ContextImpl& innerContext, bool includeForces, bool includeEnergy);
/**
* Copy state information to the inner context.
*
* @param context the context in which to execute this kernel
* @param innerContext the context created by the CustomCVForce for computing collective variables
*/
void copyState(ContextImpl& context, ContextImpl& innerContext);
private:
ReferenceCustomCVForce* ixn;
std::vector<std::string> globalParameterNames, energyParamDerivNames;
};
/** /**
* This kernel is invoked by VerletIntegrator to take one time step. * This kernel is invoked by VerletIntegrator to take one time step.
*/ */
......
...@@ -78,6 +78,8 @@ KernelImpl* ReferenceKernelFactory::createKernelImpl(std::string name, const Pla ...@@ -78,6 +78,8 @@ KernelImpl* ReferenceKernelFactory::createKernelImpl(std::string name, const Pla
return new ReferenceCalcCustomCentroidBondForceKernel(name, platform); return new ReferenceCalcCustomCentroidBondForceKernel(name, platform);
if (name == CalcCustomCompoundBondForceKernel::Name()) if (name == CalcCustomCompoundBondForceKernel::Name())
return new ReferenceCalcCustomCompoundBondForceKernel(name, platform); return new ReferenceCalcCustomCompoundBondForceKernel(name, platform);
if (name == CalcCustomCVForceKernel::Name())
return new ReferenceCalcCustomCVForceKernel(name, platform);
if (name == CalcCustomManyParticleForceKernel::Name()) if (name == CalcCustomManyParticleForceKernel::Name())
return new ReferenceCalcCustomManyParticleForceKernel(name, platform); return new ReferenceCalcCustomManyParticleForceKernel(name, platform);
if (name == CalcGayBerneForceKernel::Name()) if (name == CalcGayBerneForceKernel::Name())
......
...@@ -42,6 +42,7 @@ ...@@ -42,6 +42,7 @@
#include "ReferenceCustomBondIxn.h" #include "ReferenceCustomBondIxn.h"
#include "ReferenceCustomCentroidBondIxn.h" #include "ReferenceCustomCentroidBondIxn.h"
#include "ReferenceCustomCompoundBondIxn.h" #include "ReferenceCustomCompoundBondIxn.h"
#include "ReferenceCustomCVForce.h"
#include "ReferenceCustomDynamics.h" #include "ReferenceCustomDynamics.h"
#include "ReferenceCustomExternalIxn.h" #include "ReferenceCustomExternalIxn.h"
#include "ReferenceCustomGBIxn.h" #include "ReferenceCustomGBIxn.h"
...@@ -2015,6 +2016,44 @@ void ReferenceCalcGayBerneForceKernel::copyParametersToContext(ContextImpl& cont ...@@ -2015,6 +2016,44 @@ void ReferenceCalcGayBerneForceKernel::copyParametersToContext(ContextImpl& cont
ixn = new ReferenceGayBerneForce(force); ixn = new ReferenceGayBerneForce(force);
} }
ReferenceCalcCustomCVForceKernel::~ReferenceCalcCustomCVForceKernel() {
if (ixn != NULL)
delete ixn;
}
void ReferenceCalcCustomCVForceKernel::initialize(const System& system, const CustomCVForce& force) {
for (int i = 0; i < force.getNumGlobalParameters(); i++)
globalParameterNames.push_back(force.getGlobalParameterName(i));
for (int i = 0; i < force.getNumEnergyParameterDerivatives(); i++)
energyParamDerivNames.push_back(force.getEnergyParameterDerivativeName(i));
ixn = new ReferenceCustomCVForce(force);
}
double ReferenceCalcCustomCVForceKernel::execute(ContextImpl& context, ContextImpl& innerContext, bool includeForces, bool includeEnergy) {
copyState(context, innerContext);
vector<Vec3>& posData = extractPositions(context);
vector<Vec3>& forceData = extractForces(context);
double energy = 0;
map<string, double> globalParameters;
for (auto& name : globalParameterNames)
globalParameters[name] = context.getParameter(name);
map<string, double>& energyParamDerivs = extractEnergyParameterDerivatives(context);
ixn->calculateIxn(innerContext, posData, globalParameters, forceData, includeEnergy ? &energy : NULL, energyParamDerivs);
return energy;
}
void ReferenceCalcCustomCVForceKernel::copyState(ContextImpl& context, ContextImpl& innerContext) {
extractPositions(innerContext) = extractPositions(context);
extractVelocities(innerContext) = extractVelocities(context);
extractBoxSize(innerContext) = extractBoxSize(context);
for (int i = 0; i < 3; i++)
extractBoxVectors(innerContext)[i] = extractBoxVectors(context)[i];
reinterpret_cast<ReferencePlatform::PlatformData*>(innerContext.getPlatformData())->time = reinterpret_cast<ReferencePlatform::PlatformData*>(context.getPlatformData())->time;
map<string, double> innerParameters = innerContext.getParameters();
for (auto& param : innerParameters)
innerContext.setParameter(param.first, context.getParameter(param.first));
}
ReferenceIntegrateVerletStepKernel::~ReferenceIntegrateVerletStepKernel() { ReferenceIntegrateVerletStepKernel::~ReferenceIntegrateVerletStepKernel() {
if (dynamics) if (dynamics)
delete dynamics; delete dynamics;
......
...@@ -64,6 +64,7 @@ ReferencePlatform::ReferencePlatform() { ...@@ -64,6 +64,7 @@ ReferencePlatform::ReferencePlatform() {
registerKernelFactory(CalcCustomHbondForceKernel::Name(), factory); registerKernelFactory(CalcCustomHbondForceKernel::Name(), factory);
registerKernelFactory(CalcCustomCentroidBondForceKernel::Name(), factory); registerKernelFactory(CalcCustomCentroidBondForceKernel::Name(), factory);
registerKernelFactory(CalcCustomCompoundBondForceKernel::Name(), factory); registerKernelFactory(CalcCustomCompoundBondForceKernel::Name(), factory);
registerKernelFactory(CalcCustomCVForceKernel::Name(), factory);
registerKernelFactory(CalcCustomManyParticleForceKernel::Name(), factory); registerKernelFactory(CalcCustomManyParticleForceKernel::Name(), factory);
registerKernelFactory(CalcGayBerneForceKernel::Name(), factory); registerKernelFactory(CalcGayBerneForceKernel::Name(), factory);
registerKernelFactory(IntegrateVerletStepKernel::Name(), factory); registerKernelFactory(IntegrateVerletStepKernel::Name(), factory);
......
/* Portions copyright (c) 2009-2017 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 "ReferenceCustomCVForce.h"
#include "ReferencePlatform.h"
#include "ReferenceTabulatedFunction.h"
#include "lepton/CustomFunction.h"
#include "lepton/ParsedExpression.h"
#include "lepton/Parser.h"
using namespace OpenMM;
using namespace std;
ReferenceCustomCVForce::ReferenceCustomCVForce(const CustomCVForce& force) {
// Create custom functions for the tabulated functions.
map<string, Lepton::CustomFunction*> functions;
for (int i = 0; i < (int) force.getNumTabulatedFunctions(); i++)
functions[force.getTabulatedFunctionName(i)] = createReferenceTabulatedFunction(force.getTabulatedFunction(i));
// Create the expressions.
Lepton::ParsedExpression energyExpr = Lepton::Parser::parse(force.getEnergyFunction(), functions);
energyExpression = energyExpr.createProgram();
for (int i = 0; i < force.getNumCollectiveVariables(); i++) {
string name = force.getCollectiveVariableName(i);
variableNames.push_back(name);
variableDerivExpressions.push_back(energyExpr.differentiate(name).optimize().createProgram());
}
for (int i = 0; i < force.getNumEnergyParameterDerivatives(); i++) {
string name = force.getEnergyParameterDerivativeName(i);
paramDerivNames.push_back(name);
paramDerivExpressions.push_back(energyExpr.differentiate(name).optimize().createProgram());
}
// Delete the custom functions.
for (auto& function : functions)
delete function.second;
}
ReferenceCustomCVForce::~ReferenceCustomCVForce() {
}
void ReferenceCustomCVForce::calculateIxn(ContextImpl& innerContext, vector<Vec3>& atomCoordinates,
const map<string, double>& globalParameters, vector<Vec3>& forces,
double* totalEnergy, map<string, double>& energyParamDerivs) const {
// Compute the collective variables, and their derivatives with respect to particle positions.
int numCVs = variableNames.size();
ReferencePlatform::PlatformData* data = reinterpret_cast<ReferencePlatform::PlatformData*>(innerContext.getPlatformData());
vector<Vec3>& innerForces = *((vector<Vec3>*) data->forces);
map<string, double>& innerDerivs = *((map<string, double>*) data->energyParameterDerivatives);
vector<double> cvValues;
vector<vector<Vec3> > cvForces;
vector<map<string, double> > cvDerivs;
for (int i = 0; i < numCVs; i++) {
cvValues.push_back(innerContext.calcForcesAndEnergy(true, true, 1<<i));
cvForces.push_back(innerForces);
cvDerivs.push_back(innerDerivs);
}
// Compute the energy and forces.
int numParticles = atomCoordinates.size();
map<string, double> variables = globalParameters;
for (int i = 0; i < numCVs; i++)
variables[variableNames[i]] = cvValues[i];
if (totalEnergy != NULL)
*totalEnergy += energyExpression.evaluate(variables);
for (int i = 0; i < numCVs; i++) {
double dEdV = variableDerivExpressions[i].evaluate(variables);
for (int j = 0; j < numParticles; j++)
forces[j] += cvForces[i][j]*dEdV;
}
// Compute the energy parameter derivatives.
for (int i = 0; i < paramDerivExpressions.size(); i++)
energyParamDerivs[paramDerivNames[i]] += paramDerivExpressions[i].evaluate(variables);
for (int i = 0; i < numCVs; i++) {
double dEdV = variableDerivExpressions[i].evaluate(variables);
for (auto& deriv : cvDerivs[i])
energyParamDerivs[deriv.first] += dEdV*deriv.second;
}
}
/* -------------------------------------------------------------------------- *
* 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) 2017 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 "TestCustomCVForce.h"
void runPlatformTests() {
}
/* -------------------------------------------------------------------------- *
* 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) 2017 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. *
* -------------------------------------------------------------------------- */
#ifdef WIN32
#define _USE_MATH_DEFINES // Needed to get M_PI
#endif
#include "openmm/internal/AssertionUtilities.h"
#include "openmm/Context.h"
#include "openmm/CustomBondForce.h"
#include "openmm/CustomCVForce.h"
#include "openmm/CustomExternalForce.h"
#include "openmm/System.h"
#include "openmm/VerletIntegrator.h"
#include <iostream>
#include <vector>
using namespace OpenMM;
using namespace std;
void testCVs() {
System system;
system.addParticle(1.0);
system.addParticle(1.0);
system.addParticle(1.0);
// Create a CustomCVForce with two collective variables.
CustomCVForce* cv = new CustomCVForce("v1+3*v2");
system.addForce(cv);
CustomBondForce* v1 = new CustomBondForce("2*r");
v1->addBond(0, 1);
cv->addCollectiveVariable("v1", v1);
CustomBondForce* v2 = new CustomBondForce("r");
v2->addBond(0, 2);
cv->addCollectiveVariable("v2", v2);
ASSERT(!cv->usesPeriodicBoundaryConditions());
// Create a context for evaluating it.
VerletIntegrator integrator(1.0);
Context context(system, integrator, platform);
vector<Vec3> positions(3);
positions[0] = Vec3(0, 0, 0);
positions[1] = Vec3(1.5, 0, 0);
positions[2] = Vec3(0, 0, 2.5);
context.setPositions(positions);
// Verify the values of the collective variables.
vector<double> values;
cv->getCollectiveVariableValues(context, values);
ASSERT_EQUAL_TOL(2*1.5, values[0], 1e-6);
ASSERT_EQUAL_TOL(2.5, values[1], 1e-6);
// Verify the energy and forces.
State state = context.getState(State::Energy | State::Forces);
ASSERT_EQUAL_TOL(2*1.5+3*2.5, state.getPotentialEnergy(), 1e-6);
ASSERT_EQUAL_VEC(Vec3(2.0, 0.0, 3.0), state.getForces()[0], 1e-6);
ASSERT_EQUAL_VEC(Vec3(-2.0, 0.0, 0.0), state.getForces()[1], 1e-6);
ASSERT_EQUAL_VEC(Vec3(0.0, 0.0, -3.0), state.getForces()[2], 1e-6);
}
void testEnergyParameterDerivatives() {
System system;
system.addParticle(1.0);
system.addParticle(1.0);
// Create a CustomCVForce with one collective variable and two global parameters.
// The CV in turn depends on a global parameter.
CustomCVForce* cv = new CustomCVForce("v1*g1+g2");
system.addForce(cv);
CustomBondForce* v1 = new CustomBondForce("r*g3");
v1->addGlobalParameter("g3", 2.0);
v1->addEnergyParameterDerivative("g3");
v1->addBond(0, 1);
cv->addCollectiveVariable("v1", v1);
cv->addGlobalParameter("g1", 1.5);
cv->addGlobalParameter("g2", -1.0);
cv->addEnergyParameterDerivative("g2");
cv->addEnergyParameterDerivative("g1");
// Create a context for evaluating it.
VerletIntegrator integrator(1.0);
Context context(system, integrator, platform);
vector<Vec3> positions(2);
positions[0] = Vec3(0, 0, 0);
positions[1] = Vec3(2.0, 0, 0);
context.setPositions(positions);
// Verify the energy and parameter derivatives.
State state = context.getState(State::Energy | State::ParameterDerivatives);
ASSERT_EQUAL_TOL(4.0*1.5-1.0, state.getPotentialEnergy(), 1e-6);
map<string, double> derivs = state.getEnergyParameterDerivatives();
ASSERT_EQUAL_TOL(4.0, derivs["g1"], 1e-6);
ASSERT_EQUAL_TOL(1.0, derivs["g2"], 1e-6);
ASSERT_EQUAL_TOL(2.0*1.5, derivs["g3"], 1e-6);
}
void testTabulatedFunction() {
const int xsize = 10;
const int ysize = 11;
const double xmin = 0.4;
const double xmax = 1.1;
const double ymin = 0.0;
const double ymax = 0.95;
System system;
system.addParticle(1.0);
VerletIntegrator integrator(0.01);
CustomCVForce* cv = new CustomCVForce("fn(x,y)+1");
CustomExternalForce* v1 = new CustomExternalForce("x");
v1->addParticle(0);
cv->addCollectiveVariable("x", v1);
CustomExternalForce* v2 = new CustomExternalForce("y");
v2->addParticle(0);
cv->addCollectiveVariable("y", v2);
vector<double> table(xsize*ysize);
for (int i = 0; i < xsize; i++) {
for (int j = 0; j < ysize; j++) {
double x = xmin + i*(xmax-xmin)/xsize;
double y = ymin + j*(ymax-ymin)/ysize;
table[i+xsize*j] = sin(0.25*x)*cos(0.33*y);
}
}
cv->addTabulatedFunction("fn", new Continuous2DFunction(xsize, ysize, table, xmin, xmax, ymin, ymax));
system.addForce(cv);
Context context(system, integrator, platform);
vector<Vec3> positions(1);
for (double x = xmin-0.15; x < xmax+0.2; x += 0.1) {
for (double y = ymin-0.15; y < ymax+0.2; y += 0.1) {
positions[0] = Vec3(x, y, 1.5);
context.setPositions(positions);
State state = context.getState(State::Forces | State::Energy);
const vector<Vec3>& forces = state.getForces();
double energy = 1;
Vec3 force(0, 0, 0);
if (x >= xmin && x <= xmax && y >= ymin && y <= ymax) {
energy = sin(0.25*x)*cos(0.33*y)+1;
force[0] = -0.25*cos(0.25*x)*cos(0.33*y);
force[1] = 0.3*sin(0.25*x)*sin(0.33*y);
}
ASSERT_EQUAL_VEC(force, forces[0], 0.1);
ASSERT_EQUAL_TOL(energy, state.getPotentialEnergy(), 0.05);
}
}
}
void runPlatformTests();
int main(int argc, char* argv[]) {
try {
initializeTests(argc, argv);
testCVs();
testEnergyParameterDerivatives();
testTabulatedFunction();
runPlatformTests();
}
catch(const exception& e) {
cout << "exception: " << e.what() << endl;
return 1;
}
cout << "Done" << endl;
return 0;
}
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