Skip to content

Commit

Permalink
Vtk various enhancements (#606)
Browse files Browse the repository at this point in the history
  • Loading branch information
xavArtley authored and philippjfr committed Sep 30, 2019
1 parent 5b8a3b9 commit f4f2579
Show file tree
Hide file tree
Showing 12 changed files with 913 additions and 240 deletions.
88 changes: 83 additions & 5 deletions examples/reference/panes/VTK.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,12 @@
" - w: set representation of all actors to *wireframe*\n",
" - v: set representation of all actors to *vertex*\n",
" - r: center the actors and move the camera so that all actors are visible\n",
" \n",
" The mouse must be over the pane to work\n",
" <br>**Warning**: These keybindings may not work as expected in a notebook context, if they interact with already bound keys\n",
"* **``orientation_widget``** (bool): A boolean to activate/deactivate the orientation widget in the 3D pane. This widget is clickable and allows to rotate the scene in one of the orthographic projections.\n",
"* **``object``** (str or object): Can be a string pointing to a local or remote file with a `.vtkjs` extension, or a `vtkRenderWindow` object \n",
"\n",
"* **``serialize_on_instantiation``** (bool): It defines when the serialization of the 3D scene occurs. If set to `True` (default) the scene object is serialized when the panel is created else when the panel is displayed to the screen. This parameter is constant, once set it can't be modified\n",
"___"
]
},
Expand All @@ -46,7 +49,8 @@
"outputs": [],
"source": [
"dragon = pn.pane.VTK('https://raw.githubusercontent.com/Kitware/vtk-js/master/Data/StanfordDragon.vtkjs',\n",
" sizing_mode='stretch_width', height=400)\n",
" sizing_mode='stretch_width', height=400, enable_keybindings=True, orientation_widget=True,\n",
" serialize_on_instantiation=True)\n",
"dragon"
]
},
Expand All @@ -66,6 +70,16 @@
"dragon.object = \"https://github.com/Kitware/vtk-js-datasets/raw/master/data/vtkjs/TBarAssembly.vtkjs\""
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"dragon.orientation_widget = False # remove the orientation widget\n",
"dragon.enable_keybindings = False # remove the key bindings"
]
},
{
"cell_type": "markdown",
"metadata": {},
Expand Down Expand Up @@ -144,9 +158,9 @@
"metadata": {},
"outputs": [],
"source": [
"if dragon.camera:\n",
" dragon.camera['viewAngle'] = 50\n",
" dragon.param.trigger('camera')"
"if dragon1.camera:\n",
" dragon1.camera['viewAngle'] = 50\n",
" dragon1.param.trigger('camera')"
]
},
{
Expand Down Expand Up @@ -236,6 +250,70 @@
"\n",
"geom_pane.param.trigger('object')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Construction of ColorBars for VTK objects\n",
"\n",
"When working with VTK objects, a `scalar array` can be associated with `vertices` or `cells` of an `actor` `mesh`. With the help of a `look-up table`, scalar values are associated with colors at rendering time.\n",
"\n",
"**Colorbars** are used to represent the association between scalars and colors. The `VTK pane` allows constructing colorbars for the `vtk actors` in the scene using the `construct_colorbars` method. This method will return a bokeh plot containing colorbars for each actor that uses a scalar array and a lookup table.\n",
"\n",
"If no colorbar is found in the scene the method return `None`."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"We present an example of the use of `construct_colorbars`. Here we use `pyvista` module which simplifies the construction of VTK scenes"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pyvista as pv\n",
"import numpy as np\n",
"def make_points():\n",
" \"\"\"Helper to make XYZ points\"\"\"\n",
" theta = np.linspace(-4 * np.pi, 4 * np.pi, 100)\n",
" z = np.linspace(-2, 2, 100)\n",
" r = z**2 + 1\n",
" x = r * np.sin(theta)\n",
" y = r * np.cos(theta)\n",
" return np.column_stack((x, y, z))\n",
"\n",
"def lines_from_points(points):\n",
" \"\"\"Given an array of points, make a line set\"\"\"\n",
" poly = pv.PolyData()\n",
" poly.points = points\n",
" cells = np.full((len(points)-1, 3), 2, dtype=np.int)\n",
" cells[:, 1] = np.arange(0, len(points)-1, dtype=np.int)\n",
" cells[:, 2] = np.arange(1, len(points), dtype=np.int)\n",
" poly.lines = cells\n",
" return poly\n",
"\n",
"points = make_points()\n",
"line = lines_from_points(points)\n",
"line[\"scalars\"] = np.arange(line.n_points) # By default pyvista use viridis colormap\n",
"tube = line.tube(radius=0.1) #=> the object we will represent in the scene\n",
"\n",
"\n",
"#pyvista plotter => it constructs a vtkRenderWindow under the attribute ren_win\n",
"pl = pv.Plotter(notebook=True)\n",
"pl.camera_position = [(4.440892098500626e-16, -21.75168228149414, 4.258553981781006),\n",
" (4.440892098500626e-16, 0.8581731039809382, 0),\n",
" (0, 0.1850949078798294, 0.982720673084259)]\n",
"\n",
"pl.add_mesh(tube, smooth_shading=True)\n",
"pan = pn.panel(pl.ren_win, sizing_mode='stretch_width', orientation_widget=True)\n",
"pn.Row(pn.Column(pan, pan.construct_colorbars()), pn.pane.Str(type(pl.ren_win), width=500))"
]
}
],
"metadata": {
Expand Down
101 changes: 101 additions & 0 deletions examples/reference/panes/VTKVolume.ipynb
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
{
"cells": [
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import panel as pn\n",
"pn.extension('vtk')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The ``VTKVolume`` pane renders 3d volumetric data defined on regular grids. It may be constructed from a 3D NumPy array or a `vtkVolume`. The pane provides interactive control over the color opacity to look through the volume.\n",
"\n",
"#### Parameters:\n",
"\n",
"For layout and styling related parameters see the [customization user guide](../../user_guide/Customization.ipynb).\n",
"\n",
"* **``object``** (ndarray or object): Can be a 3d numpy array or an instance of`vtkImageData` class\n",
"\n",
"* **``spacing``** (3-tuple): Define the distance between 2 adjacent voxels in the 3 dimensions. By default the value is (1,1,1)\n",
"\n",
"* **``origin``** (3-tuple): Origin of the volume in the scene. By default value is (0,0,0)\n",
"\n",
"* **``max_data_size``** (Number): Maximum data size (in MB) of the data array allowed to be passed through the websockets without subsampling. If the data exceeded this size data are downsampled using scipy if installed or by taking 1 sample on N (N choosen to have an array size smaller than max_data_size) in each dimension \n",
"___"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The simplest way to create a VTKVolume pane is to use a 3d numpy array. The spacing is used to produced a \n",
"rectangular parallelepiped instead of a cube."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"pn.panel(np.random.rand(100,100,100), sizing_mode='stretch_width', spacing=(3,2,1))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Alternatively the pane maybe constructed from a `vtkImageData` object. This type of object can be construct directly with vtk or pyvista module:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"import pyvista as pv\n",
"from pyvista import examples\n",
"\n",
"# Download a volumetric dataset\n",
"vol = examples.download_head()\n",
"pn.panel(vol, sizing_mode='stretch_width')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.2"
}
},
"nbformat": 4,
"nbformat_minor": 4
}
32 changes: 30 additions & 2 deletions panel/models/vtk.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

