Ejemplo n.º 1
0
def plot_mesh(self, indices=[]):
    """Plot the mesh using pyvista plotter.

    Parameters
    ----------
    self : MeshVTK
        a MeshVTK object
    indices : list
        list of the points to extract (optional)

    Returns
    -------
    """

    mesh = self.get_mesh(indices)

    # Configure plot
    p = pv.BackgroundPlotter()
    p.set_background("white")
    p.add_mesh(mesh,
               color="grey",
               opacity=1,
               show_edges=True,
               edge_color="white",
               line_width=1)
    p.show()
Ejemplo n.º 2
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 = pvqt.BackgroundPlotter(**kwargs)

        self.set_bounds()
        self.p.view_isometric(negative=False)
Ejemplo n.º 3
0
def plot_contour(self,
                 field,
                 field_name="Magnitude",
                 indices=[],
                 cmap="RdBu_r"):
    """Plot a scalar field as a color contour over a mesh.

    Parameters
    ----------
    self : MeshVTK
        a MeshVTK object
    field : ndarray
        array of the field
    indices : list
        list of the points to extract (optional)

    Returns
    -------
    """

    # Get the mesh
    mesh = self.get_mesh(indices)

    # Extract subset of the field if necessary
    if indices != [] and field.shape != indices.shape:
        field = field[indices]

    # Add field to mesh
    mesh[field_name] = field

    # Configure plot
    p = pv.BackgroundPlotter()
    p.set_background("white")
    sargs = dict(
        interactive=True,
        title_font_size=20,
        label_font_size=16,
        font_family="arial",
        color="black",
    )
    p.add_mesh(
        mesh,
        scalars=field_name,
        show_edges=True,
        edge_color="white",
        line_width=1,
        cmap=cmap,
        scalar_bar_args=sargs,
    )
    p.show()
