DrudeHelpers.cpp 9.51 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) 2008-2025 Stanford University and the Authors.      *
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
 * 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.                                     *
 * -------------------------------------------------------------------------- */

32
#include "openmm/internal/DrudeHelpers.h"
33
34
#include "sfmt/SFMT.h"
#include "SimTKOpenMMRealType.h"
35
#include "openmm/CMMotionRemover.h"
36
37
38
#include "openmm/DrudeLangevinIntegrator.h"
#include "openmm/Context.h"
#include "openmm/OpenMMException.h"
39
#include "openmm/internal/ForceImpl.h"
40
41
42

#include <set>

43
44
using namespace std;

45
46
namespace OpenMM {

47
/**
48
 * Find the DrudeForce contained in the System.
49
 */
50
51
52
const DrudeForce* getDrudeForce(const ContextImpl& context) {
    const DrudeForce* force = NULL;
    const System& system = context.getSystem();
53
54
    for (int i = 0; i < system.getNumForces(); i++)
        if (dynamic_cast<const DrudeForce*>(&system.getForce(i)) != NULL) {
55
56
            if (force == NULL)
                force = dynamic_cast<const DrudeForce*>(&system.getForce(i));
57
58
59
            else
                throw OpenMMException("The System contains multiple DrudeForces");
        }
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
    if (force != NULL)
        return force;

    // The System doesn't directly contain a DrudeForce.  Look for one inside another force.

    for (const ForceImpl* impl : context.getForceImpls())
        for (const Force* f : impl->getContainedForces())
            if (dynamic_cast<const DrudeForce*>(f) != NULL) {
                if (force == NULL)
                    force = dynamic_cast<const DrudeForce*>(f);
                else
                    throw OpenMMException("The System contains multiple DrudeForces");
            }
    if (force != NULL)
        return force;
    throw OpenMMException("The System does not contain a DrudeForce");
}

/**
 * Identify normal particles (not part of a pair) and Drude particle pairs.
 */
void findParticlesAndPairs(const ContextImpl& context, vector<int>& normalParticles, vector<pair<int, int> >& pairParticles) {
    const System& system = context.getSystem();
    const DrudeForce* drudeForce = getDrudeForce(context);
84
85

    // Figure out which particles are individual and which are Drude pairs
86
87
    set<int> particles;
    for (int i = 0; i < system.getNumParticles(); i++)
88
89
90
91
92
93
94
95
96
        particles.insert(i);
    for (int i = 0; i < drudeForce->getNumParticles(); i++) {
        int p, p1, p2, p3, p4;
        double charge, polarizability, aniso12, aniso34;
        drudeForce->getParticleParameters(i, p, p1, p2, p3, p4, charge, polarizability, aniso12, aniso34);
        particles.erase(p);
        particles.erase(p1);
        pairParticles.emplace_back(p, p1);
    }
97
98
99
    normalParticles.insert(normalParticles.begin(), particles.begin(), particles.end());
}

100
101
vector<Vec3> assignDrudeVelocities(const ContextImpl& context, double temperature, double drudeTemperature, int randomSeed) {
    const System& system = context.getSystem();
102
103
    vector<int> normalParticles;
    vector<pair<int, int> > pairParticles;
104
    findParticlesAndPairs(context, normalParticles, pairParticles);
105
106
107
108

    // Generate the list of Gaussian random numbers.
    OpenMM_SFMT::SFMT sfmt;
    init_gen_rand(randomSeed, sfmt);
109
    vector<double> randoms;
110
111
112
113
114
115
116
    while (randoms.size() < system.getNumParticles()*3) {
        double x, y, r2;
        do {
            x = 2.0*genrand_real2(sfmt)-1.0;
            y = 2.0*genrand_real2(sfmt)-1.0;
            r2 = x*x + y*y;
        } while (r2 >= 1.0 || r2 == 0.0);
117
        double multiplier = sqrt((-2.0*log(r2))/r2);
118
119
120
121
122
        randoms.push_back(x*multiplier);
        randoms.push_back(y*multiplier);
    }

    // Assign the velocities.
123
    vector<Vec3> velocities(system.getNumParticles(), Vec3());
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
    int nextRandom = 0;
    // First the indivitual atoms
    for (const auto &atom : normalParticles ) {
        double mass = system.getParticleMass(atom);
        if (mass != 0) {
            double velocityScale = sqrt(BOLTZ*temperature/mass);
            velocities[atom] = Vec3(randoms[nextRandom++], randoms[nextRandom++], randoms[nextRandom++])*velocityScale;
        }
    }
    // Now the particle-Drude pairs
    for (const auto &pair : pairParticles ) {
        const auto atom1 = pair.first;
        const auto atom2 = pair.second;
        double mass1 = system.getParticleMass(atom1);
        double mass2 = system.getParticleMass(atom2);
        if (mass1 != 0 && mass2 != 0) {
            double invMass = 1.0 / (mass1 + mass2);
            double redMass = mass1 * mass2 * invMass;
            double fracM1 = mass1 * invMass;
            double fracM2 = mass2 * invMass;
            Vec3 comVelocity = Vec3(randoms[nextRandom++], randoms[nextRandom++], randoms[nextRandom++])*sqrt(BOLTZ*temperature*invMass);
            Vec3 relVelocity = Vec3(randoms[nextRandom++], randoms[nextRandom++], randoms[nextRandom++])*sqrt(BOLTZ*drudeTemperature/redMass);
            velocities[atom1] = comVelocity - fracM2 * relVelocity;
            velocities[atom2] = comVelocity + fracM1 * relVelocity;
        }
149
150
151
152
        else if (mass2 != 0) {
            double velocityScale = sqrt(BOLTZ*temperature/mass2);
            velocities[atom2] = Vec3(randoms[nextRandom++], randoms[nextRandom++], randoms[nextRandom++])*velocityScale;
        }
153
154
155
156
    }
    return velocities;
}

157
158
159
160

/**
 * Computes the instantaneous temperatures of the system and the internal Drude motion and returns a pair (T_system, T_drude)
 */
161
162
pair<double, double> computeTemperaturesFromVelocities(const ContextImpl& context, const vector<Vec3>& velocities) {
    const System& system = context.getSystem();
163
164
    vector<int> normalParticles;
    vector<pair<int, int> > pairParticles;
165
    findParticlesAndPairs(context, normalParticles, pairParticles);
166
167
    double energy = 0.0, drudeEnergy = 0;
    int dof = 0, drudeDof = 0;
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
    
    // Kinetic energy and degrees of freedom from normal particles.
    
    for (int i : normalParticles) {
        double mass = system.getParticleMass(i);
        if (mass > 0) {
            energy += mass*(velocities[i].dot(velocities[i]));
            dof += 3;
        }
    }
    
    // Kinetic energy and degrees of freedom from Drude particle pairs.
    
    for (auto pair : pairParticles) {
        int p1 = pair.first;
        int p2 = pair.second;
        double mass1 = system.getParticleMass(p1);
        double mass2 = system.getParticleMass(p2);
186
	double reducedMass = (mass1*mass2)/(mass1+mass2);
187
188
189
        if (mass1 != 0 || mass2 != 0) {
            Vec3 momentum = mass1*velocities[p1] + mass2*velocities[p2];
            energy += momentum.dot(momentum)/(mass1+mass2);
190
191
192
193
	    Vec3 drudeVelocity = velocities[p1] - velocities[p2];
            drudeEnergy += reducedMass*drudeVelocity.dot(drudeVelocity);
	    dof += 3;
	    drudeDof += 3;
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
        }
    }
    
    // Reduce degrees of freedom for constraints.

    for (int i = 0; i < system.getNumConstraints(); i++) {
        int p1, p2;
        double distance;
        system.getConstraintParameters(i, p1, p2, distance);
        if (system.getParticleMass(p1) > 0 || system.getParticleMass(p2) > 0)
            dof--;
    }

    // Reduce degrees of freedom if there is a CMMotionRemover.

    for (int i = 0; i < system.getNumForces(); i++)
        if (dynamic_cast<const CMMotionRemover*>(&system.getForce(i)) != NULL) {
            dof -= 3;
            break;
        }
    energy *= 0.5;
215
216
217
218
    drudeEnergy *= 0.5;
    if (drudeDof == 0)
        drudeDof = 1; // so that the drude temperature is reported as 0
    return make_pair<double, double>(2*energy/(dof*BOLTZ), 2*drudeEnergy/(drudeDof*BOLTZ));
219
220
}

221
}