Skip to content

Apply cuts and stretch in the browser instead of resending the image (bqplot) - #244

Merged
mwcraig merged 5 commits into
astropy:mainfrom
mwcraig:bqplot-gpu-cuts-stretch
Dec 2, 2026
Merged

mwcraig merged 5 commits into
astropy:mainfrom
mwcraig:bqplot-gpu-cuts-stretch

Conversation

@mwcraig

@mwcraig mwcraig commented Nov 23, 2026

Copy link
Copy Markdown
Member

The bqplot ImageWidget applies 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:

  • The pixels are sent once, unscaled, when an image is loaded.
  • The cuts become the min and max of the color scale.
  • The stretch is built into the list of 256 colors.

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 LogStretch draws 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 than MAX_BUILT_IN_STEP (0.1) between neighboring colors is still applied to the pixels and resent when the cuts or stretch change, but as uint8, 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.

Change 0.6.0 This branch Screenshot vs. 0.6.0
Load image 67 MB 67 MB identical
Move cuts, linear 67 MB, ~1.8 s no image, <0.3 s identical
Set SqrtStretch 67 MB, ~1.8 s no image, <0.3 s differs by up to 17 of 255 levels
Set LogStretch 67 MB, ~1.8 s 17 MB, ~0.9 s identical
Move cuts under log 67 MB, ~1.9 s 17 MB, ~0.9 s identical
Change colormap no image no image identical

An 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, SqrtStretch is 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

  • Loading an image is still one full-size send.
  • Going from a steep stretch back to a gentle one sends the unscaled pixels again, once.
  • Only the bqplot backend is touched.

🤖 Generated with Claude Code

https://claude.ai/code/session_01Gy3gmbgEL7BGJ5P8ucd5mG

mwcraig and others added 2 commits November 23, 2026 12:11
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
mwcraig marked this pull request as ready for review November 23, 2026 18:43

@mwcraig mwcraig left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. Stale pixels when a float32 array is edited in place and reloaded (reproduced).
  2. float32 precision: images with a large offset and small structure become a flat field (reproduced).
  3. 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-line out= 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_changed is wired to update_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).

Comment thread astrowidgets/bqplot.py
Comment on lines +741 to +744
self._astro_im.set_data(
np.asarray(self._data, dtype=np.float32),
reset_view=False,
)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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").

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, and agreed. Re-run today against 6a51b5f: after load_image(a); a[:] = a + 5000; load_image(a) the image trait notifies 0 times for native float32 and for CCDData wrapping float32, and once for float64 and uint16, while the limits move to the new data in every case. On main the float32 reload resends.

The fix to make is the simple one: always copy, np.array(self._data, dtype=np.float32). I would not keep the pass-through with an explicit send_state("image"): it leaves the trait holding the caller's array, so what the kernel thinks the browser has can still drift from what was sent. The copy also stops costing anything for big images once #246 is in, because an image bigger than the viewer is averaged into a fresh array there.

