File size: 10,006 Bytes
3f6deab
d207c48
3f6deab
 
 
 
 
 
 
 
 
 
 
 
 
 
d207c48
 
 
 
 
 
 
3f6deab
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import os
import requests
import pandas as pd
import plotly.express as px
from datetime import datetime, timedelta

# App title and description
st.title("🌠 NASA Near-Earth Objects Tracker")
st.markdown("""
This application uses NASA's NeoWs (Near Earth Object Web Service) API to retrieve and visualize 
information about asteroids and other near-Earth objects.
""")

# API Configuration
NASA_API_URL = "https://api.nasa.gov/neo/rest/v1/feed"
import os  # Ensure this is at the top

API_KEY = os.getenv("NASA_API_KEY")
if not API_KEY:
    st.error("🚨 NASA_API_KEY environment variable is not set.")
    st.stop()


# Date selection
st.sidebar.header("Search Parameters")
today = datetime.now()
default_start_date = today.date()
default_end_date = (today + timedelta(days=7)).date()

start_date = st.sidebar.date_input("Start Date", default_start_date)
end_date = st.sidebar.date_input("End Date", default_end_date)

# Validate date range
date_diff = (end_date - start_date).days
if date_diff > 7:
    st.warning("⚠️ NASA API limits date range to 7 days or less. Adjusting to a 7-day period.")
    end_date = start_date + timedelta(days=7)

# Function to fetch data from NASA API
def fetch_asteroid_data(start_date, end_date, api_key):
    params = {
        "start_date": start_date.strftime("%Y-%m-%d"),
        "end_date": end_date.strftime("%Y-%m-%d"),
        "api_key": api_key
    }
    
    with st.spinner("Fetching asteroid data from NASA..."):
        try:
            response = requests.get(NASA_API_URL, params=params)
            response.raise_for_status()  # Raise an exception for HTTP errors
            return response.json()
        except requests.exceptions.RequestException as e:
            st.error(f"Error accessing NASA API: {e}")
            return None

# Search button
if st.sidebar.button("Search Asteroids"):
    # Fetch data
    data = fetch_asteroid_data(start_date, end_date, API_KEY)
    
    if data:
        # Store data in session state
        st.session_state.asteroid_data = data
        st.session_state.searched = True
    else:
        st.error("Failed to fetch asteroid data. Please check your API key and try again.")

# Display results if search was performed
if 'searched' in st.session_state and st.session_state.searched:
    data = st.session_state.asteroid_data
    
    # Extract asteroid count
    element_count = data.get('element_count', 0)
    st.success(f"Found {element_count} near-Earth objects between {start_date} and {end_date}")
    
    # Process and organize data
    neo_data = data.get('near_earth_objects', {})
    
    all_asteroids = []
    for date, asteroids in neo_data.items():
        for asteroid in asteroids:
            asteroid_info = {
                'id': asteroid['id'],
                'name': asteroid['name'],
                'date': date,
                'diameter_min_km': asteroid['estimated_diameter']['kilometers']['estimated_diameter_min'],
                'diameter_max_km': asteroid['estimated_diameter']['kilometers']['estimated_diameter_max'],
                'is_hazardous': asteroid['is_potentially_hazardous_asteroid'],
                'close_approach_date': asteroid['close_approach_data'][0]['close_approach_date'],
                'miss_distance_km': float(asteroid['close_approach_data'][0]['miss_distance']['kilometers']),
                'relative_velocity_kph': float(asteroid['close_approach_data'][0]['relative_velocity']['kilometers_per_hour'])
            }
            all_asteroids.append(asteroid_info)
    
    # Convert to DataFrame for easier manipulation
    df = pd.DataFrame(all_asteroids)
    
    # Add average diameter column
    df['avg_diameter_km'] = (df['diameter_min_km'] + df['diameter_max_km']) / 2
    
    # Display summary statistics
    st.header("Summary Statistics")
    col1, col2, col3 = st.columns(3)
    
    with col1:
        st.metric("Total Asteroids", len(df))
    
    with col2:
        hazardous_count = df['is_hazardous'].sum()
        st.metric("Potentially Hazardous", f"{hazardous_count} ({hazardous_count/len(df)*100:.1f}%)")
    
    with col3:
        st.metric("Avg. Size", f"{df['avg_diameter_km'].mean():.2f} km")
    
    # Visualizations
    st.header("Visualizations")
    
    viz_tab1, viz_tab2 = st.tabs(["Size Distribution", "Miss Distance"])
    
    with viz_tab1:
        # Size distribution chart
        fig1 = px.histogram(
            df, 
            x="avg_diameter_km", 
            color="is_hazardous",
            title="Size Distribution of Near-Earth Objects",
            labels={"avg_diameter_km": "Average Diameter (km)", "is_hazardous": "Potentially Hazardous"},
            color_discrete_map={True: "red", False: "green"}
        )
        st.plotly_chart(fig1, use_container_width=True)
    
    with viz_tab2:
        # Miss distance scatter plot
        fig2 = px.scatter(
            df, 
            x="miss_distance_km", 
            y="avg_diameter_km",
            color="is_hazardous",
            size="relative_velocity_kph",
            hover_name="name",
            title="Miss Distance vs. Size (with velocity)",
            labels={
                "miss_distance_km": "Miss Distance (km)",
                "avg_diameter_km": "Average Diameter (km)",
                "is_hazardous": "Potentially Hazardous",
                "relative_velocity_kph": "Velocity (km/h)"
            },
            color_discrete_map={True: "red", False: "green"}
        )
        fig2.update_layout(xaxis_type="log")
        st.plotly_chart(fig2, use_container_width=True)
    
    # Detailed asteroid data
    st.header("Detailed Asteroid Data")
    
    # Filter options
    st.subheader("Filters")
    col1, col2 = st.columns(2)
    
    with col1:
        show_hazardous = st.checkbox("Show only hazardous asteroids", False)
    
    with col2:
        size_threshold = st.slider("Minimum size (km)", 0.0, max(df['avg_diameter_km']), 0.0, 0.01)
    
    # Apply filters
    filtered_df = df.copy()
    if show_hazardous:
        filtered_df = filtered_df[filtered_df['is_hazardous'] == True]
    
    filtered_df = filtered_df[filtered_df['avg_diameter_km'] >= size_threshold]
    
    # Sort options
    sort_by = st.selectbox(
        "Sort by", 
        ["close_approach_date", "name", "avg_diameter_km", "miss_distance_km", "relative_velocity_kph"]
    )
    
    sort_order = st.radio("Sort order", ["Ascending", "Descending"], horizontal=True)
    
    # Apply sorting
    ascending = sort_order == "Ascending"
    filtered_df = filtered_df.sort_values(by=sort_by, ascending=ascending)
    
    # Display dataframe with key information
    display_df = filtered_df[[
        'name', 'close_approach_date', 'avg_diameter_km', 
        'miss_distance_km', 'relative_velocity_kph', 'is_hazardous'
    ]].rename(columns={
        'name': 'Name',
        'close_approach_date': 'Approach Date',
        'avg_diameter_km': 'Diameter (km)',
        'miss_distance_km': 'Miss Distance (km)',
        'relative_velocity_kph': 'Velocity (km/h)',
        'is_hazardous': 'Hazardous'
    })
    
    st.dataframe(display_df, use_container_width=True)
    
    # Asteroid details expander
    st.subheader("Individual Asteroid Details")
    
    # Allow user to select an asteroid for detailed view
    selected_asteroid = st.selectbox("Select an asteroid", filtered_df['name'].tolist())
    
    if selected_asteroid:
        asteroid_details = filtered_df[filtered_df['name'] == selected_asteroid].iloc[0]
        
        st.subheader(f"πŸŒ‘ {selected_asteroid}")
        
        col1, col2 = st.columns(2)
        
        with col1:
            st.write("**ID:**", asteroid_details['id'])
            st.write("**Approach Date:**", asteroid_details['close_approach_date'])
            st.write("**Hazardous:**", "Yes ⚠️" if asteroid_details['is_hazardous'] else "No βœ“")
        
        with col2:
            st.write("**Diameter Range:**", f"{asteroid_details['diameter_min_km']:.3f} - {asteroid_details['diameter_max_km']:.3f} km")
            st.write("**Miss Distance:**", f"{asteroid_details['miss_distance_km']:,.0f} km")
            st.write("**Relative Velocity:**", f"{asteroid_details['relative_velocity_kph']:,.0f} km/h")
        
        # Create a gauge-like visualization for the hazard level
        hazard_level = 0
        if asteroid_details['is_hazardous']:
            # Calculate hazard level based on size and miss distance
            size_factor = min(asteroid_details['avg_diameter_km'] / 0.5, 1)  # Normalize by 0.5km
            distance_factor = min(1000000 / asteroid_details['miss_distance_km'], 1)  # Normalize by 1M km
            hazard_level = (size_factor * 0.7 + distance_factor * 0.3) * 100
        
        st.progress(int(hazard_level), text=f"Relative Hazard Level: {hazard_level:.1f}%")
        
        # Add some context about the asteroid
        st.write("### Context")
        if hazard_level > 70:
            st.warning("This asteroid is classified as potentially hazardous and is relatively large and close.")
        elif hazard_level > 40:
            st.info("This asteroid is classified as potentially hazardous but poses minimal risk at this time.")
        else:
            st.success("This asteroid is not considered hazardous and poses no risk to Earth.")

# Add information about the NASA API
st.sidebar.markdown("---")
st.sidebar.markdown("""
### About NASA NeoWs API
The [Near Earth Object Web Service](https://api.nasa.gov) is a RESTful web service for near earth asteroid information. 
This API provides data on asteroids based on their closest approach date to Earth.

To get your own API key, visit [api.nasa.gov](https://api.nasa.gov).
""")

# Add deployment instructions
st.sidebar.markdown("---")
st.sidebar.markdown("""
### Deployment Instructions
1. Save this code as `app.py`
2. Create `requirements.txt` with:
   ```
   streamlit
   requests
   pandas
   plotly
   ```
3. Upload to Hugging Face Spaces
""")