Spaces:
Sleeping
Sleeping
Commit ·
b687153
1
Parent(s): b8c1bd0
add rgb composite
Browse filesFiles changed (10)
- docs/api-reference.md+14-5
- docs/data-layer.md+10
- docs/frontend.md+38-10
- docs/visualization.md+45-4
- src/jellyscope/config.py+3
- src/jellyscope/visualization/rgb_composite.py+92-12
- src/jellyscope/web/routes.py+4-1
- src/jellyscope/web/static/app.js+85-4
- src/jellyscope/web/templates/index.html+10-3
- tests/visualization/test_rgb_composite.py+72-2
125 unmodified lines1261271281291301311321331341354 unmodified lines140141142143144145146147148149150128 unmodified lines279280281282283284285286125 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**:4 unmodified lines| `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**:128 unmodified linesconst 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);125 unmodified lines1261271281291301311321331341351361371381391401411424 unmodified lines147148149150151152153154155156157158159128 unmodified lines288289290291292293294295125 unmodified lines### `GET /api/viewer/{datacube_name}/rgb`Returns an RGB composite Plotly figure with clump overlays. Two stretch methods are available, selectable via the `method` query parameter:- **`percentile_asinh`** (default) — per-band median subtract, percentile clip, asinh stretch, and pedestal cut. Recipe contributed by Andressa; produces clean, deep-field-style images.- **`lupton`** — Lupton et al. (2004) Eq. 2 color-preserving mapping. Output color depends only on flux ratios, not brightness. The `softening` (Q) parameter applies only to this method.```bash# Default method (percentile_asinh) with R=F200W, G=F115W, B=F090Wcurl "http://localhost:5000/api/viewer/nircam/rgb?r=7&g=2&b=1&method=percentile_asinh"# Lupton method with custom softeningcurl "http://localhost:5000/api/viewer/nircam/rgb?r=19&g=10&b=0&method=lupton&softening=8.0"```**Query parameters**:4 unmodified lines| `g` | `int` | required | Green channel filter index || `b` | `int` | required | Blue channel filter index || `selected` | `string` | `""` | Comma-separated clump IDs to highlight || `method` | `"percentile_asinh"` \| `"lupton"` | `"percentile_asinh"` | Stretch method || `softening` | `float` | `8.0` | Lupton Q parameter (only used when `method="lupton"`) |**Error responses**:- `400` — channel index out of range- `422` — invalid `method` value**Response**:128 unmodified linesconst data = await resp.json();Plotly.react("galaxy-viewer", data.figure.data, data.figure.layout);// Get RGB composite (default percentile_asinh method)const resp = await fetch(`/api/viewer/nircam/rgb?r=7&g=2&b=1&method=percentile_asinh`);const data = await resp.json();Plotly.react("galaxy-viewer", data.figure.data, data.figure.layout);
30 unmodified lines31323334353630 unmodified linesThe naming convention (`F` + wavelength in nm + `W`/`M`) follows JWST standard: `W` = wide-band, `M` = medium-band.### `JellyscopeConfig`Pydantic `BaseModel` holding all application settings. Every field has a sensible default, so `JellyscopeConfig()` works out of the box with the toy data.30 unmodified lines3132333435363738394041424344454630 unmodified linesThe naming convention (`F` + wavelength in nm + `W`/`M`) follows JWST standard: `W` = wide-band, `M` = medium-band.### `DEFAULT_RGB`Module-level dictionary defining the default filter assignments for the RGB composite view.```pythonDEFAULT_RGB: dict[str, str] = {"r": "F200W", "g": "F115W", "b": "F090W"}```These are the filters the frontend uses to seed the R/G/B dropdowns at startup (via `DEFAULT_RGB_FILTERS` in `app.js`, resolved to channel indices by `defaultRgbIndex()`). They satisfy the wavelength-ordering constraint λ_R > λ_G > λ_B that the UI enforces on user selections.### `JellyscopeConfig`Pydantic `BaseModel` holding all application settings. Every field has a sensible default, so `JellyscopeConfig()` works out of the box with the toy data.
53 unmodified lines545556575859606134 unmodified lines969798991001014 unmodified lines1061071081091101111121131141151161171181191201211221231241251261 unmodified line12812913013113213313414 unmodified lines1491501511521531541551561571581591601617 unmodified lines1691701711721731741753 unmodified lines17918018118218318418553 unmodified lines| `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 |34 unmodified linesAll UI state is tracked in a single global object:```javascriptconst state = {datacube: "nircam", // Currently selected datacubechannel: 7, // Current filter channel (default: F200W)4 unmodified linesclumps: [], // Loaded clump list from APIshowCentroids: false, // Whether centroid markers are visibleviewMode: "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};```### Initialization Flow```plaintextDOMContentLoaded└── init()├── 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()1 unmodified line├── 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()14 unmodified linesUtility 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"`7 unmodified lines```plaintext1. 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 unmodified lines6. Attach plotly_click event handler```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)`53 unmodified lines5455565758596061626334 unmodified lines98991001011021031041054 unmodified lines1101111121131141151161171181191201211221231241251261271281291301311321331341 unmodified line13613713813914014114214314 unmodified lines1581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881897 unmodified lines1971981992002012022033 unmodified lines20720820921021121221353 unmodified lines| `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. Wavelengths constrained: λ_R > λ_G > λ_B || `rgb-method` | `<select>` | RGB stretch method: `"Percentile Asinh"` (default) or `"Lupton"` || `rgb-q-wrap` | `<span>` | Wrapper around the Q slider — hidden when method ≠ Lupton || `rgb-q` | `<input type="range">` | Softening (Q) parameter for Lupton stretch — only visible when method = Lupton || `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 |34 unmodified linesAll UI state is tracked in a single global object:```javascriptconst DEFAULT_RGB_FILTERS = {r: "F200W", g: "F115W", b: "F090W"};const state = {datacube: "nircam", // Currently selected datacubechannel: 7, // Current filter channel (default: F200W)4 unmodified linesclumps: [], // Loaded clump list from APIshowCentroids: false, // Whether centroid markers are visibleviewMode: "single", // "single" (heatmap) or "rgb" (composite)rgbR: defaultRgbIndex(DEFAULT_RGB_FILTERS.r, FILTERS.length - 1), // F200WrgbG: defaultRgbIndex(DEFAULT_RGB_FILTERS.g, Math.floor(FILTERS.length / 2)), // F115WrgbB: defaultRgbIndex(DEFAULT_RGB_FILTERS.b, 0), // F090WrgbQ: 8.0, // Lupton softening parameterrgbMethod: "percentile_asinh",// "percentile_asinh" (default) or "lupton"};```The RGB defaults come from `DEFAULT_RGB_FILTERS` (mirrors `DEFAULT_RGB` in `src/jellyscope/config.py`) and are resolved to channel indices via the `defaultRgbIndex(filterName, fallback)` helper, which falls back to a positional index if the named filter is missing from `FILTERS`.### Initialization Flow```plaintextDOMContentLoaded└── init()├── populateRGBSelects() → fill R/G/B dropdowns; calls updateRGBFilterOptions() at end├── loadClumpList() → GET /api/clumps → populate clump list├── updateFilterLabel() → set initial status label├── updateRGBMethodUI() → show/hide Q slider based on state.rgbMethod├── renderViewer() → GET /api/viewer/... → render Plotly figure└── setupEventListeners()├── datacube-select → onChange → renderViewer()1 unmodified line├── colorscale-select → onChange → renderViewer()├── stretch-select → onChange → renderViewer()├── view-btn (Single/RGB) → onClick → updateViewModeUI() + renderViewer()├── rgb-r/g/b → onChange → updateRGBFilterOptions() + updateFilterLabel() + renderViewer()├── rgb-method → onChange → updateRGBMethodUI() + renderViewer()├── rgb-q → onInput → debounced(renderViewer, 300ms)├── mode buttons → onClick → Plotly.relayout(dragmode)├── btn-centroids → onClick → toggle + renderViewer()14 unmodified linesUtility that delays function execution until `ms` milliseconds after the last invocation. Used for the Q slider to avoid flooding the API during drag.#### `defaultRgbIndex(filterName, fallback)`Resolves a filter name (e.g. `"F200W"`) to its index in the `FILTERS` array. Returns `fallback` if the name is not found. Used to seed `state.rgbR/G/B` from `DEFAULT_RGB_FILTERS` at startup.#### `populateRGBSelects()`Fills the R/G/B `<select>` dropdowns with filter options (name + wavelength labels). The default selections come from `DEFAULT_RGB_FILTERS` (R = F200W, G = F115W, B = F090W) via `defaultRgbIndex()`. Calls `updateRGBFilterOptions()` at the end to apply the wavelength-ordering constraint.#### `updateRGBFilterOptions()`Enforces the constraint **λ_R > λ_G > λ_B** on the R/G/B dropdowns:1. If the current `state.rgbG` has λ ≥ λ_R, auto-select the longest available filter still below λ_R.2. If the current `state.rgbB` has λ ≥ λ_G, do the same for B (longest filter still below λ_G).3. Mark every option whose wavelength would violate the constraint as `disabled` (greyed out in the dropdown).Called whenever any of the R/G/B selectors change so the user cannot pick a non-monotonic combination.#### `updateRGBMethodUI()`Shows or hides `#rgb-q-wrap` (the Q slider wrapper) based on `state.rgbMethod`. The Q parameter only matters for the Lupton method, so the slider is hidden when the method is `percentile_asinh`.#### `updateFilterLabel()`Updates the `#filter-label` status indicator:- **Single mode**: shows `"F200W (1.99 µm)"`- **RGB mode**: shows `"R:F480M G:F277W B:F070W"`7 unmodified lines```plaintext1. If viewMode == "rgb":Build URL: /api/viewer/{datacube}/rgb?r={R}&g={G}&b={B}&selected={ids}&method={rgbMethod}&softening={Q}Else:Build URL: /api/viewer/{datacube}/{channel}?selected={ids}&colorscale={scale}&stretch={stretch}2. fetch(url) → JSON response with figure dict3 unmodified lines6. Attach plotly_click event handler```Called whenever: datacube changes, filter changes, colorscale changes, stretch changes, view mode changes, RGB channels change, RGB method changes, Q slider moves (debounced, Lupton only), clump selection changes, or centroids toggled.#### `onViewerClick(eventData)`
4 unmodified lines567891011212 unmodified lines22422522622722822923023123223323417 unmodified lines2522532542552562572582592602614 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 formatting212 unmodified lines**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**:17 unmodified lines8. 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`)4 unmodified lines567891011212 unmodified lines22422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226317 unmodified lines2812822832842852862872882892902912922932942952962972982993003013024 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) — RGB composite (percentile+asinh and Lupton)- [visualization/spectrum_plot.py](../src/jellyscope/visualization/spectrum_plot.py) — SED line plots- [visualization/properties_panel.py](../src/jellyscope/visualization/properties_panel.py) — Property formatting212 unmodified lines**Location**: `src/jellyscope/visualization/rgb_composite.py`The module offers two RGB composite methods, selectable at call time:- **`percentile_asinh`** (default) — per-band median subtract, percentile clip, asinh stretch, pedestal cut. Not strictly color-preserving, but produces clean, deep-field-style images. Recipe contributed by Andressa.- **`lupton`** — Lupton et al. (2004) Eq. 2 color-preserving mapping. The output color of an object depends only on its flux ratios, not its brightness.### `RGBMethod` type alias```pythonRGBMethod = Literal["percentile_asinh", "lupton"]```Used by `build_rgb_figure` and the corresponding FastAPI endpoint to dispatch between the two methods.### `percentile_asinh_composite(r_data, g_data, b_data, pmin=10.0, pmax=99.9, scale=0.1, floor=0.05, weights=(1.0, 1.02, 1.02)) -> np.ndarray`Per-band, independent stretch pipeline.**Parameters**:| Param | Type | Description || ------- | ------ | ------------- || `r_data`, `g_data`, `b_data` | `np.ndarray` | 2D flux arrays || `pmin`, `pmax` | `float` | Percentile bounds for the linear clip (in percent) || `scale` | `float` | asinh softening; smaller boosts faint features more || `floor` | `float` | Pedestal cut applied after the stretch — pixels below become 0 || `weights` | `tuple[float, float, float]` | Per-channel multipliers `(wR, wG, wB)` applied at the end |**Algorithm** (per band, then combined): median-subtract → percentile-clip to `[pmin, pmax]` → asinh stretch via `arcsinh(y/scale) / arcsinh(1/scale)` → floor cut → channel weight. NaN-safe: any pixel non-finite in any band becomes black.The actual per-band work is done by the private helper `_normalize_band_asinh`.### `lupton_rgb_composite(r_data, g_data, b_data, softening=8.0, alpha=None) -> np.ndarray`Lupton et al. (2004) Eq. 2.**Parameters**:17 unmodified lines8. 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, selected_ids=None, method="percentile_asinh", softening=8.0, alpha=None) -> dict`Assembles the Plotly figure with RGB image + clump overlays.**Parameters**:| Param | Type | Description || ------- | ------ | ------------- || `datacube` | `DataCube` | Datacube to visualize || `r_index`, `g_index`, `b_index` | `int` | Channel indices for the R, G, B bands || `clumps` | `ClumpCatalog` | Clump catalog for overlays || `selected_ids` | `list[int] \| None` | Clumps to highlight in red || `method` | `RGBMethod` | `"percentile_asinh"` (default) or `"lupton"` || `softening` | `float` | Lupton Q — only used when `method="lupton"` || `alpha` | `float \| None` | Lupton linear stretch factor — only used when `method="lupton"` |**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`)
28 unmodified lines29303132333428 unmodified lines"F480M": 4.834,}class JellyscopeConfig(BaseModel):"""Configuration for the Jellyscope application.28 unmodified lines29303132333435363728 unmodified lines"F480M": 4.834,}# Default RGB filter assignment.DEFAULT_RGB: dict[str, str] = {"r": "F200W", "g": "F115W", "b": "F090W"}class JellyscopeConfig(BaseModel):"""Configuration for the Jellyscope application.
123456789105 unmodified lines16171819202121 unmodified lines43444546474849505152535439 unmodified lines9495969798991 unmodified line101102103104105106107108109110111112113114115"""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 Anyimport numpy as np5 unmodified linescreate_clump_boundary_traces,)_GRAY: str = "#cccccc"_DARK_GRAY: str = "#999"_SOFT_BLACK: str = "#333"21 unmodified linesReturns:uint8 array of shape (ny, nx, 3) suitable for Plotly go.Image."""# TODO: Arrumar a equação.# Não faz sentido ter os filtros daquela forma.# Limitar a escolha de filtros.# Deixar 3 filtros pro azul por exemplo.# Escolher os outros filtros a partir do primeiro.# A partir da primeira escolha, restringir as próximas opções.intensity = (r_data + g_data + b_data) / 3.0m, sigma = _estimate_background(intensity)if alpha is None:39 unmodified linesreturn (rgb * 255).astype(np.uint8)def build_rgb_figure(datacube: DataCube,r_index: int,1 unmodified lineb_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)1234567891011121314155 unmodified lines212223242526272821 unmodified lines50515253545539 unmodified lines95969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681 unmodified line170171172173174175176177178179180181182183184185186187188189190191192193194195"""RGB color composite for JWST NIRCam imaging.Two methods are provided:- ``percentile_asinh_composite`` (default): per-band background subtraction,percentile clipping, asinh stretch, and pedestal cut. Not strictly color-preservingbut produces clean, deep-field-style images.- ``lupton_rgb_composite``: Lupton et al. (2004) Eq. 2 — color-preservingmapping where an object's RGB color depends only on its flux ratios."""from typing import Any, Literalimport numpy as np5 unmodified linescreate_clump_boundary_traces,)RGBMethod = Literal["percentile_asinh", "lupton"]_GRAY: str = "#cccccc"_DARK_GRAY: str = "#999"_SOFT_BLACK: str = "#333"21 unmodified linesReturns:uint8 array of shape (ny, nx, 3) suitable for Plotly go.Image."""intensity = (r_data + g_data + b_data) / 3.0m, sigma = _estimate_background(intensity)if alpha is None:39 unmodified linesreturn (rgb * 255).astype(np.uint8)def _normalize_band_asinh(band: np.ndarray,pmin: float,pmax: float,scale: float,floor: float,) -> np.ndarray:"""Per-band normalization: median subtract, percentile clip, asinh, floor."""finite = band[np.isfinite(band)]if finite.size == 0:return np.zeros_like(band, dtype=np.float64)bkg = float(np.median(finite))x = band - bkgfinite_x = x[np.isfinite(x)]lo = float(np.percentile(finite_x, pmin))hi = float(np.percentile(finite_x, pmax))denom = hi - lo if hi > lo else 1.0y = (x - lo) / denomy = np.clip(y, 0.0, 1.0)y = np.arcsinh(y / scale) / np.arcsinh(1.0 / scale)y = np.where(y < floor, 0.0, y)y = np.clip(y, 0.0, 1.0)return ydef percentile_asinh_composite(r_data: np.ndarray,g_data: np.ndarray,b_data: np.ndarray,pmin: float = 10.0,pmax: float = 99.9,scale: float = 0.1,floor: float = 0.05,weights: tuple[float, float, float] = (1.0, 1.02, 1.02),) -> np.ndarray:"""Per-band percentile + asinh stretch composite (Andressa's recipe).Each band is independently background-subtracted (median), percentile-clipped,asinh-stretched, and pedestal-cut, then weighted. Not color-preserving in theLupton sense, but produces a clean image for deep-field NIRCam data.Args:r_data, g_data, b_data: 2D flux arrays.pmin, pmax: Percentile bounds for the linear clip step (in percent).scale: asinh softening parameter — smaller boosts faint features more.floor: pedestal cut applied after stretch; pixels below become 0.weights: (wR, wG, wB) per-channel multipliers applied at the end.Returns:uint8 array (ny, nx, 3) suitable for Plotly go.Image."""r = _normalize_band_asinh(r_data, pmin, pmax, scale, floor) * weights[0]g = _normalize_band_asinh(g_data, pmin, pmax, scale, floor) * weights[1]b = _normalize_band_asinh(b_data, pmin, pmax, scale, floor) * weights[2]nan_mask = ~(np.isfinite(r_data) & np.isfinite(g_data) & np.isfinite(b_data))r[nan_mask] = 0.0g[nan_mask] = 0.0b[nan_mask] = 0.0rgb = np.stack([r, g, b], axis=-1)rgb = np.clip(rgb, 0.0, 1.0)return (rgb * 255).astype(np.uint8)def build_rgb_figure(datacube: DataCube,r_index: int,1 unmodified lineb_index: int,clumps: ClumpCatalog,selected_ids: list[int] | None = None,method: RGBMethod = "percentile_asinh",softening: float = 8.0,alpha: float | None = None,) -> dict[str, Any]:"""Build a Plotly figure with RGB composite + clump overlays.Args:method: ``"percentile_asinh"`` (default) or ``"lupton"``.softening: Lupton ``Q`` parameter (only used when ``method='lupton'``).alpha: Lupton linear stretch factor (only used when ``method='lupton'``)."""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)if method == "lupton":rgb = lupton_rgb_composite(r_data, g_data, b_data, softening, alpha)else:rgb = percentile_asinh_composite(r_data, g_data, b_data)ny = rgb.shape[0]rgb = np.flipud(rgb)
85 unmodified lines8687888990918 unmodified lines10010110210310410510685 unmodified linesg: 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()8 unmodified linesselected_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],85 unmodified lines868788899091928 unmodified lines10110210310410510610710810985 unmodified linesg: Annotated[int, Query(description="Green channel filter index")],b: Annotated[int, Query(description="Blue channel filter index")],selected: Annotated[str, Query()] = "",method: Annotated[Literal["percentile_asinh", "lupton"], Query()] = "percentile_asinh",softening: Annotated[float, Query()] = 8.0,) -> RGBViewerResponse:store = _store()8 unmodified linesselected_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, method=method, softening=softening)return RGBViewerResponse(figure=figure,r_filter=dc.filter_names[r],
10 unmodified lines1112131415164 unmodified lines212223242526272829309 unmodified lines40414243444512 unmodified lines58596061626333 unmodified lines97989910010110210310410510610710810911011111211311411511640 unmodified lines15715815916016116216316416516616716844 unmodified lines21321421521621721821910 unmodified lines};}const state = {datacube: "nircam",channel: 7, // F200W default4 unmodified linesclumps: [],showCentroids: false,viewMode: "single", // "single" or "rgb"rgbR: FILTERS.length - 1, // F480M (longest wavelength -> Red)rgbG: Math.floor(FILTERS.length / 2), // middle -> GreenrgbB: 0, // F070W (shortest wavelength -> Blue)rgbQ: 8.0,};const plotlyConfig = {9 unmodified linespopulateRGBSelects();await loadClumpList();updateFilterLabel();await renderViewer();setupEventListeners();}12 unmodified linessel.appendChild(opt);});});}function setupEventListeners() {33 unmodified lines// RGB filter selectorsdocument.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 debounceconst debouncedRender = debounce(renderViewer, 300);document.getElementById("rgb-q").addEventListener("input", (e) => {40 unmodified linesif (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");44 unmodified lineslet 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}`;}10 unmodified lines111213141516171819202122234 unmodified lines28293031323334353637389 unmodified lines4849505152535412 unmodified lines67686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512633 unmodified lines16016116216316416516616716816917017117217317417517617717817918018118218318418518618718818940 unmodified lines23023123223323423523623723823924024124224324424524624724824944 unmodified lines29429529629729829930010 unmodified lines};}const DEFAULT_RGB_FILTERS = {r: "F200W", g: "F115W", b: "F090W"};function defaultRgbIndex(filterName, fallback) {const idx = FILTERS.indexOf(filterName);return idx >= 0 ? idx : fallback;}const state = {datacube: "nircam",channel: 7, // F200W default4 unmodified linesclumps: [],showCentroids: false,viewMode: "single", // "single" or "rgb"rgbR: defaultRgbIndex(DEFAULT_RGB_FILTERS.r, FILTERS.length - 1),rgbG: defaultRgbIndex(DEFAULT_RGB_FILTERS.g, Math.floor(FILTERS.length / 2)),rgbB: defaultRgbIndex(DEFAULT_RGB_FILTERS.b, 0),rgbQ: 8.0,rgbMethod: "percentile_asinh",};const plotlyConfig = {9 unmodified linespopulateRGBSelects();await loadClumpList();updateFilterLabel();updateRGBMethodUI();await renderViewer();setupEventListeners();}12 unmodified linessel.appendChild(opt);});});updateRGBFilterOptions();}// Enforce λ_R > λ_G > λ_B by disabling invalid options.// If current state.rgbG / rgbB violate the constraint, auto-pick the// next-longest valid filter beneath the upstream one.function updateRGBFilterOptions() {const wlOf = (i) => WAVELENGTHS[FILTERS[i]] ?? -Infinity;// G must have λ < λ_R; if violated, pick the longest filter still < λ_R.if (wlOf(state.rgbG) >= wlOf(state.rgbR)) {let best = -1;let bestWl = -Infinity;FILTERS.forEach((name, i) => {const wl = WAVELENGTHS[name] ?? -Infinity;if (wl < wlOf(state.rgbR) && wl > bestWl) {best = i;bestWl = wl;}});if (best >= 0) state.rgbG = best;}// B must have λ < λ_G; same fallback strategy.if (wlOf(state.rgbB) >= wlOf(state.rgbG)) {let best = -1;let bestWl = -Infinity;FILTERS.forEach((name, i) => {const wl = WAVELENGTHS[name] ?? -Infinity;if (wl < wlOf(state.rgbG) && wl > bestWl) {best = i;bestWl = wl;}});if (best >= 0) state.rgbB = best;}// Apply disabled flags + sync selected values to the (possibly updated) state.const limits = {"rgb-r": Infinity,"rgb-g": wlOf(state.rgbR),"rgb-b": wlOf(state.rgbG),};const current = {"rgb-r": state.rgbR, "rgb-g": state.rgbG, "rgb-b": state.rgbB};for (const id of Object.keys(limits)) {const sel = document.getElementById(id);if (!sel) continue;const max = limits[id];for (const opt of sel.options) {const wl = WAVELENGTHS[FILTERS[parseInt(opt.value)]] ?? -Infinity;opt.disabled = !(wl < max);}sel.value = String(current[id]);}}function setupEventListeners() {33 unmodified lines// RGB filter selectorsdocument.getElementById("rgb-r").addEventListener("change", (e) => {state.rgbR = parseInt(e.target.value);updateRGBFilterOptions();updateFilterLabel();renderViewer();});document.getElementById("rgb-g").addEventListener("change", (e) => {state.rgbG = parseInt(e.target.value);updateRGBFilterOptions();updateFilterLabel();renderViewer();});document.getElementById("rgb-b").addEventListener("change", (e) => {state.rgbB = parseInt(e.target.value);updateRGBFilterOptions();updateFilterLabel();renderViewer();});// RGB method toggledocument.getElementById("rgb-method").addEventListener("change", (e) => {state.rgbMethod = e.target.value;updateRGBMethodUI();renderViewer();});// Q slider with debounceconst debouncedRender = debounce(renderViewer, 300);document.getElementById("rgb-q").addEventListener("input", (e) => {40 unmodified linesif (state.viewMode === "rgb") {singleControls.style.display = "none";rgbControls.style.display = "flex";updateRGBMethodUI();} else {singleControls.style.display = "flex";rgbControls.style.display = "none";}}// Q only matters for the Lupton method; hide its slider otherwise.function updateRGBMethodUI() {const qWrap = document.getElementById("rgb-q-wrap");if (!qWrap) return;qWrap.style.display = state.rgbMethod === "lupton" ? "" : "none";}// Clump List.async function loadClumpList() {const filter = document.getElementById("clump-filter");44 unmodified lineslet url;if (state.viewMode === "rgb") {url = `/api/viewer/${state.datacube}/rgb?r=${state.rgbR}&g=${state.rgbG}&b=${state.rgbB}&selected=${selectedStr}&method=${state.rgbMethod}&softening=${state.rgbQ}`;} else {url = `/api/viewer/${state.datacube}/${state.channel}?selected=${selectedStr}&colorscale=${state.colorscale}&stretch=${state.stretch}`;}
53 unmodified lines54555657585960616263646566676853 unmodified lines</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>53 unmodified lines5455565758596061626364656667686970717273747553 unmodified lines</div><div id="rgb-controls" style="display:none;"><label for="rgb-method">Method:</label><select id="rgb-method"><option value="percentile_asinh" selected>Percentile Asinh</option><option value="lupton">Lupton</option></select><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><span id="rgb-q-wrap"><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></span></div><span id="filter-label">{{ filters[7] }}</span>
1234567873 unmodified lines828384"""Tests for the Lupton RGB composite algorithm."""import numpy as npfrom jellyscope.visualization.rgb_composite import lupton_rgb_compositeclass TestLuptonRGBComposite:73 unmodified lines# Should be dominantly red, NOT whiteassert pixel[0] > pixel[1]assert pixel[0] > pixel[2]123456789101173 unmodified lines858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154"""Tests for the RGB composite algorithms."""import numpy as npfrom jellyscope.visualization.rgb_composite import (lupton_rgb_composite,percentile_asinh_composite,)class TestLuptonRGBComposite:73 unmodified lines# Should be dominantly red, NOT whiteassert pixel[0] > pixel[1]assert pixel[0] > pixel[2]class TestPercentileAsinhComposite: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 = percentile_asinh_composite(r, g, b)assert result.shape == (30, 40, 3)assert result.dtype == np.uint8def test_output_range(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 = percentile_asinh_composite(r, g, b)assert np.all(result >= 0)assert np.all(result <= 255)def test_nan_becomes_black(self):rng = np.random.default_rng(1)r = rng.normal(100, 10, (10, 10))g = rng.normal(80, 10, (10, 10))b = rng.normal(60, 10, (10, 10))r[3, 4] = np.nanresult = percentile_asinh_composite(r, g, b)assert result[3, 4, 0] == 0assert result[3, 4, 1] == 0assert result[3, 4, 2] == 0def 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 = percentile_asinh_composite(r, g, b)assert np.all(result == 0)def test_constant_image_below_floor_is_black(self):# A flat image after median-subtract becomes 0; after the floor cut it stays 0.r = np.full((10, 10), 5.0)g = np.full((10, 10), 5.0)b = np.full((10, 10), 5.0)result = percentile_asinh_composite(r, g, b)assert np.all(result == 0)def test_bright_pixel_dominates(self):# Faint flat background plus a bright red pixel: that pixel should be the brightest.rng = np.random.default_rng(3)r = rng.normal(50, 1, (10, 10))g = rng.normal(50, 1, (10, 10))b = rng.normal(50, 1, (10, 10))r[5, 5] = 500.0result = percentile_asinh_composite(r, g, b)# Channel R at the bright pixel should hit (or be near) the max.assert result[5, 5, 0] == result[..., 0].max()def test_weights_scale_channels(self):rng = np.random.default_rng(11)r = rng.normal(100, 10, (15, 15))g = rng.normal(100, 10, (15, 15))b = rng.normal(100, 10, (15, 15))baseline = percentile_asinh_composite(r, g, b, weights=(1.0, 1.0, 1.0))boosted = percentile_asinh_composite(r, g, b, weights=(2.0, 1.0, 1.0))# Boosting R by 2x should not decrease the R channel anywhere.assert (boosted[..., 0] >= baseline[..., 0]).all()
docs/api-reference.md+14-5
docs/data-layer.md+10
docs/frontend.md+38-10
docs/visualization.md+45-4
src/jellyscope/config.py+3
src/jellyscope/visualization/rgb_composite.py+92-12
src/jellyscope/web/routes.py+4-1
src/jellyscope/web/static/app.js+85-4
src/jellyscope/web/templates/index.html+10-3
tests/visualization/test_rgb_composite.py+72-2