ReferenceCustomDynamics.cpp 18.8 KB
Newer Older
1

2
/* Portions copyright (c) 2011-2017 Stanford University and Simbios.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 * 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.
 */

25
#include "SimTKOpenMMUtilities.h"
26
#include "ReferenceVirtualSites.h"
27
#include "ReferenceCustomDynamics.h"
28
#include "ReferenceTabulatedFunction.h"
29
#include "openmm/OpenMMException.h"
30
31
32
#include "openmm/internal/ContextImpl.h"
#include "openmm/internal/ForceImpl.h"
#include "lepton/Operation.h"
33
34
#include "lepton/ParsedExpression.h"
#include "lepton/Parser.h"
35
#include <set>
36
#include <sstream>
37
38
39

using namespace std;
using namespace OpenMM;
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
using namespace Lepton;

class ReferenceCustomDynamics::DerivFunction : public CustomFunction {
public:
    DerivFunction(map<string, double>& energyParamDerivs, const string& param) : energyParamDerivs(energyParamDerivs), param(param) {
    }
    int getNumArguments() const {
        return 0;
    }
    double evaluate(const double* arguments) const {
        return energyParamDerivs[param];
    }
    double evaluateDerivative(const double* arguments, const int* derivOrder) const {
        return 0;
    }
    CustomFunction* clone() const {
        return new DerivFunction(energyParamDerivs, param);
    }
private:
    map<string, double>& energyParamDerivs;
    string param;
};
62
63
64
65
66
67
68
69
70
71
72
73

/**---------------------------------------------------------------------------------------

   ReferenceCustomDynamics constructor

   @param numberOfAtoms  number of atoms
   @param integrator     the integrator definition to use

   --------------------------------------------------------------------------------------- */

ReferenceCustomDynamics::ReferenceCustomDynamics(int numberOfAtoms, const CustomIntegrator& integrator) : 
           ReferenceDynamics(numberOfAtoms, integrator.getStepSize(), 0.0), integrator(integrator) {
74
    sumBuffer.resize(numberOfAtoms);
75
    oldPos.resize(numberOfAtoms);
76
77
78
79
80
    stepType.resize(integrator.getNumComputations());
    stepVariable.resize(integrator.getNumComputations());
    for (int i = 0; i < integrator.getNumComputations(); i++) {
        string expression;
        integrator.getComputationStep(i, stepType[i], stepVariable[i], expression);
81
    }
82
83
84
85
86
87
88
89
90
91
92
}

/**---------------------------------------------------------------------------------------

   ReferenceCustomDynamics destructor

   --------------------------------------------------------------------------------------- */

ReferenceCustomDynamics::~ReferenceCustomDynamics() {
}

