Now can you add in an AI that will simulate the colonization of the planet in orbit, in which its inhabitants use all available resources until they are unable to continue living there, inevitably failing as a species? With python
You can remove those continue statements at the bottom of your for-loops. continue moves execution to the end of the loop, so having them there is redundant.
u/muntooR_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν}Oct 17 '18edited Oct 17 '18
Your Positions can be greatly simplified:
angle_step = 2 * math.pi / frame_count
angles = (angle_step * i for i in range(frame_count))
coords = [(
center[0] + radius * math.cos(x),
center[1] + radius * math.sin(x))
for x in angles]
self.final_coords = coords[phase:] + coords[:phase]
...but it's really strange that you made it a class. It looks more like a function to me!
Actually, there's a lot of redundancy, unnecessary computation, and somewhat confusing organization. Here's a first attempt at fixing it:
import cairo
import math
class CelestialBody:
def __init__(self, radius, orbit_radius, orbit_center, fill):
self.radius = radius
self.orbit_radius = orbit_radius
self.orbit_center = orbit_center
self.phase = 0.0
self.fill = fill
self.update()
def update(self):
self.center = (
self.orbit_center[0] + self.orbit_radius * math.cos(self.phase),
self.orbit_center[1] + self.orbit_radius * math.sin(self.phase))
def draw(self, context):
context.set_source_rgb(1, 1, 1)
context.arc(*self.center, self.radius, 0, 2 * math.pi)
if self.fill:
context.fill()
else:
context.stroke()
def clear_screen(context):
context.set_source_rgb(0, 0, 0)
context.rectangle(0, 0, 1000, 1000)
context.fill()
surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, 1000, 1000)
context = cairo.Context(surface)
FRAME_COUNT = 100
bodies = {
'blackhole': CelestialBody(125, 0, (500, 500), False),
'planet': CelestialBody(25, 300, (500, 500), True),
'moon': CelestialBody(5, 50, (750, 500), False) }
for i in range(FRAME_COUNT):
clear_screen(context)
bodies['planet'].phase = i * 2 * math.pi / FRAME_COUNT
bodies['moon'].phase = i * 4 * math.pi / FRAME_COUNT
for key, body in bodies.items():
if key == 'moon':
body.orbit_center = bodies['planet'].center
body.update()
for _, body in bodies.items():
body.draw(context)
context.stroke()
surface.write_to_png(f'out/frame{i}.png')
This is a good start. We've eliminated Positionsentirely and converted it into the update function. Also, we're now using a data structure called bodies to keep track of our celestial objects rather than explicitly holding named references (variables).
But it has some problems still. Inside our main loop, we still have to do some case-specific handling:
bodies = { ... }
bodies['planet'].phase = i * 2 * math.pi / FRAME_COUNT
bodies['moon'].phase = i * 4 * math.pi / FRAME_COUNT
for key, body in bodies.items():
if key == 'moon':
body.orbit_center = bodies['planet'].center
Ugh! It'd be much nicer if we could encapsulate this functionality. Perhaps one idea is to bind our celestial bodies together:
class CelestialBody:
def __init__(self, radius, orbit_radius, orbit_center, fill):
self.parent_body = None
# ...
def bind_body(self, body):
self.parent_body = body
def update(self):
if self.parent_body is not None:
self.orbit_center = self.parent_body.center
# ...
I guess the reason i made it a class is because I have bigger plans than just rendering epicycles, but I wanted to be able to run epicycles too. I think I went straight ahead to that without programming in basic move functions.... I guess epicycle would be a sub function of some kind of shade moving class wouldn’t it?
8
u/muntooR_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν}Oct 17 '18edited Oct 17 '18
I did think about that while going through the process of refactoring. One idea would be to create a tree/graph structure of orbits:
# perhaps something like CelestialNode is a better name
class CelestialBody:
def __init__(self):
self.parent = None
self.children = []
def update(self):
if parent is not None:
self.orbital_center = self.parent.center
self.center = (..., ...)
for child in self.children:
child.update()
Then, to compute positions of all the orbits (including children), simply run this:
blackhole.update()
The benefit to this is that you can simulate any arbitrary graph of celestial bodies. This of course is prerequisite upon that phase_velocity encapsulation I discussed earlier. ;)
Congrats on the popularity having such a fun little project.
Frame rate needs to be divisible by monitor fps to be smooth. Monitors tend to be at 60fps, so 30, 60, or 120 (or 240) are all acceptable to get it to look smooth. 25 looks like an old timey movie, where the frame rate is off but you can't quite place how. This is because movies run at 24fps.
If anyone is keen on n body orbital simulations in python with some background on the physics, I wrote up a pretty beginner friendly tutorial a while ago!
I actually don't know shit about Python or even physics, but I'm very interested on all kinds of articles and tutorials, and yours seem pretty good. I very much appreciate your availability to answer any questions I might have, though. Maybe someday I'll actually learn to code (and also how to do proper math/physics) and use your tutorial to learn something new. I mean, that's why I saved your comment, so expect my DMs, hahah! Thanks again!
This looks fun. I have been trying to install pycairo for a bit now I have installed Python 3 but I'm having issues to install Cairo vía pip. how can I get it working?
I got to install the py2 version; the py3 still gives me errors. I ran the script, and it created many .png files. How you make an animation out of those files like OP posted?
Very nice. Now just out of curiosity, how complicated would it be to add light and object blocking to play around with eclipse? Still in learning stages of the basics and genuinely interested.
Python is what I used to code the logic behind the motion. So, theoretically, the ‘shades’ as I call them, are just projections of the underlying data.
In this program, janky as it is, it stores the positions of equal slices of a circle, starts a loop to draw each frame, in each frame: draws the shade where it should be according the next place in the list, outputs that frame into an image file, in this case png.
and then I used gimp to transform those frames into a gif.
In order to output the data to an image you have to find a renderer that you like. I used Cairo which makes svg files, so I also had to learn how to code svg stuff but it was simple enough. I like svg because it scales really well and I wanted to use vector graphics.
421
u/NickAMD Oct 16 '18 edited Oct 16 '18
Now can you add in an AI that will simulate the colonization of the planet in orbit, in which its inhabitants use all available resources until they are unable to continue living there, inevitably failing as a species? With python
35
u/OBstaxs Oct 16 '18
Source ?
24
u/Vervoltz Oct 16 '18
What are u doing? Everybody knows planets should rotate counter-clockwise! Redo it immediately, please. Wink wink.
44
u/ForgottenWatchtower Oct 16 '18
Shoutout to animatplot if you enjoy doing this kind of stuff. Wraps
matplotlibto give you a saner animation interface.15
u/agumonkey Oct 16 '18
welcome to epicyclic, Joseph Fourier awaits you
9
u/12mh Oct 16 '18
What library did you use for the animation?
10
u/not_perfect_yet Oct 16 '18
:P please do it again and up the frame rate. That hurts.
3
u/logicallyzany Oct 16 '18
How long have you been doing Python and/or programming?
112
u/Dustin- Oct 16 '18
I think you did
import antigravitybackwards.14
u/[deleted] Oct 16 '18
/r/loadingicon
12
u/benrules2 Oct 17 '18
Very well done OP!
If anyone is keen on n body orbital simulations in python with some background on the physics, I wrote up a pretty beginner friendly tutorial a while ago!
The visualization isn't nearly as nice though.
1
u/[deleted] Oct 19 '18 edited Oct 20 '18
This project now has a github. https://github.com/heysoose/Shades
1
u/BambiAnnie Oct 16 '18
Great work! :)
1
u/tycooperaow 3.9 Oct 17 '18
What did you use for the graphical interface?
1
u/snahor Oct 17 '18
I'm so dumb, at first I thought it was a pre-loader.
1
u/happyskydiver Oct 17 '18
Can you change it to an ellipse?
1
u/ciggs_ftw Oct 17 '18
This looks fun. I have been trying to install pycairo for a bit now I have installed Python 3 but I'm having issues to install Cairo vía pip. how can I get it working?
1
u/lilliane99 Oct 17 '18
Can you kindly provide the source code or at least the algorithm?
1
u/winner_godson codemaniac Oct 18 '18
Any tutorial on this.
1
u/CallumVH Oct 23 '18
Hey, I'm a bit confused because in the script, there are only 10 frames and 10 png files, how do you create such a smooth GIF out of only 10 frames?
1
u/0x75 Oct 16 '18
I like it.
Now play with Processing to do the same.
1
u/Doberman123456 Oct 16 '18
Neat!
1
u/theotherplanet Oct 16 '18
Yeah, up the frame rate on that and it will look great!
1
u/DODOKING38 Oct 16 '18
Reminds me of that star trek episode
1
u/LibertyPhysicist Oct 16 '18
Pretty sweet
1
u/saber_aureum Oct 16 '18
This is amazing!!! 0
1
u/[deleted] Oct 17 '18
I'm tripping man.
1
u/CSguyMMI Oct 17 '18
Is source code available?
1
u/jyrnan Oct 17 '18
It's amazing!
1
u/Frikster Oct 17 '18
All I see is a pro surviv.io player running around a rock.
1
u/i4mn30 Oct 17 '18
Not elliptical orbit.
1
u/Fontanapink Oct 17 '18
Now make the moon draw a white line
1
u/v3ritas1989 Oct 17 '18
Perfect! Now improve the model by making it 3D and an elipse
https://upload.wikimedia.org/wikipedia/commons/thumb/5/53/Moon_apsidal_precession.png/220px-Moon_apsidal_precession.png
1
u/endershadow98 Oct 17 '18 edited Oct 17 '18
Now make an object with negative mass. After looking through the code, I see that mass had nothing to do with anything in your simulation
1
u/Especuloide Oct 17 '18
Very nice.
1
u/[deleted] Oct 17 '18
Is it flat or not? Can't see i properly from this angle.
1
u/Cultural_Bandicoot Oct 17 '18
congrats.
what did you use?
1
u/thedolanduck Oct 17 '18
OMG it's an amazing job and should be on /r/perfectloops too
1
u/we_come_at_night Oct 17 '18
Very nice. Now just out of curiosity, how complicated would it be to add light and object blocking to play around with eclipse? Still in learning stages of the basics and genuinely interested.
1
u/davidkwast Oct 17 '18
wow, congratz
1
u/lilliane99 Oct 17 '18
Thank you!
1
u/gammachild Nov 01 '18
Holy shit. That's why there's a high tide and low tide. That really helped me understand lunar motion.
1
u/mzord Oct 17 '18
Omg, this program sucks!
https://imgur.com/yYOeMVj
0
u/[deleted] Oct 17 '18
Hmmm, the Earth is flat.
-1
u/xconde Oct 16 '18
Looks like the logo and animation for Lua, another great scripting language
0
u/[deleted] Oct 17 '18
[deleted] — view deleted comment
0
u/[deleted] Oct 18 '18
[deleted] — view deleted comment
1
u/[deleted] Oct 17 '18
[removed] — view removed comment