Exemple #1
0
def plot_two_pc(x, y, point_size=0.005, c1='g', c2='r'):
    if c1 == 'b':
        k = 245
    elif c1 == 'g':
        k = 25811000
    elif c1 == 'r':
        k = 11801000
    elif c1 == 'black':
        k = 2580
    else:
        k = 2580

    if c2 == 'b':
        k2 = 245
    elif c2 == 'g':
        k2 = 25811000
    elif c2 == 'r':
        k2 = 11801000
    elif c2 == 'black':
        k2 = 2580
    else:
        k2 = 2580

    col1 = np.ones(x.shape[0]) * k
    col2 = np.ones(y.shape[0]) * k2
    plot = k3d.plot(name='points')
    plt_points = k3d.points(x, col1.astype(np.uint32), point_size=point_size)
    plot += plt_points
    plt_points = k3d.points(y, col2.astype(np.uint32), point_size=point_size)
    plot += plt_points
    plt_points.shader = '3d'
    plot.display()
def Icosahedron(origin, size=1):

    if np.shape(origin) == (3, ):
        fi = (1 + np.sqrt(5)) / 2
        icosahedron_vertices = k3d.points([(1, fi, 0),
                                           (1, -fi, 0), (-1, fi, 0),
                                           (-1, -fi, 0), (fi, 0, 1),
                                           (fi, 0, -1), (-fi, 0, 1),
                                           (-fi, 0, -1), (0, 1, fi),
                                           (0, 1, -fi), (0, -1, fi),
                                           (0, -1, -fi)],
                                          point_size=0.1)

        icosahedron_vertices.positions = np.float32(
            size * np.array(icosahedron_vertices.positions) + np.array(origin))

        icosahedron_mesh = k3d.mesh(icosahedron_vertices.positions,
                                    indices=[
                                        0, 2, 8, 0, 4, 8, 0, 2, 9, 0, 5, 9, 2,
                                        6, 8, 2, 7, 9, 2, 6, 7, 0, 4, 5, 1, 4,
                                        5, 1, 5, 11, 7, 9, 11, 3, 7, 11, 3, 6,
                                        7, 3, 6, 10, 4, 8, 10, 6, 8, 10, 1, 4,
                                        10, 1, 3, 11, 1, 3, 10, 5, 9, 11
                                    ])
    else:
        raise TypeError('Origin attribute should have 3 coordinates.')

    return [icosahedron_vertices, icosahedron_mesh]
def vis_pcloud_interactive(res, img):
    import k3d
    from colormap import rgb2hex
    color_vals = np.zeros((img.shape[0], img.shape[1]))
    for i in range(img.shape[0]):
        for j in range(img.shape[1]):
            color_vals[i, j] = int(
                rgb2hex(img[i, j, 0], img[i, j, 1],
                        img[i, j, 2]).replace('#', '0x'), 0)
    colors = color_vals.flatten()

    points = np.stack(
        (res['X'].flatten(), res['Y'].flatten(), res['Z'].flatten()), axis=1)

    invalid_inds = np.any(np.isnan(points), axis=1)
    points_valid = points[invalid_inds == False]
    colors_valid = colors[invalid_inds == False]
    plot = k3d.plot(grid_auto_fit=True, camera_auto_fit=False)
    plot += k3d.points(points_valid,
                       colors_valid,
                       point_size=0.01,
                       compression_level=9,
                       shader='flat')
    plot.display()
    plot.camera = [
        -0.3568942548181382, -0.12775125650240726, 3.5390732533009452,
        0.33508163690567017, 0.3904658555984497, -0.0499117374420166,
        0.11033077266672488, 0.9696364582197756, 0.2182481603445357
    ]
    return plot
def illustrate_points(points, plot=None, size=0.1):
    if plot is None:
        plot = k3d.plot(name='points')
    plt_points = k3d.points(positions=points, point_size=size)
    plot += plt_points
    plt_points.shader = '3d'
    return plot
Exemple #5
0
def scatter2k3d(x, **kwargs):
    """Convert DataFrame with x,y,z columns to plotly scatter plot."""
    c = eval_color(kwargs.get('color', kwargs.get('c', (100, 100, 100))),
                   color_range=255)
    c = color_to_int(c)
    s = kwargs.get('size', kwargs.get('s', 1))
    name = kwargs.get('name', None)

    trace_data = []
    for scatter in x:
        if isinstance(scatter, pd.DataFrame):
            if not all([c in scatter.columns for c in ['x', 'y', 'z']]):
                raise ValueError('DataFrame must have x, y and z columns')
            scatter = [['x', 'y', 'z']].values

        if not isinstance(scatter, np.ndarray):
            scatter = np.array(scatter)

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            trace_data.append(k3d.points(positions=scatter,
                                         name=name,
                                         color=c,
                                         point_size=s,
                                         shader='dot'))
    return trace_data
Exemple #6
0
    def setup_plot(self, pb):
        super(WBShellFETriangularMesh, self).setup_plot(pb)

        X_Id = self.X_Id.astype(np.float32)

        fixed_nodes = self.bc_fixed_nodes
        loaded_nodes = self.bc_loaded_nodes

        X_Ma = X_Id[fixed_nodes]
        k3d_fixed_nodes = k3d.points(X_Ma, color=0x22ffff, point_size=100)
        pb.plot_fig += k3d_fixed_nodes
        pb.objects['fixed_nodes'] = k3d_fixed_nodes

        X_Ma = X_Id[loaded_nodes]
        k3d_loaded_nodes = k3d.points(X_Ma, color=0xff22ff, point_size=100)
        pb.plot_fig += k3d_loaded_nodes
        pb.objects['loaded_nodes'] = k3d_loaded_nodes
Exemple #7
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()
Exemple #8
0
    def setup_plot(self, pb):
        X_Ia = self.mesh.X_Ia.astype(np.float32)
        I_Fi = self.mesh.I_Fi.astype(np.uint32)

        X_Ma = X_Ia[self.bc_J_xyz]
        self.k3d_fixed_xyz = k3d.points(X_Ma)
        pb.plot_fig += self.k3d_fixed_xyz

        X_Ma = X_Ia[self.bc_J_x]
        self.k3d_fixed_x = k3d.points(X_Ma, color=0x22ffff)
        pb.plot_fig += self.k3d_fixed_x

        X_Ma = X_Ia[self.bc_J_F_xyz]
        self.k3d_load_z = k3d.points(X_Ma, color=0xff22ff)
        pb.plot_fig += self.k3d_load_z

        self.k3d_mesh = k3d.mesh(X_Ia, I_Fi, color=0x999999, side='double')
        pb.plot_fig += self.k3d_mesh
Exemple #9
0
 def __get_joint_points(self) -> List[Points]:
     skeleton_joint_colors: np.ndarray = self.__get_joint_colors()
     return [
         k3d.points(positions=self.joint_positions[line_index],
                    point_size=self.part_size,
                    shader='mesh',
                    color=int(skeleton_joint_colors[line_index]))
         for line_index in range(self.joint_set.number_of_joints)
     ]
Exemple #10
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
Exemple #11
0
 def __get_joint_points_for_video(self) -> List[Points]:
     skeleton_joint_colors: np.ndarray = self.__get_joint_colors()
     return [
         k3d.points(positions={
             current_timestamp[0]: current_timestamp[1][line_index]
             for current_timestamp in self.joint_positions.items()
         },
                    color=int(skeleton_joint_colors[line_index]),
                    point_size=self.part_size,
                    shader='mesh')
         for line_index in range(self.joint_set.number_of_joints)
     ]
Exemple #12
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
Exemple #13
0
 def test_drawable_notification(self):
     # given
     transform = Transform()
     points = k3d.points([0, 0, 1])
     transform.add_drawable(points)
     # when
     transform.scaling = [1., 2., 3.]
     # then
     self.assertTrue((points.model_matrix == np.array([[1., 0., 0., 0.],
                                                       [0., 2., 0., 0.],
                                                       [0., 0., 3., 0.],
                                                       [0., 0., 0.,
                                                        1.]])).all())
