sandyyuan commited on
Commit
1edced1
·
verified ·
1 Parent(s): b709de2

Upload folder using huggingface_hub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. README.md +108 -0
  2. README_HF.md +104 -0
  3. dataset_card.md +104 -0
  4. metadata.csv +0 -0
  5. plot_desi_spectra.py +247 -0
  6. sample_elg_galaxies.py +129 -0
  7. spectrum_GALAXY_0.6004_7006c68c_20250811_152534.json +0 -0
  8. spectrum_GALAXY_0.6005_02faa4bf_20250811_155621.json +0 -0
  9. spectrum_GALAXY_0.6008_6ce6cb33_20250811_155529.json +0 -0
  10. spectrum_GALAXY_0.6011_cebb7ee5_20250811_162429.json +0 -0
  11. spectrum_GALAXY_0.6067_9a28c694_20250811_160933.json +0 -0
  12. spectrum_GALAXY_0.6103_f21a4d7e_20250811_161921.json +0 -0
  13. spectrum_GALAXY_0.6116_a8282d87_20250811_162100.json +0 -0
  14. spectrum_GALAXY_0.6118_1489a218_20250811_162059.json +0 -0
  15. spectrum_GALAXY_0.6135_e5dc1406_20250811_162452.json +0 -0
  16. spectrum_GALAXY_0.6136_b4a514e0_20250811_160440.json +0 -0
  17. spectrum_GALAXY_0.6175_eecb7c1d_20250811_161002.json +0 -0
  18. spectrum_GALAXY_0.6177_95fdcf42_20250811_160536.json +0 -0
  19. spectrum_GALAXY_0.6179_6a5f0d21_20250811_160439.json +0 -0
  20. spectrum_GALAXY_0.6204_5af39e3b_20250811_160840.json +0 -0
  21. spectrum_GALAXY_0.6219_c0ef549a_20250811_155646.json +0 -0
  22. spectrum_GALAXY_0.6222_78d898aa_20250811_160823.json +0 -0
  23. spectrum_GALAXY_0.6232_bcd7e093_20250811_160432.json +0 -0
  24. spectrum_GALAXY_0.6242_f16f6497_20250811_162107.json +0 -0
  25. spectrum_GALAXY_0.6243_c1b34d42_20250811_162032.json +0 -0
  26. spectrum_GALAXY_0.6257_bae353db_20250811_160533.json +0 -0
  27. spectrum_GALAXY_0.6278_450a52c2_20250811_155702.json +0 -0
  28. spectrum_GALAXY_0.6283_065d858c_20250811_152530.json +0 -0
  29. spectrum_GALAXY_0.6300_926ed846_20250811_162150.json +0 -0
  30. spectrum_GALAXY_0.6301_d9adf642_20250811_162005.json +0 -0
  31. spectrum_GALAXY_0.6305_e06a8867_20250811_160933.json +0 -0
  32. spectrum_GALAXY_0.6335_49d3ee00_20250811_162009.json +0 -0
  33. spectrum_GALAXY_0.6342_40e72d49_20250811_160543.json +0 -0
  34. spectrum_GALAXY_0.6375_5065e5d8_20250811_162215.json +0 -0
  35. spectrum_GALAXY_0.6389_3c1e976b_20250811_162439.json +0 -0
  36. spectrum_GALAXY_0.6405_069dde84_20250811_162328.json +0 -0
  37. spectrum_GALAXY_0.6413_70fd16ea_20250811_162135.json +0 -0
  38. spectrum_GALAXY_0.6418_8c2456ca_20250811_162400.json +0 -0
  39. spectrum_GALAXY_0.6440_41808267_20250811_161901.json +0 -0
  40. spectrum_GALAXY_0.6455_9bb84015_20250811_161937.json +0 -0
  41. spectrum_GALAXY_0.6500_28bc39be_20250811_160421.json +0 -0
  42. spectrum_GALAXY_0.6506_bfca87aa_20250811_160608.json +0 -0
  43. spectrum_GALAXY_0.6527_f8e97f60_20250811_161837.json +0 -0
  44. spectrum_GALAXY_0.6534_27d72849_20250811_160902.json +0 -0
  45. spectrum_GALAXY_0.6556_971b4bd6_20250811_161010.json +0 -0
  46. spectrum_GALAXY_0.6557_8a53ac17_20250811_162411.json +0 -0
  47. spectrum_GALAXY_0.6578_a684f173_20250811_162245.json +0 -0
  48. spectrum_GALAXY_0.6595_3102415b_20250811_160531.json +0 -0
  49. spectrum_GALAXY_0.6599_4d3e2365_20250811_160551.json +0 -0
  50. spectrum_GALAXY_0.6618_9aaf95fb_20250811_160949.json +0 -0
