HelloSodiumChlorideInC.c 15.5 KB
Newer Older
1
/* -----------------------------------------------------------------------------
Michael Sherman's avatar
Michael Sherman committed
2
 *           OpenMM(tm) HelloSodiumChloride example in C (June 2009)
3
4
 * -----------------------------------------------------------------------------
 * This is a complete, self-contained "hello world" example demonstrating 
Michael Sherman's avatar
Michael Sherman committed
5
6
7
8
9
 * GPU-accelerated constant temperature simulation of a very simple system with
 * just nonbonded forces, consisting of several sodium (Na+) and chloride (Cl-) 
 * ions in implicit solvent. A multi-frame PDB file is written to stdout which 
 * can be read by VMD or other visualization tool to produce an animation of the 
 * resulting trajectory.
10
11
12
 *
 * Pay particular attention to the handling of units in this example. Incorrect
 * handling of units is a very common error; this example shows how you can
Michael Sherman's avatar
Michael Sherman committed
13
14
 * continue to work with Amber-style units like Angstroms, kCals, and van der
 * Waals radii while correctly communicating with OpenMM in nm, kJ, and sigma.
15
 *
16
 * This example is written entirely in ANSI C, using the OpenMM C bindings.
17
 * -------------------------------------------------------------------------- */
Michael Sherman's avatar
Michael Sherman committed
18

19
20

#include <stdio.h>
21
#include <stdlib.h>
22

Michael Sherman's avatar
Michael Sherman committed
23
/* --------------------------------------------------------------------------
24
25
 *                   MODELING AND SIMULATION PARAMETERS
 * -------------------------------------------------------------------------- */
Michael Sherman's avatar
Michael Sherman committed
26
static const double Temperature         = 300;    /*Kelvins */
27
static const double FrictionInPerPs     = 91.;    /*collisions per ps*/
Michael Sherman's avatar
Michael Sherman committed
28
29
static const double SolventDielectric   = 80.;    /*typical for water    */
static const double SoluteDielectric    = 2.;     /*typical for protein  */
30

Michael Sherman's avatar
Michael Sherman committed
31
static const double StepSizeInFs        = 2;      /*integration step size (fs)  */
32
static const double ReportIntervalInFs  = 50;     /*how often for PDB frame (fs)*/
Michael Sherman's avatar
Michael Sherman committed
33
static const double SimulationTimeInPs  = 100;    /*total simulation time (ps)  */
34

Michael Sherman's avatar
Michael Sherman committed
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/* Currently energy calculation is not available in the GPU kernels so asking
   for it requires slow Reference Platform computation at reporting intervals. */
static const int    WantEnergy          = 1;


/* --------------------------------------------------------------------------
 *                          ATOM AND FORCE FIELD DATA
 * --------------------------------------------------------------------------
 * This is not part of OpenMM; just a struct we can use to collect atom 
 * parameters for this example. Normally atom parameters would come from the 
 * force field's parameterization file. We're going to use data in Angstrom and 
 * Kilocalorie units and show how to safely convert to OpenMM's internal unit 
 * system which uses nanometers and kilojoules.
 */
typedef struct MyAtomInfo_s { 
    const char* pdb; 
    double      mass, charge, vdwRadiusInAng, vdwEnergyInKcal,
                gbsaRadiusInAng, gbsaScaleFactor;
    double      initPosInAng[3];
    double      posInAng[3]; /*leave room for runtime state info*/
} MyAtomInfo;
static MyAtomInfo atoms[] = {
/* pdb   mass  charge  vdwRad vdwEnergy   gbsaRad gbsaScale  initPos */
{" NA ", 22.99,  1,    1.8680, 0.00277,    1.992,   0.8,     8, 0,  0},
{" CL ", 35.45, -1,    2.4700, 0.1000,     1.735,   0.8,    -8, 0,  0},
{" NA ", 22.99,  1,    1.8680, 0.00277,    1.992,   0.8,     0, 9,  0},
{" CL ", 35.45, -1,    2.4700, 0.1000,     1.735,   0.8,     0,-9,  0},
{" NA ", 22.99,  1,    1.8680, 0.00277,    1.992,   0.8,     0, 0,-10},
{" CL ", 35.45, -1,    2.4700, 0.1000,     1.735,   0.8,     0, 0, 10},
{""} // end of list
};


/* --------------------------------------------------------------------------
 *                           INTERFACE TO OpenMM
 * --------------------------------------------------------------------------
 * These four functions and an opaque structure are used to interface our main
 * program with OpenMM without the main program having any direct interaction
 * with the OpenMM API. This is a clean approach for interfacing with any MD
 * code, although the details of the interface routines will differ.
 */
