Skip to Content
MathematicsMathematics
  • Article
  • Open Access

22 April 2026

42 Pages

On Parallel and Distributed N-Body Simulations

Faculty of Computer Science, Dalhousie University, Halifax, NS B3H 4R2, Canada

Abstract

The N-body problem is a classic problem involving a system of N discrete bodies mutually interacting in a dynamical system. At any moment in time there are N ( N − 1 ) / 2 such interactions occurring. This N 2 scaling leads to computational difficulties where simulations range from tens of thousands of bodies to billions or trillions. Approximation algorithms, such as the famous Barnes–Hut algorithm, simplify the number of interactions to scale as N log N . Even still, this improvement in complexity is insufficient to achieve the desired performance for very large simulations on computing clusters with many nodes and many cores. In this work we explore a variety of algorithmic techniques for parallel and distributed variations on the Barnes–Hut algorithm to improve parallelism and reduce inter-process communication requirements. This includes the costzones and hashed octree techniques. We implement these techniques in a gravitational N-body simulation and show that they can be applied to both a parallel and distributed context. This work collects and unifies over 30 years of research, while filling in missing details, to provide a comprehensive and reproducible source.
MSC:
70F15; 70-04; 85-08; 85-04; 68W10; 68W15

1. Introduction

N-body problems include a large collection of problems wherein a set of N bodies, particles, or points interact under mutually influential forces together in a dynamical system. Often, the dynamical system is governed by a potential field, for example, electrical, magnetic, or gravitational. The result is a system of second-order differential equations where the acceleration of each body is computed from forces or potential created by the other N − 1 bodies. Then, velocities and positions are updated from this acceleration. Targeted applications include fluid dynamics, molecular dynamics, quantum mechanics, astrophysics, and cosmology. Historically, the N-body problem refers specifically to the problem where bodies are governed by gravity; moreover, it will be the focus of this work. Whether the physical scale of each body is very small or very large, these N-body problems share two common issues: the lack of analytic solutions and scalability.
As the number of bodies in a system increases, the number of differential equations describing the dynamical system grows proportionally. Due to the mutual interaction of those bodies, the number of interactions and the number of terms in the differential equations grow as N 2 . It is therefore prohibitively challenging to determine exact solutions to these systems of equations as the value of N increases. For example, in quantum mechanics, and when restricting the number of dimensions to only 2, exact solutions are only known up to the order of N = 10  [1]. For bodies moving under the force of gravity, general solutions are known only for N = 2 , while for N = 3 , solutions exist for only very specific initial conditions [2] (Ch. 5). Simulations are therefore required to study systems with any practically meaningful number of bodies. In practice, billions or trillions of particles may be simulated, requiring distributed computing due to the sheer size of computation. The efficiency and scalability of such simulations are thus highly important.
In astronomy and gravitational N-body systems there are several different simulation scales of practical importance:
  • Celestial mechanics, where a few dozen bodies—planets, stars—typically orbit a single body of much higher mass than the others, e.g., a solar system;
  • Stellar dynamics, where a collection of roughly equal mass stars interact under their mutual gravity, e.g., 10 4 – 10 6 stars bound in a globular cluster (see Figure 1);
    Figure 1. Simulating the collision of two globular clusters, each consisting of 1000 stars.
  • Galaxy cluster evolution, where each body represents an entire galaxy and 10 2 – 10 3 such galaxies are gravitationally bound in a so-called galaxy cluster;
  • Cosmological simulation, where 10 6 – 10 12 bodies simulate the evolving structure of the universe.
These latter two, however, must also account for dark matter and relativistic behaviour (see [3] and references therein). The former two categories are dominated, rather, by Newtonian dynamics, posing less of a mathematical challenge and more of a computational one. Cosmological simulation also requires extreme-scale computing (petascale computing and beyond). For these reasons, we focus on stellar dynamics throughout this article.
Where the number of bodies in a simulation increases from hundreds to thousands, or millions, or even billions, the ability to simulate that number quickly becomes infeasible. While, technically, simulating a system with N 2 interactions is a polynomial-time algorithm, these N 2 interactions must be computed at every time step of the simulation. The result is a O ( T N 2 ) running time for T simulation steps. T is relatively unbounded as scientists wish to examine the long-term evolution of these systems. As either T or N grows in orders of magnitude, a so-called direct simulation of these N 2 interactions becomes a challenge.
Research into approximation algorithms to reduce the running time complexity of such simulations, while maintaining accurate results, has been ongoing for decades. Several different methods appeared in the late 1980s, bringing the complexity of computing interactions down to O ( N log N ) or less. The Particle–Mesh method [4] (Ch. 1) represents particles (particles, points, bodies are all terms used interchangeably to mean the same thing: discrete positions in space) as a grid or mesh and then solves the potential on this density-mesh. This method is well-suited where separations between particles are large, but is insufficient where particle density is high. Hierarchical methods, or treecodes, on the other hand, look to balance approximating long-range interactions with using the direct method for close-range interactions. The Fast Multipole Method [5] and the Barnes–Hut algorithm [6] are two examples of hierarchical methods. We explore both in more detail in Section 3.
As computer hardware began to evolve in the 1990s, so did support for parallel execution of N-body simulations on multiprocessors and distributed systems. Two different pioneering works appeared simultaneously at Supercomputing ’93: the costzones approach by Singh et al. [7] and the hashed octree method of Warren and Salmon [8]. Both works attempt to parallelize hierarchical methods through adaptive domain decomposition, dynamic load balancing across processors, and parallel interaction computation. The costzones approach was initially developed for a (distributed) shared memory system, while the hashed octree method was developed explicitly for distributed systems. On modern multi-core multiprocessor systems, the shared memory costzones approach is simple and efficient on a single compute node. Yet, as simulation sizes and durations grow, explicit distributed computing is required to achieve higher performance without limiting simulations to a single node. Nonetheless, the costzones approach can be adapted to distributed computing, as we will explore in later sections.

1.1. Related Work

N-body simulations continue to be an indispensable tool in astrophysics. These simulations offer practical means to test theories and compare against observational data. For example, in studying the merging of galaxies and the orbital evolution of a pair of supermassive black holes [9,10], studying the evolution of globular clusters in the Milky Way [11], studying the evolution of dark matter in the early universe [12], or constraining the nature of dark matter [13].
The most extensive N-body simulations are typically cosmological simulations, which are used to study the evolving structure of the universe. These simulations continuously push the limits of the world’s most powerful supercomputers. The first gravitational N-body simulation to reach over 1 trillion particles used the world’s fastest supercomputer at the time, the K computer, with 82,944 nodes and a total of 663,552 cores [14]. In 2017, an 8 trillion particle simulation was conducted on the Titan supercomputer using its 18,688 nodes (299,008 cores), with each node equipped with an NVIDIA K20X GPU [15]. In 2022, over 18 trillion particles were simulated on the Fugaku supercomputer, which housed 158,976 nodes and 7,630,848 cores [16]. Other simulations using more than 1 trillion particles include Dark Sky [17], TianNu [18], Outer Rim [19], Uchuu [20], and Last Journey [21]. Further details of such large-scale cosmological simulations can be found in two recent review papers [22,23].
Other works have also focused on improving the performance of N-body simulations by optimizing performance at the level of a single node rather than across large-scale distributed systems. One direction involves the use of SIMD (single instruction multiple data) instructions on modern CPUs, also known as vectorized instructions, which can perform the same operations on multiple data objects. SIMD instructions have been successfully employed in most modern N-body simulations with detailed explanations found in [24,25,26,27]. In another direction, hardware accelerators have seen great success in improving performance beyond what is capable with a CPU. The GRAPE (GRAvity PipEline) chip [28] is an ASIC (application-specific integrated circuit) specifically developed to compute gravitational forces in hardware, leading to highly specialized computers containing up to 2048 such chips [29]. The use of FPGAs (field-programmable gate arrays) has also seen success in improving the performance of N-body codes [30,31,32].
However, the most widespread success of hardware accelerators in recent years has been through the use of GPUs (graphics processing units). Early works, e.g., [33,34,35], accelerated the direct simulation of all N 2 interactions owing to the challenges of mapping the irregular parallelism of treecodes to GPU hardware. Nonetheless, further work to implement such hierarchical methods eventually found success. One of the first works to implement treecodes on GPU was [36], which was successfully deployed on a cluster containing 256 GPUs [37]. Since then, much work has gone into improving GPU implementations of hierarchical methods [15,38,39,40,41,42,43]. Very recently, modern GPUs provide further specialized hardware in the form of ray-tracing cores, which have been shown to successfully accelerate the irregular workloads of tree traversals in the Barnes–Hut method [44].
In yet another direction are works dedicated to algorithmic improvements to sub-steps of N-body treecodes. In [45], the authors investigate tree construction on GPUs; meanwhile, ref. [46] investigates tree construction on modern CPUs with dozens of cores. Optimizing tree traversal is studied in [47]. Sorting, a crucial operation for load balancing in tree-based N-body simulations, is considered in [48].
We have already introduced approximation methods such as Particle–Mesh (PM) [4] (Ch. 1), Fast Multipole Method (FMM) [5], and Barnes–Hut (BH) [6] which reduce the number of interactions to be computed. Recall that the direct method, or particle–particle (PP) method, computes all N 2 interactions. The PM and BH methods reduce this number to O ( N log N ) while FMM reduces this to O ( N ) . Generally speaking, the PM method is very fast but is not effective for regions with high particle density. To overcome this disadvantage, the P3M (particle–particle–particle–mesh) algorithm was introduced, where long-range interactions are computed using the PM method and short-range interactions are computed using the PP method [4] (Ch. 8). However, the PP part quickly dominates in simulations with high levels of clustering, which is common in practice. Therefore, another hybrid PM approach is called TreePM, where short-range interactions are instead computed using the BH method [49,50,51]. TreePM and its variants have seen widespread adoption and are used in some of the largest N-body simulations to date [14,16,19,20,21]. Despite the attractive O ( N ) number of interactions to be computed in FMM, it has not seen widespread use like that of BH or TreePM. This may be attributed to the difficulty in parallelizing the FMM and it being an overall more complex algorithm [23,52]. Nonetheless, some recent works are employing FMM [15] and a new hybrid FMM-PM method [52,53].

1.2. Contributions and Organization

The landscape of N-body simulations in the literature is vast and spans several decades. As a general trend, this author notices that these works typically focus on the underlying physics of the simulation, the performance of the simulation, and the scientific implications of the results of the simulation. The result is a lack of sufficient detail needed to actually implement the algorithms and techniques described in the literature. These papers may describe what the algorithm does, but do not adequately describe the how. One could reverse-engineer the source code if the source code is even publicly available, but that is a monumental task in itself. This leaves newcomers quite lost and unable to make a foothold in this research area.
This article attempts to close this gap by providing a detailed, self-contained source which describes the basis of modern N-body simulations from an algorithmic and computational point of view. As described in the previous subsection, treecodes and the Barnes–Hut method in particular still form the foundation of recent N-body simulations despite the more than 30 years since they were first introduced. Indeed, the original papers  [6,8] are still widely cited as the algorithmic basis for many N-body simulations.
Throughout this article we present a step-by-step guide to the implementation of gravitational N-body simulation and, in particular, algorithmic techniques that bolster a distributed and parallel implementation based on treecodes. We collect and coherently present the work of many papers:  [3,6,7,8,54,55,56]. To be precise, the ideas behind each of our forthcoming algorithms are not new. What is new is our extensive exposition and algorithmic presentation, which provides the necessary details to actually implement and reproduce the ideas presented in these papers. Our hope is that this work may serve as a pedagogical resource as well as a sufficiently detailed basis for future implementations of distributed N-body simulations based on treecodes.
The contributions of this work can be summarized as follows.
  • A detailed, self-contained, algorithmic exposition of distributed Barnes–Hut methods for N-body simulation.
  • A novel presentation of the hashed octree and costzones methods, showing that they are essentially the same up to communication of the tree.
  • An open-source implementation written in C/C++ using OpenMPI for distributed computation.
In Section 3 we present the classical Barnes–Hut method [6] and the motivation behind all hierarchical N-body methods. In Section 4 we give a novel and complete presentation of parallelization techniques for N-body simulations based on treecodes. We show that costzones and hashed octree are very similar and differ only in the communication of the constructed octree. Our presentation is sufficiently detailed with ample figures and algorithmic listings to enhance understandability and reproducibility. Further, our implementation, written in C/C++ and making use of the OpenMPI [57] implementation of Message Passing Interface (MPI), is freely and openly available at https://github.com/alexgbrandt/Parallel-NBody/ (accessed on 12 December 2025).
The remainder of this article is organized as follows. We begin in Section 2 by describing the mathematical model underpinning gravitational simulations. Section 3 is further background describing the basis of hierarchical methods through their use of spatial tree representations (quadtrees, octrees) and force approximations. Section 4 explores the algorithmic techniques of the costzones and hashed octree methods to parallelize treecodes. These techniques are applied incrementally to produce continually more complex code but with continually increasing scalability, resulting in 8 total algorithm configurations. Section 5 evaluates the implementation of these algorithms on a small, local compute cluster totalling 100 cores. Lastly, Section 6 concludes and presents directions for future work.

2. Gravitational N-Body Simulation

This section reviews the mathematical background necessary to perform an N-body simulation governed by the force of gravity. While this information is not strictly necessary to understand the distributed computing and algorithmic techniques discussed later in Section 4, it does concretely define how “interactions” between bodies are computed. Moreover, this section presents the mathematical reasoning, particularly gravitational potential, which allows for the development of the approximation algorithms described in Section 3.
We begin in Section 2.1 describing the direct interactions between particles using Newton’s law of universal gravitation. Then, Section 2.2 describes gravitational potential and the gravitational field. Through superposition of gravitational potentials and a multipole expansion of that superposition, the acceleration due to the collective gravity of many bodies can be accurately approximated. Section 2.3 explains how this acceleration can be used to update the dynamical system over time (i.e., perform integration). Finally, Section 2.4 explains how N-body simulations can be scaled and standardized for consistent comparison across simulation scales.
This section is largely based on a comprehensive text by Sverre Aarseth; see [58] and references therein for further details. Throughout this section, scalars are given by Latin characters, and vectors are three-dimensional and given by bold Latin characters. The vector norm | | · | | is the Euclidean norm.

2.1. Gravitational Force

Newton’s law of universal gravitation describes the attractive forces between any two particles. For two point masses with mass m i and m j , respectively, separated by a distance r, we know the magnitude of their mutual attractive gravitational force is given by
F = G m i m j r 2
where G is the gravitational constant.
For brevity, let us describe a particle whose mass is m i as the mass m i . Let mass m i be at position r i and mass m j be at position r j . Describing the force exerted on mass m i by mass m j can then be given by:
F i j = G m i m j ∥ r i − r j ∥ 2 · − ( r i − r j ) ∥ r i − r j ∥ .
Here, ∥ r i − r j ∥ = r and − ( r i − r j ) ∥ r i − r j ∥ is a unit vector pointing from mass m i to mass m j . Using Newton’s second law, the acceleration a i j induced on mass m i by the force F i j is given by F i j = m i a i j .
Using Newtonian dynamics combined with this law of gravity yields the equations of motion for a system of bodies moving under gravitational forces. For a system of N bodies there exist 3 N second-order differential equations describing the motion of the bodies. Using vector notation reduces the number of equations to N and improves readability. Then, the position of the body with index i evolves as:
(3) r ¨ i = a i = ∑ j = 1 j ≠ i N a i j (4)   = 1 m i ∑ j = 1 j ≠ i N F i j (5)   = − G ∑ j = 1 j ≠ i N m j ( r i − r j ) ∥ r i − r j ∥ 3 .
Therefore, determining the interaction between two bodies i and j in an N-body simulation is simply the computation of this F i j or, equivalently, the acceleration a i j . This defines a so-called particle–particle interaction. Summing (2) over all other bodies, as given by (5), and dividing through by m i , yields the acceleration of body i, a i , as in (3).
Due to the finite and numerical nature of the simulation, it is useful to introduce a so-called softening factor to a particle–particle interaction. Including a small value ϵ in computing particle separations helps reduce the effects of close encounters. One simply replaces ∥ r i − r j ∥ with ( ∥ r i − r j ∥ 2 + ϵ 2 ) 1 2 . This softening avoids numerical errors associated with singularities and prevents odd behaviour arising from discretizing time steps during close encounters [58] (Ch. 2).
However, we know that to compute F i j for every pair of points quickly becomes computationally infeasible. One key observation, which is employed by hierarchical N-body methods, is the approximation of the gravitational force exerted by many discrete bodies at once. The fundamental observation is that for some subset of bodies J, whose centre of mass is r J and total mass is m J , the force acting on particle i from this ensemble of points is:
F i J = ∑ j ∈ J − G m i m j ( r i − r j ) ∥ r i − r j ∥ 3 ≈ − G m i m J ( r i − r J ) ∥ r i − r J ∥ 3 .
Recall computing the centre of mass is simply r J = ∑ j ∈ J m j r j . This approximation approaches equality as the separation distance ∥ r i − r J ∥ grows larger. However, this approximation can be further refined by using gravitational potential.

2.2. Gravitational Field, Gravitational Potential, and Multipole Expansion

Expanding from Newton’s original idea of an attractive force between point masses, a better model is that of the gravitational field. The gravitational field of a point mass M is a vector field describing the force of gravity per unit mass felt by a body at any point in space in the field. The gravitational field is typically denoted by g and, for a body with mass m at position r , is defined as:
g ( r ) = F ( r ) m = − G M r 3 r .
Notice that force per unit mass is precisely acceleration as from Newton’s second law. Hence, the acceleration due to gravity of mass m by mass M is precisely g .
The gravitational potential Φ relates energy, work, and force. It can be defined as the gravitational potential energy per unit mass at a particular location. Equivalently, it can be defined as the amount of work per unit mass done against gravity to move a mass from infinity to that location. In the frame of reference of the point mass M inducing a gravitational field (i.e., putting the point mass at the origin), the gravitational potential at position r at a distance r from the point mass is:
Φ ( r ) = 1 m ∫ ∞ r F · d r = ∫ ∞ r G M r 2 d r = − G M r .
Gravitational potential is related to the gravitational field by the gradient. Since gravity is an attractive force, gravitational potential is negative while the gravitational field is positive. The acceleration due to gravity of an object at position r is then given as the negative gradient of the potential:
a = g ( r ) = − ∇ Φ ( r ) = − G M r 3 r .
This implies that we can use gravitational potential for the force calculations and interactions in our N-body system. The useful consequence of this is that gravitational potentials can be combined via superposition. Given a subset of points J, as before, and a point r external to the sphere enclosing the points in J, the resulting potential is:
Φ ( r ) = ∑ j ∈ J − G m j ∥ r − r j ∥
      ≈ − G m J ∥ r − r J ∥ .
Much like forces, we can approximate the superposition of potentials using their total mass m J and their centre of mass r J as seen in (11). However, an even better approximation can be obtained using a multipole expansion.
For simplicity of notation, let us take G = 1 henceforth. A multipole expansion is a series expansion of a function depending on angles. Often, the set of basis functions for this series expansion is the spherical harmonics, a set of orthogonal functions defined on the surface of a sphere. In Cartesian coordinates these functions are the Legendre polynomials. Following [58] (Ch. 3), let us denote the Legendre polynomial of order (degree) k as P k . The multipole expansion of (10) is then given by:
Φ ( r ) = − 1 r ∑ j ∈ J m j ∑ k = 0 n r j r k P k ( cos θ j ) ,
with r j = ∥ r j ∥ and cos θ j = r · r j / r r j . The direct summation of (10) is approached with higher order n in the series (12).
In this series expansion the first few terms are called the monopole, dipole, and quadrupole terms. Including even higher-ordered terms in the approximation yields diminishing returns since their contribution to the approximation decreases with higher order; meanwhile, their computational cost increases. Often, only up to quadrupole terms are included, yet more recent works have included up to octopole terms [59].
Using the compact notation of [58], the multipole expansion of Φ to order 2 is:
Φ 2 ( r ) = − M 0 r − D a x a r 3 − Q a b x a x b 2 r 5 ,
where r = ( x 1 , x 2 , x 3 ) and the summation over { 1 , 2 , 3 } for indices a and b is implied. There are therefore 3 dipole coefficients D a and 9 quadrupole coefficients Q a b . The multipole coefficients hide the summation over the bodies in J as:
M 0 = ∑ j ∈ J m j , Q a a = ∑ j ∈ J m j 3 x a , j 2 − r j 2 ,   D a = ∑ j ∈ J m j x a , j , Q a b = ∑ j ∈ J m j 3 x a , j x b , j ,   if   ( a ≠ b ) ,
where x a , j is the ath coordinate of r j .
Notice that the monopole term is precisely the sum of the masses in J as in our initial approximation. Next, notice that taking the frame of reference to be the centre of mass of the points in J causes the dipole term to vanish ( D a = 0 ) by definition of r J . Via the relation g ( r ) = − ∇ Φ ( r ) , the multipole expansion (13) can be used in place of the approximation (6) for a set of masses J. Therefore, we need only to add the quadrupole terms to obtain an approximation that is better by two orders.

2.3. Simulating Dynamical Systems with Leapfrog Integration

Up to this point we have focused on how to calculate the interactions between bodies in our simulation, and thus each body’s acceleration. Now we must use this acceleration to update the positions and velocities of the bodies in our system so that it may evolve over time.
The simplest method is the basic Euler method. Velocities are updated from accelerations, and positions are updated from velocities. Let r i ( k ) and v i ( k ) be the position and velocity, respectively, of the ith particle at the kth time step. The forward Euler method uses values of derivatives at the current step to approximate values at the next step:
r ( k + 1 ) = r ( k ) + v ( k ) Δ t ,
v ( k + 1 ) = v ( k ) + a ( k ) Δ t .
While simple, the forward Euler method is only a first-order method, meaning that the (local) error introduced at each time step is proportional to O ( Δ t 2 )  [60]. A higher-order method would see that the error reduces more quickly with smaller time steps. For example, a common fourth-order method is the Hermite scheme [58] (Ch. 2). This scheme is a more complex generalization of the classic and simpler scheme known as leapfrog, which is sufficient in many cases.
The leapfrog method is as simple and as computationally expensive as the Euler method, but it is a second-order method, thus providing better accuracy. Leapfrog specifically solves second-order differential equations of the form r ¨ = a ( r ) or, equivalently, v ˙ = a ( r ) , r ˙ = v . The method gets its name from the way that the two differential equations are solved at interleaved time steps, so that each equation jumps over the other in time. The classic formulation of leapfrog shows this jumping structure:
v ( k + 1 2 ) = v ( k − 1 2 ) + a ( k ) Δ t ,
r ( k + 1 ) = r ( k ) + v ( k + 1 2 ) Δ t .
One of the key advantages of this scheme is its simplicity and time symmetry. That is, it provides the same results when run forward in time as when run backward in time. In the context of gravitational simulations, this time symmetry prevents systematic build-up in error in the total energy of the system over time [61]. Why this is a favourable condition is discussed next in Section 2.4.
With a simple rearrangement and translation of time steps, these equations can be written at integer time steps. In particular, we can arrive at the “Kick-Drift-Kick” (KDK) version of leapfrog, also known as the velocity Verlet method:
v ( k + 1 2 ) = v ( k ) + a ( k ) Δ t 2 ,
r ( k + 1 ) = r ( k ) + v ( k + 1 2 ) Δ t ,
v ( k + 1 ) = v ( k + 1 2 ) + a ( k + 1 ) Δ t 2 .
The idea behind KDK leapfrog is to use acceleration from the previous step (k) to update velocity a little bit, to time step k + 1 2 ; this is the first kick. Then, the position is allowed to update by drifting along the trajectory induced by the updated velocity. Then, a second kick occurs to update the velocity based on the acceleration at the current time step ( k + 1 ).
This variation of leapfrog allows for variable time steps. That is, changing the value of Δ t over the course of a simulation to give more precision during volatile points of the simulation (i.e., close encounters). While the KDK leapfrog is employed in our implementation, we currently only use a fixed time step.

2.4. Energy of the System and Standard Units

In order to understand the accuracy of our simulation, particularly our approximation method, a quantitative measure of accuracy or stability is very useful. In a gravitational N-body simulation, this value is the total system’s energy. This is natural as it follows the law of conservation of energy. Since our simulation, by construction, simulates an isolated system, the total energy should be conserved. The total energy of an N-body system is given by the kinetic energy and the potential energy of the N particles. For masses m i , positions r i , and velocities v i , we have:
E k i n = ∑ i = 1 N 1 2 m i ∥ v i ∥ 2 ,   E p o t = ∑ i = 1 N ∑ j = 1 j ≠ i N − G m i m j ∥ r i − r j ∥ ,   E t o t = E k i n + E p o t .
By computing E t o t at the beginning and the end of a simulation (or even throughout), it is possible to obtain a measure of how well the simulation performed. A perfect simulation would perfectly conserve energy. Of course this is not possible due to floating-point errors, truncation errors in the numerical integrator (see Section 2.3), and the approximations introduced in the approximation algorithm itself.
While looking at conservation of energy for any one system is a good measure of its stability, it is not completely adequate. Different systems, with different initial conditions, can have vastly different values for their total energy. We would like a way to measure accuracy agnostic to particular initial conditions or simulation parameters like N or total mass. The few practitioners of N-body simulation in the 1980s then decided on the so-called standard units for gravitational N-body simulations, see [58,62] (Ch. 7).
The standard units define a scaling whereby all simulations have an initial total energy E 0 = − 0.25 . In the standard units, the total mass of the system is scaled to 1, the gravitational constant is 1, and the system’s coordinates are shifted to be centred at its centre of mass. This latter fact makes the system’s centre of mass the origin and the net velocity 0 → . To scale a system to standard units it is first shifted to its centre of mass frame and then its kinetic energy and potential energy are calculated. From the virial theorem, a system in equilibrium has kinetic energy equal to a negative half of its potential energy. One can scale velocities and positions to independently and respectively scale E k i n and E p o t to obtain E k i n = − 1 2 E p o t . Finally, the positions and velocities are scaled together so that E 0 = − 0.25 ; see Algorithm 7.2 in [58].

3. Hierarchical N -Body Methods

In N-body simulations, the dynamical system describing the bodies includes N differential equations. By the mutual interaction of these N bodies, the differential equation describing each body includes N − 1 terms for the N − 1 interactions of that body with all others. The details of this dynamical system were described in Section 2.
From the tools established in the previous section—force or potential calculation, acceleration calculation, and discretized updates to velocity and position via leapfrog integration—we have everything required to perform an N-body simulation. Directly computing the N ( N − 1 ) interaction terms (or 1 2 N ( N − 1 ) , if taking advantage of symmetries), of the dynamical system is infeasible for large-scale simulations. Nonetheless, Algorithm 1 depicts this simple scheme. For each discrete time step in the simulation, the acceleration is computed for each body (Lines 2–5), and then each body’s position and velocity are updated (Lines 6–7).
Algorithm 1 Direct N-Body Simulation (P, Δ t , t e n d )
The general scheme loops over small time intervals, first computing the forces on and the acceleration of each body for that interval, then updating each body’s position. P is the list of bodies and t e n d and Δ t are simulation parameters for the total simulation time and time step, respectively.
1:
for t from 0 to  t e n d  by  Δ t  do
2:
for each particle p in P do                                                                         ▹ Force Calculation
3:
Set the acceleration of p to 0 → .
4:
for each particle q in P ∖ { p }  do
5:
Add the force contribution of q acting on p to the acceleration of p.
6:
for each particle p in P do                                                                         ▹ Position Update
7:
Update position and velocity of p using its current acceleration.
Computing these direct particle–particle interactions scales as N 2 , and is computationally infeasible in practice. Much research has been dedicated to reducing the number of interactions computed while maintaining accuracy in the simulation. As we have seen in Section 2.1 and Section 2.2, a collection of bodies, or a mass distribution, can be approximated by its total mass and centre of mass. The multipole expansion can also be used for an even better approximation. Moreover, recall that the approximation (6) in Section 2.1 approaches equality with larger distances from this centre of mass. Hierarchical methods (treecodes) take advantage of this approximation to reduce the number of interaction terms computed in the force calculations of each time step in the simulation. These methods only modify the force calculation loop of the simulation, leaving the position update, i.e., numerical integration, unchanged.
In the late 1980s two such hierarchical methods arose to reduce the computational efforts required in the force calculation step of N-body simulations. The first method to appear was by Barnes and Hut [6] and eventually named the Barnes–Hut algorithm. The second method of Greengard and Rokhlin is the Fast Multipole Method (FMM) [63]. Both of these approximation algorithms—approximate in the way force acting on a body is calculated, not by numerical or truncation errors—are based on a hierarchical tree representation of the geometric space containing the bodies; hence, treecodes. In two dimensions these methods employ quadtrees, while in three dimensions, octrees are used.
The key idea in treecodes is to describe an ensemble of bodies, a mass distribution, by a single representative pseudo-body in place of its constituents. Then, a far-enough-away test body can approximate its interactions with each of the constituent bodies by a single interaction with the pseudo-body. These are so-called long-range interactions. When this technique is applied hierarchically, the further away a target point is from a group of points, the more of those points can be included in an ensemble to further reduce the number of interactions to be computed for the target point. Whenever two points are considered to be too close, and thus the approximation too inaccurate, computations fall back to the direct method of computing particle–particle interactions. Hierarchical methods thus drastically reduce the total number of interactions needed to be computed, down to O ( N log N ) .
The Barnes–Hut and FMM methods are both hierarchical methods. They differ in two places: (i) how an interaction is determined to be “long-range”; (ii) how long-range interactions are specifically computed. However, let us begin with the commonalities. Both methods begin by constructing a hierarchical tree representing the entire geometric space, which bounds the particles being simulated. The root of this tree is precisely the bounding box of all the particles. The root is then split in half in each of its dimensions. In two dimensions, a quadtree has each node split into 4 children, the area of each being 1 4 of its parent. In three dimensions, an octree splits each of its nodes into 8 children, the volume of each being 1 8 of its parent. This splitting continues recursively until each leaf node contains exactly one particle. A quadtree is shown in Figure 2a, while an octree is shown in Figure 2b.
Figure 2. Two hierarchical trees: (a) the particle distribution of 21 points in two dimensions contained in a quadtree; (b) the particle distribution of 20 points in three dimensions contained in an octree.
With each particle assigned to a leaf node, each method now begins parsing the tree in a bottom-up fashion. Starting from the leaves, for each level in the tree, a single representative particle is computed for the ensemble of particles in the child (and grandchild, etc.) nodes below it. To compute this representative particle, one can simply place it at the centre of mass of the child particles and set its mass equal to the sum of the masses of its children. This is the original formulation of the Barnes–Hut method [6]. However, in the FMM method and later variations of the Barnes–Hut method [3,54,55], the representative particle is instead described by a multipole expansion of the gravitational potential of the ensemble of points. Recall that the centre of mass formulation is equivalent to only the monopole term in the multipole expansion, and including more terms is only required for increased accuracy in approximation; see Section 2.2.
When including terms in the multipole expansion beyond the centre of mass, this representative particle, or pseudo-body, at each level is no longer really a single particle but rather a formula expressing the mass distribution of its children. For a better description we then refer to such a pseudo-body as simply a cell, or node, since there is a one-to-one correspondence between these and the nodes or cells of a tree structure. By both node and cell we refer to the discrete data units of a tree structure. Cell is more common in the context of treecodes, while node is more common for generic data structures. In treecodes, the tree structure thus fulfills two aspects: (i) a spatial decomposition of the bodies being simulated; (ii) succinctly encoding hierarchical groupings of bodies and the approximations of those mass distributions.
With the tree structure fully constructed, it is now used for force calculations for each body. Recall that the key behaviour of treecodes is to approximate the interaction between a body and an ensemble of bodies. Hierarchical ensembles are precisely what are encoded as the internal cells of the tree. To accurately approximate the interaction between a body and an internal cell, they must be “far enough away” or well-separated. If a body and a cell are well-separated, then the force acting on the body by the bodies contained in the cell can be approximated by a single interaction between the body and cell. What it means to be well-separated depends on the particular method.
(i)
In the FMM method, a cell d is statically determined to be well-separated from another cell c if the separation is greater than the side length of c. Note that this definition is not symmetric.
(ii)
In the Barnes–Hut method, a parameter θ , called the opening angle or multipole acceptance criterion (MAC), controls whether a cell should be considered well-separated. If the ratio between a cell’s side length ℓ and the separation d between a point and the cell’s centre of mass is less than θ (i.e., l d < θ ), then they are well-separated. This is depicted in Figure 3.
Figure 3. Determining particle–particle and particle–cell interactions in the Barnes–Hut method. The yellow point is well-separated from the cell, highlighted in red, with side length l 1 if l 1 d 1 < θ . The purple point is well-separated from the large cell, highlighted in red, with side length l 2 if l 2 d 2 < θ . The non-particle endpoints of the two line segments are at the centre of mass of the respective ensemble of points. The two green points are not well-separated, and their close-range interaction must be computed directly.
These two definitions also imply the second major difference between the two methods. While both methods directly compute the so-called particle–particle interactions when two particles are close together, the approximation of long-range interactions differs. In the Barnes–Hut method, all long-range interactions are computed as particle–cell interactions. That is, a cell contributes to the net force acting on a particle. In contrast, in FMM, cell-cell interactions are possible, where all bodies in an ensemble experience the same exerted force by another ensemble. This additional type of interaction allows the FMM method to reach an asymptotic complexity of O ( N ) for the force calculation step. Despite this attractive computational complexity, this method is more mathematically difficult and more challenging to implement [55]. Further, particularly in three dimensions, the constants discarded by the big- O notation in fact dominate running time for practical values of N [54]. For these reasons, we focus on the Barnes–Hut algorithm. We refer the reader to [7,58,63] for further information on the FMM method.
In the Barnes–Hut method, the forces acting on each body are computed via a top-down tree traversal, which can be implemented recursively, starting at the root node. Let ℓ and d be defined as before for the current node. If the multipole approximation is acceptable, l d < θ (i.e., the particle is far enough away from the cell), then a particle–cell interaction is computed, and the traversal along this branch of the tree is complete. Otherwise, the cell is “opened”, and the traversal continues down each of the current node’s children. If a leaf node is encountered, a typical particle–particle interaction is computed.
The entire Barnes–Hut method is detailed in Algorithm 2. It begins by building the tree, which describes the current positions of bodies (Lines 2–7). Notice that the tree construction here proceeds differently, as previously mentioned. Rather than loading all particles into the tree and then recursively dividing cells until the leaves contain exactly one particle, the tree is constructed one particle at a time, splitting cells and pushing particles down the tree until each particle is alone in its leaf node. Once the tree is constructed, it is parsed bottom-up to compute the internal cell multipole moments (Lines 8–9). Next, forces acting on each particle are computed via a tree traversal (Lines 13–22), where particle–particle interactions or particle–cell interactions are computed as appropriate. This is repeated for every body in the simulation. Finally, just as in the direct method, velocities and positions are updated (Lines 23–24).
We conclude the discussion of the classic Barnes–Hut method with a final remark. The essential benefit of the Barnes–Hut method is that traversing the tree and computing the forces on a single particle in this hierarchical manner takes time O ( log N ) . Thus, to compute forces acting on all N particles is O ( N log N ) . First, notice that constructing the tree also takes time O ( N log N ) since N bodies are inserted, on average, to a depth of log N in the tree. This depth arises from the fact that the average size of a leaf node is on the order of the average inter-particle spacing. The best case is a uniform distribution of particles, which creates a balanced tree with log 8 N levels. Then, traversing the tree to compute the forces acting on a particle is also on the order of O ( log N ) . In the worst case, the target particle is “close” to every other particle, and no approximations can be made, thus computing N interactions for that target particle. However, it is not possible for every particle to be close to every particle. Indeed, for branches of the tree not including the target particle, it is much more common for those branches to be approximated with a single particle–cell interaction. Since well-separateness is controlled by the parameter θ , the amount of work spent in the force calculation phase is dependent on θ . It is found that the force calculation for a single particle typically scales as 1 θ 2 log N  [64]; a smaller value of θ requires more cells to be opened and thus more interactions to be computed. Typical values of θ are on the order of 1 2  [6,58].
Algorithm 2 Barnes–Hut Simulation Loop Body (P, θ )
Given a list of particles P and a MAC criterion θ , compute forces and update positions for the current time step. This is repeated for each time step in the simulation.
Build Tree:
  1:
Create a tree T with a single root node that is the bounding box of all particles.
  2:
for each particle p in P do                                             ▹ Spatial decomposition of bodies
  3:
Insert p into the leaf node L of T which encloses the point’s coordinates.
  4:
if L now holds two particles then
  5:
Split L in half in each of its dimensions to create children, L is now an internal node.
  6:
Insert each particle of L into the appropriate child.
  7:
Repeat until each particle is in a separate leaf node.
  8:
for each node in T from leaves to root do                                ▹ Compute mass distribution approximations
  9:
Compute sum of masses of contained points, centre of mass, and multipole values.
Compute Forces:
10:
for each particle p in P do
11:
Set the acceleration of p to 0 → .
12:
N o d e  ← the root node of T  
Compute Cell Force:
13:
for each child cell C of N o d e  do
14:
if C contains 1 particle then                                                   ▹C is a leaf
15:
Add to p’s acceleration the contribution from C’s particle.                                  ▹ particle–particle
16:
else
17:
ℓ ← C’s side length
18:
d ← distance between C’s centre of mass (c.o.m.) and p’s position.
19:
if  l / d < θ  then
20:
Add to p’s acceleration the contribution from C.                                       ▹ particle–cell
21:
else
22:
Compute Cell Force with N o d e ← C                                             ▹ recursive call
Integration step (update velocities and positions):
23:
for each particle p in P do
24:
Update p’s position and velocity using its acceleration.

4. Parallel Implementation of N -Body Simulations and Treecodes

To gain further performance in N-body simulations, and hierarchical methods for such simulations, parallel execution is a natural choice. Toward that goal we will examine two pioneering works: the costzones approach of Singh et al. [7,55], and the hashed octree method of Warren and Salmon [8,54]. The costzones approach was first developed for a shared-memory architecture; meanwhile, the hashed octree method was explicitly developed for a distributed system. Nonetheless, all the techniques we will discuss can be applied to either a shared-memory system or a distributed system, thanks to the message passing model being agnostic to the underlying communication protocol.
We begin this section with a high-level overview of the designs and parallelization techniques of the costzones and hashed octree methods. The details follow in the below subsections.
Just as with any parallel algorithm, both methods are concerned with:
(i)
Minimizing synchronization—where processes must wait for all others before proceeding;
(ii)
Load balancing—ensuring each process has an equal amount of work, thus reducing wait times at synchronization points;
(iii)
Reducing communication overheads—the amount data and number of messages to be shared between processes;
(iv)
Reducing span—the maximum amount of work done by any one process.
Reducing span means parallelizing as many parts of the algorithm as possible. Both the costzones and hashed octree algorithms attempt to parallelize the Barnes–Hut algorithm by:
(a)
Parallelizing the building of the octree;
(b)
Parallelizing the force calculation on each body, i.e., parallelizing the tree traversal
(c)
Parallelizing the integration step.
An obvious and simple approach to parallelizing an N-body simulation is to simply assign N s bodies to each of the s parallel processes. This would be sufficient for the integration step, where each body’s position and velocity are easily updated from its own acceleration. However, due to the mutual interaction between all bodies, the computation of that acceleration requires a global view of the entire simulation domain, and thus a global view of the octree. Both methods have a solution to this global view requirement.
In the costzones method, each process, in parallel, builds a so-called local octree for its assigned bodies. Then, these local octrees are merged into a global octree, which is then shared with all processes. Finally, with each process having a global view of the simulation domain, each process can proceed in parallel to compute the forces on each of its assigned bodies.
In the hashed octree method, again, each process builds its local octree in parallel for its assigned bodies. This method, however, explicitly avoids creating a single global tree. Instead, during the tree traversal and force calculations, when a local particle needs information about the position or multipole values of a non-local particle or cell, that information is requested dynamically from the owning process. An optional improvement is to use asynchronous communication and a latency-hiding traversal to avoid stalling computations while waiting for communications (see Section 4.8). To facilitate consistent addressing of octree cells stored on different processes, the octree is implemented as a hashed octree or linear octree [65]; hence the naming of this method.
Both methods are, in fact, very similar in design. They differ only in how a process receives octree information for non-local bodies. The costzones approach uses upfront communication to construct and share the global octree, and then proceeds with tree traversals in parallel, without any communication. On the other hand, the global tree is not strictly needed to calculate the force on any one particle due to the particle–cell interactions of the Barnes–Hut method. The hashed octree method thus avoids computing the entire global tree at the beginning and instead uses extra communication during the tree traversal to obtain only the essential data for its assigned bodies. In principle, this latter approach is the most scalable, where simulation sizes may grow so large that the entire domain cannot be stored in the memory of a single process.
Nonetheless, both techniques share many similarities to reduce span and improve load balancing. Firstly, a spatial decomposition of the simulation domain is performed. Each process is then assigned a partition of the spatial domain, and the bodies it contains, rather than statically assigning N s bodies to each process. Having the bodies assigned to one process be spatially local greatly improves the tree merging of the costzones method and reduces the number of communications required during the tree traversal step of the hashed octree method. This latter fact is obvious when particle–particle interactions are computed in a Barnes–Hut algorithm. Secondly, dynamic load balancing is achieved by re-partitioning the spatial domain at every time step. Particles in regions dense with others require more work during force computation due to the higher number of particle–particle interactions. Those spatial partitions should be smaller and contain fewer particles so that each process computes roughly the same number of interactions. Thirdly, the spatial partitioning of bodies is implemented by linearizing three-dimensional space via a space-filling curve, sorting the list of bodies based on this linearization, and then partitioning the sorted list. This sort can be parallelized to further reduce span.
Clearly, there are many different opportunities for parallelization in the Barnes–Hut algorithm and many different algorithmic techniques which can be implemented to improve this parallelization through improved load balancing, etc. We now detail each parallelization and technique, one at a time, in the following subsections. These techniques are added incrementally to our implementation to step-by-step improve the parallelization and scalability of the algorithm; see Section 5 for that experimentation.
We begin in Section 4.1 by describing a simple parallelization of the direct method and the parallelization of the integration step. This serves as a point of comparison for the remaining methods to show that the additional work of creating and using the octree is worthwhile. Section 4.2 presents a first parallelization of the Barnes–Hut method where parallel force calculation via tree traversal is added to the previously described parallel integration step. Next, building the octree in parallel and the octree merging process is detailed in Section 4.3. The method of spatial decomposition is then detailed in Section 4.4. Spatial decomposition is further enhanced by dynamic load balancing in Section 4.5 and by distributed sorting in Section 4.6. Section 4.7 introduces the hashed octree and the techniques required to build local octrees which are globally consistent. Finally, we add latency-hiding asynchronous communication to the hashed octree tree traversal in Section 4.8. Therefore, the algorithm described in Section 4.6 describes the “final” version of our costzones-based method, meanwhile the algorithm described in Section 4.8 describes the “final” version of our hashed octree method.
In the following sections we use common terminology from parallel processing and distributed computing, e.g., gather, scatter, and broadcast. For definitions and further details see [66].

4.1. Naive Parallelization of Integration and Particle–Particle Interactions

We have already seen the serial direct method as Algorithm 1 in Section 3. We now formulate this algorithm as a distributed algorithm, as shown in Algorithm 3. We begin by partitioning the bodies evenly across the s processes. No care is taken for spatial decomposition because all O ( N 2 ) interactions will be computed. Next, we compute the mutual forces on the local bodies by the other local bodies (Lines 6–8). Each process sets a temporary list of particles to its own list of local particles. Then, s − 1 rounds of message passing occur (Lines 9–14). Assuming a ring topology, each process sends its current temporary list of particles to the process on the right and receives a new list from the process on the left. The force from each particle in this temporary list is then added to each particle in the local list. Then, the next round begins. After s − 1 rounds, process i d − 1 has received process i d ’s particles and all other particles. This concludes the force calculation in this time step. Each process then updates the positions and velocities of each local particle (Lines 15–16). In this algorithm and all algorithms which follow, we assume the processes are ranked 0 , … , s − 1 .
In this algorithm, each process computes only N ′ ( N ′ − 1 ) + N ′ ( N ′ ) ( s − 1 ) = 1 s N ( N − 1 ) interactions. Further, each process integrates for only N s particles. The span and load-balance of this algorithm are thus optimal, since the total work is N ( N − 1 ) interactions plus N integrations. Nonetheless, the number of interactions still scales as O ( N 2 ) . We thus look to parallelize the Barnes–Hut method with its O ( N log N ) number of interactions.
Algorithm 3 Parallel Direct N-Body Simulation ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                                   ▹ Get Local Bodies
  3:
for t from 0 to  t e n d  by  Δ t  do
  4:
P ′ ← P
  5:
for each particle p in P set acceleration to 0 → .
  6:
for each particle p in P do                                            ▹ Force Calculation with Locals
  7:
for each particle q in P ∖ { p }  do
  8:
Add the force contribution of q acting on p to the acceleration of p.
  9:
for i from 0 to  s − 1  do
10:
Send P ′ to process i d + 1   mod   s
11:
P ′ ← particles received from process i d − 1   mod   s
12:
for each particle p in P do                                          ▹ Force Calculation with Remotes
13:
for each particle q in P ′  do
14:
Add the force contribution of q acting on p to the acceleration of p.
15:
for each particle p in P do                                                  ▹ Position Update
16:
Update position and velocity of p using its current acceleration.

4.2. Parallel Tree Traversal

Having seen our first distributed algorithm, we are now ready to modify the Barnes–Hut algorithm to be executed in parallel. As seen at the beginning of Section 4, there are three aspects to parallelize: (a) the building of the octree; (b) the force calculation; (c) the integration step. Parallelizing the integration is embarrassingly parallel and is as simple as assigning a subset of the bodies to each process, as was just seen in Algorithm 3. The next simplest procedure is to parallelize the force calculation. In the Barnes–Hut method, if the octree encompassing all bodies in the simulation has already been constructed, then parallel force calculation is also embarrassingly parallel, as each process simply traverses the octree for each of its local bodies.
Let us begin with a short review of the implementation of an octree. A simple recursive implementation based on pointers is a direct generalization of a rooted binary tree based on linked lists; see, e.g., [67] (Ch. 11). Each cell in an octree is represented by its data or payload and 8 pointers to its children. Since the octree is deeply connected with the spatial domain, each node is also affixed with its spatial centre and its size—the side length of the cell. The payload of each node, for the purpose of N-body simulation, also includes the position and mass of the body it contains, if a leaf node, or the center of mass and multipole coefficients, if an internal node; see Section 2.2. Figure 4 shows the encoding of an octree with two spatial divisions as a rooted tree of nodes.
Figure 4. An octree with two levels of spatial division, and its corresponding encoding as a rooted tree. The root is black, with side length l 1 ; this side length is the extent of the entire simulation domain. The next division is blue, with side length l 2 , and the next green, with side length l 3 .
Algorithm 4 shows the Barnes–Hut method with simple parallel tree traversal. It begins by assigning N s bodies to each process. Then, the root process (id 0) gathers all bodies (since their positions were updated in the previous simulation step). The root process simply builds the global tree from all bodies at once. This global tree is then broadcast to all other processes (Lines 5–7). With each process having the global octree, they can proceed in parallel to compute the forces on their local bodies with respect to the entire octree (Lines 8–20). Integration steps then proceed in parallel as before (Lines 21–22).
Algorithm 4 Parallel Barnes–Hut V1 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                                                        ▹ Get Local Bodies
  3:
for t from 0 to  t e n d  by  Δ t  do
  4:
P a l l ←  Gather P to process 0.
  5:
if  i d = 0  then
  6:
T ← build octree from P a l l
  7:
Broadcast T from process 0 to all others.
  8:
for each particle p in P do                                                                        ▹ Compute Forces
  9:
Set the acceleration of p to 0 → .
10:
N o d e  ← the root node of T  
  Compute Cell Force:
11:
for each child cell C of N o d e  do
12:
if C contains 1 particle then                                                                                      ▹C is a leaf
13:
Add to p’s acceleration the contribution from C’s particle.                                                                                     ▹ particle–particle
14:
else
15:
ℓ ←C’s side length
16:
d ← distance between C’s c.o.m. and p’s position.
17:
if  l / d < θ  then
18:
Add to p’s acceleration the contribution from C.                                                                                       ▹ particle–cell
19:
else
20:
Compute Cell Force with N o d e ← C                                                                                   ▹ recursive call
21:
for each particle p in P do                                                                         ▹ Position Update
22:
Update position and velocity of p using its current acceleration.
Notice that for this algorithm to fit within the message passing model for distributed algorithms, we must have a way to serialize the octree into a message. Since its encoding is based on pointers and linked lists, this is not immediately obvious. One solution, which we implement, is to add to each node an 8-bit mask whose bits encode whether any of the 8 children actually exist. Then, serializing the octree is as simple as serializing each node and concatenating them in the order of pre-order tree traversal. Deserializing is also made simple by following a pre-order traversal in combination with the deserialized bitmask.
In this simple parallel Barnes–Hut algorithm, the span is not very good since the root process must construct the entire octree in time O ( N log N ) . The force calculation is still done in parallel, but now taking time O ( N s log N ) thanks to the octree and particle–cell interactions. Updating the particle positions and velocities remains at N s integrations.

4.3. Parallel Octree Construction and Merging

Parallelizing the octree construction is a non-trivial task. Naive attempts, such as all processes simultaneously inserting their assigned bodies into a single global octree, require an excessive amount of synchronization. This technique was explored, and abandoned, in [7]. Their improved variation involves each process creating its own local octree from its local bodies and then merging trees together. One fundamental aspect of this merge operation is that each local tree must cover the same spatial domain. That is, their root nodes must have the same size. Then, all cells in all of the local trees have the same sizes. This allows entire subtrees to be inserted into a merged tree where there is an otherwise empty child node. Algorithm 5 presents this merge algorithm; Lines 5–6 and Lines 11–12 show this subtree replacement.
Algorithm 5 Octree Merge ( T 1 , T 2 )
Merges the two octrees rooted at nodes T 1 and T 2 by moving data from T 2 into T 1 . This assumes both T 1 and T 2 have at least one level of children.
  1:
for i from 0 to 7 do
  2:
if  T 1 and T 2 both have an ith child then
  3:
( C 1 , C 2 ) ← (the ith child of T 1 , the ith child of T 2 )
  4:
if  C 1 is a leaf node then
  5:
Insert the particle of C 1 into C 2                                   ▹ see Build Tree of Algorithm 2
  6:
Replace C 1 in T 1 with C 2
  7:
else if  C 2 is a leaf node then
  8:
Insert the particle of C 2 into C 1
  9:
else
10:
Octree Merge ( C 1 , C 2 )                                             ▹ Recursive Call
11:
else if  T 2 has an ith child then                                     ▹ T 1 does not have an ith child
12:
Set the ith child of T 1 to C 2
In the original octree merge of [7], each process’s local tree was merged one at a time into the global tree. This was feasible in a shared-memory model. In a message passing model, or in any more generic parallel scheme, this would require excessive communication and synchronization. Instead, we perform merges of local trees pairwise, in a reduction (see [66] (Ch. 5)), until a single tree contains all N bodies. This single tree is then broadcast to all other processes. Note that while this is phrased in terms of a Map-Reduce pattern, the reduction in fact does not “reduce” the size of data, but performs a gather of the individual local trees. Algorithm 6 shows this scheme, where the parallel tree building occurs in Lines 4–6, and the remaining lines are the same as Algorithm 4. Notice that the reduce step hides many serializations, inter-process messages, and deserializations.
Algorithm 6 Parallel Barnes–Hut V2 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                               ▹ Get Local Bodies
  3:
for t from 0 to  t e n d  by  Δ t  do
  4:
T ′ ← build octree from P                                              ▹ Parallel Tree Build
  5:
T ←  Reduce, via Octree Merge, T ′ to process 0.
  6:
Broadcast T from process 0 to all others.
  7:
for each particle p in P do                                ▹ Compute Forces; unchanged from Algorithm 4
  8:
…
  9:
for each particle p in P do                                               ▹ Position Update
10:
Update position and velocity of p using its current acceleration.
While the above algorithm parallelizes the tree building step, and building each local octree now only incurs time O ( N s log ( N s ) ) , the span of the reduce still requires log ( s ) merges to occur. In the worst case, where each process’s local bodies are uniformly distributed across the entire spatial domain, merging octrees is a laborious process where both trees must be traversed all the way down to their leaves (see the recursive call in Algorithm 5), and then leaf nodes inserted into the other subtree (see Build Tree step of Algorithm 2). A single merge of two trees with n bodies each thus requires time O ( n log n ) , resulting in a span of the parallel octree build of O ( log s ( N log N ) ) . This does not exhibit strong scaling—where the span would reduce with an increased number of processes—since the dominant term is still N log N . A better parallel solution would result in a span with a dominant term of O ( N s log ( N s ) ) .

4.4. Spatial Decomposition via Morton’s Ordering

A key consideration in both the costzones and hashed octree methods is the spatial decomposition of bodies rather than static assignment of bodies to processes. Both methods are based on the idea that each process is responsible for a spatial subdomain of the simulation, and the bodies contained therein, rather than a set of bodies spread across the entire domain. In the costzones method this allows for dynamic load balancing into the namesake costzones (see Section 4.5) and improves the octree merge, as we will soon see. In the hashed octree method, the spatial decomposition minimizes inter-process communication (see Section 4.7).
However, one key challenge for N-body simulation is its dynamic nature and irregularity. It would be wholly insufficient to simply divide the spatial domain into regular pieces and assign one piece to each process. As bodies move throughout the spatial domain during the simulation, some areas would have more bodies, some would have fewer, and some may not contain any bodies at all. This load-balancing problem is further exacerbated by the formation of highly clustered areas as the gravitational system evolves [8].
A first attempt at spatial decomposition involves partitioning the spatial domain so that each process’s domain contains the same number of bodies. This will naturally create different shapes and sizes for each spatial partition. First, a linear ordering is given to the leaf nodes of the octree or, equivalently, the bodies themselves. This is done through the use of a space-filling curve: the Peano–Hilbert curve in the case of costzones and the use of Morton ordering in the case of the hashed octree. This linear ordering on the bodies is then partitioned evenly, and each partition is assigned to a process.
The simpler Morton ordering, or Z-ordering, involves transforming a multi-dimensional coordinate tuple into a single integer, which can then be sorted in a typical integer order. This single integer spatial key is created by interleaving the bits of each coordinate’s value. For example, a 2-dimension ( x , y ) coordinate ( 3 , 5 ) = ( 0 b 0011 , 0 b 0101 ) can be interleaved into the 8-bit spatial key  0 b ( 0 0 ) ( 0 1 ) ( 1 0 ) ( 1 1 ) = 27 . Notice this interleaves and orders the bits such that those from the x-coordinate are more significant; thus, we say this ordering has x > y . A different orientation would be produced with y > x , but it would still create a space-filling curve.
With such a bit interleave, in d dimensions, the spatial key requires d · b bits to encode spatial coordinates which range over the integers [ 0 , 2 b ) . Moreover, spatial coordinates are often encoded using floating-point values, not integers. To remedy this, we perform several mappings to obtain integer spatial coordinates in the range [ 0 , 2 21 − 1 ] ; 2 21 is chosen so that the three-dimensional spatial key of 3 · 21 = 63 bits can be stored in a single 64-bit machine word. First, we must know the extents of the spatial domain. Let us assume the position of each body falls in the range ( − R , R ) , for some integer R, in each dimension. We first translate each coordinate of each body to the range ( 0 , 2 R ) . Then, we map the range ( 0 , 2 R ) to ( 0 , 2 21 ) . Notice this mapping causes a loss of precision, with at most 2 21 discrete values in each dimension. This is sufficient for simulations with up to several million bodies. In larger simulations, a 128-bit key is more than sufficient.
Figure 5a presents the Morton ordering, for x > y , for a quadtree with three levels of spatial division. Figure 5b then shows this Morton ordering applied to a collection of bodies in two-dimensional space; the line connects the bodies in order. In this same figure, a spatial decomposition into 3 partitions is shown, where the list of bodies is separated into 3 sections, each containing 7 bodies. Notice that a partition may span a spatial discontinuity. This is a result of the Morton ordering; a solution would be to use the more complicated Peano–Hilbert ordering.
Figure 5. The Morton ordering on the cells of a quad tree and on a collection of bodies in 2 dimensions. (a) The Morton ordering of a quadtree with three levels of spatial division. This ordering treats the x dimension as more significant than the y dimension in the bit interleave. y > x would instead create a mirrored “Z” shape; (b) The Morton ordering of 21 points in two dimensions. The spatial domain is partitioned into three pieces according to the cell colours. Notice that the second domain contains a spatial discontinuity.
Algorithm 7 presents the parallel Barnes–Hut algorithm, which makes use of spatial decomposition. At each simulation step, all bodies must be gathered to the root process so that their spatial keys can be computed, the bodies sorted, and then the bodies scattered again to each process (Lines 4–8). The sort followed by the scatter implies the spatial decomposition, where the scatter evenly distributes the sorted bodies to each process. The algorithm then proceeds as in Algorithm 6, constructing and sharing a global octree by a reduce and broadcast.
One crucial side effect of the spatial decomposition is its effect on the octree merge. Recall that, in the worst case, each merge requires O ( n log n ) steps to merge two trees, each having n uniformly distributed bodies. As noted in [7] (Section 5.3), since each process now contains a distinct spatial partition, the leaf nodes in each local octree do not overlap. Each local octree thus only shares a few high-level nodes with other local octrees. A merge between two octrees then occurs in time O ( log n ) , since only one traversal is needed to find where to place entire subtrees. The entire reduce then has a span of O ( log N ) , meanwhile the span of the local tree construction remains as O ( N s log ( N s ) ) The dominant term is the latter, and thus the span of the entire parallel tree construction becomes O ( N s log ( N s ) ) .
Notice further that, for a sufficiently small time step Δ t , the bodies will only move very slightly between time steps. Thus, a sorted list of bodies will, after the integration step, still be mostly sorted. We thus implement an insertion sort to sort the particles and keys. Sorting, therefore, only requires a few swaps and time O ( N ) . Yet, it still requires high amounts of communication and sub-optimal scalability, where the particles are gathered to the root process for sorting. We tackle this problem in Section 4.6. However, we first explore a more crucial part of the algorithm: load-balancing the force calculations.
Algorithm 7 Parallel Barnes–Hut V3 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                                 ▹ Get Local Bodies
  3:
for t from 0 to  t e n d  by  Δ t  do
  4:
P a l l ←  Gather P to process 0.                                             ▹ Spatial Decomposition
  5:
if id = 0 then
  6:
k e y s ←  ConstructSpatialKeys ( P a l l ).
  7:
Sort P a l l by k e y s .
  8:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]
  9:
T ′ ← build octree from P                                               ▹ Parallel Tree Build
10:
T ←  Reduce, via Octree Merge, T ′ to process 0.
11:
Broadcast T from process 0 to all others.
12:
for each particle p in P do                                  ▹ Compute Forces; unchanged from Algorithm 6
13:
…
14:
for each particle p in P do                                                ▹ Position Update
15:
Update position and velocity of p using its current acceleration.

4.5. Dynamic Load Balancing

The dominant operation in an N-body simulation is the force calculation. In the direct method it takes time O ( N 2 ) ; in a hierarchical method, it takes time O ( N log N ) . However, not every interaction is created equal when computing forces acting on a particle. A particle in a dense region will have more particle–particle interactions, thus approaching an N number of interactions. A very distant particle in a sparse region may have only particle–cell interactions, thus requiring only O ( 1 ) interactions, depending on the value of the MAC; see Section 3. Moreover, the big- O notation can be misleading. The force calculation step is by far the most dominant part of the N-body simulation—despite it and tree building both taking O ( N log N ) time in serial—taking between 70% and 90% of the time of each simulation time step [7,8]. Therefore, our spatial decomposition scheme, which assigns an equal N / s number of bodies to each of the s processes, is likely insufficient.
The resolution is that of the aptly named costzones, to determine zones—spatial partitions—of equal cost. The exact same operation is performed in the hashed octree method, but it is neither named nor emphasized. The method of determining costzones is simple. Begin with a work estimate w i for each body as the number of interactions computed for that body in the previous time step (in the very first time step, assume w i = N ). Then, each partition (costzone) should be responsible for w = ∑ i = 0 N w i / s amount of work. Determining costzones proceeds by iterating over the spatially linear list of bodies (the list of bodies after sorting by the Morton ordering) and partitioning it into sets whose work estimate is at least w. Algorithm 8 shows this iteration.
Algorithm 9 adds the Costzones load balancing to Algorithm 7. It begins by gathering the work estimates of each particle to the root process (Line 6). This list of work estimates W a l l is then sorted along with P a l l as parallel arrays (Lines 8–9). Costzones are computed using W a l l , and then P a l l is scattered to all processes based on the costzones partitioning (Lines 10–11). Lastly, the tree traversal is modified to accumulate the number of interactions of each particle in the array W (Lines 16, 22, 28). A subtle optimization for the work estimate is to weigh the work of a particle–cell interaction twice as much as a particle–particle interaction. This is because of the multipole approximation incurred by a particle–cell interaction; computing acceleration from a particle–cell interaction involves twice as many floating-point operations as a simple particle–particle interaction (see Section 2.2).
Algorithm 8 Costzones (W, s)
W is a list of size N of work estimates such that W [ i ] is the work estimate of the ith body in the Morton (or other) ordering; s is the number of processes.
Returns a list Z of size s + 1 , returning the index of the first body in process k’s domain partition as Z [ k ] .
  1:
w t o t ← 0
  2:
for i from 0 to  N − 1  do
  3:
w t o t ← w t o t + W [ i ]
  4:
w t a r g ← w t o t / s
  5:
k ← 0 ; w ← 0
  6:
j ← 0 ; Z ← [   ]
  7:
for i from 0 to  N − 1  do
  8:
w ← w + W [ i ]
  9:
if  w ≥ w t a r g  then
10:
Z [ k ] ← j ; j ← i + 1
11:
k ← k + 1 ; w ← 0
12:
Z [ s − 1 ] ← j                                                        ▹ Commit final partition
13:
Z [ s ] ← N                                               ▹ Used to compute end of partition for i d   s − 1
14:
return  Z
Algorithm 9 Parallel Barnes–Hut V4 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                                  ▹ Get Local Bodies
  3:
W ← [ N , … , N ]                                                           ▹W of size N ′
  4:
for t from 0 to  t e n d  by  Δ t  do
  5:
P a l l ←  Gather P to process 0.                                               ▹ Spatial Decomposition
  6:
W a l l ←  Gather W to process 0.
  7:
if id = 0 then
  8:
k e y s ←  ConstructSpatialKeys ( P a l l ).
  9:
Sort P a l l and W a l l by k e y s .
10:
Z ←  Costzones ( W a l l , s)
11:
P ←  Scatter  P a l l sending to process i d   P a l l [ Z [ i d ] , … , Z [ i d + 1 ] − 1 ]
12:
T ′ ← build octree from P                                                 ▹ Parallel Tree Build
13:
T ←  Reduce, via Octree Merge, T ′ to process 0.
14:
Broadcast T from process 0 to all others.
15:
for i from 0 to  | P | − 1  do                                                  ▹ Compute Forces
16:
p ← P [ i ] ; W [ i ] ← 0
17:
Set the acceleration of p to 0 → .
18:
N o d e  ← the root node of T  
   Compute Cell Force:
19:
for each child cell C of N o d e  do
20:
if C contains 1 particle then                                                   ▹C is a leaf
21:
Add to p’s acceleration the contribution from C’s particle.                                  ▹ particle–particle
22:
W [ i ] ← W [ i ] + 1
23:
else
24:
ℓ ←C’s side length
25:
d ← distance between C’s c.o.m. and p’s position.
26:
if  l / d < θ  then
27:
Add to p’s acceleration the contribution from C.                                        ▹ particle–cell
28:
W [ i ] ← W [ i ] + 2
29:
else
30:
Compute Cell Force with N o d e ← C                                             ▹ recursive call
31:
for each particle p in P do                                                  ▹ Position Update
32:
Update position and velocity of p using its current acceleration.
The load balancing of costzones more evenly distributes the amount of work performed by each process during the force calculation step. This comes at the expense of an uneven number of bodies assigned to each process for the octree construction and integration steps. Experiments suggest the number of bodies assigned to any one process is roughly twice that of another. In long-term evolution, clustering may lead to the maximum number of bodies on one process being 10 times as many as the one with the fewest [8] (Section 4). Nonetheless, since the force calculation is such a dominant part of the algorithm, load-balancing the force calculation results in better overall performance despite the loss of load balancing in the other steps.

4.6. Parallel and Distributed Sorting

Our next step toward improved scalability is to avoid the gather of bodies and work estimates to the root process. This gather occurs so that the spatial decomposition via sorting and load balancing via costzones can occur. This gather also incurs high amounts of communication cost, particularly as the number of processes increases. We propose here a solution that provides a distributed algorithm for both the sorting and load-balancing steps so as to avoid excess communication. We note that methods detailed in this section did not appear in the original costzones method [7], but are a result of applying this method to a distributed system.
We begin with the sorting algorithm. One could implement a generalized and highly scalable distributed sort, e.g., methods based on sample sort; see [3,68]. However, we have already made the observation that bodies remain mostly sorted between time steps. Hence, we implement a modification of bubble sort to a distributed system. Simply stated, elements out of place bubble up and are exchanged with the process’s right neighbour, or sink down and are exchanged with the process’s left neighbour.
Assume a linear topology of the processes. Neighbour processes exchange fixed amounts of data, both neighbours sort this exchanged data, and then each keeps their respective halves. For example, process with i d 0 would send its k largest elements to i d 1, and i d 1 would send its k smallest elements. These 2 k elements are locally sorted by both processes, and i d 0 keeps the smallest k, while i d 1 keeps the largest k. Finally, the new data is sorted into the local data collection on each process to update which elements are now the k largest or k smallest. These exchanges repeat between all sets of neighbours until an iteration occurs with no changes on any process.
This distributed sort is shown in Algorithm 10. Local sorting is implemented by insertion sort. Again, since bodies are already mostly sorted, this bubble sort generalization should behave as in the best case, resulting in only O ( 1 ) rounds of exchanges and O ( N s ) total work.
Algorithm 10 Parallel Sort (V, i d , s, k = 64 )
V is a list of size n of values to sort, in place. i d is the executing process’s id, s is the number of processes. k controls the number of values to exchange between neighbours at each step. The result is that any element of V on process i d is less than any element of V on process i d + 1 , and V is locally sorted. This assumes n > 2 k . An experimentally determined default is k = 64 .
  1:
do
  2:
Sort V.
  3:
L e f t ← V [ 0 , … , k − 1 ] concat V [ 0 , … , k − 1 ]
  4:
R i g h t ← V [ n − k , … , n − 1 ] concat V [ n − k , … , n − 1 ]
  5:
if  i d − 1 > 0  then
  6:
Send L e f t [ 0 , … , k − 1 ] to i d − 1 .
  7:
L e f t [ 0 , … , k − 1 ] ← k values from i d − 1 .
  8:
Sort L e f t .
  9:
V [ 0 , … , k − 1 ] ← L e f t [ k , … , 2 k − 1 ]                                                                    ▹ Keep upper half
10:
if  i d + 1 < s  then
11:
Send R i g h t [ k , … , 2 k − 1 ] to i d + 1 .
12:
R i g h t [ k , … , 2 k − 1 ] ← k values from i d + 1 .
13:
Sort R i g h t .
14:
V [ n − k , … , n − 1 ] ← R i g h t [ 0 , … , k − 1 ]                                                                   ▹ Keep lower half
15:
Sort V.
16:
c ′ ← V modified during sort?
17:
c ←  Reduce, via logical OR, c ′ to process 0.
18:
c ←  Broadcast c from process 0 to all others.
19:
while  c ≠ 0
With the addition of a distributed sort, we would like to continue to avoid gathering the bodies and work estimates to the root process for the computation of the costzones. We thus propose a modified costzones approach which load-balances without a gather, requiring only exchanges between neighbouring processes. This is a simple greedy algorithm, shown in Algorithm 11. Each process begins by determining the work target via a reduce and broadcast (Lines 1–6). Then, iterating from process 0 to process s − 2 , each process “pushes” (Lines 14–16) or “pulls” (Lines 17–19) data to or from its right neighbour to achieve its own load balance. Process s − 1 is left with whatever remains. This redistribution and data transfer must be careful not to change the ordering. Notice the ordering of the concatenations upon receiving data (Lines 19 and 24).
Algorithm 11 ParallelCostzones (P, W, i d , s)
P and W are lists of size n of particles and work estimates such that W [ i ] is the work estimate for P [ i ] . i d is the executing process’s id, s is the number of processes. Distributes work between neighbours to achieve costzones-like load balancing.
  1:
w t o t ← 0
  2:
for i from 0 to  N − 1  do
  3:
w t o t ← w t o t + W [ i ]
  4:
w t o t ←  Reduce, via addition, w t o t to process 0.
  5:
w t o t ←  Broadcast  w t o t from process 0 to all others.
  6:
w t a r g ← w t o t / s
  7:
for k from 0 to  s − 2  do
  8:
if  i d = k  then
  9:
w ← 0 ; j ← 0
10:
for i from 0 to  n − 1  do
11:
w ← w + W [ i ]
12:
if  w ≥ w t a r g  and  j = 0  then  j ← i
13:
Send to process i d + 1   ( w − w t a r g )
14:
if  w > w t a r g  then                                                                  ▹ Push excess work to right neighbour
15:
P , P ′ ← P [ 0 , … , j ] , P [ j + 1 , … , n ] ; W , W ′ ← W [ 0 , … , j ] , W [ j + 1 , … , n ]
16:
Send to process i d + 1   ( P ′ , W ′ )
17:
if  w < w t a r g  then                                                                    ▹ Pull work from right neighbour
18:
P ′ , W ′ ← Receive data from process i d + 1
19:
P ← P  concat  P ′ ; W ← W  concat  W ′
20:
else if  i d = k + 1  then
21:
w ′ ← Receive work difference from i d − 1
22:
if  w ′ > 0  then                                                                  ▹ Pull excess work from left neighbour
23:
P ′ , W ′ ← Receive data from process i d − 1
24:
P ← P ′  concat P; W ← W ′  concat W
25:
else if  w ′ < 0  then                                                                    ▹ Push work to left neighbour
26:
w ← 0 ; j ← n
27:
for i from 0 to  n − 1  do
28:
w ← w + W [ i ]
29:
if  w ≥ | w ′ |  then  j ← i ; break;
30:
P ′ , P ← P [ 0 , … , j ] , P [ j + 1 , … , n ] ; W ′ , W ← W [ 0 , … , j ] , W [ j + 1 , … , n ]
31:
Send to process i d − 1   ( P ′ , W ′ )
32:
n ← | P |
33:
Synchronize all processes                                                         ▹ Ensure process k has finished before continuing
Having modified the spatial decomposition and load balancing to be in a distributed manner, Algorithm 12 presents this finalized costzones method, with reduced communications and still parallelized tree construction, tree traversal, and integration steps. This presents the “final” version of a costzones-based Barnes–Hut simulation. The next improvement to make on top of Algorithm 12 is to avoid the octree merge and broadcast. Indeed, for the highest scalability on the largest simulations, we should avoid having the entire global tree present on one process. This is precisely the intent of the hashed-octree method.

4.7. A Distributed Octree Implementation

The hashed octree method is concerned with keeping the scalability of the simulation high and avoiding excess communication caused by broadcasting the global octree. Rather, this method sees that each process dynamically requests the data it needs from other processes during the tree traversal of its local tree.
Such a distributed data structure requires a consistent addressing scheme such that an octree node on one process can be translated into a node on a different process. Moreover, a data structure which allows direct access to a particular node would be beneficial. Recall the basic implementation of an octree based on pointers and linked lists from Section 4.2. Accessing this structure involves traversing pointers and moving from root to leaf— accessing a leaf thus requires time O ( log N ) . Both aspects do not fulfill the needs of a distributed data structure. However, the linear octree or hashed octree (originally presented in [65]) does serve this purpose.
Algorithm 12 Parallel Barnes–Hut V5 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps.
i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]         ▹ Get Local Bodies
  3:
W ← [ N , … , N ]                                   ▹W of size N ′
  4:
for t from 0 to  t e n d  by  Δ t  do
  5:
k e y s ←  ConstructSpatialKeys (P)
  6:
ParallelSort ( { P , W , k e y s } , i d , s )     ▹ Spatial Decomp.; sorting particle-work-key tuples by key
  7:
ParallelCostzones ( P , W , i d , s )                          ▹ Load balance
  8:
T ′ ← build octree from P                          ▹ Parallel Tree Build
  9:
T ←  Reduce, via Octree Merge, T ′ to process 0.
10:
Broadcast T from process 0 to all others.
11:
for i from 0 to  | P | − 1  do             ▹ Compute Forces; unchanged from Algorithm 9
12:
…
13:
for each particle p in P do                          ▹ Position Update
14:
Update position and velocity of p using its current acceleration.
In a hashed octree, each cell is given a unique key. This key directly serves as the index—modulo the table size—into a hash table. The hash table is a standard implementation using chaining and linked lists for conflict resolution; see, e.g., [67] (Ch. 12) or [69] (Ch. 3). A child cell’s key is derived from its parent’s key plus its linear order in the parent’s list of children. These keys will be represented in octal notation for simplicity. The root has key 1; its 8 children have keys: 10, 11, 12, 13, 14, 15, 16, 17. This procedure continues recursively; for example, the children of node 12 are: 120, 121, 122, 123, 124, 125, 126, 127. Notice that this scheme allows for determining the key of a parent or child of a particular node through simple bit operations. The parent’s key is obtained by a 3-bit right shift; the child’s key is obtained by a 3-bit left shift followed by a bit-wise or with the child’s index (0–7).
Any ordering may be used when assigning the indices 0–7 to the children of a particular node, as long as the same ordering is used at each level. A natural ordering in our context is, of course, the Morton ordering of Section 4.4. This Morton ordering of a cell’s position to a spatial key serves the purpose of a traditional hash function, distributing cells of the octree evenly across the hash table. The hash function is then just a mod function over the hash table’s size. Moreover, the spatial keys computed for each body using the Morton ordering directly correspond to the key of the octree node—or the node’s child, grandchild, etc.—in which they are contained. That is to say, the body’s key corresponds to a leaf node’s key if all levels of spatial division are used. It is often not needed to actually divide the octree into that many levels.
Figure 6 shows the key assignment via Morton’s ordering for up to three levels of an octree and an encoding of that octree as a hash table. The nodes of the pointer-based octree can be repurposed to be nodes of the hash table linked list with a simple transformation: (i) the list of pointers to children is replaced by a single pointer to the next cell for collision resolution via chaining; (ii) the cell’s key is included in the payload.
Figure 6. An octree with cells labelled by their hashed octree key, written in octal. Keys are created from a Morton ordering with x > y > z . That octree’s encoding as a hash table—an array of linked lists—with 8 entries is shown to the right. Cells in the octree and nodes in the linked lists are colour-coded. Note that the payload of each node in the linked list is not drawn for clarity.
A hashed octree implementation allows for consistent indexing of nodes in the tree, rather than reliance on pointer traversal. Further, it allows access to any node in the tree in time O ( 1 ) . This scheme allows the N-body simulation to avoid the creation of a global tree and for each process to dynamically and efficiently request remote data from other processes as needed during the tree traversal.
The last requirement is for each process to share the boundary of its spatial domain so that each process knows from where to request data during during the tree traversal. This sharing proceeds in the following three steps and is summarized in Algorithm 13.
(i)
Assume a linear topology of processes, just as in distributed sorting and costzones. In the first step, each process shares the first body in its spatial domain with its left neighbour and the last body in its spatial domain with its right neighbour, if such a neighbour exists. The “neighbour bodies” (or single body for process 0 and s − 1 ) are inserted into the local octree, splitting as needed so that each leaf node contains exactly one body. Due to the spatial ordering of bodies, this insertion will cause the required splitting of leaf nodes so that the union of all leaf nodes across the s local octrees is exactly the leaf nodes that would be created if a global octree were to be constructed. That is to say, all leaf nodes (excluding the leaves containing neighbour nodes) are distinct across all processes, and a consistent spatial partitioning has been created.
(ii)
In the second step, each process computes and broadcasts its so-called branch nodes. These are the set of nodes of the octree which are closest to the root, but which do not contain a neighbour body in their domain. They represent the entire spatial domain of a process at the coarsest level possible. Branch nodes can be found easily by a depth-first traversal of the local octree: if a cell’s domain does not contain a neighbour body, but the cell’s parent’s domain does, then that cell is a branch node.
(iii)
In the third step, a process receives sets of branch nodes as they are broadcast. For each set, those branch nodes are inserted into the local octree and marked with their source process. This source id will allow for dynamically requesting data during tree traversal. If a branch node is received for which its parent is not in the local octree, the parent, grandparent, etc., nodes are “filled” in to the local octree as well.
Upon inserting all the branch nodes, each process has a local octree which is globally and mutually consistent with the other local trees. Figure 7 shows this neighbour exchange and resulting branch nodes for three processes. After sharing and inserting these branch nodes, each local tree contains the required information to request nodes below those of the received branch nodes. Such nodes must be requested during tree traversal when nodes fail the multiple acceptance criterion and must be “opened” (see Section 3).
Algorithm 13 DistributeBranchNodes (P, T, i d , s)
P is the list of local bodies and T is the octree containing those bodies.
i d is the executing process’s id, s is the number of processes.
  1:
if  i d − 1 ≥ 0   then
  2:
Send P [ 0 ] to process i d − 1
  3:
p ← Receive neighbour body from i d − 1
  4:
Insert p into T, splitting as required.
  5:
if  i d + 1 < s   then
  6:
Send P [ n ] to process i d + 1
  7:
p ← Receive neighbour body from i d + 1
  8:
Insert p into T, splitting as required.
  9:
B ← Branch nodes of T, the coarsest noes which do not contain a neighbour body.
10:
for i from 0 to  s − 1  do
11:
Broadcast B from process i to all others.
12:
if  i d ≠ i  then
13:
B ′ ← Receive branch nodes from i
14:
for each node b in B ′  do insert b into T and fill in parents
Figure 7. Three local quadtrees, (a,c,e), before sharing neighbour bodies, and their respective updated quadtrees (b,d,f), after sharing neighbour bodies. The neighbour bodies are coloured corresponding to their owning process. Notice in (f) that the addition of the neighbour body causes a leaf node to split, creating consistent leaf nodes between (d,f). The branch nodes of each process are coloured in (b,d,f). The branch nodes collectively cover every body in the simulation domain.
With the hashed octree data structure and the required branch nodes fully specified, we can now take advantage of this distributed data structure to remove the final reduce and broadcast (apart from a few branch nodes) of our parallel Barnes–Hut algorithm. The span of the simulation is now minimized. Algorithm 14 presents this modified Barnes–Hut method, which implicitly makes use of a hashed octree encoding of the octree. First, the reduce–broadcast of the global tree is replaced with a call to DistributeBranchNodes (Line 9). Second, the tree traversal is slightly modified to check if a node’s children are local or not. If not, they are requested from their source process, as determined by their containing branch node (Lines 14–16). Finally, all processes synchronize before moving to the integration step to ensure all requests from all processes have been fulfilled (Lines 19–20).
Algorithm 14 Parallel Barnes–Hut V6 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps. i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]                                   ▹ Get Local Bodies
  3:
W ← [ N , … , N ]                                                                 ▹W of size N ′
  4:
for t from 0 to  t e n d  by  Δ t  do
  5:
k e y s ←  ConstructSpatialKeys (P)
  6:
ParallelSort ( { P , W , k e y s } , i d , s )                                ▹ Spatial Decomp.; sorting particle-work-key tuples by key
  7:
ParallelCostzones ( P , W , i d , s )                                                    ▹ Load balance
  8:
T ← build hashed octree from P                                                ▹ Parallel Tree Build
  9:
DistributeBranchNodes (P, T, i d , s)
10:
for i from 0 to  | P | − 1  do                                                     ▹ Compute Forces
11:
p ← P [ i ] ; W [ i ] ← 0
12:
Set the acceleration of p to 0 → .
13:
N o d e  ← the root node of T  
Compute Cell Force:
14:
if children of N o d e are not stored locally then
15:
Fulfill any waiting requests for local children from other processes                                 ▹ avoid deadlock
16:
Request and receive the children of N o d e from its owning process
17:
for each child cell C of N o d e  do                                   ▹ Tree traversal unchanged from Algorithm 12
18:
…
19:
while not all processes done force computation do
20:
Fulfill any waiting requests for local children from other processes
21:
for each particle p in P do                                                     ▹ Position Update
22:
Update position and velocity of p using its current acceleration.
In this configuration the requesting process stalls until its request has been fulfilled. Therefore, before a request is actually sent, the process fulfills any and all requests made to it. This avoids the situation where two processes are waiting on each other to fulfill a request. In the next section we will improve this to avoid stalling and instead perform asynchronous communication.

4.8. Latency-Hiding Tree Traversal

The hashed octree method avoids each process from needing the global octree for force computation. Instead, branch nodes are used as entry points to remote trees, where any child node can be dynamically requested from the source process during the tree traversal. In Algorithm 14 that dynamic request is made simple through synchronous and blocking communication. We now suggest a latency-hiding scheme, which uses asynchronous communication to avoid communication overheads.
The concept is simple: during the tree traversal for a particle, maintain a walk list—a queue of nodes which have yet to be traversed—and a defer list—the queue of nodes whose children have been requested from other processes. This strategy also transforms the tree traversal from a recursive method to an iterative one. Algorithm 15 shows this iterative tree traversal to compute the acceleration of one particular body. The walk list begins containing the root node. For each iteration of the traversal, the children of the active node are iterated over, testing for multipole acceptance, which is a particle–cell interaction. If the particle–cell interaction is not acceptable, the child is added to the walk list. If, at any point, a node is encountered whose child cells are not stored locally, then an asynchronous request is sent to the source process for the children, and the node is enqueued to the defer list. The traversal then skips to the next iteration. If, at any point, the walk list becomes empty, then a node is dequeued from the defer list. If the child data of that dequeued node has not yet arrived, the traversal waits synchronously for it. The traversal then continues as normal.
Algorithm 15 AsyncHashedOctreeTraversal (p, T)
p is the body for which to compute its acceleration, T is the local octree.
Returns the work estimate for p for the next time step.
  1:
w ← 0 ; Set the acceleration of p to 0 → .
  2:
w a l k ← [ the   root   node   of   T ] ; d e f e r ← [   ]
  3:
while  w a l k is not empty or  d e f e r is not empty do
  4:
if  w a l k is not empty then
  5:
N o d e ←  dequeue  w a l k
  6:
else
  7:
N o d e ←  dequeue  d e f e r
  8:
Fulfill any waiting requests for local children from other processes
  9:
Wait for receipt of children of N o d e from its owning process
10:
if Children of N o d e are not stored locally then
11:
Fulfill any waiting requests for local children from other processes
12:
Send synchronous request for children of N o d e to its owning process
13:
enqueue  N o d e to d e f e r
14:
continue
15:
for each child cell C of N o d e  do
16:
if C contains 1 particle then                   ▹C is a leaf
17:
Add to p’s acceleration the contribution from C’s particle.   ▹ particle–particle
18:
w ← w + 1
19:
else
20:
ℓ ←C’s side length
21:
d ← distance between C’s c.o.m. and p’s position.
22:
if  l / d < θ  then
23:
Add to p’s acceleration the contribution from C.         ▹ particle–cell
24:
w ← w + 2
25:
else
26:
enqueue C to w a l k
27:
return  w
The individual processes operating in this asynchronous request-and-reply scheme must act cooperatively to achieve the best results. To ensure no request is left waiting for too long, other processes should frequently check for and fulfill incoming requests for data. Such a fulfillment occurs every time a process wishes to make a request itself, thus minimizing access to the communication subprograms and improving locality of operation.
The asynchronous tree traversal easily slots into the previous Barnes–Hut algorithm based on hashed octrees (Algorithm 14). The modified algorithm is presented in Algorithm 16. Notice that each force calculation step still must end with a synchronization so that all requests are fulfilled before any process continues to the integration step (Lines 12–13). This algorithm is the final version of our many parallel Barnes–Hut methods.
Algorithm 16 Parallel Barnes–Hut V7 ( i d , s, Δ t , t e n d , N, P a l l )
P a l l is the list of size N of bodies to simulate from 0 to t e n d going by Δ t time steps.
i d is the executing process’s id, s is the number of processes. Assume s ∣ N .
  1:
N ′ ← N / s
  2:
P ←  Scatter  P a l l , sending to process i d   P a l l [ i d · N ′ , … , i d · N ′ + N ′ − 1 ]          ▹ Get Local Bodies
  3:
W ← [ N , … , N ]                                   ▹W of size N ′
  4:
for t from 0 to  t e n d  by  Δ t  do
  5:
k e y s ←  ConstructSpatialKeys (P)
  6:
ParallelSort ( { P , W , k e y s } , i d , s )     ▹ Spatial Decomp.; sorting particle-work-key tuples by key
  7:
ParallelCostzones ( P , W , i d , s )                           ▹ Load balance
  8:
T ← build hashed octree from P                      ▹ Parallel Tree Build
  9:
DistributeBranchNodes (P, T, i d , s)
10:
for i from 0 to  | P | − 1  do                           ▹ Compute Forces
11:
W [ i ] ←  AsyncHashedOctreeTraversal ( P [ i ] , T)
12:
while not all processes done force computation do
13:
Fulfill any waiting requests for local children from other processes
14:
for each particle p in P do                           ▹ Position Update
15:
Update position and velocity of p using its current acceleration.

5. Experimental Results and Discussion

Throughout the last section, we presented and developed many algorithms for parallel N-body simulation. These algorithms saw various techniques applied incrementally to improve scalability and load balancing. This leads to one parallel version of the direct method and seven versions of the Barnes–Hut method. We summarize those methods here and rename them as follows. The various algorithmic features of these algorithms, and their associated algorithm listing as presented in the previous section, are also summarized in Table 1.
Table 1. A summary of the algorithmic features of the various algorithms to be evaluated in the experimentation. A mapping between the algorithmic listings of Section 4 and the naming conventions presented in this section.
Algorithm 0:
The parallelization of the direct N 2 method. Each process is assigned an equal number of bodies, and the force calculations and integration steps are computed in parallel. This method passes each process’s local set of bodies around in a ring formation to compute forces at each time step. See Algorithm 3.
Algorithm 1:
Barnes–Hut parallelization version 1. Bodies are gathered to the root process, a global octree is constructed serially, and then broadcast to all processes. Force computation (tree traversals) and integration steps are performed in parallel. See Algorithm 4.
Algorithm 2:
Parallel octree construction is added to Algorithm 1, where each process builds a local octree from its local bodies, and then a global tree is constructed through pair-wise merges. The global octree is then broadcast. Force computation and integration steps continue to be computed in parallel. See Algorithm 6.
Algorithm 3:
Spatial decomposition is added to Algorithm 2. Each process is now responsible for some partition of the spatial domain at each time step rather than a fixed set of local bodies. This domain decomposition follows a Morton ordering on the bodies to assign an equal number of bodies, but an unequal amount of space, to each process. The re-partitioning occurs every time step. See Algorithm 7.
Algorithm 4:
Load balancing via costzones is added to Algorithm 3. Bodies are constantly re-distributed such that each process computes roughly the same number of interactions per time step, rather than having the same number of bodies. The spatial partitioning is still applied. See Algorithm 9.
Algorithm 5:
Collective gather and scatter operations are removed from Algorithm 4 with the addition of a distributed sort for the spatial decomposition and a greedy distributed re-balance into costzones. This is the final variation of our costzones-based method. See Algorithm 12.
Algorithm 6:
The final collective operations are removed from Algorithm 5: the octree merge and broadcast of the global octree. The basic octree implementation is reformed as a hashed octree implementation to allow for unique and consistent indexing into all local octrees. The global octree thus remains distributed. During tree traversal, when a process requires non-local data, it is requested dynamically from the owning remote process. See Algorithm 14.
Algorithm 7:
The tree traversal of Algorithm 6 is improved by asynchronous communication and a latency-hiding tree traversal. Rather than waiting for requested remote data to be returned, those requested nodes are put on a so-called defer list, and the algorithm proceeds in the meantime by traversing other branches. See Algorithm 16.
These eight algorithms have been implemented in C/C++ using C++11 and the OpenMPI v2.1.1 implementation [57]. We also implement an OpenGL 3.3 implementation of a 3D visualization tool for the simulations. Screenshots of which are shown in Figure 1 and Figure 8. Our source code is freely available at https://github.com/alexgbrandt/Parallel-NBody/ (accessed on 12 December 2025).
Figure 8. The interaction and evolution of two Plummer model clusters, each with 2000 bodies.
To test these algorithms, we consider a standard test [6,7,55,56] involving the interaction and eventual collision of two globular clusters. Each spherical cluster contains equal-mass stars and follows a Plummer model [70]. In this model, the mass density of a core of some Plummer radius is highly dense and then falls off as r − 5 2 outside the core. These clusters are initially separated from each other in each of the spatial dimensions and then brought together under their mutual gravity. In a simulation with N bodies, each cluster is given N 2 . Figure 8 shows how this simulation evolves over time for N = 4000 .
All experiments in this section simulate this interaction of two Plummer clusters, varying only in N, the number of bodies in the system, and p, the number of parallel processes executing the problem. All trials use the same random seed when constructing the clusters. All simulations are run in the standard units (see Section 2.4) and with a multipole acceptance criterion θ = 0.5 , a time step of 0.01, and 500 total time steps. Our experiments were performed on a local area network cluster of 10 nodes, each with two Intel Xeon X5650 processors (6 cores each; 12 cores per node), a 12 × 4 GB DDR3 main memory at 1.33 GHz, and running Ubuntu 18.04.4 and GCC 7.5.0. For tests where p ≤ 10 , each process is mapped to a distinct node of the cluster, where p > 10 processes are distributed evenly across nodes and across sockets on each node.
We begin our experimentation by validating the correctness of our implementation. Recall from Section 2.4 that a stable simulation will—up to numerical errors—conserve energy. Table 2 shows the percent change in total energy of the system at the end of the 500 simulation steps. These changes represent a change in energy of less than 0.0005 in standard units. The original implementation of Barnes and Hut conserved energy to about 1% [6], thus these results are satisfactory. Note also that for any one algorithm the change in energy was identical for every number of processes p—even up to machine precision—suggesting that the parallelization itself is correct and does not modify the operation of the simulation itself.
Table 2. Absolute value of percent change in total energy after 500 simulation steps for various experimental trials. Change in total energy was identical for all number of processes p for any one algorithm. Change in energy for the direct method (Algorithm 0) can be attributed to the truncation error in integration and floating-point error. Change in energy for all others also includes the added error of force approximation.
Next, we consider a large test suite of our eight algorithms. For each algorithm we run the previously described two-cluster scenario for N ∈ { 10,000 , 20,000 , 40,000 , 60,000 , 80,000 } and p ∈ { 1 , 2 , 4 , 8 , 10 , 20 , 40 , 80 , 100 } . Figure 9 summarizes these results. As expected, Algorithm 0 runs much slower than the other algorithms with its O ( N 2 ) complexity. However, its optimal parallelization and minimal communication overhead lead to near-linear parallel speedup. For N = 10,000, algorithms achieve moderate speedup for small p but then communication overheads quickly dominate. This can be seen as the up then down shape of parallel speedup curves for Algorithms 4–7 and the flattening of the curve for the other algorithms. For N = 80,000, the achieved speedup is much better for the more complex algorithms, with Algorithm 7 achieving the highest speedup, as hoped for. Nonetheless, speedup still quickly flattens after p = 40 . This again indicates communications are dominating, and a larger N is needed to take full advantage of the scalability of the algorithms. The algorithms exhibit weak scaling but not strong scaling.
Figure 9. First column: execution time vs. simulation size (number of bodies N) for p = 10 and p = 40 , respectively. Second column: parallel speedup vs. number of processes, for N = 10,000 and N = 80,000 , respectively. No data for Algorithm 0 for N = 80,000 . Third column: the same as the second column, but focusing on the range p ∈ [ 0 , 10 ] . Parallel speedup plots include the ideal speedup as a dashed line. Algorithm 0 achieves near-linear speedup but an exorbitant running time. The simpler algorithms achieve better execution time, but worse parallel speedup, indicating that larger values of N are needed for other algorithms to perform favourably.
Throughout Section 4 we presented incremental changes as an attempt to continually improve the parallelization of the Barnes–Hut algorithms. Despite this, the data shows some surprising results, listed below.
(i)
The most simple Barnes–Hut algorithm, Algorithm 1, achieves the best performance in terms of execution time. Further, even for N = 80,000 , it achieves the third-best parallel speedup. The scheme is simple and does not involve much additional work for computing spatial decomposition or load balancing, just a single gather of bodies and broadcast of the serially constructed tree. However, the slopes of the execution times for p = 40 suggest this would no longer hold for slightly larger values of N.
(ii)
Algorithm 7 achieves superlinear speedup for a low to moderate number of processes. While the work law tells us that p T p ≥ T 1 (the time to execute a program in parallel times the number of processes should always be more than the serial execution time), notice that Algorithm 7 in fact can perform less overall work when more processes are added. This is due to each process computing only a local tree, and the global tree is never fully constructed.
(iii)
Algorithm 4 achieves very poor performance. The change from Algorithm 3 to Algorithm 4 is the simple addition of costzones load balancing. Computing costzones is a simple O ( N ) operation which requires only a single iteration over the list of work estimates. This alone cannot explain the difference. Rather, this experimentation suggests that the performance of a regular gather and scatter—where each process sends and receives the exact same size of data—is able to achieve much better performance than a irregular gather and scatter—where each process sends and receives a different amount of data. The costzones load balancing requires the latter. In implementation this causes the MPI_Gather and MPI_Scatter calls to be replaced with MPI_Gatherv and MPI_Scatterv, respectively. Some slowdowns are expected when moving to the more generalized irregular routine [71], but this experimentation suggests the performance difference in OpenMPI is quite drastic. It could perhaps be mitigated with a newer version of OpenMPI. Regardless, moving to a distributed sort and costzones in Algorithm 5 removes these irregular gather and scatters and again improves performance.
To examine more closely the performance characteristics of the different parallelization algorithms, Figure 10 presents data for Algorithms 1, 5 and 7. Recall that Algorithm 5 is the final variation based on costzones and Algorithm 7 is the final variation based on the hashed octree. We choose these algorithms as the others are intermediary algorithms with only a subset of optimizations applied. Figure 10 presents 3 plots for each algorithm: (i) the parallel speedup achieved for various sizes of N; (ii) the execution time for various numbers of processes p (as a log–log plot); (iii) the parallel cost—p times the execution time in parallel T p —scaled by N and for various number of processes (as a log–log plot).
Figure 10. (Top row): the parellel speedup vs. number p of processes for Algorithms 1, 5 and 7. (Middle row): the execution time vs. number N of bodies in the system for Algorithms 1, 5 and 7. Note log–log scaling. (Bottom row): the parallel cost (number p of processes times execution time) per body vs. number N of bodies in the system for Algorithms 1, 5 and 7. Note log–log scaling.
First, we consider parallel speedup. The parallel speedups for Algorithm 1 show that increasing speedup has reached a limit as N increases. Parallel speedup does not continue to increase with a per-process increase in problem size, thus Algorithm 1 has poor scalability. Algorithm 5 improves in its speedup with increased work per process, but overall speedup is still lacking. Communication costs begin to dominate. Algorithm 7 achieves great and continual improvements in speedup for increasing problem size, indicating its superior scalability.
Second, the execution time for each algorithm for various process sizes is plotted against the value of N. Where these log–log plots show nearly parallel lines, it indicates that adding more processes scales down work proportionately. The separation between lines shows continual improvement in speedup with adding more processes; for Algorithm 1, the lines for p = 40 , 80 , 100 are not well-separated, again indicating its poor scalability. For Algorithms 5 and 7 the curvature of the lines for high values of p and low values of N indicate how communication and parallelization overheads dominate the running time. Where the lines have flattened for larger values of N, it indicates that the algorithm has reached a sufficient problem size where the simulation work rather dominates. Importantly, we see that for p ≥ 80 , neither algorithm has really reached its full potential with these smaller data sets.
Third, we present the value p T p N vs. N for various values of p. This parallel cost indicates how the additional work for parallelization and communication overheads changes with adding processes and more work per process. The distance between the p = 1 line and any other line indicates the parallel overhead. For larger values of N these lines should converge but remain parallel as communication becomes a fixed proportion of the overall running time. For Algorithm 1 all lines have reached the parallel stage for low to moderate values of N, indicating they have reached their limit in scalability. For Algorithm 5, trends have begun to flatten for high values of N; meanwhile, the vertical distance between, say, p = 100 and p = 1 is still quite large. This indicates that a large proportion of Algorithm 5 is spent on parallel overheads. For large values of N we see that the lines for Algorithm 7 converge, and even intersect, where any line below that of p = 1 indicates superlinear speedup. For p ≥ 40 we see that the lines are still trending downward, indicating that Algorithm 7 has not reached its “large-N limit”, and further speedup can be achieved on any fixed number of processes by increasing the simulation size.

