Spaces:
Sleeping
Sleeping
File size: 9,946 Bytes
230ea06 71192b4 230ea06 71192b4 230ea06 944f7e5 230ea06 71192b4 230ea06 d40edc5 230ea06 d40edc5 230ea06 d40edc5 230ea06 0c3044a 230ea06 0c3044a 230ea06 35de79c 230ea06 71192b4 230ea06 71192b4 230ea06 0c3044a 35de79c 230ea06 35de79c 71192b4 230ea06 35de79c 230ea06 71192b4 230ea06 71192b4 230ea06 71192b4 230ea06 71192b4 230ea06 71192b4 230ea06 0c3044a 71192b4 230ea06 d40edc5 71192b4 230ea06 71192b4 230ea06 d40edc5 230ea06 d40edc5 230ea06 d40edc5 230ea06 d40edc5 230ea06 d40edc5 230ea06 d40edc5 230ea06 71192b4 230ea06 71192b4 230ea06 944f7e5 230ea06 71192b4 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 | # Extending Jellyscope
This guide explains how to add new data, features, and modules to Jellyscope.
---
## 1. Adding a New Dataset
A dataset is a collection of FITS datacubes and CSV clump catalogs for one galaxy observation. Each dataset is a subdirectory of `data/` (the directory name becomes the dataset's API identifier). A flat `data/` (files directly under it) is loaded as a single dataset called `default`.
### Step 1: Prepare the data files
Place your files in a subdirectory of `data/`:
```mermaid
flowchart LR
data(["data/"])
galaxy["my_new_galaxy/"]
fits1["datacube.fits"]
fits2["datacube_matched.fits"]
csv1["clumps_properties.csv"]
csv2["clumps_pixels.csv"]
data --> galaxy
galaxy --> fits1
galaxy --> fits2
galaxy --> csv1
galaxy --> csv2
```
`DataStore` discovers all subdirectories at startup; the first (alphabetical) becomes the `default_dataset`. Add more subdirectories to expose more datasets — no code changes required.
**FITS requirements**:
- Primary HDU with 3D data array `(n_channels, ny, nx)`
- Header keys `FILTER1`, `FILTER2`, ..., `FILTERn` with filter names
- Standard WCS keys (`CTYPE1`, `CTYPE2`, `CRVAL1`, etc.) are optional but recommended
**CSV requirements**:
- `clumps_properties.csv` columns: `clump_id, area_pix, area_arcsec2, r_eff_arcsec, x0, y0, area_kpc2, r_eff_kpc, inside, component`
- `clumps_pixels.csv` columns: `clump_id, x, y`
- Pixel coordinates must be within the datacube spatial dimensions
### Step 2: Update configuration
Edit `config.py` or pass a custom config:
```python
config = JellyscopeConfig(
data_dir=Path("data"),
datacube_file="my_new_galaxy.fits",
datacube_matched_file="my_new_galaxy_matched.fits",
)
```
Or run from CLI:
```bash
jellyscope --data-dir data
```
### Step 3: Add filter wavelengths (if different instrument)
If your datacube uses filters not in `NIRCAM_WAVELENGTHS`, update the config:
```python
config = JellyscopeConfig(
filter_wavelengths={
"F560W": 5.6,
"F770W": 7.7,
# ... MIRI filters for example
}
)
```
Or add them to `NIRCAM_WAVELENGTHS` in `config.py`.
---
## 2. Adding a New Analysis Module
### Step 1: Create the module
Create a new file in `src/jellyscope/analysis/`:
```python
# src/jellyscope/analysis/color_magnitude.py
"""Color-magnitude diagram analysis."""
import numpy as np
from ..data.model.datacube import DataCube
from ..data.model.clumps import ClumpCatalog
def compute_clump_colors(
datacube: DataCube,
clumps: ClumpCatalog,
blue_filter: str,
red_filter: str,
) -> list[dict]:
"""Compute color (blue - red) and magnitude for each clump."""
results = []
for c in clumps.list_clumps():
mask = clumps.get_pixel_mask(c.clump_id)
blue = datacube.get_slice_by_name(blue_filter)[mask]
red = datacube.get_slice_by_name(red_filter)[mask]
color = -2.5 * np.log10(np.nanmean(blue) / np.nanmean(red))
mag = -2.5 * np.log10(np.nanmean(red))
results.append({
"clump_id": c.clump_id,
"color": float(color),
"magnitude": float(mag),
"component": c.component,
})
return results
```
### Step 2: Add a visualization (optional)
```python
# src/jellyscope/visualization/color_magnitude_plot.py
def create_cmd_figure(data: list[dict]) -> dict:
"""Create a color-magnitude diagram Plotly figure."""
disk = [d for d in data if d["component"] == "disk"]
outside = [d for d in data if d["component"] == "outside"]
return {
"data": [
{
"type": "scatter",
"x": [d["color"] for d in disk],
"y": [d["magnitude"] for d in disk],
"mode": "markers",
"name": "Disk",
"marker": {"color": "#44ff44"},
},
{
"type": "scatter",
"x": [d["color"] for d in outside],
"y": [d["magnitude"] for d in outside],
"mode": "markers",
"name": "Outside",
"marker": {"color": "#ffaa00"},
},
],
"layout": {
"title": {"text": "Color-Magnitude Diagram"},
"xaxis": {"title": "Color (mag)"},
"yaxis": {"title": "Magnitude", "autorange": "reversed"},
"plot_bgcolor": "#1a1a2e",
"paper_bgcolor": "#16213e",
"font": {"color": "#cccccc"},
},
}
```
### Step 3: Add a REST endpoint
In `routes.py`, add (note the `/api/datasets/{dataset_name}/` namespace and the `_dataset(name)` helper):
```python
@router.get("/api/datasets/{dataset_name}/cmd/{datacube_name}")
def get_color_magnitude(dataset_name: str, datacube_name: str):
dataset = _dataset(dataset_name) # Resolve dataset by name (404 if missing)
dc = dataset.get_datacube(datacube_name) # Get the datacube on that dataset
from jellyscope.analysis.color_magnitude import compute_clump_colors
from jellyscope.visualization.color_magnitude_plot import create_cmd_figure
blue = "F150W"
red = "F444W"
data = compute_clump_colors(dc, dataset.clumps, blue, red)
figure = create_cmd_figure(data)
return {"data": data, "figure": figure}
```
If the response shape is non-trivial, define a Pydantic model in `src/jellyscope/model/schemas.py` and return it instead of a bare dict — that file is the single source of truth for the API contract.
### Step 4: Add to the frontend (optional)
In `index.html`, add a new panel or button. In `app.js`, add a fetch call:
```javascript
async function showCMD() {
const resp = await fetch(`/api/datasets/${state.dataset}/cmd/${state.datacube}?blue=F150W&red=F444W`);
const data = await resp.json();
Plotly.react("cmd-plot", data.figure.data, data.figure.layout);
}
```
---
## 3. Adding a New REST Endpoint
All endpoints are in [routes.py](../src/jellyscope/web/routes.py). Every data endpoint is namespaced under `/api/datasets/{dataset_name}/...` so the dataset is explicit in the URL. Follow this pattern:
```python
@router.get("/api/datasets/{dataset_name}/your-endpoint/{datacube_name}")
def your_endpoint(dataset_name: str, datacube_name: str):
dataset = _dataset(dataset_name) # Helper: resolves dataset or 404s
dc = dataset.get_datacube(datacube_name) # Get the datacube
# ... compute something ...
return {"result": ...} # Return dict or Pydantic model
```
For routes that should be opt-in, you can add a config flag plus a small guard helper that 404s when the flag is off — handlers then call the guard at the top.
**Conventions**:
- Prefix all data routes with `/api/datasets/{dataset_name}/`
- Use path parameters for required IDs: `/api/datasets/{dataset_name}/clumps/{clump_id}`
- Use query parameters for optional filters: `?component=disk`
- POST for requests with complex bodies (pixel lists, clump ID arrays)
- Define request/response Pydantic models in `src/jellyscope/model/schemas.py` and reference them via `response_model=...` (FastAPI handles JSON serialization)
---
## 4. Adding a New Visualization
Visualization modules in `src/jellyscope/visualization/` are pure functions that return Plotly figure dicts. They follow this pattern:
```python
def create_my_figure(data: ...) -> dict:
"""Create a Plotly figure for X."""
return {
"data": [
{"type": "scatter", "x": [...], "y": [...], ...},
],
"layout": {
"title": {"text": "My Plot", "font": {"color": "#cccccc"}},
"xaxis": {"title": "X Label", "gridcolor": "#333", "color": "#999"},
"yaxis": {"title": "Y Label", "gridcolor": "#333", "color": "#999"},
"plot_bgcolor": "#1a1a2e",
"paper_bgcolor": "#16213e",
"font": {"color": "#cccccc"},
"margin": {"l": 60, "r": 20, "t": 40, "b": 50},
},
}
```
**Dark theme values** (copy these for consistency):
- `plot_bgcolor`: `#1a1a2e`
- `paper_bgcolor`: `#16213e`
- `font.color`: `#cccccc`
- `gridcolor`: `#333`
- `axis.color`: `#999`
---
## 5. Publishing as a PyPI Package
The project is already structured for this. Steps:
### Build
```bash
pip install build
python -m build
# Creates dist/jellyscope-0.1.0.tar.gz and dist/jellyscope-0.1.0-py3-none-any.whl
```
### Test locally
```bash
pip install dist/jellyscope-0.1.0-py3-none-any.whl
jellyscope --data-dir /path/to/data
```
### Publish to PyPI
```bash
pip install twine
twine upload dist/*
```
### Publish to TestPyPI (for testing)
```bash
twine upload --repository testpypi dist/*
pip install --index-url https://test.pypi.org/simple/ jellyscope
```
### Version bump
Update the version in two places:
1. `pyproject.toml`: `version = "0.2.0"`
2. `src/jellyscope/__init__.py`: `__version__ = "0.2.0"`
---
## 6. Multiple Galaxies (already supported)
`DataStore` already discovers multiple galaxies as subdirectories of `config.data_dir`. Drop your data in:
```mermaid
flowchart LR
data(["data/"])
g1["jw2736-jfg1/"]
g1f1["datacube.fits"]
g1f2["datacube_matched.fits"]
g1f3["clumps_properties.csv"]
g1f4["clumps_pixels.csv"]
g2["jw2736-jfg2/"]
data --> g1
data --> g2
g1 --> g1f1
g1 --> g1f2
g1 --> g1f3
g1 --> g1f4
```
Each subdirectory is loaded as a `Dataset` named after the directory. The first (alphabetical) becomes `default_dataset`. A flat layout (files directly under `data/`) is loaded as a single dataset called `default` for backward compatibility.
The frontend exposes the active dataset via `DEFAULT_DATASET` (template-injected) and `state.dataset` (JS), so all `/api/datasets/${state.dataset}/...` calls automatically scope to it. To let the user switch galaxies, add a `<select>` populated from `DATASETS` and update `state.dataset` on change before re-rendering.
|