OpenCLExpressionUtilities.cpp 21.3 KB
Newer Older
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) 2009-2014 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
 * Authors: Peter Eastman                                                     *
 * Contributors:                                                              *
 *                                                                            *
 * This program is free software: you can redistribute it and/or modify       *
 * it under the terms of the GNU Lesser General Public License as published   *
 * by the Free Software Foundation, either version 3 of the License, or       *
 * (at your option) any later version.                                        *
 *                                                                            *
 * This program is distributed in the hope that it will be useful,            *
 * but WITHOUT ANY WARRANTY; without even the implied warranty of             *
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              *
 * GNU Lesser General Public License for more details.                        *
 *                                                                            *
 * You should have received a copy of the GNU Lesser General Public License   *
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.      *
 * -------------------------------------------------------------------------- */

#include "OpenCLExpressionUtilities.h"
#include "openmm/OpenMMException.h"
29
#include "openmm/internal/SplineFitter.h"
30
31
32
33
34
35
#include "lepton/Operation.h"

using namespace OpenMM;
using namespace Lepton;
using namespace std;

36
string OpenCLExpressionUtilities::createExpressions(const map<string, ParsedExpression>& expressions, const map<string, string>& variables,
peastman's avatar
peastman committed
37
38
        const vector<const TabulatedFunction*>& functions, const vector<pair<string, string> >& functionNames, const string& prefix,
        const string& functionParams, const string& tempType) {
39
40
41
    vector<pair<ExpressionTreeNode, string> > variableNodes;
    for (map<string, string>::const_iterator iter = variables.begin(); iter != variables.end(); ++iter)
        variableNodes.push_back(make_pair(ExpressionTreeNode(new Operation::Variable(iter->first)), iter->second));
peastman's avatar
peastman committed
42
    return createExpressions(expressions, variableNodes, functions, functionNames, prefix, functionParams, tempType);
43
44
45
}

string OpenCLExpressionUtilities::createExpressions(const map<string, ParsedExpression>& expressions, const vector<pair<ExpressionTreeNode, string> >& variables,
peastman's avatar
peastman committed
46
47
        const vector<const TabulatedFunction*>& functions, const vector<pair<string, string> >& functionNames, const string& prefix,
        const string& functionParams, const string& tempType) {
48
    stringstream out;
49
50
51
    vector<ParsedExpression> allExpressions;
    for (map<string, ParsedExpression>::const_iterator iter = expressions.begin(); iter != expressions.end(); ++iter)
        allExpressions.push_back(iter->second);
52
    vector<pair<ExpressionTreeNode, string> > temps = variables;
53
    for (map<string, ParsedExpression>::const_iterator iter = expressions.begin(); iter != expressions.end(); ++iter) {
peastman's avatar
peastman committed
54
        processExpression(out, iter->second.getRootNode(), temps, functions, functionNames, prefix, functionParams, allExpressions, tempType);
55
56
57
        out << iter->first << getTempName(iter->second.getRootNode(), temps) << ";\n";
    }
    return out.str();
58
59
}

60
void OpenCLExpressionUtilities::processExpression(stringstream& out, const ExpressionTreeNode& node, vector<pair<ExpressionTreeNode, string> >& temps,
peastman's avatar
peastman committed
61
62
        const vector<const TabulatedFunction*>& functions, const vector<pair<string, string> >& functionNames, const string& prefix, const string& functionParams,
        const vector<ParsedExpression>& allExpressions, const string& tempType) {
63
64
65
66
    for (int i = 0; i < (int) temps.size(); i++)
        if (temps[i].first == node)
            return;
    for (int i = 0; i < (int) node.getChildren().size(); i++)
peastman's avatar
peastman committed
67
        processExpression(out, node.getChildren()[i], temps, functions, functionNames, prefix, functionParams, allExpressions, tempType);
68
    string name = prefix+context.intToString(temps.size());
69
    bool hasRecordedNode = false;
70
    
71
    out << tempType << " " << name << " = ";
72
73
    switch (node.getOperation().getId()) {
        case Operation::CONSTANT:
74
            out << context.doubleToString(dynamic_cast<const Operation::Constant*>(&node.getOperation())->getValue());
75
            break;
76
        case Operation::VARIABLE:
77
            throw OpenMMException("Unknown variable in expression: "+node.getOperation().getName());
78
79
80
        case Operation::CUSTOM:
        {
            int i;
peastman's avatar
peastman committed
81
            for (i = 0; i < (int) functionNames.size() && functionNames[i].first != node.getOperation().getName(); i++)
82
                ;
peastman's avatar
peastman committed
83
            if (i == functionNames.size())
84
                throw OpenMMException("Unknown function in expression: "+node.getOperation().getName());
85
            bool isDeriv = (dynamic_cast<const Operation::Custom*>(&node.getOperation())->getDerivOrder()[0] == 1);
86
            out << "0.0f;\n";
87
88
89
90
91
92
93
94
95
96
97
98
99
            temps.push_back(make_pair(node, name));
            hasRecordedNode = true;

            // If both the value and derivative of the function are needed, it's faster to calculate them both
            // at once, so check to see if both are needed.

            const ExpressionTreeNode* valueNode = NULL;
            const ExpressionTreeNode* derivNode = NULL;
            for (int j = 0; j < (int) allExpressions.size(); j++)
                findRelatedTabulatedFunctions(node, allExpressions[j].getRootNode(), valueNode, derivNode);
            string valueName = name;
            string derivName = name;
            if (valueNode != NULL && derivNode != NULL) {
100
                string name2 = prefix+context.intToString(temps.size());
101
                out << tempType << " " << name2 << " = 0.0f;\n";
102
103
104
105
106
107
108
109
110
                if (isDeriv) {
                    valueName = name2;
                    temps.push_back(make_pair(*valueNode, name2));
                }
                else {
                    derivName = name2;
                    temps.push_back(make_pair(*derivNode, name2));
                }
            }
111
            out << "{\n";
peastman's avatar
peastman committed
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
            if (dynamic_cast<const Continuous1DFunction*>(functions[i]) != NULL) {
                out << "float4 params = " << functionParams << "[" << i << "];\n";
                out << "real x = " << getTempName(node.getChildren()[0], temps) << ";\n";
                out << "if (x >= params.x && x <= params.y) {\n";
                out << "x = (x-params.x)*params.z;\n";
                out << "int index = (int) (floor(x));\n";
                out << "index = min(index, (int) params.w);\n";
                out << "float4 coeff = " << functionNames[i].second << "[index];\n";
                out << "real b = x-index;\n";
                out << "real a = 1.0f-b;\n";
                if (valueNode != NULL)
                    out << valueName << " = a*coeff.x+b*coeff.y+((a*a*a-a)*coeff.z+(b*b*b-b)*coeff.w)/(params.z*params.z);\n";
                if (derivNode != NULL)
                    out << derivName << " = (coeff.y-coeff.x)*params.z+((1.0f-3.0f*a*a)*coeff.z+(3.0f*b*b-1.0f)*coeff.w)/params.z;\n";
                out << "}\n";
            }
            else if (dynamic_cast<const Discrete1DFunction*>(functions[i]) != NULL) {
                if (valueNode != NULL) {
                    out << "float4 params = " << functionParams << "[" << i << "];\n";
                    out << "real x = " << getTempName(node.getChildren()[0], temps) << ";\n";
                    out << "if (x >= 0 && x < params.x) {\n";
                    out << "int index = (int) round(x);\n";
                    out << valueName << " = " << functionNames[i].second << "[index];\n";
                    out << "}\n";
                }
            }
138
139
            out << "}";
            break;
140
141
        }
        case Operation::ADD:
142
143
            out << getTempName(node.getChildren()[0], temps) << "+" << getTempName(node.getChildren()[1], temps);
            break;
144
        case Operation::SUBTRACT:
145
146
            out << getTempName(node.getChildren()[0], temps) << "-" << getTempName(node.getChildren()[1], temps);
            break;
147
        case Operation::MULTIPLY:
148
149
            out << getTempName(node.getChildren()[0], temps) << "*" << getTempName(node.getChildren()[1], temps);
            break;
150
        case Operation::DIVIDE:
151
152
153
154
155
156
157
158
159
        {
            bool haveReciprocal = false;
            for (int i = 0; i < (int) temps.size(); i++)
                if (temps[i].first.getOperation().getId() == Operation::RECIPROCAL && temps[i].first.getChildren()[0] == node.getChildren()[1]) {
                    haveReciprocal = true;
                    out << getTempName(node.getChildren()[0], temps) << "*" << temps[i].second;
                }
            if (!haveReciprocal)
                out << getTempName(node.getChildren()[0], temps) << "/" << getTempName(node.getChildren()[1], temps);
160
            break;
161
        }
162
        case Operation::POWER:
163
164
            out << "pow(" << getTempName(node.getChildren()[0], temps) << ", " << getTempName(node.getChildren()[1], temps) << ")";
            break;
165
        case Operation::NEGATE:
166
167
            out << "-" << getTempName(node.getChildren()[0], temps);
            break;
168
        case Operation::SQRT:
169
170
            out << "sqrt(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
171
        case Operation::EXP:
172
            out << "EXP(" << getTempName(node.getChildren()[0], temps) << ")";
173
            break;
174
        case Operation::LOG:
175
            out << "LOG(" << getTempName(node.getChildren()[0], temps) << ")";
176
            break;
177
        case Operation::SIN:
178
179
            out << "sin(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
180
        case Operation::COS:
181
182
            out << "cos(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
183
        case Operation::SEC:
184
185
            out << "1.0f/cos(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
186
        case Operation::CSC:
187
188
            out << "1.0f/sin(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
189
        case Operation::TAN:
190
191
            out << "tan(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
192
        case Operation::COT:
193
194
            out << "1.0f/tan(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
195
        case Operation::ASIN:
196
197
            out << "asin(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
198
        case Operation::ACOS:
199
200
            out << "acos(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
201
        case Operation::ATAN:
202
203
            out << "atan(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
204
205
206
207
208
209
210
211
212
        case Operation::SINH:
            out << "sinh(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
        case Operation::COSH:
            out << "cosh(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
        case Operation::TANH:
            out << "tanh(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
213
214
215
216
217
218
        case Operation::ERF:
            out << "erf(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
        case Operation::ERFC:
            out << "erfc(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
219
220
221
        case Operation::STEP:
            out << getTempName(node.getChildren()[0], temps) << " >= 0.0f ? 1.0f : 0.0f";
            break;
222
223
224
        case Operation::DELTA:
            out << getTempName(node.getChildren()[0], temps) << " == 0.0f ? 1.0f : 0.0f";
            break;
225
        case Operation::SQUARE:
226
227
228
229
230
        {
            string arg = getTempName(node.getChildren()[0], temps);
            out << arg << "*" << arg;
            break;
        }
231
        case Operation::CUBE:
232
233
234
235
236
        {
            string arg = getTempName(node.getChildren()[0], temps);
            out << arg << "*" << arg << "*" << arg;
            break;
        }
237
        case Operation::RECIPROCAL:
238
            out << "RECIP(" << getTempName(node.getChildren()[0], temps) << ")";
239
            break;
240
        case Operation::ADD_CONSTANT:
241
            out << context.doubleToString(dynamic_cast<const Operation::AddConstant*>(&node.getOperation())->getValue()) << "+" << getTempName(node.getChildren()[0], temps);
242
            break;
243
        case Operation::MULTIPLY_CONSTANT:
244
            out << context.doubleToString(dynamic_cast<const Operation::MultiplyConstant*>(&node.getOperation())->getValue()) << "*" << getTempName(node.getChildren()[0], temps);
245
            break;
246
        case Operation::POWER_CONSTANT:
247
248
249
250
251
252
        {
            double exponent = dynamic_cast<const Operation::PowerConstant*>(&node.getOperation())->getValue();
            if (exponent == 0.0)
                out << "1.0f";
            else if (exponent == (int) exponent) {
                out << "0.0f;\n";
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
                temps.push_back(make_pair(node, name));
                hasRecordedNode = true;

                // If multiple integral powers of the same base are needed, it's faster to calculate all of them
                // at once, so check to see if others are also needed.

                map<int, const ExpressionTreeNode*> powers;
                powers[(int) exponent] = &node;
                for (int j = 0; j < (int) allExpressions.size(); j++)
                    findRelatedPowers(node, allExpressions[j].getRootNode(), powers);
                vector<int> exponents;
                vector<string> names;
                vector<bool> hasAssigned(powers.size(), false);
                exponents.push_back((int) fabs(exponent));
                names.push_back(name);
                for (map<int, const ExpressionTreeNode*>::const_iterator iter = powers.begin(); iter != powers.end(); ++iter) {
                    if (iter->first != exponent) {
270
                        exponents.push_back(iter->first >= 0 ? iter->first : -iter->first);
271
                        string name2 = prefix+context.intToString(temps.size());
272
273
                        names.push_back(name2);
                        temps.push_back(make_pair(*iter->second, name2));
274
                        out << tempType << " " << name2 << " = 0.0f;\n";
275
276
                    }
                }
277
278
                out << "{\n";
                out << "float multiplier = " << (exponent < 0.0 ? "1.0f/" : "") << getTempName(node.getChildren()[0], temps) << ";\n";
279
280
281
                bool done = false;
                while (!done) {
                    done = true;
282
                    for (int i = 0; i < (int) exponents.size(); i++) {
283
284
285
286
287
288
289
290
291
292
                        if (exponents[i]%2 == 1) {
                            if (!hasAssigned[i])
                                out << names[i] << " = multiplier;\n";
                            else
                                out << names[i] << " *= multiplier;\n";
                            hasAssigned[i] = true;
                        }
                        exponents[i] >>= 1;
                        if (exponents[i] != 0)
                            done = false;
293
                    }
294
                    if (!done)
295
296
297
298
299
                        out << "multiplier *= multiplier;\n";
                }
                out << "}";
            }
            else
300
                out << "pow(" << getTempName(node.getChildren()[0], temps) << ", " << context.doubleToString(exponent) << ")";
301
            break;
302
        }
303
304
305
306
307
308
309
310
311
        case Operation::MIN:
            out << "min(" << getTempName(node.getChildren()[0], temps) << ", " << getTempName(node.getChildren()[1], temps) << ")";
            break;
        case Operation::MAX:
            out << "max(" << getTempName(node.getChildren()[0], temps) << ", " << getTempName(node.getChildren()[1], temps) << ")";
            break;
        case Operation::ABS:
            out << "fabs(" << getTempName(node.getChildren()[0], temps) << ")";
            break;
312
313
        default:
            throw OpenMMException("Internal error: Unknown operation in user-defined expression: "+node.getOperation().getName());
314
    }
315
    out << ";\n";
316
317
    if (!hasRecordedNode)
        temps.push_back(make_pair(node, name));
318
319
320
321
322
323
324
325
326
}

