3 * This source code is part of
7 * GROningen MAchine for Chemical Simulations
9 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11 * Copyright (c) 2001-2008, The GROMACS development team,
12 * check out http://www.gromacs.org for more information.
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
19 * If you want to redistribute modifications, please consider that
20 * scientific software is very special. Version control is crucial -
21 * bugs must be traceable. We will be happy to consider code for
22 * inclusion in the official distribution, but derived work must not
23 * be called official GROMACS. Details are found in the README & COPYING
24 * files - if they are missing, get the official version at www.gromacs.org.
26 * To help us fund GROMACS development, we humbly ask that you cite
27 * the papers on the package - you can find them in the top README file.
29 * For more info, check our website at http://www.gromacs.org
32 * Gallium Rubidium Oxygen Manganese Argon Carbon Silicon
48 #include "checkpoint.h"
55 ddnoSEL, ddnoINTERLEAVE, ddnoPP_PME, ddnoCARTESIAN, ddnoNR
58 /* Enum for situations that can occur during log file parsing, the
59 * corresponding string entries can be found in do_the_tests() in
60 * const char* ParseLog[] */
66 eParselogResetProblem,
77 int nPMEnodes; /* number of PME only nodes used in this test */
78 int nx, ny, nz; /* DD grid */
79 int guessPME; /* if nPMEnodes == -1, this is the guessed number of PME nodes */
80 double *Gcycles; /* This can contain more than one value if doing multiple tests */
84 float *PME_f_load; /* PME mesh/force load average*/
85 float PME_f_load_Av; /* Average average ;) ... */
86 char *mdrun_cmd_line; /* Mdrun command line used for this test */
92 int nr_inputfiles; /* The number of tpr and mdp input files */
93 gmx_large_int_t orig_sim_steps; /* Number of steps to be done in the real simulation */
94 real *rcoulomb; /* The coulomb radii [0...nr_inputfiles] */
95 real *rvdw; /* The vdW radii */
96 real *rlist; /* Neighbourlist cutoff radius */
99 real *fsx, *fsy, *fsz; /* Fourierspacing in x,y,z dimension */
103 static void sep_line(FILE *fp)
105 fprintf(fp, "\n------------------------------------------------------------\n");
109 /* Wrapper for system calls */
110 static int gmx_system_call(char *command)
113 gmx_fatal(FARGS,"No calls to system(3) supported on this platform. Attempted to call:\n'%s'\n",command);
115 return ( system(command) );
120 /* Check if string starts with substring */
121 static gmx_bool str_starts(const char *string, const char *substring)
123 return ( strncmp(string, substring, strlen(substring)) == 0);
127 static void cleandata(t_perf *perfdata, int test_nr)
129 perfdata->Gcycles[test_nr] = 0.0;
130 perfdata->ns_per_day[test_nr] = 0.0;
131 perfdata->PME_f_load[test_nr] = 0.0;
137 static gmx_bool is_equal(real a, real b)
139 real diff, eps=1.0e-7;
144 if (diff < 0.0) diff = -diff;
153 static void finalize(const char *fn_out)
159 fp = fopen(fn_out,"r");
160 fprintf(stdout,"\n\n");
162 while( fgets(buf,STRLEN-1,fp) != NULL )
164 fprintf(stdout,"%s",buf);
167 fprintf(stdout,"\n\n");
172 enum {eFoundNothing, eFoundDDStr, eFoundAccountingStr, eFoundCycleStr};
174 static int parse_logfile(const char *logfile, const char *errfile,
175 t_perf *perfdata, int test_nr, int presteps, gmx_large_int_t cpt_steps,
179 char line[STRLEN], dumstring[STRLEN], dumstring2[STRLEN];
180 const char matchstrdd[]="Domain decomposition grid";
181 const char matchstrcr[]="resetting all time and cycle counters";
182 const char matchstrbal[]="Average PME mesh/force load:";
183 const char matchstring[]="R E A L C Y C L E A N D T I M E A C C O U N T I N G";
184 const char errSIG[]="signal, stopping at the next";
187 float dum1,dum2,dum3;
189 gmx_large_int_t resetsteps=-1;
190 gmx_bool bFoundResetStr = FALSE;
191 gmx_bool bResetChecked = FALSE;
194 if (!gmx_fexist(logfile))
196 fprintf(stderr, "WARNING: Could not find logfile %s.\n", logfile);
197 cleandata(perfdata, test_nr);
198 return eParselogNotFound;
201 fp = fopen(logfile, "r");
202 perfdata->PME_f_load[test_nr] = -1.0;
203 perfdata->guessPME = -1;
205 iFound = eFoundNothing;
207 iFound = eFoundDDStr; /* Skip some case statements */
209 while (fgets(line, STRLEN, fp) != NULL)
211 /* Remove leading spaces */
214 /* Check for TERM and INT signals from user: */
215 if ( strstr(line, errSIG) != NULL )
218 cleandata(perfdata, test_nr);
219 return eParselogTerm;
222 /* Check whether cycle resetting worked */
223 if (presteps > 0 && !bFoundResetStr)
225 if (strstr(line, matchstrcr) != NULL)
227 sprintf(dumstring, "Step %s", gmx_large_int_pfmt);
228 sscanf(line, dumstring, &resetsteps);
229 bFoundResetStr = TRUE;
230 if (resetsteps == presteps+cpt_steps)
232 bResetChecked = TRUE;
236 sprintf(dumstring , gmx_large_int_pfmt, resetsteps);
237 sprintf(dumstring2, gmx_large_int_pfmt, presteps+cpt_steps);
238 fprintf(stderr, "WARNING: Time step counters were reset at step %s,\n"
239 " though they were supposed to be reset at step %s!\n",
240 dumstring, dumstring2);
245 /* Look for strings that appear in a certain order in the log file: */
249 /* Look for domain decomp grid and separate PME nodes: */
250 if (str_starts(line, matchstrdd))
252 sscanf(line, "Domain decomposition grid %d x %d x %d, separate PME nodes %d",
253 &(perfdata->nx), &(perfdata->ny), &(perfdata->nz), &npme);
254 if (perfdata->nPMEnodes == -1)
255 perfdata->guessPME = npme;
256 else if (perfdata->nPMEnodes != npme)
257 gmx_fatal(FARGS, "PME nodes from command line and output file are not identical");
258 iFound = eFoundDDStr;
260 /* Catch a few errors that might have occured: */
261 else if (str_starts(line, "There is no domain decomposition for"))
263 return eParselogNoDDGrid;
265 else if (str_starts(line, "reading tpx file"))
267 return eParselogTPXVersion;
269 else if (str_starts(line, "The -dd or -npme option request a parallel simulation"))
271 return eParselogNotParallel;
275 /* Look for PME mesh/force balance (not necessarily present, though) */
276 if (str_starts(line, matchstrbal))
277 sscanf(&line[strlen(matchstrbal)], "%f", &(perfdata->PME_f_load[test_nr]));
278 /* Look for matchstring */
279 if (str_starts(line, matchstring))
280 iFound = eFoundAccountingStr;
282 case eFoundAccountingStr:
283 /* Already found matchstring - look for cycle data */
284 if (str_starts(line, "Total "))
286 sscanf(line,"Total %d %lf",&procs,&(perfdata->Gcycles[test_nr]));
287 iFound = eFoundCycleStr;
291 /* Already found cycle data - look for remaining performance info and return */
292 if (str_starts(line, "Performance:"))
294 sscanf(line,"%s %f %f %f %f", dumstring, &dum1, &dum2, &(perfdata->ns_per_day[test_nr]), &dum3);
296 if (bResetChecked || presteps == 0)
299 return eParselogResetProblem;
305 /* Check why there is no performance data in the log file.
306 * Did a fatal errors occur? */
307 if (gmx_fexist(errfile))
309 fp = fopen(errfile, "r");
310 while (fgets(line, STRLEN, fp) != NULL)
312 if ( str_starts(line, "Fatal error:") )
314 if (fgets(line, STRLEN, fp) != NULL)
315 fprintf(stderr, "\nWARNING: A fatal error has occured during this benchmark:\n"
318 cleandata(perfdata, test_nr);
319 return eParselogFatal;
326 fprintf(stderr, "WARNING: Could not find stderr file %s.\n", errfile);
329 /* Giving up ... we could not find out why there is no performance data in
331 fprintf(stdout, "No performance data in log file.\n");
333 cleandata(perfdata, test_nr);
335 return eParselogNoPerfData;
339 static gmx_bool analyze_data(
348 int *index_tpr, /* OUT: Nr of mdp file with best settings */
349 int *npme_optimal) /* OUT: Optimal number of PME nodes */
352 int line=0, line_win=-1;
353 int k_win=-1, i_win=-1, winPME;
354 double s=0.0; /* standard deviation */
357 char str_PME_f_load[13];
358 gmx_bool bCanUseOrigTPR;
364 fprintf(fp, "Summary of successful runs:\n");
365 fprintf(fp, "Line tpr PME nodes Gcycles Av. Std.dev. ns/day PME/f");
367 fprintf(fp, " DD grid");
372 for (k=0; k<ntprs; k++)
374 for (i=0; i<ntests; i++)
376 /* Select the right dataset: */
377 pd = &(perfdata[k][i]);
379 pd->Gcycles_Av = 0.0;
380 pd->PME_f_load_Av = 0.0;
381 pd->ns_per_day_Av = 0.0;
383 if (pd->nPMEnodes == -1)
384 sprintf(strbuf, "(%3d)", pd->guessPME);
386 sprintf(strbuf, " ");
388 /* Get the average run time of a setting */
389 for (j=0; j<nrepeats; j++)
391 pd->Gcycles_Av += pd->Gcycles[j];
392 pd->PME_f_load_Av += pd->PME_f_load[j];
394 pd->Gcycles_Av /= nrepeats;
395 pd->PME_f_load_Av /= nrepeats;
397 for (j=0; j<nrepeats; j++)
399 if (pd->ns_per_day[j] > 0.0)
400 pd->ns_per_day_Av += pd->ns_per_day[j];
403 /* Somehow the performance number was not aquired for this run,
404 * therefor set the average to some negative value: */
405 pd->ns_per_day_Av = -1.0f*nrepeats;
409 pd->ns_per_day_Av /= nrepeats;
412 if (pd->PME_f_load_Av > 0.0)
413 sprintf(str_PME_f_load, "%12.3f", pd->PME_f_load_Av);
415 sprintf(str_PME_f_load, "%s", " - ");
418 /* We assume we had a successful run if both averages are positive */
419 if (pd->Gcycles_Av > 0.0 && pd->ns_per_day_Av > 0.0)
421 /* Output statistics if repeats were done */
424 /* Calculate the standard deviation */
426 for (j=0; j<nrepeats; j++)
427 s += pow( pd->Gcycles[j] - pd->Gcycles_Av, 2 );
431 fprintf(fp, "%4d %3d %4d%s %12.3f %12.3f %12.3f %s",
432 line, k, pd->nPMEnodes, strbuf, pd->Gcycles_Av, s,
433 pd->ns_per_day_Av, str_PME_f_load);
435 fprintf(fp, " %3d %3d %3d", pd->nx, pd->ny, pd->nz);
438 /* Store the index of the best run found so far in 'winner': */
439 if ( (k_win == -1) || (pd->Gcycles_Av < perfdata[k_win][i_win].Gcycles_Av) )
451 gmx_fatal(FARGS, "None of the runs was successful! Check %s for problems.", fn);
455 winPME = perfdata[k_win][i_win].nPMEnodes;
457 sprintf(strbuf, "%s", "the automatic number of");
459 sprintf(strbuf, "%d", winPME);
460 fprintf(fp, "Best performance was achieved with %s PME nodes", strbuf);
462 fprintf(fp, " (see line %d)", line_win);
465 /* Only mention settings if they were modified: */
466 bCanUseOrigTPR = TRUE;
467 if ( !is_equal(info->rcoulomb[k_win], info->rcoulomb[0]) )
469 fprintf(fp, "Optimized PME settings:\n"
470 " New Coulomb radius: %f nm (was %f nm)\n",
471 info->rcoulomb[k_win], info->rcoulomb[0]);
472 bCanUseOrigTPR = FALSE;
475 if ( !is_equal(info->rvdw[k_win], info->rvdw[0]) )
477 fprintf(fp, " New Van der Waals radius: %f nm (was %f nm)\n",
478 info->rvdw[k_win], info->rvdw[0]);
479 bCanUseOrigTPR = FALSE;
482 if ( ! (info->nkx[k_win] == info->nkx[0] &&
483 info->nky[k_win] == info->nky[0] &&
484 info->nkz[k_win] == info->nkz[0] ) )
486 fprintf(fp, " New Fourier grid xyz: %d %d %d (was %d %d %d)\n",
487 info->nkx[k_win], info->nky[k_win], info->nkz[k_win],
488 info->nkx[0], info->nky[0], info->nkz[0]);
489 bCanUseOrigTPR = FALSE;
491 if (bCanUseOrigTPR && ntprs > 1)
492 fprintf(fp, "and original PME settings.\n");
496 /* Return the index of the mdp file that showed the highest performance
497 * and the optimal number of PME nodes */
499 *npme_optimal = winPME;
501 return bCanUseOrigTPR;
505 /* Get the commands we need to set up the runs from environment variables */
506 static void get_program_paths(gmx_bool bThreads, char *cmd_mpirun[], char cmd_np[],
507 char *cmd_mdrun[], int repeats)
514 const char def_mpirun[] = "mpirun";
515 const char def_mdrun[] = "mdrun";
516 const char filename[] = "benchtest.log";
517 const char match_mpi[] = "NNODES=";
518 const char match_mdrun[]= "Program: ";
519 const char empty_mpirun[] = "";
520 gmx_bool bMdrun = FALSE;
521 gmx_bool bMPI = FALSE;
524 /* Get the commands we need to set up the runs from environment variables */
527 if ( (cp = getenv("MPIRUN")) != NULL)
528 *cmd_mpirun = strdup(cp);
530 *cmd_mpirun = strdup(def_mpirun);
534 *cmd_mpirun = strdup(empty_mpirun);
537 if ( (cp = getenv("MDRUN" )) != NULL )
538 *cmd_mdrun = strdup(cp);
540 *cmd_mdrun = strdup(def_mdrun);
543 /* If no simulations have to be performed, we are done here */
547 /* Run a small test to see whether mpirun + mdrun work */
548 fprintf(stdout, "Making sure that mdrun can be executed. ");
551 snew(command, strlen(*cmd_mdrun) + strlen(cmd_np) + strlen(filename) + 50);
552 sprintf(command, "%s%s-version -maxh 0.001 1> %s 2>&1", *cmd_mdrun, cmd_np, filename);
556 snew(command, strlen(*cmd_mpirun) + strlen(cmd_np) + strlen(*cmd_mdrun) + strlen(filename) + 50);
557 sprintf(command, "%s%s%s -version -maxh 0.001 1> %s 2>&1", *cmd_mpirun, cmd_np, *cmd_mdrun, filename);
559 fprintf(stdout, "Trying '%s' ... ", command);
560 make_backup(filename);
561 gmx_system_call(command);
563 /* Check if we find the characteristic string in the output: */
564 if (!gmx_fexist(filename))
565 gmx_fatal(FARGS, "Output from test run could not be found.");
567 fp = fopen(filename, "r");
568 /* We need to scan the whole output file, since sometimes the queuing system
569 * also writes stuff to stdout/err */
572 cp2=fgets(line, STRLEN, fp);
575 if ( str_starts(line, match_mdrun) )
577 if ( str_starts(line, match_mpi) )
587 gmx_fatal(FARGS, "Need a threaded version of mdrun. This one\n"
589 "seems to have been compiled with MPI instead.",
597 gmx_fatal(FARGS, "Need an MPI-enabled version of mdrun. This one\n"
599 "seems to have been compiled without MPI support.",
606 gmx_fatal(FARGS, "Cannot execute mdrun. Please check %s for problems!",
610 fprintf(stdout, "passed.\n");
618 static void launch_simulation(
619 gmx_bool bLaunch, /* Should the simulation be launched? */
620 FILE *fp, /* General log file */
621 gmx_bool bThreads, /* whether to use threads */
622 char *cmd_mpirun, /* Command for mpirun */
623 char *cmd_np, /* Switch for -np or -nt or empty */
624 char *cmd_mdrun, /* Command for mdrun */
625 char *args_for_mdrun, /* Arguments for mdrun */
626 const char *simulation_tpr, /* This tpr will be simulated */
627 int nnodes, /* Number of nodes to run on */
628 int nPMEnodes) /* Number of PME nodes to use */
633 /* Make enough space for the system call command,
634 * (100 extra chars for -npme ... etc. options should suffice): */
635 snew(command, strlen(cmd_mpirun)+strlen(cmd_mdrun)+strlen(cmd_np)+strlen(args_for_mdrun)+strlen(simulation_tpr)+100);
637 /* Note that the -passall options requires args_for_mdrun to be at the end
638 * of the command line string */
641 sprintf(command, "%s%s-npme %d -s %s %s",
642 cmd_mdrun, cmd_np, nPMEnodes, simulation_tpr, args_for_mdrun);
646 sprintf(command, "%s%s%s -npme %d -s %s %s",
647 cmd_mpirun, cmd_np, cmd_mdrun, nPMEnodes, simulation_tpr, args_for_mdrun);
650 fprintf(fp, "%s this command line to launch the simulation:\n\n%s", bLaunch? "Using":"Please use", command);
654 /* Now the real thing! */
657 fprintf(stdout, "\nLaunching simulation with best parameters now.\nExecuting '%s'", command);
660 gmx_system_call(command);
666 static void modify_PMEsettings(
667 gmx_large_int_t simsteps, /* Set this value as number of time steps */
668 const char *fn_best_tpr, /* tpr file with the best performance */
669 const char *fn_sim_tpr) /* name of tpr file to be launched */
677 read_tpx_state(fn_best_tpr,ir,&state,NULL,&mtop);
679 /* Set nsteps to the right value */
680 ir->nsteps = simsteps;
682 /* Write the tpr file which will be launched */
683 sprintf(buf, "Writing optimized simulation file %s with nsteps=%s.\n", fn_sim_tpr, gmx_large_int_pfmt);
684 fprintf(stdout,buf,ir->nsteps);
686 write_tpx_state(fn_sim_tpr,ir,&state,&mtop);
694 int nkx, nky, nkz; /* Fourier grid */
695 real fac; /* actual scaling factor */
696 real fs; /* Fourierspacing */
700 static void copy_grid(t_pmegrid *ingrid, t_pmegrid *outgrid)
702 outgrid->nkx = ingrid->nkx;
703 outgrid->nky = ingrid->nky;
704 outgrid->nkz = ingrid->nkz;
705 outgrid->fac = ingrid->fac;
706 outgrid->fs = ingrid->fs;
709 /* Removes entry 'index' from the t_pmegrid list */
710 static void remove_from_list(
711 t_pmegrid gridlist[],
712 int *nlist, /* Length of the list */
713 int index) /* Index to remove from the list */
718 for (j = index; j < (*nlist - 1); j++)
720 copy_grid(&gridlist[j+1], &gridlist[j]);
726 /* Returns the index of the least necessary grid in the list.
728 * This is the one where the following conditions hold for the scaling factor:
729 * 1. this grid has the smallest distance to its neighboring grid (distance
730 * measured by fac) -> this condition is true for two grids at the same time
731 * 2. this grid (of the two) has the smaller distance to the other neighboring
734 * The extreme grids (the ones with the smallest and largest
735 * scaling factor) are never thrown away.
737 static int get_throwaway_index(
738 t_pmegrid gridlist[],
739 int nlist) /* Length of the list */
742 real dist,mindist,d_left,d_right;
745 /* Find the two factors with the smallest mutual distance */
746 mindist = GMX_FLOAT_MAX;
747 for (i = 1; i < nlist; i++)
749 dist = fabs(gridlist[i].fac - gridlist[i-1].fac);
756 /* index and index-1 have the smallest mutual distance */
759 /* Never return the first index, i.e. index == 0 */
764 d_left = fabs(gridlist[index-1].fac - gridlist[index-2].fac);
765 d_right = fabs(gridlist[index+1].fac - gridlist[index ].fac);
767 /* Return the left index if its distance to its left neighbor is shorter
768 * than the distance of the right index to its right neighbor */
769 if (d_left < d_right)
772 /* Never return the last index */
773 if (index == nlist-1)
780 static void make_grid_list(
781 real fmin, /* minimum scaling factor (downscaling fac) */
782 real fmax, /* maximum scaling factor (upscaling fac) */
783 int ntprs, /* Number of tpr files to test */
784 matrix box, /* The box */
785 t_pmegrid *griduse[], /* List of grids that have to be tested */
786 int *npmegrid, /* Number of grids in the list */
787 real fs) /* Requested fourierspacing at a scaling factor
790 real req_fac,act_fac=0,act_fs,eps;
792 int i,jmin=0,d,ngridall=0;
793 int nkx=0,nky=0,nkz=0;
794 int nkx_old=0,nky_old=0,nkz_old=0;
796 int gridalloc,excess;
799 /* Determine length of triclinic box vectors */
804 box_size[d] += box[d][i]*box[d][i];
805 box_size[d] = sqrt(box_size[d]);
809 snew(gridall, gridalloc);
811 fprintf(stdout, "Possible PME grid settings (apart from input file settings):\n");
812 fprintf(stdout, " nkx nky nkz max spacing scaling factor\n");
814 /* eps should provide a fine enough spacing not to miss any grid */
816 eps = (fmax-fmin)/(100.0*(ntprs-1));
818 eps = 1.0/max( (*griduse)[0].nkz, max( (*griduse)[0].nkx, (*griduse)[0].nky ) );
820 for (req_fac = fmin; act_fac < fmax; req_fac += eps)
825 calc_grid(NULL,box,fs*req_fac,&nkx,&nky,&nkz);
826 act_fs = max(box_size[XX]/nkx,max(box_size[YY]/nky,box_size[ZZ]/nkz));
828 if ( ! ( nkx==nkx_old && nky==nky_old && nkz==nkz_old ) /* Exclude if grid is already in list */
829 && ! ( nkx==(*griduse)[0].nkx && nky==(*griduse)[0].nky && nkz==(*griduse)[0].nkz ) ) /* Exclude input file grid */
831 /* We found a new grid that will do */
835 gridall[ngridall].nkx = nkx;
836 gridall[ngridall].nky = nky;
837 gridall[ngridall].nkz = nkz;
838 gridall[ngridall].fac = act_fac;
839 gridall[ngridall].fs = act_fs;
840 fprintf(stdout, "%5d%5d%5d %12f %12f\n",nkx,nky,nkz,act_fs,act_fac);
842 if (ngridall >= gridalloc)
845 srenew(gridall, gridalloc);
850 /* Return the actual number of grids that can be tested. We cannot test more
851 * than the number of grids we found plus 1 (the input file) */
852 *npmegrid = min(ngridall+1,ntprs);
854 /* excess is the number of grids we have to get rid of */
855 excess = ngridall+1 - ntprs;
857 /* If we found less grids than tpr files were requested, simply test all
858 * the grid there are ... */
861 fprintf(stdout, "NOTE: You requested %d tpr files, but apart from the input file grid only the\n"
862 " above listed %d suitable PME grids were found. Will test all suitable settings.\n",
869 /* We can only keep the input tpr file plus one extra tpr file.
870 * We make that choice depending on the values of -upfac and -downfac */
873 /* Keep the one with the -downfac as scaling factor. This is already
874 * stored in gridall[0] */
879 /* Keep the one with -upfac as scaling factor */
880 copy_grid(&(gridall[ngridall-1]), &(gridall[0]));
886 /* From the grid list throw away the unnecessary ones (keep the extremes) */
887 for (i = 0; i < excess; i++)
889 /* Get the index of the least necessary grid from the list ... */
890 jmin = get_throwaway_index(gridall, ngridall);
891 /* ... and remove the grid from the list */
892 remove_from_list(gridall, &ngridall, jmin);
897 /* The remaining list contains the grids we want to test */
898 for (i=1; i < *npmegrid; i++)
899 copy_grid(&(gridall[i-1]), &((*griduse)[i]));
905 #define EPME_SWITCHED(e) ((e) == eelPMESWITCH || (e) == eelPMEUSERSWITCH)
907 /* Make additional TPR files with more computational load for the
908 * direct space processors: */
909 static void make_benchmark_tprs(
910 const char *fn_sim_tpr, /* READ : User-provided tpr file */
911 char *fn_bench_tprs[], /* WRITE: Names of benchmark tpr files */
912 gmx_large_int_t benchsteps, /* Number of time steps for benchmark runs */
913 gmx_large_int_t statesteps, /* Step counter in checkpoint file */
914 real upfac, /* Scale rcoulomb inbetween downfac and upfac */
916 int ntprs, /* No. of TPRs to write, each with a different rcoulomb and fourierspacing */
917 real fourierspacing, /* Basic fourierspacing from tpr input file */
918 t_inputinfo *info, /* Contains information about mdp file options */
919 FILE *fp) /* Write the output here */
925 real nlist_buffer; /* Thickness of the buffer regions for PME-switch potentials: */
928 gmx_bool bNote = FALSE;
929 t_pmegrid *pmegrid=NULL; /* Grid settings for the PME grids to test */
930 int npmegrid=1; /* Number of grids that can be tested,
931 * normally = ntpr but could be less */
934 sprintf(buf, "Making benchmark tpr file%s with %s time step%s",
935 ntprs>1? "s":"", gmx_large_int_pfmt, benchsteps>1?"s":"");
936 fprintf(stdout, buf, benchsteps);
939 sprintf(buf, " (adding %s steps from checkpoint file)", gmx_large_int_pfmt);
940 fprintf(stdout, buf, statesteps);
941 benchsteps += statesteps;
943 fprintf(stdout, ".\n");
947 read_tpx_state(fn_sim_tpr,ir,&state,NULL,&mtop);
949 /* Check if some kind of PME was chosen */
950 if (EEL_PME(ir->coulombtype) == FALSE)
951 gmx_fatal(FARGS, "Can only do optimizations for simulations with %s electrostatics.",
954 /* Check if rcoulomb == rlist, which is necessary for plain PME. */
955 if ( (eelPME == ir->coulombtype) && !(ir->rcoulomb == ir->rlist) )
957 gmx_fatal(FARGS, "%s requires rcoulomb (%f) to be equal to rlist (%f).",
958 EELTYPE(eelPME), ir->rcoulomb, ir->rlist);
960 /* For other PME types, rcoulomb is allowed to be smaller than rlist */
961 else if (ir->rcoulomb > ir->rlist)
963 gmx_fatal(FARGS, "%s requires rcoulomb (%f) to be equal to or smaller than rlist (%f)",
964 EELTYPE(ir->coulombtype), ir->rcoulomb, ir->rlist);
967 /* Reduce the number of steps for the benchmarks */
968 info->orig_sim_steps = ir->nsteps;
969 ir->nsteps = benchsteps;
971 /* For PME-switch potentials, keep the radial distance of the buffer region */
972 nlist_buffer = ir->rlist - ir->rcoulomb;
974 /* Determine length of triclinic box vectors */
979 box_size[d] += state.box[d][i]*state.box[d][i];
980 box_size[d] = sqrt(box_size[d]);
983 /* Reconstruct fourierspacing per dimension from the number of grid points and box size */
984 info->fsx[0] = box_size[XX]/ir->nkx;
985 info->fsy[0] = box_size[YY]/ir->nky;
986 info->fsz[0] = box_size[ZZ]/ir->nkz;
988 /* Put the input grid as first entry into the grid list */
989 snew(pmegrid, ntprs);
990 pmegrid[0].fac = 1.00;
991 pmegrid[0].nkx = ir->nkx;
992 pmegrid[0].nky = ir->nky;
993 pmegrid[0].nkz = ir->nkz;
994 pmegrid[0].fs = max(box_size[ZZ]/ir->nkz, max(box_size[XX]/ir->nkx, box_size[YY]/ir->nky));
996 /* If no value for the fourierspacing was provided on the command line, we
997 * use the reconstruction from the tpr file */
998 if (fourierspacing <= 0)
1000 fourierspacing = pmegrid[0].fs;
1003 fprintf(stdout, "Calculating PME grid points on the basis of a fourierspacing of %f nm\n", fourierspacing);
1005 /* Print information about settings of which some are potentially modified: */
1006 fprintf(fp, " Coulomb type : %s\n", EELTYPE(ir->coulombtype));
1007 fprintf(fp, " Grid spacing x y z : %f %f %f\n",
1008 box_size[XX]/ir->nkx, box_size[YY]/ir->nky, box_size[ZZ]/ir->nkz);
1009 fprintf(fp, " Van der Waals type : %s\n", EVDWTYPE(ir->vdwtype));
1010 if (EVDW_SWITCHED(ir->vdwtype))
1011 fprintf(fp, " rvdw_switch : %f nm\n", ir->rvdw_switch);
1012 if (EPME_SWITCHED(ir->coulombtype))
1013 fprintf(fp, " rlist : %f nm\n", ir->rlist);
1014 if (ir->rlistlong != max_cutoff(ir->rvdw,ir->rcoulomb))
1015 fprintf(fp, " rlistlong : %f nm\n", ir->rlistlong);
1017 /* Print a descriptive line about the tpr settings tested */
1018 fprintf(fp, "\nWill try these real/reciprocal workload settings:\n");
1019 fprintf(fp, " No. scaling rcoulomb");
1020 fprintf(fp, " nkx nky nkz");
1021 fprintf(fp, " spacing");
1022 if (evdwCUT == ir->vdwtype)
1023 fprintf(fp, " rvdw");
1024 if (EPME_SWITCHED(ir->coulombtype))
1025 fprintf(fp, " rlist");
1026 if ( ir->rlistlong != max_cutoff(ir->rlist,max_cutoff(ir->rvdw,ir->rcoulomb)) )
1027 fprintf(fp, " rlistlong");
1028 fprintf(fp, " tpr file\n");
1031 /* Get useful PME grids if requested, the actual number of entries is
1032 * returned in npmegrid */
1034 make_grid_list(downfac, upfac, ntprs, state.box, &pmegrid, &npmegrid, fourierspacing);
1036 /* Loop to create the requested number of tpr input files */
1037 for (j = 0; j < npmegrid; j++)
1039 /* The first one is the provided tpr file, just need to modify the number
1040 * of steps, so skip the following block */
1043 /* Scale the Coulomb radius */
1044 ir->rcoulomb = info->rcoulomb[0]*pmegrid[j].fac;
1046 /* Adjust other radii since various conditions neet to be fulfilled */
1047 if (eelPME == ir->coulombtype)
1049 /* plain PME, rcoulomb must be equal to rlist */
1050 ir->rlist = ir->rcoulomb;
1054 /* rlist must be >= rcoulomb, we keep the size of the buffer region */
1055 ir->rlist = ir->rcoulomb + nlist_buffer;
1058 if (evdwCUT == ir->vdwtype)
1060 /* For vdw cutoff, rvdw >= rlist */
1061 ir->rvdw = max(info->rvdw[0], ir->rlist);
1064 ir->rlistlong = max_cutoff(ir->rlist,max_cutoff(ir->rvdw,ir->rcoulomb));
1066 /* Copy the optimal grid dimensions to ir */
1067 ir->nkx = pmegrid[j].nkx;
1068 ir->nky = pmegrid[j].nky;
1069 ir->nkz = pmegrid[j].nkz;
1071 } /* end of "if (j != 0)" */
1073 /* for j==0: Save the original settings
1074 * for j >0: Save modified radii and fourier grids */
1075 info->rcoulomb[j] = ir->rcoulomb;
1076 info->rvdw[j] = ir->rvdw;
1077 info->nkx[j] = ir->nkx;
1078 info->nky[j] = ir->nky;
1079 info->nkz[j] = ir->nkz;
1080 info->rlist[j] = ir->rlist;
1081 info->rlistlong[j] = ir->rlistlong;
1082 info->fsx[j] = pmegrid[j].fs;
1083 info->fsy[j] = pmegrid[j].fs;
1084 info->fsz[j] = pmegrid[j].fs;
1086 /* Write the benchmark tpr file */
1087 strncpy(fn_bench_tprs[j],fn_sim_tpr,strlen(fn_sim_tpr)-strlen(".tpr"));
1088 sprintf(buf, "_bench%.2d.tpr", j);
1089 strcat(fn_bench_tprs[j], buf);
1090 fprintf(stdout,"Writing benchmark tpr %s with nsteps=", fn_bench_tprs[j]);
1091 fprintf(stdout, gmx_large_int_pfmt, ir->nsteps);
1093 fprintf(stdout,", scaling factor %f\n", pmegrid[j].fac);
1095 fprintf(stdout,", unmodified settings\n");
1097 write_tpx_state(fn_bench_tprs[j],ir,&state,&mtop);
1099 /* Write information about modified tpr settings to log file */
1101 fprintf(fp, "%4d%10s%10f", j, "-input-", ir->rcoulomb);
1103 fprintf(fp, "%4d%10f%10f", j, pmegrid[j].fac, ir->rcoulomb);
1104 fprintf(fp, "%5d%5d%5d", ir->nkx, ir->nky, ir->nkz);
1105 fprintf(fp, " %9f ", info->fsx[j]);
1106 if (evdwCUT == ir->vdwtype)
1107 fprintf(fp, "%10f", ir->rvdw);
1108 if (EPME_SWITCHED(ir->coulombtype))
1109 fprintf(fp, "%10f", ir->rlist);
1110 if ( info->rlistlong[0] != max_cutoff(info->rlist[0],max_cutoff(info->rvdw[0],info->rcoulomb[0])) )
1111 fprintf(fp, "%10f", ir->rlistlong);
1112 fprintf(fp, " %-14s\n",fn_bench_tprs[j]);
1114 /* Make it clear to the user that some additional settings were modified */
1115 if ( !is_equal(ir->rvdw , info->rvdw[0])
1116 || !is_equal(ir->rlistlong, info->rlistlong[0]) )
1122 fprintf(fp, "\nNote that in addition to rcoulomb and the fourier grid\n"
1123 "also other input settings were changed (see table above).\n"
1124 "Please check if the modified settings are appropriate.\n");
1131 /* Whether these files are written depends on tpr (or mdp) settings,
1132 * not on mdrun command line options! */
1133 static gmx_bool tpr_triggers_file(const char *opt)
1135 if ( (0 == strcmp(opt, "-pf"))
1136 || (0 == strcmp(opt, "-px")) )
1143 /* Rename the files we want to keep to some meaningful filename and
1144 * delete the rest */
1145 static void cleanup(const t_filenm *fnm, int nfile, int k, int nnodes,
1146 int nPMEnodes, int nr, gmx_bool bKeepStderr)
1148 char numstring[STRLEN];
1149 char newfilename[STRLEN];
1150 const char *fn=NULL;
1155 fprintf(stdout, "Cleaning up, deleting benchmark temp files ...\n");
1157 for (i=0; i<nfile; i++)
1159 opt = (char *)fnm[i].opt;
1160 if ( strcmp(opt, "-p") == 0 )
1162 /* do nothing; keep this file */
1165 else if (strcmp(opt, "-bg") == 0)
1167 /* Give the log file a nice name so one can later see which parameters were used */
1168 numstring[0] = '\0';
1170 sprintf(numstring, "_%d", nr);
1171 sprintf(newfilename, "%s_no%d_np%d_npme%d%s", opt2fn("-bg",nfile,fnm), k, nnodes, nPMEnodes, numstring);
1172 if (gmx_fexist(opt2fn("-bg",nfile,fnm)))
1174 fprintf(stdout, "renaming log file to %s\n", newfilename);
1175 make_backup(newfilename);
1176 rename(opt2fn("-bg",nfile,fnm), newfilename);
1179 else if (strcmp(opt, "-err") == 0)
1181 /* This file contains the output of stderr. We want to keep it in
1182 * cases where there have been problems. */
1183 fn = opt2fn(opt, nfile, fnm);
1184 numstring[0] = '\0';
1186 sprintf(numstring, "_%d", nr);
1187 sprintf(newfilename, "%s_no%d_np%d_npme%d%s", fn, k, nnodes, nPMEnodes, numstring);
1192 fprintf(stdout, "Saving stderr output in %s\n", newfilename);
1193 make_backup(newfilename);
1194 rename(fn, newfilename);
1198 fprintf(stdout, "Deleting %s\n", fn);
1203 /* Delete the files which are created for each benchmark run: (options -b*) */
1204 else if ( ( (0 == strncmp(opt, "-b", 2)) && (opt2bSet(opt,nfile,fnm) || !is_optional(&fnm[i])) )
1205 || tpr_triggers_file(opt) )
1207 fn = opt2fn(opt, nfile, fnm);
1210 fprintf(stdout, "Deleting %s\n", fn);
1218 /* Returns the largest common factor of n1 and n2 */
1219 static int largest_common_factor(int n1, int n2)
1224 for (factor=nmax; factor > 0; factor--)
1226 if ( 0==(n1 % factor) && 0==(n2 % factor) )
1231 return 0; /* one for the compiler */
1234 enum {eNpmeAuto, eNpmeAll, eNpmeReduced, eNpmeSubset, eNpmeNr};
1236 /* Create a list of numbers of PME nodes to test */
1237 static void make_npme_list(
1238 const char *npmevalues_opt, /* Make a complete list with all
1239 * possibilities or a short list that keeps only
1240 * reasonable numbers of PME nodes */
1241 int *nentries, /* Number of entries we put in the nPMEnodes list */
1242 int *nPMEnodes[], /* Each entry contains the value for -npme */
1243 int nnodes, /* Total number of nodes to do the tests on */
1244 int minPMEnodes, /* Minimum number of PME nodes */
1245 int maxPMEnodes) /* Maximum number of PME nodes */
1248 int min_factor=1; /* We request that npp and npme have this minimal
1249 * largest common factor (depends on npp) */
1250 int nlistmax; /* Max. list size */
1251 int nlist; /* Actual number of entries in list */
1255 /* Do we need to check all possible values for -npme or is a reduced list enough? */
1256 if ( 0 == strcmp(npmevalues_opt, "all") )
1260 else if ( 0 == strcmp(npmevalues_opt, "subset") )
1262 eNPME = eNpmeSubset;
1264 else if ( 0 == strcmp(npmevalues_opt, "auto") )
1268 else if (nnodes < 128)
1269 eNPME = eNpmeReduced;
1271 eNPME = eNpmeSubset;
1275 gmx_fatal(FARGS, "Unknown option for -npme in make_npme_list");
1278 /* Calculate how many entries we could possibly have (in case of -npme all) */
1281 nlistmax = maxPMEnodes - minPMEnodes + 3;
1282 if (0 == minPMEnodes)
1288 /* Now make the actual list which is at most of size nlist */
1289 snew(*nPMEnodes, nlistmax);
1290 nlist = 0; /* start counting again, now the real entries in the list */
1291 for (i = 0; i < nlistmax - 2; i++)
1293 npme = maxPMEnodes - i;
1304 /* For 2d PME we want a common largest factor of at least the cube
1305 * root of the number of PP nodes */
1306 min_factor = (int) pow(npp, 1.0/3.0);
1309 gmx_fatal(FARGS, "Unknown option for eNPME in make_npme_list");
1312 if (largest_common_factor(npp, npme) >= min_factor)
1314 (*nPMEnodes)[nlist] = npme;
1318 /* We always test 0 PME nodes and the automatic number */
1319 *nentries = nlist + 2;
1320 (*nPMEnodes)[nlist ] = 0;
1321 (*nPMEnodes)[nlist+1] = -1;
1323 fprintf(stderr, "Will try the following %d different values for -npme:\n", *nentries);
1324 for (i=0; i<*nentries-1; i++)
1325 fprintf(stderr, "%d, ", (*nPMEnodes)[i]);
1326 fprintf(stderr, "and %d (auto).\n", (*nPMEnodes)[*nentries-1]);
1330 /* Allocate memory to store the performance data */
1331 static void init_perfdata(t_perf *perfdata[], int ntprs, int datasets, int repeats)
1336 for (k=0; k<ntprs; k++)
1338 snew(perfdata[k], datasets);
1339 for (i=0; i<datasets; i++)
1341 for (j=0; j<repeats; j++)
1343 snew(perfdata[k][i].Gcycles , repeats);
1344 snew(perfdata[k][i].ns_per_day, repeats);
1345 snew(perfdata[k][i].PME_f_load, repeats);
1352 static void do_the_tests(
1353 FILE *fp, /* General g_tune_pme output file */
1354 char **tpr_names, /* Filenames of the input files to test */
1355 int maxPMEnodes, /* Max fraction of nodes to use for PME */
1356 int minPMEnodes, /* Min fraction of nodes to use for PME */
1357 const char *npmevalues_opt, /* Which -npme values should be tested */
1358 t_perf **perfdata, /* Here the performace data is stored */
1359 int *pmeentries, /* Entries in the nPMEnodes list */
1360 int repeats, /* Repeat each test this often */
1361 int nnodes, /* Total number of nodes = nPP + nPME */
1362 int nr_tprs, /* Total number of tpr files to test */
1363 gmx_bool bThreads, /* Threads or MPI? */
1364 char *cmd_mpirun, /* mpirun command string */
1365 char *cmd_np, /* "-np", "-n", whatever mpirun needs */
1366 char *cmd_mdrun, /* mdrun command string */
1367 char *cmd_args_bench, /* arguments for mdrun in a string */
1368 const t_filenm *fnm, /* List of filenames from command line */
1369 int nfile, /* Number of files specified on the cmdl. */
1370 int sim_part, /* For checkpointing */
1371 int presteps, /* DLB equilibration steps, is checked */
1372 gmx_large_int_t cpt_steps) /* Time step counter in the checkpoint */
1374 int i,nr,k,ret,count=0,totaltests;
1375 int *nPMEnodes=NULL;
1378 char *command, *cmd_stub;
1380 gmx_bool bResetProblem=FALSE;
1383 /* This string array corresponds to the eParselog enum type at the start
1385 const char* ParseLog[] = {"OK.",
1386 "Logfile not found!",
1387 "No timings, logfile truncated?",
1388 "Run was terminated.",
1389 "Counters were not reset properly.",
1390 "No DD grid found for these settings.",
1391 "TPX version conflict!",
1392 "mdrun was not started in parallel!",
1393 "A fatal error occured!" };
1394 char str_PME_f_load[13];
1397 /* Allocate space for the mdrun command line. 100 extra characters should
1398 be more than enough for the -npme etcetera arguments */
1399 cmdline_length = strlen(cmd_mpirun)
1402 + strlen(cmd_args_bench)
1403 + strlen(tpr_names[0]) + 100;
1404 snew(command , cmdline_length);
1405 snew(cmd_stub, cmdline_length);
1407 /* Construct the part of the command line that stays the same for all tests: */
1410 sprintf(cmd_stub, "%s%s", cmd_mdrun, cmd_np);
1414 sprintf(cmd_stub, "%s%s%s ", cmd_mpirun, cmd_np, cmd_mdrun);
1417 /* Create a list of numbers of PME nodes to test */
1418 make_npme_list(npmevalues_opt, pmeentries, &nPMEnodes,
1419 nnodes, minPMEnodes, maxPMEnodes);
1423 fprintf(fp, "\nNo benchmarks done since number of repeats (-r) is 0.\n");
1425 finalize(opt2fn("-p", nfile, fnm));
1429 /* Allocate one dataset for each tpr input file: */
1430 init_perfdata(perfdata, nr_tprs, *pmeentries, repeats);
1432 /*****************************************/
1433 /* Main loop over all tpr files to test: */
1434 /*****************************************/
1435 totaltests = nr_tprs*(*pmeentries)*repeats;
1436 for (k=0; k<nr_tprs;k++)
1438 fprintf(fp, "\nIndividual timings for input file %d (%s):\n", k, tpr_names[k]);
1439 fprintf(fp, "PME nodes Gcycles ns/day PME/f Remark\n");
1440 /* Loop over various numbers of PME nodes: */
1441 for (i = 0; i < *pmeentries; i++)
1443 pd = &perfdata[k][i];
1445 /* Loop over the repeats for each scenario: */
1446 for (nr = 0; nr < repeats; nr++)
1448 pd->nPMEnodes = nPMEnodes[i];
1450 /* Add -npme and -s to the command line and save it. Note that
1451 * the -passall (if set) options requires cmd_args_bench to be
1452 * at the end of the command line string */
1453 snew(pd->mdrun_cmd_line, cmdline_length);
1454 sprintf(pd->mdrun_cmd_line, "%s-npme %d -s %s %s",
1455 cmd_stub, pd->nPMEnodes, tpr_names[k], cmd_args_bench);
1457 /* Do a benchmark simulation: */
1459 sprintf(buf, ", pass %d/%d", nr+1, repeats);
1462 fprintf(stdout, "\n=== Progress %2.0f%%, tpr %d/%d, run %d/%d%s:\n",
1463 (100.0*count)/totaltests,
1464 k+1, nr_tprs, i+1, *pmeentries, buf);
1465 make_backup(opt2fn("-err",nfile,fnm));
1466 sprintf(command, "%s 1> /dev/null 2>%s", pd->mdrun_cmd_line, opt2fn("-err",nfile,fnm));
1467 fprintf(stdout, "%s\n", pd->mdrun_cmd_line);
1468 gmx_system_call(command);
1470 /* Collect the performance data from the log file; also check stderr
1471 * for fatal errors */
1472 ret = parse_logfile(opt2fn("-bg",nfile,fnm), opt2fn("-err",nfile,fnm),
1473 pd, nr, presteps, cpt_steps, nnodes);
1474 if ((presteps > 0) && (ret == eParselogResetProblem))
1475 bResetProblem = TRUE;
1477 if (-1 == pd->nPMEnodes)
1478 sprintf(buf, "(%3d)", pd->guessPME);
1483 if (pd->PME_f_load[nr] > 0.0)
1484 sprintf(str_PME_f_load, "%12.3f", pd->PME_f_load[nr]);
1486 sprintf(str_PME_f_load, "%s", " - ");
1488 /* Write the data we got to disk */
1489 fprintf(fp, "%4d%s %12.3f %12.3f %s %s", pd->nPMEnodes,
1490 buf, pd->Gcycles[nr], pd->ns_per_day[nr], str_PME_f_load, ParseLog[ret]);
1491 if (! (ret==eParselogOK || ret==eParselogNoDDGrid || ret==eParselogNotFound) )
1492 fprintf(fp, " Check %s file for problems.", ret==eParselogFatal? "err":"log");
1497 /* Do some cleaning up and delete the files we do not need any more */
1498 cleanup(fnm, nfile, k, nnodes, pd->nPMEnodes, nr, ret==eParselogFatal);
1500 /* If the first run with this number of processors already failed, do not try again: */
1501 if (pd->Gcycles[0] <= 0.0 && repeats > 1)
1503 fprintf(stdout, "Skipping remaining passes of unsuccessful setting, see log file for details.\n");
1504 count += repeats-(nr+1);
1507 } /* end of repeats loop */
1508 } /* end of -npme loop */
1509 } /* end of tpr file loop */
1513 fprintf(fp, "WARNING: The cycle and time step counters could not be reset\n"
1514 "properly. The reason could be that mpirun did not manage to\n"
1515 "export the environment variable GMX_RESET_COUNTER. You might\n"
1516 "have to give a special switch to mpirun for that.\n"
1517 "Alternatively, you can manually set GMX_RESET_COUNTER to the\n"
1518 "value normally provided by -presteps.");
1526 static void check_input(
1532 real maxPMEfraction,
1533 real minPMEfraction,
1534 real fourierspacing,
1535 gmx_large_int_t bench_nsteps,
1536 const t_filenm *fnm,
1543 /* Make sure the input file exists */
1544 if (!gmx_fexist(opt2fn("-s",nfile,fnm)))
1545 gmx_fatal(FARGS, "File %s not found.", opt2fn("-s",nfile,fnm));
1547 /* Make sure that the checkpoint file is not overwritten by the benchmark runs */
1548 if ( (0 == strcmp(opt2fn("-cpi",nfile,fnm), opt2fn("-cpo",nfile,fnm)) ) && (sim_part > 1) )
1549 gmx_fatal(FARGS, "Checkpoint input and output file must not be identical,\nbecause then the input file might change during the benchmarks.");
1551 /* Make sure that repeats is >= 0 (if == 0, only write tpr files) */
1553 gmx_fatal(FARGS, "Number of repeats < 0!");
1555 /* Check number of nodes */
1557 gmx_fatal(FARGS, "Number of nodes/threads must be a positive integer.");
1559 /* Automatically choose -ntpr if not set */
1566 fprintf(stderr, "Will test %d tpr file%s.\n", *ntprs, *ntprs==1?"":"s");
1571 fprintf(stderr, "Note: Choose ntpr>1 to shift PME load between real and reciprocal space.\n");
1574 if ( is_equal(*downfac,*upfac) && (*ntprs > 2) && !(fourierspacing > 0.0))
1576 fprintf(stderr, "WARNING: Resetting -ntpr to 2 since both scaling factors are the same.\n"
1577 "Please choose upfac unequal to downfac to test various PME grid settings\n");
1581 /* Check whether max and min fraction are within required values */
1582 if (maxPMEfraction > 0.5 || maxPMEfraction < 0)
1583 gmx_fatal(FARGS, "-max must be between 0 and 0.5");
1584 if (minPMEfraction > 0.5 || minPMEfraction < 0)
1585 gmx_fatal(FARGS, "-min must be between 0 and 0.5");
1586 if (maxPMEfraction < minPMEfraction)
1587 gmx_fatal(FARGS, "-max must be larger or equal to -min");
1589 /* Check whether the number of steps - if it was set - has a reasonable value */
1590 if (bench_nsteps < 0)
1591 gmx_fatal(FARGS, "Number of steps must be positive.");
1593 if (bench_nsteps > 10000 || bench_nsteps < 100)
1595 fprintf(stderr, "WARNING: steps=");
1596 fprintf(stderr, gmx_large_int_pfmt, bench_nsteps);
1597 fprintf(stderr, ". Are you sure you want to perform so %s steps for each benchmark?\n", (bench_nsteps < 100)? "few" : "many");
1602 gmx_fatal(FARGS, "Cannot have a negative number of presteps.\n");
1605 if (*upfac <= 0.0 || *downfac <= 0.0 || *downfac > *upfac)
1606 gmx_fatal(FARGS, "Both scaling factors must be larger than zero and upper\n"
1607 "scaling limit (%f) must be larger than lower limit (%f).",
1610 if (*downfac < 0.75 || *upfac > 1.25)
1611 fprintf(stderr, "WARNING: Applying extreme scaling factor. I hope you know what you are doing.\n");
1613 if (fourierspacing < 0)
1614 gmx_fatal(FARGS, "Please choose a positive value for fourierspacing.");
1616 /* Make shure that the scaling factor options are compatible with the number of tprs */
1617 if ( (*ntprs < 3) && ( opt2parg_bSet("-upfac",npargs,pa) || opt2parg_bSet("-downfac",npargs,pa) ) )
1619 if (opt2parg_bSet("-upfac",npargs,pa) && opt2parg_bSet("-downfac",npargs,pa) && !is_equal(*upfac,*downfac))
1621 fprintf(stderr, "NOTE: Specify -ntpr > 2 for both scaling factors to take effect.\n"
1622 "(upfac=%f, downfac=%f)\n", *upfac, *downfac);
1624 if (opt2parg_bSet("-upfac",npargs,pa))
1626 if (opt2parg_bSet("-downfac",npargs,pa))
1629 if ( (2 == *ntprs) && (opt2parg_bSet("-downfac",npargs,pa)) && !is_equal(*downfac, 1.0))
1636 /* Returns TRUE when "opt" is a switch for g_tune_pme itself */
1637 static gmx_bool is_main_switch(char *opt)
1639 if ( (0 == strcmp(opt,"-s" ))
1640 || (0 == strcmp(opt,"-p" ))
1641 || (0 == strcmp(opt,"-launch" ))
1642 || (0 == strcmp(opt,"-r" ))
1643 || (0 == strcmp(opt,"-ntpr" ))
1644 || (0 == strcmp(opt,"-max" ))
1645 || (0 == strcmp(opt,"-min" ))
1646 || (0 == strcmp(opt,"-upfac" ))
1647 || (0 == strcmp(opt,"-downfac" ))
1648 || (0 == strcmp(opt,"-four" ))
1649 || (0 == strcmp(opt,"-steps" ))
1650 || (0 == strcmp(opt,"-simsteps" ))
1651 || (0 == strcmp(opt,"-resetstep"))
1652 || (0 == strcmp(opt,"-so" ))
1653 || (0 == strcmp(opt,"-npstring" ))
1654 || (0 == strcmp(opt,"-npme" ))
1655 || (0 == strcmp(opt,"-passall" )) )
1662 /* Returns TRUE when "opt" is needed at launch time */
1663 static gmx_bool is_launch_option(char *opt, gmx_bool bSet)
1672 /* Returns TRUE when "opt" is needed at launch time */
1673 static gmx_bool is_launch_file(char *opt, gmx_bool bSet)
1675 /* We need all options that were set on the command line
1676 * and that do not start with -b */
1677 if (0 == strncmp(opt,"-b", 2))
1687 /* Returns TRUE when "opt" gives an option needed for the benchmarks runs */
1688 static gmx_bool is_bench_option(char *opt, gmx_bool bSet)
1690 /* If option is set, we might need it for the benchmarks.
1691 * This includes -cpi */
1694 if ( (0 == strcmp(opt, "-append" ))
1695 || (0 == strcmp(opt, "-maxh" ))
1696 || (0 == strcmp(opt, "-deffnm" ))
1697 || (0 == strcmp(opt, "-resethway"))
1698 || (0 == strcmp(opt, "-cpnum" )) )
1708 /* Returns TRUE when "opt" defines a file which is needed for the benchmarks runs */
1709 static gmx_bool is_bench_file(char *opt, gmx_bool bSet, gmx_bool bOptional, gmx_bool bIsOutput)
1711 /* All options starting with "-b" are for _b_enchmark files exclusively */
1712 if (0 == strncmp(opt,"-b", 2))
1714 if (!bOptional || bSet)
1724 if (bSet) /* These are additional input files like -cpi -ei */
1732 /* Adds 'buf' to 'str' */
1733 static void add_to_string(char **str, char *buf)
1738 len = strlen(*str) + strlen(buf) + 1;
1744 /* Create the command line for the benchmark as well as for the real run */
1745 static void create_command_line_snippets(
1752 const char *procstring, /* How to pass the number of processors to $MPIRUN */
1753 char *cmd_np[], /* Actual command line snippet, e.g. '-np <N>' */
1754 char *cmd_args_bench[], /* command line arguments for benchmark runs */
1755 char *cmd_args_launch[], /* command line arguments for simulation run */
1756 char extra_args[]) /* Add this to the end of the command line */
1762 #define BUFLENGTH 255
1763 char buf[BUFLENGTH];
1764 char strbuf[BUFLENGTH];
1765 char strbuf2[BUFLENGTH];
1769 np_or_nt=strdup("-nt");
1771 np_or_nt=strdup("-np");
1773 /* strlen needs at least '\0' as a string: */
1774 snew(*cmd_args_bench ,1);
1775 snew(*cmd_args_launch,1);
1776 *cmd_args_launch[0]='\0';
1777 *cmd_args_bench[0] ='\0';
1780 /*******************************************/
1781 /* 1. Process other command line arguments */
1782 /*******************************************/
1783 for (i=0; i<npargs; i++)
1785 /* What command line switch are we currently processing: */
1786 opt = (char *)pa[i].option;
1787 /* Skip options not meant for mdrun */
1788 if (!is_main_switch(opt))
1790 /* Print it to a string buffer, strip away trailing whitespaces that pa_val also returns: */
1791 sprintf(strbuf2, "%s", pa_val(&pa[i],buf,BUFLENGTH));
1793 sprintf(strbuf, "%s %s ", opt, strbuf2);
1794 /* We need the -np (or -nt) switch in a separate buffer - whether or not it was set! */
1795 if (0 == strcmp(opt,np_or_nt))
1797 if (strcmp(procstring, "none")==0 && !bThreads)
1799 /* Omit -np <N> entirely */
1801 sprintf(*cmd_np, " ");
1805 /* This is the normal case with -np <N> */
1806 snew(*cmd_np, strlen(procstring)+strlen(strbuf2)+4);
1807 sprintf(*cmd_np, " %s %s ", bThreads? "-nt" : procstring, strbuf2);
1812 if (is_bench_option(opt,pa[i].bSet))
1813 add_to_string(cmd_args_bench, strbuf);
1815 if (is_launch_option(opt,pa[i].bSet))
1816 add_to_string(cmd_args_launch, strbuf);
1822 /* Add equilibration steps to benchmark options */
1823 sprintf(strbuf, "-resetstep %d ", presteps);
1824 add_to_string(cmd_args_bench, strbuf);
1827 /********************/
1828 /* 2. Process files */
1829 /********************/
1830 for (i=0; i<nfile; i++)
1832 opt = (char *)fnm[i].opt;
1833 name = opt2fn(opt,nfile,fnm);
1835 /* Strbuf contains the options, now let's sort out where we need that */
1836 sprintf(strbuf, "%s %s ", opt, name);
1838 /* Skip options not meant for mdrun */
1839 if (!is_main_switch(opt))
1842 if ( is_bench_file(opt, opt2bSet(opt,nfile,fnm), is_optional(&fnm[i]), is_output(&fnm[i])) )
1844 /* All options starting with -b* need the 'b' removed,
1845 * therefore overwrite strbuf */
1846 if (0 == strncmp(opt, "-b", 2))
1847 sprintf(strbuf, "-%s %s ", &opt[2], name);
1849 add_to_string(cmd_args_bench, strbuf);
1852 if ( is_launch_file(opt,opt2bSet(opt,nfile,fnm)) )
1853 add_to_string(cmd_args_launch, strbuf);
1857 add_to_string(cmd_args_bench , extra_args);
1858 add_to_string(cmd_args_launch, extra_args);
1863 /* Set option opt */
1864 static void setopt(const char *opt,int nfile,t_filenm fnm[])
1868 for(i=0; (i<nfile); i++)
1869 if (strcmp(opt,fnm[i].opt)==0)
1870 fnm[i].flag |= ffSET;
1874 static void couple_files_options(int nfile, t_filenm fnm[])
1877 gmx_bool bSet,bBench;
1882 for (i=0; i<nfile; i++)
1884 opt = (char *)fnm[i].opt;
1885 bSet = ((fnm[i].flag & ffSET) != 0);
1886 bBench = (0 == strncmp(opt,"-b", 2));
1888 /* Check optional files */
1889 /* If e.g. -eo is set, then -beo also needs to be set */
1890 if (is_optional(&fnm[i]) && bSet && !bBench)
1892 sprintf(buf, "-b%s", &opt[1]);
1893 setopt(buf,nfile,fnm);
1895 /* If -beo is set, then -eo also needs to be! */
1896 if (is_optional(&fnm[i]) && bSet && bBench)
1898 sprintf(buf, "-%s", &opt[2]);
1899 setopt(buf,nfile,fnm);
1905 static double gettime()
1907 #ifdef HAVE_GETTIMEOFDAY
1909 struct timezone tz = { 0,0 };
1912 gettimeofday(&t,&tz);
1914 seconds = (double) t.tv_sec + 1e-6*(double)t.tv_usec;
1920 seconds = time(NULL);
1927 #define BENCHSTEPS (1000)
1929 int gmx_tune_pme(int argc,char *argv[])
1931 const char *desc[] = {
1932 "For a given number [TT]-np[tt] or [TT]-nt[tt] of processors/threads, this program systematically",
1933 "times mdrun with various numbers of PME-only nodes and determines",
1934 "which setting is fastest. It will also test whether performance can",
1935 "be enhanced by shifting load from the reciprocal to the real space",
1936 "part of the Ewald sum. ",
1937 "Simply pass your [TT].tpr[tt] file to g_tune_pme together with other options",
1938 "for mdrun as needed.[PAR]",
1939 "Which executables are used can be set in the environment variables",
1940 "MPIRUN and MDRUN. If these are not present, 'mpirun' and 'mdrun'",
1941 "will be used as defaults. Note that for certain MPI frameworks you",
1942 "need to provide a machine- or hostfile. This can also be passed",
1943 "via the MPIRUN variable, e.g.",
1944 "'export MPIRUN=\"/usr/local/mpirun -machinefile hosts\"'[PAR]",
1945 "Please call g_tune_pme with the normal options you would pass to",
1946 "mdrun and add [TT]-np[tt] for the number of processors to perform the",
1947 "tests on, or [TT]-nt[tt] for the number of threads. You can also add [TT]-r[tt]",
1948 "to repeat each test several times to get better statistics. [PAR]",
1949 "g_tune_pme can test various real space / reciprocal space workloads",
1950 "for you. With [TT]-ntpr[tt] you control how many extra [TT].tpr[tt] files will be",
1951 "written with enlarged cutoffs and smaller fourier grids respectively.",
1952 "Typically, the first test (no. 0) will be with the settings from the input",
1953 "[TT].tpr[tt] file; the last test (no. [TT]ntpr[tt]) will have cutoffs multiplied",
1954 "by (and at the same time fourier grid dimensions divided by) the scaling",
1955 "factor [TT]-fac[tt] (default 1.2). The remaining [TT].tpr[tt] files will have equally",
1956 "spaced values inbetween these extremes. Note that you can set [TT]-ntpr[tt] to 1",
1957 "if you just want to find the optimal number of PME-only nodes; in that case",
1958 "your input [TT].tpr[tt] file will remain unchanged.[PAR]",
1959 "For the benchmark runs, the default of 1000 time steps should suffice for most",
1960 "MD systems. The dynamic load balancing needs about 100 time steps",
1961 "to adapt to local load imbalances, therefore the time step counters",
1962 "are by default reset after 100 steps. For large systems",
1963 "(>1M atoms) you may have to set [TT]-resetstep[tt] to a higher value.",
1964 "From the 'DD' load imbalance entries in the md.log output file you",
1965 "can tell after how many steps the load is sufficiently balanced.[PAR]"
1966 "Example call: [TT]g_tune_pme -np 64 -s protein.tpr -launch[tt][PAR]",
1967 "After calling mdrun several times, detailed performance information",
1968 "is available in the output file perf.out. ",
1969 "Note that during the benchmarks a couple of temporary files are written",
1970 "(options -b*), these will be automatically deleted after each test.[PAR]",
1971 "If you want the simulation to be started automatically with the",
1972 "optimized parameters, use the command line option [TT]-launch[tt].[PAR]",
1977 int pmeentries=0; /* How many values for -npme do we actually test for each tpr file */
1978 real maxPMEfraction=0.50;
1979 real minPMEfraction=0.25;
1980 int maxPMEnodes, minPMEnodes;
1981 real downfac=1.0,upfac=1.2;
1983 real fs=0.0; /* 0 indicates: not set by the user */
1984 gmx_large_int_t bench_nsteps=BENCHSTEPS;
1985 gmx_large_int_t new_sim_nsteps=-1; /* -1 indicates: not set by the user */
1986 gmx_large_int_t cpt_steps=0; /* Step counter in .cpt input file */
1987 int presteps=100; /* Do a full cycle reset after presteps steps */
1988 gmx_bool bOverwrite=FALSE, bKeepTPR;
1989 gmx_bool bLaunch=FALSE;
1990 gmx_bool bPassAll=FALSE;
1991 char *ExtraArgs=NULL;
1992 char **tpr_names=NULL;
1993 const char *simulation_tpr=NULL;
1994 int best_npme, best_tpr;
1995 int sim_part = 1; /* For benchmarks with checkpoint files */
1997 /* Default program names if nothing else is found */
1998 char *cmd_mpirun=NULL, *cmd_mdrun=NULL;
1999 char *cmd_args_bench, *cmd_args_launch;
2002 t_perf **perfdata=NULL;
2008 /* Print out how long the tuning took */
2011 static t_filenm fnm[] = {
2013 { efOUT, "-p", "perf", ffWRITE },
2014 { efLOG, "-err", "errors", ffWRITE },
2015 { efTPX, "-so", "tuned", ffWRITE },
2017 { efTPX, NULL, NULL, ffREAD },
2018 { efTRN, "-o", NULL, ffWRITE },
2019 { efXTC, "-x", NULL, ffOPTWR },
2020 { efCPT, "-cpi", NULL, ffOPTRD },
2021 { efCPT, "-cpo", NULL, ffOPTWR },
2022 { efSTO, "-c", "confout", ffWRITE },
2023 { efEDR, "-e", "ener", ffWRITE },
2024 { efLOG, "-g", "md", ffWRITE },
2025 { efXVG, "-dhdl", "dhdl", ffOPTWR },
2026 { efXVG, "-field", "field", ffOPTWR },
2027 { efXVG, "-table", "table", ffOPTRD },
2028 { efXVG, "-tablep", "tablep", ffOPTRD },
2029 { efXVG, "-tableb", "table", ffOPTRD },
2030 { efTRX, "-rerun", "rerun", ffOPTRD },
2031 { efXVG, "-tpi", "tpi", ffOPTWR },
2032 { efXVG, "-tpid", "tpidist", ffOPTWR },
2033 { efEDI, "-ei", "sam", ffOPTRD },
2034 { efEDO, "-eo", "sam", ffOPTWR },
2035 { efGCT, "-j", "wham", ffOPTRD },
2036 { efGCT, "-jo", "bam", ffOPTWR },
2037 { efXVG, "-ffout", "gct", ffOPTWR },
2038 { efXVG, "-devout", "deviatie", ffOPTWR },
2039 { efXVG, "-runav", "runaver", ffOPTWR },
2040 { efXVG, "-px", "pullx", ffOPTWR },
2041 { efXVG, "-pf", "pullf", ffOPTWR },
2042 { efMTX, "-mtx", "nm", ffOPTWR },
2043 { efNDX, "-dn", "dipole", ffOPTWR },
2044 /* Output files that are deleted after each benchmark run */
2045 { efTRN, "-bo", "bench", ffWRITE },
2046 { efXTC, "-bx", "bench", ffWRITE },
2047 { efCPT, "-bcpo", "bench", ffWRITE },
2048 { efSTO, "-bc", "bench", ffWRITE },
2049 { efEDR, "-be", "bench", ffWRITE },
2050 { efLOG, "-bg", "bench", ffWRITE },
2051 { efEDO, "-beo", "bench", ffOPTWR },
2052 { efXVG, "-bdhdl", "benchdhdl",ffOPTWR },
2053 { efXVG, "-bfield", "benchfld" ,ffOPTWR },
2054 { efXVG, "-btpi", "benchtpi", ffOPTWR },
2055 { efXVG, "-btpid", "benchtpid",ffOPTWR },
2056 { efGCT, "-bjo", "bench", ffOPTWR },
2057 { efXVG, "-bffout", "benchgct", ffOPTWR },
2058 { efXVG, "-bdevout","benchdev", ffOPTWR },
2059 { efXVG, "-brunav", "benchrnav",ffOPTWR },
2060 { efXVG, "-bpx", "benchpx", ffOPTWR },
2061 { efXVG, "-bpf", "benchpf", ffOPTWR },
2062 { efMTX, "-bmtx", "benchn", ffOPTWR },
2063 { efNDX, "-bdn", "bench", ffOPTWR }
2066 /* Command line options of mdrun */
2067 gmx_bool bDDBondCheck = TRUE;
2068 gmx_bool bDDBondComm = TRUE;
2069 gmx_bool bVerbose = FALSE;
2070 gmx_bool bCompact = TRUE;
2071 gmx_bool bSepPot = FALSE;
2072 gmx_bool bRerunVSite = FALSE;
2073 gmx_bool bIonize = FALSE;
2074 gmx_bool bConfout = TRUE;
2075 gmx_bool bReproducible = FALSE;
2076 gmx_bool bThreads = FALSE;
2079 int nstglobalcomm=-1;
2081 int repl_ex_seed=-1;
2085 const char *ddno_opt[ddnoNR+1] =
2086 { NULL, "interleave", "pp_pme", "cartesian", NULL };
2087 const char *dddlb_opt[] =
2088 { NULL, "auto", "no", "yes", NULL };
2089 const char *procstring[] =
2090 { NULL, "-np", "-n", "none", NULL };
2091 const char *npmevalues_opt[] =
2092 { NULL, "auto", "all", "subset", NULL };
2093 real rdd=0.0,rconstr=0.0,dlb_scale=0.8,pforce=-1;
2094 char *ddcsx=NULL,*ddcsy=NULL,*ddcsz=NULL;
2096 #define STD_CPT_PERIOD (15.0)
2097 real cpt_period=STD_CPT_PERIOD,max_hours=-1;
2098 gmx_bool bAppendFiles=TRUE;
2099 gmx_bool bKeepAndNumCPT=FALSE;
2100 gmx_bool bResetCountersHalfWay=FALSE;
2101 output_env_t oenv=NULL;
2104 /***********************/
2105 /* g_tune_pme options: */
2106 /***********************/
2107 { "-np", FALSE, etINT, {&nnodes},
2108 "Number of nodes to run the tests on (must be > 2 for separate PME nodes)" },
2109 { "-npstring", FALSE, etENUM, {procstring},
2110 "Specify the number of processors to $MPIRUN using this string"},
2111 { "-passall", FALSE, etBOOL, {&bPassAll},
2112 "HIDDENPut arguments unknown to mdrun at the end of the command line. Can e.g. be used for debugging purposes. "},
2113 { "-nt", FALSE, etINT, {&nthreads},
2114 "Number of threads to run the tests on (turns MPI & mpirun off)"},
2115 { "-r", FALSE, etINT, {&repeats},
2116 "Repeat each test this often" },
2117 { "-max", FALSE, etREAL, {&maxPMEfraction},
2118 "Max fraction of PME nodes to test with" },
2119 { "-min", FALSE, etREAL, {&minPMEfraction},
2120 "Min fraction of PME nodes to test with" },
2121 { "-npme", FALSE, etENUM, {npmevalues_opt},
2122 "Benchmark all possible values for -npme or just the subset that is expected to perform well"},
2123 { "-upfac", FALSE, etREAL, {&upfac},
2124 "Upper limit for rcoulomb scaling factor (Note that rcoulomb upscaling results in fourier grid downscaling)" },
2125 { "-downfac", FALSE, etREAL, {&downfac},
2126 "Lower limit for rcoulomb scaling factor" },
2127 { "-ntpr", FALSE, etINT, {&ntprs},
2128 "Number of tpr files to benchmark. Create these many files with scaling factors ranging from 1.0 to fac. If < 1, automatically choose the number of tpr files to test" },
2129 { "-four", FALSE, etREAL, {&fs},
2130 "Use this fourierspacing value instead of the grid found in the tpr input file. (Spacing applies to a scaling factor of 1.0 if multiple tpr files are written)" },
2131 { "-steps", FALSE, etGMX_LARGE_INT, {&bench_nsteps},
2132 "Take timings for these many steps in the benchmark runs" },
2133 { "-resetstep",FALSE, etINT, {&presteps},
2134 "Let dlb equilibrate these many steps before timings are taken (reset cycle counters after these many steps)" },
2135 { "-simsteps", FALSE, etGMX_LARGE_INT, {&new_sim_nsteps},
2136 "If non-negative, perform these many steps in the real run (overwrite nsteps from tpr, add cpt steps)" },
2137 { "-launch", FALSE, etBOOL, {&bLaunch},
2138 "Lauch the real simulation after optimization" },
2139 /******************/
2140 /* mdrun options: */
2141 /******************/
2142 { "-deffnm", FALSE, etSTR, {&deffnm},
2143 "Set the default filename for all file options at launch time" },
2144 { "-ddorder", FALSE, etENUM, {ddno_opt},
2146 { "-ddcheck", FALSE, etBOOL, {&bDDBondCheck},
2147 "Check for all bonded interactions with DD" },
2148 { "-ddbondcomm",FALSE, etBOOL, {&bDDBondComm},
2149 "HIDDENUse special bonded atom communication when -rdd > cut-off" },
2150 { "-rdd", FALSE, etREAL, {&rdd},
2151 "The maximum distance for bonded interactions with DD (nm), 0 is determine from initial coordinates" },
2152 { "-rcon", FALSE, etREAL, {&rconstr},
2153 "Maximum distance for P-LINCS (nm), 0 is estimate" },
2154 { "-dlb", FALSE, etENUM, {dddlb_opt},
2155 "Dynamic load balancing (with DD)" },
2156 { "-dds", FALSE, etREAL, {&dlb_scale},
2157 "Minimum allowed dlb scaling of the DD cell size" },
2158 { "-ddcsx", FALSE, etSTR, {&ddcsx},
2159 "HIDDENThe DD cell sizes in x" },
2160 { "-ddcsy", FALSE, etSTR, {&ddcsy},
2161 "HIDDENThe DD cell sizes in y" },
2162 { "-ddcsz", FALSE, etSTR, {&ddcsz},
2163 "HIDDENThe DD cell sizes in z" },
2164 { "-gcom", FALSE, etINT, {&nstglobalcomm},
2165 "Global communication frequency" },
2166 { "-v", FALSE, etBOOL, {&bVerbose},
2167 "Be loud and noisy" },
2168 { "-compact", FALSE, etBOOL, {&bCompact},
2169 "Write a compact log file" },
2170 { "-seppot", FALSE, etBOOL, {&bSepPot},
2171 "Write separate V and dVdl terms for each interaction type and node to the log file(s)" },
2172 { "-pforce", FALSE, etREAL, {&pforce},
2173 "Print all forces larger than this (kJ/mol nm)" },
2174 { "-reprod", FALSE, etBOOL, {&bReproducible},
2175 "Try to avoid optimizations that affect binary reproducibility" },
2176 { "-cpt", FALSE, etREAL, {&cpt_period},
2177 "Checkpoint interval (minutes)" },
2178 { "-cpnum", FALSE, etBOOL, {&bKeepAndNumCPT},
2179 "Keep and number checkpoint files" },
2180 { "-append", FALSE, etBOOL, {&bAppendFiles},
2181 "Append to previous output files when continuing from checkpoint instead of adding the simulation part number to all file names (for launch only)" },
2182 { "-maxh", FALSE, etREAL, {&max_hours},
2183 "Terminate after 0.99 times this time (hours)" },
2184 { "-multi", FALSE, etINT, {&nmultisim},
2185 "Do multiple simulations in parallel" },
2186 { "-replex", FALSE, etINT, {&repl_ex_nst},
2187 "Attempt replica exchange every # steps" },
2188 { "-reseed", FALSE, etINT, {&repl_ex_seed},
2189 "Seed for replica exchange, -1 is generate a seed" },
2190 { "-rerunvsite", FALSE, etBOOL, {&bRerunVSite},
2191 "HIDDENRecalculate virtual site coordinates with -rerun" },
2192 { "-ionize", FALSE, etBOOL, {&bIonize},
2193 "Do a simulation including the effect of an X-Ray bombardment on your system" },
2194 { "-confout", FALSE, etBOOL, {&bConfout},
2195 "HIDDENWrite the last configuration with -c and force checkpointing at the last step" },
2196 { "-stepout", FALSE, etINT, {&nstepout},
2197 "HIDDENFrequency of writing the remaining runtime" },
2198 { "-resethway", FALSE, etBOOL, {&bResetCountersHalfWay},
2199 "HIDDENReset the cycle counters after half the number of steps or halfway -maxh (launch only)" }
2203 #define NFILE asize(fnm)
2205 CopyRight(stderr,argv[0]);
2207 seconds = gettime();
2209 parse_common_args(&argc,argv,PCA_NOEXIT_ON_ARGS,
2210 NFILE,fnm,asize(pa),pa,asize(desc),desc,
2213 /* Store the remaining unparsed command line entries in a string */
2215 ExtraArgs[0] = '\0';
2216 for (i=1; i<argc; i++) /* argc will now be 1 if everything was understood */
2218 add_to_string(&ExtraArgs, argv[i]);
2219 add_to_string(&ExtraArgs, " ");
2221 if ( !bPassAll && (ExtraArgs[0] != '\0') )
2223 fprintf(stderr, "\nWARNING: The following arguments you provided have no effect:\n"
2225 "Use the -passall option to force them to appear on the command lines\n"
2226 "for the benchmark simulations%s.\n\n",
2227 ExtraArgs, bLaunch? " and at launch time" : "");
2230 if (opt2parg_bSet("-nt",asize(pa),pa))
2233 if (opt2parg_bSet("-npstring",asize(pa),pa))
2234 fprintf(stderr, "WARNING: -npstring has no effect when using threads.\n");
2237 gmx_fatal(FARGS, "Can't run multi-threaded MPI simulation yet!");
2238 /* and now we just set this; a bit of an ugly hack*/
2241 /* Automatically set -beo options if -eo is set etc. */
2242 couple_files_options(NFILE,fnm);
2244 /* Construct the command line arguments for benchmark runs
2245 * as well as for the simulation run
2247 create_command_line_snippets(bThreads,presteps,NFILE,fnm,asize(pa),pa,procstring[0],
2248 &cmd_np, &cmd_args_bench, &cmd_args_launch,
2249 bPassAll? ExtraArgs : (char *)"");
2251 /* Read in checkpoint file if requested */
2253 if(opt2bSet("-cpi",NFILE,fnm))
2256 cr->duty=DUTY_PP; /* makes the following routine happy */
2257 read_checkpoint_simulation_part(opt2fn("-cpi",NFILE,fnm),
2258 &sim_part,&cpt_steps,cr,
2259 FALSE,NFILE,fnm,NULL,NULL);
2262 /* sim_part will now be 1 if no checkpoint file was found */
2264 gmx_fatal(FARGS, "Checkpoint file %s not found!", opt2fn("-cpi",
2269 /* Open performance output file and write header info */
2270 fp = ffopen(opt2fn("-p",NFILE,fnm),"w");
2272 /* Make a quick consistency check of command line parameters */
2273 check_input(nnodes, repeats, &ntprs, &upfac, &downfac, maxPMEfraction,
2274 minPMEfraction, fs, bench_nsteps, fnm, NFILE, sim_part, presteps,
2277 /* Determine max and min number of PME nodes to test: */
2280 maxPMEnodes = floor(maxPMEfraction*nnodes);
2281 minPMEnodes = max(floor(minPMEfraction*nnodes), 0);
2282 fprintf(stdout, "Will try runs with %d ", minPMEnodes);
2283 if (maxPMEnodes != minPMEnodes)
2284 fprintf(stdout, "- %d ", maxPMEnodes);
2285 fprintf(stdout, "PME-only nodes.\n Note that the automatic number of PME-only nodes and no separate PME nodes are always tested.\n");
2293 /* Get the commands we need to set up the runs from environment variables */
2294 get_program_paths(bThreads, &cmd_mpirun, cmd_np, &cmd_mdrun, repeats);
2296 /* Print some header info to file */
2298 fprintf(fp, "\n P E R F O R M A N C E R E S U L T S\n");
2300 fprintf(fp, "%s for Gromacs %s\n", ShortProgram(),GromacsVersion());
2303 fprintf(fp, "Number of nodes : %d\n", nnodes);
2304 fprintf(fp, "The mpirun command is : %s\n", cmd_mpirun);
2305 if ( strcmp(procstring[0], "none") != 0)
2306 fprintf(fp, "Passing # of nodes via : %s\n", procstring[0]);
2308 fprintf(fp, "Not setting number of nodes in system call\n");
2311 fprintf(fp, "Number of threads : %d\n", nnodes);
2313 fprintf(fp, "The mdrun command is : %s\n", cmd_mdrun);
2314 fprintf(fp, "mdrun args benchmarks : %s\n", cmd_args_bench);
2315 fprintf(fp, "Benchmark steps : ");
2316 fprintf(fp, gmx_large_int_pfmt, bench_nsteps);
2318 fprintf(fp, "dlb equilibration steps : %d\n", presteps);
2321 fprintf(fp, "Checkpoint time step : ");
2322 fprintf(fp, gmx_large_int_pfmt, cpt_steps);
2326 fprintf(fp, "mdrun args at launchtime: %s\n", cmd_args_launch);
2327 if (!bPassAll && ExtraArgs[0] != '\0')
2328 fprintf(fp, "Unused arguments : %s\n", ExtraArgs);
2329 if (new_sim_nsteps >= 0)
2332 fprintf(stderr, "Note: Simulation input file %s will have ", opt2fn("-so",NFILE,fnm));
2333 fprintf(stderr, gmx_large_int_pfmt, new_sim_nsteps+cpt_steps);
2334 fprintf(stderr, " steps.\n");
2335 fprintf(fp, "Simulation steps : ");
2336 fprintf(fp, gmx_large_int_pfmt, new_sim_nsteps);
2340 fprintf(fp, "Repeats for each test : %d\n", repeats);
2344 fprintf(fp, "Requested grid spacing : %f (This will be the grid spacing at a scaling factor of 1.0)\n", fs);
2347 fprintf(fp, "Input file : %s\n", opt2fn("-s",NFILE,fnm));
2349 /* Allocate memory for the inputinfo struct: */
2351 info->nr_inputfiles = ntprs;
2352 for (i=0; i<ntprs; i++)
2354 snew(info->rcoulomb , ntprs);
2355 snew(info->rvdw , ntprs);
2356 snew(info->rlist , ntprs);
2357 snew(info->rlistlong, ntprs);
2358 snew(info->nkx , ntprs);
2359 snew(info->nky , ntprs);
2360 snew(info->nkz , ntprs);
2361 snew(info->fsx , ntprs);
2362 snew(info->fsy , ntprs);
2363 snew(info->fsz , ntprs);
2365 /* Make alternative tpr files to test: */
2366 snew(tpr_names, ntprs);
2367 for (i=0; i<ntprs; i++)
2368 snew(tpr_names[i], STRLEN);
2370 make_benchmark_tprs(opt2fn("-s",NFILE,fnm), tpr_names, bench_nsteps+presteps,
2371 cpt_steps, upfac, downfac, ntprs, fs, info, fp);
2374 /********************************************************************************/
2375 /* Main loop over all scenarios we need to test: tpr files, PME nodes, repeats */
2376 /********************************************************************************/
2377 snew(perfdata, ntprs);
2378 do_the_tests(fp, tpr_names, maxPMEnodes, minPMEnodes, npmevalues_opt[0], perfdata, &pmeentries,
2379 repeats, nnodes, ntprs, bThreads, cmd_mpirun, cmd_np, cmd_mdrun,
2380 cmd_args_bench, fnm, NFILE, sim_part, presteps, cpt_steps);
2382 fprintf(fp, "\nTuning took%8.1f minutes.\n", (gettime()-seconds)/60.0);
2384 /* Analyse the results and give a suggestion for optimal settings: */
2385 bKeepTPR = analyze_data(fp, opt2fn("-p", NFILE, fnm), perfdata, nnodes, ntprs, pmeentries,
2386 repeats, info, &best_tpr, &best_npme);
2388 /* Take the best-performing tpr file and enlarge nsteps to original value */
2389 if ( bKeepTPR && !bOverwrite && !(fs > 0.0) )
2391 simulation_tpr = opt2fn("-s",NFILE,fnm);
2395 simulation_tpr = opt2fn("-so",NFILE,fnm);
2396 modify_PMEsettings(bOverwrite? (new_sim_nsteps+cpt_steps) :
2397 info->orig_sim_steps, tpr_names[best_tpr],
2401 /* Now start the real simulation if the user requested it ... */
2402 launch_simulation(bLaunch, fp, bThreads, cmd_mpirun, cmd_np, cmd_mdrun,
2403 cmd_args_launch, simulation_tpr, nnodes, best_npme);
2406 /* ... or simply print the performance results to screen: */
2408 finalize(opt2fn("-p", NFILE, fnm));