Interpreting and Extrapolating the Results

The data provided in Figure 9 and Figure 10 may initially be surprising. Indeed, Algorithm 1, the simplest parallelization scheme of the Barnes–Hut method, has the fastest execution time and the lowest parallel cost per body for the number of processes and number of bodies tested. However, this is merely the result of the relatively small number of processes and bodies evaluated in this study. In the original hashed octree work [8], 512 processes were used to simulate 8.8 million particles. This is clearly much larger than the 100 processes and 80,000 particles used in this study. These experiments were limited by the executing environment, and larger experiments are left to future work. Nonetheless, one can reasonably extrapolate the data provided here to draw additional conclusions. We again focus on Algorithms 1, 5 and 7 as the others are intermediary algorithms with only a subset of optimizations applied.
In Figure 10, we can see that the parallel speedup of Algorithm 1 has reached a limit. Increasing the number of bodies being simulated no longer improves parallel speedup. This indicates that Algorithm 1 has poor scalability despite it having the fastest execution time, as just discussed. This algorithm, at each time step, collects all particles to the root process and serially builds the global octree before broadcasting the global tree to all other processes. Therefore, one may reasonably expect that Algorithm 1 will be dominated by communication costs with increasing numbers of processes. For the best scalability, we must avoid such all-to-one (and one-to-all) communications. Moreover, with very large numbers of particles, it may be impossible for a single process to store the entire set of particles and the entire global octree in its memory.
Algorithm 5 similarly suffers from some all-to-one communications. Although this algorithm has been enhanced with load balancing, spatial decomposition, and building the octree in parallel, it still requires collecting the various local octrees and merging them into a single global octree via a reduce operation before broadcasting the resulting global octree. This is a natural bottleneck. Recall that Algorithm 5 is based on the costzones method. Costzones was originally designed for a shared memory architecture, where this reduction to the root process and subsequent broadcast of the global octree would be much less costly. Despite this, we can still see some promising results from the parallel cost for Algorithm 5 in Figure 10. For larger number of processes and large values of N, the parallel costs are still marginally decreasing, indicating it has the potential to improve its performance with larger simulations, That is, until we reach a point as just discussed about Algorithm 1 where it becomes impossible for a single process to store in its memory the entire global octree.
This limiting feature of Algorithm 1 and 5 is removed from Algorithm 7 with its use of a distributed global octree. Therefore, in the large-scale, where the simulation is so large as to not be able to fit on a single process, Algorithm 7 is essential. The distributed global octree also results in Algorithm 7, which avoids any all-to-one communications, removing this bottleneck. Further, Algorithm 7 has the most promising results in Figure 10. It notably has the highest parallel speedup among the algorithms, and this speedup continues to increase with larger simulation sizes, unlike the other algorithms. Although Algorithm 7 has a higher execution time than Algorithm 1 or Algorithm 5, this is only due to the scale of these particular experiments. For p ≥ 80 , the execution time of Algorithm 7 barely increases as the simulation size increases. It is clear that with slightly larger values of N than were tested here, Algorithm 7 would be the algorithm with the lowest execution time. This argument is further bolstered by the steep negative slope of the parallel cost per body for Algorithm 7 and p ≥ 80 . This tells us that the parallel and communication overheads dominate with the relatively small numbers of bodies, but the parallel cost per body will further decrease with larger values of N.
In conclusion, Algorithm 7 is thus the most promising algorithm for future work and experimentation. This is not surprising given that methods based on hashed octree and a distributed global octree, like TreePM, form the basis of the largest and most advanced N-body simulations to date (See Section 1.1). Our experimentation shows that Algorithm 7 offers the best parallel speedup and scalability among the algorithms described and evaluated in this paper. Nonetheless, other algorithms have their place in special circumstances, including Algorithm 1, which offers the overall fastest execution time for small numbers of bodies and Algorithm 5, which offers potential in a shared memory environment where communication overheads are less drastic.

6. Conclusions

Throughout this article we have examined the necessary mathematical background and the classical formulations of hierarchical methods for gravitational N-body simulations. We have collected and presented the work of many papers: [3,6,7,8,54,55,56], providing a cohesive and thoroughly detailed source for reproducibility and as a basis for future work. In Section 4, we provide a comprehensive guide to the parallelization and distributed implementation of hierarchical N-body methods, motivated by the costzones [7] and hashed octree [8] methods. We have incrementally applied various techniques to progressively improve a parallel and distributed Barnes–Hut algorithm. The open-source implementation of these algorithms in C/C++ using MPI was tested on a small compute cluster with great results.
Overall, the experimental data presented in Section 5 suggests two things. First, that the costzones method and octree merge [7,55,56] used in Algorithms 3–5 incur a high degree of parallel overhead. This method was first developed for a shared-memory system where communication and inter-process synchronization are significantly cheaper. On distributed systems this method is less practical, although much simpler and easy to implement. Second, the scalability of Algorithm 7, based on the hashed octree method [8,54] is highly encouraging. While, for raw execution time, the simplest parallelization scheme of Algorithm 1 won out, this trend would not continue for larger simulation sizes or for a larger number of processes. The hashed octree method can provide superlinear speedup for large simulations and provides excellent scaling and speedup for increasing amounts of work per process. Further refinement and experimentation are needed to fully validate the trends and conclusions drawn from the rather limited experimentation presented here. Indeed, experimentation on a compute cluster with many more nodes and cores is needed to fully assess the large-scale scalability of the methods presented here and to better compare them to other state-of-the-art implementations. This is left to future work.

Future Work

In this work we have extensively described the Barnes–Hut method and various algorithms and optimizations toward its effective implementation in a distributed environment. Yet, much work can still be done to further expand this work. Continuing in this paper’s spirit of reproducibility and detailed exposition, a natural direction for future work is the continued study and algorithmic description of more advanced methods used in more recent N-body simulations. The TreePM method [49,50,51], for example, has been used in some of the most advanced and large-scale simulations to date; see Section 1.1. This hybrid method applies the Particle–Mesh method on top of treecodes like Barnes–Hut. Thus, a detailed examination of Particle–Mesh and TreePM is a clear objective for future work.
Focusing on computation, there are many possible future directions in conjunction with distributed computing. Recent advancements in hardware technologies provide interesting opportunities. GPUs provide one of the most promising directions. They can be applied to accelerate the entire tree-based algorithm, such as in [42], or to accelerate parts of the algorithm, including those for tree traversal and force calculation [38]. Yet, as GPU hardware continues to quickly and drastically evolve, novel approaches are needed. One very recent approach is to leverage ray-tracing cores to accelerate the Barnes–Hut method [44]. However, we believe that an even more promising approach is the use of high-throughput tensor cores in recent GPUs. Motivated by artificial intelligence workloads, tensor cores provide vastly higher throughput than standard GPU processing units for matrix operations. Although N-body simulations are not typically expressed in terms of matrix operations, recent work has shown that tensor cores can be exploited for non-matrix operations as well, such as in stencil computations [72].
Another recent direction taken by hardware technology is the rapid increase in the number of cores available on a single CPU. In the 2010s, the number of cores on a CPU was rather modest, typically ranging from 8 to 16. Recently, however, this number has exploded. For example, the AMD EPYC 9965 CPU boasts a staggering 192 cores. Practitioners have noticed that N-body algorithms developed for early multi-core CPUs and distributed computing may not be optimal for these new many-core shared-memory environments [46]. Moving forward, algorithms must be designed to explicitly take advantage of these many-core CPUs in combination with distributed algorithms. Indeed, MPI allows for cores on a single node to act as independent ranks, thus allowing a single MPI implementation to execute across multiple cores and multiple nodes. However, it has been seen that explicitly using multithreading for intra-node parallelization provides improvements compared to using only a message-passing scheme [15,16]. We believe future N-body simulations will need an explicit hybrid parallel-distributed approach. We will need to develop novel techniques to take advantage of these modern many-core CPUs and develop novel techniques to best manage distributed algorithms executed across clusters of these many-core CPUs.

Funding

This research received no external funding.

Data Availability Statement

The original data presented in the study are openly available in GitHub at https://github.com/alexgbrandt/Parallel-NBody/ (accessed on 12 December 2025).

Conflicts of Interest

The authors declare no conflict of interest.

