main.c 34.9 KB
Newer Older
1
/*******************************************************************************
2
 * This file is part of SWIFT.
3
 * Copyright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk),
4
 *                    Matthieu Schaller (matthieu.schaller@durham.ac.uk)
5
 *               2015 Peter W. Draper (p.w.draper@durham.ac.uk)
6
7
8
 *                    Angus Lepper (angus.lepper@ed.ac.uk)
 *               2016 John A. Regan (john.a.regan@durham.ac.uk)
 *                    Tom Theuns (tom.theuns@durham.ac.uk)
9
 *
10
11
12
13
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published
 * by the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
14
 *
15
16
17
18
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
19
 *
20
21
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22
 *
23
24
 ******************************************************************************/

Pedro Gonnet's avatar
Pedro Gonnet committed
25
26
/* Config parameters. */
#include "../config.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
27
28

/* Some standard headers. */
29
#include <errno.h>
30
#include <fenv.h>
31
#include <libgen.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
32
33
34
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
35
#include <sys/stat.h>
36
#include <unistd.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
37

38
39
/* MPI headers. */
#ifdef WITH_MPI
40
#include <mpi.h>
41
42
#endif

Pedro Gonnet's avatar
Pedro Gonnet committed
43
/* Local headers. */
44
#include "swift.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
45

46
47
/* Engine policy flags. */
#ifndef ENGINE_POLICY
48
#define ENGINE_POLICY engine_policy_none
49
50
#endif

James Willis's avatar
James Willis committed
51
52
53
/* Global profiler. */
struct profiler prof;

54
55
56
/**
 * @brief Help messages for the command line parameters.
 */
57
58
void print_help_message() {

Matthieu Schaller's avatar
Matthieu Schaller committed
59
  printf("\nUsage: swift [OPTION]... PARAMFILE\n");
60
  printf("       swift_mpi [OPTION]... PARAMFILE\n\n");
61

62
  printf("Valid options are:\n");
63
64
65
66
  printf("  %2s %14s %s\n", "-a", "", "Pin runners using processor affinity.");
  printf("  %2s %14s %s\n", "-c", "",
         "Run with cosmological time integration.");
  printf("  %2s %14s %s\n", "-C", "", "Run with cooling.");
67
  printf(
68
      "  %2s %14s %s\n", "-d", "",
69
70
      "Dry run. Read the parameter file, allocate memory but does not read ");
  printf(
71
      "  %2s %14s %s\n", "", "",
72
      "the particles from ICs and exit before the start of time integration.");
73
  printf("  %2s %14s %s\n", "", "",
74
75
         "Allows user to check validy of parameter and IC files as well as "
         "memory limits.");
76
  printf("  %2s %14s %s\n", "-D", "",
77
78
         "Always drift all particles even the ones far from active particles. "
         "This emulates");
79
  printf("  %2s %14s %s\n", "", "",
80
         "Gadget-[23] and GIZMO's default behaviours.");
81
  printf("  %2s %14s %s\n", "-e", "",
82
         "Enable floating-point exceptions (debugging mode).");
83
  printf("  %2s %14s %s\n", "-f", "{int}",
84
         "Overwrite the CPU frequency (Hz) to be used for time measurements.");
85
  printf("  %2s %14s %s\n", "-g", "",
86
         "Run with an external gravitational potential.");
87
88
  printf("  %2s %14s %s\n", "-G", "", "Run with self-gravity.");
  printf("  %2s %14s %s\n", "-M", "",
89
         "Reconstruct the multipoles every time-step.");
90
  printf("  %2s %14s %s\n", "-n", "{int}",
91
92
         "Execute a fixed number of time steps. When unset use the time_end "
         "parameter to stop.");
93
94
95
  printf("  %2s %14s %s\n", "-P", "{sec:par:val}",
         "Set parameter value and overwrites values read from the parameters "
         "file. Can be used more than once.");
96
  printf("  %2s %14s %s\n", "-r", "", "Continue using restart files.");
97
98
99
  printf("  %2s %14s %s\n", "-s", "", "Run with hydrodynamics.");
  printf("  %2s %14s %s\n", "-S", "", "Run with stars.");
  printf("  %2s %14s %s\n", "-t", "{int}",
100
101
         "The number of threads to use on each MPI rank. Defaults to 1 if not "
         "specified.");
102
103
104
105
106
  printf("  %2s %14s %s\n", "-T", "", "Print timers every time-step.");
  printf("  %2s %14s %s\n", "-v", "[12]", "Increase the level of verbosity:");
  printf("  %2s %14s %s\n", "", "", "1: MPI-rank 0 writes,");
  printf("  %2s %14s %s\n", "", "", "2: All MPI-ranks write.");
  printf("  %2s %14s %s\n", "-y", "{int}",
107
         "Time-step frequency at which task graphs are dumped.");
108
109
  printf("  %2s %14s %s\n", "-Y", "{int}",
         "Time-step frequency at which threadpool tasks are dumped.");
110
  printf("  %2s %14s %s\n", "-h", "", "Print this help message and exit.");
111
112
113
  printf(
      "\nSee the file parameter_example.yml for an example of "
      "parameter file.\n");
114
115
}

Pedro Gonnet's avatar
Pedro Gonnet committed
116
117
118
119
/**
 * @brief Main routine that loads a few particles and generates some output.
 *
 */
120
121
int main(int argc, char *argv[]) {

122
  struct clocks_time tic, toc;
123
  struct engine e;
124

125
126
127
128
  /* Structs used by the engine. Declare now to make sure these are always in
   * scope.  */
  struct chemistry_data chemistry;
  struct cooling_function_data cooling_func;
129
  struct cosmology cosmo;
130
131
132
133
134
135
136
137
138
139
  struct external_potential potential;
  struct gpart *gparts = NULL;
  struct gravity_props gravity_properties;
  struct hydro_props hydro_properties;
  struct part *parts = NULL;
  struct phys_const prog_const;
  struct sourceterms sourceterms;
  struct space s;
  struct spart *sparts = NULL;
  struct unit_system us;
140

141
  int nr_nodes = 1, myrank = 0;
142

143
#ifdef WITH_MPI
144
  /* Start by initializing MPI. */
145
  int res = 0, prov = 0;
146
147
  if ((res = MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &prov)) !=
      MPI_SUCCESS)
148
149
    error("Call to MPI_Init failed with error %i.", res);
  if (prov != MPI_THREAD_MULTIPLE)
150
    error(
151
152
        "MPI does not provide the level of threading"
        " required (MPI_THREAD_MULTIPLE).");
153
  if ((res = MPI_Comm_size(MPI_COMM_WORLD, &nr_nodes)) != MPI_SUCCESS)
154
155
156
    error("MPI_Comm_size failed with error %i.", res);
  if ((res = MPI_Comm_rank(MPI_COMM_WORLD, &myrank)) != MPI_SUCCESS)
    error("Call to MPI_Comm_rank failed with error %i.", res);
157
158
159
160

  /* Make sure messages are stamped with the correct rank. */
  engine_rank = myrank;

161
162
163
  if ((res = MPI_Comm_set_errhandler(MPI_COMM_WORLD, MPI_ERRORS_RETURN)) !=
      MPI_SUCCESS)
    error("Call to MPI_Comm_set_errhandler failed with error %i.", res);
164
165
  if (myrank == 0)
    printf("[0000] [00000.0] main: MPI is up and running with %i node(s).\n\n",
Peter W. Draper's avatar
Peter W. Draper committed
166
           nr_nodes);
167
168
169
170
  if (nr_nodes == 1) {
    message("WARNING: you are running with one MPI rank.");
    message("WARNING: you should use the non-MPI version of this program.");
  }
171
  fflush(stdout);
172

173
#endif
174

175
176
  /* Welcome to SWIFT, you made the right choice */
  if (myrank == 0) greetings();
177

178
  int with_aff = 0;
179
  int dry_run = 0;
180
  int dump_tasks = 0;
181
  int dump_threadpool = 0;
182
  int nsteps = -2;
183
  int restart = 0;
184
185
  int with_cosmology = 0;
  int with_external_gravity = 0;
Tom Theuns's avatar
Tom Theuns committed
186
  int with_sourceterms = 0;
187
  int with_cooling = 0;
188
189
  int with_self_gravity = 0;
  int with_hydro = 0;
190
  int with_stars = 0;
191
  int with_fp_exceptions = 0;
192
  int with_drift_all = 0;
193
  int with_mpole_reconstruction = 0;
194
  int verbose = 0;
195
  int nr_threads = 1;
196
  int with_verbose_timers = 0;
197
198
  int nparams = 0;
  char *cmdparams[PARSER_MAX_NO_OF_PARAMS];
199
  char paramFileName[200] = "";
200
  char restart_file[200] = "";
201
202
203
  unsigned long long cpufreq = 0;

  /* Parse the parameters */
204
  int c;
205
  while ((c = getopt(argc, argv, "acCdDef:FgGhMn:P:rsSt:Tv:y:Y:")) != -1)
206
    switch (c) {
207
      case 'a':
208
#if defined(HAVE_SETAFFINITY) && defined(HAVE_LIBNUMA)
209
        with_aff = 1;
210
211
212
#else
        error("Need NUMA support for thread affinity");
#endif
213
        break;
214
      case 'c':
215
        with_cosmology = 1;
216
        break;
217
218
219
      case 'C':
        with_cooling = 1;
        break;
220
      case 'd':
221
        dry_run = 1;
222
        break;
223
224
225
      case 'D':
        with_drift_all = 1;
        break;
226
      case 'e':
227
#ifdef HAVE_FE_ENABLE_EXCEPT
228
        with_fp_exceptions = 1;
229
230
231
#else
        error("Need support for floating point exception on this platform");
#endif
232
        break;
233
      case 'f':
234
235
236
        if (sscanf(optarg, "%llu", &cpufreq) != 1) {
          if (myrank == 0) printf("Error parsing CPU frequency (-f).\n");
          if (myrank == 0) print_help_message();
237
          return 1;
238
        }
239
        break;
240
241
242
      case 'F':
        with_sourceterms = 1;
        break;
243
      case 'g':
244
        with_external_gravity = 1;
245
        break;
246
247
      case 'G':
        with_self_gravity = 1;
Tom Theuns's avatar
Tom Theuns committed
248
        break;
249
      case 'h':
250
        if (myrank == 0) print_help_message();
251
        return 0;
252
253
254
      case 'M':
        with_mpole_reconstruction = 1;
        break;
255
256
257
258
259
260
261
      case 'n':
        if (sscanf(optarg, "%d", &nsteps) != 1) {
          if (myrank == 0) printf("Error parsing fixed number of steps.\n");
          if (myrank == 0) print_help_message();
          return 1;
        }
        break;
262
263
264
265
      case 'P':
        cmdparams[nparams] = optarg;
        nparams++;
        break;
266
267
268
      case 'r':
        restart = 1;
        break;
269
      case 's':
270
        with_hydro = 1;
271
        break;
272
273
274
      case 'S':
        with_stars = 1;
        break;
275
276
277
278
279
280
281
282
      case 't':
        if (sscanf(optarg, "%d", &nr_threads) != 1) {
          if (myrank == 0)
            printf("Error parsing the number of threads (-t).\n");
          if (myrank == 0) print_help_message();
          return 1;
        }
        break;
283
284
285
      case 'T':
        with_verbose_timers = 1;
        break;
286
      case 'v':
287
288
289
        if (sscanf(optarg, "%d", &verbose) != 1) {
          if (myrank == 0) printf("Error parsing verbosity level (-v).\n");
          if (myrank == 0) print_help_message();
290
          return 1;
291
        }
292
        break;
293
      case 'y':
294
295
296
        if (sscanf(optarg, "%d", &dump_tasks) != 1) {
          if (myrank == 0) printf("Error parsing dump_tasks (-y). \n");
          if (myrank == 0) print_help_message();
297
          return 1;
298
        }
299
300
301
302
303
304
#ifndef SWIFT_DEBUG_TASKS
        if (dump_tasks) {
          error(
              "Task dumping is only possible if SWIFT was configured with the "
              "--enable-task-debugging option.");
        }
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
#endif
        break;
      case 'Y':
        if (sscanf(optarg, "%d", &dump_threadpool) != 1) {
          if (myrank == 0) printf("Error parsing dump_threadpool (-Y). \n");
          if (myrank == 0) print_help_message();
          return 1;
        }
#ifndef SWIFT_DEBUG_THREADPOOL
        if (dump_threadpool) {
          error(
              "Threadpool dumping is only possible if SWIFT was configured "
              "with the "
              "--enable-threadpool-debugging option.");
        }
320
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
321
322
323
324
325
        break;
      case '?':
        if (myrank == 0) print_help_message();
        return 1;
        break;
326
    }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
327
328
329
330
331
  if (optind == argc - 1) {
    if (!strcpy(paramFileName, argv[optind++]))
      error("Error reading parameter file name.");
  } else if (optind > argc - 1) {
    if (myrank == 0) printf("Error: A parameter file name must be provided\n");
332
333
    if (myrank == 0) print_help_message();
    return 1;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
334
335
336
337
338
339
340
341
342
343
344
  } else {
    if (myrank == 0) printf("Error: Too many parameters given\n");
    if (myrank == 0) print_help_message();
    return 1;
  }
  if (!with_self_gravity && !with_hydro && !with_external_gravity) {
    if (myrank == 0)
      printf("Error: At least one of -s, -g or -G must be chosen.\n");
    if (myrank == 0) print_help_message();
    return 1;
  }
345
346
347
  if (with_stars && !with_external_gravity && !with_self_gravity) {
    if (myrank == 0)
      printf(
348
          "Error: Cannot process stars without gravity, -g or -G must be "
349
350
351
352
          "chosen.\n");
    if (myrank == 0) print_help_message();
    return 1;
  }
353

354
355
/* Let's pin the main thread, now we know if affinity will be used. */
#if defined(HAVE_SETAFFINITY) && defined(HAVE_LIBNUMA) && defined(_GNU_SOURCE)
356
357
  if (with_aff &&
      ((ENGINE_POLICY)&engine_policy_setaffinity) == engine_policy_setaffinity)
358
359
360
    engine_pin();
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
361
362
  /* Genesis 1.1: And then, there was time ! */
  clocks_set_cpufreq(cpufreq);
363

364
365
366
  /* How vocal are we ? */
  const int talking = (verbose == 1 && myrank == 0) || (verbose == 2);

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
367
368
369
  if (myrank == 0 && dry_run)
    message(
        "Executing a dry run. No i/o or time integration will be performed.");
370

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
371
372
373
374
375
  /* Report CPU frequency.*/
  cpufreq = clocks_get_cpufreq();
  if (myrank == 0) {
    message("CPU frequency used for tick conversion: %llu Hz", cpufreq);
  }
376

Matthieu Schaller's avatar
Matthieu Schaller committed
377
/* Report host name(s). */
378
#ifdef WITH_MPI
379
  if (talking) {
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
380
381
    message("Rank %d running on: %s", myrank, hostname());
  }
382
#else
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
383
  message("Running on: %s", hostname());
384
385
#endif

386
387
/* Do we have debugging checks ? */
#ifdef SWIFT_DEBUG_CHECKS
388
389
  if (myrank == 0)
    message("WARNING: Debugging checks activated. Code will be slower !");
390
391
#endif

392
393
394
395
396
397
398
/* Do we have debugging checks ? */
#ifdef SWIFT_USE_NAIVE_INTERACTIONS
  if (myrank == 0)
    message(
        "WARNING: Naive cell interactions activated. Code will be slower !");
#endif

399
400
401
402
403
404
405
406
407
/* Do we have gravity accuracy checks ? */
#ifdef SWIFT_GRAVITY_FORCE_CHECKS
  if (myrank == 0)
    message(
        "WARNING: Checking 1/%d of all gpart for gravity accuracy. Code will "
        "be slower !",
        SWIFT_GRAVITY_FORCE_CHECKS);
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
408
409
  /* Do we choke on FP-exceptions ? */
  if (with_fp_exceptions) {
410
#ifdef HAVE_FE_ENABLE_EXCEPT
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
411
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
412
#endif
413
414
    if (myrank == 0)
      message("WARNING: Floating point exceptions will be reported.");
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
415
  }
416

417
/* Do we have slow barriers? */
418
#ifndef HAVE_PTHREAD_BARRIERS
419
  if (myrank == 0)
420
    message("WARNING: Non-optimal thread barriers are being used.");
421
422
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
423
424
  /* How large are the parts? */
  if (myrank == 0) {
425
426
427
428
429
430
431
432
    message("sizeof(part)        is %4zi bytes.", sizeof(struct part));
    message("sizeof(xpart)       is %4zi bytes.", sizeof(struct xpart));
    message("sizeof(spart)       is %4zi bytes.", sizeof(struct spart));
    message("sizeof(gpart)       is %4zi bytes.", sizeof(struct gpart));
    message("sizeof(multipole)   is %4zi bytes.", sizeof(struct multipole));
    message("sizeof(grav_tensor) is %4zi bytes.", sizeof(struct grav_tensor));
    message("sizeof(task)        is %4zi bytes.", sizeof(struct task));
    message("sizeof(cell)        is %4zi bytes.", sizeof(struct cell));
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
433
  }
434

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
435
  /* Read the parameter file */
Matthieu Schaller's avatar
Matthieu Schaller committed
436
437
  struct swift_params *params =
      (struct swift_params *)malloc(sizeof(struct swift_params));
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
438
439
440
441
  if (params == NULL) error("Error allocating memory for the parameter file.");
  if (myrank == 0) {
    message("Reading runtime parameters from file '%s'", paramFileName);
    parser_read_file(paramFileName, params);
442
443

    /* Handle any command-line overrides. */
444
445
446
447
    if (nparams > 0) {
      message(
          "Overwriting values read from the YAML file with command-line "
          "values.");
448
      for (int k = 0; k < nparams; k++) parser_set_param(params, cmdparams[k]);
449
    }
450
451

    /* And dump the parameters as used. */
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
452
453
454
    // parser_print_params(&params);
    parser_write_params_to_file(params, "used_parameters.yml");
  }
455
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
456
457
  /* Broadcast the parameter file */
  MPI_Bcast(params, sizeof(struct swift_params), MPI_BYTE, 0, MPI_COMM_WORLD);
458
#endif
459

460
  /* Check that we can write the snapshots by testing if the output
461
   * directory exists and is searchable and writable. */
462
463
464
  char basename[PARSER_MAX_LINE_SIZE];
  parser_get_param_string(params, "Snapshots:basename", basename);
  const char *dirp = dirname(basename);
465
466
  if (access(dirp, W_OK | X_OK) != 0) {
    error("Cannot write snapshots in directory %s (%s)", dirp, strerror(errno));
467
468
  }

469
  /* Prepare the domain decomposition scheme */
470
  struct repartition reparttype;
471
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
472
473
474
475
476
477
478
479
480
481
  struct partition initial_partition;
  partition_init(&initial_partition, &reparttype, params, nr_nodes);

  /* Let's report what we did */
  if (myrank == 0) {
    message("Using initial partition %s",
            initial_partition_name[initial_partition.type]);
    if (initial_partition.type == INITPART_GRID)
      message("grid set to [ %i %i %i ].", initial_partition.grid[0],
              initial_partition.grid[1], initial_partition.grid[2]);
482
    message("Using %s repartitioning", repartition_name[reparttype.type]);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
483
  }
484
#endif
485

486
487
488
489
490
  /* Common variables for restart and IC sections. */
  int clean_h_values = 0;
  int flag_entropy_ICs = 0;

  /* Work out where we will read and write restart files. */
491
  char restart_dir[PARSER_MAX_LINE_SIZE];
Peter W. Draper's avatar
Peter W. Draper committed
492
493
  parser_get_opt_param_string(params, "Restarts:subdir", restart_dir,
                              "restart");
494
495

  /* The directory must exist. */
496
  if (myrank == 0) {
497
    if (access(restart_dir, W_OK | X_OK) != 0) {
498
      if (restart) {
499
        error("Cannot restart as no restart subdirectory: %s (%s)", restart_dir,
500
              strerror(errno));
501
      } else {
Peter W. Draper's avatar
Peter W. Draper committed
502
503
504
        if (mkdir(restart_dir, 0777) != 0)
          error("Failed to create restart directory: %s (%s)", restart_dir,
                strerror(errno));
505
      }
506
    }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
507
508
  }

509
  /* Basename for any restart files. */
510
511
  char restart_name[PARSER_MAX_LINE_SIZE];
  parser_get_opt_param_string(params, "Restarts:basename", restart_name,
512
                              "swift");
513

514
515
  /* How often to check for the stop file and dump restarts and exit the
   * application. */
Peter W. Draper's avatar
Peter W. Draper committed
516
517
  int restart_stop_steps =
      parser_get_opt_param_int(params, "Restarts:stop_steps", 100);
518
519

  /* If restarting, look for the restart files. */
