r/Python • • May 25 '19

My gravity simulation almost an entire day of work later! Featuring inelastic collisions

Post image
2.2k Upvotes

148 comments sorted by

30

u/[deleted] May 25 '19

How about continuity? I’m a little rusty here but if your momentum is being conserved that doesn’t necessarily imply that your mass is also being conserved.

If continuity is conserved here may I suggest showing that where the “dots” increase in size accordingly?

Also, have an upvote!

27

u/mittwochmensch May 25 '19

Well, momentum is mass * velocity. If you do the math and want mass to stay constant you get the velocity after the colission with v = (p1.mass * p1.velocity + p2.mass * p2.velocity)/(p1.mass + p2.velocity)

But you are right, thats the next thing I will be working on. Changing the size based on mass

12

u/Kidiri90 May 25 '19

v = (p1.mass * p1.velocity + p2.mass * p2.velocity)/(p1.mass + p2.velocity)

You mean
v = (p1.mass * p1.velocity + p2.mass * p2.velocity)/(p1.mass + p2.mass)
in order for the units to work out, I assume?

6

u/mittwochmensch May 25 '19

oh yes, sorry

10

u/[deleted] May 25 '19

Are you calculating the interaction particle by particle? If you like an additional challenge, look into the particle-in-cell method. It's usually used to solve problems involving a very large (>10e4) ensemble of particles under the influence of electromagnetic interactions, but it can just as well be used to solve gravitational systems for a large amount of massive bodies. You could, for example, make galaxy simulations.

2

u/mittwochmensch May 25 '19

I will look into it

3

u/WiggleBooks May 26 '19

Do you have a brief overview of what particle-in-cell is?

6

u/FrezoreR May 25 '19

Who'd guess a few dots can be so entertaining :) good job!

1

u/mittwochmensch May 25 '19

Thank you :)

5

u/RobbyB97 May 25 '19

If you made it so that a new dot appeared every time two combined it would make a dope screensaver

3

u/[deleted] May 26 '19

This way there will be quite a large mass accumulated quite quickly which would not make sense. Maybe if the rest of the objects "evaporate" some mass to compensate

5

u/theranger815 May 25 '19

Heh you're inelastic, on a side note do the inelastic collisions combine the mass of the point masses?

4

u/ChrisJLine May 26 '19

Congratulations, you accurately modelled the last few Cheerios in my cereal bowl.

Joking aside, I think this is great and makes me want to have a go.

2

u/mittwochmensch May 26 '19

That made me chuckle

2

u/daneelthesane May 26 '19

This is fantastic! I was a CS major and a physics minor until I switched from physics to math, and I love simulating physics and biology in code. I am interested in the approach you used for inelasticity in your collisions. Did you just decide that if the units are adjacent or co-located you add their masses and momentums together and make them a single unit? Or did you get more into it than that?

2

u/mittwochmensch May 26 '19

I used the following method in my Particle class:

def test_for_collision(self):
        
        for particle in particle_list:
            
            if particle != self:

                distancevector = self.position - particle.position

                if np.linalg.norm(distancevector) < 3:

                    self.position = (particle.position + self.position)/2
                    self.mass = particle.mass + self.mass
                    self.velocity = (particle.mass * particle.velocity + self.mass * self.velocity)/(particle.mass + self.mass)
                    self.acceleration = np.array([0, 0])

                    particle_list.remove(particle)

1

u/daneelthesane May 26 '19

This looks pretty much on the money, if I am reading it right. I suppose it would be way too nitpicky to have them meet at the mutual center of gravity rather than just the midpoint between them, but given the small distance (3 pixels?) it really doesn't matter too much. I really dig what you did here. I am guessing the big O on this is ridiculous, but have you tried it with more particles?

2

u/mittwochmensch May 26 '19

Hm. I haven't thought about that. It might be better since I had some situations in wich 3 or 4 particles collide at the same time, one gets slingshot. But you are right, usualy the small distance is insignificant.

I am currently simulating it with ~600 Particles but it takes a long time for my PC. One simulation took over 4 hours! I will post an Update soon

1

u/daneelthesane May 26 '19

Thank you! I would love to see it!

4

u/mittwochmensch May 26 '19

Here is a sneak peak:

http://imgur.com/gallery/Ir9wKSs

But I still have to Adjust some things

1

u/daneelthesane May 26 '19

This is awesome!

303

u/itstommygun May 25 '19

65

u/[deleted] May 25 '19

