Spaces:
Sleeping
Sleeping
Commit ·
b377f5d
1
Parent(s): 26e93ee
updt with code adjustments
Browse filesFiles changed (16)
- src/jellyscope/data/data_store.py+6-4
- src/jellyscope/data/model/clumps.py+1-1
- src/jellyscope/data/model/coordinates.py+33-21
- src/jellyscope/model/display.pyAdded+21
- src/jellyscope/model/plotly.pyAdded+172
- src/jellyscope/model/schemas.py+7-6
- src/jellyscope/visualization/_viz_helpers.py+55-47
- src/jellyscope/visualization/image_viewer.py+105-85
- src/jellyscope/visualization/properties_panel.py+22-20
- src/jellyscope/visualization/rgb_composite.py+63-36
- src/jellyscope/web/routes.py+8-10
- src/jellyscope/web/static/app.js+2-3
- tests/coordinates/test_coordinates.py+15-15
- tests/visualization/test_image_viewer.py+13-13
- tests/visualization/test_rgb_composite.py+39-39
- tests/web/test_routes.py+17-11
1234567895 unmodified lines151617181920212223242526"""Data store: discovers and caches datasets (datacubes + clump catalogs)."""import loggingfrom dataclasses import dataclass, fieldfrom pathlib import Pathfrom jellyscope.config import JellyscopeConfigfrom jellyscope.data.model.clumps import ClumpCatalogfrom jellyscope.data.model.datacube import DataCube5 unmodified linesDEFAULT_DATASET = "default"@dataclassclass Dataset:"""A self-contained dataset: one or more datacubes + a clump catalog."""name: strdatacubes: dict[str, DataCube] = field(default_factory=dict)clumps: ClumpCatalog | None = Nonedef get_datacube(self, name: str) -> DataCube:123456789105 unmodified lines16171819202122232425262728"""Data store: discovers and caches datasets (datacubes + clump catalogs)."""import loggingfrom pathlib import Pathfrom pydantic import BaseModel, ConfigDictfrom jellyscope.config import JellyscopeConfigfrom jellyscope.data.model.clumps import ClumpCatalogfrom jellyscope.data.model.datacube import DataCube5 unmodified linesDEFAULT_DATASET = "default"class Dataset(BaseModel):"""A self-contained dataset: one or more datacubes + a clump catalog."""model_config = ConfigDict(arbitrary_types_allowed=True)name: strdatacubes: dict[str, DataCube] = {}clumps: ClumpCatalog | None = Nonedef get_datacube(self, name: str) -> DataCube:
116 unmodified lines117118119120121122123116 unmodified linesself._centroid_skycoords: SkyCoord | None = Nonedef get_clump_by_id(self, clump_id: int) -> ClumpProperties:"""Fetch the property dataclass for a specific ID."""return self.clumps[clump_id]def get_pixel_mask(self, clump_id: int) -> np.ndarray:116 unmodified lines117118119120121122123116 unmodified linesself._centroid_skycoords: SkyCoord | None = Nonedef get_clump_by_id(self, clump_id: int) -> ClumpProperties:"""Fetch the ClumpProperties model for a specific ID."""return self.clumps[clump_id]def get_pixel_mask(self, clump_id: int) -> np.ndarray:
6 unmodified lines789101112131415161718192021222324252627282962 unmodified lines92939495969798991001011021031041051061071084 unmodified lines1131141151161171181191201218 unmodified lines1301311321331341351361371381391401411421431446 unmodified linesfrom __future__ import annotationsfrom typing import TypedDictimport numpy as npfrom astropy import units as ufrom astropy.coordinates import SkyCoordfrom astropy.wcs import WCSclass ImageAxisBounds(TypedDict):"""FOV bounds and min-span for an image figure's axes."""x: tuple[float, float]y: tuple[float, float]x_min_span: floaty_min_span: floatdef pixel_to_skycoord(x: float | np.ndarray, y: float | np.ndarray, wcs: WCS) -> SkyCoord:"""Convert pixel coordinates to a SkyCoord (RA/Dec).62 unmodified linesreturn (np.arange(n, dtype=np.float64) - ref) * arcsec_per_pixdef image_arcsec_extent(nx: int, ny: int, arcsec_per_pix: float) -> dict[str, float]:"""Image-extent kwargs (``x``, ``y``, ``sizex``, ``sizey``) for``layout.images[]`` so a PNG image overlay aligns with the centeredarcsec axes produced by :func:`arcsec_axis`."""return {"x": -nx * arcsec_per_pix / 2.0,"y": -ny * arcsec_per_pix / 2.0,"sizex": nx * arcsec_per_pix,"sizey": ny * arcsec_per_pix,}def image_axis_bounds(4 unmodified lines) -> ImageAxisBounds:"""Axis bounds and min-span for the image FOV.Returns a dict with:- ``"x"``, ``"y"``: ``(min, max)`` tuples for the axis range.- ``"x_min_span"``, ``"y_min_span"``: minimum allowed visible span inaxis units (``min_span_pixels`` * pixel scale). Used by thefront-end zoom handler to floor the zoom-in level so users do notzoom past the underlying pixel resolution.8 unmodified linesif arcsec_per_pix is not None:ext = image_arcsec_extent(nx, ny, arcsec_per_pix)x_bounds = (ext["x"], ext["x"] + ext["sizex"])y_bounds = (ext["y"], ext["y"] + ext["sizey"])else:x_bounds = (0.0, float(nx))y_bounds = (0.0, float(ny))return {"x": x_bounds,"y": y_bounds,"x_min_span": min_span,"y_min_span": min_span,}6 unmodified lines789101112131415161718192021222324252627282930313233343536373839404162 unmodified lines1041051061071081091101111121131141151161171181191204 unmodified lines1251261271281291301311321338 unmodified lines1421431441451461471481491501511521531541551566 unmodified linesfrom __future__ import annotationsimport numpy as npfrom astropy import units as ufrom astropy.coordinates import SkyCoordfrom astropy.wcs import WCSfrom pydantic import BaseModel, ConfigDictclass ImageAxisBounds(BaseModel):"""FOV bounds and min-span for an image figure's axes."""model_config = ConfigDict(extra="forbid")x: tuple[float, float]y: tuple[float, float]x_min_span: floaty_min_span: floatclass ImageExtent(BaseModel):"""Image-extent kwargs for Plotly ``layout.images[]`` placement."""model_config = ConfigDict(extra="forbid")x: floaty: floatsizex: floatsizey: floatdef pixel_to_skycoord(x: float | np.ndarray, y: float | np.ndarray, wcs: WCS) -> SkyCoord:"""Convert pixel coordinates to a SkyCoord (RA/Dec).62 unmodified linesreturn (np.arange(n, dtype=np.float64) - ref) * arcsec_per_pixdef image_arcsec_extent(nx: int, ny: int, arcsec_per_pix: float) -> ImageExtent:"""Image-extent kwargs (``x``, ``y``, ``sizex``, ``sizey``) for``layout.images[]`` so a PNG image overlay aligns with the centeredarcsec axes produced by :func:`arcsec_axis`."""return ImageExtent(x=-nx * arcsec_per_pix / 2.0,y=-ny * arcsec_per_pix / 2.0,sizex=nx * arcsec_per_pix,sizey=ny * arcsec_per_pix,)def image_axis_bounds(4 unmodified lines) -> ImageAxisBounds:"""Axis bounds and min-span for the image FOV.Returns an ``ImageAxisBounds`` with:- ``x``, ``y``: ``(min, max)`` tuples for the axis range.- ``x_min_span``, ``y_min_span``: minimum allowed visible span inaxis units (``min_span_pixels`` * pixel scale). Used by thefront-end zoom handler to floor the zoom-in level so users do notzoom past the underlying pixel resolution.8 unmodified linesif arcsec_per_pix is not None:ext = image_arcsec_extent(nx, ny, arcsec_per_pix)x_bounds = (ext.x, ext.x + ext.sizex)y_bounds = (ext.y, ext.y + ext.sizey)else:x_bounds = (0.0, float(nx))y_bounds = (0.0, float(ny))return ImageAxisBounds(x=x_bounds,y=y_bounds,x_min_span=min_span,y_min_span=min_span,)
123456789101112131415161718192021"""Display payload for the clump properties panel.
The frontend renders these as a generic two-column table. Keeping an ordered``entries`` list (instead of a flat dict) preserves row order across JSONserialization and avoids stringly-typed dict keys."""
from pydantic import BaseModel, ConfigDict
class DisplayEntry(BaseModel): model_config = ConfigDict(extra="forbid")
label: str value: str
class ClumpDetailDisplay(BaseModel): model_config = ConfigDict(extra="forbid")
entries: list[DisplayEntry]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""Strict Pydantic models for the subset of Plotly's schema this app emits.
Each model is ``extra="forbid"`` so a typo or stray field fails loudly atconstruction time. Adding a Plotly attribute we want to set requires editingthis file — the explicit catalog is the point.
JSON wire format matches Plotly.js: ``model.model_dump(mode="json",exclude_none=True)`` (or FastAPI's response serialization, which does thesame) produces the dicts ``Plotly.newPlot`` expects."""
from typing import Annotated, Literal
from pydantic import BaseModel, ConfigDict, Field
ColorScale = str | list[list[float | str]]"""Plotly accepts a named colorscale (e.g. ``"Viridis"``) or an explicit``[[stop, color], ...]`` list."""
class _Strict(BaseModel): model_config = ConfigDict(extra="forbid")
# --- hover ---
class HoverTemplate(_Strict): """Wraps Plotly's printf-DSL hovertemplate string.
Plotly's hovertemplate has no formal grammar; the leaf is a string with ``%{field:fmt}`` substitutions. This wrapper centralizes construction so callers go through named factories instead of pasting literals. """
template: str
@classmethod def radec_prefix(cls, suffix: str) -> "HoverTemplate": """RA/Dec hover prefix shared by heatmap and RGB click-target traces.""" prefix = ( "pix: (%{customdata[0]:d}, %{customdata[1]:d})<br>" 'sky: (%{x:.3f}", %{y:.3f}")<br>' "RA: %{customdata[2]:.6f}°<br>" "Dec: %{customdata[3]:.6f}°<br>" ) return cls(template=prefix + suffix)
# --- leaf models ---
class Font(_Strict): color: str | None = None size: int | None = None
class Title(_Strict): text: str font: Font | None = None
class ColorBar(_Strict): title: str thickness: int
class Line(_Strict): color: str width: float
class Marker(_Strict): color: str size: int symbol: str
class Axis(_Strict): title: str gridcolor: str color: str range: tuple[float, float] minallowed: float maxallowed: float autorange: bool
class Margin(_Strict): # Plotly uses single-letter keys; ruff E741 is for "l" as variable, not field. l: int # noqa: E741 r: int t: int b: int
class LayoutImage(_Strict): source: str xref: Literal["x"] yref: Literal["y"] x: float y: float yanchor: Literal["bottom"] sizex: float sizey: float sizing: Literal["stretch"] layer: Literal["below"]
class ImageBoundsMeta(_Strict): x_min_span: float y_min_span: float
class LayoutMeta(_Strict): imageBounds: ImageBoundsMeta # noqa: N815 — Plotly key is camelCase by convention
class Layout(_Strict): title: Title xaxis: Axis yaxis: Axis plot_bgcolor: str paper_bgcolor: str font: Font margin: Margin dragmode: Literal["pan"] meta: LayoutMeta images: list[LayoutImage] = []
# --- traces (discriminated union on ``type``) ---
class HeatmapTrace(_Strict): type: Literal["heatmap"] = "heatmap" z: list[list[float | None]] colorscale: ColorScale hoverongaps: bool showscale: bool colorbar: ColorBar | None = None opacity: float | None = None x: list[float] | None = None y: list[float] | None = None customdata: list[list[list[float | int | None]]] | None = None hovertemplate: str | None = None hoverinfo: Literal["skip"] | None = None
class ScatterTrace(_Strict): type: Literal["scatter"] = "scatter" x: list[float] y: list[float] mode: Literal["lines", "markers+text"] line: Line | None = None marker: Marker | None = None name: str showlegend: bool customdata: list[list[float | None]] | None = None hovertemplate: str | None = None hoverinfo: Literal["text"] | None = None text: str | list[str] | None = None textposition: str | None = None textfont: Font | None = None
PlotlyTrace = Annotated[HeatmapTrace | ScatterTrace, Field(discriminator="type")]
class Figure(_Strict): data: list[PlotlyTrace] layout: Layout12345678938 unmodified lines484950515253546 unmodified lines61626364656667685 unmodified lines74757677787980"""Pydantic models for API request/response validation."""from typing import Anyfrom pydantic import BaseModel# --- Response models ---38 unmodified linesclass ViewerResponse(BaseModel):"""Plotly figure for the galaxy viewer plus current filter name."""figure: dict[str, Any]filter_name: str6 unmodified linesclass ClumpDetailResponse(BaseModel):"""Full properties and boundary polygon for a single clump."""properties: dict[str, Any]boundary: list[list[float]]class PixelClumpResponse(BaseModel):5 unmodified linesclass RGBViewerResponse(BaseModel):"""Plotly figure for RGB composite viewer."""figure: dict[str, Any]r_filter: strg_filter: strb_filter: str1234567891038 unmodified lines495051525354556 unmodified lines62636465666768695 unmodified lines75767778798081"""Pydantic models for API request/response validation."""from pydantic import BaseModelfrom jellyscope.model.display import ClumpDetailDisplayfrom jellyscope.model.plotly import Figure# --- Response models ---38 unmodified linesclass ViewerResponse(BaseModel):"""Plotly figure for the galaxy viewer plus current filter name."""figure: Figurefilter_name: str6 unmodified linesclass ClumpDetailResponse(BaseModel):"""Full properties and boundary polygon for a single clump."""properties: ClumpDetailDisplayboundary: list[tuple[float, float]]class PixelClumpResponse(BaseModel):5 unmodified linesclass RGBViewerResponse(BaseModel):"""Plotly figure for RGB composite viewer."""figure: Figurer_filter: strg_filter: strb_filter: str
4 unmodified lines567891011121 unmodified line1415161718192 unmodified lines22232425262728293031323334353632 unmodified lines697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091104 unmodified linesRGB figure builders."""from typing import Anyimport numpy as npfrom astropy.wcs import WCS1 unmodified lineImageAxisBounds,pixel_to_skycoord,)# Shared dark-theme colors used by both image_viewer and rgb_composite layouts.GRAY: str = "#cccccc"2 unmodified linesDARK_BLUE: str = "#1a1a2e"SOFT_DARK_BLUE: str = "#16213e"# Hover prefix shared by heatmap and RGB click-target traces. Heatmap appends# "flux: %{z:.4f}<extra></extra>"; RGB appends "<extra></extra>".RADEC_HOVER_PREFIX: str = ("pix: (%{customdata[0]:d}, %{customdata[1]:d})<br>"'sky: (%{x:.3f}", %{y:.3f}")<br>'"RA: %{customdata[2]:.6f}°<br>""Dec: %{customdata[3]:.6f}°<br>")def build_radec_customdata_grid(nx: int, ny: int, wcs: WCS32 unmodified linesaxis_label_x: str,axis_label_y: str,bounds: ImageAxisBounds,) -> dict[str, Any]:"""Return the dark-theme figure layout (xaxis/yaxis/bg/font/margin/dragmode/meta).Caller appends ``layout["images"]`` for figures that overlay a PNG."""x_min, x_max = bounds["x"]y_min, y_max = bounds["y"]return {"title": {"text": title_text, "font": {"color": GRAY}},"xaxis": {"title": axis_label_x,"gridcolor": SOFT_BLACK,"color": DARK_GRAY,"range": [x_min, x_max],"minallowed": x_min,"maxallowed": x_max,"autorange": False,},"yaxis": {"title": axis_label_y,"gridcolor": SOFT_BLACK,"color": DARK_GRAY,"range": [y_min, y_max],"minallowed": y_min,"maxallowed": y_max,"autorange": False,},"plot_bgcolor": DARK_BLUE,"paper_bgcolor": SOFT_DARK_BLUE,"font": {"color": GRAY},"margin": {"l": 50, "r": 20, "t": 40, "b": 50},"dragmode": "pan","meta": {"imageBounds": {"x_min_span": bounds["x_min_span"],"y_min_span": bounds["y_min_span"],}},}4 unmodified lines56789101 unmodified line121314151617181920212223242526272 unmodified lines30313233343532 unmodified lines68697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171184 unmodified linesRGB figure builders."""import numpy as npfrom astropy.wcs import WCS1 unmodified lineImageAxisBounds,pixel_to_skycoord,)from jellyscope.model.plotly import (Axis,Font,HoverTemplate,ImageBoundsMeta,Layout,LayoutMeta,Margin,Title,)# Shared dark-theme colors used by both image_viewer and rgb_composite layouts.GRAY: str = "#cccccc"2 unmodified linesDARK_BLUE: str = "#1a1a2e"SOFT_DARK_BLUE: str = "#16213e"def build_radec_customdata_grid(nx: int, ny: int, wcs: WCS32 unmodified linesaxis_label_x: str,axis_label_y: str,bounds: ImageAxisBounds,) -> Layout:"""Return the dark-theme figure layout (xaxis/yaxis/bg/font/margin/dragmode/meta).Caller appends ``layout.images`` for figures that overlay a PNG."""x_min, x_max = bounds.xy_min, y_max = bounds.yreturn Layout(title=Title(text=title_text, font=Font(color=GRAY)),xaxis=Axis(title=axis_label_x,gridcolor=SOFT_BLACK,color=DARK_GRAY,range=(x_min, x_max),minallowed=x_min,maxallowed=x_max,autorange=False,),yaxis=Axis(title=axis_label_y,gridcolor=SOFT_BLACK,color=DARK_GRAY,range=(y_min, y_max),minallowed=y_min,maxallowed=y_max,autorange=False,),plot_bgcolor=DARK_BLUE,paper_bgcolor=SOFT_DARK_BLUE,font=Font(color=GRAY),margin=Margin(l=50, r=20, t=40, b=50),dragmode="pan",meta=LayoutMeta(imageBounds=ImageBoundsMeta(x_min_span=bounds.x_min_span,y_min_span=bounds.y_min_span,)),)def radec_hover(suffix: str) -> HoverTemplate:"""Build the RA/Dec hover prefix + caller-supplied suffix.Heatmap appends ``"flux: %{z:.4f}<extra></extra>"``; RGB click targetappends ``"<extra></extra>"``."""return HoverTemplate.radec_prefix(suffix)
12345676 unmodified lines141516171819202122232496 unmodified lines1211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571587 unmodified lines1661671681691701711725 unmodified lines17817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021 unmodified lines2322332342352362372386 unmodified lines24524624724824925025116 unmodified lines2682692702712722732746 unmodified lines2812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113 unmodified lines3153163173183193203216 unmodified lines328329330331332333334335336337338339340341342343344345346347348349350351"""Plotly figure builders for galaxy image viewing."""from collections.abc import Callablefrom typing import Anyimport numpy as npfrom astropy.wcs import WCS6 unmodified linespixel_scale_arcsec,pixels_to_radec_arrays,)from jellyscope.visualization._viz_helpers import (GRAY,RADEC_HOVER_PREFIX,build_dark_axis_layout,build_radec_customdata_grid,)_RED: str = "#ff4444"96 unmodified linescolorscale: str = "viridis",stretch: str = "log",wcs: WCS | None = None,) -> dict[str, Any]:"""Create a Plotly heatmap trace for a datacube slice.When ``wcs`` is celestial, the trace's ``x``/``y`` arrays are arcsecoffsets from the image center and per-cell ``customdata`` carries``[x_pix, y_pix, ra_deg, dec_deg]`` so hover reveals pixel + RA/Dec."""z = []for row in _normalize_stretch(data=slice_data, stretch=stretch):z.append([None if np.isnan(v) else float(v) for v in row])trace: dict[str, Any] = {"type": "heatmap","z": z,"colorscale": colorscale,"hoverongaps": False,"showscale": True,"colorbar": {"title": "Flux (stretched)", "thickness": 15},}has_sky = wcs is not None and wcs.has_celestialif has_sky:ny, nx = slice_data.shapesec_pix = pixel_scale_arcsec(wcs)trace["x"] = arcsec_axis(nx, sec_pix).tolist()trace["y"] = arcsec_axis(ny, sec_pix).tolist()trace["customdata"] = build_radec_customdata_grid(nx, ny, wcs)trace["hovertemplate"] = RADEC_HOVER_PREFIX + "flux: %{z:.4f}<extra></extra>"else:trace["hovertemplate"] = "x: %{x}<br>y: %{y}<br>flux: %{z:.4f}<extra></extra>"return tracedef _build_clump_boundary_trace(7 unmodified linescx: float,cy: float,wcs: WCS | None,) -> dict[str, Any]:"""Build a single clump-boundary scatter trace."""xs_pix = [p[0] for p in boundary]ys_pix = [p[1] for p in boundary]5 unmodified linesxs_plot = list(xs_pix)ys_plot = list(ys_pix)trace: dict[str, Any] = {"type": "scatter","x": xs_plot,"y": ys_plot,"mode": "lines","line": {"color": _RED if is_selected else _BLUE,"width": 2.5 if is_selected else 1.2,},"name": f"Clump {cid}","showlegend": False,}customdata = _clump_radec_customdata(xs_pix, ys_pix, wcs) if has_sky else Noneif customdata is not None:trace["customdata"] = customdatatrace["hovertemplate"] = (f"Clump {cid} ({c.component})<br>""pix: (%{customdata[0]:.0f}, %{customdata[1]:.0f})<br>"'sky: (%{x:.3f}", %{y:.3f}")<br>'"RA: %{customdata[2]:.6f}°<br>""Dec: %{customdata[3]:.6f}°<extra></extra>")else:trace["hoverinfo"] = "text"trace["text"] = f"Clump {cid} ({c.component})"return tracedef _clump_radec_customdata(21 unmodified linesclumps: ClumpCatalog,selected_ids: list[int] | None = None,wcs: WCS | None = None,) -> list[dict[str, Any]]:"""Create Plotly scatter traces for clump boundaries.When ``wcs`` is celestial, vertices are placed in arcsec offsets from the6 unmodified linescx = (clumps.nx - 1) / 2.0cy = (clumps.ny - 1) / 2.0traces: list[dict[str, Any]] = []for cid, boundary in clumps.get_all_boundaries().items():traces.append(_build_clump_boundary_trace(16 unmodified lines*,has_sky: bool,sec_pix: float,) -> dict[str, Any]:"""Create scatter trace of clump centroids with labels."""all_clumps: list[ClumpProperties] = clumps.list_clumps()cx = (clumps.nx - 1) / 2.06 unmodified linesxs_plot = [c.x0 for c in all_clumps]ys_plot = [c.y0 for c in all_clumps]trace: dict[str, Any] = {"type": "scatter","x": xs_plot,"y": ys_plot,"mode": "markers+text","marker": {"color": _WHITE, "size": 5, "symbol": "x"},"text": [str(c.clump_id) for c in all_clumps],"textposition": "top right","textfont": {"color": GRAY, "size": 9},"name": "Centroids","showlegend": False,}if has_sky:trace["customdata"] = [[c.x0, c.y0, c.ra_deg, c.dec_deg] for c in all_clumps]trace["hovertemplate"] = ("Clump %{text}<br>""pix: (%{customdata[0]:.1f}, %{customdata[1]:.1f})<br>"'sky: (%{x:.3f}", %{y:.3f}")<br>'"RA: %{customdata[2]:.6f}°<br>""Dec: %{customdata[3]:.6f}°<extra></extra>")else:trace["hovertemplate"] = "Clump %{text}<br>x: %{x:.1f}<br>y: %{y:.1f}<extra></extra>"return tracedef build_viewer_figure(3 unmodified linesselected_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]6 unmodified linessec_pix = pixel_scale_arcsec(datacube.wcs) if has_sky else Nonebounds = image_axis_bounds(nx, ny, sec_pix)heatmap: dict[str, Any] = create_galaxy_heatmap(slice_data, colorscale, stretch, wcs=datacube.wcs)boundaries: list[dict[str, Any]] = create_clump_boundary_traces(clumps, selected_ids, wcs=datacube.wcs)centroids: dict[str, Any] = create_centroid_markers(clumps, has_sky=has_sky, sec_pix=sec_pix or 0.0)# *boundaries unpacks the list from. E.g: boundaries = [a, b, c...]; *boundaries = a, b, c...data: list[dict[str, Any]] = [heatmap, *boundaries, centroids]layout: dict[str, Any] = build_dark_axis_layout(title_text=f"{datacube.name} \u2014 {filter_name}",axis_label_x=axis_label_x,axis_label_y=axis_label_y,bounds=bounds,)return {"data": data, "layout": layout}1234566 unmodified lines13141516171819202122232425262728293031323396 unmodified lines1301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691707 unmodified lines1781791801811821831845 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822921 unmodified lines2512522532542552562576 unmodified lines26426526626726826927016 unmodified lines2872882892902912922936 unmodified lines3003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383 unmodified lines3423433443453463473486 unmodified lines355356357358359360361362363364365366367368369370371"""Plotly figure builders for galaxy image viewing."""from collections.abc import Callableimport numpy as npfrom astropy.wcs import WCS6 unmodified linespixel_scale_arcsec,pixels_to_radec_arrays,)from jellyscope.model.plotly import (ColorBar,Figure,Font,HeatmapTrace,Line,Marker,PlotlyTrace,ScatterTrace,)from jellyscope.visualization._viz_helpers import (GRAY,build_dark_axis_layout,build_radec_customdata_grid,radec_hover,)_RED: str = "#ff4444"96 unmodified linescolorscale: str = "viridis",stretch: str = "log",wcs: WCS | None = None,) -> HeatmapTrace:"""Create a Plotly heatmap trace for a datacube slice.When ``wcs`` is celestial, the trace's ``x``/``y`` arrays are arcsecoffsets from the image center and per-cell ``customdata`` carries``[x_pix, y_pix, ra_deg, dec_deg]`` so hover reveals pixel + RA/Dec."""z: list[list[float | None]] = []for row in _normalize_stretch(data=slice_data, stretch=stretch):z.append([None if np.isnan(v) else float(v) for v in row])has_sky = wcs is not None and wcs.has_celestialif has_sky:ny, nx = slice_data.shapesec_pix = pixel_scale_arcsec(wcs)return HeatmapTrace(z=z,colorscale=colorscale,hoverongaps=False,showscale=True,colorbar=ColorBar(title="Flux (stretched)", thickness=15),x=arcsec_axis(nx, sec_pix).tolist(),y=arcsec_axis(ny, sec_pix).tolist(),customdata=build_radec_customdata_grid(nx, ny, wcs),hovertemplate=radec_hover("flux: %{z:.4f}<extra></extra>").template,)return HeatmapTrace(z=z,colorscale=colorscale,hoverongaps=False,showscale=True,colorbar=ColorBar(title="Flux (stretched)", thickness=15),hovertemplate="x: %{x}<br>y: %{y}<br>flux: %{z:.4f}<extra></extra>",)def _build_clump_boundary_trace(7 unmodified linescx: float,cy: float,wcs: WCS | None,) -> ScatterTrace:"""Build a single clump-boundary scatter trace."""xs_pix = [p[0] for p in boundary]ys_pix = [p[1] for p in boundary]5 unmodified linesxs_plot = list(xs_pix)ys_plot = list(ys_pix)line = Line(color=_RED if is_selected else _BLUE,width=2.5 if is_selected else 1.2,)customdata = _clump_radec_customdata(xs_pix, ys_pix, wcs) if has_sky else Noneif customdata is not None:return ScatterTrace(x=xs_plot,y=ys_plot,mode="lines",line=line,name=f"Clump {cid}",showlegend=False,customdata=customdata,hovertemplate=(f"Clump {cid} ({c.component})<br>""pix: (%{customdata[0]:.0f}, %{customdata[1]:.0f})<br>"'sky: (%{x:.3f}", %{y:.3f}")<br>'"RA: %{customdata[2]:.6f}°<br>""Dec: %{customdata[3]:.6f}°<extra></extra>"),)return ScatterTrace(x=xs_plot,y=ys_plot,mode="lines",line=line,name=f"Clump {cid}",showlegend=False,hoverinfo="text",text=f"Clump {cid} ({c.component})",)def _clump_radec_customdata(21 unmodified linesclumps: ClumpCatalog,selected_ids: list[int] | None = None,wcs: WCS | None = None,) -> list[ScatterTrace]:"""Create Plotly scatter traces for clump boundaries.When ``wcs`` is celestial, vertices are placed in arcsec offsets from the6 unmodified linescx = (clumps.nx - 1) / 2.0cy = (clumps.ny - 1) / 2.0traces: list[ScatterTrace] = []for cid, boundary in clumps.get_all_boundaries().items():traces.append(_build_clump_boundary_trace(16 unmodified lines*,has_sky: bool,sec_pix: float,) -> ScatterTrace:"""Create scatter trace of clump centroids with labels."""all_clumps: list[ClumpProperties] = clumps.list_clumps()cx = (clumps.nx - 1) / 2.06 unmodified linesxs_plot = [c.x0 for c in all_clumps]ys_plot = [c.y0 for c in all_clumps]if has_sky:return ScatterTrace(x=xs_plot,y=ys_plot,mode="markers+text",marker=Marker(color=_WHITE, size=5, symbol="x"),text=[str(c.clump_id) for c in all_clumps],textposition="top right",textfont=Font(color=GRAY, size=9),name="Centroids",showlegend=False,customdata=[[c.x0, c.y0, c.ra_deg, c.dec_deg] for c in all_clumps],hovertemplate=("Clump %{text}<br>""pix: (%{customdata[0]:.1f}, %{customdata[1]:.1f})<br>"'sky: (%{x:.3f}", %{y:.3f}")<br>'"RA: %{customdata[2]:.6f}°<br>""Dec: %{customdata[3]:.6f}°<extra></extra>"),)return ScatterTrace(x=xs_plot,y=ys_plot,mode="markers+text",marker=Marker(color=_WHITE, size=5, symbol="x"),text=[str(c.clump_id) for c in all_clumps],textposition="top right",textfont=Font(color=GRAY, size=9),name="Centroids",showlegend=False,hovertemplate="Clump %{text}<br>x: %{x:.1f}<br>y: %{y:.1f}<extra></extra>",)def build_viewer_figure(3 unmodified linesselected_ids: list[int] | None = None,colorscale: str = "Viridis",stretch: str = "log",) -> Figure:"""Assembles heatmap + boundaries + centroids."""slice_data: np.ndarray = datacube.get_slice_by_channel_index(channel_index)filter_name: str = datacube.filter_names[channel_index]6 unmodified linessec_pix = pixel_scale_arcsec(datacube.wcs) if has_sky else Nonebounds = image_axis_bounds(nx, ny, sec_pix)heatmap = create_galaxy_heatmap(slice_data, colorscale, stretch, wcs=datacube.wcs)boundaries = create_clump_boundary_traces(clumps, selected_ids, wcs=datacube.wcs)centroids = create_centroid_markers(clumps, has_sky=has_sky, sec_pix=sec_pix or 0.0)data: list[PlotlyTrace] = [heatmap, *boundaries, centroids]layout = build_dark_axis_layout(title_text=f"{datacube.name} — {filter_name}",axis_label_x=axis_label_x,axis_label_y=axis_label_y,bounds=bounds,)return Figure(data=data, layout=layout)
12345678910111213141516171819202122232425"""Format clump properties for displaying it with Plotly."""from typing import Anyfrom jellyscope.data.model.clumps import ClumpPropertiesdef format_clump_properties(clump: ClumpProperties) -> dict[str, Any]:"""Format a single clump's properties for displaying in the UI."""ra_str = f"{clump.ra_deg:.6f}" if clump.ra_deg is not None else "\u2014"dec_str = f"{clump.dec_deg:.6f}" if clump.dec_deg is not None else "\u2014"return {"Clump ID": clump.clump_id,"Component": clump.component.capitalize(),"Inside disk": "Yes" if clump.inside else "No","Area (pixels)": clump.area_pix,"Area (arcsec\u00b2)": f"{clump.area_arcsec2:.4f}","Area (kpc\u00b2)": f"{clump.area_kpc2:.4f}","R_eff (arcsec)": f"{clump.r_eff_arcsec:.4f}","R_eff (kpc)": f"{clump.r_eff_kpc:.4f}","Centroid x": f"{clump.x0:.1f}","Centroid y": f"{clump.y0:.1f}","RA (deg)": ra_str,"Dec (deg)": dec_str,}123456789101112131415161718192021222324252627"""Format clump properties for displaying it with Plotly."""from jellyscope.data.model.clumps import ClumpPropertiesfrom jellyscope.model.display import ClumpDetailDisplay, DisplayEntrydef format_clump_properties(clump: ClumpProperties) -> ClumpDetailDisplay:"""Format a single clump's properties as an ordered display table."""ra_str = f"{clump.ra_deg:.6f}" if clump.ra_deg is not None else "—"dec_str = f"{clump.dec_deg:.6f}" if clump.dec_deg is not None else "—"rows: list[tuple[str, str]] = [("Clump ID", str(clump.clump_id)),("Component", clump.component.capitalize()),("Inside disk", "Yes" if clump.inside else "No"),("Area (pixels)", str(clump.area_pix)),("Area (arcsec²)", f"{clump.area_arcsec2:.4f}"),("Area (kpc²)", f"{clump.area_kpc2:.4f}"),("R_eff (arcsec)", f"{clump.r_eff_arcsec:.4f}"),("R_eff (kpc)", f"{clump.r_eff_kpc:.4f}"),("Centroid x", f"{clump.x0:.1f}"),("Centroid y", f"{clump.y0:.1f}"),("RA (deg)", ra_str),("Dec (deg)", dec_str),]return ClumpDetailDisplay(entries=[DisplayEntry(label=label, value=value) for label, value in rows])
10 unmodified lines111213141516171 unmodified line192021222324252627282930313233150 unmodified lines1841851861871881894 unmodified lines19419519619719819920018 unmodified lines2192202212222232242252262272282292302312322332342352362372382392402412422432444 unmodified lines24925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827910 unmodified linesimport base64import iofrom typing import Any, Literalimport numpy as npfrom PIL import Image as PILImage1 unmodified linefrom jellyscope.data.data_store import DataCubefrom jellyscope.data.model.clumps import ClumpCatalogfrom jellyscope.data.model.coordinates import (arcsec_axis,image_arcsec_extent,image_axis_bounds,pixel_scale_arcsec,)from jellyscope.visualization._viz_helpers import (RADEC_HOVER_PREFIX,build_dark_axis_layout,build_radec_customdata_grid,)from jellyscope.visualization.image_viewer import (_default_alpha,150 unmodified linesreturn "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")def build_rgb_figure(datacube: DataCube,r_index: int,4 unmodified linesmethod: RGBMethod = "percentile_asinh",softening: float = 8.0,alpha: float | None = None,) -> dict[str, Any]:"""Build a Plotly figure with RGB composite + clump overlays.Pixels are rendered via ``layout.images[]`` (PNG annotation) on a Cartesian18 unmodified lineshas_sky = datacube.wcs is not None and datacube.wcs.has_celestialsec_pix: float | None = pixel_scale_arcsec(datacube.wcs) if has_sky else Noneclick_target: dict[str, Any] = {"type": "heatmap","z": np.zeros((ny, nx)).tolist(),"showscale": False,"opacity": 0,"colorscale": [[0, "rgba(0,0,0,0)"], [1, "rgba(0,0,0,0)"]],}if has_sky and sec_pix is not None:click_target["x"] = arcsec_axis(nx, sec_pix).tolist()click_target["y"] = arcsec_axis(ny, sec_pix).tolist()click_target["customdata"] = build_radec_customdata_grid(nx, ny, datacube.wcs)click_target["hovertemplate"] = RADEC_HOVER_PREFIX + "<extra></extra>"else:click_target["hoverinfo"] = "skip"boundaries = create_clump_boundary_traces(clumps, selected_ids, wcs=datacube.wcs)centroids = create_centroid_markers(clumps, has_sky=has_sky, sec_pix=sec_pix or 0.0)data: list[dict[str, Any]] = [click_target, *boundaries, centroids]r_name = datacube.filter_names[r_index]g_name = datacube.filter_names[g_index]4 unmodified linesaxis_label_x = "x offset (arcsec)"axis_label_y = "y offset (arcsec)"else:extent = {"x": 0, "y": 0, "sizex": nx, "sizey": ny}axis_label_x = "x (pixels)"axis_label_y = "y (pixels)"bounds = image_axis_bounds(nx, ny, sec_pix)layout: dict[str, Any] = build_dark_axis_layout(title_text=f"RGB: {r_name} / {g_name} / {b_name}",axis_label_x=axis_label_x,axis_label_y=axis_label_y,bounds=bounds,)layout["images"] = [{"source": _rgb_to_png_data_url(rgb),"xref": "x","yref": "y","x": extent["x"],"y": extent["y"],"yanchor": "bottom","sizex": extent["sizex"],"sizey": extent["sizey"],"sizing": "stretch","layer": "below",}]return {"data": data, "layout": layout}10 unmodified lines111213141516171 unmodified line19202122232425262728293031323334353637383940150 unmodified lines1911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302314 unmodified lines23623723823924024124218 unmodified lines2612622632642652662672682692702714 unmodified lines27627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530610 unmodified linesimport base64import iofrom typing import Literalimport numpy as npfrom PIL import Image as PILImage1 unmodified linefrom jellyscope.data.data_store import DataCubefrom jellyscope.data.model.clumps import ClumpCatalogfrom jellyscope.data.model.coordinates import (ImageExtent,arcsec_axis,image_arcsec_extent,image_axis_bounds,pixel_scale_arcsec,)from jellyscope.model.plotly import (Figure,HeatmapTrace,LayoutImage,PlotlyTrace,)from jellyscope.visualization._viz_helpers import (build_dark_axis_layout,build_radec_customdata_grid,radec_hover,)from jellyscope.visualization.image_viewer import (_default_alpha,150 unmodified linesreturn "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode("ascii")def _build_click_target(nx: int,ny: int,has_sky: bool,sec_pix: float | None,datacube: DataCube,) -> HeatmapTrace:"""Invisible heatmap layered under the PNG to receive click events."""z: list[list[float | None]] = [[0.0] * nx for _ in range(ny)]transparent: list[list[float | str]] = [[0.0, "rgba(0,0,0,0)"],[1.0, "rgba(0,0,0,0)"],]if has_sky and sec_pix is not None:return HeatmapTrace(z=z,colorscale=transparent,hoverongaps=False,showscale=False,opacity=0,x=arcsec_axis(nx, sec_pix).tolist(),y=arcsec_axis(ny, sec_pix).tolist(),customdata=build_radec_customdata_grid(nx, ny, datacube.wcs),hovertemplate=radec_hover("<extra></extra>").template,)return HeatmapTrace(z=z,colorscale=transparent,hoverongaps=False,showscale=False,opacity=0,hoverinfo="skip",)def build_rgb_figure(datacube: DataCube,r_index: int,4 unmodified linesmethod: RGBMethod = "percentile_asinh",softening: float = 8.0,alpha: float | None = None,) -> Figure:"""Build a Plotly figure with RGB composite + clump overlays.Pixels are rendered via ``layout.images[]`` (PNG annotation) on a Cartesian18 unmodified lineshas_sky = datacube.wcs is not None and datacube.wcs.has_celestialsec_pix: float | None = pixel_scale_arcsec(datacube.wcs) if has_sky else Noneclick_target = _build_click_target(nx, ny, has_sky, sec_pix, datacube)boundaries = create_clump_boundary_traces(clumps, selected_ids, wcs=datacube.wcs)centroids = create_centroid_markers(clumps, has_sky=has_sky, sec_pix=sec_pix or 0.0)data: list[PlotlyTrace] = [click_target, *boundaries, centroids]r_name = datacube.filter_names[r_index]g_name = datacube.filter_names[g_index]4 unmodified linesaxis_label_x = "x offset (arcsec)"axis_label_y = "y offset (arcsec)"else:extent = ImageExtent(x=0.0, y=0.0, sizex=float(nx), sizey=float(ny))axis_label_x = "x (pixels)"axis_label_y = "y (pixels)"bounds = image_axis_bounds(nx, ny, sec_pix)layout = build_dark_axis_layout(title_text=f"RGB: {r_name} / {g_name} / {b_name}",axis_label_x=axis_label_x,axis_label_y=axis_label_y,bounds=bounds,)layout.images = [LayoutImage(source=_rgb_to_png_data_url(rgb),xref="x",yref="y",x=extent.x,y=extent.y,yanchor="bottom",sizex=extent.sizex,sizey=extent.sizey,sizing="stretch",layer="below",)]return Figure(data=data, layout=layout)
12345695 unmodified lines10210310410510610710817 unmodified lines1261271281291301311327 unmodified lines14014114214314414513 unmodified lines15916016116216316416516616777 unmodified lines245246247248249250251252253254"""REST API endpoints and page routes."""from typing import Annotated, Any, Literalimport numpy as npfrom fastapi import APIRouter, HTTPException, Query, Request95 unmodified lines# Image viewer.@router.get("/api/datasets/{dataset_name}/viewer/{datacube_name}/rgb", response_model=RGBViewerResponse)def get_rgb_viewer_figure(dataset_name: str,17 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, clumps, selected_ids, method=method, softening=softening)return RGBViewerResponse(7 unmodified lines@router.get("/api/datasets/{dataset_name}/viewer/{datacube_name}/{channel_index}",response_model=ViewerResponse,)def get_viewer_figure(dataset_name: str,13 unmodified linesselected_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, clumps, selected_ids, colorscale, stretch)return ViewerResponse(figure=figure, filter_name=dc.filter_names[channel_index])77 unmodified linesclump = clumps.get_clump_by_id(clump_id)boundary = clumps.get_boundary_coords(clump_id)props = format_clump_properties(clump)return ClumpDetailResponse(properties=props,boundary=[list(coord) for coord in boundary],)# Pixel Interaction.12345695 unmodified lines10210310410510610710810911017 unmodified lines1281291301311321331347 unmodified lines14214314414514614714813 unmodified lines16216316416516616716877 unmodified lines246247248249250251252"""REST API endpoints and page routes."""from typing import Annotated, Literalimport numpy as npfrom fastapi import APIRouter, HTTPException, Query, Request95 unmodified lines# Image viewer.@router.get("/api/datasets/{dataset_name}/viewer/{datacube_name}/rgb",response_model=RGBViewerResponse,response_model_exclude_none=True,)def get_rgb_viewer_figure(dataset_name: str,17 unmodified linesselected_ids: list[int] = ([int(i) for i in selected.split(",") if i.strip()] if selected else [])figure = build_rgb_figure(dc, r, g, b, clumps, selected_ids, method=method, softening=softening)return RGBViewerResponse(7 unmodified lines@router.get("/api/datasets/{dataset_name}/viewer/{datacube_name}/{channel_index}",response_model=ViewerResponse,response_model_exclude_none=True,)def get_viewer_figure(dataset_name: str,13 unmodified linesselected_ids: list[int] = ([int(i) for i in selected.split(",") if i.strip()] if selected else [])figure = build_viewer_figure(dc, channel_index, clumps, selected_ids, colorscale, stretch)return ViewerResponse(figure=figure, filter_name=dc.filter_names[channel_index])77 unmodified linesclump = clumps.get_clump_by_id(clump_id)boundary = clumps.get_boundary_coords(clump_id)props = format_clump_properties(clump)return ClumpDetailResponse(properties=props, boundary=boundary)# Pixel Interaction.
930 unmodified lines931932933934935936937938939940930 unmodified linesasync function showClumpDetails(clumpId) {const propsResp = await fetch(`${dsBase()}/clumps/${clumpId}`);const propsData = await propsResp.json();const props = propsData.properties;let html = '<table class="prop-table">';for (const [key, val] of Object.entries(props)) {html += `<tr><td>${key}</td><td>${val}</td></tr>`;}html += "</table>";document.getElementById("properties-content").innerHTML = html;930 unmodified lines931932933934935936937938939930 unmodified linesasync function showClumpDetails(clumpId) {const propsResp = await fetch(`${dsBase()}/clumps/${clumpId}`);const propsData = await propsResp.json();let html = '<table class="prop-table">';for (const {label, value} of propsData.properties.entries) {html += `<tr><td>${label}</td><td>${value}</td></tr>`;}html += "</table>";document.getElementById("properties-content").innerHTML = html;
117 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152117 unmodified linesdef test_image_arcsec_extent_matches_axis_span():nx, ny, sec = 170, 155, 0.02extent = image_arcsec_extent(nx, ny, sec)assert extent["x"] == pytest.approx(-nx * sec / 2.0)assert extent["y"] == pytest.approx(-ny * sec / 2.0)assert extent["sizex"] == pytest.approx(nx * sec)assert extent["sizey"] == pytest.approx(ny * sec)# Image lower-left to upper-right spans the full FOV.assert extent["x"] + extent["sizex"] == pytest.approx(nx * sec / 2.0)def test_image_axis_bounds_arcsec_branch():nx, ny, sec = 170, 155, 0.02bounds = image_axis_bounds(nx, ny, sec)assert bounds["x"] == pytest.approx((-nx * sec / 2.0, nx * sec / 2.0))assert bounds["y"] == pytest.approx((-ny * sec / 2.0, ny * sec / 2.0))# Default min span = 5 pixels.assert bounds["x_min_span"] == pytest.approx(5 * sec)assert bounds["y_min_span"] == pytest.approx(5 * sec)def test_image_axis_bounds_pixel_fallback():nx, ny = 170, 155bounds = image_axis_bounds(nx, ny, None)assert bounds["x"] == (0.0, float(nx))assert bounds["y"] == (0.0, float(ny))assert np.isclose(bounds["x_min_span"], 5.0, rtol=1e-09, atol=1e-09)assert np.isclose(bounds["y_min_span"], 5.0, rtol=1e-09, atol=1e-09)def test_image_axis_bounds_custom_min_span_pixels():nx, ny, sec = 100, 100, 0.04bounds = image_axis_bounds(nx, ny, sec, min_span_pixels=10)assert bounds["x_min_span"] == pytest.approx(10 * sec)assert bounds["y_min_span"] == pytest.approx(10 * sec)117 unmodified lines118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152117 unmodified linesdef test_image_arcsec_extent_matches_axis_span():nx, ny, sec = 170, 155, 0.02extent = image_arcsec_extent(nx, ny, sec)assert extent.x == pytest.approx(-nx * sec / 2.0)assert extent.y == pytest.approx(-ny * sec / 2.0)assert extent.sizex == pytest.approx(nx * sec)assert extent.sizey == pytest.approx(ny * sec)# Image lower-left to upper-right spans the full FOV.assert extent.x + extent.sizex == pytest.approx(nx * sec / 2.0)def test_image_axis_bounds_arcsec_branch():nx, ny, sec = 170, 155, 0.02bounds = image_axis_bounds(nx, ny, sec)assert bounds.x == pytest.approx((-nx * sec / 2.0, nx * sec / 2.0))assert bounds.y == pytest.approx((-ny * sec / 2.0, ny * sec / 2.0))# Default min span = 5 pixels.assert bounds.x_min_span == pytest.approx(5 * sec)assert bounds.y_min_span == pytest.approx(5 * sec)def test_image_axis_bounds_pixel_fallback():nx, ny = 170, 155bounds = image_axis_bounds(nx, ny, None)assert bounds.x == (0.0, float(nx))assert bounds.y == (0.0, float(ny))assert np.isclose(bounds.x_min_span, 5.0, rtol=1e-09, atol=1e-09)assert np.isclose(bounds.y_min_span, 5.0, rtol=1e-09, atol=1e-09)def test_image_axis_bounds_custom_min_span_pixels():nx, ny, sec = 100, 100, 0.04bounds = image_axis_bounds(nx, ny, sec, min_span_pixels=10)assert bounds.x_min_span == pytest.approx(10 * sec)assert bounds.y_min_span == pytest.approx(10 * sec)
123 unmodified lines1241251261271281291301311321331346 unmodified lines1411421431441451461471481491501516 unmodified lines158159160161162163123 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)x = fig["layout"]["xaxis"]assert x["autorange"] is Falseassert x["range"] == [bounds["x"][0], bounds["x"][1]]assert x["minallowed"] == bounds["x"][0]assert x["maxallowed"] == bounds["x"][1]def test_yaxis_locked_to_image_extent(self, store):from jellyscope.data.model.coordinates import (6 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)y = fig["layout"]["yaxis"]assert y["autorange"] is Falseassert y["range"] == [bounds["y"][0], bounds["y"][1]]assert y["minallowed"] == bounds["y"][0]assert y["maxallowed"] == bounds["y"][1]def test_meta_image_bounds_min_span(self, store):from jellyscope.data.model.coordinates import (6 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)ib = fig["layout"]["meta"]["imageBounds"]assert ib["x_min_span"] == bounds["x_min_span"]assert ib["y_min_span"] == bounds["y_min_span"]123 unmodified lines1241251261271281291301311321331346 unmodified lines1411421431441451461471481491501516 unmodified lines158159160161162163123 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)x = fig.layout.xaxisassert x.autorange is Falseassert x.range == bounds.xassert x.minallowed == bounds.x[0]assert x.maxallowed == bounds.x[1]def test_yaxis_locked_to_image_extent(self, store):from jellyscope.data.model.coordinates import (6 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)y = fig.layout.yaxisassert y.autorange is Falseassert y.range == bounds.yassert y.minallowed == bounds.y[0]assert y.maxallowed == bounds.y[1]def test_meta_image_bounds_min_span(self, store):from jellyscope.data.model.coordinates import (6 unmodified linessec = pixel_scale_arcsec(dc.wcs) if dc.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)ib = fig.layout.meta.imageBoundsassert ib.x_min_span == bounds.x_min_spanassert ib.y_min_span == bounds.y_min_span
163 unmodified lines16416516616716816917012 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092103 unmodified lines21421521621721821922022122222322413 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642658 unmodified lines2742752762772782792802812822832842852862872882898 unmodified lines298299300301302303163 unmodified linesclass TestBuildRGBFigure:"""Figure assembly: invisible heatmap click target + layout.images PNG."""def _build(self, store: DataStore, method: str = "percentile_asinh") -> dict:dataset_name = store.list_datasets()[0]dataset = store.get_dataset(dataset_name)datacube_name = dataset.list_datacubes()[0]12 unmodified linesdef test_data0_is_invisible_heatmap(self, store: DataStore):fig = self._build(store)d0 = fig["data"][0]assert d0["type"] == "heatmap"assert d0["opacity"] == 0assert d0["showscale"] is Falsedef test_layout_images_png_annotation(self, store: DataStore):fig = self._build(store)images = fig["layout"]["images"]assert len(images) == 1img = images[0]assert img["xref"] == "x"assert img["yref"] == "y"assert img["sizing"] == "stretch"# Image is centered on (0, 0) in arcsec offsets.assert img["x"] < 0assert img["y"] < 0assert img["source"].startswith("data:image/png;base64,")def test_no_yaxis_autorange_reversed(self, store: DataStore):fig = self._build(store)yaxis = fig["layout"]["yaxis"]assert yaxis.get("autorange") != "reversed"def test_png_dimensions_match_datacube(self, store: DataStore):from jellyscope.data.model.coordinates import pixel_scale_arcsec3 unmodified linesdatacube = dataset.get_datacube(dataset.list_datacubes()[0])ny, nx = datacube.spatial_shapesec_pix = pixel_scale_arcsec(datacube.wcs)img = fig["layout"]["images"][0]assert img["sizex"] == pytest.approx(nx * sec_pix, rel=1e-9)assert img["sizey"] == pytest.approx(ny * sec_pix, rel=1e-9)# Decode PNG and confirm dimensions still match the source pixel grid.b64 = img["source"].removeprefix("data:image/png;base64,")png_bytes = base64.b64decode(b64)png = PILImage.open(io.BytesIO(png_bytes))assert png.size == (nx, ny)13 unmodified linesny, _ = datacube.spatial_shapesec_pix = pixel_scale_arcsec(datacube.wcs)cy = (ny - 1) / 2.0centroids = fig["data"][-1]expected_ys = [(c.y0 - cy) * sec_pix for c in clump_list]for got, exp in zip(centroids["y"], expected_ys, strict=True):assert got == pytest.approx(exp, rel=1e-9, abs=1e-12)def test_data_order_preserves_clickable_first(self, store: DataStore):"""app.js relies on data[0] being the click target; centroids are last."""fig = self._build(store)assert fig["data"][0]["type"] == "heatmap"# Last trace must be the centroid scatter so fig.data.pop() in JS toggles it.assert fig["data"][-1].get("name") == "Centroids"def test_lupton_method_path(self, store: DataStore):fig = self._build(store, method="lupton")assert fig["data"][0]["type"] == "heatmap"assert fig["layout"]["images"][0]["source"].startswith("data:image/png;base64,")def test_image_yanchor_bottom(self, store: DataStore):"""Image bottom must anchor at y=0 so it occupies y∈[0, ny] with overlays."""fig = self._build(store)img = fig["layout"]["images"][0]assert img["yanchor"] == "bottom"def test_axes_locked_to_image_extent(self, store: DataStore):from jellyscope.data.model.coordinates import (8 unmodified linessec = pixel_scale_arcsec(datacube.wcs) if datacube.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)x = fig["layout"]["xaxis"]y = fig["layout"]["yaxis"]assert x["autorange"] is Falseassert y["autorange"] is Falseassert x["range"] == [bounds["x"][0], bounds["x"][1]]assert y["range"] == [bounds["y"][0], bounds["y"][1]]assert x["minallowed"] == bounds["x"][0]assert x["maxallowed"] == bounds["x"][1]assert y["minallowed"] == bounds["y"][0]assert y["maxallowed"] == bounds["y"][1]def test_meta_image_bounds_min_span(self, store: DataStore):from jellyscope.data.model.coordinates import (8 unmodified linessec = pixel_scale_arcsec(datacube.wcs) if datacube.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)ib = fig["layout"]["meta"]["imageBounds"]assert ib["x_min_span"] == bounds["x_min_span"]assert ib["y_min_span"] == bounds["y_min_span"]163 unmodified lines16416516616716816917012 unmodified lines1831841851861871881891901911921931941951961971981992002012022032042052062072082092103 unmodified lines21421521621721821922022122222322413 unmodified lines2382392402412422432442452462472482492502512522532542552562572582592602612622632642658 unmodified lines2742752762772782792802812822832842852862872882898 unmodified lines298299300301302303163 unmodified linesclass TestBuildRGBFigure:"""Figure assembly: invisible heatmap click target + layout.images PNG."""def _build(self, store: DataStore, method: str = "percentile_asinh"):dataset_name = store.list_datasets()[0]dataset = store.get_dataset(dataset_name)datacube_name = dataset.list_datacubes()[0]12 unmodified linesdef test_data0_is_invisible_heatmap(self, store: DataStore):fig = self._build(store)d0 = fig.data[0]assert d0.type == "heatmap"assert d0.opacity == 0assert d0.showscale is Falsedef test_layout_images_png_annotation(self, store: DataStore):fig = self._build(store)images = fig.layout.imagesassert len(images) == 1img = images[0]assert img.xref == "x"assert img.yref == "y"assert img.sizing == "stretch"# Image is centered on (0, 0) in arcsec offsets.assert img.x < 0assert img.y < 0assert img.source.startswith("data:image/png;base64,")def test_no_yaxis_autorange_reversed(self, store: DataStore):fig = self._build(store)# autorange is bool now; reversed mode would have been a special string.assert fig.layout.yaxis.autorange is Falsedef test_png_dimensions_match_datacube(self, store: DataStore):from jellyscope.data.model.coordinates import pixel_scale_arcsec3 unmodified linesdatacube = dataset.get_datacube(dataset.list_datacubes()[0])ny, nx = datacube.spatial_shapesec_pix = pixel_scale_arcsec(datacube.wcs)img = fig.layout.images[0]assert img.sizex == pytest.approx(nx * sec_pix, rel=1e-9)assert img.sizey == pytest.approx(ny * sec_pix, rel=1e-9)# Decode PNG and confirm dimensions still match the source pixel grid.b64 = img.source.removeprefix("data:image/png;base64,")png_bytes = base64.b64decode(b64)png = PILImage.open(io.BytesIO(png_bytes))assert png.size == (nx, ny)13 unmodified linesny, _ = datacube.spatial_shapesec_pix = pixel_scale_arcsec(datacube.wcs)cy = (ny - 1) / 2.0centroids = fig.data[-1]expected_ys = [(c.y0 - cy) * sec_pix for c in clump_list]for got, exp in zip(centroids.y, expected_ys, strict=True):assert got == pytest.approx(exp, rel=1e-9, abs=1e-12)def test_data_order_preserves_clickable_first(self, store: DataStore):"""app.js relies on data[0] being the click target; centroids are last."""fig = self._build(store)assert fig.data[0].type == "heatmap"# Last trace must be the centroid scatter so fig.data.pop() in JS toggles it.assert fig.data[-1].name == "Centroids"def test_lupton_method_path(self, store: DataStore):fig = self._build(store, method="lupton")assert fig.data[0].type == "heatmap"assert fig.layout.images[0].source.startswith("data:image/png;base64,")def test_image_yanchor_bottom(self, store: DataStore):"""Image bottom must anchor at y=0 so it occupies y∈[0, ny] with overlays."""fig = self._build(store)img = fig.layout.images[0]assert img.yanchor == "bottom"def test_axes_locked_to_image_extent(self, store: DataStore):from jellyscope.data.model.coordinates import (8 unmodified linessec = pixel_scale_arcsec(datacube.wcs) if datacube.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)x = fig.layout.xaxisy = fig.layout.yaxisassert x.autorange is Falseassert y.autorange is Falseassert x.range == bounds.xassert y.range == bounds.yassert x.minallowed == bounds.x[0]assert x.maxallowed == bounds.x[1]assert y.minallowed == bounds.y[0]assert y.maxallowed == bounds.y[1]def test_meta_image_bounds_min_span(self, store: DataStore):from jellyscope.data.model.coordinates import (8 unmodified linessec = pixel_scale_arcsec(datacube.wcs) if datacube.wcs.has_celestial else Nonebounds = image_axis_bounds(nx, ny, sec)ib = fig.layout.meta.imageBoundsassert ib.x_min_span == bounds.x_min_spanassert ib.y_min_span == bounds.y_min_span
63 unmodified lines64656667686990 unmodified lines1601611621631641651661671681691701719 unmodified lines18118218318418518618718863 unmodified linesdata = resp.json()assert "properties" in dataassert "boundary" in datadef test_pixel_clump_lookup(client):90 unmodified linesfrom astropy import units as ufrom astropy.coordinates import SkyCoorddetail_a = client.get(f"{BASE}/clumps/0").json()detail_b = client.get(f"{BASE}/clumps/1").json()ra_a = float(detail_a["properties"]["RA (deg)"])dec_a = float(detail_a["properties"]["Dec (deg)"])ra_b = float(detail_b["properties"]["RA (deg)"])dec_b = float(detail_b["properties"]["Dec (deg)"])expected = (SkyCoord(ra=ra_a * u.deg, dec=dec_a * u.deg).separation(SkyCoord(ra=ra_b * u.deg, dec=dec_b * u.deg))9 unmodified linesdef test_clump_detail_has_radec(client):resp = client.get(f"{BASE}/clumps/0")props = resp.json()["properties"]assert "RA (deg)" in propsassert "Dec (deg)" in propsassert props["RA (deg)"] != "—"assert props["Dec (deg)"] != "—"63 unmodified lines646566676869707190 unmodified lines1621631641651661671681691701711721731741751769 unmodified lines18618718818919019119219319463 unmodified linesdata = resp.json()assert "properties" in dataassert "boundary" in dataassert isinstance(data["properties"]["entries"], list)assert len(data["properties"]["entries"]) > 0def test_pixel_clump_lookup(client):90 unmodified linesfrom astropy import units as ufrom astropy.coordinates import SkyCoorddef _lookup(entries: list[dict], label: str) -> str:return next(e["value"] for e in entries if e["label"] == label)detail_a = client.get(f"{BASE}/clumps/0").json()["properties"]["entries"]detail_b = client.get(f"{BASE}/clumps/1").json()["properties"]["entries"]ra_a = float(_lookup(detail_a, "RA (deg)"))dec_a = float(_lookup(detail_a, "Dec (deg)"))ra_b = float(_lookup(detail_b, "RA (deg)"))dec_b = float(_lookup(detail_b, "Dec (deg)"))expected = (SkyCoord(ra=ra_a * u.deg, dec=dec_a * u.deg).separation(SkyCoord(ra=ra_b * u.deg, dec=dec_b * u.deg))9 unmodified linesdef test_clump_detail_has_radec(client):resp = client.get(f"{BASE}/clumps/0")entries = resp.json()["properties"]["entries"]by_label = {e["label"]: e["value"] for e in entries}assert "RA (deg)" in by_labelassert "Dec (deg)" in by_labelassert by_label["RA (deg)"] != "—"assert by_label["Dec (deg)"] != "—"
src/jellyscope/data/data_store.py+6-4
src/jellyscope/data/model/clumps.py+1-1
src/jellyscope/data/model/coordinates.py+33-21
src/jellyscope/model/display.pyAdded+21
src/jellyscope/model/plotly.pyAdded+172
src/jellyscope/model/schemas.py+7-6
src/jellyscope/visualization/_viz_helpers.py+55-47
src/jellyscope/visualization/image_viewer.py+105-85
src/jellyscope/visualization/properties_panel.py+22-20
src/jellyscope/visualization/rgb_composite.py+63-36
src/jellyscope/web/routes.py+8-10
src/jellyscope/web/static/app.js+2-3
tests/coordinates/test_coordinates.py+15-15
tests/visualization/test_image_viewer.py+13-13
tests/visualization/test_rgb_composite.py+39-39
tests/web/test_routes.py+17-11