mesh_gravity.c 26.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
23
24
25
26
27
28
29
30
/*******************************************************************************
 * This file is part of SWIFT.
 * Copyright (c) 2016 Matthieu Schaller (matthieu.schaller@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/>.
 *
 ******************************************************************************/

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

#ifdef HAVE_FFTW
#include <fftw3.h>
#endif

/* This object's header. */
#include "mesh_gravity.h"

/* Local includes. */
31
#include "accumulate.h"
32
33
34
35
36
37
38
#include "active.h"
#include "debug.h"
#include "engine.h"
#include "error.h"
#include "gravity_properties.h"
#include "kernel_long_gravity.h"
#include "part.h"
39
#include "restart.h"
40
41
#include "runner.h"
#include "space.h"
42
#include "threadpool.h"
43

44
45
#ifdef HAVE_FFTW

46
47
48
49
50
51
52
53
54
55
56
/**
 * @brief Returns 1D index of a 3D NxNxN array using row-major style.
 *
 * Wraps around in the corresponding dimension if any of the 3 indices is >= N
 * or < 0.
 *
 * @param i Index along x.
 * @param j Index along y.
 * @param k Index along z.
 * @param N Size of the array along one axis.
 */
57
58
59
__attribute__((always_inline, const)) INLINE static int row_major_id_periodic(
    const int i, const int j, const int k, const int N) {

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
  return (((i + N) % N) * N * N + ((j + N) % N) * N + ((k + N) % N));
}

/**
 * @brief Interpolate values from a the mesh using CIC.
 *
 * @param mesh The mesh to read from.
 * @param i The index of the cell along x
 * @param j The index of the cell along y
 * @param k The index of the cell along z
 * @param tx First CIC coefficient along x
 * @param ty First CIC coefficient along y
 * @param tz First CIC coefficient along z
 * @param dx Second CIC coefficient along x
 * @param dy Second CIC coefficient along y
 * @param dz Second CIC coefficient along z
 */
77
__attribute__((always_inline, const)) INLINE static double CIC_get(
78
    double mesh[6][6][6], const int i, const int j, const int k,
79
80
    const double tx, const double ty, const double tz, const double dx,
    const double dy, const double dz) {
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111

  double temp;
  temp = mesh[i + 0][j + 0][k + 0] * tx * ty * tz;
  temp += mesh[i + 0][j + 0][k + 1] * tx * ty * dz;
  temp += mesh[i + 0][j + 1][k + 0] * tx * dy * tz;
  temp += mesh[i + 0][j + 1][k + 1] * tx * dy * dz;
  temp += mesh[i + 1][j + 0][k + 0] * dx * ty * tz;
  temp += mesh[i + 1][j + 0][k + 1] * dx * ty * dz;
  temp += mesh[i + 1][j + 1][k + 0] * dx * dy * tz;
  temp += mesh[i + 1][j + 1][k + 1] * dx * dy * dz;

  return temp;
}

/**
 * @brief Interpolate a value to a mesh using CIC.
 *
 * @param mesh The mesh to write to
 * @param N The side-length of the mesh
 * @param i The index of the cell along x
 * @param j The index of the cell along y
 * @param k The index of the cell along z
 * @param tx First CIC coefficient along x
 * @param ty First CIC coefficient along y
 * @param tz First CIC coefficient along z
 * @param dx Second CIC coefficient along x
 * @param dy Second CIC coefficient along y
 * @param dz Second CIC coefficient along z
 * @param value The value to interpolate.
 */
__attribute__((always_inline)) INLINE static void CIC_set(
112
113
114
    double* mesh, const int N, const int i, const int j, const int k,
    const double tx, const double ty, const double tz, const double dx,
    const double dy, const double dz, const double value) {
115
116

  /* Classic CIC interpolation */
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
  atomic_add_d(&mesh[row_major_id_periodic(i + 0, j + 0, k + 0, N)],
               value * tx * ty * tz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 0, j + 0, k + 1, N)],
               value * tx * ty * dz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 0, j + 1, k + 0, N)],
               value * tx * dy * tz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 0, j + 1, k + 1, N)],
               value * tx * dy * dz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 1, j + 0, k + 0, N)],
               value * dx * ty * tz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 1, j + 0, k + 1, N)],
               value * dx * ty * dz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 1, j + 1, k + 0, N)],
               value * dx * dy * tz);
  atomic_add_d(&mesh[row_major_id_periodic(i + 1, j + 1, k + 1, N)],
               value * dx * dy * dz);