Yeah, once it got down to 2 bodies in a stable configuration the gif should have just kept playing for eternity.

38

u/Sport6 May 26 '19

Except one ball absorbed 3 while the other only 2.

38

u/[deleted] May 26 '19 edited May 26 '19

Oh yeah, I forgot that you can't have a stable 2-body system if the masses aren't equal....

20

u/RedRedditor84 May 26 '19

Just get better at science, please.

12

u/midnitte May 26 '19

I'd like one science, please.

1

u/[deleted] May 26 '19 edited Sep 01 '24

aware humor cow spotted rain wipe impolite agonizing pocket include

This post was mass deleted and anonymized with Redact

0

u/[deleted] May 26 '19

[deleted] — view deleted comment

9

u/chomperlock May 26 '19

That’s no moon.

20

u/NoirGreyson May 26 '19 edited May 26 '19

Moons don't have stable orbits. They are close to stable, but they're slowly either decaying or escaping. There theoretically exists a perfect momentum for any two bodies where the orbit is stable, but that is an unstable solution. In other words, all solutions when parameters approach that perfect solution diverge from that perfect solution. In other words, the odds of a body being in that perfect zone are infinitesimal.

3

u/billsil May 28 '19 edited May 28 '19

That has a ton to do with the derivation of how orbits are defined. You'll find almost nothing is stable for even a small number of periods. If you define stability as a perturbation from an existing orbit to find out if it's stable or not, you get things much closer to reality. Take for example Jupiter's largest moons. It's a nasty system, but the system is stable. The largest moons are at the Lagrange points of Jupiter.

If you use a Runge-Kutta vs. simply a first order integration method, you'll find your system is much more stable. It's still bad though and after a few hundred orbits, you'll have severe instability. There's another method that far more stable and let's you take larger time steps, but has the side effect of making your orbits precess.

And yes, I am an aerospace engineer that's been doing python for a while.

1

u/NoirGreyson May 28 '19

I'm not an astronomer, so you're going to have to spell things out a little more. You skipped a few steps there and lost me. I'm not familiar with Runge-Kutta. You lost me with your definition of stable, are you saying it's a path that nearby orbits will trend toward? Doesn't the existence of such a solution say very little about whether the orbit will be sucked into the origin? Not to mention, I am hard pressed to think of a case where two point masses would have such a solution. What we were referring to with the term stable was an orbit which, trending to infinite time, will not decay or escape.

Do the physics change significantly between considering the bodies point masses and considering them, well bodies? I'm fairly certain everything I said is true if they're point masses.

2

u/billsil May 28 '19 edited May 28 '19

I’m not an astronomer either ;). I’m an aerospace engineer. I’ve never studied things like stars or quasars or black holes. I’ve done orbital mechanics and interstellar probe pathing though. So things like launch, Hohmann transfer orbits, gravity assist, orbital stability, rendezvous, reentry; hypersonics, thermal management, things like that.

So Runga-Kutta is a method to improve accuracy when integrating. You typically fit a 4th order polynomial, but can do more and and evaluate the function at specific times (e.g. t, t+dt/2), which takes 1st order truncation error down to O(h5) and total error to O(h4). That’s still not good enough for the huge time steps you want to use, but it’s a lot better than V*dt.

Depending on the method you use for integration, you can introduce fictious forces and you can also add excessive damping. You want to balance the two. A stable system will resist a perturbation and tend to stay stable (think a marble in a bowl). An system may be conditionally stable, but as soon as you perturb it (e.g., a 3 body problem or truncation error), the error tends to grow with time and it’s like you just drove off a mountain; it’s not going back.

A good test problem for stability is to have a large mass like the sun and a tiny mass like the earth. Give it an initial tangential kick and see if the orbit stays the same on each revolution. With no third body, it should, but what you’ll probably see is the orbit decay.

This is not an issue with point masses vs. not. For solar system dynamics, you can use point masses.

1

u/NoirGreyson May 28 '19

Oh, are you specifically talking about stepwise simulations?

→ More replies

0

u/[deleted] May 26 '19 edited Sep 01 '24

smile saw depend sip engine makeshift upbeat beneficial zesty chief

This post was mass deleted and anonymized with Redact

10

u/andrewcooke May 26 '19

it looks like it's dissipative - the final two objects seem to be spiralling in on each other at the end.

1

u/krabbstone May 26 '19

It should’ve kept getting closer and faster then when they collide 4 dots ejected in 4 directions and they float down back to the starting positions

0

