Skip to content
Snippets Groups Projects
Commit 839d2646 authored by Andrew Maclean's avatar Andrew Maclean
Browse files

Adding more examples

parent 04bd9325
No related branches found
No related tags found
1 merge request!339Classes in python not in pythonic api 2
Showing
with 757 additions and 0 deletions
...@@ -109,6 +109,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w ...@@ -109,6 +109,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w
| Example Name | Description | Image | | Example Name | Description | Image |
| -------------- | ------------- | ------- | | -------------- | ------------- | ------- |
[EarthSource](/PythonicAPI/GeometricObjects/EarthSource) | Create the Earth.
[TessellatedBoxSource](/PythonicAPI/GeometricObjects/TessellatedBoxSource) | Generate a box with tessellated sides. [TessellatedBoxSource](/PythonicAPI/GeometricObjects/TessellatedBoxSource) | Generate a box with tessellated sides.
### Non Linear ### Non Linear
...@@ -131,6 +132,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w ...@@ -131,6 +132,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w
[BooleanOperationImplicitFunctions](/PythonicAPI/ImplicitFunctions/BooleanOperationImplicitFunctions) | Demonstrate booleans of two different implicit functions [BooleanOperationImplicitFunctions](/PythonicAPI/ImplicitFunctions/BooleanOperationImplicitFunctions) | Demonstrate booleans of two different implicit functions
[ContourTriangulator](/PythonicAPI/Modelling/ContourTriangulator) | Create a contour from a structured point set (image) and triangulate it. [ContourTriangulator](/PythonicAPI/Modelling/ContourTriangulator) | Create a contour from a structured point set (image) and triangulate it.
[DiscreteFlyingEdges3D](/PythonicAPI/Modelling/DiscreteFlyingEdges3D) | Generate surfaces from labeled data. [DiscreteFlyingEdges3D](/PythonicAPI/Modelling/DiscreteFlyingEdges3D) | Generate surfaces from labeled data.
[ExtractData](/src/Python/VisualizationAlgorithms/ExtractData.md) | Implicit functions used to select data: Two ellipsoids are combined using the union operation used to select voxels from a volume. Voxels are shrunk 50 percent.
[IceCream](/PythonicAPI/VisualizationAlgorithms/IceCream) | How to use boolean combinations of implicit functions to create a model of an ice cream cone. [IceCream](/PythonicAPI/VisualizationAlgorithms/IceCream) | How to use boolean combinations of implicit functions to create a model of an ice cream cone.
[ImplicitQuadric](/PythonicAPI/ImplicitFunctions/ImplicitQuadric) | Create an ellipsoid using an implicit quadric [ImplicitQuadric](/PythonicAPI/ImplicitFunctions/ImplicitQuadric) | Create an ellipsoid using an implicit quadric
[ImplicitSphere](/PythonicAPI/ImplicitFunctions/ImplicitSphere) | Demonstrate sampling of a sphere implicit function [ImplicitSphere](/PythonicAPI/ImplicitFunctions/ImplicitSphere) | Demonstrate sampling of a sphere implicit function
...@@ -150,6 +152,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w ...@@ -150,6 +152,7 @@ This Python script, [SelectExamples](../PythonicAPI/Utilities/SelectExamples), w
[ExtractPolyLinesFromPolyData](/PythonicAPI/PolyData/ExtractPolyLinesFromPolyData) | Extract polylines from polydata. [ExtractPolyLinesFromPolyData](/PythonicAPI/PolyData/ExtractPolyLinesFromPolyData) | Extract polylines from polydata.
[ExtractSelection](/PythonicAPI/PolyData/ExtractSelection) |Extract selected points. [ExtractSelection](/PythonicAPI/PolyData/ExtractSelection) |Extract selected points.
[ExtractSelectionCells](/PythonicAPI/PolyData/ExtractSelectionCells) | Extract cell, select cell. [ExtractSelectionCells](/PythonicAPI/PolyData/ExtractSelectionCells) | Extract cell, select cell.
[Finance](/PythonicAPI/Modelling/Finance) | Visualization of multidimensional financial data. The gray/wireframe surface represents the total data population. The red surface represents data points delinquent on loan payment.
[LineOnMesh](/PythonicAPI/DataManipulation/LineOnMesh) | Plot a spline on a terrain-like surface. [LineOnMesh](/PythonicAPI/DataManipulation/LineOnMesh) | Plot a spline on a terrain-like surface.
[MeshLabelImageColor](/PythonicAPI/DataManipulation/MeshLabelImageColor) | Mesh a single label from a label image. Then smooth and color the vertices according to the displacement error introduced by the smoothing. [MeshLabelImageColor](/PythonicAPI/DataManipulation/MeshLabelImageColor) | Mesh a single label from a label image. Then smooth and color the vertices according to the displacement error introduced by the smoothing.
[SmoothMeshGrid](/PythonicAPI/PolyData/SmoothMeshGrid) | Create a terrain with regularly spaced points and smooth it with ?vtkLoopSubdivisionFilter? and ?vtkButterflySubdivisionFilter?. [SmoothMeshGrid](/PythonicAPI/PolyData/SmoothMeshGrid) | Create a terrain with regularly spaced points and smooth it with ?vtkLoopSubdivisionFilter? and ?vtkButterflySubdivisionFilter?.
...@@ -171,6 +174,7 @@ This section includes examples of manipulating meshes. ...@@ -171,6 +174,7 @@ This section includes examples of manipulating meshes.
| Example Name | Description | Image | | Example Name | Description | Image |
| -------------- | ------------- | ------- | | -------------- | ------------- | ------- |
[DeformPointSet](/PythonicAPI/Meshes/DeformPointSet) | Use the vtkDeformPointSet filter to deform a vtkSphereSource with arbitrary polydata.
[DelaunayMesh](/PythonicAPI/Modelling/DelaunayMesh) | Two-dimensional Delaunay triangulation of a random set of points. Points and edges are shown highlighted with sphere glyphs and tubes. [DelaunayMesh](/PythonicAPI/Modelling/DelaunayMesh) | Two-dimensional Delaunay triangulation of a random set of points. Points and edges are shown highlighted with sphere glyphs and tubes.
#### Clipping #### Clipping
...@@ -322,6 +326,7 @@ See [this tutorial](http://www.vtk.org/Wiki/VTK/Tutorials/3DDataTypes) for a bri ...@@ -322,6 +326,7 @@ See [this tutorial](http://www.vtk.org/Wiki/VTK/Tutorials/3DDataTypes) for a bri
[ColoredAnnotatedCube](/PythonicAPI/Visualization/ColoredAnnotatedCube) | How to color the individual faces of an annotated cube. [ColoredAnnotatedCube](/PythonicAPI/Visualization/ColoredAnnotatedCube) | How to color the individual faces of an annotated cube.
[CollisionDetection](/PythonicAPI/Visualization/CollisionDetection) | Collison between two spheres. [CollisionDetection](/PythonicAPI/Visualization/CollisionDetection) | Collison between two spheres.
[CubeAxesActor](/PythonicAPI/Visualization/CubeAxesActor) | Display three orthogonal axes with [CurvaturesNormalsElevations](/PythonicAPI/Visualization/CurvaturesNormalsElevations) | Gaussian and Mean curvatures of a surface with arrows colored by elevation to display the normals. [CubeAxesActor](/PythonicAPI/Visualization/CubeAxesActor) | Display three orthogonal axes with [CurvaturesNormalsElevations](/PythonicAPI/Visualization/CurvaturesNormalsElevations) | Gaussian and Mean curvatures of a surface with arrows colored by elevation to display the normals.
[DataSetSurface](/PythonicAPI/VisualizationAlgorithms/DataSetSurface) | Cutting a hexahedron with a plane. The red line on the surface shows the cut.
[PointDataSubdivision](/PythonicAPI/Visualization/PointDataSubdivision) | Demonstrates the use of the vtkLinearSubdivisionFilter and vtkButterflySubdivisionFilter. [PointDataSubdivision](/PythonicAPI/Visualization/PointDataSubdivision) | Demonstrates the use of the vtkLinearSubdivisionFilter and vtkButterflySubdivisionFilter.
[QuadricVisualization](/PythonicAPI/Visualization/QuadricVisualization) | Visualizing a quadric function. [QuadricVisualization](/PythonicAPI/Visualization/QuadricVisualization) | Visualizing a quadric function.
[WarpCombustor](/PythonicAPI/VisualizationAlgorithms/WarpCombustor) | Carpet plots of combustor flow energy in a structured grid. Colors and plane displacement represent energy values. [WarpCombustor](/PythonicAPI/VisualizationAlgorithms/WarpCombustor) | Carpet plots of combustor flow energy in a structured grid. Colors and plane displacement represent energy values.
......
#!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkUnsignedCharArray
)
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersGeneral import vtkTransformPolyDataFilter
from vtkmodules.vtkFiltersHybrid import vtkEarthSource
from vtkmodules.vtkFiltersSources import (
vtkCubeSource
)
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkInteractionStyle import vtkInteractorStyleTrackballCamera
from vtkmodules.vtkInteractionWidgets import (
vtkOrientationMarkerWidget
)
from vtkmodules.vtkRenderingAnnotation import (
vtkAnnotatedCubeActor,
vtkAxesActor
)
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkPropAssembly,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Earth source
earth_source = vtkEarthSource(outline=True)
earth_source.update()
r = earth_source.GetRadius()
# Transform to geographic coordinates.
transform = vtkTransform()
transform.RotateZ(-180.0)
transform.RotateX(90.0)
transform.RotateZ(90.0)
transform_filter = vtkTransformPolyDataFilter(transform=transform)
# earth_source >> transform_filter
# Create a sphere
sphere = vtkSphereSource(theta_resolution=100, phi_resolution=100, radius=r)
# Create a mapper and actor
mapper = vtkPolyDataMapper()
earth_source >> transform_filter >> mapper
# mapper.SetInputConnection(earth_source.GetOutputPort())
actor = vtkActor(mapper=mapper)
# actor.SetMapper(mapper)
actor.property.color = colors.GetColor3d('Black')
actor.property.line_width = 2.0
sphere_mapper = vtkPolyDataMapper()
sphere >> sphere_mapper
# sphere_mapper.SetInputConnection(sphere.GetOutputPort())
sphere_actor = vtkActor(mapper=sphere_mapper)
# sphere_actor.SetMapper(sphere_mapper)
sphere_actor.property.color = colors.GetColor3d('PeachPuff')
# Create a renderer, render window, and interactor
renderer = vtkRenderer(background=colors.GetColor3d('LightCyan'))
render_window = vtkRenderWindow(size=(640, 480), window_name='EarthSource')
render_window.AddRenderer(renderer)
render_window_interactor = vtkRenderWindowInteractor()
render_window_interactor.render_window = render_window
style = vtkInteractorStyleTrackballCamera()
render_window_interactor.interactor_style = style
# Add the actor to the scene.
renderer.AddActor(actor)
renderer.AddActor(sphere_actor)
# Render and interact.
render_window.Render()
renderer.active_camera.Zoom(1.5)
renderer.ResetCameraClippingRange()
render_window.Render()
xyz_labels = ['90°E', '90°N', '0°E']
scale = [2.0, 2.0, 2.0]
total_length = [2.0, 2.0, 2.0]
axes = make_axes_actor(scale, total_length, xyz_labels)
om2 = vtkOrientationMarkerWidget(orientation_marker=axes, viewport=(0.8, 0, 1.0, 0.2),
interactor=render_window_interactor, default_renderer=renderer, enabled=True,
interactive=True
)
# Set up the Orientation Marker Widget.
prop_assembly = make_annotated_cube_actor()
om1 = vtkOrientationMarkerWidget(orientation_marker=prop_assembly,
interactor=render_window_interactor, default_renderer=renderer, enabled=True,
interactive=True
)
# Begin interaction.
render_window_interactor.Start()
def make_annotated_cube_actor():
annotated_cube = vtkAnnotatedCubeActor(face_text_scale=1.0 / 4.0,
x_plus_face_text='90°E', x_minus_face_text='90°W',
y_plus_face_text='90°N', y_minus_face_text='90°S',
z_plus_face_text='0°E', z_minus_face_text='180°E'
)
colors = vtkNamedColors()
# Change the vector text colors.
annotated_cube.text_edges_property.color = colors.GetColor3d('Black')
annotated_cube.text_edges_property.line_width = 1
annotated_cube.x_plus_face_property.color = colors.GetColor3d('Turquoise')
annotated_cube.x_minus_face_property.color = colors.GetColor3d('Turquoise')
annotated_cube.y_plus_face_property.color = colors.GetColor3d('Mint')
annotated_cube.y_minus_face_property.color = colors.GetColor3d('Mint')
annotated_cube.z_plus_face_property.color = colors.GetColor3d('Tomato')
annotated_cube.z_minus_face_property.color = colors.GetColor3d('Tomato')
annotated_cube.x_face_text_rotation = -90
annotated_cube.y_face_text_rotation = 180
annotated_cube.z_face_text_rotation = 90
# Make the annotated cube transparent.
annotated_cube.cube_property.opacity = 0
# Colored faces for the cube.
face_colors = vtkUnsignedCharArray()
face_colors.SetNumberOfComponents(3)
face_x_plus = colors.GetColor3ub('FireBrick')
face_x_minus = colors.GetColor3ub('FireBrick')
face_y_plus = colors.GetColor3ub('DarkGreen')
face_y_minus = colors.GetColor3ub('DarkGreen')
face_z_plus = colors.GetColor3ub('DarkBlue')
face_z_minus = colors.GetColor3ub('DarkBlue')
face_colors.InsertNextTypedTuple(face_x_minus)
face_colors.InsertNextTypedTuple(face_x_plus)
face_colors.InsertNextTypedTuple(face_y_minus)
face_colors.InsertNextTypedTuple(face_y_plus)
face_colors.InsertNextTypedTuple(face_z_minus)
face_colors.InsertNextTypedTuple(face_z_plus)
cube_source = vtkCubeSource()
cube_source.update()
cube_source.output.cell_data.SetScalars(face_colors)
cube_mapper = vtkPolyDataMapper()
cube_source >> cube_mapper
cube_actor = vtkActor(mapper=cube_mapper)
# Assemble the colored cube and annotated cube texts into a composite prop.
prop_assembly = vtkPropAssembly()
prop_assembly.AddPart(annotated_cube)
prop_assembly.AddPart(cube_actor)
return prop_assembly
def make_axes_actor(scale, total_length, xyz_labels):
axes = vtkAxesActor(shaft_type=vtkAxesActor.CYLINDER_SHAFT, tip_type=vtkAxesActor.CONE_TIP,
x_axis_label_text=xyz_labels[0], y_axis_label_text=xyz_labels[1],
z_axis_label_text=xyz_labels[2],
scale=scale,
total_length=total_length)
axes.cylinder_radius = 0.5 * axes.cylinder_radius
axes.cone_radius = 1.025 * axes.cone_radius
axes.sphere_radius = 1.5 * axes.sphere_radius
# Set the font properties.
tprop = axes.x_axis_caption_actor2d.caption_text_property
tprop.italic = True
tprop.shadow = True
tprop.SetFontFamilyToTimes()
# Use the same text properties on the other two axes.
axes.y_axis_caption_actor2d.caption_text_property.ShallowCopy(tprop)
axes.z_axis_caption_actor2d.caption_text_property.ShallowCopy(tprop)
# Now color the labels.
colors = vtkNamedColors()
axes.x_axis_caption_actor2d.caption_text_property.color = colors.GetColor3d('FireBrick')
axes.y_axis_caption_actor2d.caption_text_property.color = colors.GetColor3d('DarkGreen')
axes.z_axis_caption_actor2d.caption_text_property.color = colors.GetColor3d('DarkBlue')
return axes
if __name__ == '__main__':
main()
### Description
An example that shows how to use the vtkDeformPointSet filter to deform a sphere with arbitrary polydata. This example uses a vtkSphereSource to generate polydata to use, however any polydata could be used, including stl files.
#!/usr/bin/env python3
from dataclasses import dataclass
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkPolyData
)
from vtkmodules.vtkFiltersCore import vtkElevationFilter
from vtkmodules.vtkFiltersGeneral import vtkDeformPointSet
from vtkmodules.vtkFiltersSources import vtkSphereSource
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Set the background color.
# colors.SetColor('bkg', 0.2, 0.3, 0.4, 1.0)
# Create a sphere to deform
sphere = vtkSphereSource(theta_resolution=51, phi_resolution=17)
# Create a filter to color the sphere.
bounds = sphere.update().output.bounds
low_point = [(bounds[1] + bounds[0]) / 2.0, (bounds[3] + bounds[2]) / 2.0, -bounds[5]]
high_point = low_point[:2] + [bounds[5]]
ele = vtkElevationFilter(low_point=low_point, high_point=high_point)
# Create a mesh to deform the sphere
pts = vtkPoints()
pts.SetNumberOfPoints(6)
pts.SetPoint(0,
bounds[0] - 0.1 * (bounds[1] - bounds[0]),
(bounds[3] + bounds[2]) / 2.0,
(bounds[5] + bounds[4]) / 2.0)
pts.SetPoint(1,
bounds[1] + 0.1 * (bounds[1] - bounds[0]),
(bounds[3] + bounds[2]) / 2.0,
(bounds[5] + bounds[4]) / 2.0)
pts.SetPoint(2,
(bounds[1] + bounds[0]) / 2.0,
bounds[2] - 0.1 * (bounds[3] - bounds[2]),
(bounds[5] + bounds[4]) / 2.0)
pts.SetPoint(3,
(bounds[1] + bounds[0]) / 2.0,
bounds[3] + 0.1 * (bounds[3] - bounds[2]),
(bounds[5] + bounds[4]) / 2.0)
pts.SetPoint(4,
(bounds[1] + bounds[0]) / 2.0,
(bounds[3] + bounds[2]) / 2.0,
bounds[4] - 0.1 * (bounds[5] - bounds[4]))
pts.SetPoint(5,
(bounds[1] + bounds[0]) / 2.0,
(bounds[3] + bounds[2]) / 2.0,
bounds[5] + 0.1 * (bounds[5] - bounds[4]))
tris = vtkCellArray()
cells = [[2, 0, 4], [1, 2, 4], [3, 1, 4], [0, 3, 4], [0, 2, 5], [2, 1, 5], [1, 3, 5], [3, 0, 5]]
for cell in cells:
tris.InsertNextCell(3)
for c in cell:
tris.InsertCellPoint(c)
pd = vtkPolyData(points=pts, polys=tris)
mesh_mapper = vtkPolyDataMapper()
pd >> mesh_mapper
mesh_actor = vtkActor(mapper=mesh_mapper)
mesh_actor.property.representation = Property.Representation.VTK_WIREFRAME
mesh_actor.property.color = colors.GetColor3d('Black')
deform = vtkDeformPointSet(control_mesh_data=pd)
sphere >> ele >> deform
deform.update()
control_point = pts.GetPoint(5)
pts.SetPoint(5, control_point[0],
control_point[1],
bounds[5] + .8 * (bounds[5] - bounds[4]))
pts.Modified()
poly_mapper = vtkPolyDataMapper()
deform >> poly_mapper
poly_mapper.SetInputConnection(deform.GetOutputPort())
poly_actor = vtkActor(mapper=poly_mapper)
renderer = vtkRenderer(background=colors.GetColor3d('DarkSlateGray'))
ren_win = vtkRenderWindow(size=(300, 300), window_name='DeformPointSet')
ren_win.AddRenderer(renderer)
iren = vtkRenderWindowInteractor()
iren.render_window = ren_win
renderer.AddActor(poly_actor)
renderer.AddActor(mesh_actor)
renderer.active_camera.position = (1, 1, 1)
renderer.ResetCamera()
ren_win.Render()
iren.Start()
@dataclass(frozen=True)
class Property:
@dataclass(frozen=True)
class Interpolation:
VTK_FLAT: int = 0
VTK_GOURAUD: int = 1
VTK_PHONG: int = 2
VTK_PBR: int = 3
@dataclass(frozen=True)
class Representation:
VTK_POINTS: int = 0
VTK_WIREFRAME: int = 1
VTK_SURFACE: int = 2
if __name__ == '__main__':
main()
### Description
The first step is to choose dependent and independent variables. This choice is essentially a mapping from multidimensional data into an unstructured point dataset. This example chooses MONTHLY_PAYMENT, INTEREST_RATE, and LOAN_AMOUNT as (x, y, z) point coordinates, and TIME_LATE as a scalar value. This maps four of six variables. For now we will ignore the other two variables.
The example uses vtkGaussianSplatter to perform the splatting operation (i.e., conversion from unstructured points to volume dataset). This is followed by an isosurface extraction. We splat the data two times. The first time we splat the entire population. This is to show context and appears as gray/ wireframe in the figure. The second time we splat the data and scale it by the value of TIME_LATE . As a result, only payments that are late contribute to the second isosurface. The results of this visualization are interesting. First, we see that there is a strong correlation between the two independent variables MONTHLY_PAYMENT and LOAN_AMOUNT . (This is more evident when viewing the data interactively.) We see that the data falls roughly on a plane at a 45 degree angle between these two axes. With a little reflection this is evident: the monthly payment is strongly a function of loan amount (as well as interest rate and payment period). Second, we see that there is a clustering of delinquent accounts within the total population. The cluster tends to grow with larger interest rates and shrink with smaller monthly payments and loan amounts. Although the relationship with interest rate is expected, the clustering towards smaller monthly payments is not. Thus our visualization has provided a clue into the data. Further exploration may reveal the reason(s), or we may perform additional data analysis and acquisition to understand the phenomena.
One important note about multidimensional visualization. Because we tend to combine variables in odd ways (e.g., the use of MONTHLY_PAYMENT , INTEREST_RATE , and LOAN_AMOUNT as (x, y, z) coordinates), normalization of the data is usually required. To normalize data we simply adjust data values to lie between (0,1). Otherwise our data can be badly skewed and result in poor visualizations.
!!! info
See [Figure 9-50](../../../VTKBook/09Chapter9/#Figure%209-50) in [Chapter 9](../../../VTKBook/09Chapter9) The [VTK Textbook](../../../VTKBook/01Chapter1).
#!/usr/bin/env python3
from pathlib import Path
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import (
vtkFloatArray,
vtkPoints
)
from vtkmodules.vtkCommonDataModel import vtkUnstructuredGrid
from vtkmodules.vtkFiltersCore import (
vtkContourFilter,
vtkTubeFilter
)
from vtkmodules.vtkFiltersGeneral import vtkAxes
from vtkmodules.vtkImagingHybrid import vtkGaussianSplatter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
colors.SetColor('PopColor', 230, 230, 230, 255)
file_name = get_program_parameters()
path = Path(file_name)
if not path.is_file():
print(f'Nonexistent file: {path}')
return
keys = ['NUMBER_POINTS', 'MONTHLY_PAYMENT', 'INTEREST_RATE', 'LOAN_AMOUNT', 'TIME_LATE']
# Read in the data and make an unstructured data set.
data_set = make_dataset(path, keys)
# Construct the pipeline for the original population.
pop_splatter = vtkGaussianSplatter(sample_dimensions=(100, 100, 100), radius=0.05, scalar_warping=False)
pop_surface = vtkContourFilter()
pop_surface.SetValue(0, 0.01)
pop_mapper = vtkPolyDataMapper(scalar_visibility=False)
data_set >> pop_splatter >> pop_surface >> pop_mapper
pop_actor = vtkActor(mapper=pop_mapper)
pop_actor.property.opacity = 0.3
pop_actor.property.color = colors.GetColor3d('PopColor')
# Construct the pipeline for the delinquent population.
late_splatter = vtkGaussianSplatter(sample_dimensions=(50, 50, 50), radius=0.05, scale_factor=0.005)
late_surface = vtkContourFilter()
late_surface.SetValue(0, 0.01)
late_mapper = vtkPolyDataMapper(scalar_visibility=False)
data_set >> late_splatter >> late_surface >> late_mapper
late_actor = vtkActor(mapper=late_mapper)
late_actor.SetMapper(late_mapper)
late_actor.property.color = colors.GetColor3d('Red')
# Create axes.
bounds = pop_splatter.update().output.bounds
scale_factor = pop_splatter.output.length / 5
axes = vtkAxes(origin=(bounds[0], bounds[2], bounds[4]), scale_factor=scale_factor)
axes_tubes = vtkTubeFilter(radius=axes.scale_factor / 25, number_of_sides=6)
axes_mapper = vtkPolyDataMapper()
axes >> axes_tubes >> axes_mapper
axes_actor = vtkActor(mapper=axes_mapper)
# Graphics stuff.
renderer = vtkRenderer(background=colors.GetColor3d('Wheat'))
ren_win = vtkRenderWindow(size=(640, 480), window_name='Finance')
ren_win.AddRenderer(renderer)
interactor = vtkRenderWindowInteractor()
interactor.render_window = ren_win
# Set up the renderer.
renderer.AddActor(late_actor)
renderer.AddActor(axes_actor)
renderer.AddActor(pop_actor)
renderer.ResetCamera()
renderer.active_camera.Dolly(1.3)
renderer.ResetCameraClippingRange()
# Interact with the data.
ren_win.Render()
interactor.Start()
def get_program_parameters():
import argparse
description = 'Visualization of multidimensional financial data.'
epilogue = '''
The gray/wireframe surface represents the total data population.
The red surface represents data points delinquent on loan payment.
'''
parser = argparse.ArgumentParser(description=description, epilog=epilogue,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument('filename', help='financial.txt.')
args = parser.parse_args()
return args.filename
def normalise(maximum, minimum, x):
return minimum + x / (maximum - minimum)
def read_file(path):
"""
Read in the data set.
:param path: The file.
:return:
"""
res = dict()
content = path.read_text(encoding="utf-8")
has_key = False
for line in content.split('\n'):
cl = ' '.join(line.split()).split() # Clean the line.
if cl:
if len(cl) == 2 and cl[0] == 'NUMBER_POINTS':
k = cl[0]
v = [int(cl[1])]
has_key = True
continue
if len(cl) == 1 and not has_key:
has_key = True
k = cl[0]
v = list()
else:
v += map(float, cl)
else:
if has_key:
# Normalise the data.
minimum = min(v)
maximum = max(v)
# Emulate the bug in the C++ code.
for i in v:
if i > minimum:
maximum = i
if maximum != minimum:
res[k] = list(map(lambda x: minimum + x / (maximum - minimum), v))
else:
res[k] = v
has_key = False
return res
def make_dataset(path, keys):
res = read_file(path)
if res:
new_pts = vtkPoints()
new_scalars = vtkFloatArray()
xyz = list(zip(res[keys[1]], res[keys[2]], res[keys[3]]))
for i in range(0, res[keys[0]][0]):
new_pts.InsertPoint(i, xyz[i])
new_scalars.InsertValue(i, res[keys[4]][i])
dataset = vtkUnstructuredGrid(points=new_pts)
dataset.GetPointData().SetScalars(new_scalars)
return dataset
if __name__ == '__main__':
main()
#!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonCore import vtkPoints
from vtkmodules.vtkCommonDataModel import (
vtkCellArray,
vtkHexahedron,
vtkPlane,
vtkUnstructuredGrid
)
from vtkmodules.vtkFiltersCore import vtkCutter
from vtkmodules.vtkFiltersGeometry import vtkDataSetSurfaceFilter
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkPolyDataMapper,
vtkProperty,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
# Set up the coordinates of eight points
# (the two faces must be in counterclockwise order as viewed from the
# outside)
point_coords = [
[0.0, 0.0, 0.0],
[1.0, 0.0, 0.0],
[1.0, 1.0, 0.0],
[0.0, 1.0, 0.0],
[0.0, 0.0, 1.0],
[1.0, 0.0, 1.0],
[1.0, 1.0, 1.0],
[0.0, 1.0, 1.0]
]
# Create the points and a hexahedron from the points.
points = vtkPoints()
hexa = vtkHexahedron()
for i, pointCoord in enumerate(point_coords):
points.InsertNextPoint(pointCoord)
hexa.GetPointIds().SetId(i, i)
# Add the hexahedron to a cell array.
hexs = vtkCellArray()
hexs.InsertNextCell(hexa)
# Add the points and hexahedron to an unstructured grid.
u_grid = vtkUnstructuredGrid()
u_grid.SetPoints(points)
u_grid.InsertNextCell(hexa.GetCellType(), hexa.GetPointIds())
# Extract the outer (polygonal) surface.
surface = vtkDataSetSurfaceFilter()
a_beam_mapper = vtkDataSetMapper()
u_grid >> surface >> a_beam_mapper
a_beam_property = vtkProperty(color=colors.GetColor3d('Yellow'), opacity=0.60, edge_visibility=True,
edge_color=colors.GetColor3d('Black'), line_width=1.5)
a_beam_actor = vtkActor(mapper=a_beam_mapper, property=a_beam_property)
a_beam_actor.AddPosition(0, 0, 0)
# Create a plane to cut, here it cuts in the XZ direction
# (XZ normal=(1,0,0) XY =(0,0,1), YZ =(0,1,0)
plane = vtkPlane(origin=(0.5, 0, 0), normal=(1, 0, 0))
# Create cutter.
cutter = vtkCutter(cut_function=plane, input_data=a_beam_actor.mapper.input)
cutter_mapper = vtkPolyDataMapper()
cutter >> cutter_mapper
# Create plane actor.
plane_actor = vtkActor(mapper=cutter_mapper)
plane_actor.property.color = colors.GetColor3d('Red')
plane_actor.property.line_width = 2
# Create a renderer, render window, and interactor.
renderer = vtkRenderer(background=colors.GetColor3d('Seashell'))
render_window = vtkRenderWindow(window_name='DatasetSurface')
render_window.AddRenderer(renderer)
render_window_interactor = vtkRenderWindowInteractor()
render_window_interactor.render_window = render_window
# Add the actors to the scene.
renderer.AddActor(a_beam_actor)
renderer.AddActor(plane_actor)
renderer.ResetCamera()
renderer.GetActiveCamera().Azimuth(-25)
renderer.GetActiveCamera().Elevation(30)
# Render and interact.
render_window.Render()
render_window_interactor.Start()
if __name__ == '__main__':
main()
### Description
This example takes advantage of the properties of implicit functions to select and cut data. In particular it uses the region separation property to select data. Selecting or extracting data with an implicit function means choosing cells and points (and associated attribute data) that lie within a particular region of the function. To determine whether a point x-y-z lies within a region, we simply evaluate the point and examine the sign of the result. A cell lies in a region if all its points lie in the region. Here, two ellipses are used in combination to select voxels within a volume dataset. Note that extracting data often changes the structure of the dataset. In this example the input type is a image data dataset, while the output type is an unstructured grid dataset.
!!! info
See [Figure 6-24](../../../VTKBook/06Chapter6/#Figure%206-24) in [Chapter 6](../../../VTKBook/06Chapter6) the [VTK Textbook](../../../VTKBook/01Chapter1).
#!/usr/bin/env python3
# noinspection PyUnresolvedReferences
import vtkmodules.vtkInteractionStyle
# noinspection PyUnresolvedReferences
import vtkmodules.vtkRenderingOpenGL2
from vtkmodules.vtkCommonColor import vtkNamedColors
from vtkmodules.vtkCommonDataModel import (
vtkImplicitBoolean,
vtkQuadric,
vtkSphere
)
from vtkmodules.vtkCommonTransforms import vtkTransform
from vtkmodules.vtkFiltersExtraction import vtkExtractGeometry
from vtkmodules.vtkFiltersGeneral import vtkShrinkFilter
from vtkmodules.vtkFiltersModeling import vtkOutlineFilter
from vtkmodules.vtkImagingHybrid import vtkSampleFunction
from vtkmodules.vtkRenderingCore import (
vtkActor,
vtkDataSetMapper,
vtkPolyDataMapper,
vtkRenderWindow,
vtkRenderWindowInteractor,
vtkRenderer
)
def main():
colors = vtkNamedColors()
quadric = vtkQuadric(coefficients=(0.5, 1, 0.2, 0, 0.1, 0, 0, 0.2, 0, 0))
sample = vtkSampleFunction(implicit_function=quadric, sample_dimensions=(50, 50, 50), compute_normals=False)
trans = vtkTransform()
trans.Scale(1, 0.5, 0.333)
sphere = vtkSphere(radius=0.25)
sphere.SetTransform(trans)
trans2 = vtkTransform()
trans2.Scale(0.25, 0.5, 1.0)
sphere2 = vtkSphere(radius=0.25)
sphere2.SetTransform(trans2)
boolean_union = vtkImplicitBoolean(operation_type=vtkImplicitBoolean.VTK_UNION)
boolean_union.AddFunction(sphere)
boolean_union.AddFunction(sphere2)
extract = vtkExtractGeometry()
extract.SetImplicitFunction(boolean_union)
shrink = vtkShrinkFilter(shrink_factor=0.5)
data_mapper = vtkDataSetMapper()
sample >> extract >> shrink >> data_mapper
data_actor = vtkActor(mapper=data_mapper)
# outline
outline = vtkOutlineFilter()
outline_mapper = vtkPolyDataMapper()
sample >> outline >> outline_mapper
outline_actor = vtkActor(mapper=outline_mapper)
outline_actor.property.color = colors.GetColor3d('Black')
ren = vtkRenderer(background=colors.GetColor3d('SlateGray'))
ren_win = vtkRenderWindow(size=(640, 480), window_name='ExtractData')
ren_win.AddRenderer(ren)
iren = vtkRenderWindowInteractor()
iren.render_window = ren_win
# Add the actors to the renderer.
ren.AddActor(outline_actor)
ren.AddActor(data_actor)
ren_win.Render()
ren.active_camera.Azimuth(30)
ren.active_camera.Elevation(30)
ren_win.Render()
iren.Start()
if __name__ == '__main__':
main()
src/Testing/Baseline/PythonicAPI/GeometricObjects/TestEarthSource.png

130 B

src/Testing/Baseline/PythonicAPI/Meshes/TestDeformPointSet.png

130 B

src/Testing/Baseline/PythonicAPI/Modelling/TestFinance.png

130 B

src/Testing/Baseline/PythonicAPI/VisualizationAlgorithms/TestDataSetSurface.png

130 B

src/Testing/Baseline/PythonicAPI/VisualizationAlgorithms/TestExtractData.png

130 B

0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment