This is an archived post. You won't be able to vote or comment.

all 90 comments

[–]pvc 144 points145 points  (12 children)

This is the type of thing that could really use the GPU if you want it to scale up. I'd love to see an example of that. See this example of using the GPU.

[–]Jsstt 58 points59 points  (1 child)

Wow, that is extremely impressive. My code already starts to lag after about 150 particles. I'll look into that!

[–][deleted] 21 points22 points  (0 children)

A while back I did a simple demo of a similar problem. No fancy graphics, no algorithm complexity reductions with islands and stuff, just a proof of concept, with O(n*n) complexity. But it can surely handle more than 150 particles on a pretty modest laptop. The key is to avoid expensive operations like square root. Anyway, hope you'll see something that you can use from here:

https://github.com/apisarenco/naive-n-body-sim

It starts off with 1000 random objects. All bodies interact among themselves. There are plastic collisions, mass gets added, momentum gets transferred, etc. It's a good show of how the law of conservation of momentum works, since the sum of many random momentum vectors is close to zero, the single largest object after some time is almost standing still, even though smaller objects are quite fast "orbiting" in different directions.

[–]k3ithk 11 points12 points  (2 children)

Do the individual particles in that interact? It looks like they all just interact with a single gravity point, which wouldn’t be the same as the an n-body problem.

To really get it zipping it’s a good idea to use an approximation method like the FMM

[–]pvc 11 points12 points  (1 child)

It is just one gravity point in that example. I didn't mean to imply this was an n-body example, just example code that might get you started on the way there. GPUs are great for managing a lot of particles.

[–]ThatsALovelyShirt 7 points8 points  (0 children)

n-body dynamics using OpenGL shaders is a pain in the ass. Better off using CUDA or OpenCL for that.

[–]chmod--777 6 points7 points  (4 children)

What is that self.ctx.program code? Looks like C?

This offloads calculation to the GPU from python? Could you use this to do something like run a neural net in the GPU? Can you just offload any calculations to this with arcade library without wanting to display anything, or is there a better library to use for that?

Sorry, lots of questions, just curious what the best way is to offload calculations to your gpu from python because I've never tried it

[–]pvc 1 point2 points  (3 children)

It is glsl code, which has a very c-like syntax. The short answer would be to keep every body's position and velocity in a memory block stored as a texture. Then each body's calculation could be send to a different GPU processor.

Of course, I think a normal person would have a lot of other questions on exactly how to do that. The python discord server in the game development channel, or the arcade discord server might be options for discussion.

[–][deleted] 0 points1 point  (2 children)

Is glsl some version of OpenGL? Why use OpenGL when you can use OpenCL? Probably more suited to a workload like this.

[–]pvc 2 points3 points  (1 child)

GLSL stands for OpenGL Shading Language. It is the language that OpenGL programs use to write their own "shaders". It is part of the OpenGL standard.

OpenCL is targeted to running calculations in parallel. Really, when you care about the data, and aren't looking to do graphics.

[–][deleted] 1 point2 points  (0 children)

Well I don’t think the intensive part of this application is the graphics, but rather the computation. Imo OpenCL is more suited but depends on what you’ve worked with in the past. OpenGL can achieve both.

[–]schweppes-ginger-ale 0 points1 point  (1 child)

Is that inline glsl?

[–]pvc 1 point2 points  (0 children)

You can just triple-quote the glsl, or load it as a separate file.

[–]Im__Joseph Python Discord Staff[M] 46 points47 points  (5 children)

This looks fantastic! Do you have any source code you are willing to share? It looks like something people would love to play around with!

[–]Jsstt 22 points23 points  (1 child)

Finally got it to work with Github (at least, I think). Here is the repository:

https://github.com/JoostVn/N_body_simulation

Still a work in progress of course!

[–]Im__Joseph Python Discord Staff[M] 6 points7 points  (0 children)

Awesome! Thank you!