Ejemplo n.º 4
0
    def __init__(self,
                 model: gp.Model,
                 extent: List[float] = None,
                 color_lot: pn.DataFrame = None,
                 real_time: bool = False,
                 lith_c: pn.DataFrame = None,
                 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 plotter_type == 'basic':
            self.p = pv.Plotter(**kwargs)
        elif plotter_type == 'background':
            self.p = pvqt.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()
        self.p.view_isometric(negative=False)
Ejemplo n.º 5
0
def plot_deformation(self, field, indices=[], factor=1):
    """Plot a vector field as glyphs over a mesh.

    Parameters
    ----------
    self : MeshVTK
        a MeshVTK object
    field : ndarray
        array of the field
    indices : list
        list of the points to extract (optional)
    factor : float
        factor to multiply the field vectors for visualization

    Returns
    -------
    """

    # Get the mesh
    mesh = self.get_mesh(indices)

    # Extract subset of the field if necessary
    if indices != [] and field.shape != indices.shape:
        field = field[indices]

    # Add field to mesh
    mesh.vectors = field * factor

    # Warp by vectors
    mesh_warp = mesh.warp_by_vector()

    # Configure plot
    p = pv.BackgroundPlotter()
    p.set_background("white")
    p.add_mesh(
        mesh_warp,
        color="grey",
        opacity=1,
        show_edges=True,
        edge_color="white",
        line_width=1,
    )
    p.show()
Ejemplo n.º 6
0
def plot_glyph(self, field, indices=[], factor=1):
    """Plot a vector field as glyphs over a mesh.

    Parameters
    ----------
    self : MeshVTK
        a MeshVTK object
    field : ndarray
        array of the field
    indices : list
        list of the points to extract (optional)
    factor : float
        factor to multiply the field vectors for visualization

    Returns
    -------
    """

    # Get the mesh
    mesh = self.get_mesh(indices)

    # Extract subset of the field if necessary
    if indices != [] and field.shape != indices.shape:
        field = field[indices]

    # Add field to mesh
    mesh["field"] = field
    mesh_cell = mesh.point_data_to_cell_data()
    surf = mesh_cell.extract_surface()
    centers2 = surf.cell_centers()
    centers2.vectors = surf["field"] * factor

    # Configure plot
    p = pv.BackgroundPlotter()
    p.set_background("white")
    p.add_mesh(mesh,
               color="grey",
               opacity=0.7,
               show_edges=True,
               edge_color="white")
    p.add_mesh(centers2.arrows, color="white")
    p.show()
Ejemplo n.º 7
0
    def view_obj(self):
        if sys.platform == "win32":
            homepath = os.environ["HOMEPATH"]
        if sys.platform == "linux":
            homepath = os.environ["HOME"]

        fname = QFileDialog.getOpenFileName(self, "Open file", homepath, "OBJ file (*.obj)")

        if self.ui.checkBox_wireframe.isChecked():
            edges = True
            opacity = 0.5
            text = os.path.basename(fname[0]) + " wireframe"
        else:
            edges = False
            opacity = 1
            text = os.path.basename(fname[0])

        if fname[0]:
            mesh = pyvista.read(fname[0])
            plotter = pyvistaqt.BackgroundPlotter()
            plotter.add_mesh(mesh, show_edges=edges, opacity=opacity, color='blue')
            plotter.add_text(text)
            plotter.show_axes()
Ejemplo n.º 8
0
# Check if we are running on CI server and reduce run time
if "CI" in os.environ.keys() or "GITHUB_ACTIONS" in os.environ.keys():
    T = 3 * dt
else:
    T = 50 * dt

u.vector.copy(result=u0.vector)
u.x.scatter_forward()

# Prepare viewer for plotting solution during the computation
if have_pyvista:
    topology, cell_types = plot.create_vtk_topology(mesh, mesh.topology.dim)
    grid = pv.UnstructuredGrid(topology, cell_types, mesh.geometry.x)
    grid.point_arrays["u"] = u.sub(0).compute_point_values().real
    grid.set_active_scalars("u")
    p = pvqt.BackgroundPlotter(title="concentration", auto_update=True)
    p.add_mesh(grid, clim=[0, 1])
    p.view_xy(True)
    p.add_text(f"time: {t}", font_size=12, name="timelabel")

while (t < T):
    t += dt
    r = solver.solve(u)
    print(f"Step {int(t/dt)}: num iterations: {r[0]}")
    u.vector.copy(result=u0.vector)
    file.write_function(u.sub(0), t)

    # Update the plot window
    if have_pyvista:
        p.add_text(f"time: {t:.2e}", font_size=12, name="timelabel")
        grid.point_arrays["u"] = u.sub(0).compute_point_values().real
Ejemplo n.º 9
0
def plot_deflection(
    self,
    label=None,
    index=None,
    indices=None,
    clim=None,
    factor=None,
    field_name=None,
    ifreq=0,
    save_path=None,
    title="",
    win_title=None,
    is_surf=True,
):
    """Plot the operational deflection shape using pyvista plotter.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    clim : list
        a list of 2 elements for the limits of the colorbar
    factor : float
        factor to multiply vector field
    field_name : str
        title of the field to display on plot
    ifreq : int
        index of the frequency to use for plot (if exists)

    Returns
    -------
    """

    if save_path is None:
        try:
            import pyvistaqt as pv

            is_pyvistaqt = True
        except:
            import pyvista as pv

            is_pyvistaqt = False
    else:
        import pyvista as pv

        is_pyvistaqt = False

    if save_path is None:
        try:
            import pyvistaqt as pv

            is_pyvistaqt = True
        except:
            import pyvista as pv

            is_pyvistaqt = False
    else:
        import pyvista as pv

        is_pyvistaqt = False

    if title != "" and win_title == "":
        win_title = title
    elif win_title != "" and title == "":
        title = win_title

    # Get the mesh
    mesh = self.get_mesh(label=label, index=index)
    if isinstance(mesh, MeshMat):
        mesh_pv = mesh.get_mesh_pv(indices=indices)
        mesh = MeshVTK(mesh=mesh_pv, is_pyvista_mesh=True)

    # Get the field
    field = real(
        self.get_field(label=label,
                       index=index,
                       indices=indices,
                       is_surf=is_surf,
                       is_radial=True))
    vect_field = real(self.get_field(label=label, index=index,
                                     indices=indices))
    if len(field.shape) == 2:
        # Third dimension is frequencies
        field = field[:, ifreq]
        vect_field = vect_field[:, :, ifreq]
    if field_name is None:
        if label is not None:
            field_name = label
        elif self.get_solution(index=index).label is not None:
            field_name = self.get_solution(index=index).label
        else:
            field_name = "Field"

    # Compute colorbar boundaries
    if clim is None:
        clim = [np_min(real(field)), np_max(real(field))]
        if (clim[1] - clim[0]) / clim[1] < 0.01:
            clim[0] = -clim[1]

    # Compute deformation factor
    if factor is None:
        factor = 1 / (100 * clim[1])

    # Extract surface
    if is_surf:
        surf = mesh.get_surf(indices=indices)
    else:
        surf = mesh.get_mesh_pv(indices=indices)

    # Add field to surf
    surf.vectors = real(vect_field) * factor

    # Warp by vectors
    surf_warp = surf.warp_by_vector()

    # Add radial field
    surf_warp[field_name] = real(field)

    # Configure plot
    if is_pyvistaqt:
        p = pv.BackgroundPlotter()
        p.set_background("white")
    else:
        pv.set_plot_theme("document")
        p = pv.Plotter(notebook=False, title=win_title)
    sargs = dict(
        interactive=True,
        title_font_size=20,
        label_font_size=16,
        font_family="arial",
        color="black",
    )
    p.add_mesh(
        surf_warp,
        scalars=field_name,
        opacity=1,
        show_edges=False,
        cmap=COLOR_MAP,
        clim=clim,
        scalar_bar_args=sargs,
    )
    p.add_text(title, position="upper_edge")
    if self.dimension == 2:
        p.view_xy()
    if save_path is None:
        p.show()
    else:
        p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 10
0
def plot_deflection(
    self,
    *args,
    label=None,
    index=None,
    indices=None,
    clim=None,
    factor=None,
    field_name=None,
    group_names=None,
    save_path=None,
    title="",
    win_title=None,
    is_surf=True,
    is_show_fig=True,
):
    """Plot the operational deflection shape using pyvista plotter.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    clim : list
        a list of 2 elements for the limits of the colorbar
    factor : float
        factor to multiply vector field
    field_name : str
        title of the field to display on plot
    is_show_fig : bool
        To call show at the end of the method

    Returns
    -------
    """
    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_deflection(
            *args,
            label=label,
            index=index,
            indices=indices,
            clim=clim,
            factor=factor,
            field_name=field_name,
            save_path=save_path,
            title=title,
            win_title=win_title,
            is_surf=is_surf,
            is_show_fig=is_show_fig,
            group_names=None,
        )
    else:
        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        if title != "" and win_title == "":
            win_title = title
        elif win_title != "" and title == "":
            title = win_title

        # Get mesh and field
        mesh_pv, field, field_name = self.get_mesh_field_pv(
            *args,
            label=label,
            index=index,
            indices=indices,
            field_name=field_name,
            is_radial=True,
        )
        mesh = MeshVTK(mesh=mesh_pv, is_pyvista_mesh=True)
        _, vect_field, _ = self.get_mesh_field_pv(
            *args,
            label=label,
            index=index,
            indices=indices,
            field_name=field_name,
            is_radial=False,
        )

        if field_name is None:
            if label is not None:
                field_name = label
            elif self.get_solution(index=index).label is not None:
                field_name = self.get_solution(index=index).label
            else:
                field_name = "Field"

        # Compute colorbar boundaries
        if clim is None:
            clim = [np_min(real(field)), np_max(real(field))]
            if (clim[1] - clim[0]) / clim[1] < 0.01:
                clim[0] = -abs(clim[1])
                clim[1] = abs(clim[1])

        # Compute deformation factor
        if factor is None:
            # factor = 1 / (100 * clim[1])
            factor = 1 / clim[1] * 10

        # Add third dimension if needed
        solution = self.get_solution(
            label=label,
            index=index,
        )
        if solution.dimension == 2:
            vect_field = hstack((vect_field, zeros((vect_field.shape[0], 1))))

        # Extract surface
        if is_surf:
            surf = mesh.get_surf(indices=indices)
        else:
            surf = mesh.get_mesh_pv(indices=indices)

        # Add field to surf
        surf.vectors = real(vect_field) * factor

        # Warp by vectors
        surf_warp = surf.warp_by_vector()

        # Add radial field
        surf_warp[field_name] = real(field)

        # Configure plot
        if is_pyvistaqt:
            p = pv.BackgroundPlotter()
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False, title=win_title)
        sargs = dict(
            interactive=True,
            title_font_size=20,
            label_font_size=16,
            font_family="arial",
            color="black",
        )
        p.add_mesh(mesh_pv,
                   color="grey",
                   opacity=1,
                   show_edges=True,
                   edge_color="white")
        p.set_position((0.2, 0.2, 0.5))
        p.reset_camera()
        p.clear()
        p.add_mesh(
            surf_warp,
            scalars=field_name,
            opacity=1,
            show_edges=False,
            cmap=COLOR_MAP,
            clim=clim,
            scalar_bar_args=sargs,
        )
        p.add_text(title, position="upper_edge")
        p.add_axes()
        if self.dimension == 2:
            p.view_xy()
        if save_path is None and is_show_fig:
            p.show()
        elif save_path is not None:
            p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 11
