Ejemplo n.º 1
0
    def __init__(self, env, grid_size=64, occlusion_reward=False):
        super().__init__(env)

        self.grid_shape = ((grid_size, grid_size, grid_size))
        self.observation_space = spaces.Box(0, 1, self.grid_shape, dtype=bool)

        self.builder = VoxelGridBuilder(grid_size)

        self.mesh_grid = None
        self.gt_size = None
        self.bounds = None
        self.plot = k3d.plot(name='wrapper')
Ejemplo n.º 2
0
def points(plot_array, point_size=0.1, color=0x99bbff, plot=None, **kwargs):
    plot_array = plot_array.astype(np.float32)  # to avoid k3d warning

    if plot is None:
        plot = k3d.plot()
        plot.display()
    plot += k3d.points(plot_array,
                       point_size=point_size,
                       color=color,
                       **kwargs)

    return plot
Ejemplo n.º 3
0
    def new_plot(self, bs=1.0):
        points_number = 1
        positions = 50 * np.random.random_sample((points_number, 3)) - 25
        colors = np.random.randint(0, 0x777777, points_number)

        self.plot = k3d.plot()
        self.pkts = k3d.points(positions, colors, point_size=.3)
        self.plot += self.pkts
        self.plot.camera_auto_fit = False
        self.plot.grid_auto_fit = False
        self.box = k3d.line(self.box_coords(bs=bs))

        self.plot += self.box
Ejemplo n.º 4
0
 def init_plot(self):
     plot = k3d.plot(height=self.height)
     self.meshes = []
     for (corner, sizes), color in zip(iter_corner_sizes(self.L, self.D),
                                       palette):
         mesh = Box(corner=corner, sizes=sizes).mesh
         mesh.color = color
         plot += mesh
         # set aside for updates
         self.meshes.append(mesh)
     self.plot = plot
     # return the plot so it gets displayed
     return self.plot
Ejemplo n.º 5
0
def visualize_mesh(vertices, faces, flip_axes=False):
    plot = k3d.plot(name='points',
                    grid_visible=False,
                    grid=(-0.55, -0.55, -0.55, 0.55, 0.55, 0.55))
    if flip_axes:
        vertices[:, 2] = vertices[:, 2] * -1
        vertices[:, [0, 1, 2]] = vertices[:, [0, 2, 1]]
    plt_mesh = k3d.mesh(vertices.astype(np.float32),
                        faces.astype(np.uint32),
                        color=0xd0d0d0)
    plot += plt_mesh
    plt_mesh.shader = '3d'
    plot.display()
Ejemplo n.º 6
0
class Animator3(type(k3d.plot())):
    
    def __init__(self, L, D, height=800):
        super().__init__(height=height)
        self.L = L
        self.D = D
        
        # formerly in init_plot()
        self.meshes = []
        for (corner, sizes), color in zip(iter_corner_sizes(self.L, self.D),
                                          palette):
            mesh = Box(corner=corner, sizes=sizes).mesh
            mesh.color = color
            # former 'plot' attribute is now just self
            self += mesh
            # set aside for updates
            self.meshes.append(mesh)
        display(self)
    
    def update_plot(self, newL, newD):
        self.D = newD
        self.L = newL
        for (corner, sizes), mesh in zip(iter_corner_sizes(newL, newD),
                                         self.meshes):
            newBox = Box(corner=corner, sizes=sizes)
            mesh.vertices = newBox.mesh.vertices


    # limited control over the sliders arrangement
    def interact_D(self, **slider_as_dict):
        # closure just capture self in function
        def update(L, D):
            self.update_plot(L, D)
        interact(update,
                 L=fixed(self.L),
                 D=FloatSlider(**slider_as_dict, value=self.D,
                               layout=Layout(width="90%")
                              ))
                 

    # full control: here we put them in a simple horizontal box
    def interact_LD(self, L_dict, D_dict):
        # closure just capture self in function
        def update(L, D):
            self.update_plot(L, D)
        layout = Layout(width="50%")
        lw = FloatSlider(**L_dict, layout=layout, description="L")
        dw = FloatSlider(**D_dict, layout=layout, description="D")
        box = HBox([lw, dw])
        interactive_output(update, {'L': lw, 'D': dw})
        display(box)
Ejemplo n.º 7
0
    def vectors_plot(self):
        plot = k3d.plot()
        plot.camera_auto_fit = False
        plot.grid_auto_fit = False

        field = self.get_field
        coord, vect = field.get_coord_and_vect(field.mesh.coordinates)
        colors = df.plot3d.get_colors(vect)

        vectors = k3d.vectors(coord, vect, colors=colors)
        plot += vectors
        plot.display()

        return vectors
Ejemplo n.º 8
0
def visualize_pointcloud(point_cloud,
                         point_size,
                         flip_axes=False,
                         name='point_cloud'):
    plot = k3d.plot(name=name,
                    grid_visible=False,
                    grid=(-0.55, -0.55, -0.55, 0.55, 0.55, 0.55))
    if flip_axes:
        point_cloud[:, 2] = point_cloud[:, 2] * -1
        point_cloud[:, [0, 1, 2]] = point_cloud[:, [0, 2, 1]]
    plt_points = k3d.points(positions=point_cloud.astype(np.float32),
                            point_size=point_size,
                            color=0xd0d0d0)
    plot += plt_points
    plt_points.shader = '3d'
    plot.display()
