itkwidgets
itkwidgets copied to clipboard
How to add points at runtime?
I created a new .ipynb
notebook. With only one cell in it. I want to add points on slider drag. So I wrote this:
#Based on https://docs.pyvista.org/examples/01-filter/poly-ray-trace.html#sphx-glr-examples-01-filter-poly-ray-trace-py
# and on https://github.com/InsightSoftwareConsortium/itkwidgets/blob/master/examples/InteractiveParameterExploration.ipynb
from ipywidgets import interactive
import ipywidgets as widgets
from itkwidgets import view
import pyvista as pv
import numpy as np
from random import random
# Create source to ray trace
sphere = pv.Sphere(radius=0.85)
# Define line segment
start = [0, 0, 0]
stop = [random(), 1, random()]
# Perform ray trace
points, ind = sphere.ray_trace(start, stop)
# Create geometry to represent ray trace
ray = pv.Line(start, stop)
intersection = pv.PolyData(points)
points = np.concatenate((points, [start, stop]))
viewer = view(point_sets=[points], point_set_colors=['red'], geometries=[sphere, ray], geometry_colors=['white', 'blue'])
# Define a function to use with ipywidgets `interactive`
def smooth_and_view(radius=2):
stop = [random(), 1, random()]
points, ind = sphere.ray_trace(start, stop)
intersection = pv.PolyData(points)
points = np.concatenate((points, [start, stop]))
print("before:")
print(len(viewer.point_sets))
viewer.point_sets.append(points)
print("after:")
print(len(viewer.point_sets))
slider = interactive(smooth_and_view, radius=(0, 10, 1))
widgets.VBox([viewer, slider])
Its rendering looks similar to this:
The len
of viewer.point_sets
does change, while rendering does not, pointset selector does not update, as do not update 3d visuals.
The code seems to suggest it shall be changeable and updatable. What do I get wrong - how to add points at runtime?
Very close!
Instead of:
viewer.point_sets.append(points)
try
viewer.point_sets = points
due to the way traitlets handles changes. traitlets are used by ipywidgets / jupyter-widgets and itkwidgets.
I am looking into adding a picked_point
traitlet, which may also help with #269.