A lookup table's scalar range is sent as valueRange, so a scalar bar with its own table reads 0 to 255

Open Beginner friendly
#129 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
2/5
Estimated time
1-3 hours
Newbie friendliness
72/100
Issue type
Bug
Clarity
Clearly specified
Activity status
Active
Tech stack
javascript, python

Research direction

The fix is in lookup_table_serializer in src/trame_vtk/modules/vtk/serializers/lookup_tables.py, which writes valueRange where it should write mappingRange (GetRange()), and calls GetHueRange with an argument it does not accept. Read the vtk.js lookup-table properties to confirm the names, then add a test that serializes a lookup table and checks mappingRange and hueRange. Done when the scalar range round-trips and the hue call no longer raises.

Written by the indexing model from the issue text.

Description

This issue was researched and drafted by an AI agent (Claude Code) working with the geovista maintainer, who reviewed it before it was posted.

A lookup table's scalar range is sent as valueRange, which vtk.js reads as HSV brightness

lookup_table_serializer writes lookup_table.GetRange(), the table's scalar range, as "valueRange". In vtk.js, as in VTK, a lookup table's valueRange is the HSV value (brightness) range that forceBuild ramps through. The scalar range is mappingRange on vtkScalarsToColors, which defaults to [0, 255], so the client never receives the range.

A mesh still colours correctly, because the vtk.js mapper calls lookupTable.setRange(scalarRange) when it renders, unless useLookupTableScalarRange is set. A scalar bar whose lookup table isn't also a mapper's keeps [0, 255], and its ticks read 0 to 250 whatever the data.

pyvista up to 0.49 gives a scalar bar its own copy of the lookup table when background_color is set. pyvista main shares the mapper's table instead (pyvista/pyvista#9181), but any scalar bar with a table of its own is affected. This reproduces it with pyvista 0.49.2, trame-vtk 2.11.17 and VTK 9.7.2:

import numpy as np
import pyvista as pv

mesh = pv.Sphere()
mesh.point_data["temperature"] = np.linspace(271.35, 303.27, mesh.n_points)

p = pv.Plotter(off_screen=True)
# background_color gives the scalar bar its own copy of the lookup table
p.add_mesh(mesh, scalars="temperature", scalar_bar_args={"background_color": "white"})
p.export_vtksz("repro.vtksz")

Rendered in trame's static viewer, on the left as exported, and on the right with each lookup table's valueRange renamed to mappingRange in index.json:

The scalar bar reads 0 to 250 as exported, and 271 to 303 with mappingRange

geovista's plotter sets background_color, so its documentation hits this. For example, lfric_sst has data from 271 to 303 K and a bar that reads 0 to 250:

geovista's lfric_sst scene: the scalar bar reads 0 to 250 as exported, and 271 to 303 K with mappingRange

hueRange is always [0.5, 0]

The same function fills its hue range with lookup_table.GetHueRange(lookup_table_hue_range), but VTK's Python wrapping of GetHueRange takes no arguments. The call raises a TypeError, which suppress(Exception) swallows, so every table is sent with the fallback [0.5, 0]. VTK's default is [0, 0.66667]. This matters only when the client rebuilds the table, since a sent table takes precedence.

Suggested fix
properties = {
    "numberOfColors": lookup_table.GetNumberOfColors(),
    "mappingRange": lookup_table.GetRange(),
    "hueRange": lookup_table.GetHueRange(),
    "saturationRange": lookup_table.GetSaturationRange(),
    "valueRange": lookup_table.GetValueRange(),
    ...
}

vtk.js's set() applies mappingRange through setMappingRange. I checked this by editing exported scenes as above. I haven't checked a live trame view with local rendering, which uses the same serializer.

We'd be glad to open a pull request with this change and a test that serializes a lookup table and checks its mappingRange.

The scripts behind the renders

render.py draws a scene in trame-vtk's static viewer in headless chromium (Playwright). patch_luts.py makes the right-hand scenes.

patch_luts.py

"""Copy a .vtksz scene, writing each lookup table's range as mappingRange, not valueRange.

This is what trame-vtk's lookup_table_serializer would write if it named the
table range as vtk.js names it: vtkScalarsToColors.mappingRange. vtk.js reads
valueRange as the HSV value (brightness) range, which a supplied table ignores.
"""
import json
import sys
import zipfile


def walk(node):
    if isinstance(node, dict):
        if node.get("type") == "vtkLookupTable":
            props = node["properties"]
            props["mappingRange"] = props.pop("valueRange")
        for v in node.values():
            walk(v)
    elif isinstance(node, list):
        for v in node:
            walk(v)


src, dst = sys.argv[1], sys.argv[2]
with zipfile.ZipFile(src) as z:
    doc = json.loads(z.read("index.json"))
walk(doc["scene"])
with zipfile.ZipFile(dst, "w", zipfile.ZIP_DEFLATED) as z:
    z.writestr("index.json", json.dumps(doc))
print(dst)

render.py

"""Render .vtksz scenes in trame's static vtk.js viewer, in headless chromium.

Usage: python render.py <out.png> <title> <scene.vtksz> [<title> <scene.vtksz> ...]
Panels are laid side by side with their titles.
"""
import asyncio
import sys
from pathlib import Path

from PIL import Image, ImageDraw
from playwright.async_api import async_playwright
from trame_vtk.tools.vtksz2html import embed_data_to_viewer_file

W, H = 900, 700


async def render(html: Path, png: Path) -> None:
    async with async_playwright() as pw:
        browser = await pw.chromium.launch(
            args=["--use-gl=angle", "--use-angle=swiftshader", "--enable-unsafe-swiftshader"]
        )
        page = await browser.new_page(viewport={"width": W, "height": H})
        await page.goto(html.resolve().as_uri())
        await page.wait_for_selector("canvas", timeout=120000)
        await page.wait_for_timeout(8000)
        await page.screenshot(path=str(png))
        await browser.close()


out = Path(sys.argv[1])
pairs = list(zip(sys.argv[2::2], sys.argv[3::2]))
panels = []
for title, scene in pairs:
    scene = Path(scene)
    html = scene.with_suffix(".html")
    if scene.suffix != ".html":
        embed_data_to_viewer_file(scene.read_bytes(), html)
    png = scene.with_name(scene.stem + "_browser.png")
    asyncio.run(render(html, png))
    panels.append((title, Image.open(png).convert("RGB")))

sheet = Image.new("RGB", (len(panels) * (W + 20), H + 40), "white")
draw = ImageDraw.Draw(sheet)
for i, (title, image) in enumerate(panels):
    sheet.paste(image, (i * (W + 20), 40))
    draw.text((i * (W + 20) + 10, 12), title, fill="black")
sheet.save(out)
print(out)
Dominant language
HTML
Stars
37
Forks
21
PR merge metrics
No merged PRs in 30d

Getting set up

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from Kitware/trame-vtk

All issues in Kitware/trame-vtk

Similar issues

More Data Visualization issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.