Exemple #14
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()))
Exemple #15
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()
Exemple #16
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
def Tetrahedron(origin, size=1):

    if np.shape(origin) == (3, ):
        tetrahedron_vertices = k3d.points(positions=[(1, 1, 1), (1, -1, -1),
                                                     (-1, 1, -1), (-1, -1, 1)],
                                          point_size=0.1)
        tetrahedron_vertices.positions = np.float32(
            size * np.array(tetrahedron_vertices.positions) +
            np.array(origin, np.float32))

        tetrahedron_mesh = k3d.mesh(
            tetrahedron_vertices.positions,
            indices=[0, 1, 2, 0, 1, 3, 1, 2, 3, 0, 2, 3])

    else:
        raise TypeError('Origin attribute should have 3 coordinates.')

    return [tetrahedron_vertices, tetrahedron_mesh]
def Octahedron(origin, size=1):

    if np.shape(origin) == (3, ):
        octahedron_vertices = k3d.points([(1, 0, 0), (0, 1, 0), (0, 0, 1),
                                          (-1, 0, 0), (0, -1, 0), (0, 0, -1)],
                                         point_size=0.1)
        octahedron_vertices.positions = np.float32(
            size * np.array(octahedron_vertices.positions) + np.array(origin))

        octahedron_mesh = k3d.mesh(octahedron_vertices.positions,
                                   indices=[
                                       0, 1, 2, 0, 1, 5, 1, 2, 3, 1, 3, 5, 0,
                                       4, 5, 0, 2, 4, 2, 3, 4, 3, 4, 5
                                   ])
    else:
        raise TypeError('Origin attribute should have 3 coordinates.')

    return [octahedron_vertices, octahedron_mesh]
Exemple #19
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()
Exemple #20
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()
Exemple #21
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
Exemple #22
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()
def Cube(origin, size=1):

    if np.shape(origin) == (3, ):
        cube_vertices = np.array(list(product([1, -1], [1, -1], [1, -1])),
                                 np.float32)
        cube_vertices = k3d.points(positions=cube_vertices, point_size=0.1)

        cube_vertices.positions = np.float32(size * cube_vertices.positions +
                                             np.array(origin))

        cube_mesh = k3d.mesh(cube_vertices.positions,
                             indices=[
                                 0, 1, 2, 1, 2, 3, 0, 1, 4, 1, 4, 5, 1, 3, 5,
                                 3, 5, 7, 0, 2, 4, 2, 4, 6, 2, 3, 7, 2, 6, 7,
                                 4, 5, 6, 5, 6, 7
                             ])

    else:
        raise TypeError('Origin attribute should have 3 coordinates.')

    return [cube_vertices, cube_mesh]
def Dodecahedron(origin, size=1):

    origin = np.array(origin, dtype=np.float32)

    if np.shape(origin) == (3, ):
        fi = (1 + np.sqrt(5)) / 2
        dodecahedron_vertices = list(product([-1, 1], [-1, 1], [-1, 1]))
        dodecahedron_vertices += [(0, fi, 1 / fi), (0, -fi, 1 / fi),
                                  (0, -fi, -1 / fi), (0, fi, -1 / fi),
                                  (1 / fi, 0, fi), (-1 / fi, 0, fi),
                                  (-1 / fi, 0, -fi), (1 / fi, 0, -fi),
                                  (fi, 1 / fi, 0), (-fi, 1 / fi, 0),
                                  (-fi, -1 / fi, 0), (fi, -1 / fi, 0)]
        dodecahedron_vertices = np.float32(size *
                                           np.array(dodecahedron_vertices) +
                                           origin)

        dodecahedron_vertices = k3d.points(dodecahedron_vertices,
                                           point_size=0.1,
                                           visible=False)
        indices = [
            0, 1, 18, 0, 1, 10, 1, 9, 10, 0, 10, 14, 10, 14, 15, 4, 10, 15, 4,
            9, 10, 4, 5, 9, 4, 5, 19, 4, 15, 19, 6, 15, 19, 6, 16, 19, 6, 7,
            16, 6, 7, 8, 6, 8, 11, 2, 3, 17, 2, 3, 8, 2, 8, 11, 1, 3, 13, 1, 3,
            18, 3, 17, 18, 1, 9, 13, 9, 12, 13, 5, 9, 12, 5, 12, 19, 12, 16,
            19, 7, 12, 16, 3, 7, 8, 3, 7, 12, 3, 12, 13, 14, 6, 15, 14, 6, 11,
            2, 11, 14, 0, 17, 18, 0, 2, 17, 0, 2, 14
        ]

        dodecahedron_mesh = k3d.mesh(dodecahedron_vertices.positions,
                                     indices=indices,
                                     wireframe=False)
    else:
        raise TypeError('Origin attribute should have 3 coordinates.')

    return [dodecahedron_vertices, dodecahedron_mesh]
Exemple #25
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()
Exemple #26
0
    def __init__(
        self,
        data: Union[np.ndarray, geo.SpatialData],
        name: str,
        reference_system: str,
        plot: k3d.Plot = None,
        color: int = None,
        visualization_method: str = "auto",
        show_wireframe: bool = False,
    ):
        """Create a ``SpatialDataVisualizer`` instance.

        Parameters
        ----------
        data :
            The data that should be visualized
        name :
            Name of the data
        reference_system :
            Name of the data's reference system
        plot :
            A k3d plotting widget.
        color :
            The RGB color of the coordinate system (affects trace and label) as a 24 bit
            integer value.
        visualization_method :
            The initial data visualization method. Options are ``point``, ``mesh``,
            ``both``and ``auto``. If ``auto`` is selected, a mesh will be drawn if
            triangle data is available and points if not.
        show_wireframe :
            If `True`, meshes will be drawn as wireframes

        """
        if not isinstance(data, geo.SpatialData):
            data = geo.SpatialData(coordinates=data)

        colors = []
        if color is None or isinstance(color, str):
            if isinstance(color, str):
                colors = data.attributes[color]
            color = RGB_GREY

        if data.triangles is not None:
            triangles = data.triangles.astype(np.uint32)
        else:
            triangles = None

        self._reference_system = reference_system

        self._label_pos = data.coordinates.mean(dim=data.additional_dims).data
        if isinstance(self._label_pos, Q_):
            self._label_pos = self._label_pos.to(_DEFAULT_LEN_UNIT).m
        self._label = None
        if name is not None:
            self._label = k3d.text(
                text=name,
                position=self._label_pos,
                reference_point="cc",
                color=color,
                size=0.5,
                label_box=True,
                name=name if name is None else f"{name} (text)",
            )

        coordinates = data.coordinates.data
        if isinstance(coordinates, Q_):
            coordinates = coordinates.to(_DEFAULT_LEN_UNIT).m

        self._points = k3d.points(
            coordinates,
            point_size=0.05,
            color=color,
            name=name if name is None else f"{name} (points)",
        )
        self._mesh = None
        if data.triangles is not None:
            self._mesh = k3d.mesh(
                coordinates.astype(np.float32).reshape(-1, 3),
                triangles,
                side="double",
                color=color,
                attribute=colors,
                color_map=k3d.colormaps.matplotlib_color_maps.Viridis,
                wireframe=show_wireframe,
                name=name if name is None else f"{name} (mesh)",
            )

        self.set_visualization_method(visualization_method)

        if plot is not None:
            plot += self._points
            if self._mesh is not None:
                plot += self._mesh
            if self._label is not None:
                plot += self._label

        self.data = data
 def _add_nodes_to_fig(self, pb, X_Ma):
     k3d_points = k3d.points(X_Ma, point_size=300)
     pb.objects[self.NODES] = k3d_points
     pb.plot_fig += k3d_points
Exemple #28
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
Exemple #29
0
    xyz1 = xyz + np.array([0.5, 0.5, 0])
    xyz2 = xyz + np.array([0.5, 0, 0.5])
    xyz3 = xyz + np.array([0, 0.5, 0.5])

    XYZ = np.vstack([xyz, xyz1, xyz2, xyz3]).astype(np.float32)

    return XYZ


def distance(a, b):
    return np.sqrt(np.sum((a - b)**2, axis=1))


### FIRST DRAWING
cubic_system = cubic(0, 0, 0, 3, 3, 3)
red_point = k3d.points(cubic_system[0], point_size=0.2, color=0xff0000)
system = k3d.points(cubic_system[1:], point_size=0.2, color=0)
a_vec = k3d.vectors(red_point.positions,
                    cubic_system[3],
                    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],
Exemple #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