35
u/OBstaxs Oct 16 '18
Source ?
54
Oct 16 '18
55
u/Nicksil Oct 16 '18
You can remove those
continuestatements at the bottom of your for-loops.continuemoves execution to the end of the loop, so having them there is redundant.Thanks for sharing
30
Oct 16 '18
Thanks for the feedback.
12
u/doinkypoink Oct 16 '18
I'm learning class and python. I think comments would make it really helpful for me to read your code :(
23
21
u/muntoo R_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} Oct 17 '18 edited Oct 17 '18
Your
Positionscan 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 theupdatefunction. Also, we're now using a data structure calledbodiesto 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'].centerUgh! 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 # ...Now, after defining
bodies, we may bind them:bodies['planet'].bind_body(bodies['blackhole']) bodies['moon'] .bind_body(bodies['planet'])Now we can finally cut out this horrendous if statement:
if key == 'moon': body.orbit_center = bodies['planet'].centerYay!
I'll leave encapsulation of the following as an exercise to the reader:
bodies['planet'].phase = i * 2 * math.pi / FRAME_COUNT bodies['moon'].phase = i * 4 * math.pi / FRAME_COUNT(Perhaps a
phase_velocityparameter insideCelestialBody?)4
3
Oct 17 '18
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/muntoo R_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} Oct 17 '18 edited 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()And construct a tree as follows:
blackhole.children = [planet] planet.children = [moon] planet.parent = blackhole moon.parent = planetThen, 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_velocityencapsulation I discussed earlier. ;)4
1
8
u/quotemycode Oct 16 '18
Line 24 last constant should be math.tau (added to python in 2016). 2*pi is wrong.
5
2
Oct 17 '18
You should put it on github! People could send you pull requests, you could re-use it, people could find it in searches...
3
-1
24
u/Vervoltz Oct 16 '18
What are u doing? Everybody knows planets should rotate counter-clockwise! Redo it immediately, please. Wink wink.
13
29
Oct 16 '18
What if this is the view from "below".
29
1
44
u/ForgottenWatchtower Oct 16 '18
Shoutout to animatplot if you enjoy doing this kind of stuff. Wraps matplotlib to give you a saner animation interface.
9
15
u/agumonkey Oct 16 '18
welcome to epicyclic, Joseph Fourier awaits you
6
Oct 16 '18
do you know any good books on epicycles?
13
u/tomekanco Oct 16 '18
Haven't read into the details but here are some primers:
Mathologer: Epicycles, complex Fourier series and Homer Simpson's orbit
3Blue1Brown: But what is the Fourier Transform? A visual introduction.
4
5
3
9
u/12mh Oct 16 '18
What library did you use for the animation?
20
Oct 16 '18
i used cairo to output to png, then i made the gif using Gimp
8
u/pvc Oct 16 '18
Take a look at http://arcade.academy as another choice if you want to do visualization.
10
u/not_perfect_yet Oct 16 '18
:P please do it again and up the frame rate. That hurts.
6
Oct 16 '18 edited Oct 16 '18
yeah i have it at 100 but the code is built to handle any framerate. i was worried it would get too unwieldy.
edit: correction i have the animation at 100 frames and the frame rate is 25 fps
3
u/proverbialbunny Data Scientist Oct 16 '18
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.
2
0
3
u/logicallyzany Oct 16 '18
How long have you been doing Python and/or programming?
3
Oct 16 '18
Off and on. Never too committed. Just as a hobby. Bought the big O'Reilly book and just browsed through it whenever I had the chance.
1
112
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.
4
u/lucas123500 Oct 17 '18
First comment I have ever saved on Reddit.
1
u/benrules2 Oct 17 '18
That is awesome, thanks! Feel free to ping me if you get stuck on anything, I'm more active than I should be on here.
2
u/lucas123500 Oct 17 '18
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!
1
1
1
1
1
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
Oct 17 '18
Is it telling you you need the build tools?
My Cairo didn’t load from pip. I had to download a package from https://www.lfd.uci.edu/~gohlke/pythonlibs/
1
u/ciggs_ftw Oct 17 '18
yes i have installed visual studio c++ and now i gues this error
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2017\\Community\\VC\\Tools\\MSVC\\14.15.26726\\bin\\HostX86\\x86\\cl.exe' failed with exit status 21
Oct 17 '18
I have no idea what that is.
1
u/ciggs_ftw Oct 17 '18
how you got Cairo to install?
2
Oct 17 '18
I downloaded the package from the site I linked.
1
u/ciggs_ftw Oct 17 '18
can you please tell me which package you dl? I tried downloading a package from there and install the file using pip but got a different error. :/
1
0
Oct 19 '18
[deleted]
1
u/ciggs_ftw Oct 19 '18
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?
1
1
u/winner_godson codemaniac Oct 18 '18
Any tutorial on this.
2
Oct 18 '18
Not currently but i will once I get it more easy to understand and use
1
u/winner_godson codemaniac Oct 18 '18
Okay... I check the net. There are not much. And the documentation is not informative.
2
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/CallumVH Oct 23 '18
Surely you would need a few hundred frames as this GIF look like 60fps?
1
Oct 23 '18
You can set it to 240 and get a 4 second gif at 60 FPS.
An updated, cleaner script is available here: https://github.com/heysoose/Shades
2
1
1
1
1
1
1
1
1
1
1
1
1
1
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
1
1
1
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
1
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
0
Oct 17 '18
Hmmm, the Earth is flat.
1
u/MrNotSoRight Oct 17 '18
It's flat in the animation too, I'm sure the poster could have easily made it a 3D oblate spheroid if he believed it would be more accurate...
-1
-1
0
Oct 17 '18
[deleted]
1
Oct 17 '18
Currently it only does the Epicycle model. But gravity will come soon enough. I have to read more about it. 😆
1
0
1
Oct 17 '18
[removed] — view removed comment
1
Oct 17 '18
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