space.c 92.7 KB
Newer Older
1
/*******************************************************************************
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 * This file is part of SWIFT.
 * Copyright (c) 2012 Pedro Gonnet (pedro.gonnet@durham.ac.uk)
 *                    Matthieu Schaller (matthieu.schaller@durham.ac.uk)
 *               2015 Peter W. Draper (p.w.draper@durham.ac.uk)
 *               2016 John A. Regan (john.a.regan@durham.ac.uk)
 *                    Tom Theuns (tom.theuns@durham.ac.uk)
 *
 * 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.
 *
 * 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.
 *
 * 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/>.
 *
 ******************************************************************************/
Pedro Gonnet's avatar
Pedro Gonnet committed
23
24
25
26
27
28
29
30

/* Config parameters. */
#include "../config.h"

/* Some standard headers. */
#include <float.h>
#include <limits.h>
#include <math.h>
31
#include <stdlib.h>
32
#include <string.h>
Pedro Gonnet's avatar
Pedro Gonnet committed
33

34
35
/* MPI headers. */
#ifdef WITH_MPI
36
#include <mpi.h>
37
38
#endif

39
40
41
/* This object's header. */
#include "space.h"

Pedro Gonnet's avatar
Pedro Gonnet committed
42
/* Local headers. */
43
#include "atomic.h"
44
#include "const.h"
45
#include "cooling.h"
46
#include "engine.h"
47
#include "error.h"
48
49
#include "gravity.h"
#include "hydro.h"
50
#include "kernel_hydro.h"
51
#include "lock.h"
52
#include "memswap.h"
53
#include "minmax.h"
54
#include "multipole.h"
55
#include "runner.h"
56
#include "sort_part.h"
57
#include "stars.h"
58
#include "threadpool.h"
59
#include "tools.h"
Pedro Gonnet's avatar
Pedro Gonnet committed
60
61
62

/* Split size. */
int space_splitsize = space_splitsize_default;
63
int space_subsize = space_subsize_default;
64
int space_maxsize = space_maxsize_default;
65
int space_maxcount = space_maxcount_default;
Pedro Gonnet's avatar
Pedro Gonnet committed
66

67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
 * @brief Interval stack necessary for parallel particle sorting.
 */
struct qstack {
  volatile ptrdiff_t i, j;
  volatile int min, max;
  volatile int ready;
};

/**
 * @brief Parallel particle-sorting stack
 */
struct parallel_sort {
  struct part *parts;
  struct gpart *gparts;
  struct xpart *xparts;
83
  struct spart *sparts;
84
85
86
87
88
89
  int *ind;
  struct qstack *stack;
  unsigned int stack_size;
  volatile unsigned int first, last, waiting;
};

90
91
92
93
94
95
96
97
98
/**
 * @brief Information required to compute the particle cell indices.
 */
struct index_data {
  struct space *s;
  struct cell *cells;
  int *ind;
};

99
100
101
102
103
104
105
106
107
108
109
/**
 * @brief Get the shift-id of the given pair of cells, swapping them
 *      if need be.
 *
 * @param s The space
 * @param ci Pointer to first #cell.
 * @param cj Pointer second #cell.
 * @param shift Vector from ci to cj.
 *
 * @return The shift ID and set shift, may or may not swap ci and cj.
 */
110
111
112
113
int space_getsid(struct space *s, struct cell **ci, struct cell **cj,
                 double *shift) {

  /* Get the relative distance between the pairs, wrapping. */
114
115
116
  const int periodic = s->periodic;
  double dx[3];
  for (int k = 0; k < 3; k++) {
117
118
119
120
121
122
123
124
125
126
127
    dx[k] = (*cj)->loc[k] - (*ci)->loc[k];
    if (periodic && dx[k] < -s->dim[k] / 2)
      shift[k] = s->dim[k];
    else if (periodic && dx[k] > s->dim[k] / 2)
      shift[k] = -s->dim[k];
    else
      shift[k] = 0.0;
    dx[k] += shift[k];
  }

  /* Get the sorting index. */
128
  int sid = 0;
129
  for (int k = 0; k < 3; k++)
130
131
132
133
    sid = 3 * sid + ((dx[k] < 0.0) ? 0 : ((dx[k] > 0.0) ? 2 : 1));

  /* Switch the cells around? */
  if (runner_flip[sid]) {
134
    struct cell *temp = *ci;
135
136
    *ci = *cj;
    *cj = temp;
137
    for (int k = 0; k < 3; k++) shift[k] = -shift[k];
138
139
140
141
142
143
  }
  sid = sortlistID[sid];

  /* Return the sort ID. */
  return sid;
}
144

145
/**
146
 * @brief Recursively dismantle a cell tree.
147
 *
148
149
 * @param s The #space.
 * @param c The #cell to recycle.
Matthieu Schaller's avatar
Matthieu Schaller committed
150
151
152
153
154
155
 * @param cell_rec_begin Pointer to the start of the list of cells to recycle.
 * @param cell_rec_end Pointer to the end of the list of cells to recycle.
 * @param multipole_rec_begin Pointer to the start of the list of multipoles to
 * recycle.
 * @param multipole_rec_end Pointer to the end of the list of multipoles to
 * recycle.
156
 */
157
void space_rebuild_recycle_rec(struct space *s, struct cell *c,
158
159
                               struct cell **cell_rec_begin,
                               struct cell **cell_rec_end,
160
161
                               struct gravity_tensors **multipole_rec_begin,
                               struct gravity_tensors **multipole_rec_end) {
162
  if (c->split)
163
    for (int k = 0; k < 8; k++)
164
      if (c->progeny[k] != NULL) {
165
166
167
168
169
170
        space_rebuild_recycle_rec(s, c->progeny[k], cell_rec_begin,
                                  cell_rec_end, multipole_rec_begin,
                                  multipole_rec_end);

        c->progeny[k]->next = *cell_rec_begin;
        *cell_rec_begin = c->progeny[k];
171
172
173
174
175

        if (s->gravity) {
          c->progeny[k]->multipole->next = *multipole_rec_begin;
          *multipole_rec_begin = c->progeny[k]->multipole;
        }
176
177

        if (*cell_rec_end == NULL) *cell_rec_end = *cell_rec_begin;
178
        if (s->gravity && *multipole_rec_end == NULL)
179
180
181
          *multipole_rec_end = *multipole_rec_begin;

        c->progeny[k]->multipole = NULL;
182
183
184
185
        c->progeny[k] = NULL;
      }
}

186
187
188
189
190
191
192
193
void space_rebuild_recycle_mapper(void *map_data, int num_elements,
                                  void *extra_data) {

  struct space *s = (struct space *)extra_data;
  struct cell *cells = (struct cell *)map_data;

  for (int k = 0; k < num_elements; k++) {
    struct cell *c = &cells[k];
194
    struct cell *cell_rec_begin = NULL, *cell_rec_end = NULL;
195
196
    struct gravity_tensors *multipole_rec_begin = NULL,
                           *multipole_rec_end = NULL;
197
198
199
200
201
    space_rebuild_recycle_rec(s, c, &cell_rec_begin, &cell_rec_end,
                              &multipole_rec_begin, &multipole_rec_end);
    if (cell_rec_begin != NULL)
      space_recycle_list(s, cell_rec_begin, cell_rec_end, multipole_rec_begin,
                         multipole_rec_end);
202
203
204
205
206
207
208
209
210
211
    c->sorts = NULL;
    c->nr_tasks = 0;
    c->density = NULL;
    c->gradient = NULL;
    c->force = NULL;
    c->grav = NULL;
    c->dx_max = 0.0f;
    c->sorted = 0;
    c->count = 0;
    c->gcount = 0;
212
    c->scount = 0;
213
214
215
    c->init = NULL;
    c->extra_ghost = NULL;
    c->ghost = NULL;
216
217
    c->kick1 = NULL;
    c->kick2 = NULL;
218
    c->timestep = NULL;
219
    c->drift = NULL;
220
221
    c->cooling = NULL;
    c->sourceterms = NULL;
222
223
224
    c->grav_top_level = NULL;
    c->grav_long_range = NULL;
    c->grav_down = NULL;
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
    c->super = c;
    if (c->sort != NULL) {
      free(c->sort);
      c->sort = NULL;
    }
#if WITH_MPI
    c->recv_xv = NULL;
    c->recv_rho = NULL;
    c->recv_gradient = NULL;
    c->recv_ti = NULL;

    c->send_xv = NULL;
    c->send_rho = NULL;
    c->send_gradient = NULL;
    c->send_ti = NULL;
#endif
  }
}

244
/**
245
 * @brief Re-build the top-level cell grid.
246
 *
247
 * @param s The #space.
248
 * @param verbose Print messages to stdout or not.
249
 */
250
void space_regrid(struct space *s, int verbose) {
251

252
  const size_t nr_parts = s->nr_parts;
253
  const ticks tic = getticks();
254
  const integertime_t ti_old = (s->e != NULL) ? s->e->ti_old : 0;
255

256
  /* Run through the cells and get the current h_max. */
257
  // tic = getticks();
258
  float h_max = s->cell_min / kernel_gamma / space_stretch;
259
  if (nr_parts > 0) {
260
    if (s->cells_top != NULL) {
Tom Theuns's avatar
Tom Theuns committed
261
      for (int k = 0; k < s->nr_cells; k++) {
262
263
264
        if (s->cells_top[k].nodeID == engine_rank &&
            s->cells_top[k].h_max > h_max) {
          h_max = s->cells_top[k].h_max;
265
        }
266
267
      }
    } else {
268
      for (size_t k = 0; k < nr_parts; k++) {
Matthieu Schaller's avatar
Matthieu Schaller committed
269
        if (s->parts[k].h > h_max) h_max = s->parts[k].h;
270
      }
271
272
273
274
275
276
277
278
279
280
    }
  }

/* If we are running in parallel, make sure everybody agrees on
   how large the largest cell should be. */
#ifdef WITH_MPI
  {
    float buff;
    if (MPI_Allreduce(&h_max, &buff, 1, MPI_FLOAT, MPI_MAX, MPI_COMM_WORLD) !=
        MPI_SUCCESS)
281
      error("Failed to aggregate the rebuild flag across nodes.");
282
283
284
    h_max = buff;
  }
#endif
285
  if (verbose) message("h_max is %.3e (cell_min=%.3e).", h_max, s->cell_min);
286
287

  /* Get the new putative cell dimensions. */
288
  const int cdim[3] = {
289
290
291
292
293
294
      floor(s->dim[0] /
            fmax(h_max * kernel_gamma * space_stretch, s->cell_min)),
      floor(s->dim[1] /
            fmax(h_max * kernel_gamma * space_stretch, s->cell_min)),
      floor(s->dim[2] /
            fmax(h_max * kernel_gamma * space_stretch, s->cell_min))};
295
296
297
298
299

  /* Check if we have enough cells for periodicity. */
  if (s->periodic && (cdim[0] < 3 || cdim[1] < 3 || cdim[2] < 3))
    error(
        "Must have at least 3 cells in each spatial dimension when periodicity "
300
301
302
        "is switched on.\nThis error is often caused by any of the "
        "followings:\n"
        " - too few particles to generate a sensible grid,\n"
303
304
        " - the initial value of 'Scheduler:max_top_level_cells' is too "
        "small,\n"
305
        " - the (minimal) time-step is too large leading to particles with "
306
307
308
        "predicted smoothing lengths too large for the box size,\n"
        " - particle with velocities so large that they move by more than two "
        "box sizes per time-step.\n");
309

310
311
312
313
314
315
  /* Check if we have enough cells for gravity. */
  if (s->gravity && (cdim[0] < 8 || cdim[1] < 8 || cdim[2] < 8))
    error(
        "Must have at least 8 cells in each spatial dimension when gravity "
        "is switched on.");

316
317
318
/* In MPI-Land, changing the top-level cell size requires that the
 * global partition is recomputed and the particles redistributed.
 * Be prepared to do that. */
319
#ifdef WITH_MPI
Matthieu Schaller's avatar
Matthieu Schaller committed
320
  double oldwidth[3];
321
322
323
324
325
326
327
328
  double oldcdim[3];
  int *oldnodeIDs = NULL;
  if (cdim[0] < s->cdim[0] || cdim[1] < s->cdim[1] || cdim[2] < s->cdim[2]) {

    /* Capture state of current space. */
    oldcdim[0] = s->cdim[0];
    oldcdim[1] = s->cdim[1];
    oldcdim[2] = s->cdim[2];
329
330
331
    oldwidth[0] = s->width[0];
    oldwidth[1] = s->width[1];
    oldwidth[2] = s->width[2];
332
333
334
335
336
337
338
339
340

    if ((oldnodeIDs = (int *)malloc(sizeof(int) * s->nr_cells)) == NULL)
      error("Failed to allocate temporary nodeIDs.");

    int cid = 0;
    for (int i = 0; i < s->cdim[0]; i++) {
      for (int j = 0; j < s->cdim[1]; j++) {
        for (int k = 0; k < s->cdim[2]; k++) {
          cid = cell_getid(oldcdim, i, j, k);
341
          oldnodeIDs[cid] = s->cells_top[cid].nodeID;
342
343
344
345
346
        }
      }
    }
  }

347
348
349
350
#endif

  /* Do we need to re-build the upper-level cells? */
  // tic = getticks();
351
  if (s->cells_top == NULL || cdim[0] < s->cdim[0] || cdim[1] < s->cdim[1] ||
352
353
      cdim[2] < s->cdim[2]) {

354
355
356
357
358
359
/* Be verbose about this. */
#ifdef SWIFT_DEBUG_CHECKS
    message("re)griding space cdim=(%d %d %d)", cdim[0], cdim[1], cdim[2]);
    fflush(stdout);
#endif

360
    /* Free the old cells, if they were allocated. */
361
    if (s->cells_top != NULL) {
362
363
      threadpool_map(&s->e->threadpool, space_rebuild_recycle_mapper,
                     s->cells_top, s->nr_cells, sizeof(struct cell), 100, s);
364
      free(s->cells_top);
365
      free(s->multipoles_top);
366
367
368
369
      s->maxdepth = 0;
    }

    /* Set the new cell dimensions only if smaller. */
370
    for (int k = 0; k < 3; k++) {
371
      s->cdim[k] = cdim[k];
372
373
      s->width[k] = s->dim[k] / cdim[k];
      s->iwidth[k] = 1.0 / s->width[k];
374
    }
375
    const float dmin = min(s->width[0], min(s->width[1], s->width[2]));
376
377
378

    /* Allocate the highest level of cells. */
    s->tot_cells = s->nr_cells = cdim[0] * cdim[1] * cdim[2];
379
    if (posix_memalign((void *)&s->cells_top, cell_align,
380
                       s->nr_cells * sizeof(struct cell)) != 0)
381
      error("Failed to allocate top-level cells.");
382
    bzero(s->cells_top, s->nr_cells * sizeof(struct cell));
383

384
385
386
    /* Allocate the multipoles for the top-level cells. */
    if (s->gravity) {
      if (posix_memalign((void *)&s->multipoles_top, multipole_align,
387
                         s->nr_cells * sizeof(struct gravity_tensors)) != 0)
388
        error("Failed to allocate top-level multipoles.");
389
      bzero(s->multipoles_top, s->nr_cells * sizeof(struct gravity_tensors));
390
391
    }

392
    /* Set the cells' locks */
393
    for (int k = 0; k < s->nr_cells; k++) {
394
      if (lock_init(&s->cells_top[k].lock) != 0)
395
396
397
398
399
400
401
402
        error("Failed to init spinlock for hydro.");
      if (lock_init(&s->cells_top[k].glock) != 0)
        error("Failed to init spinlock for gravity.");
      if (lock_init(&s->cells_top[k].mlock) != 0)
        error("Failed to init spinlock for multipoles.");
      if (lock_init(&s->cells_top[k].slock) != 0)
        error("Failed to init spinlock for stars.");
    }
403
404

    /* Set the cell location and sizes. */
405
406
407
    for (int i = 0; i < cdim[0]; i++)
      for (int j = 0; j < cdim[1]; j++)
        for (int k = 0; k < cdim[2]; k++) {
408
409
          const size_t cid = cell_getid(cdim, i, j, k);
          struct cell *restrict c = &s->cells_top[cid];
410
411
412
413
414
415
          c->loc[0] = i * s->width[0];
          c->loc[1] = j * s->width[1];
          c->loc[2] = k * s->width[2];
          c->width[0] = s->width[0];
          c->width[1] = s->width[1];
          c->width[2] = s->width[2];
416
417
418
419
          c->dmin = dmin;
          c->depth = 0;
          c->count = 0;
          c->gcount = 0;
420
          c->scount = 0;
421
          c->super = c;
422
          c->ti_old = ti_old;
423
          c->ti_old_multipole = ti_old;
424
          if (s->gravity) c->multipole = &s->multipoles_top[cid];
Pedro Gonnet's avatar
Pedro Gonnet committed
425
        }
426
427

    /* Be verbose about the change. */
428
429
430
    if (verbose)
      message("set cell dimensions to [ %i %i %i ].", cdim[0], cdim[1],
              cdim[2]);
431

432
#ifdef WITH_MPI
433
434
435
436
437
    if (oldnodeIDs != NULL) {
      /* We have changed the top-level cell dimension, so need to redistribute
       * cells around the nodes. We repartition using the old space node
       * positions as a grid to resample. */
      if (s->e->nodeID == 0)
438
439
440
        message(
            "basic cell dimensions have increased - recalculating the "
            "global partition.");
441

Matthieu Schaller's avatar
Matthieu Schaller committed
442
      if (!partition_space_to_space(oldwidth, oldcdim, oldnodeIDs, s)) {
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

        /* Failed, try another technique that requires no settings. */
        message("Failed to get a new partition, trying less optimal method");
        struct partition initial_partition;
#ifdef HAVE_METIS
        initial_partition.type = INITPART_METIS_NOWEIGHT;
#else
        initial_partition.type = INITPART_VECTORIZE;
#endif
        partition_initial_partition(&initial_partition, s->e->nodeID,
                                    s->e->nr_nodes, s);
      }

      /* Re-distribute the particles to their new nodes. */
      engine_redistribute(s->e);

      /* Make the proxies. */
      engine_makeproxies(s->e);
461

462
463
      /* Finished with these. */
      free(oldnodeIDs);
464
    }
Pedro Gonnet's avatar
Pedro Gonnet committed
465
#endif /* WITH_MPI */
466
467
468
469

    // message( "rebuilding upper-level cells took %.3f %s." ,
    // clocks_from_ticks(double)(getticks() - tic), clocks_getunit());

470
  }      /* re-build upper-level cells? */
471
  else { /* Otherwise, just clean up the cells. */
472
473

    /* Free the old cells, if they were allocated. */
474
475
    threadpool_map(&s->e->threadpool, space_rebuild_recycle_mapper,
                   s->cells_top, s->nr_cells, sizeof(struct cell), 100, s);
476
477
    s->maxdepth = 0;
  }
478
479
480
481

  if (verbose)
    message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
            clocks_getunit());
