MonteCarloBarostatImpl.cpp 7.75 KB
Newer Older
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.                                        *
6
 *                                                                            *
7
 * Portions copyright (c) 2010-2026 Stanford University and the Authors.      *
8
9
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.                                     *
 * -------------------------------------------------------------------------- */

#include "openmm/internal/MonteCarloBarostatImpl.h"
#include "openmm/internal/ContextImpl.h"
32
#include "openmm/internal/OSRngSeed.h"
33
34
#include "openmm/Context.h"
#include "openmm/kernels.h"
35
#include "openmm/OpenMMException.h"
36
#include "SimTKOpenMMUtilities.h"
37
38
#include <cmath>
#include <vector>
39
#include <algorithm>
40
41

using namespace OpenMM;
42
using namespace std;
43

44
MonteCarloBarostatImpl::MonteCarloBarostatImpl(const MonteCarloBarostat& owner) : owner(owner), step(0) {
45
46
47
}

void MonteCarloBarostatImpl::initialize(ContextImpl& context) {
48
49
    if (!context.getSystem().usesPeriodicBoundaryConditions())
        throw OpenMMException("A barostat cannot be used with a non-periodic system");
50
    kernel = context.getPlatform().createKernel(ApplyMonteCarloBarostatKernel::Name(), context);
51
    kernel.getAs<ApplyMonteCarloBarostatKernel>().initialize(context.getSystem(), owner, 1, owner.getScaleMoleculesAsRigid());
52
    Vec3 box[3];
53
    context.getPeriodicBoxVectors(box[0], box[1], box[2]);
54
55
    double volume = box[0][0]*box[1][1]*box[2][2];
    volumeScale = 0.01*volume;
56
57
    numAttempted = 0;
    numAccepted = 0;
58
    SimTKOpenMMUtilities::setRandomNumberSeed(owner.getRandomNumberSeed());
59
60
}

61
void MonteCarloBarostatImpl::updateContextState(ContextImpl& context, bool& forcesInvalid) {
62
    if (++step < owner.getFrequency() || owner.getFrequency() == 0)
63
64
        return;
    step = 0;
65

66
    // Compute the current potential energy.
67

68
69
    int groups = context.getIntegrator().getIntegrationForceGroups();
    double initialEnergy = context.getOwner().getState(State::Energy, false, groups).getPotentialEnergy();
70

71
    // Modify the periodic box size.
72

73
    Vec3 box[3];
74
    context.getPeriodicBoxVectors(box[0], box[1], box[2]);
75
    double volume = box[0][0]*box[1][1]*box[2][2];
76
    double deltaVolume = volumeScale*2*(SimTKOpenMMUtilities::getUniformlyDistributedRandomNumber()-0.5);
77
    double newVolume = volume+deltaVolume;
78
    double lengthScale = pow(newVolume/volume, 1.0/3.0);
79
    kernel.getAs<ApplyMonteCarloBarostatKernel>().saveCoordinates(context);
80
    context.getOwner().setPeriodicBoxVectors(box[0]*lengthScale, box[1]*lengthScale, box[2]*lengthScale);
81
    kernel.getAs<ApplyMonteCarloBarostatKernel>().scaleCoordinates(context, lengthScale, lengthScale, lengthScale);
82

83
    // Compute the energy of the modified system.
84
85
86
87
88
89

    double numberOfScaledParticles;
    if (owner.getScaleMoleculesAsRigid())
        numberOfScaledParticles = context.getMolecules().size();
    else
        numberOfScaledParticles = context.getSystem().getNumParticles();
90
    double finalEnergy = context.getOwner().getState(State::Energy, false, groups).getPotentialEnergy();
91
    double pressure = context.getParameter(MonteCarloBarostat::Pressure())*(AVOGADRO*1e-25);
92
    double kT = BOLTZ*context.getParameter(MonteCarloBarostat::Temperature());
93
    double w = finalEnergy-initialEnergy + pressure*deltaVolume - numberOfScaledParticles*kT*log(newVolume/volume);
94
    if (w > 0 && SimTKOpenMMUtilities::getUniformlyDistributedRandomNumber() > exp(-w/kT)) {
95
        // Reject the step.
96

97
        context.getOwner().setPeriodicBoxVectors(box[0], box[1], box[2]);
98
        kernel.getAs<ApplyMonteCarloBarostatKernel>().restoreCoordinates(context);
99
    }
100
    else {
101
        numAccepted++;
102
103
        forcesInvalid = true;
    }
104
105
106
107
108
109
110
111
    numAttempted++;
    if (numAttempted >= 10) {
        if (numAccepted < 0.25*numAttempted) {
            volumeScale /= 1.1;
            numAttempted = 0;
            numAccepted = 0;
        }
        else if (numAccepted > 0.75*numAttempted) {
112
            volumeScale = min(volumeScale*1.1, volume*0.3);
113
114
115
116
            numAttempted = 0;
            numAccepted = 0;
        }
    }
117
118
}

119
map<string, double> MonteCarloBarostatImpl::getDefaultParameters() {
Peter Eastman's avatar
Peter Eastman committed
120
121
    return {{MonteCarloBarostat::Pressure(), getOwner().getDefaultPressure()},
            {MonteCarloBarostat::Temperature(), getOwner().getDefaultTemperature()}};
122
123
}

124
vector<string> MonteCarloBarostatImpl::getKernelNames() {
Peter Eastman's avatar
Peter Eastman committed
125
    return {ApplyMonteCarloBarostatKernel::Name()};
126
127
}

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
156
157
158
159
160
161
162
double MonteCarloBarostatImpl::computeCurrentPressure(ContextImpl& context) {
    Vec3 box[3];
    context.getPeriodicBoxVectors(box[0], box[1], box[2]);
    double volume = box[0][0]*box[1][1]*box[2][2];
    double delta = 1e-3;
    int groups = context.getIntegrator().getIntegrationForceGroups();
    kernel.getAs<ApplyMonteCarloBarostatKernel>().saveCoordinates(context);

    // Compute the first energy.

    double scale1 = 1.0+delta;
    context.getOwner().setPeriodicBoxVectors(box[0]*scale1, box[1]*scale1, box[2]*scale1);
    kernel.getAs<ApplyMonteCarloBarostatKernel>().scaleCoordinates(context, scale1, scale1, scale1);
    double energy1 = context.getOwner().getState(State::Energy, false, groups).getPotentialEnergy();

    // Compute the second energy.

    double scale2 = 1.0-delta;
    context.getOwner().setPeriodicBoxVectors(box[0]*scale2, box[1]*scale2, box[2]*scale2);
    kernel.getAs<ApplyMonteCarloBarostatKernel>().scaleCoordinates(context, scale2/scale1, scale2/scale1, scale2/scale1);
    double energy2 = context.getOwner().getState(State::Energy, false, groups).getPotentialEnergy();

    // Restore the context to its original state.

    context.getOwner().setPeriodicBoxVectors(box[0], box[1], box[2]);
    kernel.getAs<ApplyMonteCarloBarostatKernel>().restoreCoordinates(context);

    // Compute the pressure.

    vector<double> ke;
    kernel.getAs<ApplyMonteCarloBarostatKernel>().computeKineticEnergy(context, ke);
    double deltaVolume = volume*(scale1*scale1*scale1 - scale2*scale2*scale2);
    double pressure = (2.0/3.0)*ke[0]/volume - (energy1-energy2)/deltaVolume;
    return pressure/(AVOGADRO*1e-25);
}