Massless acceleration

Source code (Click to expand)
  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
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
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
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
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
339
340
341
342
343
344
345
346
347
348
349
350
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
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
/**
 * \file acceleration.c
 * \brief Functions for computing gravitational acceleration
 * 
 * \author Ching-Yin Ng
 */

#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "acceleration.h"
#include "common.h"
#include "error.h"
#include "math_functions.h"
#include "system.h"
#include "utils.h"

/**
 * \brief Check the acceleration method
 * 
 * \param acceleration_method Acceleration method
 * 
 * \return ErrorStatus
 */
IN_FILE ErrorStatus check_acceleration_method(const int acceleration_method);

/**
 * \brief Compute acceleration with direct pairwise method
 * 
 * \param a Array of acceleration vectors to be modified
 * \param system Pointer to the gravitational system
 * \param acceleration_param Pointer to the acceleration parameters
 * 
 * \return ErrorStatus
 */
IN_FILE ErrorStatus acceleration_pairwise(
    double *restrict a,
    const System *restrict system,
    const AccelerationParam *restrict acceleration_param
);

/**
 * \brief Compute acceleration with direct pairwise method,
 *        ignoring the contribution of massless particles
 * 
 * \param a Array of acceleration vectors to be modified
 * \param system Pointer to the gravitational system
 * \param acceleration_param Pointer to the acceleration parameters
 * 
 * \return ErrorStatus
 */
IN_FILE ErrorStatus acceleration_massless(
    double *restrict a,
    const System *restrict system,
    const AccelerationParam *restrict acceleration_param
);


WIN32DLL_API AccelerationParam get_new_acceleration_param(void)
{
    AccelerationParam acceleration_param = {
        .method = ACCELERATION_METHOD_PAIRWISE,
        .opening_angle = 1.0,
        .softening_length = 0.0,
        .max_num_particles_per_leaf = -1
    };
    return acceleration_param;
}

WIN32DLL_API ErrorStatus finalize_acceleration_param(
    AccelerationParam *restrict acceleration_param
)
{
    ErrorStatus error_status;

    /* Check the acceleration method */
    error_status = WRAP_TRACEBACK(
        check_acceleration_method(acceleration_param->method)
    );
    if (error_status.return_code != GRAV_SUCCESS)
    {
        return error_status;
    }

    /* Check the softening length */
    if (acceleration_param->softening_length < 0.0)
    {
        return raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
            GRAV_VALUE_ERROR,
            "Softening length is negative. Got: %.3g",
            acceleration_param->softening_length
        );
    }

    /* Check the opening angle */
    if (
        acceleration_param->method == ACCELERATION_METHOD_BARNES_HUT
        && acceleration_param->opening_angle < 0.0
    )
    {
        return raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
            GRAV_VALUE_ERROR,
            "Opening angle is negative. Got: %.3g",
            acceleration_param->opening_angle
        );
    }

    /* Check the maximum number of particles per leaf */
    if (acceleration_param->method == ACCELERATION_METHOD_BARNES_HUT)
    {
        if (acceleration_param->max_num_particles_per_leaf == -1)
        {
            acceleration_param->max_num_particles_per_leaf = 1;
        }
        else if (acceleration_param->max_num_particles_per_leaf < 1)
        {
            return raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
                GRAV_VALUE_ERROR,
                "Maximum number of particles per leaf must be positive. Got: %d",
                acceleration_param->max_num_particles_per_leaf
            );
        }
    }

    return make_success_error_status();
}

WIN32DLL_API ErrorStatus acceleration(
    double *restrict a,
    const System *restrict system,
    const AccelerationParam *restrict acceleration_param
)
{
    switch (acceleration_param->method)
    {
        case ACCELERATION_METHOD_PAIRWISE:
            return acceleration_pairwise(a, system, acceleration_param);
        case ACCELERATION_METHOD_MASSLESS:
            return acceleration_massless(a, system, acceleration_param);
        case ACCELERATION_METHOD_BARNES_HUT:
            return acceleration_barnes_hut(a, system, acceleration_param);
        default:
        {
            return raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
                GRAV_VALUE_ERROR,
                "Unknown acceleration method. Got: %d",
                acceleration_param->method
            );
        }
    }
}

IN_FILE ErrorStatus check_acceleration_method(const int acceleration_method)
{
    switch (acceleration_method)
    {
        case ACCELERATION_METHOD_PAIRWISE:
        case ACCELERATION_METHOD_MASSLESS:
        case ACCELERATION_METHOD_BARNES_HUT:
            break;
        default:
        {
            return raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
                GRAV_VALUE_ERROR,
                "Unknown acceleration method. Got: %d",
                acceleration_method
            );
        }
    }

    return make_success_error_status();
}

IN_FILE ErrorStatus acceleration_pairwise(
    double *restrict a,
    const System *restrict system,
    const AccelerationParam *restrict acceleration_param
)
{
    const int num_particles = system->num_particles;
    const double *x = system->x;
    const double *m = system->m;
    const double G = system->G;
    const double softening_length = acceleration_param->softening_length;

    /* Empty the input array */
    for (int i = 0; i < num_particles; i++)
    {
        a[i * 3 + 0] = 0.0;
        a[i * 3 + 1] = 0.0;
        a[i * 3 + 2] = 0.0;
    }

    /* Compute the pairwise acceleration */
    for (int i = 0; i < num_particles; i++)
    {
        const double m_i = m[i];
        for (int j = i + 1; j < num_particles; j++)
        {
            // Calculate \vec{R} and its norm
            const double R[3] = {
                x[i * 3 + 0] - x[j * 3 + 0],
                x[i * 3 + 1] - x[j * 3 + 1],
                x[i * 3 + 2] - x[j * 3 + 2]
            };
            const double R_norm = sqrt(
                R[0] * R[0] + 
                R[1] * R[1] + 
                R[2] * R[2] +
                softening_length * softening_length
            );

            // Calculate the acceleration
            const double temp_value = G / (R_norm * R_norm * R_norm);
            const double m_j = m[j];
            double temp_vec[3] = {
                temp_value * R[0],
                temp_value * R[1],
                temp_value * R[2]
            };
            a[i * 3 + 0] -= temp_vec[0] * m_j;
            a[i * 3 + 1] -= temp_vec[1] * m_j;
            a[i * 3 + 2] -= temp_vec[2] * m_j;
            a[j * 3 + 0] += temp_vec[0] * m_i;
            a[j * 3 + 1] += temp_vec[1] * m_i;
            a[j * 3 + 2] += temp_vec[2] * m_i;
        }
    }

    return make_success_error_status();
}