133
134
135
136
137
138
139
140
141
142
143
}

/**
 * @brief Assigns a given #gpart to a density mesh using the CIC method.
 *
 * @param gp The #gpart.
 * @param rho The density mesh.
 * @param N the size of the mesh along one axis.
 * @param fac The width of a mesh cell.
 * @param dim The dimensions of the simulation box.
 */
144
145
146
INLINE static void gpart_to_mesh_CIC(const struct gpart* gp, double* rho,
                                     const int N, const double fac,
                                     const double dim[3]) {
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180

  /* Box wrap the multipole's position */
  const double pos_x = box_wrap(gp->x[0], 0., dim[0]);
  const double pos_y = box_wrap(gp->x[1], 0., dim[1]);
  const double pos_z = box_wrap(gp->x[2], 0., dim[2]);

  /* Workout the CIC coefficients */
  int i = (int)(fac * pos_x);
  if (i >= N) i = N - 1;
  const double dx = fac * pos_x - i;
  const double tx = 1. - dx;

  int j = (int)(fac * pos_y);
  if (j >= N) j = N - 1;
  const double dy = fac * pos_y - j;
  const double ty = 1. - dy;

  int k = (int)(fac * pos_z);
  if (k >= N) k = N - 1;
  const double dz = fac * pos_z - k;
  const double tz = 1. - dz;

#ifdef SWIFT_DEBUG_CHECKS
  if (i < 0 || i >= N) error("Invalid gpart position in x");
  if (j < 0 || j >= N) error("Invalid gpart position in y");
  if (k < 0 || k >= N) error("Invalid gpart position in z");
#endif

  const double mass = gp->mass;

  /* CIC ! */
  CIC_set(rho, N, i, j, k, tx, ty, tz, dx, dy, dz, mass);
}

181
182
183
184
185
186
187
188
189
190
/**
 * @brief Assigns all the #gpart of a #cell to a density mesh using the CIC
 * method.
 *
 * @param c The #cell.
 * @param rho The density mesh.
 * @param N the size of the mesh along one axis.
 * @param fac The width of a mesh cell.
 * @param dim The dimensions of the simulation box.
 */
191
192
193
void cell_gpart_to_mesh_CIC(const struct cell* c, double* rho, const int N,
                            const double fac, const double dim[3]) {

194
195
  const int gcount = c->grav.count;
  const struct gpart* gparts = c->grav.parts;
196
197
198
199
200
201

  /* Assign all the gpart of that cell to the mesh */
  for (int i = 0; i < gcount; ++i)
    gpart_to_mesh_CIC(&gparts[i], rho, N, fac, dim);
}

202
/**
203
204
 * @brief Shared information about the mesh to be used by all the threads in the
 * pool.
205
 */
206
207
208
struct cic_mapper_data {
  const struct cell* cells;
  double* rho;
209
210
211
212
213
214
215
216
217
218
219
220
  int N;
  double fac;
  double dim[3];
};

/**
 * @brief Threadpool mapper function for the mesh CIC assignment of a cell.
 *
 * @param map_data A chunk of the list of local cells.
 * @param num The number of cells in the chunk.
 * @param extra The information about the mesh and cells.
 */
221
void cell_gpart_to_mesh_CIC_mapper(void* map_data, int num, void* extra) {
222
223

  /* Unpack the shared information */
224
225
226
  const struct cic_mapper_data* data = (struct cic_mapper_data*)extra;
  const struct cell* cells = data->cells;
  double* rho = data->rho;
227
228
229
230
231
  const int N = data->N;
  const double fac = data->fac;
  const double dim[3] = {data->dim[0], data->dim[1], data->dim[2]};

  /* Pointer to the chunk to be processed */
232
  int* local_cells = (int*)map_data;
233

234
235
236
237
  // MATTHIEU: This could in principle be improved by creating a local mesh
  //           with just the extent required for the cell. Assignment can
  //           then be done without atomics. That local mesh is then added
  //           atomically to the global one.
238

239
240
241
242
  /* Loop over the elements assigned to this thread */
  for (int i = 0; i < num; ++i) {

    /* Pointer to local cell */
243
    const struct cell* c = &cells[local_cells[i]];
244
245
246
247
248
249

    /* Assign this cell's content to the mesh */
    cell_gpart_to_mesh_CIC(c, rho, N, fac, dim);
  }
}