One part a copy does not fix: editing the array and then calling only set_cuts. That sends no pixels today for any dtype, because pixels are now sent once by design; main happened to resend. So load_image has to be the stated way to show edited data, which is worth a sentence in the changelog.

Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
# size, and refuses the rest. A float32 image is not
# copied.
self._astro_im.set_data(
np.asarray(self._data, dtype=np.float32),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed. Re-running the table gives 4096 → 1, 100 → 1, 984 → 1 and 10 → 3 distinct values after the cast, and in the first three the two limits are the same float32. (984 against the table's 975 for int64 is just the random draw.)

Of the two options I'd take the second, and decide it from the cuts rather than the data: if the limits are not at least 256 float32 steps apart,

abs(high - low) <= LEVELS * np.spacing(np.float32(max(abs(low), abs(high))))

scale in Python, as for a steep stretch. A reviewer tried that today and it gives the exact shade counts for these cases. The cost is a resend per change of cuts, as uint8, for such images only.

The offset idea keeps those images on the fast path, but only if the offset is fixed per image and not tied to low, otherwise every change of cuts resends anyway; and it would have to be carried through the averaging in #246. That is more machinery than this edge deserves.

I also checked that the kernel path stays exact for these inputs with the loop-free scale_to_levels from the band-loop thread, since the subtraction happens in the input's precision before the float32 buffer is written: exact for the int64 and int32 rows, and 1 level off in 2 of 90000 pixels for 1e9 + U(0, 10).

Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
Comment on lines +674 to +677
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, both parts. set_cuts((400, 100)) gives limits (400, 401) here; on main the image sent for the same call is inverted (correlation with the data of -1). Agreed on high == low.

On the second part: a constant image at 3e7 or 1e9 gets limits that are equal as float32, and at 1e20 low + 1.0 == low even in float64. main draws all of them in the first color. Rather than a second formula such as low + max(1.0, abs(low) * 1e-6), I'd let the rule from the float32 thread cover it: limits the GPU cannot tell apart go down the kernel path, where astropy's interval already does the right thing for equal limits by skipping the division. Checked: that path draws constant 3e7 and constant 1e20 as level 0.

Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
Comment on lines +671 to +673
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: jupyter_client packs a NaN limit as the string "nan" (with a deprecation warning), cuts of (0, np.inf) come out as limits (0, 1), and astropy maps every pixel to 0 for those cuts.

It was not so much deliberate as the nearest safe value. If the routing rule from the float32 thread goes in, this guard can use it too: limits that are not finite go down the kernel path and astropy decides, as on main (everything in the first color for (0, inf), nothing drawn for NaN). That removes the invented (0, 1) instead of documenting it. I have not tried that combination; if it turns out awkward, the fallback is a comment saying the contrast is arbitrary.

Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
Comment on lines +454 to +461
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)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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_limits runs first on every update, and with the default AsymmetricPercentileInterval its get_limits peaks 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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed: drop the loop. Re-measured today on 4096 x 4096 with LogStretch, peak by tracemalloc:

Input This loop The out= version in this comment
float32 29 MB 84 MB
float64 42 MB 84 MB
float32 with one NaN 155 MB 84 MB

The default percentile get_limits peaks at 134 MB before either runs, so under the default cuts the loop saves nothing at the peak. Times are the same within noise.

The version in this comment is the one to use. For float64 input it differed from the loop by 1 level in 97 of 16.7 million pixels; uint16 and float32 were identical. It also stays exact for large-offset data, which matters if such data is sent this way (see the float32 thread).

Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment on lines +567 to +570
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: recording the argument both as passed and as a copy shows {'image'} at the time of the call and set() afterwards.

Agreed. I'd observe the trait rather than patch send_state, since it uses the real object and needs no mocker:

sends = []
image_mark.observe(sends.append, names="image")
change(self.image)
assert sends == []

The tests in #246 already count sends that way. Not applied yet.

— Written by Claude at @mwcraig's direction.


assert_displayed(self.image, arr, cuts, apviz.LinearStretch())

def test_float32_image_is_not_copied(self):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Once the image is always copied this test goes, replaced by one that edits the array in place, reloads, and checks that the image trait notified and that the pixels held for the browser are the new values. Not applied yet.

— Written by Claude at @mwcraig's direction.

@pytest.mark.parametrize(
"dtype", [np.uint8, np.uint16, np.int32, np.float32, np.float64]
)
def test_image_is_sent_as_float32(self, dtype):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Right: every value in the list is exact in float32, so the test shows only that the dtype is float32.

Agreed on a high-offset case, with one adjustment. It belongs with the fix in the float32 thread, as a check of what the screen shows (2**25 + arange(10) as int32 should give 10 distinct shades between its own cuts) and not of the bytes sent, because after that fix such data is no longer sent as raw float32. Not applied yet.

— Written by Claude at @mwcraig's direction.

(apviz.PowerStretch(0.2), False),
],
)
def test_stretch_fits_in_colors(stretch, fits):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: with MAX_BUILT_IN_STEP = 0.065 all 128 tests pass.

Agreed on both points: pin the boundary with LogStretch(a=100) (0.072) once the value is settled, and use AsinhStretch() (0.013) for the no-resend case so that it does not flip when the value moves. Not applied yet.

— Written by Claude at @mwcraig's direction.

arr = np.asarray(arr)
low, high = cuts.get_limits(arr)

if stretch is None or stretch_fits_in_colors(stretch):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Partly agreed.

assert_displayed sharing stretch_fits_in_colors and bqcolors with the code is acceptable for what it is used for, which is checking that the right image, limits and colormap were sent after some sequence of calls. It is not where the formulas are checked, and I would not rebuild them independently inside it: that would be a second implementation to keep in step with the first. The independent checks are, as you say, test_bqcolors_builds_in_a_stretch and test_screen_matches_astropy_scaling through screen_levels.

The suggestion for screen_levels I'd take: cast the pixels and both limits to float32 before the arithmetic, and treat a NaN result as undrawn. It is two or three lines, and it is what would have caught the large-value cases. Not applied yet.

— Written by Claude at @mwcraig's direction.

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Unresolved issues can erase valid image contrast, cause division by zero for large constant images, and exhaust memory when processing NaN-masked images.

3 open issues
What changed in this PR

Reduces image transfers in the bqplot backend by applying cuts and suitable stretches through the browser’s color scale.

Changes:

  • Sends raw pixels for gentle stretches and compact scaled pixels for steep stretches.
  • Avoids image resends when removing catalogs.
  • Adds rendering, transfer, dtype, and edge-case regression tests.
File Description
CHANGES.rst Documents reduced image transfers and stretch fallback.
astrowidgets/​tests/​test_widget_api_bqplot.py Tests rendering accuracy and transfer behavior.
astrowidgets/​bqplot.py Implements color-scale updates, compact scaling, and conditional refreshes.

Review effort: Balanced

Comment thread astrowidgets/bqplot.py Outdated
# size, and refuses the rest. A float32 image is not
# copied.
self._astro_im.set_data(
np.asarray(self._data, dtype=np.float32),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: int32 values 1,000,000,000 to 1,000,000,002 become a single float32 value, and both limits become the same float32.

This is the problem in #244 (comment), and the plan there is your second suggestion: when float32 cannot separate the cuts by 256 steps, scale in the kernel, on the existing uint8 path. I would not rebase the pixels. The offset would have to be fixed per image to avoid a resend on every change of cuts, which is more machinery than this edge needs. A high-offset test goes in with the fix. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
Comment on lines +457 to +458
if np.isnan(scaled).any():
return np.asarray(stretch(interval(data)), dtype=np.float32)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The facts are right: with one NaN in a 4096 x 4096 float32 image this function peaks at 155 MB, against 29 MB without.

I disagree with the remedy. More banding goes the wrong way. The bands save nothing at the peak under the default cuts, because the percentile computation that runs first takes 134 MB by itself, and "can exhaust a memory-limited kernel" overstates it for the same reason. The plan in #244 (comment) is to drop the loop for a single float32 buffer filled through out=, which peaks at 84 MB with or without NaNs. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed: a constant image at 1e20 gets limits (1e20, 1e20), since adding 1 changes nothing even in float64, and at 3e7 or 1e9 the two limits are the same float32. main draws all of these in the first color.

Covered by the fix planned in #244 (comment): limits the GPU cannot tell apart are scaled in the kernel, where astropy handles equal limits. Checked that this path gives level 0 for constant 3e7 and constant 1e20. The regression test will go beyond 7.0. Not applied yet.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ok, but a constant image of 1e20 is an absolutely stupid image....

@mwcraig mwcraig left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Four things draw a wrong picture here that main draws correctly; I would fix them before merging. Two are easy to hit (a reused float32 array, inverted cuts), one needs an environment variable, one is a corner case. The details and suggested changes are in the inline comments, most important first:

  1. A float32 array changed in place and loaded again is not sent (bqplot.py line 742).
  2. Inverted cuts draw one flat color (line 674).
  3. BQPLOT_IMAGE_GL_IMAGE_DATA_COMPRESSION=png gives a badly wrong picture (comment on line 753; the fix is where the mark is created, line 81).
  4. Narrow cuts on large values lose shades or draw nothing (line 746). Not ordinary CCD frames.
  5. A loop in test_changing_the_display_does_not_resend_the_image can never fail (tests, lines 567-570).

Then four places where lines can go, about 68 from the tests and 14 from bqplot.py, also inline.

Looked at and not asking for a change

  • Square-root stretch at the faint end. Built into 256 colors, SqrtStretch is up to 0.0625 of full scale darker than astropy just above the low cut, where main was within 0.004 for every stretch. Color i is taken at i/255, which lies inside the bin the front end uses it for, so this is the tolerance the description already states, not an indexing error. Taking colors at bin centers would lift pixels below the low cut off black, so it is not a clean fix. The real lever is MAX_BUILT_IN_STEP: about 0.05 sends sqrt down the exact path. Measured by running.
  • Order of the image and the color limits. The image mark flushes before the color scale, so when both change (a switch between a built-in and an applied stretch, or a new image) one frame of new pixels against old limits is possible. Read from the code only, not seen in a browser. Reversing the order would be worse: the small limits message would land first and sit over the old pixels for the whole transfer.
  • Commit layout. 9220601 has the tests and the implementation together; the repository's CLAUDE.md asks for the tests in their own commit first.

How this was checked

Two rounds: three independent reviewers (correctness, simplification, and OpenAI Codex), then a fresh reviewer who tried to disprove each finding. 13 findings were raised; the 4 bugs, the test that cannot fail and all 5 simplifications survived, the rest are in the list above. "Confirmed by running" means Python run against this branch and against main, with what the screen shows worked out by redoing the shader's arithmetic in float32. Nothing here was looked at in a real 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.

Comment thread astrowidgets/bqplot.py Outdated
# size, and refuses the rest. A float32 image is not
# copied.
self._astro_im.set_data(
np.asarray(self._data, dtype=np.float32),

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A float32 array changed in place and loaded again is not sent. np.asarray returns the caller's own array when it is already native float32, and the image trait sends only when the new value differs from the old (traittypes.Array.set compares with np.array_equal). So

viewer.load_image(buf)
buf[:] = new_frame
viewer.load_image(buf)

sends no image, for a bare array and for a CCDData wrapping it, and the browser keeps the old pixels under cuts worked out from the new ones. On main the same sequence resends. Confirmed by running. float32 read straight from FITS is big-endian and is copied, so it escapes; a reused native float32 buffer does not.

Suggested change: always copy, np.array(self._data, dtype=np.float32), and delete test_float32_image_is_not_copied. That is one 64 MB copy for a 4096 x 4096 frame. Changing the array and then calling only set_cuts stays stale either way; load_image is the refresh.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats #244 (comment) from the 23 November review; today's review was written without reading the threads already here. Confirmed again and agreed there: always copy. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
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
if high <= low:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Inverted cuts draw one flat color. set_cuts((1300, 1100)) on an image spanning 1100 to 1299 comes out as limits (1300, 1301), so every pixel is drawn in the first color. On main the same call gives a negative image: 200 shades, within 0.004 of astropy. Confirmed by running.

The front end needs no protection from this. Its shader computes (value - min) / (max - min) with nothing special for min above max, which is the inverted ramp astropy's ManualInterval(1300, 1100) gives (read from the shader source, not seen in a browser).

Suggested change: if high == low:. Tried: the inverted case then matches astropy to within 0.004.

A related corner: for a constant image above 2^24 (about 1.7e7), low + 1.0 is the same float32 as low by the time it reaches the GPU, so nothing is drawn. The fallback suggested on line 746 covers it.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats #244 (comment). Agreed there: high == low, with limits the GPU cannot separate going to the kernel path. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
scale_to_levels(self._data, low, high, stretch),
reset_view=False,
)
# Both forms scale_to_levels sends run from 0 to 1 as the

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BQPLOT_IMAGE_GL_IMAGE_DATA_COMPRESSION=png (or webp) gives a badly wrong picture. With it set, bqplot-image-gl squeezes each array to 8 bits across its own minimum to maximum before sending (array_to_image in bqplot_image_gl/serialize.py). main applied the cuts first, so that was harmless. Now:

  • Gentle stretch: a uint16 background of 1100 to 1299 with one pixel at 65535 shows 2 shades where astropy gives 133.
  • Default LogStretch: the uint8 levels arrive with range (0, 255) while the color limits are (0, 1), so every level of 1 or more is pure white: 70% of the image, where astropy has 4%. This comment does not hold under compression.

Confirmed by running with the variable set and decoding the PNG that would be sent. Only people who set the variable are affected, but they are the slow-network users this change is for.

Suggested change: pass compression="none" where the ImageGL mark is created (line 81). Tried: the raw array is then sent whatever the variable says.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats the second point of #244 (comment). Re-run today: 2 shades against 133 for the linear case, and 70% of the image in the top color against 5% for log. Agreed: compression="none". Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py
reset_view=False,
)
self._front_end_has_pixels = True
self._astro_im.set_color_limits(low, high)

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Narrow cuts on large values lose shades, or draw nothing. A corner case, but new here. The pixels and both limits are float32 by the time the GPU subtracts them, where main applied the cuts in float64 in Python. Confirmed by running, with the shader's arithmetic redone in float32:

  • float64 or int32 data at 2^24 + 0..10 with cuts 10 apart: 6 shades where exact scaling gives 11.
  • A float64 map of Julian dates (2460000.5 + 0..0.01) with cuts 0.01 apart, or data near 1e9 with cuts 16 apart: the two limits are the same float32 and no pixel is drawn.
  • Data near 50000 with cuts 10 apart: fine, 256 shades.

Raw and calibrated CCD frames are not affected: 256 shades need a cut range above roughly 3e-5 of the pixel value, which is 2 counts at 65535.

Suggested change (about 6 lines, tried): when abs(high - low) <= LEVELS * np.spacing(np.float32(max(abs(low), abs(high)))), take the existing branch that scales the pixels in Python, and have _colors follow the same decision.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats #244 (comment). Agreed there, with this comment's test (limits less than 256 float32 steps apart) as the rule for falling back to the kernel.

One number re-checked: data near 50000 with cuts 10 apart keeps 2044 distinct float32 values, so it stays on the fast path with all 256 shades, as stated. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment on lines +567 to +570
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

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This loop can never fail. hold_sync calls self.send_state(self._states_to_send) and then clears that same set, so by the time the test reads call_args_list every recorded argument is an empty set.

Confirmed by running: with set_cuts changed so that it does resend the image, the keys are ['image'] at the time of the call and set() when the test looks, and all five cases still pass once the is assertion below is removed. That assertion, image_mark.image is sent_before, is what catches a resend.

Suggested change: delete the loop, the spy and the mocker argument.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats #244 (comment). Agreed there: the loop and the spy go, replaced by observing the image trait. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
data = np.asarray(data)
interval = apviz.ManualInterval(low, high)
levels = np.empty(data.shape, dtype=np.uint8)
for start in range(0, data.shape[0], _ROWS_PER_BAND):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The banding can go, with _ROWS_PER_BAND and test_scale_to_levels_is_the_color_each_pixel_is_drawn_in (about 34 lines). Scaling the whole image in place gives identical results:

scaled = interval(data)
stretch(scaled, out=scaled)
scaled *= LEVELS
np.minimum(scaled, LEVELS - 1, out=scaled)

followed by the NaN check and the cast to uint8 as now. Peak extra memory for 4096 x 4096 float32, measured with tracemalloc: 28 MB banded, 80 MB in place, 128 MB on main. With a NaN anywhere the banded version already redoes the whole image and peaks at 148 MB. Speed is the same.

The dedicated test exists to cross a band boundary; breaking the rounding or the clamp at 255 still fails six other tests, and test_scale_to_levels_keeps_nans shrinks to a 10 x 4 image. Tried.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed on dropping the loop; this repeats #244 (comment).

One correction to the snippet here. As written, scaled = interval(data) allocates a float64 result for integer and float64 input: 144 MB at the peak for uint16 in the second-round measurement. The 80 MB figure holds for every dtype only in the earlier thread's version, which fills one float32 buffer through out= (84 MB today for float32, float64 and uint16). That is the one to use.

On deleting test_scale_to_levels_is_the_color_each_pixel_is_drawn_in: fine. Its expected value is the code's own formula restated, and the independent check of the steep path is test_screen_matches_astropy_scaling with LogStretch. Not applied yet.

— Written by Claude at @mwcraig's direction.

assert spy_image.call_count == 2
assert_displayed(self.image, arr, cuts, stretch)

def test_colormap_change_never_resends_the_image(self, mocker):

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test and test_back_to_a_gentle_stretch_sends_the_pixels_again below repeat the setup of test_steep_stretch_is_applied_to_the_pixels. Both can become a few lines at the end of that test (about 30 lines fewer):

# A colormap is only a list of colors: the image is not sent.
self.image.set_colormap("viridis")
assert spy_image.call_count == 2
assert_displayed(self.image, arr, cuts, stretch, colormap="viridis")

# The front end now holds scaled pixels, so a gentle stretch has to
# send the pixels as they are once more.
self.image.set_stretch(apviz.LinearStretch())
assert_displayed(self.image, arr, cuts, colormap="viridis")

Tried: it passes, and it fails if a colormap change goes through the full update or if the return to a gentle stretch does not resend.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed to fold them. I ran the reviewer's folded file and it passes.

One change to the proposed lines: spy_image.call_count counts flushes of the mark's state, not sends of the image, so == 2 would still hold if a colormap change sent the image inside a flush that was happening anyway. With the trait observer from #244 (comment) the added lines become:

sends = []
image_mark.observe(sends.append, names="image")

# A colormap is only a list of colors: the image is not sent.
self.image.set_colormap("viridis")
assert sends == []
assert_displayed(self.image, arr, cuts, stretch, colormap="viridis")

# The front end now holds scaled pixels, so a gentle stretch has to
# send the pixels as they are once more.
self.image.set_stretch(apviz.LinearStretch())
assert_displayed(self.image, arr, cuts, colormap="viridis")

That form has not been run. Not applied yet.

— Written by Claude at @mwcraig's direction.

assert greys[-1] == 1


def test_bqcolors_linear_stretch_changes_nothing():

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Redundant. An image is loaded with LinearStretch() stored, and every assert_displayed call that leaves out the stretch compares the colors with bqcolors(colormap). Making a linear stretch alter the colors fails six of those tests without this one. Tried.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, delete. From reading: assert_displayed compares the colors with bqcolors(colormap, stretch=stretch), where stretch is None in every call that leaves it out, while the stretch stored for a freshly loaded image is LinearStretch(). So a linear stretch that altered the colors would fail those calls. The second-round reviewer ran that mutation and six tests failed without this one. Not applied yet.

— Written by Claude at @mwcraig's direction.

Comment thread astrowidgets/bqplot.py Outdated
self._astro_im.set_color(
bqcolors(self.get_colormap(image_label=image_label))
)
if self._batching:

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This early return is not needed. Only load_image's batch calls _apply_colormap, and _render_image has already marked the display stale by then. The messages sent are identical with and without it, on a first load and on a reload with a log stretch and viridis. Tried.

— Written by Claude at @mwcraig's direction.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This repeats #244 (comment). Confirmed there: the file's 128 tests pass without the three lines. Agreed, remove. Not applied yet.

— 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
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
@mwcraig
mwcraig merged commit db93b88 into astropy:main Dec 2, 2026
9 checks passed
@mwcraig
mwcraig deleted the bqplot-gpu-cuts-stretch branch December 2, 2026 19:28
@mwcraig mwcraig mentioned this pull request Dec 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants