Merge branch 'release-4-5-patches'
[alexxy/gromacs.git] / src / kernel / runner.c
1 /* -*- mode: c; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4; c-file-style: "stroustrup"; -*-
2  *
3  * 
4  *                This source code is part of
5  * 
6  *                 G   R   O   M   A   C   S
7  * 
8  *          GROningen MAchine for Chemical Simulations
9  * 
10  *                        VERSION 3.2.0
11  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
12  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
13  * Copyright (c) 2001-2004, The GROMACS development team,
14  * check out http://www.gromacs.org for more information.
15
16  * This program is free software; you can redistribute it and/or
17  * modify it under the terms of the GNU General Public License
18  * as published by the Free Software Foundation; either version 2
19  * of the License, or (at your option) any later version.
20  * 
21  * If you want to redistribute modifications, please consider that
22  * scientific software is very special. Version control is crucial -
23  * bugs must be traceable. We will be happy to consider code for
24  * inclusion in the official distribution, but derived work must not
25  * be called official GROMACS. Details are found in the README & COPYING
26  * files - if they are missing, get the official version at www.gromacs.org.
27  * 
28  * To help us fund GROMACS development, we humbly ask that you cite
29  * the papers on the package - you can find them in the top README file.
30  * 
31  * For more info, check our website at http://www.gromacs.org
32  * 
33  * And Hey:
34  * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
35  */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include <signal.h>
41 #include <stdlib.h>
42
43 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
44 /* _isnan() */
45 #include <float.h>
46 #endif
47
48 #include "typedefs.h"
49 #include "smalloc.h"
50 #include "sysstuff.h"
51 #include "statutil.h"
52 #include "mdrun.h"
53 #include "network.h"
54 #include "pull.h"
55 #include "names.h"
56 #include "disre.h"
57 #include "orires.h"
58 #include "dihre.h"
59 #include "pppm.h"
60 #include "pme.h"
61 #include "mdatoms.h"
62 #include "repl_ex.h"
63 #include "qmmm.h"
64 #include "mpelogging.h"
65 #include "domdec.h"
66 #include "partdec.h"
67 #include "coulomb.h"
68 #include "constr.h"
69 #include "mvdata.h"
70 #include "checkpoint.h"
71 #include "mtop_util.h"
72 #include "sighandler.h"
73 #include "tpxio.h"
74 #include "txtdump.h"
75 #include "membed.h"
76
77 #include "md_openmm.h"
78
79 #ifdef GMX_LIB_MPI
80 #include <mpi.h>
81 #endif
82 #ifdef GMX_THREADS
83 #include "tmpi.h"
84 #endif
85
86 #ifdef GMX_FAHCORE
87 #include "corewrap.h"
88 #endif
89
90 #ifdef GMX_OPENMM
91 #include "md_openmm.h"
92 #endif
93
94
95 typedef struct { 
96     gmx_integrator_t *func;
97 } gmx_intp_t;
98
99 /* The array should match the eI array in include/types/enums.h */
100 #ifdef GMX_OPENMM  /* FIXME do_md_openmm needs fixing */
101 const gmx_intp_t integrator[eiNR] = { {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm}, {do_md_openmm},{do_md_openmm}};
102 #else
103 const gmx_intp_t integrator[eiNR] = { {do_md}, {do_steep}, {do_cg}, {do_md}, {do_md}, {do_nm}, {do_lbfgs}, {do_tpi}, {do_tpi}, {do_md}, {do_md},{do_md}};
104 #endif
105
106 gmx_large_int_t     deform_init_init_step_tpx;
107 matrix              deform_init_box_tpx;
108 #ifdef GMX_THREADS
109 tMPI_Thread_mutex_t deform_init_box_mutex=TMPI_THREAD_MUTEX_INITIALIZER;
110 #endif
111
112
113 #ifdef GMX_THREADS
114 struct mdrunner_arglist
115 {
116     FILE *fplog;
117     t_commrec *cr;
118     int nfile;
119     const t_filenm *fnm;
120     output_env_t oenv;
121     gmx_bool bVerbose;
122     gmx_bool bCompact;
123     int nstglobalcomm;
124     ivec ddxyz;
125     int dd_node_order;
126     real rdd;
127     real rconstr;
128     const char *dddlb_opt;
129     real dlb_scale;
130     const char *ddcsx;
131     const char *ddcsy;
132     const char *ddcsz;
133     int nstepout;
134     int resetstep;
135     int nmultisim;
136     int repl_ex_nst;
137     int repl_ex_seed;
138     real pforce;
139     real cpt_period;
140     real max_hours;
141     const char *deviceOptions;
142     unsigned long Flags;
143     int ret; /* return value */
144 };
145
146
147 /* The function used for spawning threads. Extracts the mdrunner() 
148    arguments from its one argument and calls mdrunner(), after making
149    a commrec. */
150 static void mdrunner_start_fn(void *arg)
151 {
152     struct mdrunner_arglist *mda=(struct mdrunner_arglist*)arg;
153     struct mdrunner_arglist mc=*mda; /* copy the arg list to make sure 
154                                         that it's thread-local. This doesn't
155                                         copy pointed-to items, of course,
156                                         but those are all const. */
157     t_commrec *cr;  /* we need a local version of this */
158     FILE *fplog=NULL;
159     t_filenm *fnm;
160
161     fnm = dup_tfn(mc.nfile, mc.fnm);
162
163     cr = init_par_threads(mc.cr);
164
165     if (MASTER(cr))
166     {
167         fplog=mc.fplog;
168     }
169
170     mda->ret=mdrunner(cr->nnodes, fplog, cr, mc.nfile, fnm, mc.oenv, 
171                       mc.bVerbose, mc.bCompact, mc.nstglobalcomm, 
172                       mc.ddxyz, mc.dd_node_order, mc.rdd,
173                       mc.rconstr, mc.dddlb_opt, mc.dlb_scale, 
174                       mc.ddcsx, mc.ddcsy, mc.ddcsz, mc.nstepout, mc.resetstep, 
175                       mc.nmultisim, mc.repl_ex_nst, mc.repl_ex_seed, mc.pforce, 
176                       mc.cpt_period, mc.max_hours, mc.deviceOptions, mc.Flags);
177 }
178
179 /* called by mdrunner() to start a specific number of threads (including 
180    the main thread) for thread-parallel runs. This in turn calls mdrunner()
181    for each thread. 
182    All options besides nthreads are the same as for mdrunner(). */
183 static t_commrec *mdrunner_start_threads(int nthreads, 
184               FILE *fplog,t_commrec *cr,int nfile, 
185               const t_filenm fnm[], const output_env_t oenv, gmx_bool bVerbose,
186               gmx_bool bCompact, int nstglobalcomm,
187               ivec ddxyz,int dd_node_order,real rdd,real rconstr,
188               const char *dddlb_opt,real dlb_scale,
189               const char *ddcsx,const char *ddcsy,const char *ddcsz,
190               int nstepout,int resetstep,int nmultisim,int repl_ex_nst,
191               int repl_ex_seed, real pforce,real cpt_period, real max_hours, 
192               const char *deviceOptions, unsigned long Flags)
193 {
194     int ret;
195     struct mdrunner_arglist *mda;
196     t_commrec *crn; /* the new commrec */
197     t_filenm *fnmn;
198
199     /* first check whether we even need to start tMPI */
200     if (nthreads<2)
201         return cr;
202
203     /* a few small, one-time, almost unavoidable memory leaks: */
204     snew(mda,1);
205     fnmn=dup_tfn(nfile, fnm);
206
207     /* fill the data structure to pass as void pointer to thread start fn */
208     mda->fplog=fplog;
209     mda->cr=cr;
210     mda->nfile=nfile;
211     mda->fnm=fnmn;
212     mda->oenv=oenv;
213     mda->bVerbose=bVerbose;
214     mda->bCompact=bCompact;
215     mda->nstglobalcomm=nstglobalcomm;
216     mda->ddxyz[XX]=ddxyz[XX];
217     mda->ddxyz[YY]=ddxyz[YY];
218     mda->ddxyz[ZZ]=ddxyz[ZZ];
219     mda->dd_node_order=dd_node_order;
220     mda->rdd=rdd;
221     mda->rconstr=rconstr;
222     mda->dddlb_opt=dddlb_opt;
223     mda->dlb_scale=dlb_scale;
224     mda->ddcsx=ddcsx;
225     mda->ddcsy=ddcsy;
226     mda->ddcsz=ddcsz;
227     mda->nstepout=nstepout;
228     mda->resetstep=resetstep;
229     mda->nmultisim=nmultisim;
230     mda->repl_ex_nst=repl_ex_nst;
231     mda->repl_ex_seed=repl_ex_seed;
232     mda->pforce=pforce;
233     mda->cpt_period=cpt_period;
234     mda->max_hours=max_hours;
235     mda->deviceOptions=deviceOptions;
236     mda->Flags=Flags;
237
238     fprintf(stderr, "Starting %d threads\n",nthreads);
239     fflush(stderr);
240     /* now spawn new threads that start mdrunner_start_fn(), while 
241        the main thread returns */
242     ret=tMPI_Init_fn(TRUE, nthreads, mdrunner_start_fn, (void*)(mda) );
243     if (ret!=TMPI_SUCCESS)
244         return NULL;
245
246     /* make a new comm_rec to reflect the new situation */
247     crn=init_par_threads(cr);
248     return crn;
249 }
250
251
252 /* get the number of threads based on how many there were requested, 
253    which algorithms we're using, and how many particles there are. */
254 static int get_nthreads(int nthreads_requested, t_inputrec *inputrec,
255                         gmx_mtop_t *mtop)
256 {
257     int nthreads,nthreads_new;
258     int min_atoms_per_thread;
259     char *env;
260
261     nthreads = nthreads_requested;
262
263     /* determine # of hardware threads. */
264     if (nthreads_requested < 1)
265     {
266         if ((env = getenv("GMX_MAX_THREADS")) != NULL)
267         {
268             nthreads = 0;
269             sscanf(env,"%d",&nthreads);
270             if (nthreads < 1)
271             {
272                 gmx_fatal(FARGS,"GMX_MAX_THREADS (%d) should be larger than 0",
273                           nthreads);
274             }
275         }
276         else
277         {
278             nthreads = tMPI_Get_recommended_nthreads();
279         }
280     }
281
282     if (inputrec->eI == eiNM || EI_TPI(inputrec->eI))
283     {
284         /* Steps are divided over the nodes iso splitting the atoms */
285         min_atoms_per_thread = 0;
286     }
287     else
288     {
289         min_atoms_per_thread = MIN_ATOMS_PER_THREAD;
290     }
291
292     /* Check if an algorithm does not support parallel simulation.  */
293     if (nthreads != 1 && 
294         ( inputrec->eI == eiLBFGS ||
295           inputrec->coulombtype == eelEWALD ) )
296     {
297         fprintf(stderr,"\nThe integration or electrostatics algorithm doesn't support parallel runs. Not starting any threads.\n");
298         nthreads = 1;
299     }
300     else if (nthreads_requested < 1 &&
301              mtop->natoms/nthreads < min_atoms_per_thread)
302     {
303         /* the thread number was chosen automatically, but there are too many
304            threads (too few atoms per thread) */
305         nthreads_new = max(1,mtop->natoms/min_atoms_per_thread);
306
307         if (nthreads_new > 8 || (nthreads == 8 && nthreads_new > 4))
308         {
309             /* Use only multiples of 4 above 8 threads
310              * or with an 8-core processor
311              * (to avoid 6 threads on 8 core processors with 4 real cores).
312              */
313             nthreads_new = (nthreads_new/4)*4;
314         }
315         else if (nthreads_new > 4)
316         {
317             /* Avoid 5 or 7 threads */
318             nthreads_new = (nthreads_new/2)*2;
319         }
320
321         nthreads = nthreads_new;
322
323         fprintf(stderr,"\n");
324         fprintf(stderr,"NOTE: Parallelization is limited by the small number of atoms,\n");
325         fprintf(stderr,"      only starting %d threads.\n",nthreads);
326         fprintf(stderr,"      You can use the -nt option to optimize the number of threads.\n\n");
327     }
328     return nthreads;
329 }
330 #endif
331
332
333 int mdrunner(int nthreads_requested, FILE *fplog,t_commrec *cr,int nfile,
334              const t_filenm fnm[], const output_env_t oenv, gmx_bool bVerbose,
335              gmx_bool bCompact, int nstglobalcomm,
336              ivec ddxyz,int dd_node_order,real rdd,real rconstr,
337              const char *dddlb_opt,real dlb_scale,
338              const char *ddcsx,const char *ddcsy,const char *ddcsz,
339              int nstepout,int resetstep,int nmultisim,int repl_ex_nst,
340              int repl_ex_seed, real pforce,real cpt_period,real max_hours,
341              const char *deviceOptions, unsigned long Flags)
342 {
343     double     nodetime=0,realtime;
344     t_inputrec *inputrec;
345     t_state    *state=NULL;
346     matrix     box;
347     gmx_ddbox_t ddbox={0};
348     int        npme_major,npme_minor;
349     real       tmpr1,tmpr2;
350     t_nrnb     *nrnb;
351     gmx_mtop_t *mtop=NULL;
352     t_mdatoms  *mdatoms=NULL;
353     t_forcerec *fr=NULL;
354     t_fcdata   *fcd=NULL;
355     real       ewaldcoeff=0;
356     gmx_pme_t  *pmedata=NULL;
357     gmx_vsite_t *vsite=NULL;
358     gmx_constr_t constr;
359     int        i,m,nChargePerturbed=-1,status,nalloc;
360     char       *gro;
361     gmx_wallcycle_t wcycle;
362     gmx_bool       bReadRNG,bReadEkin;
363     int        list;
364     gmx_runtime_t runtime;
365     int        rc;
366     gmx_large_int_t reset_counters;
367     gmx_edsam_t ed=NULL;
368     t_commrec   *cr_old=cr; 
369     int         nthreads=1;
370     gmx_membed_t *membed=NULL;
371
372     /* CAUTION: threads may be started later on in this function, so
373        cr doesn't reflect the final parallel state right now */
374     snew(inputrec,1);
375     snew(mtop,1);
376
377     if (bVerbose && SIMMASTER(cr))
378     {
379         fprintf(stderr,"Getting Loaded...\n");
380     }
381     
382     if (Flags & MD_APPENDFILES) 
383     {
384         fplog = NULL;
385     }
386
387     snew(state,1);
388     if (MASTER(cr)) 
389     {
390         /* Read (nearly) all data required for the simulation */
391         read_tpx_state(ftp2fn(efTPX,nfile,fnm),inputrec,state,NULL,mtop);
392
393         /* NOW the threads will be started: */
394 #ifdef GMX_THREADS
395         nthreads = get_nthreads(nthreads_requested, inputrec, mtop);
396
397         if (nthreads > 1)
398         {
399             /* now start the threads. */
400             cr=mdrunner_start_threads(nthreads, fplog, cr_old, nfile, fnm, 
401                                       oenv, bVerbose, bCompact, nstglobalcomm, 
402                                       ddxyz, dd_node_order, rdd, rconstr, 
403                                       dddlb_opt, dlb_scale, ddcsx, ddcsy, ddcsz,
404                                       nstepout, resetstep, nmultisim, 
405                                       repl_ex_nst, repl_ex_seed, pforce, 
406                                       cpt_period, max_hours, deviceOptions, 
407                                       Flags);
408             /* the main thread continues here with a new cr. We don't deallocate
409                the old cr because other threads may still be reading it. */
410             if (cr == NULL)
411             {
412                 gmx_comm("Failed to spawn threads");
413             }
414         }
415 #endif
416     }
417     /* END OF CAUTION: cr is now reliable */
418
419     /* g_membed initialisation *
420      * Because we change the mtop, init_membed is called before the init_parallel *
421      * (in case we ever want to make it run in parallel) */
422     if (opt2bSet("-membed",nfile,fnm))
423     {
424         fprintf(stderr,"Entering membed code");
425         snew(membed,1);
426         init_membed(fplog,membed,nfile,fnm,mtop,inputrec,state,cr,&cpt_period);
427     }
428
429     if (PAR(cr))
430     {
431         /* now broadcast everything to the non-master nodes/threads: */
432         init_parallel(fplog, cr, inputrec, mtop);
433     }
434     if (fplog != NULL)
435     {
436         pr_inputrec(fplog,0,"Input Parameters",inputrec,FALSE);
437     }
438
439     /* now make sure the state is initialized and propagated */
440     set_state_entries(state,inputrec,cr->nnodes);
441
442     /* A parallel command line option consistency check that we can
443        only do after any threads have started. */
444     if (!PAR(cr) &&
445         (ddxyz[XX] > 1 || ddxyz[YY] > 1 || ddxyz[ZZ] > 1 || cr->npmenodes > 0))
446     {
447         gmx_fatal(FARGS,
448                   "The -dd or -npme option request a parallel simulation, "
449 #ifndef GMX_MPI
450                   "but mdrun was compiled without threads or MPI enabled"
451 #else
452 #ifdef GMX_THREADS
453                   "but the number of threads (option -nt) is 1"
454 #else
455                   "but mdrun was not started through mpirun/mpiexec or only one process was requested through mpirun/mpiexec" 
456 #endif
457 #endif
458             );
459     }
460
461     if ((Flags & MD_RERUN) &&
462         (EI_ENERGY_MINIMIZATION(inputrec->eI) || eiNM == inputrec->eI))
463     {
464         gmx_fatal(FARGS, "The .mdp file specified an energy mininization or normal mode algorithm, and these are not compatible with mdrun -rerun");
465     }
466
467     if (can_use_allvsall(inputrec,mtop,TRUE,cr,fplog))
468     {
469         /* All-vs-all loops do not work with domain decomposition */
470         Flags |= MD_PARTDEC;
471     }
472
473     if (!EEL_PME(inputrec->coulombtype) || (Flags & MD_PARTDEC))
474     {
475         cr->npmenodes = 0;
476     }
477
478 #ifdef GMX_FAHCORE
479     fcRegisterSteps(inputrec->nsteps,inputrec->init_step);
480 #endif
481
482     /* NMR restraints must be initialized before load_checkpoint,
483      * since with time averaging the history is added to t_state.
484      * For proper consistency check we therefore need to extend
485      * t_state here.
486      * So the PME-only nodes (if present) will also initialize
487      * the distance restraints.
488      */
489     snew(fcd,1);
490
491     /* This needs to be called before read_checkpoint to extend the state */
492     init_disres(fplog,mtop,inputrec,cr,Flags & MD_PARTDEC,fcd,state);
493
494     if (gmx_mtop_ftype_count(mtop,F_ORIRES) > 0)
495     {
496         if (PAR(cr) && !(Flags & MD_PARTDEC))
497         {
498             gmx_fatal(FARGS,"Orientation restraints do not work (yet) with domain decomposition, use particle decomposition (mdrun option -pd)");
499         }
500         /* Orientation restraints */
501         if (MASTER(cr))
502         {
503             init_orires(fplog,mtop,state->x,inputrec,cr->ms,&(fcd->orires),
504                         state);
505         }
506     }
507
508     if (DEFORM(*inputrec))
509     {
510         /* Store the deform reference box before reading the checkpoint */
511         if (SIMMASTER(cr))
512         {
513             copy_mat(state->box,box);
514         }
515         if (PAR(cr))
516         {
517             gmx_bcast(sizeof(box),box,cr);
518         }
519         /* Because we do not have the update struct available yet
520          * in which the reference values should be stored,
521          * we store them temporarily in static variables.
522          * This should be thread safe, since they are only written once
523          * and with identical values.
524          */
525 #ifdef GMX_THREADS
526         tMPI_Thread_mutex_lock(&deform_init_box_mutex);
527 #endif
528         deform_init_init_step_tpx = inputrec->init_step;
529         copy_mat(box,deform_init_box_tpx);
530 #ifdef GMX_THREADS
531         tMPI_Thread_mutex_unlock(&deform_init_box_mutex);
532 #endif
533     }
534
535     if (opt2bSet("-cpi",nfile,fnm)) 
536     {
537         /* Check if checkpoint file exists before doing continuation.
538          * This way we can use identical input options for the first and subsequent runs...
539          */
540         if( gmx_fexist_master(opt2fn_master("-cpi",nfile,fnm,cr),cr) )
541         {
542             load_checkpoint(opt2fn_master("-cpi",nfile,fnm,cr),&fplog,
543                             cr,Flags & MD_PARTDEC,ddxyz,
544                             inputrec,state,&bReadRNG,&bReadEkin,
545                             (Flags & MD_APPENDFILES));
546             
547             if (bReadRNG)
548             {
549                 Flags |= MD_READ_RNG;
550             }
551             if (bReadEkin)
552             {
553                 Flags |= MD_READ_EKIN;
554             }
555         }
556     }
557
558     if (((MASTER(cr) || (Flags & MD_SEPPOT)) && (Flags & MD_APPENDFILES))
559 #ifdef GMX_THREADS
560         /* With thread MPI only the master node/thread exists in mdrun.c,
561          * therefore non-master nodes need to open the "seppot" log file here.
562          */
563         || (!MASTER(cr) && (Flags & MD_SEPPOT))
564 #endif
565         )
566     {
567         gmx_log_open(ftp2fn(efLOG,nfile,fnm),cr,!(Flags & MD_SEPPOT),
568                              Flags,&fplog);
569     }
570
571     if (SIMMASTER(cr)) 
572     {
573         copy_mat(state->box,box);
574     }
575
576     if (PAR(cr)) 
577     {
578         gmx_bcast(sizeof(box),box,cr);
579     }
580
581     /* Essential dynamics */
582     if (opt2bSet("-ei",nfile,fnm))
583     {
584         /* Open input and output files, allocate space for ED data structure */
585         ed = ed_open(nfile,fnm,Flags,cr);
586     }
587
588     if (bVerbose && SIMMASTER(cr))
589     {
590         fprintf(stderr,"Loaded with Money\n\n");
591     }
592
593     if (PAR(cr) && !((Flags & MD_PARTDEC) ||
594                      EI_TPI(inputrec->eI) ||
595                      inputrec->eI == eiNM))
596     {
597         cr->dd = init_domain_decomposition(fplog,cr,Flags,ddxyz,rdd,rconstr,
598                                            dddlb_opt,dlb_scale,
599                                            ddcsx,ddcsy,ddcsz,
600                                            mtop,inputrec,
601                                            box,state->x,
602                                            &ddbox,&npme_major,&npme_minor);
603
604         make_dd_communicators(fplog,cr,dd_node_order);
605
606         /* Set overallocation to avoid frequent reallocation of arrays */
607         set_over_alloc_dd(TRUE);
608     }
609     else
610     {
611         /* PME, if used, is done on all nodes with 1D decomposition */
612         cr->npmenodes = 0;
613         cr->duty = (DUTY_PP | DUTY_PME);
614         npme_major = 1;
615         npme_minor = 1;
616         if (!EI_TPI(inputrec->eI))
617         {
618             npme_major = cr->nnodes;
619         }
620         
621         if (inputrec->ePBC == epbcSCREW)
622         {
623             gmx_fatal(FARGS,
624                       "pbc=%s is only implemented with domain decomposition",
625                       epbc_names[inputrec->ePBC]);
626         }
627     }
628
629     if (PAR(cr))
630     {
631         /* After possible communicator splitting in make_dd_communicators.
632          * we can set up the intra/inter node communication.
633          */
634         gmx_setup_nodecomm(fplog,cr);
635     }
636
637     wcycle = wallcycle_init(fplog,resetstep,cr);
638     if (PAR(cr))
639     {
640         /* Master synchronizes its value of reset_counters with all nodes 
641          * including PME only nodes */
642         reset_counters = wcycle_get_reset_counters(wcycle);
643         gmx_bcast_sim(sizeof(reset_counters),&reset_counters,cr);
644         wcycle_set_reset_counters(wcycle, reset_counters);
645     }
646
647
648     snew(nrnb,1);
649     if (cr->duty & DUTY_PP)
650     {
651         /* For domain decomposition we allocate dynamically
652          * in dd_partition_system.
653          */
654         if (DOMAINDECOMP(cr))
655         {
656             bcast_state_setup(cr,state);
657         }
658         else
659         {
660             if (PAR(cr))
661             {
662                 if (!MASTER(cr))
663                 {
664                     snew(state,1);
665                 }
666                 bcast_state(cr,state,TRUE);
667             }
668         }
669
670         /* Dihedral Restraints */
671         if (gmx_mtop_ftype_count(mtop,F_DIHRES) > 0)
672         {
673             init_dihres(fplog,mtop,inputrec,fcd);
674         }
675
676         /* Initiate forcerecord */
677         fr = mk_forcerec();
678         init_forcerec(fplog,oenv,fr,fcd,inputrec,mtop,cr,box,FALSE,
679                       opt2fn("-table",nfile,fnm),
680                       opt2fn("-tablep",nfile,fnm),
681                       opt2fn("-tableb",nfile,fnm),FALSE,pforce);
682
683         /* version for PCA_NOT_READ_NODE (see md.c) */
684         /*init_forcerec(fplog,fr,fcd,inputrec,mtop,cr,box,FALSE,
685           "nofile","nofile","nofile",FALSE,pforce);
686           */        
687         fr->bSepDVDL = ((Flags & MD_SEPPOT) == MD_SEPPOT);
688
689         /* Initialize QM-MM */
690         if(fr->bQMMM)
691         {
692             init_QMMMrec(cr,box,mtop,inputrec,fr);
693         }
694
695         /* Initialize the mdatoms structure.
696          * mdatoms is not filled with atom data,
697          * as this can not be done now with domain decomposition.
698          */
699         mdatoms = init_mdatoms(fplog,mtop,inputrec->efep!=efepNO);
700
701         /* Initialize the virtual site communication */
702         vsite = init_vsite(mtop,cr);
703
704         calc_shifts(box,fr->shift_vec);
705
706         /* With periodic molecules the charge groups should be whole at start up
707          * and the virtual sites should not be far from their proper positions.
708          */
709         if (!inputrec->bContinuation && MASTER(cr) &&
710             !(inputrec->ePBC != epbcNONE && inputrec->bPeriodicMols))
711         {
712             /* Make molecules whole at start of run */
713             if (fr->ePBC != epbcNONE)
714             {
715                 do_pbc_first_mtop(fplog,inputrec->ePBC,box,mtop,state->x);
716             }
717             if (vsite)
718             {
719                 /* Correct initial vsite positions are required
720                  * for the initial distribution in the domain decomposition
721                  * and for the initial shell prediction.
722                  */
723                 construct_vsites_mtop(fplog,vsite,mtop,state->x);
724             }
725         }
726
727         /* Initiate PPPM if necessary */
728         if (fr->eeltype == eelPPPM)
729         {
730             if (mdatoms->nChargePerturbed)
731             {
732                 gmx_fatal(FARGS,"Free energy with %s is not implemented",
733                           eel_names[fr->eeltype]);
734             }
735             status = gmx_pppm_init(fplog,cr,oenv,FALSE,TRUE,box,
736                                    getenv("GMXGHAT"),inputrec, (Flags & MD_REPRODUCIBLE));
737             if (status != 0)
738             {
739                 gmx_fatal(FARGS,"Error %d initializing PPPM",status);
740             }
741         }
742
743         if (EEL_PME(fr->eeltype))
744         {
745             ewaldcoeff = fr->ewaldcoeff;
746             pmedata = &fr->pmedata;
747         }
748         else
749         {
750             pmedata = NULL;
751         }
752     }
753     else
754     {
755         /* This is a PME only node */
756
757         /* We don't need the state */
758         done_state(state);
759
760         ewaldcoeff = calc_ewaldcoeff(inputrec->rcoulomb, inputrec->ewald_rtol);
761         snew(pmedata,1);
762     }
763
764     /* Initiate PME if necessary,
765      * either on all nodes or on dedicated PME nodes only. */
766     if (EEL_PME(inputrec->coulombtype))
767     {
768         if (mdatoms)
769         {
770             nChargePerturbed = mdatoms->nChargePerturbed;
771         }
772         if (cr->npmenodes > 0)
773         {
774             /* The PME only nodes need to know nChargePerturbed */
775             gmx_bcast_sim(sizeof(nChargePerturbed),&nChargePerturbed,cr);
776         }
777         if (cr->duty & DUTY_PME)
778         {
779             status = gmx_pme_init(pmedata,cr,npme_major,npme_minor,inputrec,
780                                   mtop ? mtop->natoms : 0,nChargePerturbed,
781                                   (Flags & MD_REPRODUCIBLE));
782             if (status != 0) 
783             {
784                 gmx_fatal(FARGS,"Error %d initializing PME",status);
785             }
786         }
787     }
788
789
790     if (integrator[inputrec->eI].func == do_md
791 #ifdef GMX_OPENMM
792         ||
793         integrator[inputrec->eI].func == do_md_openmm
794 #endif
795         )
796     {
797         /* Turn on signal handling on all nodes */
798         /*
799          * (A user signal from the PME nodes (if any)
800          * is communicated to the PP nodes.
801          */
802         signal_handler_install();
803     }
804
805     if (cr->duty & DUTY_PP)
806     {
807         if (inputrec->ePull != epullNO)
808         {
809             /* Initialize pull code */
810             init_pull(fplog,inputrec,nfile,fnm,mtop,cr,oenv,
811                       EI_DYNAMICS(inputrec->eI) && MASTER(cr),Flags);
812         }
813
814         constr = init_constraints(fplog,mtop,inputrec,ed,state,cr);
815
816         if (DOMAINDECOMP(cr))
817         {
818             dd_init_bondeds(fplog,cr->dd,mtop,vsite,constr,inputrec,
819                             Flags & MD_DDBONDCHECK,fr->cginfo_mb);
820
821             set_dd_parameters(fplog,cr->dd,dlb_scale,inputrec,fr,&ddbox);
822
823             setup_dd_grid(fplog,cr->dd);
824         }
825
826         /* Now do whatever the user wants us to do (how flexible...) */
827         integrator[inputrec->eI].func(fplog,cr,nfile,fnm,
828                                       oenv,bVerbose,bCompact,
829                                       nstglobalcomm,
830                                       vsite,constr,
831                                       nstepout,inputrec,mtop,
832                                       fcd,state,
833                                       mdatoms,nrnb,wcycle,ed,fr,
834                                       repl_ex_nst,repl_ex_seed,
835                                       membed,
836                                       cpt_period,max_hours,
837                                       deviceOptions,
838                                       Flags,
839                                       &runtime);
840
841         if (inputrec->ePull != epullNO)
842         {
843             finish_pull(fplog,inputrec->pull);
844         }
845     } 
846     else 
847     {
848         /* do PME only */
849         gmx_pmeonly(*pmedata,cr,nrnb,wcycle,ewaldcoeff,FALSE,inputrec);
850     }
851
852     if (EI_DYNAMICS(inputrec->eI) || EI_TPI(inputrec->eI))
853     {
854         /* Some timing stats */  
855         if (SIMMASTER(cr))
856         {
857             if (runtime.proc == 0)
858             {
859                 runtime.proc = runtime.real;
860             }
861         }
862         else
863         {
864             runtime.real = 0;
865         }
866     }
867
868     wallcycle_stop(wcycle,ewcRUN);
869
870     /* Finish up, write some stuff
871      * if rerunMD, don't write last frame again 
872      */
873     finish_run(fplog,cr,ftp2fn(efSTO,nfile,fnm),
874                inputrec,nrnb,wcycle,&runtime,
875                EI_DYNAMICS(inputrec->eI) && !MULTISIM(cr));
876     
877     if (opt2bSet("-membed",nfile,fnm))
878     {
879         sfree(membed);
880     }
881
882     /* Does what it says */  
883     print_date_and_time(fplog,cr->nodeid,"Finished mdrun",&runtime);
884
885     /* Close logfile already here if we were appending to it */
886     if (MASTER(cr) && (Flags & MD_APPENDFILES))
887     {
888         gmx_log_close(fplog);
889     }   
890
891     rc=(int)gmx_get_stop_condition();
892
893 #ifdef GMX_THREADS
894     /* we need to join all threads. The sub-threads join when they
895        exit this function, but the master thread needs to be told to 
896        wait for that. */
897     if (PAR(cr) && MASTER(cr))
898     {
899         tMPI_Finalize();
900     }
901 #endif
902
903     return rc;
904 }
905
906 void md_print_warning(const t_commrec *cr,FILE *fplog,const char *buf)
907 {
908     if (MASTER(cr))
909     {
910         fprintf(stderr,"\n%s\n",buf);
911     }
912     if (fplog)
913     {
914         fprintf(fplog,"\n%s\n",buf);
915     }
916 }