from ..compiler import CUSTOM_MODELS

vtk_cdn = "https://unpkg.com/vtk.js@8.3.15/dist/vtk.js"
vtk_cdn = "https://unpkg.com/vtk.js"


class VTKPlot(HTMLBox):
Expand All @@ -33,10 +33,38 @@ class VTKPlot(HTMLBox):

enable_keybindings = Bool(default=False)

orientation_widget = Bool(default=False)

renderer_el = Any(readonly=True)

height = Override(default=300)

width = Override(default=300)



CUSTOM_MODELS['panel.models.plots.VTKPlot'] = VTKPlot


class VTKVolumePlot(HTMLBox):
"""
A Bokeh model that wraps around a vtk-js library and renders it inside
a Bokeh plot.
"""

__javascript__ = [vtk_cdn]

__js_require__ = {"paths": {"vtk": vtk_cdn[:-3]},
"shim": {"vtk": {"exports": "vtk"}}}

__implementation__ = os.path.join(os.path.abspath(os.path.dirname(__file__)), 'vtkvolume.ts')

actor = Any(readonly=True)

data = Dict(String, Any)

height = Override(default=300)

width = Override(default=300)


CUSTOM_MODELS['panel.models.plots.VTKVolumePlot'] = VTKVolumePlot
Loading

0 comments on commit f4f2579

Please sign in to comment.