Move smalloc.h to utility/
[alexxy/gromacs.git] / src / gromacs / gmxlib / main.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
5  * Copyright (c) 2001-2004, The GROMACS development team.
6  * Copyright (c) 2013,2014, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 #ifdef HAVE_CONFIG_H
38 #include <config.h>
39 #endif
40
41 #include <stdio.h>
42 #include <stdlib.h>
43 #include <string.h>
44 #include <limits.h>
45 #include <time.h>
46
47 #ifdef HAVE_SYS_TIME_H
48 #include <sys/time.h>
49 #endif
50
51 #include "gromacs/utility/smalloc.h"
52 #include "types/commrec.h"
53 #include "gmx_fatal.h"
54 #include "network.h"
55 #include "main.h"
56 #include "macros.h"
57 #include "gromacs/fileio/futil.h"
58 #include "gromacs/fileio/filenm.h"
59 #include "gromacs/fileio/gmxfio.h"
60 #include "string2.h"
61 #include "copyrite.h"
62
63 #include "gromacs/utility/exceptions.h"
64 #include "gromacs/utility/gmxmpi.h"
65 #include "gromacs/utility/programcontext.h"
66
67 /* The source code in this file should be thread-safe.
68          Please keep it that way. */
69
70
71 #ifdef HAVE_UNISTD_H
72 #include <unistd.h>
73 #endif
74
75 #ifdef GMX_NATIVE_WINDOWS
76 #include <process.h>
77 #endif
78
79 #define BUFSIZE 1024
80
81
82 static void par_fn(char *base, int ftp, const t_commrec *cr,
83                    gmx_bool bAppendSimId, gmx_bool bAppendNodeId,
84                    char buf[], int bufsize)
85 {
86     if ((size_t)bufsize < (strlen(base)+10))
87     {
88         gmx_mem("Character buffer too small!");
89     }
90
91     /* Copy to buf, and strip extension */
92     strcpy(buf, base);
93     buf[strlen(base) - strlen(ftp2ext(fn2ftp(base))) - 1] = '\0';
94
95     if (bAppendSimId)
96     {
97         sprintf(buf+strlen(buf), "%d", cr->ms->sim);
98     }
99     if (bAppendNodeId)
100     {
101         strcat(buf, "_node");
102         sprintf(buf+strlen(buf), "%d", cr->nodeid);
103     }
104     strcat(buf, ".");
105
106     /* Add extension again */
107     strcat(buf, (ftp == efTPX) ? "tpr" : (ftp == efEDR) ? "edr" : ftp2ext(ftp));
108     if (debug)
109     {
110         fprintf(debug, "node %d par_fn '%s'\n", cr->nodeid, buf);
111         if (fn2ftp(buf) == efLOG)
112         {
113             fprintf(debug, "log\n");
114         }
115     }
116 }
117
118 void check_multi_int(FILE *log, const gmx_multisim_t *ms, int val,
119                      const char *name,
120                      gmx_bool bQuiet)
121 {
122     int     *ibuf, p;
123     gmx_bool bCompatible;
124
125     if (NULL != log && !bQuiet)
126     {
127         fprintf(log, "Multi-checking %s ... ", name);
128     }
129
130     if (ms == NULL)
131     {
132         gmx_fatal(FARGS,
133                   "check_multi_int called with a NULL communication pointer");
134     }
135
136     snew(ibuf, ms->nsim);
137     ibuf[ms->sim] = val;
138     gmx_sumi_sim(ms->nsim, ibuf, ms);
139
140     bCompatible = TRUE;
141     for (p = 1; p < ms->nsim; p++)
142     {
143         bCompatible = bCompatible && (ibuf[p-1] == ibuf[p]);
144     }
145
146     if (bCompatible)
147     {
148         if (NULL != log && !bQuiet)
149         {
150             fprintf(log, "OK\n");
151         }
152     }
153     else
154     {
155         if (NULL != log)
156         {
157             fprintf(log, "\n%s is not equal for all subsystems\n", name);
158             for (p = 0; p < ms->nsim; p++)
159             {
160                 fprintf(log, "  subsystem %d: %d\n", p, ibuf[p]);
161             }
162         }
163         gmx_fatal(FARGS, "The %d subsystems are not compatible\n", ms->nsim);
164     }
165
166     sfree(ibuf);
167 }
168
169 void check_multi_int64(FILE *log, const gmx_multisim_t *ms,
170                        gmx_int64_t val, const char *name,
171                        gmx_bool bQuiet)
172 {
173     gmx_int64_t      *ibuf;
174     int               p;
175     gmx_bool          bCompatible;
176
177     if (NULL != log && !bQuiet)
178     {
179         fprintf(log, "Multi-checking %s ... ", name);
180     }
181
182     if (ms == NULL)
183     {
184         gmx_fatal(FARGS,
185                   "check_multi_int called with a NULL communication pointer");
186     }
187
188     snew(ibuf, ms->nsim);
189     ibuf[ms->sim] = val;
190     gmx_sumli_sim(ms->nsim, ibuf, ms);
191
192     bCompatible = TRUE;
193     for (p = 1; p < ms->nsim; p++)
194     {
195         bCompatible = bCompatible && (ibuf[p-1] == ibuf[p]);
196     }
197
198     if (bCompatible)
199     {
200         if (NULL != log && !bQuiet)
201         {
202             fprintf(log, "OK\n");
203         }
204     }
205     else
206     {
207         if (NULL != log)
208         {
209             fprintf(log, "\n%s is not equal for all subsystems\n", name);
210             for (p = 0; p < ms->nsim; p++)
211             {
212                 char strbuf[255];
213                 /* first make the format string */
214                 snprintf(strbuf, 255, "  subsystem %%d: %s\n",
215                          "%" GMX_PRId64);
216                 fprintf(log, strbuf, p, ibuf[p]);
217             }
218         }
219         gmx_fatal(FARGS, "The %d subsystems are not compatible\n", ms->nsim);
220     }
221
222     sfree(ibuf);
223 }
224
225
226 int gmx_gethostname(char *name, size_t len)
227 {
228     if (len < 8)
229     {
230         gmx_incons("gmx_gethostname called with len<8");
231     }
232 #if defined(HAVE_UNISTD_H) && !defined(__native_client__)
233     if (gethostname(name, len-1) != 0)
234     {
235         strncpy(name, "unknown", 8);
236         return -1;
237     }
238     return 0;
239 #else
240     strncpy(name, "unknown", 8);
241     return -1;
242 #endif
243 }
244
245
246 void gmx_log_open(const char *lognm, const t_commrec *cr, gmx_bool bMasterOnly,
247                   gmx_bool bAppendFiles, FILE** fplog)
248 {
249     int    len, pid;
250     char   buf[256], host[256];
251     time_t t;
252     char   timebuf[STRLEN];
253     FILE  *fp = *fplog;
254     char  *tmpnm;
255
256     debug_gmx();
257
258     /* Communicate the filename for logfile */
259     if (cr->nnodes > 1 && !bMasterOnly
260 #ifdef GMX_THREAD_MPI
261         /* With thread MPI the non-master log files are opened later
262          * when the files names are already known on all nodes.
263          */
264         && FALSE
265 #endif
266         )
267     {
268         if (MASTER(cr))
269         {
270             len = strlen(lognm) + 1;
271         }
272         gmx_bcast(sizeof(len), &len, cr);
273         if (!MASTER(cr))
274         {
275             snew(tmpnm, len+8);
276         }
277         else
278         {
279             tmpnm = gmx_strdup(lognm);
280         }
281         gmx_bcast(len*sizeof(*tmpnm), tmpnm, cr);
282     }
283     else
284     {
285         tmpnm = gmx_strdup(lognm);
286     }
287
288     debug_gmx();
289
290     if (!bMasterOnly && !MASTER(cr))
291     {
292         /* Since log always ends with '.log' let's use this info */
293         par_fn(tmpnm, efLOG, cr, FALSE, !bMasterOnly, buf, 255);
294         fp = gmx_fio_fopen(buf, bAppendFiles ? "a+" : "w+" );
295     }
296     else if (!bAppendFiles)
297     {
298         fp = gmx_fio_fopen(tmpnm, bAppendFiles ? "a+" : "w+" );
299     }
300
301     sfree(tmpnm);
302
303     gmx_fatal_set_log_file(fp);
304
305     /* Get some machine parameters */
306     gmx_gethostname(host, 256);
307
308     time(&t);
309
310 #ifndef NO_GETPID
311 #   ifdef GMX_NATIVE_WINDOWS
312     pid = _getpid();
313 #   else
314     pid = getpid();
315 #   endif
316 #else
317     pid = 0;
318 #endif
319
320     if (bAppendFiles)
321     {
322         fprintf(fp,
323                 "\n"
324                 "\n"
325                 "-----------------------------------------------------------\n"
326                 "Restarting from checkpoint, appending to previous log file.\n"
327                 "\n"
328                 );
329     }
330
331     gmx_ctime_r(&t, timebuf, STRLEN);
332
333     fprintf(fp,
334             "Log file opened on %s"
335             "Host: %s  pid: %d  nodeid: %d  nnodes:  %d\n",
336             timebuf, host, pid, cr->nodeid, cr->nnodes);
337     try
338     {
339         gmx::BinaryInformationSettings settings;
340         settings.extendedInfo(true);
341         settings.copyright(!bAppendFiles);
342         gmx::printBinaryInformation(fp, gmx::getProgramContext(), settings);
343     }
344     GMX_CATCH_ALL_AND_EXIT_WITH_FATAL_ERROR;
345     fprintf(fp, "\n\n");
346
347     fflush(fp);
348     debug_gmx();
349
350     *fplog = fp;
351 }
352
353 void gmx_log_close(FILE *fp)
354 {
355     if (fp)
356     {
357         gmx_fatal_set_log_file(NULL);
358         gmx_fio_fclose(fp);
359     }
360 }
361
362 void init_multisystem(t_commrec *cr, int nsim, char **multidirs,
363                       int nfile, const t_filenm fnm[], gmx_bool bParFn)
364 {
365     gmx_multisim_t *ms;
366     int             nnodes, nnodpersim, sim, i, ftp;
367     char            buf[256];
368 #ifdef GMX_MPI
369     MPI_Group       mpi_group_world;
370     int            *rank;
371 #endif
372
373 #ifndef GMX_MPI
374     if (nsim > 1)
375     {
376         gmx_fatal(FARGS, "This binary is compiled without MPI support, can not do multiple simulations.");
377     }
378 #endif
379
380     nnodes  = cr->nnodes;
381     if (nnodes % nsim != 0)
382     {
383         gmx_fatal(FARGS, "The number of nodes (%d) is not a multiple of the number of simulations (%d)", nnodes, nsim);
384     }
385
386     nnodpersim = nnodes/nsim;
387     sim        = cr->nodeid/nnodpersim;
388
389     if (debug)
390     {
391         fprintf(debug, "We have %d simulations, %d nodes per simulation, local simulation is %d\n", nsim, nnodpersim, sim);
392     }
393
394     snew(ms, 1);
395     cr->ms   = ms;
396     ms->nsim = nsim;
397     ms->sim  = sim;
398 #ifdef GMX_MPI
399     /* Create a communicator for the master nodes */
400     snew(rank, ms->nsim);
401     for (i = 0; i < ms->nsim; i++)
402     {
403         rank[i] = i*nnodpersim;
404     }
405     MPI_Comm_group(MPI_COMM_WORLD, &mpi_group_world);
406     MPI_Group_incl(mpi_group_world, nsim, rank, &ms->mpi_group_masters);
407     sfree(rank);
408     MPI_Comm_create(MPI_COMM_WORLD, ms->mpi_group_masters,
409                     &ms->mpi_comm_masters);
410
411 #if !defined(MPI_IN_PLACE_EXISTS)
412     /* initialize the MPI_IN_PLACE replacement buffers */
413     snew(ms->mpb, 1);
414     ms->mpb->ibuf        = NULL;
415     ms->mpb->libuf       = NULL;
416     ms->mpb->fbuf        = NULL;
417     ms->mpb->dbuf        = NULL;
418     ms->mpb->ibuf_alloc  = 0;
419     ms->mpb->libuf_alloc = 0;
420     ms->mpb->fbuf_alloc  = 0;
421     ms->mpb->dbuf_alloc  = 0;
422 #endif
423
424 #endif
425
426     /* Reduce the intra-simulation communication */
427     cr->sim_nodeid = cr->nodeid % nnodpersim;
428     cr->nnodes     = nnodpersim;
429 #ifdef GMX_MPI
430     MPI_Comm_split(MPI_COMM_WORLD, sim, cr->sim_nodeid, &cr->mpi_comm_mysim);
431     cr->mpi_comm_mygroup = cr->mpi_comm_mysim;
432     cr->nodeid           = cr->sim_nodeid;
433 #endif
434
435     if (debug)
436     {
437         fprintf(debug, "This is simulation %d", cr->ms->sim);
438         if (PAR(cr))
439         {
440             fprintf(debug, ", local number of nodes %d, local nodeid %d",
441                     cr->nnodes, cr->sim_nodeid);
442         }
443         fprintf(debug, "\n\n");
444     }
445
446     if (multidirs)
447     {
448         if (debug)
449         {
450             fprintf(debug, "Changing to directory %s\n", multidirs[cr->ms->sim]);
451         }
452         gmx_chdir(multidirs[cr->ms->sim]);
453     }
454     else if (bParFn)
455     {
456         /* Patch output and tpx, cpt and rerun input file names */
457         for (i = 0; (i < nfile); i++)
458         {
459             /* Because of possible multiple extensions per type we must look
460              * at the actual file name
461              */
462             if (is_output(&fnm[i]) ||
463                 fnm[i].ftp == efTPX || fnm[i].ftp == efCPT ||
464                 strcmp(fnm[i].opt, "-rerun") == 0)
465             {
466                 ftp = fn2ftp(fnm[i].fns[0]);
467                 par_fn(fnm[i].fns[0], ftp, cr, TRUE, FALSE, buf, 255);
468                 sfree(fnm[i].fns[0]);
469                 fnm[i].fns[0] = gmx_strdup(buf);
470             }
471         }
472     }
473 }