N-body problem and the Barnes-Hut algorithm: visualizing the quadtree spatial partitioning that cuts complexity from O(N²) to O(N logN) through hierarchical force approximation
I am thinking of making a video series on an Introduction to Physics and Math Animation with Blender.
The plan is to do everything through Python Scripting.
Maybe 4 to 5h of content: cover the basics, optimal set up, defining typical functions for math/physics stuff, making
This is the first ever periodic solution found for the Three-Body Problem.
It was discovered by Leonard Euler in 1767 after imposing the condition of collinearity: the three bodies must remain at all times in a straight line.
This is a movie from 1960 of the first ever computer-made N-body simulation of a galaxy
The galaxy was modeled with only N=116 bodies, they used RK4 for integration, and the whole thing took 15 hours of computing time.
Bach's Cancrizans Spectrogram in Python 🔊
A time-symmetric piece of music where the left hand (blue) is the right hand (red) played in reverse. The melody is identical when played backwards.
N-body simulation made with Python, parallelized with numba, and animated with matplotlib.
N=100.000. Computation time around 5h for 2.000 steps. Around 1s of compute time per step. Collisions are handled with a softening length.
Code will be on my github, eventually
An spectrogram is a good pictorical representation of the harmony of a song.
This is one I made with python-matplotlib for 'Besalú' (a song from my brother). It makes a good present when printed on an aluminium plate.
Simulated with Python. Animated with Blender.
The mass ratio between planets is 3 to 1 (blue is more massive) and the pass by occurs during the close encounter of a highly eccentric elliptic orbit.
Each planet has a ring system of about 20.000 particles which are set to have
A Toy Model of the Milky Way
Orbital simulation of ~10.000 Milky Way stars using data from
@ESAGaia
.
Red, blue and dim purple stars correspond roughly to the bulge, disk and halo. Integration of the orbits with gala python package (
@adrianprw
). Animated with
@matplotlib
.
These two solutions, Euler's and Lagrange's, remain the only two solutions of the three-body problem for which an analytical solution is known.
Currently thousands of other solutions have been found, like this one from R. Brooke, but numerical methods are required to find them.
@PabloIglesias
Puede alguien dar una definición de fascismo aplicable en este contexto? Que no sea 'todo aquello que no se alinea con mis ideas' si puede ser.
And this is the second, by Joseph-Luis Lagrange (1772). He found it after imposing the condition that all three bodies must remain at he vertices of an equilateral triangle at all times.
@Rainmaker1973
Well Wikipedia makes you make a request for username change. I guess that proves it. It should appear under my current twitter handle in Wikipedia after the request is satisfied.
Slowly building an astro-ray tracer.
Here is a K-type star (a bit colder than the Sun) with procedurally generated star-spots and showing the limb-darkening effect.
Python only.
Genuine question: Why isn't there a dedicated platform to share, rate, and discuss introductory notes on STEM subjects? (Long post)
What I am reffering to is like a digital ecosystem where students, self-learners, teachers, etc. can freely share and discuss their notes with
Here N=50.000. I relied on numba for parallelization. With 12 cores It took ~1h to integrate 1000 time-steps. No tree algorithm used yet, so complexity is O(N²). I see myself migrating to C++ in the long term for this stuff.
N=20,000 in the simulation above (2D).
The Barnes-Hut algorithm (1986) reduces complexity by approximating distant particle effects as single mass points by means of the quadtree spatial division.
The darker side of the algorithm is that the force computation becomes
In about 4 billion years, the Sun will reach the peak of its Red Giant phase, expanding to ~250 times its current radius and engulfing the inner planets in the process.
Each particle is roughly representative of a small galaxy, with a mass of 5.1 billion solar masses.
This is example simulation DM-L50-N128 from Gadget-4. Animated with Blender.
10 billion years for a Sun-like star.
Everything stable till Hydrogen runs out in the core.
Then the Helium core contracts and heats up. Radius and luminosity increase exponentially.
The star turns into a Red Giant.
Gravitationally collapse yourself or whatever you want. When time-reversed (like above) it makes for good logos. It can also be used for non silly purposes.
Examples with different softening lengths and circular velocities.
Animation made with matplotlib, blender, and a bit of manim. Also, kind of my first fluid dynamics simulation.
The simulation is of an inviscid perfect gas. The initial conditions are those of a Gresho vortex [1], which is a useful test case to check numerical schemes. Ideally,
@RBehiel
@memecrashes
I had my 'aha' moment with this when I saw somewhere that this identity for the generator of rotations in 2D, J, is identical to Euler's identity for i.
The idea is to only post my simulations in this account, but I felt this was cool and niche enough to be shared.
I say 'computer-made' because, amazingly enough, the first one was actually performed mechanically with light bulbs as bodies to use their radiation flux as a proxy
Mixed and interpreted on guitar by my brother (Sebastià Gris on spotify).
The left hand is played an octave lower, so the spectrograms don't exactly overlap.
Made with python and matplotlib. Check the code at:
For those wondering where the pattern comes from, each frame is generated by color-coding which body is hit when releasing test particles at rest in a grid. It’s basically a 2D map of which ‘planet’ would an ‘asteroid’ hit if released from (X, Y).
*Technically, it's blueshift when photons are moving towards the Black Hole and redshift when they're heading away from it.
First time doing numerical GR so I just hope I didn't mess it up.
Made with python (numpy and matplotlib)
Finally: made with Python and animated with Blender.
Code will be published as a response to this post whenever I clean the original mess that got it working.
The study of fractal basin boundaries, [pioneered by James A. Yorke], is the study of systems that could reach one of several nonchaotic final states, raising the question of how to predict which (Chaos, James Cleick).
Inspired by:
This one was a bit of a challenge. To generate the image on must first integrate three coupled differential equations *for each pixel* to get the goedesics of the photons. This is very computationally expensive.
The approach is just like in this previous simulation.
@DerickZill
@Rainmaker1973
Three bodies interacting gravitationally usually leads to chaos and unpredictability. However for very precise initial conditions and mass ratios, researchers have found special periodic solutions. Most of these are unstable, meaning that little perturbations mess up the order.
Regarding the specifics of the code:
Code is pure python. numba is used for parallelization. Animations with matplotlib. Data storage as .hdf5 files.
The N-body simulator is brute-force and straightforward, with O(N²) force computations per time step. It is not too bad. In my
The other tricky thing I did not know was going to be a challenge was redshifting RGB colors.
After many blunders what I did was to assume each pixel is like a LED display, with three lightbulbs (red, green and blue) shinning at different intensities to get all the colors. Then
At high z, the expansion of the universe was much faster. This, explains why the original sphere does not collapse like the one we simulated a few days ago. Dark energy prevents it! And filaments and galaxy clusters can form.
The galaxy is modeled with 50k baryonic matter particles following a 5 kpc exponential disk distribution with a total mass of 5e10 M☉.
The dark matter halo is not implemented as particles but as a continuous spherical density field following a Navarro-Frenk-White profile, with
@nik_greenwall
The gravitational potential defines the dynamical evolution of the system, setting the force felt by each particle, which only depends on their position. Time evolution is found by integrating Newton's second law, which here takes the following form:
Little repository for doing this animation. It's a fragment of code I've quickly split from an ongoing N-body package I am trying to build, so it may not be very readable.
@pawjast
@AddySmith4
The only force at play is newtonian gravity, which we modify by adding a softening length, ε.
This way we avoid numerical instabilities due to divergent forces when two particles get to close together.
Figure: Newtonian force in solid-black, modified force in dashed-black.
This is a demo: a first approach. It was made from scratch, and I guess there are tools to get it done faster and better out there.
However, I will probably refine it and have a bit more fun with it. I feel this may be even worth an in depth youtube video.
Also, it would be
Finally, the confinement methods used in actual fusion reactors are obviously way more complex.
A Tokamak configuration, a most popular choice, confines plasma (ionized particles) in a toroidal ring.
But the fundamental principle remains the same: that of a magnetic mirror.
Simulated with Python. Animated with Blender. Code repository at:
And I would like to credit this little jupyter notebook, which really helped for the initial set up:
Here is how they come up:
- Each vertex has a mass and a color
- Circumscribe a sphere and place there test particles
- Let the particles orbit the vertices
- Color-code original position with the color of the vertex they hit
An animated explanation here: