Redefine the default boolean type to gmx_bool.
[alexxy/gromacs.git] / src / gmxlib / main.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  * GROningen Mixture of Alchemy and Childrens' Stories
35  */
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <string.h>
43 #include <limits.h>
44 #include <time.h>
45
46 #ifdef HAVE_SYS_TIME_H
47 #include <sys/time.h>
48 #endif
49
50
51 #include "smalloc.h"
52 #include "gmx_fatal.h"
53 #include "network.h"
54 #include "main.h"
55 #include "macros.h"
56 #include "futil.h"
57 #include "filenm.h"
58 #include "mdrun.h"
59 #include "gmxfio.h"
60 #include "string2.h"
61
62 #ifdef GMX_THREADS
63 #include "thread_mpi.h"
64 #endif
65
66 /* The source code in this file should be thread-safe. 
67          Please keep it that way. */
68
69
70 #ifdef HAVE_UNISTD_H
71 #include <unistd.h>
72 #endif
73
74 #if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
75 #include <process.h>
76 #endif
77
78
79 /* Portable version of ctime_r implemented in src/gmxlib/string2.c, but we do not want it declared in public installed headers */
80 char *
81 gmx_ctime_r(const time_t *clock,char *buf, int n);
82
83
84 #define BUFSIZE 1024
85
86 /* this is not strictly thread-safe, but it's only written to at the beginning
87    of the simulation, once by each thread with the same value. We assume
88    that writing to an int is atomic.*/
89 static gmx_bool parallel_env_val;
90 #ifdef GMX_THREADS
91 tMPI_Thread_mutex_t parallel_env_mutex=TMPI_THREAD_MUTEX_INITIALIZER;
92 #endif
93
94
95 /* returns 1 when running in a parallel environment, so could also be 1 if
96    mdrun was started with: mpirun -np 1.
97      
98    Use this function only to check whether a parallel environment has   
99    been initialized, for example when checking whether gmx_finalize()   
100    needs to be called. Use PAR(cr) to check whether the simulation actually
101    has more than one node/thread.  */
102 gmx_bool gmx_parallel_env_initialized(void)
103 {
104     gmx_bool ret;
105 #ifdef GMX_THREADS
106     tMPI_Thread_mutex_lock(&parallel_env_mutex);
107 #endif
108     ret=parallel_env_val;
109 #ifdef GMX_THREADS
110     tMPI_Thread_mutex_unlock(&parallel_env_mutex);
111 #endif
112     return ret;
113 }
114
115 static void set_parallel_env(gmx_bool val)
116 {
117 #ifdef GMX_THREADS
118     tMPI_Thread_mutex_lock(&parallel_env_mutex);
119 #endif
120     if (!parallel_env_val)
121     {
122         /* we only allow it to be set, not unset */
123         parallel_env_val=val;
124     }
125 #ifdef GMX_THREADS
126     tMPI_Thread_mutex_unlock(&parallel_env_mutex);
127 #endif
128 }
129
130
131 static void par_fn(char *base,int ftp,const t_commrec *cr,
132                    gmx_bool bAppendSimId,gmx_bool bAppendNodeId,
133                    char buf[],int bufsize)
134 {
135   int n;
136   
137   if((size_t)bufsize<(strlen(base)+10))
138      gmx_mem("Character buffer too small!");
139
140   /* Copy to buf, and strip extension */
141   strcpy(buf,base);
142   buf[strlen(base) - strlen(ftp2ext(fn2ftp(base))) - 1] = '\0';
143
144   if (bAppendSimId) {
145     sprintf(buf+strlen(buf),"%d",cr->ms->sim);
146   }
147   if (bAppendNodeId) {
148     strcat(buf,"_node");
149     sprintf(buf+strlen(buf),"%d",cr->nodeid);
150   }
151   strcat(buf,".");
152   
153   /* Add extension again */
154   strcat(buf,(ftp == efTPX) ? "tpr" : (ftp == efEDR) ? "edr" : ftp2ext(ftp));
155   if (cr->nodeid == 0) {
156     printf("node %d par_fn '%s'\n",cr->nodeid,buf);
157     if (fn2ftp(buf) == efLOG) {
158       printf("log\n");
159     }
160   }
161 }
162
163 void check_multi_int(FILE *log,const gmx_multisim_t *ms,int val,
164                      const char *name)
165 {
166   int  *ibuf,p;
167   gmx_bool bCompatible;
168
169   fprintf(log,"Multi-checking %s ... ",name);
170   
171   if (ms == NULL)
172     gmx_fatal(FARGS,
173               "check_multi_int called with a NULL communication pointer");
174
175   snew(ibuf,ms->nsim);
176   ibuf[ms->sim] = val;
177   gmx_sumi_sim(ms->nsim,ibuf,ms);
178   
179   bCompatible = TRUE;
180   for(p=1; p<ms->nsim; p++)
181     bCompatible = bCompatible && (ibuf[p-1] == ibuf[p]);
182   
183   if (bCompatible) 
184     fprintf(log,"OK\n");
185   else {
186     fprintf(log,"\n%s is not equal for all subsystems\n",name);
187     for(p=0; p<ms->nsim; p++)
188       fprintf(log,"  subsystem %d: %d\n",p,ibuf[p]);
189     gmx_fatal(FARGS,"The %d subsystems are not compatible\n",ms->nsim);
190   }
191   
192   sfree(ibuf);
193 }
194
195 void gmx_log_open(const char *lognm,const t_commrec *cr,gmx_bool bMasterOnly, 
196                    unsigned long Flags, FILE** fplog)
197 {
198     int  len,testlen,pid;
199     char buf[256],host[256];
200     time_t t;
201     char timebuf[STRLEN];
202     FILE *fp=*fplog;
203     char *tmpnm;
204
205     gmx_bool bAppend = Flags & MD_APPENDFILES;  
206   
207     debug_gmx();
208   
209     /* Communicate the filename for logfile */
210     if (cr->nnodes > 1 && !bMasterOnly
211 #ifdef GMX_THREADS
212         /* With thread MPI the non-master log files are opened later
213          * when the files names are already known on all nodes.
214          */
215         && FALSE
216 #endif
217         )
218     {
219         if (MASTER(cr))
220         {
221             len = strlen(lognm) + 1;
222         }
223         gmx_bcast(sizeof(len),&len,cr);
224         if (!MASTER(cr))
225         {
226             snew(tmpnm,len+8);
227         }
228         else
229         {
230             tmpnm=strdup(lognm);
231         }
232         gmx_bcast(len*sizeof(*tmpnm),tmpnm,cr);
233     }
234     else
235     {
236         tmpnm=strdup(lognm);
237     }
238   
239     debug_gmx();
240
241     if (!bMasterOnly)
242     {
243         /* Since log always ends with '.log' let's use this info */
244         par_fn(tmpnm,efLOG,cr,FALSE,!bMasterOnly,buf,255);
245         fp = gmx_fio_fopen(buf, bAppend ? "a+" : "w+" );
246     }
247     else
248     {
249         fp = gmx_fio_fopen(tmpnm, bAppend ? "a+" : "w+" );
250     }
251
252     sfree(tmpnm);
253
254     gmx_fatal_set_log_file(fp);
255   
256     /* Get some machine parameters */
257 #ifdef HAVE_UNISTD_H
258     if (gethostname(host,255) != 0)
259     {
260         sprintf(host,"unknown");
261     }
262 #else
263     sprintf(host,"unknown");
264 #endif  
265
266     time(&t);
267
268 #ifndef NO_GETPID
269 #   if ((defined WIN32 || defined _WIN32 || defined WIN64 || defined _WIN64) && !defined __CYGWIN__ && !defined __CYGWIN32__)
270     pid = _getpid();
271 #   else
272     pid = getpid();
273 #   endif
274 #else
275         pid = 0;
276 #endif
277
278     if (bAppend)
279     {
280         fprintf(fp,
281                 "\n"
282                 "\n"
283                 "-----------------------------------------------------------\n"
284                 "Restarting from checkpoint, appending to previous log file.\n"
285                 "\n"
286             );
287     }
288         
289     gmx_ctime_r(&t,timebuf,STRLEN);
290
291     fprintf(fp,
292             "Log file opened on %s"
293             "Host: %s  pid: %d  nodeid: %d  nnodes:  %d\n",
294             timebuf,host,pid,cr->nodeid,cr->nnodes);
295
296 #if (defined BUILD_MACHINE && defined BUILD_TIME && defined BUILD_USER) 
297     fprintf(fp,
298             "The Gromacs distribution was built %s by\n"
299             "%s (%s)\n\n\n",BUILD_TIME,BUILD_USER,BUILD_MACHINE);
300 #endif
301
302     fflush(fp);
303     debug_gmx();
304
305     *fplog = fp;
306 }
307
308 void gmx_log_close(FILE *fp)
309 {
310   if (fp) {
311     gmx_fatal_set_log_file(NULL);
312     gmx_fio_fclose(fp);
313   }
314 }
315
316 static void comm_args(const t_commrec *cr,int *argc,char ***argv)
317 {
318   int i,len;
319   
320   if ((cr) && PAR(cr))
321     gmx_bcast(sizeof(*argc),argc,cr);
322   
323   if (!MASTER(cr))
324     snew(*argv,*argc+1);
325   fprintf(stderr,"NODEID=%d argc=%d\n",cr->nodeid,*argc);
326   for(i=0; (i<*argc); i++) {
327     if (MASTER(cr))
328       len = strlen((*argv)[i])+1;
329     gmx_bcast(sizeof(len),&len,cr);
330     if (!MASTER(cr))
331       snew((*argv)[i],len);
332     /*gmx_bcast(len*sizeof((*argv)[i][0]),(*argv)[i],cr);*/
333     gmx_bcast(len*sizeof(char),(*argv)[i],cr);
334   }
335   debug_gmx();
336 }
337
338 void init_multisystem(t_commrec *cr,int nsim, int nfile,
339                       const t_filenm fnm[],gmx_bool bParFn)
340 {
341     gmx_multisim_t *ms;
342     int  nnodes,nnodpersim,sim,i,ftp;
343     char buf[256];
344 #ifdef GMX_MPI
345     MPI_Group mpi_group_world;
346 #endif  
347     int *rank;
348
349 #ifndef GMX_MPI
350     if (nsim > 1)
351     {
352         gmx_fatal(FARGS,"This binary is compiled without MPI support, can not do multiple simulations.");
353     }
354 #endif
355
356     nnodes  = cr->nnodes;
357     if (nnodes % nsim != 0)
358     {
359         gmx_fatal(FARGS,"The number of nodes (%d) is not a multiple of the number of simulations (%d)",nnodes,nsim);
360     }
361
362     nnodpersim = nnodes/nsim;
363     sim = cr->nodeid/nnodpersim;
364
365     if (debug)
366     {
367         fprintf(debug,"We have %d simulations, %d nodes per simulation, local simulation is %d\n",nsim,nnodpersim,sim);
368     }
369
370     snew(ms,1);
371     cr->ms = ms;
372     ms->nsim = nsim;
373     ms->sim  = sim;
374 #ifdef GMX_MPI
375     /* Create a communicator for the master nodes */
376     snew(rank,ms->nsim);
377     for(i=0; i<ms->nsim; i++)
378     {
379         rank[i] = i*nnodpersim;
380     }
381     MPI_Comm_group(MPI_COMM_WORLD,&mpi_group_world);
382     MPI_Group_incl(mpi_group_world,nsim,rank,&ms->mpi_group_masters);
383     sfree(rank);
384     MPI_Comm_create(MPI_COMM_WORLD,ms->mpi_group_masters,
385                     &ms->mpi_comm_masters);
386
387 #if !defined(GMX_THREADS) && !defined(MPI_IN_PLACE_EXISTS)
388     /* initialize the MPI_IN_PLACE replacement buffers */
389     snew(ms->mpb, 1);
390     ms->mpb->ibuf=NULL;
391     ms->mpb->fbuf=NULL;
392     ms->mpb->dbuf=NULL;
393     ms->mpb->ibuf_alloc=0;
394     ms->mpb->fbuf_alloc=0;
395     ms->mpb->dbuf_alloc=0;
396 #endif
397
398 #endif
399
400     /* Reduce the intra-simulation communication */
401     cr->sim_nodeid = cr->nodeid % nnodpersim;
402     cr->nnodes = nnodpersim;
403 #ifdef GMX_MPI
404     MPI_Comm_split(MPI_COMM_WORLD,sim,cr->sim_nodeid,&cr->mpi_comm_mysim);
405     cr->mpi_comm_mygroup = cr->mpi_comm_mysim;
406     cr->nodeid = cr->sim_nodeid;
407 #endif
408
409     if (debug)
410     {
411         fprintf(debug,"This is simulation %d",cr->ms->sim);
412         if (PAR(cr))
413         {
414             fprintf(debug,", local number of nodes %d, local nodeid %d",
415                     cr->nnodes,cr->sim_nodeid);
416         }
417         fprintf(debug,"\n\n");
418     }
419
420     if (bParFn)
421     {
422         /* Patch output and tpx, cpt and rerun input file names */
423         for(i=0; (i<nfile); i++)
424         {
425             /* Because of possible multiple extensions per type we must look 
426              * at the actual file name 
427              */
428             if (is_output(&fnm[i]) ||
429                 fnm[i].ftp == efTPX || fnm[i].ftp == efCPT ||
430                 strcmp(fnm[i].opt,"-rerun") == 0)
431             {
432                 ftp = fn2ftp(fnm[i].fns[0]);
433                 par_fn(fnm[i].fns[0],ftp,cr,TRUE,FALSE,buf,255);
434                 sfree(fnm[i].fns[0]);
435                 fnm[i].fns[0] = strdup(buf);
436             }
437         }
438     }
439 }
440
441 t_commrec *init_par(int *argc,char ***argv_ptr)
442 {
443     t_commrec *cr;
444     char      **argv;
445     int       i;
446     gmx_bool      pe=FALSE;
447
448     snew(cr,1);
449
450     argv = *argv_ptr;
451
452 #ifdef GMX_MPI
453 #ifdef GMX_LIB_MPI
454     pe = TRUE;
455 #ifdef GMX_CHECK_MPI_ENV
456     /* Do not use MPI calls when env.var. GMX_CHECK_MPI_ENV is not set */
457     if (getenv(GMX_CHECK_MPI_ENV) == NULL)
458         pe = FALSE;
459 #endif /* GMX_CHECK_MPI_ENV */
460 #endif /* GMX_LIB_MPI  */
461     set_parallel_env(pe);
462     if (pe) {
463         cr->sim_nodeid = gmx_setup(argc,argv,&cr->nnodes);
464     } else {
465         cr->nnodes     = 1;
466         cr->sim_nodeid = 0;
467     }
468 #else /* GMX_MPI */
469     pe=FALSE;
470     set_parallel_env(pe);
471     cr->sim_nodeid   = 0;
472     cr->nnodes       = 1;
473 #endif /* GMX_MPI */
474
475     if (!PAR(cr) && (cr->sim_nodeid != 0))
476         gmx_comm("(!PAR(cr) && (cr->sim_nodeid != 0))");
477
478     if (PAR(cr)) 
479     {
480 #ifdef GMX_MPI
481         cr->mpi_comm_mysim = MPI_COMM_WORLD;
482         cr->mpi_comm_mygroup = cr->mpi_comm_mysim;
483 #endif /* GMX_MPI */
484     }
485     cr->nodeid = cr->sim_nodeid;
486
487     cr->duty = (DUTY_PP | DUTY_PME);
488
489     /* Communicate arguments if parallel */
490 #ifndef GMX_THREADS
491     if (PAR(cr))
492         comm_args(cr,argc,argv_ptr);
493 #endif /* GMX_THREADS */
494
495 #ifdef GMX_MPI
496 #if !defined(GMX_THREADS) && !defined(MPI_IN_PLACE_EXISTS)
497   /* initialize the MPI_IN_PLACE replacement buffers */
498   snew(cr->mpb, 1);
499   cr->mpb->ibuf=NULL;
500   cr->mpb->fbuf=NULL;
501   cr->mpb->dbuf=NULL;
502   cr->mpb->ibuf_alloc=0;
503   cr->mpb->fbuf_alloc=0;
504   cr->mpb->dbuf_alloc=0;
505 #endif
506 #endif
507
508     return cr;
509 }
510
511 t_commrec *init_par_threads(const t_commrec *cro)
512 {
513 #ifdef GMX_THREADS
514     int initialized;
515     t_commrec *cr;
516
517     /* make a thread-specific commrec */
518     snew(cr,1);
519     /* now copy the whole thing, so settings like the number of PME nodes
520        get propagated. */
521     *cr=*cro;
522
523     /* and we start setting our own thread-specific values for things */
524     MPI_Initialized(&initialized);
525     if (!initialized)
526         gmx_comm("Initializing threads without comm");
527     set_parallel_env(TRUE);
528     /* once threads will be used together with MPI, we'll
529        fill the cr structure with distinct data here. This might even work: */
530     cr->sim_nodeid = gmx_setup(0,NULL, &cr->nnodes);
531
532     cr->mpi_comm_mysim = MPI_COMM_WORLD;
533     cr->mpi_comm_mygroup = cr->mpi_comm_mysim;
534     cr->nodeid = cr->sim_nodeid;
535     cr->duty = (DUTY_PP | DUTY_PME);
536
537     return cr;
538 #else
539     return NULL;
540 #endif
541 }
542
543
544 t_commrec *init_cr_nopar(void)
545 {
546     t_commrec *cr;
547
548     snew(cr,1);
549
550     cr->nnodes     = 1; 
551     /* cr->nthreads   = 1; */
552     cr->sim_nodeid = 0;
553     cr->nodeid     = 0;
554     /* cr->threadid   = 0; */
555     cr->duty       = (DUTY_PP | DUTY_PME);
556
557     return cr;
558 }