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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import requests
|
3 |
+
import pandas as pd
|
4 |
+
import plotly.express as px
|
5 |
+
from datetime import datetime, timedelta
|
6 |
+
|
7 |
+
# App title and description
|
8 |
+
st.title("🌠 NASA Near-Earth Objects Tracker")
|
9 |
+
st.markdown("""
|
10 |
+
This application uses NASA's NeoWs (Near Earth Object Web Service) API to retrieve and visualize
|
11 |
+
information about asteroids and other near-Earth objects.
|
12 |
+
""")
|
13 |
+
|
14 |
+
# API Configuration
|
15 |
+
NASA_API_URL = "https://api.nasa.gov/neo/rest/v1/feed"
|
16 |
+
API_KEY = st.sidebar.text_input("NASA API Key", value="NASA_API_KEY", type="password")
|
17 |
+
|
18 |
+
# Date selection
|
19 |
+
st.sidebar.header("Search Parameters")
|
20 |
+
today = datetime.now()
|
21 |
+
default_start_date = today.date()
|
22 |
+
default_end_date = (today + timedelta(days=7)).date()
|
23 |
+
|
24 |
+
start_date = st.sidebar.date_input("Start Date", default_start_date)
|
25 |
+
end_date = st.sidebar.date_input("End Date", default_end_date)
|
26 |
+
|
27 |
+
# Validate date range
|
28 |
+
date_diff = (end_date - start_date).days
|
29 |
+
if date_diff > 7:
|
30 |
+
st.warning("⚠️ NASA API limits date range to 7 days or less. Adjusting to a 7-day period.")
|
31 |
+
end_date = start_date + timedelta(days=7)
|
32 |
+
|
33 |
+
# Function to fetch data from NASA API
|
34 |
+
def fetch_asteroid_data(start_date, end_date, api_key):
|
35 |
+
params = {
|
36 |
+
"start_date": start_date.strftime("%Y-%m-%d"),
|
37 |
+
"end_date": end_date.strftime("%Y-%m-%d"),
|
38 |
+
"api_key": api_key
|
39 |
+
}
|
40 |
+
|
41 |
+
with st.spinner("Fetching asteroid data from NASA..."):
|
42 |
+
try:
|
43 |
+
response = requests.get(NASA_API_URL, params=params)
|
44 |
+
response.raise_for_status() # Raise an exception for HTTP errors
|
45 |
+
return response.json()
|
46 |
+
except requests.exceptions.RequestException as e:
|
47 |
+
st.error(f"Error accessing NASA API: {e}")
|
48 |
+
return None
|
49 |
+
|
50 |
+
# Search button
|
51 |
+
if st.sidebar.button("Search Asteroids"):
|
52 |
+
# Fetch data
|
53 |
+
data = fetch_asteroid_data(start_date, end_date, API_KEY)
|
54 |
+
|
55 |
+
if data:
|
56 |
+
# Store data in session state
|
57 |
+
st.session_state.asteroid_data = data
|
58 |
+
st.session_state.searched = True
|
59 |
+
else:
|
60 |
+
st.error("Failed to fetch asteroid data. Please check your API key and try again.")
|
61 |
+
|
62 |
+
# Display results if search was performed
|
63 |
+
if 'searched' in st.session_state and st.session_state.searched:
|
64 |
+
data = st.session_state.asteroid_data
|
65 |
+
|
66 |
+
# Extract asteroid count
|
67 |
+
element_count = data.get('element_count', 0)
|
68 |
+
st.success(f"Found {element_count} near-Earth objects between {start_date} and {end_date}")
|
69 |
+
|
70 |
+
# Process and organize data
|
71 |
+
neo_data = data.get('near_earth_objects', {})
|
72 |
+
|
73 |
+
all_asteroids = []
|
74 |
+
for date, asteroids in neo_data.items():
|
75 |
+
for asteroid in asteroids:
|
76 |
+
asteroid_info = {
|
77 |
+
'id': asteroid['id'],
|
78 |
+
'name': asteroid['name'],
|
79 |
+
'date': date,
|
80 |
+
'diameter_min_km': asteroid['estimated_diameter']['kilometers']['estimated_diameter_min'],
|
81 |
+
'diameter_max_km': asteroid['estimated_diameter']['kilometers']['estimated_diameter_max'],
|
82 |
+
'is_hazardous': asteroid['is_potentially_hazardous_asteroid'],
|
83 |
+
'close_approach_date': asteroid['close_approach_data'][0]['close_approach_date'],
|
84 |
+
'miss_distance_km': float(asteroid['close_approach_data'][0]['miss_distance']['kilometers']),
|
85 |
+
'relative_velocity_kph': float(asteroid['close_approach_data'][0]['relative_velocity']['kilometers_per_hour'])
|
86 |
+
}
|
87 |
+
all_asteroids.append(asteroid_info)
|
88 |
+
|
89 |
+
# Convert to DataFrame for easier manipulation
|
90 |
+
df = pd.DataFrame(all_asteroids)
|
91 |
+
|
92 |
+
# Add average diameter column
|
93 |
+
df['avg_diameter_km'] = (df['diameter_min_km'] + df['diameter_max_km']) / 2
|
94 |
+
|
95 |
+
# Display summary statistics
|
96 |
+
st.header("Summary Statistics")
|
97 |
+
col1, col2, col3 = st.columns(3)
|
98 |
+
|
99 |
+
with col1:
|
100 |
+
st.metric("Total Asteroids", len(df))
|
101 |
+
|
102 |
+
with col2:
|
103 |
+
hazardous_count = df['is_hazardous'].sum()
|
104 |
+
st.metric("Potentially Hazardous", f"{hazardous_count} ({hazardous_count/len(df)*100:.1f}%)")
|
105 |
+
|
106 |
+
with col3:
|
107 |
+
st.metric("Avg. Size", f"{df['avg_diameter_km'].mean():.2f} km")
|
108 |
+
|
109 |
+
# Visualizations
|
110 |
+
st.header("Visualizations")
|
111 |
+
|
112 |
+
viz_tab1, viz_tab2 = st.tabs(["Size Distribution", "Miss Distance"])
|
113 |
+
|
114 |
+
with viz_tab1:
|
115 |
+
# Size distribution chart
|
116 |
+
fig1 = px.histogram(
|
117 |
+
df,
|
118 |
+
x="avg_diameter_km",
|
119 |
+
color="is_hazardous",
|
120 |
+
title="Size Distribution of Near-Earth Objects",
|
121 |
+
labels={"avg_diameter_km": "Average Diameter (km)", "is_hazardous": "Potentially Hazardous"},
|
122 |
+
color_discrete_map={True: "red", False: "green"}
|
123 |
+
)
|
124 |
+
st.plotly_chart(fig1, use_container_width=True)
|
125 |
+
|
126 |
+
with viz_tab2:
|
127 |
+
# Miss distance scatter plot
|
128 |
+
fig2 = px.scatter(
|
129 |
+
df,
|
130 |
+
x="miss_distance_km",
|
131 |
+
y="avg_diameter_km",
|
132 |
+
color="is_hazardous",
|
133 |
+
size="relative_velocity_kph",
|
134 |
+
hover_name="name",
|
135 |
+
title="Miss Distance vs. Size (with velocity)",
|
136 |
+
labels={
|
137 |
+
"miss_distance_km": "Miss Distance (km)",
|
138 |
+
"avg_diameter_km": "Average Diameter (km)",
|
139 |
+
"is_hazardous": "Potentially Hazardous",
|
140 |
+
"relative_velocity_kph": "Velocity (km/h)"
|
141 |
+
},
|
142 |
+
color_discrete_map={True: "red", False: "green"}
|
143 |
+
)
|
144 |
+
fig2.update_layout(xaxis_type="log")
|
145 |
+
st.plotly_chart(fig2, use_container_width=True)
|
146 |
+
|
147 |
+
# Detailed asteroid data
|
148 |
+
st.header("Detailed Asteroid Data")
|
149 |
+
|
150 |
+
# Filter options
|
151 |
+
st.subheader("Filters")
|
152 |
+
col1, col2 = st.columns(2)
|
153 |
+
|
154 |
+
with col1:
|
155 |
+
show_hazardous = st.checkbox("Show only hazardous asteroids", False)
|
156 |
+
|
157 |
+
with col2:
|
158 |
+
size_threshold = st.slider("Minimum size (km)", 0.0, max(df['avg_diameter_km']), 0.0, 0.01)
|
159 |
+
|
160 |
+
# Apply filters
|
161 |
+
filtered_df = df.copy()
|
162 |
+
if show_hazardous:
|
163 |
+
filtered_df = filtered_df[filtered_df['is_hazardous'] == True]
|
164 |
+
|
165 |
+
filtered_df = filtered_df[filtered_df['avg_diameter_km'] >= size_threshold]
|
166 |
+
|
167 |
+
# Sort options
|
168 |
+
sort_by = st.selectbox(
|
169 |
+
"Sort by",
|
170 |
+
["close_approach_date", "name", "avg_diameter_km", "miss_distance_km", "relative_velocity_kph"]
|
171 |
+
)
|
172 |
+
|
173 |
+
sort_order = st.radio("Sort order", ["Ascending", "Descending"], horizontal=True)
|
174 |
+
|
175 |
+
# Apply sorting
|
176 |
+
ascending = sort_order == "Ascending"
|
177 |
+
filtered_df = filtered_df.sort_values(by=sort_by, ascending=ascending)
|
178 |
+
|
179 |
+
# Display dataframe with key information
|
180 |
+
display_df = filtered_df[[
|
181 |
+
'name', 'close_approach_date', 'avg_diameter_km',
|
182 |
+
'miss_distance_km', 'relative_velocity_kph', 'is_hazardous'
|
183 |
+
]].rename(columns={
|
184 |
+
'name': 'Name',
|
185 |
+
'close_approach_date': 'Approach Date',
|
186 |
+
'avg_diameter_km': 'Diameter (km)',
|
187 |
+
'miss_distance_km': 'Miss Distance (km)',
|
188 |
+
'relative_velocity_kph': 'Velocity (km/h)',
|
189 |
+
'is_hazardous': 'Hazardous'
|
190 |
+
})
|
191 |
+
|
192 |
+
st.dataframe(display_df, use_container_width=True)
|
193 |
+
|
194 |
+
# Asteroid details expander
|
195 |
+
st.subheader("Individual Asteroid Details")
|
196 |
+
|
197 |
+
# Allow user to select an asteroid for detailed view
|
198 |
+
selected_asteroid = st.selectbox("Select an asteroid", filtered_df['name'].tolist())
|
199 |
+
|
200 |
+
if selected_asteroid:
|
201 |
+
asteroid_details = filtered_df[filtered_df['name'] == selected_asteroid].iloc[0]
|
202 |
+
|
203 |
+
st.subheader(f"🌑 {selected_asteroid}")
|
204 |
+
|
205 |
+
col1, col2 = st.columns(2)
|
206 |
+
|
207 |
+
with col1:
|
208 |
+
st.write("**ID:**", asteroid_details['id'])
|
209 |
+
st.write("**Approach Date:**", asteroid_details['close_approach_date'])
|
210 |
+
st.write("**Hazardous:**", "Yes ⚠️" if asteroid_details['is_hazardous'] else "No ✓")
|
211 |
+
|
212 |
+
with col2:
|
213 |
+
st.write("**Diameter Range:**", f"{asteroid_details['diameter_min_km']:.3f} - {asteroid_details['diameter_max_km']:.3f} km")
|
214 |
+
st.write("**Miss Distance:**", f"{asteroid_details['miss_distance_km']:,.0f} km")
|
215 |
+
st.write("**Relative Velocity:**", f"{asteroid_details['relative_velocity_kph']:,.0f} km/h")
|
216 |
+
|
217 |
+
# Create a gauge-like visualization for the hazard level
|
218 |
+
hazard_level = 0
|
219 |
+
if asteroid_details['is_hazardous']:
|
220 |
+
# Calculate hazard level based on size and miss distance
|
221 |
+
size_factor = min(asteroid_details['avg_diameter_km'] / 0.5, 1) # Normalize by 0.5km
|
222 |
+
distance_factor = min(1000000 / asteroid_details['miss_distance_km'], 1) # Normalize by 1M km
|
223 |
+
hazard_level = (size_factor * 0.7 + distance_factor * 0.3) * 100
|
224 |
+
|
225 |
+
st.progress(int(hazard_level), text=f"Relative Hazard Level: {hazard_level:.1f}%")
|
226 |
+
|
227 |
+
# Add some context about the asteroid
|
228 |
+
st.write("### Context")
|
229 |
+
if hazard_level > 70:
|
230 |
+
st.warning("This asteroid is classified as potentially hazardous and is relatively large and close.")
|
231 |
+
elif hazard_level > 40:
|
232 |
+
st.info("This asteroid is classified as potentially hazardous but poses minimal risk at this time.")
|
233 |
+
else:
|
234 |
+
st.success("This asteroid is not considered hazardous and poses no risk to Earth.")
|
235 |
+
|
236 |
+
# Add information about the NASA API
|
237 |
+
st.sidebar.markdown("---")
|
238 |
+
st.sidebar.markdown("""
|
239 |
+
### About NASA NeoWs API
|
240 |
+
The [Near Earth Object Web Service](https://api.nasa.gov) is a RESTful web service for near earth asteroid information.
|
241 |
+
This API provides data on asteroids based on their closest approach date to Earth.
|
242 |
+
|
243 |
+
To get your own API key, visit [api.nasa.gov](https://api.nasa.gov).
|
244 |
+
""")
|
245 |
+
|
246 |
+
# Add deployment instructions
|
247 |
+
st.sidebar.markdown("---")
|
248 |
+
st.sidebar.markdown("""
|
249 |
+
### Deployment Instructions
|
250 |
+
1. Save this code as `app.py`
|
251 |
+
2. Create `requirements.txt` with:
|
252 |
+
```
|
253 |
+
streamlit
|
254 |
+
requests
|
255 |
+
pandas
|
256 |
+
plotly
|
257 |
+
```
|
258 |
+
3. Upload to Hugging Face Spaces
|
259 |
+
""")
|