References

  1. Sutherland, B. Beautiful Models: 70 Years of Exactly Solved Quantum Many-Body Problems; World Scientific Publishing Company: Singapore, 2004. [Google Scholar]
  2. Gould, H.; Tobochnik, J.; Christian, W. Computer Simulation Methods, 3rd ed.; Addison-Wesley: Reading, MA, USA, 2006. [Google Scholar]
  3. Warren, M.S. 2HOT: An improved parallel hashed oct-tree n-body algorithm for cosmological simulation. Sci. Program. 2014, 22, 109–124. [Google Scholar] [CrossRef] [Scilit]
  4. Hockney, R.W.; Eastwood, J.W. Computer Simulation Using Particles; CRC Press: Boca Raton, FL, USA, 1988. [Google Scholar]
  5. Carrier, J.; Greengard, L.; Rokhlin, V. A fast adaptive multipole algorithm for particle simulations. SIAM J. Sci. Stat. Comput. 1988, 9, 669–686. [Google Scholar] [CrossRef] [Scilit]
  6. Barnes, J.; Hut, P. A hierarchical O(N log N) force-calculation algorithm. Nature 1986, 324, 446–449. [Google Scholar] [CrossRef] [Scilit]
  7. Singh, J.P.; Holt, C.; Hennessy, J.L.; Gupta, A. A parallel adaptive fast multipole method. In Proceedings of the 1993 ACM/IEEE Conference on Supercomputing; ACM: New York, NY, USA, 1993; pp. 54–65. [Google Scholar]
  8. Warren, M.S.; Salmon, J.K. A Parallel Hashed Oct-Tree N-Body Algorithm. In Proceedings of the 1993 ACM/IEEE Conference on Supercomputing; Supercomputing ’93; ACM: New York, NY, USA, 1993; pp. 12–21. [Google Scholar]
  9. Khan, F.M.; Berentzen, I.; Berczik, P.; Just, A.; Mayer, L.; Nitadori, K.; Callegari, S. Formation and hardening of supermassive black hole binaries in minor mergers of disk galaxies. Astrophys. J. 2012, 756, 30. [Google Scholar] [CrossRef] [Scilit]
  10. Mayer, L.; Kazantzidis, S.; Madau, P.; Colpi, M.; Quinn, T.; Wadsley, J. Rapid formation of supermassive black hole binaries in galaxy mergers with gas. Science 2007, 316, 1874–1877. [Google Scholar] [CrossRef] [Scilit] [PubMed]
  11. Ishchenko, M.; Sobolenko, M.; Berczik, P.; Khoperskov, S.; Omarov, C.; Sobodar, O.; Makukov, M. Milky Way globular clusters on cosmological timescales-I. Evolution of the orbital parameters in time-varying potentials. Astron. Astrophys. 2023, 673, A152. [Google Scholar] [CrossRef] [Scilit]
  12. Ogiya, G.; Nagai, D.; Ishiyama, T. Dynamical evolution of primordial dark matter haloes through mergers. Mon. Not. R. Astron. Soc. 2016, 461, 3385–3396. [Google Scholar] [CrossRef] [Scilit]
  13. Ebisu, T.; Ishiyama, T.; Hayashi, K. Constraining self-interacting dark matter with dwarf spheroidal galaxies and high-resolution cosmological N-body simulations. Phys. Rev. D 2022, 105, 023016. [Google Scholar] [CrossRef] [Scilit]
  14. Ishiyama, T.; Nitadori, K.; Makino, J. 4.45 Pflops astrophysical N-body simulation on K computer–The gravitational trillion-body problem. In SC’12: Proceedings of the International Conference on High Performance Computing, Networking, Storage and Analysis; IEEE: Washington, DC, USA, 2012; pp. 1–10. [Google Scholar]
  15. Potter, D.; Stadel, J.; Teyssier, R. PKDGRAV3: Beyond trillion particle cosmological simulations for the next era of galaxy surveys. Comput. Astrophys. Cosmol. 2017, 4, 2. [Google Scholar] [CrossRef] [Scilit]
  16. Ishiyama, T.; Yoshikawa, K.; Tanikawa, A. High performance gravitational N-body simulations on supercomputer Fugaku. In Proceedings of the International Conference on High Performance Computing in Asia-Pacific Region; ACM: New York, NY, USA, 2022; pp. 10–17. [Google Scholar]
  17. Skillman, S.W.; Warren, M.S.; Turk, M.J.; Wechsler, R.H.; Holz, D.E.; Sutter, P. Dark sky simulations: Early data release. arXiv 2014, arXiv:1407.2600. [Google Scholar] [CrossRef] [Scilit]
  18. Inman, D.; Yu, H.R.; Zhu, H.M.; Emberson, J.; Pen, U.L.; Zhang, T.J.; Yuan, S.; Chen, X.; Xing, Z.Z. Simulating the cold dark matter-neutrino dipole with TianNu. Phys. Rev. D 2017, 95, 083518. [Google Scholar] [CrossRef] [Scilit]
  19. Heitmann, K.; Finkel, H.; Pope, A.; Morozov, V.; Frontiere, N.; Habib, S.; Rangel, E.; Uram, T.; Korytov, D.; Child, H.; et al. The outer rim simulation: A path to many-core supercomputers. Astrophys. J. Suppl. Ser. 2019, 245, 16. [Google Scholar] [CrossRef] [Scilit]
  20. Ishiyama, T.; Prada, F.; Klypin, A.A.; Sinha, M.; Metcalf, R.B.; Jullo, E.; Altieri, B.; Cora, S.A.; Croton, D.; de La Torre, S.; et al. The Uchuu simulations: Data Release 1 and dark matter halo concentrations. Mon. Not. R. Astron. Soc. 2021, 506, 4210–4231. [Google Scholar] [CrossRef] [Scilit]
  21. Heitmann, K.; Frontiere, N.; Rangel, E.; Larsen, P.; Pope, A.; Sultan, I.; Uram, T.; Habib, S.; Finkel, H.; Korytov, D.; et al. The last journey. I. An extreme-scale simulation on the Mira supercomputer. Astrophys. J. Suppl. Ser. 2021, 252, 19. [Google Scholar] [CrossRef] [Scilit]
  22. Vogelsberger, M.; Marinacci, F.; Torrey, P.; Puchwein, E. Cosmological simulations of galaxy formation. Nat. Rev. Phys. 2020, 2, 42–66. [Google Scholar] [CrossRef] [Scilit]
  23. Angulo, R.E.; Hahn, O. Large-scale dark matter simulations. Living Rev. Comput. Astrophys. 2022, 8, 1. [Google Scholar] [CrossRef] [Scilit]
  24. Nitadori, K.; Makino, J.; Hut, P. Performance tuning of N-body codes on modern microprocessors: I. Direct integration with a hermite scheme on x86_64 architecture. New Astron. 2006, 12, 169–181. [Google Scholar] [CrossRef] [Scilit]
  25. Tanikawa, A.; Yoshikawa, K.; Okamoto, T.; Nitadori, K. N-body simulation for self-gravitating collisional systems with a new SIMD instruction set extension to the x86 architecture, Advanced Vector eXtensions. New Astron. 2012, 17, 82–92. [Google Scholar] [CrossRef] [Scilit]
  26. Tanikawa, A.; Yoshikawa, K.; Nitadori, K.; Okamoto, T. Phantom-GRAPE: Numerical software library to accelerate collisionless N-body simulation with SIMD instruction set on x86 architecture. New Astron. 2013, 19, 74–88. [Google Scholar] [CrossRef] [Scilit]
  27. Kodama, T.; Ishiyama, T. Acceleration of the tree method with an SIMD instruction set. Publ. Astron. Soc. Jpn. 2019, 71, 35. [Google Scholar] [CrossRef] [Scilit]
  28. Sugimoto, D.; Chikada, Y.; Makino, J.; Ito, T.; Ebisuzaki, T.; Umemura, M. A special-purpose computer for gravitational many-body problems. Nature 1990, 345, 33–35. [Google Scholar] [CrossRef] [Scilit]
  29. Makino, J.; Fukushige, T.; Koga, M.; Namura, K. GRAPE-6: Massively-parallel special-purpose computer for astrophysical particle simulations. Publ. Astron. Soc. Jpn. 2003, 55, 1163–1187. [Google Scholar] [CrossRef] [Scilit]
  30. Kawai, A.; Fukushige, T. $158/Gflops astrophysical N-body simulation with reconfigurable add-in card and hierarchical tree algorithm. In Proceedings of the 2006 ACM/IEEE Conference on Supercomputing; IEEE: Washington, DC, USA, 2006; p. 48. [Google Scholar]
  31. Del Sozzo, E.; Rabozzi, M.; Di Tucci, L.; Sciuto, D.; Santambrogio, M.D. A scalable FPGA design for cloud n-body simulation. In Proceedings of the 2018 IEEE 29th International Conference on Application-Specific Systems, Architectures and Processors (ASAP); IEEE: Washington, DC, USA, 2018; pp. 1–8. [Google Scholar]
  32. Menzel, J.; Plessl, C.; Kenter, T. The strong scaling advantage of FPGAs in HPC for N-body simulations. ACM Trans. Reconfig. Technol. Syst. (TRETS) 2021, 15, 10. [Google Scholar] [CrossRef] [Scilit]
  33. Belleman, R.G.; Bédorf, J.; Zwart, S.F.P. High performance direct gravitational N-body simulations on graphics processing units II: An implementation in CUDA. New Astron. 2008, 13, 103–112. [Google Scholar] [CrossRef] [Scilit]
  34. Gaburov, E.; Harfst, S.; Zwart, S.P. SAPPORO: A way to turn your graphics cards into a GRAPE-6. New Astron. 2009, 14, 630–637. [Google Scholar] [CrossRef] [Scilit]
  35. Nitadori, K.; Aarseth, S.J. Accelerating NBODY6 with graphics processing units. Mon. Not. R. Astron. Soc. 2012, 424, 545–552. [Google Scholar] [CrossRef] [Scilit]
  36. Hamada, T.; Nitadori, K.; Benkrid, K.; Ohno, Y.; Morimoto, G.; Masada, T.; Shibata, Y.; Oguri, K.; Taiji, M. A novel multiple-walk parallel algorithm for the Barnes–Hut treecode on GPUs–towards cost effective, high performance N-body simulation. Comput. Sci.-Res. Dev. 2009, 24, 21–31. [Google Scholar] [CrossRef] [Scilit]
  37. Hamada, T.; Narumi, T.; Yokota, R.; Yasuoka, K.; Nitadori, K.; Taiji, M. 42 TFlops hierarchical N-body simulations on GPUs with applications in both astrophysics and turbulence. In Proceedings of the Conference on High Performance Computing Networking, Storage and Analysis; ACM: New York, NY, USA, 2009; pp. 1–12. [Google Scholar]
  38. Hamada, T.; Nitadori, K. 190 tflops astrophysical n-body simulation on a cluster of gpus. In SC’10: Proceedings of the 2010 ACM/IEEE International Conference for High Performance Computing, Networking, Storage and Analysis; IEEE: Washington, DC, USA, 2010; pp. 1–9. [Google Scholar]
  39. Gaburov, E.; Bédorf, J.; Zwart, S.P. Gravitational tree-code on graphics processing units: Implementation in CUDA. Procedia Comput. Sci. 2010, 1, 1119–1127. [Google Scholar] [CrossRef] [Scilit]
  40. Jetley, P.; Wesolowski, L.; Gioachin, F.; Kalé, L.V.; Quinn, T.R. Scaling hierarchical N-body simulations on GPU clusters. In SC’10: Proceedings of the 2010 ACM/IEEE International Conference for High Performance Computing, Networking, Storage and Analysis; IEEE: Washington, DC, USA, 2010; pp. 1–11. [Google Scholar]
  41. Habib, S.; Morozov, V.; Frontiere, N.; Finkel, H.; Pope, A.; Heitmann, K. HACC: Extreme scaling and performance across diverse architectures. In Proceedings of the International Conference on High Performance Computing, Networking, Storage and Analysis; ACM: New York, NY, USA, 2013; pp. 1–10. [Google Scholar]
  42. Bédorf, J.; Gaburov, E.; Zwart, S.P. A sparse octree gravitational N-body code that runs entirely on the GPU processor. J. Comput. Phys. 2012, 231, 2825–2839. [Google Scholar] [CrossRef] [Scilit]
  43. Bédorf, J.; Gaburov, E.; Fujii, M.S.; Nitadori, K.; Ishiyama, T.; Zwart, S.P. 24.77 Pflops on a gravitational tree-code to simulate the Milky Way Galaxy with 18,600 GPUs. In Proceedings of the SC’14: Proceedings of the International Conference for High Performance Computing, Networking, Storage and Analysis; IEEE: Washington, DC, USA, 2014; pp. 54–65. [Google Scholar]
  44. Nagarajan, V.; Gangaraju, R.; Sundararajah, K.; Pelenitsyn, A.; Kulkarni, M. RT-BarnesHut: Accelerating Barnes-Hut Using Ray-Tracing Hardware. In Proceedings of the 30th ACM SIGPLAN Annual Symposium on Principles and Practice of Parallel Programming; ACM: New York, NY, USA, 2025; pp. 43–56. [Google Scholar]
  45. Keller, S.; Cavelan, A.; Cabezon, R.; Mayer, L.; Ciorba, F. Cornerstone: Octree construction algorithms for scalable particle simulations. In Proceedings of the Platform for Advanced Scientific Computing Conference; ACM: New York, NY, USA, 2023; pp. 1–10. [Google Scholar]
  46. Tokuue, T.; Ishiyama, T. Optimizing the gravitational tree algorithm for many-core processors. Mon. Not. R. Astron. Soc. 2024, 528, 821–832. [Google Scholar] [CrossRef] [Scilit]
  47. Hutter, J.; Szaday, J.; Choi, J.; Liu, S.; Kale, L.; Wallace, S.; Quinn, T. ParaTreeT: A Fast, General Framework for Spatial Tree Traversal. In Proceedings of the 2022 IEEE International Parallel and Distributed Processing Symposium (IPDPS); IEEE: Washington, DC, USA, 2022; pp. 762–772. [Google Scholar]
  48. Tokuue, T.; Ishiyama, T. Performance Evaluation of Parallel Sortings on the Supercomputer Fugaku. J. Inf. Process. 2023, 31, 452–458. [Google Scholar] [CrossRef] [Scilit]
  49. Bode, P.; Ostriker, J.P.; Xu, G. The tree particle-mesh N-body gravity solver. Astrophys. J. Suppl. Ser. 2000, 128, 561–569. [Google Scholar] [CrossRef] [Scilit]
  50. Bagla, J.S. TreePM: A code for cosmological N-body simulations. J. Astrophys. Astron. 2002, 23, 185–196. [Google Scholar] [CrossRef] [Scilit]
  51. Dubinski, J.; Kim, J.; Park, C.; Humble, R. GOTPM: A parallel hybrid particle-mesh treecode. New Astron. 2004, 9, 111–126. [Google Scholar] [CrossRef] [Scilit]
  52. Springel, V.; Pakmor, R.; Zier, O.; Reinecke, M. Simulating cosmic structure formation with the gadget-4 code. Mon. Not. R. Astron. Soc. 2021, 506, 2871–2949. [Google Scholar] [CrossRef] [Scilit]
  53. Zhao, W.L.; Wang, W.; Wang, Q. Optimization of cosmological N-body simulation with FMM-PM on SIMT accelerators. J. Supercomput. 2022, 78, 7186–7205. [Google Scholar] [CrossRef] [Scilit]
  54. Salmon, J.K.; Warren, M.S. Fast Parallel Tree Codes for Gravitational and Fluid Dynamical N-Body Problems. Int. J. High Perform. Comput. Appl. 1994, 8, 129–142. [Google Scholar] [CrossRef] [Scilit]
  55. Singh, J.P.; Holt, C.; Totsuka, T.; Gupta, A.; Hennessy, J.L. Load Balancing and Data locality in Adaptive Hierarchical N-Body Methods: Barnes-Hut, Fast Multipole, and Rasiosity. J. Parallel Distrib. Comput. 1995, 27, 118–141. [Google Scholar] [CrossRef] [Scilit]
  56. Singh, J.P.; Hennessy, J.L.; Gupta, A. Implications of Hierarchical N-Body Methods for Multiprocessor Architectures. ACM Trans. Comput. Syst. 1995, 13, 141–202. [Google Scholar] [CrossRef] [Scilit]
  57. Gabriel, E.; Fagg, G.E.; Bosilca, G.; Angskun, T.; Dongarra, J.J.; Squyres, J.M.; Sahay, V.; Kambadur, P.; Barrett, B.; Lumsdaine, A.; et al. Open MPI: Goals, Concept, and Design of a Next Generation MPI Implementation. In Proceedings of the 11th European PVM/MPI Users’ Group Meeting, Budapest, Hungary, September 2004; Springer: Berlin/Heidelberg, Germany, 2004; pp. 97–104. [Google Scholar]
  58. Aarseth, S.J. Gravitational N-Body Simulations: Tools and Algorithms; Cambridge University Press: Cambridge, UK, 2003. [Google Scholar]
  59. Hubber, D.A.; Batty, C.P.; McLeod, A.; Whitworth, A.P. SEREN—A new SPH code for star and planet formation simulations-Algorithms and tests. Astron. Astrophys. 2011, 529, A27. [Google Scholar] [CrossRef] [Scilit]
  60. Corless, R.M.; Fillion, N. A Graduate Introduction to Numerical Methods; Springer: Berlin/Heidelberg, Germany, 2013. [Google Scholar]
  61. Hut, P.; Makino, J.; McMillan, S. Building a better leapfrog. Astrophys. J. 1995, 443, L93–L96. [Google Scholar] [CrossRef] [Scilit]
  62. Heggie, D.; Mathieu, R. Standardised units and time scales. In The Use of Supercomputers in Stellar Dynamics; Springer: Berlin/Heidelberg, Germany, 1986; pp. 233–235. [Google Scholar]
  63. Greengard, L.; Rokhlin, V. A fast algorithm for particle simulations. J. Comput. Phys. 1987, 73, 325–348. [Google Scholar] [CrossRef] [Scilit]
  64. Hernquist, L. Hierarchical N-body methods. Comput. Phys. Commun. 1988, 48, 107–115. [Google Scholar] [CrossRef] [Scilit]
  65. Gargantini, I. An Effective Way to Represent Quadtrees. Commun. ACM 1982, 25, 905–910. [Google Scholar] [CrossRef] [Scilit]
  66. McCool, M.; Reinders, J.; Robison, A. Structured Parallel Programming: Patterns for Efficient Computation; Elsevier: Amsterdam, The Netherlands, 2012. [Google Scholar]
  67. Cormen, T.H.; Leiserson, C.E.; Rivest, R.L.; Stein, C. Introduction to Algorithms, 3rd ed.; MIT Press: Cambridge, MA, USA, 2009. [Google Scholar]
  68. Solomonik, E.; Kalé, L.V. Highly scalable parallel sorting. In Proceedings of the 24th IEEE International Symposium on Parallel and Distributed Processing, IPDPS 2010, Atlanta, Georgia, USA, 19–23 April 2010—Conference Proceedings; IEEE: Washington, DC, USA, 2010; pp. 1–12. [Google Scholar] [CrossRef] [Scilit]
  69. Sedgewick, R.; Wayne, K. Algorithms, 4th ed.; Addison-Wesley: Reading, MA, USA, 2011. [Google Scholar]
  70. Hut, P.; Makino, J. The Art of Computational Science; Piet Hut & Jun Makino: Princeton, NJ, USA, 2007; Volume 11. [Google Scholar]
  71. Träff, J.L.; Gropp, W.D.; Thakur, R. Self-Consistent MPI Performance Guidelines. IEEE Trans. Parallel Distrib. Syst. 2010, 21, 698–709. [Google Scholar] [CrossRef] [Scilit]
  72. Liu, X.; Liu, Y.; Yang, H.; Liao, J.; Li, M.; Luan, Z.; Qian, D. Toward accelerated stencil computation by adapting tensor core unit on gpu. In Proceedings of the 36th ACM International Conference on Supercomputing; ACM: New York, NY, USA, 2022; pp. 1–12. [Google Scholar]
Disclaimer/Publisher’s Note: The statements, opinions and data contained in all publications are solely those of the individual author(s) and contributor(s) and not of MDPI and/or the editor(s). MDPI and/or the editor(s) disclaim responsibility for any injury to people or property resulting from any ideas, methods, instructions or products referred to in the content.

Article Metrics

Citations

Article Access Statistics

Multiple requests from the same IP address are counted as one view.