Spaces:
Sleeping

File size: 14,596 Bytes
230ea06
 
35de79c
230ea06
 
d40edc5
230ea06
 
 
 
 
 
 
 
 
 
71192b4
d40edc5
71192b4
 
 
 
 
2dc366b
71192b4
0c3044a
230ea06
 
 
 
 
944f7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230ea06
 
 
2dc366b
230ea06
 
 
 
d40edc5
230ea06
2dc366b
 
 
 
b687153
 
 
 
2dc366b
 
230ea06
2dc366b
 
230ea06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc366b
230ea06
71192b4
 
 
 
 
 
230ea06
 
2dc366b
 
230ea06
 
 
 
 
 
 
 
 
 
 
 
 
 
b687153
 
230ea06
71192b4
 
230ea06
 
 
2dc366b
230ea06
 
2dc366b
 
b687153
 
 
2dc366b
b687153
230ea06
 
 
b687153
 
230ea06
 
944f7e5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
230ea06
 
0c3044a
71192b4
230ea06
 
 
d40edc5
230ea06
 
 
d40edc5
230ea06
 
2dc366b
 
 
 
b687153
 
 
 
2dc366b
 
b687153
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2dc366b
 
 
 
b687153
2dc366b
 
 
 
 
 
 
230ea06
d40edc5
230ea06
d40edc5
 
2dc366b
71192b4
2dc366b
71192b4
230ea06
 
2dc366b
 
 
230ea06
 
b687153
230ea06
 
d40edc5
230ea06
d40edc5
230ea06
71192b4
230ea06
0c3044a
230ea06
 
d40edc5
230ea06
d40edc5
230ea06
0c3044a
 
230ea06
 
 
 
d40edc5
0c3044a
d40edc5
230ea06
0c3044a
230ea06
d40edc5
230ea06
d40edc5
230ea06
 
 
d40edc5
230ea06
d40edc5
230ea06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d40edc5
230ea06
 
 
d40edc5
0c3044a
230ea06
 
 
 
d40edc5
0c3044a
230ea06
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d40edc5
230ea06
 
 
 
 
d40edc5
230ea06
 
 
 
 
d40edc5
230ea06
 
 
 
 
 
 
 
 
 
 
 
 
 
d40edc5
230ea06
 
 
 
 
 
d40edc5
2dc366b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
# Frontend

The Jellyscope frontend is a single-page application built with vanilla HTML, CSS, and JavaScript, using Plotly.js for all interactive visualizations. No frontend framework is needed.

**Files covered**:

- [web/templates/index.html](../src/jellyscope/web/templates/index.html) β€” HTML structure
- [web/static/app.js](../src/jellyscope/web/static/app.js) β€” JavaScript controller
- [web/static/style.css](../src/jellyscope/web/static/style.css) β€” Dark theme CSS

---

## index.html β€” Page Structure

**Location**: `src/jellyscope/web/templates/index.html`

This is a Jinja2 template rendered by FastAPI (via `Jinja2Templates`). It receives the following variables from the server:

- `datasets`: list of available dataset names (e.g., `["galaxy_a", "galaxy_b"]` or `["default"]` for a flat layout)
- `default_dataset`: name of the default dataset (active at page load)
- `default_datacube`: name of the datacube to display first (first available datacube of the default dataset)
- `datacubes`: list of available datacube names for the default dataset (e.g., `["nircam", "nircam_matched"]`)
- `filters`: list of filter names for the default datacube (e.g., `["F070W", "F090W", ...]`)
- `wavelengths`: dict mapping filter names to central wavelengths in Β΅m

These are exposed to JavaScript as `DATASETS`, `DEFAULT_DATASET`, `DEFAULT_DATACUBE`, `FILTERS`, and `WAVELENGTHS` constants.

### Layout

The page uses CSS Grid with two columns:

```mermaid
flowchart TB
    header["Header"]

    subgraph leftcol["Left column"]
        controls["Viewer controls"]
        viewer["Galaxy viewer"]
        controls --> viewer
    end

    subgraph rightcol["Right column"]
        properties["Properties panel"]
        clumplist["Clump list"]
        properties --> clumplist
    end

    header --> leftcol
    header --> rightcol
```

Left column: `1fr` (flexible) β€” the galaxy viewer expands to fill available space.
Right column: `360px` fixed β€” the panels stack vertically.

### Key HTML Elements

| Element ID | Type | Purpose |
| ----------- | ------ | --------- |
| `datacube-select` | `<select>` | Choose between nircam / nircam_matched |
| `stretch-select` | `<select>` | Intensity stretch: Log, Asinh (Lupton), Power |
| `btn-view-single` / `btn-view-rgb` | `<button>` | Toggle between single-band and RGB mode |
| `filter-slider` | `<input type="range">` | Navigate 20 filter channels (0-19) β€” single mode only |
| `colorscale-select` | `<select>` | Viridis, Inferno, Plasma, Cividis, Hot, Greys β€” single mode only |
| `rgb-r` / `rgb-g` / `rgb-b` | `<select>` | Filter channel for each RGB band β€” RGB mode only. Wavelengths constrained: Ξ»_R > Ξ»_G > Ξ»_B |
| `rgb-method` | `<select>` | RGB stretch method: `"Percentile Asinh"` (default) or `"Lupton"` |
| `rgb-q-wrap` | `<span>` | Wrapper around the Q slider β€” hidden when method β‰  Lupton |
| `rgb-q` | `<input type="range">` | Softening (Q) parameter for Lupton stretch β€” only visible when method = Lupton |
| `rgb-q-label` | `<span>` | Shows current Q value |
| `filter-label` | `<span>` | Unified status: filter name (single) or R/G/B combo (RGB) |
| `btn-click` / `btn-select` / `btn-lasso` | `<button>` | Interaction mode buttons |
| `btn-centroids` | `<button>` | Toggle centroid markers visibility |
| `galaxy-viewer` | `<div>` | Plotly mounts the figure here |
| `properties-content` | `<div>` | Clump properties table or status message |
| `clump-filter` | `<select>` | Filter clump list: All / Disk / Outside |
| `clump-list` | `<div>` | Dynamic clump list with checkboxes |

### Jinja2 Template Variables

```html
<!-- Datacube dropdown populated from server -->
{% for dc in datacubes %}
<option value="{{ dc }}">{{ dc }}</option>
{% endfor %}

<!-- Filter slider range from server -->
<input type="range" min="0" max="{{ filters|length - 1 }}" value="7">

<!-- Filter names and wavelengths passed to JavaScript -->
<script>
    const DATASETS = {{ datasets | tojson }};
    // β†’ ["galaxy_a", "galaxy_b"] (or ["default"] for a flat data dir)
    const DEFAULT_DATASET = {{ default_dataset | tojson }};
    // β†’ "galaxy_a"
    const DEFAULT_DATACUBE = {{ default_datacube | tojson }};
    // β†’ "nircam"
    const FILTERS = {{ filters | tojson }};
    // β†’ ["F070W", "F090W", ..., "F480M"]
    const WAVELENGTHS = {{ wavelengths | tojson }};
    // β†’ {"F070W": 0.704, "F090W": 0.901, ...}
</script>
```

---

## app.js β€” JavaScript Controller

**Location**: `src/jellyscope/web/static/app.js`

### Application State

All UI state is tracked in a single global object:

```javascript
const DEFAULT_RGB_FILTERS = {r: "F200W", g: "F115W", b: "F090W"};

const state = {
    dataset: DEFAULT_DATASET,     // Active dataset (from template)
    datacube: DEFAULT_DATACUBE,   // Currently selected datacube
    channel: 7,                   // Current filter channel (default: F200W)
    selectedClumps: new Set(),    // Set of selected clump IDs
    colorscale: "Viridis",        // Current colorscale
    stretch: "log",               // Intensity stretch function
    dragmode: "pan",              // Plotly interaction mode
    clumps: [],                   // Loaded clump list from API
    showCentroids: false,         // Whether centroid markers are visible
    viewMode: "single",           // "single" (heatmap) or "rgb" (composite)
    rgbR: defaultRgbIndex(DEFAULT_RGB_FILTERS.r, FILTERS.length - 1),  // F200W
    rgbG: defaultRgbIndex(DEFAULT_RGB_FILTERS.g, Math.floor(FILTERS.length / 2)),  // F115W
    rgbB: defaultRgbIndex(DEFAULT_RGB_FILTERS.b, 0),                   // F090W
    rgbQ: 8.0,                    // Lupton softening parameter
    rgbMethod: "percentile_asinh",// "percentile_asinh" (default) or "lupton"
};
```

The RGB defaults come from `DEFAULT_RGB_FILTERS` (mirrors `DEFAULT_RGB` in `src/jellyscope/config.py`) and are resolved to channel indices via the `defaultRgbIndex(filterName, fallback)` helper, which falls back to a positional index if the named filter is missing from `FILTERS`.

### Initialization Flow

```mermaid
flowchart TD
    dom["DOMContentLoaded"] --> init["Initialize app"]

    init --> populate["Populate RGB selects"]
    init --> loadclumps["Load clump list"]
    init --> updlabel["Set filter label"]
    init --> updmethod["Toggle Lupton controls"]
    init --> render["Render viewer"]
    init --> setup["Wire event listeners"]

    setup --> ev_dc["Datacube change"]
    setup --> ev_slider["Filter slider"]
    setup --> ev_color["Colorscale change"]
    setup --> ev_stretch["Stretch change"]
    setup --> ev_view["View mode toggle"]
    setup --> ev_rgb["RGB band change"]
    setup --> ev_method["RGB method change"]
    setup --> ev_q["Lupton softening"]
    setup --> ev_mode["Drag mode buttons"]
    setup --> ev_centroids["Centroid toggle"]
    setup --> ev_filter["Clump filter"]
```

All API URLs are namespaced under `/api/datasets/${state.dataset}/`. The active dataset is read from the template-injected `DEFAULT_DATASET` constant at startup.

### Function Reference

#### `init()`

Async entry point. Called on `DOMContentLoaded`. Loads the clump list, renders the initial viewer, and attaches all event listeners.

#### `setupEventListeners()`

Attaches DOM event handlers to all control elements. Each handler updates `state` and triggers the appropriate re-render.

#### `debounce(fn, ms)`

Utility that delays function execution until `ms` milliseconds after the last invocation. Used for the Q slider to avoid flooding the API during drag.

#### `defaultRgbIndex(filterName, fallback)`

Resolves a filter name (e.g. `"F200W"`) to its index in the `FILTERS` array. Returns `fallback` if the name is not found. Used to seed `state.rgbR/G/B` from `DEFAULT_RGB_FILTERS` at startup.

#### `populateRGBSelects()`

Fills the R/G/B `<select>` dropdowns with filter options (name + wavelength labels). The default selections come from `DEFAULT_RGB_FILTERS` (R = F200W, G = F115W, B = F090W) via `defaultRgbIndex()`. Calls `updateRGBFilterOptions()` at the end to apply the wavelength-ordering constraint.

#### `updateRGBFilterOptions()`

Enforces the constraint **Ξ»_R > Ξ»_G > Ξ»_B** on the R/G/B dropdowns:

1. If the current `state.rgbG` has Ξ» β‰₯ Ξ»_R, auto-select the longest available filter still below Ξ»_R.
2. If the current `state.rgbB` has Ξ» β‰₯ Ξ»_G, do the same for B (longest filter still below Ξ»_G).
3. Mark every option whose wavelength would violate the constraint as `disabled` (greyed out in the dropdown).

Called whenever any of the R/G/B selectors change so the user cannot pick a non-monotonic combination.

#### `updateRGBMethodUI()`

Shows or hides `#rgb-q-wrap` (the Q slider wrapper) based on `state.rgbMethod`. The Q parameter only matters for the Lupton method, so the slider is hidden when the method is `percentile_asinh`.

#### `updateFilterLabel()`

Updates the `#filter-label` status indicator:

- **Single mode**: shows `"F200W (1.99 Β΅m)"`
- **RGB mode**: shows `"R:F480M  G:F277W  B:F070W"`

#### `updateViewModeUI()`

Shows/hides the appropriate control group (`#single-controls` vs `#rgb-controls`) based on `state.viewMode`.

#### `renderViewer()`

The core render function. Fetches the Plotly figure from the API and renders it:

```plaintext
1. If viewMode == "rgb":
     Build URL: /api/datasets/{dataset}/viewer/{datacube}/rgb?r={R}&g={G}&b={B}&selected={ids}&method={rgbMethod}&softening={Q}
   Else:
     Build URL: /api/datasets/{dataset}/viewer/{datacube}/{channel}?selected={ids}&colorscale={scale}&stretch={stretch}
2. fetch(url) β†’ JSON response with figure dict
3. Set figure.layout.dragmode = state.dragmode
4. If !showCentroids β†’ remove last trace (centroids) from data
5. Plotly.react("galaxy-viewer", fig.data, fig.layout, plotlyConfig)
6. Attach plotly_click event handler
```

Called whenever: datacube changes, filter changes, colorscale changes, stretch changes, view mode changes, RGB channels change, RGB method changes, Q slider moves (debounced, Lupton only), clump selection changes, or centroids toggled.

#### `onViewerClick(eventData)`

Handles clicks on the galaxy image:

1. Extract `(x, y)` pixel coordinates from the clicked point
2. `GET /api/datasets/{state.dataset}/pixel/{x}/{y}/clump` β€” check if pixel belongs to a clump
3. If clump found β†’ `toggleClumpSelection(clumpId)`
4. If no clump β†’ show a "no clump at this pixel" status message

#### `toggleClumpSelection(clumpId)`

Toggles a clump in/out of `state.selectedClumps`:

- **0 selected**: clear all panels
- **1 selected**: show that clump's properties
- **2+ selected**: show a status message listing the selected clump IDs

Also calls `renderViewer()` to update boundary highlighting (selected = red).

#### `showClumpDetails(clumpId)`

Fetches properties for a single clump and renders the HTML table in the properties panel:

```javascript
const propsResp = await fetch(`/api/datasets/${state.dataset}/clumps/${clumpId}`);
```

#### `loadClumpList()`

Fetches the clump list from the API (with optional component filter) and calls `renderClumpList()`.

#### `renderClumpList()`

Generates HTML for the clump list panel. Each item has:

- A checkbox for multi-selection
- The clump ID
- A colored badge showing component (`disk` = green, `outside` = orange)
- Pixel count

```html
<div class="clump-item selected" onclick="toggleClumpSelection(4)">
    <input type="checkbox" checked>
    <span>Clump 4</span>
    <span class="clump-badge disk">disk</span>
    <span>144px</span>
</div>
```

#### `updateClumpListUI()`

Updates checkbox states and selected styling without re-rendering the entire list.

#### `showPropertiesMessage(msg)` / `clearPanels()`

Helper functions for updating/clearing the properties panel.

### Plotly Events Used

| Event | When | Action |
| ------- | ------ | -------- |
| `plotly_click` | User clicks on the heatmap | Identify clump under the cursor |

### Plotly Configuration

```javascript
const plotlyConfig = {
    responsive: true,                                  // Resize with container
    displayModeBar: true,                              // Show toolbar
    modeBarButtonsToRemove: ["toImage", "sendDataToCloud"],
    scrollZoom: true,                                  // Zoom with mouse wheel
};
```

---

## style.css β€” Dark Theme

**Location**: `src/jellyscope/web/static/style.css`

### CSS Custom Properties (Variables)

```css
:root {
    --bg-primary: #0f0f23;       /* Darkest background (main area) */
    --bg-secondary: #16213e;     /* Header and control bars */
    --bg-panel: #1a1a2e;         /* Panel backgrounds */
    --text-primary: #e0e0e0;     /* Main text */
    --text-secondary: #999;      /* Labels, secondary text */
    --accent: #00ccff;           /* Cyan accent (titles, highlights) */
    --accent-hover: #33ddff;     /* Lighter accent for hover */
    --border: #2a2a4a;           /* Borders and dividers */
    --danger: #ff4444;           /* Selected clump highlight */
}
```

### Grid Layout

```css
main {
    display: grid;
    grid-template-columns: 1fr 360px;   /* Flexible left, fixed 360px right */
    height: calc(100vh - 41px);          /* Full height minus header */
}
```

### Customization Guide

**Change the accent color**:

```css
:root { --accent: #ff6600; }   /* Orange theme */
```

**Change the right panel width**:

```css
main { grid-template-columns: 1fr 450px; }
```

**Light theme** (override all `--bg-*` and `--text-*` variables):

```css
:root {
    --bg-primary: #ffffff;
    --bg-secondary: #f5f5f5;
    --bg-panel: #fafafa;
    --text-primary: #333333;
    --text-secondary: #666666;
    --border: #dddddd;
}
```

### Component Badges

Clumps are color-coded by component:

- **Disk clumps**: Green border and text (`#44ff44`)
- **Outside clumps**: Orange border and text (`#ffaa00`)

```css
.clump-badge.disk    { color: #44ff44; border: 1px solid #44ff44; }
.clump-badge.outside { color: #ffaa00; border: 1px solid #ffaa00; }
```

### View Mode Buttons and Toggle Buttons

View mode (`Single` / `RGB`) and interaction mode buttons share styling patterns:

```css
.view-btn, .mode-btn, .toggle-btn {
    background: var(--bg-panel);
    border: 1px solid var(--border);
    /* Active state: cyan background, black text */
}
.view-btn.active, .mode-btn.active, .toggle-btn.active {
    background: var(--accent);
    color: #000;
}
```

### RGB Controls

The Q slider and its label are styled to match the filter slider:

```css
#rgb-q {
    width: 80px;
    accent-color: var(--accent);
}
#rgb-q-label {
    color: var(--accent);
    font-weight: 600;
}
```