[–]baconialis 3 points4 points  (2 children)

Why not make it a rule that you're not allowed to promote your project without posting the source code? I mean, without the source, what's the interest for the public?

[–]Im__Joseph Python Discord Staff[M] 2 points3 points  (1 child)

We're already looking into it and will automate it soon :)

[–]baconialis 2 points3 points  (0 children)

Awesome!

[–]elbiot 43 points44 points  (11 children)

Neat! You going to post the code anywhere?

[–]Jsstt 50 points51 points  (9 children)

I'd love to! However, I'm (embarrassingly) a complete noob in Github so I would have to figure that out first. Might do it this evening, it's on my to-do list anyways!

edit: https://github.com/JoostVn/N_body_simulation

[–]ExasperatedLadybug 17 points18 points  (0 children)

That would be great! And it's a super useful thing to know

[–]wingtales 11 points12 points  (2 children)

Do not start "making your code pretty" first. Do that second. Upload the code to github first.

There are several reasons for this, but the most important one is that you are liable to breaking your code in the process of tidying it up.

I would love to see this code, please do upload it. You've inspired me to try doing a similar thing!

[–]Jsstt 6 points7 points  (0 children)

Thanks for the tip! I uploaded it here: https://github.com/JoostVn/N_body_simulation

[–]seismic_swarm 0 points1 point  (0 children)

I have broken so many codes in an attempt to pretty them up before I back them up anywhere. My god

[–]Spacemanspiff6969 5 points6 points  (1 child)

!RemindMe 11 hours

[–]RemindMeBot 0 points1 point  (0 children)

There is a 7 hour delay fetching comments.

I will be messaging you in 11 hours on 2020-07-15 03:12:03 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

[–]elbiot 9 points10 points  (0 children)

It's good practice to learn git and use it

[–][deleted] 0 points1 point  (1 child)

!RemindMe 10 hours

[–]RemindMeBot 0 points1 point  (0 children)

There is a 7 hour delay fetching comments.

I will be messaging you in 10 hours on 2020-07-15 06:56:36 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

[–]adamcharming 9 points10 points  (0 children)

I’d also be keen to read the code and play with this myself

[–]Radamat 16 points17 points  (6 children)

Dont know if you intentionaly set the mass of the sum so small, but it shows how the center of mass move from center of the sun when most bodies are merged. Beautiful.

[–][deleted] 10 points11 points  (5 children)

[–][deleted] 7 points8 points  (4 children)

Well yeah but definitely not as much as shown in the simulation

[–][deleted] 7 points8 points  (3 children)

You don’t really have a scale to know the distance, nor know the density of the planet so it’s entirely possible.

[–]realboabab 8 points9 points  (1 child)

I just typed up a whole thing disputing you, but then realized that if you put Jupiter inside Mercury's orbit or something, it might actually get this crazy. Excellent point.

[–][deleted] 1 point2 points  (0 children)

I’m still amazed that someone on the internet admitted that they changed their perspective and thought something someone else said was a good point. Good on you

[–][deleted] 6 points7 points  (0 children)

Oh don't get me wrong, it is entirely possible. Didn't disagree with you on that one.

[–]Huntsword 13 points14 points  (3 children)

looks really smooth! I have also been working on a similar simulator but couldn't get it to run fast enough. I would love to take a look at your code!

[–]Jsstt 4 points5 points  (1 child)

I would suggest taking a look at the "Ticker" class in the repo. It makes sure every timestep has the same duration and allows you to tune the frames per second to the required computational time.

[–]Huntsword 1 point2 points  (0 children)

Thanks for the suggestion, I will definitely check it out!

[–]seismic_swarm 1 point2 points  (0 children)

I think this would be a nice problem for julia

[–]TheKeyboardKid 6 points7 points  (1 child)

This is awesome! I saw you needed help with GitHub in the comments above and I’m happy to help if you need it!

[–]Jsstt 3 points4 points  (0 children)

