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
75
19.8k
code_tokens
listlengths
20
707
docstring
stringlengths
3
17.3k
docstring_tokens
listlengths
3
222
sha
stringlengths
40
40
url
stringlengths
87
242
partition
stringclasses
1 value
idx
int64
0
252k
vtkiorg/vtki
vtki/plotting.py
plot
def plot(var_item, off_screen=None, full_screen=False, screenshot=None, interactive=True, cpos=None, window_size=None, show_bounds=False, show_axes=True, notebook=None, background=None, text='', return_img=False, eye_dome_lighting=False, use_panel=None, **kwargs): """ Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. 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 Returned only when screenshot enabled """ if notebook is None: if run_from_ipython(): try: notebook = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass if notebook: off_screen = notebook plotter = Plotter(off_screen=off_screen, notebook=notebook) if show_axes: plotter.add_axes() plotter.set_background(background) if isinstance(var_item, list): if len(var_item) == 2: # might be arrows isarr_0 = isinstance(var_item[0], np.ndarray) isarr_1 = isinstance(var_item[1], np.ndarray) if isarr_0 and isarr_1: plotter.add_arrows(var_item[0], var_item[1]) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: plotter.add_mesh(var_item, **kwargs) if text: plotter.add_text(text) if show_bounds or kwargs.get('show_grid', False): if kwargs.get('show_grid', False): plotter.show_grid() else: plotter.show_bounds() if cpos is None: cpos = plotter.get_default_cam_pos() plotter.camera_position = cpos plotter.camera_set = False else: plotter.camera_position = cpos if eye_dome_lighting: plotter.enable_eye_dome_lighting() result = plotter.show(window_size=window_size, auto_close=False, interactive=interactive, full_screen=full_screen, screenshot=screenshot, return_img=return_img, use_panel=use_panel) # close and return camera position and maybe image plotter.close() # Result will be handled by plotter.show(): cpos or [cpos, img] return result
python
def plot(var_item, off_screen=None, full_screen=False, screenshot=None, interactive=True, cpos=None, window_size=None, show_bounds=False, show_axes=True, notebook=None, background=None, text='', return_img=False, eye_dome_lighting=False, use_panel=None, **kwargs): """ Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. 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 Returned only when screenshot enabled """ if notebook is None: if run_from_ipython(): try: notebook = type(get_ipython()).__module__.startswith('ipykernel.') except NameError: pass if notebook: off_screen = notebook plotter = Plotter(off_screen=off_screen, notebook=notebook) if show_axes: plotter.add_axes() plotter.set_background(background) if isinstance(var_item, list): if len(var_item) == 2: # might be arrows isarr_0 = isinstance(var_item[0], np.ndarray) isarr_1 = isinstance(var_item[1], np.ndarray) if isarr_0 and isarr_1: plotter.add_arrows(var_item[0], var_item[1]) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: for item in var_item: plotter.add_mesh(item, **kwargs) else: plotter.add_mesh(var_item, **kwargs) if text: plotter.add_text(text) if show_bounds or kwargs.get('show_grid', False): if kwargs.get('show_grid', False): plotter.show_grid() else: plotter.show_bounds() if cpos is None: cpos = plotter.get_default_cam_pos() plotter.camera_position = cpos plotter.camera_set = False else: plotter.camera_position = cpos if eye_dome_lighting: plotter.enable_eye_dome_lighting() result = plotter.show(window_size=window_size, auto_close=False, interactive=interactive, full_screen=full_screen, screenshot=screenshot, return_img=return_img, use_panel=use_panel) # close and return camera position and maybe image plotter.close() # Result will be handled by plotter.show(): cpos or [cpos, img] return result
[ "def", "plot", "(", "var_item", ",", "off_screen", "=", "None", ",", "full_screen", "=", "False", ",", "screenshot", "=", "None", ",", "interactive", "=", "True", ",", "cpos", "=", "None", ",", "window_size", "=", "None", ",", "show_bounds", "=", "False"...
Convenience plotting function for a vtk or numpy object. Parameters ---------- item : vtk or numpy object VTK object or numpy array to be plotted. off_screen : bool Plots off screen when True. Helpful for saving screenshots without a window popping up. full_screen : bool, optional Opens window in full screen. When enabled, ignores window_size. Default False. screenshot : str or bool, optional Saves screenshot to file when enabled. See: help(vtkinterface.Plotter.screenshot). Default disabled. When True, takes screenshot and returns numpy array of image. window_size : list, optional Window size in pixels. Defaults to [1024, 768] show_bounds : bool, optional Shows mesh bounds when True. Default False. Alias ``show_grid`` also accepted. notebook : bool, optional When True, the resulting plot is placed inline a jupyter notebook. Assumes a jupyter console is active. show_axes : bool, optional Shows a vtk axes widget. Enabled by default. text : str, optional Adds text at the bottom of the plot. **kwargs : optional keyword arguments See help(Plotter.add_mesh) for additional options. Returns ------- cpos : list List of camera position, focal point, and view up. 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 Returned only when screenshot enabled
[ "Convenience", "plotting", "function", "for", "a", "vtk", "or", "numpy", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L140-L260
train
217,500
vtkiorg/vtki
vtki/plotting.py
system_supports_plotting
def system_supports_plotting(): """ Check if x server is running Returns ------- system_supports_plotting : bool True when on Linux and running an xserver. Returns None when on a non-linux platform. """ try: if os.environ['ALLOW_PLOTTING'].lower() == 'true': return True except KeyError: pass try: p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 except: return False
python
def system_supports_plotting(): """ Check if x server is running Returns ------- system_supports_plotting : bool True when on Linux and running an xserver. Returns None when on a non-linux platform. """ try: if os.environ['ALLOW_PLOTTING'].lower() == 'true': return True except KeyError: pass try: p = Popen(["xset", "-q"], stdout=PIPE, stderr=PIPE) p.communicate() return p.returncode == 0 except: return False
[ "def", "system_supports_plotting", "(", ")", ":", "try", ":", "if", "os", ".", "environ", "[", "'ALLOW_PLOTTING'", "]", ".", "lower", "(", ")", "==", "'true'", ":", "return", "True", "except", "KeyError", ":", "pass", "try", ":", "p", "=", "Popen", "("...
Check if x server is running Returns ------- system_supports_plotting : bool True when on Linux and running an xserver. Returns None when on a non-linux platform.
[ "Check", "if", "x", "server", "is", "running" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L287-L308
train
217,501
vtkiorg/vtki
vtki/plotting.py
single_triangle
def single_triangle(): """ A single PolyData triangle """ points = np.zeros((3, 3)) points[1] = [1, 0, 0] points[2] = [0.5, 0.707, 0] cells = np.array([[3, 0, 1, 2]], ctypes.c_long) return vtki.PolyData(points, cells)
python
def single_triangle(): """ A single PolyData triangle """ points = np.zeros((3, 3)) points[1] = [1, 0, 0] points[2] = [0.5, 0.707, 0] cells = np.array([[3, 0, 1, 2]], ctypes.c_long) return vtki.PolyData(points, cells)
[ "def", "single_triangle", "(", ")", ":", "points", "=", "np", ".", "zeros", "(", "(", "3", ",", "3", ")", ")", "points", "[", "1", "]", "=", "[", "1", ",", "0", ",", "0", "]", "points", "[", "2", "]", "=", "[", "0.5", ",", "0.707", ",", "...
A single PolyData triangle
[ "A", "single", "PolyData", "triangle" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2970-L2976
train
217,502
vtkiorg/vtki
vtki/plotting.py
parse_color
def parse_color(color): """ Parses color into a vtk friendly rgb list """ if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input Must ba string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF'""")
python
def parse_color(color): """ Parses color into a vtk friendly rgb list """ if color is None: color = rcParams['color'] if isinstance(color, str): return vtki.string_to_rgb(color) elif len(color) == 3: return color else: raise Exception(""" Invalid color input Must ba string, rgb list, or hex color string. For example: color='white' color='w' color=[1, 1, 1] color='#FFFFFF'""")
[ "def", "parse_color", "(", "color", ")", ":", "if", "color", "is", "None", ":", "color", "=", "rcParams", "[", "'color'", "]", "if", "isinstance", "(", "color", ",", "str", ")", ":", "return", "vtki", ".", "string_to_rgb", "(", "color", ")", "elif", ...
Parses color into a vtk friendly rgb list
[ "Parses", "color", "into", "a", "vtk", "friendly", "rgb", "list" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2979-L2994
train
217,503
vtkiorg/vtki
vtki/plotting.py
plot_compare_four
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None, plotter_kwargs=None, show_kwargs=None, screenshot=None, camera_position=None, outline=None, outline_color='k', labels=('A', 'B', 'C', 'D')): """Plot a 2 by 2 comparison of data objects. Plotting parameters and camera positions will all be the same. """ datasets = [[data_a, data_b], [data_c, data_d]] labels = [labels[0:2], labels[2:4]] if plotter_kwargs is None: plotter_kwargs = {} if disply_kwargs is None: disply_kwargs = {} if show_kwargs is None: show_kwargs = {} p = vtki.Plotter(shape=(2,2), **plotter_kwargs) for i in range(2): for j in range(2): p.subplot(i, j) p.add_mesh(datasets[i][j], **disply_kwargs) p.add_text(labels[i][j]) if is_vtki_obj(outline): p.add_mesh(outline, color=outline_color) if camera_position is not None: p.camera_position = camera_position return p.show(screenshot=screenshot, **show_kwargs)
python
def plot_compare_four(data_a, data_b, data_c, data_d, disply_kwargs=None, plotter_kwargs=None, show_kwargs=None, screenshot=None, camera_position=None, outline=None, outline_color='k', labels=('A', 'B', 'C', 'D')): """Plot a 2 by 2 comparison of data objects. Plotting parameters and camera positions will all be the same. """ datasets = [[data_a, data_b], [data_c, data_d]] labels = [labels[0:2], labels[2:4]] if plotter_kwargs is None: plotter_kwargs = {} if disply_kwargs is None: disply_kwargs = {} if show_kwargs is None: show_kwargs = {} p = vtki.Plotter(shape=(2,2), **plotter_kwargs) for i in range(2): for j in range(2): p.subplot(i, j) p.add_mesh(datasets[i][j], **disply_kwargs) p.add_text(labels[i][j]) if is_vtki_obj(outline): p.add_mesh(outline, color=outline_color) if camera_position is not None: p.camera_position = camera_position return p.show(screenshot=screenshot, **show_kwargs)
[ "def", "plot_compare_four", "(", "data_a", ",", "data_b", ",", "data_c", ",", "data_d", ",", "disply_kwargs", "=", "None", ",", "plotter_kwargs", "=", "None", ",", "show_kwargs", "=", "None", ",", "screenshot", "=", "None", ",", "camera_position", "=", "None...
Plot a 2 by 2 comparison of data objects. Plotting parameters and camera positions will all be the same.
[ "Plot", "a", "2", "by", "2", "comparison", "of", "data", "objects", ".", "Plotting", "parameters", "and", "camera", "positions", "will", "all", "be", "the", "same", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L3008-L3037
train
217,504
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_focus
def set_focus(self, point): """ sets focus to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetFocalPoint(point) self._render()
python
def set_focus(self, point): """ sets focus to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetFocalPoint(point) self._render()
[ "def", "set_focus", "(", "self", ",", "point", ")", ":", "if", "isinstance", "(", "point", ",", "np", ".", "ndarray", ")", ":", "if", "point", ".", "ndim", "!=", "1", ":", "point", "=", "point", ".", "ravel", "(", ")", "self", ".", "camera", ".",...
sets focus to a point
[ "sets", "focus", "to", "a", "point" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L480-L486
train
217,505
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_position
def set_position(self, point, reset=False): """ sets camera position to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetPosition(point) if reset: self.reset_camera() self.camera_set = True self._render()
python
def set_position(self, point, reset=False): """ sets camera position to a point """ if isinstance(point, np.ndarray): if point.ndim != 1: point = point.ravel() self.camera.SetPosition(point) if reset: self.reset_camera() self.camera_set = True self._render()
[ "def", "set_position", "(", "self", ",", "point", ",", "reset", "=", "False", ")", ":", "if", "isinstance", "(", "point", ",", "np", ".", "ndarray", ")", ":", "if", "point", ".", "ndim", "!=", "1", ":", "point", "=", "point", ".", "ravel", "(", "...
sets camera position to a point
[ "sets", "camera", "position", "to", "a", "point" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L488-L497
train
217,506
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_viewup
def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
python
def set_viewup(self, vector): """ sets camera viewup vector """ if isinstance(vector, np.ndarray): if vector.ndim != 1: vector = vector.ravel() self.camera.SetViewUp(vector) self._render()
[ "def", "set_viewup", "(", "self", ",", "vector", ")", ":", "if", "isinstance", "(", "vector", ",", "np", ".", "ndarray", ")", ":", "if", "vector", ".", "ndim", "!=", "1", ":", "vector", "=", "vector", ".", "ravel", "(", ")", "self", ".", "camera", ...
sets camera viewup vector
[ "sets", "camera", "viewup", "vector" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L499-L505
train
217,507
vtkiorg/vtki
vtki/plotting.py
BasePlotter._render
def _render(self): """ redraws render window if the render window exists """ if hasattr(self, 'ren_win'): if hasattr(self, 'render_trigger'): self.render_trigger.emit() elif not self._first_time: self.render()
python
def _render(self): """ redraws render window if the render window exists """ if hasattr(self, 'ren_win'): if hasattr(self, 'render_trigger'): self.render_trigger.emit() elif not self._first_time: self.render()
[ "def", "_render", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'ren_win'", ")", ":", "if", "hasattr", "(", "self", ",", "'render_trigger'", ")", ":", "self", ".", "render_trigger", ".", "emit", "(", ")", "elif", "not", "self", ".", "_fi...
redraws render window if the render window exists
[ "redraws", "render", "window", "if", "the", "render", "window", "exists" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L507-L513
train
217,508
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_axes
def add_axes(self, interactive=None, color=None): """ Add an interactive axes widget """ if interactive is None: interactive = rcParams['interactive'] if hasattr(self, 'axes_widget'): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return self.axes_actor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(self.axes_actor) if hasattr(self, 'iren'): self.axes_widget.SetInteractor(self.iren) self.axes_widget.SetEnabled(1) self.axes_widget.SetInteractive(interactive) # Set the color self._update_axes_color(color)
python
def add_axes(self, interactive=None, color=None): """ Add an interactive axes widget """ if interactive is None: interactive = rcParams['interactive'] if hasattr(self, 'axes_widget'): self.axes_widget.SetInteractive(interactive) self._update_axes_color(color) return self.axes_actor = vtk.vtkAxesActor() self.axes_widget = vtk.vtkOrientationMarkerWidget() self.axes_widget.SetOrientationMarker(self.axes_actor) if hasattr(self, 'iren'): self.axes_widget.SetInteractor(self.iren) self.axes_widget.SetEnabled(1) self.axes_widget.SetInteractive(interactive) # Set the color self._update_axes_color(color)
[ "def", "add_axes", "(", "self", ",", "interactive", "=", "None", ",", "color", "=", "None", ")", ":", "if", "interactive", "is", "None", ":", "interactive", "=", "rcParams", "[", "'interactive'", "]", "if", "hasattr", "(", "self", ",", "'axes_widget'", "...
Add an interactive axes widget
[ "Add", "an", "interactive", "axes", "widget" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L515-L531
train
217,509
vtkiorg/vtki
vtki/plotting.py
BasePlotter.key_press_event
def key_press_event(self, obj, event): """ Listens for key press event """ key = self.iren.GetKeySym() log.debug('Key %s pressed' % key) if key == 'q': self.q_pressed = True # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) elif key == 'b': self.observer = self.iren.AddObserver('LeftButtonPressEvent', self.left_button_down) elif key == 'v': self.isometric_view_interactive()
python
def key_press_event(self, obj, event): """ Listens for key press event """ key = self.iren.GetKeySym() log.debug('Key %s pressed' % key) if key == 'q': self.q_pressed = True # Grab screenshot right before renderer closes self.last_image = self.screenshot(True, return_img=True) elif key == 'b': self.observer = self.iren.AddObserver('LeftButtonPressEvent', self.left_button_down) elif key == 'v': self.isometric_view_interactive()
[ "def", "key_press_event", "(", "self", ",", "obj", ",", "event", ")", ":", "key", "=", "self", ".", "iren", ".", "GetKeySym", "(", ")", "log", ".", "debug", "(", "'Key %s pressed'", "%", "key", ")", "if", "key", "==", "'q'", ":", "self", ".", "q_pr...
Listens for key press event
[ "Listens", "for", "key", "press", "event" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L545-L557
train
217,510
vtkiorg/vtki
vtki/plotting.py
BasePlotter.left_button_down
def left_button_down(self, obj, event_type): """Register the event for a left button down click""" # Get 2D click location on window click_pos = self.iren.GetEventPosition() # Get corresponding click location in the 3D plot picker = vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0
python
def left_button_down(self, obj, event_type): """Register the event for a left button down click""" # Get 2D click location on window click_pos = self.iren.GetEventPosition() # Get corresponding click location in the 3D plot picker = vtk.vtkWorldPointPicker() picker.Pick(click_pos[0], click_pos[1], 0, self.renderer) self.pickpoint = np.asarray(picker.GetPickPosition()).reshape((-1, 3)) if np.any(np.isnan(self.pickpoint)): self.pickpoint[:] = 0
[ "def", "left_button_down", "(", "self", ",", "obj", ",", "event_type", ")", ":", "# Get 2D click location on window", "click_pos", "=", "self", ".", "iren", ".", "GetEventPosition", "(", ")", "# Get corresponding click location in the 3D plot", "picker", "=", "vtk", "...
Register the event for a left button down click
[ "Register", "the", "event", "for", "a", "left", "button", "down", "click" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L559-L569
train
217,511
vtkiorg/vtki
vtki/plotting.py
BasePlotter.isometric_view_interactive
def isometric_view_interactive(self): """ sets the current interactive render window to isometric view """ interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric()
python
def isometric_view_interactive(self): """ sets the current interactive render window to isometric view """ interactor = self.iren.GetInteractorStyle() renderer = interactor.GetCurrentRenderer() renderer.view_isometric()
[ "def", "isometric_view_interactive", "(", "self", ")", ":", "interactor", "=", "self", ".", "iren", ".", "GetInteractorStyle", "(", ")", "renderer", "=", "interactor", ".", "GetCurrentRenderer", "(", ")", "renderer", ".", "view_isometric", "(", ")" ]
sets the current interactive render window to isometric view
[ "sets", "the", "current", "interactive", "render", "window", "to", "isometric", "view" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L571-L575
train
217,512
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update
def update(self, stime=1, force_redraw=True): """ Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if not hasattr(self, 'iren'): return update_rate = self.iren.GetDesiredUpdateRate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.CreateRepeatingTimer(stime) self.iren.Start() self.iren.DestroyTimer(self.right_timer_id) self._render() Plotter.last_update_time = curr_time else: if force_redraw: self.iren.Render()
python
def update(self, stime=1, force_redraw=True): """ Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately. """ if stime <= 0: stime = 1 curr_time = time.time() if Plotter.last_update_time > curr_time: Plotter.last_update_time = curr_time if not hasattr(self, 'iren'): return update_rate = self.iren.GetDesiredUpdateRate() if (curr_time - Plotter.last_update_time) > (1.0/update_rate): self.right_timer_id = self.iren.CreateRepeatingTimer(stime) self.iren.Start() self.iren.DestroyTimer(self.right_timer_id) self._render() Plotter.last_update_time = curr_time else: if force_redraw: self.iren.Render()
[ "def", "update", "(", "self", ",", "stime", "=", "1", ",", "force_redraw", "=", "True", ")", ":", "if", "stime", "<=", "0", ":", "stime", "=", "1", "curr_time", "=", "time", ".", "time", "(", ")", "if", "Plotter", ".", "last_update_time", ">", "cur...
Update window, redraw, process messages query Parameters ---------- stime : int, optional Duration of timer that interrupt vtkRenderWindowInteractor in milliseconds. force_redraw : bool, optional Call vtkRenderWindowInteractor.Render() immediately.
[ "Update", "window", "redraw", "process", "messages", "query" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L577-L612
train
217,513
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_scalar_bar_range
def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise RuntimeError('This plotter does not have an active mapper.') return self.mapper.SetScalarRange(*clim) # Use the name to find the desired actor def update_mapper(mapper): return mapper.SetScalarRange(*clim) try: for m in self._scalar_bar_mappers[name]: update_mapper(m) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return
python
def update_scalar_bar_range(self, clim, name=None): """Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update """ if isinstance(clim, float) or isinstance(clim, int): clim = [-clim, clim] if len(clim) != 2: raise TypeError('clim argument must be a length 2 iterable of values: (min, max).') if name is None: if not hasattr(self, 'mapper'): raise RuntimeError('This plotter does not have an active mapper.') return self.mapper.SetScalarRange(*clim) # Use the name to find the desired actor def update_mapper(mapper): return mapper.SetScalarRange(*clim) try: for m in self._scalar_bar_mappers[name]: update_mapper(m) except KeyError: raise KeyError('Name ({}) not valid/not found in this plotter.') return
[ "def", "update_scalar_bar_range", "(", "self", ",", "clim", ",", "name", "=", "None", ")", ":", "if", "isinstance", "(", "clim", ",", "float", ")", "or", "isinstance", "(", "clim", ",", "int", ")", ":", "clim", "=", "[", "-", "clim", ",", "clim", "...
Update the value range of the active or named scalar bar. Parameters ---------- 2 item list The new range of scalar bar. Example: ``[-1, 2]``. name : str, optional The title of the scalar bar to update
[ "Update", "the", "value", "range", "of", "the", "active", "or", "named", "scalar", "bar", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1087-L1114
train
217,514
vtkiorg/vtki
vtki/plotting.py
BasePlotter.clear
def clear(self): """ Clears plot by removing all actors and properties """ for renderer in self.renderers: renderer.RemoveAllViewProps() self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {}
python
def clear(self): """ Clears plot by removing all actors and properties """ for renderer in self.renderers: renderer.RemoveAllViewProps() self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} self._scalar_bar_actors = {} self._scalar_bar_widgets = {}
[ "def", "clear", "(", "self", ")", ":", "for", "renderer", "in", "self", ".", "renderers", ":", "renderer", ".", "RemoveAllViewProps", "(", ")", "self", ".", "_scalar_bar_slots", "=", "set", "(", "range", "(", "MAX_N_COLOR_BARS", ")", ")", "self", ".", "_...
Clears plot by removing all actors and properties
[ "Clears", "plot", "by", "removing", "all", "actors", "and", "properties" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1150-L1159
train
217,515
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_actor
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed. """ for renderer in self.renderers: renderer.remove_actor(actor, reset_camera) return True
python
def remove_actor(self, actor, reset_camera=False): """ Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed. """ for renderer in self.renderers: renderer.remove_actor(actor, reset_camera) return True
[ "def", "remove_actor", "(", "self", ",", "actor", ",", "reset_camera", "=", "False", ")", ":", "for", "renderer", "in", "self", ".", "renderers", ":", "renderer", ".", "remove_actor", "(", "actor", ",", "reset_camera", ")", "return", "True" ]
Removes an actor from the Plotter. Parameters ---------- actor : vtk.vtkActor Actor that has previously added to the Renderer. reset_camera : bool, optional Resets camera so all actors can be seen. Returns ------- success : bool True when actor removed. False when actor has not been removed.
[ "Removes", "an", "actor", "from", "the", "Plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1161-L1181
train
217,516
vtkiorg/vtki
vtki/plotting.py
BasePlotter.loc_to_index
def loc_to_index(self, loc): """ Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window. """ if loc is None: return self._active_renderer_index elif isinstance(loc, int): return loc elif isinstance(loc, collections.Iterable): assert len(loc) == 2, '"loc" must contain two items' return loc[0]*self.shape[0] + loc[1]
python
def loc_to_index(self, loc): """ Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window. """ if loc is None: return self._active_renderer_index elif isinstance(loc, int): return loc elif isinstance(loc, collections.Iterable): assert len(loc) == 2, '"loc" must contain two items' return loc[0]*self.shape[0] + loc[1]
[ "def", "loc_to_index", "(", "self", ",", "loc", ")", ":", "if", "loc", "is", "None", ":", "return", "self", ".", "_active_renderer_index", "elif", "isinstance", "(", "loc", ",", "int", ")", ":", "return", "loc", "elif", "isinstance", "(", "loc", ",", "...
Return index of the render window given a location index. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- idx : int Index of the render window.
[ "Return", "index", "of", "the", "render", "window", "given", "a", "location", "index", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1222-L1244
train
217,517
vtkiorg/vtki
vtki/plotting.py
BasePlotter.index_to_loc
def index_to_loc(self, index): """Convert a 1D index location to the 2D location on the plotting grid """ sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: raise RuntimeError('Index ({}) is out of range.') return args[0]
python
def index_to_loc(self, index): """Convert a 1D index location to the 2D location on the plotting grid """ sz = int(self.shape[0] * self.shape[1]) idxs = np.array([i for i in range(sz)], dtype=int).reshape(self.shape) args = np.argwhere(idxs == index) if len(args) < 1: raise RuntimeError('Index ({}) is out of range.') return args[0]
[ "def", "index_to_loc", "(", "self", ",", "index", ")", ":", "sz", "=", "int", "(", "self", ".", "shape", "[", "0", "]", "*", "self", ".", "shape", "[", "1", "]", ")", "idxs", "=", "np", ".", "array", "(", "[", "i", "for", "i", "in", "range", ...
Convert a 1D index location to the 2D location on the plotting grid
[ "Convert", "a", "1D", "index", "location", "to", "the", "2D", "location", "on", "the", "plotting", "grid" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1246-L1254
train
217,518
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_axes_at_origin
def add_axes_at_origin(self, loc=None): """ Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self._active_renderer_index = self.loc_to_index(loc) return self.renderers[self._active_renderer_index].add_axes_at_origin()
python
def add_axes_at_origin(self, loc=None): """ Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor """ self._active_renderer_index = self.loc_to_index(loc) return self.renderers[self._active_renderer_index].add_axes_at_origin()
[ "def", "add_axes_at_origin", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "return", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]", ".", ...
Add axes actor at the origin of a render window. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. When None, defaults to the active render window. Returns -------- marker_actor : vtk.vtkAxesActor vtkAxesActor actor
[ "Add", "axes", "actor", "at", "the", "origin", "of", "a", "render", "window", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1262-L1279
train
217,519
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_bounding_box
def remove_bounding_box(self, loc=None): """ Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounding_box()
python
def remove_bounding_box(self, loc=None): """ Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounding_box()
[ "def", "remove_bounding_box", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "renderer", "=", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]"...
Removes bounding box from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer.
[ "Removes", "bounding", "box", "from", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1460-L1473
train
217,520
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_bounds_axes
def remove_bounds_axes(self, loc=None): """ Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounds_axes()
python
def remove_bounds_axes(self, loc=None): """ Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer. """ self._active_renderer_index = self.loc_to_index(loc) renderer = self.renderers[self._active_renderer_index] renderer.remove_bounds_axes()
[ "def", "remove_bounds_axes", "(", "self", ",", "loc", "=", "None", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "loc", ")", "renderer", "=", "self", ".", "renderers", "[", "self", ".", "_active_renderer_index", "]",...
Removes bounds axes from the active renderer. Parameters ---------- loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. If None, selects the last active Renderer.
[ "Removes", "bounds", "axes", "from", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1475-L1488
train
217,521
vtkiorg/vtki
vtki/plotting.py
BasePlotter.subplot
def subplot(self, index_x, index_y): """ Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction. """ self._active_renderer_index = self.loc_to_index((index_x, index_y))
python
def subplot(self, index_x, index_y): """ Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction. """ self._active_renderer_index = self.loc_to_index((index_x, index_y))
[ "def", "subplot", "(", "self", ",", "index_x", ",", "index_y", ")", ":", "self", ".", "_active_renderer_index", "=", "self", ".", "loc_to_index", "(", "(", "index_x", ",", "index_y", ")", ")" ]
Sets the active subplot. Parameters ---------- index_x : int Index of the subplot to activate in the x direction. index_y : int Index of the subplot to activate in the y direction.
[ "Sets", "the", "active", "subplot", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1490-L1503
train
217,522
vtkiorg/vtki
vtki/plotting.py
BasePlotter.show_grid
def show_grid(self, **kwargs): """ A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function. """ kwargs.setdefault('grid', 'back') kwargs.setdefault('location', 'outer') kwargs.setdefault('ticks', 'both') return self.show_bounds(**kwargs)
python
def show_grid(self, **kwargs): """ A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function. """ kwargs.setdefault('grid', 'back') kwargs.setdefault('location', 'outer') kwargs.setdefault('ticks', 'both') return self.show_bounds(**kwargs)
[ "def", "show_grid", "(", "self", ",", "*", "*", "kwargs", ")", ":", "kwargs", ".", "setdefault", "(", "'grid'", ",", "'back'", ")", "kwargs", ".", "setdefault", "(", "'location'", ",", "'outer'", ")", "kwargs", ".", "setdefault", "(", "'ticks'", ",", "...
A wrapped implementation of ``show_bounds`` to change default behaviour to use gridlines and showing the axes labels on the outer edges. This is intended to be silimar to ``matplotlib``'s ``grid`` function.
[ "A", "wrapped", "implementation", "of", "show_bounds", "to", "change", "default", "behaviour", "to", "use", "gridlines", "and", "showing", "the", "axes", "labels", "on", "the", "outer", "edges", ".", "This", "is", "intended", "to", "be", "silimar", "to", "ma...
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1505-L1515
train
217,523
vtkiorg/vtki
vtki/plotting.py
BasePlotter.set_scale
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen. """ self.renderer.set_scale(xscale, yscale, zscale, reset_camera)
python
def set_scale(self, xscale=None, yscale=None, zscale=None, reset_camera=True): """ Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen. """ self.renderer.set_scale(xscale, yscale, zscale, reset_camera)
[ "def", "set_scale", "(", "self", ",", "xscale", "=", "None", ",", "yscale", "=", "None", ",", "zscale", "=", "None", ",", "reset_camera", "=", "True", ")", ":", "self", ".", "renderer", ".", "set_scale", "(", "xscale", ",", "yscale", ",", "zscale", "...
Scale all the datasets in the scene of the active renderer. Scaling in performed independently on the X, Y and Z axis. A scale of zero is illegal and will be replaced with one. Parameters ---------- xscale : float, optional Scaling of the x axis. Must be greater than zero. yscale : float, optional Scaling of the y axis. Must be greater than zero. zscale : float, optional Scaling of the z axis. Must be greater than zero. reset_camera : bool, optional Resets camera so all actors can be seen.
[ "Scale", "all", "the", "datasets", "in", "the", "scene", "of", "the", "active", "renderer", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1517-L1539
train
217,524
vtkiorg/vtki
vtki/plotting.py
BasePlotter._update_axes_color
def _update_axes_color(self, color): """Internal helper to set the axes label color""" prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() if color is None: color = rcParams['font']['color'] color = parse_color(color) for prop in [prop_x, prop_y, prop_z]: prop.SetColor(color[0], color[1], color[2]) prop.SetShadow(False) return
python
def _update_axes_color(self, color): """Internal helper to set the axes label color""" prop_x = self.axes_actor.GetXAxisCaptionActor2D().GetCaptionTextProperty() prop_y = self.axes_actor.GetYAxisCaptionActor2D().GetCaptionTextProperty() prop_z = self.axes_actor.GetZAxisCaptionActor2D().GetCaptionTextProperty() if color is None: color = rcParams['font']['color'] color = parse_color(color) for prop in [prop_x, prop_y, prop_z]: prop.SetColor(color[0], color[1], color[2]) prop.SetShadow(False) return
[ "def", "_update_axes_color", "(", "self", ",", "color", ")", ":", "prop_x", "=", "self", ".", "axes_actor", ".", "GetXAxisCaptionActor2D", "(", ")", ".", "GetCaptionTextProperty", "(", ")", "prop_y", "=", "self", ".", "axes_actor", ".", "GetYAxisCaptionActor2D",...
Internal helper to set the axes label color
[ "Internal", "helper", "to", "set", "the", "axes", "label", "color" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1546-L1557
train
217,525
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_scalars
def update_scalars(self, scalars, mesh=None, render=True): """ Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.Iterable, vtki.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.ren_win.Render() return if isinstance(scalars, str): # Grab scalar array if name given scalars = get_scalar(mesh, scalars) if scalars is None: if render: self.ren_win.Render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: _raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise Exception('No active scalars') s = VN.vtk_to_numpy(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalar array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.ren_win.Render()
python
def update_scalars(self, scalars, mesh=None, render=True): """ Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh if isinstance(mesh, (collections.Iterable, vtki.MultiBlock)): # Recursive if need to update scalars on many meshes for m in mesh: self.update_scalars(scalars, mesh=m, render=False) if render: self.ren_win.Render() return if isinstance(scalars, str): # Grab scalar array if name given scalars = get_scalar(mesh, scalars) if scalars is None: if render: self.ren_win.Render() return if scalars.shape[0] == mesh.GetNumberOfPoints(): data = mesh.GetPointData() elif scalars.shape[0] == mesh.GetNumberOfCells(): data = mesh.GetCellData() else: _raise_not_matching(scalars, mesh) vtk_scalars = data.GetScalars() if vtk_scalars is None: raise Exception('No active scalars') s = VN.vtk_to_numpy(vtk_scalars) s[:] = scalars data.Modified() try: # Why are the points updated here? Not all datasets have points # and only the scalar array is modified by this function... mesh.GetPoints().Modified() except: pass if render: self.ren_win.Render()
[ "def", "update_scalars", "(", "self", ",", "scalars", ",", "mesh", "=", "None", ",", "render", "=", "True", ")", ":", "if", "mesh", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "if", "isinstance", "(", "mesh", ",", "(", "collections", ".", ...
Updates scalars of the an object in the plotter. Parameters ---------- scalars : np.ndarray Scalars to replace existing scalars. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True.
[ "Updates", "scalars", "of", "the", "an", "object", "in", "the", "plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1809-L1867
train
217,526
vtkiorg/vtki
vtki/plotting.py
BasePlotter.update_coordinates
def update_coordinates(self, points, mesh=None, render=True): """ Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh mesh.points = points if render: self._render()
python
def update_coordinates(self, points, mesh=None, render=True): """ Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True. """ if mesh is None: mesh = self.mesh mesh.points = points if render: self._render()
[ "def", "update_coordinates", "(", "self", ",", "points", ",", "mesh", "=", "None", ",", "render", "=", "True", ")", ":", "if", "mesh", "is", "None", ":", "mesh", "=", "self", ".", "mesh", "mesh", ".", "points", "=", "points", "if", "render", ":", "...
Updates the points of the an object in the plotter. Parameters ---------- points : np.ndarray Points to replace existing points. mesh : vtk.PolyData or vtk.UnstructuredGrid, optional Object that has already been added to the Plotter. If None, uses last added mesh. render : bool, optional Forces an update to the render window. Default True.
[ "Updates", "the", "points", "of", "the", "an", "object", "in", "the", "plotter", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1869-L1892
train
217,527
vtkiorg/vtki
vtki/plotting.py
BasePlotter.close
def close(self): """ closes render window """ # must close out axes marker if hasattr(self, 'axes_widget'): del self.axes_widget # reset scalar bar stuff self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win if hasattr(self, '_style'): del self._style if hasattr(self, 'iren'): self.iren.RemoveAllObservers() del self.iren if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass
python
def close(self): """ closes render window """ # must close out axes marker if hasattr(self, 'axes_widget'): del self.axes_widget # reset scalar bar stuff self._scalar_bar_slots = set(range(MAX_N_COLOR_BARS)) self._scalar_bar_slot_lookup = {} self._scalar_bar_ranges = {} self._scalar_bar_mappers = {} if hasattr(self, 'ren_win'): self.ren_win.Finalize() del self.ren_win if hasattr(self, '_style'): del self._style if hasattr(self, 'iren'): self.iren.RemoveAllObservers() del self.iren if hasattr(self, 'textActor'): del self.textActor # end movie if hasattr(self, 'mwriter'): try: self.mwriter.close() except BaseException: pass
[ "def", "close", "(", "self", ")", ":", "# must close out axes marker", "if", "hasattr", "(", "self", ",", "'axes_widget'", ")", ":", "del", "self", ".", "axes_widget", "# reset scalar bar stuff", "self", ".", "_scalar_bar_slots", "=", "set", "(", "range", "(", ...
closes render window
[ "closes", "render", "window" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1894-L1925
train
217,528
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_text
def add_text(self, text, position=None, font_size=50, color=None, font=None, shadow=False, name=None, loc=None): """ Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : tuple(float) Length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False 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. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot """ if font is None: font = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] self.textActor = vtk.vtkTextActor() self.textActor.SetPosition(position) self.textActor.GetTextProperty().SetFontSize(font_size) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONT_KEYS[font]) self.textActor.GetTextProperty().SetShadow(shadow) self.textActor.SetInput(text) self.add_actor(self.textActor, reset_camera=False, name=name, loc=loc) return self.textActor
python
def add_text(self, text, position=None, font_size=50, color=None, font=None, shadow=False, name=None, loc=None): """ Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : tuple(float) Length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False 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. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot """ if font is None: font = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if color is None: color = rcParams['font']['color'] if position is None: # Set the position of the text to the top left corner window_size = self.window_size x = (window_size[0] * 0.02) / self.shape[0] y = (window_size[1] * 0.85) / self.shape[0] position = [x, y] self.textActor = vtk.vtkTextActor() self.textActor.SetPosition(position) self.textActor.GetTextProperty().SetFontSize(font_size) self.textActor.GetTextProperty().SetColor(parse_color(color)) self.textActor.GetTextProperty().SetFontFamily(FONT_KEYS[font]) self.textActor.GetTextProperty().SetShadow(shadow) self.textActor.SetInput(text) self.add_actor(self.textActor, reset_camera=False, name=name, loc=loc) return self.textActor
[ "def", "add_text", "(", "self", ",", "text", ",", "position", "=", "None", ",", "font_size", "=", "50", ",", "color", "=", "None", ",", "font", "=", "None", ",", "shadow", "=", "False", ",", "name", "=", "None", ",", "loc", "=", "None", ")", ":",...
Adds text to plot object in the top left corner by default Parameters ---------- text : str The text to add the the rendering position : tuple(float) Length 2 tuple of the pixelwise position to place the bottom left corner of the text box. Default is to find the top left corner of the renderering window and place text box up there. font : string, optional Font name may be courier, times, or arial shadow : bool, optional Adds a black shadow to the text. Defaults to False 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. loc : int, tuple, or list Index of the renderer to add the actor to. For example, ``loc=2`` or ``loc=(1, 1)``. Returns ------- textActor : vtk.vtkTextActor Text actor added to plot
[ "Adds", "text", "to", "plot", "object", "in", "the", "top", "left", "corner", "by", "default" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1927-L1984
train
217,529
vtkiorg/vtki
vtki/plotting.py
BasePlotter.open_movie
def open_movie(self, filename, framerate=24): """ Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second. """ if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self.mwriter = imageio.get_writer(filename, fps=framerate)
python
def open_movie(self, filename, framerate=24): """ Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second. """ if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self.mwriter = imageio.get_writer(filename, fps=framerate)
[ "def", "open_movie", "(", "self", ",", "filename", ",", "framerate", "=", "24", ")", ":", "if", "isinstance", "(", "vtki", ".", "FIGURE_PATH", ",", "str", ")", "and", "not", "os", ".", "path", ".", "isabs", "(", "filename", ")", ":", "filename", "=",...
Establishes a connection to the ffmpeg writer Parameters ---------- filename : str Filename of the movie to open. Filename should end in mp4, but other filetypes may be supported. See "imagio.get_writer" framerate : int, optional Frames per second.
[ "Establishes", "a", "connection", "to", "the", "ffmpeg", "writer" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L1986-L2002
train
217,530
vtkiorg/vtki
vtki/plotting.py
BasePlotter.open_gif
def open_gif(self, filename): """ Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif. """ if filename[-3:] != 'gif': raise Exception('Unsupported filetype. Must end in .gif') if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = imageio.get_writer(filename, mode='I')
python
def open_gif(self, filename): """ Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif. """ if filename[-3:] != 'gif': raise Exception('Unsupported filetype. Must end in .gif') if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) self._gif_filename = os.path.abspath(filename) self.mwriter = imageio.get_writer(filename, mode='I')
[ "def", "open_gif", "(", "self", ",", "filename", ")", ":", "if", "filename", "[", "-", "3", ":", "]", "!=", "'gif'", ":", "raise", "Exception", "(", "'Unsupported filetype. Must end in .gif'", ")", "if", "isinstance", "(", "vtki", ".", "FIGURE_PATH", ",", ...
Open a gif file. Parameters ---------- filename : str Filename of the gif to open. Filename must end in gif.
[ "Open", "a", "gif", "file", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2004-L2019
train
217,531
vtkiorg/vtki
vtki/plotting.py
BasePlotter.write_frame
def write_frame(self): """ Writes a single frame to the movie file """ if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image)
python
def write_frame(self): """ Writes a single frame to the movie file """ if not hasattr(self, 'mwriter'): raise AssertionError('This plotter has not opened a movie or GIF file.') self.mwriter.append_data(self.image)
[ "def", "write_frame", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'mwriter'", ")", ":", "raise", "AssertionError", "(", "'This plotter has not opened a movie or GIF file.'", ")", "self", ".", "mwriter", ".", "append_data", "(", "self", ".",...
Writes a single frame to the movie file
[ "Writes", "a", "single", "frame", "to", "the", "movie", "file" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2021-L2025
train
217,532
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_lines
def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """ Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or vtki.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) 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' width : float, optional Thickness of lines 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 ------- actor : vtk.vtkActor Lines actor. """ if not isinstance(lines, np.ndarray): raise Exception('Input should be an array of point segments') lines = vtki.lines_from_points(lines) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor self.scalar_bar = vtk.vtkActor() self.scalar_bar.SetMapper(mapper) self.scalar_bar.GetProperty().SetLineWidth(width) self.scalar_bar.GetProperty().EdgeVisibilityOn() self.scalar_bar.GetProperty().SetEdgeColor(rgb_color) self.scalar_bar.GetProperty().SetColor(rgb_color) self.scalar_bar.GetProperty().LightingOff() # Add to renderer self.add_actor(self.scalar_bar, reset_camera=False, name=name) return self.scalar_bar
python
def add_lines(self, lines, color=(1, 1, 1), width=5, label=None, name=None): """ Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or vtki.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) 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' width : float, optional Thickness of lines 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 ------- actor : vtk.vtkActor Lines actor. """ if not isinstance(lines, np.ndarray): raise Exception('Input should be an array of point segments') lines = vtki.lines_from_points(lines) # Create mapper and add lines mapper = vtk.vtkDataSetMapper() mapper.SetInputData(lines) rgb_color = parse_color(color) # legend label if label: if not isinstance(label, str): raise AssertionError('Label must be a string') self._labels.append([lines, label, rgb_color]) # Create actor self.scalar_bar = vtk.vtkActor() self.scalar_bar.SetMapper(mapper) self.scalar_bar.GetProperty().SetLineWidth(width) self.scalar_bar.GetProperty().EdgeVisibilityOn() self.scalar_bar.GetProperty().SetEdgeColor(rgb_color) self.scalar_bar.GetProperty().SetColor(rgb_color) self.scalar_bar.GetProperty().LightingOff() # Add to renderer self.add_actor(self.scalar_bar, reset_camera=False, name=name) return self.scalar_bar
[ "def", "add_lines", "(", "self", ",", "lines", ",", "color", "=", "(", "1", ",", "1", ",", "1", ")", ",", "width", "=", "5", ",", "label", "=", "None", ",", "name", "=", "None", ")", ":", "if", "not", "isinstance", "(", "lines", ",", "np", "....
Adds lines to the plotting object. Parameters ---------- lines : np.ndarray or vtki.PolyData Points representing line segments. For example, two line segments would be represented as: np.array([[0, 0, 0], [1, 0, 0], [1, 0, 0], [1, 1, 0]]) 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' width : float, optional Thickness of lines 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 ------- actor : vtk.vtkActor Lines actor.
[ "Adds", "lines", "to", "the", "plotting", "object", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2081-L2142
train
217,533
vtkiorg/vtki
vtki/plotting.py
BasePlotter.remove_scalar_bar
def remove_scalar_bar(self): """ Removes scalar bar """ if hasattr(self, 'scalar_bar'): self.remove_actor(self.scalar_bar, reset_camera=False)
python
def remove_scalar_bar(self): """ Removes scalar bar """ if hasattr(self, 'scalar_bar'): self.remove_actor(self.scalar_bar, reset_camera=False)
[ "def", "remove_scalar_bar", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'scalar_bar'", ")", ":", "self", ".", "remove_actor", "(", "self", ".", "scalar_bar", ",", "reset_camera", "=", "False", ")" ]
Removes scalar bar
[ "Removes", "scalar", "bar" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2144-L2147
train
217,534
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_point_labels
def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color='k', font_family=None, shadow=False, show_points=True, point_color='k', point_size=5, name=None): """ Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray n x 3 numpy array of points. labels : list List of labels. Must be the same length as points. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional, defaults to black Color of text. Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional, defaults to black Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) 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 ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels. """ if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if len(points) != len(labels): raise Exception('There must be one label for each point') vtkpoints = vtki.PolyData(points) vtklabels = vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # create label mapper labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputData(vtkpoints) textprop = labelMapper.GetLabelTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName('labels') labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # add points if show_points: style = 'points' else: style = 'surface' self.add_mesh(vtkpoints, style=style, color=point_color, point_size=point_size) self.add_actor(labelActor, reset_camera=False, name=name) return labelMapper
python
def add_point_labels(self, points, labels, italic=False, bold=True, font_size=None, text_color='k', font_family=None, shadow=False, show_points=True, point_color='k', point_size=5, name=None): """ Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray n x 3 numpy array of points. labels : list List of labels. Must be the same length as points. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional, defaults to black Color of text. Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional, defaults to black Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) 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 ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels. """ if font_family is None: font_family = rcParams['font']['family'] if font_size is None: font_size = rcParams['font']['size'] if len(points) != len(labels): raise Exception('There must be one label for each point') vtkpoints = vtki.PolyData(points) vtklabels = vtk.vtkStringArray() vtklabels.SetName('labels') for item in labels: vtklabels.InsertNextValue(str(item)) vtkpoints.GetPointData().AddArray(vtklabels) # create label mapper labelMapper = vtk.vtkLabeledDataMapper() labelMapper.SetInputData(vtkpoints) textprop = labelMapper.GetLabelTextProperty() textprop.SetItalic(italic) textprop.SetBold(bold) textprop.SetFontSize(font_size) textprop.SetFontFamily(parse_font_family(font_family)) textprop.SetColor(parse_color(text_color)) textprop.SetShadow(shadow) labelMapper.SetLabelModeToLabelFieldData() labelMapper.SetFieldDataName('labels') labelActor = vtk.vtkActor2D() labelActor.SetMapper(labelMapper) # add points if show_points: style = 'points' else: style = 'surface' self.add_mesh(vtkpoints, style=style, color=point_color, point_size=point_size) self.add_actor(labelActor, reset_camera=False, name=name) return labelMapper
[ "def", "add_point_labels", "(", "self", ",", "points", ",", "labels", ",", "italic", "=", "False", ",", "bold", "=", "True", ",", "font_size", "=", "None", ",", "text_color", "=", "'k'", ",", "font_family", "=", "None", ",", "shadow", "=", "False", ","...
Creates a point actor with one label from list labels assigned to each point. Parameters ---------- points : np.ndarray n x 3 numpy array of points. labels : list List of labels. Must be the same length as points. italic : bool, optional Italicises title and bar labels. Default False. bold : bool, optional Bolds title and bar labels. Default True font_size : float, optional Sets the size of the title font. Defaults to 16. text_color : string or 3 item list, optional, defaults to black Color of text. Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' font_family : string, optional Font family. Must be either courier, times, or arial. shadow : bool, optional Adds a black shadow to the text. Defaults to False show_points : bool, optional Controls if points are visible. Default True point_color : string or 3 item list, optional, defaults to black Color of points (if visible). Either a string, rgb list, or hex color string. For example: text_color='white' text_color='w' text_color=[1, 1, 1] text_color='#FFFFFF' point_size : float, optional Size of points (if visible) 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 ------- labelMapper : vtk.vtkvtkLabeledDataMapper VTK label mapper. Can be used to change properties of the labels.
[ "Creates", "a", "point", "actor", "with", "one", "label", "from", "list", "labels", "assigned", "to", "each", "point", "." ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2149-L2257
train
217,535
vtkiorg/vtki
vtki/plotting.py
BasePlotter.add_arrows
def add_arrows(self, cent, direction, mag=1, **kwargs): """ Adds arrows to plotting object """ direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) direction[:,0] *= mag direction[:,1] *= mag direction[:,2] *= mag pdata = vtki.vector_poly_data(cent, direction) # Create arrow object arrow = vtk.vtkArrowSource() arrow.Update() glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs)
python
def add_arrows(self, cent, direction, mag=1, **kwargs): """ Adds arrows to plotting object """ direction = direction.copy() if cent.ndim != 2: cent = cent.reshape((-1, 3)) if direction.ndim != 2: direction = direction.reshape((-1, 3)) direction[:,0] *= mag direction[:,1] *= mag direction[:,2] *= mag pdata = vtki.vector_poly_data(cent, direction) # Create arrow object arrow = vtk.vtkArrowSource() arrow.Update() glyph3D = vtk.vtkGlyph3D() glyph3D.SetSourceData(arrow.GetOutput()) glyph3D.SetInputData(pdata) glyph3D.SetVectorModeToUseVector() glyph3D.Update() arrows = wrap(glyph3D.GetOutput()) return self.add_mesh(arrows, **kwargs)
[ "def", "add_arrows", "(", "self", ",", "cent", ",", "direction", ",", "mag", "=", "1", ",", "*", "*", "kwargs", ")", ":", "direction", "=", "direction", ".", "copy", "(", ")", "if", "cent", ".", "ndim", "!=", "2", ":", "cent", "=", "cent", ".", ...
Adds arrows to plotting object
[ "Adds", "arrows", "to", "plotting", "object" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2264-L2289
train
217,536
vtkiorg/vtki
vtki/plotting.py
BasePlotter._save_image
def _save_image(image, filename, return_img=None): """Internal helper for saving a NumPy image array""" if not image.size: raise Exception('Empty image. Have you run plot() first?') # write screenshot to file if isinstance(filename, str): if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) if not return_img: return imageio.imwrite(filename, image) imageio.imwrite(filename, image) return image
python
def _save_image(image, filename, return_img=None): """Internal helper for saving a NumPy image array""" if not image.size: raise Exception('Empty image. Have you run plot() first?') # write screenshot to file if isinstance(filename, str): if isinstance(vtki.FIGURE_PATH, str) and not os.path.isabs(filename): filename = os.path.join(vtki.FIGURE_PATH, filename) if not return_img: return imageio.imwrite(filename, image) imageio.imwrite(filename, image) return image
[ "def", "_save_image", "(", "image", ",", "filename", ",", "return_img", "=", "None", ")", ":", "if", "not", "image", ".", "size", ":", "raise", "Exception", "(", "'Empty image. Have you run plot() first?'", ")", "# write screenshot to file", "if", "isinstance", "...
Internal helper for saving a NumPy image array
[ "Internal", "helper", "for", "saving", "a", "NumPy", "image", "array" ]
5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1
https://github.com/vtkiorg/vtki/blob/5ccad7ae6d64a03e9594c9c7474c8aab3eb22dd1/vtki/plotting.py#L2293-L2306
train
217,537
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): """ 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)
[ "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
train
217,538
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): """ 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
[ "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
train
217,539
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'): """ 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)
[ "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
train
217,540
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): """ Removes legend actor """ 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
train
217,541
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): """ 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)
[ "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
train
217,542
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): """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)
[ "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
train
217,543
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): """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
[ "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
train
217,544
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): """ 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)
[ "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
train
217,545
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): """ 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
[ "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
train
217,546
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(): """ 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)
[ "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
train
217,547
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): """ 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()
[ "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
train
217,548
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): """ 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
[ "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
train
217,549
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'): """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
[ "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
train
217,550
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): """ 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
[ "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
train
217,551
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): """ 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)
[ "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
train
217,552
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): """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)
[ "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
train
217,553
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): """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
[ "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
train
217,554
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): """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
[ "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
train
217,555
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): """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
[ "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
train
217,556
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'): """ 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)
[ "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
train
217,557
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'): """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)
[ "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
train
217,558
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): """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))
[ "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
train
217,559
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): """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))
[ "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
train
217,560
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): """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)
[ "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
train
217,561
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): """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')
[ "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
train
217,562
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'): """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)
[ "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
train
217,563
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'): """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
[ "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
train
217,564
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): """ 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
[ "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
train
217,565
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): """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)
[ "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
train
217,566
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): """ 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')
[ "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
train
217,567
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): """ 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()
[ "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
train
217,568
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): """ 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
[ "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
train
217,569
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): """ 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)
[ "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
train
217,570
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): """ 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
[ "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
train
217,571
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): """ 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
[ "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
train
217,572
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): """ 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
[ "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
train
217,573
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): """ 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
[ "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
train
217,574
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'): """ 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())
[ "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
train
217,575
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): """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
[ "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
train
217,576
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): """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
[ "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
train
217,577
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): """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
[ "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
train
217,578
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): """ 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
[ "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
train
217,579
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): """ 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
[ "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
train
217,580
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): """ 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
[ "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
train
217,581
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): """ 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())
[ "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
train
217,582
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): """ 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
[ "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
train
217,583
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): """ 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
[ "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
train
217,584
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 """ 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
[ "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
train
217,585
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): """ Mesh surface area Returns ------- area : float Total area of the mesh. """ 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
train
217,586
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): """ 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
[ "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
train
217,587
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): """ 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
[ "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
train
217,588
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): """ 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
[ "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
train
217,589
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): """ 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()
[ "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
train
217,590
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): """ 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()
[ "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
train
217,591
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): """ 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
[ "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
train
217,592
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): """ 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]
[ "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
train
217,593
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): """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
[ "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
train
217,594
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): """ 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)
[ "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
train
217,595
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): """ 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
[ "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
train
217,596
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): """ 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)
[ "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
train
217,597
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): """ 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)
[ "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
train
217,598
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): """ 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
[ "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
train
217,599