main.c 30.3 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 <unistd.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
36

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

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

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

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

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

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

61
  printf("Valid options are:\n");
62
63
64
65
  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.");
66
  printf(
67
      "  %2s %14s %s\n", "-d", "",
68
69
      "Dry run. Read the parameter file, allocate memory but does not read ");
  printf(
70
      "  %2s %14s %s\n", "", "",
71
      "the particles from ICs and exit before the start of time integration.");
72
  printf("  %2s %14s %s\n", "", "",
73
74
         "Allows user to check validy of parameter and IC files as well as "
         "memory limits.");
75
  printf("  %2s %14s %s\n", "-D", "",
76
77
         "Always drift all particles even the ones far from active particles. "
         "This emulates");
78
  printf("  %2s %14s %s\n", "", "",
79
         "Gadget-[23] and GIZMO's default behaviours.");
80
  printf("  %2s %14s %s\n", "-e", "",
81
         "Enable floating-point exceptions (debugging mode).");
82
  printf("  %2s %14s %s\n", "-f", "{int}",
83
         "Overwrite the CPU frequency (Hz) to be used for time measurements.");
84
  printf("  %2s %14s %s\n", "-g", "",
85
         "Run with an external gravitational potential.");
86
87
  printf("  %2s %14s %s\n", "-G", "", "Run with self-gravity.");
  printf("  %2s %14s %s\n", "-M", "",
88
         "Reconstruct the multipoles every time-step.");
89
  printf("  %2s %14s %s\n", "-n", "{int}",
90
91
         "Execute a fixed number of time steps. When unset use the time_end "
         "parameter to stop.");
92
93
94
95
96
97
  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.");
  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}",
98
99
         "The number of threads to use on each MPI rank. Defaults to 1 if not "
         "specified.");
100
101
102
103
104
  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}",
105
         "Time-step frequency at which task graphs are dumped.");
106
107
  printf("  %2s %14s %s\n", "-Y", "{int}",
         "Time-step frequency at which threadpool tasks are dumped.");
108
  printf("  %2s %14s %s\n", "-h", "", "Print this help message and exit.");
109
110
111
  printf(
      "\nSee the file parameter_example.yml for an example of "
      "parameter file.\n");
112
113
}

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

120
  struct clocks_time tic, toc;
121

122
  int nr_nodes = 1, myrank = 0;
123

124
#ifdef WITH_MPI
125
  /* Start by initializing MPI. */
126
  int res = 0, prov = 0;
127
128
  if ((res = MPI_Init_thread(&argc, &argv, MPI_THREAD_MULTIPLE, &prov)) !=
      MPI_SUCCESS)
129
130
    error("Call to MPI_Init failed with error %i.", res);
  if (prov != MPI_THREAD_MULTIPLE)
131
    error(
132
133
        "MPI does not provide the level of threading"
        " required (MPI_THREAD_MULTIPLE).");
134
  if ((res = MPI_Comm_size(MPI_COMM_WORLD, &nr_nodes)) != MPI_SUCCESS)
135
136
137
    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);
138
139
140
141

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

142
143
144
  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);
145
146
  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
147
           nr_nodes);
148
149
150
151
  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.");
  }
152
  fflush(stdout);
153

154
#endif
155

156
157
  /* Welcome to SWIFT, you made the right choice */
  if (myrank == 0) greetings();
158

159
  int with_aff = 0;
160
  int dry_run = 0;
161
  int dump_tasks = 0;
162
  int dump_threadpool = 0;
163
  int nsteps = -2;
164
165
  int with_cosmology = 0;
  int with_external_gravity = 0;
Tom Theuns's avatar
Tom Theuns committed
166
  int with_sourceterms = 0;
167
  int with_cooling = 0;
168
169
  int with_self_gravity = 0;
  int with_hydro = 0;
170
  int with_stars = 0;
171
  int with_fp_exceptions = 0;
172
  int with_drift_all = 0;
173
  int with_mpole_reconstruction = 0;
174
  int verbose = 0;
175
  int nr_threads = 1;
176
  int with_verbose_timers = 0;
177
178
  int nparams = 0;
  char *cmdparams[PARSER_MAX_NO_OF_PARAMS];
179
180
181
182
  char paramFileName[200] = "";
  unsigned long long cpufreq = 0;

  /* Parse the parameters */
183
  int c;
184
  while ((c = getopt(argc, argv, "acCdDef:FgGhMn:P:sSt:Tv:y:Y:")) != -1)
185
    switch (c) {
186
      case 'a':
187
#if defined(HAVE_SETAFFINITY) && defined(HAVE_LIBNUMA)
188
        with_aff = 1;
189
190
191
#else
        error("Need NUMA support for thread affinity");
#endif
192
        break;
193
      case 'c':
194
        with_cosmology = 1;
195
        break;
196
197
198
      case 'C':
        with_cooling = 1;
        break;
199
      case 'd':
200
        dry_run = 1;
201
        break;
202
203
204
      case 'D':
        with_drift_all = 1;
        break;
205
      case 'e':
206
#ifdef HAVE_FE_ENABLE_EXCEPT
207
        with_fp_exceptions = 1;
208
209
210
#else
        error("Need support for floating point exception on this platform");
#endif
211
        break;
212
      case 'f':
213
214
215
        if (sscanf(optarg, "%llu", &cpufreq) != 1) {
          if (myrank == 0) printf("Error parsing CPU frequency (-f).\n");
          if (myrank == 0) print_help_message();
216
          return 1;
217
        }
218
        break;
219
220
221
      case 'F':
        with_sourceterms = 1;
        break;
222
      case 'g':
223
        with_external_gravity = 1;
224
        break;
225
226
      case 'G':
        with_self_gravity = 1;
Tom Theuns's avatar
Tom Theuns committed
227
        break;
228
      case 'h':
229
        if (myrank == 0) print_help_message();
230
        return 0;
231
232
233
      case 'M':
        with_mpole_reconstruction = 1;
        break;
234
235
236
237
238
239
240
      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;
241
242
243
244
      case 'P':
        cmdparams[nparams] = optarg;
        nparams++;
        break;
245
      case 's':
246
        with_hydro = 1;
247
        break;
248
249
250
      case 'S':
        with_stars = 1;
        break;
251
252
253
254
255
256
257
258
      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;
259
260
261
      case 'T':
        with_verbose_timers = 1;
        break;
262
      case 'v':
263
264
265
        if (sscanf(optarg, "%d", &verbose) != 1) {
          if (myrank == 0) printf("Error parsing verbosity level (-v).\n");
          if (myrank == 0) print_help_message();
266
          return 1;
267
        }
268
        break;
269
      case 'y':
270
271
272
        if (sscanf(optarg, "%d", &dump_tasks) != 1) {
          if (myrank == 0) printf("Error parsing dump_tasks (-y). \n");
          if (myrank == 0) print_help_message();
273
          return 1;
274
        }
275
276
277
278
279
280
#ifndef SWIFT_DEBUG_TASKS
        if (dump_tasks) {
          error(
              "Task dumping is only possible if SWIFT was configured with the "
              "--enable-task-debugging option.");
        }
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#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.");
        }
296
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
297
298
299
300
301
        break;
      case '?':
        if (myrank == 0) print_help_message();
        return 1;
        break;
302
    }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
303
304
305
306
307
  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");
308
309
    if (myrank == 0) print_help_message();
    return 1;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
310
311
312
313
314
315
316
317
318
319
320
  } 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;
  }
321
322
323
  if (with_stars && !with_external_gravity && !with_self_gravity) {
    if (myrank == 0)
      printf(
324
          "Error: Cannot process stars without gravity, -g or -G must be "
325
326
327
328
          "chosen.\n");
    if (myrank == 0) print_help_message();
    return 1;
  }
329

330
331
/* Let's pin the main thread, now we know if affinity will be used. */
#if defined(HAVE_SETAFFINITY) && defined(HAVE_LIBNUMA) && defined(_GNU_SOURCE)
332
333
  if (with_aff &&
      ((ENGINE_POLICY)&engine_policy_setaffinity) == engine_policy_setaffinity)
334
335
336
    engine_pin();
#endif

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

340
341
342
  /* How vocal are we ? */
  const int talking = (verbose == 1 && myrank == 0) || (verbose == 2);

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

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
347
348
349
350
351
  /* Report CPU frequency.*/
  cpufreq = clocks_get_cpufreq();
  if (myrank == 0) {
    message("CPU frequency used for tick conversion: %llu Hz", cpufreq);
  }
352

Matthieu Schaller's avatar
Matthieu Schaller committed
353
/* Report host name(s). */
354
#ifdef WITH_MPI
355
  if (talking) {
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
356
357
    message("Rank %d running on: %s", myrank, hostname());
  }
358
#else
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
359
  message("Running on: %s", hostname());
360
361
#endif

362
363
/* Do we have debugging checks ? */
#ifdef SWIFT_DEBUG_CHECKS
364
365
  if (myrank == 0)
    message("WARNING: Debugging checks activated. Code will be slower !");
366
367
#endif

368
369
370
371
372
373
374
/* Do we have debugging checks ? */
#ifdef SWIFT_USE_NAIVE_INTERACTIONS
  if (myrank == 0)
    message(
        "WARNING: Naive cell interactions activated. Code will be slower !");
#endif

375
376
377
378
379
380
381
382
383
/* 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
384
385
  /* Do we choke on FP-exceptions ? */
  if (with_fp_exceptions) {
386
#ifdef HAVE_FE_ENABLE_EXCEPT
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
387
    feenableexcept(FE_DIVBYZERO | FE_INVALID | FE_OVERFLOW);
388
#endif
389
390
    if (myrank == 0)
      message("WARNING: Floating point exceptions will be reported.");
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
391
  }
392

393
/* Do we have slow barriers? */
394
#ifndef HAVE_PTHREAD_BARRIERS
395
  if (myrank == 0)
396
    message("WARNING: Non-optimal thread barriers are being used.");
397
398
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
399
400
  /* How large are the parts? */
  if (myrank == 0) {
401
402
403
404
405
406
407
408
    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
409
  }
410

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
411
412
413
414
415
416
  /* Read the parameter file */
  struct swift_params *params = malloc(sizeof(struct swift_params));
  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);
417
418

    /* Handle any command-line overrides. */
419
420
421
422
    if (nparams > 0) {
      message(
          "Overwriting values read from the YAML file with command-line "
          "values.");
423
      for (int k = 0; k < nparams; k++) parser_set_param(params, cmdparams[k]);
424
    }
425
426

    /* And dump the parameters as used. */
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
427
428
429
    // parser_print_params(&params);
    parser_write_params_to_file(params, "used_parameters.yml");
  }
430
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
431
432
  /* Broadcast the parameter file */
  MPI_Bcast(params, sizeof(struct swift_params), MPI_BYTE, 0, MPI_COMM_WORLD);
433
#endif
434

435
  /* Check that we can write the snapshots by testing if the output
436
   * directory exists and is searchable and writable. */
437
438
439
  char basename[PARSER_MAX_LINE_SIZE];
  parser_get_param_string(params, "Snapshots:basename", basename);
  const char *dirp = dirname(basename);
440
441
  if (access(dirp, W_OK | X_OK) != 0) {
    error("Cannot write snapshots in directory %s (%s)", dirp, strerror(errno));
442
443
  }

444
  /* Prepare the domain decomposition scheme */
445
  struct repartition reparttype;
446
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
447
448
449
450
451
452
453
454
455
456
  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]);
457
    message("Using %s repartitioning", repartition_name[reparttype.type]);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
458
  }
459
#endif
460

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
461
  /* Initialize unit system and constants */
462
  struct unit_system us;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
463
464
465
466
467
468
469
470
471
472
473
474
  struct phys_const prog_const;
  units_init(&us, params, "InternalUnitSystem");
  phys_const_init(&us, &prog_const);
  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);
  }

475
476
  /* Initialise the cosmology */
  struct cosmology cosmo;
477
478
479
480
481
482
483
484
485
486
487
488
489
490
  if (with_cosmology) cosmology_init(params, &us, &prog_const, &cosmo);
  if (with_cosmology) cosmology_print(&cosmo);

  struct engine ee;
  ee.ti_current = 0;
  ee.timeBase = (log(cosmo.a_end) - log(cosmo.a_begin)) / max_nr_timesteps;
  cosmology_update(&cosmo, &ee);

  for (int i = 0; i <= 16; ++i) {

    ee.ti_current = (max_nr_timesteps / 16) * i;

    cosmology_update(&cosmo, &ee);

491
492
493
    message("z=%e H(z)=%e w=%f t=%e [yrs] t_l=%e [yrs]", cosmo.z, cosmo.H,
            cosmo.w, cosmo.time / prog_const.const_year,
            cosmo.lookback_time / prog_const.const_year);
494
495
496
497
  }

  return 0;

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
498
499
  /* Initialise the hydro properties */
  struct hydro_props hydro_properties;