Ejemplo n.º 9
0
def visualization_inter3D_xyz(pa):

    if (pa.shape[1] == 4):
        pa = np.delete(pa, (3), axis=1)
    plot = k3d.plot()
    print(pa.shape[0])
    points_number = pa.shape[0]
    colors = np.random.randint(0, 0xFFFFFF, points_number)

    points = k3d.points(pa, colors, point_size=0.01, shader='3d')
    plot += points
    plot.camera_auto_fit = False
    plot.display()
    print("(x) : {:2.1f}m".format(pa[:, 0:1].max() - pa[:, 0:1].min()))
    print("(y) : {:2.1f}m".format(pa[:, 1:2].max() - pa[:, 1:2].min()))
    print("(z) : {:2.1f}m".format(pa[:, 2:3].max() - pa[:, 2:3].min()))
Ejemplo n.º 10
0
def viz_dimer_positions_k3d(positions,
                            size=5,
                            cmap_name="tab20c",
                            color_feature_name=None):
    try:
        import k3d
    except ImportError:
        mess = "YOu need to install the k3d library. "
        mess += (
            "Please follow the official instructions at https://github.com/K3D-tools/K3D-jupyter/."
        )
        raise ImportError(mess)

    # Only show visible dimers
    selected_dimers = positions[positions["visible"]]

    coordinates = selected_dimers[["x", "y", "z"]].values.astype("float")
    coordinates = coordinates.astype("float32")

    if color_feature_name:
        # TODO: that code should be much simpler...
        cmap = matplotlib.cm.get_cmap(cmap_name)
        categories = selected_dimers[color_feature_name].unique()
        color_indices = cmap([i / len(categories) for i in categories])

        colors = np.zeros((len(selected_dimers[color_feature_name]), ),
                          dtype="uint32")
        for color_index, _ in enumerate(categories):
            mask = selected_dimers[color_feature_name] == categories[
                color_index]
            color = color_indices[color_index]
            color = "".join([format(int(x * 255), "02X") for x in color[:-1]])
            color = int(color, 16)
            colors[mask] = color
    else:
        colors = "#e4191b"

    plot = k3d.plot()

    plt_points = k3d.points(positions=coordinates,
                            point_size=size,
                            colors=colors)
    plot += plt_points

    plot.display()
    return plot
Ejemplo n.º 11
0
 def k3d(self, point_size=.8, color=True):
     '''makes a 3d plot of the lattice using k3d visualization'''
     import k3d
     plot = k3d.plot(name='lattice_plot')
     if not color:
         for layer in range(self.n_layers):
             plot += k3d.points(positions=self.layer_coords(layer, z=True),
                                point_size=point_size)
     if color:
         color_list = [
             0x0054a7, 0xe41134, 0x75ac4f, 0xf4ea19, 0xffaff8, 0xa35112,
             0x15e3f4, 0xcfc7ff
         ]
         for layer in range(self.n_layers):
             plot += k3d.points(positions=self.layer_coords(layer, z=True),
                                point_size=point_size,
                                color=color_list[layer % 8])
     plot.display()
Ejemplo n.º 12
0
def display_3d(K,show_labels=False):
    """display a 3d simplicial complex using k3d, in jupyter

    to install it: 
    sudo pip install k3d
    sudo jupyter nbextension install --py k3d
    sudo jupyter nbextension enable --py k3d
    """
    import k3d
    if not isinstance(K.vertices[0] ,Point):
        raise Exception("Can display only Point-class vertices of dim 3!!!")
    dim=K.vertices[0].dim
    if dim != 3:
        sys.stderr.write("Not yet implemented display in dim = %s\n" % dim ) 
        return None
    vertices =  [v.coords for v in K.vertices] 
    edges = [ s for s in K.simplices[1] ]
    faces = []
    if 2 in K.simplices:
        faces = [ s for s in K.simplices[2] ]
    plt=k3d.plot(name='points')
    plt_points = k3d.points( positions=vertices , point_size=0.05)
    plt_points.shader ='3dSpecular'
    plt_points.color = 14
    plt += plt_points

    # now lines:
    for s in edges:
        plt_line = k3d.line([vertices[s[0]],vertices[s[1]] ],shader='mesh', width=0.01, 
                            color=0xff0000)
        plt += plt_line 

    # now convert all faces to a mesh
    plt_mesh = k3d.mesh(vertices,faces,color=0xff, wireframe=False, opacity=0.7, name="Simplicial Complex")
    plt += plt_mesh

    # now add the text
    for P in K.vertices:
        if show_labels and P.label is not None:
            plt_text = k3d.text("%s" % repr(P), position = P.coords, color=0x7700,size=1)
            plt += plt_text 
      
    #finally display
    plt.display()
Ejemplo n.º 13
0
    def create(self, data):

        self.plot = k3d.plot()
        self.data = data

        # Equatorial slice
        self.equatorial_slice \
            = k3d.vtk_poly_data(serpentine.tools.extract_plane(data, [0, 0, 0], [0, 0, 1]),
                                color_attribute=self.color_attribute,
                                color_map=self.color_map)

        # Meridional slice
        self.meridional_slice \
            = k3d.vtk_poly_data(serpentine.tools.extract_plane(data, [0, 0, 0], [0, 1, 0]),
                                color_attribute=self.color_attribute,
                                color_map=self.color_map)

        # Spherical slice
        self.spherical_slice \
            = k3d.vtk_poly_data(serpentine.tools.extract_sphere(data, [0, 0, 0], 0.105),
                                color_attribute=self.color_attribute,
                                color_map=self.color_map)

        self.boundary_sphere = k3d.points([0, 0, 0],
                                          point_size=0.2,
                                          shader="mesh",
                                          color=0xffffff,
                                          mesh_detail=3)

        # Get rmin and rmax
        x, y, z = np.split(self.equatorial_slice.vertices.T, 1, axis=0)[0]
        rsqr = x**2 + y**2 + z**2
        self.r_bounds = (np.sqrt(min(rsqr)), np.sqrt(max(rsqr)))

        # Add to plot
        self.plot += self.equatorial_slice
        self.plot += self.meridional_slice
        self.plot += self.spherical_slice
        self.plot += self.boundary_sphere

        # Modify defaults
        self.plot.grid_auto_fit = False

        self.initialize_sliders()
Ejemplo n.º 14
0
def show_points(points,
                colors=[],
                normals=None,
                point_size=0.1,
                line_width=0.00001):
    plot = k3d.plot(grid_visible=False, axes_helper=0)
    if normals is not None:
        normal_vectors = k3d.vectors(points,
                                     normals,
                                     line_width=line_width,
                                     use_head=False)
        plot += normal_vectors
    point_cloud = k3d.points(points,
                             colors=colors,
                             point_size=point_size,
                             shader='flat')
    plot += point_cloud
    plot.display()
    return None
Ejemplo n.º 15
0
def plot_pcd(x, point_size=0.005, c='g'):
    """
    x: point_nr,3
    """
    if c == 'b':
        k = 245
    elif c == 'g':
        k = 25811000
    elif c == 'r':
        k = 11801000
    elif c == 'black':
        k = 2580
    else:
        k = 2580
    colors = np.ones(x.shape[0]) * k
    plot = k3d.plot(name='points')
    plt_points = k3d.points(x, colors.astype(np.uint32), point_size=point_size)
    plot += plt_points
    plt_points.shader = '3d'
    plot.display()
Ejemplo n.º 16
0
def init_scene(d):
    plot = k3d.plot(height=800)
    m000 = Box((0,0,0), (3,3,3)).mesh
    plot += m000
    m100 = Box((3+d,0,0), (1,3,3)).mesh
    plot += m100
    m010 = Box((0,3+d,0), (3,1,3)).mesh
    plot += m010
    m001 = Box((0,0,3+d), (3,3,1)).mesh
    plot += m001
    m110 = Box((3+d,3+d,0), (1,1,3)).mesh
    plot += m110
    m101 = Box((3+d,0,3+d), (1,3,1)).mesh
    plot += m101
    m011 = Box((0,3+d,3+d), (3,1,1)).mesh
    plot += m011
    m111 = Box((3+d,3+d,3+d), (1,1,1)).mesh
    plot += m111
    
    return plot
Ejemplo n.º 17
0
    def _load_k3d_objects(self):
        # text objects
        self.finish_text = k3d.text2d(
            "FINISHED",
            position=(.5, .5),
            size=3,
        )
        self.processing_text = k3d.text2d(
            "PROCESSING",
            position=(.5, .5),
            size=3,
        )

        # the plot area
        self.plot = k3d.plot()

        # gosht objects
        self.m1 = None
        self.m2 = None
        self.m3 = None
Ejemplo n.º 18
0
    def reset(self):
        """
        Reset the environment for new episode.
        Randomly (or not) generate CAD model for this episode.
        """
        if self.models_path is not None:
            self.model_path = os.path.join(self.models_path,
                                      random.sample(os.listdir(self.models_path), 1)[0])
        self.model = Model(self.model_path, resolution_image=self.image_size)
        self.model.generate_view_points(self.number_of_view_points)
        
        if self.illustrate:
            self.model.illustrate().display()

            self.plot = k3d.plot()
            self.plot.display()
        
        init_action = self.action_space.sample()
        observation = self.model.get_observation(init_action)
        return observation, init_action
Ejemplo n.º 19
0
def vis_depth_interactive(Z):
    import k3d
    Nx, Ny = 1, 1
    xmin, xmax = 0, Z.shape[0]
    ymin, ymax = 0, Z.shape[1]

    x = np.linspace(xmin, xmax, Nx)
    y = np.linspace(ymin, ymax, Ny)
    x, y = np.meshgrid(x, y)
    plot = k3d.plot(grid_auto_fit=True, camera_auto_fit=False)
    plt_surface = k3d.surface(-Z.astype(np.float32),
                              color=0xb2ccff,
                              bounds=[xmin, xmax, ymin,
                                      ymax])  # -Z for mirroring
    plot += plt_surface
    plot.display()
    plot.camera = [
        242.57934019166004, 267.50948550191197, -406.62328311352337, 256, 256,
        -8.300323486328125, -0.13796270478729053, -0.987256298362836,
        -0.07931767413815752
    ]
    return plot
Ejemplo n.º 20
0
def voxels(plot_array,
           pmin,
           pmax,
           colormap,
           outlines=False,
           plot=None,
           **kwargs):
    plot_array = plot_array.astype(np.uint8)  # to avoid k3d warning
    if plot is None:
        plot = k3d.plot()
        plot.display()

    xmin, ymin, zmin = pmin
    xmax, ymax, zmax = pmax
    bounds = [xmin, xmax, ymin, ymax, zmin, zmax]

    plot += k3d.voxels(plot_array,
                       color_map=colormap,
                       bounds=bounds,
                       outlines=outlines,
                       **kwargs)

    return plot
Ejemplo n.º 21
0
 def __init_skeleton_plot(
         self,
         skeletons: np.ndarray,
         automatic_camera_orientation: bool = False) -> None:
     self.plot = k3d.plot(antialias=1, camera_auto_fit=False)
     centroid: np.ndarray = np.average(np.average(skeletons, axis=0),
                                       axis=0)
     if automatic_camera_orientation:
         camera_up_vector: np.ndarray = np.zeros(shape=(3, ))
         for line_indices in self.joint_set.vertically_aligned_line_indices:
             camera_up_vector += np.sum(skeletons[:, line_indices[1]] -
                                        skeletons[:, line_indices[0]],
                                        axis=0)
         camera_up_vector /= np.linalg.norm(camera_up_vector, ord=2)
         self.plot.camera = [
             0.0,
             0.0,
             0.0,  # Camera position
             centroid[0],
             centroid[1],
             centroid[2],  # Camera looking at
             camera_up_vector[0],
             camera_up_vector[1],
             camera_up_vector[2]
         ]  # Camera up vector
     else:
         self.plot.camera = [
             0.0,
             0.0,
             0.0,  # Camera position
             0.0,
             0.0,
             centroid[2],  # Camera looking at
             0.0,
             -1.0,
             0.0
         ]  # Camera up vector
Ejemplo n.º 22
0
def plot_pcd(x, point_size=0.005, c='g'):
    """[summary]

    Args:
        x ([type]): point_nr,3
        point_size (float, optional): [description]. Defaults to 0.005.
        c (str, optional): [description]. Defaults to 'g'.
    """
    if c == 'b':
        k = 245
    elif c == 'g':
        k = 25811000
    elif c == 'r':
        k = 11801000
    elif c == 'black':
        k = 2580
    else:
        k = 2580
    colors = np.ones(x.shape[0]) * k
    plot = k3d.plot(name='points')
    plt_points = k3d.points(x, colors.astype(np.uint32), point_size=point_size)
    plot += plt_points
    plt_points.shader = '3d'
    plot.display()
Ejemplo n.º 23
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        if self._get_mode() != 0:
            raise ValueError(
                "Sorry, K3D backend only works within Jupyter Notebook")

        self._bounds = []
        self._clipping = []
        self._handles = dict()

        self._init_cyclers()

        self._fig = k3d.plot(
            grid_visible=self.grid,
            menu_visibility=True,
            background_color=int(cfg["k3d"]["bg_color"]),
            grid_color=int(cfg["k3d"]["grid_color"]),
            label_color=int(cfg["k3d"]["label_color"]),
        )
        if (self.xscale == "log") or (self.yscale == "log"):
            warnings.warn("K3D-Jupyter doesn't support log scales. We will " +
                          "continue with linear scales.")
        self.plot_shown = False
        self._process_series(self._series)
Ejemplo n.º 24
0
def visualize_shape_alignment(R=None, t=None):
    mesh_input = trimesh.load(
        Path(__file__).parent.parent / "resources" / "mesh_input.obj")
    mesh_target = trimesh.load(
        Path(__file__).parent.parent / "resources" / "mesh_target.obj")
    plot = k3d.plot(name='aligment',
                    grid_visible=False,
                    grid=(-0.55, -0.55, -0.55, 0.55, 0.55, 0.55))
    input_vertices = np.array(mesh_input.vertices)
    if not (R is None or t is None):
        t_broadcast = np.broadcast_to(t[:, np.newaxis],
                                      (3, mesh_input.vertices.shape[0]))
        input_vertices = (R @ input_vertices.T + t_broadcast).T
    plt_mesh_0 = k3d.mesh(input_vertices.astype(np.float32),
                          np.array(mesh_input.faces).astype(np.uint32),
                          color=0xd00d0d)
    plt_mesh_1 = k3d.mesh(np.array(mesh_target.vertices).astype(np.float32),
                          np.array(mesh_target.faces).astype(np.uint32),
                          color=0x0dd00d)
    plot += plt_mesh_0
    plot += plt_mesh_1
    plt_mesh_0.shader = '3d'
    plt_mesh_1.shader = '3d'
    plot.display()
Ejemplo n.º 25
0
def PlantGL(pglobject, plot=None, group_by_color=True, property=None):
    """Return a k3d plot from PlantGL shape, geometry and scene objects"""
    if plot is None:
        plot = k3d.plot()

    if isinstance(pglobject, Geometry):
        mesh = tomesh(pglobject)
        plot += mesh
    elif isinstance(pglobject, Shape):
        mesh = tomesh(pglobject.geometry)
        mesh.color = pglobject.appearance.ambient.toUint()
        plot += mesh
    elif isinstance(pglobject, Scene):
        if group_by_color:
            meshes = group_meshes_by_color(pglobject)
            for mesh in meshes:
                plot += mesh
        else:
            mesh = scene2mesh(pglobject, property)
            plot += mesh

    plot.lighting = 3
    #plot.colorbar_object_id = randint(0, 1000)
    return plot
Ejemplo n.º 26
0
def getNotebookBackend(actors2show, zoom, viewup):

    vp = settings.plotter_instance

    if isinstance(vp.shape, str) or sum(vp.shape) > 2:
        colors.printc("Multirendering is not supported in jupyter.", c=1)
        return

    ####################################################################################
    # https://github.com/InsightSoftwareConsortium/itkwidgets
    #  /blob/master/itkwidgets/widget_viewer.py
    if 'itk' in settings.notebookBackend:
        from itkwidgets import view

        settings.notebook_plotter = view(actors=actors2show,
                                         cmap='jet', ui_collapsed=True,
                                         gradient_opacity=False)


    ####################################################################################
    elif settings.notebookBackend == 'k3d':
        try:
            import k3d # https://github.com/K3D-tools/K3D-jupyter
        except:
            print("Cannot find k3d, install with:  pip install k3d")
            return

        actors2show2 = []
        for ia in actors2show:
            if not ia:
                continue
            if isinstance(ia, vtk.vtkAssembly): #unpack assemblies
                acass = ia.unpack()
                actors2show2 += acass
            else:
                actors2show2.append(ia)

        # vbb, sizes, _, _ = addons.computeVisibleBounds()
        # kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5]

        settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle],
                                             menu_visibility=True,
                                             # height=int(vp.size[1]/2),
                                             )
        # settings.notebook_plotter.grid = kgrid
        settings.notebook_plotter.lighting = 1.2

        # set k3d camera
        settings.notebook_plotter.camera_auto_fit = True

        if settings.plotter_instance and settings.plotter_instance.camera:
            k3dc =  utils.vtkCameraToK3D(settings.plotter_instance.camera)
            if zoom:
                k3dc[0] /= zoom
                k3dc[1] /= zoom
                k3dc[2] /= zoom
            settings.notebook_plotter.camera = k3dc
        # else:
        #     vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5]
        #     vss = numpy.linalg.norm([vsx, vsy, vsz])
        #     if zoom:
        #         vss /= zoom
        #     vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target
        #     if viewup == 'z':
        #         vup = (0,0,1) # camera up vector
        #         vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01  # camera position
        #     elif viewup == 'x':
        #         vup = (1,0,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2]  # camera position
        #     else:
        #         vup = (0,1,0)
        #         vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5  # camera position
        #     settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2],
        #                                           vfp[0],  vfp[1],  vfp[2],
        #                                           vup[0],  vup[1],  vup[2] ]
        if not vp.axes:
            settings.notebook_plotter.grid_visible = False

        for ia in actors2show2:

            if isinstance(ia, (vtk.vtkCornerAnnotation, vtk.vtkAssembly)):
                continue

            kobj = None
            kcmap= None
            name = None
            if hasattr(ia, 'filename'):
                if ia.filename:
                    name = os.path.basename(ia.filename)
                if ia.name:
                    name = os.path.basename(ia.name)

            #####################################################################scalars
            # work out scalars first, Points Lines are also Mesh objs
            if isinstance(ia, (Mesh, shapes.Line, Points)):
#                print('scalars', ia.name, ia.N())
                iap = ia.GetProperty()

                if isinstance(ia, (shapes.Line, Points)):
                    iapoly = ia.polydata()
                else:
                    iapoly = ia.clone().clean().triangulate().computeNormals().polydata()

                vtkscals = None
                color_attribute = None
                if ia.mapper().GetScalarVisibility():
                    vtkdata = iapoly.GetPointData()
                    vtkscals = vtkdata.GetScalars()

                    if vtkscals is None:
                        vtkdata = iapoly.GetCellData()
                        vtkscals = vtkdata.GetScalars()
                        if vtkscals is not None:
                            c2p = vtk.vtkCellDataToPointData()
                            c2p.SetInputData(iapoly)
                            c2p.Update()
                            iapoly = c2p.GetOutput()
                            vtkdata = iapoly.GetPointData()
                            vtkscals = vtkdata.GetScalars()

                    if vtkscals is not None:
                        if not vtkscals.GetName():
                            vtkscals.SetName('scalars')
                        scals_min, scals_max = ia.mapper().GetScalarRange()
                        color_attribute = (vtkscals.GetName(), scals_min, scals_max)
                        lut = ia.mapper().GetLookupTable()
                        lut.Build()
                        kcmap=[]
                        nlut = lut.GetNumberOfTableValues()
                        for i in range(nlut):
                            r,g,b,a = lut.GetTableValue(i)
                            kcmap += [i/(nlut-1), r,g,b]


            #####################################################################Volume
            if isinstance(ia, Volume):
#                print('Volume', ia.name, ia.dimensions())
                kx, ky, kz = ia.dimensions()
                arr = ia.getPointArray()
                kimage = arr.reshape(-1, ky, kx)

                colorTransferFunction = ia.GetProperty().GetRGBTransferFunction()
                kcmap=[]
                for i in range(128):
                    r,g,b = colorTransferFunction.GetColor(i/127)
                    kcmap += [i/127, r,g,b]

                kbounds = numpy.array(ia.imagedata().GetBounds()) \
                    + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\
                    * numpy.array([-1,1] * 3)

                kobj = k3d.volume(kimage.astype(numpy.float32),
                                  color_map=kcmap,
                                  #color_range=ia.imagedata().GetScalarRange(),
                                  alpha_coef=10,
                                  bounds=kbounds,
                                  name=name,
                                  )
                settings.notebook_plotter += kobj

            #####################################################################text
            elif hasattr(ia, 'info') and 'formula' in ia.info.keys():
                pos = (ia.GetPosition()[0],ia.GetPosition()[1])
                kobj = k3d.text2d(ia.info['formula'], position=pos)
                settings.notebook_plotter += kobj


            #####################################################################Mesh
            elif isinstance(ia, Mesh) and ia.N() and len(ia.faces()):
                # print('Mesh', ia.name, ia.N(), len(ia.faces()))
                kobj = k3d.vtk_poly_data(iapoly,
                                         name=name,
                                         # color=_rgb2int(iap.GetColor()),
                                         color_attribute=color_attribute,
                                         color_map=kcmap,
                                         opacity=iap.GetOpacity(),
                                         wireframe=(iap.GetRepresentation()==1))

                if iap.GetInterpolation() == 0:
                    kobj.flat_shading = True
                settings.notebook_plotter += kobj

            #####################################################################Points
            elif isinstance(ia, Points) or ia.NPoints() == ia.NCells():
                # print('Points', ia.name, ia.N())
                kcols=[]
                if color_attribute is not None:
                    scals = utils.vtk2numpy(vtkscals)
                    kcols = k3d.helpers.map_colors(scals, kcmap,
                                                   [scals_min,scals_max]).astype(numpy.uint32)
                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                kobj = k3d.points(ia.points().astype(numpy.float32),
                                  color=_rgb2int(iap.GetColor()),
                                  colors=kcols,
                                  opacity=iap.GetOpacity(),
                                  shader="dot",
                                  point_size=3, # point_size=iap.GetPointSize()*sqsize/800,
                                  name=name,
                                  )
                settings.notebook_plotter += kobj


            #####################################################################Line
            elif ia.polydata(False).GetNumberOfLines():
                # print('Line', ia.name, ia.N(), len(ia.faces()),
                #       ia.polydata(False).GetNumberOfLines(), len(ia.lines()),
                #       color_attribute, [vtkscals])

                # kcols=[]
                # if color_attribute is not None:
                #     scals = utils.vtk2numpy(vtkscals)
                #     kcols = k3d.helpers.map_colors(scals, kcmap,
                #                                    [scals_min,scals_max]).astype(numpy.uint32)

                # sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                for i, ln_idx in enumerate(ia.lines()):
                    if i>200:
                        print('WARNING: K3D nr of line segments is limited to 200.')
                        break
                    pts = ia.points()[ln_idx]
                    kobj = k3d.line(pts.astype(numpy.float32),
                                    color=_rgb2int(iap.GetColor()),
#                                    colors=kcols,
                                    opacity=iap.GetOpacity(),
                                    shader="thick",
                                    # width=iap.GetLineWidth()*sqsize/1000,
                                    name=name,
                                    )

                    settings.notebook_plotter += kobj


    ####################################################################################
    elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window:

        import panel # https://panel.pyviz.org/reference/panes/VTK.html
        vp.renderer.ResetCamera()
        settings.notebook_plotter = panel.pane.VTK(vp.window,
                                                   width=int(vp.size[0]/1.5),
                                                   height=int(vp.size[1]/2))


    ####################################################################################
    elif 'ipyvtk' in settings.notebookBackend and hasattr(vp, 'window') and vp.window:

        from ipyvtklink.viewer import ViewInteractiveWidget
        vp.renderer.ResetCamera()
        settings.notebook_plotter = ViewInteractiveWidget(vp.window)


    ####################################################################################
    elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window:
        import PIL.Image
        try:
            import IPython
        except ImportError:
            raise Exception('IPython not available.')

        from vedo.io import screenshot
        settings.screeshotLargeImage = True
        nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2)
        pil_img = PIL.Image.fromarray(nn)
        settings.notebook_plotter = IPython.display.display(pil_img)

    return settings.notebook_plotter
Ejemplo n.º 27
0
 def _ipython_display_(self, **kwargs):
     """Called when `IPython.display.display` is called on the widget."""
     import k3d
     plot = k3d.plot()
     plot += self
     plot.display()
Ejemplo n.º 28
0
    def k3d(self,
            *,
            plot=None,
            color=dfu.cp_int[0],
            multiplier=None,
            **kwargs):
        """``k3d`` plot.

        If ``plot`` is not passed, ``k3d.Plot`` object is created
        automatically. The colour of the region can be specified using
        ``color`` argument.

        For details about ``multiplier``, please refer to
        ``discretisedfield.Region.mpl``.

        This method is based on ``k3d.voxels``, so any keyword arguments
        accepted by it can be passed (e.g. ``wireframe``).

        Parameters
        ----------
        plot : k3d.Plot, optional

            Plot to which the plot is added. Defaults to ``None`` - plot is
            created internally.

        color : int, optional

            Colour of the region. Defaults to the default color palette.

        multiplier : numbers.Real, optional

            Axes multiplier. Defaults to ``None``.

        Examples
        --------
        1. Visualising the region using ``k3d``.

        >>> import discretisedfield as df
        ...
        >>> p1 = (-50e-9, -50e-9, 0)
        >>> p2 = (50e-9, 50e-9, 10e-9)
        >>> region = df.Region(p1=p1, p2=p2)
        >>> region.k3d()
        Plot(...)

        """
        if plot is None:
            plot = k3d.plot()
            plot.display()

        if multiplier is None:
            multiplier = uu.si_max_multiplier(self.edges)

        unit = f'({uu.rsi_prefixes[multiplier]}m)'

        plot_array = np.ones((1, 1, 1)).astype(np.uint8)  # avoid k3d warning

        bounds = [
            i for sublist in zip(np.divide(self.pmin, multiplier),
                                 np.divide(self.pmax, multiplier))
            for i in sublist
        ]

        plot += k3d.voxels(plot_array,
                           color_map=color,
                           bounds=bounds,
                           outlines=False,
                           **kwargs)

        plot.axes = [
            i + r'\,\text{{{}}}'.format(unit) for i in dfu.axesdict.keys()
        ]
Ejemplo n.º 29
0
                    head_size=1.5,
                    labels=['a'])
b_vec = k3d.vectors(red_point.positions,
                    cubic_system[9],
                    head_size=1.5,
                    labels=['b'])
c_vec = k3d.vectors(red_point.positions,
                    cubic_system[1],
                    head_size=1.5,
                    labels=['c'])
ab_vec = k3d.vectors(red_point.positions,
                     cubic_system[3] + 2 * cubic_system[9],
                     head_size=1.5,
                     labels=['a+2b'])

plot1 = k3d.plot()
plot1 += red_point + system + a_vec + b_vec + c_vec + ab_vec

### SECOND DRAWING
cubic_system = cubic(0, 0, 0, 3, 3, 3)
mask = np.arange(cubic_system.shape[0])
chosen = [0, 1, 3, 4, 21, 22, 24, 25]

red_points = k3d.points(cubic_system[chosen], point_size=0.2, color=0xff0000)
system = k3d.points(np.delete(cubic_system, chosen, axis=0),
                    point_size=0.2,
                    color=0)
ab_vec = k3d.vectors(red_point.positions,
                     cubic_system[3] + 2 * cubic_system[9],
                     head_size=1.5,
                     labels=['a+2b'])
Ejemplo n.º 30
0
def getNotebookBackend(actors2show, zoom, viewup):

    vp = settings.plotter_instance

    ####################################################################################
    # https://github.com/InsightSoftwareConsortium/itkwidgets
    #  /blob/master/itkwidgets/widget_viewer.py
    if 'itk' in settings.notebookBackend:
        from itkwidgets import view

        if sum(vp.shape) != 2:
            colors.printc("Warning: multirendering is not supported in jupyter.", c=1)

        settings.notebook_plotter = view(actors=actors2show,
                                         cmap='jet', ui_collapsed=True,
                                         gradient_opacity=False)


    ####################################################################################
    elif settings.notebookBackend == 'k3d':
        import k3d # https://github.com/K3D-tools/K3D-jupyter

        if vp.shape[0] != 1 or vp.shape[1] != 1:
            colors.printc("Warning: multirendering is not supported in jupyter.", c=1)

        actors2show2 = []
        for ia in actors2show:
            if isinstance(ia, vtk.vtkAssembly): #unpack assemblies
                acass = ia.unpack()
                #for a in acass:
                #    a.SetScale(ia.GetScale())
                actors2show2 += acass
            else:
                actors2show2.append(ia)

        vbb, sizes, min_bns, max_bns = addons.computeVisibleBounds()
        kgrid = vbb[0], vbb[2], vbb[4], vbb[1], vbb[3], vbb[5]

        settings.notebook_plotter = k3d.plot(axes=[vp.xtitle, vp.ytitle, vp.ztitle],
                                             menu_visibility=True,
                                             height=int(vp.size[1]/2) )
        settings.notebook_plotter.grid = kgrid
        settings.notebook_plotter.lighting = 1.2

        # set k3d camera
        settings.notebook_plotter.camera_auto_fit = False

        eps = 1 + numpy.random.random()*1.0e-04 # workaround to bug in k3d
        # https://github.com/K3D-tools/K3D-jupyter/issues/180

        if settings.plotter_instance and settings.plotter_instance.camera:
            k3dc =  utils.vtkCameraToK3D(settings.plotter_instance.camera)
            k3dc[2] = k3dc[2]*eps
            settings.notebook_plotter.camera = k3dc
        else:
            vsx, vsy, vsz = vbb[0]-vbb[1], vbb[2]-vbb[3], vbb[4]-vbb[5]
            vss = numpy.linalg.norm([vsx, vsy, vsz])
            if zoom:
                vss /= zoom
            vfp = (vbb[0]+vbb[1])/2, (vbb[2]+vbb[3])/2, (vbb[4]+vbb[5])/2 # camera target
            if viewup == 'z':
                vup = (0,0,1) # camera up vector
                vpos= vfp[0] + vss/1.9, vfp[1] + vss/1.9, vfp[2]+vss*0.01  # camera position
            elif viewup == 'x':
                vup = (1,0,0)
                vpos= vfp[0]+vss*0.01, vfp[1] + vss/1.5, vfp[2]  # camera position
            else:
                vup = (0,1,0)
                vpos= vfp[0]+vss*0.01, vfp[1]+vss*0.01, vfp[2] + vss/1.5  # camera position
            settings.notebook_plotter.camera = [vpos[0], vpos[1], vpos[2]*eps,
                                                 vfp[0],  vfp[1],  vfp[2],
                                                 vup[0],  vup[1],  vup[2] ]
        if not vp.axes:
            settings.notebook_plotter.grid_visible = False

        for ia in actors2show2:
            kobj = None
            kcmap= None

            if isinstance(ia, Mesh) and ia.N():

                iap = ia.GetProperty()
                #ia.clean().triangulate().computeNormals()
                #ia.triangulate())
                iapoly = ia.clone().clean().triangulate().computeNormals().polydata()

                vtkscals = None
                color_attribute = None
                if ia.mapper().GetScalarVisibility():
                    vtkdata = iapoly.GetPointData()
                    vtkscals = vtkdata.GetScalars()

                    if vtkscals is None:
                        vtkdata = iapoly.GetCellData()
                        vtkscals = vtkdata.GetScalars()
                        if vtkscals is not None:
                            c2p = vtk.vtkCellDataToPointData()
                            c2p.SetInputData(iapoly)
                            c2p.Update()
                            iapoly = c2p.GetOutput()
                            vtkdata = iapoly.GetPointData()
                            vtkscals = vtkdata.GetScalars()

                    if vtkscals is not None:
                        if not vtkscals.GetName():
                            vtkscals.SetName('scalars')
                        scals_min, scals_max = ia.mapper().GetScalarRange()
                        color_attribute = (vtkscals.GetName(), scals_min, scals_max)
                        lut = ia.mapper().GetLookupTable()
                        lut.Build()
                        kcmap=[]
                        nlut = lut.GetNumberOfTableValues()
                        for i in range(nlut):
                            r,g,b,a = lut.GetTableValue(i)
                            kcmap += [i/(nlut-1), r,g,b]

                if iapoly.GetNumberOfPolys() > 0:
                    name = None
                    if ia.filename:
                        name = os.path.basename(ia.filename)
                    kobj = k3d.vtk_poly_data(iapoly,
                                             name=name,
                                             color=colors.rgb2int(iap.GetColor()),
                                             color_attribute=color_attribute,
                                             color_map=kcmap,
                                             opacity=iap.GetOpacity(),
                                             wireframe=(iap.GetRepresentation()==1))

                    if iap.GetInterpolation() == 0:
                        kobj.flat_shading = True

                else:
                    kcols=[]
                    if color_attribute is not None:
                        scals = vtk_to_numpy(vtkscals)
                        kcols = k3d.helpers.map_colors(scals, kcmap,
                                                       [scals_min,scals_max]).astype(numpy.uint32)
                    sqsize = numpy.sqrt(numpy.dot(sizes, sizes))

                    if ia.NPoints() == ia.NCells():
                        kobj = k3d.points(ia.points().astype(numpy.float32),
                                          color=colors.rgb2int(iap.GetColor()),
                                          colors=kcols,
                                          opacity=iap.GetOpacity(),
                                          shader="3d",
                                          point_size=iap.GetPointSize()*sqsize/400,
                                          #compression_level=9,
                                          )
                    else:
                        kobj = k3d.line(ia.points().astype(numpy.float32),
                                        color=colors.rgb2int(iap.GetColor()),
                                        colors=kcols,
                                        opacity=iap.GetOpacity(),
                                        shader="thick",
                                        width=iap.GetLineWidth()*sqsize/1000,
                                        )

                settings.notebook_plotter += kobj

            elif isinstance(ia, Volume):
                kx, ky, kz = ia.dimensions()
                arr = ia.getPointArray()
                kimage = arr.reshape(-1, ky, kx)

                colorTransferFunction = ia.GetProperty().GetRGBTransferFunction()
                kcmap=[]
                for i in range(128):
                    r,g,b = colorTransferFunction.GetColor(i/127)
                    kcmap += [i/127, r,g,b]

                #print('vol scal range', ia.imagedata().GetScalarRange())
                #print(numpy.min(kimage), numpy.max(kimage))

                kbounds = numpy.array(ia.imagedata().GetBounds()) \
                    + numpy.repeat(numpy.array(ia.imagedata().GetSpacing()) / 2.0, 2)\
                    * numpy.array([-1,1] * 3)

                kobj = k3d.volume(kimage.astype(numpy.float32),
                                  color_map=kcmap,
                                  #color_range=ia.imagedata().GetScalarRange(),
                                  alpha_coef=10,
                                  bounds=kbounds,
                                  )
                settings.notebook_plotter += kobj

            elif hasattr(ia, 'info') and 'formula' in ia.info.keys():
                pos = (ia.GetPosition()[0],ia.GetPosition()[1])
                kobj = k3d.text2d(ia.info['formula'], position=pos)
                settings.notebook_plotter += kobj


    ####################################################################################
    elif settings.notebookBackend == 'panel' and hasattr(vp, 'window') and vp.window:

        import panel # https://panel.pyviz.org/reference/panes/VTK.html

        vp.renderer.ResetCamera()

        settings.notebook_plotter = panel.pane.VTK(vp.window,
                                                   width=int(vp.size[0]/1.5),
                                                   height=int(vp.size[1]/2))


    ####################################################################################
    elif '2d' in settings.notebookBackend.lower() and hasattr(vp, 'window') and vp.window:
        import PIL.Image
        try:
            import IPython
        except ImportError:
            raise Exception('IPython not available.')
            return

        from vtkplotter.vtkio import screenshot
        settings.screeshotLargeImage = True
        nn = screenshot(returnNumpy=True, scale=settings.screeshotScale+2)
        pil_img = PIL.Image.fromarray(nn)
        settings.notebook_plotter = IPython.display.display(pil_img)

    return settings.notebook_plotter