Example #1
0
def _create_testing_scene(empty_scene, show=False, off_screen=False):
    if empty_scene:
        plotter = pyvista.BackgroundPlotter(show=show, off_screen=off_screen)
    else:
        plotter = pyvista.BackgroundPlotter(shape=(2, 2),
                                            border=True,
                                            border_width=10,
                                            border_color='grey',
                                            show=show,
                                            off_screen=off_screen)
        plotter.set_background('black', top='blue')
        plotter.subplot(0, 0)
        cone = pyvista.Cone(resolution=4)
        actor = plotter.add_mesh(cone)
        plotter.remove_actor(actor)
        plotter.add_text('Actor is removed')
        plotter.subplot(0, 1)
        plotter.add_mesh(pyvista.Box(), color='green', opacity=0.8)
        plotter.subplot(1, 0)
        cylinder = pyvista.Cylinder(resolution=6)
        plotter.add_mesh(cylinder, smooth_shading=True)
        plotter.show_bounds()
        plotter.subplot(1, 1)
        sphere = pyvista.Sphere(phi_resolution=6, theta_resolution=6)
        plotter.add_mesh(sphere)
        plotter.enable_cell_picking()
    return plotter
Example #2
0
def test_background_plotting_toolbar(qtbot):
    with pytest.raises(TypeError, match='toolbar'):
        pyvista.BackgroundPlotter(off_screen=False, toolbar="foo")

    plotter = pyvista.BackgroundPlotter(off_screen=False, toolbar=False)
    assert plotter.default_camera_tool_bar is None
    assert plotter.saved_camera_positions is None
    assert plotter.saved_cameras_tool_bar is None
    plotter.close()

    plotter = pyvista.BackgroundPlotter(off_screen=False)

    assert _hasattr(plotter, "app_window", MainWindow)
    assert _hasattr(plotter, "default_camera_tool_bar", QToolBar)
    assert _hasattr(plotter, "saved_camera_positions", list)
    assert _hasattr(plotter, "saved_cameras_tool_bar", QToolBar)

    window = plotter.app_window
    default_camera_tool_bar = plotter.default_camera_tool_bar
    saved_cameras_tool_bar = plotter.saved_cameras_tool_bar

    with qtbot.wait_exposed(window, timeout=500):
        window.show()

    assert default_camera_tool_bar.isVisible()
    assert saved_cameras_tool_bar.isVisible()

    plotter.close()
Example #3
0
def test_background_plotting_menu_bar(qtbot):
    with pytest.raises(TypeError, match='menu_bar'):
        pyvista.BackgroundPlotter(off_screen=False, menu_bar="foo")

    plotter = pyvista.BackgroundPlotter(off_screen=False, menu_bar=False)
    assert plotter.main_menu is None
    assert plotter._menu_close_action is None
    plotter.close()

    plotter = pyvista.BackgroundPlotter(off_screen=False)  # menu_bar=True

    assert _hasattr(plotter, "app_window", MainWindow)
    assert _hasattr(plotter, "main_menu", QMenuBar)
    assert _hasattr(plotter, "_menu_close_action", QAction)

    window = plotter.app_window
    main_menu = plotter.main_menu
    assert not main_menu.isNativeMenuBar()

    with qtbot.wait_exposed(window, timeout=500):
        window.show()

    assert main_menu.isVisible()
    plotter.close()
    assert not main_menu.isVisible()
Example #4
0
def plot_3d_pyvista(Data,
                    slice=0,
                    origin=(0, 0, 0),
                    spacing=(1, 1, 1),
                    threshold=(),
                    filename='',
                    header=''):
    '''
    plot 3D cube using 'pyvista' 
    '''
    import numpy as np

    if module_exists('pyvista', 1):
        import pyvista
    else:
        return 1
    print(filename)

    # create uniform grid
    grid = numpy_to_pvgrid(Data, origin=(0, 0, 0), spacing=(1, 1, 1))

    # Now plot the grid!
    if (len(threshold) == 2):
        plot = pyvista.BackgroundPlotter()  # interactive
        #plot = pyvista.Plotter() # interactive
        grid_threshold = grid.threshold(threshold)
        try:
            pass
            # crashed in version 0.17.3 on linux
            # plot.eye_dome_lighting_on()
        except:
            pass
        plot.add_mesh(grid_threshold)
        if len(filename) > 0:
            plot.screenshot(filename)
        plot.show()

    elif (slice == 1):
        # plot = pyvista.Plotter() # static
        plot = pyvista.BackgroundPlotter()  # interactive

        grid_slice = grid.slice_orthogonal()
        plot.add_mesh(grid_slice)

        plot.add_text(header)
        plot.show_grid()
        if len(filename) > 0:
            plot.screenshot(filename)
        plot.show()

    else:
        grid.plot(show_edges=True)
Example #5
0
def plot_subset_cells(grid, subset=None, scalar='z', invert=False):
    if invert == True:
        flag_bool = False
        flag_int = 0
    else:
        flag_bool = True
        flag_int = 1
    if subset != None:
        extract_idx = []
        for i_cell in range(grid.n_cells):
            if grid.cell_arrays[subset][i_cell] == flag_bool \
            or grid.cell_arrays[subset][i_cell] == flag_int:
                extract_idx.append(i_cell)
        plot_grid = grid.extract_cells(extract_idx)
    else:
        plot_grid = grid
    plotter = pv.BackgroundPlotter()
    if scalar == 'z':
        s = plot_grid.points[:, 2]
    else:
        s = plot_grid.cell_arrays[scalar]

    plotter.add_mesh(plot_grid, show_edges=True, scalars=s)
    plotter.add_scalar_bar()
    return
Example #6
0
    def plot(self,
             sim_property,
             plotter=None,
             parts=None,
             cmap=None,
             **kwargs):
        #        self.sim_input.put('SimSpace.'+sim_property)

        var = self.getvar(sim_property).to_numpy()

        pv.UnstructuredGrid(self.assembly.export_vtk())

        if not cmap: cmap = plt.cm.get_cmap("viridis", 5)

        grid = pv.UnstructuredGrid(self.assembly.export_vtk())

        if not plotter:
            plotter = pv.BackgroundPlotter()

        plotter.add_mesh(grid,
                         scalars=var,
                         stitle=sim_property,
                         rng=[var.min(), var.max()],
                         cmap=cmap,
                         **kwargs)

        plotter.add_axes()
        plotter.show()

        return plotter
Example #7
0
def test_background_plotting_orbit(qtbot):
    plotter = pyvista.BackgroundPlotter(off_screen=False,
                                        title='Testing Window')
    plotter.add_mesh(pyvista.Sphere())
    # perform the orbit:
    plotter.orbit_on_path(bkg=False, step=0.0)
    plotter.close()
Example #8
0
    def __init__(self,
                 model,
                 extent=None,
                 lith_c: pn.DataFrame = None,
                 real_time=False,
                 plotter_type='basic',
                 **kwargs):

        # Override default notebook value
        kwargs['notebook'] = kwargs.get('notebook', True)

        self.model = model
        self.extent = model.grid.regular_grid.extent if extent is None else extent
        self._color_lot = model.surfaces.df.set_index(
            'id')['color'] if lith_c is None else lith_c

        self.s_widget = pn.DataFrame(columns=['val'])
        self.p_widget = pn.DataFrame(columns=['val'])
        self.surf_polydata = pn.DataFrame(columns=['val'])

        self.vista_rgrids_mesh = {}
        self.vista_rgrids_actors = {}
        self.vista_topo_actors = {}
        self.vista_surf_actor = {}

        self.real_time = real_time

        if plotter_type == 'basic':
            self.p = pv.Plotter(**kwargs)
        elif plotter_type == 'background':
            self.p = pv.BackgroundPlotter(**kwargs)

        self.set_bounds()
        self.p.view_isometric(negative=False)
Example #9
0
def test_isocell():
    isocell = Isocell(rays=1000, div=5, isrand=0, draw_cells=True)

    # # Plot points in 2D
    # fig = plt.figure()
    # ax = fig.add_axes([0, 0, 1, 1])
    # ax.scatter(isocell.Xr, isocell.Yr, color='r')
    # ax.scatter(isocell.Xc, isocell.Yc, color='b')
    # ax.set_xlabel('')
    # ax.set_ylabel('')
    # ax.set_title('Isocell Unit circle')
    # # plt.show()
    # plt.show(block=True)

    # # Plot points in 3D
    # mlab.points3d(isocell.Xr, isocell.Yr, isocell.Zr, color=(1,0,0), scale_factor=.01)
    # mlab.points3d(isocell.Xc, isocell.Yc, isocell.Zc, color=(0, 0, 1), scale_factor=.01)
    # mlab.show()

    points = np.column_stack([isocell.Xr, isocell.Yr, isocell.Zr])
    cell_points = np.column_stack([isocell.Xc, isocell.Yc, isocell.Zc])
    poly = pv.PolyData(points)
    cell = pv.PolyData(cell_points)
    # poly["My Labels"] = ["P {}".format(i) for i in range(poly.n_points)]

    plotter = pv.BackgroundPlotter()
    # plotter = pv.Plotter()
    # # plotter.add_point_labels(poly, "My Labels", point_size=20, font_size=36)
    plotter.add_mesh(poly, color="red", point_size=1)
    plotter.add_mesh(cell, color="blue", point_size=1)
    plotter.add_axes()
    plotter.show()
    plotter.app.exec_()

    print('End testing the isocell module!!!!')
