CustomIntegratorUtilities.cpp 16.1 KB
Newer Older
peastman's avatar
peastman committed
1
2
3
4
5
6
7
8
/* -------------------------------------------------------------------------- *
 *                                   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.               *
 *                                                                            *
9
 * Portions copyright (c) 2015-2023 Stanford University and the Authors.      *
peastman's avatar
peastman committed
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 * 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/CustomIntegratorUtilities.h"
#include "openmm/OpenMMException.h"
#include "openmm/internal/ForceImpl.h"
#include "lepton/Operation.h"
#include "lepton/Parser.h"
37
#include <algorithm>
peastman's avatar
peastman committed
38
39
#include <set>
#include <sstream>
40
#include <utility>
peastman's avatar
peastman committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62

using namespace OpenMM;
using namespace std;

void CustomIntegratorUtilities::parseCondition(const string& expression, string& lhs, string& rhs, Comparison& comparison) {
    string operators[] = {"=", "<", ">", "!=", "<=", ">="};
    for (int i = 5; i >= 0; i--) {
        int index = expression.find(operators[i]);
        if (index != string::npos) {
            lhs = expression.substr(0, index);
            rhs = expression.substr(index+operators[i].size());
            comparison = Comparison(i);
            return;
        }
    }
    throw OpenMMException("No comparison operator found in condition: "+expression);
}

bool CustomIntegratorUtilities::usesVariable(const Lepton::ExpressionTreeNode& node, const string& variable) {
    const Lepton::Operation& op = node.getOperation();
    if (op.getId() == Lepton::Operation::VARIABLE && op.getName() == variable)
        return true;
peastman's avatar
peastman committed
63
64
    for (auto& child : node.getChildren())
        if (usesVariable(child, variable))
peastman's avatar
peastman committed
65
66
67
68
69
70
71
72
73
            return true;
    return false;
}

bool CustomIntegratorUtilities::usesVariable(const Lepton::ParsedExpression& expression, const string& variable) {
    return usesVariable(expression.getRootNode(), variable);
}

void CustomIntegratorUtilities::analyzeComputations(const ContextImpl& context, const CustomIntegrator& integrator, vector<vector<Lepton::ParsedExpression> >& expressions,
74
            vector<Comparison>& comparisons, vector<int>& blockEnd, vector<bool>& invalidatesForces, vector<bool>& needsForces, vector<bool>& needsEnergy,
75
            vector<bool>& computeBoth, vector<int>& forceGroup, const map<string, Lepton::CustomFunction*>& functions) {
peastman's avatar
peastman committed
76
77
78
79
80
81
82
83
84
85
    int numSteps = integrator.getNumComputations();
    expressions.resize(numSteps);
    comparisons.resize(numSteps);
    invalidatesForces.resize(numSteps, false);
    needsForces.resize(numSteps, false);
    needsEnergy.resize(numSteps, false);
    computeBoth.resize(numSteps, false);
    forceGroup.resize(numSteps, -2);
    vector<CustomIntegrator::ComputationType> stepType(numSteps);
    vector<string> stepVariable(numSteps);
Peter Eastman's avatar
Peter Eastman committed
86
    vector<bool> alwaysInvalidatesForces(numSteps, false);
87
    map<string, Lepton::CustomFunction*> customFunctions = functions;
88
89
90
91
92
93
94
95
96
    Lepton::PlaceholderFunction fn1(1), fn2(2), fn3(3);
    customFunctions["deriv"] = &fn2;
    map<string, Lepton::CustomFunction*> vectorFunctions = customFunctions;
    vectorFunctions["dot"] = &fn2;
    vectorFunctions["cross"] = &fn2;
    vectorFunctions["_x"] = &fn1;
    vectorFunctions["_y"] = &fn1;
    vectorFunctions["_z"] = &fn1;
    vectorFunctions["vector"] = &fn3;
peastman's avatar
peastman committed
97
98
99
100
101
102

    // Parse the expressions.

    for (int step = 0; step < numSteps; step++) {
        string expression;
        integrator.getComputationStep(step, stepType[step], stepVariable[step], expression);
103
        if (stepType[step] == CustomIntegrator::IfBlockStart || stepType[step] == CustomIntegrator::WhileBlockStart) {
peastman's avatar
peastman committed
104
105
106
107
            // This step involves a condition.

            string lhs, rhs;
            parseCondition(expression, lhs, rhs, comparisons[step]);
108
109
            expressions[step].push_back(Lepton::Parser::parse(lhs, customFunctions).optimize());
            expressions[step].push_back(Lepton::Parser::parse(rhs, customFunctions).optimize());
peastman's avatar
peastman committed
110
        }
111
112
        else if (stepType[step] == CustomIntegrator::ComputePerDof || stepType[step] == CustomIntegrator::ComputeSum)
            expressions[step].push_back(Lepton::Parser::parse(expression, vectorFunctions).optimize());
peastman's avatar
peastman committed
113
        else if (expression.size() > 0)
114
            expressions[step].push_back(Lepton::Parser::parse(expression, customFunctions).optimize());
peastman's avatar
peastman committed
115
116
117
118
119
120
    }

    // Identify which steps invalidate the forces.

    set<string> affectsForce;
    affectsForce.insert("x");
peastman's avatar
peastman committed
121
122
123
    for (auto force : context.getForceImpls())
        for (auto& param : force->getDefaultParameters())
            affectsForce.insert(param.first);
Peter Eastman's avatar
Peter Eastman committed
124
125
126
127
    for (int i = 0; i < numSteps; i++) {
        alwaysInvalidatesForces[i] = (stepType[i] == CustomIntegrator::ConstrainPositions || affectsForce.find(stepVariable[i]) != affectsForce.end());
        invalidatesForces[i] = (alwaysInvalidatesForces[i] || stepType[i] == CustomIntegrator::UpdateContextState);
    }
peastman's avatar
peastman committed
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

    // Make a list of which steps require valid forces or energy to be known.

    vector<string> forceGroupName;
    vector<string> energyGroupName;
    for (int i = 0; i < 32; i++) {
        stringstream fname;
        fname << "f" << i;
        forceGroupName.push_back(fname.str());
        stringstream ename;
        ename << "energy" << i;
        energyGroupName.push_back(ename.str());
    }
    for (int step = 0; step < numSteps; step++) {
        for (int expr = 0; expr < expressions[step].size(); expr++) {
            if (usesVariable(expressions[step][expr], "f")) {
                needsForces[step] = true;
                forceGroup[step] = -1;
            }
            if (usesVariable(expressions[step][expr], "energy")) {
                needsEnergy[step] = true;
                forceGroup[step] = -1;
            }
            for (int i = 0; i < 32; i++) {
                if (usesVariable(expressions[step][expr], forceGroupName[i])) {
                    if (forceGroup[step] != -2)
                        throw OpenMMException("A single computation step cannot depend on multiple force groups");
                    needsForces[step] = true;
156
                    forceGroup[step] = i;
peastman's avatar
peastman committed
157
158
159
160
161
                }
                if (usesVariable(expressions[step][expr], energyGroupName[i])) {
                    if (forceGroup[step] != -2)
                        throw OpenMMException("A single computation step cannot depend on multiple force groups");
                    needsEnergy[step] = true;
162
                    forceGroup[step] = i;
peastman's avatar
peastman committed
163
164
165
166
                }
            }
        }
    }
peastman's avatar
peastman committed
167
168
169
    for (int step = numSteps-2; step >= 0; step--)
        if (forceGroup[step] == -2)
            forceGroup[step] = forceGroup[step+1];
peastman's avatar
peastman committed
170
171
172
173

    // Find the end point of each block.

    vector<int> blockStart;
174
    blockEnd.resize(numSteps, -1);
peastman's avatar
peastman committed
175
    for (int step = 0; step < numSteps; step++) {
176
        if (stepType[step] == CustomIntegrator::IfBlockStart || stepType[step] == CustomIntegrator::WhileBlockStart)
peastman's avatar
peastman committed
177
            blockStart.push_back(step);
178
        else if (stepType[step] == CustomIntegrator::BlockEnd) {
peastman's avatar
peastman committed
179
180
181
182
183
184
185
186
187
188
189
190
            if (blockStart.size() == 0) {
                stringstream error("CustomIntegrator: Unexpected end of block at computation ");
                error << step;
                throw OpenMMException(error.str());
            }
            blockEnd[blockStart.back()] = step;
            blockStart.pop_back();
        }
    }
    if (blockStart.size() > 0)
        throw OpenMMException("CustomIntegrator: Missing EndBlock");

191
192
193
194
195
196
197
198
199
200
201
202
203
204
    // Identify whether each block contains any operation that either invalidates forces,
    // or requires forces or energy.  These are the ones that are significant for the
    // analysis that follows.

    vector<bool> isSignificant(numSteps, false);
    for (int step = 0; step < numSteps; step++) {
        if (stepType[step] == CustomIntegrator::IfBlockStart || stepType[step] == CustomIntegrator::WhileBlockStart)
            for (int i = step; i < blockEnd[step]; i++)
                if (needsForces[i] || needsEnergy[i] || invalidatesForces[i]) {
                    isSignificant[step] = true;
                    break;
                }
    }

peastman's avatar
peastman committed
205
206
207
208
209
210
211
212
213
214
215
216
217
218
    // If a step requires either forces or energy, and a later step will require the other one, it's most efficient
    // to compute both at the same time.  Figure out whether we should do that.  In principle it's easy: step through
    // the sequence of computations and see if the other one is used before the next time they get invalidated.
    // Unfortunately, flow control makes this much more complicated, because there are many possible paths to
    // consider.
    //
    // The cost of computing both when we really only needed one is much less than the cost of computing only one,
    // then later finding we need to compute the other separately.  So we always err on the side of computing both.
    // If there is any possible path that would lead to us needing it, go ahead and compute it.
    //
    // So we need to enumerate all possible paths.  For each "if" block, there are two possibilities: execute it
    // or don't.  For each "while" block there are three possibilities: don't execute it; execute it and then
    // continue on; or execute it and then jump back to the beginning.  I'm assuming the number of blocks will
    // always remain small.  Otherwise, this could become very expensive!
Peter Eastman's avatar
Peter Eastman committed
219
220
221
    //
    // We also need to consider two full passes through the algorithm.  That way, we detect if a step at the beginning
    // means a step at the end should compute both forces and energy.
peastman's avatar
peastman committed
222

Peter Eastman's avatar
Peter Eastman committed
223
    vector<int> jumps(2*numSteps, -1);
peastman's avatar
peastman committed
224
    vector<int> stepsInPath;
Peter Eastman's avatar
Peter Eastman committed
225
226
227
    int numBlocks = blockEnd.size();
    for (int i = 0; i < numBlocks; i++)
        blockEnd.push_back(blockEnd[i]+numSteps);
228
    enumeratePaths(0, stepsInPath, jumps, blockEnd, stepType, needsForces, needsEnergy, alwaysInvalidatesForces, forceGroup, computeBoth, isSignificant);
229
230
231
232
233
234
235
236
    
    // Make sure calls to deriv() all valid.
    
    vector<string> derivNames = energyGroupName;
    derivNames.push_back("energy");
    for (int i = 0; i < expressions.size(); i++)
        for (int j = 0; j < expressions[i].size(); j++)
            validateDerivatives(expressions[i][j].getRootNode(), derivNames);
peastman's avatar
peastman committed
237
238
239
240
}

void CustomIntegratorUtilities::enumeratePaths(int firstStep, vector<int> steps, vector<int> jumps, const vector<int>& blockEnd,
            const vector<CustomIntegrator::ComputationType>& stepType, const vector<bool>& needsForces, const vector<bool>& needsEnergy,
241
            const vector<bool>& invalidatesForces, const vector<int>& forceGroup, vector<bool>& computeBoth, const vector<bool>& isSignificant) {
peastman's avatar
peastman committed
242
243
    int step = firstStep;
    int numSteps = stepType.size();
Peter Eastman's avatar
Peter Eastman committed
244
    while (step < 2*numSteps) {
peastman's avatar
peastman committed
245
        steps.push_back(step);
Peter Eastman's avatar
Peter Eastman committed
246
        int index = step % stepType.size();
peastman's avatar
peastman committed
247
248
249
250
251
252
253
        if (jumps[step] > 0) {
            // Follow the jump and remove it from the list.

            int nextStep = jumps[step];
            jumps[step] = -1;
            step = nextStep;
        }
254
        else if (stepType[index] == CustomIntegrator::IfBlockStart && isSignificant[index]) {
peastman's avatar
peastman committed
255
256
            // Consider skipping the block.

257
            enumeratePaths(blockEnd[step]+1, steps, jumps, blockEnd, stepType, needsForces, needsEnergy, invalidatesForces, forceGroup, computeBoth, isSignificant);
peastman's avatar
peastman committed
258
259
260
261
262

            // Continue on to execute the block.

            step++;
        }
263
        else if (stepType[index] == CustomIntegrator::WhileBlockStart && jumps[step] != -2 && isSignificant[index]) {
peastman's avatar
peastman committed
264
265
            // Consider skipping the block.

266
            enumeratePaths(blockEnd[step]+1, steps, jumps, blockEnd, stepType, needsForces, needsEnergy, invalidatesForces, forceGroup, computeBoth, isSignificant);
peastman's avatar
peastman committed
267
268
269

            // Consider executing the block once.

270
            enumeratePaths(step+1, steps, jumps, blockEnd, stepType, needsForces, needsEnergy, invalidatesForces, forceGroup, computeBoth, isSignificant);
peastman's avatar
peastman committed
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

            // Continue on to execute the block twice.

            jumps[step] = -2; // Mark this "while" block as already processed.
            jumps[blockEnd[step]] = step;
            step++;
        }
        else
            step++;
    }
    analyzeForceComputationsForPath(steps, needsForces, needsEnergy, invalidatesForces, forceGroup, computeBoth);
}

void CustomIntegratorUtilities::analyzeForceComputationsForPath(vector<int>& steps, const vector<bool>& needsForces, const vector<bool>& needsEnergy,
            const vector<bool>& invalidatesForces, const vector<int>& forceGroup, vector<bool>& computeBoth) {
286
    vector<pair<int, int> > candidatePoints;
peastman's avatar
peastman committed
287
    for (int step : steps) {
Peter Eastman's avatar
Peter Eastman committed
288
289
        int index = step % computeBoth.size();
        if (invalidatesForces[index]) {
290
            // Forces and energies are invalidated at this step, so anything from this point on won't affect what we do at earlier steps.
peastman's avatar
peastman committed
291
292
293

            candidatePoints.clear();
        }
Peter Eastman's avatar
Peter Eastman committed
294
        if (needsForces[index] || needsEnergy[index]) {
peastman's avatar
peastman committed
295
296
            // See if this step affects what we do at earlier points.

Peter Eastman's avatar
Peter Eastman committed
297
298
299
300
301
            for (auto candidate : candidatePoints) {
                int candidateIndex = candidate.first % computeBoth.size();
                if (candidate.second == forceGroup[index] && ((needsForces[candidateIndex] && needsEnergy[index]) || (needsEnergy[candidateIndex] && needsForces[index])))
                    computeBoth[candidateIndex] = true;
            }
peastman's avatar
peastman committed
302
303
304

            // Add this to the list of candidates that might be affected by later steps.

Peter Eastman's avatar
Peter Eastman committed
305
            candidatePoints.push_back(make_pair(step, forceGroup[index]));
peastman's avatar
peastman committed
306
307
        }
    }
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
}

void CustomIntegratorUtilities::validateDerivatives(const Lepton::ExpressionTreeNode& node, const vector<string>& derivNames) {
    const Lepton::Operation& op = node.getOperation();
    if (op.getId() == Lepton::Operation::CUSTOM && op.getName() == "deriv") {
        const Lepton::Operation& child = node.getChildren()[0].getOperation();
        if (child.getId() != Lepton::Operation::VARIABLE || find(derivNames.begin(), derivNames.end(), child.getName()) == derivNames.end())
            throw OpenMMException("The first argument to deriv() must be an energy variable");
        if (node.getChildren()[1].getOperation().getId() != Lepton::Operation::VARIABLE)
            throw OpenMMException("The second argument to deriv() must be a context parameter");
    }
    else {
        for (int i = 0; i < node.getChildren().size(); i++)
            validateDerivatives(node.getChildren()[i], derivNames);
    }
}