Spaces:
Sleeping
Sleeping
Commit ·
069fa26
1
Parent(s): 0339d09
start from scratch
Browse filesFiles changed (28)
- src/jellyscope/__init__.pyDeleted-3
- src/jellyscope/analysis/__init__.pyDeleted-1
- src/jellyscope/analysis/spectral.pyDeleted-62
- src/jellyscope/analysis/statistics.pyDeleted-50
- src/jellyscope/cli.pyDeleted-33
- src/jellyscope/config.pyDeleted-48
- src/jellyscope/data/__init__.pyDeleted-1
- src/jellyscope/data/cache.pyDeleted-57
- src/jellyscope/data/clumps.pyDeleted-159
- src/jellyscope/data/fits_handler.pyDeleted-82
- src/jellyscope/visualization/__init__.pyDeleted-1
- src/jellyscope/visualization/image_viewer.pyDeleted-136
- src/jellyscope/visualization/properties_panel.pyDeleted-19
- src/jellyscope/visualization/spectrum_plot.pyDeleted-129
- src/jellyscope/web/__init__.pyDeleted-28
- src/jellyscope/web/routes.pyDeleted-190
- src/jellyscope/web/static/app.jsDeleted-249
- src/jellyscope/web/static/style.cssDeleted-279
- src/jellyscope/web/templates/index.htmlDeleted-85
- tests/__init__.pyDeleted
- tests/conftest.pyDeleted-34
- tests/test_cache.pyDeleted-31
- tests/test_cli.pyDeleted-46
- tests/test_clumps.pyDeleted-133
- tests/test_fits_handler.pyDeleted-69
- tests/test_routes.pyDeleted-134
- tests/test_spectral.pyDeleted-44
- tests/test_statistics.pyDeleted-44
123"""Jellyscope: Interactive visualization of JWST jellyfish galaxy datacubes."""
__version__ = "0.1.0"1"""Analysis subpackage: spectral extraction and statistics."""1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162"""Spectral extraction from datacubes for pixels, clumps, and arbitrary regions."""
import numpy as np
from ..config import NIRCAM_WAVELENGTHSfrom ..data.clumps import ClumpCatalogfrom ..data.fits_handler import DataCube
def _wavelengths_for(filter_names: list[str]) -> list[float]: """Map filter names to central wavelengths in microns.""" return [NIRCAM_WAVELENGTHS.get(f, 0.0) for f in filter_names]
def extract_pixel_spectrum(datacube: DataCube, x: int, y: int) -> dict: """Extract spectrum at a single pixel.
Returns dict with filter_names, wavelengths, and fluxes arrays. """ fluxes = datacube.get_spectrum_at_pixel(x, y) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "fluxes": [float(v) if not np.isnan(v) else None for v in fluxes], "n_pixels": 1, }
def extract_clump_spectrum(datacube: DataCube, clumps: ClumpCatalog, clump_id: int) -> dict: """Mean spectrum for a clump region.""" mask = clumps.get_pixel_mask(clump_id) mean_flux, std_flux = datacube.get_mean_spectrum_for_mask(mask) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [float(v) if not np.isnan(v) else None for v in mean_flux], "std_flux": [float(v) if not np.isnan(v) else None for v in std_flux], "n_pixels": int(mask.sum()), "clump_id": clump_id, }
def extract_region_spectrum(datacube: DataCube, mask: np.ndarray) -> dict: """Mean spectrum for an arbitrary boolean mask (from lasso/rectangle selection).""" n_pixels = int(mask.sum()) if n_pixels == 0: n_ch = datacube.n_channels return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [None] * n_ch, "std_flux": [None] * n_ch, "n_pixels": 0, } mean_flux, std_flux = datacube.get_mean_spectrum_for_mask(mask) return { "filter_names": datacube.filter_names, "wavelengths": _wavelengths_for(datacube.filter_names), "mean_flux": [float(v) if not np.isnan(v) else None for v in mean_flux], "std_flux": [float(v) if not np.isnan(v) else None for v in std_flux], "n_pixels": n_pixels, }1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950"""Summary statistics for selected regions."""
import numpy as np
from ..data.clumps import ClumpCatalogfrom ..data.fits_handler import DataCube
def compute_region_stats(datacube: DataCube, mask: np.ndarray, channel_index: int) -> dict: """Compute statistics for a spatial region at a given filter channel.""" slice_data = datacube.get_slice(channel_index) values = slice_data[mask] valid = values[~np.isnan(values)] if len(valid) == 0: return { "filter": datacube.filter_names[channel_index], "n_pixels": 0, "mean": None, "median": None, "std": None, "min": None, "max": None, "sum": None, } return { "filter": datacube.filter_names[channel_index], "n_pixels": len(valid), "mean": float(np.mean(valid)), "median": float(np.median(valid)), "std": float(np.std(valid)), "min": float(np.min(valid)), "max": float(np.max(valid)), "sum": float(np.sum(valid)), }
def compute_clump_summary(datacube: DataCube, clumps: ClumpCatalog, clump_id: int) -> dict: """Full summary: clump properties + per-channel statistics.""" props = clumps.get_clump(clump_id) mask = clumps.get_pixel_mask(clump_id) channel_stats = [compute_region_stats(datacube, mask, i) for i in range(datacube.n_channels)] return { "clump_id": clump_id, "component": props.component, "area_pix": props.area_pix, "area_kpc2": props.area_kpc2, "r_eff_kpc": props.r_eff_kpc, "inside": props.inside, "channel_stats": channel_stats, }123456789101112131415161718192021222324252627282930313233"""Command-line entry point for Jellyscope."""
import argparsefrom pathlib import Path
from .config import JellyscopeConfigfrom .web import create_app
def main() -> None: parser = argparse.ArgumentParser(description="Jellyscope: JWST Jellyfish Galaxy Explorer") parser.add_argument("--host", default="127.0.0.1", help="Server host (default: 127.0.0.1)") parser.add_argument("--port", type=int, default=5000, help="Server port (default: 5000)") parser.add_argument( "--data-dir", default="data", help="Path to data directory (default: data)" ) parser.add_argument("--no-debug", action="store_true", help="Disable debug mode") args = parser.parse_args()
config = JellyscopeConfig( data_dir=Path(args.data_dir), host=args.host, port=args.port, debug=not args.no_debug, ) app = create_app(config) print(f"Starting Jellyscope on http://{config.host}:{config.port}") print(f"Data directory: {config.data_dir.resolve()}") app.run(host=config.host, port=config.port, debug=config.debug)
if __name__ == "__main__": main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748"""Application configuration with sensible defaults."""
from dataclasses import dataclass, fieldfrom pathlib import Path
# JWST NIRCam filter central wavelengths in micronsNIRCAM_WAVELENGTHS: dict[str, float] = { "F070W": 0.704, "F090W": 0.901, "F115W": 1.154, "F140M": 1.404, "F150W": 1.501, "F162M": 1.627, "F182M": 1.845, "F200W": 1.990, "F210M": 2.093, "F250M": 2.503, "F277W": 2.786, "F300M": 2.996, "F335M": 3.365, "F356W": 3.563, "F360M": 3.621, "F410M": 4.092, "F430M": 4.280, "F444W": 4.421, "F460M": 4.624, "F480M": 4.834,}
@dataclassclass JellyscopeConfig: """Configuration for the Jellyscope application.
The data_dir can point to a flat directory (backward-compatible with toy data) or contain subdirectories for multiple datasets. """
data_dir: Path = field(default_factory=lambda: Path("data")) datacube_file: str = "cut_datacube_nircam.fits" datacube_matched_file: str = "cut_datacube_nircam_matched.fits" clumps_properties_file: str = "clumps_properties.csv" clumps_pixels_file: str = "clumps_pixels.csv" host: str = "127.0.0.1" port: int = 5000 debug: bool = True default_colorscale: str = "Viridis" filter_wavelengths: dict[str, float] = field(default_factory=lambda: dict(NIRCAM_WAVELENGTHS))1"""Data loading and processing subpackage."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657"""Data store: pre-loads and caches datacubes and clump catalog."""
from pathlib import Path
from ..config import JellyscopeConfigfrom .clumps import ClumpCatalogfrom .fits_handler import DataCube
class DataStore: """Holds loaded datacubes and clump catalog in memory.
For small datasets this loads everything eagerly. Can be extended with lazy-loading / LRU eviction for larger collections. """
_instance: "DataStore | None" = None
def __init__(self, config: JellyscopeConfig) -> None: self.config = config data = config.data_dir
self.datacubes: dict[str, DataCube] = {} self._load_datacube(data / config.datacube_file, "nircam") self._load_datacube(data / config.datacube_matched_file, "nircam_matched")
ref_dc = self.datacubes["nircam"] self.clumps = ClumpCatalog( data / config.clumps_properties_file, data / config.clumps_pixels_file, ref_dc.spatial_shape, )
def _load_datacube(self, path: Path, name: str) -> None: if path.exists(): self.datacubes[name] = DataCube(path)
def get_datacube(self, name: str) -> DataCube: if name not in self.datacubes: raise KeyError(f"Unknown datacube '{name}'. Available: {list(self.datacubes)}") return self.datacubes[name]
def list_datacubes(self) -> list[str]: return list(self.datacubes.keys())
@classmethod def get(cls, config: JellyscopeConfig | None = None) -> "DataStore": if cls._instance is None: if config is None: config = JellyscopeConfig() cls._instance = cls(config) return cls._instance
@classmethod def reset(cls) -> None: """Reset the singleton (useful for testing).""" cls._instance = None123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159"""Clump catalog: properties, pixel masks, and boundaries."""
from dataclasses import dataclassfrom pathlib import Path
import numpy as npimport pandas as pdfrom scipy.spatial import ConvexHull, QhullError
@dataclassclass ClumpProperties: """Physical properties of a single detected clump."""
clump_id: int area_pix: int area_arcsec2: float r_eff_arcsec: float x0: float y0: float area_kpc2: float r_eff_kpc: float inside: bool component: str
class ClumpCatalog: """Manages the clump catalog: properties, pixel masks, and boundaries.
Dimensions are inferred from the datacube shape, not hardcoded. """
def __init__( self, properties_path: Path | str, pixels_path: Path | str, spatial_shape: tuple[int, int], ) -> None: self.ny, self.nx = spatial_shape
props_df = pd.read_csv(properties_path) self.clumps: dict[int, ClumpProperties] = {} for _, row in props_df.iterrows(): cid = int(row["clump_id"]) self.clumps[cid] = ClumpProperties( clump_id=cid, area_pix=int(row["area_pix"]), area_arcsec2=float(row["area_arcsec2"]), r_eff_arcsec=float(row["r_eff_arcsec"]), x0=float(row["x0"]), y0=float(row["y0"]), area_kpc2=float(row["area_kpc2"]), r_eff_kpc=float(row["r_eff_kpc"]), inside=bool(row["inside"]), component=str(row["component"]), )
pixels_df = pd.read_csv(pixels_path) self._pixel_masks: dict[int, np.ndarray] = {} self._clump_map = np.full((self.ny, self.nx), -1, dtype=np.int32)
for cid in self.clumps: mask = np.zeros((self.ny, self.nx), dtype=bool) cpx = pixels_df[pixels_df["clump_id"] == cid] for _, px in cpx.iterrows(): x, y = int(px["x"]), int(px["y"]) if 0 <= y < self.ny and 0 <= x < self.nx: mask[y, x] = True self._clump_map[y, x] = cid self._pixel_masks[cid] = mask
self._boundaries: dict[int, list[tuple[float, float]]] = {}
def get_clump(self, clump_id: int) -> ClumpProperties: return self.clumps[clump_id]
def get_pixel_mask(self, clump_id: int) -> np.ndarray: return self._pixel_masks[clump_id]
def get_combined_mask(self, clump_ids: list[int]) -> np.ndarray: """OR together masks for multiple clumps.""" mask = np.zeros((self.ny, self.nx), dtype=bool) for cid in clump_ids: mask |= self._pixel_masks[cid] return mask
def get_clump_at_pixel(self, x: int, y: int) -> int | None: """Return clump_id at pixel, or None if no clump there.""" if 0 <= y < self.ny and 0 <= x < self.nx: val = self._clump_map[y, x] return int(val) if val >= 0 else None return None
def get_boundary_coords(self, clump_id: int) -> list[tuple[float, float]]: """Return ordered boundary coordinates for a clump contour.
Uses ConvexHull for clean polygon outlines. Returns pixel coords as (x, y) tuples forming a closed polygon. """ if clump_id in self._boundaries: return self._boundaries[clump_id]
mask = self._pixel_masks[clump_id] ys, xs = np.where(mask)
if len(xs) < 3: coords = list(zip(xs.astype(float), ys.astype(float), strict=True)) coords.append(coords[0]) self._boundaries[clump_id] = coords return coords
points = np.column_stack([xs, ys]) try: hull = ConvexHull(points) verts = hull.vertices coords = [(float(points[v, 0]), float(points[v, 1])) for v in verts] coords.append(coords[0]) except QhullError: coords = list(zip(xs.astype(float), ys.astype(float), strict=True)) coords.append(coords[0])
self._boundaries[clump_id] = coords return coords
def get_all_boundaries(self) -> dict[int, list[tuple[float, float]]]: return {cid: self.get_boundary_coords(cid) for cid in self.clumps}
def list_clumps(self) -> list[ClumpProperties]: return list(self.clumps.values())
def filter_clumps( self, component: str | None = None, inside: bool | None = None, ) -> list[ClumpProperties]: result = self.list_clumps() if component is not None: result = [c for c in result if c.component == component] if inside is not None: result = [c for c in result if c.inside == inside] return result
def to_properties_list(self) -> list[dict]: """Return all clump properties as a list of dicts for JSON serialization.""" return [ { "clump_id": c.clump_id, "area_pix": c.area_pix, "area_arcsec2": round(c.area_arcsec2, 6), "r_eff_arcsec": round(c.r_eff_arcsec, 4), "x0": round(c.x0, 2), "y0": round(c.y0, 2), "area_kpc2": round(c.area_kpc2, 4), "r_eff_kpc": round(c.r_eff_kpc, 4), "inside": c.inside, "component": c.component, } for c in self.list_clumps() ]12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182"""FITS datacube I/O and slicing."""
from pathlib import Path
import numpy as npfrom astropy.io import fitsfrom astropy.wcs import WCS
class DataCube: """Manages a 3D FITS datacube (filter, y, x).
Reads all metadata (filter names, WCS, dimensions) from the FITS header, so it works with any datacube without hardcoded assumptions. """
def __init__(self, filepath: Path | str) -> None: filepath = Path(filepath) with fits.open(filepath) as hdul: self.data: np.ndarray = hdul[0].data.astype(np.float64) self.header = hdul[0].header self.wcs = WCS(self.header, naxis=2)
self.n_channels, self.ny, self.nx = self.data.shape self.filter_names = self._read_filter_names() self.name = filepath.stem
def _read_filter_names(self) -> list[str]: """Read filter names from FITS header keys FILTER1..FILTERn.""" names = [] for i in range(1, self.n_channels + 1): key = f"FILTER{i}" if key in self.header: names.append(str(self.header[key])) else: names.append(f"CH{i}") return names
@property def shape(self) -> tuple[int, int, int]: return self.data.shape
@property def spatial_shape(self) -> tuple[int, int]: return (self.ny, self.nx)
def get_slice(self, channel_index: int) -> np.ndarray: """Return 2D array (ny, nx) for a single filter channel.""" if not 0 <= channel_index < self.n_channels: raise IndexError(f"Channel index {channel_index} out of range [0, {self.n_channels})") return np.asarray(self.data[channel_index])
def get_slice_by_name(self, filter_name: str) -> np.ndarray: """Return 2D slice by filter name (e.g., 'F200W').""" idx = self.filter_names.index(filter_name) return self.get_slice(idx)
def get_spectrum_at_pixel(self, x: int, y: int) -> np.ndarray: """Return 1D array of length n_channels for a single spatial pixel.""" return self.data[:, y, x].copy()
def get_mean_spectrum_for_mask(self, mask: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """Compute mean and std spectrum across masked pixels.
Args: mask: Boolean 2D array (ny, nx).
Returns: Tuple of (mean_spectrum, std_spectrum), each 1D with n_channels elements. """ pixels = self.data[:, mask] # shape: (n_channels, n_pixels) mean = np.nanmean(pixels, axis=1) std = np.nanstd(pixels, axis=1) return mean, std
def to_json_slice(self, channel_index: int) -> list[list[float | None]]: """Return a 2D slice as nested lists, with NaN replaced by None for Plotly.""" arr = self.get_slice(channel_index) result = [] for row in arr: result.append([None if np.isnan(v) else float(v) for v in row]) return result1"""Visualization subpackage: Plotly figure builders."""123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136"""Plotly figure builders for the galaxy image viewer."""
import numpy as np
from ..data.clumps import ClumpCatalogfrom ..data.fits_handler import DataCube
def _asinh_stretch(data: np.ndarray) -> np.ndarray: """Apply arcsinh stretch to bring out faint features.
Standard in astronomy for handling extreme dynamic range. """ finite = data[np.isfinite(data)] if len(finite) == 0: return data vmin = np.percentile(finite, 1) vmax = np.percentile(finite, 99.5) clipped = np.clip(data, vmin, vmax) normalized = (clipped - vmin) / (vmax - vmin + 1e-10) stretched: np.ndarray = np.arcsinh(normalized * 10) / np.arcsinh(10) return stretched
def create_galaxy_heatmap( slice_data: np.ndarray, _filter_name: str, colorscale: str = "Viridis",) -> dict: """Create a Plotly heatmap trace for a datacube slice.""" stretched = _asinh_stretch(slice_data) z = [] for row in stretched: z.append([None if np.isnan(v) else float(v) for v in row]) return { "type": "heatmap", "z": z, "colorscale": colorscale, "hoverongaps": False, "hovertemplate": "x: %{x}<br>y: %{y}<br>flux: %{z:.4f}<extra></extra>", "showscale": True, "colorbar": {"title": "Flux (stretched)", "thickness": 15}, }
def create_clump_boundary_traces( clumps: ClumpCatalog, selected_ids: list[int] | None = None,) -> list[dict]: """Create Plotly scatter traces for clump boundaries.""" selected = set(selected_ids or []) traces = [] for cid, boundary in clumps.get_all_boundaries().items(): xs = [p[0] for p in boundary] ys = [p[1] for p in boundary] is_selected = cid in selected c = clumps.get_clump(cid) traces.append( { "type": "scatter", "x": xs, "y": ys, "mode": "lines", "line": { "color": "#ff4444" if is_selected else "#00ccff", "width": 2.5 if is_selected else 1.2, }, "name": f"Clump {cid}", "hoverinfo": "text", "text": f"Clump {cid} ({c.component})", "showlegend": False, } ) return traces
def create_centroid_markers(clumps: ClumpCatalog) -> dict: """Create scatter trace of clump centroids with labels.""" all_clumps = clumps.list_clumps() return { "type": "scatter", "x": [c.x0 for c in all_clumps], "y": [c.y0 for c in all_clumps], "mode": "markers+text", "marker": {"color": "#ffffff", "size": 5, "symbol": "x"}, "text": [str(c.clump_id) for c in all_clumps], "textposition": "top right", "textfont": {"color": "#cccccc", "size": 9}, "hovertemplate": ("Clump %{text}<br>x: %{x:.1f}<br>y: %{y:.1f}<extra></extra>"), "name": "Centroids", "showlegend": False, }
def build_viewer_figure( datacube: DataCube, channel_index: int, clumps: ClumpCatalog, selected_ids: list[int] | None = None, colorscale: str = "Viridis",) -> dict: """Assemble the complete Plotly figure: heatmap + boundaries + centroids.""" slice_data = datacube.get_slice(channel_index) filter_name = datacube.filter_names[channel_index]
heatmap = create_galaxy_heatmap(slice_data, filter_name, colorscale) boundaries = create_clump_boundary_traces(clumps, selected_ids) centroids = create_centroid_markers(clumps)
data = [heatmap, *boundaries, centroids]
layout = { "title": { "text": f"{datacube.name} \u2014 {filter_name}", "font": {"color": "#cccccc"}, }, "xaxis": { "title": "x (pixels)", "scaleanchor": "y", "constrain": "domain", "gridcolor": "#333", "color": "#999", }, "yaxis": { "title": "y (pixels)", "gridcolor": "#333", "color": "#999", }, "plot_bgcolor": "#1a1a2e", "paper_bgcolor": "#16213e", "font": {"color": "#cccccc"}, "margin": {"l": 50, "r": 20, "t": 40, "b": 50}, "dragmode": "pan", }
return {"data": data, "layout": layout}12345678910111213141516171819"""Format clump properties for display."""
from ..data.clumps import ClumpProperties
def format_clump_properties(clump: ClumpProperties) -> dict: """Format a single clump's properties for display in the UI.""" 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}", }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129"""Plotly figure builders for spectral energy distribution (SED) plots."""
def create_sed_figure(spectrum: dict, title: str = "Spectral Energy Distribution") -> dict: """Create a Plotly scatter plot of flux vs wavelength.
Args: spectrum: Dict with 'wavelengths', 'mean_flux' (or 'fluxes'), and optionally 'std_flux'. title: Plot title. """ wavelengths = spectrum["wavelengths"] fluxes = spectrum.get("mean_flux") or spectrum.get("fluxes", []) filter_names = spectrum.get("filter_names", [])
traces = [ { "type": "scatter", "x": wavelengths, "y": fluxes, "mode": "lines+markers", "marker": {"size": 7, "color": "#00ccff"}, "line": {"color": "#00ccff", "width": 2}, "text": filter_names, "hovertemplate": ( "%{text}<br>\u03bb: %{x:.3f} \u00b5m<br>Flux: %{y:.4e}<extra></extra>" ), "name": "SED", } ]
if "std_flux" in spectrum: std = spectrum["std_flux"] upper = [ (f + s) if f is not None and s is not None else None for f, s in zip(fluxes, std, strict=True) ] lower = [ (f - s) if f is not None and s is not None else None for f, s in zip(fluxes, std, strict=True) ] traces.append( { "type": "scatter", "x": wavelengths + wavelengths[::-1], "y": upper + lower[::-1], "fill": "toself", "fillcolor": "rgba(0, 204, 255, 0.15)", "line": {"color": "rgba(0,0,0,0)"}, "hoverinfo": "skip", "showlegend": False, "name": "\u00b11\u03c3", } )
layout = { "title": {"text": title, "font": {"color": "#cccccc"}}, "xaxis": { "title": "Wavelength (\u00b5m)", "gridcolor": "#333", "color": "#999", }, "yaxis": { "title": "Flux", "gridcolor": "#333", "color": "#999", }, "plot_bgcolor": "#1a1a2e", "paper_bgcolor": "#16213e", "font": {"color": "#cccccc"}, "margin": {"l": 60, "r": 20, "t": 40, "b": 50}, "showlegend": False, }
return {"data": traces, "layout": layout}
def create_multi_sed_figure(spectra: list[dict], labels: list[str]) -> dict: """Overlay multiple SEDs for comparison.""" colors = [ "#00ccff", "#ff4444", "#44ff44", "#ffaa00", "#ff44ff", "#44ffff", "#ffff44", "#aa44ff", ] traces = [] for i, (spec, label) in enumerate(zip(spectra, labels, strict=True)): color = colors[i % len(colors)] fluxes = spec.get("mean_flux") or spec.get("fluxes", []) traces.append( { "type": "scatter", "x": spec["wavelengths"], "y": fluxes, "mode": "lines+markers", "marker": {"size": 6, "color": color}, "line": {"color": color, "width": 2}, "name": label, "text": spec.get("filter_names", []), "hovertemplate": ( f"{label}<br>%{{text}}<br>" "\u03bb: %{x:.3f} \u00b5m<br>Flux: %{y:.4e}<extra></extra>" ), } )
layout = { "title": {"text": "SED Comparison", "font": {"color": "#cccccc"}}, "xaxis": { "title": "Wavelength (\u00b5m)", "gridcolor": "#333", "color": "#999", }, "yaxis": { "title": "Flux", "gridcolor": "#333", "color": "#999", }, "plot_bgcolor": "#1a1a2e", "paper_bgcolor": "#16213e", "font": {"color": "#cccccc"}, "margin": {"l": 60, "r": 20, "t": 40, "b": 50}, "legend": {"font": {"color": "#cccccc"}}, }
return {"data": traces, "layout": layout}12345678910111213141516171819202122232425262728"""Flask application factory."""
from flask import Flask
from ..config import JellyscopeConfigfrom ..data.cache import DataStore
def create_app(config: JellyscopeConfig | None = None) -> Flask: """Create and configure the Flask application.""" if config is None: config = JellyscopeConfig()
app = Flask( __name__, static_folder="static", template_folder="templates", ) app.config["JELLYSCOPE"] = config
# Pre-load data into memory DataStore.get(config)
from .routes import bp
app.register_blueprint(bp)
return app123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190"""REST API endpoints and page routes."""
import numpy as npfrom flask import Blueprint, Response, jsonify, render_template, request
from ..analysis.spectral import ( extract_clump_spectrum, extract_pixel_spectrum, extract_region_spectrum,)from ..data.cache import DataStorefrom ..visualization.image_viewer import build_viewer_figurefrom ..visualization.properties_panel import format_clump_propertiesfrom ..visualization.spectrum_plot import create_multi_sed_figure, create_sed_figure
bp = Blueprint("api", __name__)
def _store() -> DataStore: return DataStore.get()
# --- Pages ---
@bp.route("/")def index() -> str: store = _store() return render_template( "index.html", datacubes=store.list_datacubes(), filters=store.get_datacube("nircam").filter_names, )
# --- Datacube info ---
@bp.route("/api/datacubes")def list_datacubes() -> Response: store = _store() return jsonify({"datacubes": store.list_datacubes()})
@bp.route("/api/filters/<datacube_name>")def list_filters(datacube_name: str) -> Response: dc = _store().get_datacube(datacube_name) from ..config import NIRCAM_WAVELENGTHS
filters = [] for i, name in enumerate(dc.filter_names): filters.append( { "index": i, "name": name, "wavelength": NIRCAM_WAVELENGTHS.get(name, 0.0), } ) return jsonify({"filters": filters})
# --- Image viewer ---
@bp.route("/api/viewer/<datacube_name>/<int:channel_index>")def get_viewer_figure(datacube_name: str, channel_index: int) -> Response: store = _store() dc = store.get_datacube(datacube_name) selected_str = request.args.get("selected", "") selected_ids = [int(x) for x in selected_str.split(",") if x.strip()] if selected_str else [] colorscale = request.args.get("colorscale", "Viridis") figure = build_viewer_figure(dc, channel_index, store.clumps, selected_ids, colorscale) return jsonify({"figure": figure, "filter_name": dc.filter_names[channel_index]})
# --- Clumps ---
@bp.route("/api/clumps")def list_clumps() -> Response: store = _store() component = request.args.get("component") inside_param = request.args.get("inside") is_inside: bool | None = None if inside_param is not None: is_inside = inside_param.lower() == "true" clumps = store.clumps.filter_clumps(component=component, inside=is_inside) return jsonify( { "clumps": [ { "clump_id": c.clump_id, "x0": round(c.x0, 2), "y0": round(c.y0, 2), "area_pix": c.area_pix, "component": c.component, "inside": c.inside, } for c in clumps ] } )
@bp.route("/api/clumps/<int:clump_id>")def get_clump(clump_id: int) -> Response: store = _store() clump = store.clumps.get_clump(clump_id) boundary = store.clumps.get_boundary_coords(clump_id) props = format_clump_properties(clump) return jsonify({"properties": props, "boundary": boundary})
@bp.route("/api/clumps/<int:clump_id>/spectrum/<datacube_name>")def get_clump_spectrum(clump_id: int, datacube_name: str) -> Response: store = _store() dc = store.get_datacube(datacube_name) spectrum = extract_clump_spectrum(dc, store.clumps, clump_id) figure = create_sed_figure(spectrum, f"Clump {clump_id} — SED") return jsonify({"spectrum": spectrum, "figure": figure})
# --- Pixel interaction ---
@bp.route("/api/pixel/<int:x>/<int:y>/clump")def get_pixel_clump(x: int, y: int) -> Response: store = _store() cid = store.clumps.get_clump_at_pixel(x, y) return jsonify({"clump_id": cid})
@bp.route("/api/pixel/<int:x>/<int:y>/spectrum/<datacube_name>")def get_pixel_spectrum(x: int, y: int, datacube_name: str) -> Response: store = _store() dc = store.get_datacube(datacube_name) spectrum = extract_pixel_spectrum(dc, x, y) figure = create_sed_figure(spectrum, f"Pixel ({x}, {y}) — SED") return jsonify({"spectrum": spectrum, "figure": figure})
# --- Region selection ---
@bp.route("/api/region/spectrum/<datacube_name>", methods=["POST"])def get_region_spectrum(datacube_name: str) -> Response: store = _store() dc = store.get_datacube(datacube_name) body = request.get_json()
mask = np.zeros(dc.spatial_shape, dtype=bool)
if "pixels" in body: for px in body["pixels"]: x, y = int(px[0]), int(px[1]) if 0 <= y < dc.ny and 0 <= x < dc.nx: mask[y, x] = True elif "rect" in body: r = body["rect"] x0, y0 = int(r["x0"]), int(r["y0"]) x1, y1 = int(r["x1"]), int(r["y1"]) x0, x1 = max(0, min(x0, x1)), min(dc.nx, max(x0, x1)) y0, y1 = max(0, min(y0, y1)), min(dc.ny, max(y0, y1)) mask[y0:y1, x0:x1] = True
spectrum = extract_region_spectrum(dc, mask) figure = create_sed_figure(spectrum, f"Selected Region ({spectrum['n_pixels']} px)") return jsonify({"spectrum": spectrum, "figure": figure})
# --- Multi-clump comparison ---
@bp.route("/api/compare/spectrum/<datacube_name>", methods=["POST"])def compare_spectra(datacube_name: str) -> Response: store = _store() dc = store.get_datacube(datacube_name) body = request.get_json() clump_ids = body.get("clump_ids", [])
spectra = [] labels = [] for cid in clump_ids: spec = extract_clump_spectrum(dc, store.clumps, cid) spectra.append(spec) c = store.clumps.get_clump(cid) labels.append(f"Clump {cid} ({c.component})")
figure = create_multi_sed_figure(spectra, labels) return jsonify({"figure": figure, "spectra": spectra})123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249/** * Jellyscope — Frontend controller * Manages state, API calls, Plotly rendering, and user interactions. */
const state = { datacube: "nircam", channel: 7, // F200W default selectedClumps: new Set(), colorscale: "Viridis", dragmode: "pan", clumps: [],};
const plotlyConfig = { responsive: true, displayModeBar: true, modeBarButtonsToRemove: ["toImage", "sendDataToCloud"], scrollZoom: true,};
// ─── Initialization ────────────────────────────────────────────────
async function init() { await loadClumpList(); await renderViewer(); setupEventListeners();}
function setupEventListeners() { document.getElementById("datacube-select").addEventListener("change", (e) => { state.datacube = e.target.value; renderViewer(); });
document.getElementById("filter-slider").addEventListener("input", (e) => { state.channel = parseInt(e.target.value); document.getElementById("filter-label").textContent = FILTERS[state.channel]; renderViewer(); });
document.getElementById("colorscale-select").addEventListener("change", (e) => { state.colorscale = e.target.value; renderViewer(); });
document.querySelectorAll(".mode-btn").forEach((btn) => { btn.addEventListener("click", () => { document.querySelectorAll(".mode-btn").forEach((b) => b.classList.remove("active")); btn.classList.add("active"); const mode = btn.dataset.mode; state.dragmode = mode; const viewer = document.getElementById("galaxy-viewer"); Plotly.relayout(viewer, { dragmode: mode }); }); });
document.getElementById("clump-filter").addEventListener("change", loadClumpList);}
// ─── Galaxy Viewer ─────────────────────────────────────────────────
async function renderViewer() { const selectedStr = Array.from(state.selectedClumps).join(","); const url = `/api/viewer/${state.datacube}/${state.channel}?selected=${selectedStr}&colorscale=${state.colorscale}`; const resp = await fetch(url); const data = await resp.json(); const fig = data.figure;
fig.layout.dragmode = state.dragmode;
const viewer = document.getElementById("galaxy-viewer"); await Plotly.react(viewer, fig.data, fig.layout, plotlyConfig);
// Attach click handler viewer.removeAllListeners?.("plotly_click"); viewer.on("plotly_click", onViewerClick); viewer.on("plotly_selected", onViewerSelected);}
async function onViewerClick(eventData) { if (!eventData.points || eventData.points.length === 0) return; const point = eventData.points[0]; const x = Math.round(point.x); const y = Math.round(point.y);
// Check if pixel belongs to a clump const resp = await fetch(`/api/pixel/${x}/${y}/clump`); const data = await resp.json();
if (data.clump_id !== null) { toggleClumpSelection(data.clump_id); } else { // Show pixel spectrum showPixelSpectrum(x, y); }}
async function onViewerSelected(eventData) { if (!eventData || !eventData.points || eventData.points.length === 0) return;
const pixels = eventData.points .filter((p) => p.curveNumber === 0) // Only heatmap points .map((p) => [Math.round(p.x), Math.round(p.y)]);
if (pixels.length === 0) return;
const resp = await fetch(`/api/region/spectrum/${state.datacube}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ pixels }), }); const data = await resp.json();
const specPlot = document.getElementById("spectrum-plot"); Plotly.react(specPlot, data.figure.data, data.figure.layout, plotlyConfig);
showPropertiesMessage(`Selected region: ${data.spectrum.n_pixels} pixels`);}
// ─── Clump Selection ───────────────────────────────────────────────
function toggleClumpSelection(clumpId) { if (state.selectedClumps.has(clumpId)) { state.selectedClumps.delete(clumpId); } else { state.selectedClumps.add(clumpId); } updateClumpListUI(); renderViewer();
const selected = Array.from(state.selectedClumps); if (selected.length === 0) { clearPanels(); } else if (selected.length === 1) { showClumpDetails(selected[0]); } else { showMultiClumpComparison(selected); }}
async function showClumpDetails(clumpId) { // Fetch properties and spectrum in parallel const [propsResp, specResp] = await Promise.all([ fetch(`/api/clumps/${clumpId}`), fetch(`/api/clumps/${clumpId}/spectrum/${state.datacube}`), ]); const propsData = await propsResp.json(); const specData = await specResp.json();
// Update properties panel const props = propsData.properties; let html = '<table class="prop-table">'; for (const [key, value] of Object.entries(props)) { html += `<tr><td>${key}</td><td>${value}</td></tr>`; } html += "</table>"; document.getElementById("properties-content").innerHTML = html;
// Update spectrum plot const specPlot = document.getElementById("spectrum-plot"); Plotly.react(specPlot, specData.figure.data, specData.figure.layout, plotlyConfig);}
async function showMultiClumpComparison(clumpIds) { const resp = await fetch(`/api/compare/spectrum/${state.datacube}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ clump_ids: clumpIds }), }); const data = await resp.json();
const specPlot = document.getElementById("spectrum-plot"); Plotly.react(specPlot, data.figure.data, data.figure.layout, plotlyConfig);
showPropertiesMessage(`Comparing ${clumpIds.length} clumps: ${clumpIds.join(", ")}`);}
async function showPixelSpectrum(x, y) { const resp = await fetch(`/api/pixel/${x}/${y}/spectrum/${state.datacube}`); const data = await resp.json();
const specPlot = document.getElementById("spectrum-plot"); Plotly.react(specPlot, data.figure.data, data.figure.layout, plotlyConfig);
showPropertiesMessage(`Pixel (${x}, ${y}) — no clump`);}
// ─── Clump List ────────────────────────────────────────────────────
async function loadClumpList() { const filter = document.getElementById("clump-filter").value; let url = "/api/clumps"; if (filter) url += `?component=${filter}`;
const resp = await fetch(url); const data = await resp.json(); state.clumps = data.clumps; renderClumpList();}
function renderClumpList() { const container = document.getElementById("clump-list"); let html = ""; for (const c of state.clumps) { const isSelected = state.selectedClumps.has(c.clump_id); const badgeClass = c.component === "disk" ? "disk" : "outside"; html += ` <div class="clump-item ${isSelected ? "selected" : ""}" onclick="toggleClumpSelection(${c.clump_id})"> <input type="checkbox" ${isSelected ? "checked" : ""} onclick="event.stopPropagation(); toggleClumpSelection(${c.clump_id})"> <span>Clump ${c.clump_id}</span> <span class="clump-badge ${badgeClass}">${c.component}</span> <span style="color: var(--text-secondary); font-size: 10px; margin-left: auto;"> ${c.area_pix}px </span> </div>`; } container.innerHTML = html;}
function updateClumpListUI() { const items = document.querySelectorAll(".clump-item"); items.forEach((item) => { const checkbox = item.querySelector("input[type=checkbox]"); const clumpId = parseInt(item.querySelector("span").textContent.replace("Clump ", "")); const isSelected = state.selectedClumps.has(clumpId); item.classList.toggle("selected", isSelected); if (checkbox) checkbox.checked = isSelected; });}
// ─── Helpers ───────────────────────────────────────────────────────
function showPropertiesMessage(msg) { document.getElementById("properties-content").innerHTML = `<p style="color: var(--accent); font-size: 12px;">${msg}</p>`;}
function clearPanels() { document.getElementById("properties-content").innerHTML = '<p class="placeholder">Click on a clump to see its properties</p>'; Plotly.purge(document.getElementById("spectrum-plot"));}
// ─── Start ─────────────────────────────────────────────────────────
document.addEventListener("DOMContentLoaded", init);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279/* Jellyscope — Dark theme for astronomical visualization */
:root { --bg-primary: #0f0f23; --bg-secondary: #16213e; --bg-panel: #1a1a2e; --text-primary: #e0e0e0; --text-secondary: #999; --accent: #00ccff; --accent-hover: #33ddff; --border: #2a2a4a; --danger: #ff4444;}
* { margin: 0; padding: 0; box-sizing: border-box;}
body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, monospace; background: var(--bg-primary); color: var(--text-primary); height: 100vh; overflow: hidden;}
header { background: var(--bg-secondary); padding: 8px 20px; display: flex; align-items: baseline; gap: 12px; border-bottom: 1px solid var(--border);}
header h1 { font-size: 18px; color: var(--accent); font-weight: 700;}
header .subtitle { font-size: 12px; color: var(--text-secondary);}
main { display: grid; grid-template-columns: 1fr 360px; height: calc(100vh - 41px); gap: 1px; background: var(--border);}
/* Galaxy Viewer */#viewer-section { background: var(--bg-primary); display: flex; flex-direction: column; overflow: hidden;}
#viewer-controls { display: flex; align-items: center; gap: 8px; padding: 6px 12px; background: var(--bg-secondary); font-size: 12px; border-bottom: 1px solid var(--border); flex-wrap: wrap;}
#viewer-controls label { color: var(--text-secondary);}
#viewer-controls select,#clump-filter { background: var(--bg-panel); color: var(--text-primary); border: 1px solid var(--border); border-radius: 4px; padding: 3px 6px; font-size: 12px;}
#filter-slider { width: 120px; accent-color: var(--accent);}
#filter-label { color: var(--accent); font-weight: 600; min-width: 50px;}
.separator { color: var(--border); margin: 0 4px;}
.mode-btn { background: var(--bg-panel); color: var(--text-secondary); border: 1px solid var(--border); border-radius: 4px; padding: 3px 10px; cursor: pointer; font-size: 12px; transition: all 0.15s;}
.mode-btn:hover { border-color: var(--accent); color: var(--text-primary);}
.mode-btn.active { background: var(--accent); color: #000; border-color: var(--accent); font-weight: 600;}
#galaxy-viewer { flex: 1; min-height: 0;}
/* Right panels */#right-panels { display: flex; flex-direction: column; background: var(--bg-primary); overflow: hidden;}
#right-panels section { background: var(--bg-panel); border-bottom: 1px solid var(--border); overflow: auto;}
#right-panels h2 { font-size: 13px; color: var(--accent); padding: 8px 12px; border-bottom: 1px solid var(--border); display: flex; justify-content: space-between; align-items: center; position: sticky; top: 0; background: var(--bg-panel); z-index: 1;}
/* Properties panel */#properties-panel { max-height: 220px;}
#properties-content { padding: 8px 12px; font-size: 12px;}
#properties-content .placeholder { color: var(--text-secondary); font-style: italic;}
.prop-table { width: 100%; border-collapse: collapse;}
.prop-table td { padding: 3px 0; font-size: 12px;}
.prop-table td:first-child { color: var(--text-secondary); width: 45%;}
.prop-table td:last-child { color: var(--text-primary); font-weight: 500;}
/* Clump list */#clump-list-panel { flex: 0 0 auto; max-height: 200px;}
#clump-list { padding: 4px 8px; font-size: 12px; max-height: 160px; overflow-y: auto;}
.clump-item { display: flex; align-items: center; gap: 6px; padding: 3px 4px; border-radius: 3px; cursor: pointer; transition: background 0.1s;}
.clump-item:hover { background: rgba(0, 204, 255, 0.1);}
.clump-item.selected { background: rgba(0, 204, 255, 0.2);}
.clump-item input[type="checkbox"] { accent-color: var(--accent);}
.clump-badge { font-size: 10px; padding: 1px 5px; border-radius: 3px; background: var(--bg-secondary); color: var(--text-secondary);}
.clump-badge.disk { color: #44ff44; border: 1px solid #44ff44;}
.clump-badge.outside { color: #ffaa00; border: 1px solid #ffaa00;}
/* Spectrum panel */#spectrum-panel { flex: 1; min-height: 200px; display: flex; flex-direction: column;}
#spectrum-plot { flex: 1; min-height: 180px;}
/* Scrollbar styling */::-webkit-scrollbar { width: 6px;}
::-webkit-scrollbar-track { background: var(--bg-primary);}
::-webkit-scrollbar-thumb { background: var(--border); border-radius: 3px;}
::-webkit-scrollbar-thumb:hover { background: var(--text-secondary);}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Jellyscope — JWST Jellyfish Galaxy Explorer</title> <script src="https://cdn.plot.ly/plotly-2.35.2.min.js"></script> <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}"></head><body> <header> <h1>Jellyscope</h1> <span class="subtitle">JWST Jellyfish Galaxy Explorer</span> </header>
<main> <!-- Left: Galaxy Viewer --> <section id="viewer-section"> <div id="viewer-controls"> <label for="datacube-select">Datacube:</label> <select id="datacube-select"> {% for dc in datacubes %} <option value="{{ dc }}">{{ dc }}</option> {% endfor %} </select>
<label for="filter-slider">Filter:</label> <input type="range" id="filter-slider" min="0" max="{{ filters|length - 1 }}" value="7" step="1"> <span id="filter-label">{{ filters[7] }}</span>
<label for="colorscale-select">Colors:</label> <select id="colorscale-select"> <option value="Viridis" selected>Viridis</option> <option value="Inferno">Inferno</option> <option value="Plasma">Plasma</option> <option value="Cividis">Cividis</option> <option value="Hot">Hot</option> <option value="Greys">Greys</option> </select>
<span class="separator">|</span>
<button id="btn-click" class="mode-btn active" data-mode="pan" title="Pan / Click to select clump">Pan</button> <button id="btn-select" class="mode-btn" data-mode="select" title="Rectangle selection">Rect</button> <button id="btn-lasso" class="mode-btn" data-mode="lasso" title="Lasso selection">Lasso</button> </div> <div id="galaxy-viewer"></div> </section>
<!-- Right panels --> <aside id="right-panels"> <!-- Properties --> <section id="properties-panel"> <h2>Properties</h2> <div id="properties-content"> <p class="placeholder">Click on a clump to see its properties</p> </div> </section>
<!-- Clump List --> <section id="clump-list-panel"> <h2>Clumps <select id="clump-filter" title="Filter clumps"> <option value="">All</option> <option value="disk">Disk</option> <option value="outside">Outside</option> </select> </h2> <div id="clump-list"></div> </section>
<!-- Spectrum --> <section id="spectrum-panel"> <h2>Spectral Energy Distribution</h2> <div id="spectrum-plot"></div> </section> </aside> </main>
<script> const FILTERS = {{ filters | tojson }}; </script> <script src="{{ url_for('static', filename='app.js') }}"></script></body></html>12345678910111213141516171819202122232425262728293031323334"""Shared test fixtures."""
from pathlib import Path
import pytest
from jellyscope.config import JellyscopeConfigfrom jellyscope.data.cache import DataStore
@pytest.fixture(scope="session")def config(): return JellyscopeConfig(data_dir=Path("data"))
@pytest.fixture(scope="session")def store(config): DataStore.reset() return DataStore.get(config)
@pytest.fixturedef app(config): from jellyscope.web import create_app
DataStore.reset() app = create_app(config) app.config["TESTING"] = True return app
@pytest.fixturedef client(app): return app.test_client()12345678910111213141516171819202122232425262728293031"""Tests for DataStore cache and app factory defaults."""
import pytest
from jellyscope.data.cache import DataStore
def test_unknown_datacube_raises(store): with pytest.raises(KeyError, match="Unknown datacube"): store.get_datacube("nonexistent")
def test_default_config_fallback(): DataStore.reset() try: store = DataStore.get() assert store is not None assert "nircam" in store.list_datacubes() finally: DataStore.reset()
def test_create_app_no_config(): DataStore.reset() try: from jellyscope.web import create_app
app = create_app() assert app is not None finally: DataStore.reset()12345678910111213141516171819202122232425262728293031323334353637383940414243444546"""Tests for CLI entry point."""
from unittest.mock import patch
from jellyscope.cli import main
def test_main_default_args(): with ( patch("sys.argv", ["jellyscope", "--data-dir", "data"]), patch("jellyscope.cli.create_app") as mock_create_app, ): mock_app = mock_create_app.return_value mock_app.run = lambda **kwargs: None main() mock_create_app.assert_called_once() config = mock_create_app.call_args[0][0] assert config.host == "127.0.0.1" assert config.port == 5000 assert config.debug is True
def test_main_custom_args(): with ( patch( "sys.argv", [ "jellyscope", "--host", "0.0.0.0", "--port", "8080", "--no-debug", "--data-dir", "data", ], ), patch("jellyscope.cli.create_app") as mock_create_app, ): mock_app = mock_create_app.return_value mock_app.run = lambda **kwargs: None main() config = mock_create_app.call_args[0][0] assert config.host == "0.0.0.0" assert config.port == 8080 assert config.debug is False123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133"""Tests for clump catalog."""
def test_clump_count(store): assert len(store.clumps.list_clumps()) == 23
def test_clump_properties(store): c = store.clumps.get_clump(0) assert c.clump_id == 0 assert c.area_pix == 121 assert c.component == "outside" assert c.inside is False
def test_pixel_mask(store): mask = store.clumps.get_pixel_mask(0) assert mask.shape == (221, 172) assert mask.dtype == bool assert mask.sum() == 121 # matches area_pix
def test_clump_at_pixel(store): # Clump 0 centroid is near (71.8, 19.9) cid = store.clumps.get_clump_at_pixel(72, 20) assert cid == 0
def test_no_clump_at_empty_pixel(store): cid = store.clumps.get_clump_at_pixel(0, 0) assert cid is None
def test_boundary_coords(store): boundary = store.clumps.get_boundary_coords(0) assert len(boundary) >= 3 # Closed polygon: first == last assert boundary[0] == boundary[-1]
def test_filter_by_component(store): disk = store.clumps.filter_clumps(component="disk") outside = store.clumps.filter_clumps(component="outside") assert all(c.component == "disk" for c in disk) assert all(c.component == "outside" for c in outside) assert len(disk) + len(outside) == 23
def test_combined_mask(store): mask = store.clumps.get_combined_mask([0, 1]) assert mask.sum() == 121 + 60 # area_pix of clump 0 + clump 1
def test_pixel_out_of_bounds(store): assert store.clumps.get_clump_at_pixel(-1, -1) is None assert store.clumps.get_clump_at_pixel(9999, 9999) is None
def test_boundary_cache_hit(store): b1 = store.clumps.get_boundary_coords(0) b2 = store.clumps.get_boundary_coords(0) assert b1 is b2
def test_small_clump_boundary(tmp_path): import pandas as pd
from jellyscope.data.clumps import ClumpCatalog
props_df = pd.DataFrame( [ { "clump_id": 99, "area_pix": 2, "area_arcsec2": 0.1, "r_eff_arcsec": 0.05, "x0": 5.0, "y0": 5.0, "area_kpc2": 0.01, "r_eff_kpc": 0.005, "inside": True, "component": "disk", } ] ) pixels_df = pd.DataFrame([{"clump_id": 99, "x": 5, "y": 5}, {"clump_id": 99, "x": 6, "y": 5}]) props_df.to_csv(tmp_path / "props.csv", index=False) pixels_df.to_csv(tmp_path / "pixels.csv", index=False)
catalog = ClumpCatalog(tmp_path / "props.csv", tmp_path / "pixels.csv", (10, 10)) boundary = catalog.get_boundary_coords(99) assert len(boundary) >= 2 assert boundary[0] == boundary[-1]
def test_qhull_error_fallback(store): from unittest.mock import patch
from scipy.spatial import QhullError
# Clear cache so we force recomputation store.clumps._boundaries.pop(0, None) with patch("jellyscope.data.clumps.ConvexHull", side_effect=QhullError("mock")): boundary = store.clumps.get_boundary_coords(0) assert len(boundary) >= 2 assert boundary[0] == boundary[-1]
def test_filter_by_inside(store): inside = store.clumps.filter_clumps(inside=True) outside = store.clumps.filter_clumps(inside=False) assert all(c.inside is True for c in inside) assert all(c.inside is False for c in outside) assert len(inside) + len(outside) == 23
def test_to_properties_list(store): props = store.clumps.to_properties_list() assert len(props) == 23 assert all(isinstance(p, dict) for p in props) keys = { "clump_id", "area_pix", "area_arcsec2", "r_eff_arcsec", "x0", "y0", "area_kpc2", "r_eff_kpc", "inside", "component", } assert all(keys <= set(p.keys()) for p in props)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Tests for FITS datacube handler."""
import numpy as np
def test_datacube_loads(store): dc = store.get_datacube("nircam") assert dc.shape == (20, 221, 172) assert dc.n_channels == 20 assert dc.ny == 221 assert dc.nx == 172
def test_filter_names_from_header(store): dc = store.get_datacube("nircam") assert dc.filter_names[0] == "F070W" assert dc.filter_names[-1] == "F480M" assert len(dc.filter_names) == 20
def test_get_slice(store): dc = store.get_datacube("nircam") s = dc.get_slice(0) assert s.shape == (221, 172) assert s.dtype == np.float64
def test_get_slice_by_name(store): dc = store.get_datacube("nircam") s = dc.get_slice_by_name("F200W") assert s.shape == (221, 172)
def test_get_spectrum_at_pixel(store): dc = store.get_datacube("nircam") spec = dc.get_spectrum_at_pixel(80, 100) assert spec.shape == (20,)
def test_to_json_slice(store): dc = store.get_datacube("nircam") js = dc.to_json_slice(0) assert len(js) == 221 assert len(js[0]) == 172 assert all(isinstance(v, (float, type(None))) for v in js[0])
def test_both_datacubes_available(store): assert "nircam" in store.list_datacubes() assert "nircam_matched" in store.list_datacubes()
def test_get_slice_out_of_range(store): import pytest
dc = store.get_datacube("nircam") with pytest.raises(IndexError, match="out of range"): dc.get_slice(99)
def test_fallback_filter_names(store): dc = store.get_datacube("nircam") # Temporarily remove a filter key and test fallback original = dc.header.get("FILTER1") del dc.header["FILTER1"] names = dc._read_filter_names() assert names[0] == "CH1" assert names[1] == dc.filter_names[1] # rest unchanged dc.header["FILTER1"] = original123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134"""Tests for Flask routes."""
import json
def test_index_page(client): resp = client.get("/") assert resp.status_code == 200 assert b"Jellyscope" in resp.data
def test_list_datacubes(client): resp = client.get("/api/datacubes") assert resp.status_code == 200 data = resp.get_json() assert "nircam" in data["datacubes"]
def test_list_filters(client): resp = client.get("/api/filters/nircam") assert resp.status_code == 200 data = resp.get_json() assert len(data["filters"]) == 20
def test_viewer_figure(client): resp = client.get("/api/viewer/nircam/7") assert resp.status_code == 200 data = resp.get_json() assert "figure" in data assert len(data["figure"]["data"]) > 0
def test_list_clumps(client): resp = client.get("/api/clumps") data = resp.get_json() assert len(data["clumps"]) == 23
def test_filter_clumps_by_component(client): resp = client.get("/api/clumps?component=disk") data = resp.get_json() assert all(c["component"] == "disk" for c in data["clumps"])
def test_get_clump_detail(client): resp = client.get("/api/clumps/0") data = resp.get_json() assert "properties" in data assert "boundary" in data
def test_clump_spectrum(client): resp = client.get("/api/clumps/0/spectrum/nircam") data = resp.get_json() assert "spectrum" in data assert "figure" in data assert len(data["spectrum"]["mean_flux"]) == 20
def test_pixel_clump_lookup(client): resp = client.get("/api/pixel/72/20/clump") data = resp.get_json() assert data["clump_id"] == 0
def test_pixel_spectrum(client): resp = client.get("/api/pixel/80/100/spectrum/nircam") data = resp.get_json() assert len(data["spectrum"]["fluxes"]) == 20
def test_region_spectrum(client): resp = client.post( "/api/region/spectrum/nircam", data=json.dumps({"rect": {"x0": 70, "y0": 15, "x1": 80, "y1": 25}}), content_type="application/json", ) data = resp.get_json() assert data["spectrum"]["n_pixels"] > 0
def test_compare_spectra(client): resp = client.post( "/api/compare/spectrum/nircam", data=json.dumps({"clump_ids": [0, 1, 3]}), content_type="application/json", ) data = resp.get_json() assert len(data["spectra"]) == 3 assert len(data["figure"]["data"]) == 3
def test_list_clumps_with_inside_filter(client): resp = client.get("/api/clumps?inside=true") data = resp.get_json() assert all(c["inside"] is True for c in data["clumps"])
resp = client.get("/api/clumps?inside=false") data = resp.get_json() assert all(c["inside"] is False for c in data["clumps"])
def test_region_spectrum_pixels(client): resp = client.post( "/api/region/spectrum/nircam", data=json.dumps({"pixels": [[80, 100], [81, 100]]}), content_type="application/json", ) data = resp.get_json() assert data["spectrum"]["n_pixels"] == 2
def test_region_spectrum_rect_clipping(client): resp = client.post( "/api/region/spectrum/nircam", data=json.dumps({"rect": {"x0": -10, "y0": -10, "x1": 5, "y1": 5}}), content_type="application/json", ) data = resp.get_json() assert data["spectrum"]["n_pixels"] > 0
def test_viewer_all_nan(client): from unittest.mock import patch
import numpy as np
nan_slice = np.full((221, 172), np.nan) with patch("jellyscope.visualization.image_viewer.DataCube") as _: from jellyscope.visualization.image_viewer import _asinh_stretch
result = _asinh_stretch(nan_slice) assert result.shape == (221, 172)1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Tests for spectral extraction."""
from jellyscope.analysis.spectral import ( extract_clump_spectrum, extract_pixel_spectrum, extract_region_spectrum,)
def test_pixel_spectrum(store): dc = store.get_datacube("nircam") result = extract_pixel_spectrum(dc, 80, 100) assert len(result["fluxes"]) == 20 assert len(result["wavelengths"]) == 20 assert result["n_pixels"] == 1
def test_clump_spectrum(store): dc = store.get_datacube("nircam") result = extract_clump_spectrum(dc, store.clumps, 0) assert len(result["mean_flux"]) == 20 assert len(result["std_flux"]) == 20 assert result["n_pixels"] == 121 assert result["clump_id"] == 0
def test_region_spectrum_with_mask(store): import numpy as np
dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) mask[50:60, 50:60] = True result = extract_region_spectrum(dc, mask) assert result["n_pixels"] == 100 assert len(result["mean_flux"]) == 20
def test_empty_region_spectrum(store): import numpy as np
dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) result = extract_region_spectrum(dc, mask) assert result["n_pixels"] == 01234567891011121314151617181920212223242526272829303132333435363738394041424344"""Tests for statistics module."""
import numpy as np
from jellyscope.analysis.statistics import compute_clump_summary, compute_region_stats
def test_region_stats_normal(store): dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) mask[50:60, 50:60] = True stats = compute_region_stats(dc, mask, 0) assert stats["filter"] == "F070W" assert stats["n_pixels"] > 0 assert isinstance(stats["mean"], float) assert isinstance(stats["median"], float) assert isinstance(stats["std"], float) assert isinstance(stats["min"], float) assert isinstance(stats["max"], float) assert isinstance(stats["sum"], float)
def test_region_stats_empty(store): dc = store.get_datacube("nircam") mask = np.zeros(dc.spatial_shape, dtype=bool) stats = compute_region_stats(dc, mask, 0) assert stats["n_pixels"] == 0 assert stats["mean"] is None assert stats["median"] is None assert stats["std"] is None assert stats["min"] is None assert stats["max"] is None assert stats["sum"] is None
def test_clump_summary(store): dc = store.get_datacube("nircam") summary = compute_clump_summary(dc, store.clumps, 0) assert summary["clump_id"] == 0 assert summary["component"] == "outside" assert summary["area_pix"] == 121 assert summary["inside"] is False assert len(summary["channel_stats"]) == 20 assert all(s["n_pixels"] > 0 for s in summary["channel_stats"])src/jellyscope/__init__.pyDeleted-3
src/jellyscope/analysis/__init__.pyDeleted-1
src/jellyscope/analysis/spectral.pyDeleted-62
src/jellyscope/analysis/statistics.pyDeleted-50
src/jellyscope/cli.pyDeleted-33
src/jellyscope/config.pyDeleted-48
src/jellyscope/data/__init__.pyDeleted-1
src/jellyscope/data/cache.pyDeleted-57
src/jellyscope/data/clumps.pyDeleted-159
src/jellyscope/data/fits_handler.pyDeleted-82
src/jellyscope/visualization/__init__.pyDeleted-1
src/jellyscope/visualization/image_viewer.pyDeleted-136
src/jellyscope/visualization/properties_panel.pyDeleted-19
src/jellyscope/visualization/spectrum_plot.pyDeleted-129
src/jellyscope/web/__init__.pyDeleted-28
src/jellyscope/web/routes.pyDeleted-190
src/jellyscope/web/static/app.jsDeleted-249
src/jellyscope/web/static/style.cssDeleted-279
src/jellyscope/web/templates/index.htmlDeleted-85
tests/__init__.pyDeleted
tests/conftest.pyDeleted-34
tests/test_cache.pyDeleted-31
tests/test_cli.pyDeleted-46
tests/test_clumps.pyDeleted-133
tests/test_fits_handler.pyDeleted-69
tests/test_routes.pyDeleted-134
tests/test_spectral.pyDeleted-44
tests/test_statistics.pyDeleted-44