0
    # to NaN.
    block_inds = np.empty(FF.num_faces, dtype=np.float64)
    block_inds[...] = np.nan
    for i, row_inds in enumerate(FF.get_row_inds_at_depth(depth)):
        block_inds[row_inds] = i

    # Get the number of blocks at this depth.
    num_blocks_at_depth = len(list(FF.get_blocks_at_depth(depth)))

    # Set up a trimesh with the block indices as a cell array for
    # plotting.
    tri_mesh = pv.make_tri_mesh(FF.shape_model.V, FF.shape_model.F)
    tri_mesh.cell_arrays['block_inds'] = block_inds

    # We want to use the same camera for each plot. We set it up here.
    V_ptp = FF.shape_model.V.ptp(0)
    V_mean = FF.shape_model.V.mean(0)
    camera = pv.Camera()
    camera.position = V_mean + np.array([0, 0, 2.2*V_ptp[:2].mean()])
    camera.focal_point = V_mean
    camera.up = np.array([1, 0, 0])

    # Make plot using PyVista
    plotter = pvqt.BackgroundPlotter()
    plotter.add_text(f'Block indices', font_size=12)
    plotter.add_mesh(tri_mesh, clim=(0, num_blocks_at_depth),
                     lighting=False, cmap=cc.cm.glasbey)
    plotter.remove_scalar_bar()
    plotter.camera = camera
    plotter.show()
Ejemplo n.º 12
0
import time
import numpy as np
from threading import Thread
import pyvista as pv
import pyvistaqt as pvqt
from pyvista import examples

if __name__ == "__main__":

    globe = examples.load_globe()
    globe.point_arrays['scalars'] = np.random.rand(globe.n_points)
    globe.set_active_scalars('scalars')

    # Create background plotter
    plotter_bg = pvqt.BackgroundPlotter()
    plotter_bg.add_mesh(globe, scalars='scalars', lighting=False, show_edges=True, texture=True)
    plotter_bg.view_isometric()

    # Change globe size in the background
    def change_size():
        for i in range(50):
            globe.points *= 0.95
            globe.point_arrays['scalars'] = np.random.rand(globe.n_points)
            time.sleep(0.5)

    thread = Thread(target=change_size)
    thread.start()

    plotter_bg.app.exec_()
Ejemplo n.º 13
0
def plot_mesh(
    self,
    label=None,
    index=None,
    indices=None,
    save_path=None,
    group_names=None,
):
    """Plot the mesh using pyvista plotter.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)

    Returns
    -------
    """
    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_mesh(
            label,
            index,
            indices,
            save_path,
            None,
        )
    else:

        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        print(save_path)

        # Get the mesh
        mesh_obj = self.get_mesh(label=label, index=index)
        if isinstance(mesh_obj, MeshMat):
            mesh = mesh_obj.get_mesh_pv(indices=indices)
        else:
            mesh = mesh_obj.get_mesh(indices=indices)

        # Configure plot
        if is_pyvistaqt:
            p = pv.BackgroundPlotter()
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False)
        p.add_mesh(
            mesh,
            color="grey",
            opacity=1,
            show_edges=True,
            edge_color="white",
            line_width=1,
        )
        if self.dimension == 2:
            p.view_xy()
        if save_path is None:
            p.show()
        else:
            p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 14
0
 def __init__(self):
     self._plotter = pyvistaqt.BackgroundPlotter()
Ejemplo n.º 15
0
def plot_mesh(
    self,
    p=None,
    label=None,
    index=None,
    indices=None,
    save_path=None,
    group_names=None,
    node_label=None,
    is_show_axes=False,
    is_show_fig=True,
    is_show_grid=False,
    win_title=None,
):
    """Plot the mesh using pyvista plotter.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    p : a pyvista(qt) object, optional
        a pyvista object which will be used for the plot
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    is_show_axes : bool
        True to show axes
    is_show_fig : bool
        To call show at the end of the method
    is_show_grid : bool
        True to show grid

    Returns
    -------
    """

    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_mesh(
            label=label,
            index=index,
            indices=indices,
            save_path=save_path,
            group_names=None,
        )
    else:

        if p is None:
            if save_path is None:
                try:
                    import pyvistaqt as pv

                    is_pyvistaqt = True
                except:
                    import pyvista as pv

                    is_pyvistaqt = False
            else:
                import pyvista as pv

                is_pyvistaqt = False

            print(save_path)

            # Configure plot
            if is_pyvistaqt:
                p = pv.BackgroundPlotter(title=win_title)
                p.set_background("white")
            else:
                pv.set_plot_theme("document")
                p = pv.Plotter(notebook=False, title=win_title)
        else:
            is_show_fig = False
        # Get the mesh
        mesh_obj = self.get_mesh(label=label, index=index)
        if isinstance(mesh_obj, MeshMat):
            new_mesh = mesh_obj.copy()
            new_mesh.renum()
            mesh = new_mesh.get_mesh_pv(indices=indices)
        else:
            mesh = mesh_obj.get_mesh_pv(indices=indices)

        p.add_mesh(
            mesh,
            color="grey",
            opacity=1,
            show_edges=True,
            edge_color="white",
            line_width=1,
        )
        if is_show_axes:
            p.add_axes(color="k",
                       x_color="#da3061",
                       y_color="#0069a1",
                       z_color="#bbcf1c")
        if is_show_grid:
            p.show_grid()
        if self.dimension == 2:
            # 2D view
            p.view_xy()
        else:
            # isometric view with z towards left
            p.view_isometric()
            p.camera_position = [
                p.camera_position[0],
                (
                    p.camera_position[1][0],
                    p.camera_position[1][2],
                    p.camera_position[1][0],
                ),
                (
                    p.camera_position[2][1],
                    p.camera_position[2][2],
                    p.camera_position[2][0],
                ),
            ]
        if save_path is None and is_show_fig:
            p.show()
        elif save_path is not None:  # and is_show_fig:
            p.show(interactive=False, screenshot=save_path)

    return p
Ejemplo n.º 16
0
def plot_glyph(
    self,
    label=None,
    index=None,
    indices=None,
    clim=None,
    factor=None,
    field_name=None,
    ifreq=0,
    save_path=None,
    is_point_arrow=False,
    group_names=None,
):
    """Plot the vector field as a glyph (or quiver) over the mesh.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    clim : list
        a list of 2 elements for the limits of the colorbar
    factor : float
        factor to multiply vector field
    field_name : str
        title of the field to display on plot
    ifreq : int
        index of the frequency to use for plot (if exists)
    save_path : str
        path to save the plot into an image
    is_point_arrow : bool
        to plot a nodal field (point-wise solution required)
    group_names : [str]
        plot is restricted to the group(s) corresponding to this list of group names.


    Returns
    -------
    """
    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_glyph(
            label,
            index,
            indices,
            clim,
            factor,
            field_name,
            ifreq,
            save_path,
            is_point_arrow,
            None,
        )
    else:

        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        # Get the mesh
        mesh = self.get_mesh(label=label, index=index)
        mesh_pv = mesh.get_mesh_pv(indices=indices)

        # Get the vector field
        args = dict()
        args["freq"] = [0]
        args["time"] = [0]
        vect_field = real(
            self.get_field(label=label,
                           index=index,
                           indices=indices,
                           args=args))
        # if len(vect_field.shape) == 3:
        #     # Third dimension is frequencies
        #     vect_field = vect_field[:, :, ifreq]

        # Compute factor
        if factor is None:
            factor = 1 / (100 * np_max(vect_field))

        if self.dimension == 2:
            vect_field = np.hstack(
                (vect_field, np.zeros((vect_field.shape[0], 1))))

        # Add field to mesh
        if is_point_arrow:
            mesh_pv.vectors = vect_field * factor
            arrows_plt = mesh_pv.arrows
        else:
            mesh_pv["field"] = vect_field
            mesh_cell = mesh_pv.point_data_to_cell_data()
            surf = mesh_cell.extract_geometry()
            centers2 = surf.cell_centers()
            centers2.vectors = surf["field"] * factor
            arrows_plt = centers2.arrows

        # Configure plot
        if is_pyvistaqt:
            p = pv.BackgroundPlotter()
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False)
        p.add_mesh(mesh_pv,
                   color="grey",
                   opacity=0.7,
                   show_edges=True,
                   edge_color="white")
        p.add_mesh(arrows_plt, color="red")
        if self.dimension:
            p.view_xy()
        if save_path is None:
            p.show()
        else:
            p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 17
0
def configure_plot(p, win_title, save_path):
    """Configure a pyvista plot. If the plotter doesn't exist, create one depending on avaialble package.

    Parameters
    ----------
    p : pyvista plotter
        a pyvista plotter
    win_title : str
        title of the window
    save_path : str
        path where to save the plot
    """

    if p is None:
        # Configure plot
        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        if is_pyvistaqt:
            p = pv.BackgroundPlotter(title=win_title)
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False, title=win_title)

    # isometric view with z towards left
    p.view_isometric()
    # p.camera_position = [
    #     p.camera_position[0],
    #     (
    #         p.camera_position[1][0],
    #         p.camera_position[1][2],
    #         p.camera_position[1][0],
    #     ),
    #     (
    #         p.camera_position[2][1],
    #         p.camera_position[2][2],
    #         p.camera_position[2][0],
    #     ),
    # ]

    p.add_axes(color="k",
               x_color="#da3061",
               y_color="#0069a1",
               z_color="#bbcf1c")

    sargs = dict(
        interactive=True,
        title_font_size=12,
        label_font_size=10,
        font_family=FONT_FAMILY_PYVISTA,
        color="black",
    )

    return p, sargs
Ejemplo n.º 18
0
def isosurface(
        data,  # complex-valued array 
        isoval=0.5,  # isovalue of surface plot (this value chosen from erf inflection)
        Br=np.eye(3),  # real-space basis
        offset=[0., 0., 0.],  # offset of object centroid
        cartesian_frame=False,  # hack to ensure that the default matrix frame is aligned with the Cartesian frame if necessary.
        smooth=True,  # Gaussian kernel smoothing
        plot_handle=None,  # if not provided, plot in new figure
        mc_spacing=(1., 1., 1.),  # spacing for marching cubes algorithm
        colorbar=None,
        axes=True,
        cmap='viridis'):
    """
    isosurface:
    Designed to work similar to Matlab's isosurface function.
    To add a color scale, the 'colorbar' function argument (default None) should look something like:  
    
    colorbar = { 
        'title':'My title', 
        'vertical':True, 
        'interactive':True,
        'label_font_size':10,
        'title_font_size':25, 
        'font_family':'times', 
        'color':[ 0., 0., 0. ] # black lettering, for default white background. In general, grayscale.
    }
    """
    if smooth:
        amp_s, phs_s = tuple([
            gaussian_filter(field(data), sigma=1.)
            for field in [np.absolute, np.angle]
        ])
    else:
        amp_s, phs_s = tuple(
            [field(data) for field in [np.absolute, np.angle]])
    amp_s /= amp_s.max()
    verts, faces, norms, vals = measure.marching_cubes_lewiner(
        amp_s, level=isoval, spacing=mc_spacing)
    i, j, k = tuple([np.arange(n) for n in data.shape])
    phase = interpolate.interpn((i, j, k), phs_s, verts)
    verts -= verts.mean(axis=0, keepdims=True).repeat(verts.shape[0], axis=0)
    if cartesian_frame:
        R = Rotation.from_rotvec(-np.pi / 2. *
                                 np.array([0., 0., 1.])).as_matrix()
    else:
        R = np.eye(3)
    verts = (R @ Br @ verts.T).T
    verts += np.array(offset).reshape(1, -1).repeat(verts.shape[0], axis=0)
    faces = np.concatenate((3 * np.ones((faces.shape[0], 1)), faces),
                           axis=1).astype(int)
    plotdata = pv.PolyData(verts, np.hstack(faces))
    if plot_handle == None:
        plot_handle = pvqt.BackgroundPlotter()

    plot_handle.set_background(color='white')
    plot_handle.add_mesh(plotdata, scalars=phase, specular=0.5, cmap=cmap)
    if colorbar != None:
        plot_handle.add_scalar_bar(**colorbar)

    if axes:
        plot_handle.add_axes(interactive=True,
                             line_width=10,
                             color=[0., 0., 0.],
                             xlabel='',
                             ylabel='',
                             zlabel='')
    return plot_handle
Ejemplo n.º 19
0
def plot_glyph(
    self,
    *args,
    label=None,
    index=None,
    indices=None,
    clim=None,
    factor=None,
    field_name=None,
    save_path=None,
    is_point_arrow=False,
    group_names=None,
    is_show_fig=True,
):
    """Plot the vector field as a glyph (or quiver) over the mesh.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    *args: list of strings
        List of axes requested by the user, their units and values (optional)
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    clim : list
        a list of 2 elements for the limits of the colorbar
    factor : float
        factor to multiply vector field
    field_name : str
        title of the field to display on plot
    save_path : str
        path to save the plot into an image
    is_point_arrow : bool
        to plot a nodal field (point-wise solution required)
    group_names : [str]
        plot is restricted to the group(s) corresponding to this list of group names.


    Returns
    -------
    """
    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_glyph(
            *args,
            label=label,
            index=index,
            indices=indices,
            clim=clim,
            factor=factor,
            field_name=field_name,
            save_path=save_path,
            is_point_arrow=is_point_arrow,
            group_names=None,
        )
    else:

        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        # Get the mesh
        mesh_pv, field, field_name = self.get_mesh_field_pv(
            *args,
            label=label,
            index=index,
            indices=indices,
            field_name=field_name,
        )

        vect_field = real(field)

        # Compute factor
        if factor is None:
            # factor = 1 / (100 * np_max(vect_field))
            factor = 1 / np_max(vect_field) * 10

        # Add third dimension if needed
        solution = self.get_solution(
            label=label,
            index=index,
        )
        if solution.dimension == 2:
            vect_field = np.hstack(
                (vect_field, np.zeros((vect_field.shape[0], 1))))

        # Add field to mesh
        if is_point_arrow:
            mesh_pv.vectors = vect_field * factor
            arrows_plt = mesh_pv.arrows
        else:
            mesh_pv["field"] = vect_field
            mesh_cell = mesh_pv.point_data_to_cell_data()
            surf = mesh_cell.extract_geometry()
            centers2 = surf.cell_centers()
            centers2.vectors = surf["field"] * factor
            arrows_plt = centers2.arrows

        # Configure plot
        if is_pyvistaqt:
            p = pv.BackgroundPlotter()
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False)
        p.add_mesh(mesh_pv,
                   color="grey",
                   opacity=0.7,
                   show_edges=True,
                   edge_color="white")
        p.set_position((0.2, 0.2, 0.5))
        p.reset_camera()
        p.add_mesh(arrows_plt, color="red")
        p.add_axes()
        # if self.dimension:
        #     p.view_xy()
        if save_path is None and is_show_fig:
            p.show()
        else:
            p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 20
0
def plot_contour(
    self,
    label=None,
    index=None,
    indices=None,
    is_surf=False,
    is_radial=False,
    is_center=False,
    clim=None,
    field_name=None,
    group_names=None,
    save_path=None,
    itimefreq=0,
    is_show_fig=True,
):
    """Plot the contour of a field on a mesh using pyvista plotter.

    Parameters
    ----------
    self : MeshSolution
        a MeshSolution object
    label : str
        a label
    index : int
        an index
    indices : list
        list of the points to extract (optional)
    is_surf : bool
        field over outer surface
    is_radial : bool
        radial component only
    is_center : bool
        field at cell-centers
    clim : list
        a list of 2 elements for the limits of the colorbar
    field_name : str
        title of the field to display on plot
    group_names : list
        a list of str corresponding to group name(s)
    save_path : str
        path to save the figure
    itimefreq : int
        index of the time step (or frequency) to be plotted
    is_show_fig : bool
        To call show at the end of the method

    Returns
    -------

    """
    if group_names is not None:
        meshsol_grp = self.get_group(group_names)
        meshsol_grp.plot_contour(
            label=label,
            index=index,
            indices=indices,
            is_surf=is_surf,
            is_radial=is_radial,
            is_center=is_center,
            clim=clim,
            field_name=field_name,
            group_names=None,
            save_path=save_path,
            itimefreq=itimefreq,
        )
    else:
        if save_path is None:
            try:
                import pyvistaqt as pv

                is_pyvistaqt = True
            except:
                import pyvista as pv

                is_pyvistaqt = False
        else:
            import pyvista as pv

            is_pyvistaqt = False

        # Get the mesh_pv and field
        mesh_pv, field, field_name = self.get_mesh_field_pv(
            label=label,
            index=index,
            indices=indices,
            is_surf=is_surf,
            is_radial=is_radial,
            is_center=is_center,
            field_name=field_name,
        )

        # Add field to mesh
        if is_surf:
            surf = mesh_pv.get_surf(indices=indices)
            surf[field_name] = real(field)
            mesh_field = surf
        else:
            mesh_pv[field_name] = real(field)
            mesh_field = mesh_pv

        # Configure plot
        if is_pyvistaqt:
            p = pv.BackgroundPlotter()
            p.set_background("white")
        else:
            pv.set_plot_theme("document")
            p = pv.Plotter(notebook=False)
        sargs = dict(
            interactive=True,
            title_font_size=20,
            label_font_size=16,
            font_family="arial",
            color="black",
        )
        p.add_mesh(
            mesh_field,
            scalars=field_name,
            show_edges=False,
            cmap=COLOR_MAP,
            clim=clim,
            scalar_bar_args=sargs,
        )
        if self.dimension == 2:
            p.view_xy()
        if save_path is None and is_show_fig:
            p.show()
        elif save_path is not None:
            p.show(interactive=False, screenshot=save_path)
Ejemplo n.º 21
0
    def plotter(self):
        if not self._plotter.isVisible():
            self._plotter = pyvistaqt.BackgroundPlotter()

        return self._plotter