typedef struct MyOpenMMData_s MyOpenMMData;
static MyOpenMMData* myInitializeOpenMM(const MyAtomInfo atoms[],
                                        double temperature,
                                        double frictionInPs,
                                        double solventDielectric,
                                        double soluteDielectric,
                                        double stepSizeInFs, 
                                        const char** platformName);
static void          myStepWithOpenMM(MyOpenMMData*, int numSteps);
static void          myGetOpenMMState(MyOpenMMData*, int wantEnergy,
                                      double* time, double* energy, 
                                      MyAtomInfo atoms[]);
static void          myTerminateOpenMM(MyOpenMMData*);

/* --------------------------------------------------------------------------
 *                               PDB FILE WRITER
 * --------------------------------------------------------------------------
 * Given state data, output a single frame (pdb "model") of the trajectory.
 */
static void
myWritePDBFrame(int frameNum, double timeInPs, double energyInKcal, 
                const MyAtomInfo atoms[]) 
{
    int n;

101
    /* Write out in PDB format. */
Michael Sherman's avatar
Michael Sherman committed
102
103
104
105
106
107
108
109
110
111
112
113
    printf("MODEL     %d\n", frameNum);
    printf("REMARK 250 time=%.3f ps; energy=%.3f kcal/mole\n", 
           timeInPs, energyInKcal);
    for (n=0; *atoms[n].pdb; ++n)
        printf("ATOM  %5d %4s SLT     1    %8.3f%8.3f%8.3f  1.00  0.00\n", 
            n+1, atoms[n].pdb, 
            atoms[n].posInAng[0], atoms[n].posInAng[1], atoms[n].posInAng[2]);
    printf("ENDMDL\n");
}


/* --------------------------------------------------------------------------
114
 *                                MAIN PROGRAM
Michael Sherman's avatar
Michael Sherman committed
115
 * -------------------------------------------------------------------------- */
116
int main() {
Michael Sherman's avatar
Michael Sherman committed
117
118
119
120
    const int NumReports     = (int)(SimulationTimeInPs*1000 / ReportIntervalInFs + 0.5);
    const int NumSilentSteps = (int)(ReportIntervalInFs / StepSizeInFs + 0.5);
    int frame;

121
    /* TODO: what about thrown exceptions? */
Michael Sherman's avatar
Michael Sherman committed
122
123
    double        time, energy;
    const char*   platformName;
124

125
    /* Set up OpenMM data structures; returns OpenMM Platform name. */
126
    MyOpenMMData* omm = myInitializeOpenMM(atoms, Temperature, FrictionInPerPs,
Michael Sherman's avatar
Michael Sherman committed
127
128
                                           SolventDielectric, SoluteDielectric,
                                           StepSizeInFs, &platformName);
129

130
131
132
133
    /* Run the simulation:
     *  (1) Write the first line of the PDB file and the initial configuration.
     *  (2) Run silently entirely within OpenMM between reporting intervals.
     *  (3) Write a PDB frame when the time comes. */
Michael Sherman's avatar
Michael Sherman committed
134
135
136
137
138
139
140
141
142
143
    printf("REMARK  Using OpenMM platform %s\n", platformName);
    myGetOpenMMState(omm, WantEnergy, &time, &energy, atoms);
    myWritePDBFrame(0, time, energy, atoms);

    for (frame=1; frame <= NumReports; ++frame) {
        myStepWithOpenMM(omm, NumSilentSteps);
        myGetOpenMMState(omm, WantEnergy, &time, &energy, atoms);
        myWritePDBFrame(frame, time, energy, atoms);
    } 

144
    /* Clean up OpenMM data structures. */
Michael Sherman's avatar
Michael Sherman committed
145
146
    myTerminateOpenMM(omm);

147
    return 0; /* Normal return from main. */
148
149
}

Michael Sherman's avatar
Michael Sherman committed
150
151
152
153
154
155
156
157
158

/* --------------------------------------------------------------------------
 *                           OpenMM-USING CODE
 * --------------------------------------------------------------------------
 * The OpenMM C-wrapped API is visible only at this point and below. Normally 
 * this would be in a separate compilation module; we're including it here for 
 * simplicity. We suggest that you write them in C++ if possible; in fact you
 * can use the implementation from the C++ version of this example if you 
 * want. However, the methods are reimplemented in C below in case you prefer.
159
 */
160
#include "OpenMMCWrapper.h"
161

Michael Sherman's avatar
Michael Sherman committed
162
163
164

struct MyOpenMMData_s {
    OpenMM_System*      system;
165
    OpenMM_Context*     context;
Michael Sherman's avatar
Michael Sherman committed
166
167
168
169
170
171
172
    OpenMM_Integrator*  integrator;
};

/* --------------------------------------------------------------------------
 *                      INITIALIZE OpenMM DATA STRUCTURES
 * --------------------------------------------------------------------------
 * We take these actions here:
Michael Sherman's avatar
Michael Sherman committed
173
174
 * (1) Load any available OpenMM plugins, e.g. Cuda and Brook.
 * (2) Allocate a MyOpenMMData structure to hang on to OpenMM data structures
Michael Sherman's avatar
Michael Sherman committed
175
176
177
178
179
180
 *     in a manner which is opaque to the caller.
 * (3) Fill the OpenMM::System with the force field parameters we want to
 *     use and the particular set of atoms to be simulated.
 * (4) Create an Integrator and a Context associating the Integrator with
 *     the System.
 * (5) Select the OpenMM platform to be used.
Michael Sherman's avatar
Michael Sherman committed
181
182
 * (6) Return an opaque pointer to the MyOpenMMData struct and the name 
 *     of the Platform in use.
Michael Sherman's avatar
Michael Sherman committed
183
184
185
 *
 * Note that this function must understand the calling MD code's molecule and
 * force field data structures so will need to be customized for each MD code.
Michael Sherman's avatar
Michael Sherman committed
186
 */
Michael Sherman's avatar
Michael Sherman committed
187
188
189
static MyOpenMMData* 
myInitializeOpenMM( const MyAtomInfo    atoms[],
                    double              temperature,
190
                    double              frictionInPerPs,
Michael Sherman's avatar
Michael Sherman committed
191
192
193
194
195
196
197
198
199
200
201
                    double              solventDielectric,
                    double              soluteDielectric,
                    double              stepSizeInFs, 
                    const char**        platformName) 
{
    /* Allocate space to hold OpenMM objects while we're using them. */
    MyOpenMMData* omm = (MyOpenMMData*)malloc(sizeof(struct MyOpenMMData_s));
    /* These are temporary OpenMM objects used and discarded here. */
    OpenMM_Vec3Array*       initialPosInNm;
    OpenMM_NonbondedForce*  nonbond;
    OpenMM_GBSAOBCForce*    gbsa;
202
    OpenMM_Platform*        platform;
203
    int n;
Michael Sherman's avatar
Michael Sherman committed
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222

    /* Load all available OpenMM plugins from their default location. */
    OpenMM_Platform_loadPluginsFromDirectory
       (OpenMM_Platform_getDefaultPluginsDirectory());

    /* Create a System and Force objects within the System. Retain a reference
     * to each force object so we can fill in the forces. Note: the OpenMM
     * System takes ownership of the force objects; don't delete them yourself. */
    omm->system = OpenMM_System_create();
    nonbond     = OpenMM_NonbondedForce_create();
    gbsa        = OpenMM_GBSAOBCForce_create();
    OpenMM_System_addForce(omm->system, (OpenMM_Force*)nonbond);
    OpenMM_System_addForce(omm->system, (OpenMM_Force*)gbsa);

    /* Specify dielectrics for GBSA implicit solvation. */
    OpenMM_GBSAOBCForce_setSolventDielectric(gbsa, solventDielectric);
    OpenMM_GBSAOBCForce_setSoluteDielectric(gbsa, soluteDielectric);

    /* Specify the atoms and their properties:
223
224
     *  (1) System needs to know the masses.
     *  (2) NonbondedForce needs charges,van der Waals properties (in MD units!).
Michael Sherman's avatar
Michael Sherman committed
225
     *  (3) GBSA needs charge, radius, and scale factor.
Michael Sherman's avatar
Michael Sherman committed
226
     *  (4) Collect default positions for initializing the simulation later. */
Michael Sherman's avatar
Michael Sherman committed
227
    initialPosInNm = OpenMM_Vec3Array_create(0);
228
    for (n=0; *atoms[n].pdb; ++n) {
Michael Sherman's avatar
Michael Sherman committed
229
        const MyAtomInfo* atom = &atoms[n];
230
        OpenMM_Vec3 posInNm;
231

Michael Sherman's avatar
Michael Sherman committed
232
233
234
235
236
237
238
239
240
241
242
243
        OpenMM_System_addParticle(omm->system, atom->mass);

        OpenMM_NonbondedForce_addParticle(nonbond,
                                atom->charge,
                                atom->vdwRadiusInAng  * OpenMM_NmPerAngstrom 
                                                      * OpenMM_SigmaPerVdwRadius,
                                atom->vdwEnergyInKcal * OpenMM_KJPerKcal);

        OpenMM_GBSAOBCForce_addParticle(gbsa,
                                atom->charge, 
                                atom->gbsaRadiusInAng * OpenMM_NmPerAngstrom,
                                atom->gbsaScaleFactor);
244
245

        /* Convert the initial position to nm and append to the array. */
246
        posInNm = OpenMM_Vec3_scale(*(const OpenMM_Vec3*)atom->initPosInAng, OpenMM_NmPerAngstrom);
Michael Sherman's avatar
Michael Sherman committed
247
        OpenMM_Vec3Array_append(initialPosInNm, posInNm);
248
249
    }

Michael Sherman's avatar
Michael Sherman committed
250
    /* Choose an Integrator for advancing time, and a Context connecting the
251
252
     * System with the Integrator for simulation. Let the Context choose the
     * best available Platform. Initialize the configuration from the default
Michael Sherman's avatar
Michael Sherman committed
253
254
255
     * positions we collected above. Initial velocities will be zero but could
     * have been set here. */
    omm->integrator = (OpenMM_Integrator*)OpenMM_LangevinIntegrator_create(
256
                                            temperature, frictionInPerPs, 
Michael Sherman's avatar
Michael Sherman committed
257
258
259
                                            stepSizeInFs * OpenMM_PsPerFs);
    omm->context    = OpenMM_Context_create(omm->system, omm->integrator);
    OpenMM_Context_setPositions(omm->context, initialPosInNm);
260

261
262
    platform = OpenMM_Context_getPlatform(omm->context);
    *platformName = OpenMM_Platform_getName(platform);
Michael Sherman's avatar
Michael Sherman committed
263
    return omm;
264
265
266
267
268
}