250
251
252
253
254
255
256
257
258
259
260
261
/**
 * @brief Computes the potential on a gpart from a given mesh using the CIC
 * method.
 *
 * Debugging routine.
 *
 * @param gp The #gpart.
 * @param pot The potential mesh.
 * @param N the size of the mesh along one axis.
 * @param fac width of a mesh cell.
 * @param dim The dimensions of the simulation box.
 */
262
263
void mesh_to_gparts_CIC(struct gpart* gp, const double* pot, const int N,
                        const double fac, const double dim[3]) {
264

265
  /* Box wrap the gpart's position */
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
  const double pos_x = box_wrap(gp->x[0], 0., dim[0]);
  const double pos_y = box_wrap(gp->x[1], 0., dim[1]);
  const double pos_z = box_wrap(gp->x[2], 0., dim[2]);

  int i = (int)(fac * pos_x);
  if (i >= N) i = N - 1;
  const double dx = fac * pos_x - i;
  const double tx = 1. - dx;

  int j = (int)(fac * pos_y);
  if (j >= N) j = N - 1;
  const double dy = fac * pos_y - j;
  const double ty = 1. - dy;

  int k = (int)(fac * pos_z);
  if (k >= N) k = N - 1;
  const double dz = fac * pos_z - k;
  const double tz = 1. - dz;

#ifdef SWIFT_DEBUG_CHECKS
Matthieu Schaller's avatar
Matthieu Schaller committed
286
287
288
  if (i < 0 || i >= N) error("Invalid gpart position in x");
  if (j < 0 || j >= N) error("Invalid gpart position in y");
  if (k < 0 || k >= N) error("Invalid gpart position in z");
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#endif

#ifdef SWIFT_GRAVITY_FORCE_CHECKS
  if (gp->a_grav_PM[0] != 0. || gp->potential_PM != 0.)
    error("Particle with non-initalised stuff");
#endif

  /* First, copy the necessary part of the mesh for stencil operations */
  /* This includes box-wrapping in all 3 dimensions. */
  double phi[6][6][6];
  for (int iii = -2; iii <= 3; ++iii) {
    for (int jjj = -2; jjj <= 3; ++jjj) {
      for (int kkk = -2; kkk <= 3; ++kkk) {
        phi[iii + 2][jjj + 2][kkk + 2] =
            pot[row_major_id_periodic(i + iii, j + jjj, k + kkk, N)];
      }
    }
  }

  /* Some local accumulators */
  double p = 0.;
  double a[3] = {0.};

  /* Indices of (i,j,k) in the local copy of the mesh */
  const int ii = 2, jj = 2, kk = 2;

  /* Simple CIC for the potential itself */
  p += CIC_get(phi, ii, jj, kk, tx, ty, tz, dx, dy, dz);

  /* ---- */

  /* 5-point stencil along each axis for the accelerations */
  a[0] += (1. / 12.) * CIC_get(phi, ii + 2, jj, kk, tx, ty, tz, dx, dy, dz);
  a[0] -= (2. / 3.) * CIC_get(phi, ii + 1, jj, kk, tx, ty, tz, dx, dy, dz);
  a[0] += (2. / 3.) * CIC_get(phi, ii - 1, jj, kk, tx, ty, tz, dx, dy, dz);
  a[0] -= (1. / 12.) * CIC_get(phi, ii - 2, jj, kk, tx, ty, tz, dx, dy, dz);

  a[1] += (1. / 12.) * CIC_get(phi, ii, jj + 2, kk, tx, ty, tz, dx, dy, dz);
  a[1] -= (2. / 3.) * CIC_get(phi, ii, jj + 1, kk, tx, ty, tz, dx, dy, dz);
  a[1] += (2. / 3.) * CIC_get(phi, ii, jj - 1, kk, tx, ty, tz, dx, dy, dz);
  a[1] -= (1. / 12.) * CIC_get(phi, ii, jj - 2, kk, tx, ty, tz, dx, dy, dz);

  a[2] += (1. / 12.) * CIC_get(phi, ii, jj, kk + 2, tx, ty, tz, dx, dy, dz);
  a[2] -= (2. / 3.) * CIC_get(phi, ii, jj, kk + 1, tx, ty, tz, dx, dy, dz);
  a[2] += (2. / 3.) * CIC_get(phi, ii, jj, kk - 1, tx, ty, tz, dx, dy, dz);
  a[2] -= (1. / 12.) * CIC_get(phi, ii, jj, kk - 2, tx, ty, tz, dx, dy, dz);

  /* ---- */

  /* Store things back */
339
340
341
  accumulate_add_f(&gp->a_grav[0], fac * a[0]);
  accumulate_add_f(&gp->a_grav[1], fac * a[1]);
  accumulate_add_f(&gp->a_grav[2], fac * a[2]);
342
  gravity_add_comoving_potential(gp, p);
343
344
345
346
347
348
349
350
#ifdef SWIFT_GRAVITY_FORCE_CHECKS
  gp->potential_PM = p;
  gp->a_grav_PM[0] = fac * a[0];
  gp->a_grav_PM[1] = fac * a[1];
  gp->a_grav_PM[2] = fac * a[2];
#endif
}