peastman's avatar
peastman committed
93
void ReferenceCustomDynamics::initialize(ContextImpl& context, vector<double>& masses, map<string, double>& globals) {
94
95
96
    // Some initialization can't be done in the constructor, since we need a ContextImpl from which to get the list of
    // Context parameters.  Instead, we do it the first time update() or computeKineticEnergy() is called.

97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
    std::map<std::string, double*> variableLocations;
    variableLocations["x"] = &x;
    variableLocations["v"] = &v;
    variableLocations["m"] = &m;
    variableLocations["f"] = &f;
    variableLocations["energy"] = &energy;
    variableLocations["gaussian"] = &gaussian;
    variableLocations["uniform"] = &uniform;
    perDofVariable.resize(integrator.getNumPerDofVariables());
    for (int i = 0; i < integrator.getNumPerDofVariables(); i++)
        variableLocations[integrator.getPerDofVariableName(i)] = &perDofVariable[i];
    for (int i = 0; i < 32; i++) {
        stringstream fname;
        fname << "f" << i;
        variableLocations[fname.str()] = &f;
        stringstream ename;
        ename << "energy" << i;
        variableLocations[ename.str()] = &energy;
    }
    
117
118
119
120
121
122
    // Create custom functions for the tabulated functions.

    map<string, Lepton::CustomFunction*> functions;
    for (int i = 0; i < integrator.getNumTabulatedFunctions(); i++)
        functions[integrator.getTabulatedFunctionName(i)] = createReferenceTabulatedFunction(integrator.getTabulatedFunction(i));
    
123
124
    // Parse the expressions.
    
125
126
    int numSteps = stepType.size();
    vector<int> forceGroup;
127
    vector<vector<ParsedExpression> > expressions;
128
    CustomIntegratorUtilities::analyzeComputations(context, integrator, expressions, comparisons, blockEnd, invalidatesForces, needsForces, needsEnergy, computeBothForceAndEnergy, forceGroup, functions);
129
130
131
132
    stepExpressions.resize(expressions.size());
    for (int i = 0; i < numSteps; i++) {
        stepExpressions[i].resize(expressions[i].size());
        for (int j = 0; j < (int) expressions[i].size(); j++) {
133
            stepExpressions[i][j] = ParsedExpression(replaceDerivFunctions(expressions[i][j].getRootNode(), context)).createCompiledExpression();
134
            stepExpressions[i][j].setVariableLocations(variableLocations);
135
136
137
138
139
            expressionSet.registerExpression(stepExpressions[i][j]);
        }
        if (stepType[i] == CustomIntegrator::WhileBlockStart)
            blockEnd[blockEnd[i]] = i; // Record where to branch back to.
    }
140
141
142
143
144
145
    kineticEnergyExpression = Parser::parse(integrator.getKineticEnergyExpression()).optimize().createCompiledExpression();
    kineticEnergyExpression.setVariableLocations(variableLocations);
    expressionSet.registerExpression(kineticEnergyExpression);
    kineticEnergyNeedsForce = false;
    if (kineticEnergyExpression.getVariables().find("f") != kineticEnergyExpression.getVariables().end())
        kineticEnergyNeedsForce = true;
146

147
148
149
150
151
    // Delete the custom functions.

    for (auto& function : functions)
        delete function.second;

152
    // Record the force group flags for each step.
153
154

    forceGroupFlags.resize(numSteps, -1);
155
    for (int i = 0; i < numSteps; i++)
156
157
158
159
160
161
162
163
164
165
166
167
168
169
        if (forceGroup[i] > -1)
            forceGroupFlags[i] = 1<<forceGroup[i];

    // Build the list of inverse masses.

    int numberOfAtoms = masses.size();
    inverseMasses.resize(numberOfAtoms);
    for (int i = 0; i < numberOfAtoms; i++) {
        if (masses[i] == 0.0)
            inverseMasses[i] = 0.0;
        else
            inverseMasses[i] = 1.0/masses[i];
    }

170
    // Record indices of variables.
171
172
173
174
175
176
177
178
179

    xIndex = expressionSet.getVariableIndex("x");
    vIndex = expressionSet.getVariableIndex("v");
    for (int i = 0; i < integrator.getNumPerDofVariables(); i++)
        perDofVariableIndex.push_back(expressionSet.getVariableIndex(integrator.getPerDofVariableName(i)));
    for (int i = 0; i < stepVariable.size(); i++)
        stepVariableIndex.push_back(expressionSet.getVariableIndex(stepVariable[i]));
}

180
181
182
183
184
185
186
187
188
189
ExpressionTreeNode ReferenceCustomDynamics::replaceDerivFunctions(const ExpressionTreeNode& node, ContextImpl& context) {
    const Operation& op = node.getOperation();
    if (op.getId() == Operation::CUSTOM && op.getName() == "deriv") {
        string param = node.getChildren()[1].getOperation().getName();
        if (context.getParameters().find(param) == context.getParameters().end())
            throw OpenMMException("The second argument to deriv() must be a context parameter");
        return ExpressionTreeNode(new Operation::Custom("deriv", new DerivFunction(energyParamDerivs, param)));
    }
    else {
        vector<ExpressionTreeNode> children;
peastman's avatar
peastman committed
190
191
        for (auto& child : node.getChildren())
            children.push_back(replaceDerivFunctions(child, context));
192
193
194
195
        return ExpressionTreeNode(op.clone(), children);
    }
}

196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
/**---------------------------------------------------------------------------------------

   Update -- driver routine for performing Custom dynamics update of coordinates
   and velocities

   @param context             the context this integrator is updating
   @param numberOfAtoms       number of atoms
   @param atomCoordinates     atom coordinates
   @param velocities          velocities
   @param forces              forces
   @param masses              atom masses
   @param globals             a map containing values of global variables
   @param forcesAreValid      whether the current forces are valid or need to be recomputed

   --------------------------------------------------------------------------------------- */

peastman's avatar
peastman committed
212
213
214
void ReferenceCustomDynamics::update(ContextImpl& context, int numberOfAtoms, vector<Vec3>& atomCoordinates,
                                     vector<Vec3>& velocities, vector<Vec3>& forces, vector<double>& masses,
                                     map<string, double>& globals, vector<vector<Vec3> >& perDof, bool& forcesAreValid, double tolerance) {
215
216
    if (invalidatesForces.size() == 0)
        initialize(context, masses, globals);
217
218
    int numSteps = stepType.size();
    globals.insert(context.getParameters().begin(), context.getParameters().end());
peastman's avatar
peastman committed
219
220
    for (auto& global : globals)
        expressionSet.setVariable(expressionSet.getVariableIndex(global.first), global.second);
221
    oldPos = atomCoordinates;
222
223
224
225
    map<int, double> groupEnergy;
    map<int, vector<Vec3> > groupForces;
    if (forcesAreValid)
        groupForces[context.getLastForceGroups()] = forces;
226
227
228
    
    // Loop over steps and execute them.
    
229
    for (int step = 0; step < numSteps; ) {
230
231
        int flags = forceGroupFlags[step];
        if ((needsForces[step] && groupForces.find(flags) == groupForces.end()) || (needsEnergy[step] && groupEnergy.find(flags) == groupEnergy.end())) {
232
            // Recompute forces and/or energy.
233
            
234
235
            bool computeForce = needsForces[step] || computeBothForceAndEnergy[step];
            bool computeEnergy = needsEnergy[step] || computeBothForceAndEnergy[step];
236
            recordChangedParameters(context, globals);
peastman's avatar
peastman committed
237
            double e = context.calcForcesAndEnergy(computeForce, computeEnergy, forceGroupFlags[step]);
238
239
            if (computeForce)
                groupForces[flags] = forces;
240
            if (computeEnergy) {
241
                groupEnergy[flags] = e;
242
243
                context.getEnergyParameterDerivatives(energyParamDerivs);
            }
244
245
246
247
            forcesAreValid = true;
        }
        
        // Execute the step.
248

249
250
        energy = (needsEnergy[step] ? groupEnergy[flags] : 0);
        vector<Vec3>& stepForces = (needsForces[step] ? groupForces[flags] : forces);
251
252
        int nextStep = step+1;
        switch (stepType[step]) {
253
            case CustomIntegrator::ComputeGlobal: {
254
255
                uniform = SimTKOpenMMUtilities::getUniformlyDistributedRandomNumber();
                gaussian = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
peastman's avatar
peastman committed
256
                double result = stepExpressions[step][0].evaluate();
257
258
                globals[stepVariable[step]] = result;
                expressionSet.setVariable(stepVariableIndex[step], result);
259
260
261
                break;
            }
            case CustomIntegrator::ComputePerDof: {
peastman's avatar
peastman committed
262
                vector<Vec3>* results = NULL;
263
                if (stepVariableIndex[step] == xIndex)
264
                    results = &atomCoordinates;
265
                else if (stepVariableIndex[step] == vIndex)
266
267
268
                    results = &velocities;
                else {
                    for (int j = 0; j < integrator.getNumPerDofVariables(); j++)
269
                        if (stepVariableIndex[step] == perDofVariableIndex[j])
270
271
272
                            results = &perDof[j];
                }
                if (results == NULL)
273
                    throw OpenMMException("Illegal per-DOF output variable: "+stepVariable[step]);
274
                computePerDof(numberOfAtoms, *results, atomCoordinates, velocities, stepForces, masses, perDof, stepExpressions[step][0]);
275
276
277
                break;
            }
            case CustomIntegrator::ComputeSum: {
278
                computePerDof(numberOfAtoms, sumBuffer, atomCoordinates, velocities, stepForces, masses, perDof, stepExpressions[step][0]);
peastman's avatar
peastman committed
279
                double sum = 0.0;
280
                for (int j = 0; j < numberOfAtoms; j++)
281
282
                    if (masses[j] != 0.0)
                        sum += sumBuffer[j][0]+sumBuffer[j][1]+sumBuffer[j][2];
283
                globals[stepVariable[step]] = sum;
284
                expressionSet.setVariable(stepVariableIndex[step], sum);
285
286
287
                break;
            }
            case CustomIntegrator::ConstrainPositions: {
288
                getReferenceConstraintAlgorithm()->apply(oldPos, atomCoordinates, inverseMasses, tolerance);
289
                oldPos = atomCoordinates;
290
291
292
                break;
            }
            case CustomIntegrator::ConstrainVelocities: {
293
                getReferenceConstraintAlgorithm()->applyToVelocities(oldPos, velocities, inverseMasses, tolerance);
294
                break;
295
296
297
298
299
            }
            case CustomIntegrator::UpdateContextState: {
                recordChangedParameters(context, globals);
                context.updateContextState();
                globals.insert(context.getParameters().begin(), context.getParameters().end());
peastman's avatar
peastman committed
300
301
                for (auto& global : globals)
                    expressionSet.setVariable(expressionSet.getVariableIndex(global.first), global.second);
302
303
                break;
            }
304
            case CustomIntegrator::IfBlockStart: {
305
                if (!evaluateCondition(step))
306
307
308
                    nextStep = blockEnd[step]+1;
                break;
            }
309
            case CustomIntegrator::WhileBlockStart: {
310
                if (!evaluateCondition(step))
311
312
313
                    nextStep = blockEnd[step]+1;
                break;
            }
314
            case CustomIntegrator::BlockEnd: {
315
316
317
                if (blockEnd[step] != -1)
                    nextStep = blockEnd[step]; // Return to the start of a while block.
                break;
318
319
            }
        }
320
        if (invalidatesForces[step]) {
321
            forcesAreValid = false;
322
323
324
            groupForces.clear();
            groupEnergy.clear();
        }
325
        step = nextStep;
326
    }
327
    ReferenceVirtualSites::computePositions(context.getSystem(), atomCoordinates);
328
329
330
331
    incrementTimeStep();
    recordChangedParameters(context, globals);
}