IN_FILE ErrorStatus acceleration_massless(
    double *restrict a,
    const System *restrict system,
    const AccelerationParam *restrict acceleration_param
)
{
    const int num_particles = system->num_particles;
    const double *x = system->x;
    const double *m = system->m;
    const double G = system->G;
    const double softening_length = acceleration_param->softening_length;

    /* Empty the input array */
    for (int i = 0; i < num_particles; i++)
    {
        a[i * 3 + 0] = 0.0;
        a[i * 3 + 1] = 0.0;
        a[i * 3 + 2] = 0.0;
    }

    /* Find the numbers of massive and massless particles */
    int massive_objects_count = 0;
    int massless_objects_count = 0;
    for (int i = 0; i < num_particles; i++)
    {
        if (m[i] != 0.0)
        {
            massive_objects_count++;
        }
        else
        {
            massless_objects_count++;
        }
    }

    /* Find the indices of massive and massless particles */
    int *restrict massive_indices = malloc(massive_objects_count * sizeof(int));
    int *restrict massless_indices = malloc(massless_objects_count * sizeof(int));
    massive_objects_count = 0;
    massless_objects_count = 0;

    if (massive_indices == NULL || massless_indices == NULL)
    {
        free(massive_indices);
        free(massless_indices);
        return WRAP_RAISE_ERROR(GRAV_MEMORY_ERROR, "Failed to allocate memory for massive and massless indices");
    }

    for (int i = 0; i < num_particles; i++)
    {
        if (m[i] != 0.0)
        {
            massive_indices[massive_objects_count] = i;
            massive_objects_count++;
        }
        else
        {
            massless_indices[massless_objects_count] = i;
            massless_objects_count++;
        }
    }

    /* Pairwise acceleration calculation for massive particles */
    for (int i = 0; i < massive_objects_count; i++)
    {
        const int idx_i = massive_indices[i];
        const double m_i = m[idx_i];
        for (int j = i + 1; j < massive_objects_count; j++)
        {
            const int idx_j = massive_indices[j];
            const double m_j = m[idx_j];
            double temp_vec[3];
            double R[3];

            // Calculate \vec{R} and its norm
            R[0] = x[idx_i * 3 + 0] - x[idx_j * 3 + 0];
            R[1] = x[idx_i * 3 + 1] - x[idx_j * 3 + 1];
            R[2] = x[idx_i * 3 + 2] - x[idx_j * 3 + 2];
            const double R_norm = sqrt(
                R[0] * R[0] + 
                R[1] * R[1] + 
                R[2] * R[2] +
                softening_length * softening_length
            );

            // Calculate the acceleration
            double temp_value = G / (R_norm * R_norm * R_norm);
            temp_vec[0] = temp_value * R[0];
            temp_vec[1] = temp_value * R[1];
            temp_vec[2] = temp_value * R[2];
            a[idx_i * 3 + 0] -= temp_vec[0] * m_j;
            a[idx_i * 3 + 1] -= temp_vec[1] * m_j;
            a[idx_i * 3 + 2] -= temp_vec[2] * m_j;
            a[idx_j * 3 + 0] += temp_vec[0] * m_i;
            a[idx_j * 3 + 1] += temp_vec[1] * m_i;
            a[idx_j * 3 + 2] += temp_vec[2] * m_i;
        }
    }

    /* Acceleration calculation for massless particles due to massive particles */
    for (int i = 0; i < massive_objects_count; i++)
    {
        for (int j = 0; j < massless_objects_count; j++)
        {
            int idx_i = massive_indices[i];
            int idx_j = massless_indices[j];
            double R[3];

            // Calculate \vec{R} and its norm
            R[0] = x[idx_i * 3 + 0] - x[idx_j * 3 + 0];
            R[1] = x[idx_i * 3 + 1] - x[idx_j * 3 + 1];
            R[2] = x[idx_i * 3 + 2] - x[idx_j * 3 + 2];
            double R_norm = sqrt(
                R[0] * R[0] + 
                R[1] * R[1] + 
                R[2] * R[2] +
                softening_length * softening_length
            );

            // Calculate the acceleration
            double temp_value = G / (R_norm * R_norm * R_norm);
            a[idx_j * 3 + 0] += temp_value * R[0] * m[i];
            a[idx_j * 3 + 1] += temp_value * R[1] * m[i];
            a[idx_j * 3 + 2] += temp_value * R[2] * m[i];
        }
    }

    free(massive_indices);
    free(massless_indices);

    return make_success_error_status();
}

WIN32DLL_API ErrorStatus benchmark_acceleration(
    const System *restrict system,
    const AccelerationParam *acceleration_params,
    const int num_acceleration_params,
    const int *restrict num_times_acceleration_param    
)
{
    ErrorStatus error_status;

    double *restrict reference_a = malloc(
        system->num_particles * 3 * sizeof(double)
    );
    double *restrict a = malloc(
        system->num_particles * 3 * sizeof(double)
    );
    if (!reference_a || !a)
    {
        error_status = WRAP_RAISE_ERROR(
            GRAV_MEMORY_ERROR,
            "Failed to allocate memory for acceleration arrays"
        );
        goto err_malloc;
    }

    fputs("Benchmarking acceleration...\n", stdout);

    for (int i = 0; i < num_acceleration_params; i++)
    {
        const AccelerationParam *acceleration_param = &(acceleration_params[i]);
        const int num_times = num_times_acceleration_param[i];

        if (num_times <= 0)
        {
            printf("Test %d:    Skipped since num_times: %d <= 0\n\n", i, num_times);
            continue;
        }

        double *restrict run_time = calloc(num_times, sizeof(double));
        double mae = 0.0;

        if (!run_time)
        {
            free(run_time);
            error_status = WRAP_RAISE_ERROR(
                GRAV_MEMORY_ERROR,
                "Failed to allocate memory for runtime array"
            );
            goto err_malloc;
        }

        for (int j = 0; j < num_times; j++)
        {
            if (i == 0 && j == 0)
            {
                double start_time = grav_get_current_time();
                error_status = WRAP_TRACEBACK(acceleration(
                    reference_a,
                    system,
                    acceleration_param
                ));
                if (error_status.return_code != GRAV_SUCCESS)
                {
                    return error_status;
                }
                double end_time = grav_get_current_time();
                run_time[j] += (end_time - start_time);
            }
            else
            {
                double start_time = grav_get_current_time();
                error_status = WRAP_TRACEBACK(acceleration(
                    a,
                    system,
                    acceleration_param
                ));
                if (error_status.return_code != GRAV_SUCCESS)
                {
                    return error_status;
                }
                double end_time = grav_get_current_time();
                run_time[j] += (end_time - start_time);
            }

            // Calculate the MAE
            if (i != 0 && j == 0)
            {
                for (int k = 0; k < system->num_particles; k++)
                {
                    const double diff[3] = {
                        reference_a[k * 3 + 0] - a[k * 3 + 0],
                        reference_a[k * 3 + 1] - a[k * 3 + 1],
                        reference_a[k * 3 + 2] - a[k * 3 + 2]
                    };
                    mae += fabs(diff[0]) + fabs(diff[1]) + fabs(diff[2]);
                }
                mae /= system->num_particles;
            }
        }

        printf("Test %d:", i);
        switch(acceleration_param->method)
        {
            case ACCELERATION_METHOD_PAIRWISE:
                fputs("    Method: Pairwise\n", stdout);
                break;
            case ACCELERATION_METHOD_MASSLESS:
                fputs("    Method: Massless\n", stdout);
                break;
            case ACCELERATION_METHOD_BARNES_HUT:
                fputs("    Method: Barnes-Hut\n", stdout);
                break;
            default:
                error_status = raise_error_fmt(
            __FILE__,
            __LINE__,
            __func__,
                    GRAV_VALUE_ERROR,
                    "Unknown acceleration method. Got: %d",
                    acceleration_param->method
                );
                goto err_unknown_acceleration_method;
        }

        printf("    Number of times: %d\n", num_times);
        printf("    Avg time: %.3g (+- %.3g) s\n", compute_mean(run_time, num_times), compute_std(run_time, num_times, 1) / sqrt(num_times));
        printf("    MAE: %.3g\n", mae);
        printf("\n");

        free(run_time);
    }

    free(reference_a);
    free(a);

    return make_success_error_status();

err_unknown_acceleration_method:
err_malloc:
    free(reference_a);
    free(a);
    return error_status;
}

Let's say you have 10 regular particles and 10 massless particles (i.e. particles with mass so small that is negligible). One may compute the acceleration with the brute-force algorithm

\[ \mathbf{a}_i = \sum_{j \neq i} \frac{G m_j}{r_{ij}^2} \hat{\mathbf{r}}_{ij} \quad \text{for } i = 1, \ldots, N \]

But this is \(\mathcal{O}(N^2)\), and we don't actually need to compute the acceleration due to the massless particles. Therefore, a more efficient way is to separate the calculations for massive and massless particles.

We first produce two list of indices, one for the massive particles and one for the massless particles. Then, we compute the acceleration for the massive particles with the brute-force algorithm. For the massless particles, we compute the acceleration of them due to the massive particles only. This gives a time complexity: \(O(M^2 + MN)\), where \(M\) and \(N\) are the number of massive and massless particles respectively.

Comments