r/Python • • Oct 16 '18

I made this with Python. So Proud.

1.8k Upvotes

149 comments sorted by

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

191

u/[deleted] Oct 16 '18

One day I will be god and it will be good

17

u/[deleted] Oct 16 '18

Eli?

4

u/Melkor333 Oct 17 '18

Eru?

2

u/Haldiron Nov 01 '18

No more are you now than an escaped thrall of the Valar, and their chain still awaits you!

2

u/Pehrgryn Oct 17 '18

Try: import divinity

56

u/bitflip Oct 16 '18

Isn't there a library for that?

127

u/writing_from_mars Oct 16 '18

import humanity

52

u/UnholyBlackJesus Oct 16 '18

pip install godMode

13

u/MyNameisGregHai Oct 16 '18 edited Oct 18 '18

pip install -m Christianity

Now it's time to delete all scientific advancements

13

u/__deerlord__ Oct 16 '18

To be fair, even the NT says "question everything". Its the stupid humans that went and mucked it all up.

6

u/UnholyBlackJesus Oct 16 '18

Hey in still a huge newbie, so forgive me, but what does the "-m" mean?

11

u/C0DK Oct 16 '18

there is no "-m" for pip (or pup :P ) but there is for python itself. It is used to run a specific module. so for instance

python3 -m unittest

runs the unit testing framework, which automically looks for tests in the current directory.

from the help text :

-m mod : run library module as a script (terminates option list)

2

u/radiantyellow Oct 17 '18
alias pip=pup

2

u/ForgottenWatchtower Oct 16 '18

python -m SimpleHttpServer 10000

The only thing I use py2 for these days. Well that and occasionally some scapy.

16

u/pvkooten Oct 16 '18

python3 -m http.server 10000

26

u/ForgottenWatchtower Oct 16 '18

And just like that, I've abandoned py2

→ More replies (0)

1

u/UnholyBlackJesus Oct 16 '18

Oh wow, thank you! TIL.

7

u/lemon_tea Oct 16 '18

Shit, the program runs for about 30,000 cycles, then becomes too memory bloated and seg faults the runtime environment.

3

u/atheist_apostate Oct 17 '18

Humanity is a resource hog.

30

u/[deleted] Oct 16 '18

"And make it in a week for $100" - 8/10 clients

1

u/gustavsen Oct 17 '18

A new Aurora implementation?

35

u/OBstaxs Oct 16 '18

Source ?

54

u/[deleted] Oct 16 '18

55

u/Nicksil Oct 16 '18

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.

Thanks for sharing

30

u/[deleted] 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

u/[deleted] Oct 16 '18

same thing, more comments

https://pastebin.com/qyDRBYUM

18

u/ElBroet Oct 17 '18

was expecting the same code with the comment "fuck you" at the top

5

u/Mattho Oct 17 '18

You can use """Docstrings.""" for many of those.

21

u/muntoo R_{μν} - 1/2 R g_{μν} + Λ g_{μν} = 8π T_{μν} Oct 17 '18 edited 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
        # ...

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'].center

Yay!

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_velocity parameter inside CelestialBody?)


See almost-encapsulated code here.

4

u/[deleted] Oct 17 '18

Wow thanks.

3

u/[deleted] 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 = planet

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. ;)

4

u/[deleted] Oct 17 '18

Wow. I’d never have thought of these structures

1

u/[deleted] Oct 17 '18

Ok thats awesome, thanks for helping!

8

u/quotemycode Oct 16 '18

Line 24 last constant should be math.tau (added to python in 2016). 2*pi is wrong.

5

u/[deleted] Oct 16 '18

It’s wrong in a readability/good code standards sense?

21

u/Trippyy_420 Oct 16 '18

Tau = 2pi

He's havin a giggle.

6

u/[deleted] Oct 16 '18

Ah

8

u/_DirtyHarry_ Oct 16 '18

2*pi is better, nobody actually uses tau.

2

u/[deleted] 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

u/[deleted] Oct 17 '18

I might do something like that in the future once I start getting it more structured.

-1

u/mihird9 Oct 16 '18

Does this work on Python 2.7?

2

u/[deleted] Oct 16 '18

in 2.7 maybe not.

Edit: I'm in 3.7.0

24

u/Vervoltz Oct 16 '18

What are u doing? Everybody knows planets should rotate counter-clockwise! Redo it immediately, please. Wink wink.

13

u/[deleted] Oct 16 '18

You're right I need to add in how to control the direction of the orbit, thank you.

29

u/[deleted] Oct 16 '18

What if this is the view from "below".

29

u/Fiskepudding Oct 16 '18

What, are you an Australian or something?

5

u/nemom Oct 17 '18

No... You can tell by his accent.

1

u/jabies Oct 17 '18

You just need to say reverse please

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

u/[deleted] Oct 16 '18

Yeah, the gimp interface is lacking. I'll look into this.

15

u/agumonkey Oct 16 '18

welcome to epicyclic, Joseph Fourier awaits you

6

u/[deleted] 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

u/[deleted] Oct 16 '18

Thank you

3

u/agumonkey Oct 16 '18

that's one topic I know no books about, ask quora or r/maths :)

2

u/[deleted] Oct 16 '18

sure thing.

9

u/12mh Oct 16 '18

What library did you use for the animation?

20

u/[deleted] 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

u/[deleted] 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

u/[deleted] Oct 16 '18

cool cool. yeah you're totally right

0

u/[deleted] Oct 16 '18

[deleted]

8

u/[deleted] Oct 16 '18

doing it now

7

u/theng Oct 16 '18

yay :3

3

u/logicallyzany Oct 16 '18

How long have you been doing Python and/or programming?

3

u/[deleted] 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

u/rptr87 Oct 17 '18

Book link?

112

u/Dustin- Oct 16 '18

I think you did import antigravity backwards.

24

u/mr1337 Oct 16 '18
import gravity

4

u/timmermans_ Oct 17 '18

YtIvArGiTnA tRoPmI

14

u/[deleted] Oct 16 '18

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

u/[deleted] Oct 19 '18 edited Oct 20 '18

This project now has a github. https://github.com/heysoose/Shades

1

u/winner_godson codemaniac Nov 21 '18

The link is not valid. Can you please share the code

1

u/BambiAnnie Oct 16 '18

Great work! :)

1

u/[deleted] Oct 16 '18

Thank you!

1

u/tycooperaow 3.9 Oct 17 '18

What did you use for the graphical interface?

1

u/[deleted] Oct 17 '18

pycairo.

1

u/snahor Oct 17 '18

I'm so dumb, at first I thought it was a pre-loader.

1

u/[deleted] Oct 17 '18

It could be that too. I see planets or people. Could be lots of stuff.

1

u/happyskydiver Oct 17 '18

Can you change it to an ellipse?

1

u/[deleted] Oct 17 '18

Not currently.

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/[deleted] 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 2    

1

u/[deleted] Oct 17 '18

I have no idea what that is.

1

u/ciggs_ftw Oct 17 '18

how you got Cairo to install?

2

u/[deleted] 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

u/[deleted] Oct 17 '18

Search for a tutorial on how to install packages.

0

u/[deleted] 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

u/lilliane99 Oct 17 '18

Can you kindly provide the source code or at least the algorithm?

2

u/[deleted] Oct 17 '18

I have in the comments. :)

1

u/winner_godson codemaniac Oct 18 '18

Any tutorial on this.

2

u/[deleted] 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

u/[deleted] Oct 18 '18

Save this post. I'll let you know.

1

u/winner_godson codemaniac Oct 18 '18

Definitely I will.

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

u/[deleted] 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

u/CallumVH Oct 23 '18

Oh thank you so much, that makes sense.

1

u/0x75 Oct 16 '18

I like it.

Now play with Processing to do the same.

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/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/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/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

u/NikkoTheGreeko Oct 17 '18

Everyone knows this

-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]

1

u/[deleted] Oct 17 '18

Currently it only does the Epicycle model. But gravity will come soon enough. I have to read more about it. 😆

1

u/[deleted] Oct 17 '18

looks awesome either way! Congrats! I'm just starting my Python journey :D

0

u/[deleted] Oct 18 '18

[deleted]

1

u/[deleted] Oct 18 '18

Thank you

1

u/[deleted] Oct 17 '18

[removed] — view removed comment

1

u/[deleted] 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.