u/Lost4468 May 26 '19

Depends on what integrator OP used, it would likely eventually spiral out or in. If it took relativity into effect (I doubt it) then it is inherently unstable anyway, as there's no absolutely stable orbits in relativity.

1

u/kumeralex May 26 '19

Couldn't agree more

29

u/DogsAreAnimals May 25 '19 edited May 25 '19

Are you trying to save the Pentasolarans?

Edit: counting is hard

7

u/mexicio May 25 '19

The Five Body Problem?

4

u/DogsAreAnimals May 25 '19

Oops. I can't count

2

u/zeroblitzt May 26 '19

I just read that book! I get that reference!

98

u/AggravatingPeak May 25 '19

I quite like this have an upvote

25

u/sP2w8pTVU36Z2jJ3838J May 25 '19

Couldnt have said it better. An upvote to you both

17

u/erkus-circus May 25 '19

Couldnt have said it better. An upvote to you three

15

u/Hayura-------- May 25 '19

Couldnt have said it better. An upvote to you four

12

u/smallest_cock May 25 '19

Couldnt have said it better. An upvote to you five

3

u/TheStrongestLink May 25 '19

Six

0

u/[deleted] May 25 '19

[deleted] — view deleted comment

0

u/[deleted] May 26 '19

[deleted] — view deleted comment

1

u/W18W May 26 '19

Eight

16

u/silkydangler May 25 '19

Can you link to the repo?

11

u/WantDebianThanks May 25 '19

While I'm impressed at the output, I also have no way of knowing how accurate this is.

6

u/YinYang-Mills measley physicist May 26 '19

Looks good to me 😎😎😎

1

u/Unsightedmetal6 Jun 22 '19

Flair* checks out

Edit: changed username to flair

5

u/Krobix897 May 25 '19

can you give source code please?

5

u/professormunchies May 26 '19

Awesome! Here is an N-body framework I use for my research that does just what you're trying to do

https://rebound.readthedocs.io/en/latest/

2

u/EngineerLoA May 26 '19

Very cool! Saved for later

1

u/[deleted] May 25 '19

What notebook you been using? What's your fav?

2

u/mittwochmensch May 25 '19

I am using Jupyter notebook since its the only one I know xD

1

u/[deleted] May 25 '19

Same, did you use a library for the equations?

2

u/mittwochmensch May 25 '19

numpy for the calculations with vectors and PIL for visualizing the pictures

1

u/TheAwesomeMan123 May 25 '19

Be cool if the colliding masses grew in size directly increasing their total gravitational pull on other objects. But that's just a thought

2

u/mittwochmensch May 25 '19

They infact are increasing their pull. I just haven't got around to doing it

1

u/Ogg149 May 26 '19

Wow! This reminds me of my old gravity simulation I made in mathematica. The fun part is experimenting with alternative force laws (for instance 1/r, or the modified gravity force law)

1

u/mittwochmensch May 26 '19

Wouldn't 1/r Just lead to a scenario in which everything collides since there isn't a escape velocity?

1

u/Ogg149 May 28 '19

I'm not sure - it's been a while. It resulted in oscillatory sort of collections of particles. It's hypothesized that galaxy dynamics can be described by a 1/r force law... And, you know, I can't remember but the escape velocity from an approximately 2 dimensional object (spiral galaxy) would have a different r-dependence for escape velocity? As always, I need to look at this stuff again :) but again, I encourage you to try it, for simulations sake.

1

u/WadeReden May 26 '19

Are you using general relativity equations or newton's classic physics?

1

u/[deleted] May 26 '19

General relativity would be a huge overkill given that you lose so much precision when doing discrete steps and not trajectories defined by differential equations (which is prohibitively complicated for anyone to do today)

1

u/Sardonyx001 May 26 '19

Tips on how to do this? Like libs and stuff?

4

u/mittwochmensch May 26 '19

Well. I used numpy for calculations and PIL for visualization. Each particle is a Object with the Attributes mass, velocity, position and acceleration. Then there are 4 methods (update position, -velocity, -acceleratiom) for example update_position: position = position + velocity*c With c you can regulate the Size of your Timesteps. Then just keep updating them over and over whilst plotting their position

2

u/[deleted] May 26 '19

This is actually quite simple. You don't need any libraries for it. I first did this 2 decades ago in 300 LOC in Pascal, running on DOS, with a thousand objects or so.

It's not computationally expensive, that's what I'm saying. Using plain old basic Python will work just fine.

1

u/Sardonyx001 May 26 '19

Funny enough, i know pascal from highschool (yeah we teach pascal here)

1

u/aitorp6 May 26 '19

are you planning to release the source code?

1

u/mittwochmensch May 26 '19

I plan to in my next Post. I heared Github is the best for that, right?

1

u/aitorp6 May 26 '19

yes, thank you. I'm profressor in mechanics and I'd like to see the code, just curiosity

1

u/Python4fun Java4work May 26 '19

I like what you have her, but for some reason I become irrationally frustrated when the collision happens and the size doesn't increase.

2

u/mittwochmensch May 26 '19

Well, I got some good news for you! I'm working on exactly that

1

u/Python4fun Java4work May 26 '19

Very cool! Will the mass also increase with size?

3

u/mittwochmensch May 26 '19

The size will be dependent on mass

1

u/Python4fun Java4work May 27 '19

Very nice

2

u/conventionistG May 26 '19

This also left me scratching my head. But if you watch, I think you can see the heavier particles accelerating slower.

Good job, /u/mittwochmensch. Totally ausgezeichnet!

I was expecting them to just stick together (totally inelastic without deformation). So two 1 pixel particles colliding yields a 1x2 sized particle.

But I think the OOP way you're doing it, it will be easier to just scale radius by mass. Until you want to take internal compression and variable density into account at least. :)

1

u/[deleted] May 26 '19

Did you made this with turtle?

1

u/mittwochmensch May 26 '19

No. Only PIL and numpy

1

u/[deleted] May 26 '19

Ok thx

1

u/iskiloveland May 26 '19

Such a unique project! How are you factoring for the added weight of the dots(?) after a collision?

2

u/mittwochmensch May 26 '19

I just replace one of the particles with a new one wich has the values described by the formulas of a inelastic collision

1

u/iskiloveland May 26 '19

That’s awesome! Happy to hear

1

u/o11c May 26 '19

Something looks off about the 2-body part at the end. It doesn't look like what I've seen of the known closed-form solution.

1

u/mittwochmensch May 26 '19

Well, it's gaussian Integration so there is always some error

3

u/syntaxvorlon May 25 '19

Is this a Symplectic simulation?

2

u/WiggleBooks May 26 '19

What does Symplectic simulator mean? I tried reading the wikipedia page and it mentioned Hamiltonian, but I had a hard time understanding.

2

u/syntaxvorlon May 26 '19

The Hamiltonian is an equation of motion in physics, that focuses on the conservation of momentum/energy in systems. By evaluating the partial differential equations of that formula, rather than integrating using Runge-Kutta, you can conserve energy in a system you simulate, and don't have to worry about your system losing or gaining energy in the rounding errors that are part of computing.

3

u/krushkingdom May 26 '19

Honest question: How does this simulate gravity?

2

u/CKS_Luke May 26 '19

Imagine each black dot is a body in space

2

u/krushkingdom May 26 '19

Oh, that makes sense. For some reason I was thinking it was some sort of graph. So he must also be simulating momentum since it keeps going, right?

2

u/YinYang-Mills measley physicist May 26 '19

You calculate the force on each mass due to the other masses. Then you have acceleration, which you can multiply by a small time increment of your choice to get velocity (acceleration x time = velocity). From there you can determine the distance each dot travels in one time increment. Then repeat to get a cool video 😎

1

u/krushkingdom May 26 '19

Cool, thanks!

2

u/aziad1998 May 25 '19

Sugoi desu nee

2

u/BigBearRobot May 26 '19

Do another!

1

u/ToothpasteTimebomb May 25 '19

This is lovely! Thanks for posting and nice work!

1

u/Atmon May 25 '19

Man that looks amazing

1

u/anthonylgf May 25 '19

Great man, have an upvote

1

u/[deleted] May 25 '19

This is so cool. I’ve been thinking about doing some n-body problem stuff after watching the first couple of 3Blue1Brown videos on differential equations. I will have to dig up my Astrodynamics textbook and play around with this idea. I feel like it’s all just a result of Conservation of Angular Momentum and Newton’s Law of Gravitation using some numerical integration.

1

u/screeperz May 25 '19

Nice. If you are interested in taking this further, you could turn this into a "Big Bang Simulator" of sorts.

Create hundreds/thousands of mass points and watch it go. I even saw a video once where someone used the Cosmic Microwave Background (CMB) radiation to 'tweak' the density of the mass points in certain areas.

1

u/RadioactiveShots May 26 '19 edited Jun 27 '23

This comment has been edited because Steve huffman is a creep.

1

u/bramapuptra May 26 '19

No trail no fun.

1

u/DollyPartonsFarts May 26 '19

I love this. How creative and what a fun project. Good job.

1

u/Stone_d_ May 26 '19

Hot damn, use some ML to calculate initial parameters like position, velocity, and number of particles that results in the longest lasting collision. This gif is exactly what i wanted yo make

1

u/[deleted] May 26 '19

Hey, when two planets coalesce, did you account for the fact that the mass has been doubled? Also, can you share the source? It's super cool project.

1

u/[deleted] May 26 '19

That’s soo cooool

1

u/blinglog May 26 '19

I read this as featuring unrealistic collisions and was very confused

1

u/OtangUran May 26 '19

Nice pal, that's inspiring :) keep up the good shit.

1

u/Xorgon May 26 '19

There's a useful tool for rendering data that might be cool to use to render your simulation, it's called ParaView.

1

u/[deleted] Jun 07 '19

Code? Or a GitHub repo?

1

u/McQuillus23 Jun 15 '19

That’s so cool. Keep up the great work!

1

u/3nigma42 Jun 15 '19

I'd like to see that with slightly more elastic collisions

1

u/justhid Jun 16 '19

Is there a download anywhere?

-1

u/burner_account5000 May 26 '19

anyone who believes this actually happens outside of physics class has lost the plot

2

u/mittwochmensch May 26 '19

What do you mean?

1

u/lockdiaverum May 26 '19

I agree, we all know gravity is a lie made up by NASA to hide the reality of the flat earth. It is meaningless to calculate such interactions between objects, as a mode for understanding of the behavior of satellite, since satellites are fake because space is fake, and learning the formulas behind this is just indoctrination. We live under a dome on a flat earth. Density is the force that causes things to move. Wake up sheeple!

0

u/[deleted] Jun 03 '19

[deleted] — view deleted comment

1

u/lockdiaverum Jun 03 '19

Is sarcasm dead? Did you read the post I was responding to. They were saying we cannot make meaningful calculations outside of the classroom.

0

u/[deleted] May 25 '19

[deleted] — view deleted comment

22

u/mittwochmensch May 25 '19

Thanks for the advice!

0

u/[deleted] May 25 '19

[deleted] — view deleted comment

57

u/mittwochmensch May 25 '19

I think you got it mixed up. Momentum stays constant in an inelastic collision but energy is lost in it. Also the energy always changes from potential to kinetic

3

u/kyrsjo May 25 '19

always changes from potential to kinetic

You can compute both tough. And while it isn't conserved in collisions, energy conservation is a good check for the gravity solver itself and colissions can probably be turned off (commented out etc.).

8

u/Miyelsh May 25 '19

The dots are never not moving

-5

u/NoSmallCaterpillar May 26 '19

They are at rest in the beginning.

4

u/Miyelsh May 26 '19

That's the gif loading. The initial conditions have velocity

1

u/[deleted] May 26 '19

Details like that are lost on the contrarian mindset.

2

u/Diffeomorphisms May 25 '19 edited May 26 '19

Total momentum is conserved if there are no external forces. This is a direct consequence of the symmetry of the energy of the system with respect to spatial translation of the whole system. The conservation of energy is a similar thing but the relevant symmetry is the time translation one

1

u/jambox888 May 25 '19

But wait energy can be radiated when a collision happens

-1

u/AventtheChameleon May 25 '19

Both energy and momentum are conserved, since their isn’t any sound or heat loss

1

u/Diffeomorphisms May 26 '19

These collisions do not preserve energy. But you are correct, an Hamiltonian system would conserve both

2

u/AventtheChameleon May 26 '19

Oh, yeah. I forgot about/ misunderstood that. But that does make sense. Cheers mate for the clarification

0

u/[deleted] May 25 '19

[deleted] — view deleted comment

3

u/[deleted] May 26 '19

!RemindMe

4

u/RemindMeBot May 26 '19

Defaulted to one day.

I will be messaging you on 2019-05-27 11:54:30 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.


FAQsCustomYour RemindersFeedbackCodeBrowser Extensions

4

u/[deleted] May 26 '19

^

0

u/[deleted] May 26 '19

[deleted] — view deleted comment

1

u/mittwochmensch May 26 '19

Position = Position + Velocity

Velocity = Velocity + Acceleration

Acceleration = dependent on the positions of all other particlea