peastman's avatar
peastman committed
332
333
334
void ReferenceCustomDynamics::computePerDof(int numberOfAtoms, vector<Vec3>& results, const vector<Vec3>& atomCoordinates,
              const vector<Vec3>& velocities, const vector<Vec3>& forces, const vector<double>& masses,
              const vector<vector<Vec3> >& perDof, const CompiledExpression& expression) {
335
    // Loop over all degrees of freedom.
336

337
    for (int i = 0; i < numberOfAtoms; i++) {
338
        if (masses[i] != 0.0) {
339
            m = masses[i];
340
341
342
            for (int j = 0; j < 3; j++) {
                // Compute the expression.

343
344
345
346
347
                x = atomCoordinates[i][j];
                v = velocities[i][j];
                f = forces[i][j];
                uniform = SimTKOpenMMUtilities::getUniformlyDistributedRandomNumber();
                gaussian = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
348
                for (int k = 0; k < (int) perDof.size(); k++)
349
                    perDofVariable[k] = perDof[k][i][j];
350
                results[i][j] = expression.evaluate();
351
            }
352
353
354
355
        }
    }
}

356
bool ReferenceCustomDynamics::evaluateCondition(int step) {
357
358
    uniform = SimTKOpenMMUtilities::getUniformlyDistributedRandomNumber();
    gaussian = SimTKOpenMMUtilities::getNormallyDistributedRandomNumber();
359
360
    double lhs = stepExpressions[step][0].evaluate();
    double rhs = stepExpressions[step][1].evaluate();
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
    switch (comparisons[step]) {
        case CustomIntegratorUtilities::EQUAL:
            return (lhs == rhs);
        case CustomIntegratorUtilities::LESS_THAN:
            return (lhs < rhs);
        case CustomIntegratorUtilities::GREATER_THAN:
            return (lhs > rhs);
        case CustomIntegratorUtilities::NOT_EQUAL:
            return (lhs != rhs);
        case CustomIntegratorUtilities::LESS_THAN_OR_EQUAL:
            return (lhs <= rhs);
        case CustomIntegratorUtilities::GREATER_THAN_OR_EQUAL:
            return (lhs >= rhs);
    }
    throw OpenMMException("ReferenceCustomDynamics: Invalid comparison operator");
}

378
379
380
/**
 * Check which context parameters have changed and register them with the context.
 */
peastman's avatar
peastman committed
381
void ReferenceCustomDynamics::recordChangedParameters(OpenMM::ContextImpl& context, std::map<std::string, double>& globals) {
peastman's avatar
peastman committed
382
383
    for (auto& param : context.getParameters()) {
        string name = param.first;
384
        double value = globals[name];
peastman's avatar
peastman committed
385
        if (value != param.second)
386
387
388
            context.setParameter(name, globals[name]);
    }
}
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405

/**---------------------------------------------------------------------------------------

   Compute the kinetic energy of the system.

   @param context             the context this integrator is updating
   @param numberOfAtoms       number of atoms
   @param atomCoordinates     atom coordinates
   @param velocities          velocities
   @param forces              forces
   @param masses              atom masses
   @param globals             a map containing values of global variables
   @param perDof              the values of per-DOF variables
   @param forcesAreValid      whether the current forces are valid or need to be recomputed

   --------------------------------------------------------------------------------------- */

peastman's avatar
peastman committed
406
407
408
double ReferenceCustomDynamics::computeKineticEnergy(OpenMM::ContextImpl& context, int numberOfAtoms, std::vector<OpenMM::Vec3>& atomCoordinates,
        std::vector<OpenMM::Vec3>& velocities, std::vector<OpenMM::Vec3>& forces, std::vector<double>& masses,
        std::map<std::string, double>& globals, std::vector<std::vector<OpenMM::Vec3> >& perDof, bool& forcesAreValid) {
409
410
    if (invalidatesForces.size() == 0)
        initialize(context, masses, globals);
411
    globals.insert(context.getParameters().begin(), context.getParameters().end());
peastman's avatar
peastman committed
412
413
    for (auto& global : globals)
        expressionSet.setVariable(expressionSet.getVariableIndex(global.first), global.second);
414
415
416
417
    if (kineticEnergyNeedsForce) {
        energy = context.calcForcesAndEnergy(true, true, -1);
        forcesAreValid = true;
    }
418
    computePerDof(numberOfAtoms, sumBuffer, atomCoordinates, velocities, forces, masses, perDof, kineticEnergyExpression);
peastman's avatar
peastman committed
419
    double sum = 0.0;
420
421
422
423
424
    for (int j = 0; j < numberOfAtoms; j++)
        if (masses[j] != 0.0)
            sum += sumBuffer[j][0]+sumBuffer[j][1]+sumBuffer[j][2];
    return sum;
}