"...opencl/tests/TestOpenCLLangevinMiddleIntegrator.cpp" did not exist on "52c35f70a95a305ea78186ec847ce1bff4ac7929"
LocalEnergyMinimizer.cpp 8.04 KB
Newer Older
Peter Eastman's avatar
Peter Eastman 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) 2010-2016 Stanford University and the Authors.      *
Peter Eastman's avatar
Peter Eastman 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
37
38
 * 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 "lbfgs.h"
#include "openmm/Platform.h"
#include <cmath>
#include <sstream>
#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
48
49
    MinimizerData(Context& context, double k)
        : context(context), k(k) {}
};
50

Peter Eastman's avatar
Peter Eastman committed
51
static lbfgsfloatval_t evaluate(void *instance, const lbfgsfloatval_t *x, lbfgsfloatval_t *g, const int n, const lbfgsfloatval_t step) {
52
53
54
55
56
57
58
    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.

Peter Eastman's avatar
Peter Eastman committed
59
60
61
    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]);
62
    context.setPositions(positions);
63
    context.computeVirtualSites();
64
    State state = context.getState(State::Forces | State::Energy);
Peter Eastman's avatar
Peter Eastman committed
65
66
    const vector<Vec3>& forces = state.getForces();
    for (int i = 0; i < numParticles; i++) {
67
        if (system.getParticleMass(i) == 0) {
68
69
70
71
72
73
74
75
76
            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
77
    }
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
    double energy = state.getPotentialEnergy();

    // 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;
        g[3*particle1] -= kdr*delta[0];
        g[3*particle1+1] -= kdr*delta[1];
        g[3*particle1+2] -= kdr*delta[2];
        g[3*particle2] += kdr*delta[0];
        g[3*particle2+1] += kdr*delta[1];
        g[3*particle2+2] += kdr*delta[2];
    }
    return energy;
Peter Eastman's avatar
Peter Eastman committed
103
104
105
}

void LocalEnergyMinimizer::minimize(Context& context, double tolerance, int maxIterations) {
106
    const System& system = context.getSystem();
107
    int numParticles = system.getNumParticles();
Peter Eastman's avatar
Peter Eastman committed
108
109
110
    lbfgsfloatval_t *x = lbfgs_malloc(numParticles*3);
    if (x == NULL)
        throw OpenMMException("LocalEnergyMinimizer: Failed to allocate memory");
111
    double constraintTol = context.getIntegrator().getConstraintTolerance();
peastman's avatar
peastman committed
112
    double workingConstraintTol = std::max(1e-4, constraintTol);
113
    double k = tolerance/workingConstraintTol;
Peter Eastman's avatar
Peter Eastman committed
114

115
    // Initialize the minimizer.
Peter Eastman's avatar
Peter Eastman committed
116
117
118
119
120
121
122

    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;
123

124
    // Make sure the initial configuration satisfies all constraints.
125

126
    context.applyConstraints(workingConstraintTol);
127

128
    // Record the initial positions and determine a normalization constant for scaling the tolerance.
129

130
131
132
133
134
135
136
137
138
139
140
    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]);
    }
    norm /= numParticles;
    norm = (norm < 1 ? 1 : sqrt(norm));
    param.epsilon = tolerance/norm;
141

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

144
145
    double prevMaxError = 1e10;
    while (true) {
146
147
148
        // Perform the minimization.

        lbfgsfloatval_t fx;
149
        MinimizerData data(context, k);
150
151
152
153
        lbfgs(numParticles*3, x, &fx, evaluate, NULL, &data, &param);

        // Check whether all constraints are satisfied.

154
        vector<Vec3> positions = context.getState(State::Positions).getPositions();
155
156
157
158
159
160
161
162
163
164
165
166
        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));
            double error = fabs(r-distance);
            if (error > maxError)
                maxError = error;
        }
167
        if (maxError <= workingConstraintTol)
168
            break; // All constraints are satisfied.
169
170
171
        context.setPositions(initialPos);
        if (maxError >= prevMaxError)
            break; // Further tightening the springs doesn't seem to be helping, so just give up.
172
173
        prevMaxError = maxError;
        k *= 10;
174
        if (maxError > 100*workingConstraintTol) {
175
176
177
178
179
180
181
182
183
            // 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];
            }
        }
184
    }
Peter Eastman's avatar
Peter Eastman committed
185
    lbfgs_free(x);
186
187
188
189
190
191
    
    // 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
192
193
}