520
  if (restart) {
521

522
    /* Attempting a restart. */
523
524
    char **restart_files = NULL;
    int restart_nfiles = 0;
525
526

    if (myrank == 0) {
527
      message("Restarting SWIFT");
528

529
      /* Locate the restart files. */
Peter W. Draper's avatar
Peter W. Draper committed
530
531
      restart_files =
          restart_locate(restart_dir, restart_name, &restart_nfiles);
532
533
      if (restart_nfiles == 0)
        error("Failed to locate any restart files in %s", restart_dir);
534
535

      /* We need one file per rank. */
536
      if (restart_nfiles != nr_nodes)
537
        error("Incorrect number of restart files, expected %d found %d",
538
              nr_nodes, restart_nfiles);
539
540

      if (verbose > 0)
541
542
        for (int i = 0; i < restart_nfiles; i++)
          message("found restart file: %s", restart_files[i]);
543
544
545
    }

#ifdef WITH_MPI
546
    /* Distribute the restart files, need one for each rank. */
547
548
549
    if (myrank == 0) {

      for (int i = 1; i < nr_nodes; i++) {
550
551
        strcpy(restart_file, restart_files[i]);
        MPI_Send(restart_file, 200, MPI_BYTE, i, 0, MPI_COMM_WORLD);
552
553
554
      }

      /* Keep local file. */
555
      strcpy(restart_file, restart_files[0]);
556
557

      /* Finished with the list. */
558
      restart_locate_free(restart_nfiles, restart_files);
559
560

    } else {
561
      MPI_Recv(restart_file, 200, MPI_BYTE, 0, 0, MPI_COMM_WORLD,
562
563
               MPI_STATUS_IGNORE);
    }
564
    if (verbose > 1) message("local restart file = %s", restart_file);
565
#else
566

567
    /* Just one restart file. */
568
    strcpy(restart_file, restart_files[0]);
569
570
#endif

571
    /* Now read it. */
572
    restart_read(&e, restart_file);
573
574
575

    /* And initialize the engine with the space and policies. */
    if (myrank == 0) clocks_gettime(&tic);
Peter W. Draper's avatar
Peter W. Draper committed
576
577
    engine_config(1, &e, params, nr_nodes, myrank, nr_threads, with_aff,
                  talking, restart_file);
578
579
    if (myrank == 0) {
      clocks_gettime(&toc);
580
      message("engine_config took %.3f %s.", clocks_diff(&tic, &toc),
581
582
583
584
              clocks_getunit());
      fflush(stdout);
    }

585
586
    /* Check if we are already done when given steps on the command-line. */
    if (e.step >= nsteps && nsteps > 0)
587
      error("Not restarting, already completed %d steps", e.step);
588

589
  } else {
590

591
    /* Not restarting so look for the ICs. */
592
593
    /* Initialize unit system and constants */
    units_init(&us, params, "InternalUnitSystem");
594
    phys_const_init(&us, params, &prog_const);
595
596
597
598
599
600
601
602
    if (myrank == 0 && verbose > 0) {
      message("Internal unit system: U_M = %e g.", us.UnitMass_in_cgs);
      message("Internal unit system: U_L = %e cm.", us.UnitLength_in_cgs);
      message("Internal unit system: U_t = %e s.", us.UnitTime_in_cgs);
      message("Internal unit system: U_I = %e A.", us.UnitCurrent_in_cgs);
      message("Internal unit system: U_T = %e K.", us.UnitTemperature_in_cgs);
      phys_const_print(&prog_const);
    }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
603

604
    /* Initialise the cosmology */
605
606
607
    if (with_cosmology)
      cosmology_init(params, &us, &prog_const, &cosmo);
    else
608
      cosmology_init_no_cosmo(&cosmo);
609
610
    if (with_cosmology) cosmology_print(&cosmo);

611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
    /* Initialise the hydro properties */
    if (with_hydro) hydro_props_init(&hydro_properties, params);
    if (with_hydro) eos_init(&eos, params);

    /* Initialise the gravity properties */
    if (with_self_gravity) gravity_props_init(&gravity_properties, params);

    /* Read particles and space information from (GADGET) ICs */
    char ICfileName[200] = "";
    parser_get_param_string(params, "InitialConditions:file_name", ICfileName);
    const int replicate =
        parser_get_opt_param_int(params, "InitialConditions:replicate", 1);
    clean_h_values =
        parser_get_opt_param_int(params, "InitialConditions:cleanup_h", 0);
    if (myrank == 0) message("Reading ICs from file '%s'", ICfileName);
    fflush(stdout);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
627

628
629
630
631
632
    /* Get ready to read particles of all kinds */
    size_t Ngas = 0, Ngpart = 0, Nspart = 0;
    double dim[3] = {0., 0., 0.};
    int periodic = 0;
    if (myrank == 0) clocks_gettime(&tic);
633
634
#if defined(WITH_MPI)
#if defined(HAVE_PARALLEL_HDF5)
635
636
637
638
639
640
641
    read_ic_parallel(ICfileName, &us, dim, &parts, &gparts, &sparts, &Ngas,
                     &Ngpart, &Nspart, &periodic, &flag_entropy_ICs, with_hydro,
                     (with_external_gravity || with_self_gravity), with_stars,
                     myrank, nr_nodes, MPI_COMM_WORLD, MPI_INFO_NULL,
                     nr_threads, dry_run);
#else
    read_ic_serial(ICfileName, &us, dim, &parts, &gparts, &sparts, &Ngas,
Matthieu Schaller's avatar
Matthieu Schaller committed
642
643
                   &Ngpart, &Nspart, &periodic, &flag_entropy_ICs, with_hydro,
                   (with_external_gravity || with_self_gravity), with_stars,
644
645
                   myrank, nr_nodes, MPI_COMM_WORLD, MPI_INFO_NULL, nr_threads,
                   dry_run);
646
647
#endif
#else
648
649
650
651
    read_ic_single(ICfileName, &us, dim, &parts, &gparts, &sparts, &Ngas,
                   &Ngpart, &Nspart, &periodic, &flag_entropy_ICs, with_hydro,
                   (with_external_gravity || with_self_gravity), with_stars,
                   nr_threads, dry_run);
652
#endif
653
654
655
656
657
658
    if (myrank == 0) {
      clocks_gettime(&toc);
      message("Reading initial conditions took %.3f %s.",
              clocks_diff(&tic, &toc), clocks_getunit());
      fflush(stdout);
    }
659

660
#ifdef SWIFT_DEBUG_CHECKS
661
662
663
664
665
666
667
668
669
    /* Check once and for all that we don't have unwanted links */
    if (!with_stars) {
      for (size_t k = 0; k < Ngpart; ++k)
        if (gparts[k].type == swift_type_star) error("Linking problem");
    }
    if (!with_hydro) {
      for (size_t k = 0; k < Ngpart; ++k)
        if (gparts[k].type == swift_type_gas) error("Linking problem");
    }
670
#endif
671

672
673
    /* Get the total number of particles across all nodes. */
    long long N_total[3] = {0, 0, 0};
674
#if defined(WITH_MPI)
675
676
677
    long long N_long[3] = {Ngas, Ngpart, Nspart};
    MPI_Allreduce(&N_long, &N_total, 3, MPI_LONG_LONG_INT, MPI_SUM,
                  MPI_COMM_WORLD);
678
#else
679
680
681
    N_total[0] = Ngas;
    N_total[1] = Ngpart;
    N_total[2] = Nspart;
682
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
683

684
685
    if (myrank == 0)
      message(
Peter W. Draper's avatar
Peter W. Draper committed
686
687
          "Read %lld gas particles, %lld star particles and %lld gparts from "
          "the "
688
          "ICs.",
689
          N_total[0], N_total[2], N_total[1]);
690

691
692
693
694
695
696
697
698
699
700
701
702
703
    /* Initialize the space with these data. */
    if (myrank == 0) clocks_gettime(&tic);
    space_init(&s, params, dim, parts, gparts, sparts, Ngas, Ngpart, Nspart,
               periodic, replicate, with_self_gravity, talking, dry_run);

    if (myrank == 0) {
      clocks_gettime(&toc);
      message("space_init took %.3f %s.", clocks_diff(&tic, &toc),
              clocks_getunit());
      fflush(stdout);
    }

/* Also update the total counts (in case of changes due to replication) */
704
#if defined(WITH_MPI)
705
706
707
708
709
    N_long[0] = s.nr_parts;
    N_long[1] = s.nr_gparts;
    N_long[2] = s.nr_sparts;
    MPI_Allreduce(&N_long, &N_total, 3, MPI_LONG_LONG_INT, MPI_SUM,
                  MPI_COMM_WORLD);
710
#else
711
712
713
    N_total[0] = s.nr_parts;
    N_total[1] = s.nr_gparts;
    N_total[2] = s.nr_sparts;
714
715
#endif

716
717
718
719
720
721
722
723
724
725
726
727
728
    /* Say a few nice things about the space we just created. */
    if (myrank == 0) {
      message("space dimensions are [ %.3f %.3f %.3f ].", s.dim[0], s.dim[1],
              s.dim[2]);
      message("space %s periodic.", s.periodic ? "is" : "isn't");
      message("highest-level cell dimensions are [ %i %i %i ].", s.cdim[0],
              s.cdim[1], s.cdim[2]);
      message("%zi parts in %i cells.", s.nr_parts, s.tot_cells);
      message("%zi gparts in %i cells.", s.nr_gparts, s.tot_cells);
      message("%zi sparts in %i cells.", s.nr_sparts, s.tot_cells);
      message("maximum depth is %d.", s.maxdepth);
      fflush(stdout);
    }
729

730
731
732
733
734
735
    /* Verify that each particle is in it's proper cell. */
    if (talking && !dry_run) {
      int icount = 0;
      space_map_cells_pre(&s, 0, &map_cellcheck, &icount);
      message("map_cellcheck picked up %i parts.", icount);
    }
736

737
738
739
740
741
742
    /* Verify the maximal depth of cells. */
    if (talking && !dry_run) {
      int data[2] = {s.maxdepth, 0};
      space_map_cells_pre(&s, 0, &map_maxdepth, data);
      message("nr of cells at depth %i is %i.", data[0], data[1]);
    }
743

744
745
746
747
    /* Initialise the external potential properties */
    if (with_external_gravity)
      potential_init(params, &prog_const, &us, &s, &potential);
    if (myrank == 0) potential_print(&potential);
748

749
750
    /* Initialise the cooling function properties */
    if (with_cooling) cooling_init(params, &us, &prog_const, &cooling_func);
751
    if (myrank == 0) cooling_print(&cooling_func);
752

753
754
755
756
    /* Initialise the chemistry */
    chemistry_init(params, &us, &prog_const, &chemistry);
    if (myrank == 0) chemistry_print(&chemistry);

757
758
    /* Initialise the feedback properties */
    if (with_sourceterms) sourceterms_init(params, &us, &sourceterms);
Peter W. Draper's avatar
Peter W. Draper committed
759
    if (with_sourceterms && myrank == 0) sourceterms_print(&sourceterms);
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776

    /* Construct the engine policy */
    int engine_policies = ENGINE_POLICY | engine_policy_steal;
    if (with_drift_all) engine_policies |= engine_policy_drift_all;
    if (with_mpole_reconstruction)
      engine_policies |= engine_policy_reconstruct_mpoles;
    if (with_hydro) engine_policies |= engine_policy_hydro;
    if (with_self_gravity) engine_policies |= engine_policy_self_gravity;
    if (with_external_gravity)
      engine_policies |= engine_policy_external_gravity;
    if (with_cosmology) engine_policies |= engine_policy_cosmology;
    if (with_cooling) engine_policies |= engine_policy_cooling;
    if (with_sourceterms) engine_policies |= engine_policy_sourceterms;
    if (with_stars) engine_policies |= engine_policy_stars;

    /* Initialize the engine with the space and policies. */
    if (myrank == 0) clocks_gettime(&tic);
777
    engine_init(&e, &s, params, N_total[0], N_total[1], engine_policies,
778
779
780
                talking, &reparttype, &us, &prog_const, &cosmo,
                &hydro_properties, &gravity_properties, &potential,
                &cooling_func, &chemistry, &sourceterms);
Peter W. Draper's avatar
Peter W. Draper committed
781
782
    engine_config(0, &e, params, nr_nodes, myrank, nr_threads, with_aff,
                  talking, restart_file);
783
784
785
786
787
788
    if (myrank == 0) {
      clocks_gettime(&toc);
      message("engine_init took %.3f %s.", clocks_diff(&tic, &toc),
              clocks_getunit());
      fflush(stdout);
    }
789

790
791
792
793
794
795
796
797
798
799
800
    /* Get some info to the user. */
    if (myrank == 0) {
      long long N_DM = N_total[1] - N_total[2] - N_total[0];
      message(
          "Running on %lld gas particles, %lld star particles and %lld DM "
          "particles (%lld gravity particles)",
          N_total[0], N_total[2], N_total[1] > 0 ? N_DM : 0, N_total[1]);
      message(
          "from t=%.3e until t=%.3e with %d threads and %d queues "
          "(dt_min=%.3e, "
          "dt_max=%.3e)...",
801
          e.time_begin, e.time_end, e.nr_threads, e.sched.nr_queues, e.dt_min,
802
803
804
          e.dt_max);
      fflush(stdout);
    }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
805
  }
806

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
807
808
  /* Time to say good-bye if this was not a serious run. */
  if (dry_run) {
809
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
810
811
    if ((res = MPI_Finalize()) != MPI_SUCCESS)
      error("call to MPI_Finalize failed with error %i.", res);
812
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
813
814
815
816
817
818
    if (myrank == 0)
      message("Time integration ready to start. End of dry-run.");
    engine_clean(&e);
    free(params);
    return 0;
  }
819

820
821
822
/* Initialise the table of Ewald corrections for the gravity checks */
#ifdef SWIFT_GRAVITY_FORCE_CHECKS
  if (periodic) gravity_exact_force_ewald_init(e.s->dim[0]);
823
824
#endif

825
826
827
828
/* Init the runner history. */
#ifdef HIST
  for (k = 0; k < runner_hist_N; k++) runner_hist_bins[k] = 0;
#endif
829

Peter W. Draper's avatar
Peter W. Draper committed
830
831
  if (!restart) {

832
#ifdef WITH_MPI
833
834
835
    /* Split the space. */
    engine_split(&e, &initial_partition);
    engine_redistribute(&e);
836
837
#endif

838
839
    /* Initialise the particles */
    engine_init_particles(&e, flag_entropy_ICs, clean_h_values);
840

841
842
843
844
    /* Write the state of the system before starting time integration. */
    engine_dump_snapshot(&e);
    engine_print_stats(&e);
  }
845

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
846
  /* Legend */
847
  if (myrank == 0)
848
849
850
    printf("# %6s %14s %14s %9s %12s %12s %12s %16s [%s] %6s\n", "Step", "Time",
           "Time-step", "Time-bins", "Updates", "g-Updates", "s-Updates",
           "Wall-clock time", clocks_getunit(), "Props");
851

852
  /* File for the timers */
853
  if (with_verbose_timers) timers_open_file(myrank);
854

855
  /* Create a name for restart file of this rank. */
Peter W. Draper's avatar
Peter W. Draper committed
856
857
  if (restart_genname(restart_dir, restart_name, e.nodeID, restart_file, 200) !=
      0)
858
859
    error("Failed to generate restart filename");

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
860
  /* Main simulation loop */
861
862
  /* ==================== */
  int force_stop = 0;
Peter W. Draper's avatar
Peter W. Draper committed
863
864
  for (int j = 0; !engine_is_done(&e) && e.step - 1 != nsteps && !force_stop;
       j++) {
865

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
866
    /* Reset timers */
867
    timers_reset_all();
868

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
869
870
    /* Take a step. */
    engine_step(&e);
871

872
    /* Print the timers. */
873
    if (with_verbose_timers) timers_print(e.step);
874

Peter W. Draper's avatar
Peter W. Draper committed
875
    /* Every so often allow the user to stop the application and dump the
876
     * restart files. */
877
    if (j % restart_stop_steps == 0) {
Peter W. Draper's avatar
Peter W. Draper committed
878
879
880
      force_stop = restart_stop_now(restart_dir, 0);
      if (myrank == 0 && force_stop)
        message("Forcing application exit, dumping restart files...");
881
882
    }

Peter W. Draper's avatar
Peter W. Draper committed
883
    /* Also if using nsteps to exit, will not have saved any restarts on exit,
884
     * make sure we do that (useful in testing only). */
Peter W. Draper's avatar
Peter W. Draper committed
885
886
    if (force_stop || (e.restart_onexit && e.step - 1 == nsteps))
      engine_dump_restarts(&e, 0, 1);
887

888
#ifdef SWIFT_DEBUG_TASKS
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
889
890
    /* Dump the task data using the given frequency. */
    if (dump_tasks && (dump_tasks == 1 || j % dump_tasks == 1)) {
891
892
#ifdef WITH_MPI

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
893
894
895
896
897
898
      /* Make sure output file is empty, only on one rank. */
      char dumpfile[30];
      snprintf(dumpfile, 30, "thread_info_MPI-step%d.dat", j + 1);
      FILE *file_thread;
      if (myrank == 0) {
        file_thread = fopen(dumpfile, "w");
899
        fclose(file_thread);