Repository navigation
Send the bqplot image at the resolution the screen needs - #246
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.
Nothing here blocks on its own, but one new corner-case bug and one deliberate choice are worth changing, and a fair amount can be shorter. This covers only this pull request's own two commits, 4f370a9 and cb75be2; the two below them are #244 and are reviewed there.
The implementation in these commits was also written with Claude, so the reviewing was done by independent reviewers that were not shown its reasoning (correctness, simplification, and OpenAI Codex), followed by a fresh reviewer who tried to disprove each finding.
Inline, most important first:
- A stretch applied in Python now works on float32 copies of the data (
bqplot.pyline 1015). New here; a corner case. - Panning a view that contains a NaN shows blank outside the old sharp rectangle (line 1078). Deliberate, but every first-round reviewer flagged it.
- Inherited from #244: a small float32 image changed in place and reloaded is not sent (line 1190).
- Three pieces of per-widget state, a hand-written
nanmean, a repeated special case and about 80 lines of tests can go: about 18 lines frombqplot.pyin all.
Raised and checked: not a problem
- The strip left out when the image is not a whole number of blocks. Two reviewers reported the top and right edge as never drawn (pixels 400 to 406 of a 407 x 407 image in a 50 pixel viewer; 4 rows and columns of a 4100 x 4100 frame). The facts are right, but on screen the strip is always under one screen pixel at the view each picture is made for: 0.86 for the 407 case at fit and at worst 0.875 over every zoom on the top-right corner; 0.49 at fit and at worst 0.67 for the 4100 case; nothing missing at
pixel_density=2or once a screen pixel covers one image pixel or less. It is wider only while the coarse picture is being stretched, in the 0.3 s before the sharp one arrives or while the kernel is busy. Measured by running. - A wrongly sized piece sent first. With no asyncio loop, a browser zoom arrives as an x change then a y change and the sharp part is worked out after the first: 4096 x 4096 zoomed from fit to a 410 pixel field sends 4096 x 411 (6.7 MB), then 411 x 411. With a loop there is one send, and
set_viewportfrom Python cannot hit it. ipykernel 6.29.5 runs comm handlers inside a coroutine, so a notebook always has the loop. Confirmed by running. - An error in the delayed send reaches only the event loop's handler, the same place as an error in any widget callback triggered from the browser. No realistic input was found that raises there.
test_pan_with_no_event_loop_sharpens_at_oncechecks values and not placement; shifting the picture by a pixel is caught by two neighboring tests.
How this was checked
13 findings were raised in the first round; 2 bugs and all 7 simplifications survived the second, which added one more simplification and the inherited bug. "Confirmed by running" means Python run against this branch and against 6a51b5f; the simplifications were run together against the test suite and against 16 random sequences of about 60 operations each (loads, view changes from Python and the browser, cuts, gentle and steep stretches, colormaps, catalogs, images with NaN and inf, with and without a loop) with identical arrays, placement, visibility and sends throughout. No reviewer used a browser. Codex ran without the review's focus list, because its installed version refuses instructions together with a base branch.
— Written by Claude at @mwcraig's direction.
| self._scaling = (low, high, stretch) | ||
| self._front_end_has_pixels = False | ||
| self._astro_im.set_data( | ||
| scale_to_levels(self._whole, low, high, stretch), |
There was a problem hiding this comment.
A stretch applied in Python now works on float32 copies. At 6a51b5f scale_to_levels was given the original data. Here it is given self._whole, which is float32, and on line 1077 the float32 part on view. Confirmed by running, comparing levels with 6a51b5f:
- float64
1e7 + uniform(0, 3), cuts (1e7, 1e7 + 3),LogStretch: 94.6% of pixels at a different level, the worst by 189 of 256. - int32
2**25 + randint(0, 4): 50% different, the worst by 240. - Realistic frames (sky 1000 with sigma 30, bias 1000 with sigma 2) with the default cuts: at most 1 level, in under 0.1% of pixels.
A corner case: it shows only when the cut range is under about 0.1% of the pixel values. For stretches applied in the browser the same loss is already there at 6a51b5f; see the review of #244.
Suggested change (about 5 lines, tried): have block_mean return float64, and the image untouched for a block of 1, and cast to float32 only where pixel values are sent. The one test that then fails is the small.dtype == np.float32 assertion. test_steep_stretch_is_applied_to_both_pictures uses float32 data only, so it cannot see this; a float64 case would.
— Written by Claude at @mwcraig's direction.
| has_nans = bool(np.isnan(pixels).any()) | ||
| if self._scaling is not None: | ||
| pixels = scale_to_levels(pixels, *self._scaling) | ||
| astro_im.set_detail(pixels, x_start, y_start, block, alone=has_nans) |
There was a problem hiding this comment.
Panning a view with a NaN in it shows blank outside the old sharp rectangle. This is the choice listed in the description, but all three first-round reviewers flagged it.
Confirmed by running: 4096 x 4096 with one NaN at (2000, 2000) and a 500 pixel field. Five pans of 80 pixels, 50 ms apart, leave 80, 160, 240, 320, then 400 of 500 columns blank, filled only 0.3 s after the last. A long drag or a wheel zoom out leaves most of the viewer blank until the mouse stops, because the timer restarts on each change, and for as long as the kernel is busy. It is blank, not wrong. It never happens for raw integer frames; it does for mosaic and reprojection borders, masked pixels and dead columns set to NaN.
Possible change, not tried: in _sharpen_when_view_settles, show the coarse picture again when a move arrives from the browser and hide it again when the timer fires. The early return for an unchanged part would have to hide it again too. The cost is that while the view is moving, a NaN pixel in the old sharp area shows the coarse average through it.
— Written by Claude at @mwcraig's direction.
| # reads uint8 as a fraction of 255, converts float64 itself | ||
| # after it has been sent at twice the size, and refuses the | ||
| # rest. A float32 image is not copied. | ||
| self._whole = np.asarray(self._data, dtype=np.float32) |
There was a problem hiding this comment.
Inherited from #244, not new here: when the image fits the viewer this hands the caller's own float32 array to the image trait, so an array changed in place and loaded again is not sent (details in the review of #244). Images big enough to be averaged get a fresh array and are not affected. The fix belongs on #244: copy when the dtype is already float32.
— Written by Claude at @mwcraig's direction.
| self._display_is_stale = False | ||
| for image_label in self._displayed_image_labels: | ||
| self._update_display(image_label) | ||
| elif view_is_stale: |
There was a problem hiding this comment.
_view_is_stale is never needed. With astro-image-display-api 0.3.0 the only batch that calls _apply_viewport is load_image, after _render_image has marked the display stale, so this branch never runs. _apply_viewport can end with
if not self._batching:
self._update_detail()and the attribute, the swap line above and this elif go. Tried; no test fails. To stay correct if a later batch changes only the viewport, set self._display_is_stale = True inside a batch instead.
— Written by Claude at @mwcraig's direction.
| pixels = scale_to_levels(pixels, *self._scaling) | ||
| astro_im.set_detail(pixels, x_start, y_start, block, alone=has_nans) | ||
| self._detail_part = part | ||
| self._detail_is_scaled = self._scaling is not None |
There was a problem hiding this comment.
_detail_is_scaled repeats what _front_end_has_pixels already says: while a sharp part exists it always equals not self._front_end_has_pixels. The gentle branch of _update_display can use one flag for both pictures:
resend = not self._front_end_has_pixels
if resend:
self._astro_im.set_data(self._whole, **placement)
self._front_end_has_pixels = True
self._astro_im.set_color_limits(low, high)
self._update_detail(resend=resend)resend has to be read before the flag is set. Tried, including the return from a steep stretch to a linear one.
— Written by Claude at @mwcraig's direction.
| if part != self._detail_part: | ||
| cutout = np.asarray(self._data)[y_start:y_stop, x_start:x_stop] | ||
| if block > 1: | ||
| self._detail_pixels = block_mean(cutout, block) |
There was a problem hiding this comment.
Two things can go here, both tried.
_detail_pixels: recompute the cutout whenever something is sent, with if part == self._detail_part and not resend: return first. The cost is averaging at most about 1000 x 1000 pixels again on a change of cuts under a steep stretch, far less than the percentile over the full image that already runs then.
The test for a block of 1, which is written here and again in _render_image: put
if block == 1:
return np.asarray(data, dtype=np.float32)at the top of block_mean, with the comment about float32, and call it unconditionally in both places. A small float32 image is still sent without a copy.
— Written by Claude at @mwcraig's direction.
| ) | ||
| band = squares.mean(axis=(1, 3), dtype=np.float64) | ||
| if np.isnan(band).any(): | ||
| present = ~np.isnan(squares) |
There was a problem hiding this comment.
This branch is np.nanmean written out. With import warnings:
with warnings.catch_warnings():
# A square with no pixels present is NaN, which is what is wanted.
warnings.simplefilter("ignore", RuntimeWarning)
band = np.nanmean(squares, axis=(1, 3), dtype=np.float64)Bit-identical, NaN positions included, on a 4096 x 4096 image with scattered and all-NaN squares, at the same speed (0.07 s), and no warning escapes with RuntimeWarning as an error. Tried.
— Written by Claude at @mwcraig's direction.
| part on view is sent straight away. | ||
| """ | ||
| self._refresh_deferred = True | ||
| if self._whole_block == 1: |
There was a problem hiding this comment.
Redundant: with a block of 1, _update_detail already stops at part[-1] >= self._whole_block. Without this a small image gets one timer and one call that sends nothing per pan, so it is optional.
— Written by Claude at @mwcraig's direction.
| return x_start, x_stop, y_start, y_stop, block | ||
|
|
||
|
|
||
| def watch_image_sends(mark): |
There was a problem hiding this comment.
Test lines that can go, all tried together: 150 pass with about 80 lines fewer, and flipping the rows in block_mean, resending the same view, or shifting either picture is each still caught.
- Delete this helper and the
sends == []asserts. The image trait notifies only whennp.array_equalis false, somark.image is before, which each of those tests also has, is the stricter check. The pan test is the only one that counts sends and keeps two lines:sends = []anddetail.observe(sends.append, names="image"). - Fold
test_block_mean_leaves_out_part_blocksintotest_block_mean_averages_squares_of_pixelsby giving that one the shape (1203, 38). - Fold
test_pixel_density_sets_how_many_pixels_are_sentintotest_big_image_is_sent_at_screen_resolutionwith@pytest.mark.parametrize("pixel_density, block", [(1, 8), (2, 4)]). - Delete
test_same_view_is_not_sent_twiceand add alambda image: image.set_viewport(center=(117, 203), fov=40)case totest_changing_the_display_resends_neither_picture. test_averaged_image_lines_up_with_the_pixelsis implied by the not-whole-blocks test, which checks which pixels the picture covers and that it equalsaveraged(arr, 8). If it goes, keep the double loop inaveraged: that is then the only check ofblock_meanthat does not share its reshape. If it stays,averagedcan be three lines with a reshape and a mean over axes (1, 3).
— Written by Claude at @mwcraig's direction.
Five tests fail, each for a picture that is drawn wrong: - A float32 array edited in place and loaded again is not sent. - Cuts with the high level first draw one flat color, not a negative. - Values a few counts apart on a large offset share a shade, because the front end holds pixels and limits as 32 bit floats. - An infinite high cut draws ordinary contrast where astropy scales every pixel to zero. - The square root stretch is built into the colors, where it steps by 16 of 255 levels at the faint end; the limit is to be 0.05. The rest tidy the tests. The loop that looked for the image among the keys passed to send_state could not fail, because ipywidgets empties that set straight after the call; sends are now counted by observing the image trait. The steep stretch test takes in the colormap, catalog and back-to-gentle cases that had their own copies of its setup. What the screen shows is worked out in 32 bit floats, as the GPU does it. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
From the review of the change that has the browser apply the cuts and the stretch: - The image is always copied before it is sent. Handed the caller's own float32 array, the image trait saw no change when that array was edited and loaded again, and sent nothing, so old pixels stayed on the screen under new cuts. - Cuts the front end cannot apply are applied to the pixels instead, as astropy's interval applies them: cuts that are reversed, equal or not numbers, and cuts closer together than 256 steps of a 32 bit float, such as a few counts on top of a large offset. Reversed cuts drew one flat color, and close ones lost shades or drew nothing. This replaces the invented limits of (0, 1) and low + 1. - The image mark is never compressed. With bqplot-image-gl's environment variable set to png it squeezed the unscaled pixels into 8 bits over their own range before the cuts were applied. - The limit on a stretch built into the colors drops from 0.1 to 0.05, so the square root stretch, whose first step was 16 of 255 levels, is applied to the pixels. And less code: scaling to levels fills one float32 buffer instead of working through the image in bands, which saved nothing once the percentile cuts had run and cost more for an image with a NaN; the colormap hook no longer has its own check for a batch; and the names added for this are private. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
cb75be2 to
2cbc338
Compare
The changelog and the docstring said that data edited in place is not shown until it is loaded again. It can be, in part: the limits are worked out from the data each time the cuts or stretch change, and pixels the cuts and stretch are applied to are read then as well, while the front end still holds the pixels sent before. Say that the picture may mix the two until the image is loaded again. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
A 4096 x 4096 camera frame is sent to the browser whole, 67 MB, when it is loaded, into a viewer that is 500 pixels across. These tests describe sending instead the mean of each block of pixels that lands on one screen pixel, and, once the view is zoomed in, the part of the image on view at the resolution that zoom needs, drawn over the coarse picture of the whole image. They fail: the viewer has no second picture and sends every pixel. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
Loading a 4096 x 4096 camera frame sent all 67 MB of it to the browser, which took about 15 s at 54 Mbit/s, to be drawn in a viewer 500 pixels across. An image with more pixels than the viewer can show is now averaged over squares of pixels, down to the size of the viewer, before it is sent: 512 x 512, 1 MB, for that frame. The picture is drawn over the coordinates of the whole image, so pixel coordinates, markers and the cursor readout are as they were, and the cuts are still worked out from every pixel. That picture is coarse once the view is zoomed in, so the part of the image on view is then sent too, at the resolution that zoom needs, as a second picture drawn over the first. A change of view made from Python sends it at once. A pan or zoom in the browser arrives as a stream of changes, and it is sent once, 0.3 s after the last of them; until then the browser stretches what it has, and the coarse picture stays underneath to fill what the sharp one does not cover. Both pictures share the color scale, so the cuts and a gentle stretch are still applied by the front end with no pixels sent, and a steep stretch is applied to both before they are sent, as 8 bit. The averages leave NaN pixels out, so that one bad pixel does not blank the square it is in. The coarse picture would then show through a NaN pixel of the sharp one as if it had a value, so it is hidden while the sharp picture has any. The new pixel_density argument sets how many pixels are sent for each screen pixel. Python cannot ask the browser, so the default is 1; 2 is as sharp as a high-density screen can show, at four times the data. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
The flag saying whether the front end applies the cuts and stretch was always the same as having no scaling stored for the pixels, so the colors now ask that. The method that worked out the limits had one caller and had become a wrapper around the cuts' own get_limits, so it is done where it is used. Co-written with Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX
2cbc338 to
d2ed30b
Compare
Stacked on #244. The first two commits here are that pull request; only the last two are new. Review and merge #244 first.
Loading an image into the bqplot
ImageWidgetsends every pixel to the browser: 67 MB for a 4096 x 4096 camera frame, to be drawn in a viewer 500 pixels across. #244 removed the resend on each change of cuts or stretch but left the load as it was. Measured from a stellarphot notebook in headless Chromium throttled to 54 Mbit/s, that load takes about 15 s per viewer, on 0.6.0 and on #244 alike.What changes
ImageWidget(pixel_density=1): how many pixels are sent for each screen pixel of the viewer. Python cannot ask the browser for the screen's density. 2 is as sharp as a high-density screen can show, at four times the data.Measured
Sizes are what the kernel hands the front end for a 4096 x 4096 float32 image in the default 500 pixel viewer.
pixel_density=1pixel_density=2LogStretchThe worst case at
pixel_density=1is a field just under 1000 pixels wide, which is sent unaveraged, about 4 MB.load_imagetakes 0.22 s in the kernel, of which the averaging is about 0.02 s.Checked in headless Chromium driving JupyterLab, over loopback, with a synthetic star field:
set_cuts,LogStretchand back to linear, screenshots are identical to Apply cuts and stretch in the browser instead of resending the image (bqplot) #244's, pixel for pixel.Not measured here: load time over a slow network with this branch, a JupyterHub, a real high-density screen.
What looks different
Choices worth a second opinion
Not changed
BQPLOT_IMAGE_GL_IMAGE_DATA_COMPRESSION=pngstill gives a black viewer, as it does on Apply cuts and stretch in the browser instead of resending the image (bqplot) #244: bqplot-image-gl then squeezes each array into 8 bits across its own range.https://claude.ai/code/session_01Gy3gmYu7t55HbLHWarbMKX