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

Aperta Adatta ai principianti
#129 4 commenti 0 reazioni 0 assegnatari Vedi su GitHub

Nessuno ha ancora preso questa issue.

Valutazione

Difficoltà
2/5
Tempo stimato
1-3 ore
Idoneità per principianti
72/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
javascript, python

Direzione di ricerca

La correzione è in lookup_table_serializer in src/trame_vtk/modules/vtk/serializers/lookup_tables.py, che scrive valueRange dove dovrebbe scrivere mappingRange (GetRange()), e chiama GetHueRange con un argomento che non accetta. Leggi le proprietà delle lookup table di vtk.js per confermare i nomi, poi aggiungi un test che serializza una lookup table e verifica mappingRange e hueRange. È fatto quando l'intervallo scalare fa il round-trip correttamente e la chiamata hue non solleva più un'eccezione.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

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)
Lingua principale
HTML
Stelle
37
Fork
21
Metriche di merge delle PR
Nessuna PR unita negli ultimi 30g

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di Kitware/trame-vtk

Tutte le issue di Kitware/trame-vtk

Issue simili

Altre issue su Data Visualization

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.