482
}
483
484
485
486
487

/**
 * @brief Re-build the cells as well as the tasks.
 *
 * @param s The #space in which to update the cells.
488
 * @param verbose Print messages to stdout or not
489
490
 *
 */
491
void space_rebuild(struct space *s, int verbose) {
492

Matthieu Schaller's avatar
Matthieu Schaller committed
493
  const ticks tic = getticks();
494

495
496
/* Be verbose about this. */
#ifdef SWIFT_DEBUG_CHECKS
Matthieu Schaller's avatar
Matthieu Schaller committed
497
  if (s->e->nodeID == 0 || verbose) message("re)building space");
498
499
  fflush(stdout);
#endif
500
501

  /* Re-grid if necessary, or just re-set the cell data. */
502
  space_regrid(s, verbose);
503

Pedro Gonnet's avatar
Pedro Gonnet committed
504
505
  size_t nr_parts = s->nr_parts;
  size_t nr_gparts = s->nr_gparts;
506
  size_t nr_sparts = s->nr_sparts;
507
  struct cell *restrict cells_top = s->cells_top;
508
  const integertime_t ti_old = (s->e != NULL) ? s->e->ti_old : 0;
509

Pedro Gonnet's avatar
Pedro Gonnet committed
510
511
512
  /* Run through the particles and get their cell index. Allocates
     an index that is larger than the number of particles to avoid
     re-allocating after shuffling. */
513
  const size_t ind_size = s->size_parts + 100;
514
515
  int *ind;
  if ((ind = (int *)malloc(sizeof(int) * ind_size)) == NULL)
516
    error("Failed to allocate temporary particle indices.");
517
  if (s->size_parts > 0) space_parts_get_cell_index(s, ind, cells_top, verbose);
518

519
  /* Run through the gravity particles and get their cell index. */
520
  const size_t gind_size = s->size_gparts + 100;
521
522
523
  int *gind;
  if ((gind = (int *)malloc(sizeof(int) * gind_size)) == NULL)
    error("Failed to allocate temporary g-particle indices.");
Pedro Gonnet's avatar
Pedro Gonnet committed
524
525
  if (s->size_gparts > 0)
    space_gparts_get_cell_index(s, gind, cells_top, verbose);
526

527
528
529
530
531
532
533
534
  /* Run through the star particles and get their cell index. */
  const size_t sind_size = s->size_sparts + 100;
  int *sind;
  if ((sind = (int *)malloc(sizeof(int) * sind_size)) == NULL)
    error("Failed to allocate temporary s-particle indices.");
  if (s->size_sparts > 0)
    space_sparts_get_cell_index(s, sind, cells_top, verbose);

535
#ifdef WITH_MPI
536
  const int local_nodeID = s->e->nodeID;
537

538
  /* Move non-local parts to the end of the list. */
539
  for (size_t k = 0; k < nr_parts;) {
540
    if (cells_top[ind[k]].nodeID != local_nodeID) {
541
      nr_parts -= 1;
542
      /* Swap the particle */
Matthieu Schaller's avatar
Bug fix    
Matthieu Schaller committed
543
      const struct part tp = s->parts[k];
544
545
      s->parts[k] = s->parts[nr_parts];
      s->parts[nr_parts] = tp;
546
      /* Swap the link with the gpart */
547
      if (s->parts[k].gpart != NULL) {
548
        s->parts[k].gpart->id_or_neg_offset = -k;
549
550
      }
      if (s->parts[nr_parts].gpart != NULL) {
551
        s->parts[nr_parts].gpart->id_or_neg_offset = -nr_parts;
552
      }
553
      /* Swap the xpart */
Matthieu Schaller's avatar
Bug fix    
Matthieu Schaller committed
554
      const struct xpart txp = s->xparts[k];
555
556
      s->xparts[k] = s->xparts[nr_parts];
      s->xparts[nr_parts] = txp;
557
      /* Swap the index */
Matthieu Schaller's avatar
Bug fix    
Matthieu Schaller committed
558
      const int t = ind[k];
559
560
      ind[k] = ind[nr_parts];
      ind[nr_parts] = t;
Matthieu Schaller's avatar
Matthieu Schaller committed
561
    } else {
562
563
564
565
      /* Increment when not exchanging otherwise we need to retest "k".*/
      k++;
    }
  }
566

567
#ifdef SWIFT_DEBUG_CHECKS
Peter W. Draper's avatar
Peter W. Draper committed
568
  /* Check that all parts are in the correct places. */
569
  for (size_t k = 0; k < nr_parts; k++) {
570
    if (cells_top[ind[k]].nodeID != local_nodeID) {
571
572
573
574
      error("Failed to move all non-local parts to send list");
    }
  }
  for (size_t k = nr_parts; k < s->nr_parts; k++) {
575
    if (cells_top[ind[k]].nodeID == local_nodeID) {
576
      error("Failed to remove local parts from send list");
577
    }
578
579
  }
#endif
580

581
582
583
584
585
586
587
588
589
590
591
592
  /* Move non-local sparts to the end of the list. */
  for (size_t k = 0; k < nr_sparts;) {
    if (cells_top[sind[k]].nodeID != local_nodeID) {
      nr_sparts -= 1;
      /* Swap the particle */
      const struct spart tp = s->sparts[k];
      s->sparts[k] = s->sparts[nr_sparts];
      s->sparts[nr_sparts] = tp;
      /* Swap the link with the gpart */
      if (s->sparts[k].gpart != NULL) {
        s->sparts[k].gpart->id_or_neg_offset = -k;
      }
593
594
      if (s->sparts[nr_sparts].gpart != NULL) {
        s->sparts[nr_sparts].gpart->id_or_neg_offset = -nr_sparts;
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
      }
      /* Swap the index */
      const int t = sind[k];
      sind[k] = sind[nr_sparts];
      sind[nr_sparts] = t;
    } else {
      /* Increment when not exchanging otherwise we need to retest "k".*/
      k++;
    }
  }

#ifdef SWIFT_DEBUG_CHECKS
  /* Check that all sparts are in the correct place (untested). */
  for (size_t k = 0; k < nr_sparts; k++) {
    if (cells_top[sind[k]].nodeID != local_nodeID) {
      error("Failed to move all non-local sparts to send list");
    }
  }
  for (size_t k = nr_sparts; k < s->nr_sparts; k++) {
    if (cells_top[sind[k]].nodeID == local_nodeID) {
      error("Failed to remove local sparts from send list");
    }
  }
#endif

620
  /* Move non-local gparts to the end of the list. */
621
  for (size_t k = 0; k < nr_gparts;) {
622
    if (cells_top[gind[k]].nodeID != local_nodeID) {
623
      nr_gparts -= 1;
624
      /* Swap the particle */
Matthieu Schaller's avatar
Bug fix    
Matthieu Schaller committed
625
      const struct gpart tp = s->gparts[k];
626
627
      s->gparts[k] = s->gparts[nr_gparts];
      s->gparts[nr_gparts] = tp;
628
629
      /* Swap the link with part/spart */
      if (s->gparts[k].type == swift_type_gas) {
630
        s->parts[-s->gparts[k].id_or_neg_offset].gpart = &s->gparts[k];
631
632
      } else if (s->gparts[k].type == swift_type_star) {
        s->sparts[-s->gparts[k].id_or_neg_offset].gpart = &s->gparts[k];
633
      }
634
      if (s->gparts[nr_gparts].type == swift_type_gas) {
635
636
        s->parts[-s->gparts[nr_gparts].id_or_neg_offset].gpart =
            &s->gparts[nr_gparts];
637
638
639
      } else if (s->gparts[nr_gparts].type == swift_type_star) {
        s->sparts[-s->gparts[nr_gparts].id_or_neg_offset].gpart =
            &s->gparts[nr_gparts];
640
      }
641
      /* Swap the index */
Matthieu Schaller's avatar
Bug fix    
Matthieu Schaller committed
642
643
644
      const int t = gind[k];
      gind[k] = gind[nr_gparts];
      gind[nr_gparts] = t;
Matthieu Schaller's avatar
Matthieu Schaller committed
645
    } else {
646
647
648
649
      /* Increment when not exchanging otherwise we need to retest "k".*/
      k++;
    }
  }
650

651
#ifdef SWIFT_DEBUG_CHECKS
652
653
  /* Check that all gparts are in the correct place (untested). */
  for (size_t k = 0; k < nr_gparts; k++) {
654
    if (cells_top[gind[k]].nodeID != local_nodeID) {
655
656
657
658
      error("Failed to move all non-local gparts to send list");
    }
  }
  for (size_t k = nr_gparts; k < s->nr_gparts; k++) {
659
    if (cells_top[gind[k]].nodeID == local_nodeID) {
660
      error("Failed to remove local gparts from send list");
661
    }
662
663
  }
#endif
664

665
666
  /* Exchange the strays, note that this potentially re-allocates
     the parts arrays. */
667
  size_t nr_parts_exchanged = s->nr_parts - nr_parts;
668
  size_t nr_gparts_exchanged = s->nr_gparts - nr_gparts;
669
  size_t nr_sparts_exchanged = s->nr_sparts - nr_sparts;
Pedro Gonnet's avatar
Pedro Gonnet committed
670
  engine_exchange_strays(s->e, nr_parts, &ind[nr_parts], &nr_parts_exchanged,
671
672
                         nr_gparts, &gind[nr_gparts], &nr_gparts_exchanged,
                         nr_sparts, &sind[nr_sparts], &nr_sparts_exchanged);
Pedro Gonnet's avatar
Pedro Gonnet committed
673
674

  /* Set the new particle counts. */
675
  s->nr_parts = nr_parts + nr_parts_exchanged;
676
  s->nr_gparts = nr_gparts + nr_gparts_exchanged;
677
  s->nr_sparts = nr_sparts + nr_sparts_exchanged;
678

679
  /* Re-allocate the index array for the parts if needed.. */
680
  if (s->nr_parts + 1 > ind_size) {
681
    int *ind_new;
682
    if ((ind_new = (int *)malloc(sizeof(int) * (s->nr_parts + 1))) == NULL)
683
      error("Failed to allocate temporary particle indices.");
684
    memcpy(ind_new, ind, sizeof(int) * nr_parts);
685
686
    free(ind);
    ind = ind_new;
687
688
  }

689
  /* Re-allocate the index array for the sparts if needed.. */
690
  if (s->nr_sparts + 1 > sind_size) {
691
692
    int *sind_new;
    if ((sind_new = (int *)malloc(sizeof(int) * (s->nr_sparts + 1))) == NULL)
693
      error("Failed to allocate temporary s-particle indices.");
694
695
696
697
698
    memcpy(sind_new, sind, sizeof(int) * nr_sparts);
    free(sind);
    sind = sind_new;
  }

699
700
701
  const int cdim[3] = {s->cdim[0], s->cdim[1], s->cdim[2]};
  const double ih[3] = {s->iwidth[0], s->iwidth[1], s->iwidth[2]};

702
  /* Assign each received part to its cell. */
Pedro Gonnet's avatar
Pedro Gonnet committed
703
  for (size_t k = nr_parts; k < s->nr_parts; k++) {
Matthieu Schaller's avatar
Matthieu Schaller committed
704
    const struct part *const p = &s->parts[k];
705
    ind[k] =
706
        cell_getid(cdim, p->x[0] * ih[0], p->x[1] * ih[1], p->x[2] * ih[2]);
707
#ifdef SWIFT_DEBUG_CHECKS
708
    if (cells_top[ind[k]].nodeID != local_nodeID)
709
      error("Received part that does not belong to me (nodeID=%i).",
710
            cells_top[ind[k]].nodeID);
711
#endif
712
  }
713
  nr_parts = s->nr_parts;
714

715
  /* Assign each received spart to its cell. */
716
717
718
719
720
721
  for (size_t k = nr_sparts; k < s->nr_sparts; k++) {
    const struct spart *const sp = &s->sparts[k];
    sind[k] =
        cell_getid(cdim, sp->x[0] * ih[0], sp->x[1] * ih[1], sp->x[2] * ih[2]);
#ifdef SWIFT_DEBUG_CHECKS
    if (cells_top[sind[k]].nodeID != local_nodeID)
722
      error("Received s-part that does not belong to me (nodeID=%i).",
723
724
725
726
727
            cells_top[sind[k]].nodeID);
#endif
  }
  nr_sparts = s->nr_sparts;

728
#endif /* WITH_MPI */
729
730

  /* Sort the parts according to their cells. */
731
732
  if (nr_parts > 0)
    space_parts_sort(s, ind, nr_parts, 0, s->nr_cells - 1, verbose);
733

734
735
736
#ifdef SWIFT_DEBUG_CHECKS
  /* Verify that the part have been sorted correctly. */
  for (size_t k = 0; k < nr_parts; k++) {
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
    const struct part *p = &s->parts[k];

    /* New cell index */
    const int new_ind =
        cell_getid(s->cdim, p->x[0] * s->iwidth[0], p->x[1] * s->iwidth[1],
                   p->x[2] * s->iwidth[2]);

    /* New cell of this part */
    const struct cell *c = &s->cells_top[new_ind];

    if (ind[k] != new_ind)
      error("part's new cell index not matching sorted index.");

    if (p->x[0] < c->loc[0] || p->x[0] > c->loc[0] + c->width[0] ||
        p->x[1] < c->loc[1] || p->x[1] > c->loc[1] + c->width[1] ||
        p->x[2] < c->loc[2] || p->x[2] > c->loc[2] + c->width[2])
753
754
755
756
      error("part not sorted into the right top-level cell!");
  }
#endif

757
758
759
760
  /* Sort the sparts according to their cells. */
  if (nr_sparts > 0)
    space_sparts_sort(s, sind, nr_sparts, 0, s->nr_cells - 1, verbose);

761
762
763
#ifdef SWIFT_DEBUG_CHECKS
  /* Verify that the spart have been sorted correctly. */
  for (size_t k = 0; k < nr_sparts; k++) {
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
    const struct spart *sp = &s->sparts[k];

    /* New cell index */
    const int new_sind =
        cell_getid(s->cdim, sp->x[0] * s->iwidth[0], sp->x[1] * s->iwidth[1],
                   sp->x[2] * s->iwidth[2]);

    /* New cell of this spart */
    const struct cell *c = &s->cells_top[new_sind];

    if (sind[k] != new_sind)
      error("spart's new cell index not matching sorted index.");

    if (sp->x[0] < c->loc[0] || sp->x[0] > c->loc[0] + c->width[0] ||
        sp->x[1] < c->loc[1] || sp->x[1] > c->loc[1] + c->width[1] ||
        sp->x[2] < c->loc[2] || sp->x[2] > c->loc[2] + c->width[2])
780
781
782
783
      error("spart not sorted into the right top-level cell!");
  }
#endif

784
785
786
787
788
  /* Re-link the gparts to their (s-)particles. */
  if (nr_parts > 0 && nr_gparts > 0)
    part_relink_gparts_to_parts(s->parts, nr_parts, 0);
  if (nr_sparts > 0 && nr_gparts > 0)
    part_relink_gparts_to_sparts(s->sparts, nr_sparts, 0);
789

790
791
792
793
794
795
796
797
798
799
  /* Extract the cell counts from the sorted indices. */
  size_t last_index = 0;
  ind[nr_parts] = s->nr_cells;  // sentinel.
  for (size_t k = 0; k < nr_parts; k++) {
    if (ind[k] < ind[k + 1]) {
      cells_top[ind[k]].count = k - last_index + 1;
      last_index = k + 1;
    }
  }

800
801
  /* Extract the cell counts from the sorted indices. */
  size_t last_sindex = 0;
802
  sind[nr_sparts] = s->nr_cells;  // sentinel.
803
804
805
806
807
808
809
  for (size_t k = 0; k < nr_sparts; k++) {
    if (sind[k] < sind[k + 1]) {
      cells_top[sind[k]].scount = k - last_sindex + 1;
      last_sindex = k + 1;
    }
  }

810
  /* We no longer need the indices as of here. */
811
  free(ind);
812
  free(sind);
813

814
815
#ifdef WITH_MPI

816
  /* Re-allocate the index array for the gparts if needed.. */
817
  if (s->nr_gparts + 1 > gind_size) {
818
    int *gind_new;
819
    if ((gind_new = (int *)malloc(sizeof(int) * (s->nr_gparts + 1))) == NULL)
820
      error("Failed to allocate temporary g-particle indices.");
821
    memcpy(gind_new, gind, sizeof(int) * nr_gparts);
822
823
824
825
    free(gind);
    gind = gind_new;
  }

826
  /* Assign each received gpart to its cell. */
827
  for (size_t k = nr_gparts; k < s->nr_gparts; k++) {
Matthieu Schaller's avatar
Matthieu Schaller committed
828
    const struct gpart *const p = &s->gparts[k];
829
830
    gind[k] =
        cell_getid(cdim, p->x[0] * ih[0], p->x[1] * ih[1], p->x[2] * ih[2]);
831
832

#ifdef SWIFT_DEBUG_CHECKS
833
    if (cells_top[gind[k]].nodeID != s->e->nodeID)
834
      error("Received g-part that does not belong to me (nodeID=%i).",
835
            cells_top[gind[k]].nodeID);
836
#endif
837
838
839
  }
  nr_gparts = s->nr_gparts;

840
#endif /* WITH_MPI */
841

842
  /* Sort the gparts according to their cells. */
843
844
  if (nr_gparts > 0)
    space_gparts_sort(s, gind, nr_gparts, 0, s->nr_cells - 1, verbose);
845

846
847
848
#ifdef SWIFT_DEBUG_CHECKS
  /* Verify that the gpart have been sorted correctly. */
  for (size_t k = 0; k < nr_gparts; k++) {
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
    const struct gpart *gp = &s->gparts[k];

    /* New cell index */
    const int new_gind =
        cell_getid(s->cdim, gp->x[0] * s->iwidth[0], gp->x[1] * s->iwidth[1],
                   gp->x[2] * s->iwidth[2]);

    /* New cell of this gpart */
    const struct cell *c = &s->cells_top[new_gind];

    if (gind[k] != new_gind)
      error("gpart's new cell index not matching sorted index.");

    if (gp->x[0] < c->loc[0] || gp->x[0] > c->loc[0] + c->width[0] ||
        gp->x[1] < c->loc[1] || gp->x[1] > c->loc[1] + c->width[1] ||
        gp->x[2] < c->loc[2] || gp->x[2] > c->loc[2] + c->width[2])
865
866
867
868
      error("gpart not sorted into the right top-level cell!");
  }
#endif

869
  /* Re-link the parts. */
870
  if (nr_parts > 0 && nr_gparts > 0)
871
872
873
874
875
    part_relink_parts_to_gparts(s->gparts, nr_gparts, s->parts);

  /* Re-link the sparts. */
  if (nr_sparts > 0 && nr_gparts > 0)
    part_relink_sparts_to_gparts(s->gparts, nr_gparts, s->sparts);
876

877
878
  /* Extract the cell counts from the sorted indices. */
  size_t last_gindex = 0;
879
  gind[nr_gparts] = s->nr_cells;
880
881
  for (size_t k = 0; k < nr_gparts; k++) {
    if (gind[k] < gind[k + 1]) {
882
      cells_top[gind[k]].gcount = k - last_gindex + 1;
883
884
885
886
      last_gindex = k + 1;
    }
  }

887
  /* We no longer need the indices as of here. */
888
  free(gind);
889

890
#ifdef SWIFT_DEBUG_CHECKS
891
  /* Verify that the links are correct */
892
  part_verify_links(s->parts, s->gparts, s->sparts, nr_parts, nr_gparts,
893
                    nr_sparts, verbose);
894
#endif
895

896
897
  /* Hook the cells up to the parts. */
  // tic = getticks();
898
899
900
  struct part *finger = s->parts;
  struct xpart *xfinger = s->xparts;
  struct gpart *gfinger = s->gparts;
901
  struct spart *sfinger = s->sparts;
902
  for (int k = 0; k < s->nr_cells; k++) {
903
    struct cell *restrict c = &cells_top[k];
904
    c->ti_old = ti_old;
905
    c->ti_old_multipole = ti_old;
906
907
908
    c->parts = finger;
    c->xparts = xfinger;
    c->gparts = gfinger;
909
    c->sparts = sfinger;
910
911
912
    finger = &finger[c->count];
    xfinger = &xfinger[c->count];
    gfinger = &gfinger[c->gcount];
913
    sfinger = &sfinger[c->scount];
914
  }
915
  // message( "hooking up cells took %.3f %s." ,
Matthieu Schaller's avatar
Matthieu Schaller committed
916
  // clocks_from_ticks(getticks() - tic), clocks_getunit());
917
918
919

  /* At this point, we have the upper-level cells, old or new. Now make
     sure that the parts in each cell are ok. */
920
  space_split(s, cells_top, s->nr_cells, verbose);
921

922
923
#ifdef SWIFT_DEBUG_CHECKS
  /* Check that the multipole construction went OK */
924
925
926
  if (s->gravity)
    for (int k = 0; k < s->nr_cells; k++)
      cell_check_multipole(&s->cells_top[k], NULL);
927
928
#endif

929
930
931
932
933
934
935
936
  if (verbose)
    message("took %.3f %s.", clocks_from_ticks(getticks() - tic),
            clocks_getunit());
}

/**
 * @brief Split particles between cells of a hierarchy
 *
937
938
 * This is done in parallel using threads in the #threadpool.
 *
939
 * @param s The #space.
940
941
 * @param cells The cell hierarchy.
 * @param nr_cells The number of cells.
942
943
 * @param verbose Are we talkative ?
 */
944
945
void space_split(struct space *s, struct cell *cells, int nr_cells,
                 int verbose) {