Example #1
0
    def set_background(self, color, top=None):
        """Set the 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'
        top : string or 3 item list, optional, defaults to None
            If given, this will enable a gradient background where the
            ``color`` argument is at the bottom and the color given in ``top``
            will be the color at the top of the renderer.
        """
        if color is None:
            color = rcParams['background']

        use_gradient = False
        if top is not None:
            use_gradient = True
        c = parse_color(color)
        self.SetBackground(c)
        if use_gradient:
            self.GradientBackgroundOn()
            self.SetBackground2(parse_color(top))
        else:
            self.GradientBackgroundOff()
        self.Modified()
    def add_mesh(self, mesh, color=None, scalars=None, clim=None,
                 opacity=1.0, n_colors=256, cmap='Viridis (matplotlib)',
                 **kwargs):
        """Add mesh to the scene."""
        if not pv.is_pyvista_dataset(mesh):
            mesh = pv.wrap(mesh)
        mesh = mesh.copy()
        if scalars is None and color is None:
            scalars = mesh.active_scalars_name

        if scalars is not None:
            array = mesh[scalars].copy()
            mesh.clear_arrays()
            mesh[scalars] = array
            mesh.active_scalars_name = scalars
        elif color is not None:
            mesh.clear_arrays()


        mesh = to_geometry(mesh)
        self._geometries.append(mesh)
        self._geometry_colors.append(pv.parse_color(color))
        self._geometry_opacities.append(opacity)
        self._cmap = cmap

        return
    def add_points(self, points, color=None):
        """Add XYZ points to the scene."""
        if pv.is_pyvista_dataset(points):
            point_array = points.points
        else:
            point_array = points

        self._point_set_colors.append(pv.parse_color(color))
        self._point_sets.append(point_array)
Example #4
0
def test_set_background():
    plotter = pyvista.Plotter(off_screen=OFF_SCREEN)
    plotter.set_background('k')
    plotter.set_background([0, 0, 0], top=[1,1,1]) # Gradient
    plotter.show()

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN, shape=(1,2))
    plotter.set_background('orange')
    for renderer in plotter.renderers:
        assert renderer.GetBackground() == pyvista.parse_color('orange')
    plotter.show()

    plotter = pyvista.Plotter(off_screen=OFF_SCREEN, shape=(1,2))
    plotter.subplot(0,1)
    plotter.set_background('orange', all_renderers=False)
    assert plotter.renderers[0].GetBackground() != pyvista.parse_color('orange')
    assert plotter.renderers[1].GetBackground() == pyvista.parse_color('orange')
    plotter.show()
Example #5
0
    def background_color(self, color):
        """Set the background color of the plotter.

        Examples
        --------
        Set the background color to black

        >>> plotter.background_color = 'k'
        """
        self._background_color = pv.parse_color(color)
Example #6
0
def test_set_background():
    plotter = pyvista.Plotter()
    plotter.set_background('k')
    plotter.background_color = "yellow"
    plotter.set_background([0, 0, 0], top=[1, 1, 1])  # Gradient
    plotter.background_color
    plotter.show()

    plotter = pyvista.Plotter(shape=(1, 2))
    plotter.set_background('orange')
    for renderer in plotter.renderers:
        assert renderer.GetBackground() == pyvista.parse_color('orange')
    plotter.show()

    plotter = pyvista.Plotter(shape=(1, 2))
    plotter.subplot(0, 1)
    plotter.set_background('orange', all_renderers=False)
    assert plotter.renderers[0].GetBackground() != pyvista.parse_color('orange')
    assert plotter.renderers[1].GetBackground() == pyvista.parse_color('orange')
    plotter.show(before_close_callback=verify_cache_image)
Example #7
0
def test_plot_silhouette(tri_cylinder):
    # silhouette=True and default properties
    plotter = pyvista.Plotter()
    plotter.add_mesh(tri_cylinder, silhouette=True)
    actors = list(plotter.renderer.GetActors())
    assert len(actors) == 2  # cylinder + silhouette
    actor = actors[0]  # get silhouette actor
    props = actor.GetProperty()
    assert props.GetColor() == pyvista.parse_color(pyvista.rcParams["silhouette"]["color"])
    assert props.GetOpacity() == pyvista.rcParams["silhouette"]["opacity"]
    assert props.GetLineWidth() == pyvista.rcParams["silhouette"]["line_width"]
    plotter.show(before_close_callback=verify_cache_image)
Example #8
0
    def add_points(self, points, color=None, point_size=3.0):
        """Add points to plotter.

        Parameters
        ----------
        points : np.ndarray or pyvista.DataSet
            n x 3 numpy array of points or pyvista dataset with points.

        color : string or 3 item list, optional. Color of points (if visible).
            Either a string, rgb list, or hex color string.  For example:

            ``color='white'``
            ``color='w'``
            ``color=[1, 1, 1]``
            ``color='#FFFFFF'``

        point_size : float, optional
            Point size of any nodes in the dataset plotted. Also applicable
            when style='points'. Default ``3.0``

        Examples
        --------
        Add 10 random points to the plotter

        >>> add_points(np.random.random((10, 3)), 'r', 10)  # doctest:+SKIP
        """
        if pv.is_pyvista_dataset(points):
            point_array = points.points
        else:
            point_array = points


        # style : str, optional
        #     How to represent the point set. One of ``'hidden'``,
        #     ``'points'``, or ``'spheres'``.


        # if style not in ['hidden', 'points', 'spheres']:
        #     raise ValueError("``style`` must be either 'hidden', 'points', or"
        #                      "'spheres'")

        if not isinstance(point_size, (int, float)):
            raise TypeError('``point_size`` parameter must be a float')

        self._point_set_sizes.append(point_size)
        self._point_set_colors.append(pv.parse_color(color))
        self._point_sets.append(point_array)
Example #9
0
    def add_points(self, points, color=None):
        """Add points to plotting object.

        Parameters
        ----------
        points : np.ndarray or pyvista.Common
            n x 3 numpy array of points or pyvista dataset with points.

        color : string or 3 item list, optional. Color of points (if visible).
            Either a string, rgb list, or hex color string.  For example:

            color='white'
            color='w'
            color=[1, 1, 1]
            color='#FFFFFF'
        """
        if pv.is_pyvista_dataset(points):
            point_array = points.points
        else:
            point_array = points

        self._point_set_colors.append(pv.parse_color(color))
        self._point_sets.append(point_array)
Example #10
0
    def add_mesh(self,
                 mesh,
                 color=None,
                 scalars=None,
                 opacity=1.0,
                 smooth_shading=False):
        """Add a PyVista/VTK mesh or dataset.

        Adds any PyVista/VTK mesh that itkwidgets can wrap to the
        scene.

        Parameters
        ----------
        mesh : pyvista.DataSet or pyvista.MultiBlock
            Any PyVista or VTK mesh is supported. Also, any dataset
            that :func:`pyvista.wrap` can handle including NumPy arrays of XYZ
            points.

        color : string or 3 item list, optional, defaults to white
            Use to make the entire mesh have a single solid color.
            Either a string, RGB list, or hex color string.  For example:
            ``color='white'``, ``color='w'``, ``color=[1, 1, 1]``, or
            ``color='#FFFFFF'``. Color will be overridden if scalars are
            specified.

        scalars : str or numpy.ndarray, optional
            Scalars used to "color" the mesh.  Accepts a string name of an
            array that is present on the mesh or an array equal
            to the number of cells or the number of points in the
            mesh.  Array should be sized as a single vector. If both
            ``color`` and ``scalars`` are ``None``, then the active scalars are
            used.

        opacity : float, optional
            Opacity of the mesh. If a single float value is given, it will be
            the global opacity of the mesh and uniformly applied everywhere -
            should be between 0 and 1.  Default 1.0

        smooth_shading : bool, optional
            Smooth mesh surface mesh by taking into account surface
            normals.  Surface will appear smoother while sharp edges
            will still look sharp.  Default False.

        """
        if not pv.is_pyvista_dataset(mesh):
            mesh = pv.wrap(mesh)

        # smooth shading requires point normals to be freshly computed
        if smooth_shading:
            # extract surface if mesh is exterior
            if not isinstance(mesh, pv.PolyData):
                grid = mesh
                mesh = grid.extract_surface()
                ind = mesh.point_arrays['vtkOriginalPointIds']
                # remap scalars
                if isinstance(scalars, np.ndarray):
                    scalars = scalars[ind]

            mesh.compute_normals(cell_normals=False, inplace=True)
        elif 'Normals' in mesh.point_arrays:
            # if 'normals' in mesh.point_arrays:
            mesh.point_arrays.pop('Normals')

        # make the scalars active
        if isinstance(scalars, str):
            if scalars in mesh.point_arrays or scalars in mesh.cell_arrays:
                array = mesh[scalars].copy()
            else:
                raise ValueError(f'Scalars ({scalars}) not in mesh')
            mesh[scalars] = array
            mesh.active_scalars_name = scalars
        elif isinstance(scalars, np.ndarray):
            array = scalars
            scalar_name = '_scalars'
            mesh[scalar_name] = array
            mesh.active_scalars_name = scalar_name
        elif color is not None:
            mesh.active_scalars_name = None

        # itkwidgets does not support VTK_ID_TYPE
        if 'vtkOriginalPointIds' in mesh.point_arrays:
            mesh.point_arrays.pop('vtkOriginalPointIds')

        if 'vtkOriginalCellIds' in mesh.cell_arrays:
            mesh.cell_arrays.pop('vtkOriginalCellIds')

        from itkwidgets._transform_types import to_geometry
        mesh = to_geometry(mesh)
        self._geometries.append(mesh)
        self._geometry_colors.append(pv.parse_color(color))
        self._geometry_opacities.append(opacity)