Example #10
0
def Plot3DSlices(axes, DataVol, points, InteractiveSlices=False):
    """
    3D rendering of 3 slices in orthogonal planes.
    
    Parameters
    ----------
    axes:
        x, y and z 1Darray vectors of coordinates on which the data is 
        calculated. Usually passed as (x,y,z) or np.array((x,y,z))
        
    DataVol: len(x) by len(y) by len(z) numpy array
        Volumetric data in numpy array to be plotted
        Usually obtained using :py:func:`S4Utils.S4Utils.GetFieldVolume` or 
        :py:func:`S4Utils.S4Utils.GetEpsilonVolume` functions.
    
    points: tuple, list or array
        point at which to slice the volume data. Usually (xs, ys, zs), in 
        real space coordinates
    
    InteractiveSlices: bool (opt)
        Boolean flag to activate PyVista's defaults 3D slicing. Defaults to 
        False. 
        
    Returns
    -------
        None.
        
    Notes
    -----
        Follows https://docs.pyvista.org/examples/00-load/create-uniform-grid.html
        and https://docs.pyvista.org/plotting/widgets.html#pyvista.WidgetHelper.add_mesh_slice_orthogonal
    """
    xs, ys, zs = points  ## coordinates for each slice
    x, y, z = axes  ## axes
    xi = np.abs(x - xs).argmin()  # index of x-coordinate of the yz slice
    yi = np.abs(y - ys).argmin()  # index of y-coordinate of the xz slice
    zi = np.abs(z - zs).argmin()  # index of z-coordinate of the xy slice

    grid = pv.UniformGrid()  # initialize the 3D grid
    grid.dimensions = DataVol.shape
    grid.point_arrays['values'] = DataVol.flatten(order='F')
    plotter = pv.BackgroundPlotter()
    if not InteractiveSlices:
        slices = grid.slice_orthogonal(x=xi, y=yi, z=zi)
        plotter.add_mesh(slices, cmap='bwr')
    else:
        ### this alone does the trick but I find it hard to manipulate
        ## maybe leave as an option
        plotter.add_mesh_slice_orthogonal(grid, cmap='bwr')
    ##########
    ## plotter options
    plotter.set_viewup((1, 1, -1))  ## flip z-axis view to match S4 coordinates
    isocam = plotter.camera.GetPosition()  ## get initial camera location
    plotter.camera.SetPosition(
        (isocam[0], isocam[1], 0))  ## set new camera location
    plotter.show_axes()  ## show axes orientation widget
    plotter.show_grid()  ## show the grid and axes
def test_background_plotting_add_callback(qtbot):
    plotter = pyvista.BackgroundPlotter(show=False, title='Testing Window')
    sphere = pyvista.Sphere()
    plotter.add_mesh(sphere)

    def mycallback():
        sphere.points *= 0.5
    plotter.add_callback(mycallback, interval=1000, count=3)
    plotter.close()
Example #12
0
def test_background_plotter_export_vtkjs(qtbot, tmpdir):
    plotter = pyvista.BackgroundPlotter(show=False, title='Testing Window')
    plotter.add_mesh(pyvista.Sphere())

    filename = str(tmpdir.mkdir("tmpdir").join('tmp'))
    dlg = plotter._qt_export_vtkjs(show=False)
    dlg.selectFile(filename)
    dlg.accept()
    plotter.close()

    assert os.path.isfile(filename + '.vtkjs')
Example #13
0
    def plot_rt(self,
                sim_property,
                plotter=None,
                dt=0.5,
                t=None,
                update_scale=True,
                **kwargs):

        var = self.getvar(sim_property).to_numpy()

        pv.UnstructuredGrid(self.assembly.export_vtk())

        #        if not cmap: cmap = plt.cm.get_cmap("viridis", 5)

        grid = pv.UnstructuredGrid(self.assembly.export_vtk())
        grid.cell_arrays[sim_property] = var
        grid.set_active_scalar(sim_property)

        if not plotter:
            plotter = pv.BackgroundPlotter()

        plotter.add_mesh(
            grid,
            scalars=sim_property,
            stitle=sim_property,
            #                         rng=[var.min(), var.max()],
            lighting=False,
            testure=True,
            #                         cmap = cmap,
            show_edges=True,
            **kwargs)

        plotter.add_axes()
        #        plotter.show()
        plotter.view_isometric()

        def update(sim):
            t_c = 0

            while not t or t_c < t:
                var = sim.getvar(sim_property).to_numpy()
                grid.cell_arrays[sim_property] = var
                if update_scale:
                    plotter.update_scalar_bar_range([var.min(), var.max()])
                #this is not some critical task, good enough
                t_c = t_c + dt
                time.sleep(dt)

        thread = threading.Thread(target=update, args=(self, ))
        thread.start()

        return plotter
Example #14
0
def test_background_plotter_export_files(qtbot, tmpdir):
    plotter = pyvista.BackgroundPlotter(off_screen=False,
                                        title='Testing Window')
    plotter.add_mesh(pyvista.Sphere())

    filename = str(tmpdir.mkdir("tmpdir").join('tmp.png'))
    plotter.update()
    dlg = plotter._qt_screenshot(show=False)
    dlg.selectFile(filename)
    dlg.accept()
    plotter.close()

    assert os.path.isfile(filename)
Example #15
0
def test_background_plotting_add_callback(qtbot):
    class CallBack(object):
        def __init__(self, sphere):
            self.sphere = sphere

        def __call__(self):
            self.sphere.points *= 0.5

    plotter = pyvista.BackgroundPlotter(show=False,
                                        off_screen=False,
                                        title='Testing Window')
    sphere = pyvista.Sphere()
    mycallback = CallBack(sphere)
    plotter.add_mesh(sphere)
    plotter.add_callback(mycallback, interval=200, count=3)

    # check that timers are set properly in add_callback()
    assert _hasattr(plotter, "app_window", MainWindow)
    assert _hasattr(plotter, "_callback_timer", QTimer)
    assert _hasattr(plotter, "counters", list)

    window = plotter.app_window  # MainWindow
    callback_timer = plotter._callback_timer  # QTimer
    counter = plotter.counters[-1]  # Counter

    # ensure that the window is showed
    assert not window.isVisible()
    with qtbot.wait_exposed(window, timeout=500):
        window.show()
    assert window.isVisible()
    # ensure that self.callback_timer send a signal
    callback_blocker = qtbot.wait_signals([callback_timer.timeout],
                                          timeout=300)
    callback_blocker.wait()
    # ensure that self.counters send a signal
    counter_blocker = qtbot.wait_signals([counter.signal_finished],
                                         timeout=700)
    counter_blocker.wait()
    assert not callback_timer.isActive()  # counter stops the callback

    plotter.add_callback(mycallback, interval=200)
    callback_timer = plotter._callback_timer  # QTimer

    # ensure that self.callback_timer send a signal
    callback_blocker = qtbot.wait_signals([callback_timer.timeout],
                                          timeout=300)
    callback_blocker.wait()

    assert callback_timer.isActive()
    plotter.close()
    assert not callback_timer.isActive()  # window stops the callback
Example #16
0
def plot_mesh(verts, faces):
    # points = isocell.points
    # cell_points = np.column_stack([isocell.Xc, isocell.Yc, isocell.Zc])
    poly = pv.PolyData(verts, faces)
    # cell = pv.PolyData(cell_points)
    # # lines = pv.lines_from_points(cell.points)
    #
    plotter = pv.BackgroundPlotter()
    plotter.add_mesh(poly, show_edges=True)
    # # plotter.add_mesh(cell, color="blue", point_size=1)
    # # plotter.add_mesh(lines, color='blue')
    plotter.add_axes()
    plotter.show()
    plotter.app.exec_()
Example #17
0
def plot_weighted_isocell(isocell):
    points = isocell.points
    cell_points = np.column_stack([isocell.Xc, isocell.Yc, isocell.Zc])
    poly = pv.PolyData(points)
    cell = pv.PolyData(cell_points)
    # lines = pv.lines_from_points(cell.points)

    plotter = pv.BackgroundPlotter()
    plotter.add_mesh(poly, scalars=isocell.weights, point_size=2)
    # plotter.add_mesh(cell, color="blue", point_size=1)
    # plotter.add_mesh(lines, color='blue')
    plotter.add_axes()
    plotter.show()
    plotter.app.exec_()
Example #18
0
def plot_subset_index_cells(grid, i_cell, i_neighbors=np.array([])):
    plotter = pv.BackgroundPlotter()
    plotter.add_mesh(grid.extract_all_edges(), color='k', label='whole mesh')
    if i_neighbors.size != 0:
        plotter.add_mesh(grid.extract_cells(i_neighbors),
                         color=True,
                         opacity=0.5,
                         label='neighbors')
    plotter.add_mesh(grid.extract_cells(i_cell),
                     color='pink',
                     opacity=0.75,
                     label='the cell')
    plotter.add_legend()
    plotter.show()
    return
