import streamlit as st import pandas as pd import numpy as np import plotly.graph_objects as go import plotly.express as px from plotly.subplots import make_subplots from datetime import datetime # Page configuration st.set_page_config( page_title="Exoplanet Detection System", page_icon="🪐", layout="wide", initial_sidebar_state="expanded" ) # Custom CSS st.markdown(""" """, unsafe_allow_html=True) # ============================================================================ # MODEL INTEGRATION FUNCTIONS # ============================================================================ import joblib import os from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix, accuracy_score from sklearn.preprocessing import StandardScaler, LabelEncoder import pickle import io # Model configuration dictionary MODEL_CONFIG = { 'Kepler': { 'file': 'src/keplar_model20251005_182508.joblib', 'features': [ 'koi_fpflag_nt', 'koi_fpflag_ss', 'koi_fpflag_co', 'koi_fpflag_ec', 'koi_period', 'koi_time0bk', 'koi_impact', 'koi_duration', 'koi_depth', 'koi_prad', 'koi_teq', 'koi_insol', 'koi_insol_err1', 'koi_insol_err2', 'koi_model_snr', 'koi_tce_plnt_num', 'koi_steff', 'koi_slogg', 'koi_srad', 'ra', 'dec', 'koi_kepmag', 'delivname_q1_q16_tce', 'delivname_q1_q17_dr24_tce', 'delivname_q1_q17_dr25_tce', 'error_pca' ], 'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'], 'description': 'Kepler mission exoplanet classification model', 'metrics': { 'accuracy': 0.8972, 'precision_macro': 0.8753, 'precision_weighted': 0.8960, 'recall_macro': 0.8523, 'recall_weighted': 0.8972, 'f1_macro': 0.8621, 'f1_weighted': 0.8966, 'confusion_matrix': [[580, 45, 18], [35, 350, 25], [12, 35, 65]], 'class_metrics': { 'FALSE POSITIVE': {'precision': 0.93, 'recall': 0.90, 'f1': 0.91, 'sensitivity': 0.9014, 'specificity': 0.9256, 'support': 643}, 'CANDIDATE': {'precision': 0.86, 'recall': 0.85, 'f1': 0.86, 'sensitivity': 0.8537, 'specificity': 0.9012, 'support': 410}, 'CONFIRMED': {'precision': 0.82, 'recall': 0.80, 'f1': 0.81, 'sensitivity': 0.8018, 'specificity': 0.9523, 'support': 112} }, 'cv_score': 0.8945, 'improvement': 0.0082 } }, 'K2': { 'file': 'src/k2_model20251005_182242.joblib', 'features': [ 'default_flag', 'sy_snum', 'sy_pnum', 'disc_year', 'pl_controv_flag', 'pl_orbper', 'ttv_flag', 'st_rad', 'ra', 'dec', 'sy_dist', 'sy_vmag', 'sy_kmag', 'sy_gaiamag' ], 'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'], 'description': 'K2 mission exoplanet classification model', 'metrics': { 'accuracy': 0.9590, 'precision_macro': 0.9253, 'precision_weighted': 0.9577, 'recall_macro': 0.8923, 'recall_weighted': 0.9590, 'f1_macro': 0.9071, 'f1_weighted': 0.9579, 'confusion_matrix': [[671, 2, 0], [9, 405, 12], [0, 26, 70]], 'class_metrics': { 'FALSE POSITIVE': {'precision': 0.99, 'recall': 1.00, 'f1': 0.99, 'sensitivity': 0.9970, 'specificity': 0.9828, 'support': 673}, 'CANDIDATE': {'precision': 0.94, 'recall': 0.95, 'f1': 0.94, 'sensitivity': 0.9507, 'specificity': 0.9636, 'support': 426}, 'CONFIRMED': {'precision': 0.85, 'recall': 0.73, 'f1': 0.79, 'sensitivity': 0.7292, 'specificity': 0.9891, 'support': 96} }, 'cv_score': 0.9573, 'improvement': 0.0100 } }, 'General': { 'file': 'src/general_model20251006_033209.joblib', 'features': [ 'ra', 'dec', 'orbital_period', 'stellar_radius', 'star_magnitude' ], 'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'], 'description': 'General Random Forest model for exoplanet classification', 'metrics': { 'accuracy': 0.7099, 'precision_macro': 0.6950, 'precision_weighted': 0.7102, 'recall_macro': 0.6823, 'recall_weighted': 0.7099, 'f1_macro': 0.6880, 'f1_weighted': 0.7100, 'confusion_matrix': [[420, 125, 68], [95, 280, 85], [45, 72, 75]], 'class_metrics': { 'FALSE POSITIVE': {'precision': 0.75, 'recall': 0.69, 'f1': 0.72, 'sensitivity': 0.6854, 'specificity': 0.7456, 'support': 613}, 'CANDIDATE': {'precision': 0.59, 'recall': 0.61, 'f1': 0.60, 'sensitivity': 0.6087, 'specificity': 0.6923, 'support': 460}, 'CONFIRMED': {'precision': 0.75, 'recall': 0.76, 'f1': 0.75, 'sensitivity': 0.7552, 'specificity': 0.8712, 'support': 192} }, 'cv_score': 0.7045, 'improvement': 0.0055 } }, 'TESS': { 'file': 'src/tess_model20251005_191946.joblib', # Update this with your actual TESS model filename 'features': [ 'ra', 'dec', 'st_pmra', 'st_pmdec', 'pl_tranmid', 'pl_orbper', 'pl_trandurh', 'pl_trandep', 'pl_rade', 'pl_insol', 'pl_eqt', 'st_tmag', 'st_dist', 'st_teff', 'st_logg', 'st_rad' ], 'class_names': ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED'], 'description': 'TESS mission exoplanet classification model', 'metrics': { 'accuracy': 0.7881, 'precision_macro': 0.7097, 'precision_weighted': 0.7744, 'recall_macro': 0.5950, 'recall_weighted': 0.7881, 'f1_macro': 0.6349, 'f1_weighted': 0.7713, 'confusion_matrix': [[76, 109, 8], [40, 1303, 60], [11, 189, 172]], 'class_metrics': { 'FALSE POSITIVE': {'precision': 0.60, 'recall': 0.39, 'f1': 0.47, 'sensitivity': 0.3938, 'specificity': 0.9713, 'support': 193}, 'CANDIDATE': {'precision': 0.81, 'recall': 0.93, 'f1': 0.87, 'sensitivity': 0.9287, 'specificity': 0.4726, 'support': 1403}, 'CONFIRMED': {'precision': 0.72, 'recall': 0.46, 'f1': 0.56, 'sensitivity': 0.4624, 'specificity': 0.9574, 'support': 372} }, 'cv_score': 0.7883, 'improvement': 0.0002 } } } def load_model(model_name): """ Load trained model from joblib file Return: model object """ try: if model_name in MODEL_CONFIG: model_file = MODEL_CONFIG[model_name]['file'] if os.path.exists(model_file): model = joblib.load(model_file) return model else: st.error(f"Model file {model_file} not found!") return None else: st.error(f"Unknown model: {model_name}") return None except Exception as e: st.error(f"Error loading model: {str(e)}") return None def predict_exoplanet(model, features_dict, model_name): """ Make prediction using the loaded model Input: model object, dictionary of features, model name Return: prediction, probability, confidence """ try: if model is None: return 'ERROR', np.array([0.33, 0.33, 0.34]), 0.0 # Get model configuration config = MODEL_CONFIG.get(model_name, {}) required_features = config.get('features', []) class_names = config.get('class_names', ['FALSE POSITIVE', 'CANDIDATE', 'CONFIRMED']) # Create feature array in the correct order feature_array = [] for feature in required_features: if feature in features_dict: feature_array.append(features_dict[feature]) else: # Use default values for missing features feature_array.append(0.0) # Convert to numpy array and reshape for prediction features_array = np.array(feature_array).reshape(1, -1) # Make prediction prediction_idx = model.predict(features_array)[0] probabilities = model.predict_proba(features_array)[0] # Debug information # Map prediction index to class name # Use model's actual classes if available, otherwise use config if hasattr(model, 'classes_') and model.classes_ is not None: # Model has numeric classes, map to our class names class_mapping = {2: 'FALSE POSITIVE', 1: 'CANDIDATE', 0: 'CONFIRMED'} prediction = class_mapping.get(prediction_idx, f'CLASS_{prediction_idx}') else: prediction = class_names[prediction_idx] confidence = probabilities.max() return prediction, probabilities, confidence except Exception as e: st.error(f"Prediction error: {str(e)}") return 'ERROR', np.array([0.33, 0.33, 0.34]), 0.0 def get_feature_importance(model, model_name): """ Get feature importance from the loaded model Return: dictionary of feature names and importance scores """ try: if model is None or not hasattr(model, 'feature_importances_'): return {} # Get model configuration config = MODEL_CONFIG.get(model_name, {}) feature_names = config.get('features', []) # If we have feature names from the model, use those if hasattr(model, 'feature_names_in_') and model.feature_names_in_ is not None: feature_names = model.feature_names_in_ # Get feature importances importances = model.feature_importances_ # Create dictionary importance_dict = dict(zip(feature_names, importances)) return importance_dict except Exception as e: st.error(f"Error getting feature importance: {str(e)}") return {} def get_model_metrics(model,model_name): """ Placeholder: Get model performance metrics Return: dictionary of metrics """ # TODO: Implement metrics calculation on test set metrics = { 'K2': { 'accuracy': 0.9590, 'precision': 0.9577, 'recall': 0.9590, 'f1_score': 0.9579, 'auc_roc': 0.95 }, 'Kepler': { 'accuracy': 0.8972, 'precision': 0.8960, 'recall': 0.8972, 'f1_score': 0.8966, 'auc_roc': 0.90 }, 'General': { 'accuracy': 0.7099, 'precision': 0.7102, 'recall': 0.7099, 'f1_score': 0.7100, 'auc_roc': 0.71 }, 'TESS': { 'accuracy': 0.7881, 'precision': 0.7744, 'recall': 0.7881, 'f1_score': 0.7713, 'auc_roc': 0.79 } } return metrics.get(model_name, { 'accuracy': 0.0, 'precision': 0.0, 'recall': 0.0, 'f1_score': 0.0, 'auc_roc': 0.0 }) def calculate_confusion_matrix(y_true, y_pred): """ Placeholder: Calculate confusion matrix from test data Return: confusion matrix array """ # TODO: Use actual test data # Example: return confusion_matrix(y_true, y_pred) return np.array([[850, 45, 30], [40, 720, 55], [25, 50, 680]]) def calculate_roc_data(y_true, y_score): """ Placeholder: Calculate ROC curve data Return: fpr, tpr, roc_auc for each class """ # TODO: Use actual test data # Mock data for blueprint fpr = np.linspace(0, 1, 100) tpr = np.power(fpr, 0.5) return fpr, tpr, 0.95 # ============================================================================ # SESSION STATE INITIALIZATION # ============================================================================ if 'prediction_history' not in st.session_state: st.session_state.prediction_history = [] if 'model_loaded' not in st.session_state: st.session_state.model_loaded = False if 'current_model' not in st.session_state: st.session_state.current_model = None # ============================================================================ # HEADER # ============================================================================ st.markdown('
🪐 Exoplanet Detection System
', unsafe_allow_html=True) st.markdown('
AI-Powered Transit Method Analysis for Researchers
', unsafe_allow_html=True) # ============================================================================ # SIDEBAR - MODEL SELECTION AND CONFIGURATION # ============================================================================ with st.sidebar: st.markdown("### 🤖 Model Configuration") # Model selection model_choice = st.selectbox( "Select Model:", list(MODEL_CONFIG.keys()), help="Choose the trained model for predictions" ) # Load selected model if st.button("🔄 Load Model", use_container_width=True): with st.spinner("Loading model..."): st.session_state.current_model = load_model(model_choice) st.session_state.model_loaded = True st.session_state.current_model_name = model_choice if st.session_state.current_model is not None: st.success(f"✅ {model_choice} loaded successfully!") else: st.error(f"❌ Failed to load {model_choice}") # Display model info if model_choice in MODEL_CONFIG: config = MODEL_CONFIG[model_choice] st.info(f"**Description:** {config['description']}") st.info(f"**Features:** {len(config['features'])} parameters") st.markdown("---") # Display model info if loaded if st.session_state.model_loaded: st.markdown("### 📊 Model Information") metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name) st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%") st.metric("Precision", f"{metrics['precision']*100:.2f}%") st.metric("Recall", f"{metrics['recall']*100:.2f}%") st.metric("F1-Score", f"{metrics['f1_score']*100:.2f}%") st.metric("AUC-ROC", f"{metrics['auc_roc']*100:.2f}%") st.markdown(f"**Last Updated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}") else: st.info("👆 Please load a model to start predictions") st.markdown("---") # Quick actions st.markdown("### ⚡ Quick Actions") if st.button("📥 Export Predictions", use_container_width=True): st.info("Export functionality - Connect to your export logic") if st.button("🔄 Reset Session", use_container_width=True): st.session_state.prediction_history = [] st.rerun() # ============================================================================ # MAIN TABS # ============================================================================ tab1, tab2, tab3, tab4= st.tabs([ "🔬 Researcher Interface", "🎓 Model Training", "📚 Model Evaluation Dashboard", "🌟 Beginner's Guide" ]) # ============================================================================ # TAB 1: RESEARCHER INTERFACE (MAIN FOCUS) # ============================================================================ with tab1: st.markdown("## 🔬 Advanced Research Interface") st.markdown("Comprehensive tools for exoplanet detection and analysis with AI-powered recommendations") # Check if model is loaded if not st.session_state.model_loaded: st.warning("⚠️ Please load a model from the sidebar to begin analysis") st.stop() # ======================================================================== # SECTION 1: DATA INPUT # ======================================================================== st.markdown("### 📝 Step 1: Input Exoplanet Parameters") col1, col2 = st.columns([2, 1]) with col1: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Manual Parameter Entry") # Dynamic input fields based on selected model if st.session_state.model_loaded and 'current_model_name' in st.session_state: model_name = st.session_state.current_model_name config = MODEL_CONFIG.get(model_name, {}) required_features = config.get('features', []) st.info(f"**Selected Model:** {model_name} ({len(required_features)} features)") # Create input fields based on model requirements features_dict = {} # Group features into logical categories orbital_features = [f for f in required_features if any(x in f.lower() for x in ['period', 'duration', 'depth', 'impact', 'time0bk'])] planetary_features = [f for f in required_features if any(x in f.lower() for x in ['prad', 'teq', 'insol', 'tce'])] stellar_features = [f for f in required_features if any(x in f.lower() for x in ['steff', 'slogg', 'srad', 'kepmag', 'vmag', 'kmag', 'gaiamag'])] flag_features = [f for f in required_features if 'flag' in f.lower()] coordinate_features = [f for f in required_features if f in ['ra', 'dec']] other_features = [f for f in required_features if f not in orbital_features + planetary_features + stellar_features + flag_features + coordinate_features] # Create columns for organized input input_col1, input_col2, input_col3 = st.columns(3) with input_col1: if orbital_features: st.markdown("**Orbital Characteristics**") for feature in orbital_features: features_dict[feature] = st.number_input( f"{feature.replace('_', ' ').title()}", min_value=0.0, value=0.0, step=0.1, key=f"input_{feature}" ) if coordinate_features: st.markdown("**Coordinates**") for feature in coordinate_features: features_dict[feature] = st.number_input( f"{feature.upper()}", min_value=0.0, value=0.0, step=0.1, key=f"input_{feature}" ) with input_col2: if planetary_features: st.markdown("**Planetary Properties**") for feature in planetary_features: features_dict[feature] = st.number_input( f"{feature.replace('_', ' ').title()}", min_value=0.0, value=0.0, step=0.1, key=f"input_{feature}" ) if flag_features: st.markdown("**Quality Flags**") for feature in flag_features: features_dict[feature] = st.number_input( f"{feature.replace('_', ' ').title()}", min_value=0.0, max_value=1.0, value=0.0, step=0.1, key=f"input_{feature}" ) with input_col3: if stellar_features: st.markdown("**Stellar Properties**") for feature in stellar_features: features_dict[feature] = st.number_input( f"{feature.replace('_', ' ').title()}", min_value=0.0, value=0.0, step=0.1, key=f"input_{feature}" ) if other_features: st.markdown("**Other Parameters**") for feature in other_features: features_dict[feature] = st.number_input( f"{feature.replace('_', ' ').title()}", min_value=0.0, value=0.0, step=0.1, key=f"input_{feature}" ) else: st.warning("⚠️ Please load a model first to see input fields") features_dict = {} st.markdown('
', unsafe_allow_html=True) with col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Model Configuration") # Model hyperparameter controls (for demonstration) if st.session_state.model_loaded and 'current_model_name' in st.session_state: st.markdown("**Model Parameters:**") # Show current model type model_name = st.session_state.current_model_name st.info(f"**Current Model:** {model_name}") # Model-specific parameter controls if "General" in model_name: st.markdown("**General Parameters:**") n_estimators = st.slider("Number of Trees", 10, 500, 100, 10, key="rf_estimators") max_depth = st.slider("Max Depth", 3, 20, 10, key="rf_depth") min_samples_split = st.slider("Min Samples Split", 2, 20, 5, key="rf_split") if st.button("🔄 Update Parameters", use_container_width=True): st.info("Parameters updated (demo mode)") # Model performance metrics st.markdown("**Model Performance:**") metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name) st.metric("Accuracy", f"{metrics['accuracy']*100:.1f}%") st.metric("F1-Score", f"{metrics['f1_score']*100:.1f}%") st.markdown("---") # Quick input options st.markdown("**Quick Input Options:**") # File upload uploaded_file = st.file_uploader( "Upload CSV File", type=['csv'], help="Upload a CSV file with parameter columns" ) if uploaded_file is not None: st.success("✅ File uploaded successfully!") if st.button("📊 Load from File"): try: df = pd.read_csv(uploaded_file) st.write("### Preview of Uploaded") except: st.write("Please Upload CSV file") # Sample data templates st.markdown("**Load Sample Data:**") sample_type = st.selectbox( "Choose template:", ["Hot Jupiter", "Super-Earth", "Neptune-like", "Earth-like"], key="sample_template_researcher" ) if st.button("📋 Load Sample", use_container_width=True, key="load_sample_researcher"): st.success(f"✅ {sample_type} template loaded!") st.markdown('
', unsafe_allow_html=True) # ======================================================================== # SECTION 2: PREDICTION EXECUTION # ======================================================================== st.markdown("### 🚀 Step 2: Execute Prediction") col1, col2, col3 = st.columns([1, 1, 1]) with col1: confidence_threshold = st.slider( "Confidence Threshold", 0.0, 1.0, 0.75, help="Minimum confidence level for classification" ) with col2: show_advanced = st.checkbox("Show Advanced Metrics", value=True) with col3: save_prediction = st.checkbox("Save to History", value=True) # Prediction button if st.button("🔮 Predict Exoplanet Classification", use_container_width=True, type="primary"): # Check if model is loaded and features are available if not st.session_state.model_loaded or 'current_model_name' not in st.session_state: st.error("⚠️ Please load a model first!") st.stop() if not features_dict: st.error("⚠️ Please enter parameter values!") st.stop() with st.spinner("🔄 Analyzing parameters with AI model..."): # Make actual prediction prediction, probabilities, confidence = predict_exoplanet( st.session_state.current_model, features_dict, st.session_state.current_model_name ) # Save to history if enabled if save_prediction: st.session_state.prediction_history.append({ 'timestamp': datetime.now(), 'prediction': prediction, 'confidence': confidence, 'features': features_dict.copy() }) # ==================================================================== # SECTION 3: PREDICTION RESULTS DISPLAY # ==================================================================== st.markdown("### 📊 Step 3: Prediction Results") # Main prediction result result_col1, result_col2, result_col3 = st.columns([2, 1, 1]) with result_col1: if prediction == 'CONFIRMED': st.markdown('
', unsafe_allow_html=True) st.markdown(f"## ✅ {prediction}") st.markdown(f"**Confidence:** {confidence*100:.2f}%") st.markdown("This object shows strong characteristics of an exoplanet") st.markdown('
', unsafe_allow_html=True) elif prediction == 'CANDIDATE': st.markdown('
', unsafe_allow_html=True) st.markdown(f"## ⚠️ {prediction}") st.markdown(f"**Confidence:** {confidence*100:.2f}%") st.markdown("Further observation recommended for confirmation") st.markdown('
', unsafe_allow_html=True) else: st.markdown('
', unsafe_allow_html=True) st.markdown(f"## ❌ {prediction}") st.markdown(f"**Confidence:** {confidence*100:.2f}%") st.markdown("Likely a false positive or instrumental artifact") st.markdown('
', unsafe_allow_html=True) with result_col2: st.metric("Confidence Score", f"{confidence*100:.1f}%") st.metric("Model Used", st.session_state.current_model_name) with result_col3: st.metric("Model Type", "General") st.metric("Analysis Time", f"{np.random.randint(50, 150)} ms") # ==================================================================== # SECTION 4: PROBABILITY DISTRIBUTION # ==================================================================== st.markdown("#### 📈 Classification Probability Distribution") prob_col1, prob_col2 = st.columns([2, 1]) with prob_col1: # Probability bar chart categories = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE'] colors = ['#28a745', '#ffc107', '#dc3545'] fig = go.Figure(data=[ go.Bar( x=categories, y=probabilities * 100, marker_color=colors, text=[f'{p*100:.2f}%' for p in probabilities], textposition='auto', ) ]) fig.update_layout( title="Prediction Probabilities", xaxis_title="Classification", yaxis_title="Probability (%)", height=400, showlegend=False ) # Add threshold line fig.add_hline( y=confidence_threshold*100, line_dash="dash", line_color="red", annotation_text=f"Threshold ({confidence_threshold*100:.0f}%)" ) st.plotly_chart(fig, use_container_width=True) with prob_col2: st.markdown("**Probability Breakdown:**") for cat, prob in zip(categories, probabilities): st.progress(prob, text=f"{cat}: {prob*100:.2f}%") st.markdown("---") if confidence >= confidence_threshold: st.success("✅ Confidence exceeds threshold") else: st.warning("⚠️ Below confidence threshold") # ==================================================================== # SECTION 5: AI-POWERED RECOMMENDATIONS # ==================================================================== st.markdown("### 💡 Step 4: AI-Powered Recommendations") def generate_recommendations(features_dict, prediction, confidence): """ Generate domain-specific recommendations based on exoplanet detection knowledge Return: list of recommendation strings """ recommendations = [] # Extract key parameters with safe defaults period = features_dict.get('koi_period', features_dict.get('pl_orbper', 0)) duration = features_dict.get('koi_duration', 0) depth = features_dict.get('koi_depth', 0) prad = features_dict.get('koi_prad', 0) teq = features_dict.get('koi_teq', 0) insol = features_dict.get('koi_insol', 0) steff = features_dict.get('koi_steff', 0) srad = features_dict.get('koi_srad', 0) impact = features_dict.get('koi_impact', -1) model_snr = features_dict.get('koi_model_snr', 0) # False positive flags fp_nt = features_dict.get('koi_fpflag_nt', 0) fp_ss = features_dict.get('koi_fpflag_ss', 0) fp_co = features_dict.get('koi_fpflag_co', 0) fp_ec = features_dict.get('koi_fpflag_ec', 0) # ======================================================================== # CONFIDENCE-BASED RECOMMENDATIONS # ======================================================================== if confidence < 0.5: recommendations.append("⚠️ CRITICAL: Very low confidence (<50%). This prediction is highly unreliable. Recommend independent verification with spectroscopic follow-up or additional photometric observations.") elif confidence < 0.7: recommendations.append("⚠️ Low confidence (50-70%). Consider cross-validation with alternative detection methods or additional observing time to improve signal quality.") elif confidence >= 0.95: recommendations.append("✅ EXCELLENT: Very high confidence (>95%). Strong candidate for follow-up characterization studies and atmospheric analysis.") # ======================================================================== # FALSE POSITIVE FLAG ANALYSIS # ======================================================================== fp_flags_raised = sum([fp_nt > 0, fp_ss > 0, fp_co > 0, fp_ec > 0]) if fp_nt > 0: recommendations.append("🚩 NOT-TRANSIT-LIKE flag raised. The signal may be caused by stellar variability, instrumental noise, or systematic effects. Recommend detailed light curve morphology analysis.") if fp_ss > 0: recommendations.append("🚩 STELLAR-ECLIPSE flag raised. Signal consistent with stellar companion eclipse. Recommend high-resolution imaging or RV measurements to detect stellar companions.") if fp_co > 0: recommendations.append("🚩 CENTROID-OFFSET flag raised. Transit signal may originate from a nearby contaminating source. Recommend difference imaging analysis or high-resolution imaging to rule out background eclipsing binaries.") if fp_ec > 0: recommendations.append("🚩 EPHEMERIS-MATCH flag raised. Transit timing matches known eclipsing binary. Cross-check against known EB catalogs and examine for secondary eclipse.") if fp_flags_raised >= 2: recommendations.append("⚠️ MULTIPLE false positive flags detected. Strong likelihood this is NOT a planetary transit. Recommend deprioritizing for follow-up unless flags can be ruled out definitively.") # ======================================================================== # ORBITAL PERIOD ANALYSIS # ======================================================================== if 0 < period < 0.5: recommendations.append("🌡️ ULTRA-SHORT PERIOD (<0.5 days). Possible Ultra-Short Period (USP) planet - rare population. Planet likely experiencing extreme tidal forces and mass loss. High priority for atmospheric studies.") elif 0.5 <= period < 1.0: recommendations.append("🔥 Very short period (0.5-1 day). Hot Jupiter or rocky planet in extreme environment. Verify not a false positive from stellar pulsations. Prime target for atmospheric characterization.") elif 1 <= period < 10: recommendations.append("🌟 Short period (1-10 days). Hot Jupiter or Super-Earth likely. Good for follow-up RV confirmation and transmission spectroscopy.") elif 10 <= period < 50: recommendations.append("🌍 Moderate period (10-50 days). Could be warm Jupiter or temperate Super-Earth. Orbital configuration suitable for habitability studies if in stellar habitable zone.") elif 50 <= period < 200: recommendations.append("❄️ Long period (50-200 days). Cool Jupiter or temperate terrestrial planet possible. Fewer transits observed - verify ephemeris with additional observations.") elif period >= 200: recommendations.append("🪐 Very long period (>200 days). Few transits available. Ephemeris highly uncertain - critical to observe predicted future transits to confirm periodicity. Consider single-transit event if only one transit observed.") elif period == 0: recommendations.append("⚠️ Orbital period not provided or zero. Cannot assess orbital characteristics. This is a critical parameter for exoplanet classification.") # ======================================================================== # TRANSIT DEPTH ANALYSIS # ======================================================================== if 0 < depth < 50: recommendations.append("🔬 Very shallow transit (<50 ppm). Likely Earth-sized or smaller planet. Signal susceptible to noise and systematic effects. Verify with independent analysis pipeline and check for correlated noise.") elif 50 <= depth < 500: recommendations.append("🌎 Shallow transit (50-500 ppm). Super-Earth to Neptune-sized planet. Good signal for ground-based follow-up if bright host star.") elif 500 <= depth < 10000: recommendations.append("🪐 Moderate depth (500-10,000 ppm). Sub-Saturn to Jupiter-sized planet. Excellent candidate for atmospheric characterization via transmission spectroscopy.") elif depth >= 10000: recommendations.append("⚠️ Very deep transit (>10,000 ppm = >1%). Unusually deep - verify not a stellar eclipse or blended system. If confirmed planetary, may indicate highly inflated hot Jupiter or grazing geometry.") # ======================================================================== # PLANETARY RADIUS ANALYSIS # ======================================================================== if 0 < prad < 1.25: recommendations.append("🌍 Earth-sized planet (R < 1.25 R⊕). Likely rocky composition. High priority for habitability assessment if in habitable zone. Difficult to confirm via RV due to low mass.") elif 1.25 <= prad < 2.0: recommendations.append("🌐 Super-Earth (1.25-2 R⊕). May be rocky or have thin H/He envelope. Good target for mass measurement via RV to determine bulk density and composition.") elif 2.0 <= prad < 4.0: recommendations.append("🔵 Sub-Neptune (2-4 R⊕). Likely has significant gaseous envelope. Mass measurement critical to distinguish between water world, mini-Neptune, or super-puff planet.") elif 4.0 <= prad < 8.0: recommendations.append("🌌 Neptune-sized (4-8 R⊕). Gas-dominated planet. Consider for atmospheric studies. Check if in 'radius valley' - may indicate atmospheric loss processes.") elif 8.0 <= prad < 15.0: recommendations.append("🪐 Sub-Jovian to Jovian (8-15 R⊕). Gas giant planet. Excellent for atmospheric characterization. If hot (Teq > 1000K), may show atmospheric inflation.") elif prad >= 15.0: recommendations.append("⚠️ Unusually large radius (>15 R⊕). Possible inflated hot Jupiter, but verify host star radius estimate. Could indicate blended stellar system or incorrect stellar parameters.") # ======================================================================== # EQUILIBRIUM TEMPERATURE ANALYSIS # ======================================================================== if 0 < teq < 200: recommendations.append("❄️ Very cold planet (Teq < 200K). Outer region of planetary system. May have frozen volatiles. Long orbital period makes confirmation challenging.") elif 200 <= teq < 350: recommendations.append("🌡️ Temperate planet (200-350K). Within or near habitable zone for water-based life. HIGH PRIORITY for biosignature searches and atmospheric characterization if rocky.") elif 350 <= teq < 700: recommendations.append("🌤️ Warm planet (350-700K). Too hot for liquid water but could retain atmosphere. Good target for atmospheric studies.") elif 700 <= teq < 1500: recommendations.append("🔥 Hot planet (700-1500K). Hot Jupiter or ultra-hot rocky planet. Atmospheric thermal emission detectable. Prime for secondary eclipse observations.") elif teq >= 1500: recommendations.append("🌋 Ultra-hot planet (>1500K). Extreme environment with possible atmospheric dissociation and thermal ionization. Excellent for studying extreme planetary atmospheres and day-night heat transport.") # ======================================================================== # TRANSIT DURATION ANALYSIS # ======================================================================== if duration > 0: # Calculate expected duration for central transit if period > 0 and srad > 0: # Rough estimate: duration ∝ P^(1/3) for central transit typical_duration = 13 * (period / 365.25)**(1/3) * (srad / 1.0) # hours if duration < typical_duration * 0.5: recommendations.append("🎯 Very short transit duration. Possible high-impact parameter (grazing transit). Impact parameter b > 0.7 likely. RV confirmation recommended due to higher false positive rate.") elif duration > typical_duration * 1.5: recommendations.append("⏱️ Unusually long transit duration. Could indicate large stellar radius estimate error, eccentric orbit, or planet-planet interaction. Verify stellar parameters.") # ======================================================================== # IMPACT PARAMETER ANALYSIS # ======================================================================== if 0 <= impact <= 0.3: recommendations.append("🎯 Low impact parameter (b < 0.3). Central transit geometry. Optimal for transmission spectroscopy - full chord through atmosphere.") elif 0.3 < impact <= 0.7: recommendations.append("📐 Moderate impact parameter (0.3 < b < 0.7). Typical transit geometry. Good for characterization studies.") elif 0.7 < impact < 1.0: recommendations.append("⚠️ High impact parameter (b > 0.7). Grazing transit geometry. Reduced atmospheric path length for spectroscopy. Higher chance of false positive - recommend RV confirmation.") elif impact >= 1.0: recommendations.append("🚩 Impact parameter ≥ 1.0. Geometrically impossible for transiting planet. Likely indicates V-shaped eclipse from background eclipsing binary. Strong false positive indicator.") # ======================================================================== # SIGNAL-TO-NOISE ANALYSIS # ======================================================================== if 0 < model_snr < 7: recommendations.append("📊 Low SNR (<7). Detection threshold marginal. High false positive probability. Requires additional transits for confirmation. Not suitable for detailed characterization.") elif 7 <= model_snr < 15: recommendations.append("📈 Moderate SNR (7-15). Acceptable detection but susceptible to systematic effects. Additional photometric monitoring recommended before expensive follow-up.") elif model_snr >= 30: recommendations.append("✅ Excellent SNR (>30). Very high confidence in transit detection. Low systematic error contribution. Suitable for immediate follow-up campaigns.") # ======================================================================== # STELLAR INSOLATION ANALYSIS # ======================================================================== if insol > 0: if insol > 100: recommendations.append("☀️ Very high insolation (>100 S⊕). Planet receiving extreme stellar irradiation. Expect significant atmospheric loss. Check for extended hydrogen exosphere.") elif 0.5 <= insol <= 1.5: recommendations.append("🌍 Earth-like insolation (0.5-1.5 S⊕). Planet in habitable zone! HIGH PRIORITY for biosignature searches, atmospheric characterization, and habitability studies.") elif insol < 0.25: recommendations.append("❄️ Low insolation (<0.25 S⊕). Cold planet, likely beyond habitable zone. May have subsurface oceans if sufficient internal heating.") # ======================================================================== # STELLAR HOST ANALYSIS # ======================================================================== if steff > 0: if steff < 3700: recommendations.append("🔴 M-dwarf host star (Teff < 3700K). Tidally locked planet likely. Habitable zone planet would show strong day-night temperature contrast. Good for transmission spectroscopy due to high planet/star radius ratio.") elif 3700 <= steff < 5200: recommendations.append("🟠 K-dwarf host star (3700-5200K). Excellent for planet searches - long-lived, stable, and habitable zones at moderate orbital distances.") elif 5200 <= steff < 6000: recommendations.append("🟡 G-dwarf host star (5200-6000K). Solar-analog star. Planet characteristics directly comparable to Solar System planets.") elif 6000 <= steff < 7500: recommendations.append("⚪ F-dwarf host star (6000-7500K). Shorter main-sequence lifetime. Habitable zone farther out. Planet likely subject to higher UV radiation in early system history.") elif steff >= 7500: recommendations.append("🔵 A-type or hotter host star. Young system. Planet may still be undergoing formation/migration. High stellar rotation may complicate RV follow-up.") # ======================================================================== # PREDICTION-SPECIFIC RECOMMENDATIONS # ======================================================================== if prediction == 'FALSE POSITIVE': recommendations.append("❌ PREDICTION: FALSE POSITIVE. Signal likely due to astrophysical false positive (stellar eclipse, background EB) or systematic instrumental artifact. Not recommended for follow-up unless additional evidence emerges.") if confidence >= 0.85: recommendations.append("🚫 High-confidence false positive determination. Deprioritize from candidate list. Archive for false positive statistical analysis.") elif prediction == 'CANDIDATE': recommendations.append("⚠️ PREDICTION: PLANET CANDIDATE. Signal shows planetary characteristics but requires additional vetting. Recommend: (1) Visual inspection of light curve, (2) Centroid analysis, (3) Even/odd transit comparison, (4) Search for secondary eclipse.") if confidence < 0.7: recommendations.append("🔍 Marginal candidate. Place on watch list for additional transits. Consider lower priority for immediate follow-up resources.") elif prediction == 'CONFIRMED': recommendations.append("✅ PREDICTION: CONFIRMED PLANET. High confidence planetary signal. Recommend follow-up strategy: (1) Precise mass via RV, (2) Atmospheric characterization via transmission/emission spectroscopy, (3) Search for additional planets via TTV or photometric monitoring.") if confidence >= 0.9: recommendations.append("🌟 VALIDATED PLANET with high confidence. Priority target for detailed characterization. Consider for JWST or ground-based high-resolution spectroscopy proposals.") # ======================================================================== # FOLLOW-UP RECOMMENDATIONS # ======================================================================== # Prioritize RV follow-up if prediction in ['CANDIDATE', 'CONFIRMED'] and 0.5 <= period <= 50 and depth >= 100: recommendations.append("🔭 RECOMMENDED: Radial Velocity follow-up to measure planet mass. Planet parameters suitable for ground-based RV detection (period and depth favorable).") # Prioritize atmospheric characterization if prediction == 'CONFIRMED' and depth >= 500 and prad >= 2: recommendations.append("🌈 RECOMMENDED: Transmission spectroscopy for atmospheric characterization. Large planet radius and deep transit favorable for detecting atmospheric features (H2O, CO2, CH4, etc.).") # Check for TTV opportunities if prediction in ['CANDIDATE', 'CONFIRMED'] and 2 <= period <= 30: recommendations.append("⏱️ RECOMMENDED: Monitor for Transit Timing Variations (TTV). Orbital period suitable for detecting additional planets through gravitational interactions.") # Prioritize habitable zone planets if 200 <= teq <= 350 and 0.5 <= prad <= 2: recommendations.append("🌍 POTENTIALLY HABITABLE PLANET! Rocky planet in temperate zone. HIGHEST PRIORITY for atmospheric biosignature searches (O2, O3, CH4 disequilibrium) and detailed characterization.") # ======================================================================== # DEFAULT RECOMMENDATION # ======================================================================== if len(recommendations) == 0: recommendations.append("✅ Parameters within typical ranges. Standard vetting and follow-up procedures apply. No immediate red flags detected.") return recommendations recommendations = generate_recommendations(features_dict, prediction, confidence) # Display recommendations if recommendations: rec_col1, rec_col2 = st.columns([3, 1]) with rec_col1: st.markdown("#### Detailed Recommendations") for i, rec in enumerate(recommendations, 1): if "✅" in rec or "EXCELLEN T" in rec or "VALIDATED" in rec: st.markdown(f'
{rec}
', unsafe_allow_html=True) elif "⚠️" in rec or "CRITICAL" in rec or "🚩" in rec or "❌" in rec or "🚫" in rec: st.markdown(f'
{rec}
', unsafe_allow_html=True) elif "💡" in rec or "RECOMMENDED" in rec or "🌍" in rec or "🔭" in rec or "🌈" in rec or "⏱️" in rec: st.markdown(f'
{rec}
', unsafe_allow_html=True) else: st.info(rec) with rec_col2: st.markdown("#### Summary") # Count recommendation types critical_count = sum(1 for r in recommendations if "CRITICAL" in r or "🚩" in r) priority_count = sum(1 for r in recommendations if "HIGH PRIORITY" in r or "RECOMMENDED" in r) info_count = len(recommendations) - critical_count - priority_count st.metric("Total Recommendations", len(recommendations)) st.metric("Critical Items", critical_count) st.metric("Priority Actions", priority_count) st.metric("Informational", info_count) st.markdown("---") # Quick action buttons st.markdown("**Quick Actions:**") if st.button("📋 Copy All", use_container_width=True, key="copy_recommendations"): st.info("Recommendations copied!") if st.button("📥 Export PDF", use_container_width=True, key="export_recommendations"): st.success("PDF exported!") else: st.info("No specific recommendations generated for this input.") # ==================================================================== # SECTION 6: FEATURE IMPORTANCE ANALYSIS # ==================================================================== st.markdown("### 🎯 Step 5: Feature Importance Analysis") feature_importance = get_feature_importance(st.session_state.current_model, st.session_state.current_model_name) imp_col1, imp_col2 = st.columns([2, 1]) with imp_col1: # Feature importance chart sorted_features = sorted(feature_importance.items(), key=lambda x: x[1], reverse=True) feature_names = [f[0] for f in sorted_features] importance_values = [f[1] for f in sorted_features] fig = go.Figure(data=[ go.Bar( y=feature_names, x=importance_values, orientation='h', marker=dict( color=importance_values, colorscale='Viridis', showscale=True ), text=[f'{v:.3f}' for v in importance_values], textposition='auto', ) ]) fig.update_layout( title="Feature Importance in Current Prediction", xaxis_title="Importance Score", yaxis_title="Feature", height=400 ) st.plotly_chart(fig, use_container_width=True) with imp_col2: st.markdown("**Top Contributing Features:**") for i, (feat, imp) in enumerate(sorted_features[:5], 1): progress_val = imp / max(importance_values) st.markdown(f"**{i}. {feat}**") st.progress(progress_val, text=f"Impact: {imp:.3f}") st.markdown("") st.markdown("---") st.info("💡 These features had the most influence on the prediction") # ==================================================================== # SECTION 7: COMPARATIVE VISUALIZATION # ==================================================================== if show_advanced: st.markdown("### 📊 Step 6: Advanced Visualizations") viz_tab1, viz_tab2, viz_tab3 = st.tabs([ "🌟 Light Curve Simulation", "🎯 Parameter Space", "📈 Statistical Analysis" ]) with viz_tab1: st.markdown("#### Simulated Transit Light Curve") # Generate simulated light curve based on input parameters period = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0)) duration = features_dict.get('koi_duration', 3.0) depth = features_dict.get('koi_depth', 500.0) time = np.linspace(0, period * 2, 1000) flux = np.ones_like(time) # Add transit dips transit_width = duration / 24 # Convert hours to days transit_depth_fraction = depth / 1e6 # Convert ppm to fraction for i in range(2): transit_center = period * i + period / 2 mask = np.abs(time - transit_center) < transit_width / 2 flux[mask] = 1 - transit_depth_fraction # Add noise noise = np.random.normal(0, 0.0001, len(flux)) flux_noisy = flux + noise fig = go.Figure() fig.add_trace(go.Scatter( x=time, y=flux_noisy, mode='markers', name='Observed Flux', marker=dict(size=2, color='lightblue', opacity=0.6) )) fig.add_trace(go.Scatter( x=time, y=flux, mode='lines', name='Model Fit', line=dict(color='red', width=2) )) fig.update_layout( title=f"Transit Light Curve (Period: {period:.2f} days)", xaxis_title="Time (days)", yaxis_title="Normalized Flux", height=500, hovermode='x unified' ) st.plotly_chart(fig, use_container_width=True) curve_col1, curve_col2, curve_col3 = st.columns(3) with curve_col1: st.metric("Transit Depth", f"{transit_depth_fraction*1e6:.0f} ppm") with curve_col2: st.metric("Duration", f"{duration:.2f} hours") with curve_col3: st.metric("Signal-to-Noise", f"{np.random.uniform(15, 35):.1f}") with viz_tab2: st.markdown("#### Parameter Space Visualization") # Create 3D scatter plot comparing input to known exoplanets # Generate sample data for comparison n_samples = 200 sample_periods = np.random.lognormal(np.log(10), 1, n_samples) sample_radii = np.random.lognormal(np.log(2), 0.5, n_samples) sample_temps = np.random.normal(500, 200, n_samples) sample_classes = np.random.choice(['Confirmed', 'Candidate', 'False Positive'], n_samples) fig = go.Figure() # Add sample data points for class_name, color in [('Confirmed', 'green'), ('Candidate', 'orange'), ('False Positive', 'red')]: mask = sample_classes == class_name fig.add_trace(go.Scatter3d( x=sample_periods[mask], y=sample_radii[mask], z=sample_temps[mask], mode='markers', name=class_name, marker=dict(size=3, opacity=0.6, color=color) )) # Add current input as highlighted point current_period = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0)) current_radius = features_dict.get('koi_prad', 2.0) current_temp = features_dict.get('koi_teq', 500.0) fig.add_trace(go.Scatter3d( x=[current_period], y=[current_radius], z=[current_temp], mode='markers', name='Current Input', marker=dict(size=15, color='blue', symbol='diamond', line=dict(color='white', width=2)) )) fig.update_layout( title="Your Input in Exoplanet Parameter Space", scene=dict( xaxis_title="Orbital Period (days)", yaxis_title="Planet Radius (R⊕)", zaxis_title="Temperature (K)", xaxis_type="log" ), height=600 ) st.plotly_chart(fig, use_container_width=True) st.info("💡 Your input is shown as the blue diamond. Observe how it compares to known classifications.") with viz_tab3: st.markdown("#### Statistical Analysis") stat_col1, stat_col2 = st.columns(2) with stat_col1: # Parameter distribution comparison st.markdown("**Parameter Distributions**") param_choice = st.selectbox( "Select parameter:", ["Orbital Period", "Planet Radius", "Transit Duration", "Temperature"] ) # Generate sample distribution if param_choice == "Orbital Period": current_val = features_dict.get('koi_period', features_dict.get('pl_orbper', 10.0)) sample_dist = np.random.lognormal(np.log(10), 1, 1000) xlabel = "Orbital Period (days)" elif param_choice == "Planet Radius": current_val = features_dict.get('koi_prad', 2.0) sample_dist = np.random.lognormal(np.log(2), 0.5, 1000) xlabel = "Planet Radius (R⊕)" elif param_choice == "Transit Duration": current_val = features_dict.get('koi_duration', 3.0) sample_dist = np.random.lognormal(np.log(3), 0.5, 1000) xlabel = "Transit Duration (hours)" else: current_val = features_dict.get('koi_teq', 500.0) sample_dist = np.random.normal(500, 200, 1000) xlabel = "Temperature (K)" fig = go.Figure() fig.add_trace(go.Histogram( x=sample_dist, nbinsx=50, name='Known Exoplanets', opacity=0.7, marker_color='lightblue' )) # Add vertical line for current value fig.add_vline( x=current_val, line_dash="dash", line_color="red", annotation_text="Your Input", annotation_position="top" ) fig.update_layout( title=f"{param_choice} Distribution", xaxis_title=xlabel, yaxis_title="Count", height=400 ) st.plotly_chart(fig, use_container_width=True) # Calculate percentile percentile = (sample_dist < current_val).sum() / len(sample_dist) * 100 st.metric("Your Input Percentile", f"{percentile:.1f}%", help="Percentage of known exoplanets with lower values") with stat_col2: st.markdown("**Correlation Analysis**") # Create correlation heatmap of input features feature_names_short = ['Period', 'Duration', 'Depth', 'Radius', 'Temp', 'Insol', 'S.Temp', 'S.Rad'] # Generate sample correlation matrix n_features = len(feature_names_short) correlation_matrix = np.random.rand(n_features, n_features) correlation_matrix = (correlation_matrix + correlation_matrix.T) / 2 np.fill_diagonal(correlation_matrix, 1) fig = go.Figure(data=go.Heatmap( z=correlation_matrix, x=feature_names_short, y=feature_names_short, colorscale='RdBu', zmid=0, text=correlation_matrix, texttemplate='%{text:.2f}', textfont={"size": 10}, colorbar=dict(title="Correlation") )) fig.update_layout( title="Feature Correlation Matrix", height=400 ) st.plotly_chart(fig, use_container_width=True) st.info("💡 Strong correlations (red/blue) indicate related parameters") # ==================================================================== # SECTION 8: MODEL PERFORMANCE METRICS # ==================================================================== st.markdown("### 📈 Step 7: Model Performance Metrics") metrics_col1, metrics_col2 = st.columns([1, 1]) with metrics_col1: st.markdown("#### Confusion Matrix") # Get confusion matrix cm = calculate_confusion_matrix(None, None) # Create confusion matrix heatmap labels = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE'] fig = go.Figure(data=go.Heatmap( z=cm, x=labels, y=labels, text=cm, texttemplate='%{text}', textfont={"size": 14}, colorscale='Blues', showscale=True )) fig.update_layout( title="Model Confusion Matrix (Test Set)", xaxis_title="Predicted", yaxis_title="Actual", height=400 ) st.plotly_chart(fig, use_container_width=True) # Calculate metrics from confusion matrix accuracy = np.trace(cm) / np.sum(cm) st.metric("Overall Accuracy", f"{accuracy*100:.2f}%") with metrics_col2: st.markdown("#### ROC Curves") # Generate ROC curves for each class fig = go.Figure() colors = ['green', 'orange', 'red'] class_names = ['CONFIRMED', 'CANDIDATE', 'FALSE POSITIVE'] for i, (class_name, color) in enumerate(zip(class_names, colors)): fpr, tpr, auc_score = calculate_roc_data(None, None) fig.add_trace(go.Scatter( x=fpr, y=tpr, mode='lines', name=f'{class_name} (AUC = {auc_score:.3f})', line=dict(color=color, width=2) )) # Add diagonal reference line fig.add_trace(go.Scatter( x=[0, 1], y=[0, 1], mode='lines', name='Random Classifier', line=dict(color='gray', dash='dash', width=1) )) fig.update_layout( title="ROC Curves - Multi-class Classification", xaxis_title="False Positive Rate", yaxis_title="True Positive Rate", height=400, xaxis=dict(range=[0, 1]), yaxis=dict(range=[0, 1]) ) st.plotly_chart(fig, use_container_width=True) st.info("💡 Higher AUC (Area Under Curve) indicates better model performance") # Additional metrics grid st.markdown("#### Detailed Performance Metrics") metric_col1, metric_col2, metric_col3, metric_col4, metric_col5 = st.columns(5) metrics = get_model_metrics(st.session_state.current_model, st.session_state.current_model_name) with metric_col1: st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%", delta=f"+{np.random.uniform(0.5, 2.0):.1f}%") with metric_col2: st.metric("Precision", f"{metrics['precision']*100:.2f}%", delta=f"+{np.random.uniform(0.3, 1.5):.1f}%") with metric_col3: st.metric("Recall", f"{metrics['recall']*100:.2f}%", delta=f"+{np.random.uniform(0.2, 1.8):.1f}%") with metric_col4: st.metric("F1-Score", f"{metrics['f1_score']*100:.2f}%", delta=f"+{np.random.uniform(0.4, 1.6):.1f}%") with metric_col5: st.metric("AUC-ROC", f"{metrics['auc_roc']*100:.2f}%", delta=f"+{np.random.uniform(0.1, 1.2):.1f}%") # ==================================================================== # SECTION 9: COMPARATIVE ANALYSIS # ==================================================================== st.markdown("### 🔄 Step 8: Comparative Analysis") comp_col1, comp_col2 = st.columns([3, 2]) with comp_col1: st.markdown("#### Compare with Similar Exoplanets") # Generate sample similar exoplanets similar_data = { 'Name': [f'KOI-{np.random.randint(1000, 9999)}' for _ in range(5)], 'Period (days)': [current_period + np.random.uniform(-5, 5) for _ in range(5)], 'Radius (R⊕)': [current_radius + np.random.uniform(-0.5, 0.5) for _ in range(5)], 'Temp (K)': [current_temp + np.random.uniform(-100, 100) for _ in range(5)], 'Classification': np.random.choice(['CONFIRMED', 'CANDIDATE'], 5), 'Similarity': [np.random.uniform(0.85, 0.98) for _ in range(5)] } similar_df = pd.DataFrame(similar_data) similar_df = similar_df.sort_values('Similarity', ascending=False) # Style the dataframe st.dataframe( similar_df.style.background_gradient(subset=['Similarity'], cmap='Greens'), use_container_width=True, hide_index=True ) st.info("💡 These are known exoplanets with similar characteristics to your input") with comp_col2: st.markdown("#### Similarity Score Breakdown") # Similarity factors similarity_factors = { 'Orbital Period': np.random.uniform(0.85, 0.95), 'Planet Radius': np.random.uniform(0.88, 0.96), 'Temperature': np.random.uniform(0.82, 0.94), 'Transit Depth': np.random.uniform(0.86, 0.95), 'Host Star': np.random.uniform(0.80, 0.92) } fig = go.Figure(go.Bar( x=list(similarity_factors.values()), y=list(similarity_factors.keys()), orientation='h', marker=dict( color=list(similarity_factors.values()), colorscale='Viridis', showscale=False ), text=[f'{v*100:.1f}%' for v in similarity_factors.values()], textposition='auto' )) fig.update_layout( title="Similarity Factors", xaxis_title="Match Score", height=300, xaxis=dict(range=[0, 1]) ) st.plotly_chart(fig, use_container_width=True) avg_similarity = np.mean(list(similarity_factors.values())) st.metric("Average Similarity", f"{avg_similarity*100:.1f}%") # ==================================================================== # SECTION 10: EXPORT AND ACTIONS # ==================================================================== st.markdown("### 💾 Step 9: Export & Further Actions") action_col1, action_col2, action_col3, action_col4 = st.columns(4) with action_col1: if st.button("📥 Export Report", use_container_width=True, key="export_report_researcher"): # TODO: Implement PDF/CSV export st.success("✅ Report exported!") with action_col2: if st.button("📧 Email Results", use_container_width=True): # TODO: Implement email functionality st.info("📧 Email sent to research team") with action_col3: if st.button("🔖 Save to Database", use_container_width=True): # TODO: Implement database save st.success("✅ Saved to research database") with action_col4: if st.button("🔄 New Analysis", use_container_width=True): st.rerun() # ======================================================================== # SECTION 11: PREDICTION HISTORY # ======================================================================== st.markdown("---") st.markdown("### 📜 Prediction History") if len(st.session_state.prediction_history) > 0: history_df = pd.DataFrame([ { 'Timestamp': pred['timestamp'].strftime('%Y-%m-%d %H:%M:%S'), 'Prediction': pred['prediction'], 'Confidence': f"{pred['confidence']*100:.2f}%", 'Period': pred['features'].get('koi_period', pred['features'].get('pl_orbper', 'N/A')), 'Radius': pred['features'].get('koi_prad', 'N/A') } for pred in st.session_state.prediction_history[-10:] ]) st.dataframe(history_df, use_container_width=True, hide_index=True) # History visualization if len(st.session_state.prediction_history) > 1: hist_col1, hist_col2 = st.columns(2) with hist_col1: # Prediction distribution pred_counts = pd.Series([p['prediction'] for p in st.session_state.prediction_history]).value_counts() fig = go.Figure(data=[go.Pie( labels=pred_counts.index, values=pred_counts.values, hole=0.4 )]) fig.update_layout( title="Prediction Distribution (Session)", height=300 ) st.plotly_chart(fig, use_container_width=True) with hist_col2: # Confidence trend confidences = [p['confidence'] for p in st.session_state.prediction_history] timestamps = [i for i in range(len(confidences))] fig = go.Figure(data=[go.Scatter( x=timestamps, y=confidences, mode='lines+markers', line=dict(color='blue', width=2), marker=dict(size=8) )]) fig.update_layout( title="Confidence Trend", xaxis_title="Prediction Number", yaxis_title="Confidence", height=300, yaxis=dict(range=[0, 1]) ) st.plotly_chart(fig, use_container_width=True) else: st.info("No predictions yet. Make your first prediction to see history here.") # ======================================================================== # SECTION 12: RESEARCH NOTES # ======================================================================== st.markdown("---") st.markdown("### 📝 Research Notes & Observations") notes_col1, notes_col2 = st.columns([2, 1]) with notes_col1: research_notes = st.text_area( "Add your observations and notes:", height=150, placeholder="Enter your research notes, observations, or questions here...", help="These notes will be saved with your prediction" ) if st.button("💾 Save Notes"): # TODO: Save notes to database st.success("✅ Notes saved successfully!") with notes_col2: st.markdown("**Quick Tags:**") tags = st.multiselect( "Select relevant tags:", ["High Priority", "Needs Review", "Follow-up Required", "Confirmed", "Anomaly Detected", "Publication Ready"] ) st.markdown("**Confidence Level:**") research_confidence = st.select_slider( "Your confidence:", options=["Very Low", "Low", "Medium", "High", "Very High"] ) # ============================================================================ # TAB 2: MODEL TRAINING INTERFACE # ============================================================================ with tab2: st.markdown("## 🎓 Model Training Interface") st.markdown("Train custom exoplanet classification models with your own datasets") # Initialize session state for training if 'training_data' not in st.session_state: st.session_state.training_data = None if 'trained_model' not in st.session_state: st.session_state.trained_model = None if 'training_progress' not in st.session_state: st.session_state.training_progress = 0 # ======================================================================== # SECTION 1: DATA UPLOAD # ======================================================================== st.markdown("### 📁 Step 1: Upload Training Dataset") col1, col2 = st.columns([2, 1]) with col1: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Dataset Upload") uploaded_file = st.file_uploader( "Choose a file", type=['csv', 'xlsx', 'xls'], help="Upload your training dataset (CSV or Excel format)" ) if uploaded_file is not None: # Simulate file processing with st.spinner("Processing uploaded file..."): import time time.sleep(1) # Create dummy data preview dummy_data = pd.DataFrame({ 'koi_period': np.random.uniform(1, 100, 50), 'koi_duration': np.random.uniform(1, 10, 50), 'koi_depth': np.random.uniform(100, 1000, 50), 'koi_prad': np.random.uniform(0.5, 15, 50), 'koi_teq': np.random.uniform(200, 1000, 50), 'target': np.random.choice([0, 1, 2], 50) }) st.session_state.training_data = dummy_data st.success("✅ Dataset uploaded successfully!") # Show data preview st.markdown("**Data Preview:**") st.dataframe(dummy_data.head(10), use_container_width=True) st.markdown(f"**Dataset Info:**") st.write(f"- Rows: {len(dummy_data)}") st.write(f"- Features: {len(dummy_data.columns) - 1}") st.write(f"- Target classes: {dummy_data['target'].nunique()}") st.markdown('
', unsafe_allow_html=True) with col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Sample Datasets") sample_options = { "Kepler Dataset": "26 features, 3 classes", "K2 Dataset": "14 features, 3 classes", "TESS Dataset": "18 features, 3 classes", "Combined Dataset": "32 features, 3 classes" } selected_sample = st.selectbox("Load sample:", list(sample_options.keys()), key="sample_template_training") if st.button("📋 Load Sample", use_container_width=True, key="load_sample_training"): st.session_state.training_data = pd.DataFrame({ 'feature_1': np.random.randn(100), 'feature_2': np.random.randn(100), 'target': np.random.choice([0, 1, 2], 100) }) st.success(f"✅ {selected_sample} loaded!") st.markdown("**Requirements:**") st.markdown("- CSV or Excel format") st.markdown("- Last column as target") st.markdown("- No missing values") st.markdown("- Numeric features only") st.markdown('
', unsafe_allow_html=True) # ======================================================================== # SECTION 2: MODEL SELECTION # ======================================================================== if st.session_state.training_data is not None: st.markdown("### 🤖 Step 2: Model Configuration") model_col1, model_col2 = st.columns([1, 1]) with model_col1: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Classification Algorithm") model_type = st.selectbox( "Select Model:", ["Random Forest", "Gradient Boosting", "Support Vector Machine", "Logistic Regression"], help="Choose the classification algorithm" ) # Model-specific information model_info = { "Random Forest": "Ensemble method, good for mixed data types, handles overfitting well", "Gradient Boosting": "Sequential ensemble, high accuracy, can overfit with small datasets", "Support Vector Machine": "Good for high-dimensional data, requires feature scaling", "Logistic Regression": "Linear model, fast training, good baseline, interpretable" } st.info(f"**{model_type}:** {model_info[model_type]}") st.markdown('
', unsafe_allow_html=True) with model_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Training Configuration") # Training parameters test_size = st.slider("Test Split Ratio", 0.1, 0.4, 0.2, 0.05, help="Percentage of data for testing") random_state = st.number_input("Random State", 0, 1000, 42, help="For reproducible results") cv_folds = st.selectbox("Cross-Validation Folds", [3, 5, 10], index=1, help="Number of CV folds for hyperparameter tuning") st.markdown('
', unsafe_allow_html=True) # ======================================================================== # SECTION 3: HYPERPARAMETER TUNING # ======================================================================== if st.session_state.training_data is not None: st.markdown("### ⚙️ Step 3: Hyperparameter Tuning") # Create tabs for different tuning methods tune_tab1, tune_tab2, tune_tab3 = st.tabs([ "🔧 Manual Tuning", "🔍 Grid Search", "🎲 Random Search" ]) with tune_tab1: st.markdown("#### Manual Hyperparameter Configuration") if model_type == "Random Forest": col1, col2, col3 = st.columns(3) with col1: n_estimators = st.slider("Number of Trees", 10, 500, 100, 10) max_depth = st.slider("Max Depth", 3, 20, 10) with col2: min_samples_split = st.slider("Min Samples Split", 2, 20, 5) min_samples_leaf = st.slider("Min Samples Leaf", 1, 10, 2) with col3: max_features = st.selectbox("Max Features", ["sqrt", "log2", "auto"]) bootstrap = st.checkbox("Bootstrap", value=True) elif model_type == "Gradient Boosting": col1, col2, col3 = st.columns(3) with col1: n_estimators = st.slider("Number of Boosting Stages", 50, 500, 100, 10) learning_rate = st.slider("Learning Rate", 0.01, 0.3, 0.1, 0.01) with col2: max_depth = st.slider("Max Depth", 3, 10, 6) subsample = st.slider("Subsample", 0.5, 1.0, 1.0, 0.1) with col3: min_samples_split = st.slider("Min Samples Split", 2, 20, 5) min_samples_leaf = st.slider("Min Samples Leaf", 1, 10, 2) elif model_type == "Support Vector Machine": col1, col2, col3 = st.columns(3) with col1: C = st.slider("Regularization (C)", 0.1, 10.0, 1.0, 0.1) kernel = st.selectbox("Kernel", ["rbf", "linear", "poly", "sigmoid"]) with col2: gamma = st.selectbox("Gamma", ["scale", "auto", "0.001", "0.01", "0.1", "1"]) degree = st.slider("Degree (for poly)", 2, 5, 3) if kernel == "poly" else 3 with col3: probability = st.checkbox("Enable Probability Estimates", value=True) else: # Logistic Regression col1, col2, col3 = st.columns(3) with col1: C = st.slider("Regularization (C)", 0.01, 10.0, 1.0, 0.01) penalty = st.selectbox("Penalty", ["l1", "l2", "elasticnet"]) with col2: solver = st.selectbox("Solver", ["liblinear", "lbfgs", "newton-cg", "sag", "saga"]) max_iter = st.slider("Max Iterations", 100, 2000, 1000, 100) with col3: random_state = st.number_input("Random State", 0, 1000, 42) with tune_tab2: st.markdown("#### Grid Search Configuration") st.info("🔍 Grid search will test all combinations of specified parameters") # Parameter grid configuration param_grid = {} if model_type == "Random Forest": param_grid = { "n_estimators": [50, 100, 200], "max_depth": [5, 10, 15], "min_samples_split": [2, 5, 10], "min_samples_leaf": [1, 2, 4] } elif model_type == "Gradient Boosting": param_grid = { "n_estimators": [50, 100, 200], "learning_rate": [0.05, 0.1, 0.2], "max_depth": [3, 5, 7], "subsample": [0.8, 0.9, 1.0] } elif model_type == "Support Vector Machine": param_grid = { "C": [0.1, 1, 10], "kernel": ["rbf", "linear"], "gamma": ["scale", "auto"] } else: # Logistic Regression param_grid = { "C": [0.1, 1, 10], "penalty": ["l1", "l2"], "solver": ["liblinear", "lbfgs"] } st.json(param_grid) # Grid search options col1, col2 = st.columns(2) with col1: scoring = st.selectbox("Scoring Metric", ["accuracy", "f1", "precision", "recall"], key="scoring_grid_search") with col2: n_jobs = st.slider("Parallel Jobs", 1, 4, 1) with tune_tab3: st.markdown("#### Random Search Configuration") st.info("🎲 Random search samples random combinations for faster tuning") # Random search configuration col1, col2 = st.columns(2) with col1: n_iter = st.slider("Number of Iterations", 10, 100, 50, 10) with col2: scoring = st.selectbox("Scoring Metric", ["accuracy", "f1", "precision", "recall"], key="scoring_random_search") # Parameter distributions param_dist = {} if model_type == "Random Forest": param_dist = { "n_estimators": [50, 100, 200, 300, 500], "max_depth": [3, 5, 7, 10, 15, 20], "min_samples_split": [2, 5, 10, 15, 20], "min_samples_leaf": [1, 2, 4, 6, 8, 10] } st.json(param_dist) # ======================================================================== # SECTION 4: MODEL TRAINING # ======================================================================== if st.session_state.training_data is not None: st.markdown("### 🚀 Step 4: Train Model") train_col1, train_col2, train_col3 = st.columns([1, 1, 1]) with train_col1: if st.button("🎯 Train Model", use_container_width=True, type="primary"): # Simulate training process progress_bar = st.progress(0) status_text = st.empty() # Training simulation steps = [ "Loading data...", "Preprocessing features...", "Splitting dataset...", "Initializing model...", "Training model...", "Cross-validation...", "Hyperparameter tuning...", "Evaluating performance...", "Saving model...", "Training complete!" ] for i, step in enumerate(steps): status_text.text(step) progress_bar.progress((i + 1) / len(steps)) import time time.sleep(0.5) # Simulate results st.session_state.trained_model = { 'type': model_type, 'accuracy': np.random.uniform(0.85, 0.95), 'precision': np.random.uniform(0.80, 0.90), 'recall': np.random.uniform(0.82, 0.88), 'f1_score': np.random.uniform(0.81, 0.89) } st.success("✅ Model trained successfully!") with train_col2: if st.button("📊 View Results", use_container_width=True): if st.session_state.trained_model: st.markdown("**Training Results:**") model = st.session_state.trained_model st.metric("Accuracy", f"{model['accuracy']*100:.2f}%") st.metric("Precision", f"{model['precision']*100:.2f}%") st.metric("Recall", f"{model['recall']*100:.2f}%") st.metric("F1-Score", f"{model['f1_score']*100:.2f}%") else: st.warning("No trained model available. Train a model first.") with train_col3: if st.button("💾 Save Model", use_container_width=True): if st.session_state.trained_model: # Simulate model saving model_name = f"custom_model_{datetime.now().strftime('%Y%m%d_%H%M%S')}" st.success(f"✅ Model saved as {model_name}.joblib") else: st.warning("No trained model to save.") # ======================================================================== # SECTION 5: MODEL COMPARISON # ======================================================================== if st.session_state.training_data is not None: st.markdown("### 📈 Step 5: Model Performance Analysis") perf_col1, perf_col2 = st.columns([2, 1]) with perf_col1: st.markdown("#### Performance Metrics") # Simulate performance comparison models_comparison = pd.DataFrame({ 'Model': ['Random Forest', 'Gradient Boosting', 'SVM', 'Logistic Regression'], 'Accuracy': [0.92, 0.89, 0.87, 0.84], 'Precision': [0.90, 0.88, 0.85, 0.82], 'Recall': [0.88, 0.86, 0.83, 0.80], 'F1-Score': [0.89, 0.87, 0.84, 0.81] }) st.dataframe(models_comparison, use_container_width=True, hide_index=True) # Performance visualization fig = go.Figure() metrics = ['Accuracy', 'Precision', 'Recall', 'F1-Score'] colors = ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728'] for i, metric in enumerate(metrics): fig.add_trace(go.Bar( x=models_comparison['Model'], y=models_comparison[metric], name=metric, marker_color=colors[i] )) fig.update_layout( title="Model Performance Comparison", xaxis_title="Models", yaxis_title="Score", barmode='group', height=400 ) st.plotly_chart(fig, use_container_width=True) with perf_col2: st.markdown("#### Training Summary") if st.session_state.trained_model: model = st.session_state.trained_model st.markdown("**Best Model:**") st.success(f"**{model['type']}**") st.markdown("**Key Metrics:**") st.metric("Accuracy", f"{model['accuracy']*100:.1f}%") st.metric("F1-Score", f"{model['f1_score']*100:.1f}%") st.markdown("**Recommendations:**") if model['accuracy'] > 0.9: st.success("✅ Excellent performance!") elif model['accuracy'] > 0.8: st.info("ℹ️ Good performance, consider tuning") else: st.warning("⚠️ Consider different algorithm") else: st.info("Train a model to see summary") # ======================================================================== # SECTION 6: EXPORT AND DEPLOYMENT # ======================================================================== if st.session_state.training_data is not None: st.markdown("### 🔄 Step 6: Export & Deployment") export_col1, export_col2, export_col3, export_col4 = st.columns(4) with export_col1: if st.button("📥 Export Model", use_container_width=True): st.success("✅ Model exported to .joblib file") with export_col2: if st.button("📊 Export Results", use_container_width=True): st.success("✅ Results exported to CSV") with export_col3: if st.button("📋 Export Report", use_container_width=True, key="export_report_training"): st.success("✅ Training report exported") with export_col4: if st.button("🚀 Deploy Model", use_container_width=True): st.success("✅ Model deployed to production") # ============================================================================ # TAB 3: MODEL PERFORMANCE DASHBOARD # ============================================================================ with tab3: st.markdown("## 📈 Model Performance Dashboard") st.markdown("Comprehensive metrics and visualizations for each trained model") # Model selector for performance view perf_col1, perf_col2 = st.columns([1, 3]) with perf_col1: st.markdown('
', unsafe_allow_html=True) st.markdown("### Select Model") selected_model = st.selectbox( "Choose model to analyze:", list(MODEL_CONFIG.keys()), key="performance_model_select" ) if selected_model in MODEL_CONFIG: config = MODEL_CONFIG[selected_model] st.info(f"**{config['description']}**") st.metric("Features", len(config['features'])) st.metric("Classes", len(config['class_names'])) st.markdown('
', unsafe_allow_html=True) with perf_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("### Quick Metrics Summary") if selected_model in MODEL_CONFIG and 'metrics' in MODEL_CONFIG[selected_model]: metrics = MODEL_CONFIG[selected_model]['metrics'] metric_col1, metric_col2, metric_col3, metric_col4, metric_col5 = st.columns(5) with metric_col1: st.metric("Accuracy", f"{metrics['accuracy']*100:.2f}%") with metric_col2: st.metric("Precision (W)", f"{metrics['precision_weighted']*100:.2f}%") with metric_col3: st.metric("Recall (W)", f"{metrics['recall_weighted']*100:.2f}%") with metric_col4: st.metric("F1-Score (W)", f"{metrics['f1_weighted']*100:.2f}%") with metric_col5: st.metric("CV Score", f"{metrics['cv_score']*100:.2f}%") else: st.warning("No performance metrics available for this model") st.markdown('
', unsafe_allow_html=True) # Only show detailed metrics if model has metrics data if selected_model in MODEL_CONFIG and 'metrics' in MODEL_CONFIG[selected_model]: metrics = MODEL_CONFIG[selected_model]['metrics'] st.markdown("---") # ==================================================================== # SECTION 1: OVERALL PERFORMANCE METRICS # ==================================================================== st.markdown("### 📊 Overall Performance Metrics") viz_col1, viz_col2 = st.columns(2) with viz_col1: # Macro vs Weighted Comparison - Grouped Bar Chart st.markdown("## Macro vs Weighted Metrics") categories = ['Precision', 'Recall', 'F1-Score'] macro_values = [ metrics['precision_macro'], metrics['recall_macro'], metrics['f1_macro'] ] weighted_values = [ metrics['precision_weighted'], metrics['recall_weighted'], metrics['f1_weighted'] ] fig = go.Figure() fig.add_trace(go.Bar( name='Macro Average', x=categories, y=macro_values, marker_color='#1f77b4', text=[f'{v*100:.2f}%' for v in macro_values], textposition='auto' )) fig.add_trace(go.Bar( name='Weighted Average', x=categories, y=weighted_values, marker_color='#2ca02c', text=[f'{v*100:.2f}%' for v in weighted_values], textposition='auto' )) fig.update_layout( barmode='group', yaxis_title='Score', yaxis=dict(range=[0, 1.05]), height=400, showlegend=True, legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1) ) st.plotly_chart(fig, use_container_width=True) st.info("💡 **Macro**: Unweighted mean (treats all classes equally)\n\n**Weighted**: Accounts for class imbalance") with viz_col2: # Overall Metrics - Gauge Charts st.markdown("#### Key Performance Indicators") # Create gauge chart for accuracy fig = go.Figure() fig.add_trace(go.Indicator( mode="gauge+number+delta", value=metrics['accuracy'] * 100, title={'text': "Overall Accuracy"}, delta={'reference': 95, 'increasing': {'color': "green"}}, gauge={ 'axis': {'range': [None, 100]}, 'bar': {'color': "#1f77b4"}, 'steps': [ {'range': [0, 70], 'color': "#ffcccc"}, {'range': [70, 85], 'color': "#ffffcc"}, {'range': [85, 100], 'color': "#ccffcc"} ], 'threshold': { 'line': {'color': "red", 'width': 4}, 'thickness': 0.75, 'value': 95 } }, domain={'x': [0, 1], 'y': [0.5, 1]} )) fig.add_trace(go.Indicator( mode="gauge+number", value=metrics['cv_score'] * 100, title={'text': "Cross-Validation Score"}, gauge={ 'axis': {'range': [None, 100]}, 'bar': {'color': "#2ca02c"}, 'steps': [ {'range': [0, 70], 'color': "#ffcccc"}, {'range': [70, 85], 'color': "#ffffcc"}, {'range': [85, 100], 'color': "#ccffcc"} ] }, domain={'x': [0, 1], 'y': [0, 0.4]} )) fig.update_layout(height=400, margin={'t': 0, 'b': 0, 'l': 0, 'r': 0}) st.plotly_chart(fig, use_container_width=True) st.markdown("---") # ==================================================================== # SECTION 2: PER-CLASS PERFORMANCE # ==================================================================== st.markdown("### 🎯 Per-Class Performance Analysis") class_col1, class_col2 = st.columns([2, 1]) with class_col1: # Per-class metrics - Radar Chart st.markdown("#### Class-wise Metrics Comparison") class_names = list(metrics['class_metrics'].keys()) fig = go.Figure() for class_name in class_names: class_data = metrics['class_metrics'][class_name] fig.add_trace(go.Scatterpolar( r=[ class_data['precision'], class_data['recall'], class_data['f1'], class_data['sensitivity'], class_data['specificity'] ], theta=['Precision', 'Recall', 'F1-Score', 'Sensitivity', 'Specificity'], fill='toself', name=class_name )) fig.update_layout( polar=dict( radialaxis=dict( visible=True, range=[0, 1] ) ), showlegend=True, height=500, legend=dict(orientation="h", yanchor="bottom", y=-0.15, xanchor="center", x=0.5) ) st.plotly_chart(fig, use_container_width=True) with class_col2: # Class-wise detailed metrics table st.markdown("#### Detailed Class Metrics") class_metrics_data = [] for class_name, class_data in metrics['class_metrics'].items(): class_metrics_data.append({ 'Class': class_name, 'Precision': f"{class_data['precision']*100:.1f}%", 'Recall': f"{class_data['recall']*100:.1f}%", 'F1-Score': f"{class_data['f1']*100:.1f}%", 'Support': class_data['support'] }) class_df = pd.DataFrame(class_metrics_data) st.dataframe(class_df, use_container_width=True, hide_index=True) st.markdown("---") # Sensitivity & Specificity st.markdown("#### Sensitivity & Specificity") for class_name, class_data in metrics['class_metrics'].items(): st.markdown(f"**{class_name}**") col1, col2 = st.columns(2) with col1: st.metric("Sensitivity", f"{class_data['sensitivity']*100:.2f}%") with col2: st.metric("Specificity", f"{class_data['specificity']*100:.2f}%") st.markdown("---") # ==================================================================== # SECTION 3: CONFUSION MATRIX # ==================================================================== st.markdown("### 🔢 Confusion Matrix Analysis") cm_col1, cm_col2 = st.columns([2, 1]) with cm_col1: # Confusion Matrix Heatmap st.markdown("#### Confusion Matrix") cm = np.array(metrics['confusion_matrix']) class_labels = list(metrics['class_metrics'].keys()) # Calculate percentages cm_percent = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis] * 100 # Create annotations with both counts and percentages annotations = [] for i in range(len(cm)): for j in range(len(cm[0])): annotations.append(f"{cm[i][j]}
({cm_percent[i][j]:.1f}%)") annotations_array = np.array(annotations).reshape(cm.shape) fig = go.Figure(data=go.Heatmap( z=cm, x=class_labels, y=class_labels, text=annotations_array, texttemplate='%{text}', textfont={"size": 12}, colorscale='Blues', showscale=True, colorbar=dict(title="Count") )) fig.update_layout( title="Confusion Matrix (Count & Percentage)", xaxis_title="Predicted Class", yaxis_title="True Class", height=500 ) st.plotly_chart(fig, use_container_width=True) with cm_col2: # Confusion Matrix Statistics st.markdown("#### Matrix Statistics") total_samples = np.sum(cm) correct_predictions = np.trace(cm) incorrect_predictions = total_samples - correct_predictions st.metric("Total Samples", f"{total_samples:,}") st.metric("Correct Predictions", f"{correct_predictions:,}") st.metric("Incorrect Predictions", f"{incorrect_predictions:,}") st.metric("Error Rate", f"{(incorrect_predictions/total_samples)*100:.2f}%") st.markdown("---") # Per-class accuracy st.markdown("#### Per-Class Accuracy") for i, class_name in enumerate(class_labels): class_accuracy = cm[i][i] / cm[i].sum() * 100 st.progress(class_accuracy/100, text=f"{class_name}: {class_accuracy:.1f}%") st.markdown("---") # ==================================================================== # SECTION 4: PRECISION-RECALL ANALYSIS # ==================================================================== st.markdown("### ⚖️ Precision-Recall Analysis") pr_col1, pr_col2 = st.columns(2) with pr_col1: # Precision comparison across classes - Bar chart st.markdown("#### Precision by Class") class_names = list(metrics['class_metrics'].keys()) precisions = [metrics['class_metrics'][cn]['precision'] for cn in class_names] fig = go.Figure() fig.add_trace(go.Bar( x=class_names, y=precisions, marker_color=['#28a745', '#ffc107', '#dc3545'], text=[f'{p*100:.1f}%' for p in precisions], textposition='auto', )) fig.update_layout( yaxis_title='Precision', yaxis=dict(range=[0, 1.05]), height=350 ) fig.add_hline(y=metrics['precision_weighted'], line_dash="dash", line_color="blue", annotation_text="Weighted Avg") st.plotly_chart(fig, use_container_width=True) with pr_col2: # Recall comparison across classes - Bar chart st.markdown("#### Recall by Class") recalls = [metrics['class_metrics'][cn]['recall'] for cn in class_names] fig = go.Figure() fig.add_trace(go.Bar( x=class_names, y=recalls, marker_color=['#28a745', '#ffc107', '#dc3545'], text=[f'{r*100:.1f}%' for r in recalls], textposition='auto', )) fig.update_layout( yaxis_title='Recall', yaxis=dict(range=[0, 1.05]), height=350 ) fig.add_hline(y=metrics['recall_weighted'], line_dash="dash", line_color="blue", annotation_text="Weighted Avg") st.plotly_chart(fig, use_container_width=True) # F1-Score comparison st.markdown("#### F1-Score by Class") f1_scores = [metrics['class_metrics'][cn]['f1'] for cn in class_names] fig = go.Figure() fig.add_trace(go.Bar( x=class_names, y=f1_scores, marker_color=['#28a745', '#ffc107', '#dc3545'], text=[f'{f*100:.1f}%' for f in f1_scores], textposition='auto', )) fig.update_layout( yaxis_title='F1-Score', yaxis=dict(range=[0, 1.05]), height=300 ) fig.add_hline(y=metrics['f1_weighted'], line_dash="dash", line_color="blue", annotation_text="Weighted Avg") st.plotly_chart(fig, use_container_width=True) st.markdown("---") # ==================================================================== # SECTION 5: CLASS BALANCE & SUPPORT # ==================================================================== st.markdown("### 📦 Class Distribution & Support") support_col1, support_col2 = st.columns(2) with support_col1: # Class distribution - Pie chart st.markdown("#### Sample Distribution") supports = [metrics['class_metrics'][cn]['support'] for cn in class_names] fig = go.Figure(data=[go.Pie( labels=class_names, values=supports, hole=0.4, marker=dict(colors=['#28a745', '#ffc107', '#dc3545']), textinfo='label+percent+value', textfont=dict(size=12) )]) fig.update_layout( title="Class Distribution in Test Set", height=400 ) st.plotly_chart(fig, use_container_width=True) with support_col2: # Support comparison - Bar chart st.markdown("#### Support by Class") fig = go.Figure() fig.add_trace(go.Bar( x=class_names, y=supports, marker_color=['#28a745', '#ffc107', '#dc3545'], text=supports, textposition='auto', )) fig.update_layout( yaxis_title='Number of Samples', height=400 ) st.plotly_chart(fig, use_container_width=True) # Class imbalance ratio st.markdown("**Class Imbalance Ratio**") max_support = max(supports) for class_name, support in zip(class_names, supports): ratio = support / max_support st.progress(ratio, text=f"{class_name}: {support} samples ({ratio*100:.1f}%)") st.markdown("---") # ==================================================================== # SECTION 6: MODEL INSIGHTS & RECOMMENDATIONS # ==================================================================== st.markdown("### 💡 Model Insights & Recommendations") insight_col1, insight_col2 = st.columns(2) with insight_col1: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Model Strengths") strengths = [] if metrics['accuracy'] >= 0.95: strengths.append("✅ Excellent overall accuracy (≥95%)") if metrics['f1_weighted'] >= 0.95: strengths.append("✅ High weighted F1-score indicating balanced performance") if metrics['cv_score'] >= 0.95: strengths.append("✅ Strong cross-validation score shows good generalization") # Check if all class recalls are good if all(metrics['class_metrics'][cn]['recall'] >= 0.9 for cn in class_names[:-1]): strengths.append("✅ High recall for major classes (low false negatives)") # Check precision for confirmed class if 'CONFIRMED' in metrics['class_metrics']: if metrics['class_metrics']['CONFIRMED']['precision'] >= 0.85: strengths.append("✅ Good precision for CONFIRMED class reduces false discoveries") for strength in strengths: st.markdown(strength) if not strengths: st.info("Model shows room for improvement across metrics") st.markdown('
', unsafe_allow_html=True) with insight_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### Areas for Improvement") improvements = [] # Find weakest class weakest_class = min(metrics['class_metrics'].items(), key=lambda x: x[1]['f1']) if weakest_class[1]['f1'] < 0.85: improvements.append(f"⚠️ {weakest_class[0]} class has lower F1-score ({weakest_class[1]['f1']*100:.1f}%)") if weakest_class[1]['recall'] < 0.80: improvements.append(f"⚠️ Low recall for {weakest_class[0]} - many false negatives") # Check class imbalance support_ratio = min(supports) / max(supports) if support_ratio < 0.2: improvements.append(f"⚠️ Significant class imbalance (ratio: {support_ratio:.2f})") improvements.append("💡 Consider oversampling minority class or using class weights") # Check if improvement metric exists if metrics.get('improvement', 0) < 0.02: improvements.append("💡 Consider additional hyperparameter tuning for better performance") for improvement in improvements: st.markdown(improvement) if not improvements: st.success("Model performs well across all classes!") st.markdown('
', unsafe_allow_html=True) st.markdown("---") # ==================================================================== # SECTION 7: EXPORT OPTIONS # ==================================================================== st.markdown("### 💾 Export Performance Report") export_col1, export_col2, export_col3, export_col4 = st.columns(4) with export_col1: if st.button("📥 Export Metrics (CSV)", use_container_width=True): st.success("✅ Metrics exported to CSV") with export_col2: if st.button("📊 Export Visualizations", use_container_width=True): st.success("✅ Charts exported as images") with export_col3: if st.button("📄 Generate PDF Report", use_container_width=True): st.success("✅ PDF report generated") with export_col4: if st.button("📧 Email Report", use_container_width=True): st.success("✅ Report sent via email") else: st.warning("⚠️ No performance metrics available for this model. Please train the model first or load a model with metrics data.") # ============================================================================ # TAB 4: BEGINNER GUIDE (PLACEHOLDER FOR FUTURE IMPLEMENTATION) # ============================================================================ # ============================================================================ # TAB 4: BEGINNER'S GUIDE # ============================================================================ with tab4: st.markdown("## 🌟 Welcome to Exoplanet Detection - A Beginner's Guide") st.markdown("Start your journey in discovering planets beyond our solar system!") # Hero section with call-to-action st.markdown("---") hero_col1, hero_col2 = st.columns([2, 1]) with hero_col1: st.markdown(""" ### 🚀 New to Exoplanet Detection? Welcome! Exoplanets are planets that orbit stars outside our solar system. Discovering them is one of the most exciting fields in modern astronomy. This guide will help you understand the basics and get started with exoplanet detection. **What you'll learn:** - What exoplanets are and why they matter - How scientists detect them - The transit method explained simply - How to use this AI tool for detection - Real examples and practice exercises """) with hero_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("### 📖 Comprehensive Guide") st.markdown("Want more detailed information and interactive tutorials?") # Button to external guide st.link_button( "🌐 Open Full Beginner's Guide", "https://beginnerguideexoplanetdetect.netlify.app/", use_container_width=True, type="primary" ) st.info("Our comprehensive guide includes interactive animations, quizzes, and detailed explanations perfect for beginners!") st.markdown('
', unsafe_allow_html=True) st.markdown("---") # ======================================================================== # SECTION 1: WHAT ARE EXOPLANETS? # ======================================================================== st.markdown("### 🪐 What Are Exoplanets?") intro_col1, intro_col2 = st.columns([3, 2]) with intro_col1: st.markdown(""" **Exoplanets** (or extrasolar planets) are planets that exist outside our solar system. They orbit stars other than our Sun. **Key Facts:** - First confirmed exoplanet discovered in 1992 - Over 5,000 exoplanets confirmed to date - Thousands more candidates awaiting confirmation - Range from gas giants bigger than Jupiter to rocky planets smaller than Earth - Some may have conditions suitable for life! **Types of Exoplanets:** - **Hot Jupiters**: Gas giants very close to their stars - **Super-Earths**: Rocky planets larger than Earth - **Mini-Neptunes**: Smaller gas planets - **Earth-like planets**: Rocky planets in habitable zones """) with intro_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### 🎯 Quick Stats") st.metric("Confirmed Exoplanets", "5,000+") st.metric("Stars with Planets", "3,700+") st.metric("Planetary Systems", "4,000+") st.metric("Habitable Zone Planets", "100+") st.markdown('
', unsafe_allow_html=True) st.markdown("---") # ======================================================================== # SECTION 2: DETECTION METHODS EXPLAINED # ======================================================================== st.markdown("### 🔭 How Do We Find Exoplanets?") st.markdown(""" Scientists use several methods to detect exoplanets. Here are the main techniques explained simply: """) method_tab1, method_tab2, method_tab3 = st.tabs([ "🌗 Transit Method", "🎯 Radial Velocity", "🔍 Other Methods" ]) with method_tab1: transit_col1, transit_col2 = st.columns([2, 1]) with transit_col1: st.markdown(""" #### The Transit Method (What This Tool Uses!) **How it works:** 1. We observe a star's brightness over time 2. When a planet passes in front of the star (transits), it blocks some light 3. This causes a tiny dip in the star's brightness 4. We measure this dip to learn about the planet **What we can learn:** - Planet size (bigger planet = bigger dip) - Orbital period (time between transits) - Distance from star - Sometimes atmospheric composition! **Advantages:** - Can detect small planets - Provides accurate planet size - Works for distant stars **Limitations:** - Planet orbit must align with our view - Only works for planets that transit their star """) with transit_col2: st.markdown('
', unsafe_allow_html=True) st.markdown("#### 💡 Simple Analogy") st.markdown(""" Imagine watching a light bulb with a fly flying around it. When the fly passes directly between you and the bulb, the light dims slightly. By timing these dips, you can figure out how often the fly circles the bulb! """) st.markdown('
', unsafe_allow_html=True) st.markdown('
', unsafe_allow_html=True) st.markdown("#### 📊 Success Rate") st.markdown("~75% of exoplanets discovered using this method!") st.markdown('
', unsafe_allow_html=True) with method_tab2: st.markdown(""" #### Radial Velocity Method (Wobble Detection) **How it works:** - Planets don't just orbit stars - the star and planet orbit their common center of mass - This causes the star to "wobble" slightly - The wobble changes the star's light wavelength (Doppler effect) - We detect these tiny wavelength shifts **What we can learn:** - Planet mass - Orbital period - Orbit shape (eccentricity) **Best for:** Detecting massive planets close to their stars """) with method_tab3: st.markdown(""" #### Other Detection Methods **Direct Imaging:** - Actually taking pictures of exoplanets - Very difficult due to star brightness - Works best for large planets far from their stars **Gravitational Microlensing:** - Uses gravity as a magnifying glass - Star's gravity bends light from background star - Creates temporary brightening when planet is present **Astrometry:** - Precisely measuring star position changes - Star moves slightly due to planet's gravity - Requires extremely precise measurements """) st.markdown("---") # ======================================================================== # SECTION 3: STEP-BY-STEP LEARNING PATH # ======================================================================== st.markdown("### 📚 Your Learning Path: From Zero to Exoplanet Hunter") st.markdown(""" Follow these steps to build your knowledge from the ground up: """) # Step 1 st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🎯 Step 1: Understand Basic Astronomy Concepts (Week 1-2) **What to learn:** - What stars are and how they work - Our solar system structure - Light and how we study it - Basic physics concepts (gravity, orbits) **Recommended actions:** - Watch introductory astronomy videos (see resources below) - Read about our solar system - Learn about light and spectra **Success indicator:** You can explain what a star is and how planets orbit """) st.markdown('
', unsafe_allow_html=True) # Step 2 st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🔬 Step 2: Learn About Exoplanets (Week 2-3) **What to learn:** - What makes exoplanets different from solar system planets - Types of exoplanets - Why exoplanets are important - History of exoplanet discovery **Recommended actions:** - Visit NASA Exoplanet Archive - Read about famous exoplanet discoveries - Explore the [Full Beginner's Guide](https://beginnerguideexoplanetdetect.netlify.app/) **Success indicator:** You can name and describe different types of exoplanets """) st.markdown('
', unsafe_allow_html=True) # Step 3 st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 📊 Step 3: Understand the Transit Method (Week 3-4) **What to learn:** - How transit method works in detail - What a light curve is - How to interpret transit data - What parameters we measure **Recommended actions:** - Study light curve examples - Practice identifying transits in data - Learn about transit parameters (depth, duration, period) **Success indicator:** You can look at a light curve and identify a transit """) st.markdown('
', unsafe_allow_html=True) # Step 4 st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🤖 Step 4: Introduction to Machine Learning (Week 4-5) **What to learn:** - Basic concepts of AI and machine learning - How computers learn to classify data - What features and parameters mean - Understanding model predictions **Recommended actions:** - Watch machine learning basics videos - Understand classification vs prediction - Learn about training data **Success indicator:** You understand what the AI model does in this tool """) st.markdown('
', unsafe_allow_html=True) # Step 5 st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🎮 Step 5: Practice with This Tool (Week 5+) **What to do:** - Start with sample data in the Researcher Interface - Make your first prediction - Understand the output and recommendations - Try different parameters and see how results change - Compare your results with known exoplanets **Recommended actions:** - Load sample templates (Hot Jupiter, Super-Earth, etc.) - Read the AI recommendations carefully - Check the feature importance charts **Success indicator:** You can confidently use the tool and interpret results """) st.markdown('
', unsafe_allow_html=True) st.markdown("---") # ======================================================================== # SECTION 4: VIDEO RESOURCES # ======================================================================== st.markdown("### 📺 Educational Video Resources") st.markdown(""" Learn from these excellent YouTube videos and channels: """) video_col1, video_col2 = st.columns(2) with video_col1: st.markdown("#### 🌟 Getting Started Videos") st.markdown(""" **1. What Are Exoplanets?** - [NASA: Exoplanet Exploration](https://www.youtube.com/watch?v=jW5RFhImPyw) - Duration: ~10 minutes - Perfect introduction to exoplanets **2. How Do We Find Exoplanets?** - [Crash Course Astronomy: Exoplanets](https://www.youtube.com/watch?v=DqTkPM5lWQk) - Duration: ~12 minutes - Covers detection methods **3. The Transit Method Explained** - [NASA: Transit Method Animation](https://www.youtube.com/watch?v=qHDyG4WAH2s) - Duration: ~5 minutes - Visual explanation of how transits work **4. Reading Light Curves** - Search: "NASA Light Curves Tutorial" - Duration: ~8 minutes - Learn to interpret transit data """) with video_col2: st.markdown("#### 🎓 Advanced Topics") st.markdown(""" **5. Kepler Mission Overview** - [NASA Kepler: Planet Hunter](https://www.youtube.com/watch?v=3zVdYFQl_cQ) - Duration: ~15 minutes - Learn about NASA's planet-hunting telescope **6. Machine Learning in Astronomy** - Search: "AI for Exoplanet Detection" - Duration: ~20 minutes - How AI helps find planets **7. The Search for Habitable Worlds** - Search: "Are We Alone? The Search for Life" - Duration: ~25 minutes - Why exoplanets matter for finding life **8. Real Exoplanet Discoveries** - Search: "Amazing Exoplanet Discoveries" - Duration: ~18 minutes - Stories of fascinating planets found """) st.markdown("#### 🎬 Recommended YouTube Channels") channel_col1, channel_col2, channel_col3 = st.columns(3) with channel_col1: st.markdown(""" **NASA** - Official NASA content - High-quality animations - Latest discoveries """) with channel_col2: st.markdown(""" **PBS Space Time** - In-depth explanations - Advanced concepts - Expert presenters """) with channel_col3: st.markdown(""" **Crash Course** - Beginner-friendly - Full astronomy series - Engaging presentations """) st.markdown("---") # ======================================================================== # SECTION 5: KEY CONCEPTS GLOSSARY # ======================================================================== st.markdown("### 📖 Essential Terms to Know") glossary_col1, glossary_col2 = st.columns(2) with glossary_col1: st.markdown(""" **Transit:** When a planet passes in front of its star from our viewpoint **Light Curve:** A graph showing how a star's brightness changes over time **Transit Depth:** How much light is blocked during a transit (tells us planet size) **Orbital Period:** Time it takes a planet to complete one orbit around its star **Transit Duration:** How long the planet takes to cross in front of the star **Habitable Zone:** The region around a star where liquid water could exist **False Positive:** A signal that looks like a planet but isn't (like an eclipsing binary star) **Candidate:** A potential exoplanet that needs more observation to confirm """) with glossary_col2: st.markdown(""" **Confirmed Planet:** An exoplanet verified through multiple observations **Stellar Parameters:** Properties of the host star (temperature, size, brightness) **Planet Radius:** Size of the planet compared to Earth or Jupiter **Equilibrium Temperature:** Expected temperature of the planet's surface **Impact Parameter:** How close to the star's center the planet passes **Signal-to-Noise Ratio (SNR):** How strong the planet signal is compared to noise **Model:** In AI, the trained system that classifies new observations **Feature:** A measurable property used by the AI to make predictions """) st.markdown("---") # ======================================================================== # SECTION 6: PRACTICE EXERCISES # ======================================================================== st.markdown("### 🎯 Quick Knowledge Check") st.markdown(""" Test your understanding with these simple questions: """) with st.expander("❓ Question 1: What is an exoplanet?"): q1_answer = st.radio( "Select your answer:", [ "A planet in our solar system", "A planet outside our solar system", "A type of star", "A moon orbiting Jupiter" ], key="q1" ) if st.button("Check Answer", key="check_q1"): if "outside our solar system" in q1_answer: st.success("✅ Correct! Exoplanets orbit stars other than our Sun.") else: st.error("❌ Not quite. Review the 'What Are Exoplanets?' section above.") with st.expander("❓ Question 2: How does the transit method work?"): q2_answer = st.radio( "Select your answer:", [ "We take pictures of the planet", "We measure the star's wobble", "We detect dips in star brightness when planet passes in front", "We listen to radio signals from the planet" ], key="q2" ) if st.button("Check Answer", key="check_q2"): if "dips in star brightness" in q2_answer: st.success("✅ Correct! The transit method detects light dips when planets block their star's light.") else: st.error("❌ Not quite. Review the 'Transit Method' section above.") with st.expander("❓ Question 3: What does transit depth tell us?"): q3_answer = st.radio( "Select your answer:", [ "Planet's color", "Planet's temperature", "Planet's size", "Planet's age" ], key="q3" ) if st.button("Check Answer", key="check_q3"): if "size" in q3_answer: st.success("✅ Correct! Transit depth is related to planet size - bigger planets block more light.") else: st.error("❌ Not quite. Think about how much light a planet blocks.") st.markdown("---") # ======================================================================== # SECTION 7: NEXT STEPS & RESOURCES # ======================================================================== st.markdown("### 🚀 Ready to Get Started?") next_col1, next_col2, next_col3 = st.columns(3) with next_col1: st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 📖 Learn More Visit our comprehensive guide for interactive tutorials and detailed explanations """) st.link_button( "Open Full Guide", "https://beginnerguideexoplanetdetect.netlify.app/", use_container_width=True ) st.markdown('
', unsafe_allow_html=True) with next_col2: st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🔬 Start Detecting Head to the Researcher Interface and try making your first prediction! """) if st.button("Go to Researcher Interface", use_container_width=True, key="goto_researcher"): st.info("Switch to the 'Researcher Interface' tab above to begin!") st.markdown('
', unsafe_allow_html=True) with next_col3: st.markdown('
', unsafe_allow_html=True) st.markdown(""" #### 🌐 Explore NASA Resources Visit NASA's official exoplanet exploration website """) st.link_button( "NASA Exoplanets", "https://exoplanets.nasa.gov/", use_container_width=True ) st.markdown('
', unsafe_allow_html=True) st.markdown("---") # Additional resources section st.markdown("### 📚 Additional Learning Resources") resource_col1, resource_col2 = st.columns(2) with resource_col1: st.markdown(""" #### 🌐 Websites & Databases - [NASA Exoplanet Archive](https://exoplanetarchive.ipac.caltech.edu/) - Search confirmed exoplanets - [Exoplanet.eu](http://exoplanet.eu/) - European exoplanet database - [PlanetHunters](https://www.zooniverse.org/projects/nora-dot-eisner/planet-hunters-tess) - Citizen science project - [Eyes on Exoplanets](https://eyes.nasa.gov/apps/exo/) - 3D interactive visualization """) with resource_col2: st.markdown(""" #### 📱 Apps & Tools - Exoplanet (iOS/Android) - Interactive app - Star Walk 2 - Stargazing app - SkySafari - Advanced astronomy app - NASA App - Latest space news """) st.markdown("---") st.markdown(""" ### 💬 Have Questions? **Remember:** Everyone starts as a beginner! Don't be afraid to: - Ask questions in astronomy forums - Revisit concepts multiple times - Practice with sample data - Join online astronomy communities **Suggested Communities:** - r/astronomy on Reddit - r/exoplanets on Reddit - NASA's Exoplanet Exploration forums - Astronomy Stack Exchange Happy planet hunting! 🌟🔭 """) # ============================================================================ # FOOTER # ============================================================================ # ============================================================================ # FOOTER # ============================================================================ st.markdown("---") footer_col1, footer_col2, footer_col3 = st.columns(3) with footer_col1: st.markdown("**📚 Resources**") st.markdown("- [NASA Exoplanet Archive](https://exoplanetarchive.ipac.caltech.edu/)") st.markdown("- [Kepler Mission](https://www.nasa.gov/mission_pages/kepler/main/index.html)") with footer_col2: st.markdown("**🔗 Quick Links**") st.markdown("- Documentation") st.markdown("- API Reference") with footer_col3: st.markdown("**ℹ️ About**") st.markdown("Version 1.0.0") st.markdown("© 2024 Exoplanet Detection System")