-
Notifications
You must be signed in to change notification settings - Fork 0
/
streamlit_app.py
305 lines (224 loc) · 7.99 KB
/
streamlit_app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
import streamlit as st
import matplotlib.pyplot as plt
import numpy as np
from astropy import units as u
from poliastro.bodies import Earth, Mars, Sun
from poliastro.twobody import Orbit
from datetime import datetime
import matplotlib as mpl
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import io
import requests
st.set_page_config(layout="wide")
st.title('太陽系天體軌道模擬展示')
#st.info('brbrbr~~~')
# Define Julian epoch
J2000_EPOCH = datetime(2000, 1, 1, 12) # At the noon of 2000/01/01 UTC
class Planet(object):
""" Defines a planet in the Solar system. """
def __init__(self, a, lambda0, e, I, lon_of_peri, node, T, color='blue', size=20):
"""
Args:
a (float): semi-major axis (AU)
lambda0 (float): mean longitude at epoch (degrees)
e (float): eccentricity
I (float): inclination (degrees)
lon_of_peri (float): longitude of perihelion (degrees)
node (float): longitude of ascending node (degrees)
T (float): orbital period (years)
Keyword args:
color (str): planet color
size (float): planet plot size
"""
self.a = a
self.lambda0 = lambda0
self.e = e
self.I = I
self.lon_of_peri = lon_of_peri
self.node = node
self.T = T
self.color = color
self.size = size
# Mean orbital angular velocity, in radians per year
self.n = 2*np.pi/self.T
def getPosition(self, t):
""" Returns the planet's position in a given time.
Args:
t (datetime): a point in time of the planet's orbit
"""
E = self.solveForE(t)
x, y, z = orbitalElements2Cartesian(self.a, self.e, self.I, self.lon_of_peri - self.node, self.node, E)
return x, y, z
def solveForE(self, t, E=0, n=15):
""" Find the eccentric anomaly using the iterative method.
Args:
t (float): a point in time of the planet's orbit (years from epoch)
Keyword args:
E (float): initial value of the eccentric anomaly for iteration
n (int): number of iterations
"""
# Time of perihelion passage
tau = np.radians(self.lon_of_peri - self.lambda0)/self.n
# Mean anomaly
M = self.n*(t-tau)
def f(E, e, M):
return M + e*np.sin(E)
# Solve for eccentric anomaly using the iterative method
for i in range(n):
E = f(E, self.e, M)
return E
def plotPlanet(self, ax, time):
""" Plot the planet and its orbit on a 3D plot.
Args:
ax (matplotlib object): 3D plot object
time (float): years from J2000.0 epoch
"""
# Eccentric anomaly (all ranges)
E = np.linspace(-np.pi, np.pi, 100)
# Plot the planet
x, y, z = self.getPosition(time)
ax.scatter(x, y, z, c=self.color, s=self.size, edgecolors='face')
# Plot planet's orbit
x, y, z = orbitalElements2Cartesian(self.a, self.e, self.I, self.lon_of_peri - self.node,
self.node, E)
ax.plot(x, y, z, color=self.color, linestyle='-', linewidth=0.5)
def orbitalElements2Cartesian(a, e, I, peri, node, E):
""" Convert orbital elements to Cartesian coordinates in the Solar System.
Args:
a (float): semi-major axis (AU)
e (float): eccentricity
I (float): inclination (degrees)
peri (float): longitude of perihelion (degrees)
node (float): longitude of ascending node (degrees)
E (float): eccentric anomaly (radians)
"""
# Check if the orbit is parabolic or hyperbolic
if e >=1:
e = 0.99999999
# Convert degrees to radians
I, peri, node = map(np.radians, [I, peri, node])
# True anomaly
theta = 2*np.arctan(np.sqrt((1.0 + e)/(1.0 - e))*np.tan(E/2.0))
# Distance from the Sun to the poin on orbit
r = a*(1.0 - e*np.cos(E))
# Cartesian coordinates
x = r*(np.cos(node)*np.cos(peri + theta) - np.sin(node)*np.sin(peri + theta)*np.cos(I))
y = r*(np.sin(node)*np.cos(peri + theta) + np.cos(node)*np.sin(peri + theta)*np.cos(I))
z = r*np.sin(peri + theta)*np.sin(I)
return x, y, z
def plotPlanets(ax, time):
""" Plots the Solar system planets.
Args:
ax (matplotlib object): 3D plot object
time (float): years from J2000.0 epoch
"""
# Generate Planets (J2000.0 epoch)
mercury = Planet(0.3871, 252.25, 0.20564, 7.006, 77.46, 48.34, 0.241, color='#ecd67e', size=10)
venus = Planet(0.7233, 181.98, 0.00676, 3.398, 131.77, 76.67, 0.615, color='#e7d520', size=30)
earth = Planet(1.0000, 100.47, 0.01673, 0.000, 102.93, 0, 1.000, color='#1c7ff2', size=30)
mars = Planet(1.5237, 355.43, 0.09337, 1.852, 336.08, 49.71, 1.881, color='#cc1e2c', size=20)
jupiter = Planet(5.2025, 34.33, 0.04854, 1.299, 14.27, 100.29, 11.87, color='#D8CA9D', size=55)
saturn = Planet(9.5415, 50.08, 0.05551, 2.494, 92.86, 113.64, 29.47, color='#ead6b8', size=45)
uranus = Planet(19.188, 314.20, 0.04686, 0.773, 172.43, 73.96, 84.05, color='#287290', size=40)
neptune = Planet(30.070, 304.22, 0.00895, 1.770, 46.68, 131.79, 164.9, color='#70B7BA', size=40)
planets = [mercury, venus, earth, mars, jupiter, saturn, uranus, neptune]
# Plot the Sun
ax.scatter(0, 0, 0, c='yellow', s=100)
# Plot planets
for planet in planets:
planet.plotPlanet(ax, time)
def plotOrbits(orb_elements, time, orbit_colors=None, plot_planets=True):
""" Plot the given orbits in the solar system.
Args:
orb_elements (ndarray of floats): 2D numpy array with orbits to plot, each entry contains:
a - Semimajor axis (AU)
e - Eccentricity
I - Inclination (degrees)
peri - Argument of perihelion (degrees)
node - Ascending node (degrees)
ax (matplotlib object): 3D plot object
time (datetime): datetime object of the time of the desired planet positions
"""
# Check the shape of given orbital elements array
if len(orb_elements.shape) < 2:
orb_elements = np.array([orb_elements])
# Calculate the time difference from epoch to the given time (in years)
julian = (time - J2000_EPOCH)
years_diff = (julian.days + (julian.seconds + julian.microseconds/1000000.0) /86400.0)/365.2425
# Setup the plot
fig = plt.figure()
ax = fig.gca(projection='3d', facecolor='black')
# Set a constant aspect ratio
ax.set_aspect('auto', adjustable='box')
# Hide the axes
ax.set_axis_off()
ax.grid(b=False)
# Plot the solar system planets
if plot_planets:
plotPlanets(ax, years_diff)
# Eccentric anomaly (full range)
E = np.linspace(-np.pi, np.pi, 100)
# Plot the given orbits
for i, orbit in enumerate(orb_elements):
a, e, I, peri, node = orbit
# Take extra steps in E if the orbit is very large
if a > 50:
E = np.linspace(-np.pi, np.pi, int((a/20.0)*100))
# Get the orbit in cartesian space
x, y, z = orbitalElements2Cartesian(a, e, I, peri, node, E)
# Check if the colors orbit are provided
if orbit_colors:
color = orbit_colors[i]
else:
# Set to default
color = '#32CD32'
# Plot orbits
ax.plot(x, y, z, c=color)
ax.legend()
# Add limits (in AU)
ax.set_xlim3d(-a-2,a+2)
ax.set_ylim3d(-a-2,a+2)
ax.set_zlim3d(-a-2,a+2)
ax.view_init(elev, azim)
plt.tight_layout()
return fig
mode = st.sidebar.radio(
"模式",
('輸入參數', '天體搜尋'))
azim = st.sidebar.slider("方位角", value=0, min_value=0, max_value=360, step=30)
elev = st.sidebar.slider("仰角", value=30, min_value=0, max_value=90, step=10)
# Time now
time = datetime.now()
if mode == '天體搜尋':
sstr = st.sidebar.text_input('搜尋天體', '')
sbdb = {}
r = requests.get ("https://ssd-api.jpl.nasa.gov/sbdb.api?sstr=" + sstr)
dicts = r.json()
try:
for i in dicts['orbit']['elements']:
sbdb[i['label']] = float(i['value'])
except:
st.error('查無天體資料!')
st.stop()
a = sbdb['a']
e = sbdb['e']
i = sbdb['i']
peri = sbdb['peri']
node = sbdb['node']
else:
a = st.sidebar.slider('半長軸 (a) (AU)', value=1.0, min_value=0.0, max_value=100.0)
e = st.sidebar.slider('離心率 (e)', value=0.0, min_value=0.0, max_value=0.99)
i = st.sidebar.slider('軌道傾角 (i)', value=0, min_value=0, max_value=180)
peri = st.sidebar.slider('近日點輻角 (ω)', value=0, min_value=0, max_value=90)
node = st.sidebar.slider('升交點黃經 (Ω)', value=0, min_value=0, max_value=180)
# Define orbits to plot
# a, e, incl, peri, node
orb_elements = np.array([
[a, e, i, peri, node]
])
# Plot orbits
fig = plotOrbits(orb_elements, time)
st.pyplot(fig)