LocalEnergyMinimizer.cpp 12 KB
Newer Older
Peter Eastman's avatar
Peter Eastman committed
1
2
3
/* -------------------------------------------------------------------------- *
 *                                   OpenMM                                   *
 * -------------------------------------------------------------------------- *
Evan Pretti's avatar
Evan Pretti committed
4
5
 * This is part of the OpenMM molecular simulation toolkit.                   *
 * See https://openmm.org/development.                                        *
Peter Eastman's avatar
Peter Eastman committed
6
 *                                                                            *
7
 * Portions copyright (c) 2010-2020 Stanford University and the Authors.      *
Peter Eastman's avatar
Peter Eastman committed
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
 * 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/LocalEnergyMinimizer.h"
#include "openmm/OpenMMException.h"
#include "openmm/Platform.h"
33
34
#include "openmm/VerletIntegrator.h"
#include "lbfgs.h"
Peter Eastman's avatar
Peter Eastman committed
35
36
#include <cmath>
#include <sstream>
37
#include <string>
Peter Eastman's avatar
Peter Eastman committed
38
#include <vector>
peastman's avatar
peastman committed
39
#include <algorithm>
Peter Eastman's avatar
Peter Eastman committed
40
41
42
43

using namespace OpenMM;
using namespace std;

44
struct MinimizerData {
45
46
    Context& context;
    double k;
47
    MinimizationReporter* reporter;
48
49
50
    bool checkLargeForces;
    VerletIntegrator cpuIntegrator;
    Context* cpuContext;
51
52
    MinimizerData(Context& context, double k, MinimizationReporter* reporter) :
            context(context), k(k), reporter(reporter), cpuIntegrator(1.0), cpuContext(NULL) {
53
        string platformName = context.getPlatform().getName();
54
        checkLargeForces = (platformName == "CUDA" || platformName == "OpenCL" || platformName == "HIP" || platformName == "Metal");
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
    }
    ~MinimizerData() {
        if (cpuContext != NULL)
            delete cpuContext;
    }
    Context& getCpuContext() {
        // Get an alternate context that runs on the CPU and doesn't place any limits
        // on the magnitude of forces.

        if (cpuContext == NULL) {
            Platform* cpuPlatform;
            try {
                cpuPlatform = &Platform::getPlatformByName("CPU");
            }
            catch (...) {
                cpuPlatform = &Platform::getPlatformByName("Reference");
            }
            cpuContext = new Context(context.getSystem(), cpuIntegrator, *cpuPlatform);
            cpuContext->setState(context.getState(State::Positions | State::Velocities | State::Parameters));
        }
        return *cpuContext;
    }
77
};
78

79
static double computeForcesAndEnergy(Context& context, const vector<Vec3>& positions, lbfgsfloatval_t *g) {
80
    context.setPositions(positions);
81
    context.computeVirtualSites();
82
    State state = context.getState(State::Forces | State::Energy, false, context.getIntegrator().getIntegrationForceGroups());
Peter Eastman's avatar
Peter Eastman committed
83
    const vector<Vec3>& forces = state.getForces();
84
85
    const System& system = context.getSystem();
    for (int i = 0; i < forces.size(); i++) {
86
        if (system.getParticleMass(i) == 0) {
87
88
89
90
91
92
93
94
95
            g[3*i] = 0.0;
            g[3*i+1] = 0.0;
            g[3*i+2] = 0.0;
        }
        else {
            g[3*i] = -forces[i][0];
            g[3*i+1] = -forces[i][1];
            g[3*i+2] = -forces[i][2];
        }
Peter Eastman's avatar
Peter Eastman committed
96
    }
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
    return state.getPotentialEnergy();
}

static lbfgsfloatval_t evaluate(void *instance, const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n, const lbfgsfloatval_t step) {
    MinimizerData* data = reinterpret_cast<MinimizerData*>(instance);
    Context& context = data->context;
    const System& system = context.getSystem();
    int numParticles = system.getNumParticles();

    // Compute the force and energy for this configuration.

    vector<Vec3> positions(numParticles);
    for (int i = 0; i < numParticles; i++)
        positions[i] = Vec3(x[3*i], x[3*i+1], x[3*i+2]);
    double energy = computeForcesAndEnergy(context, positions, g);
    if (data->checkLargeForces) {
113
        // The CUDA, OpenCL and HIP platforms accumulate forces in fixed point, so they
114
115
116
117
118
119
120
121
122
123
        // can't handle very large forces.  Check for problematic forces (very large,
        // infinite, or NaN) and if necessary recompute them on the CPU.

        for (int i = 0; i < 3*numParticles; i++) {
            if (!(fabs(g[i]) < 2e9)) {
                energy = computeForcesAndEnergy(data->getCpuContext(), positions, g);
                break;
            }
        }
    }
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139

    // Add harmonic forces for any constraints.

    int numConstraints = system.getNumConstraints();
    double k = data->k;
    for (int i = 0; i < numConstraints; i++) {
        int particle1, particle2;
        double distance;
        system.getConstraintParameters(i, particle1, particle2, distance);
        Vec3 delta = positions[particle2]-positions[particle1];
        double r2 = delta.dot(delta);
        double r = sqrt(r2);
        delta *= 1/r;
        double dr = r-distance;
        double kdr = k*dr;
        energy += 0.5*kdr*dr;
140
141
142
143
144
145
146
147
148
149
        if (system.getParticleMass(particle1) != 0) {
            g[3*particle1] -= kdr*delta[0];
            g[3*particle1+1] -= kdr*delta[1];
            g[3*particle1+2] -= kdr*delta[2];
        }
        if (system.getParticleMass(particle2) != 0) {
            g[3*particle2] += kdr*delta[0];
            g[3*particle2+1] += kdr*delta[1];
            g[3*particle2+2] += kdr*delta[2];
        }
150
151
    }
    return energy;
Peter Eastman's avatar
Peter Eastman committed
152
153
}

154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
static int report(void *instance, const lbfgsfloatval_t *x, const lbfgsfloatval_t *g, const lbfgsfloatval_t fx,
        const lbfgsfloatval_t xnorm, const lbfgsfloatval_t gnorm, const lbfgsfloatval_t step, int n, int iteration, int ls) {
    // Copy over the positions and gradients.

    vector<double> xout(n), gradout(n);
    for (int i = 0; i < n; i++) {
        xout[i] = x[i];
        gradout[i] = g[i];
    }

    // Compute the other arguments passed to the reporter.

    MinimizerData* data = reinterpret_cast<MinimizerData*>(instance);
    Context& context = data->context;
    const System& system = context.getSystem();
    double restraintEnergy = 0.0, maxError = 0.0;
    double k = data->k;
    for (int i = 0; i < system.getNumConstraints(); i++) {
        int p1, p2;
        double distance;
        system.getConstraintParameters(i, p1, p2, distance);
        Vec3 delta(x[3*p1]-x[3*p2], x[3*p1+1]-x[3*p2+1], x[3*p1+2]-x[3*p2+2]);
        double r2 = delta.dot(delta);
        double r = sqrt(r2);
        double dr = r-distance;
        restraintEnergy += 0.5*k*dr*dr;
        maxError = max(maxError, fabs(dr)/distance);
    }
    map<string, double> args;
    args["restraint energy"] = restraintEnergy;
    args["system energy"] = fx-restraintEnergy;
    args["restraint strength"] = k;
    args["max constraint error"] = maxError;

    // Invoke the reporter.

    MinimizationReporter* reporter = reinterpret_cast<MinimizationReporter*>(data->reporter);
    if (reporter->report(iteration-1, xout, gradout, args))
        return 1;
    return 0;
}

void LocalEnergyMinimizer::minimize(Context& context, double tolerance, int maxIterations, MinimizationReporter* reporter) {
197
    const System& system = context.getSystem();
198
199
    int numParticles = system.getNumParticles();
    double constraintTol = context.getIntegrator().getConstraintTolerance();
peastman's avatar
peastman committed
200
    double workingConstraintTol = std::max(1e-4, constraintTol);
201
    double k = 100/workingConstraintTol;
202
203
204
205
    lbfgsfloatval_t *x = lbfgs_malloc(numParticles*3);
    if (x == NULL)
        throw OpenMMException("LocalEnergyMinimizer: Failed to allocate memory");
    try {
Peter Eastman's avatar
Peter Eastman committed
206

207
        // Initialize the minimizer.
Peter Eastman's avatar
Peter Eastman committed
208

209
210
211
212
213
214
        lbfgs_parameter_t param;
        lbfgs_parameter_init(&param);
        if (!context.getPlatform().supportsDoublePrecision())
            param.xtol = 1e-7;
        param.max_iterations = maxIterations;
        param.linesearch = LBFGS_LINESEARCH_BACKTRACKING_STRONG_WOLFE;
215

216
        // Make sure the initial configuration satisfies all constraints.
217

218
        context.applyConstraints(workingConstraintTol);
219

220
        // Record the initial positions and determine a normalization constant for scaling the tolerance.
221

222
223
224
225
226
227
228
        vector<Vec3> initialPos = context.getState(State::Positions).getPositions();
        double norm = 0.0;
        for (int i = 0; i < numParticles; i++) {
            x[3*i] = initialPos[i][0];
            x[3*i+1] = initialPos[i][1];
            x[3*i+2] = initialPos[i][2];
            norm += initialPos[i].dot(initialPos[i]);
229
        }
230
231
232
233
234
235
236
        norm /= numParticles;
        norm = (norm < 1 ? 1 : sqrt(norm));
        param.epsilon = tolerance/norm;

        // Repeatedly minimize, steadily increasing the strength of the springs until all constraints are satisfied.

        double prevMaxError = 1e10;
237
        MinimizerData data(context, k, reporter);
238
239
240
241
        while (true) {
            // Perform the minimization.

            lbfgsfloatval_t fx;
242
243
            lbfgs_progress_t reportFn = (reporter == NULL ? NULL : report);
            lbfgs(numParticles*3, x, &fx, evaluate, reportFn, &data, &param);
244
245
246
247
248
249
250
251
252
253
254
255

            // Check whether all constraints are satisfied.

            vector<Vec3> positions = context.getState(State::Positions).getPositions();
            int numConstraints = system.getNumConstraints();
            double maxError = 0.0;
            for (int i = 0; i < numConstraints; i++) {
                int particle1, particle2;
                double distance;
                system.getConstraintParameters(i, particle1, particle2, distance);
                Vec3 delta = positions[particle2]-positions[particle1];
                double r = sqrt(delta.dot(delta));
256
                double error = fabs(r-distance)/distance;
257
258
259
260
261
262
263
264
265
                if (error > maxError)
                    maxError = error;
            }
            if (maxError <= workingConstraintTol)
                break; // All constraints are satisfied.
            context.setPositions(initialPos);
            if (maxError >= prevMaxError)
                break; // Further tightening the springs doesn't seem to be helping, so just give up.
            prevMaxError = maxError;
266
            data.k *= 10;
267
268
269
270
271
272
273
274
275
            if (maxError > 100*workingConstraintTol) {
                // We've gotten far enough from a valid state that we might have trouble getting
                // back, so reset to the original positions.

                for (int i = 0; i < numParticles; i++) {
                    x[3*i] = initialPos[i][0];
                    x[3*i+1] = initialPos[i][1];
                    x[3*i+2] = initialPos[i][2];
                }
276
277
            }
        }
278
    }
279
280
281
282
    catch (...) {
        lbfgs_free(x);
        throw;
    }
Peter Eastman's avatar
Peter Eastman committed
283
    lbfgs_free(x);
284
285
286
287
288
289
    
    // If necessary, do a final constraint projection to make sure they are satisfied
    // to the full precision requested by the user.
    
    if (constraintTol < workingConstraintTol)
        context.applyConstraints(workingConstraintTol);
Peter Eastman's avatar
Peter Eastman committed
290
291
}