#!/usr/bin/env python3 """ DESI Spectrum Plotter Plot downloaded DESI galaxy spectra with metadata annotations """ import json import matplotlib.pyplot as plt import numpy as np from pathlib import Path import glob from typing import Dict, Any, List import random def load_spectrum_file(filepath: str) -> Dict[str, Any]: """Load a spectrum JSON file and return the data""" with open(filepath, 'r') as f: return json.load(f) def get_spectrum_files(data_dir: str = '/Users/sandyyuan/astro_mcp_data/desi') -> List[str]: """Get all spectrum files from the data directory""" pattern = str(Path(data_dir) / 'spectrum_GALAXY_*.json') files = glob.glob(pattern) return sorted(files) def plot_spectrum(spectrum_data: Dict[str, Any], ax, title_suffix: str = ""): """Plot a single spectrum with metadata""" # Extract spectral data wavelength = np.array(spectrum_data['data']['wavelength']) flux = np.array(spectrum_data['data']['flux']) inverse_variance = np.array(spectrum_data['data']['inverse_variance']) model = np.array(spectrum_data['data']['model']) # Convert inverse variance to flux error (avoid division by zero) flux_err = np.where(inverse_variance > 0, 1.0 / np.sqrt(inverse_variance), np.inf) # Extract metadata metadata = spectrum_data['metadata'] # Plot the spectrum ax.plot(wavelength, flux, 'k-', alpha=0.7, linewidth=0.8, label='Observed Flux') ax.plot(wavelength, model, 'r-', alpha=0.8, linewidth=1.0, label='Model Fit') # Add error bars (thinned out for visibility) step = max(1, len(wavelength) // 100) # Show every ~100th error bar ax.errorbar(wavelength[::step], flux[::step], yerr=flux_err[::step], fmt='none', alpha=0.3, color='gray', capsize=0) # Format axes ax.set_xlabel('Wavelength (Å)') ax.set_ylabel('Flux (10⁻¹⁷ erg/s/cm²/Å)') ax.grid(True, alpha=0.3) ax.legend(fontsize=8) # Create title with key metadata redshift = metadata.get('redshift', 'Unknown') obj_type = metadata.get('object_type', 'Unknown') survey = metadata.get('survey', 'Unknown') target_id = metadata.get('targetid', 'Unknown') title = f"{obj_type} at z={redshift:.4f}{title_suffix}" ax.set_title(title, fontsize=10, fontweight='bold') # Add metadata text box ra = metadata.get('ra', 'Unknown') dec = metadata.get('dec', 'Unknown') redshift_err = metadata.get('redshift_err', 'Unknown') metadata_text = ( f"Target ID: {target_id}\n" f"RA, Dec: {ra:.4f}°, {dec:.4f}°\n" f"z ± err: {redshift:.4f} ± {redshift_err}\n" f"Survey: {survey}" ) # Position text box in upper right ax.text(0.98, 0.98, metadata_text, transform=ax.transAxes, verticalalignment='top', horizontalalignment='right', bbox=dict(boxstyle='round', facecolor='white', alpha=0.8), fontsize=7, family='monospace') return ax def create_spectrum_plots(num_plots: int = 6): """Create a grid of spectrum plots""" print("🔍 Finding DESI spectrum files...") spectrum_files = get_spectrum_files() if not spectrum_files: print("❌ No spectrum files found!") return print(f"📊 Found {len(spectrum_files)} spectrum files") # Select a diverse sample if len(spectrum_files) > num_plots: # Try to get a good spread of redshifts selected_files = random.sample(spectrum_files, num_plots) else: selected_files = spectrum_files num_plots = len(spectrum_files) # Create subplot grid cols = 2 rows = (num_plots + cols - 1) // cols fig, axes = plt.subplots(rows, cols, figsize=(15, 4 * rows)) fig.suptitle('DESI Galaxy Spectra - ELG Sample', fontsize=16, fontweight='bold') # Handle single subplot case if num_plots == 1: axes = [axes] elif rows == 1: axes = axes.reshape(1, -1) # Flatten axes for easy iteration axes_flat = axes.flatten() if num_plots > 1 else axes print(f"\n📈 Creating plots for {len(selected_files)} spectra...") for i, filepath in enumerate(selected_files): print(f" Loading spectrum {i+1}/{len(selected_files)}: {Path(filepath).name}") try: # Load spectrum data spectrum_data = load_spectrum_file(filepath) # Plot spectrum ax = axes_flat[i] if num_plots > 1 else axes_flat[0] plot_spectrum(spectrum_data, ax, f" ({i+1}/{len(selected_files)})") except Exception as e: print(f" ❌ Error loading {filepath}: {e}") continue # Hide unused subplots for i in range(len(selected_files), len(axes_flat)): axes_flat[i].set_visible(False) plt.tight_layout() # Save the plot output_file = '/Users/sandyyuan/astro_mcp_data/desi_spectra_plots.png' plt.savefig(output_file, dpi=300, bbox_inches='tight') print(f"\n💾 Plot saved to: {output_file}") plt.show() def create_redshift_distribution_plot(): """Create a plot showing the redshift distribution of our sample""" print("\n📊 Creating redshift distribution plot...") spectrum_files = get_spectrum_files() redshifts = [] object_types = [] for filepath in spectrum_files: try: spectrum_data = load_spectrum_file(filepath) metadata = spectrum_data['metadata'] redshift = metadata.get('redshift') obj_type = metadata.get('object_type', 'Unknown') if redshift is not None: redshifts.append(float(redshift)) object_types.append(obj_type) except Exception as e: print(f" Warning: Could not load {filepath}: {e}") continue if not redshifts: print("❌ No valid redshift data found!") return # Create histogram fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8)) # Redshift histogram ax1.hist(redshifts, bins=15, alpha=0.7, color='skyblue', edgecolor='black') ax1.set_xlabel('Redshift (z)') ax1.set_ylabel('Number of Galaxies') ax1.set_title(f'Redshift Distribution of Downloaded DESI Spectra (N={len(redshifts)})') ax1.grid(True, alpha=0.3) # Add statistics mean_z = np.mean(redshifts) median_z = np.median(redshifts) min_z = np.min(redshifts) max_z = np.max(redshifts) stats_text = ( f"Mean z: {mean_z:.3f}\n" f"Median z: {median_z:.3f}\n" f"Range: {min_z:.3f} - {max_z:.3f}" ) ax1.text(0.98, 0.98, stats_text, transform=ax1.transAxes, verticalalignment='top', horizontalalignment='right', bbox=dict(boxstyle='round', facecolor='white', alpha=0.8), fontsize=10) # Object type counts from collections import Counter type_counts = Counter(object_types) ax2.bar(type_counts.keys(), type_counts.values(), alpha=0.7, color='lightcoral') ax2.set_xlabel('Object Type') ax2.set_ylabel('Count') ax2.set_title('Object Type Distribution') ax2.grid(True, alpha=0.3) plt.tight_layout() # Save the plot output_file = '/Users/sandyyuan/astro_mcp_data/desi_redshift_distribution.png' plt.savefig(output_file, dpi=300, bbox_inches='tight') print(f"💾 Distribution plot saved to: {output_file}") plt.show() return redshifts, object_types def main(): """Main function to create all plots""" print("="*80) print("🌌 DESI SPECTRUM VISUALIZATION") print("="*80) # Create spectrum plots create_spectrum_plots(num_plots=6) # Create distribution plots redshifts, obj_types = create_redshift_distribution_plot() print(f"\n✅ Visualization complete!") print(f"📈 Plotted spectra from {len(redshifts)} galaxies") print(f"🔴 Redshift range: {min(redshifts):.3f} - {max(redshifts):.3f}") from collections import Counter type_counts = Counter(obj_types) print(f"📊 Object types: {dict(type_counts)}") if __name__ == "__main__": main()