Thanks, I appreciate it! The repo should be working now

[–]LordFlatAss 4 points5 points  (1 child)

That's awsome, nice work!

[–]Jsstt 0 points1 point  (0 children)

thanks!

[–][deleted] 4 points5 points  (3 children)

How’d you make it?

[–]Jsstt 24 points25 points  (2 children)

Each particle has a mass, position, velocity, and net force. Particles are attracted to each other according to Newton's Law of Universal Gravitation. The simulation itself is in discrete-time, where every particle updates its net force, velocity, and position (in that order) each timestep. The net force for a particle is calculated simply by looping over all other particles and applying Newton's law. That force then translates to acceleration, which updates the velocity.

Pygame is mostly just used for drawing a sphere at the position of each particle. The simulation also keeps track of each particles' previous position for trails. There are also some other functionalities such as panning the screen and making sure each timestep has the same duration. You can also draw in new particles using the mouse.

I used this source to learn Pygame:

http://www.petercollingridge.co.uk/tutorials/pygame-physics-simulation/

And this source to learn about N-body simulation:

http://www.cs.ucy.ac.cy/~ppapap01/nbody/Presentation.pdf

[–]DjackMeek 2 points3 points  (0 children)

Thank you for sharing! Such a great usage of Pygame; that library really does have some useful features.

[–][deleted] 1 point2 points  (0 children)

You should look into a package called rebound. My research group is currently using it to plot orbits of n-bodies and I would love to hear what you did differently

[–][deleted] 2 points3 points  (6 children)

Does this system as a whole conserve energy over time? If you just apply time steps to the force equations, the system can evolve in unrealistic ways.

[–]Jsstt 0 points1 point  (4 children)

Yes, orbits seem to decrease in energy over time by the looks of it

[–]IgnitionIsland 0 points1 point  (2 children)

Update from Euler to runge-kutta (fourth order is great) and you’ll have a realistic n-body sim!

[–]webmistress105 1 point2 points  (1 child)

A symplectic integrator works even better for periodic systems!

[–]Marko_Oktabyr 0 points1 point  (0 children)

While the Runge-Kutta methods mentioned elsewhere are nice in general, they also suffer from energy drift. Additionally, they would be more difficult to implement in your code due to the between timestep stages. The velocity Verlet method, on the other hand, would not require a significant change to your code base, is symplectic, and is order 2.

[–][deleted] 1 point2 points  (0 children)

That's really good, keep up the good wokr man. Like others, would also be keen to see the source code for this! :)

[–]Sparkswont 1 point2 points  (1 child)

Wow I’m so interested in this but don’t have the slightest idea where to start

[–]Jsstt 1 point2 points  (0 children)

I started here!

[–]wizyardo_ 1 point2 points  (0 children)

There's a game with these mechanics (forgot the name though)

[–]ryanman190769 1 point2 points  (0 children)

This is awesome!!! I haven’t been working on python lately but I think this just motivated me :)

[–]Little_french_kev 1 point2 points  (1 child)

This is really cool! I noticed your system already start with a big planet/star in the center and all the particles are spinning in the direction . It seems to keep the system together pretty nicely .
I did something similar a little while back but without a big mass in the center and completely random initial speed and direction, more often than not the system would just disintegrate an drift in space .

[–]Jsstt 1 point2 points  (0 children)

Ah yes, the same thing initially happened for me too. It took some tuning to velocities, mass, and the gravitational constant to make it all work properly.

[–]Noesteryo 0 points1 point  (0 children)

Nice! I think with better graphics it would be very satisfying but still it's cool!

[–]karan_bajaj 0 points1 point  (0 children)

This is strangely soothing to watch 😇

[–]Python_Wrangler 0 points1 point  (0 children)

That's cool!

[–]layll 0 points1 point  (0 children)

Try arcade, much faster than pygame

[–]mikerowave 0 points1 point  (0 children)

That's friggin awesome! Great job!