README.md ADDED
@@ -0,0 +1,108 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # DESI DR1 ELG Galaxy Spectra Dataset
2
+
3
+ This dataset contains 999 Emission Line Galaxy (ELG) spectra from the Dark Energy Spectroscopic Instrument (DESI) Data Release 1, along with associated metadata.
4
+
5
+ ## Dataset Contents
6
+
7
+ - `metadata.csv` - Galaxy properties and catalog information (999 galaxies + header)
8
+ - `spectrum_GALAXY_*.json` - Individual spectrum files (999 files)
9
+ - `*.py` - Analysis and visualization scripts
10
+
11
+ ## Metadata Columns (`metadata.csv`)
12
+
13
+ | Column | Description |
14
+ |--------|-------------|
15
+ | `targetid` | DESI target identifier |
16
+ | `galaxy_type` | Galaxy type classification (ELG) |
17
+ | `spectype` | Spectroscopic type (GALAXY) |
18
+ | `ra`, `dec` | Right ascension and declination (degrees) |
19
+ | `redshift` | Spectroscopic redshift |
20
+ | `z_bin` | Redshift bin (0.6-0.8, 0.8-1.0) |
21
+ | `survey` | DESI survey (main) |
22
+ | `program` | Observing program (dark) |
23
+ | `healpix` | HEALPix pixel ID |
24
+ | `desi_target`, `bgs_target`, `mws_target`, `scnd_target` | DESI targeting bitmasks |
25
+
26
+ ## Spectrum File Format
27
+
28
+ Each `spectrum_GALAXY_*.json` file contains:
29
+
30
+ ```json
31
+ {
32
+ "metadata": {
33
+ "sparcl_id": "UUID",
34
+ "object_type": "GALAXY",
35
+ "redshift": 0.6004,
36
+ "redshift_err": 7.4e-05,
37
+ "ra": 126.957,
38
+ "dec": 3.269,
39
+ "survey": "main",
40
+ "data_release": "DESI-DR1",
41
+ "targetid": 39636661465776861
42
+ },
43
+ "data": {
44
+ "wavelength": [3600.0, 3600.8, ...], // 7781 points, 3600-9824 Å
45
+ "flux": [...], // Observed flux (10⁻¹⁷ erg/s/cm²/Å)
46
+ "model": [...], // Best-fit model
47
+ "inverse_variance": [...] // 1/σ² for flux uncertainties
48
+ }
49
+ }
50
+ ```
51
+
52
+ ## Quick Start
53
+
54
+ ### Load metadata
55
+ ```python
56
+ import pandas as pd
57
+ metadata = pd.read_csv('metadata.csv')
58
+ print(f"Dataset contains {len(metadata)} ELG galaxies")
59
+ print(f"Redshift range: {metadata['redshift'].min():.3f} - {metadata['redshift'].max():.3f}")
60
+ ```
61
+
62
+ ### Load a spectrum
63
+ ```python
64
+ import json
65
+ import numpy as np
66
+
67
+ # Load spectrum file
68
+ with open('spectrum_GALAXY_0.6004_7006c68c_20250811_152534.json', 'r') as f:
69
+ spectrum = json.load(f)
70
+
71
+ # Extract data
72
+ wavelength = np.array(spectrum['data']['wavelength'])
73
+ flux = np.array(spectrum['data']['flux'])
74
+ model = np.array(spectrum['data']['model'])
75
+ redshift = spectrum['metadata']['redshift']
76
+
77
+ print(f"Galaxy at z={redshift:.4f}")
78
+ print(f"Spectrum covers {wavelength[0]:.0f}-{wavelength[-1]:.0f} Å")
79
+ ```
80
+
81
+ ### Plot a spectrum
82
+ ```python
83
+ import matplotlib.pyplot as plt
84
+
85
+ plt.figure(figsize=(12, 6))
86
+ plt.plot(wavelength, flux, 'k-', alpha=0.7, label='Observed')
87
+ plt.plot(wavelength, model, 'r-', label='Model')
88
+ plt.xlabel('Wavelength (Å)')
89
+ plt.ylabel('Flux (10⁻¹⁷ erg/s/cm²/Å)')
90
+ plt.title(f'DESI ELG Spectrum (z={redshift:.4f})')
91
+ plt.legend()
92
+ plt.grid(True, alpha=0.3)
93
+ plt.show()
94
+ ```
95
+
96
+ ## Analysis Scripts
97
+
98
+ - `plot_desi_spectra.py` - Create multi-panel spectrum plots and redshift distributions
99
+ - `sample_elg_galaxies.py` - Original sampling script for ELG selection
100
+ - `spectrum_downloader.py` - Script used to download spectra from DESI archives
101
+
102
+ ## Dataset Statistics
103
+
104
+ - **Total galaxies**: 999
105
+ - **Redshift range**: 0.600 - 0.948
106
+ - **Spectral coverage**: 3600 - 9824 Å (7781 wavelength points)
107
+ - **Galaxy type**: Emission Line Galaxies (ELGs)
108
+ - **Survey**: DESI Main Survey (dark time program)
README_HF.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - other
5
+ language:
6
+ - en
7
+ tags:
8
+ - astronomy
9
+ - spectroscopy
10
+ - galaxies
11
+ - desi
12
+ - cosmology
13
+ size_categories:
14
+ - n<1K
15
+ ---
16
+
17
+ # DESI DR1 ELG Galaxy Spectra Dataset
18
+
19
+ This dataset contains 999 Emission Line Galaxy (ELG) spectra from the Dark Energy Spectroscopic Instrument (DESI) Data Release 1, along with associated metadata. This is a curated sample of high-quality galaxy spectra suitable for research and educational purposes in astronomy and cosmology.
20
+
21
+ ## Dataset Summary
22
+
23
+ - **Total galaxies**: 999 Emission Line Galaxies (ELGs)
24
+ - **Data source**: DESI Data Release 1
25
+ - **Redshift range**: 0.600 - 0.948
26
+ - **Spectral coverage**: 3600 - 9824 Å (7781 wavelength points per spectrum)
27
+ - **Survey**: DESI Main Survey (dark time program)
28
+
29
+ ## Dataset Structure
30
+
31
+ ### Files
32
+
33
+ - `metadata.csv` - Galaxy properties and catalog information (999 galaxies + header)
34
+ - `spectrum_GALAXY_*.json` - Individual spectrum files (999 files)
35
+ - `README.md` - Detailed documentation and usage examples
36
+
37
+ ### Metadata Columns
38
+
39
+ | Column | Description |
40
+ |--------|-------------|
41
+ | `targetid` | DESI target identifier |
42
+ | `galaxy_type` | Galaxy type classification (ELG) |
43
+ | `spectype` | Spectroscopic type (GALAXY) |
44
+ | `ra`, `dec` | Right ascension and declination (degrees) |
45
+ | `redshift` | Spectroscopic redshift |
46
+ | `z_bin` | Redshift bin (0.6-0.8, 0.8-1.0) |
47
+ | `survey` | DESI survey (main) |
48
+ | `program` | Observing program (dark) |
49
+ | `healpix` | HEALPix pixel ID |
50
+ | `desi_target`, `bgs_target`, `mws_target`, `scnd_target` | DESI targeting bitmasks |
51
+
52
+ ### Spectrum File Format
53
+
54
+ Each spectrum file contains:
55
+ - **Metadata**: Object properties (redshift, coordinates, survey info)
56
+ - **Spectral data**: Wavelength array, observed flux, model fit, and inverse variance
57
+
58
+ ## Usage
59
+
60
+ ```python
61
+ import pandas as pd
62
+ import json
63
+ import numpy as np
64
+
65
+ # Load metadata
66
+ metadata = pd.read_csv('metadata.csv')
67
+ print(f"Dataset contains {len(metadata)} ELG galaxies")
68
+
69
+ # Load a spectrum
70
+ with open('spectrum_GALAXY_0.6004_7006c68c_20250811_152534.json', 'r') as f:
71
+ spectrum = json.load(f)
72
+
73
+ wavelength = np.array(spectrum['data']['wavelength'])
74
+ flux = np.array(spectrum['data']['flux'])
75
+ redshift = spectrum['metadata']['redshift']
76
+ ```
77
+
78
+ ## Data Source and Citation
79
+
80
+ This dataset is derived from the Dark Energy Spectroscopic Instrument (DESI) Data Release 1.
81
+
82
+ **DESI Collaboration**: Please cite the appropriate DESI DR1 papers when using this dataset:
83
+ - DESI Collaboration et al. (2024). "The Dark Energy Spectroscopic Instrument (DESI) Data Release 1"
84
+
85
+ ## License
86
+
87
+ This dataset is released under the Creative Commons Attribution 4.0 International License (CC BY 4.0).
88
+
89
+ ## Applications
90
+
91
+ This dataset is suitable for:
92
+ - Galaxy spectroscopy research
93
+ - Redshift analysis and cosmology studies
94
+ - Machine learning applications in astronomy
95
+ - Educational purposes in astrophysics courses
96
+ - Spectral analysis method development
97
+
98
+ ## Technical Details
99
+
100
+ - **Wavelength coverage**: 3600-9824 Å
101
+ - **Spectral resolution**: ~7781 points per spectrum
102
+ - **Flux units**: 10⁻¹⁷ erg/s/cm²/Å
103
+ - **File format**: JSON for spectra, CSV for metadata
104
+ - **Total size**: ~2.5 GB (including all spectrum files)
dataset_card.md ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: cc-by-4.0
3
+ task_categories:
4
+ - other
5
+ language:
6
+ - en
7
+ tags:
8
+ - astronomy
9
+ - spectroscopy
10
+ - galaxies
11
+ - desi
12
+ - cosmology
13
+ size_categories:
14
+ - n<1K
15
+ ---
16
+
17
+ # DESI DR1 ELG Galaxy Spectra Dataset
18
+
19
+ This dataset contains 999 Emission Line Galaxy (ELG) spectra from the Dark Energy Spectroscopic Instrument (DESI) Data Release 1, along with associated metadata. This is a curated sample of high-quality galaxy spectra suitable for research and educational purposes in astronomy and cosmology.
20
+
21
+ ## Dataset Summary
22
+
23
+ - **Total galaxies**: 999 Emission Line Galaxies (ELGs)
24
+ - **Data source**: DESI Data Release 1
25
+ - **Redshift range**: 0.600 - 0.948
26
+ - **Spectral coverage**: 3600 - 9824 Å (7781 wavelength points per spectrum)
27
+ - **Survey**: DESI Main Survey (dark time program)
28
+
29
+ ## Dataset Structure
30
+
31
+ ### Files
32
+
33
+ - `metadata.csv` - Galaxy properties and catalog information (999 galaxies + header)
34
+ - `spectrum_GALAXY_*.json` - Individual spectrum files (999 files)
35
+ - `README.md` - Detailed documentation and usage examples
36
+
37
+ ### Metadata Columns
38
+
39
+ | Column | Description |
40
+ |--------|-------------|
41
+ | `targetid` | DESI target identifier |
42
+ | `galaxy_type` | Galaxy type classification (ELG) |
43
+ | `spectype` | Spectroscopic type (GALAXY) |
44
+ | `ra`, `dec` | Right ascension and declination (degrees) |
45
+ | `redshift` | Spectroscopic redshift |
46
+ | `z_bin` | Redshift bin (0.6-0.8, 0.8-1.0) |
47
+ | `survey` | DESI survey (main) |
48
+ | `program` | Observing program (dark) |
49
+ | `healpix` | HEALPix pixel ID |
50
+ | `desi_target`, `bgs_target`, `mws_target`, `scnd_target` | DESI targeting bitmasks |
51
+
52
+ ### Spectrum File Format
53
+
54
+ Each spectrum file contains:
55
+ - **Metadata**: Object properties (redshift, coordinates, survey info)
56
+ - **Spectral data**: Wavelength array, observed flux, model fit, and inverse variance
57
+
58
+ ## Usage
59
+
60
+ ```python
61
+ import pandas as pd
62
+ import json
63
+ import numpy as np
64
+
65
+ # Load metadata
66
+ metadata = pd.read_csv('metadata.csv')
67
+ print(f"Dataset contains {len(metadata)} ELG galaxies")
68
+
69
+ # Load a spectrum
70
+ with open('spectrum_GALAXY_0.6004_7006c68c_20250811_152534.json', 'r') as f:
71
+ spectrum = json.load(f)
72
+
73
+ wavelength = np.array(spectrum['data']['wavelength'])
74
+ flux = np.array(spectrum['data']['flux'])
75
+ redshift = spectrum['metadata']['redshift']
76
+ ```
77
+
78
+ ## Data Source and Citation
79
+
80
+ This dataset is derived from the Dark Energy Spectroscopic Instrument (DESI) Data Release 1.
81
+
82
+ **DESI Collaboration**: Please cite the appropriate DESI DR1 papers when using this dataset:
83
+ - DESI Collaboration et al. (2024). "The Dark Energy Spectroscopic Instrument (DESI) Data Release 1"
84
+
85
+ ## License
86
+
87
+ This dataset is released under the Creative Commons Attribution 4.0 International License (CC BY 4.0).
88
+
89
+ ## Applications
90
+
91
+ This dataset is suitable for:
92
+ - Galaxy spectroscopy research
93
+ - Redshift analysis and cosmology studies
94
+ - Machine learning applications in astronomy
95
+ - Educational purposes in astrophysics courses
96
+ - Spectral analysis method development
97
+
98
+ ## Technical Details
99
+
100
+ - **Wavelength coverage**: 3600-9824 Å
101
+ - **Spectral resolution**: ~7781 points per spectrum
102
+ - **Flux units**: 10⁻¹⁷ erg/s/cm²/Å
103
+ - **File format**: JSON for spectra, CSV for metadata
104
+ - **Total size**: ~2.5 GB (including all spectrum files)
metadata.csv ADDED
The diff for this file is too large to render. See raw diff
 
plot_desi_spectra.py ADDED
@@ -0,0 +1,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ DESI Spectrum Plotter
4
+ Plot downloaded DESI galaxy spectra with metadata annotations
5
+ """
6
+
7
+ import json
8
+ import matplotlib.pyplot as plt
9
+ import numpy as np
10
+ from pathlib import Path
11
+ import glob
12
+ from typing import Dict, Any, List
13
+ import random
14
+
15
+ def load_spectrum_file(filepath: str) -> Dict[str, Any]:
16
+ """Load a spectrum JSON file and return the data"""
17
+ with open(filepath, 'r') as f:
18
+ return json.load(f)
19
+
20
+ def get_spectrum_files(data_dir: str = '/Users/sandyyuan/astro_mcp_data/desi') -> List[str]:
21
+ """Get all spectrum files from the data directory"""
22
+ pattern = str(Path(data_dir) / 'spectrum_GALAXY_*.json')
23
+ files = glob.glob(pattern)
24
+ return sorted(files)
25
+
26
+ def plot_spectrum(spectrum_data: Dict[str, Any], ax, title_suffix: str = ""):
27
+ """Plot a single spectrum with metadata"""
28
+
29
+ # Extract spectral data
30
+ wavelength = np.array(spectrum_data['data']['wavelength'])
31
+ flux = np.array(spectrum_data['data']['flux'])
32
+ inverse_variance = np.array(spectrum_data['data']['inverse_variance'])
33
+ model = np.array(spectrum_data['data']['model'])
34
+
35
+ # Convert inverse variance to flux error (avoid division by zero)
36
+ flux_err = np.where(inverse_variance > 0, 1.0 / np.sqrt(inverse_variance), np.inf)
37
+
38
+ # Extract metadata
39
+ metadata = spectrum_data['metadata']
40
+
41
+ # Plot the spectrum
42
+ ax.plot(wavelength, flux, 'k-', alpha=0.7, linewidth=0.8, label='Observed Flux')
43
+ ax.plot(wavelength, model, 'r-', alpha=0.8, linewidth=1.0, label='Model Fit')
44
+
45
+ # Add error bars (thinned out for visibility)
46
+ step = max(1, len(wavelength) // 100) # Show every ~100th error bar
47
+ ax.errorbar(wavelength[::step], flux[::step], yerr=flux_err[::step],
48
+ fmt='none', alpha=0.3, color='gray', capsize=0)
49
+
50
+ # Format axes
51
+ ax.set_xlabel('Wavelength (Å)')
52
+ ax.set_ylabel('Flux (10⁻¹⁷ erg/s/cm²/Å)')
53
+ ax.grid(True, alpha=0.3)
54
+ ax.legend(fontsize=8)
55
+
56
+ # Create title with key metadata
57
+ redshift = metadata.get('redshift', 'Unknown')
58
+ obj_type = metadata.get('object_type', 'Unknown')
59
+ survey = metadata.get('survey', 'Unknown')
60
+ target_id = metadata.get('targetid', 'Unknown')
61
+
62
+ title = f"{obj_type} at z={redshift:.4f}{title_suffix}"
63
+ ax.set_title(title, fontsize=10, fontweight='bold')
64
+
65
+ # Add metadata text box
66
+ ra = metadata.get('ra', 'Unknown')
67
+ dec = metadata.get('dec', 'Unknown')
68
+ redshift_err = metadata.get('redshift_err', 'Unknown')
69
+
70
+ metadata_text = (
71
+ f"Target ID: {target_id}\n"
72
+ f"RA, Dec: {ra:.4f}°, {dec:.4f}°\n"
73
+ f"z ± err: {redshift:.4f} ± {redshift_err}\n"
74
+ f"Survey: {survey}"
75
+ )
76
+
77
+ # Position text box in upper right
78
+ ax.text(0.98, 0.98, metadata_text, transform=ax.transAxes,
79
+ verticalalignment='top', horizontalalignment='right',
80
+ bbox=dict(boxstyle='round', facecolor='white', alpha=0.8),
81
+ fontsize=7, family='monospace')
82
+
83
+ return ax
84
+
85
+ def create_spectrum_plots(num_plots: int = 6):
86
+ """Create a grid of spectrum plots"""
87
+
88
+ print("🔍 Finding DESI spectrum files...")
89
+ spectrum_files = get_spectrum_files()
90
+
91
+ if not spectrum_files:
92
+ print("❌ No spectrum files found!")
93
+ return
94
+
95
+ print(f"📊 Found {len(spectrum_files)} spectrum files")
96
+
97
+ # Select a diverse sample
98
+ if len(spectrum_files) > num_plots:
99
+ # Try to get a good spread of redshifts
100
+ selected_files = random.sample(spectrum_files, num_plots)
101
+ else:
102
+ selected_files = spectrum_files
103
+ num_plots = len(spectrum_files)
104
+
105
+ # Create subplot grid
106
+ cols = 2
107
+ rows = (num_plots + cols - 1) // cols
108
+
109
+ fig, axes = plt.subplots(rows, cols, figsize=(15, 4 * rows))
110
+ fig.suptitle('DESI Galaxy Spectra - ELG Sample', fontsize=16, fontweight='bold')
111
+
112
+ # Handle single subplot case
113
+ if num_plots == 1:
114
+ axes = [axes]
115
+ elif rows == 1:
116
+ axes = axes.reshape(1, -1)
117
+
118
+ # Flatten axes for easy iteration
119
+ axes_flat = axes.flatten() if num_plots > 1 else axes
120
+
121
+ print(f"\n📈 Creating plots for {len(selected_files)} spectra...")
122
+
123
+ for i, filepath in enumerate(selected_files):
124
+ print(f" Loading spectrum {i+1}/{len(selected_files)}: {Path(filepath).name}")
125
+
126
+ try:
127
+ # Load spectrum data
128
+ spectrum_data = load_spectrum_file(filepath)
129
+
130
+ # Plot spectrum
131
+ ax = axes_flat[i] if num_plots > 1 else axes_flat[0]
132
+ plot_spectrum(spectrum_data, ax, f" ({i+1}/{len(selected_files)})")
133
+
134
+ except Exception as e:
135
+ print(f" ❌ Error loading {filepath}: {e}")
136
+ continue
137
+
138
+ # Hide unused subplots
139
+ for i in range(len(selected_files), len(axes_flat)):
140
+ axes_flat[i].set_visible(False)
141
+
142
+ plt.tight_layout()
143
+
144
+ # Save the plot
145
+ output_file = '/Users/sandyyuan/astro_mcp_data/desi_spectra_plots.png'
146
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
147
+ print(f"\n💾 Plot saved to: {output_file}")
148
+
149
+ plt.show()
150
+
151
+ def create_redshift_distribution_plot():
152
+ """Create a plot showing the redshift distribution of our sample"""
153
+
154
+ print("\n📊 Creating redshift distribution plot...")
155
+ spectrum_files = get_spectrum_files()
156
+
157
+ redshifts = []
158
+ object_types = []
159
+
160
+ for filepath in spectrum_files:
161
+ try:
162
+ spectrum_data = load_spectrum_file(filepath)
163
+ metadata = spectrum_data['metadata']
164
+ redshift = metadata.get('redshift')
165
+ obj_type = metadata.get('object_type', 'Unknown')
166
+
167
+ if redshift is not None:
168
+ redshifts.append(float(redshift))
169
+ object_types.append(obj_type)
170
+ except Exception as e:
171
+ print(f" Warning: Could not load {filepath}: {e}")
172
+ continue
173
+
174
+ if not redshifts:
175
+ print("❌ No valid redshift data found!")
176
+ return
177
+
178
+ # Create histogram
179
+ fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(10, 8))
180
+
181
+ # Redshift histogram
182
+ ax1.hist(redshifts, bins=15, alpha=0.7, color='skyblue', edgecolor='black')
183
+ ax1.set_xlabel('Redshift (z)')
184
+ ax1.set_ylabel('Number of Galaxies')
185
+ ax1.set_title(f'Redshift Distribution of Downloaded DESI Spectra (N={len(redshifts)})')
186
+ ax1.grid(True, alpha=0.3)
187
+
188
+ # Add statistics
189
+ mean_z = np.mean(redshifts)
190
+ median_z = np.median(redshifts)
191
+ min_z = np.min(redshifts)
192
+ max_z = np.max(redshifts)
193
+
194
+ stats_text = (
195
+ f"Mean z: {mean_z:.3f}\n"
196
+ f"Median z: {median_z:.3f}\n"
197
+ f"Range: {min_z:.3f} - {max_z:.3f}"
198
+ )
199
+
200
+ ax1.text(0.98, 0.98, stats_text, transform=ax1.transAxes,
201
+ verticalalignment='top', horizontalalignment='right',
202
+ bbox=dict(boxstyle='round', facecolor='white', alpha=0.8),
203
+ fontsize=10)
204
+
205
+ # Object type counts
206
+ from collections import Counter
207
+ type_counts = Counter(object_types)
208
+
209
+ ax2.bar(type_counts.keys(), type_counts.values(), alpha=0.7, color='lightcoral')
210
+ ax2.set_xlabel('Object Type')
211
+ ax2.set_ylabel('Count')
212
+ ax2.set_title('Object Type Distribution')
213
+ ax2.grid(True, alpha=0.3)
214
+
215
+ plt.tight_layout()
216
+
217
+ # Save the plot
218
+ output_file = '/Users/sandyyuan/astro_mcp_data/desi_redshift_distribution.png'
219
+ plt.savefig(output_file, dpi=300, bbox_inches='tight')
220
+ print(f"💾 Distribution plot saved to: {output_file}")
221
+
222
+ plt.show()
223
+
224
+ return redshifts, object_types
225
+
226
+ def main():
227
+ """Main function to create all plots"""
228
+ print("="*80)
229
+ print("🌌 DESI SPECTRUM VISUALIZATION")
230
+ print("="*80)
231
+
232
+ # Create spectrum plots
233
+ create_spectrum_plots(num_plots=6)
234
+
235
+ # Create distribution plots
236
+ redshifts, obj_types = create_redshift_distribution_plot()
237
+
238
+ print(f"\n✅ Visualization complete!")
239
+ print(f"📈 Plotted spectra from {len(redshifts)} galaxies")
240
+ print(f"🔴 Redshift range: {min(redshifts):.3f} - {max(redshifts):.3f}")
241
+
242
+ from collections import Counter
243
+ type_counts = Counter(obj_types)
244
+ print(f"📊 Object types: {dict(type_counts)}")
245
+
246
+ if __name__ == "__main__":
247
+ main()
sample_elg_galaxies.py ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script to randomly sample 1000 ELG galaxies from DESI DR1
4
+ """
5
+
6
+ import pandas as pd
7
+ import numpy as np
8
+ import os
9
+ import json
10
+ from pathlib import Path
11
+
12
+ def sample_elg_galaxies():
13
+ """Sample 1000 random ELG galaxies and prepare for spectrum download"""
14
+
15
+ # Configuration
16
+ elg_catalog_file = '/Users/sandyyuan/astro_mcp_data/desi/desi_search_dr1_types_galaxy_tracers_elg_20250811150055.csv'
17
+ output_dir = '/Users/sandyyuan/astro_mcp_data/elg_1000_sample'
18
+ n_samples = 1000
19
+
20
+ print("=== ELG Galaxy Sample Preparation ===")
21
+ print(f"Sampling {n_samples:,} ELG galaxies from DESI DR1")
22
+ print(f"Source file: {elg_catalog_file}")
23
+ print(f"Output directory: {output_dir}")
24
+
25
+ # Create output directory
26
+ Path(output_dir).mkdir(parents=True, exist_ok=True)
27
+
28
+ # Load ELG catalog in chunks and sample randomly
29
+ print(f"\nLoading ELG catalog...")
30
+ chunk_size = 100000
31
+ sampled_galaxies = []
32
+ total_loaded = 0
33
+
34
+ for chunk in pd.read_csv(elg_catalog_file, chunksize=chunk_size):
35
+ total_loaded += len(chunk)
36
+ print(f" Loaded {total_loaded:,} galaxies so far...")
37
+
38
+ # Sample from this chunk proportionally
39
+ chunk_sample_size = min(n_samples, max(1, int(n_samples * len(chunk) / 100000)))
40
+ if len(sampled_galaxies) < n_samples:
41
+ remaining = n_samples - len(sampled_galaxies)
42
+ sample_size = min(chunk_sample_size, remaining, len(chunk))
43
+
44
+ if sample_size > 0:
45
+ chunk_sample = chunk.sample(n=sample_size, random_state=42)
46
+ sampled_galaxies.append(chunk_sample)
47
+ print(f" Sampled {sample_size} galaxies from this chunk")
48
+
49
+ if len(sampled_galaxies) >= 10 or total_loaded >= 1000000: # Stop after reasonable amount
50
+ break
51
+
52
+ # Combine all samples
53
+ if sampled_galaxies:
54
+ sample_df = pd.concat(sampled_galaxies, ignore_index=True)
55
+
56
+ # If we have more than needed, randomly select final 1000
57
+ if len(sample_df) > n_samples:
58
+ sample_df = sample_df.sample(n=n_samples, random_state=123).reset_index(drop=True)
59
+ else:
60
+ print("Error: No galaxies sampled!")
61
+ return
62
+
63
+ print(f"\nFinal sample: {len(sample_df):,} ELG galaxies")
64
+
65
+ # Analyze sample
66
+ print(f"\n=== SAMPLE ANALYSIS ===")
67
+ print(f"Redshift range: {sample_df['redshift'].min():.4f} - {sample_df['redshift'].max():.4f}")
68
+ print(f"Mean redshift: {sample_df['redshift'].mean():.4f}")
69
+ print(f"Median redshift: {sample_df['redshift'].median():.4f}")
70
+
71
+ # Redshift distribution
72
+ bins = [0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 2.0]
73
+ labels = ['0.6-0.8', '0.8-1.0', '1.0-1.2', '1.2-1.4', '1.4-1.6', '1.6+']
74
+ sample_df['z_bin'] = pd.cut(sample_df['redshift'], bins=bins, labels=labels, include_lowest=True)
75
+
76
+ print(f"\nRedshift distribution:")
77
+ z_counts = sample_df['z_bin'].value_counts().sort_index()
78
+ for z_bin, count in z_counts.items():
79
+ if pd.notna(z_bin):
80
+ print(f" {z_bin}: {count:,} galaxies ({count/len(sample_df)*100:.1f}%)")
81
+
82
+ # Survey programs
83
+ if 'program' in sample_df.columns:
84
+ print(f"\nSurvey programs:")
85
+ prog_counts = sample_df['program'].value_counts()
86
+ for program, count in prog_counts.items():
87
+ print(f" {program}: {count:,} galaxies ({count/len(sample_df)*100:.1f}%)")
88
+
89
+ # Save sample metadata
90
+ sample_file = os.path.join(output_dir, 'elg_sample_metadata.csv')
91
+ sample_df.to_csv(sample_file, index=False)
92
+ print(f"\nSaved galaxy sample metadata to: {sample_file}")
93
+
94
+ # Save target IDs
95
+ target_ids = [str(tid) for tid in sample_df['targetid'].tolist()]
96
+ target_ids_file = os.path.join(output_dir, 'target_ids.json')
97
+ with open(target_ids_file, 'w') as f:
98
+ json.dump(target_ids, f, indent=2)
99
+ print(f"Saved {len(target_ids):,} target IDs to: {target_ids_file}")
100
+
101
+ # Create summary
102
+ summary = {
103
+ 'total_elg_galaxies_selected': len(sample_df),
104
+ 'redshift_range': [float(sample_df['redshift'].min()), float(sample_df['redshift'].max())],
105
+ 'mean_redshift': float(sample_df['redshift'].mean()),
106
+ 'target_ids_file': target_ids_file,
107
+ 'metadata_file': sample_file,
108
+ 'ready_for_download': True
109
+ }
110
+
111
+ summary_file = os.path.join(output_dir, 'elg_sample_summary.json')
112
+ with open(summary_file, 'w') as f:
113
+ json.dump(summary, f, indent=2, default=str)
114
+ print(f"Saved summary to: {summary_file}")
115
+
116
+ # Print first few target IDs for download
117
+ print(f"\n=== READY FOR DOWNLOAD ===")
118
+ print(f"Use MCP function 'mcp_astro-mcp_get_spectrum_by_targetid' for each target ID")
119
+ print(f"First 10 target IDs:")
120
+ for i, tid in enumerate(target_ids[:10]):
121
+ print(f" {i+1:2d}. {tid}")
122
+
123
+ if len(target_ids) > 10:
124
+ print(f" ... and {len(target_ids)-10} more in {target_ids_file}")
125
+
126
+ print(f"\nAll files saved to: {output_dir}")
127
+
128
+ if __name__ == "__main__":
129
+ sample_elg_galaxies()
spectrum_GALAXY_0.6004_7006c68c_20250811_152534.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6005_02faa4bf_20250811_155621.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6008_6ce6cb33_20250811_155529.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6011_cebb7ee5_20250811_162429.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6067_9a28c694_20250811_160933.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6103_f21a4d7e_20250811_161921.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6116_a8282d87_20250811_162100.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6118_1489a218_20250811_162059.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6135_e5dc1406_20250811_162452.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6136_b4a514e0_20250811_160440.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6175_eecb7c1d_20250811_161002.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6177_95fdcf42_20250811_160536.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6179_6a5f0d21_20250811_160439.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6204_5af39e3b_20250811_160840.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6219_c0ef549a_20250811_155646.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6222_78d898aa_20250811_160823.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6232_bcd7e093_20250811_160432.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6242_f16f6497_20250811_162107.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6243_c1b34d42_20250811_162032.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6257_bae353db_20250811_160533.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6278_450a52c2_20250811_155702.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6283_065d858c_20250811_152530.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6300_926ed846_20250811_162150.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6301_d9adf642_20250811_162005.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6305_e06a8867_20250811_160933.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6335_49d3ee00_20250811_162009.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6342_40e72d49_20250811_160543.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6375_5065e5d8_20250811_162215.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6389_3c1e976b_20250811_162439.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6405_069dde84_20250811_162328.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6413_70fd16ea_20250811_162135.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6418_8c2456ca_20250811_162400.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6440_41808267_20250811_161901.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6455_9bb84015_20250811_161937.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6500_28bc39be_20250811_160421.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6506_bfca87aa_20250811_160608.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6527_f8e97f60_20250811_161837.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6534_27d72849_20250811_160902.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6556_971b4bd6_20250811_161010.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6557_8a53ac17_20250811_162411.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6578_a684f173_20250811_162245.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6595_3102415b_20250811_160531.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6599_4d3e2365_20250811_160551.json ADDED
The diff for this file is too large to render. See raw diff
 
spectrum_GALAXY_0.6618_9aaf95fb_20250811_160949.json ADDED
The diff for this file is too large to render. See raw diff