string OpenCLExpressionUtilities::getTempName(const ExpressionTreeNode& node, const vector<pair<ExpressionTreeNode, string> >& temps) {
    for (int i = 0; i < (int) temps.size(); i++)
        if (temps[i].first == node)
            return temps[i].second;
    stringstream out;
    out << "Internal error: No temporary variable for expression node: " << node;
    throw OpenMMException(out.str());
327
}
328
329
330
331
332
333
334
335
336
337
338
339
340

void OpenCLExpressionUtilities::findRelatedTabulatedFunctions(const ExpressionTreeNode& node, const ExpressionTreeNode& searchNode,
            const ExpressionTreeNode*& valueNode, const ExpressionTreeNode*& derivNode) {
    if (searchNode.getOperation().getId() == Operation::CUSTOM && node.getChildren()[0] == searchNode.getChildren()[0]) {
        if (dynamic_cast<const Operation::Custom*>(&searchNode.getOperation())->getDerivOrder()[0] == 0)
            valueNode = &searchNode;
        else
            derivNode = &searchNode;
    }
    else
        for (int i = 0; i < (int) searchNode.getChildren().size(); i++)
            findRelatedTabulatedFunctions(node, searchNode.getChildren()[i], valueNode, derivNode);
}
341
342
343

void OpenCLExpressionUtilities::findRelatedPowers(const ExpressionTreeNode& node, const ExpressionTreeNode& searchNode, map<int, const ExpressionTreeNode*>& powers) {
    if (searchNode.getOperation().getId() == Operation::POWER_CONSTANT && node.getChildren()[0] == searchNode.getChildren()[0]) {
344
345
346
347
        double realPower = dynamic_cast<const Operation::PowerConstant*>(&searchNode.getOperation())->getValue();
        int power = (int) realPower;
        if (power != realPower)
            return; // We are only interested in integer powers.
348
349
350
351
352
353
354
355
356
357
        if (powers.find(power) != powers.end())
            return; // This power is already in the map.
        if (powers.begin()->first*power < 0)
            return; // All powers must have the same sign.
        powers[power] = &searchNode;
    }
    else
        for (int i = 0; i < (int) searchNode.getChildren().size(); i++)
            findRelatedPowers(node, searchNode.getChildren()[i], powers);
}
358

peastman's avatar
peastman committed
359
vector<float> OpenCLExpressionUtilities::computeFunctionCoefficients(const TabulatedFunction& function, int& width) {
360
    if (dynamic_cast<const Continuous1DFunction*>(&function) != NULL) {
peastman's avatar
peastman committed
361
362
        // Compute the spline coefficients.

363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
        const Continuous1DFunction& fn = dynamic_cast<const Continuous1DFunction&>(function);
        vector<double> values;
        double min, max;
        fn.getFunctionParameters(values, min, max);
        int numValues = values.size();
        vector<double> x(numValues), derivs;
        for (int i = 0; i < numValues; i++)
            x[i] = min+i*(max-min)/(numValues-1);
        SplineFitter::createNaturalSpline(x, values, derivs);
        vector<float> f(4*(numValues-1));
        for (int i = 0; i < (int) values.size()-1; i++) {
            f[4*i] = (float) values[i];
            f[4*i+1] = (float) values[i+1];
            f[4*i+2] = (float) (derivs[i]/6.0);
            f[4*i+3] = (float) (derivs[i+1]/6.0);
        }
peastman's avatar
peastman committed
379
380
381
382
383
384
385
386
387
388
389
390
391
392
        width = 4;
        return f;
    }
    if (dynamic_cast<const Discrete1DFunction*>(&function) != NULL) {
        // Record the tabulated values.
        
        const Discrete1DFunction& fn = dynamic_cast<const Discrete1DFunction&>(function);
        vector<double> values;
        fn.getFunctionParameters(values);
        int numValues = values.size();
        vector<float> f(numValues);
        for (int i = 0; i < numValues; i++)
            f[i] = (float) values[i];
        width = 1;
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
        return f;
    }
    throw OpenMMException("computeFunctionCoefficients: Unknown function type");
}

vector<mm_float4> OpenCLExpressionUtilities::computeFunctionParameters(const vector<const TabulatedFunction*>& functions) {
    vector<mm_float4> params(functions.size());
    for (int i = 0; i < (int) functions.size(); i++) {
        if (dynamic_cast<const Continuous1DFunction*>(functions[i]) != NULL) {
            const Continuous1DFunction& fn = dynamic_cast<const Continuous1DFunction&>(*functions[i]);
            vector<double> values;
            double min, max;
            fn.getFunctionParameters(values, min, max);
            params[i] = mm_float4((float) min, (float) max, (float) ((values.size()-1)/(max-min)), (float) values.size()-2);
        }
peastman's avatar
peastman committed
408
409
410
411
412
413
        else if (dynamic_cast<const Discrete1DFunction*>(functions[i]) != NULL) {
            const Discrete1DFunction& fn = dynamic_cast<const Discrete1DFunction&>(*functions[i]);
            vector<double> values;
            fn.getFunctionParameters(values);
            params[i] = mm_float4((float) values.size(), 0.0f, 0.0f, 0.0f);
        }
414
415
416
417
        else
            throw OpenMMException("computeFunctionParameters: Unknown function type");
    }
    return params;
418
}