id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 51 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
236,500 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.screenshot | def screenshot(self, filename=None, transparent_background=None,
return_img=None, window_size=None):
"""
Takes screenshot at current camera position
Parameters
----------
filename : str, optional
Location to write image to. If None, no image is written.
transparent_background : bool, optional
Makes the background transparent. Default False.
return_img : bool, optional
If a string filename is given and this is true, a NumPy array of
the image will be returned.
Returns
-------
img : numpy.ndarray
Array containing pixel RGB and alpha. Sized:
[Window height x Window width x 3] for transparent_background=False
[Window height x Window width x 4] for transparent_background=True
Examples
--------
>>> import vtki
>>> sphere = vtki.Sphere()
>>> plotter = vtki.Plotter()
>>> actor = plotter.add_mesh(sphere)
>>> plotter.screenshot('screenshot.png') # doctest:+SKIP
"""
if window_size is not None:
self.window_size = window_size
# configure image filter
if transparent_background is None:
transparent_background = rcParams['transparent_background']
self.image_transparent_background = transparent_background
# This if statement allows you to save screenshots of closed plotters
# This is needed for the sphinx-gallery work
if not hasattr(self, 'ren_win'):
# If plotter has been closed...
# check if last_image exists
if hasattr(self, 'last_image'):
# Save last image
return self._save_image(self.last_image, filename, return_img)
# Plotter hasn't been rendered or was improperly closed
raise AttributeError('This plotter is unable to save a screenshot.')
if isinstance(self, Plotter):
# TODO: we need a consistent rendering function
self.render()
else:
self._render()
# debug: this needs to be called twice for some reason,
img = self.image
img = self.image
return self._save_image(img, filename, return_img) | python | def screenshot(self, filename=None, transparent_background=None,
return_img=None, window_size=None):
if window_size is not None:
self.window_size = window_size
# configure image filter
if transparent_background is None:
transparent_background = rcParams['transparent_background']
self.image_transparent_background = transparent_background
# This if statement allows you to save screenshots of closed plotters
# This is needed for the sphinx-gallery work
if not hasattr(self, 'ren_win'):
# If plotter has been closed...
# check if last_image exists
if hasattr(self, 'last_image'):
# Save last image
return self._save_image(self.last_image, filename, return_img)
# Plotter hasn't been rendered or was improperly closed
raise AttributeError('This plotter is unable to save a screenshot.')
if isinstance(self, Plotter):
# TODO: we need a consistent rendering function
self.render()
else:
self._render()
# debug: this needs to be called twice for some reason,
img = self.image
img = self.image
return self._save_image(img, filename, return_img) | [
"def",
"screenshot",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"transparent_background",
"=",
"None",
",",
"return_img",
"=",
"None",
",",
"window_size",
"=",
"None",
")",
":",
"if",
"window_size",
"is",
"not",
"None",
":",
"self",
".",
"window_size"... | Takes screenshot at current camera position
Parameters
----------
filename : str, optional
Location to write image to. If None, no image is written.
transparent_background : bool, optional
Makes the background transparent. Default False.
return_img : bool, optional
If a string filename is given and this is true, a NumPy array of
the image will be returned.
Returns
-------
img : numpy.ndarray
Array containing pixel RGB and alpha. Sized:
[Window height x Window width x 3] for transparent_background=False
[Window height x Window width x 4] for transparent_background=True
Examples
--------
>>> import vtki
>>> sphere = vtki.Sphere()
>>> plotter = vtki.Plotter()
>>> actor = plotter.add_mesh(sphere)
>>> plotter.screenshot('screenshot.png') # doctest:+SKIP | [
"Takes",
"screenshot",
"at",
"current",
"camera",
"position"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2308-L2369 |
236,501 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.add_legend | def add_legend(self, labels=None, bcolor=(0.5, 0.5, 0.5), border=False,
size=None, name=None):
"""
Adds a legend to render window. Entries must be a list
containing one string and color entry for each item.
Parameters
----------
labels : list, optional
When set to None, uses existing labels as specified by
- add_mesh
- add_lines
- add_points
List contianing one entry for each item to be added to the
legend. Each entry must contain two strings, [label,
color], where label is the name of the item to add, and
color is the color of the label to add.
bcolor : list or string, optional
Background color, either a three item 0 to 1 RGB color
list, or a matplotlib color string (e.g. 'w' or 'white'
for a white color). If None, legend background is
disabled.
border : bool, optional
Controls if there will be a border around the legend.
Default False.
size : list, optional
Two float list, each float between 0 and 1. For example
[0.1, 0.1] would make the legend 10% the size of the
entire figure window.
name : str, optional
The name for the added actor so that it can be easily updated.
If an actor of this name already exists in the rendering window, it
will be replaced by the new actor.
Returns
-------
legend : vtk.vtkLegendBoxActor
Actor for the legend.
Examples
--------
>>> import vtki
>>> from vtki import examples
>>> mesh = examples.load_hexbeam()
>>> othermesh = examples.load_uniform()
>>> plotter = vtki.Plotter()
>>> _ = plotter.add_mesh(mesh, label='My Mesh')
>>> _ = plotter.add_mesh(othermesh, 'k', label='My Other Mesh')
>>> _ = plotter.add_legend()
>>> plotter.show() # doctest:+SKIP
Alternative manual example
>>> import vtki
>>> from vtki import examples
>>> mesh = examples.load_hexbeam()
>>> othermesh = examples.load_uniform()
>>> legend_entries = []
>>> legend_entries.append(['My Mesh', 'w'])
>>> legend_entries.append(['My Other Mesh', 'k'])
>>> plotter = vtki.Plotter()
>>> _ = plotter.add_mesh(mesh)
>>> _ = plotter.add_mesh(othermesh, 'k')
>>> _ = plotter.add_legend(legend_entries)
>>> plotter.show() # doctest:+SKIP
"""
self.legend = vtk.vtkLegendBoxActor()
if labels is None:
# use existing labels
if not self._labels:
raise Exception('No labels input.\n\n' +
'Add labels to individual items when adding them to' +
'the plotting object with the "label=" parameter. ' +
'or enter them as the "labels" parameter.')
self.legend.SetNumberOfEntries(len(self._labels))
for i, (vtk_object, text, color) in enumerate(self._labels):
self.legend.SetEntry(i, vtk_object, text, parse_color(color))
else:
self.legend.SetNumberOfEntries(len(labels))
legendface = single_triangle()
for i, (text, color) in enumerate(labels):
self.legend.SetEntry(i, legendface, text, parse_color(color))
if size:
self.legend.SetPosition2(size[0], size[1])
if bcolor is None:
self.legend.UseBackgroundOff()
else:
self.legend.UseBackgroundOn()
self.legend.SetBackgroundColor(bcolor)
if border:
self.legend.BorderOn()
else:
self.legend.BorderOff()
# Add to renderer
self.add_actor(self.legend, reset_camera=False, name=name)
return self.legend | python | def add_legend(self, labels=None, bcolor=(0.5, 0.5, 0.5), border=False,
size=None, name=None):
self.legend = vtk.vtkLegendBoxActor()
if labels is None:
# use existing labels
if not self._labels:
raise Exception('No labels input.\n\n' +
'Add labels to individual items when adding them to' +
'the plotting object with the "label=" parameter. ' +
'or enter them as the "labels" parameter.')
self.legend.SetNumberOfEntries(len(self._labels))
for i, (vtk_object, text, color) in enumerate(self._labels):
self.legend.SetEntry(i, vtk_object, text, parse_color(color))
else:
self.legend.SetNumberOfEntries(len(labels))
legendface = single_triangle()
for i, (text, color) in enumerate(labels):
self.legend.SetEntry(i, legendface, text, parse_color(color))
if size:
self.legend.SetPosition2(size[0], size[1])
if bcolor is None:
self.legend.UseBackgroundOff()
else:
self.legend.UseBackgroundOn()
self.legend.SetBackgroundColor(bcolor)
if border:
self.legend.BorderOn()
else:
self.legend.BorderOff()
# Add to renderer
self.add_actor(self.legend, reset_camera=False, name=name)
return self.legend | [
"def",
"add_legend",
"(",
"self",
",",
"labels",
"=",
"None",
",",
"bcolor",
"=",
"(",
"0.5",
",",
"0.5",
",",
"0.5",
")",
",",
"border",
"=",
"False",
",",
"size",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"self",
".",
"legend",
"=",
"v... | Adds a legend to render window. Entries must be a list
containing one string and color entry for each item.
Parameters
----------
labels : list, optional
When set to None, uses existing labels as specified by
- add_mesh
- add_lines
- add_points
List contianing one entry for each item to be added to the
legend. Each entry must contain two strings, [label,
color], where label is the name of the item to add, and
color is the color of the label to add.
bcolor : list or string, optional
Background color, either a three item 0 to 1 RGB color
list, or a matplotlib color string (e.g. 'w' or 'white'
for a white color). If None, legend background is
disabled.
border : bool, optional
Controls if there will be a border around the legend.
Default False.
size : list, optional
Two float list, each float between 0 and 1. For example
[0.1, 0.1] would make the legend 10% the size of the
entire figure window.
name : str, optional
The name for the added actor so that it can be easily updated.
If an actor of this name already exists in the rendering window, it
will be replaced by the new actor.
Returns
-------
legend : vtk.vtkLegendBoxActor
Actor for the legend.
Examples
--------
>>> import vtki
>>> from vtki import examples
>>> mesh = examples.load_hexbeam()
>>> othermesh = examples.load_uniform()
>>> plotter = vtki.Plotter()
>>> _ = plotter.add_mesh(mesh, label='My Mesh')
>>> _ = plotter.add_mesh(othermesh, 'k', label='My Other Mesh')
>>> _ = plotter.add_legend()
>>> plotter.show() # doctest:+SKIP
Alternative manual example
>>> import vtki
>>> from vtki import examples
>>> mesh = examples.load_hexbeam()
>>> othermesh = examples.load_uniform()
>>> legend_entries = []
>>> legend_entries.append(['My Mesh', 'w'])
>>> legend_entries.append(['My Other Mesh', 'k'])
>>> plotter = vtki.Plotter()
>>> _ = plotter.add_mesh(mesh)
>>> _ = plotter.add_mesh(othermesh, 'k')
>>> _ = plotter.add_legend(legend_entries)
>>> plotter.show() # doctest:+SKIP | [
"Adds",
"a",
"legend",
"to",
"render",
"window",
".",
"Entries",
"must",
"be",
"a",
"list",
"containing",
"one",
"string",
"and",
"color",
"entry",
"for",
"each",
"item",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2371-L2479 |
236,502 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.set_background | def set_background(self, color, loc='all'):
"""
Sets background color
Parameters
----------
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
loc : int, tuple, list, or str, optional
Index of the renderer to add the actor to. For example,
``loc=2`` or ``loc=(1, 1)``. If ``loc='all'`` then all
render windows will have their background set.
"""
if color is None:
color = rcParams['background']
if isinstance(color, str):
if color.lower() in 'paraview' or color.lower() in 'pv':
# Use the default ParaView background color
color = PV_BACKGROUND
else:
color = vtki.string_to_rgb(color)
if loc =='all':
for renderer in self.renderers:
renderer.SetBackground(color)
else:
renderer = self.renderers[self.loc_to_index(loc)]
renderer.SetBackground(color) | python | def set_background(self, color, loc='all'):
if color is None:
color = rcParams['background']
if isinstance(color, str):
if color.lower() in 'paraview' or color.lower() in 'pv':
# Use the default ParaView background color
color = PV_BACKGROUND
else:
color = vtki.string_to_rgb(color)
if loc =='all':
for renderer in self.renderers:
renderer.SetBackground(color)
else:
renderer = self.renderers[self.loc_to_index(loc)]
renderer.SetBackground(color) | [
"def",
"set_background",
"(",
"self",
",",
"color",
",",
"loc",
"=",
"'all'",
")",
":",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"rcParams",
"[",
"'background'",
"]",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"if",
"color",
".",
... | Sets background color
Parameters
----------
color : string or 3 item list, optional, defaults to white
Either a string, rgb list, or hex color string. For example:
color='white'
color='w'
color=[1, 1, 1]
color='#FFFFFF'
loc : int, tuple, list, or str, optional
Index of the renderer to add the actor to. For example,
``loc=2`` or ``loc=(1, 1)``. If ``loc='all'`` then all
render windows will have their background set. | [
"Sets",
"background",
"color"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2533-L2566 |
236,503 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.remove_legend | def remove_legend(self):
""" Removes legend actor """
if hasattr(self, 'legend'):
self.remove_actor(self.legend, reset_camera=False)
self._render() | python | def remove_legend(self):
if hasattr(self, 'legend'):
self.remove_actor(self.legend, reset_camera=False)
self._render() | [
"def",
"remove_legend",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'legend'",
")",
":",
"self",
".",
"remove_actor",
"(",
"self",
".",
"legend",
",",
"reset_camera",
"=",
"False",
")",
"self",
".",
"_render",
"(",
")"
] | Removes legend actor | [
"Removes",
"legend",
"actor"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2578-L2582 |
236,504 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.enable_cell_picking | def enable_cell_picking(self, mesh=None, callback=None):
"""
Enables picking of cells. Press r to enable retangle based
selection. Press "r" again to turn it off. Selection will be
saved to self.picked_cells.
Uses last input mesh for input
Parameters
----------
mesh : vtk.UnstructuredGrid, optional
UnstructuredGrid grid to select cells from. Uses last
input grid by default.
callback : function, optional
When input, calls this function after a selection is made.
The picked_cells are input as the first parameter to this function.
"""
if mesh is None:
if not hasattr(self, 'mesh'):
raise Exception('Input a mesh into the Plotter class first or '
+ 'or set it in this function')
mesh = self.mesh
def pick_call_back(picker, event_id):
extract = vtk.vtkExtractGeometry()
mesh.cell_arrays['orig_extract_id'] = np.arange(mesh.n_cells)
extract.SetInputData(mesh)
extract.SetImplicitFunction(picker.GetFrustum())
extract.Update()
self.picked_cells = vtki.wrap(extract.GetOutput())
if callback is not None:
callback(self.picked_cells)
area_picker = vtk.vtkAreaPicker()
area_picker.AddObserver(vtk.vtkCommand.EndPickEvent, pick_call_back)
self.enable_rubber_band_style()
self.iren.SetPicker(area_picker) | python | def enable_cell_picking(self, mesh=None, callback=None):
if mesh is None:
if not hasattr(self, 'mesh'):
raise Exception('Input a mesh into the Plotter class first or '
+ 'or set it in this function')
mesh = self.mesh
def pick_call_back(picker, event_id):
extract = vtk.vtkExtractGeometry()
mesh.cell_arrays['orig_extract_id'] = np.arange(mesh.n_cells)
extract.SetInputData(mesh)
extract.SetImplicitFunction(picker.GetFrustum())
extract.Update()
self.picked_cells = vtki.wrap(extract.GetOutput())
if callback is not None:
callback(self.picked_cells)
area_picker = vtk.vtkAreaPicker()
area_picker.AddObserver(vtk.vtkCommand.EndPickEvent, pick_call_back)
self.enable_rubber_band_style()
self.iren.SetPicker(area_picker) | [
"def",
"enable_cell_picking",
"(",
"self",
",",
"mesh",
"=",
"None",
",",
"callback",
"=",
"None",
")",
":",
"if",
"mesh",
"is",
"None",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'mesh'",
")",
":",
"raise",
"Exception",
"(",
"'Input a mesh into the... | Enables picking of cells. Press r to enable retangle based
selection. Press "r" again to turn it off. Selection will be
saved to self.picked_cells.
Uses last input mesh for input
Parameters
----------
mesh : vtk.UnstructuredGrid, optional
UnstructuredGrid grid to select cells from. Uses last
input grid by default.
callback : function, optional
When input, calls this function after a selection is made.
The picked_cells are input as the first parameter to this function. | [
"Enables",
"picking",
"of",
"cells",
".",
"Press",
"r",
"to",
"enable",
"retangle",
"based",
"selection",
".",
"Press",
"r",
"again",
"to",
"turn",
"it",
"off",
".",
"Selection",
"will",
"be",
"saved",
"to",
"self",
".",
"picked_cells",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2584-L2624 |
236,505 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.generate_orbital_path | def generate_orbital_path(self, factor=3., n_points=20, viewup=None, z_shift=None):
"""Genrates an orbital path around the data scene
Parameters
----------
facotr : float
A scaling factor when biulding the orbital extent
n_points : int
number of points on the orbital path
viewup : list(float)
the normal to the orbital plane
z_shift : float, optional
shift the plane up/down from the center of the scene by this amount
"""
if viewup is None:
viewup = rcParams['camera']['viewup']
center = list(self.center)
bnds = list(self.bounds)
if z_shift is None:
z_shift = (bnds[5] - bnds[4]) * factor
center[2] = center[2] + z_shift
radius = (bnds[1] - bnds[0]) * factor
y = (bnds[3] - bnds[2]) * factor
if y > radius:
radius = y
return vtki.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points) | python | def generate_orbital_path(self, factor=3., n_points=20, viewup=None, z_shift=None):
if viewup is None:
viewup = rcParams['camera']['viewup']
center = list(self.center)
bnds = list(self.bounds)
if z_shift is None:
z_shift = (bnds[5] - bnds[4]) * factor
center[2] = center[2] + z_shift
radius = (bnds[1] - bnds[0]) * factor
y = (bnds[3] - bnds[2]) * factor
if y > radius:
radius = y
return vtki.Polygon(center=center, radius=radius, normal=viewup, n_sides=n_points) | [
"def",
"generate_orbital_path",
"(",
"self",
",",
"factor",
"=",
"3.",
",",
"n_points",
"=",
"20",
",",
"viewup",
"=",
"None",
",",
"z_shift",
"=",
"None",
")",
":",
"if",
"viewup",
"is",
"None",
":",
"viewup",
"=",
"rcParams",
"[",
"'camera'",
"]",
... | Genrates an orbital path around the data scene
Parameters
----------
facotr : float
A scaling factor when biulding the orbital extent
n_points : int
number of points on the orbital path
viewup : list(float)
the normal to the orbital plane
z_shift : float, optional
shift the plane up/down from the center of the scene by this amount | [
"Genrates",
"an",
"orbital",
"path",
"around",
"the",
"data",
"scene"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2627-L2655 |
236,506 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.orbit_on_path | def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, bkg=True):
"""Orbit on the given path focusing on the focus point
Parameters
----------
path : vtki.PolyData
Path of orbital points. The order in the points is the order of
travel
focus : list(float) of length 3, optional
The point ot focus the camera.
step : float, optional
The timestep between flying to each camera position
viewup : list(float)
the normal to the orbital plane
"""
if focus is None:
focus = self.center
if viewup is None:
viewup = rcParams['camera']['viewup']
if path is None:
path = self.generate_orbital_path(viewup=viewup)
if not is_vtki_obj(path):
path = vtki.PolyData(path)
points = path.points
def orbit():
"""Internal thread for running the orbit"""
for point in points:
self.set_position(point)
self.set_focus(focus)
self.set_viewup(viewup)
time.sleep(step)
if bkg:
thread = Thread(target=orbit)
thread.start()
else:
orbit()
return | python | def orbit_on_path(self, path=None, focus=None, step=0.5, viewup=None, bkg=True):
if focus is None:
focus = self.center
if viewup is None:
viewup = rcParams['camera']['viewup']
if path is None:
path = self.generate_orbital_path(viewup=viewup)
if not is_vtki_obj(path):
path = vtki.PolyData(path)
points = path.points
def orbit():
"""Internal thread for running the orbit"""
for point in points:
self.set_position(point)
self.set_focus(focus)
self.set_viewup(viewup)
time.sleep(step)
if bkg:
thread = Thread(target=orbit)
thread.start()
else:
orbit()
return | [
"def",
"orbit_on_path",
"(",
"self",
",",
"path",
"=",
"None",
",",
"focus",
"=",
"None",
",",
"step",
"=",
"0.5",
",",
"viewup",
"=",
"None",
",",
"bkg",
"=",
"True",
")",
":",
"if",
"focus",
"is",
"None",
":",
"focus",
"=",
"self",
".",
"center... | Orbit on the given path focusing on the focus point
Parameters
----------
path : vtki.PolyData
Path of orbital points. The order in the points is the order of
travel
focus : list(float) of length 3, optional
The point ot focus the camera.
step : float, optional
The timestep between flying to each camera position
viewup : list(float)
the normal to the orbital plane | [
"Orbit",
"on",
"the",
"given",
"path",
"focusing",
"on",
"the",
"focus",
"point"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2666-L2708 |
236,507 | vtkiorg/vtki | vtki/plotting.py | BasePlotter.export_vtkjs | def export_vtkjs(self, filename, compress_arrays=False):
"""
Export the current rendering scene as a VTKjs scene for
rendering in a web browser
"""
if not hasattr(self, 'ren_win'):
raise RuntimeError('Export must be called before showing/closing the scene.')
if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):
filename = os.path.join(vtki.FIGURE_PATH, filename)
return export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays) | python | def export_vtkjs(self, filename, compress_arrays=False):
if not hasattr(self, 'ren_win'):
raise RuntimeError('Export must be called before showing/closing the scene.')
if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename):
filename = os.path.join(vtki.FIGURE_PATH, filename)
return export_plotter_vtkjs(self, filename, compress_arrays=compress_arrays) | [
"def",
"export_vtkjs",
"(",
"self",
",",
"filename",
",",
"compress_arrays",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'ren_win'",
")",
":",
"raise",
"RuntimeError",
"(",
"'Export must be called before showing/closing the scene.'",
")",
"i... | Export the current rendering scene as a VTKjs scene for
rendering in a web browser | [
"Export",
"the",
"current",
"rendering",
"scene",
"as",
"a",
"VTKjs",
"scene",
"for",
"rendering",
"in",
"a",
"web",
"browser"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2711-L2720 |
236,508 | vtkiorg/vtki | vtki/plotting.py | Plotter.show | def show(self, title=None, window_size=None, interactive=True,
auto_close=True, interactive_update=False, full_screen=False,
screenshot=False, return_img=False, use_panel=None):
"""
Creates plotting window
Parameters
----------
title : string, optional
Title of plotting window.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
interactive : bool, optional
Enabled by default. Allows user to pan and move figure.
auto_close : bool, optional
Enabled by default. Exits plotting session when user
closes the window when interactive is True.
interactive_update: bool, optional
Disabled by default. Allows user to non-blocking draw,
user should call Update() in each iteration.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores
window_size. Default False.
use_panel : bool, optional
If False, the interactive rendering from panel will not be used in
notebooks
Returns
-------
cpos : list
List of camera position, focal point, and view up
"""
if use_panel is None:
use_panel = rcParams['use_panel']
# reset unless camera for the first render unless camera is set
if self._first_time: # and not self.camera_set:
for renderer in self.renderers:
if not renderer.camera_set:
renderer.camera_position = renderer.get_default_cam_pos()
renderer.ResetCamera()
self._first_time = False
if title:
self.ren_win.SetWindowName(title)
# if full_screen:
if full_screen:
self.ren_win.SetFullScreen(True)
self.ren_win.BordersOn() # super buggy when disabled
else:
if window_size is None:
window_size = self.window_size
self.ren_win.SetSize(window_size[0], window_size[1])
# Render
log.debug('Rendering')
self.ren_win.Render()
# Keep track of image for sphinx-gallery
self.last_image = self.screenshot(screenshot, return_img=True)
disp = None
if interactive and (not self.off_screen):
try: # interrupts will be caught here
log.debug('Starting iren')
self.update_style()
self.iren.Initialize()
if not interactive_update:
self.iren.Start()
except KeyboardInterrupt:
log.debug('KeyboardInterrupt')
self.close()
raise KeyboardInterrupt
elif self.notebook and use_panel:
try:
from panel.pane import VTK as panel_display
disp = panel_display(self.ren_win, sizing_mode='stretch_width',
height=400)
except:
pass
# NOTE: after this point, nothing from the render window can be accessed
# as if a user presed the close button, then it destroys the
# the render view and a stream of errors will kill the Python
# kernel if code here tries to access that renderer.
# See issues #135 and #186 for insight before editing the
# remainder of this function.
# Get camera position before closing
cpos = self.camera_position
# NOTE: our conversion to panel currently does not support mult-view
# so we should display the static screenshot in notebooks for
# multi-view plots until we implement this feature
# If notebook is true and panel display failed:
if self.notebook and (disp is None or self.shape != (1,1)):
import PIL.Image
# sanity check
try:
import IPython
except ImportError:
raise Exception('Install IPython to display image in a notebook')
disp = IPython.display.display(PIL.Image.fromarray(self.last_image))
# Cleanup
if auto_close:
self.close()
# Return the notebook display: either panel object or image display
if self.notebook:
return disp
# If user asked for screenshot, return as numpy array after camera
# position
if return_img or screenshot == True:
return cpos, self.last_image
# default to returning last used camera position
return cpos | python | def show(self, title=None, window_size=None, interactive=True,
auto_close=True, interactive_update=False, full_screen=False,
screenshot=False, return_img=False, use_panel=None):
if use_panel is None:
use_panel = rcParams['use_panel']
# reset unless camera for the first render unless camera is set
if self._first_time: # and not self.camera_set:
for renderer in self.renderers:
if not renderer.camera_set:
renderer.camera_position = renderer.get_default_cam_pos()
renderer.ResetCamera()
self._first_time = False
if title:
self.ren_win.SetWindowName(title)
# if full_screen:
if full_screen:
self.ren_win.SetFullScreen(True)
self.ren_win.BordersOn() # super buggy when disabled
else:
if window_size is None:
window_size = self.window_size
self.ren_win.SetSize(window_size[0], window_size[1])
# Render
log.debug('Rendering')
self.ren_win.Render()
# Keep track of image for sphinx-gallery
self.last_image = self.screenshot(screenshot, return_img=True)
disp = None
if interactive and (not self.off_screen):
try: # interrupts will be caught here
log.debug('Starting iren')
self.update_style()
self.iren.Initialize()
if not interactive_update:
self.iren.Start()
except KeyboardInterrupt:
log.debug('KeyboardInterrupt')
self.close()
raise KeyboardInterrupt
elif self.notebook and use_panel:
try:
from panel.pane import VTK as panel_display
disp = panel_display(self.ren_win, sizing_mode='stretch_width',
height=400)
except:
pass
# NOTE: after this point, nothing from the render window can be accessed
# as if a user presed the close button, then it destroys the
# the render view and a stream of errors will kill the Python
# kernel if code here tries to access that renderer.
# See issues #135 and #186 for insight before editing the
# remainder of this function.
# Get camera position before closing
cpos = self.camera_position
# NOTE: our conversion to panel currently does not support mult-view
# so we should display the static screenshot in notebooks for
# multi-view plots until we implement this feature
# If notebook is true and panel display failed:
if self.notebook and (disp is None or self.shape != (1,1)):
import PIL.Image
# sanity check
try:
import IPython
except ImportError:
raise Exception('Install IPython to display image in a notebook')
disp = IPython.display.display(PIL.Image.fromarray(self.last_image))
# Cleanup
if auto_close:
self.close()
# Return the notebook display: either panel object or image display
if self.notebook:
return disp
# If user asked for screenshot, return as numpy array after camera
# position
if return_img or screenshot == True:
return cpos, self.last_image
# default to returning last used camera position
return cpos | [
"def",
"show",
"(",
"self",
",",
"title",
"=",
"None",
",",
"window_size",
"=",
"None",
",",
"interactive",
"=",
"True",
",",
"auto_close",
"=",
"True",
",",
"interactive_update",
"=",
"False",
",",
"full_screen",
"=",
"False",
",",
"screenshot",
"=",
"F... | Creates plotting window
Parameters
----------
title : string, optional
Title of plotting window.
window_size : list, optional
Window size in pixels. Defaults to [1024, 768]
interactive : bool, optional
Enabled by default. Allows user to pan and move figure.
auto_close : bool, optional
Enabled by default. Exits plotting session when user
closes the window when interactive is True.
interactive_update: bool, optional
Disabled by default. Allows user to non-blocking draw,
user should call Update() in each iteration.
full_screen : bool, optional
Opens window in full screen. When enabled, ignores
window_size. Default False.
use_panel : bool, optional
If False, the interactive rendering from panel will not be used in
notebooks
Returns
-------
cpos : list
List of camera position, focal point, and view up | [
"Creates",
"plotting",
"window"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2834-L2958 |
236,509 | vtkiorg/vtki | vtki/examples/examples.py | load_structured | def load_structured():
""" Loads a simple StructuredGrid """
x = np.arange(-10, 10, 0.25)
y = np.arange(-10, 10, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
return vtki.StructuredGrid(x, y, z) | python | def load_structured():
x = np.arange(-10, 10, 0.25)
y = np.arange(-10, 10, 0.25)
x, y = np.meshgrid(x, y)
r = np.sqrt(x**2 + y**2)
z = np.sin(r)
return vtki.StructuredGrid(x, y, z) | [
"def",
"load_structured",
"(",
")",
":",
"x",
"=",
"np",
".",
"arange",
"(",
"-",
"10",
",",
"10",
",",
"0.25",
")",
"y",
"=",
"np",
".",
"arange",
"(",
"-",
"10",
",",
"10",
",",
"0.25",
")",
"x",
",",
"y",
"=",
"np",
".",
"meshgrid",
"(",... | Loads a simple StructuredGrid | [
"Loads",
"a",
"simple",
"StructuredGrid"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/examples.py#L53-L60 |
236,510 | vtkiorg/vtki | vtki/examples/examples.py | plot_ants_plane | def plot_ants_plane(off_screen=False, notebook=None):
"""
Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane
"""
# load and shrink airplane
airplane = vtki.PolyData(planefile)
airplane.points /= 10
# pts = airplane.points # gets pointer to array
# pts /= 10 # shrink
# rotate and translate ant so it is on the plane
ant = vtki.PolyData(antfile)
ant.rotate_x(90)
ant.translate([90, 60, 15])
# Make a copy and add another ant
ant_copy = ant.copy()
ant_copy.translate([30, 0, -10])
# Create plotting object
plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook)
plotter.add_mesh(ant, 'r')
plotter.add_mesh(ant_copy, 'b')
# Add airplane mesh and make the color equal to the Y position
plane_scalars = airplane.points[:, 1]
plotter.add_mesh(airplane, scalars=plane_scalars, stitle='Plane Y\nLocation')
plotter.add_text('Ants and Plane Example')
plotter.plot() | python | def plot_ants_plane(off_screen=False, notebook=None):
# load and shrink airplane
airplane = vtki.PolyData(planefile)
airplane.points /= 10
# pts = airplane.points # gets pointer to array
# pts /= 10 # shrink
# rotate and translate ant so it is on the plane
ant = vtki.PolyData(antfile)
ant.rotate_x(90)
ant.translate([90, 60, 15])
# Make a copy and add another ant
ant_copy = ant.copy()
ant_copy.translate([30, 0, -10])
# Create plotting object
plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook)
plotter.add_mesh(ant, 'r')
plotter.add_mesh(ant_copy, 'b')
# Add airplane mesh and make the color equal to the Y position
plane_scalars = airplane.points[:, 1]
plotter.add_mesh(airplane, scalars=plane_scalars, stitle='Plane Y\nLocation')
plotter.add_text('Ants and Plane Example')
plotter.plot() | [
"def",
"plot_ants_plane",
"(",
"off_screen",
"=",
"False",
",",
"notebook",
"=",
"None",
")",
":",
"# load and shrink airplane",
"airplane",
"=",
"vtki",
".",
"PolyData",
"(",
"planefile",
")",
"airplane",
".",
"points",
"/=",
"10",
"# pts = airplane.points # gets... | Demonstrate how to create a plot class to plot multiple meshes while
adding scalars and text.
Plot two ants and airplane | [
"Demonstrate",
"how",
"to",
"create",
"a",
"plot",
"class",
"to",
"plot",
"multiple",
"meshes",
"while",
"adding",
"scalars",
"and",
"text",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/examples.py#L77-L109 |
236,511 | vtkiorg/vtki | vtki/examples/examples.py | plot_wave | def plot_wave(fps=30, frequency=1, wavetime=3, interactive=False,
off_screen=False, notebook=None):
"""
Plot a 3D moving wave in a render window.
Parameters
----------
fps : int, optional
Maximum frames per second to display. Defaults to 30.
frequency: float, optional
Wave cycles per second. Defaults to 1
wavetime : float, optional
The desired total display time in seconds. Defaults to 3 seconds.
interactive: bool, optional
Allows the user to set the camera position before the start of the
wave movement. Default False.
off_screen : bool, optional
Enables off screen rendering when True. Used for automated testing.
Disabled by default.
Returns
-------
points : np.ndarray
Position of points at last frame.
"""
# camera position
cpos = [(6.879481857604187, -32.143727535933195, 23.05622921691103),
(-0.2336056403734026, -0.6960083534590372, -0.7226721553894022),
(-0.008900669873416645, 0.6018246347860926, 0.7985786667826725)]
# Make data
X = np.arange(-10, 10, 0.25)
Y = np.arange(-10, 10, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Create and plot structured grid
sgrid = vtki.StructuredGrid(X, Y, Z)
# Get pointer to points
points = sgrid.points.copy()
# Start a plotter object and set the scalars to the Z height
plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook)
plotter.add_mesh(sgrid, scalars=Z.ravel())
plotter.camera_position = cpos
plotter.plot(title='Wave Example', window_size=[800, 600],
# auto_close=False, interactive=interactive)
auto_close=False, interactive_update=True)
# Update Z and display a frame for each updated position
tdelay = 1. / fps
tlast = time.time()
tstart = time.time()
while time.time() - tstart < wavetime:
# get phase from start
telap = time.time() - tstart
phase = telap * 2 * np.pi * frequency
Z = np.sin(R + phase)
points[:, -1] = Z.ravel()
# update plotting object, but don't automatically render
plotter.update_coordinates(points, render=False)
plotter.update_scalars(Z.ravel(), render=False)
# Render and get time to render
rstart = time.time()
plotter.update()
# plotter.render()
rstop = time.time()
# time delay
tpast = time.time() - tlast
if tpast < tdelay and tpast >= 0:
time.sleep(tdelay - tpast)
# get render time and actual FPS
# rtime = rstop - rstart
# act_fps = 1 / (time.time() - tlast + 1E-10)
tlast = time.time()
# Close movie and delete object
plotter.close()
return points | python | def plot_wave(fps=30, frequency=1, wavetime=3, interactive=False,
off_screen=False, notebook=None):
# camera position
cpos = [(6.879481857604187, -32.143727535933195, 23.05622921691103),
(-0.2336056403734026, -0.6960083534590372, -0.7226721553894022),
(-0.008900669873416645, 0.6018246347860926, 0.7985786667826725)]
# Make data
X = np.arange(-10, 10, 0.25)
Y = np.arange(-10, 10, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# Create and plot structured grid
sgrid = vtki.StructuredGrid(X, Y, Z)
# Get pointer to points
points = sgrid.points.copy()
# Start a plotter object and set the scalars to the Z height
plotter = vtki.Plotter(off_screen=off_screen, notebook=notebook)
plotter.add_mesh(sgrid, scalars=Z.ravel())
plotter.camera_position = cpos
plotter.plot(title='Wave Example', window_size=[800, 600],
# auto_close=False, interactive=interactive)
auto_close=False, interactive_update=True)
# Update Z and display a frame for each updated position
tdelay = 1. / fps
tlast = time.time()
tstart = time.time()
while time.time() - tstart < wavetime:
# get phase from start
telap = time.time() - tstart
phase = telap * 2 * np.pi * frequency
Z = np.sin(R + phase)
points[:, -1] = Z.ravel()
# update plotting object, but don't automatically render
plotter.update_coordinates(points, render=False)
plotter.update_scalars(Z.ravel(), render=False)
# Render and get time to render
rstart = time.time()
plotter.update()
# plotter.render()
rstop = time.time()
# time delay
tpast = time.time() - tlast
if tpast < tdelay and tpast >= 0:
time.sleep(tdelay - tpast)
# get render time and actual FPS
# rtime = rstop - rstart
# act_fps = 1 / (time.time() - tlast + 1E-10)
tlast = time.time()
# Close movie and delete object
plotter.close()
return points | [
"def",
"plot_wave",
"(",
"fps",
"=",
"30",
",",
"frequency",
"=",
"1",
",",
"wavetime",
"=",
"3",
",",
"interactive",
"=",
"False",
",",
"off_screen",
"=",
"False",
",",
"notebook",
"=",
"None",
")",
":",
"# camera position",
"cpos",
"=",
"[",
"(",
"... | Plot a 3D moving wave in a render window.
Parameters
----------
fps : int, optional
Maximum frames per second to display. Defaults to 30.
frequency: float, optional
Wave cycles per second. Defaults to 1
wavetime : float, optional
The desired total display time in seconds. Defaults to 3 seconds.
interactive: bool, optional
Allows the user to set the camera position before the start of the
wave movement. Default False.
off_screen : bool, optional
Enables off screen rendering when True. Used for automated testing.
Disabled by default.
Returns
-------
points : np.ndarray
Position of points at last frame. | [
"Plot",
"a",
"3D",
"moving",
"wave",
"in",
"a",
"render",
"window",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/examples/examples.py#L145-L235 |
236,512 | vtkiorg/vtki | vtki/filters.py | _get_output | def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
"""A helper to get the algorithm's output and copy input's vtki meta info"""
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
data.copy_meta_from(ido)
if active_scalar is not None:
data.set_active_scalar(active_scalar, preference=active_scalar_field)
return data | python | def _get_output(algorithm, iport=0, iconnection=0, oport=0, active_scalar=None,
active_scalar_field='point'):
ido = algorithm.GetInputDataObject(iport, iconnection)
data = wrap(algorithm.GetOutputDataObject(oport))
data.copy_meta_from(ido)
if active_scalar is not None:
data.set_active_scalar(active_scalar, preference=active_scalar_field)
return data | [
"def",
"_get_output",
"(",
"algorithm",
",",
"iport",
"=",
"0",
",",
"iconnection",
"=",
"0",
",",
"oport",
"=",
"0",
",",
"active_scalar",
"=",
"None",
",",
"active_scalar_field",
"=",
"'point'",
")",
":",
"ido",
"=",
"algorithm",
".",
"GetInputDataObject... | A helper to get the algorithm's output and copy input's vtki meta info | [
"A",
"helper",
"to",
"get",
"the",
"algorithm",
"s",
"output",
"and",
"copy",
"input",
"s",
"vtki",
"meta",
"info"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L44-L52 |
236,513 | vtkiorg/vtki | vtki/filters.py | _generate_plane | def _generate_plane(normal, origin):
""" Returns a vtk.vtkPlane """
plane = vtk.vtkPlane()
plane.SetNormal(normal[0], normal[1], normal[2])
plane.SetOrigin(origin[0], origin[1], origin[2])
return plane | python | def _generate_plane(normal, origin):
plane = vtk.vtkPlane()
plane.SetNormal(normal[0], normal[1], normal[2])
plane.SetOrigin(origin[0], origin[1], origin[2])
return plane | [
"def",
"_generate_plane",
"(",
"normal",
",",
"origin",
")",
":",
"plane",
"=",
"vtk",
".",
"vtkPlane",
"(",
")",
"plane",
".",
"SetNormal",
"(",
"normal",
"[",
"0",
"]",
",",
"normal",
"[",
"1",
"]",
",",
"normal",
"[",
"2",
"]",
")",
"plane",
"... | Returns a vtk.vtkPlane | [
"Returns",
"a",
"vtk",
".",
"vtkPlane"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L55-L60 |
236,514 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.clip | def clip(dataset, normal='x', origin=None, invert=True):
"""
Clip a dataset by a plane by specifying the origin and normal. If no
parameters are given the clip will occur in the center of that dataset
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)``, etc.
origin : tuple(float)
The center ``(x,y,z)`` coordinate of the plane on which the clip
occurs
invert : bool
Flag on whether to flip/invert the clip
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
# create the plane for clipping
plane = _generate_plane(normal, origin)
# run the clip
alg = vtk.vtkClipDataSet()
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetClipFunction(plane) # the the cutter to use the plane we made
alg.SetInsideOut(invert) # invert the clip if needed
alg.Update() # Perfrom the Cut
return _get_output(alg) | python | def clip(dataset, normal='x', origin=None, invert=True):
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
# create the plane for clipping
plane = _generate_plane(normal, origin)
# run the clip
alg = vtk.vtkClipDataSet()
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetClipFunction(plane) # the the cutter to use the plane we made
alg.SetInsideOut(invert) # invert the clip if needed
alg.Update() # Perfrom the Cut
return _get_output(alg) | [
"def",
"clip",
"(",
"dataset",
",",
"normal",
"=",
"'x'",
",",
"origin",
"=",
"None",
",",
"invert",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"normal",
",",
"str",
")",
":",
"normal",
"=",
"NORMALS",
"[",
"normal",
".",
"lower",
"(",
")",
... | Clip a dataset by a plane by specifying the origin and normal. If no
parameters are given the clip will occur in the center of that dataset
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)``, etc.
origin : tuple(float)
The center ``(x,y,z)`` coordinate of the plane on which the clip
occurs
invert : bool
Flag on whether to flip/invert the clip | [
"Clip",
"a",
"dataset",
"by",
"a",
"plane",
"by",
"specifying",
"the",
"origin",
"and",
"normal",
".",
"If",
"no",
"parameters",
"are",
"given",
"the",
"clip",
"will",
"occur",
"in",
"the",
"center",
"of",
"that",
"dataset"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L73-L106 |
236,515 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.clip_box | def clip_box(dataset, bounds=None, invert=True, factor=0.35):
"""Clips a dataset by a bounding box defined by the bounds. If no bounds
are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float)
Length 6 iterable of floats: (xmin, xmax, ymin, ymax, zmin, zmax)
invert : bool
Flag on whether to flip/invert the clip
factor : float, optional
If bounds are not given this is the factor along each axis to
extract the default box.
"""
if bounds is None:
def _get_quarter(dmin, dmax):
"""internal helper to get a section of the given range"""
return dmax - ((dmax - dmin) * factor)
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
xmin = _get_quarter(xmin, xmax)
ymin = _get_quarter(ymin, ymax)
zmin = _get_quarter(zmin, zmax)
bounds = [xmin, xmax, ymin, ymax, zmin, zmax]
if isinstance(bounds, (float, int)):
bounds = [bounds, bounds, bounds]
if len(bounds) == 3:
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
bounds = (xmin,xmin+bounds[0], ymin,ymin+bounds[1], zmin,zmin+bounds[2])
if not isinstance(bounds, collections.Iterable) or len(bounds) != 6:
raise AssertionError('Bounds must be a length 6 iterable of floats')
xmin, xmax, ymin, ymax, zmin, zmax = bounds
alg = vtk.vtkBoxClipDataSet()
alg.SetInputDataObject(dataset)
alg.SetBoxClip(xmin, xmax, ymin, ymax, zmin, zmax)
port = 0
if invert:
# invert the clip if needed
port = 1
alg.GenerateClippedOutputOn()
alg.Update()
return _get_output(alg, oport=port) | python | def clip_box(dataset, bounds=None, invert=True, factor=0.35):
if bounds is None:
def _get_quarter(dmin, dmax):
"""internal helper to get a section of the given range"""
return dmax - ((dmax - dmin) * factor)
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
xmin = _get_quarter(xmin, xmax)
ymin = _get_quarter(ymin, ymax)
zmin = _get_quarter(zmin, zmax)
bounds = [xmin, xmax, ymin, ymax, zmin, zmax]
if isinstance(bounds, (float, int)):
bounds = [bounds, bounds, bounds]
if len(bounds) == 3:
xmin, xmax, ymin, ymax, zmin, zmax = dataset.bounds
bounds = (xmin,xmin+bounds[0], ymin,ymin+bounds[1], zmin,zmin+bounds[2])
if not isinstance(bounds, collections.Iterable) or len(bounds) != 6:
raise AssertionError('Bounds must be a length 6 iterable of floats')
xmin, xmax, ymin, ymax, zmin, zmax = bounds
alg = vtk.vtkBoxClipDataSet()
alg.SetInputDataObject(dataset)
alg.SetBoxClip(xmin, xmax, ymin, ymax, zmin, zmax)
port = 0
if invert:
# invert the clip if needed
port = 1
alg.GenerateClippedOutputOn()
alg.Update()
return _get_output(alg, oport=port) | [
"def",
"clip_box",
"(",
"dataset",
",",
"bounds",
"=",
"None",
",",
"invert",
"=",
"True",
",",
"factor",
"=",
"0.35",
")",
":",
"if",
"bounds",
"is",
"None",
":",
"def",
"_get_quarter",
"(",
"dmin",
",",
"dmax",
")",
":",
"\"\"\"internal helper to get a... | Clips a dataset by a bounding box defined by the bounds. If no bounds
are given, a corner of the dataset bounds will be removed.
Parameters
----------
bounds : tuple(float)
Length 6 iterable of floats: (xmin, xmax, ymin, ymax, zmin, zmax)
invert : bool
Flag on whether to flip/invert the clip
factor : float, optional
If bounds are not given this is the factor along each axis to
extract the default box. | [
"Clips",
"a",
"dataset",
"by",
"a",
"bounding",
"box",
"defined",
"by",
"the",
"bounds",
".",
"If",
"no",
"bounds",
"are",
"given",
"a",
"corner",
"of",
"the",
"dataset",
"bounds",
"will",
"be",
"removed",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L108-L151 |
236,516 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.slice | def slice(dataset, normal='x', origin=None, generate_triangles=False,
contour=False):
"""Slice a dataset by a plane at the specified origin and normal vector
orientation. If no origin is specified, the center of the input dataset will
be used.
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)```, etc.
origin : tuple(float)
The center (x,y,z) coordinate of the plane on which the slice occurs
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
if not is_inside_bounds(origin, dataset.bounds):
raise AssertionError('Slice is outside data bounds.')
# create the plane for clipping
plane = _generate_plane(normal, origin)
# create slice
alg = vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetCutFunction(plane) # the the cutter to use the plane we made
if not generate_triangles:
alg.GenerateTrianglesOff()
alg.Update() # Perfrom the Cut
output = _get_output(alg)
if contour:
return output.contour()
return output | python | def slice(dataset, normal='x', origin=None, generate_triangles=False,
contour=False):
if isinstance(normal, str):
normal = NORMALS[normal.lower()]
# find center of data if origin not specified
if origin is None:
origin = dataset.center
if not is_inside_bounds(origin, dataset.bounds):
raise AssertionError('Slice is outside data bounds.')
# create the plane for clipping
plane = _generate_plane(normal, origin)
# create slice
alg = vtk.vtkCutter() # Construct the cutter object
alg.SetInputDataObject(dataset) # Use the grid as the data we desire to cut
alg.SetCutFunction(plane) # the the cutter to use the plane we made
if not generate_triangles:
alg.GenerateTrianglesOff()
alg.Update() # Perfrom the Cut
output = _get_output(alg)
if contour:
return output.contour()
return output | [
"def",
"slice",
"(",
"dataset",
",",
"normal",
"=",
"'x'",
",",
"origin",
"=",
"None",
",",
"generate_triangles",
"=",
"False",
",",
"contour",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"normal",
",",
"str",
")",
":",
"normal",
"=",
"NORMALS",
... | Slice a dataset by a plane at the specified origin and normal vector
orientation. If no origin is specified, the center of the input dataset will
be used.
Parameters
----------
normal : tuple(float) or str
Length 3 tuple for the normal vector direction. Can also be
specified as a string conventional direction such as ``'x'`` for
``(1,0,0)`` or ``'-x'`` for ``(-1,0,0)```, etc.
origin : tuple(float)
The center (x,y,z) coordinate of the plane on which the slice occurs
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing | [
"Slice",
"a",
"dataset",
"by",
"a",
"plane",
"at",
"the",
"specified",
"origin",
"and",
"normal",
"vector",
"orientation",
".",
"If",
"no",
"origin",
"is",
"specified",
"the",
"center",
"of",
"the",
"input",
"dataset",
"will",
"be",
"used",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L153-L196 |
236,517 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.slice_orthogonal | def slice_orthogonal(dataset, x=None, y=None, z=None,
generate_triangles=False, contour=False):
"""Creates three orthogonal slices through the dataset on the three
caresian planes. Yields a MutliBlock dataset of the three slices
Parameters
----------
x : float
The X location of the YZ slice
y : float
The Y location of the XZ slice
z : float
The Z location of the XY slice
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
output = vtki.MultiBlock()
# Create the three slices
if x is None:
x = dataset.center[0]
if y is None:
y = dataset.center[1]
if z is None:
z = dataset.center[2]
output[0, 'YZ'] = dataset.slice(normal='x', origin=[x,y,z], generate_triangles=generate_triangles)
output[1, 'XZ'] = dataset.slice(normal='y', origin=[x,y,z], generate_triangles=generate_triangles)
output[2, 'XY'] = dataset.slice(normal='z', origin=[x,y,z], generate_triangles=generate_triangles)
return output | python | def slice_orthogonal(dataset, x=None, y=None, z=None,
generate_triangles=False, contour=False):
output = vtki.MultiBlock()
# Create the three slices
if x is None:
x = dataset.center[0]
if y is None:
y = dataset.center[1]
if z is None:
z = dataset.center[2]
output[0, 'YZ'] = dataset.slice(normal='x', origin=[x,y,z], generate_triangles=generate_triangles)
output[1, 'XZ'] = dataset.slice(normal='y', origin=[x,y,z], generate_triangles=generate_triangles)
output[2, 'XY'] = dataset.slice(normal='z', origin=[x,y,z], generate_triangles=generate_triangles)
return output | [
"def",
"slice_orthogonal",
"(",
"dataset",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"z",
"=",
"None",
",",
"generate_triangles",
"=",
"False",
",",
"contour",
"=",
"False",
")",
":",
"output",
"=",
"vtki",
".",
"MultiBlock",
"(",
")",
"# Cr... | Creates three orthogonal slices through the dataset on the three
caresian planes. Yields a MutliBlock dataset of the three slices
Parameters
----------
x : float
The X location of the YZ slice
y : float
The Y location of the XZ slice
z : float
The Z location of the XY slice
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing | [
"Creates",
"three",
"orthogonal",
"slices",
"through",
"the",
"dataset",
"on",
"the",
"three",
"caresian",
"planes",
".",
"Yields",
"a",
"MutliBlock",
"dataset",
"of",
"the",
"three",
"slices"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L199-L234 |
236,518 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.slice_along_axis | def slice_along_axis(dataset, n=5, axis='x', tolerance=None,
generate_triangles=False, contour=False):
"""Create many slices of the input dataset along a specified axis.
Parameters
----------
n : int
The number of slices to create
axis : str or int
The axis to generate the slices along. Perpendicular to the slices.
Can be string name (``'x'``, ``'y'``, or ``'z'``) or axis index
(``0``, ``1``, or ``2``).
tolerance : float, optional
The toleranceerance to the edge of the dataset bounds to create the slices
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing
"""
axes = {'x':0, 'y':1, 'z':2}
output = vtki.MultiBlock()
if isinstance(axis, int):
ax = axis
axis = list(axes.keys())[list(axes.values()).index(ax)]
elif isinstance(axis, str):
try:
ax = axes[axis]
except KeyError:
raise RuntimeError('Axis ({}) not understood'.format(axis))
# get the locations along that axis
if tolerance is None:
tolerance = (dataset.bounds[ax*2+1] - dataset.bounds[ax*2]) * 0.01
rng = np.linspace(dataset.bounds[ax*2]+tolerance, dataset.bounds[ax*2+1]-tolerance, n)
center = list(dataset.center)
# Make each of the slices
for i in range(n):
center[ax] = rng[i]
slc = DataSetFilters.slice(dataset, normal=axis, origin=center,
generate_triangles=generate_triangles, contour=contour)
output[i, 'slice%.2d'%i] = slc
return output | python | def slice_along_axis(dataset, n=5, axis='x', tolerance=None,
generate_triangles=False, contour=False):
axes = {'x':0, 'y':1, 'z':2}
output = vtki.MultiBlock()
if isinstance(axis, int):
ax = axis
axis = list(axes.keys())[list(axes.values()).index(ax)]
elif isinstance(axis, str):
try:
ax = axes[axis]
except KeyError:
raise RuntimeError('Axis ({}) not understood'.format(axis))
# get the locations along that axis
if tolerance is None:
tolerance = (dataset.bounds[ax*2+1] - dataset.bounds[ax*2]) * 0.01
rng = np.linspace(dataset.bounds[ax*2]+tolerance, dataset.bounds[ax*2+1]-tolerance, n)
center = list(dataset.center)
# Make each of the slices
for i in range(n):
center[ax] = rng[i]
slc = DataSetFilters.slice(dataset, normal=axis, origin=center,
generate_triangles=generate_triangles, contour=contour)
output[i, 'slice%.2d'%i] = slc
return output | [
"def",
"slice_along_axis",
"(",
"dataset",
",",
"n",
"=",
"5",
",",
"axis",
"=",
"'x'",
",",
"tolerance",
"=",
"None",
",",
"generate_triangles",
"=",
"False",
",",
"contour",
"=",
"False",
")",
":",
"axes",
"=",
"{",
"'x'",
":",
"0",
",",
"'y'",
"... | Create many slices of the input dataset along a specified axis.
Parameters
----------
n : int
The number of slices to create
axis : str or int
The axis to generate the slices along. Perpendicular to the slices.
Can be string name (``'x'``, ``'y'``, or ``'z'``) or axis index
(``0``, ``1``, or ``2``).
tolerance : float, optional
The toleranceerance to the edge of the dataset bounds to create the slices
generate_triangles: bool, optional
If this is enabled (``False`` by default), the output will be
triangles otherwise, the output will be the intersection polygons.
contour : bool, optional
If True, apply a ``contour`` filter after slicing | [
"Create",
"many",
"slices",
"of",
"the",
"input",
"dataset",
"along",
"a",
"specified",
"axis",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L237-L283 |
236,519 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.threshold | def threshold(dataset, value=None, scalars=None, invert=False, continuous=False,
preference='cell'):
"""
This filter will apply a ``vtkThreshold`` filter to the input dataset and
return the resulting object. This extracts cells where scalar value in each
cell satisfies threshold criterion. If scalars is None, the inputs
active_scalar is used.
Parameters
----------
value : float or iterable, optional
Single value or (min, max) to be used for the data threshold. If
iterable, then length must be 2. If no value is specified, the
non-NaN data range will be used to remove any NaN values.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
If value is a single value, when invert is True cells are kept when
their values are below parameter "value". When invert is False
cells are kept when their value is above the threshold "value".
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maxmimum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
# set the scalaras to threshold on
if scalars is None:
field, scalars = dataset.active_scalar_info
arr, field = get_scalar(dataset, scalars, preference=preference, info=True)
if arr is None:
raise AssertionError('No arrays present to threshold.')
# If using an inverted range, merge the result of two fitlers:
if isinstance(value, collections.Iterable) and invert:
valid_range = [np.nanmin(arr), np.nanmax(arr)]
# Create two thresholds
t1 = dataset.threshold([valid_range[0], value[0]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
t2 = dataset.threshold([value[1], valid_range[1]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
# Use an AppendFilter to merge the two results
appender = vtk.vtkAppendFilter()
appender.AddInputData(t1)
appender.AddInputData(t2)
appender.Update()
return _get_output(appender)
# Run a standard threshold algorithm
alg = vtk.vtkThreshold()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
# set thresholding parameters
alg.SetUseContinuousCellRange(continuous)
# use valid range if no value given
if value is None:
value = dataset.get_data_range(scalars)
# check if value is iterable (if so threshold by min max range like ParaView)
if isinstance(value, collections.Iterable):
if len(value) != 2:
raise AssertionError('Value range must be length one for a float value or two for min/max; not ({}).'.format(value))
alg.ThresholdBetween(value[0], value[1])
else:
# just a single value
if invert:
alg.ThresholdByLower(value)
else:
alg.ThresholdByUpper(value)
# Run the threshold
alg.Update()
return _get_output(alg) | python | def threshold(dataset, value=None, scalars=None, invert=False, continuous=False,
preference='cell'):
# set the scalaras to threshold on
if scalars is None:
field, scalars = dataset.active_scalar_info
arr, field = get_scalar(dataset, scalars, preference=preference, info=True)
if arr is None:
raise AssertionError('No arrays present to threshold.')
# If using an inverted range, merge the result of two fitlers:
if isinstance(value, collections.Iterable) and invert:
valid_range = [np.nanmin(arr), np.nanmax(arr)]
# Create two thresholds
t1 = dataset.threshold([valid_range[0], value[0]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
t2 = dataset.threshold([value[1], valid_range[1]], scalars=scalars,
continuous=continuous, preference=preference, invert=False)
# Use an AppendFilter to merge the two results
appender = vtk.vtkAppendFilter()
appender.AddInputData(t1)
appender.AddInputData(t2)
appender.Update()
return _get_output(appender)
# Run a standard threshold algorithm
alg = vtk.vtkThreshold()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
# set thresholding parameters
alg.SetUseContinuousCellRange(continuous)
# use valid range if no value given
if value is None:
value = dataset.get_data_range(scalars)
# check if value is iterable (if so threshold by min max range like ParaView)
if isinstance(value, collections.Iterable):
if len(value) != 2:
raise AssertionError('Value range must be length one for a float value or two for min/max; not ({}).'.format(value))
alg.ThresholdBetween(value[0], value[1])
else:
# just a single value
if invert:
alg.ThresholdByLower(value)
else:
alg.ThresholdByUpper(value)
# Run the threshold
alg.Update()
return _get_output(alg) | [
"def",
"threshold",
"(",
"dataset",
",",
"value",
"=",
"None",
",",
"scalars",
"=",
"None",
",",
"invert",
"=",
"False",
",",
"continuous",
"=",
"False",
",",
"preference",
"=",
"'cell'",
")",
":",
"# set the scalaras to threshold on",
"if",
"scalars",
"is",... | This filter will apply a ``vtkThreshold`` filter to the input dataset and
return the resulting object. This extracts cells where scalar value in each
cell satisfies threshold criterion. If scalars is None, the inputs
active_scalar is used.
Parameters
----------
value : float or iterable, optional
Single value or (min, max) to be used for the data threshold. If
iterable, then length must be 2. If no value is specified, the
non-NaN data range will be used to remove any NaN values.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
If value is a single value, when invert is True cells are kept when
their values are below parameter "value". When invert is False
cells are kept when their value is above the threshold "value".
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maxmimum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'`` | [
"This",
"filter",
"will",
"apply",
"a",
"vtkThreshold",
"filter",
"to",
"the",
"input",
"dataset",
"and",
"return",
"the",
"resulting",
"object",
".",
"This",
"extracts",
"cells",
"where",
"scalar",
"value",
"in",
"each",
"cell",
"satisfies",
"threshold",
"cri... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L286-L365 |
236,520 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.threshold_percent | def threshold_percent(dataset, percent=0.50, scalars=None, invert=False,
continuous=False, preference='cell'):
"""Thresholds the dataset by a percentage of its range on the active
scalar array or as specified
Parameters
----------
percent : float or tuple(float), optional
The percentage (0,1) to threshold. If value is out of 0 to 1 range,
then it will be divided by 100 and checked to be in that range.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
When invert is True cells are kept when their values are below the
percentage of the range. When invert is False, cells are kept when
their value is above the percentage of the range.
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maxmimum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
if scalars is None:
_, tscalars = dataset.active_scalar_info
else:
tscalars = scalars
dmin, dmax = dataset.get_data_range(arr=tscalars, preference=preference)
def _check_percent(percent):
"""Make sure percent is between 0 and 1 or fix if between 0 and 100."""
if percent >= 1:
percent = float(percent) / 100.0
if percent > 1:
raise RuntimeError('Percentage ({}) is out of range (0, 1).'.format(percent))
if percent < 1e-10:
raise RuntimeError('Percentage ({}) is too close to zero or negative.'.format(percent))
return percent
def _get_val(percent, dmin, dmax):
"""Gets the value from a percentage of a range"""
percent = _check_percent(percent)
return dmin + float(percent) * (dmax - dmin)
# Compute the values
if isinstance(percent, collections.Iterable):
# Get two values
value = [_get_val(percent[0], dmin, dmax), _get_val(percent[1], dmin, dmax)]
else:
# Compute one value to threshold
value = _get_val(percent, dmin, dmax)
# Use the normal thresholding function on these values
return DataSetFilters.threshold(dataset, value=value, scalars=scalars,
invert=invert, continuous=continuous, preference=preference) | python | def threshold_percent(dataset, percent=0.50, scalars=None, invert=False,
continuous=False, preference='cell'):
if scalars is None:
_, tscalars = dataset.active_scalar_info
else:
tscalars = scalars
dmin, dmax = dataset.get_data_range(arr=tscalars, preference=preference)
def _check_percent(percent):
"""Make sure percent is between 0 and 1 or fix if between 0 and 100."""
if percent >= 1:
percent = float(percent) / 100.0
if percent > 1:
raise RuntimeError('Percentage ({}) is out of range (0, 1).'.format(percent))
if percent < 1e-10:
raise RuntimeError('Percentage ({}) is too close to zero or negative.'.format(percent))
return percent
def _get_val(percent, dmin, dmax):
"""Gets the value from a percentage of a range"""
percent = _check_percent(percent)
return dmin + float(percent) * (dmax - dmin)
# Compute the values
if isinstance(percent, collections.Iterable):
# Get two values
value = [_get_val(percent[0], dmin, dmax), _get_val(percent[1], dmin, dmax)]
else:
# Compute one value to threshold
value = _get_val(percent, dmin, dmax)
# Use the normal thresholding function on these values
return DataSetFilters.threshold(dataset, value=value, scalars=scalars,
invert=invert, continuous=continuous, preference=preference) | [
"def",
"threshold_percent",
"(",
"dataset",
",",
"percent",
"=",
"0.50",
",",
"scalars",
"=",
"None",
",",
"invert",
"=",
"False",
",",
"continuous",
"=",
"False",
",",
"preference",
"=",
"'cell'",
")",
":",
"if",
"scalars",
"is",
"None",
":",
"_",
","... | Thresholds the dataset by a percentage of its range on the active
scalar array or as specified
Parameters
----------
percent : float or tuple(float), optional
The percentage (0,1) to threshold. If value is out of 0 to 1 range,
then it will be divided by 100 and checked to be in that range.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
invert : bool, optional
When invert is True cells are kept when their values are below the
percentage of the range. When invert is False, cells are kept when
their value is above the percentage of the range.
Default is False: yielding above the threshold "value".
continuous : bool, optional
When True, the continuous interval [minimum cell scalar,
maxmimum cell scalar] will be used to intersect the threshold bound,
rather than the set of discrete scalar values from the vertices.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'`` | [
"Thresholds",
"the",
"dataset",
"by",
"a",
"percentage",
"of",
"its",
"range",
"on",
"the",
"active",
"scalar",
"array",
"or",
"as",
"specified"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L368-L428 |
236,521 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.outline | def outline(dataset, generate_faces=False):
"""Produces an outline of the full extent for the input dataset.
Parameters
----------
generate_faces : bool, optional
Generate solid faces for the box. This is off by default
"""
alg = vtk.vtkOutlineFilter()
alg.SetInputDataObject(dataset)
alg.SetGenerateFaces(generate_faces)
alg.Update()
return wrap(alg.GetOutputDataObject(0)) | python | def outline(dataset, generate_faces=False):
alg = vtk.vtkOutlineFilter()
alg.SetInputDataObject(dataset)
alg.SetGenerateFaces(generate_faces)
alg.Update()
return wrap(alg.GetOutputDataObject(0)) | [
"def",
"outline",
"(",
"dataset",
",",
"generate_faces",
"=",
"False",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkOutlineFilter",
"(",
")",
"alg",
".",
"SetInputDataObject",
"(",
"dataset",
")",
"alg",
".",
"SetGenerateFaces",
"(",
"generate_faces",
")",
"alg",
... | Produces an outline of the full extent for the input dataset.
Parameters
----------
generate_faces : bool, optional
Generate solid faces for the box. This is off by default | [
"Produces",
"an",
"outline",
"of",
"the",
"full",
"extent",
"for",
"the",
"input",
"dataset",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L431-L444 |
236,522 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.outline_corners | def outline_corners(dataset, factor=0.2):
"""Produces an outline of the corners for the input dataset.
Parameters
----------
factor : float, optional
controls the relative size of the corners to the length of the
corresponding bounds
"""
alg = vtk.vtkOutlineCornerFilter()
alg.SetInputDataObject(dataset)
alg.SetCornerFactor(factor)
alg.Update()
return wrap(alg.GetOutputDataObject(0)) | python | def outline_corners(dataset, factor=0.2):
alg = vtk.vtkOutlineCornerFilter()
alg.SetInputDataObject(dataset)
alg.SetCornerFactor(factor)
alg.Update()
return wrap(alg.GetOutputDataObject(0)) | [
"def",
"outline_corners",
"(",
"dataset",
",",
"factor",
"=",
"0.2",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkOutlineCornerFilter",
"(",
")",
"alg",
".",
"SetInputDataObject",
"(",
"dataset",
")",
"alg",
".",
"SetCornerFactor",
"(",
"factor",
")",
"alg",
".",... | Produces an outline of the corners for the input dataset.
Parameters
----------
factor : float, optional
controls the relative size of the corners to the length of the
corresponding bounds | [
"Produces",
"an",
"outline",
"of",
"the",
"corners",
"for",
"the",
"input",
"dataset",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L446-L460 |
236,523 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.extract_geometry | def extract_geometry(dataset):
"""Extract the outer surface of a volume or structured grid dataset as
PolyData. This will extract all 0D, 1D, and 2D cells producing the
boundary faces of the dataset.
"""
alg = vtk.vtkGeometryFilter()
alg.SetInputDataObject(dataset)
alg.Update()
return _get_output(alg) | python | def extract_geometry(dataset):
alg = vtk.vtkGeometryFilter()
alg.SetInputDataObject(dataset)
alg.Update()
return _get_output(alg) | [
"def",
"extract_geometry",
"(",
"dataset",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkGeometryFilter",
"(",
")",
"alg",
".",
"SetInputDataObject",
"(",
"dataset",
")",
"alg",
".",
"Update",
"(",
")",
"return",
"_get_output",
"(",
"alg",
")"
] | Extract the outer surface of a volume or structured grid dataset as
PolyData. This will extract all 0D, 1D, and 2D cells producing the
boundary faces of the dataset. | [
"Extract",
"the",
"outer",
"surface",
"of",
"a",
"volume",
"or",
"structured",
"grid",
"dataset",
"as",
"PolyData",
".",
"This",
"will",
"extract",
"all",
"0D",
"1D",
"and",
"2D",
"cells",
"producing",
"the",
"boundary",
"faces",
"of",
"the",
"dataset",
".... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L462-L470 |
236,524 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.elevation | def elevation(dataset, low_point=None, high_point=None, scalar_range=None,
preference='point', set_active=True):
"""Generate scalar values on a dataset. The scalar values lie within a
user specified range, and are generated by computing a projection of
each dataset point onto a line.
The line can be oriented arbitrarily.
A typical example is to generate scalars based on elevation or height
above a plane.
Parameters
----------
low_point : tuple(float), optional
The low point of the projection line in 3D space. Default is bottom
center of the dataset. Otherwise pass a length 3 tuple(float).
high_point : tuple(float), optional
The high point of the projection line in 3D space. Default is top
center of the dataset. Otherwise pass a length 3 tuple(float).
scalar_range : str or tuple(float), optional
The scalar range to project to the low and high points on the line
that will be mapped to the dataset. If None given, the values will
be computed from the elevation (Z component) range between the
high and low points. Min and max of a range can be given as a length
2 tuple(float). If ``str`` name of scalara array present in the
dataset given, the valid range of that array will be used.
preference : str, optional
When a scalar name is specified for ``scalar_range``, this is the
perfered scalar type to search for in the dataset.
Must be either 'point' or 'cell'.
set_active : bool, optional
A boolean flag on whethter or not to set the new `Elevation` scalar
as the active scalar array on the output dataset.
Warning
-------
This will create a scalar array named `Elevation` on the point data of
the input dataset and overasdf write an array named `Elevation` if present.
"""
# Fix the projection line:
if low_point is None:
low_point = list(dataset.center)
low_point[2] = dataset.bounds[4]
if high_point is None:
high_point = list(dataset.center)
high_point[2] = dataset.bounds[5]
# Fix scalar_range:
if scalar_range is None:
scalar_range = (low_point[2], high_point[2])
elif isinstance(scalar_range, str):
scalar_range = dataset.get_data_range(arr=scalar_range, preference=preference)
elif isinstance(scalar_range, collections.Iterable):
if len(scalar_range) != 2:
raise AssertionError('scalar_range must have a length of two defining the min and max')
else:
raise RuntimeError('scalar_range argument ({}) not understood.'.format(type(scalar_range)))
# Construct the filter
alg = vtk.vtkElevationFilter()
alg.SetInputDataObject(dataset)
# Set the parameters
alg.SetScalarRange(scalar_range)
alg.SetLowPoint(low_point)
alg.SetHighPoint(high_point)
alg.Update()
# Decide on updating active scalar array
name = 'Elevation' # Note that this is added to the PointData
if not set_active:
name = None
return _get_output(alg, active_scalar=name, active_scalar_field='point') | python | def elevation(dataset, low_point=None, high_point=None, scalar_range=None,
preference='point', set_active=True):
# Fix the projection line:
if low_point is None:
low_point = list(dataset.center)
low_point[2] = dataset.bounds[4]
if high_point is None:
high_point = list(dataset.center)
high_point[2] = dataset.bounds[5]
# Fix scalar_range:
if scalar_range is None:
scalar_range = (low_point[2], high_point[2])
elif isinstance(scalar_range, str):
scalar_range = dataset.get_data_range(arr=scalar_range, preference=preference)
elif isinstance(scalar_range, collections.Iterable):
if len(scalar_range) != 2:
raise AssertionError('scalar_range must have a length of two defining the min and max')
else:
raise RuntimeError('scalar_range argument ({}) not understood.'.format(type(scalar_range)))
# Construct the filter
alg = vtk.vtkElevationFilter()
alg.SetInputDataObject(dataset)
# Set the parameters
alg.SetScalarRange(scalar_range)
alg.SetLowPoint(low_point)
alg.SetHighPoint(high_point)
alg.Update()
# Decide on updating active scalar array
name = 'Elevation' # Note that this is added to the PointData
if not set_active:
name = None
return _get_output(alg, active_scalar=name, active_scalar_field='point') | [
"def",
"elevation",
"(",
"dataset",
",",
"low_point",
"=",
"None",
",",
"high_point",
"=",
"None",
",",
"scalar_range",
"=",
"None",
",",
"preference",
"=",
"'point'",
",",
"set_active",
"=",
"True",
")",
":",
"# Fix the projection line:",
"if",
"low_point",
... | Generate scalar values on a dataset. The scalar values lie within a
user specified range, and are generated by computing a projection of
each dataset point onto a line.
The line can be oriented arbitrarily.
A typical example is to generate scalars based on elevation or height
above a plane.
Parameters
----------
low_point : tuple(float), optional
The low point of the projection line in 3D space. Default is bottom
center of the dataset. Otherwise pass a length 3 tuple(float).
high_point : tuple(float), optional
The high point of the projection line in 3D space. Default is top
center of the dataset. Otherwise pass a length 3 tuple(float).
scalar_range : str or tuple(float), optional
The scalar range to project to the low and high points on the line
that will be mapped to the dataset. If None given, the values will
be computed from the elevation (Z component) range between the
high and low points. Min and max of a range can be given as a length
2 tuple(float). If ``str`` name of scalara array present in the
dataset given, the valid range of that array will be used.
preference : str, optional
When a scalar name is specified for ``scalar_range``, this is the
perfered scalar type to search for in the dataset.
Must be either 'point' or 'cell'.
set_active : bool, optional
A boolean flag on whethter or not to set the new `Elevation` scalar
as the active scalar array on the output dataset.
Warning
-------
This will create a scalar array named `Elevation` on the point data of
the input dataset and overasdf write an array named `Elevation` if present. | [
"Generate",
"scalar",
"values",
"on",
"a",
"dataset",
".",
"The",
"scalar",
"values",
"lie",
"within",
"a",
"user",
"specified",
"range",
"and",
"are",
"generated",
"by",
"computing",
"a",
"projection",
"of",
"each",
"dataset",
"point",
"onto",
"a",
"line",
... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L481-L552 |
236,525 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.contour | def contour(dataset, isosurfaces=10, scalars=None, compute_normals=False,
compute_gradients=False, compute_scalars=True, rng=None,
preference='point'):
"""Contours an input dataset by an array. ``isosurfaces`` can be an integer
specifying the number of isosurfaces in the data range or an iterable set of
values for explicitly setting the isosurfaces.
Parameters
----------
isosurfaces : int or iterable
Number of isosurfaces to compute across valid data range or an
iterable of float values to explicitly use as the isosurfaces.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
compute_normals : bool, optional
compute_gradients : bool, optional
Desc
compute_scalars : bool, optional
Preserves the scalar values that are being contoured
rng : tuple(float), optional
If an integer number of isosurfaces is specified, this is the range
over which to generate contours. Default is the scalar arrays's full
data range.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'``
"""
# Make sure the input has scalars to contour on
if dataset.n_scalars < 1:
raise AssertionError('Input dataset for the contour filter must have scalar data.')
alg = vtk.vtkContourFilter()
alg.SetInputDataObject(dataset)
alg.SetComputeNormals(compute_normals)
alg.SetComputeGradients(compute_gradients)
alg.SetComputeScalars(compute_scalars)
# set the array to contour on
if scalars is None:
field, scalars = dataset.active_scalar_info
else:
_, field = get_scalar(dataset, scalars, preference=preference, info=True)
# NOTE: only point data is allowed? well cells works but seems buggy?
if field != vtki.POINT_DATA_FIELD:
raise AssertionError('Contour filter only works on Point data. Array ({}) is in the Cell data.'.format(scalars))
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
# set the isosurfaces
if isinstance(isosurfaces, int):
# generate values
if rng is None:
rng = dataset.get_data_range(scalars)
alg.GenerateValues(isosurfaces, rng)
elif isinstance(isosurfaces, collections.Iterable):
alg.SetNumberOfContours(len(isosurfaces))
for i, val in enumerate(isosurfaces):
alg.SetValue(i, val)
else:
raise RuntimeError('isosurfaces not understood.')
alg.Update()
return _get_output(alg) | python | def contour(dataset, isosurfaces=10, scalars=None, compute_normals=False,
compute_gradients=False, compute_scalars=True, rng=None,
preference='point'):
# Make sure the input has scalars to contour on
if dataset.n_scalars < 1:
raise AssertionError('Input dataset for the contour filter must have scalar data.')
alg = vtk.vtkContourFilter()
alg.SetInputDataObject(dataset)
alg.SetComputeNormals(compute_normals)
alg.SetComputeGradients(compute_gradients)
alg.SetComputeScalars(compute_scalars)
# set the array to contour on
if scalars is None:
field, scalars = dataset.active_scalar_info
else:
_, field = get_scalar(dataset, scalars, preference=preference, info=True)
# NOTE: only point data is allowed? well cells works but seems buggy?
if field != vtki.POINT_DATA_FIELD:
raise AssertionError('Contour filter only works on Point data. Array ({}) is in the Cell data.'.format(scalars))
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
# set the isosurfaces
if isinstance(isosurfaces, int):
# generate values
if rng is None:
rng = dataset.get_data_range(scalars)
alg.GenerateValues(isosurfaces, rng)
elif isinstance(isosurfaces, collections.Iterable):
alg.SetNumberOfContours(len(isosurfaces))
for i, val in enumerate(isosurfaces):
alg.SetValue(i, val)
else:
raise RuntimeError('isosurfaces not understood.')
alg.Update()
return _get_output(alg) | [
"def",
"contour",
"(",
"dataset",
",",
"isosurfaces",
"=",
"10",
",",
"scalars",
"=",
"None",
",",
"compute_normals",
"=",
"False",
",",
"compute_gradients",
"=",
"False",
",",
"compute_scalars",
"=",
"True",
",",
"rng",
"=",
"None",
",",
"preference",
"="... | Contours an input dataset by an array. ``isosurfaces`` can be an integer
specifying the number of isosurfaces in the data range or an iterable set of
values for explicitly setting the isosurfaces.
Parameters
----------
isosurfaces : int or iterable
Number of isosurfaces to compute across valid data range or an
iterable of float values to explicitly use as the isosurfaces.
scalars : str, optional
Name of scalars to threshold on. Defaults to currently active scalars.
compute_normals : bool, optional
compute_gradients : bool, optional
Desc
compute_scalars : bool, optional
Preserves the scalar values that are being contoured
rng : tuple(float), optional
If an integer number of isosurfaces is specified, this is the range
over which to generate contours. Default is the scalar arrays's full
data range.
preference : str, optional
When scalars is specified, this is the perfered scalar type to
search for in the dataset. Must be either ``'point'`` or ``'cell'`` | [
"Contours",
"an",
"input",
"dataset",
"by",
"an",
"array",
".",
"isosurfaces",
"can",
"be",
"an",
"integer",
"specifying",
"the",
"number",
"of",
"isosurfaces",
"in",
"the",
"data",
"range",
"or",
"an",
"iterable",
"set",
"of",
"values",
"for",
"explicitly",... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L555-L619 |
236,526 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.texture_map_to_plane | def texture_map_to_plane(dataset, origin=None, point_u=None, point_v=None,
inplace=False, name='Texture Coordinates'):
"""Texture map this dataset to a user defined plane. This is often used
to define a plane to texture map an image to this dataset. The plane
defines the spatial reference and extent of that image.
Parameters
----------
origin : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM LEFT CORNER of the plane
point_u : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM RIGHT CORNER of the plane
point_v : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
TOP LEFT CORNER of the plane
inplace : bool, optional
If True, the new texture coordinates will be added to the dataset
inplace. If False (default), a new dataset is returned with the
textures coordinates
name : str, optional
The string name to give the new texture coordinates if applying
the filter inplace.
"""
alg = vtk.vtkTextureMapToPlane()
if origin is None or point_u is None or point_v is None:
alg.SetAutomaticPlaneGeneration(True)
else:
alg.SetOrigin(origin) # BOTTOM LEFT CORNER
alg.SetPoint1(point_u) # BOTTOM RIGHT CORNER
alg.SetPoint2(point_v) # TOP LEFT CORNER
alg.SetInputDataObject(dataset)
alg.Update()
output = _get_output(alg)
if not inplace:
return output
t_coords = output.GetPointData().GetTCoords()
t_coords.SetName(name)
otc = dataset.GetPointData().GetTCoords()
dataset.GetPointData().SetTCoords(t_coords)
dataset.GetPointData().AddArray(t_coords)
# CRITICAL:
dataset.GetPointData().AddArray(otc) # Add old ones back at the end
return | python | def texture_map_to_plane(dataset, origin=None, point_u=None, point_v=None,
inplace=False, name='Texture Coordinates'):
alg = vtk.vtkTextureMapToPlane()
if origin is None or point_u is None or point_v is None:
alg.SetAutomaticPlaneGeneration(True)
else:
alg.SetOrigin(origin) # BOTTOM LEFT CORNER
alg.SetPoint1(point_u) # BOTTOM RIGHT CORNER
alg.SetPoint2(point_v) # TOP LEFT CORNER
alg.SetInputDataObject(dataset)
alg.Update()
output = _get_output(alg)
if not inplace:
return output
t_coords = output.GetPointData().GetTCoords()
t_coords.SetName(name)
otc = dataset.GetPointData().GetTCoords()
dataset.GetPointData().SetTCoords(t_coords)
dataset.GetPointData().AddArray(t_coords)
# CRITICAL:
dataset.GetPointData().AddArray(otc) # Add old ones back at the end
return | [
"def",
"texture_map_to_plane",
"(",
"dataset",
",",
"origin",
"=",
"None",
",",
"point_u",
"=",
"None",
",",
"point_v",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"name",
"=",
"'Texture Coordinates'",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkTextureMapTo... | Texture map this dataset to a user defined plane. This is often used
to define a plane to texture map an image to this dataset. The plane
defines the spatial reference and extent of that image.
Parameters
----------
origin : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM LEFT CORNER of the plane
point_u : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
BOTTOM RIGHT CORNER of the plane
point_v : tuple(float)
Length 3 iterable of floats defining the XYZ coordinates of the
TOP LEFT CORNER of the plane
inplace : bool, optional
If True, the new texture coordinates will be added to the dataset
inplace. If False (default), a new dataset is returned with the
textures coordinates
name : str, optional
The string name to give the new texture coordinates if applying
the filter inplace. | [
"Texture",
"map",
"this",
"dataset",
"to",
"a",
"user",
"defined",
"plane",
".",
"This",
"is",
"often",
"used",
"to",
"define",
"a",
"plane",
"to",
"texture",
"map",
"an",
"image",
"to",
"this",
"dataset",
".",
"The",
"plane",
"defines",
"the",
"spatial"... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L622-L671 |
236,527 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.warp_by_scalar | def warp_by_scalar(dataset, scalars=None, scale_factor=1.0, normal=None,
inplace=False):
"""
Warp the dataset's points by a point data scalar array's values.
This modifies point coordinates by moving points along point normals by
the scalar amount times the scale factor.
Parameters
----------
scalars : str, optional
Name of scalars to warb by. Defaults to currently active scalars.
scale_factor : float, optional
A scalaing factor to increase the scaling effect
normal : np.array, list, tuple of length 3
User specified normal. If given, data normals will be ignored and
the given normal will be used to project the warp.
inplace : bool
If True, the points of the give dataset will be updated.
"""
if scalars is None:
field, scalars = dataset.active_scalar_info
arr, field = get_scalar(dataset, scalars, preference='point', info=True)
if field != vtki.POINT_DATA_FIELD:
raise AssertionError('Dataset can only by warped by a point data array.')
# Run the algorithm
alg = vtk.vtkWarpScalar()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
alg.SetScaleFactor(scale_factor)
if normal is not None:
alg.SetNormal(normal)
alg.SetUseNormal(True)
alg.Update()
output = _get_output(alg)
if inplace:
dataset.points = output.points
return
return output | python | def warp_by_scalar(dataset, scalars=None, scale_factor=1.0, normal=None,
inplace=False):
if scalars is None:
field, scalars = dataset.active_scalar_info
arr, field = get_scalar(dataset, scalars, preference='point', info=True)
if field != vtki.POINT_DATA_FIELD:
raise AssertionError('Dataset can only by warped by a point data array.')
# Run the algorithm
alg = vtk.vtkWarpScalar()
alg.SetInputDataObject(dataset)
alg.SetInputArrayToProcess(0, 0, 0, field, scalars) # args: (idx, port, connection, field, name)
alg.SetScaleFactor(scale_factor)
if normal is not None:
alg.SetNormal(normal)
alg.SetUseNormal(True)
alg.Update()
output = _get_output(alg)
if inplace:
dataset.points = output.points
return
return output | [
"def",
"warp_by_scalar",
"(",
"dataset",
",",
"scalars",
"=",
"None",
",",
"scale_factor",
"=",
"1.0",
",",
"normal",
"=",
"None",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"scalars",
"is",
"None",
":",
"field",
",",
"scalars",
"=",
"dataset",
".",... | Warp the dataset's points by a point data scalar array's values.
This modifies point coordinates by moving points along point normals by
the scalar amount times the scale factor.
Parameters
----------
scalars : str, optional
Name of scalars to warb by. Defaults to currently active scalars.
scale_factor : float, optional
A scalaing factor to increase the scaling effect
normal : np.array, list, tuple of length 3
User specified normal. If given, data normals will be ignored and
the given normal will be used to project the warp.
inplace : bool
If True, the points of the give dataset will be updated. | [
"Warp",
"the",
"dataset",
"s",
"points",
"by",
"a",
"point",
"data",
"scalar",
"array",
"s",
"values",
".",
"This",
"modifies",
"point",
"coordinates",
"by",
"moving",
"points",
"along",
"point",
"normals",
"by",
"the",
"scalar",
"amount",
"times",
"the",
... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L814-L854 |
236,528 | vtkiorg/vtki | vtki/filters.py | DataSetFilters.delaunay_3d | def delaunay_3d(dataset, alpha=0, tol=0.001, offset=2.5):
"""Constructs a 3D Delaunay triangulation of the mesh.
This helps smooth out a rugged mesh.
Parameters
----------
alpha : float, optional
Distance value to control output of this filter. For a non-zero
alpha value, only verts, edges, faces, or tetra contained within
the circumsphere (of radius alpha) will be output. Otherwise, only
tetrahedra will be output.
tol : float, optional
tolerance to control discarding of closely spaced points.
This tolerance is specified as a fraction of the diagonal length
of the bounding box of the points.
offset : float, optional
multiplier to control the size of the initial, bounding Delaunay
triangulation.
"""
alg = vtk.vtkDelaunay3D()
alg.SetInputData(dataset)
alg.SetAlpha(alpha)
alg.SetTolerance(tol)
alg.SetOffset(offset)
alg.Update()
return _get_output(alg) | python | def delaunay_3d(dataset, alpha=0, tol=0.001, offset=2.5):
alg = vtk.vtkDelaunay3D()
alg.SetInputData(dataset)
alg.SetAlpha(alpha)
alg.SetTolerance(tol)
alg.SetOffset(offset)
alg.Update()
return _get_output(alg) | [
"def",
"delaunay_3d",
"(",
"dataset",
",",
"alpha",
"=",
"0",
",",
"tol",
"=",
"0.001",
",",
"offset",
"=",
"2.5",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkDelaunay3D",
"(",
")",
"alg",
".",
"SetInputData",
"(",
"dataset",
")",
"alg",
".",
"SetAlpha",
... | Constructs a 3D Delaunay triangulation of the mesh.
This helps smooth out a rugged mesh.
Parameters
----------
alpha : float, optional
Distance value to control output of this filter. For a non-zero
alpha value, only verts, edges, faces, or tetra contained within
the circumsphere (of radius alpha) will be output. Otherwise, only
tetrahedra will be output.
tol : float, optional
tolerance to control discarding of closely spaced points.
This tolerance is specified as a fraction of the diagonal length
of the bounding box of the points.
offset : float, optional
multiplier to control the size of the initial, bounding Delaunay
triangulation. | [
"Constructs",
"a",
"3D",
"Delaunay",
"triangulation",
"of",
"the",
"mesh",
".",
"This",
"helps",
"smooth",
"out",
"a",
"rugged",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/filters.py#L914-L941 |
236,529 | vtkiorg/vtki | vtki/pointset.py | PolyData._load_file | def _load_file(self, filename):
"""
Load a surface mesh from a mesh file.
Mesh file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be loaded. File type is inferred from the
extension of the filename
Notes
-----
Binary files load much faster than ASCII.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not exist' % filename)
# Get extension
ext = vtki.get_ext(filename)
# Select reader
if ext == '.ply':
reader = vtk.vtkPLYReader()
elif ext == '.stl':
reader = vtk.vtkSTLReader()
elif ext == '.vtk':
reader = vtk.vtkPolyDataReader()
elif ext == '.vtp':
reader = vtk.vtkXMLPolyDataReader()
elif ext == '.obj':
reader = vtk.vtkOBJReader()
else:
raise TypeError('Filetype must be either "ply", "stl", "vtk", "vtp", or "obj".')
# Load file
reader.SetFileName(filename)
reader.Update()
self.ShallowCopy(reader.GetOutput())
# sanity check
if not np.any(self.points):
raise AssertionError('Empty or invalid file') | python | def _load_file(self, filename):
filename = os.path.abspath(os.path.expanduser(filename))
# test if file exists
if not os.path.isfile(filename):
raise Exception('File %s does not exist' % filename)
# Get extension
ext = vtki.get_ext(filename)
# Select reader
if ext == '.ply':
reader = vtk.vtkPLYReader()
elif ext == '.stl':
reader = vtk.vtkSTLReader()
elif ext == '.vtk':
reader = vtk.vtkPolyDataReader()
elif ext == '.vtp':
reader = vtk.vtkXMLPolyDataReader()
elif ext == '.obj':
reader = vtk.vtkOBJReader()
else:
raise TypeError('Filetype must be either "ply", "stl", "vtk", "vtp", or "obj".')
# Load file
reader.SetFileName(filename)
reader.Update()
self.ShallowCopy(reader.GetOutput())
# sanity check
if not np.any(self.points):
raise AssertionError('Empty or invalid file') | [
"def",
"_load_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# test if file exists",
"if",
"not",
"os",
".",
"path",
".",
"isfile... | Load a surface mesh from a mesh file.
Mesh file may be an ASCII or binary ply, stl, or vtk mesh file.
Parameters
----------
filename : str
Filename of mesh to be loaded. File type is inferred from the
extension of the filename
Notes
-----
Binary files load much faster than ASCII. | [
"Load",
"a",
"surface",
"mesh",
"from",
"a",
"mesh",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L110-L156 |
236,530 | vtkiorg/vtki | vtki/pointset.py | PolyData.faces | def faces(self, faces):
""" set faces without copying """
if faces.dtype != vtki.ID_TYPE:
faces = faces.astype(vtki.ID_TYPE)
# get number of faces
if faces.ndim == 1:
log.debug('efficiency warning')
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(nfaces, numpy_to_vtkIdTypeArray(faces, deep=False))
if faces.ndim > 1 and faces.shape[1] == 2:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
self._face_ref = faces
self.Modified() | python | def faces(self, faces):
if faces.dtype != vtki.ID_TYPE:
faces = faces.astype(vtki.ID_TYPE)
# get number of faces
if faces.ndim == 1:
log.debug('efficiency warning')
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(nfaces, numpy_to_vtkIdTypeArray(faces, deep=False))
if faces.ndim > 1 and faces.shape[1] == 2:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
self._face_ref = faces
self.Modified() | [
"def",
"faces",
"(",
"self",
",",
"faces",
")",
":",
"if",
"faces",
".",
"dtype",
"!=",
"vtki",
".",
"ID_TYPE",
":",
"faces",
"=",
"faces",
".",
"astype",
"(",
"vtki",
".",
"ID_TYPE",
")",
"# get number of faces",
"if",
"faces",
".",
"ndim",
"==",
"1... | set faces without copying | [
"set",
"faces",
"without",
"copying"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L185-L208 |
236,531 | vtkiorg/vtki | vtki/pointset.py | PolyData._from_arrays | def _from_arrays(self, vertices, faces, deep=True, verts=False):
"""
Set polygons and points from numpy arrays
Parameters
----------
vertices : np.ndarray of dtype=np.float32 or np.float64
Vertex array. 3D points.
faces : np.ndarray of dtype=np.int64
Face index array. Faces can contain any number of points.
Examples
--------
>>> import numpy as np
>>> import vtki
>>> vertices = np.array([[0, 0, 0],
... [1, 0, 0],
... [1, 1, 0],
... [0, 1, 0],
... [0.5, 0.5, 1]])
>>> faces = np.hstack([[4, 0, 1, 2, 3],
... [3, 0, 1, 4],
... [3, 1, 2, 4]]) # one square and two triangles
>>> surf = vtki.PolyData(vertices, faces)
"""
if deep or verts:
vtkpoints = vtk.vtkPoints()
vtkpoints.SetData(numpy_to_vtk(vertices, deep=deep))
self.SetPoints(vtkpoints)
# Convert to a vtk array
vtkcells = vtk.vtkCellArray()
if faces.dtype != vtki.ID_TYPE:
faces = faces.astype(vtki.ID_TYPE)
# get number of faces
if faces.ndim == 1:
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
idarr = numpy_to_vtkIdTypeArray(faces.ravel(), deep=deep)
vtkcells.SetCells(nfaces, idarr)
if (faces.ndim > 1 and faces.shape[1] == 2) or verts:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
else:
self.points = vertices
self.faces = faces | python | def _from_arrays(self, vertices, faces, deep=True, verts=False):
if deep or verts:
vtkpoints = vtk.vtkPoints()
vtkpoints.SetData(numpy_to_vtk(vertices, deep=deep))
self.SetPoints(vtkpoints)
# Convert to a vtk array
vtkcells = vtk.vtkCellArray()
if faces.dtype != vtki.ID_TYPE:
faces = faces.astype(vtki.ID_TYPE)
# get number of faces
if faces.ndim == 1:
c = 0
nfaces = 0
while c < faces.size:
c += faces[c] + 1
nfaces += 1
else:
nfaces = faces.shape[0]
idarr = numpy_to_vtkIdTypeArray(faces.ravel(), deep=deep)
vtkcells.SetCells(nfaces, idarr)
if (faces.ndim > 1 and faces.shape[1] == 2) or verts:
self.SetVerts(vtkcells)
else:
self.SetPolys(vtkcells)
else:
self.points = vertices
self.faces = faces | [
"def",
"_from_arrays",
"(",
"self",
",",
"vertices",
",",
"faces",
",",
"deep",
"=",
"True",
",",
"verts",
"=",
"False",
")",
":",
"if",
"deep",
"or",
"verts",
":",
"vtkpoints",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"vtkpoints",
".",
"SetData",
"("... | Set polygons and points from numpy arrays
Parameters
----------
vertices : np.ndarray of dtype=np.float32 or np.float64
Vertex array. 3D points.
faces : np.ndarray of dtype=np.int64
Face index array. Faces can contain any number of points.
Examples
--------
>>> import numpy as np
>>> import vtki
>>> vertices = np.array([[0, 0, 0],
... [1, 0, 0],
... [1, 1, 0],
... [0, 1, 0],
... [0.5, 0.5, 1]])
>>> faces = np.hstack([[4, 0, 1, 2, 3],
... [3, 0, 1, 4],
... [3, 1, 2, 4]]) # one square and two triangles
>>> surf = vtki.PolyData(vertices, faces) | [
"Set",
"polygons",
"and",
"points",
"from",
"numpy",
"arrays"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L216-L271 |
236,532 | vtkiorg/vtki | vtki/pointset.py | PolyData.edge_mask | def edge_mask(self, angle):
"""
Returns a mask of the points of a surface mesh that have a surface
angle greater than angle
Parameters
----------
angle : float
Angle to consider an edge.
"""
self.point_arrays['point_ind'] = np.arange(self.n_points)
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.FeatureEdgesOn()
featureEdges.BoundaryEdgesOff()
featureEdges.NonManifoldEdgesOff()
featureEdges.ManifoldEdgesOff()
featureEdges.SetFeatureAngle(angle)
featureEdges.Update()
edges = _get_output(featureEdges)
orig_id = vtki.point_scalar(edges, 'point_ind')
return np.in1d(self.point_arrays['point_ind'], orig_id,
assume_unique=True) | python | def edge_mask(self, angle):
self.point_arrays['point_ind'] = np.arange(self.n_points)
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.FeatureEdgesOn()
featureEdges.BoundaryEdgesOff()
featureEdges.NonManifoldEdgesOff()
featureEdges.ManifoldEdgesOff()
featureEdges.SetFeatureAngle(angle)
featureEdges.Update()
edges = _get_output(featureEdges)
orig_id = vtki.point_scalar(edges, 'point_ind')
return np.in1d(self.point_arrays['point_ind'], orig_id,
assume_unique=True) | [
"def",
"edge_mask",
"(",
"self",
",",
"angle",
")",
":",
"self",
".",
"point_arrays",
"[",
"'point_ind'",
"]",
"=",
"np",
".",
"arange",
"(",
"self",
".",
"n_points",
")",
"featureEdges",
"=",
"vtk",
".",
"vtkFeatureEdges",
"(",
")",
"featureEdges",
".",... | Returns a mask of the points of a surface mesh that have a surface
angle greater than angle
Parameters
----------
angle : float
Angle to consider an edge. | [
"Returns",
"a",
"mask",
"of",
"the",
"points",
"of",
"a",
"surface",
"mesh",
"that",
"have",
"a",
"surface",
"angle",
"greater",
"than",
"angle"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L273-L297 |
236,533 | vtkiorg/vtki | vtki/pointset.py | PolyData.boolean_cut | def boolean_cut(self, cut, tolerance=1E-5, inplace=False):
"""
Performs a Boolean cut using another mesh.
Parameters
----------
cut : vtki.PolyData
Mesh making the cut
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
The cut mesh when inplace=False
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToIntersection()
# bfilter.SetOperationToDifference()
bfilter.SetInputData(1, cut)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.SetTolerance(tolerance)
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def boolean_cut(self, cut, tolerance=1E-5, inplace=False):
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToIntersection()
# bfilter.SetOperationToDifference()
bfilter.SetInputData(1, cut)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.SetTolerance(tolerance)
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"boolean_cut",
"(",
"self",
",",
"cut",
",",
"tolerance",
"=",
"1E-5",
",",
"inplace",
"=",
"False",
")",
":",
"bfilter",
"=",
"vtk",
".",
"vtkBooleanOperationPolyDataFilter",
"(",
")",
"bfilter",
".",
"SetOperationToIntersection",
"(",
")",
"# bfilter.... | Performs a Boolean cut using another mesh.
Parameters
----------
cut : vtki.PolyData
Mesh making the cut
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
The cut mesh when inplace=False | [
"Performs",
"a",
"Boolean",
"cut",
"using",
"another",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L313-L345 |
236,534 | vtkiorg/vtki | vtki/pointset.py | PolyData.boolean_add | def boolean_add(self, mesh, inplace=False):
"""
Add a mesh to the current mesh. Does not attempt to "join"
the meshes.
Parameters
----------
mesh : vtki.PolyData
The mesh to add.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
joinedmesh : vtki.PolyData
Initial mesh and the new mesh when inplace=False.
"""
vtkappend = vtk.vtkAppendPolyData()
vtkappend.AddInputData(self)
vtkappend.AddInputData(mesh)
vtkappend.Update()
mesh = _get_output(vtkappend)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def boolean_add(self, mesh, inplace=False):
vtkappend = vtk.vtkAppendPolyData()
vtkappend.AddInputData(self)
vtkappend.AddInputData(mesh)
vtkappend.Update()
mesh = _get_output(vtkappend)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"boolean_add",
"(",
"self",
",",
"mesh",
",",
"inplace",
"=",
"False",
")",
":",
"vtkappend",
"=",
"vtk",
".",
"vtkAppendPolyData",
"(",
")",
"vtkappend",
".",
"AddInputData",
"(",
"self",
")",
"vtkappend",
".",
"AddInputData",
"(",
"mesh",
")",
"... | Add a mesh to the current mesh. Does not attempt to "join"
the meshes.
Parameters
----------
mesh : vtki.PolyData
The mesh to add.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
joinedmesh : vtki.PolyData
Initial mesh and the new mesh when inplace=False. | [
"Add",
"a",
"mesh",
"to",
"the",
"current",
"mesh",
".",
"Does",
"not",
"attempt",
"to",
"join",
"the",
"meshes",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L351-L379 |
236,535 | vtkiorg/vtki | vtki/pointset.py | PolyData.boolean_union | def boolean_union(self, mesh, inplace=False):
"""
Combines two meshes and attempts to create a manifold mesh.
Parameters
----------
mesh : vtki.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : vtki.PolyData
The union mesh when inplace=False.
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToUnion()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def boolean_union(self, mesh, inplace=False):
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToUnion()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"boolean_union",
"(",
"self",
",",
"mesh",
",",
"inplace",
"=",
"False",
")",
":",
"bfilter",
"=",
"vtk",
".",
"vtkBooleanOperationPolyDataFilter",
"(",
")",
"bfilter",
".",
"SetOperationToUnion",
"(",
")",
"bfilter",
".",
"SetInputData",
"(",
"1",
",... | Combines two meshes and attempts to create a manifold mesh.
Parameters
----------
mesh : vtki.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : vtki.PolyData
The union mesh when inplace=False. | [
"Combines",
"two",
"meshes",
"and",
"attempts",
"to",
"create",
"a",
"manifold",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L381-L410 |
236,536 | vtkiorg/vtki | vtki/pointset.py | PolyData.boolean_difference | def boolean_difference(self, mesh, inplace=False):
"""
Combines two meshes and retains only the volume in common
between the meshes.
Parameters
----------
mesh : vtki.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : vtki.PolyData
The union mesh when inplace=False.
"""
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToDifference()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def boolean_difference(self, mesh, inplace=False):
bfilter = vtk.vtkBooleanOperationPolyDataFilter()
bfilter.SetOperationToDifference()
bfilter.SetInputData(1, mesh)
bfilter.SetInputData(0, self)
bfilter.ReorientDifferenceCellsOff()
bfilter.Update()
mesh = _get_output(bfilter)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"boolean_difference",
"(",
"self",
",",
"mesh",
",",
"inplace",
"=",
"False",
")",
":",
"bfilter",
"=",
"vtk",
".",
"vtkBooleanOperationPolyDataFilter",
"(",
")",
"bfilter",
".",
"SetOperationToDifference",
"(",
")",
"bfilter",
".",
"SetInputData",
"(",
... | Combines two meshes and retains only the volume in common
between the meshes.
Parameters
----------
mesh : vtki.PolyData
The mesh to perform a union against.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
union : vtki.PolyData
The union mesh when inplace=False. | [
"Combines",
"two",
"meshes",
"and",
"retains",
"only",
"the",
"volume",
"in",
"common",
"between",
"the",
"meshes",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L412-L442 |
236,537 | vtkiorg/vtki | vtki/pointset.py | PolyData.curvature | def curvature(self, curv_type='mean'):
"""
Returns the pointwise curvature of a mesh
Parameters
----------
mesh : vtk.polydata
vtk polydata mesh
curvature string, optional
One of the following strings
Mean
Gaussian
Maximum
Minimum
Returns
-------
curvature : np.ndarray
Curvature values
"""
curv_type = curv_type.lower()
# Create curve filter and compute curvature
curvefilter = vtk.vtkCurvatures()
curvefilter.SetInputData(self)
if curv_type == 'mean':
curvefilter.SetCurvatureTypeToMean()
elif curv_type == 'gaussian':
curvefilter.SetCurvatureTypeToGaussian()
elif curv_type == 'maximum':
curvefilter.SetCurvatureTypeToMaximum()
elif curv_type == 'minimum':
curvefilter.SetCurvatureTypeToMinimum()
else:
raise Exception('Curv_Type must be either "Mean", ' +
'"Gaussian", "Maximum", or "Minimum"')
curvefilter.Update()
# Compute and return curvature
curv = _get_output(curvefilter)
return vtk_to_numpy(curv.GetPointData().GetScalars()) | python | def curvature(self, curv_type='mean'):
curv_type = curv_type.lower()
# Create curve filter and compute curvature
curvefilter = vtk.vtkCurvatures()
curvefilter.SetInputData(self)
if curv_type == 'mean':
curvefilter.SetCurvatureTypeToMean()
elif curv_type == 'gaussian':
curvefilter.SetCurvatureTypeToGaussian()
elif curv_type == 'maximum':
curvefilter.SetCurvatureTypeToMaximum()
elif curv_type == 'minimum':
curvefilter.SetCurvatureTypeToMinimum()
else:
raise Exception('Curv_Type must be either "Mean", ' +
'"Gaussian", "Maximum", or "Minimum"')
curvefilter.Update()
# Compute and return curvature
curv = _get_output(curvefilter)
return vtk_to_numpy(curv.GetPointData().GetScalars()) | [
"def",
"curvature",
"(",
"self",
",",
"curv_type",
"=",
"'mean'",
")",
":",
"curv_type",
"=",
"curv_type",
".",
"lower",
"(",
")",
"# Create curve filter and compute curvature",
"curvefilter",
"=",
"vtk",
".",
"vtkCurvatures",
"(",
")",
"curvefilter",
".",
"SetI... | Returns the pointwise curvature of a mesh
Parameters
----------
mesh : vtk.polydata
vtk polydata mesh
curvature string, optional
One of the following strings
Mean
Gaussian
Maximum
Minimum
Returns
-------
curvature : np.ndarray
Curvature values | [
"Returns",
"the",
"pointwise",
"curvature",
"of",
"a",
"mesh"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L444-L486 |
236,538 | vtkiorg/vtki | vtki/pointset.py | PolyData.smooth | def smooth(self, n_iter=20, convergence=0.0, edge_angle=15, feature_angle=45,
boundary_smoothing=True, feature_smoothing=False, inplace=False):
"""Adjust point coordinates using Laplacian smoothing.
The effect is to "relax" the mesh, making the cells better shaped and
the vertices more evenly distributed.
Parameters
----------
n_iter : int
Number of iterations for Laplacian smoothing,
convergence : float, optional
Convergence criterion for the iteration process. Smaller numbers
result in more smoothing iterations. Range from (0 to 1).
edge_angle : float, optional
Edge angle to control smoothing along edges (either interior or boundary).
feature_angle : float, optional
Feature angle for sharp edge identification.
boundary_smoothing : bool, optional
Boolean flag to control smoothing of boundary edges.
feature_smoothing : bool, optional
Boolean flag to control smoothing of feature edges.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Decimated mesh. None when inplace=True.
"""
alg = vtk.vtkSmoothPolyDataFilter()
alg.SetInputData(self)
alg.SetNumberOfIterations(n_iter)
alg.SetConvergence(convergence)
alg.SetFeatureEdgeSmoothing(feature_smoothing)
alg.SetFeatureAngle(feature_angle)
alg.SetEdgeAngle(edge_angle)
alg.SetBoundarySmoothing(boundary_smoothing)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def smooth(self, n_iter=20, convergence=0.0, edge_angle=15, feature_angle=45,
boundary_smoothing=True, feature_smoothing=False, inplace=False):
alg = vtk.vtkSmoothPolyDataFilter()
alg.SetInputData(self)
alg.SetNumberOfIterations(n_iter)
alg.SetConvergence(convergence)
alg.SetFeatureEdgeSmoothing(feature_smoothing)
alg.SetFeatureAngle(feature_angle)
alg.SetEdgeAngle(edge_angle)
alg.SetBoundarySmoothing(boundary_smoothing)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"smooth",
"(",
"self",
",",
"n_iter",
"=",
"20",
",",
"convergence",
"=",
"0.0",
",",
"edge_angle",
"=",
"15",
",",
"feature_angle",
"=",
"45",
",",
"boundary_smoothing",
"=",
"True",
",",
"feature_smoothing",
"=",
"False",
",",
"inplace",
"=",
"F... | Adjust point coordinates using Laplacian smoothing.
The effect is to "relax" the mesh, making the cells better shaped and
the vertices more evenly distributed.
Parameters
----------
n_iter : int
Number of iterations for Laplacian smoothing,
convergence : float, optional
Convergence criterion for the iteration process. Smaller numbers
result in more smoothing iterations. Range from (0 to 1).
edge_angle : float, optional
Edge angle to control smoothing along edges (either interior or boundary).
feature_angle : float, optional
Feature angle for sharp edge identification.
boundary_smoothing : bool, optional
Boolean flag to control smoothing of boundary edges.
feature_smoothing : bool, optional
Boolean flag to control smoothing of feature edges.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Decimated mesh. None when inplace=True. | [
"Adjust",
"point",
"coordinates",
"using",
"Laplacian",
"smoothing",
".",
"The",
"effect",
"is",
"to",
"relax",
"the",
"mesh",
"making",
"the",
"cells",
"better",
"shaped",
"and",
"the",
"vertices",
"more",
"evenly",
"distributed",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L591-L641 |
236,539 | vtkiorg/vtki | vtki/pointset.py | PolyData.decimate_pro | def decimate_pro(self, reduction, feature_angle=45.0, split_angle=75.0, splitting=True,
pre_split_mesh=False, preserve_topology=False, inplace=False):
"""Reduce the number of triangles in a triangular mesh, forming a good
approximation to the original geometry. Based on the algorithm originally
described in "Decimation of Triangle Meshes", Proc Siggraph `92.
Parameters
----------
reduction : float
Reduction factor. A value of 0.9 will leave 10 % of the original number
of vertices.
feature_angle : float, optional
Angle used to define what an edge is (i.e., if the surface normal between
two adjacent triangles is >= feature_angle, an edge exists).
split_angle : float, optional
Angle used to control the splitting of the mesh. A split line exists
when the surface normals between two edge connected triangles are >= split_angle.
splitting : bool, optional
Controls the splitting of the mesh at corners, along edges, at non-manifold
points, or anywhere else a split is required. Turning splitting off
will better preserve the original topology of the mesh, but may not
necessarily give the exact requested decimation.
pre_split_mesh : bool, optional
Separates the mesh into semi-planar patches, which are disconnected
from each other. This can give superior results in some cases. If pre_split_mesh
is set to True, the mesh is split with the specified split_angle. Otherwise
mesh splitting is deferred as long as possible.
preserve_topology : bool, optional
Controls topology preservation. If on, mesh splitting and hole elimination
will not occur. This may limit the maximum reduction that may be achieved.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Decimated mesh. None when inplace=True.
"""
alg = vtk.vtkDecimatePro()
alg.SetInputData(self)
alg.SetTargetReduction(reduction)
alg.SetPreserveTopology(preserve_topology)
alg.SetFeatureAngle(feature_angle)
alg.SetSplitting(splitting)
alg.SetSplitAngle(split_angle)
alg.SetPreSplitMesh(pre_split_mesh)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def decimate_pro(self, reduction, feature_angle=45.0, split_angle=75.0, splitting=True,
pre_split_mesh=False, preserve_topology=False, inplace=False):
alg = vtk.vtkDecimatePro()
alg.SetInputData(self)
alg.SetTargetReduction(reduction)
alg.SetPreserveTopology(preserve_topology)
alg.SetFeatureAngle(feature_angle)
alg.SetSplitting(splitting)
alg.SetSplitAngle(split_angle)
alg.SetPreSplitMesh(pre_split_mesh)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"decimate_pro",
"(",
"self",
",",
"reduction",
",",
"feature_angle",
"=",
"45.0",
",",
"split_angle",
"=",
"75.0",
",",
"splitting",
"=",
"True",
",",
"pre_split_mesh",
"=",
"False",
",",
"preserve_topology",
"=",
"False",
",",
"inplace",
"=",
"False"... | Reduce the number of triangles in a triangular mesh, forming a good
approximation to the original geometry. Based on the algorithm originally
described in "Decimation of Triangle Meshes", Proc Siggraph `92.
Parameters
----------
reduction : float
Reduction factor. A value of 0.9 will leave 10 % of the original number
of vertices.
feature_angle : float, optional
Angle used to define what an edge is (i.e., if the surface normal between
two adjacent triangles is >= feature_angle, an edge exists).
split_angle : float, optional
Angle used to control the splitting of the mesh. A split line exists
when the surface normals between two edge connected triangles are >= split_angle.
splitting : bool, optional
Controls the splitting of the mesh at corners, along edges, at non-manifold
points, or anywhere else a split is required. Turning splitting off
will better preserve the original topology of the mesh, but may not
necessarily give the exact requested decimation.
pre_split_mesh : bool, optional
Separates the mesh into semi-planar patches, which are disconnected
from each other. This can give superior results in some cases. If pre_split_mesh
is set to True, the mesh is split with the specified split_angle. Otherwise
mesh splitting is deferred as long as possible.
preserve_topology : bool, optional
Controls topology preservation. If on, mesh splitting and hole elimination
will not occur. This may limit the maximum reduction that may be achieved.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Decimated mesh. None when inplace=True. | [
"Reduce",
"the",
"number",
"of",
"triangles",
"in",
"a",
"triangular",
"mesh",
"forming",
"a",
"good",
"approximation",
"to",
"the",
"original",
"geometry",
".",
"Based",
"on",
"the",
"algorithm",
"originally",
"described",
"in",
"Decimation",
"of",
"Triangle",
... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L643-L703 |
236,540 | vtkiorg/vtki | vtki/pointset.py | PolyData.tube | def tube(self, radius=None, scalars=None, capping=True, n_sides=20,
radius_factor=10, preference='point', inplace=False):
"""Generate a tube around each input line. The radius of the tube can be
set to linearly vary with a scalar value.
Parameters
----------
radius : float
Minimum tube radius (minimum because the tube radius may vary).
scalars : str, optional
Scalar array by which the radius varies
capping : bool
Turn on/off whether to cap the ends with polygons. Default True.
n_sides : int
Set the number of sides for the tube. Minimum of 3.
radius_factor : float
Maximum tube radius in terms of a multiple of the minimum radius.
preference : str
The field preference when searching for the scalar array by name
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Tube-filtered mesh. None when inplace=True.
"""
if n_sides < 3:
n_sides = 3
tube = vtk.vtkTubeFilter()
tube.SetInputDataObject(self)
# User Defined Parameters
tube.SetCapping(capping)
if radius is not None:
tube.SetRadius(radius)
tube.SetNumberOfSides(n_sides)
tube.SetRadiusFactor(radius_factor)
# Check if scalar array given
if scalars is not None:
if not isinstance(scalars, str):
raise TypeError('Scalar array must be given as a string name')
_, field = self.get_scalar(scalars, preference=preference, info=True)
# args: (idx, port, connection, field, name)
tube.SetInputArrayToProcess(0, 0, 0, field, scalars)
tube.SetVaryRadiusToVaryRadiusByScalar()
# Apply the filter
tube.Update()
mesh = _get_output(tube)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def tube(self, radius=None, scalars=None, capping=True, n_sides=20,
radius_factor=10, preference='point', inplace=False):
if n_sides < 3:
n_sides = 3
tube = vtk.vtkTubeFilter()
tube.SetInputDataObject(self)
# User Defined Parameters
tube.SetCapping(capping)
if radius is not None:
tube.SetRadius(radius)
tube.SetNumberOfSides(n_sides)
tube.SetRadiusFactor(radius_factor)
# Check if scalar array given
if scalars is not None:
if not isinstance(scalars, str):
raise TypeError('Scalar array must be given as a string name')
_, field = self.get_scalar(scalars, preference=preference, info=True)
# args: (idx, port, connection, field, name)
tube.SetInputArrayToProcess(0, 0, 0, field, scalars)
tube.SetVaryRadiusToVaryRadiusByScalar()
# Apply the filter
tube.Update()
mesh = _get_output(tube)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"tube",
"(",
"self",
",",
"radius",
"=",
"None",
",",
"scalars",
"=",
"None",
",",
"capping",
"=",
"True",
",",
"n_sides",
"=",
"20",
",",
"radius_factor",
"=",
"10",
",",
"preference",
"=",
"'point'",
",",
"inplace",
"=",
"False",
")",
":",
... | Generate a tube around each input line. The radius of the tube can be
set to linearly vary with a scalar value.
Parameters
----------
radius : float
Minimum tube radius (minimum because the tube radius may vary).
scalars : str, optional
Scalar array by which the radius varies
capping : bool
Turn on/off whether to cap the ends with polygons. Default True.
n_sides : int
Set the number of sides for the tube. Minimum of 3.
radius_factor : float
Maximum tube radius in terms of a multiple of the minimum radius.
preference : str
The field preference when searching for the scalar array by name
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Tube-filtered mesh. None when inplace=True. | [
"Generate",
"a",
"tube",
"around",
"each",
"input",
"line",
".",
"The",
"radius",
"of",
"the",
"tube",
"can",
"be",
"set",
"to",
"linearly",
"vary",
"with",
"a",
"scalar",
"value",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L705-L764 |
236,541 | vtkiorg/vtki | vtki/pointset.py | PolyData.subdivide | def subdivide(self, nsub, subfilter='linear', inplace=False):
"""
Increase the number of triangles in a single, connected triangular
mesh.
Uses one of the following vtk subdivision filters to subdivide a mesh.
vtkButterflySubdivisionFilter
vtkLoopSubdivisionFilter
vtkLinearSubdivisionFilter
Linear subdivision results in the fastest mesh subdivision, but it
does not smooth mesh edges, but rather splits each triangle into 4
smaller triangles.
Butterfly and loop subdivision perform smoothing when dividing, and may
introduce artifacts into the mesh when dividing.
Subdivision filter appears to fail for multiple part meshes. Should
be one single mesh.
Parameters
----------
nsub : int
Number of subdivisions. Each subdivision creates 4 new triangles,
so the number of resulting triangles is nface*4**nsub where nface
is the current number of faces.
subfilter : string, optional
Can be one of the following: 'butterfly', 'loop', 'linear'
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : Polydata object
vtki polydata object. None when inplace=True
Examples
--------
>>> from vtki import examples
>>> import vtki
>>> mesh = vtki.PolyData(examples.planefile)
>>> submesh = mesh.subdivide(1, 'loop') # doctest:+SKIP
alternatively, update mesh in-place
>>> mesh.subdivide(1, 'loop', inplace=True) # doctest:+SKIP
"""
subfilter = subfilter.lower()
if subfilter == 'linear':
sfilter = vtk.vtkLinearSubdivisionFilter()
elif subfilter == 'butterfly':
sfilter = vtk.vtkButterflySubdivisionFilter()
elif subfilter == 'loop':
sfilter = vtk.vtkLoopSubdivisionFilter()
else:
raise Exception("Subdivision filter must be one of the following: " +
"'butterfly', 'loop', or 'linear'")
# Subdivide
sfilter.SetNumberOfSubdivisions(nsub)
sfilter.SetInputData(self)
sfilter.Update()
submesh = _get_output(sfilter)
if inplace:
self.overwrite(submesh)
else:
return submesh | python | def subdivide(self, nsub, subfilter='linear', inplace=False):
subfilter = subfilter.lower()
if subfilter == 'linear':
sfilter = vtk.vtkLinearSubdivisionFilter()
elif subfilter == 'butterfly':
sfilter = vtk.vtkButterflySubdivisionFilter()
elif subfilter == 'loop':
sfilter = vtk.vtkLoopSubdivisionFilter()
else:
raise Exception("Subdivision filter must be one of the following: " +
"'butterfly', 'loop', or 'linear'")
# Subdivide
sfilter.SetNumberOfSubdivisions(nsub)
sfilter.SetInputData(self)
sfilter.Update()
submesh = _get_output(sfilter)
if inplace:
self.overwrite(submesh)
else:
return submesh | [
"def",
"subdivide",
"(",
"self",
",",
"nsub",
",",
"subfilter",
"=",
"'linear'",
",",
"inplace",
"=",
"False",
")",
":",
"subfilter",
"=",
"subfilter",
".",
"lower",
"(",
")",
"if",
"subfilter",
"==",
"'linear'",
":",
"sfilter",
"=",
"vtk",
".",
"vtkLi... | Increase the number of triangles in a single, connected triangular
mesh.
Uses one of the following vtk subdivision filters to subdivide a mesh.
vtkButterflySubdivisionFilter
vtkLoopSubdivisionFilter
vtkLinearSubdivisionFilter
Linear subdivision results in the fastest mesh subdivision, but it
does not smooth mesh edges, but rather splits each triangle into 4
smaller triangles.
Butterfly and loop subdivision perform smoothing when dividing, and may
introduce artifacts into the mesh when dividing.
Subdivision filter appears to fail for multiple part meshes. Should
be one single mesh.
Parameters
----------
nsub : int
Number of subdivisions. Each subdivision creates 4 new triangles,
so the number of resulting triangles is nface*4**nsub where nface
is the current number of faces.
subfilter : string, optional
Can be one of the following: 'butterfly', 'loop', 'linear'
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : Polydata object
vtki polydata object. None when inplace=True
Examples
--------
>>> from vtki import examples
>>> import vtki
>>> mesh = vtki.PolyData(examples.planefile)
>>> submesh = mesh.subdivide(1, 'loop') # doctest:+SKIP
alternatively, update mesh in-place
>>> mesh.subdivide(1, 'loop', inplace=True) # doctest:+SKIP | [
"Increase",
"the",
"number",
"of",
"triangles",
"in",
"a",
"single",
"connected",
"triangular",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L766-L835 |
236,542 | vtkiorg/vtki | vtki/pointset.py | PolyData.extract_edges | def extract_edges(self, feature_angle=30, boundary_edges=True,
non_manifold_edges=True, feature_edges=True,
manifold_edges=True, inplace=False):
"""
Extracts edges from a surface. From vtk documentation, the edges are
one of the following
1) boundary (used by one polygon) or a line cell
2) non-manifold (used by three or more polygons)
3) feature edges (edges used by two triangles and whose
dihedral angle > feature_angle)
4) manifold edges (edges used by exactly two polygons).
Parameters
----------
feature_angle : float, optional
Defaults to 30 degrees.
boundary_edges : bool, optional
Defaults to True
non_manifold_edges : bool, optional
Defaults to True
feature_edges : bool, optional
Defaults to True
manifold_edges : bool, optional
Defaults to True
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
edges : vtki.vtkPolyData
Extracted edges. None if inplace=True.
"""
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.SetFeatureAngle(feature_angle)
featureEdges.SetManifoldEdges(manifold_edges)
featureEdges.SetNonManifoldEdges(non_manifold_edges)
featureEdges.SetBoundaryEdges(boundary_edges)
featureEdges.SetFeatureEdges(feature_edges)
featureEdges.SetColoring(False)
featureEdges.Update()
mesh = _get_output(featureEdges)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def extract_edges(self, feature_angle=30, boundary_edges=True,
non_manifold_edges=True, feature_edges=True,
manifold_edges=True, inplace=False):
featureEdges = vtk.vtkFeatureEdges()
featureEdges.SetInputData(self)
featureEdges.SetFeatureAngle(feature_angle)
featureEdges.SetManifoldEdges(manifold_edges)
featureEdges.SetNonManifoldEdges(non_manifold_edges)
featureEdges.SetBoundaryEdges(boundary_edges)
featureEdges.SetFeatureEdges(feature_edges)
featureEdges.SetColoring(False)
featureEdges.Update()
mesh = _get_output(featureEdges)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"extract_edges",
"(",
"self",
",",
"feature_angle",
"=",
"30",
",",
"boundary_edges",
"=",
"True",
",",
"non_manifold_edges",
"=",
"True",
",",
"feature_edges",
"=",
"True",
",",
"manifold_edges",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
... | Extracts edges from a surface. From vtk documentation, the edges are
one of the following
1) boundary (used by one polygon) or a line cell
2) non-manifold (used by three or more polygons)
3) feature edges (edges used by two triangles and whose
dihedral angle > feature_angle)
4) manifold edges (edges used by exactly two polygons).
Parameters
----------
feature_angle : float, optional
Defaults to 30 degrees.
boundary_edges : bool, optional
Defaults to True
non_manifold_edges : bool, optional
Defaults to True
feature_edges : bool, optional
Defaults to True
manifold_edges : bool, optional
Defaults to True
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
edges : vtki.vtkPolyData
Extracted edges. None if inplace=True. | [
"Extracts",
"edges",
"from",
"a",
"surface",
".",
"From",
"vtk",
"documentation",
"the",
"edges",
"are",
"one",
"of",
"the",
"following"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L837-L890 |
236,543 | vtkiorg/vtki | vtki/pointset.py | PolyData.decimate | def decimate(self, target_reduction, volume_preservation=False,
attribute_error=False, scalars=True, vectors=True,
normals=False, tcoords=True, tensors=True, scalars_weight=0.1,
vectors_weight=0.1, normals_weight=0.1, tcoords_weight=0.1,
tensors_weight=0.1, inplace=False):
"""
Reduces the number of triangles in a triangular mesh using
vtkQuadricDecimation.
Parameters
----------
mesh : vtk.PolyData
Mesh to decimate
target_reduction : float
Fraction of the original mesh to remove.
TargetReduction is set to 0.9, this filter will try to reduce
the data set to 10% of its original size and will remove 90%
of the input triangles.
volume_preservation : bool, optional
Decide whether to activate volume preservation which greatly reduces
errors in triangle normal direction. If off, volume preservation is
disabled and if AttributeErrorMetric is active, these errors can be
large. Defaults to False.
attribute_error : bool, optional
Decide whether to include data attributes in the error metric. If
off, then only geometric error is used to control the decimation.
Defaults to False.
scalars : bool, optional
If attribute errors are to be included in the metric (i.e.,
AttributeErrorMetric is on), then the following flags control which
attributes are to be included in the error calculation. Defaults to
True.
vectors : bool, optional
See scalars parameter. Defaults to True.
normals : bool, optional
See scalars parameter. Defaults to False.
tcoords : bool, optional
See scalars parameter. Defaults to True.
tensors : bool, optional
See scalars parameter. Defaults to True.
scalars_weight : float, optional
The scaling weight contribution of the scalar attribute. These
values are used to weight the contribution of the attributes towards
the error metric. Defaults to 0.1.
vectors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
normals_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tcoords_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tensors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
outmesh : vtki.PolyData
Decimated mesh. None when inplace=True.
"""
# create decimation filter
decimate = vtk.vtkQuadricDecimation() # vtkDecimatePro as well
decimate.SetVolumePreservation(volume_preservation)
decimate.SetAttributeErrorMetric(attribute_error)
decimate.SetScalarsAttribute(scalars)
decimate.SetVectorsAttribute(vectors)
decimate.SetNormalsAttribute(normals)
decimate.SetTCoordsAttribute(tcoords)
decimate.SetTensorsAttribute(tensors)
decimate.SetScalarsWeight(scalars_weight)
decimate.SetVectorsWeight(vectors_weight)
decimate.SetNormalsWeight(normals_weight)
decimate.SetTCoordsWeight(tcoords_weight)
decimate.SetTensorsWeight(tensors_weight)
decimate.SetTargetReduction(target_reduction)
decimate.SetInputData(self)
decimate.Update()
mesh = _get_output(decimate)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def decimate(self, target_reduction, volume_preservation=False,
attribute_error=False, scalars=True, vectors=True,
normals=False, tcoords=True, tensors=True, scalars_weight=0.1,
vectors_weight=0.1, normals_weight=0.1, tcoords_weight=0.1,
tensors_weight=0.1, inplace=False):
# create decimation filter
decimate = vtk.vtkQuadricDecimation() # vtkDecimatePro as well
decimate.SetVolumePreservation(volume_preservation)
decimate.SetAttributeErrorMetric(attribute_error)
decimate.SetScalarsAttribute(scalars)
decimate.SetVectorsAttribute(vectors)
decimate.SetNormalsAttribute(normals)
decimate.SetTCoordsAttribute(tcoords)
decimate.SetTensorsAttribute(tensors)
decimate.SetScalarsWeight(scalars_weight)
decimate.SetVectorsWeight(vectors_weight)
decimate.SetNormalsWeight(normals_weight)
decimate.SetTCoordsWeight(tcoords_weight)
decimate.SetTensorsWeight(tensors_weight)
decimate.SetTargetReduction(target_reduction)
decimate.SetInputData(self)
decimate.Update()
mesh = _get_output(decimate)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"decimate",
"(",
"self",
",",
"target_reduction",
",",
"volume_preservation",
"=",
"False",
",",
"attribute_error",
"=",
"False",
",",
"scalars",
"=",
"True",
",",
"vectors",
"=",
"True",
",",
"normals",
"=",
"False",
",",
"tcoords",
"=",
"True",
",... | Reduces the number of triangles in a triangular mesh using
vtkQuadricDecimation.
Parameters
----------
mesh : vtk.PolyData
Mesh to decimate
target_reduction : float
Fraction of the original mesh to remove.
TargetReduction is set to 0.9, this filter will try to reduce
the data set to 10% of its original size and will remove 90%
of the input triangles.
volume_preservation : bool, optional
Decide whether to activate volume preservation which greatly reduces
errors in triangle normal direction. If off, volume preservation is
disabled and if AttributeErrorMetric is active, these errors can be
large. Defaults to False.
attribute_error : bool, optional
Decide whether to include data attributes in the error metric. If
off, then only geometric error is used to control the decimation.
Defaults to False.
scalars : bool, optional
If attribute errors are to be included in the metric (i.e.,
AttributeErrorMetric is on), then the following flags control which
attributes are to be included in the error calculation. Defaults to
True.
vectors : bool, optional
See scalars parameter. Defaults to True.
normals : bool, optional
See scalars parameter. Defaults to False.
tcoords : bool, optional
See scalars parameter. Defaults to True.
tensors : bool, optional
See scalars parameter. Defaults to True.
scalars_weight : float, optional
The scaling weight contribution of the scalar attribute. These
values are used to weight the contribution of the attributes towards
the error metric. Defaults to 0.1.
vectors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
normals_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tcoords_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
tensors_weight : float, optional
See scalars weight parameter. Defaults to 0.1.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
outmesh : vtki.PolyData
Decimated mesh. None when inplace=True. | [
"Reduces",
"the",
"number",
"of",
"triangles",
"in",
"a",
"triangular",
"mesh",
"using",
"vtkQuadricDecimation",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L892-L991 |
236,544 | vtkiorg/vtki | vtki/pointset.py | PolyData.center_of_mass | def center_of_mass(self, scalars_weight=False):
"""
Returns the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to False.
Return
------
center : np.ndarray, float
Coordinates for the center of mass.
"""
comfilter = vtk.vtkCenterOfMass()
comfilter.SetInputData(self)
comfilter.SetUseScalarsAsWeights(scalars_weight)
comfilter.Update()
return np.array(comfilter.GetCenter()) | python | def center_of_mass(self, scalars_weight=False):
comfilter = vtk.vtkCenterOfMass()
comfilter.SetInputData(self)
comfilter.SetUseScalarsAsWeights(scalars_weight)
comfilter.Update()
return np.array(comfilter.GetCenter()) | [
"def",
"center_of_mass",
"(",
"self",
",",
"scalars_weight",
"=",
"False",
")",
":",
"comfilter",
"=",
"vtk",
".",
"vtkCenterOfMass",
"(",
")",
"comfilter",
".",
"SetInputData",
"(",
"self",
")",
"comfilter",
".",
"SetUseScalarsAsWeights",
"(",
"scalars_weight",... | Returns the coordinates for the center of mass of the mesh.
Parameters
----------
scalars_weight : bool, optional
Flag for using the mesh scalars as weights. Defaults to False.
Return
------
center : np.ndarray, float
Coordinates for the center of mass. | [
"Returns",
"the",
"coordinates",
"for",
"the",
"center",
"of",
"mass",
"of",
"the",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L993-L1011 |
236,545 | vtkiorg/vtki | vtki/pointset.py | PolyData.clip_with_plane | def clip_with_plane(self, origin, normal, value=0, inplace=False):
"""
Clip a vtki.PolyData or vtk.vtkPolyData with a plane.
Can be used to open a mesh which has been closed along a well-defined
plane.
Parameters
----------
origin : numpy.ndarray
3D point through which plane passes. Defines the plane together with
normal parameter.
normal : numpy.ndarray
3D vector defining plane normal.
value : float, optional
Scalar clipping value. The default value is 0.0.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Updated mesh with cell and point normals if inplace=False. Otherwise None.
Notes
-----
Not guaranteed to produce a manifold output.
"""
plane = vtk.vtkPlane()
plane.SetOrigin(origin)
plane.SetNormal(normal)
plane.Modified()
clip = vtk.vtkClipPolyData()
clip.SetValue(value)
clip.GenerateClippedOutputOn()
clip.SetClipFunction(plane)
clip.SetInputData(self)
clip.Update()
mesh = _get_output(clip)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def clip_with_plane(self, origin, normal, value=0, inplace=False):
plane = vtk.vtkPlane()
plane.SetOrigin(origin)
plane.SetNormal(normal)
plane.Modified()
clip = vtk.vtkClipPolyData()
clip.SetValue(value)
clip.GenerateClippedOutputOn()
clip.SetClipFunction(plane)
clip.SetInputData(self)
clip.Update()
mesh = _get_output(clip)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"clip_with_plane",
"(",
"self",
",",
"origin",
",",
"normal",
",",
"value",
"=",
"0",
",",
"inplace",
"=",
"False",
")",
":",
"plane",
"=",
"vtk",
".",
"vtkPlane",
"(",
")",
"plane",
".",
"SetOrigin",
"(",
"origin",
")",
"plane",
".",
"SetNorm... | Clip a vtki.PolyData or vtk.vtkPolyData with a plane.
Can be used to open a mesh which has been closed along a well-defined
plane.
Parameters
----------
origin : numpy.ndarray
3D point through which plane passes. Defines the plane together with
normal parameter.
normal : numpy.ndarray
3D vector defining plane normal.
value : float, optional
Scalar clipping value. The default value is 0.0.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Updated mesh with cell and point normals if inplace=False. Otherwise None.
Notes
-----
Not guaranteed to produce a manifold output. | [
"Clip",
"a",
"vtki",
".",
"PolyData",
"or",
"vtk",
".",
"vtkPolyData",
"with",
"a",
"plane",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1131-L1181 |
236,546 | vtkiorg/vtki | vtki/pointset.py | PolyData.extract_largest | def extract_largest(self, inplace=False):
"""
Extract largest connected set in mesh.
Can be used to reduce residues obtained when generating an isosurface.
Works only if residues are not connected (share at least one point with)
the main component of the image.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Largest connected set in mesh
"""
mesh = self.connectivity(largest=True)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def extract_largest(self, inplace=False):
mesh = self.connectivity(largest=True)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"extract_largest",
"(",
"self",
",",
"inplace",
"=",
"False",
")",
":",
"mesh",
"=",
"self",
".",
"connectivity",
"(",
"largest",
"=",
"True",
")",
"if",
"inplace",
":",
"self",
".",
"overwrite",
"(",
"mesh",
")",
"else",
":",
"return",
"mesh"
] | Extract largest connected set in mesh.
Can be used to reduce residues obtained when generating an isosurface.
Works only if residues are not connected (share at least one point with)
the main component of the image.
Parameters
----------
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Largest connected set in mesh | [
"Extract",
"largest",
"connected",
"set",
"in",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1183-L1206 |
236,547 | vtkiorg/vtki | vtki/pointset.py | PolyData.fill_holes | def fill_holes(self, hole_size, inplace=False): # pragma: no cover
"""
Fill holes in a vtki.PolyData or vtk.vtkPolyData object.
Holes are identified by locating boundary edges, linking them together
into loops, and then triangulating the resulting loops. Note that you
can specify an approximate limit to the size of the hole that can be
filled.
Parameters
----------
hole_size : float
Specifies the maximum hole size to fill. This is represented as a
radius to the bounding circumsphere containing the hole. Note that
this is an approximate area; the actual area cannot be computed
without first triangulating the hole.
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
mesh : vtki.PolyData
Mesh with holes filled. None when inplace=True
"""
logging.warning('vtki.pointset.PolyData.fill_holes is known to segfault. ' +
'Use at your own risk')
fill = vtk.vtkFillHolesFilter()
fill.SetHoleSize(hole_size)
fill.SetInputData(self)
fill.Update()
mesh = _get_output(fill)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def fill_holes(self, hole_size, inplace=False): # pragma: no cover
logging.warning('vtki.pointset.PolyData.fill_holes is known to segfault. ' +
'Use at your own risk')
fill = vtk.vtkFillHolesFilter()
fill.SetHoleSize(hole_size)
fill.SetInputData(self)
fill.Update()
mesh = _get_output(fill)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"fill_holes",
"(",
"self",
",",
"hole_size",
",",
"inplace",
"=",
"False",
")",
":",
"# pragma: no cover",
"logging",
".",
"warning",
"(",
"'vtki.pointset.PolyData.fill_holes is known to segfault. '",
"+",
"'Use at your own risk'",
")",
"fill",
"=",
"vtk",
".",... | Fill holes in a vtki.PolyData or vtk.vtkPolyData object.
Holes are identified by locating boundary edges, linking them together
into loops, and then triangulating the resulting loops. Note that you
can specify an approximate limit to the size of the hole that can be
filled.
Parameters
----------
hole_size : float
Specifies the maximum hole size to fill. This is represented as a
radius to the bounding circumsphere containing the hole. Note that
this is an approximate area; the actual area cannot be computed
without first triangulating the hole.
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
mesh : vtki.PolyData
Mesh with holes filled. None when inplace=True | [
"Fill",
"holes",
"in",
"a",
"vtki",
".",
"PolyData",
"or",
"vtk",
".",
"vtkPolyData",
"object",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1210-L1247 |
236,548 | vtkiorg/vtki | vtki/pointset.py | PolyData.area | def area(self):
"""
Mesh surface area
Returns
-------
area : float
Total area of the mesh.
"""
mprop = vtk.vtkMassProperties()
mprop.SetInputData(self)
return mprop.GetSurfaceArea() | python | def area(self):
mprop = vtk.vtkMassProperties()
mprop.SetInputData(self)
return mprop.GetSurfaceArea() | [
"def",
"area",
"(",
"self",
")",
":",
"mprop",
"=",
"vtk",
".",
"vtkMassProperties",
"(",
")",
"mprop",
".",
"SetInputData",
"(",
"self",
")",
"return",
"mprop",
".",
"GetSurfaceArea",
"(",
")"
] | Mesh surface area
Returns
-------
area : float
Total area of the mesh. | [
"Mesh",
"surface",
"area"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1305-L1317 |
236,549 | vtkiorg/vtki | vtki/pointset.py | PolyData.geodesic | def geodesic(self, start_vertex, end_vertex, inplace=False):
"""
Calculates the geodesic path betweeen two vertices using Dijkstra's
algorithm.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Returns
-------
output : vtki.PolyData
PolyData object consisting of the line segment between the two given
vertices.
"""
if start_vertex < 0 or end_vertex > self.n_points - 1:
raise IndexError('Invalid indices.')
dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
dijkstra.SetInputData(self)
dijkstra.SetStartVertex(start_vertex)
dijkstra.SetEndVertex(end_vertex)
dijkstra.Update()
output = _get_output(dijkstra)
if inplace:
self.overwrite(output)
else:
return output | python | def geodesic(self, start_vertex, end_vertex, inplace=False):
if start_vertex < 0 or end_vertex > self.n_points - 1:
raise IndexError('Invalid indices.')
dijkstra = vtk.vtkDijkstraGraphGeodesicPath()
dijkstra.SetInputData(self)
dijkstra.SetStartVertex(start_vertex)
dijkstra.SetEndVertex(end_vertex)
dijkstra.Update()
output = _get_output(dijkstra)
if inplace:
self.overwrite(output)
else:
return output | [
"def",
"geodesic",
"(",
"self",
",",
"start_vertex",
",",
"end_vertex",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"start_vertex",
"<",
"0",
"or",
"end_vertex",
">",
"self",
".",
"n_points",
"-",
"1",
":",
"raise",
"IndexError",
"(",
"'Invalid indices.'... | Calculates the geodesic path betweeen two vertices using Dijkstra's
algorithm.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Returns
-------
output : vtki.PolyData
PolyData object consisting of the line segment between the two given
vertices. | [
"Calculates",
"the",
"geodesic",
"path",
"betweeen",
"two",
"vertices",
"using",
"Dijkstra",
"s",
"algorithm",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1350-L1384 |
236,550 | vtkiorg/vtki | vtki/pointset.py | PolyData.geodesic_distance | def geodesic_distance(self, start_vertex, end_vertex):
"""
Calculates the geodesic distance betweeen two vertices using Dijkstra's
algorithm.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Returns
-------
length : float
Length of the geodesic segment.
"""
length = self.geodesic(start_vertex, end_vertex).GetLength()
return length | python | def geodesic_distance(self, start_vertex, end_vertex):
length = self.geodesic(start_vertex, end_vertex).GetLength()
return length | [
"def",
"geodesic_distance",
"(",
"self",
",",
"start_vertex",
",",
"end_vertex",
")",
":",
"length",
"=",
"self",
".",
"geodesic",
"(",
"start_vertex",
",",
"end_vertex",
")",
".",
"GetLength",
"(",
")",
"return",
"length"
] | Calculates the geodesic distance betweeen two vertices using Dijkstra's
algorithm.
Parameters
----------
start_vertex : int
Vertex index indicating the start point of the geodesic segment.
end_vertex : int
Vertex index indicating the end point of the geodesic segment.
Returns
-------
length : float
Length of the geodesic segment. | [
"Calculates",
"the",
"geodesic",
"distance",
"betweeen",
"two",
"vertices",
"using",
"Dijkstra",
"s",
"algorithm",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1387-L1407 |
236,551 | vtkiorg/vtki | vtki/pointset.py | PolyData.ray_trace | def ray_trace(self, origin, end_point, first_point=False, plot=False,
off_screen=False):
"""
Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : np.ndarray or list
End of the line segment.
first_point : bool, optional
Returns intersection of first point only.
plot : bool, optional
Plots ray trace results
off_screen : bool, optional
Plots off screen. Used for unit testing.
Returns
-------
intersection_points : np.ndarray
Location of the intersection points. Empty array if no
intersections.
intersection_cells : np.ndarray
Indices of the intersection cells. Empty array if no
intersections.
"""
points = vtk.vtkPoints()
cell_ids = vtk.vtkIdList()
code = self.obbTree.IntersectWithLine(np.array(origin),
np.array(end_point),
points, cell_ids)
intersection_points = vtk_to_numpy(points.GetData())
if first_point and intersection_points.shape[0] >= 1:
intersection_points = intersection_points[0]
intersection_cells = []
if intersection_points.any():
if first_point:
ncells = 1
else:
ncells = cell_ids.GetNumberOfIds()
for i in range(ncells):
intersection_cells.append(cell_ids.GetId(i))
intersection_cells = np.array(intersection_cells)
if plot:
plotter = vtki.Plotter(off_screen=off_screen)
plotter.add_mesh(self, label='Test Mesh')
segment = np.array([origin, end_point])
plotter.add_lines(segment, 'b', label='Ray Segment')
plotter.add_mesh(intersection_points, 'r', point_size=10,
label='Intersection Points')
plotter.add_legend()
plotter.add_axes()
plotter.show()
return intersection_points, intersection_cells | python | def ray_trace(self, origin, end_point, first_point=False, plot=False,
off_screen=False):
points = vtk.vtkPoints()
cell_ids = vtk.vtkIdList()
code = self.obbTree.IntersectWithLine(np.array(origin),
np.array(end_point),
points, cell_ids)
intersection_points = vtk_to_numpy(points.GetData())
if first_point and intersection_points.shape[0] >= 1:
intersection_points = intersection_points[0]
intersection_cells = []
if intersection_points.any():
if first_point:
ncells = 1
else:
ncells = cell_ids.GetNumberOfIds()
for i in range(ncells):
intersection_cells.append(cell_ids.GetId(i))
intersection_cells = np.array(intersection_cells)
if plot:
plotter = vtki.Plotter(off_screen=off_screen)
plotter.add_mesh(self, label='Test Mesh')
segment = np.array([origin, end_point])
plotter.add_lines(segment, 'b', label='Ray Segment')
plotter.add_mesh(intersection_points, 'r', point_size=10,
label='Intersection Points')
plotter.add_legend()
plotter.add_axes()
plotter.show()
return intersection_points, intersection_cells | [
"def",
"ray_trace",
"(",
"self",
",",
"origin",
",",
"end_point",
",",
"first_point",
"=",
"False",
",",
"plot",
"=",
"False",
",",
"off_screen",
"=",
"False",
")",
":",
"points",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"cell_ids",
"=",
"vtk",
".",
"... | Performs a single ray trace calculation given a mesh and a line segment
defined by an origin and end_point.
Parameters
----------
origin : np.ndarray or list
Start of the line segment.
end_point : np.ndarray or list
End of the line segment.
first_point : bool, optional
Returns intersection of first point only.
plot : bool, optional
Plots ray trace results
off_screen : bool, optional
Plots off screen. Used for unit testing.
Returns
-------
intersection_points : np.ndarray
Location of the intersection points. Empty array if no
intersections.
intersection_cells : np.ndarray
Indices of the intersection cells. Empty array if no
intersections. | [
"Performs",
"a",
"single",
"ray",
"trace",
"calculation",
"given",
"a",
"mesh",
"and",
"a",
"line",
"segment",
"defined",
"by",
"an",
"origin",
"and",
"end_point",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1409-L1474 |
236,552 | vtkiorg/vtki | vtki/pointset.py | PolyData.plot_boundaries | def plot_boundaries(self, **kwargs):
""" Plots boundaries of a mesh """
edges = self.extract_edges()
plotter = vtki.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
plotter.add_mesh(edges, 'r', style='wireframe', legend='Edges')
plotter.add_mesh(self, legend='Mesh', **kwargs)
return plotter.show() | python | def plot_boundaries(self, **kwargs):
edges = self.extract_edges()
plotter = vtki.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
plotter.add_mesh(edges, 'r', style='wireframe', legend='Edges')
plotter.add_mesh(self, legend='Mesh', **kwargs)
return plotter.show() | [
"def",
"plot_boundaries",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"edges",
"=",
"self",
".",
"extract_edges",
"(",
")",
"plotter",
"=",
"vtki",
".",
"Plotter",
"(",
"off_screen",
"=",
"kwargs",
".",
"pop",
"(",
"'off_screen'",
",",
"False",
")"... | Plots boundaries of a mesh | [
"Plots",
"boundaries",
"of",
"a",
"mesh"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1476-L1484 |
236,553 | vtkiorg/vtki | vtki/pointset.py | PolyData.plot_normals | def plot_normals(self, show_mesh=True, mag=1.0, flip=False,
use_every=1, **kwargs):
"""
Plot the point normals of a mesh.
"""
plotter = vtki.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
if show_mesh:
plotter.add_mesh(self, **kwargs)
normals = self.point_normals
if flip:
normals *= -1
plotter.add_arrows(self.points[::use_every],
normals[::use_every], mag=mag)
return plotter.show() | python | def plot_normals(self, show_mesh=True, mag=1.0, flip=False,
use_every=1, **kwargs):
plotter = vtki.Plotter(off_screen=kwargs.pop('off_screen', False),
notebook=kwargs.pop('notebook', None))
if show_mesh:
plotter.add_mesh(self, **kwargs)
normals = self.point_normals
if flip:
normals *= -1
plotter.add_arrows(self.points[::use_every],
normals[::use_every], mag=mag)
return plotter.show() | [
"def",
"plot_normals",
"(",
"self",
",",
"show_mesh",
"=",
"True",
",",
"mag",
"=",
"1.0",
",",
"flip",
"=",
"False",
",",
"use_every",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"plotter",
"=",
"vtki",
".",
"Plotter",
"(",
"off_screen",
"=",
"kw... | Plot the point normals of a mesh. | [
"Plot",
"the",
"point",
"normals",
"of",
"a",
"mesh",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1486-L1501 |
236,554 | vtkiorg/vtki | vtki/pointset.py | PolyData.remove_points | def remove_points(self, remove, mode='any', keep_scalars=True, inplace=False):
"""
Rebuild a mesh by removing points. Only valid for
all-triangle meshes.
Parameters
----------
remove : np.ndarray
If remove is a bool array, points that are True will be
removed. Otherwise, it is treated as a list of indices.
mode : str, optional
When 'all', only faces containing all points flagged for
removal will be removed. Default 'all'
keep_scalars : bool, optional
When True, point and cell scalars will be passed on to the
new mesh.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Mesh without the points flagged for removal. Not returned
when inplace=False.
ridx : np.ndarray
Indices of new points relative to the original mesh. Not
returned when inplace=False.
"""
if isinstance(remove, list):
remove = np.asarray(remove)
if remove.dtype == np.bool:
if remove.size != self.n_points:
raise AssertionError('Mask different size than n_points')
remove_mask = remove
else:
remove_mask = np.zeros(self.n_points, np.bool)
remove_mask[remove] = True
try:
f = self.faces.reshape(-1, 4)[:, 1:]
except:
raise Exception('Mesh must consist of only triangles')
vmask = remove_mask.take(f)
if mode == 'all':
fmask = ~(vmask).all(1)
else:
fmask = ~(vmask).any(1)
# Regenerate face and point arrays
uni = np.unique(f.compress(fmask, 0), return_inverse=True)
new_points = self.points.take(uni[0], 0)
nfaces = fmask.sum()
faces = np.empty((nfaces, 4), dtype=vtki.ID_TYPE)
faces[:, 0] = 3
faces[:, 1:] = np.reshape(uni[1], (nfaces, 3))
newmesh = PolyData(new_points, faces, deep=True)
ridx = uni[0]
# Add scalars back to mesh if requested
if keep_scalars:
for key in self.point_arrays:
newmesh.point_arrays[key] = self.point_arrays[key][ridx]
for key in self.cell_arrays:
try:
newmesh.cell_arrays[key] = self.cell_arrays[key][fmask]
except:
log.warning('Unable to pass cell key %s onto reduced mesh' %
key)
# Return vtk surface and reverse indexing array
if inplace:
self.overwrite(newmesh)
else:
return newmesh, ridx | python | def remove_points(self, remove, mode='any', keep_scalars=True, inplace=False):
if isinstance(remove, list):
remove = np.asarray(remove)
if remove.dtype == np.bool:
if remove.size != self.n_points:
raise AssertionError('Mask different size than n_points')
remove_mask = remove
else:
remove_mask = np.zeros(self.n_points, np.bool)
remove_mask[remove] = True
try:
f = self.faces.reshape(-1, 4)[:, 1:]
except:
raise Exception('Mesh must consist of only triangles')
vmask = remove_mask.take(f)
if mode == 'all':
fmask = ~(vmask).all(1)
else:
fmask = ~(vmask).any(1)
# Regenerate face and point arrays
uni = np.unique(f.compress(fmask, 0), return_inverse=True)
new_points = self.points.take(uni[0], 0)
nfaces = fmask.sum()
faces = np.empty((nfaces, 4), dtype=vtki.ID_TYPE)
faces[:, 0] = 3
faces[:, 1:] = np.reshape(uni[1], (nfaces, 3))
newmesh = PolyData(new_points, faces, deep=True)
ridx = uni[0]
# Add scalars back to mesh if requested
if keep_scalars:
for key in self.point_arrays:
newmesh.point_arrays[key] = self.point_arrays[key][ridx]
for key in self.cell_arrays:
try:
newmesh.cell_arrays[key] = self.cell_arrays[key][fmask]
except:
log.warning('Unable to pass cell key %s onto reduced mesh' %
key)
# Return vtk surface and reverse indexing array
if inplace:
self.overwrite(newmesh)
else:
return newmesh, ridx | [
"def",
"remove_points",
"(",
"self",
",",
"remove",
",",
"mode",
"=",
"'any'",
",",
"keep_scalars",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"remove",
",",
"list",
")",
":",
"remove",
"=",
"np",
".",
"asarray",
"(... | Rebuild a mesh by removing points. Only valid for
all-triangle meshes.
Parameters
----------
remove : np.ndarray
If remove is a bool array, points that are True will be
removed. Otherwise, it is treated as a list of indices.
mode : str, optional
When 'all', only faces containing all points flagged for
removal will be removed. Default 'all'
keep_scalars : bool, optional
When True, point and cell scalars will be passed on to the
new mesh.
inplace : bool, optional
Updates mesh in-place while returning nothing.
Returns
-------
mesh : vtki.PolyData
Mesh without the points flagged for removal. Not returned
when inplace=False.
ridx : np.ndarray
Indices of new points relative to the original mesh. Not
returned when inplace=False. | [
"Rebuild",
"a",
"mesh",
"by",
"removing",
"points",
".",
"Only",
"valid",
"for",
"all",
"-",
"triangle",
"meshes",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1503-L1586 |
236,555 | vtkiorg/vtki | vtki/pointset.py | PolyData.flip_normals | def flip_normals(self):
"""
Flip normals of a triangular mesh by reversing the point ordering.
"""
if self.faces.size % 4:
raise Exception('Can only flip normals on an all triangular mesh')
f = self.faces.reshape((-1, 4))
f[:, 1:] = f[:, 1:][:, ::-1] | python | def flip_normals(self):
if self.faces.size % 4:
raise Exception('Can only flip normals on an all triangular mesh')
f = self.faces.reshape((-1, 4))
f[:, 1:] = f[:, 1:][:, ::-1] | [
"def",
"flip_normals",
"(",
"self",
")",
":",
"if",
"self",
".",
"faces",
".",
"size",
"%",
"4",
":",
"raise",
"Exception",
"(",
"'Can only flip normals on an all triangular mesh'",
")",
"f",
"=",
"self",
".",
"faces",
".",
"reshape",
"(",
"(",
"-",
"1",
... | Flip normals of a triangular mesh by reversing the point ordering. | [
"Flip",
"normals",
"of",
"a",
"triangular",
"mesh",
"by",
"reversing",
"the",
"point",
"ordering",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1588-L1597 |
236,556 | vtkiorg/vtki | vtki/pointset.py | PolyData.delaunay_2d | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False, inplace=False):
"""Apply a delaunay 2D filter along the best fitting plane"""
alg = vtk.vtkDelaunay2D()
alg.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
alg.SetInputDataObject(self)
alg.SetTolerance(tol)
alg.SetAlpha(alpha)
alg.SetOffset(offset)
alg.SetBoundingTriangulation(bound)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False, inplace=False):
alg = vtk.vtkDelaunay2D()
alg.SetProjectionPlaneMode(vtk.VTK_BEST_FITTING_PLANE)
alg.SetInputDataObject(self)
alg.SetTolerance(tol)
alg.SetAlpha(alpha)
alg.SetOffset(offset)
alg.SetBoundingTriangulation(bound)
alg.Update()
mesh = _get_output(alg)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"delaunay_2d",
"(",
"self",
",",
"tol",
"=",
"1e-05",
",",
"alpha",
"=",
"0.0",
",",
"offset",
"=",
"1.0",
",",
"bound",
"=",
"False",
",",
"inplace",
"=",
"False",
")",
":",
"alg",
"=",
"vtk",
".",
"vtkDelaunay2D",
"(",
")",
"alg",
".",
"... | Apply a delaunay 2D filter along the best fitting plane | [
"Apply",
"a",
"delaunay",
"2D",
"filter",
"along",
"the",
"best",
"fitting",
"plane"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1599-L1614 |
236,557 | vtkiorg/vtki | vtki/pointset.py | PointGrid.plot_curvature | def plot_curvature(self, curv_type='mean', **kwargs):
"""
Plots the curvature of the external surface of the grid
Parameters
----------
curv_type : str, optional
One of the following strings indicating curvature types
- mean
- gaussian
- maximum
- minimum
**kwargs : optional
Optional keyword arguments. See help(vtki.plot)
Returns
-------
cpos : list
Camera position, focal point, and view up. Used for storing and
setting camera view.
"""
trisurf = self.extract_surface().tri_filter()
return trisurf.plot_curvature(curv_type, **kwargs) | python | def plot_curvature(self, curv_type='mean', **kwargs):
trisurf = self.extract_surface().tri_filter()
return trisurf.plot_curvature(curv_type, **kwargs) | [
"def",
"plot_curvature",
"(",
"self",
",",
"curv_type",
"=",
"'mean'",
",",
"*",
"*",
"kwargs",
")",
":",
"trisurf",
"=",
"self",
".",
"extract_surface",
"(",
")",
".",
"tri_filter",
"(",
")",
"return",
"trisurf",
".",
"plot_curvature",
"(",
"curv_type",
... | Plots the curvature of the external surface of the grid
Parameters
----------
curv_type : str, optional
One of the following strings indicating curvature types
- mean
- gaussian
- maximum
- minimum
**kwargs : optional
Optional keyword arguments. See help(vtki.plot)
Returns
-------
cpos : list
Camera position, focal point, and view up. Used for storing and
setting camera view. | [
"Plots",
"the",
"curvature",
"of",
"the",
"external",
"surface",
"of",
"the",
"grid"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1633-L1658 |
236,558 | vtkiorg/vtki | vtki/pointset.py | PointGrid.extract_surface | def extract_surface(self, pass_pointid=True, pass_cellid=True, inplace=False):
"""
Extract surface mesh of the grid
Parameters
----------
pass_pointid : bool, optional
Adds a point scalar "vtkOriginalPointIds" that idenfities which
original points these surface points correspond to
pass_cellid : bool, optional
Adds a cell scalar "vtkOriginalPointIds" that idenfities which
original cells these surface cells correspond to
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
extsurf : vtki.PolyData
Surface mesh of the grid
"""
surf_filter = vtk.vtkDataSetSurfaceFilter()
surf_filter.SetInputData(self)
if pass_pointid:
surf_filter.PassThroughCellIdsOn()
if pass_cellid:
surf_filter.PassThroughPointIdsOn()
surf_filter.Update()
mesh = _get_output(surf_filter)
if inplace:
self.overwrite(mesh)
else:
return mesh | python | def extract_surface(self, pass_pointid=True, pass_cellid=True, inplace=False):
surf_filter = vtk.vtkDataSetSurfaceFilter()
surf_filter.SetInputData(self)
if pass_pointid:
surf_filter.PassThroughCellIdsOn()
if pass_cellid:
surf_filter.PassThroughPointIdsOn()
surf_filter.Update()
mesh = _get_output(surf_filter)
if inplace:
self.overwrite(mesh)
else:
return mesh | [
"def",
"extract_surface",
"(",
"self",
",",
"pass_pointid",
"=",
"True",
",",
"pass_cellid",
"=",
"True",
",",
"inplace",
"=",
"False",
")",
":",
"surf_filter",
"=",
"vtk",
".",
"vtkDataSetSurfaceFilter",
"(",
")",
"surf_filter",
".",
"SetInputData",
"(",
"s... | Extract surface mesh of the grid
Parameters
----------
pass_pointid : bool, optional
Adds a point scalar "vtkOriginalPointIds" that idenfities which
original points these surface points correspond to
pass_cellid : bool, optional
Adds a cell scalar "vtkOriginalPointIds" that idenfities which
original cells these surface cells correspond to
inplace : bool, optional
Return new mesh or overwrite input.
Returns
-------
extsurf : vtki.PolyData
Surface mesh of the grid | [
"Extract",
"surface",
"mesh",
"of",
"the",
"grid"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1669-L1703 |
236,559 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid._from_arrays | def _from_arrays(self, offset, cells, cell_type, points, deep=True):
"""
Create VTK unstructured grid from numpy arrays
Parameters
----------
offset : np.ndarray dtype=np.int64
Array indicating the start location of each cell in the cells
array.
cells : np.ndarray dtype=np.int64
Array of cells. Each cell contains the number of points in the
cell and the node numbers of the cell.
cell_type : np.uint8
Cell types of each cell. Each cell type numbers can be found from
vtk documentation. See example below.
points : np.ndarray
Numpy array containing point locations.
Examples
--------
>>> import numpy
>>> import vtk
>>> import vtki
>>> offset = np.array([0, 9])
>>> cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15])
>>> cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON], np.int8)
>>> cell1 = np.array([[0, 0, 0],
... [1, 0, 0],
... [1, 1, 0],
... [0, 1, 0],
... [0, 0, 1],
... [1, 0, 1],
... [1, 1, 1],
... [0, 1, 1]])
>>> cell2 = np.array([[0, 0, 2],
... [1, 0, 2],
... [1, 1, 2],
... [0, 1, 2],
... [0, 0, 3],
... [1, 0, 3],
... [1, 1, 3],
... [0, 1, 3]])
>>> points = np.vstack((cell1, cell2))
>>> grid = vtki.UnstructuredGrid(offset, cells, cell_type, points)
"""
if offset.dtype != vtki.ID_TYPE:
offset = offset.astype(vtki.ID_TYPE)
if cells.dtype != vtki.ID_TYPE:
cells = cells.astype(vtki.ID_TYPE)
if not cells.flags['C_CONTIGUOUS']:
cells = np.ascontiguousarray(cells)
# if cells.ndim != 1:
# cells = cells.ravel()
if cell_type.dtype != np.uint8:
cell_type = cell_type.astype(np.uint8)
# Get number of cells
ncells = cell_type.size
# Convert to vtk arrays
cell_type = numpy_to_vtk(cell_type, deep=deep)
offset = numpy_to_vtkIdTypeArray(offset, deep=deep)
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(ncells, numpy_to_vtkIdTypeArray(cells.ravel(), deep=deep))
# Convert points to vtkPoints object
points = vtki.vtk_points(points, deep=deep)
# Create unstructured grid
self.SetPoints(points)
self.SetCells(cell_type, offset, vtkcells) | python | def _from_arrays(self, offset, cells, cell_type, points, deep=True):
if offset.dtype != vtki.ID_TYPE:
offset = offset.astype(vtki.ID_TYPE)
if cells.dtype != vtki.ID_TYPE:
cells = cells.astype(vtki.ID_TYPE)
if not cells.flags['C_CONTIGUOUS']:
cells = np.ascontiguousarray(cells)
# if cells.ndim != 1:
# cells = cells.ravel()
if cell_type.dtype != np.uint8:
cell_type = cell_type.astype(np.uint8)
# Get number of cells
ncells = cell_type.size
# Convert to vtk arrays
cell_type = numpy_to_vtk(cell_type, deep=deep)
offset = numpy_to_vtkIdTypeArray(offset, deep=deep)
vtkcells = vtk.vtkCellArray()
vtkcells.SetCells(ncells, numpy_to_vtkIdTypeArray(cells.ravel(), deep=deep))
# Convert points to vtkPoints object
points = vtki.vtk_points(points, deep=deep)
# Create unstructured grid
self.SetPoints(points)
self.SetCells(cell_type, offset, vtkcells) | [
"def",
"_from_arrays",
"(",
"self",
",",
"offset",
",",
"cells",
",",
"cell_type",
",",
"points",
",",
"deep",
"=",
"True",
")",
":",
"if",
"offset",
".",
"dtype",
"!=",
"vtki",
".",
"ID_TYPE",
":",
"offset",
"=",
"offset",
".",
"astype",
"(",
"vtki"... | Create VTK unstructured grid from numpy arrays
Parameters
----------
offset : np.ndarray dtype=np.int64
Array indicating the start location of each cell in the cells
array.
cells : np.ndarray dtype=np.int64
Array of cells. Each cell contains the number of points in the
cell and the node numbers of the cell.
cell_type : np.uint8
Cell types of each cell. Each cell type numbers can be found from
vtk documentation. See example below.
points : np.ndarray
Numpy array containing point locations.
Examples
--------
>>> import numpy
>>> import vtk
>>> import vtki
>>> offset = np.array([0, 9])
>>> cells = np.array([8, 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 10, 11, 12, 13, 14, 15])
>>> cell_type = np.array([vtk.VTK_HEXAHEDRON, vtk.VTK_HEXAHEDRON], np.int8)
>>> cell1 = np.array([[0, 0, 0],
... [1, 0, 0],
... [1, 1, 0],
... [0, 1, 0],
... [0, 0, 1],
... [1, 0, 1],
... [1, 1, 1],
... [0, 1, 1]])
>>> cell2 = np.array([[0, 0, 2],
... [1, 0, 2],
... [1, 1, 2],
... [0, 1, 2],
... [0, 0, 3],
... [1, 0, 3],
... [1, 1, 3],
... [0, 1, 3]])
>>> points = np.vstack((cell1, cell2))
>>> grid = vtki.UnstructuredGrid(offset, cells, cell_type, points) | [
"Create",
"VTK",
"unstructured",
"grid",
"from",
"numpy",
"arrays"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1839-L1923 |
236,560 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid._load_file | def _load_file(self, filename):
"""
Load an unstructured grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtu will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('%s does not exist' % filename)
# Check file extention
if '.vtu' in filename:
reader = vtk.vtkXMLUnstructuredGridReader()
elif '.vtk' in filename:
reader = vtk.vtkUnstructuredGridReader()
else:
raise Exception('Extension should be either ".vtu" or ".vtk"')
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | python | def _load_file(self, filename):
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('%s does not exist' % filename)
# Check file extention
if '.vtu' in filename:
reader = vtk.vtkXMLUnstructuredGridReader()
elif '.vtk' in filename:
reader = vtk.vtkUnstructuredGridReader()
else:
raise Exception('Extension should be either ".vtu" or ".vtk"')
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | [
"def",
"_load_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# check file exists",
"if",
"not",
"os",
".",
"path",
".",
"isfile",... | Load an unstructured grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtu will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded. | [
"Load",
"an",
"unstructured",
"grid",
"from",
"a",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L1925-L1955 |
236,561 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.linear_copy | def linear_copy(self, deep=False):
"""
Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
- VTK_QUADRATIC_WEDGE --> VTK_WEDGE
- VTK_QUADRATIC_HEXAHEDRON --> VTK_HEXAHEDRON
Parameters
----------
deep : bool
When True, makes a copy of the points array. Default
False. Cells and cell types are always copied.
Returns
-------
grid : vtki.UnstructuredGrid
UnstructuredGrid containing only linear cells.
"""
lgrid = self.copy(deep)
# grab the vtk object
vtk_cell_type = numpy_to_vtk(self.GetCellTypesArray(), deep=True)
celltype = vtk_to_numpy(vtk_cell_type)
celltype[celltype == VTK_QUADRATIC_TETRA] = VTK_TETRA
celltype[celltype == VTK_QUADRATIC_PYRAMID] = VTK_PYRAMID
celltype[celltype == VTK_QUADRATIC_WEDGE] = VTK_WEDGE
celltype[celltype == VTK_QUADRATIC_HEXAHEDRON] = VTK_HEXAHEDRON
# track quad mask for later
quad_quad_mask = celltype == VTK_QUADRATIC_QUAD
celltype[quad_quad_mask] = VTK_QUAD
quad_tri_mask = celltype == VTK_QUADRATIC_TRIANGLE
celltype[quad_tri_mask] = VTK_TRIANGLE
vtk_offset = self.GetCellLocationsArray()
cells = vtk.vtkCellArray()
cells.DeepCopy(self.GetCells())
lgrid.SetCells(vtk_cell_type, vtk_offset, cells)
# fixing bug with display of quad cells
if np.any(quad_quad_mask):
quad_offset = lgrid.offset[quad_quad_mask]
base_point = lgrid.cells[quad_offset + 1]
lgrid.cells[quad_offset + 5] = base_point
lgrid.cells[quad_offset + 6] = base_point
lgrid.cells[quad_offset + 7] = base_point
lgrid.cells[quad_offset + 8] = base_point
if np.any(quad_tri_mask):
tri_offset = lgrid.offset[quad_tri_mask]
base_point = lgrid.cells[tri_offset + 1]
lgrid.cells[tri_offset + 4] = base_point
lgrid.cells[tri_offset + 5] = base_point
lgrid.cells[tri_offset + 6] = base_point
return lgrid | python | def linear_copy(self, deep=False):
lgrid = self.copy(deep)
# grab the vtk object
vtk_cell_type = numpy_to_vtk(self.GetCellTypesArray(), deep=True)
celltype = vtk_to_numpy(vtk_cell_type)
celltype[celltype == VTK_QUADRATIC_TETRA] = VTK_TETRA
celltype[celltype == VTK_QUADRATIC_PYRAMID] = VTK_PYRAMID
celltype[celltype == VTK_QUADRATIC_WEDGE] = VTK_WEDGE
celltype[celltype == VTK_QUADRATIC_HEXAHEDRON] = VTK_HEXAHEDRON
# track quad mask for later
quad_quad_mask = celltype == VTK_QUADRATIC_QUAD
celltype[quad_quad_mask] = VTK_QUAD
quad_tri_mask = celltype == VTK_QUADRATIC_TRIANGLE
celltype[quad_tri_mask] = VTK_TRIANGLE
vtk_offset = self.GetCellLocationsArray()
cells = vtk.vtkCellArray()
cells.DeepCopy(self.GetCells())
lgrid.SetCells(vtk_cell_type, vtk_offset, cells)
# fixing bug with display of quad cells
if np.any(quad_quad_mask):
quad_offset = lgrid.offset[quad_quad_mask]
base_point = lgrid.cells[quad_offset + 1]
lgrid.cells[quad_offset + 5] = base_point
lgrid.cells[quad_offset + 6] = base_point
lgrid.cells[quad_offset + 7] = base_point
lgrid.cells[quad_offset + 8] = base_point
if np.any(quad_tri_mask):
tri_offset = lgrid.offset[quad_tri_mask]
base_point = lgrid.cells[tri_offset + 1]
lgrid.cells[tri_offset + 4] = base_point
lgrid.cells[tri_offset + 5] = base_point
lgrid.cells[tri_offset + 6] = base_point
return lgrid | [
"def",
"linear_copy",
"(",
"self",
",",
"deep",
"=",
"False",
")",
":",
"lgrid",
"=",
"self",
".",
"copy",
"(",
"deep",
")",
"# grab the vtk object",
"vtk_cell_type",
"=",
"numpy_to_vtk",
"(",
"self",
".",
"GetCellTypesArray",
"(",
")",
",",
"deep",
"=",
... | Returns a copy of the input unstructured grid containing only
linear cells. Converts the following cell types to their
linear equivalents.
- VTK_QUADRATIC_TETRA --> VTK_TETRA
- VTK_QUADRATIC_PYRAMID --> VTK_PYRAMID
- VTK_QUADRATIC_WEDGE --> VTK_WEDGE
- VTK_QUADRATIC_HEXAHEDRON --> VTK_HEXAHEDRON
Parameters
----------
deep : bool
When True, makes a copy of the points array. Default
False. Cells and cell types are always copied.
Returns
-------
grid : vtki.UnstructuredGrid
UnstructuredGrid containing only linear cells. | [
"Returns",
"a",
"copy",
"of",
"the",
"input",
"unstructured",
"grid",
"containing",
"only",
"linear",
"cells",
".",
"Converts",
"the",
"following",
"cell",
"types",
"to",
"their",
"linear",
"equivalents",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2015-L2075 |
236,562 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.extract_cells | def extract_cells(self, ind):
"""
Returns a subset of the grid
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Returns
-------
subgrid : vtki.UnstructuredGrid
Subselected grid
"""
if not isinstance(ind, np.ndarray):
ind = np.array(ind, np.ndarray)
if ind.dtype == np.bool:
ind = ind.nonzero()[0].astype(vtki.ID_TYPE)
if ind.dtype != vtki.ID_TYPE:
ind = ind.astype(vtki.ID_TYPE)
if not ind.flags.c_contiguous:
ind = np.ascontiguousarray(ind)
vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=False)
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
selectionNode.SetSelectionList(vtk_ind)
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, self)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
subgrid = _get_output(extract_sel)
# extracts only in float32
if self.points.dtype is not np.dtype('float32'):
ind = subgrid.point_arrays['vtkOriginalPointIds']
subgrid.points = self.points[ind]
return subgrid | python | def extract_cells(self, ind):
if not isinstance(ind, np.ndarray):
ind = np.array(ind, np.ndarray)
if ind.dtype == np.bool:
ind = ind.nonzero()[0].astype(vtki.ID_TYPE)
if ind.dtype != vtki.ID_TYPE:
ind = ind.astype(vtki.ID_TYPE)
if not ind.flags.c_contiguous:
ind = np.ascontiguousarray(ind)
vtk_ind = numpy_to_vtkIdTypeArray(ind, deep=False)
# Create selection objects
selectionNode = vtk.vtkSelectionNode()
selectionNode.SetFieldType(vtk.vtkSelectionNode.CELL)
selectionNode.SetContentType(vtk.vtkSelectionNode.INDICES)
selectionNode.SetSelectionList(vtk_ind)
selection = vtk.vtkSelection()
selection.AddNode(selectionNode)
# extract
extract_sel = vtk.vtkExtractSelection()
extract_sel.SetInputData(0, self)
extract_sel.SetInputData(1, selection)
extract_sel.Update()
subgrid = _get_output(extract_sel)
# extracts only in float32
if self.points.dtype is not np.dtype('float32'):
ind = subgrid.point_arrays['vtkOriginalPointIds']
subgrid.points = self.points[ind]
return subgrid | [
"def",
"extract_cells",
"(",
"self",
",",
"ind",
")",
":",
"if",
"not",
"isinstance",
"(",
"ind",
",",
"np",
".",
"ndarray",
")",
":",
"ind",
"=",
"np",
".",
"array",
"(",
"ind",
",",
"np",
".",
"ndarray",
")",
"if",
"ind",
".",
"dtype",
"==",
... | Returns a subset of the grid
Parameters
----------
ind : np.ndarray
Numpy array of cell indices to be extracted.
Returns
-------
subgrid : vtki.UnstructuredGrid
Subselected grid | [
"Returns",
"a",
"subset",
"of",
"the",
"grid"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2087-L2137 |
236,563 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.merge | def merge(self, grid=None, merge_points=True, inplace=False,
main_has_priority=True):
"""
Join one or many other grids to this grid. Grid is updated
in-place by default.
Can be used to merge points of adjcent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes.
inplace : bool, optional
Updates grid inplace when True.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the scalar arrays of the merging grids will be overwritten
by the original main mesh.
Returns
-------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
scalar array must match or the arrays will be ignored and not
included in the final merged mesh.
"""
append_filter = vtk.vtkAppendFilter()
append_filter.SetMergePoints(merge_points)
if not main_has_priority:
append_filter.AddInputData(self)
if isinstance(grid, vtki.UnstructuredGrid):
append_filter.AddInputData(grid)
elif isinstance(grid, list):
grids = grid
for grid in grids:
append_filter.AddInputData(grid)
if main_has_priority:
append_filter.AddInputData(self)
append_filter.Update()
merged = _get_output(append_filter)
if inplace:
self.DeepCopy(merged)
else:
return merged | python | def merge(self, grid=None, merge_points=True, inplace=False,
main_has_priority=True):
append_filter = vtk.vtkAppendFilter()
append_filter.SetMergePoints(merge_points)
if not main_has_priority:
append_filter.AddInputData(self)
if isinstance(grid, vtki.UnstructuredGrid):
append_filter.AddInputData(grid)
elif isinstance(grid, list):
grids = grid
for grid in grids:
append_filter.AddInputData(grid)
if main_has_priority:
append_filter.AddInputData(self)
append_filter.Update()
merged = _get_output(append_filter)
if inplace:
self.DeepCopy(merged)
else:
return merged | [
"def",
"merge",
"(",
"self",
",",
"grid",
"=",
"None",
",",
"merge_points",
"=",
"True",
",",
"inplace",
"=",
"False",
",",
"main_has_priority",
"=",
"True",
")",
":",
"append_filter",
"=",
"vtk",
".",
"vtkAppendFilter",
"(",
")",
"append_filter",
".",
"... | Join one or many other grids to this grid. Grid is updated
in-place by default.
Can be used to merge points of adjcent cells when no grids
are input.
Parameters
----------
grid : vtk.UnstructuredGrid or list of vtk.UnstructuredGrids
Grids to merge to this grid.
merge_points : bool, optional
Points in exactly the same location will be merged between
the two meshes.
inplace : bool, optional
Updates grid inplace when True.
main_has_priority : bool, optional
When this parameter is true and merge_points is true,
the scalar arrays of the merging grids will be overwritten
by the original main mesh.
Returns
-------
merged_grid : vtk.UnstructuredGrid
Merged grid. Returned when inplace is False.
Notes
-----
When two or more grids are joined, the type and name of each
scalar array must match or the arrays will be ignored and not
included in the final merged mesh. | [
"Join",
"one",
"or",
"many",
"other",
"grids",
"to",
"this",
"grid",
".",
"Grid",
"is",
"updated",
"in",
"-",
"place",
"by",
"default",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2175-L2233 |
236,564 | vtkiorg/vtki | vtki/pointset.py | UnstructuredGrid.delaunay_2d | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):
"""Apply a delaunay 2D filter along the best fitting plane. This
extracts the grid's points and perfoms the triangulation on those alone.
"""
return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound) | python | def delaunay_2d(self, tol=1e-05, alpha=0.0, offset=1.0, bound=False):
return PolyData(self.points).delaunay_2d(tol=tol, alpha=alpha, offset=offset, bound=bound) | [
"def",
"delaunay_2d",
"(",
"self",
",",
"tol",
"=",
"1e-05",
",",
"alpha",
"=",
"0.0",
",",
"offset",
"=",
"1.0",
",",
"bound",
"=",
"False",
")",
":",
"return",
"PolyData",
"(",
"self",
".",
"points",
")",
".",
"delaunay_2d",
"(",
"tol",
"=",
"tol... | Apply a delaunay 2D filter along the best fitting plane. This
extracts the grid's points and perfoms the triangulation on those alone. | [
"Apply",
"a",
"delaunay",
"2D",
"filter",
"along",
"the",
"best",
"fitting",
"plane",
".",
"This",
"extracts",
"the",
"grid",
"s",
"points",
"and",
"perfoms",
"the",
"triangulation",
"on",
"those",
"alone",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2235-L2239 |
236,565 | vtkiorg/vtki | vtki/pointset.py | StructuredGrid._from_arrays | def _from_arrays(self, x, y, z):
"""
Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
Position of the points in z direction.
"""
if not(x.shape == y.shape == z.shape):
raise Exception('Input point array shapes must match exactly')
# make the output points the same precision as the input arrays
points = np.empty((x.size, 3), x.dtype)
points[:, 0] = x.ravel('F')
points[:, 1] = y.ravel('F')
points[:, 2] = z.ravel('F')
# ensure that the inputs are 3D
dim = list(x.shape)
while len(dim) < 3:
dim.append(1)
# Create structured grid
self.SetDimensions(dim)
self.SetPoints(vtki.vtk_points(points)) | python | def _from_arrays(self, x, y, z):
if not(x.shape == y.shape == z.shape):
raise Exception('Input point array shapes must match exactly')
# make the output points the same precision as the input arrays
points = np.empty((x.size, 3), x.dtype)
points[:, 0] = x.ravel('F')
points[:, 1] = y.ravel('F')
points[:, 2] = z.ravel('F')
# ensure that the inputs are 3D
dim = list(x.shape)
while len(dim) < 3:
dim.append(1)
# Create structured grid
self.SetDimensions(dim)
self.SetPoints(vtki.vtk_points(points)) | [
"def",
"_from_arrays",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"if",
"not",
"(",
"x",
".",
"shape",
"==",
"y",
".",
"shape",
"==",
"z",
".",
"shape",
")",
":",
"raise",
"Exception",
"(",
"'Input point array shapes must match exactly'",
")"... | Create VTK structured grid directly from numpy arrays.
Parameters
----------
x : np.ndarray
Position of the points in x direction.
y : np.ndarray
Position of the points in y direction.
z : np.ndarray
Position of the points in z direction. | [
"Create",
"VTK",
"structured",
"grid",
"directly",
"from",
"numpy",
"arrays",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2303-L2334 |
236,566 | vtkiorg/vtki | vtki/pointset.py | StructuredGrid.save | def save(self, filename, binary=True):
"""
Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkStructuredGridWriter()
if binary:
writer.SetFileTypeToBinary()
else:
writer.SetFileTypeToASCII()
elif '.vts' in filename:
writer = vtk.vtkXMLStructuredGridWriter()
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
else:
raise Exception('Extension should be either ".vts" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
writer.Write() | python | def save(self, filename, binary=True):
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkStructuredGridWriter()
if binary:
writer.SetFileTypeToBinary()
else:
writer.SetFileTypeToASCII()
elif '.vts' in filename:
writer = vtk.vtkXMLStructuredGridWriter()
if binary:
writer.SetDataModeToBinary()
else:
writer.SetDataModeToAscii()
else:
raise Exception('Extension should be either ".vts" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
writer.Write() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | Writes a structured grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vts" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer. | [
"Writes",
"a",
"structured",
"grid",
"to",
"disk",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2376-L2418 |
236,567 | vtkiorg/vtki | vtki/pointset.py | StructuredGrid.dimensions | def dimensions(self, dims):
"""Sets the dataset dimensions. Pass a length three tuple of integers"""
nx, ny, nz = dims[0], dims[1], dims[2]
self.SetDimensions(nx, ny, nz)
self.Modified() | python | def dimensions(self, dims):
nx, ny, nz = dims[0], dims[1], dims[2]
self.SetDimensions(nx, ny, nz)
self.Modified() | [
"def",
"dimensions",
"(",
"self",
",",
"dims",
")",
":",
"nx",
",",
"ny",
",",
"nz",
"=",
"dims",
"[",
"0",
"]",
",",
"dims",
"[",
"1",
"]",
",",
"dims",
"[",
"2",
"]",
"self",
".",
"SetDimensions",
"(",
"nx",
",",
"ny",
",",
"nz",
")",
"se... | Sets the dataset dimensions. Pass a length three tuple of integers | [
"Sets",
"the",
"dataset",
"dimensions",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"integers"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/pointset.py#L2426-L2430 |
236,568 | vtkiorg/vtki | vtki/grid.py | RectilinearGrid._from_arrays | def _from_arrays(self, x, y, z):
"""
Create VTK rectilinear grid directly from numpy arrays. Each array
gives the uniques coordinates of the mesh along each axial direction.
To help ensure you are using this correctly, we take the unique values
of each argument.
Parameters
----------
x : np.ndarray
Coordinates of the nodes in x direction.
y : np.ndarray
Coordinates of the nodes in y direction.
z : np.ndarray
Coordinates of the nodes in z direction.
"""
x = np.unique(x.ravel())
y = np.unique(y.ravel())
z = np.unique(z.ravel())
# Set the cell spacings and dimensions of the grid
self.SetDimensions(len(x), len(y), len(z))
self.SetXCoordinates(numpy_to_vtk(x))
self.SetYCoordinates(numpy_to_vtk(y))
self.SetZCoordinates(numpy_to_vtk(z)) | python | def _from_arrays(self, x, y, z):
x = np.unique(x.ravel())
y = np.unique(y.ravel())
z = np.unique(z.ravel())
# Set the cell spacings and dimensions of the grid
self.SetDimensions(len(x), len(y), len(z))
self.SetXCoordinates(numpy_to_vtk(x))
self.SetYCoordinates(numpy_to_vtk(y))
self.SetZCoordinates(numpy_to_vtk(z)) | [
"def",
"_from_arrays",
"(",
"self",
",",
"x",
",",
"y",
",",
"z",
")",
":",
"x",
"=",
"np",
".",
"unique",
"(",
"x",
".",
"ravel",
"(",
")",
")",
"y",
"=",
"np",
".",
"unique",
"(",
"y",
".",
"ravel",
"(",
")",
")",
"z",
"=",
"np",
".",
... | Create VTK rectilinear grid directly from numpy arrays. Each array
gives the uniques coordinates of the mesh along each axial direction.
To help ensure you are using this correctly, we take the unique values
of each argument.
Parameters
----------
x : np.ndarray
Coordinates of the nodes in x direction.
y : np.ndarray
Coordinates of the nodes in y direction.
z : np.ndarray
Coordinates of the nodes in z direction. | [
"Create",
"VTK",
"rectilinear",
"grid",
"directly",
"from",
"numpy",
"arrays",
".",
"Each",
"array",
"gives",
"the",
"uniques",
"coordinates",
"of",
"the",
"mesh",
"along",
"each",
"axial",
"direction",
".",
"To",
"help",
"ensure",
"you",
"are",
"using",
"th... | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L108-L133 |
236,569 | vtkiorg/vtki | vtki/grid.py | RectilinearGrid._load_file | def _load_file(self, filename):
"""
Load a rectilinear grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtr will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('{} does not exist'.format(filename))
# Check file extention
if '.vtr' in filename:
legacy_writer = False
elif '.vtk' in filename:
legacy_writer = True
else:
raise Exception(
'Extension should be either ".vtr" (xml) or ".vtk" (legacy)')
# Create reader
if legacy_writer:
reader = vtk.vtkRectilinearGridReader()
else:
reader = vtk.vtkXMLRectilinearGridReader()
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | python | def _load_file(self, filename):
filename = os.path.abspath(os.path.expanduser(filename))
# check file exists
if not os.path.isfile(filename):
raise Exception('{} does not exist'.format(filename))
# Check file extention
if '.vtr' in filename:
legacy_writer = False
elif '.vtk' in filename:
legacy_writer = True
else:
raise Exception(
'Extension should be either ".vtr" (xml) or ".vtk" (legacy)')
# Create reader
if legacy_writer:
reader = vtk.vtkRectilinearGridReader()
else:
reader = vtk.vtkXMLRectilinearGridReader()
# load file to self
reader.SetFileName(filename)
reader.Update()
grid = reader.GetOutput()
self.ShallowCopy(grid) | [
"def",
"_load_file",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# check file exists",
"if",
"not",
"os",
".",
"path",
".",
"isfile",... | Load a rectilinear grid from a file.
The file extension will select the type of reader to use. A .vtk
extension will use the legacy reader, while .vtr will select the VTK
XML reader.
Parameters
----------
filename : str
Filename of grid to be loaded. | [
"Load",
"a",
"rectilinear",
"grid",
"from",
"a",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L160-L198 |
236,570 | vtkiorg/vtki | vtki/grid.py | RectilinearGrid.save | def save(self, filename, binary=True):
"""
Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer.
"""
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkRectilinearGridWriter()
legacy = True
elif '.vtr' in filename:
writer = vtk.vtkXMLRectilinearGridWriter()
legacy = False
else:
raise Exception('Extension should be either ".vtr" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
if binary and legacy:
writer.SetFileTypeToBinary()
writer.Write() | python | def save(self, filename, binary=True):
filename = os.path.abspath(os.path.expanduser(filename))
# Use legacy writer if vtk is in filename
if '.vtk' in filename:
writer = vtk.vtkRectilinearGridWriter()
legacy = True
elif '.vtr' in filename:
writer = vtk.vtkXMLRectilinearGridWriter()
legacy = False
else:
raise Exception('Extension should be either ".vtr" (xml) or' +
'".vtk" (legacy)')
# Write
writer.SetFileName(filename)
writer.SetInputData(self)
if binary and legacy:
writer.SetFileTypeToBinary()
writer.Write() | [
"def",
"save",
"(",
"self",
",",
"filename",
",",
"binary",
"=",
"True",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"# Use legacy writer if vtk is in filename",
"if",
... | Writes a rectilinear grid to disk.
Parameters
----------
filename : str
Filename of grid to be written. The file extension will select the
type of writer to use. ".vtk" will use the legacy writer, while
".vtr" will select the VTK XML writer.
binary : bool, optional
Writes as a binary file by default. Set to False to write ASCII.
Notes
-----
Binary files write much faster than ASCII, but binary files written on
one system may not be readable on other systems. Binary can be used
only with the legacy writer. | [
"Writes",
"a",
"rectilinear",
"grid",
"to",
"disk",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L200-L238 |
236,571 | vtkiorg/vtki | vtki/grid.py | UniformGrid.origin | def origin(self, origin):
"""Set the origin. Pass a length three tuple of floats"""
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | python | def origin(self, origin):
ox, oy, oz = origin[0], origin[1], origin[2]
self.SetOrigin(ox, oy, oz)
self.Modified() | [
"def",
"origin",
"(",
"self",
",",
"origin",
")",
":",
"ox",
",",
"oy",
",",
"oz",
"=",
"origin",
"[",
"0",
"]",
",",
"origin",
"[",
"1",
"]",
",",
"origin",
"[",
"2",
"]",
"self",
".",
"SetOrigin",
"(",
"ox",
",",
"oy",
",",
"oz",
")",
"se... | Set the origin. Pass a length three tuple of floats | [
"Set",
"the",
"origin",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"floats"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L533-L537 |
236,572 | vtkiorg/vtki | vtki/grid.py | UniformGrid.spacing | def spacing(self, spacing):
"""Set the spacing in each axial direction. Pass a length three tuple of
floats"""
dx, dy, dz = spacing[0], spacing[1], spacing[2]
self.SetSpacing(dx, dy, dz)
self.Modified() | python | def spacing(self, spacing):
dx, dy, dz = spacing[0], spacing[1], spacing[2]
self.SetSpacing(dx, dy, dz)
self.Modified() | [
"def",
"spacing",
"(",
"self",
",",
"spacing",
")",
":",
"dx",
",",
"dy",
",",
"dz",
"=",
"spacing",
"[",
"0",
"]",
",",
"spacing",
"[",
"1",
"]",
",",
"spacing",
"[",
"2",
"]",
"self",
".",
"SetSpacing",
"(",
"dx",
",",
"dy",
",",
"dz",
")",... | Set the spacing in each axial direction. Pass a length three tuple of
floats | [
"Set",
"the",
"spacing",
"in",
"each",
"axial",
"direction",
".",
"Pass",
"a",
"length",
"three",
"tuple",
"of",
"floats"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/grid.py#L545-L550 |
236,573 | vtkiorg/vtki | vtki/qt_plotting.py | resample_image | def resample_image(arr, max_size=400):
"""Resamples a square image to an image of max_size"""
dim = np.max(arr.shape[0:2])
if dim < max_size:
max_size = dim
x, y, _ = arr.shape
sx = int(np.ceil(x / max_size))
sy = int(np.ceil(y / max_size))
img = np.zeros((max_size, max_size, 3), dtype=arr.dtype)
arr = arr[0:-1:sx, 0:-1:sy, :]
xl = (max_size - arr.shape[0]) // 2
yl = (max_size - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return img | python | def resample_image(arr, max_size=400):
dim = np.max(arr.shape[0:2])
if dim < max_size:
max_size = dim
x, y, _ = arr.shape
sx = int(np.ceil(x / max_size))
sy = int(np.ceil(y / max_size))
img = np.zeros((max_size, max_size, 3), dtype=arr.dtype)
arr = arr[0:-1:sx, 0:-1:sy, :]
xl = (max_size - arr.shape[0]) // 2
yl = (max_size - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return img | [
"def",
"resample_image",
"(",
"arr",
",",
"max_size",
"=",
"400",
")",
":",
"dim",
"=",
"np",
".",
"max",
"(",
"arr",
".",
"shape",
"[",
"0",
":",
"2",
"]",
")",
"if",
"dim",
"<",
"max_size",
":",
"max_size",
"=",
"dim",
"x",
",",
"y",
",",
"... | Resamples a square image to an image of max_size | [
"Resamples",
"a",
"square",
"image",
"to",
"an",
"image",
"of",
"max_size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L229-L242 |
236,574 | vtkiorg/vtki | vtki/qt_plotting.py | pad_image | def pad_image(arr, max_size=400):
"""Pads an image to a square then resamples to max_size"""
dim = np.max(arr.shape)
img = np.zeros((dim, dim, 3), dtype=arr.dtype)
xl = (dim - arr.shape[0]) // 2
yl = (dim - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return resample_image(img, max_size=max_size) | python | def pad_image(arr, max_size=400):
dim = np.max(arr.shape)
img = np.zeros((dim, dim, 3), dtype=arr.dtype)
xl = (dim - arr.shape[0]) // 2
yl = (dim - arr.shape[1]) // 2
img[xl:arr.shape[0]+xl, yl:arr.shape[1]+yl, :] = arr
return resample_image(img, max_size=max_size) | [
"def",
"pad_image",
"(",
"arr",
",",
"max_size",
"=",
"400",
")",
":",
"dim",
"=",
"np",
".",
"max",
"(",
"arr",
".",
"shape",
")",
"img",
"=",
"np",
".",
"zeros",
"(",
"(",
"dim",
",",
"dim",
",",
"3",
")",
",",
"dtype",
"=",
"arr",
".",
"... | Pads an image to a square then resamples to max_size | [
"Pads",
"an",
"image",
"to",
"a",
"square",
"then",
"resamples",
"to",
"max_size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L245-L252 |
236,575 | vtkiorg/vtki | vtki/qt_plotting.py | FileDialog.emit_accepted | def emit_accepted(self):
"""
Sends signal that the file dialog was closed properly.
Sends:
filename
"""
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filename) | python | def emit_accepted(self):
if self.result():
filename = self.selectedFiles()[0]
if os.path.isdir(os.path.dirname(filename)):
self.dlg_accepted.emit(filename) | [
"def",
"emit_accepted",
"(",
"self",
")",
":",
"if",
"self",
".",
"result",
"(",
")",
":",
"filename",
"=",
"self",
".",
"selectedFiles",
"(",
")",
"[",
"0",
"]",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"dirname",
"(",... | Sends signal that the file dialog was closed properly.
Sends:
filename | [
"Sends",
"signal",
"that",
"the",
"file",
"dialog",
"was",
"closed",
"properly",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L92-L102 |
236,576 | vtkiorg/vtki | vtki/qt_plotting.py | ScaleAxesDialog.update_scale | def update_scale(self, value):
""" updates the scale of all actors in the plotter """
self.plotter.set_scale(self.x_slider_group.value,
self.y_slider_group.value,
self.z_slider_group.value) | python | def update_scale(self, value):
self.plotter.set_scale(self.x_slider_group.value,
self.y_slider_group.value,
self.z_slider_group.value) | [
"def",
"update_scale",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"plotter",
".",
"set_scale",
"(",
"self",
".",
"x_slider_group",
".",
"value",
",",
"self",
".",
"y_slider_group",
".",
"value",
",",
"self",
".",
"z_slider_group",
".",
"value",
")... | updates the scale of all actors in the plotter | [
"updates",
"the",
"scale",
"of",
"all",
"actors",
"in",
"the",
"plotter"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L222-L226 |
236,577 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.scale_axes_dialog | def scale_axes_dialog(self, show=True):
""" Open scale axes dialog """
return ScaleAxesDialog(self.app_window, self, show=show) | python | def scale_axes_dialog(self, show=True):
return ScaleAxesDialog(self.app_window, self, show=show) | [
"def",
"scale_axes_dialog",
"(",
"self",
",",
"show",
"=",
"True",
")",
":",
"return",
"ScaleAxesDialog",
"(",
"self",
".",
"app_window",
",",
"self",
",",
"show",
"=",
"show",
")"
] | Open scale axes dialog | [
"Open",
"scale",
"axes",
"dialog"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L418-L420 |
236,578 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.clear_camera_positions | def clear_camera_positions(self):
""" clears all camera positions """
for action in self.saved_camera_menu.actions():
self.saved_camera_menu.removeAction(action) | python | def clear_camera_positions(self):
for action in self.saved_camera_menu.actions():
self.saved_camera_menu.removeAction(action) | [
"def",
"clear_camera_positions",
"(",
"self",
")",
":",
"for",
"action",
"in",
"self",
".",
"saved_camera_menu",
".",
"actions",
"(",
")",
":",
"self",
".",
"saved_camera_menu",
".",
"removeAction",
"(",
"action",
")"
] | clears all camera positions | [
"clears",
"all",
"camera",
"positions"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L422-L425 |
236,579 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.save_camera_position | def save_camera_position(self):
""" Saves camera position to saved camera menu for recall """
self.saved_camera_positions.append(self.camera_position)
ncam = len(self.saved_camera_positions)
camera_position = self.camera_position[:] # py2.7 copy compatibility
def load_camera_position():
self.camera_position = camera_position
self.saved_camera_menu.addAction('Camera Position %2d' % ncam,
load_camera_position) | python | def save_camera_position(self):
self.saved_camera_positions.append(self.camera_position)
ncam = len(self.saved_camera_positions)
camera_position = self.camera_position[:] # py2.7 copy compatibility
def load_camera_position():
self.camera_position = camera_position
self.saved_camera_menu.addAction('Camera Position %2d' % ncam,
load_camera_position) | [
"def",
"save_camera_position",
"(",
"self",
")",
":",
"self",
".",
"saved_camera_positions",
".",
"append",
"(",
"self",
".",
"camera_position",
")",
"ncam",
"=",
"len",
"(",
"self",
".",
"saved_camera_positions",
")",
"camera_position",
"=",
"self",
".",
"cam... | Saves camera position to saved camera menu for recall | [
"Saves",
"camera",
"position",
"to",
"saved",
"camera",
"menu",
"for",
"recall"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L427-L437 |
236,580 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter._spawn_background_rendering | def _spawn_background_rendering(self, rate=5.0):
"""
Spawns a thread that updates the render window.
Sometimes directly modifiying object data doesn't trigger
Modified() and upstream objects won't be updated. This
ensures the render window stays updated without consuming too
many resources.
"""
self.render_trigger.connect(self.ren_win.Render)
twait = rate**-1
def render():
while self.active:
time.sleep(twait)
self._render()
self.render_thread = Thread(target=render)
self.render_thread.start() | python | def _spawn_background_rendering(self, rate=5.0):
self.render_trigger.connect(self.ren_win.Render)
twait = rate**-1
def render():
while self.active:
time.sleep(twait)
self._render()
self.render_thread = Thread(target=render)
self.render_thread.start() | [
"def",
"_spawn_background_rendering",
"(",
"self",
",",
"rate",
"=",
"5.0",
")",
":",
"self",
".",
"render_trigger",
".",
"connect",
"(",
"self",
".",
"ren_win",
".",
"Render",
")",
"twait",
"=",
"rate",
"**",
"-",
"1",
"def",
"render",
"(",
")",
":",
... | Spawns a thread that updates the render window.
Sometimes directly modifiying object data doesn't trigger
Modified() and upstream objects won't be updated. This
ensures the render window stays updated without consuming too
many resources. | [
"Spawns",
"a",
"thread",
"that",
"updates",
"the",
"render",
"window",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L439-L457 |
236,581 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.update_app_icon | def update_app_icon(self):
"""
Update the app icon if the user is not trying to resize the window.
"""
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.time()
if self._last_window_size != self.window_size: # pragma: no cover
# Window size hasn't remained constant since last render.
# This means the user is resizing it so ignore update.
pass
elif ((cur_time - self._last_update_time > BackgroundPlotter.ICON_TIME_STEP)
and self._last_camera_pos != self.camera_position):
# its been a while since last update OR
# the camera position has changed and its been at leat one second
# Update app icon as preview of the window
img = pad_image(self.image)
qimage = QtGui.QImage(img.copy(), img.shape[1],
img.shape[0], QtGui.QImage.Format_RGB888)
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
self.app.setWindowIcon(icon)
# Update trackers
self._last_update_time = cur_time
self._last_camera_pos = self.camera_position
# Update trackers
self._last_window_size = self.window_size | python | def update_app_icon(self):
if os.name == 'nt' or not hasattr(self, '_last_window_size'): # pragma: no cover
# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS
return
cur_time = time.time()
if self._last_window_size != self.window_size: # pragma: no cover
# Window size hasn't remained constant since last render.
# This means the user is resizing it so ignore update.
pass
elif ((cur_time - self._last_update_time > BackgroundPlotter.ICON_TIME_STEP)
and self._last_camera_pos != self.camera_position):
# its been a while since last update OR
# the camera position has changed and its been at leat one second
# Update app icon as preview of the window
img = pad_image(self.image)
qimage = QtGui.QImage(img.copy(), img.shape[1],
img.shape[0], QtGui.QImage.Format_RGB888)
icon = QtGui.QIcon(QtGui.QPixmap.fromImage(qimage))
self.app.setWindowIcon(icon)
# Update trackers
self._last_update_time = cur_time
self._last_camera_pos = self.camera_position
# Update trackers
self._last_window_size = self.window_size | [
"def",
"update_app_icon",
"(",
"self",
")",
":",
"if",
"os",
".",
"name",
"==",
"'nt'",
"or",
"not",
"hasattr",
"(",
"self",
",",
"'_last_window_size'",
")",
":",
"# pragma: no cover",
"# DO NOT EVEN ATTEMPT TO UPDATE ICON ON WINDOWS",
"return",
"cur_time",
"=",
"... | Update the app icon if the user is not trying to resize the window. | [
"Update",
"the",
"app",
"icon",
"if",
"the",
"user",
"is",
"not",
"trying",
"to",
"resize",
"the",
"window",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L472-L501 |
236,582 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter._qt_export_vtkjs | def _qt_export_vtkjs(self, show=True):
"""
Spawn an save file dialog to export a vtkjs file.
"""
return FileDialog(self.app_window,
filefilter=['VTK JS File(*.vtkjs)'],
show=show,
directory=os.getcwd(),
callback=self.export_vtkjs) | python | def _qt_export_vtkjs(self, show=True):
return FileDialog(self.app_window,
filefilter=['VTK JS File(*.vtkjs)'],
show=show,
directory=os.getcwd(),
callback=self.export_vtkjs) | [
"def",
"_qt_export_vtkjs",
"(",
"self",
",",
"show",
"=",
"True",
")",
":",
"return",
"FileDialog",
"(",
"self",
".",
"app_window",
",",
"filefilter",
"=",
"[",
"'VTK JS File(*.vtkjs)'",
"]",
",",
"show",
"=",
"show",
",",
"directory",
"=",
"os",
".",
"g... | Spawn an save file dialog to export a vtkjs file. | [
"Spawn",
"an",
"save",
"file",
"dialog",
"to",
"export",
"a",
"vtkjs",
"file",
"."
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L511-L519 |
236,583 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.window_size | def window_size(self):
""" returns render window size """
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | python | def window_size(self):
the_size = self.app_window.baseSize()
return the_size.width(), the_size.height() | [
"def",
"window_size",
"(",
"self",
")",
":",
"the_size",
"=",
"self",
".",
"app_window",
".",
"baseSize",
"(",
")",
"return",
"the_size",
".",
"width",
"(",
")",
",",
"the_size",
".",
"height",
"(",
")"
] | returns render window size | [
"returns",
"render",
"window",
"size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L532-L535 |
236,584 | vtkiorg/vtki | vtki/qt_plotting.py | BackgroundPlotter.window_size | def window_size(self, window_size):
""" set the render window size """
BasePlotter.window_size.fset(self, window_size)
self.app_window.setBaseSize(*window_size) | python | def window_size(self, window_size):
BasePlotter.window_size.fset(self, window_size)
self.app_window.setBaseSize(*window_size) | [
"def",
"window_size",
"(",
"self",
",",
"window_size",
")",
":",
"BasePlotter",
".",
"window_size",
".",
"fset",
"(",
"self",
",",
"window_size",
")",
"self",
".",
"app_window",
".",
"setBaseSize",
"(",
"*",
"window_size",
")"
] | set the render window size | [
"set",
"the",
"render",
"window",
"size"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/qt_plotting.py#L539-L542 |
236,585 | vtkiorg/vtki | vtki/colors.py | hex_to_rgb | def hex_to_rgb(h):
""" Returns 0 to 1 rgb from a hex list or tuple """
h = h.lstrip('#')
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4)) | python | def hex_to_rgb(h):
h = h.lstrip('#')
return tuple(int(h[i:i+2], 16)/255. for i in (0, 2 ,4)) | [
"def",
"hex_to_rgb",
"(",
"h",
")",
":",
"h",
"=",
"h",
".",
"lstrip",
"(",
"'#'",
")",
"return",
"tuple",
"(",
"int",
"(",
"h",
"[",
"i",
":",
"i",
"+",
"2",
"]",
",",
"16",
")",
"/",
"255.",
"for",
"i",
"in",
"(",
"0",
",",
"2",
",",
... | Returns 0 to 1 rgb from a hex list or tuple | [
"Returns",
"0",
"to",
"1",
"rgb",
"from",
"a",
"hex",
"list",
"or",
"tuple"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/colors.py#L321-L324 |
236,586 | vtkiorg/vtki | vtki/errors.py | set_error_output_file | def set_error_output_file(filename):
"""Sets a file to write out the VTK errors"""
filename = os.path.abspath(os.path.expanduser(filename))
fileOutputWindow = vtk.vtkFileOutputWindow()
fileOutputWindow.SetFileName(filename)
outputWindow = vtk.vtkOutputWindow()
outputWindow.SetInstance(fileOutputWindow)
return fileOutputWindow, outputWindow | python | def set_error_output_file(filename):
filename = os.path.abspath(os.path.expanduser(filename))
fileOutputWindow = vtk.vtkFileOutputWindow()
fileOutputWindow.SetFileName(filename)
outputWindow = vtk.vtkOutputWindow()
outputWindow.SetInstance(fileOutputWindow)
return fileOutputWindow, outputWindow | [
"def",
"set_error_output_file",
"(",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"filename",
")",
")",
"fileOutputWindow",
"=",
"vtk",
".",
"vtkFileOutputWindow",
"(",
")",
"file... | Sets a file to write out the VTK errors | [
"Sets",
"a",
"file",
"to",
"write",
"out",
"the",
"VTK",
"errors"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L8-L15 |
236,587 | vtkiorg/vtki | vtki/errors.py | Observer.log_message | def log_message(self, kind, alert):
"""Parses different event types and passes them to logging"""
if kind == 'ERROR':
logging.error(alert)
else:
logging.warning(alert)
return | python | def log_message(self, kind, alert):
if kind == 'ERROR':
logging.error(alert)
else:
logging.warning(alert)
return | [
"def",
"log_message",
"(",
"self",
",",
"kind",
",",
"alert",
")",
":",
"if",
"kind",
"==",
"'ERROR'",
":",
"logging",
".",
"error",
"(",
"alert",
")",
"else",
":",
"logging",
".",
"warning",
"(",
"alert",
")",
"return"
] | Parses different event types and passes them to logging | [
"Parses",
"different",
"event",
"types",
"and",
"passes",
"them",
"to",
"logging"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L40-L46 |
236,588 | vtkiorg/vtki | vtki/errors.py | Observer.observe | def observe(self, algorithm):
"""Make this an observer of an algorithm
"""
if self.__observing:
raise RuntimeError('This error observer is already observing an algorithm.')
if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
algorithm.GetExecutive().AddObserver(self.event_type, self)
algorithm.AddObserver(self.event_type, self)
self.__observing = True
return | python | def observe(self, algorithm):
if self.__observing:
raise RuntimeError('This error observer is already observing an algorithm.')
if hasattr(algorithm, 'GetExecutive') and algorithm.GetExecutive() is not None:
algorithm.GetExecutive().AddObserver(self.event_type, self)
algorithm.AddObserver(self.event_type, self)
self.__observing = True
return | [
"def",
"observe",
"(",
"self",
",",
"algorithm",
")",
":",
"if",
"self",
".",
"__observing",
":",
"raise",
"RuntimeError",
"(",
"'This error observer is already observing an algorithm.'",
")",
"if",
"hasattr",
"(",
"algorithm",
",",
"'GetExecutive'",
")",
"and",
"... | Make this an observer of an algorithm | [
"Make",
"this",
"an",
"observer",
"of",
"an",
"algorithm"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/errors.py#L75-L84 |
236,589 | vtkiorg/vtki | vtki/export.py | get_range_info | def get_range_info(array, component):
"""Get the data range of the array's component"""
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | python | def get_range_info(array, component):
r = array.GetRange(component)
comp_range = {}
comp_range['min'] = r[0]
comp_range['max'] = r[1]
comp_range['component'] = array.GetComponentName(component)
return comp_range | [
"def",
"get_range_info",
"(",
"array",
",",
"component",
")",
":",
"r",
"=",
"array",
".",
"GetRange",
"(",
"component",
")",
"comp_range",
"=",
"{",
"}",
"comp_range",
"[",
"'min'",
"]",
"=",
"r",
"[",
"0",
"]",
"comp_range",
"[",
"'max'",
"]",
"=",... | Get the data range of the array's component | [
"Get",
"the",
"data",
"range",
"of",
"the",
"array",
"s",
"component"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L78-L85 |
236,590 | vtkiorg/vtki | vtki/export.py | get_object_id | def get_object_id(obj):
"""Get object identifier"""
try:
idx = objIds.index(obj)
return idx + 1
except ValueError:
objIds.append(obj)
return len(objIds) | python | def get_object_id(obj):
try:
idx = objIds.index(obj)
return idx + 1
except ValueError:
objIds.append(obj)
return len(objIds) | [
"def",
"get_object_id",
"(",
"obj",
")",
":",
"try",
":",
"idx",
"=",
"objIds",
".",
"index",
"(",
"obj",
")",
"return",
"idx",
"+",
"1",
"except",
"ValueError",
":",
"objIds",
".",
"append",
"(",
"obj",
")",
"return",
"len",
"(",
"objIds",
")"
] | Get object identifier | [
"Get",
"object",
"identifier"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L104-L111 |
236,591 | vtkiorg/vtki | vtki/export.py | dump_data_array | def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
"""Dump vtkjs data arry"""
if root is None:
root = {}
if not array:
return None
if array.GetDataType() == 12:
# IdType need to be converted to Uint32
array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
new_array = vtk.vtkTypeUInt32Array()
new_array.SetNumberOfTuples(array_size)
for i in range(array_size):
new_array.SetValue(i, -1 if array.GetValue(i) <
0 else array.GetValue(i))
pbuffer = memoryview(new_array)
else:
pbuffer = memoryview(array)
pMd5 = hashlib.md5(pbuffer).hexdigest()
ppath = os.path.join(data_dir, pMd5)
with open(ppath, 'wb') as f:
f.write(pbuffer)
if compress:
with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Close then remove.
os.remove(ppath)
root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
root['vtkClass'] = 'vtkDataArray'
root['name'] = array.GetName()
root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
root['numberOfComponents'] = array.GetNumberOfComponents()
root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
root['ranges'] = []
if root['numberOfComponents'] > 1:
for i in range(root['numberOfComponents']):
root['ranges'].append(get_range_info(array, i))
root['ranges'].append(get_range_info(array, -1))
else:
root['ranges'].append(get_range_info(array, 0))
return root | python | def dump_data_array(dataset_dir, data_dir, array, root=None, compress=True):
if root is None:
root = {}
if not array:
return None
if array.GetDataType() == 12:
# IdType need to be converted to Uint32
array_size = array.GetNumberOfTuples() * array.GetNumberOfComponents()
new_array = vtk.vtkTypeUInt32Array()
new_array.SetNumberOfTuples(array_size)
for i in range(array_size):
new_array.SetValue(i, -1 if array.GetValue(i) <
0 else array.GetValue(i))
pbuffer = memoryview(new_array)
else:
pbuffer = memoryview(array)
pMd5 = hashlib.md5(pbuffer).hexdigest()
ppath = os.path.join(data_dir, pMd5)
with open(ppath, 'wb') as f:
f.write(pbuffer)
if compress:
with open(ppath, 'rb') as f_in, gzip.open(os.path.join(data_dir, pMd5 + '.gz'), 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
# Close then remove.
os.remove(ppath)
root['ref'] = get_ref(os.path.relpath(data_dir, dataset_dir), pMd5)
root['vtkClass'] = 'vtkDataArray'
root['name'] = array.GetName()
root['dataType'] = jsMapping[arrayTypesMapping[array.GetDataType()]]
root['numberOfComponents'] = array.GetNumberOfComponents()
root['size'] = array.GetNumberOfComponents() * array.GetNumberOfTuples()
root['ranges'] = []
if root['numberOfComponents'] > 1:
for i in range(root['numberOfComponents']):
root['ranges'].append(get_range_info(array, i))
root['ranges'].append(get_range_info(array, -1))
else:
root['ranges'].append(get_range_info(array, 0))
return root | [
"def",
"dump_data_array",
"(",
"dataset_dir",
",",
"data_dir",
",",
"array",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"if",
"not",
"array",
":",
"return",
"None",
"if",
... | Dump vtkjs data arry | [
"Dump",
"vtkjs",
"data",
"arry"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L116-L160 |
236,592 | vtkiorg/vtki | vtki/export.py | dump_color_array | def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
"""Dump vtkjs color array"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
colorArray = color_array_info['colorArray']
location = color_array_info['location']
dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)
if dumped_array:
root[location]['activeScalars'] = 0
root[location]['arrays'].append({'data': dumped_array})
return root | python | def dump_color_array(dataset_dir, data_dir, color_array_info, root=None, compress=True):
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
colorArray = color_array_info['colorArray']
location = color_array_info['location']
dumped_array = dump_data_array(dataset_dir, data_dir, colorArray, {}, compress)
if dumped_array:
root[location]['activeScalars'] = 0
root[location]['arrays'].append({'data': dumped_array})
return root | [
"def",
"dump_color_array",
"(",
"dataset_dir",
",",
"data_dir",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'pointData'",
"]",
"=",
"{"... | Dump vtkjs color array | [
"Dump",
"vtkjs",
"color",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L165-L212 |
236,593 | vtkiorg/vtki | vtki/export.py | dump_t_coords | def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs texture coordinates"""
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | python | def dump_t_coords(dataset_dir, data_dir, dataset, root=None, compress=True):
if root is None:
root = {}
tcoords = dataset.GetPointData().GetTCoords()
if tcoords:
dumped_array = dump_data_array(dataset_dir, data_dir, tcoords, {}, compress)
root['pointData']['activeTCoords'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | [
"def",
"dump_t_coords",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"tcoords",
"=",
"dataset",
".",
"GetPointData",
"(",
... | dump vtkjs texture coordinates | [
"dump",
"vtkjs",
"texture",
"coordinates"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L217-L225 |
236,594 | vtkiorg/vtki | vtki/export.py | dump_normals | def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
"""dump vtkjs normal vectors"""
if root is None:
root = {}
normals = dataset.GetPointData().GetNormals()
if normals:
dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | python | def dump_normals(dataset_dir, data_dir, dataset, root=None, compress=True):
if root is None:
root = {}
normals = dataset.GetPointData().GetNormals()
if normals:
dumped_array = dump_data_array(dataset_dir, data_dir, normals, {}, compress)
root['pointData']['activeNormals'] = len(root['pointData']['arrays'])
root['pointData']['arrays'].append({'data': dumped_array}) | [
"def",
"dump_normals",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"normals",
"=",
"dataset",
".",
"GetPointData",
"(",
... | dump vtkjs normal vectors | [
"dump",
"vtkjs",
"normal",
"vectors"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L230-L238 |
236,595 | vtkiorg/vtki | vtki/export.py | dump_all_arrays | def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
"""Dump all data arrays to vtkjs"""
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
# Point data
pd = dataset.GetPointData()
pd_size = pd.GetNumberOfArrays()
for i in range(pd_size):
array = pd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['pointData']['activeScalars'] = 0
root['pointData']['arrays'].append({'data': dumped_array})
# Cell data
cd = dataset.GetCellData()
cd_size = pd.GetNumberOfArrays()
for i in range(cd_size):
array = cd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['cellData']['activeScalars'] = 0
root['cellData']['arrays'].append({'data': dumped_array})
return root | python | def dump_all_arrays(dataset_dir, data_dir, dataset, root=None, compress=True):
if root is None:
root = {}
root['pointData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['cellData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
root['fieldData'] = {
'vtkClass': 'vtkDataSetAttributes',
"activeGlobalIds": -1,
"activeNormals": -1,
"activePedigreeIds": -1,
"activeScalars": -1,
"activeTCoords": -1,
"activeTensors": -1,
"activeVectors": -1,
"arrays": []
}
# Point data
pd = dataset.GetPointData()
pd_size = pd.GetNumberOfArrays()
for i in range(pd_size):
array = pd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['pointData']['activeScalars'] = 0
root['pointData']['arrays'].append({'data': dumped_array})
# Cell data
cd = dataset.GetCellData()
cd_size = pd.GetNumberOfArrays()
for i in range(cd_size):
array = cd.GetArray(i)
if array:
dumped_array = dump_data_array(
dataset_dir, data_dir, array, {}, compress)
root['cellData']['activeScalars'] = 0
root['cellData']['arrays'].append({'data': dumped_array})
return root | [
"def",
"dump_all_arrays",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'pointData'",
"]",
"=",
"{",
"'vtkC... | Dump all data arrays to vtkjs | [
"Dump",
"all",
"data",
"arrays",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L243-L303 |
236,596 | vtkiorg/vtki | vtki/export.py | dump_poly_data | def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump poly data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkPolyData'
container = root
# Points
points = dump_data_array(dataset_dir, data_dir,
dataset.GetPoints().GetData(), {}, compress)
points['vtkClass'] = 'vtkPoints'
container['points'] = points
# Cells
_cells = container
# Verts
if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
_verts = dump_data_array(dataset_dir, data_dir,
dataset.GetVerts().GetData(), {}, compress)
_cells['verts'] = _verts
_cells['verts']['vtkClass'] = 'vtkCellArray'
# Lines
if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
_lines = dump_data_array(dataset_dir, data_dir,
dataset.GetLines().GetData(), {}, compress)
_cells['lines'] = _lines
_cells['lines']['vtkClass'] = 'vtkCellArray'
# Polys
if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
_polys = dump_data_array(dataset_dir, data_dir,
dataset.GetPolys().GetData(), {}, compress)
_cells['polys'] = _polys
_cells['polys']['vtkClass'] = 'vtkCellArray'
# Strips
if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
_strips = dump_data_array(dataset_dir, data_dir,
dataset.GetStrips().GetData(), {}, compress)
_cells['strips'] = _strips
_cells['strips']['vtkClass'] = 'vtkCellArray'
dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)
# PointData TCoords
dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
# dump_normals(dataset_dir, data_dir, dataset, container, compress)
return root | python | def dump_poly_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
if root is None:
root = {}
root['vtkClass'] = 'vtkPolyData'
container = root
# Points
points = dump_data_array(dataset_dir, data_dir,
dataset.GetPoints().GetData(), {}, compress)
points['vtkClass'] = 'vtkPoints'
container['points'] = points
# Cells
_cells = container
# Verts
if dataset.GetVerts() and dataset.GetVerts().GetData().GetNumberOfTuples() > 0:
_verts = dump_data_array(dataset_dir, data_dir,
dataset.GetVerts().GetData(), {}, compress)
_cells['verts'] = _verts
_cells['verts']['vtkClass'] = 'vtkCellArray'
# Lines
if dataset.GetLines() and dataset.GetLines().GetData().GetNumberOfTuples() > 0:
_lines = dump_data_array(dataset_dir, data_dir,
dataset.GetLines().GetData(), {}, compress)
_cells['lines'] = _lines
_cells['lines']['vtkClass'] = 'vtkCellArray'
# Polys
if dataset.GetPolys() and dataset.GetPolys().GetData().GetNumberOfTuples() > 0:
_polys = dump_data_array(dataset_dir, data_dir,
dataset.GetPolys().GetData(), {}, compress)
_cells['polys'] = _polys
_cells['polys']['vtkClass'] = 'vtkCellArray'
# Strips
if dataset.GetStrips() and dataset.GetStrips().GetData().GetNumberOfTuples() > 0:
_strips = dump_data_array(dataset_dir, data_dir,
dataset.GetStrips().GetData(), {}, compress)
_cells['strips'] = _strips
_cells['strips']['vtkClass'] = 'vtkCellArray'
dump_color_array(dataset_dir, data_dir, color_array_info, container, compress)
# PointData TCoords
dump_t_coords(dataset_dir, data_dir, dataset, container, compress)
# dump_normals(dataset_dir, data_dir, dataset, container, compress)
return root | [
"def",
"dump_poly_data",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'vtkClass'",
... | Dump poly data object to vtkjs | [
"Dump",
"poly",
"data",
"object",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L308-L358 |
236,597 | vtkiorg/vtki | vtki/export.py | dump_image_data | def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
"""Dump image data object to vtkjs"""
if root is None:
root = {}
root['vtkClass'] = 'vtkImageData'
container = root
container['spacing'] = dataset.GetSpacing()
container['origin'] = dataset.GetOrigin()
container['extent'] = dataset.GetExtent()
dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)
return root | python | def dump_image_data(dataset_dir, data_dir, dataset, color_array_info, root=None, compress=True):
if root is None:
root = {}
root['vtkClass'] = 'vtkImageData'
container = root
container['spacing'] = dataset.GetSpacing()
container['origin'] = dataset.GetOrigin()
container['extent'] = dataset.GetExtent()
dump_all_arrays(dataset_dir, data_dir, dataset, container, compress)
return root | [
"def",
"dump_image_data",
"(",
"dataset_dir",
",",
"data_dir",
",",
"dataset",
",",
"color_array_info",
",",
"root",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"{",
"}",
"root",
"[",
"'vtkClass'",
... | Dump image data object to vtkjs | [
"Dump",
"image",
"data",
"object",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L366-L379 |
236,598 | vtkiorg/vtki | vtki/export.py | write_data_set | def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
"""write dataset to vtkjs"""
fileName = new_name if new_name else os.path.basename(file_path)
dataset_dir = os.path.join(output_dir, fileName)
data_dir = os.path.join(dataset_dir, 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
root = {}
root['metadata'] = {}
root['metadata']['name'] = fileName
writer = writer_mapping[dataset.GetClassName()]
if writer:
writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
else:
print(dataObject.GetClassName(), 'is not supported')
with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
f.write(json.dumps(root, indent=2))
return dataset_dir | python | def write_data_set(file_path, dataset, output_dir, color_array_info, new_name=None, compress=True):
fileName = new_name if new_name else os.path.basename(file_path)
dataset_dir = os.path.join(output_dir, fileName)
data_dir = os.path.join(dataset_dir, 'data')
if not os.path.exists(data_dir):
os.makedirs(data_dir)
root = {}
root['metadata'] = {}
root['metadata']['name'] = fileName
writer = writer_mapping[dataset.GetClassName()]
if writer:
writer(dataset_dir, data_dir, dataset, color_array_info, root, compress)
else:
print(dataObject.GetClassName(), 'is not supported')
with open(os.path.join(dataset_dir, "index.json"), 'w') as f:
f.write(json.dumps(root, indent=2))
return dataset_dir | [
"def",
"write_data_set",
"(",
"file_path",
",",
"dataset",
",",
"output_dir",
",",
"color_array_info",
",",
"new_name",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"fileName",
"=",
"new_name",
"if",
"new_name",
"else",
"os",
".",
"path",
".",
"bas... | write dataset to vtkjs | [
"write",
"dataset",
"to",
"vtkjs"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/export.py#L387-L409 |
236,599 | vtkiorg/vtki | vtki/common.py | Common.active_vectors | def active_vectors(self):
"""The active vectors array"""
field, name = self.active_vectors_info
if name:
if field is POINT_DATA_FIELD:
return self.point_arrays[name]
if field is CELL_DATA_FIELD:
return self.cell_arrays[name] | python | def active_vectors(self):
field, name = self.active_vectors_info
if name:
if field is POINT_DATA_FIELD:
return self.point_arrays[name]
if field is CELL_DATA_FIELD:
return self.cell_arrays[name] | [
"def",
"active_vectors",
"(",
"self",
")",
":",
"field",
",",
"name",
"=",
"self",
".",
"active_vectors_info",
"if",
"name",
":",
"if",
"field",
"is",
"POINT_DATA_FIELD",
":",
"return",
"self",
".",
"point_arrays",
"[",
"name",
"]",
"if",
"field",
"is",
... | The active vectors array | [
"The",
"active",
"vectors",
"array"
] | 5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1 | https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/common.py#L81-L88 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.