Spaces:
Sleeping
Sleeping
Commit ·
d4d91aa
1
Parent(s): 88b9f21
fix sonarqube findings
Browse filesFiles changed (8)
- scripts/demo_viewer.pyDeleted-15
- src/jellyscope/data/model/clumps.py+1-1
- src/jellyscope/visualization/_viz_helpers.pyAdded+116
- src/jellyscope/visualization/image_viewer.py+97-135
- src/jellyscope/visualization/rgb_composite.py+28-96
- src/jellyscope/web/static/app.js+5-9
- tests/coordinates/test_coordinates.py+2-2
- tests/visualization/test_image_viewer.py+5-5
123456789101112131415from pathlib import Path
import plotly.graph_objects as go
from jellyscope.config import JellyscopeConfigfrom jellyscope.data.data_store import DataStorefrom jellyscope.visualization.image_viewer import build_viewer_figure
config = JellyscopeConfig(data_dir=Path("data"))store = DataStore.get(config)dc = store.get_datacube("nircam")
fig_dict = build_viewer_figure(dc, channel_index=0, clumps=store.clumps, selected_ids=[0, 1])fig1 = go.Figure(fig_dict)fig1.show()160 unmodified lines161162163164164165166167160 unmodified lines return self._boundaries[clump_id]
mask = self._pixels_masks[clump_id] ys, xs = np.where(mask) ys, xs = np.nonzero(mask)
# Handle edge case: small clumps cannot form a hull if len(xs) < 3:123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116"""Shared visualization helpers: dark-theme colors, customdata grid, axis layout.
Private to the visualization package — kept here to dedupe the per-cellRA/Dec customdata loop and the layout dict shared between the heatmap andRGB figure builders."""
from typing import Any
import numpy as npfrom astropy.wcs import WCS
from jellyscope.data.model.coordinates import ( ImageAxisBounds, pixel_to_skycoord,)
# Shared dark-theme colors used by both image_viewer and rgb_composite layouts.GRAY: str = "#cccccc"DARK_GRAY: str = "#999"SOFT_BLACK: str = "#333"DARK_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: WCS) -> list[list[list[float | int | None]]]: """Per-cell ``[i, j, ra_deg|None, dec_deg|None]`` grid; shape ``(ny, nx, 4)``.
Vectorizes ``pixel_to_skycoord`` over a meshgrid and returns Python lists so non-finite values serialize as JSON ``null``. """ xx_pix, yy_pix = np.meshgrid(np.arange(nx, dtype=np.float64), np.arange(ny, dtype=np.float64)) try: sky = pixel_to_skycoord(xx_pix, yy_pix, wcs) ra = np.asarray(sky.ra.deg, dtype=np.float64) dec = np.asarray(sky.dec.deg, dtype=np.float64) except Exception: # pragma: no cover - defensive ra = np.full((ny, nx), np.nan) dec = np.full((ny, nx), np.nan)
customdata: list[list[list[float | int | None]]] = [] for j in range(ny): row_cd: list[list[float | int | None]] = [] for i in range(nx): r = ra[j, i] d = dec[j, i] row_cd.append( [ int(i), int(j), float(r) if np.isfinite(r) else None, float(d) if np.isfinite(d) else None, ] ) customdata.append(row_cd) return customdata
def build_dark_axis_layout( *, title_text: str, axis_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, "scaleanchor": "y", "constrain": "domain", "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"], } }, }11 unmodified lines121314151516171819202122232425262223242526272829131 unmodified lines16116216316416516616716816516616716816917017117217317417517617717817918018118218318418518618718818919019119219316917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021119621221321421519920021621721820320421922022122222322422522622722822923023123223323423523623723823924024124224324424524624713 unmodified lines26126226322722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028126426526626726826927027127227327427527627727827922 unmodified lines30230330431030530630730831 unmodified lines3403413423483493433443456 unmodified lines35235335436236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739835535635735835936036136211 unmodified lines arcsec_axis, image_axis_bounds, pixel_scale_arcsec, pixel_to_skycoord, 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"_BLUE: str = "#00ccff"_WHITE: str = "#ffffff"_GRAY: str = "#cccccc"_DARK_GRAY: str = "#999"_SOFT_BLACK: str = "#333"_DARK_BLUE: str = "#1a1a2e"_SOFT_DARK_BLUE: str = "#16213e"
def _estimate_background(data: np.ndarray) -> tuple[float, float]:131 unmodified lines sec_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>"
# Vectorized RA/Dec for every pixel via pixel_to_world(meshgrid). xx_pix, yy_pix = np.meshgrid( np.arange(nx, dtype=np.float64), np.arange(ny, dtype=np.float64) ) try: sky = pixel_to_skycoord(xx_pix, yy_pix, wcs) ra = np.asarray(sky.ra.deg, dtype=np.float64) dec = np.asarray(sky.dec.deg, dtype=np.float64) except Exception: # pragma: no cover - defensive ra = np.full((ny, nx), np.nan) dec = np.full((ny, nx), np.nan)
# Plotly customdata for heatmap: shape (ny, nx, k); k=4 here. # Use Python lists so non-finite values serialize as null/None. customdata: list[list[list[float | int | None]]] = [] for j in range(ny): row_cd: list[list[float | int | None]] = [] for i in range(nx): r = ra[j, i] d = dec[j, i] row_cd.append( [ int(i), int(j), float(r) if np.isfinite(r) else None, float(d) if np.isfinite(d) else None, ] ) customdata.append(row_cd) return trace
def _build_clump_boundary_trace( cid: int, boundary: list[tuple[float, float]], c: ClumpProperties, *, is_selected: bool, has_sky: bool, sec_pix: float, cx: 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]
if has_sky: xs_plot = [(x - cx) * sec_pix for x in xs_pix] ys_plot = [(y - cy) * sec_pix for y in ys_pix] else: xs_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 None if customdata is not None: trace["customdata"] = customdata trace["hovertemplate"] = ( "pix: (%{customdata[0]:d}, %{customdata[1]:d})<br>" 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}°<br>" "flux: %{z:.4f}<extra></extra>" "Dec: %{customdata[3]:.6f}°<extra></extra>" ) else: trace["hovertemplate"] = "x: %{x}<br>y: %{y}<br>flux: %{z:.4f}<extra></extra>"
trace["hoverinfo"] = "text" trace["text"] = f"Clump {cid} ({c.component})" return trace
def _clump_radec_customdata( xs_pix: list[float], ys_pix: list[float], wcs: WCS | None) -> list[list[float | None]] | None: """Per-vertex ``[x_pix, y_pix, ra|None, dec|None]``; ``None`` if conversion fails.""" if wcs is None: return None try: ra_arr, dec_arr, finite = pixels_to_radec_arrays(xs_pix, ys_pix, wcs) except Exception: # pragma: no cover - defensive return None return [ [ float(xp), float(yp), float(ra) if ok else None, float(dec) if ok else None, ] for xp, yp, ra, dec, ok in zip(xs_pix, ys_pix, ra_arr, dec_arr, finite, strict=True) ]
def create_clump_boundary_traces( clumps: ClumpCatalog, selected_ids: list[int] | None = None,13 unmodified lines
traces: list[dict[str, Any]] = [] for cid, boundary in clumps.get_all_boundaries().items(): xs_pix = [p[0] for p in boundary] ys_pix = [p[1] for p in boundary] is_selected = cid in select c: ClumpProperties = clumps.get_clump_by_id(cid)
if has_sky: xs_plot = [(x - cx) * sec_pix for x in xs_pix] ys_plot = [(y - cy) * sec_pix for y in ys_pix] else: xs_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, }
if has_sky: try: ra_arr, dec_arr, finite = pixels_to_radec_arrays(xs_pix, ys_pix, wcs) customdata = [ [ float(xp), float(yp), float(ra) if ok else None, float(dec) if ok else None, ] for xp, yp, ra, dec, ok in zip( xs_pix, ys_pix, ra_arr, dec_arr, finite, strict=True ) ] trace["customdata"] = customdata trace["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>" ) except Exception: # pragma: no cover - defensive trace["hoverinfo"] = "text" trace["text"] = f"Clump {cid} ({c.component})" else: trace["hoverinfo"] = "text" trace["text"] = f"Clump {cid} ({c.component})"
traces.append(trace) traces.append( _build_clump_boundary_trace( cid, boundary, clumps.get_clump_by_id(cid), is_selected=cid in select, has_sky=has_sky, sec_pix=sec_pix, cx=cx, cy=cy, wcs=wcs, ) ) return traces
22 unmodified lines "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}, "textfont": {"color": GRAY, "size": 9}, "name": "Centroids", "showlegend": False, }31 unmodified lines ny, nx = slice_data.shape sec_pix = pixel_scale_arcsec(datacube.wcs) if has_sky else None bounds = image_axis_bounds(nx, ny, sec_pix) x_min, x_max = bounds["x"] y_min, y_max = bounds["y"]
heatmap: dict[str, Any] = create_galaxy_heatmap( slice_data, colorscale, stretch, wcs=datacube.wcs6 unmodified lines # *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] = { "title": { "text": f"{datacube.name} \u2014 {filter_name}", "font": {"color": _GRAY}, }, "xaxis": { "title": axis_label_x, "scaleanchor": "y", "constrain": "domain", "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"], } }, } 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}22 unmodified lines2324252626272829303132333 unmodified lines373839363738394041404142186 unmodified lines22923023123423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726823223323423523616 unmodified lines25325425529129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234325625725825926026126226326426526626726826927027127227327427527634427727822 unmodified lines image_arcsec_extent, image_axis_bounds, pixel_scale_arcsec, pixel_to_skycoord,)from jellyscope.visualization._viz_helpers import ( RADEC_HOVER_PREFIX, build_dark_axis_layout, build_radec_customdata_grid,)from jellyscope.visualization.image_viewer import ( _estimate_background,3 unmodified lines
RGBMethod = Literal["percentile_asinh", "lupton"]
_GRAY: str = "#cccccc"_DARK_GRAY: str = "#999"_SOFT_BLACK: str = "#333"_DARK_BLUE: str = "#1a1a2e"_SOFT_DARK_BLUE: str = "#16213e"
def lupton_rgb_composite( r_data: np.ndarray,186 unmodified lines 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()
# Per-cell pixel + RA/Dec for hover. xx_pix, yy_pix = np.meshgrid( np.arange(nx, dtype=np.float64), np.arange(ny, dtype=np.float64) ) try: sky = pixel_to_skycoord(xx_pix, yy_pix, datacube.wcs) ra = np.asarray(sky.ra.deg, dtype=np.float64) dec = np.asarray(sky.dec.deg, dtype=np.float64) except Exception: # pragma: no cover - defensive ra = np.full((ny, nx), np.nan) dec = np.full((ny, nx), np.nan)
customdata: list[list[list[float | int | None]]] = [] for j in range(ny): row_cd: list[list[float | int | None]] = [] for i in range(nx): r = ra[j, i] d = dec[j, i] row_cd.append( [ int(i), int(j), float(r) if np.isfinite(r) else None, float(d) if np.isfinite(d) else None, ] ) customdata.append(row_cd) click_target["customdata"] = customdata click_target["hovertemplate"] = ( "pix: (%{customdata[0]:d}, %{customdata[1]:d})<br>" 'sky: (%{x:.3f}", %{y:.3f}")<br>' "RA: %{customdata[2]:.6f}°<br>" "Dec: %{customdata[3]:.6f}°<extra></extra>" ) click_target["customdata"] = build_radec_customdata_grid(nx, ny, datacube.wcs) click_target["hovertemplate"] = RADEC_HOVER_PREFIX + "<extra></extra>" else: click_target["hoverinfo"] = "skip"
16 unmodified lines axis_label_y = "y (pixels)"
bounds = image_axis_bounds(nx, ny, sec_pix) x_min, x_max = bounds["x"] y_min, y_max = bounds["y"]
layout: dict[str, Any] = { "title": { "text": f"RGB: {r_name} / {g_name} / {b_name}", "font": {"color": _GRAY}, }, "xaxis": { "title": axis_label_x, "scaleanchor": "y", "constrain": "domain", "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"], } }, "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", } ],
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}599 unmodified lines60060160260360360460560644 unmodified lines65165265365465565665765865465565665765828 unmodified lines68768868969369469069169269326 unmodified lines720721722727723724725726599 unmodified lines// image's pixel resolution.function _readBounds(viewer, axisName) { const axis = viewer.layout?.[axisName]; if (!axis || !axis.range) return null; if (!axis?.range) return null; const {minallowed, maxallowed, range} = axis; if (minallowed === undefined || maxallowed === undefined) return null; const [r0, r1] = range;44 unmodified lines}
function _cursorOnAxis(axis, pixel, fallback) { try { const v = axis?.p2d?.(pixel); if (typeof v === "number" && Number.isFinite(v)) return v; } catch (_) {} return fallback; const v = axis?.p2d?.(pixel); return (typeof v === "number" && Number.isFinite(v)) ? v : fallback;}
function _zoomOnWheel(e) {28 unmodified lines// double-click). Plotly fires plotly_relayout *after* applying the range; if// the new range is below min_span we relayout once more to grow back up to// min_span. The __clamping flag prevents feedback loops.function _relayoutClampGuard(eventData) { const div = this;function _relayoutClampGuard(div, eventData) { if (div.__clamping) return;
const xRangeChanged = "xaxis.range" in eventData ||26 unmodified linesfunction attachZoomOutLock(viewer) { if (viewer.__zoomOutLockAttached) return; viewer.addEventListener("wheel", _zoomOnWheel, {capture: true, passive: false}); viewer.on("plotly_relayout", _relayoutClampGuard); viewer.on("plotly_relayout", (ed) => _relayoutClampGuard(viewer, ed)); viewer.__zoomOutLockAttached = true;}
155 unmodified lines156157158159160159160161162163155 unmodified lines bounds = image_axis_bounds(nx, ny, None) assert bounds["x"] == (0.0, float(nx)) assert bounds["y"] == (0.0, float(ny)) assert bounds["x_min_span"] == 5.0 assert bounds["y_min_span"] == 5.0 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():19 unmodified lines20212223242324252627282930293031323316 unmodified lines505152535354555619 unmodified lines def test_all_nan_returns_defaults(self): data = np.full((10, 10), np.nan) median, std = _estimate_background(data) assert median == 0.0 assert std == 1.0 assert np.isclose(median, 0.0, rtol=1e-09, atol=1e-09) assert np.isclose(std, 1.0, rtol=1e-09, atol=1e-09)
def test_empty_array(self): data = np.array([]) median, std = _estimate_background(data) assert median == 0.0 assert std == 1.0 assert np.isclose(median, 0.0, rtol=1e-09, atol=1e-09) assert np.isclose(std, 1.0, rtol=1e-09, atol=1e-09)
class TestLuptonAsinhStretch:16 unmodified lines def test_all_nan_returns_zeros(self): data = np.full((10, 10), np.nan) result = _lupton_asinh_stretch(data) assert np.all(result == 0.0) assert np.all(np.isclose(result, 0.0, rtol=1e-09, atol=1e-09))
def test_uniform_array(self): data = np.full((20, 20), 42.0)scripts/demo_viewer.pyDeleted-15
src/jellyscope/data/model/clumps.py+1-1
src/jellyscope/visualization/_viz_helpers.pyAdded+116
src/jellyscope/visualization/image_viewer.py+97-135
src/jellyscope/visualization/rgb_composite.py+28-96
src/jellyscope/web/static/app.js+5-9
tests/coordinates/test_coordinates.py+2-2
tests/visualization/test_image_viewer.py+5-5