def drawPoints(Points,
               mlab,
               scale=0.025,
               color=(np.random.rand(1)[0], np.random.rand(1)[0],
                      np.random.rand(1)[0])):
    """
    用MayaVi绘制点
    :param Points: 欲绘制的顶点 n * 3
    :param mlab:
    :return: 返回mlab
    """
    if isinstance(Points, list):
        Points = np.array(Points, dtype=np.float32)
    mlab.points3d(Points[:, 0],
                  Points[:, 1],
                  Points[:, 2],
                  scale_factor=scale,
                  color=color)
    for i in range(0, len(Points)):
        mlab.text3d(Points[i, 0],
                    Points[i, 1],
                    Points[i, 2],
                    str(i + 1),
                    scale=scale * 1.5,
                    color=(0, 0, 0))
    return mlab
Esempio n. 2
0
def drawArrows(file1, file2, figure, bbox, index, descendant):
    """
    Draw an 'arrow' from the cell 'index' to 'descendant'
    'descendant' is assumed to be a 1D np.array with size 0, 1 or 2.
    """
    #load the center of mass position
    if descendant.size > 0 and descendant[0] != 0:
        com1 = file1["features"][str(index[0])]["com"][:]
        com2 = file2["features"][str(descendant[0])]["com"][:]
        
        #write the cell label as text
        mlab.text3d(com1[2]-bbox[2]+1,com1[1]-bbox[1]+1,com1[0]-bbox[0]+1, str(index), color=(1,1,1), figure=figure)
        
        #plot a point where the current cell is
        mlab.points3d([com1[2]-bbox[2]+1],[com1[1]-bbox[1]+1],[com1[0]-bbox[0]+1],color=(0,0,1), figure=figure)
                
        #plot a line to the descendant's center
        mlab.plot3d([com1[2]-bbox[2]+1,com2[2]-bbox[2]+1],
                    [com1[1]-bbox[1]+1,com2[1]-bbox[1]+1],
                    [com1[0]-bbox[0]+1,com2[0]-bbox[0]+1],
                    tube_radius=0.2, color=(1,0,0), figure=figure)
        
        #plot a second line, if there is a split
        if descendant.size == 2:
            com3 = file2["features"][str(descendant[1])]["com"][:]
            mlab.plot3d([com1[2]-bbox[2]+1,com3[2]-bbox[2]+1],
                        [com1[1]-bbox[1]+1,com3[1]-bbox[1]+1],
                        [com1[0]-bbox[0]+1,com3[0]-bbox[0]+1],
                        tube_radius=0.2, color=(1,0,0), figure=figure)
Esempio n. 3
0
    def _render(self, **kwargs):
        from mayavi import mlab
        # disabling the rendering greatly speeds up this for loop
        self.figure.scene.disable_render = True
        positions = []
        for label, mask in self.labels_to_masks.iteritems():
            p = self.pointcloud.from_mask(mask)
            for i, p in enumerate(p.points):
                positions.append(p)
                l = '%s_%d' % (label, i)
                # TODO: This is due to a bug in mayavi that won't allow
                # rendering text to an empty figure
                mlab.points3d(p[0], p[1], p[2])
                mlab.text3d(p[0], p[1], p[2], l, figure=self.figure)
        positions = np.array(positions)
        os = np.zeros_like(positions)
        os[:, 2] = 1
        mlab.quiver3d(positions[:, 0],
                      positions[:, 1],
                      positions[:, 2],
                      os[:, 0],
                      os[:, 1],
                      os[:, 2],
                      figure=self.figure)
        self.figure.scene.disable_render = False

        return self
Esempio n. 4
0
    def plot(self, size=(800, 800), fig=None, HPI_ns=False):
        """
        Plot sensor helmet and head. ``fig`` is used if provided, otherwise
        a new mayavi figure is created with ``size``.

        HPI_ns : bool
            Add number labels to the HPI points.

        """
        if fig is None:
            fig = mlab.figure(size=size)

        self.mrk.plot_points(fig, scale=1.1e-2, opacity=.5, color=(1, 0, 0))
        self.sensors.plot_points(fig, scale=1e-2, color=(0, 0, 1))

        self.HPI.plot_points(fig, scale=1e-2, color=(1, .8, 0))
        self.headshape.plot_solid(fig, opacity=1., color=(1, 1, 1))

        if self.MRI is not None:
            self.MRI.plot_solid(fig, opacity=1., color=(.6, .6, .5))

        # label marker points
        for i, pt in enumerate(self.mrk.pts[:3].T):
            x, y, z = pt
            self.txt = mlab.text3d(x, y, z, str(i), scale=.01)

        if HPI_ns:  # label HPI points
            for i, pt in enumerate(self.HPI.pts[:3].T):
                x, y, z = pt
                mlab.text3d(x, y, z, str(i), scale=.01, color=(1, .8, 0))

        return fig
Esempio n. 5
0
def draw_gt_boxes3d(gt_boxes3d, fig, color=(1,1,1), line_width=1, draw_text=True, text_scale=(1,1,1), color_list=None):
    ''' Draw 3D bounding boxes
    Args:
        gt_boxes3d: numpy array (n,8,3) for XYZs of the box corners
        fig: mayavi figure handler
        color: RGB value tuple in range (0,1), box line color
        line_width: box line width
        draw_text: boolean, if true, write box indices beside boxes
        text_scale: three number tuple
        color_list: a list of RGB tuple, if not None, overwrite color.
    Returns:
        fig: updated fig
    '''
    num = len(gt_boxes3d)
    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text: mlab.text3d(b[4,0], b[4,1], b[4,2], '%d'%n, scale=text_scale, color=color, figure=fig)
        for k in range(0,4):
            #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i,j=k,(k+1)%4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)

            i,j=k+4,(k+1)%4 + 4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)

            i,j=k,k+4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)
    #mlab.show(1)
    #mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)
    return fig
Esempio n. 6
0
    def render(self, scale_factor=1.0, text_scale=1.0, **kwargs):
        import mayavi.mlab as mlab
        # disabling the rendering greatly speeds up this for loop
        self.figure.scene.disable_render = True
        positions = []
        for label in self.lmark_group:
            p = self.lmark_group[label]
            for i, p in enumerate(p.points):
                positions.append(p)
                l = '%s_%d' % (label, i)
                # TODO: This is due to a bug in mayavi that won't allow
                # rendering text to an empty figure
                mlab.points3d(p[0], p[1], p[2], scale_factor=scale_factor)
                mlab.text3d(p[0], p[1], p[2], l, figure=self.figure,
                            scale=text_scale)
        positions = np.array(positions)
        os = np.zeros_like(positions)
        os[:, 2] = 1
        mlab.quiver3d(positions[:, 0], positions[:, 1], positions[:, 2],
                      os[:, 0], os[:, 1], os[:, 2], figure=self.figure)
        self.figure.scene.disable_render = False

        # Ensure everything fits inside the camera viewport
        mlab.get_engine().current_scene.scene.reset_zoom()

        return self
Esempio n. 7
0
def plot_structure(structure,
                   frac_coords=False,
                   to_unit_cell=False,
                   style="points+labels",
                   unit_cell_color=(0, 0, 0),
                   color_scheme="VESTA",
                   figure=None,
                   show=False,
                   **kwargs):  # pragma: no cover
    """
    Plot structure with mayavi.

    Args:
        structure: |Structure| object
        frac_coords:
        to_unit_cell: True if sites should be wrapped into the first unit cell.
        style: "points+labels" to show atoms sites with labels.
        unit_cell_color:
        color_scheme: color scheme for atom types. Allowed values in ("Jmol", "VESTA")
        figure:
        kwargs:

    Returns: mayavi figure
    """
    figure, mlab = get_fig_mlab(figure=figure)

    #if not frac_coords:
    plot_unit_cell(structure.lattice, color=unit_cell_color, figure=figure)
    from pymatgen.analysis.molecule_structure_comparator import CovalentRadius
    from pymatgen.vis.structure_vtk import EL_COLORS

    for site in structure:
        symbol = site.specie.symbol
        color = tuple(i / 255 for i in EL_COLORS[color_scheme][symbol])
        radius = CovalentRadius.radius[symbol]
        if to_unit_cell and hasattr(site, "to_unit_cell"):
            site = site.to_unit_cell
        x, y, z = site.frac_coords if frac_coords else site.coords

        if "points" in style:
            mlab.points3d(x,
                          y,
                          z,
                          figure=figure,
                          scale_factor=radius,
                          resolution=20,
                          color=color,
                          scale_mode='none',
                          **kwargs)
        if "labels" in style:
            mlab.text3d(x,
                        y,
                        z,
                        symbol,
                        figure=figure,
                        color=(0, 0, 0),
                        scale=0.2)

    if show: mlab.show()
    return figure
def draw_boxes3d(gt_boxes3d,
                 color=(1, 1, 1),
                 line_width=1,
                 draw_text=True,
                 text_scale=(0.01, 0.01, 0.01),
                 color_list=None):
    from mayavi import mlab
    num = len(gt_boxes3d)
    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text:
            mlab.text3d(b[7, 0],
                        b[7, 1],
                        b[7, 2],
                        '%d' % n,
                        scale=text_scale,
                        color=color)

        # hard coded
        # pairs = [(0, 1), (1, 2), (1, 3), (3, 0), (4, 5), (5, 6), (6, 7), (7, 4), (0, 4), (1, 5), (2, 6), (3, 7)]
        pairs = [(0, 1), (0, 2), (3, 1), (3, 2), (4, 5), (4, 6), (7, 5),
                 (7, 6), (0, 4), (1, 5), (2, 6), (3, 7)]
        for i, j in pairs:
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width)
Esempio n. 9
0
    def _show_labels(self, show):
        _toggle_mlab_render(self, False)
        while self.text3d:
            text = self.text3d.pop()
            text.remove()

        if show and len(self.src.data.points) > 0:
            fig = self.scene.mayavi_scene
            if self._view == 'arrow':  # for axes
                x, y, z = self.src.data.points[0]
                self.text3d.append(
                    text3d(x,
                           y,
                           z,
                           self.name,
                           scale=self.label_scale,
                           color=self.color,
                           figure=fig))
            else:
                for i, (x, y, z) in enumerate(np.array(self.src.data.points)):
                    self.text3d.append(
                        text3d(x,
                               y,
                               z,
                               ' %i' % i,
                               scale=self.label_scale,
                               color=self.color,
                               figure=fig))
        _toggle_mlab_render(self, True)
Esempio n. 10
0
def draw_gt_boxes2d(gt_boxes2d,
                    fig,
                    color=(1, 1, 1),
                    line_width=1,
                    draw_text=True,
                    text_scale=(1, 1, 1),
                    color_list=None):
    num = len(gt_boxes2d)
    for n in range(num):
        b = gt_boxes2d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text:
            mlab.text3d(b[4, 0],
                        b[4, 1],
                        b[4, 2],
                        '%d' % n,
                        scale=text_scale,
                        color=color,
                        figure=fig)
        for i in range(4):
            mlab.plot3d([b[i, 0], b[(i + 1) % 4, 0]],
                        [b[i, 1], b[(i + 1) % 4, 1]],
                        [b[i, 2], b[(i + 1) % 4, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)
    return fig
Esempio n. 11
0
    def draw_3D_bboxes(self, bboxes3d, fig, line_width=2, draw_text=True, text_scale=(1, 1, 1)):

        num = len(bboxes3d)
        for n in range(num):
            b = bboxes3d[n]
            if b[0] != "None":

                if b[0] == "car":
                    color = tuple(self.colorVehPC)
                elif b[0] == "person":
                    color = tuple(self.colorPedPC)
                elif b[0] == "cyclist":
                    color = tuple(self.colorCycPC)
                else:
                    color = (0, 0, 0)

                if draw_text:
                    mlab.text3d(b[1][0,0], b[1][1,0], b[1][2,0], '%s'%b[0], scale=text_scale, color=color, figure=fig)
                for k in range(0,4):

                    i,j=k,(k+1)%4
                    #mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)
                    mlab.plot3d([b[1][0,i], b[1][0,j]], [b[1][1,i], b[1][1,j]], [b[1][2,i], b[1][2,j]], color=color, tube_radius=None, line_width=line_width, figure=fig)

                    i,j=k+4,(k+1)%4 + 4
                    #mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)
                    mlab.plot3d([b[1][0,i], b[1][0,j]], [b[1][1,i], b[1][1,j]], [b[1][2,i], b[1][2,j]], color=color, tube_radius=None, line_width=line_width, figure=fig)

                    i,j=k,k+4
                    #mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)
                    mlab.plot3d([b[1][0,i], b[1][0,j]], [b[1][1,i], b[1][1,j]], [b[1][2,i], b[1][2,j]], color=color, tube_radius=None, line_width=line_width, figure=fig)

        return fig
Esempio n. 12
0
    def render(self, scale_factor=1.0, text_scale=1.0, **kwargs):
        import mayavi.mlab as mlab
        # disabling the rendering greatly speeds up this for loop
        self.figure.scene.disable_render = True
        positions = []
        for label in self.lmark_group:
            p = self.lmark_group[label]
            for i, p in enumerate(p.points):
                positions.append(p)
                l = '%s_%d' % (label, i)
                # TODO: This is due to a bug in mayavi that won't allow
                # rendering text to an empty figure
                mlab.points3d(p[0], p[1], p[2], scale_factor=scale_factor)
                mlab.text3d(p[0],
                            p[1],
                            p[2],
                            l,
                            figure=self.figure,
                            scale=text_scale)
        positions = np.array(positions)
        os = np.zeros_like(positions)
        os[:, 2] = 1
        mlab.quiver3d(positions[:, 0],
                      positions[:, 1],
                      positions[:, 2],
                      os[:, 0],
                      os[:, 1],
                      os[:, 2],
                      figure=self.figure)
        self.figure.scene.disable_render = False

        # Ensure everything fits inside the camera viewport
        mlab.get_engine().current_scene.scene.reset_zoom()

        return self
Esempio n. 13
0
def quiver4(datas, length = 6000, skip=5):
    black = (0,0,0)
    white = (1,1,1)
    mlab.figure(bgcolor=white)

    triangles = [
        (0, 1, 2),
        (0, 2, 4),
        (0, 4, 3),
        (0, 3, 1),
    ]
    
    for cam_id, data in datas.items():
        if cam_id == '107':
            continue
        
        x0, y0, z0, phi, psi = \
            [data[i] for i in ('x', 'y', 'z', 'bounding_phi', 'bounding_psi')]

        x = x0 + length * np.sin(phi)
        y = y0 + length * np.cos(phi)
        z = z0 + length * np.cos(psi)

        mlab.triangular_mesh(
            np.insert(x, 0, x0),
            np.insert(y, 0, y0),
            np.insert(z, 0, z0),
            triangles,
            color=(0.5, 0.5, 0.5),
            opacity=0.4
        )
        mlab.text3d(x0, y0, z0, cam_id, color=black, scale=100.)
    
    mlab.show()
 def draw_label(trk, handle):
     p = trk.center
     mlab.text3d(p[0],
                 p[1],
                 p[2] + 2,
                 str(trk.id),
                 scale=0.5,
                 figure=handle)
Esempio n. 15
0
    def draw_boxes(self,
                   boxes,
                   color=(1, 1, 1),
                   line_width=1,
                   draw_text=True,
                   text_scale=(1, 1, 1),
                   color_list=None):
        ''' Draw 3D bounding boxes
        Args:
            boxes: numpy array (n,8,3) for XYZs of the box corners
            fig: mayavi figure handler
            color: RGB value tuple in range (0,1), box line color
            line_width: box line width
            draw_text: boolean, if true, write box indices beside boxes
            text_scale: three number tuple
            color_list: a list of RGB tuple, if not None, overwrite color.
        Returns:
            fig: updated fig
        '''
        self._create_figure()
        num = len(boxes)
        for n in range(num):
            b = boxes[n]
            if color_list is not None:
                color = color_list[n]
            if draw_text:
                mlab.text3d(b[4, 0],
                            b[4, 1],
                            b[4, 2],
                            '%d' % n,
                            scale=text_scale,
                            color=color,
                            figure=fig)
            for k in range(0, 4):
                #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
                i, j = k, (k + 1) % 4
                mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                            [b[i, 2], b[j, 2]],
                            color=color,
                            tube_radius=None,
                            line_width=line_width,
                            figure=fig)

                i, j = k + 4, (k + 1) % 4 + 4
                mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                            [b[i, 2], b[j, 2]],
                            color=color,
                            tube_radius=None,
                            line_width=line_width,
                            figure=fig)

                i, j = k, k + 4
                mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                            [b[i, 2], b[j, 2]],
                            color=color,
                            tube_radius=None,
                            line_width=line_width,
                            figure=fig)