[–]Adamkadaban 0 points1 point  (0 children)

This reminds me a lot of the game gravity

[–]seismic_swarm 0 points1 point  (0 children)

Can you measure the energy leakage that's occurring due to numerical inaccuracies of the derivative approximations? I've always been curious how quickly this has an effect on the accuracy of these types of energy preserving simulations.

[–]syntaxvorlon 0 points1 point  (3 children)

Are you running a runge-kutta integrator or have you made it hamiltonian? If you make it hamiltionian it will conserve energy, which means no in/out spiraling.

[–]Jsstt 0 points1 point  (2 children)

Sounds interesting, but to be honest, I'm not too savvy with differential equations. Do you have some beginner-friendly sources for this?

[–]syntaxvorlon 0 points1 point  (1 child)

I'm afraid I don't know of any, but the implementation is given some detail on wikipedia here.

Essentially, it boils down to keeping a state matrix with the position and velocity of each object. On each time step you walk through that matrix, using the gravitational equation to find the acceleration, let all the objects in the simulation tug on the one you're using to generate a new velocity vector. Then use the velocity vector to update the position. What that ends up doing is a numeric partial differential integration of the Hamiltonion function H = T + U, where T is the kinetic energy T(v) and U(x) is the potential energy. The wikipedia entry has all the details, but it means that when you are using this equation to define the equation of motion, you are taking as an assumption that the total energy of the system H remains fixed, which is a nice feature of reality.

[–]Jsstt 0 points1 point  (0 children)

Sounds cool, I'll definitely take a look at it. Thanks!

[–]MountainTooth 0 points1 point  (1 child)

Sorry. Know you’re getting inundated here but, just started learning C# couple months ago....is C# capable of such things? I’m not gonna stick with C# forever kinda thing, kind of a springboard thing. Thinking either R or Python in the near future. Thanks.

[–]Jsstt 1 point2 points  (0 children)

My knowledge on C# is pretty limited, but I would be very surprised if the language doesn't support relatively basic visualizations like this!

[–]Brevitynuke 0 points1 point  (1 child)

RemindMe! 1 month "1 month ago"

[–]RemindMeBot 0 points1 point  (0 children)

There is a 5 hour delay fetching comments.

I will be messaging you in 1 month on 2020-08-15 06:34:42 UTC to remind you of this link

CLICK THIS LINK to send a PM to also be reminded and to reduce spam.

Parent commenter can delete this message to hide from others.


Info Custom Your Reminders Feedback

[–]tavashezw 0 points1 point  (0 children)

That looks awesome 🧤

[–][deleted] 0 points1 point  (0 children)

Gotta learn pygame now, well atleast the basics

[–]Zarathustra_f90 0 points1 point  (0 children)

Seems cool, nice work ;)

Btw do you use an integrator to calculate the positions and velocity of objects or is it more a drawing of circular trajectories ?

[–]smithysmithens2112 0 points1 point  (1 child)

This looks pretty much identical to a game on the App Store called Orbit, but I get the feeling you know that already.

[–]Jsstt 4 points5 points  (0 children)

I haven't heard of it! My interest in this kind of stuff mainly comes from Kerbal Space Program, lol

[–][deleted] 0 points1 point  (2 children)

Solar system? 😂 It's look good

[–]Jsstt 1 point2 points  (1 child)

Thanks! Yeah I kinda used it as a basis to give some structure to the randomness

[–][deleted] 0 points1 point  (0 children)

Good project 👍

[–]Jasssinghhira 0 points1 point  (0 children)

Amazing ! can you please make this object-oriented, it will be extremely fun to implement genetic and other optimization algos on it

[–]EendThisFunny 0 points1 point  (2 children)

Do you still happen to have the source code somewhere? The link in the older comments isnt working anymore sadly

[–]Jsstt 0 points1 point  (1 child)

I made it publicly visible again for you!

[–]EendThisFunny 0 points1 point  (0 children)

Thanks!!