Spaces:
Sleeping
Sleeping
Commit ·
2dc366b
1
Parent(s): bd850a2
add features
Browse filesFiles changed (20)
- docs/api-reference.md+158-3
- docs/frontend.md+109-33
- docs/visualization.md+92-3
- src/jellyscope/model/schemas.py+51
- src/jellyscope/spec_analysis/__init__.pyAdded+1
- src/jellyscope/spec_analysis/spectral.pyAdded+62
- src/jellyscope/spec_analysis/stats.pyAdded+52
- src/jellyscope/visualization/image_viewer.py+49-28
- src/jellyscope/visualization/rgb_composite.pyAdded+152
- src/jellyscope/visualization/spectrum_plot.pyAdded+129
- src/jellyscope/web/routes.py+116-4
- src/jellyscope/web/static/app.js+108-3
- src/jellyscope/web/static/style.css+56
- src/jellyscope/web/templates/index.html+42-12
- tests/spec_analysis/test_spectral.pyAdded+44
- tests/spec_analysis/test_statistics.pyAdded+44
- tests/visualization/__init__.pyAdded
- tests/visualization/test_image_viewer.pyAdded+109
- tests/visualization/test_rgb_composite.pyAdded+84
- tests/web/test_routes.py+80
76 unmodified lines77787980808182839 unmodified lines9394959697989910010110210310419 unmodified lines124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171102 unmodified lines2742752762292302772782792802812822832842852865 unmodified lines29229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539676 unmodified lines
```bash# F200W (channel 7), with clumps 0 and 4 selectedcurl "http://localhost:5000/api/viewer/nircam/7?selected=0,4&colorscale=Viridis"curl "http://localhost:5000/api/viewer/nircam/7?selected=0,4&colorscale=Viridis&stretch=log"```
**Path parameters**:9 unmodified lines| ------- | ------ | --------- | ------------- || `selected` | `string` | `""` | Comma-separated clump IDs to highlight || `colorscale` | `string` | `"Viridis"` | Plotly colorscale name || `stretch` | `string` | `"log"` | Intensity stretch: `"log"`, `"lupton_asinh"`, or `"power"` |
**Error responses**:
- `400` — channel index out of range- `422` — invalid stretch value
**Response**:
19 unmodified lines
---
### `GET /api/viewer/{datacube_name}/rgb`
Returns an RGB composite Plotly figure using the Lupton et al. (2004) algorithm.
```bashcurl "http://localhost:5000/api/viewer/nircam/rgb?r=19&g=10&b=0&softening=8.0"```
**Query parameters**:
| Param | Type | Default | Description || ------- | ------ | --------- | ------------- || `r` | `int` | required | Red channel filter index || `g` | `int` | required | Green channel filter index || `b` | `int` | required | Blue channel filter index || `selected` | `string` | `""` | Comma-separated clump IDs to highlight || `softening` | `float` | `8.0` | Q parameter (controls linear-to-log transition) |
**Error responses**:
- `400` — channel index out of range
**Response**:
```json{ "figure": { "data": [ {"type": "image", "z": [[[r,g,b], ...]], ...}, {"type": "scatter", ...}, ... ], "layout": {...} }, "r_filter": "F480M", "g_filter": "F277W", "b_filter": "F070W"}```
---
## Clumps
### `GET /api/clumps`102 unmodified linesThese examples show how the frontend calls the API (from [app.js](../src/jellyscope/web/static/app.js)):
```javascript// Get viewer figureconst resp = await fetch(`/api/viewer/nircam/7?selected=0,4&colorscale=Viridis`);// Get viewer figure (single-band)const resp = await fetch(`/api/viewer/nircam/7?selected=0,4&colorscale=Viridis&stretch=log`);const data = await resp.json();Plotly.react("galaxy-viewer", data.figure.data, data.figure.layout);
// Get RGB compositeconst resp = await fetch(`/api/viewer/nircam/rgb?r=19&g=10&b=0&softening=8.0`);const data = await resp.json();Plotly.react("galaxy-viewer", data.figure.data, data.figure.layout);
5 unmodified linesconst resp = await fetch(`/api/clumps/4`);const { properties, boundary } = await resp.json();```
---
## Spectral Extraction
### `GET /api/clumps/{clump_id}/spectrum/{datacube_name}`
Mean SED for a clump (flux averaged over all pixels in the clump mask).
```bashcurl http://localhost:5000/api/clumps/0/spectrum/nircam```
**Response**:
```json{ "spectrum": { "filter_names": ["F070W", "F090W", ...], "wavelengths": [0.704, 0.901, ...], "mean_flux": [1.2e-3, 1.5e-3, ...], "std_flux": [2e-4, 3e-4, ...], "n_pixels": 121, "clump_id": 0 }, "figure": { "data": [...], "layout": {...} }}```
---
### `GET /api/pixel/{x}/{y}/spectrum/{datacube_name}`
SED for a single pixel.
```bashcurl http://localhost:5000/api/pixel/80/100/spectrum/nircam```
**Response**:
```json{ "spectrum": { "filter_names": ["F070W", ...], "wavelengths": [0.704, ...], "fluxes": [3.1e-4, ...], "n_pixels": 1 }, "figure": { "data": [...], "layout": {...} }}```
---
### `POST /api/region/spectrum/{datacube_name}`
Mean SED for an arbitrary region (rectangle or pixel list).
```bashcurl -X POST http://localhost:5000/api/region/spectrum/nircam \ -H "Content-Type: application/json" \ -d '{"rect": {"x0": 70, "y0": 15, "x1": 80, "y1": 25}}'```
**Request body** (one of):
```json{"rect": {"x0": 70, "y0": 15, "x1": 80, "y1": 25}}```
or:
```json{"pixels": [[72, 20], [73, 20], [74, 21]]}```
**Response**: Same shape as clump spectrum (with `mean_flux`, `std_flux`, `n_pixels`).
---
### `POST /api/compare/spectrum/{datacube_name}`
Overlay multiple clump SEDs for comparison.
```bashcurl -X POST http://localhost:5000/api/compare/spectrum/nircam \ -H "Content-Type: application/json" \ -d '{"clump_ids": [0, 1, 3]}'```
**Response**:
```json{ "spectra": [ {"filter_names": [...], "wavelengths": [...], "mean_flux": [...], ...}, ... ], "figure": { "data": [...], "layout": {...} }}```13 unmodified lines14151617171819202122232425262727282930313233343536373839402829303132333435363738394041424344454446474849505152515253535455565758596061625563646566596768696 unmodified lines7677787279808182838485868713 unmodified lines1011021031041051061071081091101111121131141152 unmodified lines1181191201051061211221231241251081091101111121261271281291301311321331341351361371386 unmodified lines145146147148149150151152153154155156157158159160161162163164165166167168169170130171172173174175176133134177178179180181137182183184185162 unmodified lines34834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038113 unmodified lines
**Location**: `src/jellyscope/web/templates/index.html`
This is a Jinja2 template rendered by FastAPI (via `Jinja2Templates`). It receives two variables from the server:This is a Jinja2 template rendered by FastAPI (via `Jinja2Templates`). It receives three variables from the server:
- `datacubes`: list of available datacube names (e.g., `["nircam", "nircam_matched"]`)- `filters`: list of filter names (e.g., `["F070W", "F090W", ...]`)- `wavelengths`: dict mapping filter names to central wavelengths in µm
### Layout
The page uses CSS Grid with two columns:
```plaintext┌──────────────────────────────────────────────────────────┐│ HEADER: "Jellyscope — JWST Jellyfish Galaxy Explorer" │├──────────────────────────────┬───────────────────────────┤│ │ PROPERTIES PANEL ││ VIEWER CONTROLS │ (clump info table) ││ [Datacube ▼] [Slider] ├───────────────────────────┤│ [Colors ▼] [Pan|Rect|Lasso] │ CLUMP LIST ││ │ (checkboxes with badges) ││ GALAXY VIEWER │ [Filter: All ▼] ││ (Plotly heatmap) ├───────────────────────────┤│ 172 x 221 px image │ SPECTRUM PLOT (SED) ││ with clump overlays │ (Plotly line chart) ││ │ │└──────────────────────────────┴───────────────────────────┘┌──────────────────────────────────────────────────────────────────────┐│ HEADER: "Jellyscope — JWST Jellyfish Galaxy Explorer" │├────────────────────────────────────────┬─────────────────────────────┤│ │ PROPERTIES PANEL ││ VIEWER CONTROLS │ (clump info table) ││ [Datacube ▼] [Stretch ▼] ├─────────────────────────────┤│ [Single|RGB] [Filter/RGB controls] │ CLUMP LIST ││ [Pan|Rect|Lasso] [Centroids] │ (checkboxes with badges) ││ │ [Filter: All ▼] ││ GALAXY VIEWER │ ││ (Plotly heatmap or RGB image) │ ││ 172 x 221 px image │ ││ with clump overlays │ ││ │ │└────────────────────────────────────────┴─────────────────────────────┘```
Left column: `1fr` (flexible) — the galaxy viewer expands to fill available space.Right column: `360px` fixed — the three panels stack vertically.Right column: `360px` fixed — the panels stack vertically.
### Key HTML Elements
| Element ID | Type | Purpose || ----------- | ------ | --------- || `datacube-select` | `<select>` | Choose between nircam / nircam_matched || `filter-slider` | `<input type="range">` | Navigate 20 filter channels (0-19) || `filter-label` | `<span>` | Shows current filter name (e.g., "F200W") || `colorscale-select` | `<select>` | Viridis, Inferno, Plasma, Cividis, Hot, Greys || `stretch-select` | `<select>` | Intensity stretch: Log, Asinh (Lupton), Power || `btn-view-single` / `btn-view-rgb` | `<button>` | Toggle between single-band and RGB mode || `filter-slider` | `<input type="range">` | Navigate 20 filter channels (0-19) — single mode only || `colorscale-select` | `<select>` | Viridis, Inferno, Plasma, Cividis, Hot, Greys — single mode only || `rgb-r` / `rgb-g` / `rgb-b` | `<select>` | Filter channel for each RGB band — RGB mode only || `rgb-q` | `<input type="range">` | Softening (Q) parameter for Lupton stretch — RGB mode only || `rgb-q-label` | `<span>` | Shows current Q value || `filter-label` | `<span>` | Unified status: filter name (single) or R/G/B combo (RGB) || `btn-click` / `btn-select` / `btn-lasso` | `<button>` | Interaction mode buttons || `btn-centroids` | `<button>` | Toggle centroid markers visibility || `galaxy-viewer` | `<div>` | Plotly mounts the heatmap here || `galaxy-viewer` | `<div>` | Plotly mounts the figure here || `properties-content` | `<div>` | Clump properties table or status message || `clump-filter` | `<select>` | Filter clump list: All / Disk / Outside || `clump-list` | `<div>` | Dynamic clump list with checkboxes || `spectrum-plot` | `<div>` | Plotly mounts the SED chart here |
### Jinja2 Template Variables
6 unmodified lines<!-- Filter slider range from server --><input type="range" min="0" max="{{ filters|length - 1 }}" value="7">
<!-- Filter names passed to JavaScript --><!-- Filter names and wavelengths passed to JavaScript --><script> const FILTERS = {{ filters | tojson }}; // → ["F070W", "F090W", ..., "F480M"] const WAVELENGTHS = {{ wavelengths | tojson }}; // → {"F070W": 0.704, "F090W": 0.901, ...}</script>```
13 unmodified lines channel: 7, // Current filter channel (default: F200W) selectedClumps: new Set(), // Set of selected clump IDs colorscale: "Viridis", // Current colorscale stretch: "log", // Intensity stretch function dragmode: "pan", // Plotly interaction mode clumps: [], // Loaded clump list from API showCentroids: false, // Whether centroid markers are visible viewMode: "single", // "single" (heatmap) or "rgb" (composite) rgbR: 19, // Red channel filter index (longest λ) rgbG: 10, // Green channel filter index (middle λ) rgbB: 0, // Blue channel filter index (shortest λ) rgbQ: 8.0, // Lupton softening parameter};```
2 unmodified lines```plaintextDOMContentLoaded └── init() ├── loadClumpList() → GET /api/clumps → populate clump list ├── renderViewer() → GET /api/viewer/nircam/7 → render Plotly figure ├── populateRGBSelects() → fill R/G/B dropdowns with filter names + wavelengths ├── loadClumpList() → GET /api/clumps → populate clump list ├── updateFilterLabel() → set initial status label ├── renderViewer() → GET /api/viewer/... → render Plotly figure └── setupEventListeners() ├── datacube-select → onChange → renderViewer() ├── filter-slider → onInput → update label + renderViewer() ├── colorscale-select → onChange → renderViewer() ├── mode buttons → onClick → Plotly.relayout(dragmode) └── clump-filter → onChange → loadClumpList() ├── datacube-select → onChange → renderViewer() ├── filter-slider → onInput → updateFilterLabel() + renderViewer() ├── colorscale-select → onChange → renderViewer() ├── stretch-select → onChange → renderViewer() ├── view-btn (Single/RGB) → onClick → updateViewModeUI() + renderViewer() ├── rgb-r/g/b → onChange → updateFilterLabel() + renderViewer() ├── rgb-q → onInput → debounced(renderViewer, 300ms) ├── mode buttons → onClick → Plotly.relayout(dragmode) ├── btn-centroids → onClick → toggle + renderViewer() └── clump-filter → onChange → loadClumpList()```
### Function Reference6 unmodified lines
Attaches DOM event handlers to all control elements. Each handler updates `state` and triggers the appropriate re-render.
#### `debounce(fn, ms)`
Utility that delays function execution until `ms` milliseconds after the last invocation. Used for the Q slider to avoid flooding the API during drag.
#### `populateRGBSelects()`
Fills the R/G/B `<select>` dropdowns with filter options (name + wavelength labels). Sets default values: longest wavelength → R, middle → G, shortest → B.
#### `updateFilterLabel()`
Updates the `#filter-label` status indicator:- **Single mode**: shows `"F200W (1.99 µm)"`- **RGB mode**: shows `"R:F480M G:F277W B:F070W"`
#### `updateViewModeUI()`
Shows/hides the appropriate control group (`#single-controls` vs `#rgb-controls`) based on `state.viewMode`.
#### `renderViewer()`
The core render function. Fetches the Plotly figure from the API and renders it:
```plaintext1. Build URL: /api/viewer/{datacube}/{channel}?selected={ids}&colorscale={scale}1. If viewMode == "rgb": Build URL: /api/viewer/{datacube}/rgb?r={R}&g={G}&b={B}&softening={Q}&selected={ids} Else: Build URL: /api/viewer/{datacube}/{channel}?selected={ids}&colorscale={scale}&stretch={stretch}2. fetch(url) → JSON response with figure dict3. Set figure.layout.dragmode = state.dragmode4. Plotly.react("galaxy-viewer", fig.data, fig.layout, plotlyConfig)5. Attach plotly_click and plotly_selected event handlers4. If !showCentroids → remove last trace (centroids) from data5. Plotly.react("galaxy-viewer", fig.data, fig.layout, plotlyConfig)6. Attach plotly_click event handler```
Called whenever: datacube changes, filter changes, colorscale changes, or clump selection changes.Called whenever: datacube changes, filter changes, colorscale changes, stretch changes, view mode changes, RGB channels change, Q slider moves (debounced), clump selection changes, or centroids toggled.
#### `onViewerClick(eventData)`
162 unmodified lines.clump-badge.disk { color: #44ff44; border: 1px solid #44ff44; }.clump-badge.outside { color: #ffaa00; border: 1px solid #ffaa00; }```
### View Mode Buttons and Toggle Buttons
View mode (`Single` / `RGB`) and interaction mode buttons share styling patterns:
```css.view-btn, .mode-btn, .toggle-btn { background: var(--bg-panel); border: 1px solid var(--border); /* Active state: cyan background, black text */}.view-btn.active, .mode-btn.active, .toggle-btn.active { background: var(--accent); color: #000;}```
### RGB Controls
The Q slider and its label are styled to match the filter slider:
```css#rgb-q { width: 80px; accent-color: var(--accent);}#rgb-q-label { color: var(--accent); font-weight: 600;}```4 unmodified lines5678910111231 unmodified lines444546474849505152535455565758596061496263516465666770 unmodified lines1381391401281411421431446 unmodified lines15115215315415515615759 unmodified lines2172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932944 unmodified lines**Files covered**:
- [visualization/image_viewer.py](../src/jellyscope/visualization/image_viewer.py) — Galaxy heatmap + clump overlays- [visualization/rgb_composite.py](../src/jellyscope/visualization/rgb_composite.py) — Lupton et al. (2004) RGB composite- [visualization/spectrum_plot.py](../src/jellyscope/visualization/spectrum_plot.py) — SED line plots- [visualization/properties_panel.py](../src/jellyscope/visualization/properties_panel.py) — Property formatting
---31 unmodified lines
The factor of 18 controls the stretch intensity — higher values bring out more faint structure.
#### `_lupton_asinh_stretch(data: np.ndarray, softening=8.0, alpha=None) -> np.ndarray`
Lupton et al. (2004) single-band asinh stretch: `f(x) = arcsinh(alpha*Q*(x-m)) / Q`. Linear for faint features, logarithmic for bright features. Background level `m` and noise `sigma` are estimated via sigma-clipped statistics. If `alpha` is not provided, it is auto-computed from the noise level as `0.02 / sigma`.
**Algorithm**:
1. Estimate background `(m, sigma)` via sigma-clipped stats2. Compute `alpha = 0.02 / sigma` if not given3. Apply `arcsinh(alpha * Q * (x - m)) / Q`4. Normalize to [0, 1] using 99.5th percentile
#### `_power_stretch(data: np.ndarray) -> np.ndarray`
Power stretch using astropy's `PowerStretch(a=0.5)`. Lower exponent = more aggressive on faint features. Uses [20th, 99.5th] percentile bounds.
#### `_normalize_stretch(data, normalize_func=_log_stretch) -> np.ndarray`#### `_normalize_stretch(data, stretch="log") -> np.ndarray`
Dispatcher that applies the given stretch function. Defaults to `_log_stretch`.Dispatcher that applies the given stretch function. Accepts `"log"`, `"lupton_asinh"`, or `"power"`. Defaults to `"log"`.
---
70 unmodified lines
---
### `build_viewer_figure(datacube, channel_index, clumps, selected_ids=None, colorscale="Viridis") -> dict`### `build_viewer_figure(datacube, channel_index, clumps, selected_ids=None, colorscale="Viridis", stretch="log") -> dict`
**Main entry point**. Assembles the complete Plotly figure by combining all the traces above with a layout.
6 unmodified lines| `clumps` | `ClumpCatalog` | Clump catalog for overlays || `selected_ids` | `list[int] \| None` | Clumps to highlight in red || `colorscale` | `str` | Plotly colorscale name || `stretch` | `str` | `"log"`, `"lupton_asinh"`, or `"power"` |
**Returns**: Complete Plotly figure dict:
59 unmodified lines ...</table>```
---
## visualization/rgb_composite.py — RGB Composite
**Location**: `src/jellyscope/visualization/rgb_composite.py`
Implements the Lupton et al. (2004) color-preserving RGB mapping. The key insight: apply the intensity stretch to total intensity I = (R+G+B)/3, then scale each band by f(I)/I. This ensures an object's color in the output depends only on its flux ratios, not its brightness.
### `lupton_rgb_composite(r_data, g_data, b_data, softening=8.0, alpha=None) -> np.ndarray`
Core algorithm (Equation 2 of the paper).
**Parameters**:
| Param | Type | Description || ------- | ------ | ------------- || `r_data` | `np.ndarray` | 2D flux array for the red channel || `g_data` | `np.ndarray` | 2D flux array for the green channel || `b_data` | `np.ndarray` | 2D flux array for the blue channel || `softening` | `float` | Q parameter controlling linear-to-log transition (typical: 8-9) || `alpha` | `float \| None` | Linear stretch factor. Auto-estimated from noise if None |
**Algorithm**:
1. Compute total intensity: `I = (R + G + B) / 3`2. Estimate background `(m, sigma)` via sigma-clipped stats3. Compute `alpha = 0.02 / sigma` if not given4. Apply asinh stretch to intensity: `f(I) = arcsinh(alpha * Q * (I - m)) / Q`5. Color-preserving scale: `ratio = f(I) / (I - m)`6. Scale each band: `R_out = (R - m) * ratio`, etc.7. Per-pixel saturation clamping: if max(R,G,B) > 1, scale down to preserve hue8. Global normalization to [0,1] using 99.5th percentile9. Return uint8 array of shape `(ny, nx, 3)`
### `build_rgb_figure(datacube, r_index, g_index, b_index, clumps, ...) -> dict`
Assembles the Plotly figure with RGB image + clump overlays.
**Coordinate system note**: Plotly's `go.Image` renders array row 0 at the top (y-axis increases downward), while heatmaps render row 0 at the bottom. To match single-band visual orientation:
1. The image is flipped vertically (`np.flipud`)2. Boundary/centroid y-coordinates are transformed: `y_new = ny - 1 - y`3. The y-axis uses `autorange: "reversed"` to keep y=0 at the bottom
All three are required for correct alignment between the RGB image and scatter overlays.
---
## visualization/spectrum_plot.py — SED Plots
**Location**: `src/jellyscope/visualization/spectrum_plot.py`
Builds Plotly line charts for Spectral Energy Distributions (SEDs).
### `create_sed_figure(spectrum, title="Spectral Energy Distribution") -> dict`
Creates a single SED plot with flux vs wavelength. If the spectrum dict contains `std_flux`, a filled ±1σ uncertainty band is added.
**Input `spectrum` dict**:
```python{ "wavelengths": [0.704, 0.901, ...], # µm "mean_flux": [1.2e-3, 1.5e-3, ...], # or "fluxes" for single pixel "std_flux": [2e-4, 3e-4, ...], # optional "filter_names": ["F070W", "F090W", ...],}```
### `create_multi_sed_figure(spectra, labels) -> dict`
Overlays multiple SEDs on one plot for comparison. Each SED gets a distinct color from an 8-color palette. Used by the `/api/compare/spectrum/` endpoint.
---3 unmodified lines4567891011121314151617181920212223242526272829303132333435363752 unmodified lines909192939495969798991001011021031041051061071081091101111121131141153 unmodified lines
from pydantic import BaseModel
# --- Request models ---
class RectSelection(BaseModel): """Rectangle defined by two corners."""
x0: int y0: int x1: int y1: int
class RegionRequest(BaseModel): """Request body for region spectrum extraction.
Provide either a list of pixel coordinates or a rectangle, not both. """
pixels: list[list[int]] | None = None rect: RectSelection | None = None
class CompareRequest(BaseModel): """Request body for multi-clump SED comparison."""
clump_ids: list[int]
# --- Response models ---
52 unmodified lines """Result of looking up which clump a pixel belongs to."""
clump_id: int | None
class SpectrumResponse(BaseModel): """Spectrum data plus its Plotly figure."""
spectrum: dict[str, Any] figure: dict[str, Any]
class CompareResponse(BaseModel): """Multi-clump comparison: overlaid Plotly figure plus individual spectra."""
figure: dict[str, Any] spectra: list[dict[str, Any]]
class RGBViewerResponse(BaseModel): """Plotly figure for RGB composite viewer."""
figure: dict[str, Any] r_filter: str g_filter: str b_filter: str1"""Spectral Analysis subpackage: spectral extraction and statistics."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Spectral extraction from datacubes for pixels, clumps, and arbitrary regions."""
import numpy as np
from jellyscope.config import NIRCAM_WAVELENGTHSfrom jellyscope.data.data_store import DataCubefrom jellyscope.data.model.clumps import ClumpCatalog
def _wavelengths_for(filter_names: list[str]) -> list[float]: """Map filter names to central wavelengths in microns.""" return [NIRCAM_WAVELENGTHS.get(f, 0.0) for f in filter_names]
def extract_pixel_spectrum(datacube: DataCube, x: int, y: int) -> dict: """Extract spectrum at a single pixel.
Returns dict with filter_names, wavelengths, and fluxes arrays. """ fluxes: np.ndarray = datacube.get_spectrum_at_pixel(x, y) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "fluxes": [float(f) if not np.isnan(f) else None for f in fluxes], "n_pixels": 1, }
def extract_clump_spectrum(datacube: DataCube, clumps: ClumpCatalog, clump_id: int) -> dict: """Mean spectrum for a clump region.""" mask: np.ndarray = clumps.get_pixel_mask(clump_id) mean_flux, std_flux = datacube.get_mean_spectrum_for_mask(mask) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [float(f) if not np.isnan(f) else None for f in mean_flux], "std_flux": [float(f) if not np.isnan(f) else None for f in std_flux], "n_pixels": int(mask.sum()), "clump_id": clump_id, }
def extract_region_spectrum(datacube: DataCube, mask: np.ndarray) -> dict: """Mean spectrum for an arbitrary boolean mask (from lasso/rectangle selection).""" n_pixels = int(mask.sum()) if n_pixels == 0: n_ch: int = datacube.n_channels return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [None] * n_ch, "std_flux": [None] * n_ch, "n_pixels": 0, } mean_flux, std_flux = datacube.get_mean_spectrum_for_mask(mask) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [float(v) if not np.isnan(v) else None for v in mean_flux], "std_flux": [float(v) if not np.isnan(v) else None for v in std_flux], "n_pixels": n_pixels, }12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Summary statistics for selected regions."""
import numpy as np
from jellyscope.data.data_store import DataCubefrom jellyscope.data.model.clumps import ClumpCatalog, ClumpProperties
def compute_region_stats(datacube: DataCube, mask: np.ndarray, channel_idx: int) -> dict: """Compute statistics for a spatial region at a given filter channel.""" slice_data: np.ndarray = datacube.get_slice_by_channel_index(channel_idx) values = slice_data[mask] valid = values[~np.isnan(values)] if len(valid) == 0: return { "filter": datacube.filter_names[channel_idx], "n_pixels": 0, "mean": None, "median": None, "std": None, "min": None, "max": None, "sum": None, } return { "filter": datacube.filter_names[channel_idx], "n_pixels": len(valid), "mean": float(np.mean(valid)), "median": float(np.median(valid)), "std": float(np.std(valid)), "min": float(np.min(valid)), "max": float(np.max(valid)), "sum": float(np.sum(valid)), }
def compute_clump_summary(datacube: DataCube, clumps: ClumpCatalog, clump_id: int) -> dict: """Full summary: clump properties + per-channel statistics.""" props: ClumpProperties = clumps.get_clump_by_id(clump_id) mask = clumps.get_pixel_mask(clump_id) channel_stats: list[dict] = [ compute_region_stats(datacube, mask, i) for i in range(datacube.n_channels) ] return { "clump_id": clump_id, "component": props.component, "area_pix": props.area_pix, "area_kpc2": props.area_kpc2, "r_eff_kpc2": props.r_eff_kpc2, "inside": props.inside, "channel_stats": channel_stats, }17 unmodified lines181920212223212223242526272825262930313233282930313234343535363738393738394041424340414243444546474849505152535455565758596061626347 unmodified lines11111211397989910010110210311411511611711811912012112212312412512612712812913013111213213313413561 unmodified lines19719819920020120220320420518520620720820917 unmodified lines_SOFT_DARK_BLUE: str = "#16213e"
def _asinh_stretch(data: np.ndarray) -> np.ndarray: # pragma: no cover """Apply arcsinh stretch to bring out faint features.""" # Ignore NaN/Inf when computing percentile bounds.def _estimate_background(data: np.ndarray) -> tuple[float, float]: """Estimate background level and noise via sigma-clipped statistics.
Returns (median, std) from sigma_clipped_stats. """ from astropy.stats import sigma_clipped_stats
finite = data[np.isfinite(data)] if len(finite) == 0: return data if finite.size == 0: return 0.0, 1.0 _, median, std = sigma_clipped_stats(finite, sigma=3.0, maxiters=5) return float(median), float(std)
# Use 1st and 99.5th percentiles to define the dynamic range, # trimming extreme outliers on both ends. vmin = np.percentile(finite, 2) vmax = np.percentile(finite, 99.5) clipped = np.clip(data, a_min=vmin, a_max=vmax)
# Linearly scale to [0, 1] (epsilon avoids division by zero). normalized = (clipped - vmin) / (vmax - vmin + 1e-10)def _lupton_asinh_stretch( data: np.ndarray, softening: float = 8.0, alpha: float | None = None) -> np.ndarray: """Lupton et al. (2004) asinh stretch: f(x) = arcsinh(alpha*Q*(x-m)) / Q.
# arcsinh(x * 10) / arcsinh(10), is a non-linear mapping that compresses bright pixels # and boosts faint structure, making low-surface-brightness features, such as # jellyfish tails, visible without saturating bright regions. factor: int = 18 stretched: np.ndarray = np.arcsinh(normalized * factor) / np.arcsinh(factor) # TODO: try new values and methods together with Andressa. # stretch = HistEqStretch(data=data[~np.logical_or(np.isnan(data), data <= 0.0)]) Linear for faint features (x ~ m), logarithmic for bright features. Parameters Q and alpha control the transition point. """ finite = data[np.isfinite(data)] if finite.size == 0: return np.zeros_like(data)
m, sigma = _estimate_background(data) if alpha is None: alpha = 0.02 / (sigma + 1e-10)
stretched = np.arcsinh(alpha * softening * (data - m)) / softening
finite_stretched = stretched[np.isfinite(stretched)] if finite_stretched.size == 0: return np.zeros_like(data) vmax = np.percentile(finite_stretched, 99.5) if vmax > 0: stretched = stretched / vmax stretched = np.clip(stretched, 0.0, 1.0) stretched[~np.isfinite(data)] = np.nan return stretched
47 unmodified lines return stretched
def _normalize_stretch( data: np.ndarray, normalize_func: Callable[[np.ndarray], np.ndarray] = _log_stretch) -> np.ndarray: """Apply the given normalization stretch function to bring out faint features. Defaults to LogStretch """ return normalize_func(data)def _normalize_stretch(data: np.ndarray, stretch: str = "log") -> np.ndarray: """Apply the named stretch function to bring out faint features.""" _stretch_map: dict[str, Callable[[np.ndarray], np.ndarray]] = { "log": _log_stretch, "lupton_asinh": _lupton_asinh_stretch, "power": _power_stretch, } func = _stretch_map.get(stretch, _log_stretch) return func(data)
def create_galaxy_heatmap( slice_data: np.ndarray, colorscale: str = "viridis", stretch: str = "log",) -> dict[str, Any]: """Create a Plotly heatmap trace for a datacube slice.""" z = [] for row in _normalize_stretch(data=slice_data, normalize_func=_log_stretch): for row in _normalize_stretch(data=slice_data, stretch=stretch): z.append([None if np.isnan(v) else float(v) for v in row]) return { "type": "heatmap",61 unmodified lines clumps: ClumpCatalog, selected_ids: list[int] | None = None, colorscale: str = "Viridis", stretch: str = "log",) -> dict[str, Any]: """Assembles heatmap + boundaries + centroids.""" slice_data: np.ndarray = datacube.get_slice_by_channel_index(channel_index) filter_name: str = datacube.filter_names[channel_index]
heatmap: dict[str, Any] = create_galaxy_heatmap(slice_data, colorscale) heatmap: dict[str, Any] = create_galaxy_heatmap(slice_data, colorscale, stretch) boundaries: list[dict[str, Any]] = create_clump_boundary_traces(clumps, selected_ids) centroids: dict[str, Any] = create_centroid_markers(clumps)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152"""RGB color composite using the Lupton et al. (2004) algorithm.
Implements Equation 2 from the paper: color-preserving mapping that ensuresan object's color in the RGB image depends only on its flux ratios, not brightness."""
from typing import Any
import numpy as np
from jellyscope.data.data_store import DataCubefrom jellyscope.data.model.clumps import ClumpCatalogfrom jellyscope.visualization.image_viewer import ( _estimate_background, create_centroid_markers, create_clump_boundary_traces,)
_GRAY: str = "#cccccc"_DARK_GRAY: str = "#999"_SOFT_BLACK: str = "#333"_DARK_BLUE: str = "#1a1a2e"_SOFT_DARK_BLUE: str = "#16213e"
def lupton_rgb_composite( r_data: np.ndarray, g_data: np.ndarray, b_data: np.ndarray, softening: float = 8.0, alpha: float | None = None,) -> np.ndarray: """Create an RGB composite using Lupton et al. (2004) Eq. 2.
The key insight: apply the stretch to the total intensity I, then scale each band by f(I)/I. This preserves color regardless of brightness.
Args: r_data, g_data, b_data: 2D flux arrays (ny, nx) for each band. softening: Q parameter controlling linear-to-log transition. Typical: 8-9. alpha: Linear stretch factor. If None, auto-estimated from background noise.
Returns: uint8 array of shape (ny, nx, 3) suitable for Plotly go.Image. """ intensity = (r_data + g_data + b_data) / 3.0 m, sigma = _estimate_background(intensity) if alpha is None: alpha = 0.02 / (sigma + 1e-10)
i_shifted = intensity - m f_i = np.arcsinh(alpha * softening * i_shifted) / softening
# ratio = f(I) / (I - m) — the color-preserving scale factor with np.errstate(divide="ignore", invalid="ignore"): ratio = np.where(i_shifted > 0, f_i / i_shifted, 0.0)
r_out = (r_data - m) * ratio g_out = (g_data - m) * ratio b_out = (b_data - m) * ratio
r_out = np.maximum(r_out, 0.0) g_out = np.maximum(g_out, 0.0) b_out = np.maximum(b_out, 0.0)
# Per-pixel normalization: if max(R,G,B) > 1, scale down to preserve color max_rgb = np.maximum(np.maximum(r_out, g_out), b_out) with np.errstate(divide="ignore", invalid="ignore"): scale = np.where(max_rgb > 1.0, 1.0 / max_rgb, 1.0) r_out *= scale g_out *= scale b_out *= scale
# NaN handling: pixels invalid in any band become black nan_mask = ~(np.isfinite(r_data) & np.isfinite(g_data) & np.isfinite(b_data)) r_out[nan_mask] = 0.0 g_out[nan_mask] = 0.0 b_out[nan_mask] = 0.0
# Global normalization to [0, 1] using 99.5th percentile rgb = np.stack([r_out, g_out, b_out], axis=-1) positive = rgb[rgb > 0] vmax = float(np.percentile(positive, 99.5)) if positive.size > 0 else 1.0 if vmax > 0: rgb = rgb / vmax rgb = np.clip(rgb, 0.0, 1.0)
return (rgb * 255).astype(np.uint8)
def build_rgb_figure( datacube: DataCube, r_index: int, g_index: int, b_index: int, clumps: ClumpCatalog, selected_ids: list[int] | None = None, softening: float = 8.0, alpha: float | None = None,) -> dict[str, Any]: """Build a Plotly figure with RGB composite + clump overlays.""" r_data = datacube.get_slice_by_channel_index(r_index) g_data = datacube.get_slice_by_channel_index(g_index) b_data = datacube.get_slice_by_channel_index(b_index)
rgb = lupton_rgb_composite(r_data, g_data, b_data, softening, alpha) ny = rgb.shape[0] rgb = np.flipud(rgb)
image_trace: dict[str, Any] = { "type": "image", "z": rgb.tolist(), }
boundaries = create_clump_boundary_traces(clumps, selected_ids) for trace in boundaries: trace["y"] = [ny - 1 - y for y in trace["y"]] centroids = create_centroid_markers(clumps) centroids["y"] = [ny - 1 - y for y in centroids["y"]]
data: list[dict[str, Any]] = [image_trace, *boundaries, centroids]
r_name = datacube.filter_names[r_index] g_name = datacube.filter_names[g_index] b_name = datacube.filter_names[b_index]
layout: dict[str, Any] = { "title": { "text": f"RGB: {r_name} / {g_name} / {b_name}", "font": {"color": _GRAY}, }, "xaxis": { "title": "x (pixels)", "scaleanchor": "y", "constrain": "domain", "gridcolor": _SOFT_BLACK, "color": _DARK_GRAY, }, "yaxis": { "title": "y (pixels)", "gridcolor": _SOFT_BLACK, "color": _DARK_GRAY, "autorange": "reversed", }, "plot_bgcolor": _DARK_BLUE, "paper_bgcolor": _SOFT_DARK_BLUE, "font": {"color": _GRAY}, "margin": {"l": 50, "r": 20, "t": 40, "b": 50}, "dragmode": "pan", }
return {"data": data, "layout": layout}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Plotly figure builders for spectral energy distribution (SED) plots."""
def create_sed_figure(spectrum: dict, title: str = "Spectral Energy Distribution") -> dict: """Create a Plotly scatter plot of flux vs wavelength.
Args: spectrum: Dict with 'wavelengths', 'mean_flux' (or 'fluxes'), and optionally 'std_flux'. title: Plot title. """ wavelengths = spectrum["wavelengths"] fluxes = spectrum.get("mean_flux") or spectrum.get("fluxes", []) filter_names = spectrum.get("filter_names", [])
traces = [ { "type": "scatter", "x": wavelengths, "y": fluxes, "mode": "lines+markers", "marker": {"size": 7, "color": "#00ccff"}, "line": {"color": "#00ccff", "width": 2}, "text": filter_names, "hovertemplate": ( "%{text}<br>\u03bb: %{x:.3f} \u00b5m<br>Flux: %{y:.4e}<extra></extra>" ), "name": "SED", } ]
if "std_flux" in spectrum: std = spectrum["std_flux"] upper = [ (f + s) if f is not None and s is not None else None for f, s in zip(fluxes, std, strict=True) ] lower = [ (f - s) if f is not None and s is not None else None for f, s in zip(fluxes, std, strict=True) ] traces.append( { "type": "scatter", "x": wavelengths + wavelengths[::-1], "y": upper + lower[::-1], "fill": "toself", "fillcolor": "rgba(0, 204, 255, 0.15)", "line": {"color": "rgba(0,0,0,0)"}, "hoverinfo": "skip", "showlegend": False, "name": "\u00b11\u03c3", } )
layout = { "title": {"text": title, "font": {"color": "#cccccc"}}, "xaxis": { "title": "Wavelength (\u00b5m)", "gridcolor": "#333", "color": "#999", }, "yaxis": { "title": "Flux", "gridcolor": "#333", "color": "#999", }, "plot_bgcolor": "#1a1a2e", "paper_bgcolor": "#16213e", "font": {"color": "#cccccc"}, "margin": {"l": 60, "r": 20, "t": 40, "b": 50}, "showlegend": False, }
return {"data": traces, "layout": layout}
def create_multi_sed_figure(spectra: list[dict], labels: list[str]) -> dict: """Overlay multiple SEDs for comparison.""" colors = [ "#00ccff", "#ff4444", "#44ff44", "#ffaa00", "#ff44ff", "#44ffff", "#ffff44", "#aa44ff", ] traces = [] for i, (spec, label) in enumerate(zip(spectra, labels, strict=True)): color = colors[i % len(colors)] fluxes = spec.get("mean_flux") or spec.get("fluxes", []) traces.append( { "type": "scatter", "x": spec["wavelengths"], "y": fluxes, "mode": "lines+markers", "marker": {"size": 6, "color": color}, "line": {"color": color, "width": 2}, "name": label, "text": spec.get("filter_names", []), "hovertemplate": ( f"{label}<br>%{{text}}<br>" "\u03bb: %{x:.3f} \u00b5m<br>Flux: %{y:.4e}<extra></extra>" ), } )
layout = { "title": {"text": "SED Comparison", "font": {"color": "#cccccc"}}, "xaxis": { "title": "Wavelength (\u00b5m)", "gridcolor": "#333", "color": "#999", }, "yaxis": { "title": "Flux", "gridcolor": "#333", "color": "#999", }, "plot_bgcolor": "#1a1a2e", "paper_bgcolor": "#16213e", "font": {"color": "#cccccc"}, "margin": {"l": 60, "r": 20, "t": 40, "b": 50}, "legend": {"font": {"color": "#cccccc"}}, }
return {"data": traces, "layout": layout}123345567891011121314151617181920212223242526272829303132333435363712 unmodified lines505152535455568 unmodified lines656667536869708 unmodified lines7980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291308113113213313433 unmodified lines168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238"""REST API endpoints and page routes."""
from typing import Annotated, Anyfrom typing import Annotated, Any, Literal
import numpy as npfrom fastapi import APIRouter, Query, Requestfrom fastapi import APIRouter, HTTPException, Query, Requestfrom starlette.responses import HTMLResponse, Response
from jellyscope.config import NIRCAM_WAVELENGTHSfrom jellyscope.data.data_store import DataStorefrom jellyscope.model.schemas import ( ClumpDetailResponse, ClumpListItem, ClumpsListResponse, CompareRequest, CompareResponse, DatacubesResponse, FilterInfo, FiltersResponse, PixelClumpResponse, RegionRequest, RGBViewerResponse, SpectrumResponse, ViewerResponse,)from jellyscope.spec_analysis.spectral import ( extract_clump_spectrum, extract_pixel_spectrum, extract_region_spectrum,)from jellyscope.visualization.image_viewer import build_viewer_figurefrom jellyscope.visualization.properties_panel import format_clump_propertiesfrom jellyscope.visualization.rgb_composite import build_rgb_figurefrom jellyscope.visualization.spectrum_plot import create_multi_sed_figure, create_sed_figure
router = APIRouter()
12 unmodified lines { "datacubes": store.list_datacubes(), "filters": store.get_datacube("nircam").filter_names, "wavelengths": NIRCAM_WAVELENGTHS, }, )
8 unmodified lines@router.get("/api/filters/{datacube_name}", response_model=FiltersResponse)def list_filters(datacube_name: str) -> FiltersResponse: dc = _store().get_datacube(datacube_name) from jellyscope.config import NIRCAM_WAVELENGTHS
filters: list[FilterInfo] = [] for i, name in enumerate(dc.filter_names):8 unmodified lines
# Image viewer.@router.get("/api/viewer/{datacube_name}/rgb", response_model=RGBViewerResponse)def get_rgb_viewer_figure( datacube_name: str, r: Annotated[int, Query(description="Red channel filter index")], g: Annotated[int, Query(description="Green channel filter index")], b: Annotated[int, Query(description="Blue channel filter index")], selected: Annotated[str, Query()] = "", softening: Annotated[float, Query()] = 8.0,) -> RGBViewerResponse: store = _store() dc = store.get_datacube(datacube_name) n_ch = dc.n_channels for label, idx in [("r", r), ("g", g), ("b", b)]: if not 0 <= idx < n_ch: raise HTTPException( status_code=400, detail=f"Channel index {label}={idx} out of range [0, {n_ch})", ) selected_ids: list[int] = ( [int(i) for i in selected.split(",") if i.strip()] if selected else [] ) figure: dict[str, Any] = build_rgb_figure(dc, r, g, b, store.clumps, selected_ids, softening) return RGBViewerResponse( figure=figure, r_filter=dc.filter_names[r], g_filter=dc.filter_names[g], b_filter=dc.filter_names[b], )
@router.get("/api/viewer/{datacube_name}/{channel_index}", response_model=ViewerResponse)def get_viewer_figure( datacube_name: str, channel_index: int, selected: Annotated[str, Query()] = "", colorscale: Annotated[str, Query()] = "Viridis", stretch: Annotated[Literal["log", "lupton_asinh", "power"], Query()] = "log",) -> ViewerResponse: store = _store() dc = store.get_datacube(datacube_name) if not 0 <= channel_index < dc.n_channels: raise HTTPException( status_code=400, detail=f"Channel index {channel_index} out of range [0, {dc.n_channels})", ) selected_ids: list[int] = ( [int(i) for i in selected.split(",") if i.strip()] if selected else [] ) figure: dict[str, Any] = build_viewer_figure( dc, channel_index, store.clumps, selected_ids, colorscale dc, channel_index, store.clumps, selected_ids, colorscale, stretch ) return ViewerResponse(figure=figure, filter_name=dc.filter_names[channel_index])
33 unmodified lines )
@router.get("/api/clumps/{clump_id}/spectrum/{datacube_name}", response_model=SpectrumResponse)def get_clump_spectrum(clump_id: int, datacube_name: str) -> SpectrumResponse: store = _store() dc = store.get_datacube(datacube_name) spectrum = extract_clump_spectrum(dc, store.clumps, clump_id) figure = create_sed_figure(spectrum, f"Clump {clump_id} — SED") return SpectrumResponse(spectrum=spectrum, figure=figure)
# Pixel Interaction.@router.get("/api/pixel/{x}/{y}/clump", response_model=PixelClumpResponse)def get_pixel_clump(x: int, y: int) -> PixelClumpResponse: store = _store() cid = store.clumps.get_clump_id_at_pixel(x, y) return PixelClumpResponse(clump_id=cid)
@router.get("/api/pixel/{x}/{y}/spectrum/{datacube_name}", response_model=SpectrumResponse)def get_pixel_spectrum(x: int, y: int, datacube_name: str) -> SpectrumResponse: store = _store() dc = store.get_datacube(datacube_name) spectrum = extract_pixel_spectrum(dc, x, y) figure = create_sed_figure(spectrum, f"Pixel ({x}, {y}) — SED") return SpectrumResponse(spectrum=spectrum, figure=figure)
# Region selection.@router.post("/api/region/spectrum/{datacube_name}", response_model=SpectrumResponse)def get_region_spectrum(datacube_name: str, body: RegionRequest) -> SpectrumResponse: store = _store() dc = store.get_datacube(datacube_name)
mask = np.zeros(dc.spatial_shape, dtype=bool)
if body.pixels is not None: for px in body.pixels: x, y = int(px[0]), int(px[1]) if 0 <= y < dc.ny and 0 <= x < dc.nx: mask[y, x] = True elif body.rect is not None: r = body.rect x0, y0 = int(r.x0), int(r.y0) x1, y1 = int(r.x1), int(r.y1) x0, x1 = max(0, min(x0, x1)), min(dc.nx, max(x0, x1)) y0, y1 = max(0, min(y0, y1)), min(dc.ny, max(y0, y1)) mask[y0:y1, x0:x1] = True
spectrum = extract_region_spectrum(dc, mask) figure = create_sed_figure(spectrum, f"Selected Region ({spectrum['n_pixels']} px)") return SpectrumResponse(spectrum=spectrum, figure=figure)
# Multi-clump comparison.@router.post("/api/compare/spectrum/{datacube_name}", response_model=CompareResponse)def compare_spectra(datacube_name: str, body: CompareRequest) -> CompareResponse: store = _store() dc = store.get_datacube(datacube_name)
spectra = [] labels = [] for cid in body.clump_ids: spec = extract_clump_spectrum(dc, store.clumps, cid) spectra.append(spec) c = store.clumps.get_clump_by_id(cid) labels.append(f"Clump {cid} ({c.component})")
figure = create_multi_sed_figure(spectra, labels) return CompareResponse(figure=figure, spectra=spectra)1 unmodified line234567891011121314151617181920212223242526272829306 unmodified lines37383940414243444546474849505152535455565758596061626364652 unmodified lines68697038717273742 unmodified lines777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412514 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681697117017117237 unmodified lines2102112121152132142152162172182192202212222231 unmodified line * Jellyscope — Frontend controller * Manages state, API calls, Plotly rendering, and user interactions. */
function debounce(fn, ms) { let timer; return function (...args) { clearTimeout(timer); timer = setTimeout(() => fn.apply(this, args), ms); };}
const state = { datacube: "nircam", channel: 7, // F200W default selectedClumps: new Set(), colorscale: "Viridis", stretch: "log", dragmode: "pan", clumps: [], showCentroids: false, viewMode: "single", // "single" or "rgb" rgbR: FILTERS.length - 1, // F480M (longest wavelength -> Red) rgbG: Math.floor(FILTERS.length / 2), // middle -> Green rgbB: 0, // F070W (shortest wavelength -> Blue) rgbQ: 8.0,};
const plotlyConfig = {6 unmodified lines// Initialization.
async function init() { populateRGBSelects(); await loadClumpList(); updateFilterLabel(); await renderViewer(); setupEventListeners();}
function populateRGBSelects() { const selects = ["rgb-r", "rgb-g", "rgb-b"]; const defaults = [state.rgbR, state.rgbG, state.rgbB]; selects.forEach((id, idx) => { const sel = document.getElementById(id); FILTERS.forEach((name, i) => { const opt = document.createElement("option"); opt.value = i; const wl = WAVELENGTHS[name]; opt.textContent = wl ? `${name} (${wl} µm)` : name; if (i === defaults[idx]) opt.selected = true; sel.appendChild(opt); }); });}
function setupEventListeners() { document.getElementById("datacube-select").addEventListener("change", (e) => { state.datacube = e.target.value;2 unmodified lines
document.getElementById("filter-slider").addEventListener("input", (e) => { state.channel = parseInt(e.target.value); document.getElementById("filter-label").textContent = FILTERS[state.channel]; updateFilterLabel(); renderViewer(); });
2 unmodified lines renderViewer(); });
document.getElementById("stretch-select").addEventListener("change", (e) => { state.stretch = e.target.value; renderViewer(); });
// View mode toggle (Single / RGB) document.querySelectorAll(".view-btn").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".view-btn").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); state.viewMode = btn.dataset.view; updateViewModeUI(); updateFilterLabel(); renderViewer(); }); });
// RGB filter selectors document.getElementById("rgb-r").addEventListener("change", (e) => { state.rgbR = parseInt(e.target.value); updateFilterLabel(); renderViewer(); }); document.getElementById("rgb-g").addEventListener("change", (e) => { state.rgbG = parseInt(e.target.value); updateFilterLabel(); renderViewer(); }); document.getElementById("rgb-b").addEventListener("change", (e) => { state.rgbB = parseInt(e.target.value); updateFilterLabel(); renderViewer(); });
// Q slider with debounce const debouncedRender = debounce(renderViewer, 300); document.getElementById("rgb-q").addEventListener("input", (e) => { state.rgbQ = parseFloat(e.target.value); document.getElementById("rgb-q-label").textContent = state.rgbQ.toFixed(1); debouncedRender(); });
// Drag mode buttons document.querySelectorAll(".mode-btn").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".mode-btn").forEach((b) => b.classList.remove("active"));14 unmodified lines });}
function updateFilterLabel() { const label = document.getElementById("filter-label"); if (state.viewMode === "rgb") { label.textContent = `R:${FILTERS[state.rgbR]} G:${FILTERS[state.rgbG]} B:${FILTERS[state.rgbB]}`; } else { const name = FILTERS[state.channel]; const wl = WAVELENGTHS[name]; label.textContent = wl ? `${name} (${wl} µm)` : name; }}
function updateViewModeUI() { const singleControls = document.getElementById("single-controls"); const rgbControls = document.getElementById("rgb-controls"); if (state.viewMode === "rgb") { singleControls.style.display = "none"; rgbControls.style.display = "flex"; } else { singleControls.style.display = "flex"; rgbControls.style.display = "none"; }}
// Clump List.async function loadClumpList() { const filter = document.getElementById("clump-filter"); let url = "/api/clumps"; let html = ""; if (filter.value) url += `?component=${filter.value}`;
const resp = await fetch(url);37 unmodified lines// Galaxy Viewer.async function renderViewer() { const selectedStr = Array.from(state.selectedClumps).join(","); const url = `/api/viewer/${state.datacube}/${state.channel}?selected=${selectedStr}&colorscale=${state.colorscale}`; let url;
if (state.viewMode === "rgb") { url = `/api/viewer/${state.datacube}/rgb?r=${state.rgbR}&g=${state.rgbG}&b=${state.rgbB}&selected=${selectedStr}&softening=${state.rgbQ}`; } else { url = `/api/viewer/${state.datacube}/${state.channel}?selected=${selectedStr}&colorscale=${state.colorscale}&stretch=${state.stretch}`; }
const resp = await fetch(url); const data = await resp.json(); const fig = data.figure;125 unmodified lines126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187125 unmodified lines font-weight: 600;}
.view-btn { background: var(--bg-panel); color: var(--text-secondary); border: 1px solid var(--border); border-radius: 4px; padding: 3px 10px; cursor: pointer; font-size: 12px; transition: all 0.15s;}
.view-btn:hover { border-color: var(--accent); color: var(--text-primary);}
.view-btn.active { background: var(--accent); color: #000; border-color: var(--accent); font-weight: 600;}
#single-controls,#rgb-controls { display: flex; align-items: center; gap: 8px;}
#rgb-controls select { max-width: 90px;}
#rgb-controls input[type="number"] { background: var(--bg-panel); color: var(--text-primary); border: 1px solid var(--border); border-radius: 4px; padding: 3px 6px; font-size: 12px; width: 55px;}
#rgb-q { width: 80px; accent-color: var(--accent);}
#rgb-q-label { color: var(--accent); font-weight: 600; min-width: 30px; font-size: 12px;}
.toggle-btn { background: var(--bg-panel); color: var(--text-secondary);23 unmodified lines24252627282930313233343536373827282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737432 unmodified lines10710810911011111211323 unmodified lines {% endfor %} </select>
<label for="filter-slider">Filter:</label> <input type="range" id="filter-slider" min="0" max="{{ filters|length - 1 }}" value="7" step="1"> <span id="filter-label">{{ filters[7] }}</span>
<label for="colorscale-select">Colors:</label> <select id="colorscale-select"> <option value="Viridis" selected>Viridis</option> <option value="Inferno">Inferno</option> <option value="Plasma">Plasma</option> <option value="Cividis">Cividis</option> <option value="Hot">Hot</option> <option value="Greys">Greys</option> <label for="stretch-select">Stretch:</label> <select id="stretch-select"> <option value="log" selected>Log</option> <option value="lupton_asinh">Asinh (Lupton)</option> <option value="power">Power</option> </select>
<span class="separator">|</span>
<button id="btn-view-single" class="view-btn active" data-view="single">Single</button> <button id="btn-view-rgb" class="view-btn" data-view="rgb">RGB</button>
<span class="separator">|</span>
<div id="single-controls"> <label for="filter-slider">Filter:</label> <input type="range" id="filter-slider" min="0" max="{{ filters|length - 1 }}" value="7" step="1">
<label for="colorscale-select">Colors:</label> <select id="colorscale-select"> <option value="Viridis" selected>Viridis</option> <option value="Inferno">Inferno</option> <option value="Plasma">Plasma</option> <option value="Cividis">Cividis</option> <option value="Hot">Hot</option> <option value="Greys">Greys</option> </select> </div>
<div id="rgb-controls" style="display:none;"> <label for="rgb-r">R:</label> <select id="rgb-r"></select> <label for="rgb-g">G:</label> <select id="rgb-g"></select> <label for="rgb-b">B:</label> <select id="rgb-b"></select> <label for="rgb-q">Q:</label> <input type="range" id="rgb-q" value="8" min="1" max="30" step="0.5"> <span id="rgb-q-label">8.0</span> </div>
<span id="filter-label">{{ filters[7] }}</span>
<span class="separator">|</span>
<button id="btn-click" class="mode-btn active" data-mode="pan" title="Pan / Click to select clump">Pan</button> <button id="btn-select" class="mode-btn" data-mode="select" title="Rectangle selection">Rect</button> <button id="btn-lasso" class="mode-btn" data-mode="lasso" title="Lasso selection">Lasso</button>32 unmodified lines
<script> const FILTERS = {{ filters | tojson | safe }}; const WAVELENGTHS = {{ wavelengths | tojson | safe }}; </script> <script src="{{ url_for('static', path='app.js') }}"></script></body>1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Tests for spectral extraction."""
from jellyscope.spec_analysis.spectral import ( extract_clump_spectrum, extract_pixel_spectrum, extract_region_spectrum,)
def test_pixel_spectrum(store): dc = store.get_datacube("nircam") result = extract_pixel_spectrum(dc, 80, 100) assert len(result["fluxes"]) == 20 assert len(result["wavelengths"]) == 20 assert result["n_pixels"] == 1
def test_clump_spectrum(store): dc = store.get_datacube("nircam") result = extract_clump_spectrum(dc, store.clumps, 0) assert len(result["mean_flux"]) == 20 assert len(result["std_flux"]) == 20 assert result["n_pixels"] == 121 assert result["clump_id"] == 0
def test_region_spectrum_with_mask(store): import numpy as np
dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) mask[50:60, 50:60] = True result = extract_region_spectrum(dc, mask) assert result["n_pixels"] == 100 assert len(result["mean_flux"]) == 20
def test_empty_region_spectrum(store): import numpy as np
dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) result = extract_region_spectrum(dc, mask) assert result["n_pixels"] == 01234567891011121314151617181920212223242526272829303132333435363738394041424344"""Tests for statistics module."""
import numpy as np
from jellyscope.spec_analysis.stats import compute_clump_summary, compute_region_stats
def test_region_stats_normal(store): dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) mask[50:60, 50:60] = True stats = compute_region_stats(dc, mask, 0) assert stats["filter"] == "F070W" assert stats["n_pixels"] > 0 assert isinstance(stats["mean"], float) assert isinstance(stats["median"], float) assert isinstance(stats["std"], float) assert isinstance(stats["min"], float) assert isinstance(stats["max"], float) assert isinstance(stats["sum"], float)
def test_region_stats_empty(store): dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) stats = compute_region_stats(dc, mask, 0) assert stats["n_pixels"] == 0 assert stats["mean"] is None assert stats["median"] is None assert stats["std"] is None assert stats["min"] is None assert stats["max"] is None assert stats["sum"] is None
def test_clump_summary(store): dc = store.get_datacube("nircam") summary = compute_clump_summary(dc, store.clumps, 0) assert summary["clump_id"] == 0 assert summary["component"] == "outside" assert summary["area_pix"] == 121 assert summary["inside"] is False assert len(summary["channel_stats"]) == 20 assert all(s["n_pixels"] > 0 for s in summary["channel_stats"])123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109"""Tests for the Lupton asinh stretch and background estimation."""
import numpy as np
from jellyscope.visualization.image_viewer import ( _estimate_background, _lupton_asinh_stretch, _normalize_stretch,)
class TestEstimateBackground: def test_gaussian_noise(self): rng = np.random.default_rng(42) data = rng.normal(loc=100.0, scale=5.0, size=(100, 100)) median, std = _estimate_background(data) assert abs(median - 100.0) < 1.0 assert abs(std - 5.0) < 1.0
def test_all_nan_returns_defaults(self): data = np.full((10, 10), np.nan) median, std = _estimate_background(data) assert median == 0.0 assert std == 1.0
def test_empty_array(self): data = np.array([]) median, std = _estimate_background(data) assert median == 0.0 assert std == 1.0
class TestLuptonAsinhStretch: def test_basic_output_range(self): rng = np.random.default_rng(42) data = rng.normal(loc=50.0, scale=10.0, size=(50, 50)) result = _lupton_asinh_stretch(data) assert result.shape == (50, 50) finite = result[np.isfinite(result)] assert np.all(finite >= 0.0) assert np.all(finite <= 1.0)
def test_nan_preserved(self): data = np.array([[1.0, 2.0, np.nan], [4.0, np.nan, 6.0]]) result = _lupton_asinh_stretch(data) assert np.isnan(result[0, 2]) assert np.isnan(result[1, 1]) assert not np.isnan(result[0, 0])
def test_all_nan_returns_zeros(self): data = np.full((10, 10), np.nan) result = _lupton_asinh_stretch(data) assert np.all(result == 0.0)
def test_uniform_array(self): data = np.full((20, 20), 42.0) result = _lupton_asinh_stretch(data) # Uniform => background == data, so (data - m) ~ 0 => stretched ~ 0 finite = result[np.isfinite(result)] assert np.all(finite >= 0.0) assert np.all(finite <= 1.0)
def test_custom_softening_parameter(self): rng = np.random.default_rng(7) data = rng.normal(loc=100.0, scale=10.0, size=(30, 30)) result_q4 = _lupton_asinh_stretch(data, softening=4.0) result_q16 = _lupton_asinh_stretch(data, softening=16.0) # Different Q should produce different results assert not np.allclose(result_q4, result_q16)
def test_custom_alpha_parameter(self): rng = np.random.default_rng(7) data = rng.normal(loc=100.0, scale=10.0, size=(30, 30)) result_a1 = _lupton_asinh_stretch(data, alpha=0.001) result_a2 = _lupton_asinh_stretch(data, alpha=0.01) assert not np.allclose(result_a1, result_a2)
class TestNormalizeStretchDispatch: def test_dispatch_log(self): data = np.array([[1.0, 10.0], [100.0, 1000.0]]) result = _normalize_stretch(data, stretch="log") assert result.shape == (2, 2)
def test_dispatch_lupton_asinh(self): rng = np.random.default_rng(0) data = rng.normal(50, 10, (20, 20)) result = _normalize_stretch(data, stretch="lupton_asinh") finite = result[np.isfinite(result)] assert np.all(finite >= 0.0) assert np.all(finite <= 1.0)
def test_dispatch_power(self): rng = np.random.default_rng(0) data = rng.normal(50, 10, (20, 20)) result = _normalize_stretch(data, stretch="power") assert result.shape == (20, 20)
def test_dispatch_unknown_falls_back_to_log(self): data = np.array([[1.0, 10.0], [100.0, 1000.0]]) result_unknown = _normalize_stretch(data, stretch="unknown_stretch") result_log = _normalize_stretch(data, stretch="log") assert np.allclose(result_unknown, result_log, equal_nan=True)
def test_default_is_log(self): data = np.array([[1.0, 10.0], [100.0, 1000.0]]) result_default = _normalize_stretch(data) result_log = _normalize_stretch(data, stretch="log") assert np.allclose(result_default, result_log, equal_nan=True)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384"""Tests for the Lupton RGB composite algorithm."""
import numpy as np
from jellyscope.visualization.rgb_composite import lupton_rgb_composite
class TestLuptonRGBComposite: def test_output_shape(self): rng = np.random.default_rng(42) r = rng.normal(100, 10, (30, 40)) g = rng.normal(80, 10, (30, 40)) b = rng.normal(60, 10, (30, 40)) result = lupton_rgb_composite(r, g, b) assert result.shape == (30, 40, 3) assert result.dtype == np.uint8
def test_output_range(self): rng = np.random.default_rng(42) r = rng.normal(100, 10, (20, 20)) g = rng.normal(80, 10, (20, 20)) b = rng.normal(60, 10, (20, 20)) result = lupton_rgb_composite(r, g, b) assert np.all(result >= 0) assert np.all(result <= 255)
def test_color_preservation(self): """A pixel where r=2*g=4*b should have R > G > B in output.""" r = np.full((10, 10), 200.0) g = np.full((10, 10), 100.0) b = np.full((10, 10), 50.0) result = lupton_rgb_composite(r, g, b) # Center pixel should show R > G > B center = result[5, 5] assert center[0] >= center[1] # R >= G assert center[1] >= center[2] # G >= B
def test_nan_becomes_black(self): r = np.full((10, 10), 100.0) g = np.full((10, 10), 80.0) b = np.full((10, 10), 60.0) r[3, 4] = np.nan result = lupton_rgb_composite(r, g, b) assert result[3, 4, 0] == 0 assert result[3, 4, 1] == 0 assert result[3, 4, 2] == 0
def test_all_zero_becomes_black(self): r = np.zeros((10, 10)) g = np.zeros((10, 10)) b = np.zeros((10, 10)) result = lupton_rgb_composite(r, g, b) assert np.all(result == 0)
def test_all_nan_becomes_black(self): r = np.full((10, 10), np.nan) g = np.full((10, 10), np.nan) b = np.full((10, 10), np.nan) result = lupton_rgb_composite(r, g, b) assert np.all(result == 0)
def test_custom_softening(self): rng = np.random.default_rng(7) r = rng.normal(100, 10, (20, 20)) g = rng.normal(80, 10, (20, 20)) b = rng.normal(60, 10, (20, 20)) result_q4 = lupton_rgb_composite(r, g, b, softening=4.0) result_q16 = lupton_rgb_composite(r, g, b, softening=16.0) assert not np.array_equal(result_q4, result_q16)
def test_bright_pixel_not_clipped_to_white(self): """Bright pixel should retain color, not burn to (255, 255, 255).""" r = np.full((10, 10), 50.0) g = np.full((10, 10), 50.0) b = np.full((10, 10), 50.0) # One very bright red pixel r[5, 5] = 5000.0 g[5, 5] = 100.0 b[5, 5] = 50.0 result = lupton_rgb_composite(r, g, b) pixel = result[5, 5] # Should be dominantly red, NOT white assert pixel[0] > pixel[1] assert pixel[0] > pixel[2]74 unmodified lines7576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615774 unmodified lines
result = _normalize_stretch(nan_slice) assert result.shape == (221, 172)
def test_viewer_stretch_lupton_asinh(client): resp = client.get("/api/viewer/nircam/7?stretch=lupton_asinh") assert resp.status_code == HTTPStatus.OK data = resp.json() assert "figure" in data assert len(data["figure"]["data"]) > 0
def test_viewer_stretch_default_is_log(client): resp_default = client.get("/api/viewer/nircam/7") resp_log = client.get("/api/viewer/nircam/7?stretch=log") assert resp_default.status_code == HTTPStatus.OK assert resp_log.status_code == HTTPStatus.OK assert resp_default.json() == resp_log.json()
def test_rgb_viewer_figure(client): resp = client.get("/api/viewer/nircam/rgb?r=17&g=7&b=0") assert resp.status_code == HTTPStatus.OK data = resp.json() assert "figure" in data assert data["r_filter"] == "F444W" assert data["g_filter"] == "F200W" assert data["b_filter"] == "F070W" assert data["figure"]["data"][0]["type"] == "image"
def test_rgb_viewer_with_softening(client): resp = client.get("/api/viewer/nircam/rgb?r=17&g=7&b=0&softening=12.0") assert resp.status_code == HTTPStatus.OK
def test_viewer_invalid_stretch(client): resp = client.get("/api/viewer/nircam/7?stretch=invalid") assert resp.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
def test_rgb_viewer_invalid_channel(client): resp = client.get("/api/viewer/nircam/rgb?r=999&g=7&b=0") assert resp.status_code == HTTPStatus.BAD_REQUEST
def test_viewer_invalid_channel_index(client): resp = client.get("/api/viewer/nircam/999") assert resp.status_code == HTTPStatus.BAD_REQUEST
def test_clump_spectrum(client): resp = client.get("/api/clumps/0/spectrum/nircam") data = resp.json() assert "spectrum" in data assert "figure" in data assert len(data["spectrum"]["mean_flux"]) == 20
def test_pixel_spectrum(client): resp = client.get("/api/pixel/80/100/spectrum/nircam") data = resp.json() assert len(data["spectrum"]["fluxes"]) == 20
def test_region_spectrum(client): resp = client.post( "/api/region/spectrum/nircam", json={"rect": {"x0": 70, "y0": 15, "x1": 80, "y1": 25}}, ) data = resp.json() assert data["spectrum"]["n_pixels"] > 0
def test_compare_spectra(client): resp = client.post( "/api/compare/spectrum/nircam", json={"clump_ids": [0, 1, 3]}, ) data = resp.json() assert len(data["spectra"]) == 3 assert len(data["figure"]["data"]) == 3docs/api-reference.md+158-3
docs/frontend.md+109-33
docs/visualization.md+92-3
src/jellyscope/model/schemas.py+51
src/jellyscope/spec_analysis/__init__.pyAdded+1
src/jellyscope/spec_analysis/spectral.pyAdded+62
src/jellyscope/spec_analysis/stats.pyAdded+52
src/jellyscope/visualization/image_viewer.py+49-28
src/jellyscope/visualization/rgb_composite.pyAdded+152
src/jellyscope/visualization/spectrum_plot.pyAdded+129
src/jellyscope/web/routes.py+116-4
src/jellyscope/web/static/app.js+108-3
src/jellyscope/web/static/style.css+56
src/jellyscope/web/templates/index.html+42-12
tests/spec_analysis/test_spectral.pyAdded+44
tests/spec_analysis/test_statistics.pyAdded+44
tests/visualization/__init__.pyAdded
tests/visualization/test_image_viewer.pyAdded+109
tests/visualization/test_rgb_composite.pyAdded+84
tests/web/test_routes.py+80