Esempio n. 16
0
    def _add_points(self):

        if self.map_surface:
            temp = self.points.map_to_surface(self.map_surface)
            mapped_vertices, mapped_coords_ras_tkr = temp['vertices'], temp[
                'ras_tkr_coord']
            mapped_coords = mapped_coords_ras_tkr

        ### FreesurferCoords.map_to_annot requires map_surface to be set ( set to white by default). Here, we use map_surface if it has been set, otherwise use 'white' by default.

        if self.map_to_annot:
            if self.map_surface:
                self.points.name, self.points.color = self.points.map_to_annot(
                    self.map_to_annot, map_surface=self.map_surface)
            else:
                self.points.name, self.points.color = self.points.map_to_annot(
                    self.map_to_annot, map_surface='white')

        for i in range(self.points.npoints):
            point = self.points[i]

            if point.hemi == self.hemi or self.hemi == 'both':

                if self.map_surface:
                    self.brain.add_foci(mapped_coords[i, :],
                                        hemi=point.hemi,
                                        color=point.color,
                                        scale_factor=point.scale_factor,
                                        alpha=point.opacity)
                else:
                    self.brain.add_foci(point.ras_tkr_coord,
                                        hemi=point.hemi,
                                        color=point.color,
                                        scale_factor=point.scale_factor,
                                        alpha=point.opacity)

                if self.show_roi and hasattr(point, 'roi'):
                    self.brain.add_label(point.roi,
                                         hemi=point.hemi,
                                         color=point.roi.color)

                if self.show_name and hasattr(point, 'name'):
                    mlab.text3d(point.ras_tkr_coord[0],
                                point.ras_tkr_coord[1],
                                point.ras_tkr_coord[2],
                                point.name,
                                scale=self.name_scale,
                                color=self.name_color)

                if self.show_directions and hasattr(point, 'direction'):
                    origin = point.ras_tkr_coord.flatten().tolist()
                    X, Y, Z = zip(origin, origin, origin)
                    p0 = point.direction[0:3]
                    p1 = point.direction[3:6]
                    p2 = point.direction[6:9]
                    U, W, V = zip(p0, p1, p2)
                    plot_directions(X, Y, Z, U, W, V)
Esempio n. 17
0
 def draw_frame(self, pose, scale=10, label=''):
     R, t = pose
     scale = self.scale * scale
     clr = [RED, GREEN, BLUE]
     vecs = R[:, 0], R[:, 1], R[:, 2]
     for k in range(3):
         mlab.quiver3d(t[0], t[1], t[2], vecs[k][0], vecs[k][1], vecs[k][2],
                       color=clr[k], mode='arrow', scale_factor=scale)
     mlab.text3d(t[0], t[1], t[2], label, scale=scale/5)
Esempio n. 18
0
def res_names(atoms_df):
    """
    """
    for row in atoms_df.iterrows():
        mlab.text3d(row[1][3],
                    row[1][4],
                    row[1][5],
                    text=row[1][0] + " " + str(row[1][2]),
                    color=(0, 0, 0))
Esempio n. 19
0
 def draw_frame(self, pose, scale=10, label=''):
     R, t = pose
     scale = self.scale * scale
     clr = [RED, GREEN, BLUE]
     vecs = R[:, 0], R[:, 1], R[:, 2]
     for k in range(3):
         mlab.quiver3d(t[0], t[1], t[2], vecs[k][0], vecs[k][1], vecs[k][2],
                       color=clr[k], mode='arrow', scale_factor=scale)
     mlab.text3d(t[0], t[1], t[2], label, scale=scale/5)
Esempio n. 20
0
def draw_gt_boxes3d(gt_boxes3d,
                    conf,
                    thres=0,
                    color=(1, 1, 1),
                    fig=None,
                    engine=None,
                    line_width=1,
                    draw_text=True,
                    text_scale=(0.5, 0.5, 0.5),
                    color_list=None):
    #     if engine:
    #         fig = mlab.figure(figure=fig, engine =engine)

    num = len(gt_boxes3d)

    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if n >= thres:
            color = (0, 1, 0)
        else:
            color = (1, 0, 0)
        if draw_text and n >= thres and n - thres <= len(conf):
            mlab.text3d(b[3, 0],
                        b[3, 1],
                        b[3, 2],
                        '%.1f' % float(conf[n - thres]),
                        scale=text_scale,
                        color=color,
                        figure=fig)
        for k in range(0, 4):
            #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i, j = k, (k + 1) % 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k + 4, (k + 1) % 4 + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k, k + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)
Esempio n. 21
0
 def __plotObj(self,obj,obj_shape,base_color,obj_name):
     # objera center
     mi.points3d(obj[0],obj[1],obj[2],color=base_color,scale_factor=0.2) 
     mi.text3d(  obj[0],obj[1],obj[2],obj_name,scale=0.3,color=(0,0,0))
     # Transform 
     T,T_inv = mgo.transformLookAt(obj[0:3],obj[3:6],obj[6:9])
     obj_shape = np.dot(T,np.r_[ 
         obj_shape.transpose(),
         np.ones([1,np.shape(obj_shape)[0]])])
     mi.plot3d(obj_shape[0,:],obj_shape[1,:],obj_shape[2,:],tube_radius=None,reset_zoom=False)
Esempio n. 22
0
def _set_numbering(figure, centers, render_numbering=True, numbers_size=None,
                   numbers_colour='k'):
    import mayavi.mlab as mlab
    numbers_colour = _parse_colour(numbers_colour)
    numbers_size = _parse_marker_size(numbers_size, centers)
    if render_numbering:
        for k, p in enumerate(centers):
            mlab.text3d(p[0], p[1], p[2], str(k), figure=figure,
                        scale=numbers_size, orient_to_camera=True,
                        color=numbers_colour, line_width=2)
Esempio n. 23
0
 def draw_feature_node(self):
     label_text = []
     junc_len = len(self.skel_data.junction_index)
     for i in xrange(len(self.skel_data.feature_node_index)):
         label_text.append(str(i))
     #mlab.figure(self.program_id[0])
     pts = mlab.points3d(self.skel_data.feature_node[:junc_len,0], self.skel_data.feature_node[:junc_len,1], self.skel_data.feature_node[:junc_len,2], color=(.7,.0,0.0), scale_factor=.135, resolution=20)
     mlab.points3d(self.skel_data.feature_node[junc_len:,0], self.skel_data.feature_node[junc_len:,1], self.skel_data.feature_node[junc_len:,2], color=(.0,.0,0.7), scale_factor=.1, resolution=20)
     for i in xrange(len(label_text)):
         mlab.text3d(self.skel_data.feature_node[i,0], self.skel_data.feature_node[i,1], self.skel_data.feature_node[i,2], label_text[i], scale=.15)
Esempio n. 24
0
def draw_gt_box3d(gt_box3d,
                  fig,
                  obj,
                  line_width=1,
                  draw_text=True,
                  text_scale=(1, 1, 1)):

    if obj.type in class_colors:
        color = class_colors[obj.type]
    else:
        color = (1, 0, 1)

    if draw_text:
        label = '%s: %.1f' % (obj.type, obj.score)
        mlab.text3d(gt_box3d[4, 0],
                    gt_box3d[4, 1],
                    gt_box3d[4, 2],
                    label,
                    scale=text_scale,
                    color=color,
                    figure=fig)

    for k in range(0, 4):
        # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
        i, j = k, (k + 1) % 4
        mlab.plot3d([gt_box3d[i, 0], gt_box3d[j, 0]],
                    [gt_box3d[i, 1], gt_box3d[j, 1]],
                    [gt_box3d[i, 2], gt_box3d[j, 2]],
                    color=color,
                    tube_radius=None,
                    line_width=line_width,
                    figure=fig)

        i, j = k + 4, (k + 1) % 4 + 4
        mlab.plot3d([gt_box3d[i, 0], gt_box3d[j, 0]],
                    [gt_box3d[i, 1], gt_box3d[j, 1]],
                    [gt_box3d[i, 2], gt_box3d[j, 2]],
                    color=color,
                    tube_radius=None,
                    line_width=line_width,
                    figure=fig)

        i, j = k, k + 4
        mlab.plot3d([gt_box3d[i, 0], gt_box3d[j, 0]],
                    [gt_box3d[i, 1], gt_box3d[j, 1]],
                    [gt_box3d[i, 2], gt_box3d[j, 2]],
                    color=color,
                    tube_radius=None,
                    line_width=line_width,
                    figure=fig)

    # mlab.show(1)
    # mlab.view(azimuth=180, elevation=70, focalpoint=[ 12.0909996 , -1.04700089, -2.03249991], distance=62.0, figure=fig)
    return fig
Esempio n. 25
0
    def _PlotQuiver(self, Phi, Theta, Figure, Origin, Coord, Vector, Scalar, Label=''):

        FlatCoord = [1.01*Coord[i].flatten() + Origin[i]  for i in range(3)]

        A = Scalar.flatten()
        A /= np.max(abs(A))
        Vector = A * Vector

        mlab.quiver3d(*FlatCoord, *Vector, color=(0,0,0), scale_factor=0.25, scale_mode = 'vector', figure=Figure)

        mlab.text3d(x = Origin[0], y = Origin[1], z = Origin[2]+3.5, text = Label, line_width = 0.1, figure = Figure, scale = 0.25, color = (0,0,0))
Esempio n. 26
0
def visualize_text(point, text):
    try:
        from mayavi import mlab
    except ImportError:
        return
    mlab.figure('pc', bgcolor=(0.05, 0.05, 0.05))
    mlab.text3d(point[0],
                point[1],
                point[2] + 0.03,
                '{}'.format(int(point[3])),
                scale=0.02,
                color=(0, 0.8, 0))
Esempio n. 27
0
def _plot_axes(lattice, color=(1, 0, 0)):
    lat = np.transpose([x / np.linalg.norm(x) for x in lattice.T])
    mlab.quiver3d([0, 0, 0], [0, 0, 0], [0, 0, 0],
                  lat[0],
                  lat[1],
                  lat[2],
                  color=color,
                  line_width=3,
                  scale_factor=1)

    for c, v in zip(('a', 'b', 'c'), (lat * 1.3).T):
        mlab.text3d(v[0] + 0.15, v[1], v[2], c, color=color, scale=0.3)
Esempio n. 28
0
def draw_gt_boxes3d(gt_boxes3d,
                    iIndex,
                    fig,
                    color=(1, 1, 1),
                    line_width=1,
                    draw_text=True,
                    text_scale=(1, 1, 1),
                    color_list=None):
    num = len(gt_boxes3d)
    for n in range(num):
        b = gt_boxes3d[n]
        if color_list is not None:
            color = color_list[n]
        if draw_text:
            mlab.text3d(b[4, 0],
                        b[4, 1],
                        b[4, 2],
                        '%d' % iIndex,
                        scale=text_scale,
                        color=color,
                        figure=fig)
        for k in range(0, 4):
            # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i, j = k, (k + 1) % 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k + 4, (k + 1) % 4 + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k, k + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)
    # mlab.show()
    mlab.view(azimuth=180,
              elevation=70,
              focalpoint=[12.0909996, -1.04700089, -2.03249991],
              distance=62.0,
              figure=fig)
    return fig
Esempio n. 29
0
def WavenumberArrow(Figure, Origin, Scale=0.5):
    Vec = [0, 0, 1]

    ArrowAVec(Origin=Origin, Vec=Vec, Scale=Scale, Color=YELLOW)

    mlab.text3d(x=Vec[0] + Origin[0],
                y=Vec[1] + Origin[1],
                z=Vec[2] + Origin[2],
                text='k',
                line_width=0.1,
                figure=Figure,
                scale=0.25,
                color=BLACK)
Esempio n. 30
0
def ElectricFieldArrow(Figure, Origin, Pol, Scale=0.5):
    Vec = [sin(Pol), cos(Pol), 0]

    ArrowAVec(Origin=Origin, Vec=Vec, Scale=Scale, Color=RED)

    mlab.text3d(x=Vec[0] + Origin[0],
                y=Vec[1] + Origin[1],
                z=Vec[2] + Origin[2],
                text='E',
                line_width=0.1,
                figure=Figure,
                scale=0.25,
                color=RED)
Esempio n. 31
0
def MagneticFieldArrow(Figure, Origin, Vec, Scale=0.5):
    Vec = [Vec[0], Vec[1], 0]

    ArrowAVec(Origin=Origin, Vec=Vec, Scale=Scale, Color=BLUE)

    mlab.text3d(x=Vec[0] + Origin[0],
                y=Vec[1] + Origin[1],
                z=Vec[2] + Origin[2],
                text='B',
                line_width=0.1,
                figure=Figure,
                scale=0.25,
                color=BLACK)
Esempio n. 32
0
def draw_gt_boxes3d(gt_boxes3d, fig, color=(1, 0, 0), line_width=2):

    num = len(gt_boxes3d)
    for n in range(num):
        b = gt_boxes3d[n]

        mlab.text3d(b[0, 0],
                    b[0, 1],
                    b[0, 2],
                    '%d' % n,
                    scale=(1, 1, 1),
                    color=color,
                    figure=fig)
        for k in range(0, 4):

            #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i, j = k, (k + 1) % 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)
            mlab.text3d(b[i, 0],
                        b[i, 1],
                        b[i, 2],
                        '%d' % i,
                        scale=(1, 1, 1),
                        color=color,
                        figure=fig)
            i, j = k + 4, (k + 1) % 4 + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

            i, j = k, k + 4
            mlab.plot3d([b[i, 0], b[j, 0]], [b[i, 1], b[j, 1]],
                        [b[i, 2], b[j, 2]],
                        color=color,
                        tube_radius=None,
                        line_width=line_width,
                        figure=fig)

    mlab.view(azimuth=180,
              elevation=None,
              distance=50,
              focalpoint=[12.0909996, -1.04700089,
                          -2.03249991])  #2.0909996 , -1.04700089, -2.03249991
Esempio n. 33
0
    def test_text3d(self):
        """Test if Text3D shows"""
        # the points3d is there to provide data for
        # attaching the text3d module.  Opacity is set to
        # zero so that the image should only show
        # the text3d and we look for the pixels
        mlab.points3d(0., 0., 0., opacity=0.)

        self.addCleanup(self.mlab_close_all)

        mlab.text3d(0., 0., 0., "X")
        mlab.savefig(self.filename)

        self.check()
Esempio n. 34
0
def _plot_axes(lattice, color=(1, 0, 0)):
    lat = np.transpose([x/np.linalg.norm(x) for x in lattice.T])
    mlab.quiver3d([0, 0, 0],
                  [0, 0, 0],
                  [0, 0, 0],
                  lat[0],
                  lat[1],
                  lat[2],
                  color=color,
                  line_width=3,
                  scale_factor=1)

    for c, v in zip(('a','b','c'), (lat * 1.3).T):
        mlab.text3d(v[0]+0.15, v[1], v[2], c, color=color, scale=0.3)
Esempio n. 35
0
    def test_text3d(self):
        """Test if Text3D shows"""
        # the points3d is there to provide data for
        # attaching the text3d module.  Opacity is set to
        # zero so that the image should only show
        # the text3d and we look for the pixels
        mlab.points3d(0., 0., 0., opacity=0.)

        self.addCleanup(self.mlab_close_all)

        mlab.text3d(0., 0., 0., "X")
        mlab.savefig(self.filename)

        self.check()
Esempio n. 36
0
def mayaplot(xyznamearray):

	x = xyznamearray[1]
	y = xyznamearray[2]
	z = xyznamearray[3]
	labels = xyznamearray[0]

	s = mlab.points3d(x[0], y[0], z[0], color=(0,1,1), mode='sphere', scale_factor=100)

	for i in range(0,26):
		mlab.points3d(x[i], y[i], z[i], color=(0,1,1), mode='sphere', scale_factor=5000, opacity=0.5)
		mlab.text3d(x[i], y[i], z[i], labels[i], scale=5000)


	axes = mlab.axes(s, extent = (-220000,220000, -220000,220000, -220000,220000), nb_labels=3)
Esempio n. 37
0
def displayGeneratedEvent(tree, evID, forward=0):
    global fname, branches

    print
    print "<displayGeneratedEvent> evID =", evID, ", forward =", forward
    print "  genpart fields :"
    for name in tree.keys():
        if 'genpart_' in name:
            print "    ", tree[name]
            # x = tree[name].array()
            # print len( x[evID] ), "-->", x[evID ]
    #
    g = tree["genpart_gen"].array()[evID]
    r = tree["genpart_reachedEE"].array()[evID]
    x = tree["genpart_posx"].array()[evID]
    y = tree["genpart_posy"].array()[evID]
    z = tree["genpart_posz"].array()[evID]
    e = tree["genpart_energy"].array()[evID]
    pid = tree["genpart_pid"].array()[evID]
    print '  pid', pid
    for i in range(len(g)):
        if (r[i] > 1):
            xg = np.array(x[i], dtype=np.float32)
            yg = np.array(y[i], dtype=np.float32)
            zg = np.array(z[i], dtype=np.float32)
            if (forward > 0):
                f = (zg >= 0.0)
            elif (forward < 0):
                f = (zg < 0.0)
            else:
                f = np.ones(zg.size, dtype=bool)
            #
            xg = xg[f]
            yg = yg[f]
            zg = zg[f]

            if (xg.size != 0):
                # mlab.text3d( xg[0], yg[0], zg[0], pidToName[pid[i]])
                # mlab.text3d( xg[0], yg[0], zg[0], "xxx")
                u = mlab.points3d(xg,
                                  yg,
                                  zg,
                                  color=(1, 1, 1),
                                  scale_factor=0.2)
                str = '{:.1}'.format(e[i])
                mlab.text3d(xg[-1], yg[-1], zg[-1], str)
                str = pidToName[pid[i]]
                mlab.text3d(xg[0], yg[0], zg[0], str)
Esempio n. 38
0
 def plot_text(self, label, X, text, size=1):
     view = mlab.view()
     roll = mlab.roll()
     self.figure.scene.disable_render = True
     
     scale = (size, size, size)
     mlab_objs = self.plots.get(label)
     
     if mlab_objs != None:
         if len(mlab_objs) != len(text):
             for obj in mlab_objs:
                 obj.remove()
         self.plots.pop(label)
     
     mlab_objs = self.plots.get(label)
     if mlab_objs == None:
         text_objs = []
         for x, t in zip(X, text):
             text_objs.append(mlab.text3d(x[0], x[1], x[2], str(t), scale=scale))
         self.plots[label] = text_objs
     elif len(mlab_objs) == len(text):
         for i, obj in enumerate(mlab_objs):
             obj.position = X[i,:]
             obj.text = str(text[i])
             obj.scale = scale
     else:
         print "HELP, I shouldn\'t be here!!!!!"
     
     self.figure.scene.disable_render = False
     mlab.view(*view)
     mlab.roll(roll)
Esempio n. 39
0
	def nodes_gen(self): 
		#assumes that all LH nodes start with L.  This is not ideal.
		nodesource_lh = mlab.pipeline.scalar_scatter(
			self.ds.lab_pos[self.ds.lhnodes,0],
			self.ds.lab_pos[self.ds.lhnodes,1],
			self.ds.lab_pos[self.ds.lhnodes,2],
			figure=self.scene.mayavi_scene)
		self.nodes_lh=mlab.pipeline.glyph(nodesource_lh,
			scale_mode='none',scale_factor=3.0,mode='sphere',
			figure=self.scene.mayavi_scene)

		nodesource_rh=mlab.pipeline.scalar_scatter(
			self.ds.lab_pos[self.ds.rhnodes,0],
			self.ds.lab_pos[self.ds.rhnodes,1],
			self.ds.lab_pos[self.ds.rhnodes,2],
			figure=self.scene.mayavi_scene)
		self.nodes_rh=mlab.pipeline.glyph(nodesource_rh,
			scale_mode='none',scale_factor=3.0,mode='sphere',
			figure=self.scene.mayavi_scene)

		self.txt = mlab.text3d(0,0,83,'',scale=4.0,color=(.8,.6,.98,),
			figure=self.scene.mayavi_scene)
		self.txt.actor.actor.pickable=0

		for nodes in (self.nodes_lh,self.nodes_rh):
			nodes.glyph.color_mode='color_by_scalar'

		self.ds.chg_lh_nodemask(); self.ds.chg_rh_nodemask()
		self.draw_nodes()
Esempio n. 40
0
def drawLabels(figure, handle, vol, bbox):
    """
    Draw all labels in the volume 'vol' at the center of mass position of the object
    into the figure 'figure'. Therefore, the bounding box 'bbox' coordinates of 'vol'
    must be specified.
    """
    # find all labels
    labels = np.unique(vol)
    if(labels[0] == 0):
        # remove background label
        labels = labels[1:]

    #write the cell label as text
    for i in labels:
        com = handle["features"][str(i)]["com"][:]
        mlab.text3d(com[2]-bbox[2]+1,com[1]-bbox[1]+1,com[0]-bbox[0]+1, str(i), color=(1,1,1), figure=figure)
    def plot_pose(T_frame_world, alpha=0.5, tube_radius=0.005, center_scale=0.025):
        T_world_frame = T_frame_world.inverse()
        R = T_world_frame.rotation
        t = T_world_frame.translation

        x_axis_tf = np.array([t, t + alpha * R[:,0]])
        y_axis_tf = np.array([t, t + alpha * R[:,1]])
        z_axis_tf = np.array([t, t + alpha * R[:,2]])
            
        mv.points3d(t[0], t[1], t[2], color=(1,1,1), scale_factor=center_scale)
        
        mv.plot3d(x_axis_tf[:,0], x_axis_tf[:,1], x_axis_tf[:,2], color=(1,0,0), tube_radius=tube_radius)
        mv.plot3d(y_axis_tf[:,0], y_axis_tf[:,1], y_axis_tf[:,2], color=(0,1,0), tube_radius=tube_radius)
        mv.plot3d(z_axis_tf[:,0], z_axis_tf[:,1], z_axis_tf[:,2], color=(0,0,1), tube_radius=tube_radius)

        mv.text3d(t[0], t[1], t[2], ' %s' %T_frame_world.to_frame.upper(), scale=0.01)
Esempio n. 42
0
    def nodes_gen(self): 
        #assumes that all LH nodes start with L.  This is not ideal.
        nodesource_lh = mlab.pipeline.scalar_scatter(
            self.ds.lab_pos[self.ds.lhnodes,0],
            self.ds.lab_pos[self.ds.lhnodes,1],
            self.ds.lab_pos[self.ds.lhnodes,2],
            figure=self.scene.mayavi_scene)
        self.nodes_lh=mlab.pipeline.glyph(nodesource_lh,
            scale_mode='none',scale_factor=3.0,mode='sphere',
            figure=self.scene.mayavi_scene)

        nodesource_rh=mlab.pipeline.scalar_scatter(
            self.ds.lab_pos[self.ds.rhnodes,0],
            self.ds.lab_pos[self.ds.rhnodes,1],
            self.ds.lab_pos[self.ds.rhnodes,2],
            figure=self.scene.mayavi_scene)
        self.nodes_rh=mlab.pipeline.glyph(nodesource_rh,
            scale_mode='none',scale_factor=3.0,mode='sphere',
            figure=self.scene.mayavi_scene)

        self.txt = mlab.text3d(0,0,83,'',scale=4.0,color=(.8,.6,.98,),
            figure=self.scene.mayavi_scene)
        self.txt.actor.actor.pickable=0

        for nodes in (self.nodes_lh,self.nodes_rh):
            nodes.glyph.color_mode='color_by_scalar'

        self.ds.chg_lh_nodemask(); self.ds.chg_rh_nodemask()
        self.ds.chg_scalar_colorbar()
        #scalar colorbar is tied to lh_surf, but we dont really care if surf switches
        #between cracked and uncracked so it is more convenient to set up here

        self.draw_nodes()
Esempio n. 43
0
 def test_text3d(self):
     """ Test the text3d module.
     """
     data = np.random.random((3, 3, 3))
     src = mlab.pipeline.scalar_field(data)
     t = mlab.text3d(0, 0, 0, 'foo', opacity=0.5, scale=2,
                 orient_to_camera=False, color=(0, 0, 0),
                 orientation=(90, 0, 0))
Esempio n. 44
0
def plot_clusters():
  points = np.genfromtxt('data.csv', delimiter=',')
  means = np.genfromtxt('means.csv', delimiter=',')
  points3d(
      points[:,0],
      points[:,1],
      points[:,2],
      color=(1,1,1),
      mode='2dvertex')
  points3d(means[:,0], means[:,1], means[:,2], color=(1,0,0), scale_factor=0.2)
  for mean in means:
    text3d(
        mean[0],
        mean[1],
        mean[2],
        text='({:01.1f}, {:01.1f}, {:01.1f})'.format(mean[0], mean[1], mean[2]),
        scale=0.5,
        color=(1,1,1))
Esempio n. 45
0
    def _show_labels(self, show):
        _toggle_mlab_render(self, False)
        while self.text3d:
            text = self.text3d.pop()
            text.remove()

        if show and len(self.src.data.points) > 0:
            fig = self.scene.mayavi_scene
            if self._view == 'arrow':  # for axes
                x, y, z = self.src.data.points[0]
                self.text3d.append(text3d(
                    x, y, z, self.name, scale=self.label_scale,
                    color=self.color, figure=fig))
            else:
                for i, (x, y, z) in enumerate(np.array(self.src.data.points)):
                    self.text3d.append(text3d(
                        x, y, z, ' %i' % i, scale=self.label_scale,
                        color=self.color, figure=fig))
        _toggle_mlab_render(self, True)
Esempio n. 46
0
def _plot_coordinate_transforms(*Targs, **kwargs):
    tag = kwargs.get('tag', '')
    origin = kwargs.get('origin', True)
    scale = kwargs.get('scale', 0.1)
    x, y, z, u, v, w, scalars = quiver_args_from_transforms(*Targs,
                                                            origin=origin)
    pts = mlab.quiver3d(x, y, z, u, v, w,
                        scalars=scalars,
                        line_width=40.0 * scale,
                        scale_factor=scale)
    pts.glyph.color_mode = 'color_by_scalar'
    for i, (xi, yi, zi) in enumerate(zip(x, y, z)):
        if not (i % 3):
            txt = str(i / 3 - 1)
            if i == 0:
                txt = 'O'
            txt = '%s%s' % (tag, txt)
            mlab.text3d(xi, yi, zi, text=txt, scale=0.6 * scale)
    mlab.gcf().scene.background = (1, 1, 1)
    return pts
Esempio n. 47
0
def plot_labels(labels, lattice=None, coords_are_cartesian=False, figure=None, **kwargs):  # pragma: no cover
    """
    Adds labels to a mayavi_ figure.

    Args:
        labels: dict containing the label as a key and the coordinates as value.
        lattice: |Lattice| object used to convert from reciprocal to cartesian coordinates
        coords_are_cartesian: Set to True if you are providing.
            coordinates in cartesian coordinates. Defaults to False.
            Requires lattice if False.
        figure: mayavi figure, None to plot on the curretn figure
        kwargs: kwargs passed to the mayavi function `text3d`. Color defaults to blue and size to 25.

    Returns: mayavi figure
    """
    figure, mlab = get_fig_mlab(figure=figure)

    #if "color" not in kwargs:
    #    kwargs["color"] = "b"
    #if "size" not in kwargs:
    #    kwargs["size"] = 25
    #if "width" not in kwargs:
    #    kwargs["width"] = 0.8
    if "scale" not in kwargs:
        kwargs["scale"] = 0.1

    for k, coords in labels.items():
        label = k
        if k.startswith("\\") or k.find("_") != -1:
            label = "$" + k + "$"
        off = 0.01
        if coords_are_cartesian:
            coords = np.array(coords)
        else:
            if lattice is None:
                raise ValueError("coords_are_cartesian False requires the lattice")
            coords = lattice.get_cartesian_coords(coords)
        x, y, z = coords + off
        mlab.text3d(x, y, z, label, figure=figure, **kwargs)

    return figure
Esempio n. 48
0
File: bz.py Progetto: atztogo/cogue
 def _plot_axes(self, color=(1, 0, 0)):
     shortest = min(np.linalg.norm(self._lattice, axis=1))
     lat = np.array([x / np.linalg.norm(x) for x in self._lattice])
     lat *= shortest
     mlab.quiver3d([0, 0, 0],
                   [0, 0, 0],
                   [0, 0, 0],
                   lat[0],
                   lat[1],
                   lat[2],
                   color=color,
                   line_width=3,
                   scale_factor=1)
 
     scale = shortest / 8
     for c, v in zip(('a','b','c'), lat * (1 + scale / 2)):
         x, y, z = v
         x += scale / 2
         y -= scale / 4
         z -= scale / 4
         mlab.text3d(x, y, z, c, color=color, scale=scale)
Esempio n. 49
0
def draw_didi_boxes3d(fig, boxes3d, is_number=False, color=(1,1,1), line_width=1):

    if boxes3d.shape==(8,3): boxes3d=boxes3d.reshape(1,8,3)

    num = len(boxes3d)
    for n in range(num):
        b = boxes3d[n]

        if is_number:
            mlab.text3d(b[0,0], b[0,1], b[0,2], '%d'%n, scale=(1, 1, 1), color=color, figure=fig)
        for k in range(0,4):

            #http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
            i,j=k,(k+1)%4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)

            i,j=k+4,(k+1)%4 + 4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)

            i,j=k,k+4
            mlab.plot3d([b[i,0], b[j,0]], [b[i,1], b[j,1]], [b[i,2], b[j,2]], color=color, tube_radius=None, line_width=line_width, figure=fig)
Esempio n. 50
0
def plot_structure(structure, frac_coords=False, to_unit_cell=False, style="points+labels",
                   unit_cell_color=(0, 0, 0), color_scheme="VESTA", figure=None, show=False, **kwargs):  # pragma: no cover
    """
    Plot structure with mayavi.

    Args:
        structure: |Structure| object
        frac_coords:
        to_unit_cell: True if sites should be wrapped into the first unit cell.
        style: "points+labels" to show atoms sites with labels.
        unit_cell_color:
        color_scheme: color scheme for atom types. Allowed values in ("Jmol", "VESTA")
        figure:
        kwargs:

    Returns: mayavi figure
    """
    figure, mlab = get_fig_mlab(figure=figure)

    #if not frac_coords:
    plot_unit_cell(structure.lattice, color=unit_cell_color, figure=figure)
    from pymatgen.analysis.molecule_structure_comparator import CovalentRadius
    from pymatgen.vis.structure_vtk import EL_COLORS

    for site in structure:
        symbol = site.specie.symbol
        color = tuple(i / 255 for i in EL_COLORS[color_scheme][symbol])
        radius = CovalentRadius.radius[symbol]
        if to_unit_cell and hasattr(site, "to_unit_cell"): site = site.to_unit_cell
        x, y, z = site.frac_coords if frac_coords else site.coords

        if "points" in style:
            mlab.points3d(x, y, z, figure=figure, scale_factor=radius,
                          resolution=20, color=color, scale_mode='none', **kwargs)
        if "labels" in style:
            mlab.text3d(x, y, z, symbol, figure=figure, color=(0, 0, 0), scale=0.2)

    if show: mlab.show()
    return figure
Esempio n. 51
0
    def _render(self, **kwargs):
        from mayavi import mlab
        # disabling the rendering greatly speeds up this for loop
        self.figure.scene.disable_render = True
        positions = []
        for label, mask in self.labels_to_masks.iteritems():
            p = self.pointcloud.from_mask(mask)
            for i, p in enumerate(p.points):
                positions.append(p)
                l = '%s_%d' % (label, i)
                # TODO: This is due to a bug in mayavi that won't allow
                # rendering text to an empty figure
                mlab.points3d(p[0], p[1], p[2])
                mlab.text3d(p[0], p[1], p[2], l, figure=self.figure)
        positions = np.array(positions)
        os = np.zeros_like(positions)
        os[:, 2] = 1
        mlab.quiver3d(positions[:, 0], positions[:, 1], positions[:, 2],
                      os[:, 0], os[:, 1], os[:, 2], figure=self.figure)
        self.figure.scene.disable_render = False

        return self
Esempio n. 52
0
 def plotText(self, X, text, color=None, size=None):
     
     if self.autoRemove: self.removeText()
     
     if isinstance(X, list): X = scipy.asarray(X)
     if len(X.shape)==1: X = scipy.array([X])
     if isinstance(text, str): text = [text]
     
     if color==None: color=(1,0,0)
     if size==None: size=1.
     
     for i, x in enumerate(X):
         self.text.append(mlab.text3d(x[0], x[1], x[2], text[i], color=color, scale=size))
Esempio n. 53
0
def plot_graphs(locs,stations,nbsta,CLUSTER,nbmin,threshold):
  from mayavi import mlab

  # Event coordinates
  stack_x,stack_y,stack_z=[],[],[]
  for loc in locs:
    stack_x.append(loc['x_mean'])
    stack_y.append(loc['y_mean'])
    stack_z.append(-loc['z_mean'])

  # Extract coordinates
  xsta,ysta,zsta=[],[],[]
  for sta in sorted(stations):
    xsta.append(stations[sta]['x'])
    ysta.append(stations[sta]['y'])
    zsta.append(stations[sta]['elev'])

  # 3D PLOT USING MAYAVI
  logging.info("Plotting...")
  s1=mlab.figure(1,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,900))
  s1=mlab.points3d(xsta,ysta,zsta,color=(1,0,0),scale_factor=0.05,mode='cube')
  s1=mlab.axes(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  s1=mlab.outline(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  s1=mlab.points3d(stack_x,stack_y,stack_z,scale_factor=0.1,color=(0.8,0.8,0.8))
  s1=mlab.title("threshold=%s, nbmin=%s"%(threshold,nbmin),height=0.1,size=0.35,color=(0,0,0))
  for i_ev in range(len(nbsta)):
    for i_c in range(1,len(CLUSTER)+1):
      if i_ev+1 in CLUSTER[i_c]:
        s1=mlab.points3d(stack_x[i_ev],stack_y[i_ev],stack_z[i_ev],scale_factor=0.1,color=tuple(CZ_Clust_2_color(100*(len(CLUSTER)-i_c)/len(CLUSTER))))
        s1=mlab.text3d(stack_x[i_ev],stack_y[i_ev],stack_z[i_ev],str(i_c),color=(0,0,0),scale=0.1)
  logging.info("Done!")
   
  logging.info("Plotting...")
  s2=mlab.figure(2,bgcolor=(1,1,1),fgcolor=(0,0,0),size=(1000,900))
  mlab.points3d(xsta,ysta,zsta,color=(1,0,0),scale_factor=0.05,mode='cube')
  mlab.axes(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  mlab.outline(extent=[362,370,7647,7653,-0.5,2.5],color=(0,0,0))
  mlab.points3d(stack_x,stack_y,stack_z,scale_factor=0.1,color=(0.8,0.8,0.8))
  mlab.title("threshold=%s, nbmin=%s"%(threshold,nbmin),height=0.1,size=0.35,color=(0,0,0))
  for ind_I in range(len(nbsta)):
    for ind_J in range(ind_I+1,len(nbsta)):
      W_IJ=nbsta[ind_I,ind_J]
      if W_IJ >= nbmin:
        mlab.points3d(stack_x[ind_J],stack_y[ind_J],stack_z[ind_J],scale_factor=0.1,color=(0,0,0))
        mlab.points3d(stack_x[ind_I],stack_y[ind_I],stack_z[ind_I],scale_factor=0.1,color=(0,0,0))
        d=(stack_x[ind_J]-stack_x[ind_I],stack_y[ind_J]-stack_y[ind_I],stack_z[ind_J]-stack_z[ind_I])
        norm=np.sqrt(d[0]**2+d[1]**2+d[2]**2)
        s2=mlab.quiver3d(stack_x[ind_I],stack_y[ind_I],stack_z[ind_I],d[0],d[1],d[2],color=tuple(CZ_W_2_color(W_IJ)),mode='2ddash',scale_factor=norm,scale_mode='scalar')
  #mlab.colorbar(s2)
  logging.info("Done!")
  mlab.show()
Esempio n. 54
0
    def _show_labels(self, show):
        self.scene.disable_render = True
        while self.text3d:
            text = self.text3d.pop()
            text.remove()

        if show:
            fig = self.scene.mayavi_scene
            for i, pt in enumerate(np.array(self.src.data.points)):
                x, y, z = pt
                t = text3d(x, y, z, " %i" % i, scale=0.01, color=self.rgbcolor, figure=fig)
                self.text3d.append(t)

        self.scene.disable_render = False
Esempio n. 55
0
    def _show_labels(self, show):
        _toggle_mlab_render(self, False)
        while self.text3d:
            text = self.text3d.pop()
            text.remove()

        if show:
            fig = self.scene.mayavi_scene
            for i, pt in enumerate(np.array(self.src.data.points)):
                x, y, z = pt
                t = text3d(x, y, z, ' %i' % i, scale=.01, color=self.color,
                           figure=fig)
                self.text3d.append(t)
        _toggle_mlab_render(self, True)
Esempio n. 56
0
def plotCosy(fig,R,t,scale,name='',col=None):
  pts = np.zeros((3,6)) 
  for i in range(0,3):
    pts[:,i*2]  = np.zeros(3)
    pts[:,i*2+1] = R[:,i]
  pts *= scale
  pts+= t[:,np.newaxis]
  if col is None:
    mlab.plot3d(pts[0,0:2],pts[1,0:2],pts[2,0:2],figure=fig,color=(1.0,0.0,0.0),tube_radius=0.05*scale)
    mlab.plot3d(pts[0,2:4],pts[1,2:4],pts[2,2:4],figure=fig,color=(0.0,1.0,0.0),tube_radius=0.05*scale)
    mlab.plot3d(pts[0,4:6],pts[1,4:6],pts[2,4:6],figure=fig,color=(0.0,0.0,1.0),tube_radius=0.05*scale)  
  else:
    mlab.plot3d(pts[0,0:2],pts[1,0:2],pts[2,0:2],figure=fig,color=col)            
    mlab.plot3d(pts[0,2:4],pts[1,2:4],pts[2,2:4],figure=fig,color=col)            
    mlab.plot3d(pts[0,4:6],pts[1,4:6],pts[2,4:6],figure=fig,color=col) 
  if name!='':
    mlab.text3d(pts[0,1],pts[1,1],pts[2,1],name,
      scale=.1*scale,color=(0,0,0),line_width=1.0,figure=fig)
    mlab.text3d(pts[0,3],pts[1,3],pts[2,3],name,
      scale=.1*scale,color=(0,0,0),line_width=1.0,figure=fig)
    mlab.text3d(pts[0,5],pts[1,5],pts[2,5],name,
      scale=.1*scale,color=(0,0,0),line_width=1.0,figure=fig)
Esempio n. 57
0
def Scatter3d_Mayavi(xs, ys, zs, weights=None, weight_label=None, xlabel='x',
    ylabel='y', zlabel='z', axes=True, **points3d_kw):
  from mayavi import mlab
  # XXX error when max() returns zero
  def normalize(vs):
    a = vs.min()
    b = vs.max()
    if a != b:
      vs = vs / float(b - a)
    return vs
  xs = normalize(xs)
  ys = normalize(ys)
  zs = normalize(zs)
  if 'scale_mode' not in points3d_kw:
    points3d_kw['scale_mode'] = 'none'
  if 'scale_factor' not in points3d_kw:
    points3d_kw['scale_factor'] = .03
  if weights is None:
    mlab.points3d(xs, ys, zs, **points3d_kw)
  else:
    mlab.points3d(xs, ys, zs, weights, **points3d_kw)
  if weight_label:
    mlab.scalarbar(title=weight_label)
  if axes:
    extent = 1.2
    scale = 0.05
    tube_radius = 0.01
    color = (1,1,1)  # white
    mlab.plot3d([0,extent], [0,0], [0,0], tube_radius=tube_radius, color=color)
    mlab.plot3d([0,0], [0,extent], [0,0], tube_radius=tube_radius, color=color)
    mlab.plot3d([0,0], [0,0], [0,extent], tube_radius=tube_radius, color=color)
    if xlabel:
      mlab.text3d(extent, 0, 0, xlabel, scale=scale, color=color)
    if ylabel:
      mlab.text3d(0, extent, 0, ylabel, scale=scale, color=color)
    if zlabel:
      mlab.text3d(0, 0, extent, zlabel, scale=scale, color=color)
Esempio n. 58
0
 def plot_pos_index(p):
     pos = cent[p]
     mlab.text3d(pos[0], pos[1], pos[2], str(p), scale=0.8)
Esempio n. 59
0
    def make_sphere(self):
        """
        Plots Bloch sphere and data sets.
        """
        # setup plot
        # Figure instance for Bloch sphere plot
        from mayavi import mlab
        import matplotlib.colors as colors
        if self.user_fig:
            self.fig = self.user_fig
        else:
            self.fig = mlab.figure(
                1, size=self.size,
                bgcolor=colors.colorConverter.to_rgb(self.bgcolor),
                fgcolor=colors.colorConverter.to_rgb(self.fgcolor))

        sphere = mlab.points3d(
            0, 0, 0, figure=self.fig, scale_mode='none', scale_factor=2,
            color=colors.colorConverter.to_rgb(self.sphere_color),
            resolution=100, opacity=self.sphere_alpha, name='bloch_sphere')

        # Thse commands make the sphere look better
        sphere.actor.property.specular = 0.45
        sphere.actor.property.specular_power = 5
        sphere.actor.property.backface_culling = True

        # make frame for sphere surface
        if self.frame:
            theta = np.linspace(0, 2 * np.pi, 100)
            for angle in np.linspace(-np.pi, np.pi, self.frame_num):
                xlat = np.cos(theta) * np.cos(angle)
                ylat = np.sin(theta) * np.cos(angle)
                zlat = np.ones_like(theta) * np.sin(angle)
                xlon = np.sin(angle) * np.sin(theta)
                ylon = np.cos(angle) * np.sin(theta)
                zlon = np.cos(theta)
                mlab.plot3d(xlat, ylat, zlat,
                            color=colors.colorConverter.to_rgb(
                            self.frame_color),
                            opacity=self.frame_alpha,
                            tube_radius=self.frame_radius)
                mlab.plot3d(xlon, ylon, zlon,
                            color=colors.colorConverter.to_rgb(
                            self.frame_color),
                            opacity=self.frame_alpha,
                            tube_radius=self.frame_radius)

        # add axes
        axis = np.linspace(-1.0, 1.0, 10)
        other = np.zeros_like(axis)
        mlab.plot3d(
            axis, other, other,
            color=colors.colorConverter.to_rgb(self.axes_color),
            tube_radius=self.axes_radius, opacity=self.axes_alpha)
        mlab.plot3d(
            other, axis, other,
            color=colors.colorConverter.to_rgb(self.axes_color),
            tube_radius=self.axes_radius, opacity=self.axes_alpha)
        mlab.plot3d(
            other, other, axis,
            color=colors.colorConverter.to_rgb(self.axes_color),
            tube_radius=self.axes_radius, opacity=self.axes_alpha)

        # add data to sphere
        self.plot_points()
        self.plot_vectors()

        # #add labels
        mlab.text3d(0, 0, self.zlpos[0], self.zlabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0, 0, self.zlpos[1], self.zlabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(self.xlpos[0], 0, 0, self.xlabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(self.xlpos[1], 0, 0, self.xlabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0, self.ylpos[0], 0, self.ylabel[0],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)
        mlab.text3d(0, self.ylpos[1], 0, self.ylabel[1],
                    color=colors.colorConverter.to_rgb(self.font_color),
                    scale=self.font_scale)