Skip to content

Commit 137eb3f

Browse files
authored
Update 7_🗺️ Dashboard.py
1 parent fe10ed6 commit 137eb3f

1 file changed

Lines changed: 2 additions & 253 deletions

File tree

pages/7_🗺️ Dashboard.py

Lines changed: 2 additions & 253 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
import time
1515
import matplotlib.pyplot as plt # Needed for shap.summary_plot
1616
from streamlit_autorefresh import st_autorefresh
17-
from streamlit_lottie import st_lottie # For new animations
1817

1918
# Constants
2019
NASA_CTA_URL = "https://ssd-api.jpl.nasa.gov/cad.api" # Corrected URL
@@ -173,106 +172,6 @@ def create_parameter_matrix(body_type):
173172
}
174173
return params.get(body_type, ['unknown_body_param'])
175174

176-
# --- New Advanced Feature Functions ---
177-
178-
@st.cache_data(ttl=3600)
179-
def analyze_exoplanet_atmosphere(planet_name):
180-
"""Generates mock atmospheric composition for a given exoplanet."""
181-
np.random.seed(hash(planet_name) % (2**32 - 1)) # Seed based on planet name for consistency
182-
gases = ['N2', 'O2', 'CO2', 'CH4', 'Ar', 'H2O Vapor', 'He']
183-
composition = np.random.dirichlet(np.ones(len(gases)) * np.random.rand() * 10, size=1).flatten() * 100
184-
return pd.DataFrame({'Gas': gases, 'Percentage': composition})
185-
186-
@st.cache_data(ttl=3600)
187-
def plan_interstellar_trajectory(target_system):
188-
"""Generates mock waypoints for an interstellar trajectory."""
189-
np.random.seed(hash(target_system) % (2**32 - 1))
190-
num_waypoints = np.random.randint(5, 15)
191-
waypoints = pd.DataFrame({
192-
'x': np.cumsum(np.random.normal(0, 10, num_waypoints)),
193-
'y': np.cumsum(np.random.normal(0, 10, num_waypoints)),
194-
'z': np.cumsum(np.random.normal(0, 5, num_waypoints)),
195-
'waypoint': [f"WP-{i}" for i in range(num_waypoints)]
196-
})
197-
return waypoints
198-
199-
@st.cache_data(ttl=60) # More frequent refresh for something like signal detection
200-
def detect_alien_signal():
201-
"""Generates mock signal data with a chance of a 'detection'."""
202-
time_points = np.linspace(0, 100, 500)
203-
noise = np.random.normal(0, 1, 500)
204-
signal_strength = 5 * np.sin(time_points / 10) + noise
205-
detected = False
206-
if np.random.rand() < 0.1: # 10% chance of detection
207-
idx = np.random.randint(100, 400)
208-
signal_strength[idx:idx+10] += np.random.uniform(5, 10) # Spike for detection
209-
detected = True
210-
return pd.DataFrame({'Time': time_points, 'SignalStrength': signal_strength}), detected
211-
212-
@st.cache_data(ttl=3600)
213-
def monitor_terraforming_progress(planet_name):
214-
"""Generates mock terraforming metrics."""
215-
np.random.seed(hash(planet_name) % (2**32 - 1))
216-
metrics = {
217-
'Oxygen Level (%)': np.random.uniform(0, 21),
218-
'Surface Temp (°C)': np.random.uniform(-50, 30),
219-
'Liquid Water Coverage (%)': np.random.uniform(0, 70),
220-
'Atmospheric Pressure (kPa)': np.random.uniform(0, 101)
221-
}
222-
return metrics
223-
224-
@st.cache_data(ttl=1800)
225-
def calculate_dyson_swarm_energy(completion_percentage):
226-
"""Generates mock energy output for a Dyson swarm."""
227-
# Assume max output of a star like Sol is ~3.8e26 Watts
228-
# Let's scale this down for a more relatable number in Petawatts (1e15 W)
229-
max_petawatts = 3.8e11
230-
current_output = max_petawatts * (completion_percentage / 100)**2 # Non-linear increase
231-
time_series = pd.DataFrame({
232-
'Year': np.arange(2000, 2000 + int(completion_percentage) + 1),
233-
'EnergyOutput_PW': max_petawatts * (np.linspace(0, completion_percentage, int(completion_percentage)+1) / 100)**2
234-
})
235-
return current_output, time_series
236-
237-
@st.cache_data(ttl=3600)
238-
def visualize_accretion_disk(black_hole_mass_suns):
239-
"""Generates data for a mock accretion disk visualization."""
240-
np.random.seed(int(black_hole_mass_suns))
241-
x = np.linspace(-10, 10, 100)
242-
y = np.linspace(-10, 10, 100)
243-
X, Y = np.meshgrid(x, y)
244-
# Intensity decreases with distance, with some randomness
245-
intensity = np.exp(-(X**2 + Y**2) / (2 * (black_hole_mass_suns/2))) * (1 + 0.1*np.random.rand(100,100))
246-
intensity[np.sqrt(X**2 + Y**2) < black_hole_mass_suns*0.1] = 0 # Event horizon shadow
247-
return X, Y, intensity
248-
249-
@st.cache_data(ttl=3600)
250-
def predict_wormhole_stability(coordinates_str):
251-
"""Generates mock stability score and factors for a wormhole."""
252-
np.random.seed(hash(coordinates_str) % (2**32 - 1))
253-
stability_score = np.random.uniform(0, 100)
254-
factors = {
255-
'Exotic Matter Density': np.random.uniform(-10, 10),
256-
'Gravitational Fluctuations': np.random.uniform(-5, 5),
257-
'Temporal Distortion': np.random.uniform(-3, 3),
258-
'Energy Input': np.random.uniform(0, 15)
259-
} # Positive values contribute to stability
260-
return stability_score, pd.DataFrame(list(factors.items()), columns=['Factor', 'ImpactScore'])
261-
262-
@st.cache_data(ttl=86400) # Daily
263-
def map_dark_matter_density(sector_id):
264-
"""Generates a 2D grid of mock dark matter density values."""
265-
np.random.seed(hash(sector_id) % (2**32 - 1))
266-
density_map = np.random.rand(50, 50) * np.random.uniform(0.1, 5) # Arbitrary units
267-
return density_map
268-
269-
def simulate_relativistic_effects(velocity_fraction_c):
270-
"""Calculates mock time dilation and length contraction."""
271-
gamma = 1 / np.sqrt(1 - velocity_fraction_c**2)
272-
time_dilation_factor = gamma
273-
length_contraction_factor = 1 / gamma
274-
return time_dilation_factor, length_contraction_factor
275-
276175
# Main Visualization Page
277176
def show_visualize_page():
278177
# Immersive UI Configuration
@@ -395,9 +294,8 @@ def show_visualize_page():
395294

396295
if st.session_state.mining_sim['running']:
397296
resources = st.session_state.mining_sim['resources']
398-
# Renamed 'plt' to 'heatmap_fig' to avoid conflict with imported matplotlib.pyplot
399-
heatmap_fig = go.Figure(go.Heatmap(z=[resources], colorscale='viridis'))
400-
st.plotly_chart(heatmap_fig, use_container_width=True)
297+
plt = go.Figure(go.Heatmap(z=[resources], colorscale='viridis'))
298+
st.plotly_chart(plt, use_container_width=True)
401299
st.session_state.mining_sim['resources'] *= 0.97 # Resource depletion
402300

403301
# Exoplanetary Navigation System (Simplified without astropy)
@@ -422,154 +320,5 @@ def show_visualize_page():
422320
🔒 Quantum-Safe Encryption: AES-512 + Lattice-based NIST Standard
423321
</div>
424322
""", unsafe_allow_html=True)
425-
426-
st.markdown("<hr style='border:1px solid #00f7ff; opacity:0.3;'>", unsafe_allow_html=True)
427-
st.markdown(f"""
428-
<h2 class="title" style="color: #00f7ff; font-size: 2.5rem; text-align:center;">
429-
Advanced Analytics Modules
430-
</h2>
431-
""", unsafe_allow_html=True)
432-
433-
# --- Feature 1: Exoplanet Atmosphere Analyzer ---
434-
with st.expander("🔬 Exoplanet Atmosphere Analyzer", expanded=False):
435-
exoplanet_list = ["Kepler-186f", "TRAPPIST-1e", "Proxima Centauri b", "Gliese 581g"]
436-
selected_exoplanet = st.selectbox("Select Exoplanet:", exoplanet_list, key="exo_atm_select")
437-
if st.button("Analyze Atmosphere", key="exo_atm_btn"):
438-
with st.spinner(f"Analyzing atmosphere of {selected_exoplanet}..."):
439-
time.sleep(1.5) # Simulate analysis time
440-
atm_data = analyze_exoplanet_atmosphere(selected_exoplanet)
441-
fig_atm = px.bar(atm_data, x='Gas', y='Percentage', title=f"Atmospheric Composition of {selected_exoplanet}",
442-
color='Gas', labels={'Percentage':'Concentration (%)'})
443-
fig_atm.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
444-
st.plotly_chart(fig_atm, use_container_width=True)
445-
st.dataframe(atm_data)
446-
447-
# --- Feature 2: Interstellar Trajectory Planner ---
448-
with st.expander("🗺️ Interstellar Trajectory Planner", expanded=False):
449-
target_star_system = st.text_input("Target Star System (e.g., Alpha Centauri):", "Alpha Centauri", key="traj_target")
450-
if st.button("Plan Trajectory", key="traj_plan_btn"):
451-
if target_star_system:
452-
with st.spinner(f"Calculating trajectory to {target_star_system}..."):
453-
time.sleep(2)
454-
trajectory_data = plan_interstellar_trajectory(target_star_system)
455-
fig_traj = px.line_3d(trajectory_data, x='x', y='y', z='z', color='waypoint', markers=True,
456-
title=f"Interstellar Trajectory to {target_star_system}")
457-
fig_traj.update_layout(scene=dict(xaxis_title='X (LY)', yaxis_title='Y (LY)', zaxis_title='Z (LY)',
458-
bgcolor='rgba(0,0,0,0.1)'),
459-
paper_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
460-
st.plotly_chart(fig_traj, use_container_width=True)
461-
else:
462-
st.warning("Please enter a target star system.")
463-
464-
# --- Feature 3: Alien Signal Detector ---
465-
with st.expander("📡 Alien Signal Detector (ASD)", expanded=False):
466-
if st.button("Scan for Extraterrestrial Signals", key="asd_scan_btn"):
467-
with st.spinner("Scanning designated frequency bands..."):
468-
time.sleep(2.5)
469-
signal_data, detected = detect_alien_signal()
470-
fig_signal = px.line(signal_data, x='Time', y='SignalStrength', title="Signal Strength Analysis")
471-
fig_signal.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
472-
if detected:
473-
st.success("Potential anomalous signal detected! Further analysis required.")
474-
fig_signal.add_vline(x=signal_data[signal_data['SignalStrength'] > signal_data['SignalStrength'].mean() + 3*signal_data['SignalStrength'].std()]['Time'].mean(),
475-
line_dash="dash", line_color="red", annotation_text="Anomaly Peak")
476-
else:
477-
st.info("No anomalous signals detected in this scan cycle. Background noise levels nominal.")
478-
st.plotly_chart(fig_signal, use_container_width=True)
479-
480-
# --- Feature 4: Terraforming Progress Monitor ---
481-
with st.expander("🌍 Terraforming Progress Monitor", expanded=False):
482-
terraforming_candidates = ["Mars", "Europa", "Titan"]
483-
selected_tf_planet = st.selectbox("Select Planet for Terraforming Status:", terraforming_candidates, key="tf_planet_select")
484-
if selected_tf_planet:
485-
tf_metrics = monitor_terraforming_progress(selected_tf_planet)
486-
st.subheader(f"Terraforming Status: {selected_tf_planet}")
487-
cols_tf = st.columns(len(tf_metrics))
488-
for i, (metric_name, value) in enumerate(tf_metrics.items()):
489-
with cols_tf[i]:
490-
# Simple metric display, could be gauge charts with more effort
491-
st.metric(label=metric_name, value=f"{value:.2f}")
492-
if "Percentage" in metric_name:
493-
st.progress(int(value))
494-
495-
# --- Feature 5: Dyson Swarm Energy Output ---
496-
with st.expander("☀️ Dyson Swarm Energy Output Simulator", expanded=False):
497-
swarm_completion = st.slider("Dyson Swarm Completion (%):", 0, 100, 25, key="dyson_completion")
498-
current_output_pw, energy_time_series = calculate_dyson_swarm_energy(swarm_completion)
499-
st.metric(label="Current Estimated Energy Output", value=f"{current_output_pw:.2e} PW")
500-
501-
fig_dyson = px.line(energy_time_series, x='Year', y='EnergyOutput_PW', title="Projected Dyson Swarm Energy Output Over Time")
502-
fig_dyson.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff',
503-
yaxis_title="Energy Output (Petawatts)")
504-
st.plotly_chart(fig_dyson, use_container_width=True)
505-
506-
# --- Feature 6: Black Hole Accretion Disk Visualizer ---
507-
with st.expander("🌀 Black Hole Accretion Disk Visualizer", expanded=False):
508-
bh_mass = st.number_input("Black Hole Mass (Solar Masses):", min_value=1.0, max_value=1000.0, value=10.0, step=1.0, key="bh_mass_input")
509-
if st.button("Visualize Accretion Disk", key="bh_vis_btn"):
510-
X_disk, Y_disk, intensity_disk = visualize_accretion_disk(bh_mass)
511-
fig_bh = go.Figure(data = go.Contour(z=intensity_disk, x=X_disk[0,:], y=Y_disk[:,0], colorscale='hot'))
512-
fig_bh.update_layout(title=f"Accretion Disk Intensity - {bh_mass} Solar Masses BH",
513-
xaxis_title="Relative X", yaxis_title="Relative Y",
514-
paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
515-
st.plotly_chart(fig_bh, use_container_width=True)
516-
517-
# --- Feature 7: Wormhole Stability Predictor ---
518-
with st.expander("웜홀 안정성 예측기 (Wormhole Stability Predictor)", expanded=False): # Korean title for fun
519-
wh_coords = st.text_input("Enter Wormhole Coordinates (e.g., X:123,Y:456,Z:789):", "X:10,Y:20,Z:30", key="wh_coords")
520-
if st.button("Predict Stability", key="wh_stab_btn"):
521-
stability, factors_df = predict_wormhole_stability(wh_coords)
522-
st.metric(label=f"Predicted Stability for Wormhole at {wh_coords}", value=f"{stability:.2f}%")
523-
st.progress(int(stability))
524-
525-
fig_wh_factors = px.bar(factors_df, x='Factor', y='ImpactScore', color='ImpactScore',
526-
title="Factors Influencing Wormhole Stability",
527-
color_continuous_scale=px.colors.diverging.RdBu)
528-
fig_wh_factors.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
529-
st.plotly_chart(fig_wh_factors, use_container_width=True)
530-
531-
# --- Feature 8: Dark Matter Density Mapper ---
532-
with st.expander("👻 Dark Matter Density Mapper", expanded=False):
533-
galactic_sector = st.text_input("Galactic Sector ID (e.g., GS-007):", "GS-Alpha-Prime", key="dm_sector")
534-
if st.button("Map Dark Matter Density", key="dm_map_btn"):
535-
with st.spinner(f"Mapping dark matter in sector {galactic_sector}..."):
536-
time.sleep(1)
537-
dm_map_data = map_dark_matter_density(galactic_sector)
538-
fig_dm = px.imshow(dm_map_data, color_continuous_scale='viridis',
539-
title=f"Dark Matter Density Map - Sector {galactic_sector}")
540-
fig_dm.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
541-
st.plotly_chart(fig_dm, use_container_width=True)
542-
543-
# --- Feature 9: Relativistic Effects Simulator ---
544-
with st.expander("⏳ Relativistic Effects Simulator", expanded=False):
545-
velocity_c = st.slider("Velocity (fraction of speed of light, c):", 0.0, 0.999, 0.5, 0.001, format="%.3f", key="rel_vel")
546-
time_dilation, length_contraction = simulate_relativistic_effects(velocity_c)
547-
col_rel1, col_rel2 = st.columns(2)
548-
with col_rel1:
549-
st.metric("Time Dilation Factor (γ)", f"{time_dilation:.3f}x")
550-
st.caption("Time for moving observer appears slower by this factor to a stationary observer.")
551-
with col_rel2:
552-
st.metric("Length Contraction Factor (1/γ)", f"{length_contraction:.3f}x")
553-
st.caption("Length of moving object appears shorter by this factor in direction of motion.")
554-
if velocity_c > 0.1:
555-
st.info(f"At {velocity_c*100:.1f}% of light speed, 1 year for you would be {1*time_dilation:.2f} years for a stationary observer.")
556-
557-
# --- Feature 10: Cosmic Ray Shielding Effectiveness ---
558-
with st.expander("🛡️ Cosmic Ray Shielding Effectiveness Analyzer", expanded=False):
559-
shielding_materials = ["Titanium Alloy", "Polyethylene Composite", "Lead-Infused Aerogel", "Magnetic Deflector"]
560-
selected_material = st.selectbox("Select Shielding Material:", shielding_materials, key="shield_mat_select")
561-
if st.button("Analyze Shielding", key="shield_analyze_btn"):
562-
np.random.seed(hash(selected_material) % (2**32 - 1))
563-
effectiveness = np.random.uniform(50, 99.9) # %
564-
particle_types = ["Protons", "Alpha Particles", "Heavy Nuclei", "Gamma Rays"]
565-
reduction_data = pd.DataFrame({
566-
'Particle Type': particle_types,
567-
'Flux Reduction (%)': np.random.uniform(effectiveness*0.8, effectiveness, len(particle_types))
568-
})
569-
st.metric(f"Overall Effectiveness of {selected_material}", f"{effectiveness:.1f}%")
570-
fig_shield = px.bar(reduction_data, x='Particle Type', y='Flux Reduction (%)', color='Particle Type',
571-
title=f"Cosmic Ray Flux Reduction by {selected_material}")
572-
fig_shield.update_layout(paper_bgcolor='rgba(0,0,0,0)', plot_bgcolor='rgba(0,0,0,0)', font_color='#00f7ff')
573-
st.plotly_chart(fig_shield, use_container_width=True)
574323

575324
show_visualize_page()

0 commit comments

Comments
 (0)