Repository navigation
Conversation
The bqplot ImageWidget scaled the image by the cuts and stretch in the kernel and sent the result, all of it, every time either changed. For a 4096 x 4096 camera frame that is 67 MB per change, which makes a cuts slider unusable over a network. The front end draws a pixel in color number (value - min) / (max - min) of the color scale, on the GPU. So the pixels are now sent once, as they are, when an image is loaded; the cuts become the limits of the color scale and the stretch the spacing of its colors. A change of cuts or stretch then sends two numbers or a list of 256 colors. Building a stretch into the colors sorts the pixels into 256 equal bins before stretching them, so a stretch that is steep somewhere shows bands: the default LogStretch draws the faintest 0.4% of the range, which it spreads over a quarter of the way to white, as one shade. A stretch that steps by more than MAX_BUILT_IN_STEP between neighboring colors is therefore still applied to the pixels and sent when the cuts or stretch change, but as uint8, the number of the color each pixel is drawn in. That is a quarter of the size and draws exactly what the float image did. An image with NaNs, which uint8 cannot hold, is sent as float32. Removing catalogs also sent the image again, because the batch-update hook refreshed the display unconditionally. It now refreshes only if something in the batch changed what is drawn. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Gy3gmbgEL7BGJ5P8ucd5mG
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Gy3gmbgEL7BGJ5P8ucd5mG
mwcraig
left a comment
There was a problem hiding this comment.
Review synthesized from four independent AI reviewers (one OpenAI Codex pass, one looking only for over-engineering, one checking the front-end assumptions against the bqplot-image-gl 1.10.2 / bqscales 0.3.7 source, one on kernel-side behavior and tests), posted by Claude at Matt's request. The three items marked "reproduced" I re-ran myself against 6a51b5f. Nothing here was checked in a browser.
Verdict
The core idea holds up and should stay: pixels sent once, cuts as the color scale's min/max, gentle stretches built into the colors, steep ones resent as uint8. The reviewer who read the shader confirmed the model the PR relies on: (value - min) / (max - min) on the GPU with clamping, a 256-texel colormap read at the nearest texel, uint8 level k landing in color k, NaN left undrawn, odd widths fine for uint8. The replacement of _defer_refresh/ExitStack with two flags is simpler than what it replaced, and the state flags were consistent through every sequence and exception path tried. The tests pass (128 passed, 2 skipped).
It is not ready to merge, because of three behavior changes that the tests do not see:
- Stale pixels when a float32 array is edited in place and reloaded (reproduced).
- float32 precision: images with a large offset and small structure become a flat field (reproduced).
- Reversed cuts collapse to a threshold image instead of inverting (reproduced).
On the block/band handling
Two things in the PR serve memory rather than responsiveness, and neither was requested:
- The 256-row band loop in
scale_to_levels. Recommend removing. It saves no time, its memory saving is hidden behind the 128 MB percentile computation that runs first with default cuts, and it is worse than the plain version when the image contains a NaN. A seven-lineout=version is in the inline comment. - The uncopied float32 pass-through. This is the cause of bug 1. Recommend always copying.
Everything else that looked like extra machinery (two paths, the threshold function, _front_end_has_pixels, the stale flag) was judged to earn its place.
Needs a look in a browser
- A possible one-frame flash when a stretch change switches between the float32 and uint8 payloads, since the image and the color scale arrive as separate messages.
- Each change of limits makes the front end re-upload the stored texture to the GPU (
domain_changedis wired toupdate_image). No network traffic, and the PR's <0.3 s figure already includes it, but it is the remaining cost on the fast path.
Smaller items (inline)
MAX_BUILT_IN_STEP: data for the open question; the reviewers disagreed on the value.- New public names that could be private.
- Opt-in PNG/WebP compression breaks both paths.
- Percentile limits recomputed on every stretch change (~0.2 s for 4096 x 4096).
- Test gaps: one assertion loop that cannot fail, an unpinned threshold boundary, helpers that share code with what they check.
Checked and clean: NaN/inf data through both paths, masked/NDData input (mask ignored, as before), big-endian FITS arrays, label switching, removed private names (no remaining users).
| self._astro_im.set_data( | ||
| np.asarray(self._data, dtype=np.float32), | ||
| reset_view=False, | ||
| ) |
There was a problem hiding this comment.
Bug (reproduced): reloading an array edited in place leaves stale pixels in the browser.
For a native, contiguous float32 input this hands the image trait the caller's own array. traittypes.Array only notifies when np.array_equal(old, new) is false, and old and new are now the same memory, so after
w.load_image(a)
a[:] = something_else
w.load_image(a)the only message the image mark sends is send_state(set()): no pixels. The color limits are recomputed from the edited data and sent, so the browser draws the old pixels against the new limits. On the base commit the same sequence sends image. Editing without reloading and then calling set_cuts has the same result.
Assigning a view does not help (still equal). The simplest fix is to drop the no-copy pass-through and always send a copy: a 64 MB memcpy once per load is small beside the transfer, and avoiding it was a memory goal that was not part of the request. If the zero-copy is wanted, _render_image needs an explicit send_state("image").
| # size, and refuses the rest. A float32 image is not | ||
| # copied. | ||
| self._astro_im.set_data( | ||
| np.asarray(self._data, dtype=np.float32), |
There was a problem hiding this comment.
Regression (reproduced): data that float32 cannot hold is flattened.
The base applied the interval in the input's precision and sent 0..1. This sends raw values as float32, and the shader's min/max uniforms are float32 too. Examples, with MinMaxInterval:
| Input | Distinct values | After this cast |
|---|---|---|
float64 1e9 + U(0, 10) |
4096 | 1 |
uint32 4e9 + [0, 100) |
100 | 1 |
int64 2**40 + [0, 1000) |
975 | 1 |
int32 2**25 + [0, 10) |
10 | 3 |
In the first case both limits are also 1e9 as float32, so the shader computes 0/0 and (from reading the shader, not run in a browser) the image is drawn transparent. uint16 and ordinary float camera frames are unaffected, so this is an edge, but it is a silent one.
Options: subtract an offset (e.g. low) before the cast and send limits relative to it, or route input that does not survive the cast through the kernel path, which already handles it correctly.
| if high <= low: | ||
| # An image of a single value. Draw it in the first color, as | ||
| # astropy's intervals scale it to zero. | ||
| return low, low + 1.0 |
There was a problem hiding this comment.
Regression (reproduced): reversed cuts are no longer honored. set_cuts((400, 100)) gives color limits (400, 401), a near-threshold black/white image. astropy's ManualInterval(400, 100) and the base draw an inverted image, and the shader's (v - min) / (max - min) works with min > max. Only equality needs the guard: if high == low.
Separately, low + 1.0 equals low in float32 once |low| >= 2**24, so a constant image of a large value still reaches the shader with max == min. The test for this uses 7.0. Something like low + max(1.0, abs(low) * 1e-6) would hold; the offset fix suggested on the float32 cast would cover it as well.
| if not (np.isfinite(low) and np.isfinite(high)): | ||
| # The limits are sent as JSON, which has no NaN or infinity. | ||
| return 0.0, 1.0 |
There was a problem hiding this comment.
Minor: the guard itself is needed (a NaN limit reaches the browser as the string "nan", which the front end reads as 0), but (0, 1) shows ordinary contrast the caller did not ask for. With cuts (0, np.inf) astropy maps every pixel to 0; here an image with values in 0..1 is drawn normally. Fine to leave if deliberate, but worth saying so in the comment.
| for start in range(0, data.shape[0], _ROWS_PER_BAND): | ||
| rows = slice(start, start + _ROWS_PER_BAND) | ||
| scaled = stretch(interval(data[rows])) | ||
| if np.isnan(scaled).any(): | ||
| return np.asarray(stretch(interval(data)), dtype=np.float32) | ||
| # The front end draws a value from 0 to 1 in color number | ||
| # floor(256 * value), and the last color for 1 itself. | ||
| levels[rows] = np.minimum(scaled * LEVELS, LEVELS - 1) |
There was a problem hiding this comment.
The band loop is the one piece of real scope creep, and I'd drop it. Memory use was not part of the request, and measured on a 4096 x 4096 image with LogStretch (peak via tracemalloc, separate processes):
| Version | float32 in | float64 in | Time |
|---|---|---|---|
| This loop | 28 MB | 40 MB | ~0.11 s |
stretch(interval(data)) then uint8 |
192 MB | 384 MB | ~0.12 s |
One float32 buffer with out= |
80 MB | 80 MB | ~0.10 s |
| This loop, image containing a NaN | 148 MB | 280 MB | |
out=, image containing a NaN |
80 MB | 80 MB |
- No speed difference; the ~0.9 s in the PR table is transfer.
_color_limitsruns first on every update, and with the defaultAsymmetricPercentileIntervalitsget_limitspeaks at 128 MB (float32) by itself. So with default cuts the update's peak is the same with or without bands.- With a NaN anywhere, which is common in masked or reprojected images, the loop throws away its work and redoes the whole frame unbanded, so it is worse than the plain version exactly when it would matter.
A loop-free version that keeps most of the saving:
def _scale_to_levels(data, low, high, stretch):
scaled = apviz.ManualInterval(low, high)(
data, out=np.empty(np.shape(data), np.float32)
)
stretch(scaled, out=scaled, clip=True)
if np.isnan(scaled).any():
return scaled # float32, 0..1; the front end leaves NaN undrawn
scaled *= LEVELS
np.minimum(scaled, LEVELS - 1, out=scaled)
return scaled.astype(np.uint8)A variant of this passes all 128 tests in the file. For float64 input it can differ from the current output by one level at bin edges. _ROWS_PER_BAND and the "taller than a band" / "NaN in the last band" framing in the two scale_to_levels tests go away with it.
| for call in spy_image.call_args_list: | ||
| keys = call.kwargs.get("key", call.args[0] if call.args else None) | ||
| assert keys is not None | ||
| assert "image" not in keys |
There was a problem hiding this comment.
This loop cannot fail. hold_sync passes its own _states_to_send set to send_state and then clears it, so by the time these assertions run every recorded keys is set(). A real image resend inside _hold_all_sync was checked and still records set(). Only the image_mark.image is sent_before identity check below does any work, and that one cannot see the in-place case. Copy the keys in a side_effect, or observe the image trait instead.
|
|
||
| assert_displayed(self.image, arr, cuts, apviz.LinearStretch()) | ||
|
|
||
| def test_float32_image_is_not_copied(self): |
There was a problem hiding this comment.
This pins the memory sharing that causes the stale-pixels bug noted in bqplot.py. If the pass-through is dropped, replace this with a test that edits the array in place, reloads, and asserts image was sent.
| @pytest.mark.parametrize( | ||
| "dtype", [np.uint8, np.uint16, np.int32, np.float32, np.float64] | ||
| ) | ||
| def test_image_is_sent_as_float32(self, dtype): |
There was a problem hiding this comment.
The docstring says the values are sent unchanged, but arange(1200) is exact in float32 for every dtype in the list, so the test cannot see the precision loss noted in bqplot.py. A case such as 2**25 + arange(10) as int32, or 1e9 + small as float64, would.
| (apviz.PowerStretch(0.2), False), | ||
| ], | ||
| ) | ||
| def test_stretch_fits_in_colors(stretch, fits): |
There was a problem hiding this comment.
The threshold boundary is not pinned: changing MAX_BUILT_IN_STEP from 0.1 to 0.065 passes every test, because nothing here lies between sqrt (0.063) and the default log (0.23). Adding LogStretch(a=100) (0.072) and AsinhStretch(a=0.01) would pin it once the value is decided. Related: the "stretch" case of test_changing_the_display_does_not_resend_the_image uses SqrtStretch, which stops being a no-resend case if the threshold drops to 0.05; AsinhStretch() (0.013) is safely gentle.
| arr = np.asarray(arr) | ||
| low, high = cuts.get_limits(arr) | ||
|
|
||
| if stretch is None or stretch_fits_in_colors(stretch): |
There was a problem hiding this comment.
assert_displayed picks its branch with the code's own stretch_fits_in_colors, builds the expected colors with the code's own bqcolors(..., stretch=...), and recomputes the steep result with the same floor(scaled * 256) formula, so a mistake in any of those would pass. The independent checks are test_bqcolors_builds_in_a_stretch and screen_levels. screen_levels is worth keeping, but it does its arithmetic in float64 where the shader uses float32 uniforms; casting the pixels and limits to float32 first, and treating NaN as undrawn, would let test_screen_matches_astropy_scaling catch the large-value problems.
The bqplot
ImageWidgetapplies the cuts and stretch in the kernel and sends the whole scaled image to the browser every time either changes. For a 4096 x 4096 camera frame that is 67 MB per change, which made a black/white slider unusable for a class on a JupyterHub: updates took from tens of seconds to minutes, and for some students never arrived.What changes
The bqplot-image-gl front end colors a pixel on the GPU as color number
(value - min) / (max - min)of the color scale. This PR uses that:minandmaxof the color scale.A stretch that is steep somewhere cannot be built into 256 colors without banding, because the pixels are binned before they are stretched. The default
LogStretchdraws the faintest 0.4% of the range, which it spreads over a quarter of the way to white, as a single shade. So a stretch that steps by more thanMAX_BUILT_IN_STEP(0.1) between neighboring colors is still applied to the pixels and resent when the cuts or stretch change, but asuint8, a quarter of the size, which draws exactly what the float image did.Removing catalogs also resent the image, because the batch-update hook refreshed the display unconditionally. It no longer does.
Measured
Chrome driving JupyterLab on one machine, a 4096 x 4096 float32 image, the released 0.6.0 against this branch. Times are over loopback, so they understate a real network.
SqrtStretchLogStretchAn image whose width is not a multiple of 4 was also checked under log, since it goes as an 8 bit texture, and is identical.
Open question
Where to put
MAX_BUILT_IN_STEP. At 0.1,SqrtStretchis built into the colors and bands slightly at the faint end: visible on a noiseless ramp over the lowest 5% of the cut range, not noticeable in noise. Lowering it to about 0.05 would send sqrt the way log is sent, exact but 17 MB per change.Not changed
🤖 Generated with Claude Code
https://claude.ai/code/session_01Gy3gmbgEL7BGJ5P8ucd5mG