Michael Sherman's avatar
Michael Sherman committed
269
270
271
272
273
274
275
276
277
/* --------------------------------------------------------------------------
 *                    COPY STATE BACK TO CPU FROM OPENMM
 * -------------------------------------------------------------------------- */
static void
myGetOpenMMState(MyOpenMMData* omm, int wantEnergy, 
                 double* timeInPs, double* energyInKcal,
                 MyAtomInfo atoms[])
{
    OpenMM_State*           state;
Michael Sherman's avatar
Michael Sherman committed
278
    const OpenMM_Vec3Array* posArrayInNm;
Michael Sherman's avatar
Michael Sherman committed
279
280
281
282
283
284
285
286
287
288
289
    int                     infoMask;
    int n;

    infoMask = OpenMM_State_Positions;
    if (wantEnergy) {
        infoMask += OpenMM_State_Velocities; /*for kinetic energy (cheap)*/
        infoMask += OpenMM_State_Energy;     /*for pot. energy (expensive)*/
    }
    /* Forces are also available (and cheap). */

    /* State object is created here and must be explicitly destroyed below. */
290
    state = OpenMM_Context_getState(omm->context, infoMask);
Michael Sherman's avatar
Michael Sherman committed
291
    *timeInPs = OpenMM_State_getTime(state); /* OpenMM time is in ps already. */
292
293

    /* Positions are maintained as a Vec3Array inside the State. This will give
Michael Sherman's avatar
Michael Sherman committed
294
     * us access, but don't destroy it yourself -- it will go away with the State. */
Michael Sherman's avatar
Michael Sherman committed
295
296
297
    posArrayInNm = OpenMM_State_getPositions(state);
    for (n=0; *atoms[n].pdb; ++n)
        /* Sets atoms[n].pos = posArray[n] * Angstroms/nm. */
298
299
300
        *(OpenMM_Vec3*)atoms[n].posInAng = 
            OpenMM_Vec3_scale(*OpenMM_Vec3Array_get(posArrayInNm, n),
                              OpenMM_AngstromsPerNm); 
Michael Sherman's avatar
Michael Sherman committed
301
302
303
304
305
306
307

    /* If energy has been requested, obtain it and convert from kJ to kcal. */
    *energyInKcal = 0;
    if (wantEnergy) 
        *energyInKcal = (   OpenMM_State_getPotentialEnergy(state) 
                          + OpenMM_State_getKineticEnergy(state))
                        * OpenMM_KcalPerKJ;
308
309
310
311

    OpenMM_State_destroy(state);
}

Michael Sherman's avatar
Michael Sherman committed
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333

// -----------------------------------------------------------------------------
//                     TAKE MULTIPLE STEPS USING OpenMM 
// -----------------------------------------------------------------------------
static void 
myStepWithOpenMM(MyOpenMMData* omm, int numSteps) {
    OpenMM_Integrator_step(omm->integrator, numSteps);
}

// -----------------------------------------------------------------------------
//                     DEALLOCATE OpenMM OBJECTS
// -----------------------------------------------------------------------------
static void 
myTerminateOpenMM(MyOpenMMData* omm) {
    /* Clean up top-level heap allocated objects that we're done with now. */
    OpenMM_Context_destroy(omm->context);
    OpenMM_Integrator_destroy(omm->integrator);
    OpenMM_System_destroy(omm->system);
    free(omm);
}