N-body gravity simulation in O(N)
Comments
Transcript
Machine-transcribed by YouTube. Expect errors in names, commands and version numbers.
[music] >> Right now, you're watching an N-body simulation being run in real time. Hundreds of thousands of particles are mutually exerting gravitational forces on each other, and it's really quite mesmerizing to watch.
If you follow programming content on YouTube, chances are you've seen similar simulations before. And for some nice reason, these videos are pretty popular. However, all these explainers implement one of two algorithms. The first is the naive method, which uses sheer brute force to calculate all pairwise forces, which becomes impractically slow as soon as we try a respectable number of particles. With N particles, the complexity is O of N squared, meaning the number of operations grows approximately with N times N. The second is the more sophisticated Barnes-Hut algorithm, which divides the particles into the structure called a quadtree. This allows us to approximate the forces on each body. So, if we have a faraway cluster of particles, the algorithm treats them as one big particle placed at their collective center of mass, leading to a complexity of O N log N.
I was originally planning to implement this Barnes-Hut algorithm, but some quick research told me it seemed quite easy to implement, and that wouldn't be cool enough to try out, much less make a whole video on. Moreover, the error of this algorithm is difficult to bound, meaning it was a poor choice if I wanted realism. It was then that a link caught my eye.
The fast multiple method. Fast as the name. Invented by Leslie Greengard and Vladimir Rokhlin in 1987, it solves the N-body problem in O of N, even better time complexity than Barnes-Hut, a mathematically bounded approximation error, named as one of the top 10 algorithms of the 20th century, and no explanation of it whatsoever besides some lectures, which of course don't go into detail about the math or the code. It looked absolutely perfect to try and understand and implement, so let's do it. First off, let's look at the general strategy of these N-body algorithms. Suppose we have two point sources at positions xi, xj with masses mi, mj. In two dimensions, gravity acts differently than 3D. The magnitude of the gravitational force between them is proportional to the product of their masses divided by the distance between them without the square. So, to get the actual force vector, say from j to i, we multiply this by the normalized displacement vector from i to j. That means we have to use this expression to calculate the force, which isn't the prettiest, not going to lie. Instead, something simpler comes in the form of gravitational potential. It's a simple scalar function representing the potential energy field, so each point in space just gets associated with some numerical value.
If we take the derivative of this function, then that conveniently gives us the force vector.
But how does this work in 2D? It still seems somewhat complicated to calculate distances, but magically, as is the case so often, complex numbers make our life easier. Observe the potential function in 2D. It's related to the logarithm of the distance between our two sources, and the complex logarithm has a very unique property. If we consider their positions in 2D not as vectors, but as complex numbers, and write the displacement between our sources in polar form, then since we have a product inside the logarithm, we can split it up into a sum and cancel on the right term. Would you look at that? The real part of the complex number is precisely the log of the magnitude of our complex input.
But that still doesn't answer the question of figuring out our forces. Sure, we could approximate the slope by choosing some nearby points and drawing a line through them, but there's no guarantee of accuracy in that. Instead, I learned about this property of complex functions that let us find it directly, the Cauchy-Riemann equations. Let's imagine any complex function f that is complex differentiable. Well, what does that even mean? We learned that for a real function to be differentiable at some point, if we approach the derivative from the left and the right, then they must approach the same value. For a complex function, then there are an infinite number of ways you could approach the target point, and all of these will have to approach the same value. So, in the limit definition of the derivative, instead of some real number h, we have some complex delta z approaching zero.
Let's consider our complex function as a sum of a real part u and an imaginary part v. So, u and v are both real-valued functions. If we approach our target on the real axis, then delta z is real, so let's write it as delta x. And this gives us the derivative in terms of partial derivatives with respect to x.
If instead we approach from the imaginary axis, then delta z is complex, so we can write it as i delta y. This gives us the derivative in terms of partial derivatives with respect to y. Now, let's equate the real and imaginary parts, since these are supposed to be the same. This gives the Cauchy-Riemann equations.
The force is the opposite of the gradient of our potential, which is the real part of our function phi.
We saw the complex derivative can be written as partial of u with respect to x plus i times partial of v with respect to x. But observe, by the equations we just worked out, we can make this become partial of u with respect to x minus i times partial of u with respect to y. Thus, if we want the force as a complex number, we only have to negate the real component. By using this property of the complex logarithm, we've arrived at an extremely simple potential function, which can also be used to calculate forces in a simplified way. That's the first piece of the algorithm.
So, how does the fast multiple method, which I'll now refer to as FMM, get its speed up? Well, it's similar to what the O and log N Barnes-Hut does, just even better. So, it's honestly helpful to look at Barnes-Hut for a second.
Both FMM and Barnes-Hut are known as hierarchical methods because, well, they place the particles into a hierarchical data structure. In two dimensions, this structure is called a quadtree. Each node of the tree contains a square box of particles, and at each level, we can subdivide a node into four smaller boxes and distribute the particles into them. This is useful because it allows us to define clusters of particles. After creating a quadtree, just look at all the ones contained by node. Moreover, we can easily get a sense of distance between clusters. Why is this important? Well, in general terms, like I've mentioned, the reason for these speedups over the naive method relies on sorting particles into two different types, those that are closer in the near field, so to speak, and those that are distant in the far field.
These far-away particles can be approximated as clusters, so we can take care of many sources at once. Barnes-Hut does this in the most simple way, simply by treating a cluster as a particle with mass equal to the total mass of all the particles in the cluster positioned at the center of mass of said cluster. So, what's the criteria that allows us to treat an entire node as a cluster? Once again, what Barnes-Hut uses is intuitive if we think about it. The further away a node is from our particle, the better suited it should be as an approximation. However, a node of the quadtree is defined by two things, a position and a size.
The larger a node's box is, the less suited it will be for getting approximated. So, we can say that as long as the ratio of a node's size to its distance from a target particle is less than some threshold theta, we are allowed to use the center of mass approximation. And that's basically it. At this point, we already have many of the key ingredients of FMM. But, of course, FMM is better than Barnes-Hut in many ways, so let's look at what Barnes-Hut doesn't do quite as well. And this can give us some ideas on how to improve on it. Clearly, Barnes-Hut provides a significant speed up due to saving so many particle-to-particle interactions, but in the end, it computes the influence of faraway clusters with individual particles.
So, if we could figure out how to interact entire clusters with other clusters, then that would be a lot faster.
Also, the center of mass approximation isn't the most accurate. This is where the next key concept comes in, the multipole in fast multipole method.
Let's suppose we have some particles in a cluster with its center of mass being the origin for simplicity's sake. Barnes-Hut simply approximates this as a big particle in the center, but the problem is it doesn't capture the shape of the cluster. What if the cluster is stretched in one direction or multiple directions? Even if the difference doesn't look too big, that adds up, especially when super uneven clusters appear. To find out how the approximation can be refined, let's write down the potential function for our target point Z caused by a single source at ZI with mass MI. Barnes-Hut collected all these individual potentials into one function in terms of the distance from the evaluation point to the origin. So, let's do that with this function. We want simply log of Z instead of Z minus ZI. So, let's factor out the Z and use our log rules to separate out what we want.
What next? Well, we don't want any more logs with Z in them. That's the whole point of what we just did. So, if you've taken calculus, you may think, "What better way to eliminate it than a Taylor series?" Conveniently, we have a nice Taylor series for log of one minus something. Since we used a Taylor series, we should think about its radius of convergence. From the ratio test, we see that the magnitude of ZI over Z has to be less than one, or more simply, that the magnitude of Z has to be greater than the magnitude of ZI. That means that for this series to converge, we have to evaluate it outside the circle going through our source point.
What we can do now is find our overall potential function from this cluster by adding up the individual functions for each of, say, the N sources in the cluster and grouping by powers of Z.
Congratulations. What we have now looks complicated, but is actually extremely simple to evaluate. Look at the inner sums. Z doesn't appear at all, so we can calculate them beforehand as coefficients. Let's call these AK. Then all we have to do is find negative powers of Z for any Z that we want to plug in. This type of series is known in math as a Laurent series, but this algorithm calls it the multipole expansion. In physics, the word multipole comes from electromagnetism. A monopole is just a point charge, a dipole is a positive and negative charge, and so on. Anyways, this is transferred over to our masses here. Observe each term independently.
If we plot the real part of 1 over Z, which is the potential created by the first term of our multipole expansion, we get two lobes. That's a dipole. If we have a 1 over Z squared, then that's a quadrupole. If we have 1 over Z cubed, that's an octupole, and so on. Our multipole expansion on the left is created by these combinations of lobes, which are all rotated and scaled by the coefficients depending on the exact positions of our series in the cluster, added to the initial Barnes-Hut approximation to better fit the distribution of sources. We can't evaluate infinite terms at once, though, so we're going to have to truncate the series to finite number of terms, say, P.
That means that when we're getting too close to the circle, it'll have some noticeable error, but in general, Taylor series are very good at making approximations. Now, since we added up the series for all the individual source particles, this series converges exactly outside the radius of the cluster. And if you look at the expansion on the left, you can see a whole bunch of these lobe shapes within our cluster where it doesn't converge, caused by our multiple terms. I have to mention a caveat of difference between FMM and Barnes-Hut now, which is that FMM doesn't consider the cluster center of mass to be its center, but the center of the node which contains the cluster.
This is because these multiple expansions actually have a radius of convergence which we have to steer clear of. If we have a cluster with a center of mass near one corner of a box, but a lone particle hanging around the opposite corner, then that creates an absolutely massive radius of convergence. Instead, by shifting the center to the center of the box, we allow the multiple expansion to converge at a smaller distance dependent on a predictable factor which is the size of the box, making it much more useful if we want to use the expansion. Outside the radius of convergence, we can find a rough bound for the error of our multiple expansion. This is going to be caused by all the terms we cut off, so from P plus one to infinity.
To make this bound look somewhat cleaner, we can do two things. First, if we let R be the radius of the cluster, which is also our radius of convergence, then the magnitude of ZI is always going to be less than or equal to R, so we can replace the positions of individual source points with R. Also, this division by K is preventing us from collecting terms together. So, let's just replace it with P plus one. This will increase the bound, but as we'll see, it's not the most important part of it anyways. Now look, we have R over Z, which is almost the same as the criteria for the far field approximation we used in Barnes-Hut.
Also, since the rightmost term doesn't depend on I anymore, we can pull out the sum of the masses, which conveniently was a zero. We're left with a geometric series, which there's a formula for. We see that the error is exponential in terms of the ratio of the cluster radius R to wherever we're evaluating the potential from, which is very good. The further we are from the cluster, the faster the error bound drops, and the better the approximation becomes. And you can see how with P equals 10, the error is already barely visible.
So, in summary, we just developed an expansion centered on a cluster of sources, which approximates the effect of that source cluster on distant targets. This multipole expansion improves our potential approximation immensely, but it doesn't help with getting any actual speed up compared to Barnes-Hut. To achieve an actual speed up instead of a mere accuracy boost, takes a real shift in perspective, literally. So, it's time to see where the math of FMM really shines. What we'd really like to do now is not have to run through the multipole expansion separately, like Barnes-Hut. That's where most of our time is going. It's actually similar to the situation we faced when deriving the multipole expansion, where we wanted everything in terms of only the center of the source cluster.
Think of the multipole expansions as broadcasting these potential functions. Wouldn't it be neat to construct some sort of receiver so we could write these multipole expansions in terms of the target boxes center, and collect them all into one series centered around the target box? If so, we would only need a single run through the target sources against that one series, instead of who knows how many. This is the second key expansion, the local expansion. Unlike the multipole expansion, it's centered around a cluster of targets, and describes the effect of these targets from far away sources. Let's figure out how it should look. Once again, we have a cluster of sources ZI, but this time they're not centered around the origin. We are. Notice how we have the exact same starting function as before when we created the multipole expansion. However, we want to do something different with it, and this is an important detail that we can cleverly use. Before, we wanted our approximation to converge away from the origin. So, we factored out the Z inside the log. Since the magnitude of Z was going to be larger than the magnitude of ZI, when we factored out the Z, we got the fraction ZI over Z, which was small enough that the series would converge outside the source cluster.
Now, we want our approximation to converge within a circle centered around the target box. That means that the magnitude of the source point ZI is going to be relatively large. So, we can factor it out as the bigger number and use the Taylor series of log 1 - X once again. The specific radius of convergence here is going to be equal to the magnitude of the closest source point. If we're within the circle, then magnitude of Z is going to be less than the magnitude of all source points, so Z over ZI is going to have magnitude less than 1 and the series converges. Just like before, we can transform it into a polynomial in terms of Z by grouping the Z to the power of K terms together.
And there, that's our local Taylor expansion. Notice how similar it looks to the multiple expansion. The only two differences are that Z and ZI are swapped and the first terms look slightly different. But then again, these are both representations of the same thing, so we shouldn't be expecting too much of a difference. And if we look at the heat maps of the local expansions, on you can see how inside it's a near perfect match, while outside the radius of convergence you get all this alternating polynomial business. Like before, we can't just calculate an infinite number of coefficients, so we need to truncate the series and figure out an error bound in the terms we've lost.
Similarly, with the multiple expansion's error, we can replace the K's with P + 1's as an upper bound and set R to be the radius of convergence, which is the minimum magnitude of a source point. And once again, we see that the error bound decreases exponentially in the number of terms of our local expansion. And of course, also decreases the closer we are to the center of the expansion, just like how the multiple expansion error decreased the further we are from its center. Nice. Moving on. The whole point of creating this local expansion was to be something that the multiple expansions could be transformed into. So, let's now work out that operation, but quickly because the algebra is quite unpleasant.
Suppose we have a multiple expansion centered at Z0. We see that our convergence in this region outside the disk. By transforming it into a Taylor expansion centered around the origin, it'll only converge inside the circular region. Now, let's take our multipole expansion and see how we can flip this from a function in terms of Z minus Z0 to just a polynomial in Z. Remember the rule we saw when creating the local expansion. Depending on how we want the result to converge, we must factor out the bigger number in the log. In this case, our cluster center will be further from the origin than our reevaluation point. So, Z0 it is.
Once again, we use a Taylor series for the log to make it polynomial in terms of Z. On the right, to get rid of the negative exponent, we can use the extended binomial theorem. This is quite the mess, but we know what we're looking for, a polynomial in Z. So, let's do some rearranging.
That looks pretty nasty, but at least we figured it out. What makes this even nastier is that knowing the first P terms of the multipole expansion isn't enough to find the first P terms of this flipped local expansion. So, we in fact incur some extra error. Due to how complicated this operation is, the new error is quite complicated to derive, and I really don't want to break the flow of this video with some massive calculation that really isn't that important. You can follow it from the original FMM paper, but all you need to know for now that it is once again exponentially decreasing the closer we are to the origin.
After all that heavy math, let's take a moment to see how far we've come and also consider what to do next from the limitations of our current progress. We can create multipole expansions of each cluster that approximate the cluster's potential function outside the cluster much more accurately than Barnes-Hut. And we can also create local Taylor expansions of the potential functions of a faraway cluster centered around another cluster. We can also use the flip operation we just created to convert multipole expansions into local expansions, meaning we can add up all of them and to represent the effect of multiple faraway clusters using one single local expansion.
So, let's try this out on our quadtree here looking at this target cluster. There are a load of other clusters that we can consider far away enough such that the error is small. So, we generate multiple expansions for all of them and then flip each of them one by one to our target cell to find the aggregate effect. Seems good. Next, let's look at another target cluster next to the first one. Would you look at that? The list of faraway clusters barely changed. We have to flip all the expansions over to this new target cluster again. If we take a look at yet another target cluster, the same thing happens.
So, basically what we've done is we recreated the basic issue of having to calculate the forces between all pairs of particles, except we've made that number a bit smaller by doing it between all pairs of boxes. We need two things to fix this. >> [music] >> First is to reduce the number of multiple expansions we need to flip from and eliminate all that repetition. This could be done by grouping larger boxes into one cluster. However, if we want to create the multiple expansions at each level from the individual particles, that's going to tank our performance once again because we have to loop over all the particles multiple times.
So, is there a way we only have to construct the lowest level multiple expansions and use them to create larger expansions? Let's find out. The goal is to shift the centers of four adjacent multiple expansions to the center of the box on the next highest level so we can add up their coefficients. Let's set our target center to be the origin once again and have the original multiple centered at Z0. We've seen already that we need to be careful when changing our conditions for convergence and always factor out the bigger magnitude number inside our lock. In this case, since our new expansion contains a larger cluster, we have to evaluate it at a position further from the origin than the old cluster. So, Z is going to be our bigger number.
Once again, we can turn this negative exponent into an extra series.
Now, we want to rearrange this mess back into a multiple series. So, we sort everything by powers of Z. It's reassuring to see that our monopole here, the log, has the same coefficient, which makes sense as the overall effect of our cluster at a faraway distance should stay virtually the same, no matter where we take the center. The actual series part is more complex since there are nested sums that both affect the exponents of Z. So, let's set up a new variable R to be L + K, and then we can express L in terms of R and K.
And there we have it, a multipole shift operation. What's especially nice that didn't happen with a flip operation before is that if we truncated the original expansion to P terms, then if we want to shift it and create a new expansion with P terms, then all we need are the original P + 1 coefficients. This shift doesn't worsen the error bound, and we can do it as many times as we need without fear. So, that's pretty nice, and it's one side of our optimization story. The other half, if we think back to earlier, is of course to also have bigger target boxes to flip to instead of having each multipole expansion flip to every single little target box. So, now we can wonder, if we flip a multipole expansion to a large target box, is there a way to trickle the effects down to its smaller child boxes so in the end we can still accumulate all the faraway influences into one single series?
The answer, like always, is that the math finds a way. Let's write out a local expansion that we want to shrink and shift to the origin. Since we want Z on its own, expanding the binomial is the way to go.
We really saved the easiest operation for last. Just like multipole shift, the local shift doesn't introduce any extra error that we already had from the truncation, so we can apply it however many times we'd like. It seems like we've now built a very complete set of tools. First, we construct multiple expansions of each child box. Second, we shift these multiple expansions up the quadtree so that each larger box contains its own multiple expansion. Third, whenever two boxes are sufficiently well separated, we flip the source box's multiple expansion onto the target box's local expansion. Lastly, we shift all local expansions back down to the child boxes, so each box contains all of the local expansions collected by its parent.
What we'd really like to do now is not have to run through the multiple expansion separately, like Barnes-Hut. That's where most of our time is going. It's actually similar to the situation we faced when deriving the multiple expansion, where we wanted everything in terms of
Let's first consider a simplified algorithm which assumes our particles are more or less uniformly distributed, which allows us to use a quadtree that just looks extremely regular. Notice how the number of boxes is linear in terms of n. For example, if we have 250 particles and fix a constant of at most 10 particles per box, then we have no more than 25 boxes at the second lowest level, so no more than 100 boxes at the lowest level. As we've already established, we can start off looping across all the boxes to create the lowest level multiple expansions. Since this just takes one pass over all the particles, this is O(n).
Next, we're going to set up the multiple expansions on all higher levels by combining them in an upward pass. Since the number of boxes is proportional to n, this is also O(n). Now, we can start our downward pass. What's really cool is that the error bound in our local expansion doesn't purely depend on the radius of our cluster, but the ratio of the distance of our evaluation point to the cluster. Hence, we should start flipping at the highest level possible to maximize efficiency. So, let's see. Level zero is our whole simulation, so there's nothing to flip from. At level one, all our boxes are touching and the flip error is going to explode, so that's a no-go as well.
At level two, we begin to see our first well-separated boxes. Let's look at this box. Its neighbors aren't well-separated, but the rest are, so we can flip them over and not worry about anything on those boxes anymore. Next, let's go down a level distributing the first local expansion. We can see that it's the exact same situation as before. In our remaining grid, we have only 36 little boxes and for each little box in the center, we subtract itself and its eight neighbors, giving 27 other boxes on the same level which are well-separated. This number is even smaller if the target box were close to a natural corner. So, since we have an interaction bound that is independent of n, this is once again only dependent on the number of boxes we have, which is O of n.
After this downwards pass of flipping and shifting local expansions, we reach the finest level. For each box, the only remaining boxes we haven't considered are itself and its up to eight adjacent neighbors on the same level. Since the particles there are too close to us to create a local approximation, we can calculate the forces directly since there's not a lot of them anyway. To get the force generated by the local expansion, we can write out the expression for the derivative instead of the potential. Finally, we can add that to the forces generated by the near neighbors and obtain all the final forces. It's done.
But of course, this was under the assumption that the particles were evenly distributed. Otherwise, if we just apply an even grid, the final step of calculating near neighbors might take super long, breaking the O of n complexity. So, after publishing their original paper, Greengard and Rokhlin teamed up with Carrier to come up with the adaptive FMM next year to truly make the algorithm O of n across all distributions. The tree creation and upwards pass remain basically identical. [music] We choose a limit for the number of particles per box, then generate the quadtree with that number. >> [music] >> Then we calculate multipole expansions for all leaf nodes, which have no smaller boxes within them, and then shift all of them up.
The downwards pass is where we need to consider things more carefully, since it's impossible to go down layer by layer anymore. There are two specific problems that can happen which are to do with the mismatch in box sizes. One possibility is that we could have [music] a tiny source box next to a giant target box. If this happens, it might be impossible to create a local expansion for the box if the region where it converges overlaps with the region where our local expansion needs to converge. Instead, [music] we're forced to run the multipole expansion of the tiny source box over each target particle individually. The second possibility is the exact opposite of the first. We could have a giant source box next to a tiny target box. If this happens, it may be impossible to use the multipole expansion if it diverges within the radius of our target box. So, we can skip it entirely. Opposite to the first case again, we can create a local expansion for the target box from the individual source particles, [music] which we worked out how to do quite a while back.
This gives us two extra types of source boxes that each target box has to consider, giving a total of five, which the original paper calls lists U, [music] V, W, X, and Y, which we can give some more formal definitions than what we just discussed. For brevity, let's just call a target box B. If B has no children, list U contains all adjacent boxes plus itself. It's used when we're at the bottom of our downward pass and need to calculate forces directly with the adjacent cells. List V is also the same as from the downward pass of the balanced algorithm. If we look at all boxes adjacent to B's parent, which are on the same level, then go back to the children, then list V contains all of those children that are separated from B.
These are the boxes from which we flip multiple expansions. Lists W and X are duals of each other and are the two new lists created to deal with the size mismatch. List W contains all boxes smaller than B which don't touch B that are descendants of B's same level neighbors, which we have [music] to deal with by individually evaluating the multiple expansion for. List X is the opposite. So, if some box is in B's list W, then B is in that box's list X and we have to create its local expansion from individual particles. Last but not least, list Y contains all of the other boxes. We really don't care about it since they're all so far away that they've already been processed at some higher level of the tree.
Once again, it's possible to bound the number of boxes in each list to a constant, regardless of how messy our tree looks, and therefore our time complexity will continue to be linear. And this can complete our full FMM algorithm. I'll be going into more detail about my specific implementation in a future video, since writing this entire algorithm out is difficult in itself, not to mention how it can be optimized. But for now, let's look back at what we've done and appreciate its beauty.