Matthieu Schaller's avatar
Matthieu Schaller committed
500
  if (with_hydro) hydro_props_init(&hydro_properties, params);
501
  if (with_hydro) eos_init(&eos, params);
502

503
504
505
506
  /* Initialise the gravity properties */
  struct gravity_props gravity_properties;
  if (with_self_gravity) gravity_props_init(&gravity_properties, params);

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

517
  /* Get ready to read particles of all kinds */
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
518
519
  struct part *parts = NULL;
  struct gpart *gparts = NULL;
520
521
  struct spart *sparts = NULL;
  size_t Ngas = 0, Ngpart = 0, Nspart = 0;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
522
523
524
525
  double dim[3] = {0., 0., 0.};
  int periodic = 0;
  int flag_entropy_ICs = 0;
  if (myrank == 0) clocks_gettime(&tic);
526
527
#if defined(WITH_MPI)
#if defined(HAVE_PARALLEL_HDF5)
Matthieu Schaller's avatar
Matthieu Schaller committed
528
529
530
  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,
531
532
                   myrank, nr_nodes, MPI_COMM_WORLD, MPI_INFO_NULL, nr_threads,
                   dry_run);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
533
#else
534
  read_ic_serial(ICfileName, &us, dim, &parts, &gparts, &sparts, &Ngas, &Ngpart,
Matthieu Schaller's avatar
Typos    
Matthieu Schaller committed
535
                 &Nspart, &periodic, &flag_entropy_ICs, with_hydro,
536
                 (with_external_gravity || with_self_gravity), with_stars,
537
538
                 myrank, nr_nodes, MPI_COMM_WORLD, MPI_INFO_NULL, nr_threads,
                 dry_run);
539
540
#endif
#else
541
  read_ic_single(ICfileName, &us, dim, &parts, &gparts, &sparts, &Ngas, &Ngpart,
542
543
                 &Nspart, &periodic, &flag_entropy_ICs, with_hydro,
                 (with_external_gravity || with_self_gravity), with_stars,
544
                 nr_threads, dry_run);
545
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
546
547
548
549
550
551
  if (myrank == 0) {
    clocks_gettime(&toc);
    message("Reading initial conditions took %.3f %s.", clocks_diff(&tic, &toc),
            clocks_getunit());
    fflush(stdout);
  }
552

553
554
#ifdef SWIFT_DEBUG_CHECKS
  /* Check once and for all that we don't have unwanted links */
555
  if (!with_stars) {
556
    for (size_t k = 0; k < Ngpart; ++k)
557
558
      if (gparts[k].type == swift_type_star) error("Linking problem");
  }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
559
560
  if (!with_hydro) {
    for (size_t k = 0; k < Ngpart; ++k)
561
      if (gparts[k].type == swift_type_gas) error("Linking problem");
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
562
  }
563
#endif
564

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
565
  /* Get the total number of particles across all nodes. */
566
  long long N_total[3] = {0, 0, 0};
567
#if defined(WITH_MPI)
568
  long long N_long[3] = {Ngas, Ngpart, Nspart};
569
570
  MPI_Allreduce(&N_long, &N_total, 3, MPI_LONG_LONG_INT, MPI_SUM,
                MPI_COMM_WORLD);
571
#else
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
572
573
  N_total[0] = Ngas;
  N_total[1] = Ngpart;
574
  N_total[2] = Nspart;
575
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
576
  if (myrank == 0)
577
578
579
580
    message(
        "Read %lld gas particles, %lld star particles and %lld gparts from the "
        "ICs.",
        N_total[0], N_total[2], N_total[1]);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
581
582
583
584

  /* Initialize the space with these data. */
  if (myrank == 0) clocks_gettime(&tic);
  struct space s;
585
  space_init(&s, params, dim, parts, gparts, sparts, Ngas, Ngpart, Nspart,
586
             periodic, replicate, with_self_gravity, talking, dry_run);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
587
588
589
590
591
592
  if (myrank == 0) {
    clocks_gettime(&toc);
    message("space_init took %.3f %s.", clocks_diff(&tic, &toc),
            clocks_getunit());
    fflush(stdout);
  }
593

594
/* Also update the total counts (in case of changes due to replication) */
595
596
597
598
599
#if defined(WITH_MPI)
  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,
600
                MPI_COMM_WORLD);
601
602
603
604
605
606
#else
  N_total[0] = s.nr_parts;
  N_total[1] = s.nr_gparts;
  N_total[2] = s.nr_sparts;
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
607
608
609
610
611
612
613
614
615
  /* 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);
616
    message("%zi sparts in %i cells.", s.nr_sparts, s.tot_cells);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
617
618
619
    message("maximum depth is %d.", s.maxdepth);
    fflush(stdout);
  }
620

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
621
622
623
624
625
626
  /* 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);
  }
627

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
628
629
630
631
632
633
  /* 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]);
  }
634

635
/* Initialise the table of Ewald corrections for the gravity checks */
636
#ifdef SWIFT_GRAVITY_FORCE_CHECKS
637
  if (periodic) gravity_exact_force_ewald_init(dim[0]);
638
639
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
640
641
642
  /* Initialise the external potential properties */
  struct external_potential potential;
  if (with_external_gravity)
643
    potential_init(params, &prog_const, &us, &s, &potential);
644
  if (myrank == 0) potential_print(&potential);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
645
646
647
648

  /* Initialise the cooling function properties */
  struct cooling_function_data cooling_func;
  if (with_cooling) cooling_init(params, &us, &prog_const, &cooling_func);
649
  if (myrank == 0) cooling_print(&cooling_func);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
650

651
  /* Initialise the chemistry */
652
653
654
  struct chemistry_data chemistry;
  chemistry_init(params, &us, &prog_const, &chemistry);
  if (myrank == 0) chemistry_print(&chemistry);
655

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
656
657
658
659
660
661
662
663
  /* Initialise the feedback properties */
  struct sourceterms sourceterms;
  if (with_sourceterms) sourceterms_init(params, &us, &sourceterms);
  if (with_sourceterms && myrank == 0) sourceterms_print(&sourceterms);

  /* Construct the engine policy */
  int engine_policies = ENGINE_POLICY | engine_policy_steal;
  if (with_drift_all) engine_policies |= engine_policy_drift_all;
664
665
  if (with_mpole_reconstruction)
    engine_policies |= engine_policy_reconstruct_mpoles;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
666
667
668
669
670
671
  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;
672
  if (with_stars) engine_policies |= engine_policy_stars;
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
673
674
675
676

  /* Initialize the engine with the space and policies. */
  if (myrank == 0) clocks_gettime(&tic);
  struct engine e;
677
  engine_init(&e, &s, params, nr_nodes, myrank, nr_threads, N_total[0],
Peter W. Draper's avatar
Peter W. Draper committed
678
679
              N_total[1], with_aff, engine_policies, talking, &reparttype, &us,
              &prog_const, &hydro_properties, &gravity_properties, &potential,
680
              &cooling_func, &chemistry, &sourceterms);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
681
682
683
684
685
686
  if (myrank == 0) {
    clocks_gettime(&toc);
    message("engine_init took %.3f %s.", clocks_diff(&tic, &toc),
            clocks_getunit());
    fflush(stdout);
  }
687

688
689
/* Init the runner history. */
#ifdef HIST
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
690
  for (k = 0; k < runner_hist_N; k++) runner_hist_bins[k] = 0;
691
692
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
693
694
  /* Get some info to the user. */
  if (myrank == 0) {
Matthieu Schaller's avatar
Matthieu Schaller committed
695
    long long N_DM = N_total[1] - N_total[2] - N_total[0];
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
696
    message(
Matthieu Schaller's avatar
Matthieu Schaller committed
697
698
699
700
701
702
703
704
        "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)...",
        e.timeBegin, e.timeEnd, e.nr_threads, e.sched.nr_queues, e.dt_min,
        e.dt_max);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
705
706
    fflush(stdout);
  }
707

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
708
709
  /* Time to say good-bye if this was not a serious run. */
  if (dry_run) {
710
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
711
712
    if ((res = MPI_Finalize()) != MPI_SUCCESS)
      error("call to MPI_Finalize failed with error %i.", res);
713
#endif
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
714
715
716
717
718
719
    if (myrank == 0)
      message("Time integration ready to start. End of dry-run.");
    engine_clean(&e);
    free(params);
    return 0;
  }
720
721

#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
722
723
724
  /* Split the space. */
  engine_split(&e, &initial_partition);
  engine_redistribute(&e);
725
726
#endif

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
727
  /* Initialise the particles */
728
  engine_init_particles(&e, flag_entropy_ICs, clean_h_values);
729

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
730
731
  /* Write the state of the system before starting time integration. */
  engine_dump_snapshot(&e);
732
  engine_print_stats(&e);
733

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
734
  /* Legend */
735
  if (myrank == 0)
736
    printf("# %6s %14s %14s %12s %12s %12s %16s [%s] %6s\n", "Step", "Time",
737
           "Time-step", "Updates", "g-Updates", "s-Updates", "Wall-clock time",
738
           clocks_getunit(), "Props");
739

740
  /* File for the timers */
741
  if (with_verbose_timers) timers_open_file(myrank);
742

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
743
  /* Main simulation loop */
744
  for (int j = 0; !engine_is_done(&e) && e.step - 1 != nsteps; j++) {
745

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
746
    /* Reset timers */
747
    timers_reset_all();
748

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
749
750
    /* Take a step. */
    engine_step(&e);
751

752
    /* Print the timers. */
753
    if (with_verbose_timers) timers_print(e.step);
754

755
#ifdef SWIFT_DEBUG_TASKS
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
756
757
    /* Dump the task data using the given frequency. */
    if (dump_tasks && (dump_tasks == 1 || j % dump_tasks == 1)) {
758
759
#ifdef WITH_MPI

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
760
761
762
763
764
765
      /* 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");
766
        fclose(file_thread);
767
      }
768
      MPI_Barrier(MPI_COMM_WORLD);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
769
770
771
772
773
774
775
776
777
778
779
780

      for (int i = 0; i < nr_nodes; i++) {

        /* Rank 0 decides the index of writing node, this happens one-by-one. */
        int kk = i;
        MPI_Bcast(&kk, 1, MPI_INT, 0, MPI_COMM_WORLD);

        if (i == myrank) {

          /* Open file and position at end. */
          file_thread = fopen(dumpfile, "a");

Matthieu Schaller's avatar
Matthieu Schaller committed
781
782
783
          fprintf(file_thread, " %03i 0 0 0 0 %lli %lli %zi %zi %zi 0 0 %lli\n",
                  myrank, e.tic_step, e.toc_step, e.updates, e.g_updates,
                  e.s_updates, cpufreq);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
784
785
786
787
          int count = 0;
          for (int l = 0; l < e.sched.nr_tasks; l++) {
            if (!e.sched.tasks[l].implicit && e.sched.tasks[l].toc != 0) {
              fprintf(
Matthieu Schaller's avatar
Matthieu Schaller committed
788
789
790
                  file_thread,
                  " %03i %i %i %i %i %lli %lli %i %i %i %i %i %i\n", myrank,
                  e.sched.tasks[l].rid, e.sched.tasks[l].type,
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
791
792
793
794
795
796
797
798
799
800
                  e.sched.tasks[l].subtype, (e.sched.tasks[l].cj == NULL),
                  e.sched.tasks[l].tic, e.sched.tasks[l].toc,
                  (e.sched.tasks[l].ci != NULL) ? e.sched.tasks[l].ci->count
                                                : 0,
                  (e.sched.tasks[l].cj != NULL) ? e.sched.tasks[l].cj->count
                                                : 0,
                  (e.sched.tasks[l].ci != NULL) ? e.sched.tasks[l].ci->gcount
                                                : 0,
                  (e.sched.tasks[l].cj != NULL) ? e.sched.tasks[l].cj->gcount
                                                : 0,
801
                  e.sched.tasks[l].flags, e.sched.tasks[l].sid);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
802
803
804
805
806
807
808
809
810
811
            }
            fflush(stdout);
            count++;
          }
          fclose(file_thread);
        }

        /* And we wait for all to synchronize. */
        MPI_Barrier(MPI_COMM_WORLD);
      }
812

813
#else
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
814
815
816
817
818
      char dumpfile[30];
      snprintf(dumpfile, 30, "thread_info-step%d.dat", j + 1);
      FILE *file_thread;
      file_thread = fopen(dumpfile, "w");
      /* Add some information to help with the plots */
819
820
821
      fprintf(file_thread, " %i %i %i %i %lli %lli %zi %zi %zi %i %lli\n", -2,
              -1, -1, 1, e.tic_step, e.toc_step, e.updates, e.g_updates,
              e.s_updates, 0, cpufreq);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
822
823
824
      for (int l = 0; l < e.sched.nr_tasks; l++) {
        if (!e.sched.tasks[l].implicit && e.sched.tasks[l].toc != 0) {
          fprintf(
825
              file_thread, " %i %i %i %i %lli %lli %i %i %i %i %i\n",
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
826
827
828
829
830
831
              e.sched.tasks[l].rid, e.sched.tasks[l].type,
              e.sched.tasks[l].subtype, (e.sched.tasks[l].cj == NULL),
              e.sched.tasks[l].tic, e.sched.tasks[l].toc,
              (e.sched.tasks[l].ci == NULL) ? 0 : e.sched.tasks[l].ci->count,
              (e.sched.tasks[l].cj == NULL) ? 0 : e.sched.tasks[l].cj->count,
              (e.sched.tasks[l].ci == NULL) ? 0 : e.sched.tasks[l].ci->gcount,
832
833
              (e.sched.tasks[l].cj == NULL) ? 0 : e.sched.tasks[l].cj->gcount,
              e.sched.tasks[l].sid);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
834
        }
835
      }
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
836
      fclose(file_thread);
837
#endif  // WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
838
    }
839
#endif  // SWIFT_DEBUG_TASKS
840
841
842
843
844

#ifdef SWIFT_DEBUG_THREADPOOL
    /* Dump the task data using the given frequency. */
    if (dump_threadpool && (dump_threadpool == 1 || j % dump_threadpool == 1)) {
      char dumpfile[40];
845
#ifdef WITH_MPI
846
      snprintf(dumpfile, 40, "threadpool_info-rank%d-step%d.dat", engine_rank,
847
848
               j + 1);
#else
849
      snprintf(dumpfile, 40, "threadpool_info-step%d.dat", j + 1);
850
#endif  // WITH_MPI
851
852
853
854
855
      threadpool_dump_log(&e.threadpool, dumpfile, 1);
    } else {
      threadpool_reset_log(&e.threadpool);
    }
#endif  // SWIFT_DEBUG_THREADPOOL
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
856
  }
857
858

/* Print the values of the runner histogram. */
859
#ifdef HIST
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
860
861
862
863
864
865
866
  printf("main: runner histogram data:\n");
  for (k = 0; k < runner_hist_N; k++)
    printf(" %e %e %e\n",
           runner_hist_a + k * (runner_hist_b - runner_hist_a) / runner_hist_N,
           runner_hist_a +
               (k + 1) * (runner_hist_b - runner_hist_a) / runner_hist_N,
           (double)runner_hist_bins[k]);
867
#endif
Pedro Gonnet's avatar
Pedro Gonnet committed
868

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
869
  /* Write final output. */
870
  engine_drift_all(&e);
871
  engine_print_stats(&e);
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
872
  engine_dump_snapshot(&e);
873

874
#ifdef WITH_MPI
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
875
876
  if ((res = MPI_Finalize()) != MPI_SUCCESS)
    error("call to MPI_Finalize failed with error %i.", res);
877
#endif
878

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
879
  /* Clean everything */
880
  if (with_verbose_timers) timers_close_file();
Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
881
882
  engine_clean(&e);
  free(params);
883

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
884
885
  /* Say goodbye. */
  if (myrank == 0) message("done. Bye.");
886

Pedro Gonnet's avatar
oops.    
Pedro Gonnet committed
887
888
  /* All is calm, all is bright. */
  return 0;
889
}