Example #11
0
def test_widget_slider():
    p = pyvista.Plotter()
    func = lambda value: value  # Does nothing
    p.add_mesh(mesh)
    p.add_slider_widget(callback=func, rng=[0, 10], style="classic")
    p.close()

    p = pyvista.Plotter()
    for event_type in ['start', 'end', 'always']:
        p.add_slider_widget(callback=func, rng=[0, 10], event_type=event_type)
    with pytest.raises(TypeError, match='type for ``style``'):
        p.add_slider_widget(callback=func, rng=[0, 10], style=0)
    with pytest.raises(AttributeError):
        p.add_slider_widget(callback=func, rng=[0, 10], style="foo")
    with pytest.raises(TypeError, match='type for `event_type`'):
        p.add_slider_widget(callback=func, rng=[0, 10], event_type=0)
    with pytest.raises(ValueError, match='value for `event_type`'):
        p.add_slider_widget(callback=func, rng=[0, 10], event_type='foo')
    p.close()

    p = pyvista.Plotter()
    func = lambda value, widget: value  # Does nothing
    p.add_mesh(mesh)
    p.add_slider_widget(callback=func,
                        rng=[0, 10],
                        style="modern",
                        pass_widget=True)
    p.close()

    p = pyvista.Plotter()
    p.add_mesh_threshold(mesh, invert=True)
    p.add_mesh(mesh.outline())
    p.close()

    p = pyvista.Plotter()
    p.add_mesh_threshold(mesh, invert=False)
    p.add_mesh(mesh.outline())
    p.close()

    p = pyvista.Plotter()
    p.add_mesh_isovalue(mesh)
    p.close()

    p = pyvista.Plotter()
    title_height = np.random.random()
    s = p.add_slider_widget(callback=func,
                            rng=[0, 10],
                            style="classic",
                            title_height=title_height)
    assert s.GetRepresentation().GetTitleHeight() == title_height
    p.close()

    p = pyvista.Plotter()
    title_opacity = np.random.random()
    s = p.add_slider_widget(callback=func,
                            rng=[0, 10],
                            style="classic",
                            title_opacity=title_opacity)
    assert s.GetRepresentation().GetTitleProperty().GetOpacity(
    ) == title_opacity
    p.close()

    p = pyvista.Plotter()
    title_color = "red"
    s = p.add_slider_widget(callback=func,
                            rng=[0, 10],
                            style="classic",
                            title_color=title_color)
    assert s.GetRepresentation().GetTitleProperty().GetColor(
    ) == pyvista.parse_color(title_color)
    p.close()

    p = pyvista.Plotter()
    fmt = "%0.9f"
    s = p.add_slider_widget(callback=func,
                            rng=[0, 10],
                            style="classic",
                            fmt=fmt)
    assert s.GetRepresentation().GetLabelFormat() == fmt
    p.close()
###############################################################################
# load the gravity model
gf = gdc19.get_gravity_path('forge_inverse_problem/RESULT_THRESHED.vtu')
grav_model = pyvista.read(gf)
grav_model.active_scalar_name = 'Magnitude'

###############################################################################
# Plotting Helpers
# ++++++++++++++++
#
# Functions for adding datasets to a scene in a consistent manner

POINT_SIZE = 15
LINE_WIDTH = 15
pyvista.rcParams['window_size'] = np.array([1024, 768]) * 2
legend_color = pyvista.parse_color('lightgrey')

###############################################################################


def clip_it(data, bounds):
    if bounds is None:
        return data
    return data.clip_box(bounds, invert=False)


def add_topo(p, bounds=None):
    data = clip_it(topo, bounds)
    if data.n_points < 1:
        return
    # We can update this to change the texture