Example #19
0
    def plot(self, plane_widget=True, plot_gradient=False):
        if not plot_gradient:
            gridvalues = self.image_sequence.array
        else:
            gridvalues = self.image_gradients.array
        surf = self.init_surf
        outputsurf = self.surface
        image = pv.UniformGrid()
        image.dimensions = gridvalues.shape
        image.point_arrays["values"] = gridvalues.flatten(order="F")
        plotter = pv.BackgroundPlotter()
        plotter.add_mesh(image, cmap="bone", opacity=0.5)

        def makemesh(surf, meshtype="StructuredGrid", points='evalpts'):

            if points == 'evalpts':
                pts = np.array(surf.evalpts)
                pts_square = pts.reshape((*surf.data['sample_size'], -1))
            elif points == 'ctrlpts':
                pts = np.array(surf.ctrlpts)
                pts_square = pts.reshape((*surf.data['size'], -1))

            if meshtype.lower() == 'PolyData'.lower():
                mesh = pv.PolyData(pts_square)

            if meshtype.lower() == 'StructuredGrid'.lower():
                mesh = pv.StructuredGrid()
                mesh.points = pts
                mesh.dimensions = [*np.flip(surf.data['sample_size']), 1]
            return mesh

        plotter.add_mesh(makemesh(surf), color='blue')
        plotter.add_mesh(makemesh(surf, 'PolyData'), color='blue')

        plotter.add_mesh(makemesh(outputsurf), color='red')
        plotter.add_mesh(makemesh(outputsurf, 'PolyData'), color='red')

        plotter.add_mesh(makemesh(surf, 'PolyData', 'ctrlpts'), color='cyan')
        plotter.add_mesh(makemesh(outputsurf, 'PolyData', 'ctrlpts'),
                         color='orange')

        if plane_widget:
            plotter.add_mesh_clip_plane(image)

        plotter.show_grid()
        plotter.show()

        return plotter
Example #20
0
    def __init__(self,
                 model: gp.Model,
                 extent: List[float] = None,
                 color_lot: pn.DataFrame = None,
                 real_time: bool = False,
                 plotter_type: Union["basic", "background"] = 'basic',
                 **kwargs):
        """GemPy 3-D visualization using pyVista.
        
        Args:
            model (gp.Model): Geomodel instance with solutions.
            extent (List[float], optional): Custom extent. Defaults to None.
            color_lot (pn.DataFrame, optional): Custom color scheme in the form
                of a look-up table. Defaults to None.
            real_time (bool, optional): Toggles real-time updating of the plot. 
                Defaults to False.
            plotter_type (Union["basic", "background"], optional): Set the 
                plotter type. Defaults to 'basic'.
        """
        self.model = model
        if extent:
            self.extent = list(extent)
        else:
            self.extent = list(model.grid.regular_grid.extent)

        if color_lot:
            self._color_lot = color_lot
        else:
            self._color_lot = model.surfaces.df.set_index('surface')['color']
        self._color_id_lot = model.surfaces.df.set_index('id')['color']

        if plotter_type == 'basic':
            self.p = pv.Plotter(**kwargs)
        elif plotter_type == 'background':
            self.p = pv.BackgroundPlotter(**kwargs)

        self._surface_actors = {}
        self._surface_points_actors = {}
        self._orientations_actors = {}

        self._actors = []
        self._live_updating = False

        self.topo_edges = None
        self.topo_ctrs = None

        self.set_bounds()
Example #21
0
def test_background_plotting_camera(qtbot):
    plotter = pyvista.BackgroundPlotter(show=False, title='Testing Window')
    plotter.add_mesh(pyvista.Sphere())

    cpos = [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
    plotter.camera_position = cpos
    plotter.save_camera_position()
    plotter.camera_position = [(0.0, 0.0, 3.0), (0.0, 0.0, 0.0),
                               (0.0, 1.0, 0.0)]

    # load existing position
    plotter.saved_camera_menu.actions()[0].trigger()
    assert plotter.camera_position == cpos

    plotter.clear_camera_positions()
    assert not len(plotter.saved_camera_menu.actions())
    plotter.close()
Example #22
0
def test_background_plotter_export_vtkjs(qtbot, tmpdir, show_plotter):
    # setup filesystem
    output_dir = str(tmpdir.mkdir("tmpdir"))
    assert os.path.isdir(output_dir)

    plotter = pyvista.BackgroundPlotter(show=show_plotter,
                                        off_screen=False,
                                        title='Testing Window')
    assert _hasattr(plotter, "app_window", MainWindow)
    window = plotter.app_window  # MainWindow
    qtbot.addWidget(window)  # register the window

    # show the window
    if not show_plotter:
        assert not window.isVisible()
        with qtbot.wait_exposed(window, timeout=1000):
            window.show()
    assert window.isVisible()

    plotter.add_mesh(pyvista.Sphere())
    assert _hasattr(plotter, "renderer", Renderer)
    renderer = plotter.renderer
    assert len(renderer._actors) == 1
    assert np.any(plotter.mesh.points)

    dlg = plotter._qt_export_vtkjs(show=False)  # FileDialog
    qtbot.addWidget(dlg)  # register the dialog

    filename = str(os.path.join(output_dir, "tmp"))
    dlg.selectFile(filename)

    # show the dialog
    assert not dlg.isVisible()
    with qtbot.wait_exposed(dlg, timeout=500):
        dlg.show()
    assert dlg.isVisible()

    # synchronise signal and callback
    with qtbot.wait_signals([dlg.dlg_accepted], timeout=1000):
        dlg.accept()
    assert not dlg.isVisible()  # dialog is closed after accept()

    plotter.close()
    assert not window.isVisible()
    assert os.path.isfile(filename + '.vtkjs')
def test_background_plotting_camera(qtbot):
    plotter = pyvista.BackgroundPlotter(show=False, title='Testing Window')
    plotter.add_mesh(pyvista.Sphere())

    cpos = [(0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]
    plotter.camera_position = cpos
    plotter.save_camera_position()
    plotter.camera_position = [(0.0, 0.0, 3.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0)]

    # load existing position
    # NOTE: 2 because first two (0 and 1) bottons save and clear positions
    plotter.saved_cameras_tool_bar.actions()[2].trigger()
    assert plotter.camera_position == cpos

    plotter.clear_camera_positions()
    # 2 because the first two buttons are save and clear
    assert len(plotter.saved_cameras_tool_bar.actions()) == 2
    plotter.close()
Example #24
0
def test_background_plotting_axes_scale(qtbot, show_plotter):
    plotter = pyvista.BackgroundPlotter(show=show_plotter,
                                        off_screen=False,
                                        title='Testing Window')
    assert _hasattr(plotter, "app_window", MainWindow)
    window = plotter.app_window  # MainWindow
    qtbot.addWidget(window)  # register the window

    # show the window
    if not show_plotter:
        assert not window.isVisible()
        with qtbot.wait_exposed(window, timeout=1000):
            window.show()
    assert window.isVisible()

    plotter.add_mesh(pyvista.Sphere())
    assert _hasattr(plotter, "renderer", Renderer)
    renderer = plotter.renderer
    assert len(renderer._actors) == 1
    assert np.any(plotter.mesh.points)

    dlg = plotter.scale_axes_dialog(show=False)  # ScaleAxesDialog
    qtbot.addWidget(dlg)  # register the dialog

    # show the dialog
    assert not dlg.isVisible()
    with qtbot.wait_exposed(dlg, timeout=500):
        dlg.show()
    assert dlg.isVisible()

    value = 2.0
    dlg.x_slider_group.value = value
    assert plotter.scale[0] == value
    dlg.x_slider_group.spinbox.setValue(-1)
    assert dlg.x_slider_group.value == 0
    dlg.x_slider_group.spinbox.setValue(1000.0)
    assert dlg.x_slider_group.value < 100

    plotter._last_update_time = 0.0
    plotter.update()
    plotter.update_app_icon()
    plotter.close()
    assert not window.isVisible()
    assert not dlg.isVisible()
    def plot(self, plane_widget=True, **kwargs):

        # Display the arrows
        plotter = pv.BackgroundPlotter()

        cmap = kwargs.pop('cmap', 'bone')
        opacity = kwargs.pop('opacity', 0.5)

        grid = pv.UniformGrid()
        grid.dimensions = self.array.shape
        grid.point_arrays["values"] = self.array.flatten(order="F")
        plotter.add_mesh(grid, cmap=cmap, opacity=opacity, **kwargs)

        if plane_widget:
            plotter.add_mesh_clip_plane(grid)

        plotter.show_grid()
        plotter.show()

        return plotter
Example #26
0
def test_background_plotting_axes_scale(qtbot):
    sphere = pyvista.Sphere()
    plotter = pyvista.BackgroundPlotter(show=False, title='Testing Window')
    plotter.add_mesh(sphere)
    assert np.any(plotter.mesh.points)

    dlg = plotter.scale_axes_dialog(show=False)

    value = 2.0
    dlg.x_slider_group.value = value
    assert plotter.scale[0] == value

    dlg.x_slider_group.spinbox.setValue(-1)
    assert dlg.x_slider_group.value == 0
    dlg.x_slider_group.spinbox.setValue(1000.0)
    assert dlg.x_slider_group.value < 100

    plotter._last_update_time = 0.0
    plotter.update_app_icon()

    assert plotter.quit() is None
 def plot_boreholes(self, notebook=False, background=False, **kwargs):
     """
     Uses the previously calculated borehole tubes in self._get_polygon_data()
     when a borehole dictionary is available
     This will generate a pyvista object that can be visualized with .show()
     Args:
         notebook: If using in notebook to show inline
         background:
     Returns:
         Pyvista object with all the boreholes
     """
     self._get_polygon_data()
     if background:
         p = pv.BackgroundPlotter(**kwargs)
     else:
         p = pv.Plotter(notebook=notebook, **kwargs)
     for i in range(len(self.borehole_tube)):
         cmap = self.colors_bh[i]
         p.add_mesh(self.borehole_tube[i],
                    cmap=[cmap[j] for j in range(len(cmap) - 1)],
                    smooth_shading=False)
     # for i in range(len(self.faults_bh)):
     # for plotting the faults
     # TODO: Messing with the colors when faults
     if len(self.faults_bh) > 0:
         point = pv.PolyData(self.faults_bh)
         p.add_mesh(point,
                    render_points_as_spheres=True,
                    point_size=self._radius_borehole)
         # p.add_mesh(point, cmap = self.faults_color_bh[i],
         # render_points_as_spheres=True, point_size=self._radius_borehole)
     extent = numpy.copy(self._model_extent)
     # extent[-1] = numpy.ceil(self.modelspace_arucos.box_z.max()/100)*100
     p.show_bounds(bounds=extent)
     p.show_grid()
     p.set_scale(zscale=self._ve)
     # self.vtk = pn.panel(p.ren_win, sizing_mode='stretch_width', orientation_widget=True)
     # self.vtk = pn.Row(pn.Column(pan, pan.construct_colorbars()), pn.pane.Str(type(p.ren_win), width=500))
     return p
def get_min_SF_graph_compare(ls,
                             knn1,
                             filename,
                             NNeighbors=1024,
                             type='distance',
                             last=False):
    # print(filename)

    plotter = pv.BackgroundPlotter(shape=(2, 4))

    for idx, file_id in enumerate(ls):
        if file_id > 0:
            file = filename.filepath[file_id]
            poly, data = readVTP(file)
            MinSF = get_MinSF(data)
            _, _, nearpoints2000 = get_Nearpoints(data, MinSF, NNeighbors * 2)
            nearpoints2000 = nearpoints2000[:, 1:]

            distance, indexes, nearpoints1000 = get_Nearpoints(
                data, MinSF, NNeighbors)

            plotter.subplot(idx // 4, idx % 4)
            plotter.add_point_labels(MinSF[1:], ['minSF'],
                                     font_size=12,
                                     point_color="red",
                                     text_color="red")

            plotter.add_text(str(file_id), font_size=12)

            point_cloudall = pv.PolyData(nearpoints2000)
            plotter.add_mesh(point_cloudall,
                             color='white',
                             point_size=2.,
                             render_points_as_spheres=True)
            if type == 'SF':
                point_cloud = pv.PolyData(nearpoints1000[:, 1:4])
                plotter.add_mesh(point_cloud,
                                 scalars=nearpoints1000[:, 0],
                                 stitle='safety factor',
                                 point_size=5.,
                                 render_points_as_spheres=True,
                                 interpolate_before_map=True)
            elif type == 'distance':
                point_cloud = pv.PolyData(nearpoints1000[:, 1:4])
                plotter.add_mesh(point_cloud,
                                 scalars=distance,
                                 stitle='distance',
                                 point_size=5.,
                                 render_points_as_spheres=True,
                                 interpolate_before_map=True)
            elif type == 'knn1':
                point_cloud = pv.PolyData(nearpoints1000[:, 1:4])
                plotter.add_mesh(point_cloud,
                                 scalars=knn1[file_id],
                                 stitle=f'knn1',
                                 point_size=5.,
                                 render_points_as_spheres=True,
                                 interpolate_before_map=True)
    # plotter.link_views()
    plotter.show()
    if last:
        plotter.app.exec_()
def get_min_SF_graph(knn, ls, filename, NNeighbors=1024, last=False):
    for i, file in enumerate(filename.filepath):
        if i in ls:
            poly, data = readVTP(file)
            MinSF = get_MinSF(data)

            _, _, nearpoints2000 = get_Nearpoints(data, MinSF, NNeighbors * 2)
            nearpoints2000 = nearpoints2000[:, 1:]

            distance, indexes, nearpoints1000 = get_Nearpoints(
                data, MinSF, NNeighbors)

            normals = get_normals(data)[indexes]
            normals_distance = closest_node(normals[0], normals)
            # min-max normalize
            normal_nearpoints, normal_distance, normals = normalize_coordinate_pos(
                nearpoints1000, distance, normals_distance)

            plotter = pv.BackgroundPlotter(shape=(2, 3))

            for j in range(len(knn) + 2):
                plotter.subplot(j // 3, j % 3)

                point_cloudall = pv.PolyData(nearpoints2000)
                plotter.add_mesh(point_cloudall,
                                 color='white',
                                 point_size=2.,
                                 render_points_as_spheres=True)
                if j == 0:
                    point_cloud = pv.PolyData(nearpoints1000[:, 1:])
                    plotter.add_mesh(point_cloud,
                                     scalars=normal_nearpoints[:, 0],
                                     stitle='safety factor',
                                     point_size=5.,
                                     render_points_as_spheres=True,
                                     interpolate_before_map=True)
                elif j == 1:
                    point_cloud = pv.PolyData(nearpoints1000[:, 1:])
                    plotter.add_mesh(point_cloud,
                                     scalars=normal_distance,
                                     stitle='distance',
                                     point_size=5.,
                                     render_points_as_spheres=True,
                                     interpolate_before_map=True)
                else:
                    point_cloud = pv.PolyData(nearpoints1000[:, 1:])
                    plotter.add_mesh(point_cloud,
                                     scalars=knn[j - 2][i],
                                     stitle=f'knn{j - 1}',
                                     point_size=5.,
                                     render_points_as_spheres=True,
                                     interpolate_before_map=True)

                minpoint = pv.PolyData(MinSF[1:])
                plotter.add_mesh(minpoint,
                                 scalars=MinSF[0],
                                 point_size=8,
                                 render_points_as_spheres=True)
                # plotter.show_grid()

            plotter.link_views()
            plotter.show()
    if last:
        plotter.app.exec_()
Example #30
0
    def __init__(self,
                 model,
                 plotter_type: str = 'basic',
                 extent=None,
                 lith_c=None,
                 live_updating=False,
                 **kwargs):
        """GemPy 3-D visualization using pyVista.

        Args:
            model (gp.Model): Geomodel instance with solutions.
            plotter_type (str): Set the plotter type. Defaults to 'basic'.
            extent (List[float], optional): Custom extent. Defaults to None.
            lith_c (pn.DataFrame, optional): Custom color scheme in the form of
                a look-up table. Defaults to None.
            live_updating (bool, optional): Toggles real-time updating of the
                plot. Defaults to False.
            **kwargs:

        """

        # Override default notebook value
        pv.set_plot_theme("document")
        kwargs['notebook'] = kwargs.get('notebook', False)

        # Model properties
        self.model = model
        self.extent = model._grid.regular_grid.extent if extent is None else extent

        # plotting options
        self.live_updating = live_updating

        # Choosing plotter
        if plotter_type == 'basic':
            self.p = pv.Plotter(**kwargs)
            self.p.view_isometric(negative=False)
        elif plotter_type == 'notebook':
            raise NotImplementedError
            # self.p = pv.PlotterITK()
        elif plotter_type == 'background':
            try:
                self.p = pv.BackgroundPlotter(**kwargs)
            except pv.QtDeprecationError:
                from pyvistaqt import BackgroundPlotter
                self.p = BackgroundPlotter(**kwargs)
            self.p.view_isometric(negative=False)
        else:
            raise AttributeError(
                'Plotter type must be basic, background or notebook.')

        self.plotter_type = plotter_type
        # Default camera and bounds
        self.set_bounds()
        self.p.view_isometric(negative=False)

        # Actors containers
        self.surface_actors = {}
        self.surface_poly = {}

        self.regular_grid_actor = None
        self.regular_grid_mesh = None

        self.surface_points_actor = None
        self.surface_points_mesh = None
        self.surface_points_widgets = {}

        self.orientations_actor = None
        self.orientations_mesh = None
        self.orientations_widgets = {}

        # Private attributes
        self._grid_values = None
        col = matplotlib.cm.get_cmap('viridis')(np.linspace(0, 1, 255)) * 255
        nv = numpy_to_vtk(col, array_type=3)
        self._cmaps = {'viridis': nv}

        # Topology properties
        self.topo_edges = None
        self.topo_ctrs = None