351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
 * @brief Shared information about the Green function to be used by all the
 * threads in the pool.
 */
struct Green_function_data {

  int N;
  fftw_complex* frho;
  double green_fac;
  double a_smooth2;
  double k_fac;
};

/**
 * @brief Mapper function for the application of the Green function.
 *
 * @param map_data The array of the density field Fourier transform.
 * @param num The number of elements to iterate on (along the x-axis).
 * @param extra The properties of the Green function.
 */
void mesh_apply_Green_function_mapper(void* map_data, const int num,
                                      void* extra) {

  struct Green_function_data* data = (struct Green_function_data*)extra;

  /* Unpack the array */
  fftw_complex* const frho = data->frho;
  const int N = data->N;
  const int N_half = N / 2;

  /* Unpack the Green function properties */
  const double green_fac = data->green_fac;
  const double a_smooth2 = data->a_smooth2;
  const double k_fac = data->k_fac;

  /* Range handled by this call */
  const int i_start = (fftw_complex*)map_data - frho;
  const int i_end = i_start + num;

  /* Loop over the x range corresponding to this thread */
  for (int i = i_start; i < i_end; ++i) {

    /* kx component of vector in Fourier space and 1/sinc(kx) */
    const int kx = (i > N_half ? i - N : i);
    const double kx_d = (double)kx;
    const double fx = k_fac * kx_d;
    const double sinc_kx_inv = (kx != 0) ? fx / sin(fx) : 1.;

    for (int j = 0; j < N; ++j) {

      /* ky component of vector in Fourier space and 1/sinc(ky) */
      const int ky = (j > N_half ? j - N : j);
      const double ky_d = (double)ky;
      const double fy = k_fac * ky_d;
      const double sinc_ky_inv = (ky != 0) ? fy / sin(fy) : 1.;

      for (int k = 0; k < N_half + 1; ++k) {

        /* kz component of vector in Fourier space and 1/sinc(kz) */
        const int kz = (k > N_half ? k - N : k);
        const double kz_d = (double)kz;
        const double fz = k_fac * kz_d;
        const double sinc_kz_inv = (kz != 0) ? fz / (sin(fz) + FLT_MIN) : 1.;

        /* Norm of vector in Fourier space */
        const double k2 = (kx_d * kx_d + ky_d * ky_d + kz_d * kz_d);

        /* Avoid FPEs... */
        if (k2 == 0.) continue;

        /* Green function */
        double W = 1.;
        fourier_kernel_long_grav_eval(k2 * a_smooth2, &W);
        const double green_cor = green_fac * W / (k2 + FLT_MIN);

        /* Deconvolution of CIC */
        const double CIC_cor = sinc_kx_inv * sinc_ky_inv * sinc_kz_inv;
        const double CIC_cor2 = CIC_cor * CIC_cor;
        const double CIC_cor4 = CIC_cor2 * CIC_cor2;

        /* Combined correction */
        const double total_cor = green_cor * CIC_cor4;

        /* Apply to the mesh */
        const int index = N * (N_half + 1) * i + (N_half + 1) * j + k;
        frho[index][0] *= total_cor;
        frho[index][1] *= total_cor;
      }
    }
  }
}

/**
 * @brief Apply the Green function in Fourier space to the density
 * array to get the potential.
 *
 * Also deconvolves the CIC kernel.
 *
 * @param tp The threadpool.
 * @param frho The NxNx(N/2) complex array of the Fourier transform of the
 * density field.
 * @param N The dimension of the array.
 * @param r_s The Green function smoothing scale.
 * @param box_size The physical size of the simulation box.
 */
void mesh_apply_Green_function(struct threadpool* tp, fftw_complex* frho,
                               const int N, const double r_s,
                               const double box_size) {

  /* Some common factors */
  struct Green_function_data data;
  data.frho = frho;
  data.N = N;
  data.green_fac = -1. / (M_PI * box_size);
  data.a_smooth2 = 4. * M_PI * M_PI * r_s * r_s / (box_size * box_size);
  data.k_fac = M_PI / (double)N;

  /* Parallelize the Green function application using the threadpool
469
470
471
472
     to split the x-axis loop over the threads.
     The array is N x N x (N/2). We use the thread to each deal with
     a range [i_min, i_max[ x N x (N/2) */
  if (N < 32) {
473
474
475
    mesh_apply_Green_function_mapper(frho, N, &data);
  } else {
    threadpool_map(tp, mesh_apply_Green_function_mapper, frho, N,
476
                   sizeof(fftw_complex), threadpool_auto_chunk_size, &data);
477
478
479
480
481
482
483
  }

  /* Correct singularity at (0,0,0) */
  frho[0][0] = 0.;
  frho[0][1] = 0.;
}

484
485
#endif

486
487
488
489
490
/**
 * @brief Compute the potential, including periodic correction on the mesh.
 *
 * Interpolates the top-level multipoles on-to a mesh, move to Fourier space,
 * compute the potential including short-range correction and move back
491
492
493
 * to real space. We use CIC for the interpolation.
 *
 * Note that there is no multiplication by G_newton at this stage.
494
495
 *
 * @param mesh The #pm_mesh used to store the potential.
496
 * @param s The #space containing the particles.
497
 * @param tp The #threadpool object used for parallelisation.
498
 * @param verbose Are we talkative?
499
 */
500
void pm_mesh_compute_potential(struct pm_mesh* mesh, const struct space* s,
501
                               struct threadpool* tp, const int verbose) {
502
503
504

#ifdef HAVE_FFTW

505
  const double r_s = mesh->r_s;
506
507
  const double box_size = s->dim[0];
  const double dim[3] = {s->dim[0], s->dim[1], s->dim[2]};
508
509
  const int* local_cells = s->local_cells_top;
  const int nr_local_cells = s->nr_local_cells;
510

511
  if (r_s <= 0.) error("Invalid value of a_smooth");
512
513
  if (mesh->dim[0] != dim[0] || mesh->dim[1] != dim[1] ||
      mesh->dim[2] != dim[2])
514
    error("Domain size does not match the value stored in the space.");
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530

  /* Some useful constants */
  const int N = mesh->N;
  const int N_half = N / 2;
  const double cell_fac = N / box_size;

  /* Use the memory allocated for the potential to temporarily store rho */
  double* restrict rho = mesh->potential;
  if (rho == NULL) error("Error allocating memory for density mesh");
  bzero(rho, N * N * N * sizeof(double));

  /* Allocates some memory for the mesh in Fourier space */
  fftw_complex* restrict frho =
      (fftw_complex*)fftw_malloc(sizeof(fftw_complex) * N * N * (N_half + 1));
  if (frho == NULL)
    error("Error allocating memory for transform of density mesh");
531
532
  memuse_log_allocation("fftw_frho", frho, 1,
                        sizeof(fftw_complex) * N * N * (N_half + 1));
533
534
535
536
537
538
539

  /* Prepare the FFT library */
  fftw_plan forward_plan = fftw_plan_dft_r2c_3d(
      N, N, N, rho, frho, FFTW_ESTIMATE | FFTW_DESTROY_INPUT);
  fftw_plan inverse_plan = fftw_plan_dft_c2r_3d(
      N, N, N, frho, rho, FFTW_ESTIMATE | FFTW_DESTROY_INPUT);

540
  ticks tic = getticks();
541
542

  /* Zero everything */
543
544
  bzero(rho, N * N * N * sizeof(double));

545
546
547
548
549
550
551
552
553
554
555
556
  /* Gather the mesh shared information to be used by the threads */
  struct cic_mapper_data data;
  data.cells = s->cells_top;
  data.rho = rho;
  data.N = N;
  data.fac = cell_fac;
  data.dim[0] = dim[0];
  data.dim[1] = dim[1];
  data.dim[2] = dim[2];

  /* Do a parallel CIC mesh assignment of the gparts but only using
     the local top-level cells */
557
  threadpool_map(tp, cell_gpart_to_mesh_CIC_mapper, (void*)local_cells,
558
559
                 nr_local_cells, sizeof(int), threadpool_auto_chunk_size,
                 (void*)&data);
560

Matthieu Schaller's avatar
Matthieu Schaller committed
561
  if (verbose)
562
    message("Gpart assignment took %.3f %s.",
Matthieu Schaller's avatar
Matthieu Schaller committed
563
            clocks_from_ticks(getticks() - tic), clocks_getunit());
564

565
566
567
568
569
570
#ifdef WITH_MPI

  MPI_Barrier(MPI_COMM_WORLD);
  tic = getticks();

  /* Merge everybody's share of the density mesh */
Matthieu Schaller's avatar
Matthieu Schaller committed
571
572
  MPI_Allreduce(MPI_IN_PLACE, rho, N * N * N, MPI_DOUBLE, MPI_SUM,
                MPI_COMM_WORLD);
573
574

  if (verbose)
575
    message("Mesh communication took %.3f %s.",
576
577
578
            clocks_from_ticks(getticks() - tic), clocks_getunit());
#endif

579
  /* message("\n\n\n DENSITY"); */
580
581
  /* print_array(rho, N); */

582
  tic = getticks();
583

584
585
586
  /* Fourier transform to go to magic-land */
  fftw_execute(forward_plan);

587
588
589
590
  if (verbose)
    message("Forward Fourier transform took %.3f %s.",
            clocks_from_ticks(getticks() - tic), clocks_getunit());

591
592
593
  /* frho now contains the Fourier transform of the density field */
  /* frho contains NxNx(N/2+1) complex numbers */

594
595
  tic = getticks();

596
  /* Now de-convolve the CIC kernel and apply the Green function */
597
  mesh_apply_Green_function(tp, frho, N, r_s, box_size);
598

599
600
601
602
603
604
  if (verbose)
    message("Applying Green function took %.3f %s.",
            clocks_from_ticks(getticks() - tic), clocks_getunit());

  tic = getticks();

605
606
607
  /* Fourier transform to come back from magic-land */
  fftw_execute(inverse_plan);

608
609
610
611
  if (verbose)
    message("Backwards Fourier transform took %.3f %s.",
            clocks_from_ticks(getticks() - tic), clocks_getunit());

612
613
  /* rho now contains the potential */
  /* This array is now again NxNxN real numbers */
614

615
616
617
618
  /* Let's store it in the structure */
  mesh->potential = rho;

  /* message("\n\n\n POTENTIAL"); */
619
  /* print_array(mesh->potential, N); */
620
621
622
623

  /* Clean-up the mess */
  fftw_destroy_plan(forward_plan);
  fftw_destroy_plan(inverse_plan);
624
  memuse_log_allocation("fftw_frho", frho, 0, 0);
625
626
627
628
629
630
631
  fftw_free(frho);

#else
  error("No FFTW library found. Cannot compute periodic long-range forces.");
#endif
}

632
633
634
635
636
637
638
639
640
/**
 * @brief Interpolate the forces and potential from the mesh to the #gpart.
 *
 * We use CIC interpolation. The resulting accelerations and potential must
 * be multiplied by G_newton.
 *
 * @param mesh The #pm_mesh (containing the potential) to interpolate from.
 * @param e The #engine (to check active status).
 * @param gparts The #gpart to interpolate to.
641
 * @param gcount The number of #gpart.
642
 */
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
void pm_mesh_interpolate_forces(const struct pm_mesh* mesh,
                                const struct engine* e, struct gpart* gparts,
                                int gcount) {

#ifdef HAVE_FFTW

  const int N = mesh->N;
  const double cell_fac = mesh->cell_fac;
  const double* potential = mesh->potential;
  const double dim[3] = {e->s->dim[0], e->s->dim[1], e->s->dim[2]};

  /* Get the potential from the mesh to the active gparts using CIC */
  for (int i = 0; i < gcount; ++i) {
    struct gpart* gp = &gparts[i];

658
659
660
661
662
663
664
665
666
667
668
669
    if (gpart_is_active(gp, e)) {

#ifdef SWIFT_DEBUG_CHECKS
      /* Check that particles have been drifted to the current time */
      if (gp->ti_drift != e->ti_current)
        error("gpart not drifted to current time");

      /* Check that the particle was initialised */
      if (gp->initialised == 0)
        error("Adding forces to an un-initialised gpart.");
#endif

670
      mesh_to_gparts_CIC(gp, potential, N, cell_fac, dim);
671
    }
672
673
674
675
676
677
  }
#else
  error("No FFTW library found. Cannot compute periodic long-range forces.");
#endif
}

678
679
680
681
682
683
684
/**
 * @bried Allocates the potential grid to be ready for an FFT calculation
 *
 * @param mesh The #pm_mesh structure.
 */
void pm_mesh_allocate(struct pm_mesh* mesh) {

685
#ifdef HAVE_FFTW
686
687
688
689
690
691
692
693
694
695
  if (mesh->potential != NULL) error("Mesh already allocated!");

  const int N = mesh->N;

  /* Allocate the memory for the combined density and potential array */
  mesh->potential = (double*)fftw_malloc(sizeof(double) * N * N * N);
  if (mesh->potential == NULL)
    error("Error allocating memory for the long-range gravity mesh.");
  memuse_log_allocation("fftw_mesh.potential", mesh->potential, 1,
                        sizeof(double) * N * N * N);
696
697
698
#else
  error("No FFTW library found. Cannot compute periodic long-range forces.");
#endif
699
700
701
702
703
704
705
706
707
}

/**
 * @brief Frees the potential grid.
 *
 * @param mesh The #pm_mesh structure.
 */
void pm_mesh_free(struct pm_mesh* mesh) {

708
709
#ifdef HAVE_FFTW

710
711
712
713
714
  if (mesh->potential) {
    memuse_log_allocation("fftw_mesh.potential", mesh->potential, 0, 0);
    free(mesh->potential);
  }
  mesh->potential = NULL;
715
716
717
#else
  error("No FFTW library found. Cannot compute periodic long-range forces.");
#endif
718
719
}

720
721
722
723
724
/**
 * @brief Initialisses the mesh used for the long-range periodic forces
 *
 * @param mesh The #pm_mesh to initialise.
 * @param props The propoerties of the gravity scheme.
725
 * @param dim The (comoving) side-lengths of the simulation volume.
726
 * @param nr_threads The number of threads on this MPI rank.
727
728
 */
void pm_mesh_init(struct pm_mesh* mesh, const struct gravity_props* props,
729
                  const double dim[3], int nr_threads) {
730
731
732

#ifdef HAVE_FFTW

733
  if (dim[0] != dim[1] || dim[0] != dim[2])
734
735
    error("Doing mesh-gravity on a non-cubic domain");

736
  const int N = props->mesh_size;
737
738
  const double box_size = dim[0];

739
  mesh->nr_threads = nr_threads;
740
  mesh->periodic = 1;
741
  mesh->N = N;
742
743
744
  mesh->dim[0] = dim[0];
  mesh->dim[1] = dim[1];
  mesh->dim[2] = dim[2];
745
  mesh->cell_fac = N / box_size;
746
747
  mesh->r_s = props->a_smooth * box_size / N;
  mesh->r_s_inv = 1. / mesh->r_s;
748
749
  mesh->r_cut_max = mesh->r_s * props->r_cut_max_ratio;
  mesh->r_cut_min = mesh->r_s * props->r_cut_min_ratio;
750
  mesh->potential = NULL;
751

752
753
754
755
756
  if (mesh->N > 1290)
    error(
        "Mesh too big. The number of cells is larger than 2^31. "
        "Use a mesh side-length <= 1290.");

757
758
759
  if (2. * mesh->r_cut_max > box_size)
    error("Mesh too small or r_cut_max too big for this box size");

760
#ifdef HAVE_THREADED_FFTW
761
762
763
764
765
  /* Initialise the thread-parallel FFTW version */
  if (N >= 64) {
    fftw_init_threads();
    fftw_plan_with_nthreads(nr_threads);
  }
766
#endif
767

768
  pm_mesh_allocate(mesh);
769

770
771
772
773
774
#else
  error("No FFTW library found. Cannot compute periodic long-range forces.");
#endif
}

775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
/**
 * @brief Initialises the mesh for the case where we don't do mesh gravity
 * calculations
 *
 * Crucially this set the 'periodic' propoerty to 0 and all the relevant values
 * to a
 * state where all calculations will default to pure non-periodic Newtonian.
 *
 * @param mesh The #pm_mesh to initialise.
 * @param dim The (comoving) side-lengths of the simulation volume.
 */
void pm_mesh_init_no_mesh(struct pm_mesh* mesh, double dim[3]) {

  bzero(mesh, sizeof(struct pm_mesh));

  /* Fill in non-zero properties */
  mesh->dim[0] = dim[0];
  mesh->dim[1] = dim[1];
  mesh->dim[2] = dim[2];
  mesh->r_s = FLT_MAX;
  mesh->r_cut_min = FLT_MAX;
  mesh->r_cut_max = FLT_MAX;
}

799
800
801
802
803
/**
 * @brief Frees the memory allocated for the long-range mesh.
 */
void pm_mesh_clean(struct pm_mesh* mesh) {

804
#ifdef HAVE_THREADED_FFTW
805
  fftw_cleanup_threads();
806
#endif
807

808
  pm_mesh_free(mesh);
809
}
810
811
812
813

/**
 * @brief Write a #pm_mesh struct to the given FILE as a stream of bytes.
 *
Matthieu Schaller's avatar
Matthieu Schaller committed
814
 * @param mesh the struct
815
816
817
818
819
820
821
822
823
824
825
 * @param stream the file stream
 */
void pm_mesh_struct_dump(const struct pm_mesh* mesh, FILE* stream) {
  restart_write_blocks((void*)mesh, sizeof(struct pm_mesh), 1, stream,
                       "gravity", "gravity props");
}

/**
 * @brief Restore a #pm_mesh struct from the given FILE as a stream of
 * bytes.
 *
Matthieu Schaller's avatar
Matthieu Schaller committed
826
 * @param mesh the struct
827
828
829
830
831
832
833
 * @param stream the file stream
 */
void pm_mesh_struct_restore(struct pm_mesh* mesh, FILE* stream) {

  restart_read_blocks((void*)mesh, sizeof(struct pm_mesh), 1, stream, NULL,
                      "gravity props");

834
835
836
837
  if (mesh->periodic) {

#ifdef HAVE_FFTW
    const int N = mesh->N;
838

839
#ifdef HAVE_THREADED_FFTW
Matthieu Schaller's avatar
Matthieu Schaller committed
840
841
    /* Initialise the thread-parallel FFTW version */
    if (N >= 64) {
842
843
844
      fftw_init_threads();
      fftw_plan_with_nthreads(mesh->nr_threads);
    }
845
#endif
846

847
848
849
850
    /* Allocate the memory for the combined density and potential array */
    mesh->potential = (double*)fftw_malloc(sizeof(double) * N * N * N);
    if (mesh->potential == NULL)
      error("Error allocating memory for the long-range gravity mesh.");
851
852
    memuse_log_allocation("fftw_mesh.potential", mesh->potential, 1,
                          sizeof(double) * N * N * N);
853
#else
854
    error("No FFTW library found. Cannot compute periodic long-range forces.");
855
#endif
856
  }
857
}