Computational Astrophysics
Lets get started with the packages
Packages
- pygame is a package for creating 2d games.
- Math package contains all the math functions we would need to simulate physics in the planets
Note from Andre Dias
You may consider using Decimal, instead of floats, for more precise calculation
from decimal import Decimal
Setting Up
We will set up the view area
We start by initializing pygame with init().
The Width and the Height can be as per your wish but It is recommended to stick with the SQUARE shape, i.e. Same Height and Width
Set the caption for your window. This is your Title on the top of the window as shown below.
Basic Visual Elements
- Color values associated with RGB values
- Font will be used to display the orbital values
Planets
In the Class Planet
- AU is Astronomical unit. It is multiplied by 1000 to convert it into meters
- G denotes gravity
- Scale is the zoom of the view of your simulation
- TIMESTEP displays the timeframe of 1 day
Lets add functions
Initialization of variables
- x is x coordinate
- y is y coordinate
- radius is the size of the planet
- color is the hue of the planet
- mass is the value corresponding to the mass of the planet
- Here we are also counting the sun as a planet, so self.sun is False by default to basically say that every other planet is not sun.
- x_vel and y_vel is the Velocity value
Simulating
This function will help us place the planet in the view.
x = self.x * self.SCALE + WIDTH / 2
y = self.y * self.SCALE + HEIGHT / 2
The above line will help us center the visualization in the view.
Orbits
pygame.draw.lines(win, self.color, False, updated_points, 2)
Planets
pygame.draw.circle(win,self.color,(x,y), self.radius)
Physics
With the help of trigonometry we can estimate the position of the planet at different time. Aggregating these positions we would be gifted with the orbit the planet is following. This is the formula which is the core part of the physics in the simulation.
We need to be constantly aware of the forces from other planets and the force of the sun as well.
Velocity
As the velocity would be calculated at multiple instance, we would be appending the information to the orbit to trace the path of the planet.
The orbit will be elliptical as the angle and the distance would be changing making the force to be in negative as well as positive states.
Let’s Add Planets
Sun
Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
Pluto
to drive Neil deGrasse Tyson crazy!
The Final Simulation
The planetary information can be found on NASA site
Full code available on my github
This was based on the video by Tim